SFTP chroot with write access

I used to use rssh to lock access to SCP/SFTP only for a set of specific users.
However, the latest versions of OpenSSH has build in ChrootDirectory directive but it might not be straight forward as wrong directory permissions would not let to connect and give the folowing error

Write failed: Broken pipe
Couldn't read packet: Connection reset by peer

This can be easily fixed.

In the current scenario a ‘webdev’ user is granted access to update the web site over SFTP protocol.

Let’s assume that we use nginx and its virtual hosts are at /var/www/vhosts directory.
webdev user is granted access to update wwwtest.example.tld web site.

1. nginx vhost configuration

vhost root directory in nginx points to /var/www/vhosts/wwwtest.example.tld/web

 server {
     listen 80;
     server_name wwwtest.example.tld;
     location / {
         root /var/www/vhosts/wwwtest.example.tld/web;
         index index.html index.htm index.php;
     }
     ...
 }

2. sshd confiduration

Add the following entry to /etc/ssh/sshd_config file

Match User webdev
    X11Forwarding no
    AllowTcpForwarding no
    ChrootDirectory /var/www/vhosts/wwwtest.example.tld
    ForceCommand internal-sftp

3. create user webdev

# useradd -d /home/webdev -m webdev
# passwd webdev

4. adjust permissions
All the directories up to /var/www/vhosts/wwwtest.example.tld has to be owned by root and only root must have write access

# for i in /var /var/www /var/www/vhosts /var/www/vhosts/wwwtest.example.tld
# do
# chown root:root $i
# chmod 0755 $i
# done

5. create web site write directory at user’s home directory

# mkdir -p /home/webdev/wwwtest
# chown -R webdev:webdev /home/webdev/wwwtest

6. Create write mount point

# mkdir /var/www/vhosts/wwwtest.example.tld/web

7. Mount web site directory at the mount point

# mount --bind /home/webdev/wwwtest /var/www/vhosts/wwwtest.example.tld/web
# echo /home/webdev/wwwtest /var/www/vhosts/wwwtest.example.tld/web none bind >> /etc/fstab

8. Restart nginx and sshd

# service restart nginx
# service restart sshd

Now if webdev user SFTP into the server it will be chrooted into /var/www/vhosts/wwwtest.example.tld.
The web site files can be uploaded to web directory to which user webdev has write access now.