Today I had to set up a secure dropbox for some of our customers to deliver files to us via FTP over an SSH tunnel. However we didn’t want to just dish out SSH user accounts to anyone, so here’s how I locked down the server so users could only upload/download files to their home directory
First off, for the following guide to work you must have OpenSSH 4.9p1 or newer installed on the server. I think the latest version (at time of writing this) is 6.6 so you should be ok.
Next you need to configure SSH to handle locking down users in the sftp
group. This is done by editing the /etc/ssh/sshd_config
file
Find the Subsystem sftp /path/to/subsystem
and change it to
Subsystem sftp internal-sftp
Then add the following to the end of the file
Match Group sftp
ChrootDirectory %h
ForceCommand internal-sftp
AllowTcpForwarding no
Finally restart ssh
sudo /etc/init.d/sshd restart
Now that SSH is set up, we need to sort out the new user.
As we will be locking down users in the sftp
group, we need to make sure we have one on the server. The following command will create the user group for us.
groupadd sftp
Now, lets create and set up the user
# create a user
useradd username
# set the password for username
passwd username
After running the previous command you will need to type the password for the new username and confirm it. When you do this, there is no text and no cursor to show you the password, but it is going in. Just make sure you get a tokens successfully updated
message
We have our new user, but at the moment they have full SSH access, we only want them to access their home directory for upload and download.
The following command sets the new users shell command to /bin/false
which prevents them from accessing the servers shell under any circumstances.
usermod -s /bin/false username
Then we add them to the sftp
group we created earlier
usermod -G sftp username
Lastly we change the permissions on their home directory top level to prevent changes to it
# Modify their home directory to prevent root dir changes
chown root:root /home/username
chmod 0755 /home/username
And provide them with an uploads
directory they can use.
#Add uploads dir to home and allow them access
mkdir /home/username/uploads
chown username:username /home/username/uploads
chmod 0755 /home/username/uploads
If you try to SSH into the server using this new user account you should get an error message along the lines of This service only allows stfp. Connection terminated
, but if you do the same from an SFTP client you will see the home directory with the uploads directory within. You won’t be able to write to the root of home, but you will have full access to uploads.
There you go. A secure file transfer setup that prevents users from accessing the shell on your server.