SFTP is a secure alternative to FTP. Authentication is done via SSH and a secure tunnel is established for the entire file transfer session. In this article I look at how to restrict a user’s access to SFTP only and to a specific directory on the server.
The first step is to add a new user to the system:
Then we change the shell program to /bin/false:
chsh -s /bin/false sftptest
This will prevent the user from being able to execute arbitrary commands on the server.
Next lets add a group for all users that are restricted to SFTP access only:
And add sftptest to sftpusers:
gpasswd -a sftptest sftpusers
Next append this block in /etc/ssh/sshd_config
Match Group sftpusers ChrootDirectory /home ForceCommand internal-sftp AllowTCPForwarding no X11Forwarding no
This will restrict all users of sftpusers group to the chroot directory /home. Ideally we would restrict them to their own directories within /home but unfortunately the OpenSSH version included with Debian Wheezy requires that the chroot directory be owned by root.
When they connect to the server the command internal-sftp is run. This means that only SFTP access is available. In some guides a -d switch is used to automatically change the directory to the connecting user’s home directory. In my testing this doesn’t work on Wheezy.
To prevent users from accessing other users’ home directories you should chmod them all to 700:
chmod 700 /home/user1 chmod 700 /home/user2 ... chmod 700 /home/userN
/home can also be chmodded to 111 to prevent users listing its contents and seeing what other users are on the system:
chmod 111 /home/
It is also recommended that you setup public key authentication for each user and avoid using passwords. How to do this is covered in another article.
With the above setup users can securely upload and download files from the server over an encrypted SFTP connection. They are chrooted to /home and file system permissions are used to restrict their access to their own home directory.