Saturday, 7 March 2015

Chroot Jail for SFTP users (student web server)

I want to create some temporary accounts on a Raspberry Pi for students to practice uploading files into a web server and testing their site. I am going to use sftp chroot jails to restrict the users to their respective homes, which contains only www folder, linked to /var/www/usersite.

First install apache2 on the Pi.

  1. Become root. In /etc/ssh/sshd_config, modify the Subsystem line for sftp:

    Subsystem sftp internal-sftp

    At the end of the file, add:
     Match Group sftponly
       ChrootDirectory %h
       ForceCommand internal-sftp
       AllowTcpForwarding no
       PermitTunnel no
       X11Forwarding no
    
    Restart ssh:

    service ssh restart

  2. Add /bin/false to the list of shells in /etc/shells. This is to prevent a normal functional account.
  3. Create a group sftponly, and look up its GID (1004 in the following example) addgroup sftponly
    cat /etc/group | grep sftp
  4. Create users from a file (userlist.txt) with this structure:
    student2:student2:20002:1004:web user:/home/student2:/bin/false
    student3:student3:20003:1004:web user:/home/student3:/bin/false
    username:pw:UID:GID:comment:home:shell

    Then use the newusers command:

    newusers userlist.txt

  5. Create www folders under homes, link in /var/www, change the ownership of the homes to root:sftponly, make the www folder group-writeable (home is not group-writeable, unusually).


    for u in $(cut -d : -f 1 userlist.txt); do mkdir /home/$u/www; ln -s /home/$u/www /var/www/$u; chown -R root:sftponly /home/$u; chmod g+w /home/$u/www; done

Now when students log in via sftp using Filezilla, they see only their home folder, which contains a www folder. They can't go anywhere else on the system, or even log in via ssh.