How to create an isolated/jailed SFTP user?

Not sure what OS you are using but I use the link below when I have to configure jailed SFTP users. It is a really good tutorial on how to configure a jailed SFTP user.

https://access.redhat.com/solutions/2399571

I would then mount bind whichever directory to the chroot directory you want to give your friend access to.


Working solution

This is inspired by the tutorial How to configure an sftp server with restricted chroot users with ssh keys mentioned in @HeysusEscobar's answer.

Do this from root:

useradd friend   # NB: this doesn't create a home dir, see https://askubuntu.com/q/374870
passwd friend    # set the password 
groupadd sftpusers
mkdir /sftp
mkdir /sftp/friend        # this is where he'll be chrooted
mkdir /sftp/friend/home   # his home directory
mkdir /sftp/friend/www    # for websites
usermod -aG sftpusers friend   # aG for append group
chown friend:sftpusers /sftp/friend/home/
chown friend:sftpusers /sftp/friend/www/
usermod -d /sftp/friend/home friend   # set as his home directory

Add this to /etc/ssh/sshd_config:

# Subsystem sftp /usr/lib/openssh/sftp-server   # you'll probably need to comment this line
Subsystem sftp internal-sftp -d /home
Match Group sftpusers
ChrootDirectory /sftp/%u

and do service sshd restart. That's all!

Note that:

  • other users can still ssh, so it did not modify anything for other users
  • user friend cannot ssh
  • user friend can connect via sftp

PS: if you want to make friend's website available to internet, you can add this to Apache config:

<VirtualHost *:80>
  ServerName friend.example.com
  DocumentRoot /sftp/friend/www
  php_admin_value "open_basedir" "/sftp/friend"
  <Directory />
    AllowOverride All
    Require all granted
  </Directory>
</VirtualHost>

Site-note: even with open_basedir above, can't friend still go out of his chrooted-environment with PHP or run malicious code having impact on the whole filesystem? Linked question: A chrooted/isolated SFTP user can still visit the whole filesystem with PHP


Old (half-working only) solution

Replacing ChrootDirectory /home/friend by ChrootDirectory /home helped, according to documentation:

ChrootDirectory: Specifies the pathname of a directory to chroot(2) to after authentication. All components of the pathname must be root- owned directories that are not writable by any other user or group.

With this, user friend can connect to SFTP again; cannot go out of /home/; but can still visit /home/anotheruser/..., which is unwanted!