Chrooted SFTP (RHEL 5)

Posted on Sun 13 February 2011 by Pavlo Khmel

On RHEL 5 with default installed openssh chroot will not allow to login via ssh. (Solution: run separate sshd on another port).
To use sftp and ssh on the same port is supported in RHEL 6.
For RHEL 5 we should use not-supported version of openssh.

Latest version: http://www.openssh.com/ for today is OpenSSH 5.8/5.8p1.

Installation
Download openssh-5.8p1.tar.gz
Installing packages needed for compilation:

yum install gcc zlib-devel openssl-devel
#Compilation:
tar -xvzf openssh-5.8p1.tar.gz
ls
cd openssh-5.8p1
./configure --prefix=/opt/openssh-5.8p1
make
make install
# Autostart configuration:
cp /etc/init.d/sshd /etc/init.d/sshd_orig

Update /etc/init.d/sshd with new paths

# Some functions to make the below more readable
KEYGEN=/opt/openssh-5.8p1/bin/ssh-keygen
SSHD=/opt/openssh-5.8p1/sbin/sshd
RSA1_KEY=/opt/openssh-5.8p1/etc/ssh_host_key
RSA_KEY=/opt/openssh-5.8p1/etc/ssh_host_rsa_key
DSA_KEY=/opt/openssh-5.8p1/etc/ssh_host_dsa_key
PID_FILE=/var/run/sshd.pid

Configuration
Add and change in /opt/openssh-5.8p1/etc/sshd_config:

# override default of no subsystems
#Subsystem sftp /opt/openssh-5.8p1/libexec/sftp-server
Subsystem sftp internal-sftp

Match group sftponly
     ChrootDirectory /test
     X11Forwarding no
     AllowTcpForwarding no
     ForceCommand internal-sftp

Match group group1
     # Set umask "-u"
     ForceCommand internal-sftp -u 0027
     ChrootDirectory /test1

Match group group2
     ForceCommand internal-sftp -u 0007
     # Set username "%u" or home directory "%h"
     ChrootDirectory /test1/%u

Restart sshd:

service sshd restart

Manual start of new sshd:

/opt/openssh-5.8p1/sbin/sshd

Adding sftp user
The directory /test must be owned by root.

groupadd sftponly
useradd phn -g sftponly
passwd phn
chown root:sftponly /test
chmod 750 /test

Public keys for sftp users should be located in default place: /home/[user name]/.ssh/authorized_keys
But user should have any password, to have access via public key.
If you want to have chrooted directory on different directory levels with different users. Directory owner should be user "root", group can be different.