Use built-in Chroot sFTP to upload file

  06 Feb 2014


This post is just another tidbit intended for my own reference. Ok, let’s start to create a home directory for a user who needs an sftp account.

mkdir -p /var/sftp/upload

Add a new group and a new user without shell.

addgroup sftp
useradd catrocks -d /var/sftp/upload -M -N -G sftp -s /bin/false
chown catrocks:sftp /var/sftp/upload
passwd catrocks

And, the important tip for chroot is that the owner and the permission along the entire path must be owned by root and have permissions along the lines of 755 or 750 (/var and /var/sftp in this example)

chown root /var/sftp
chmod go-w /var/sftp

Check if your path permission is met the requirement. You could modify chrootdir path in the script below and run this little shell script:

chrootdir="/var/sftp"
ls -ld "$chrootdir"
while [ "$chrootdir" != "/" ]
do
    chrootdir=`dirname "$chrootdir"`
    ls -ld "$chrootdir"
done

The reason for this is to prevent a user from escalating their privileges and becoming root, escaping the chroot environment.

Now, it’s time to make sure that mr catrocks has a permission to upload his file to the upload directory:

chown catrocks:sftp /var/sftp/upload
chmod ug+rwX /var/sftp/upload

Tricky part, if you’d like to let user to login and start at his home directory. Check /etc/passwd file and find the catrocks user. Then, change from

catrocks:x:1004:1008:,,,:/var/sftp/upload:/bin/bash

to

catrocks:x:1004:1008:,,,:/upload:/bin/bash

Config OpenSSH by opening /etc/ssh/sshd_config file to edit and configure OpenSSH to use its internal SFTP subsystem.

Search for the follwing line and comment it out:

Subsystem sftp /usr/lib/openssh/sftp-server

And, add following setting instead:

Subsystem sftp internal-sftp
Match Group sftp
    ChrootDirectory /var/sftp
    ForceCommand internal-sftp
    X11Forwarding no
    AllowTcpForwarding no

at the end of the file (CAVEAT: In sshd_config, Match blocks must be located at the end of the file), I have spent enough time to debug this.

Save the sshd_config file and restart sshd service

service ssh restart

Use sftp client to test it out:

sftp catrocks@sftp-server-address

catrocks@sftp-server-address's password:
Connected to sftp-server-address
sftp>

If it just works, then you are the man. If there is any error, you could check the auth log at /var/log/auth.log for what the system complains about.

comments powered by Disqus