In some cases, you may want to prohibit users within a Linux server from creating a Secure Shell (SSH) session and only allow them to connect to the SSH File Transfer Protocol (SFTP). This is commonly done in web hosting environments in which each customer should only be able to connect to the SFTP to transfer files to their own website directories. In order to configure your Linux server to work this way, follow the steps below.
Configure the SSH Server with an "sftponly" Group
These steps are necessary to configure the SSH server to provide a different file system root directory for each user within the "sftponly" group you will be adding.
- Add a group named "sftponly" by running this command:
sudo groupadd sftponly
- Open the SSH server config file for editing:
sudo nano /etc/ssh/sshd_config
- Find the line that says
Subsystem sftp /usr/lib/openssh/sftp-serverand change it to:
Subsystem sftp internal-sftp
- At the end of the file, under the line containing the UsePAM setting, add these lines:
Match Group sftponly ChrootDirectory %h ForceCommand internal-sftp AllowTcpForwarding no X11Forwarding no
- Save and close the file, then restart the SSH server with this command:
sudo service ssh restart
At this point, you have configured your SSH server to handle SFTP access properly.
Add a User to the Group
For these instructions, "bob" is an example of a user's name. Replace the name "bob" with the name of the user you want to apply these changes to. To begin with, if you have not created the user yet, you can run the
sudo adduser bob command, which will create a home directory at
- Add a user to the group by running this command:
sudo usermod -G sftponly bob
- Prevent the user from logging into the SSH:
sudo usermod -s /bin/false bob
After running these commands, the user cannot access the SSH and can only connect to the SFTP to upload or download files within their home directory.
Create a Permissive Directory
You may want to disallow the user from transferring files at any location within their home directory except for a specific directory, such as
/home/bob/www/example.com. Follow the steps below to do this.
- Change the ownership of the user's home directory to the root user by running this command:
sudo chown root:root /home/bob
- Change the access permissions of the user's home directory to have suitable read, write, and execute permissions:
sudo chmod 755 /home/bob
- Create the permissive directory:
sudo mkdir -p /home/bob/www/example.com
- Give the user permission to the directory you just created:
sudo chown bob:bob /home/bob/www/example.com
Now, the user can only write and remove files within the "example.com" directory and cannot remove the directory itself.