CentOS / RHEL : How to Set up SFTP to Chroot Jail only for Specific Group

In order to allow ChrootDirectory functionality on a per-user basis, employ a conditionally-executed sshd configuration (using the “Match” keyword) in the sshd_config file. Setting ChrootDirectory on a specific Group, ensures that the users of that group can’t get out of their home directory, in turn ensuring no other users are affected.

1. Create a group for users who will be chrooted.

# groupadd sftp_group

2. Create a user for SFTP group & set password.

# useradd sftp_test1
# passwd sftp_test1
Changing password for user sftp_test1.
New password:
Retype new password:
passwd: all authentication tokens updated successfully.

3. Add sftp_test1 user to sftp_group group. Let the user shell be /bin/false as the users should only be allowed to do sftp and not ssh/scp.

# usermod -g sftp_group -s /bin/false sftp_test1
# id sftp_test1
uid=1000(sftp_test1) gid=1001(sftp_test1) groups=1001(sftp_test1),1000(sftp_group)
NOTE: Users not in this group can still log in to the host via ssh and otherwise interact with openssh normally.

4. Edit the sshd config to configure the sftp. Remove the /usr/libexec/openssh/sftp-server line and add internal-sftp line as shown below:
Remove or hash the line:

# vi /etc/ssh/sshd_config
Subsystem sftp /usr/libexec/openssh/sftp-server

add the below line:

# vi /etc/ssh/sshd_config
Subsystem sftp internal-sftp

5. Add the below content to the end of file /etc/ssh/sshd_config to add the sftp chroot environment:

# vi /etc/ssh/sshd_config
Match Group sftp_group
X11Forwarding no
AllowTcpForwarding no
ChrootDirectory /home
ForceCommand internal-sftp

5. Restart the sshd service to take effect of sftp configuration.

# systemctl restart sshd

Verify

1. Now try to access the system with SSH & SFTP service from other clients:
a. SSH

# ssh sftp_test1@x.x.x.x
The authenticity of host 'x.x.x.x (x.x.x.x)' can't be established.
ECDSA key fingerprint is 07:1c:34:30:f4:81:e1:e0:b3:13:30:b8:57:d9:d9:58.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'x.x.x.x' (ECDSA) to the list of known hosts.
sftp_test1@x.x.x.x's password:
Could not chdir to home directory /home/sftp_test1: No such file or directory
This service allows sftp connections only.
Connection to x.x.x.x closed.

As You see above connection closed and not allowed to login SSH.

b. SFTP

# sftp sftp_test1@x.x.x.x
sftp_test1@x.x.x.x's password:
Connected to x.x.x.x.
sftp> pwd
Remote working directory: /
sftp> ls
sftp_test1
sftp> cd /home
Couldn't canonicalize: No such file or directory
sftp>

As a result above sftp_test1 user is logged in via SFTP and can’t change the directory because of chroot environment

3. You can also test the SFTP-Server function from the windows client by using the “WinSCP” or “Filezilla” softwares.

Related Post