System Administration

05. May 2022

How to setup a user based web server with SFTP access

Have you ever wondered how to securely set up a user based web server like managed hosters do?

If the user should only access specific directories on the file system, we talk about jailing users. In this case, we want to restrict the user to a web server directory.

This is usually done by editing the chroot settings.

User creation and permissions

First, we will create a user called john, who is a member of the group www-data.
If you already have a user member of this group, you can skip this step.

# Create the user john
useradd john

# Assign a password to the user
passwd john

# Add john to the group www-data
# -aG - add user to a group
usermod -aG www-data john

SSHD Configuration

By restricting the user to the directory /var/www/john, the account will only have access to that.

Configuring X11Forwarding to use SSH allows the users to run graphical applications over SSH sessions securely.
If you want to read more on this topic, it is explained further in this article.

If you add ForceCommand internal-sftp it tells sshd to use the internal SFTP server built-in sshd instead of running it in another process. Also, the user will only be able to use SFTP, no other command. So no SSH Login is possible with this setting.
I found this information here to be helpful.

Add these lines to the end of your sshd configuration, which you can find in /etc/ssh/sshd_config.

Match User john
        ChrootDirectory /var/www/john
        AllowTCPForwarding no
        X11Forwarding no
        ForceCommand internal-sftp

You can also match groups by changing the first line to Match Group ${GROUP-NAME}.

Now you must restart your sshd server with one of the following commands.

systemctl restart sshd
# OR
service sshd restart

File and Folder permissions

This enabled the /var/www/john directory to have the correct permissions to view and then be able to write to subdirectories.

# user directory /var/www/john
# User is not allowed to write here.
chown root:root /var/www/john
chmod 755 /var/www/john

# site directory /var/www/john/site1
# User is allowed to write here.
chown root:john /var/www/john/site1
chmod 775 /var/www/john/site1

# site files within /var/www/john/site1/*
# This only works if there are already files within the directory.
# Otherwise just skip.
chown john:www-data /var/www/john/site1/*
chmod 755 /var/www/john/site1/*

You have now set up a user based web server and john will be able to upload, download or edit files within the /var/www/john/site1 directory.

I cannot be help responsible for any injuries, legal problems or damage to your devices.
You act upon your own responsibility and risk.