Linux Programmer | RHCE | RHCSA

Search This Blog

How to restricted SFTP-only access to a single directory?

Create a system group sftp-group.
Create a /home/sftp-group/ directory and files/ a directory within it.
Allow users in the sftp-group group to connect to the server using SFTP (but not SSH).
Lock users in the sftp-group group into the /home/sftp-group/directory using a chroot.
Restrict some other options for users in the sftp-group group.

So we’ll allow these users to connect to the SSH server and use SFTP to access a specific directory, and nothing else.

Preparations

First, lets create the new group:
Then create the new directories:

SSHD configuration

The OpenSSH server configuration is typically called something like /etc/ssh/sshd_config. Find this file and open it in an editor.                         First we’ll make sure it will support SFTP in a chrooted environment. Search for a existing Subsystem sftp statement or insert it if it’s missing:
# Enable to built-in implementation of SFTP.
Subsystem sftp internal-sftp
Next we’re going to add a section to the end of the file using the Match directive which applies to users in our group:
Match Group sftp-group
After that we specify the configuration directives which apply the matched connections:
# Force the connection to use the built-in SFTP support.
ForceCommand internal-sftp
ChrootDirectory /home/sftp-group
# Chroot the connection into the specified directory.
Let’s lock down some of the additional capabilities of the OpenSSH server so these people can’t, e.g., forward connections through the server and into our private network:
# Disable network tunneling
PermitTunnel no
# Disable authentication agent forwarding.
AllowAgentForwarding no
# Disable X11 remote desktop forwarding.
# Disable TCP connection forwarding. AllowTcpForwarding no
X11Forwarding no
So the whole block looks like this:
Match Group sftp-group
# Force the connection to use SFTP and chroot to the required directory.
ForceCommand internal-sftp ChrootDirectory /home/sftp-group
PermitTunnel no
# Disable tunneling, authentication agent, TCP and X11 forwarding. AllowAgentForwarding no AllowTcpForwarding no
X11Forwarding no

Testing

To apply the configuration change, just restart your SSH server, create a user and try to access the site.
Connecting with sftp should result in a connection, but ssh should return an error message:
This service allows sftp connections only.
Connection to server.example.com closed.
When connected you should be able to list, upload and delete files under /files/.
Note : The directory ownership must be root. 
chown root:root /home/sftp-user

No comments:

Post a Comment

SSH not working with password after upgrade ubuntu 22.04 or above

In recent upgrade of ubuntu 22.04 and above we are not able to login server with SSH password. but when we try to login with key then it all...