Problem description:
You would like to jail users to their home directories and not allow shell access, only sftp access.
Solution:
SFTP chroot jail
1. Create a system group. Here I call it sftponly
.
1 |
groupadd -r sftponly |
2. edit the sshd_config file, usually residing in /etc/ssh/sshd_config
(in weird opensuse it’s in /usr/etc/sshd/ )
and append (it needs to be appended at the end):
1 2 3 4 5 6 7 8 9 10 11 12 |
PasswordAuthentication No Subsystem sftp internal-sftp Match Group sftponly ChrootDirectory %h AllowAgentForwarding no AllowTcpForwarding no GatewayPorts no X11Forwarding no PermitTTY no ForceCommand internal-sftp |
and restart sshd.
1 |
systemctl restart sshd |
PasswordAuthentication No
means, users can only login with their ssh key, no passwords allowed.
3. create the skeleton structure for each new user
1 |
mkdir /etc/skel/{.ssh,htdocs,log} |
we create .ssh htdocs and log dirs.
4. add a user and chown its home directory to root:root and set the login shell to nologin.
Also add this user to the sftponly
group and set proper access octals.
On Rocky 9 it’s in /usr/sbin/nologin
.
1 2 3 |
useradd -m -s /usr/sbin/nologin -G sftponly username chown 0:0 /home/username chmod 0755 /home/username |
5. add the client’s ed25519 public key to /home/username/.ssh/authorized_keys
1 |
echo 'ssh-ed25519 AAAA... username@clientmachine' > /home/username/.ssh/authorized_keys |
Where AAAA… is replaced by the actual public key from the client’s machine.
Check your /home/username/.ssh/id_ed25519.pub
file or that of your customer/friend/etc.
And that’s it.
Yes, that’s all there is to it.
The user will be able to transfer files via SFTP in the sub directories you created in step 3, but not write or create directories in the root directory.