Set up a new user in a chroot jail for secure file transfers using SFTP

File transfers on the internet usually consist of uploading your file to a remote server, whether that involves email, file hosting sites, or chat applications like skype that send everything you do directly to some nefarious agency .
With Linux, and the SSH protocol, we can cut out all these unknown middlemen and let our friends send us files directly over an encrypted connection.

The issue with ssh is you want to be able to control what files can be accessed on your machine, and don’t want to give away your system password to anyone, even friends!

Luckily all we need to do to ensure these conditions are met, is make a new user and chroot jail that user to a particular directory. Many of the following commands will only run as root or sudo.

  • Register a free DDNS here, and point it at your external IP address.
  • Create a new group for the sftpuser:
    groupadd sftpusers
  • Create a new user with a nologin shell for your friends to use and set a password for that user:
    useradd -g sftpusers -d /incoming -s /sbin/nologin friend
    passwd friend
  • Edit your sshd config at /etc/ssh/sshd_config and replace this line:
    Subsystem sftp /usr/libexec/openssh/sftp-server
    Subsystem sftp internal-sftp
  • Create the chroot jail for the sftpusers group by adding these lines to the end of your sshd_config:
    Match Group sftpusers
        ChrootDirectory /sftp/%u
        ForceCommand internal-sftp
  • Finally, create the necessary directories and set permissions:
    mkdir /sftp
    mkdir /sftp/friend
    mkdir /sftp/friend/incoming
    chown friend:sftpusers /sftp/friend/incoming
    service sshd restart
  • Finally forward some random high port (25376) ? at your router to 22 at your internal ip address.

You should now be set to give your friend the password for the account you just created and they should be able to sftp files into your computer at /sftp/friend/incoming using a command similar to:

sftp -P 25376

Here is a simple script that will add users to this system with their own account and chroot jail: