Chroot sftp-only SSH user into home folder safely in Ubuntu

This seemingly-useful link on askubuntu did not work as I wanted, and neither did a few other similar sites. Trying to make it easy for the end user took longer than the 5 minutes I had available, so I'm posting the correct way to do it here for future use. The key missing ingredient was provided in a comment to the accepted answer in the askubuntu link:

you could then "move" the user to the writable directory after login by using ForceCommand internal-sftp -d /writable in /etc/ssh/sshd_config. They would still be able to browse back up to the read-only chroot dir though.

So here is the correct sequence, search/replace USERNAME and perform the following steps:

sudo groupadd sftponly

sudo useradd -g sftponly -s /bin/false -m -d /home/USERNAME USERNAME

sudo passwd USERNAME

sudo usermod -G sftponly -s /bin/false USERNAME

sudo chown root: /home/USERNAME
sudo chmod 755 /home/USERNAME

sudo mkdir /home/USERNAME/ftp
sudo chmod 755 /home/USERNAME/ftp
sudo chown USERNAME:sftponly /home/USERNAME/ftp

sudo chown root /home/USERNAME
sudo chmod go-w /home/USERNAME
sudo mkdir /home/USERNAME/ftp
sudo chown USERNAME:sftponly /home/USERNAME/ftp
sudo chmod ug+rwX /home/USERNAME/ftp

Then use sudo nano /etc/ssh/sshd_config to edit the ssh config.

Make sure this line is in place:

Subsystem       sftp    /usr/lib/openssh/sftp-server

Add this (note the -d /ftp which is missing from other guides):

Match Group sftponly
   ChrootDirectory %h
   ForceCommand internal-sftp -d /ftp
   AllowTcpForwarding no
   X11Forwarding no

Finally restart the SSH daemon:

sudo systemctl restart sshd

or, like old-timers like me prefer:

sudo service ssh restart

Explanation: The ChrootDirectory command will nicely place you into the user's home dir, but it's owned by root so he can't do anything. Since you can only use ChrootDirectory to go into a directory owned by root, you can't land in the user's /ftp folder. Within your FTP client, you could manually navigate with one click into the /ftp folder, but that's an extra step that not everyone would do right away. So, to be nice to your FTP user, the ForceCommand with -d /ftp will place you into the correctly permissioned subdirectory after you're logged in.

(Yes, you can still navigate backward one folder, but cannot navigate beyond that root-owned home folder, so you're safe.)

You should be able to upload/download, even delete anything in that ftp folder with this user.

Posted in Developing Software on Sep 16, 2021