Configure SFTP access to your Ubuntu server through SSH

Sometimes you have to give your users a way to manage files on your server. A typical scenario is a web server where your users manage their websites by themselves.

The classical approach in this scenario was to use FTP to give file management capabilities to your users, but it has many drawbacks:

  1. You have to provision and maintain a new service on your server;
  2. FTP is an annoying protocol from a firewall configuration point of view;
  3. FTP is not encrypted by default, and you have to put some effort to configure an FTP server which is protected from sniffing.

If you are a lazy sysadmin like me you’ll prefer to use a service you already have, which is encrypted by default and do not require a special firewall configuration other than the port 22 you are already using.

ssh to the rescue!

Configure ssh server to serve a directory using SFTP, chrooting the user on that directory

Edit the file /etc/ssh/sshd_config by adding the following lines at the bottom:

Match group sftp
ChrootDirectory %h
X11Forwarding no
AllowTcpForwarding no
ForceCommand internal-sftp

In this way every user belonging to group sftp will be chrooted in his home directory when connecting trough sftp.

Restart ssh server:

sudo service ssh restart

Now add a new group called sftp:

sudo addgroup sftp

And add a system user that will be used to connect:

sudo adduser --home /home/ --no-create-home --shell /usr/sbin/nologin username

Note how we set the home directory of the user to the root of the website, and how we set the shell to nologin executable, in order to deny access from a regular ssh shell.

Now add the user to sftp group:

sudo adduser username sftp

Set permissions correctly on username home directory and its content. The home directory itself should be owned by root and have 755 permissions, otherwise sftp login will fail:

cd /home/
chown root:sftp .
chmod 755 .
chown -R username:sftp *

Try to connect to your server on port 22 with a client supporting SFTP (such as Filezilla). You should see the content of /home/ directory, and you should not be able to go out from that directory.


2 thoughts on “Configure SFTP access to your Ubuntu server through SSH

Leave a comment

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s