Setup SFTP-Only User Accounts On Ubuntu 14

Modified on: Thu, Apr 7, 2016 at 12:55 pm EST

Introduction

Certain scenarios require you to create users with read and write access to a single directory via FTP only. This write-up will show you how to create such users. They will not be able to navigate outside their home directory, login to the server via SSH, or execute shell commands.

Setup SFTP Group and Service

  1. Create sftpusers group.

    sudo groupadd sftpusers
    
  2. Comment out setting disabling SFTP access from sshd config file.

    sudo sed -i "s/Subsystem sftp \/usr\/lib\/openssh\/sftp-server/#Subsystem sftp \/usr\/lib\/openssh\/sftp-server/" /etc/ssh/sshd_config
    
  3. Open sshd config file sudo nano /etc/ssh/sshd_config, add below snippet it, and exit (Ctrl+X -> Y -> Hit Enter).

    #enable sftp
    Subsystem sftp internal-sftp
    
    Match Group sftpusers
       ChrootDirectory %h #set the home directory
       ForceCommand internal-sftp
       X11Forwarding no
       AllowTCPForwarding no
       PasswordAuthentication yes
    
  4. Restart ssh.

    sudo service ssh restart
    

Creating Users

Repeat the process below for every SFTP only user you want to add to the server.

# create user
sudo adduser sftpuser1

# prevent ssh login & assign SFTP group
sudo usermod -g sftpusers sftpuser1
sudo usermod -s /bin/nologin sftpuser1

# chroot user (so they only see their directory after login)
sudo chown root:sftpuser1 /home/sftpuser1
sudo chmod 755 /home/sftpuser1

sudo mkdir /home/sftpuser1/uploads
sudo chown sftpuser1:sftpuser1 /home/sftpuser1/uploads
sudo chmod 755 /home/sftpuser1/uploads

You can make creating users faster by wrapping above into a function and adding it to your bashprofile by (1) running sudo nano ~/.bash_profile; (2) adding the snippet below to it; (3) running source ~/.bash_profile.

After that, creating a new SFTP user becomes as easy as running the command create_sftp_user along with a username as its parameter.

# usage: create_sftp_user <username>
function create_sftp_user() {
    # create user
    sudo adduser $1

    # prevent ssh login & assign SFTP group
    sudo usermod -g sftpusers $1
    sudo usermod -s /bin/nologin $1

    # chroot user (so they only see their directory after login)
    sudo chown root:$1 /home/$1
    sudo chmod 755 /home/$1

    sudo mkdir /home/$1/uploads
    sudo chown $1:$1 /home/$1/uploads
    sudo chmod 755 /home/$1/uploads
}

Test to make sure the user you created can connect to the server via SFTP (Note: Connect using SFTP and not FTP).

Get started in the SSD Cloud!