Pages

Wednesday, September 13, 2017

How to enable SFTP and disable SSH

Sometimes you want to have users, that have access to files on your server, but don't want them to be able to log in and execute commands on your server.This is done quite easily.

Add user as usually and assign him a password. Then run the following command (replace the 'username' with real user name):

Step 1: Modify the Users Shell

root@host # usermod -s /usr/lib/sftp-server username
This changes user's shell to sftp-server.

The last step for this to work is to add '/usr/lib/sftp-server' to /etc/shells to make it a valid shell, eg. like this:

root@host # echo '/usr/lib/stfp-server' >> /etc/shells

Step 2: Modify the Users Shell

There. Now you've setup a user who can only access your server with SFTP.

Subsystem sftp internal-sftp

And then block other uses:
Match group sftponly
     ChrootDirectory /home/%u
     X11Forwarding no
     AllowTcpForwarding no
     ForceCommand internal-sftp

Add your users to the sftponly group. You have to change the user's homedirectory to / because of the chroot and /home/user should be owned by root. I'd also set /bin/false as the user's shell.

Step 2: Directory Structure & Permissions

Lets setup the correct directory structure and file system security.

Just a quick note regarding the ChrootDirectory value. As you can see I’ve used /var/www/andrew however this is not the document root of the website. There is a subfolder called webroot (/var/www/andrew/webroot) which is where the user would store all their web documents. I’ve found that you’ll get unexpected results if you try drop the user directly into a directory in which they have owner/group permissions.

So we chroot the user to /var/www/andrew, however we don’t give the user andrew access other than read and execute permissions on that directory.

# ls -lad /var/www/andrew
drwxr-xr-x 3 root root 4096 Jan  7 13:24 /var/www/andrew
To configure the above permissions run:

# chown root:root /var/www/andrew ; chmod 755 /var/www/andrew
Now lets look at the file permissions of the actual webroot folder (this is where the users working web documents would be stored).

# ls -lad /var/www/andrew/webroot
drwxrwxr-x 7 andrew andrew 4096 Jan  7 13:39 /var/www/andrew/webroot
To configure the above settings run:

# chown andrew:andrew /var/www/andrew/webroot ; chmod 775 /var/www/andrew/webroot

No comments:

Post a Comment