FTP Restricted to a Directory

April 12, 2013

Users on modern Debian systems can be restricted to a particular part of the filesystem by setting a chroot directory. It’s quite simple, once you know how. To make use of this, you need to use SFTP rather than standard FTP – most FTP clients also support SFTP, so this shouldn’t be a problem and is, in fact more secure anyway.

I am going to set the restriction at the group level. This will allow you to set up various SFTP users which is useful if you have many websites on a shared host.

All you need to do is edit /etc/ssh/sshd_config (as root) and append the following:

# For chrooted sftp
Match group filetransfer
ChrootDirectory %h
ForceCommand internal-sftp

Then restart SSH:

# /etc/init.d/ssh restart

This will make sure that any user that is part of the ‘filetransfer’ group cannot escape their home directory and restricts them to SFTP, so no shell access is allowed.

Now you need to create the group:
# addgroup filetransfer

And finally, for every user you want to create:
# adduser --home /var/www/mysitefolder webeditor
# usermod -G filetransfer webeditor
# chown root:root /var/www/mysitefolder
# chmod 755 /var/www/mysitefolder
# mkdir /var/www/mysitefolder/public_html
# chown -R webeditor:webeditor /var/www/mysitefolder/*
# chown -R webeditor:webeditor /var/www/mysitefolder/.[^.]*

This will create a user called webeditor and restrict their access to the directory /var/www/mysitefolder

The home directory of your webeditor user needs to be owned by root for this to work. The public_html directory within this must then be owned by webeditor so that the SFTP user can upload to it.

The final chown command is needed to set the users hidden files back to be owned by the user. The permissions of these were changed when making the mysitefolder directory owned by root. You may find that you don’t need to do this step, unless you want to do something like place an SSH key to the .ssh folder.