Create SFTP User / Group with CHROOT option in Linux / Unix

By | July 25, 2018

Bismillahi-r-Rahmani-r-Rahim (In the name of Allah, the most Compassionate, the most Merciful)

Assalamu alaikum wa rahmatullahi wa barakatuh (May the peace, mercy, and blessings of Allah be with you)


This is the ad hoc tutorial on how to create sftp user with chroot option in CentOS. We will create a single sftp user with chroot folder defined as web sources folder. Additionally, we will create separate sftp group with the users having dynamic chrooted home folder.

Below content is complementary to the video tutorial above.

Scenario 1:
We have a web sources folder and we need to create sftp user with chrooted web sources folder

Install necessary utils if needed:

yum install -y nano openssh-server

Create the corresponding user:

useradd -g apache sftp_www
passwd sftp_www

Edit sshd_config file:

nano /etc/ssh/sshd_config

Add the following lines at the end of sshd_config file:

Subsystem sftp internal-sftp
Match User sftp_www
X11Forwarding no
AllowTcpForwarding no
ChrootDirectory /var/www/html/adhoctuts1/html
ForceCommand internal-sftp -u 002 #default umask for 775

Important Notes:
1. Only single Subsystem line is allowed in sshd_config file, so comment others if any.
2. Every element in ChrootDirectory path must be owned by root [also additionally has an executable permission if needed].
3. All the content inside the chroot directory must be accessible by the sftp user.
4. The final element in the chroot path must be at least readable by the sftp user.
5. https://en.wikipedia.org/wiki/Chmod – to learn about permissions:
numerical permission for directory = 777 – umask.
numerical permission for file = 666 – umask.

Restart the sshd service:

service sshd restart

or

systemctl restart sshd

Scenario 2:
We will create separate Group so that each user of this Group will have its home directory chrooted

Create the group and the user:

user_name="sftp_user"
groupadd sftp_users
useradd -g sftp_users $user_name
mkdir /home/$user_name/documents
mkdir /home/$user_name/pictures
chown root:root /home/$user_name
chmod 755 /home/$user_name
chown $user_name:sftp_users /home/$user_name/*
passwd $user_name

Edit sshd_config file:

nano /etc/ssh/sshd_config

Add the following to the sshd_config file:

Match Group sftp_users
X11Forwarding no
AllowTcpForwarding no
ChrootDirectory /home/%u
ForceCommand internal-sftp -u 077 #default umask for 700

Restart the sshd service:

service sshd restart

or

systemctl restart sshd

If you want to delete user:

userdel -rf $user_name

Related resources: