Home / How to set up sftp so that user cannot get out of their home directory

How to set up sftp so that user cannot get out of their home directory

This guide deals with how to set up sftp so that users are restricted to their home directory, while other users on the server are not affected.

  • To allow chroot only for specific users, use the Match keyword in /etc/ssh/sshd_config file.
  • Comment the original Subsystem entry in sshd_config file as follows:

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

  • Add the following Subsystem entry as follows:

Subsystem sftp internal-sftp

  • Type following at the end of /etc/ssh/sshd_config file and save it.

Match Group sftponly
ChrootDirectory /chroots/%u
AllowTcpForwarding no
ForceCommand internal-sftp
X11Forwarding no

  • Add a new group to add sftp users. Users in his group will be limited to their chrooted environment. These users will not have access to ssh/scp.

groupadd sftponly

  • Create accounts of sftp-chrooted-users. The home directory /home-sftp is relative to the chroot directory.
  • If the user already exists on the server then run:

usermod -g sftp -s /bin/false user

  • In case the user do not exist on the server then create a new user as follows:

useradd -d /home-sftp -M -g sftponly -s /bin/false user

  • For a newly created user account, set the password as follows:

passwd user

  • Make the chroot environment of the user and configure directory permissions while making sure the path is owned and writable by root only.

mkdir -p /chroots/user ; chmod -R 755 /chroots/user

  • In the above case, /chroot/user becomes the base root/ when the user is logged in to the server. If this is not the case then run the following command for chroot sftp setup.

chown root:root /chroots/user

  • Make the user’s actual home directory under ChrootDirectory and chown it user and group created above.

mkdir /chroots/user/home-sftp ; chown user:sftponly /chroots/user/home-sftp

  • The permission of /chroots/user/home-sftp should be 0755.
  • For setting the time zone of the host server in a chrooted environment, run the following command.

mkdir /chroots/user/etc/; cp /usr/share/zoneinfo/Asia/Singapore /chroots/user/etc/localtime

  • Restart sshd or reboot server.

systemctl restart sshd

Leave a Reply