Chroot SFTP users with OpenSSH

Thanks to

OpenSSH configuration

You need to edit the file /etc/ssh/sshd_config and configure OpenSSH to use its internal SFTP subsystem; this is needed to simplify the Chroot creation (we will not need to copy additional libraries inside the Chroot). Just add at the end of the file the following statements:

#Subsystem sftp /usr/lib/openssh/sftp-server
Subsystem sftp internal-sftp

Match Group sftpusers
    ChrootDirectory /home/%u
    X11Forwarding no
    AllowTcpForwarding no
    ForceCommand internal-sftp

of course you can customize the ChrootDirectory value to match the users home folder path, in this case is just set to “%h” which is a placeholder that get’s replaced at run-time with the home folder path. Now just restart OpenSSH:

 sudo /etc/init.d/ssh restart

User creation

Just create an user as you normally would, then you just change the ownership of his home directory, disable shell access and add the user to the sftp group to match the previous sshd_config configuration.

sudo useradd myuser
sudo passwd myuser
sudo usermod -s /bin/false myuser
sudo usermod -d /var/www/myuserhome myuser
sudo chown root.root /var/www/myuser
sudo addgroup sftpusers
sudo adduser myuser sftpusers

Take special care on the owner and permission along the entire path structure, all the folder must be owned by “root:root” and with 755 permissions. For instance:

chown root /home /home/myuser
chmod 755 /home /home/myuser

Don’t forget to check file permission, groups, etc.. and to test everything out from an SFTP client and you should already be good to go.