How to use SFTP with a chroot jail

How to admin and use Linux system
Post Reply
User avatar
azo
Site Admin
Posts: 11
Joined: Mon Jun 10, 2019 9:23 am

How to use SFTP with a chroot jail

Post by azo »

Creating a new group
The first thing to do is to create a new group for SFTP users. Open a terminal window and issue the command:

Code: Select all

sudo groupadd sftponly
Adding and modifying users
Next, we need to add users to this new group. If you need to create a new users (and add them to the group), this can be done with the useradd command like so:

Code: Select all

sudo useradd -g sftponly -s /bin/false -m -d /home/USERNAME USERNAME
Where USERNAME is the name of the user to be added.

The above command will ensure the user is unable to log in via SSH, as it assigns /bin/false as the user’s shell. Once you add a new user, make sure to set a password with the command:

Code: Select all

sudo passwd USERNAME
Where USERNAME is the name of the user just added.

If you already have users you want to add to the group, you can do so with the command:

Code: Select all

sudo usermod -G sftponly -s /bin/false USERNAME
Where USERNAME is the user to be added and their shell will be changed. Do note, however, if the user does require SSH login, they won’t be able to do this once you make that change. If that’s the case, consider creating a new user specifically for their SFTP needs.

The user’s home directory permissions must now be changed. To do this, issue the following commands:

Code: Select all

sudo chown root: /home/USERNAME
sudo chmod 755 /home/USERNAME
With the user’s directories now owned by root, they won’t be able to create files and/or directories. To get around that (so they can upload and download files), create new subdirectories (within their home directory) that they will have access to with the following commands:

Code: Select all

sudo mkdir /home/USERNAME/{ftp_up,ftp_down}
sudo chmod 755 /home/USERNAME/{ftp_up,ftp_down}
sudo chown USERNAME:sftponly /home/USERNAME/{ftp_up,ftp_down}
Note: You can name the ftp_up and ftp_down anything you like.

Configuring SSH
Now we need to configure SSH. Issue the command:

Code: Select all

sudo nano /etc/ssh/sshd_config
In that file, look for the line:

Code: Select all

Subsystem sftp /usr/lib/openssh/sftp-server
Change that line to:

Code: Select all

Subsystem sftp internal-sftp
Scroll to the bottom of the file and add the following:

Code: Select all

Match Group sftponly
ChrootDirectory %h
ForceCommand internal-sftp
AllowTcpForwarding no
X11Forwarding no
Save and close the file. Restart the SSH daemon with the command:

Code: Select all

sudo systemctl restart sshd
Testing
Now we can actually test our new setup. Log in with one of the newly created users (or an existing user) with the command:

Code: Select all

sftp USERNAME@SERVER_IP
Post Reply