Chrooted sftp server setup


There are several descriptions on the Internet about how to create a chrooted sftp account, but as usual most of these descriptions are incorrect, incomplete or outdated. So, this is my addition to this list, at least at the time that I write this (June 2011) it works. The critical part is setting the right permissions, else sshd silently refuses access.

A chrooted sftp account can be useful to allow access to a web server to upload site data.



This procedure has been tested on Slackware and Arch Linux. First we need to change the sshd configuration, the file /etc/ssh/sshd_config. The changes need to be done at the bottom of that file:

# override default of no subsystems
#Subsystem      sftp    /usr/libexec/sftp-server
Subsystem       sftp    internal-sftp

# These lines must appear at the *end* of sshd_config
Match Group sftponly
        ForceCommand internal-sftp
        ChrootDirectory %h
        AllowTcpForwarding no
        X11Forwarding no

Next you need to add the special group sftponly and add a user account:

[root@web04 ~]# groupadd -g 103 sftponly
[root@web04 ~]# useradd -g 103 -d /home/webuser -s /bin/false -c "Web User" webuser
[root@web04 ~]# passwd webuser
Enter new UNIX password:
Retype new UNIX password:
passwd: password updated successfully
[root@web04 ~]# cd /home
[root@web04 home]# mkdir webuser
[root@web04 home]# chown root:sftponly webuser
[root@web04 home]# chmod 750 webuser
[root@web04 home]# cd webuser
[root@web04 webuser]# mkdir Upload
[root@web04 webuser]# chown webuser:sftponly Upload
[root@web04 webuser]# ls -la
total 12
drwxr-x--- 3 root     sftponly  8 2010-10-16 14:38 ./
drwxr-xr-x 7 root     root     56 2010-10-16 12:21 ../
drwxr-xr-x 2 webuser  sftponly  1 2010-10-16 14:38 Upload/
[root@web04 webuser]#

You need to create a Upload directory. In this directory the user has the right to do what (s)he wants. The user is not allowed to do that in the home directory, that is owned by root. The home directory must be owned by root. The users home directory needs exactly the permissions as shown, if it is different it will not work.

You can also see that we added this user with the shell /bin/false, so the user cannot login to a shell. If everything is configured, restart sshd:

[root@web04 ~]# /etc/rc.d/sshd restart
:: Stopping Secure Shell Daemon                                          [DONE]
:: Starting Secure Shell Daemon                                          [DONE]
[root@web04 ~]#


Port listen tip.

For external use you can let the sshd process listen to another port as the default port 22. In /etc/ssh/sshd_config you can add multiple ports by adding a Port 22222 below the Port 22 line. The sshd process will listen to each port. Then only open port 22222 on your firewall.

This will not give you real protection against ssh attacks, but at least choosing a “strange” port is enough to stop most attacks.