With Linux allow specific account secure SFTP access from outside

The following situation: I have a web server, for a specific directory I want to allow access via SFTP from outside. This access should only be able to see certain directories (chroot). Another account should be accessible from my home network via SSH.

Step 1 Create User

Add user for sftp access from outside

useradd www-access

Modify Groups

usermod -a -G www-data www-access
usermod -a -G www-access www-data

Step 2 Set directory rights

Here I took the starting directory of my webserver. Modify rights of sub directories

cd /var/www/
chown -R www-data:www-data .
find . -type d -exec chmod 0775 {} \;
find . -type f -exec chmod 0664 {} \;

The root directory of the webserver must be root and only this account can have write permissions.

chown root:root /var/www
chmod 0755 /var/www

If the SFTP connection is rejected after login, please check the access rights of /var/www. It must be the owner and the group root and only the owner may have write permissions.

Step 3 Modify SSH Service

Edit the following file

nano /etc/ssh/sshd_config

Edit this row

#Subsystem sftp /usr/lib/openssh/sftp-server
Subsystem sftp internal-sftp

Add this code on the end of the file

AllowUsers pi@192.168.* www-access

#chroot for www-access
Match User www-access
	ForceCommand internal-sftp
	ChrootDirectory /var/www
	AllowTCPForwarding no
	X11Forwarding no

Here only the user pi and www-access is allowed to log in. Pi, only one SSH login from the network area 192.168. is allowed. With the “Match User www-access” and its options, this user is only allowed to log in via SFTP and not via SSH. The main directory is converted to /var/ www. It can not create files or directories in this directory, but in its subdirectories it can.

Restart SSH Service

service ssh restart

Step 4 Allow access from outside

Most have a router from the provider. In this, forwarding (NAT) must be set to the IP address of the computer with the TCP port 22.

To always have your Internet address, you can use a Dynamic DNS service on the router. Suppliers are e.g. http://dyn.com/dns/?rdr=dyndnsorg and http://www.noip.com/. Not every router supports any provider. For Kabel Deutschland customers: this service is not available in the normal cable modem. However, this modem can be put into bridge mode via the customer site, so that you can operate your own router behind the modem. Wireless Lan does not function at this cable modem, but over the own rout already.

Leave a Reply

Your email address will not be published. Required fields are marked *