Setup Chroot SFTP in Linux (Allow Only SFTP, Not SSH)

How to Setup chroot SFTP in Linux environment

Setup an account on system that will be used only to transfer files (and not to ssh to the system)

First you need to  Create a group called sftpusers. Only users who belong to this group will be automatically restricted to the SFTP chroot environment on this system.

root@linuxtweaks [~]# groupadd sftpusers

Now, you want to create an user who should be allowed only to perform SFTP in a chroot environment, and should not be allowed to perform Shell Access(SSH).
The following command creates user e.g demo, assigns this user to sftpusers group, make /home/demo as the home directory, set /sbin/nologin as shell (which will not allow the user to ssh and get shell access).

root@linuxtweaks [~]# useradd -g sftpusers -d /home/demo -s /sbin/nologin demo
root@linuxtweaks [~]# passwd demo

If you want to modify an existing user and make him an sftp user only and put him in the chroot sftp jail, do the following:

root@linuxtweaks [~]# usermod -g sftpusers -d / -s /sbin/nologin demo

Setup sftp-server Subsystem in sshd_config
At this point, you should instruct sshd to use the internal-sftp for sftp (instead of the default sftp-server).
So, you need to Modify the the /etc/ssh/sshd_config file and comment out the line and add the new line to the /etc/ssh/sshd_config file as below.

#Subsystem       sftp    /usr/libexec/openssh/sftp-server
Subsystem       sftp    internal-sftp

Specify Chroot Directory for a Group by editing the /etc/ssh/sshd_config file.

Match Group sftpusers
        ChrootDirectory /home/%u
        ForceCommand internal-sftp

Under the directory /home/demo, create any subdirectory that you like user to see. For example, create a public directory where users can sftp their files.

root@linuxtweaks [~]# mkdir /home/demo/public

For chroot to work properly, you need to make sure appropriate permissions are setup properly on the directory for every user.

Set the owenership to the user, and group to the sftpusers group as shown below.

root@linuxtweaks [~]# chown demo:sftpusers /home/demo/public

Make sure that, the permission will look like the following for the /home/demo directory.

root@linuxtweaks [~]# ls -ld /home/demo
drwxr-xr-x 3 root root 4096 Dec 1 23:49 /home/demo

root@linuxtweaks [~]# ls -ld /home
drwxr-xr-x 3 root root 4096 Dec 1 23:49 /home

At last you need restart the ssh and test you sftp user.

Balvinder Singh

Hello, I am Balvinder Singh - DevOps Engineer with 2.5+ year of working experience with different server environments. Tag Line:-Linux | AWS| WHM |Monitoring | Virtualization | Optimization | Performance | Security | Release & Deployment. I love helping companies / clients to deploy their code / applicateions to well managed, optimized, secure server and can go extra mile to satisfy.

You may also like...

Leave a Reply

Your email address will not be published.