Goal: allow a user to access only one directory by sftp or sshfs, and only that directory, with no shell access.
1. Create a new user and change ownership of their home directory to root (as root):
adduser testuser
chown root.root /home/testuser
2. Create a sub-directory in the user’s home:
mkdir /home/testuser/data
chown testuser.testuser /home/testuser/data
This is necessary because chroot requires the directory to be owned by root. So when the user logs in, the system changes the root to /home/testuser, which isn’t writable by testuser. Upon login, the user has to change into a directory he/she owns.
3. Add the following to your /etc/ssh/sshd_config and restart/reload ssh:
Subsystem sftp internal-sftp
Match user testuser
ChrootDirectory /home/testuser/
X11Forwarding no
AllowTcpForwarding no
ForceCommand internal-sftp
4. Now access /home/testuser/data remotely:
Via sftp:
sftp testuser@yourserver
cd data
Via sshfs:
sshfs testuser@yourserver:data ~/data
When testuser tries to mount anything outside /home/testuser/, it will get an error because there’s nothing else in the chroot environment where the user is jailed:
sshfs testuser@yourserver:/etc ~/data
testuser@yourserver:/etc/: No such file or directory
When testuser tries to login, he or she also gets an error:
ssh testuser@yourserver
This service allows sftp connections only.
Connection to yourserver closed.