A missing blog post image

Introduction

Using SFTP from SSH daemon is, in my opinion, not really well-documented and thrown errors are not always very explicit.
Add some security in the mix and nothing works as expected.

This is a short guide (acting a bit as a memo I admit) for SSH + SFTP + Chroot + Public key authentication :wink:

The procedure

On “SFTP” server side

Firstly we will create a new unprivileged user, without any password :

adduser archiver \
	-s /bin/bash \
	--home /home/archiver \
	--disabled-password

Now that is done, we may start our reception folder creation (still as root) :

mkdir -p /home/archiver/chroot/folder

As clients will put their files into folder/, the system user they will be using must have permissions on it :

chown archiver:archiver /home/archiver/chroot/folder

:warning: This is important, each one of the path elements leading to the chroot destination folder MUST HAVE 0755 UNIX permissions at most :warning:

You can enforce this statement with the following (commented lines should be already OK, but who knows ?) :

#chmod 0755 /
#chmod 0755 /home
#chmod 0755 /home/archiver
chmod 0755 /home/archiver/chroot

If you don’t, ssh won’t be able to chroot anywhere and your operations will crash with misguiding error in SSH logs.

Now we may tweak SSH configuration (/etc/ssh/sshd_config) :

# ...

Match User archiver
	X11Forwarding no
	AllowTCPForwarding no
	ChrootDirectory /home/archiver/chroot/
	ForceCommand internal-sftp -P read,remove -d folder/

The -P parameter allows us to restrain the operations that clients will be able to perform (black-list).
With read,remove set, clients won’t be able to fetch nor remove any files already present (useful for a write-only backup folder).
Run /usr/lib/openssh/sftp-server -Q requests to check which protocol requests you may provide.
I’ve tried to use the -p that is on the contrary a protocol requests white-list, but couldn’t figure out why it didn’t work with the thrown errors…

Please note that those protocol requests HAVE NOTHING TO DO with the (S)FTP commands that could be sent (put, get, cd, etc.).

The -d parameter will directly set clients into folder/.
This is very useful for interactive FTP operations because it allows clients not to cd somewhere and directly perform their actions.


Finally, we restart the sshd daemon :

systemctl restart ssh.service

On “SFTP” client side

We will begin here by generating a new ED25519 keys pair :

cd
ssh-keygen -t ed25519
cat .ssh/id_ed25519.pub
# Copy here the displayed public key

Before continuing, you’ll have to paste the public key within /home/archiver/.ssh/authorized_keys file on your SFTP server.

Now, you should be allowed to perform your first SFTP operation (:tada:) :

sftp -q archiver@YOUR.SFTP.SERVER.IP:/folder/ <<< $'put your_file_to_be_transfered.tar.gz'

The command issued in the snippet above IS AN EXAMPLE. Feel free to adapt it your way.

Conclusion

:wave:

References