Fully replacing FTP with SFTP
Recently while setting up a new server, I realized that I really didn’t need to run FTP anymore. I typically use SFTP where possible, and it made sense to go the extra mile and migrate to using SFTP completely, while also allowing other users to access my server and use SFTP, without allowing them a shell.
What is SFTP?
SFTP is similar but not the same as FTP. Technically, SFTP isn’t just a secure FTP, but is a completely different protocol. For the ease of explaining things, however, SFTP is essentially like FTP running through SSH. It provides you with fully encrypted sessions, and brings other benefits that SSH provides such as key based authentication.
Not many commercial web hosts use SFTP. I’m not 100% sure why, but I have a feeling it’s just general misconception that SFTP is a risk as it requires the user having an account on the server and allowing them to potentially have shell access, although I’m sure it has a very slight performance impact too, which could potentially be a large performance impact when scaled to thousands of users.
The only qualm I have with this is that with the majority of setups I have seen, they already have a system account in order for FTP/Apache to run and for them to have a home directory and such.. so there isn’t a difference.
These accounts (lets call them members of the www-data group) should already have disabled shells anyway, so running SFTP isn’t going to compromise the security of the system in any way.
Configuring SFTP
The first step will be to ensure you have openssh installed. This guide assumes you are using Debian (Squeeze), and already have a running server with users on.
Install SSH
apt-get install openssh
Prepare chroot
You will need to modify the home directory permissions for each user in order for the SSH chroot to work correctly. Each users directory needs to be owned by root. We’ll use bobdole as an example.
chown root /home/bobdole
chmod 775 /home/bobdole
Modify users default shell
In order to prevent the user from gaining shell access, we set the default shell to /bin/false, and add bobdole to the www-data group.
usermod -s /bin/false bobdole
usermod -aG www-data bobdole
Modify sshd_config
You will need to modify the Subsystem option..
#Subsystem sftp /usr/lib/openssh/sftp-server
Subsystem sftp internal-sftp
We will need to add a clause specifically for members of the www-data group (bobdole, etc..) in order to apply options to them, and enable the chroot specifically for them.
# Specific configuration for www-data
Match group www-data
ChrootDirectory /home/%u
You can also add other declarations to the Match directive. For instance, if you only allowed key based authentication to your server previously, but wanted to allow www-data members to log in without a key, you could set PasswordAuthentication to yes, only for those specific members…
# Specific configuration for www-data
Match group www-data
ChrootDirectory /home/%u
PasswordAuthentication yes