SFTP only chroot users with OpenSSH in Debian

From OpenSSH version 4.9 and up it is now possible to create chrooted SFTP-only users with OpenSSH without the need for any add-ons.

In my example i want all users within the “sftp” group to hit /srv/sftponly.  This can be done on userlevel or on group level. I will be using groups.

At first, use your favorite editor to ecit /etc/ssh/sshd_config and find the line starting with “Subsystem sftp” (usually at the bottom) – change it so it looks like this:

Subsystem sftp internal-sftp

Next, we need to add the rule to match users. Add this to your sshd_config at the bottom:

Match Group sftp
PasswordAuthentication yes
ChrootDirectory /srv/sftponly
AllowTCPForwarding no
X11Forwarding no
ForceCommand internal-sftp

Now add the sftp group:

groupadd sftp

Add our first user:

useradd -d /srv/sftponly -g sftp -s /bin/false <username>
passwd <username>

Now, restart openssh:

/etc/init.d/ssh restart

And you should be all set. Use your favorite SFTP editor to test. Also try logging on via SSH to make sure that the user does not have access to do that.

Troubleshooting

Along your way some problems might occur. I will try to address the most common ones here. At first what you want to do is enable debugging in openssh so you can see in the logs what happens. Edit /etc/ssh/sshd_server – find “LogLevel” and change the setting to “DEBUG” – and restart ssh. The problems below are shown either in these logs or in the output of the “sftp” command from the client. When using the sftp client be sure to add the “-v” flag for verbose output.

Problem: fatal: bad ownership or modes for chroot directory component “/”
Fix: chmod 755 /

Problem: fatal: bad ownership or modes for chroot directory “/srv/sftponly”
Fix: Folders in the path along the way must be owned by root:root and must not be writable by anyone but root. This is because the directory we are going to use will be the root of the new users.  In my example the fix would be: chown root:root /srv ; chown root:root /srv/sftponly ; chmod 755 /srv ; chmod 755 /srv/sftponly”

Problem: Everything seems to be OK.. The users just don’t get access.
Fix: Make sure that you don’t have any whitespaces in your sshd_config after the configuration lines. In my case this caused a real pain.

Hit me a comment if you experience anything strange.

Setting UMASK for SFTP users

Add this line to /etc/pam.d/sshd:

session    optional     pam_umask.so umask=0002

This particular line will make new files/folders user and group writable.