Jail SFTP user in Ubuntu the simple way

Easily setup SFTP jailed users in Ubuntu. I want to post a note to remind myself how to jail in a directory a system user in a given directory with a sftp connection. Commands are tested using Ubuntu 16.

Setup the SFTP jail

The user i want to create is named sftp_user and i want to jail it in the directory restricted_dir inside the user home directory.

All commands are executed with root user.

So create the system user and the home directory, the home directory created is /home/sftp_user/.

Now

  • create the restricted directory inside the home directory
  • chown the home directory to root user (root owns the home dir)
  • and chown the restricted dir to our user

So

Now edit the ssh daemon config file /etc/ssh/sshd_config and set it to restrict our user in sftp only and in his directory only.

So edit

And set this configuration at the end of file

Match User sftp_user
ChrootDirectory /home/sftp_user/
ForceCommand internal-sftp

And restart the SSH service

Consume the restricted directory in another location

Usually the restricted directory is used to upload files inside a directory of another user (eg a virtualhost’s system user), so here is how we setup it.

We can manually mount the directory with mount, but the effect is temporary until the next reboot.

To mount permanently we must edit the /etc/fstab file.

And set the line

/home/virtualhost_user/public_html/restricted_dir/ /home/sftp_user/restricted_dir/ none defaults,nofail,bind 0 0