Chrooting sftp users to home directory with openSSH
Chrooting sftp users to home directory with openSSH
In shared hosting environment it might be desired that users can only do sftp and cannot execute shell commands. Also it is desired that users cannot access any file outside their home directory. This can be achieved by chrooting users to their home directory. Creating a directory where 'chroot' would work is not easy task as lot of devices, files, etc. need to be in place for chroot to be successful. Hence we use internal-sftp server of openssh (version 4.9+) which can chroot without requiring any of these files.
Updating ssh on CentOS 5.5
- Download latest openssh portable source code from http://www.openssh.org/portable.html This is to ensure that ssh version in 4.9+. In case SSH version is already greater than 4.9 then compiling from source is not required.
- Configure using './configure --with-tcp-wrappers --with-pam --with-rand-helper --with-md5-passwords --prefix=/ --sysconfdir=/etc/ssh --sbindir=/usr/sbin --bindir=/usr/bin'
- --with-audit and --with-selinux give problem during configure or make and hence should be avoided.
- make clean
- make
- rm /etc/ssh/* (since make install does not overwrite old files).
- make install
Configuring sftp chroot for user/group
- Edit file /etc/ssh/sshd_config
- Port 22
- Protocol 2
- PermitRootLogin yes
- Subsystem sftp internal-sftp
- Match Group sftponly
- ChrootDirectory %h
- ForceCommand internal-sftp
- AllowTcpForwarding no
- X11Forwarding no
- service sshd restart
- useradd saurabh
- passwd saurabh
- groupadd sftponly
- usermod -g sftponly saurabh
- chown root:root /home/saurabh
- chmod 755 /home/saurabh
- mkdir /home/saurabh/public_html_secret
- mkdir /home/saurabh/private
- Note that user wont be able to create files in his / her home directory as it is owned by root which is required for chroot. Hence we have to create first level of directories for user.
- chown saurabh:sftponly /home/saurabh/*
- chmod 700 /home/saurabh/private
- chmod 755 /home/saurabh/public_html
Note that after this only sftp, gftp, winscp, etc. will work. This does not allow rsync to work. To make rsync work we would have to setup proper chroot environment with device files, password files, binary files, libraries, etc.
One can test the setup by using both 'ssh' and 'sftp' commands for user saurabh on machine configured as explained above to ensure that only sftp is working. After connecting using 'sftp' try 'cd ..' or 'cd /' to ensure that user can't get out of home directory.
Procedure has been learned from http://www.minstrel.org.uk/papers/sftp/builtin/