Restrict SFTP users to their home folder

sftp

I want to restrict SFTP users to their home folder so that they won't see anybody else's folder/home directories. Unfortunately all SFTP users can see other user's folders at the moment. All the posts and examples points out ChrootDirectory but for some reason I cannot get it working.

$ sudo nano /etc/ssh/sshd_config

Subsystem sftp internal-sftp
Match Group sftp
  ChrootDirectory %h            # The %h causes "Broken pipe" error while trying to login
  ChrootDirectory /var/sftp     # This allows login but all SFTP folders are visible to all user
  X11Forwarding no
  AllowTcpForwarding no
  AllowAgentForwarding no
  PermitTunnel no
  ForceCommand internal-sftp

Users, Permissions and Folders

I used command below to create users and folders.

sudo useradd -m -d /var/sftp/hello -G sftp hello --shell /usr/sbin/nologin

Result

ubuntu@linux:~$ grep hello /etc/passwd
hello:x:1001:1002::/var/sftp/hello:/usr/sbin/nologin

ubuntu@linux:~$ grep world /etc/passwd
world:x:1002:1003::/var/sftp/world:/usr/sbin/nologin

ubuntu@linux:~$ ls -l /var/
drwxr-xr-x  4 root root   4096 May  7 14:48 sftp

ubuntu@linux:~$ ls -l /var/sftp/
drwxr-xr-x 3 hello sftp 4096 May  7 14:01 hello
drwxr-xr-x 2 world sftp 4096 May  7 14:48 world

SOLUTION

The problem here is that, I had to let root:root own the home folder of my users and create another folder under users' home folder (e.g. uploads) then own it as hello|world:sftp. Originally the home folders were owned by hello|world:sftp.

Best Answer

For security reasons users under chroot shouldn't be able to create arbitrary files (for example /etc/shadow and countless others). That's why sshd forces you to take away ownership and writing privilege of the chrooted directory itself:

chown root:root /var/sftp/hello
chmod o-w       /var/sftp/hello

Alternative solution, without any sshd ChrootDirectory depends on the fact that user can only list a directory if they have r permission, while using it requires only x permission:

chown root:root /var/sftp
chmod o=x       /var/sftp    # implicitly removes rw, sets only x