sftp lock to user home

1、openssh-server 版本4.8以上才支持chroot功能
2、修改sshd_config文件

[code]
#必须使用internal-sftp
Subsystem sftp internal-sftp
#针对单个用户的设置
#Match User anoncvs
# X11Forwarding no
# AllowTcpForwarding no
# ForceCommand internal-sftp
# ChrootDirectory %h

#针对组的设置
#Match
Group sftp
# X11Forwarding no
# AllowTcpForwarding no
# ForceCommand internal-sftp
# ChrootDirectory %h
[/code]

3、使用组或者单个用户,都要保证其home目录的owner都为root,权限755或者750
例如用户test,home目录为/home/test, /home、/home/test的owner都为root
用户home目录无修改权限,只能新建个子目录,权限777,子目录里才能上传文件
4、重点:Ubuntu可能不需要其他设置就已经可以了,但是centos、redhat等需要SELinux enabled:

[code]
# setsebool -P ssh_chroot_rw_homedirs on
# restorecon -R /home/$USERNAME
[/code]

5、创建/增加用户

[code]
useradd -d /home/$USERNAME -s /usr/lib/sftp-server -M -N -g sftponly $USERNAME
mkdir -p /home/$USERNAME/uploads /home/$USERNAME/.ssh
chown $USERNAME:sftponly /home/$USERNAME/uploads /home/$USERNAME/.ssh
[/code]

参考:https://cassjohnston.wordpress.com/2012/08/16/selinux-and-chrooted-sftp/
Set up of sftp-only access to a server for a subset of users on a Scientific Linux 6 install with SELinux enforcing:

Create sftponly group and added users with sftp-server as their shell:

[code]
addgroup sftponly
useradd -d /home/$USERNAME -s /usr/lib/sftp-server -M -N -g sftponly $USERNAME
mkdir -p /home/$USERNAME/uploads /home/$USERNAME/.ssh
chown $USERNAME:sftponly /home/$USERNAME/uploads /home/$USERNAME/.ssh
chown root /home/$USERNAME
chmod 755 /home/$USERNAME
chmod 700 /home/$USERNAME/.ssh
passwd $USERNAME
echo ‘/usr/lib/sftp-server’ >> /etc/shells
[/code]

They will chroot into their home directory, so this needs to be owned by root and not writable by any other user, including $USERNAME. As the user won’t have write access to their own home directory, you need to manually create a .ssh directory for them and a subdirectory to which they do have write access, for their files.

Changed /etc/ssh/sshd_config to chroot to the home directory of sftp-only users

[code]
#Subsystem sftp /usr/lib/openssh/sftp-server
Subsystem sftp internal-sftp

Match group sftponly
ChrootDirectory %h
X11Forwarding no
AllowTcpForwarding no
ForceCommand internal-sftp
[/code]

Make sure selinux allows write access to chroot’ed home directories:

[code]
setsebool -P ssh_chroot_rw_homedirs on
[/code]

I also needed to do a restorecon on the home directory to get selinux to allow sftp users to write to their uploads directory:

[code]
restorecon -R /home/$USERNAME
[/code]

Seems to be working okay now.