Limit a Local System User Access to a Certain Folder when using SFTP on Linux (and disable SSH for him as well)

This situation might face a lot of us, if you have a certain file you want to share on your system using SFTP, but you don’t want that user to be able to:

  1. login via SSH and run any commands
  2. limit his access to a certain folder only

This can be done by what’s called chrooting.

To do this in Ubuntu (and can be applied to other Linux distros as well), follow the following steps:

  1. Create a user, let’s say his name is “external” for example
  2. Create a directory that’s writable ONLY by user root and group root “sudo mkdir /shared”
  3. open /etc/ssh/sshd_config for editing “sudo vi /etc/ssh/sshd_config”
  4. Comment the following line: “Subsystem       sftp    /usr/libexec/openssh/sftp-server” and add this section instead “Subsystem       sftp    internal-sftp”
  5. Add the following lines immediately after it, then save and exit:

    Match User external
    ChrootDirectory /shared
    AllowTCPForwarding no
    X11Forwarding no
    ForceCommand internal-sftp

  6. Restart the ssh service: “sudo /etc/init.d/ssh restart”

Now we’re done, note that this can be applied to groups as well, not just users.

As a test, first of all try using sftp and navigate to any folder other than /shared, e.g. /etc:

sftp external@myserver
external@myserver’s password:
Connected to myserver.
sftp> cd /etc
Couldn’t canonicalise: No such file or directory

Test Successful! You are jailed in the /shared folder and can’t navigate to anywhere else on the server

Second, try using ssh to connect using that user:

ssh external@myserver
external@myserver’s password:
This service allows sftp connections only.

Great! Everything is working now perfectly, Enjoy!


About SoCRaT

Systems Engineer, OSS & Linux Geek
This entry was posted in Uncategorized and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s