Chrooted (jail) home via SSH, SFTP and FTP

OS: RHEL 6.x, CentOS 6.x
Simultaneous chrooted home via SSH, SFTP and FTP

SSHD changes in file /etc/ssh/sshd_config

#Subsystem sftp /usr/libexec/openssh/sftp-server
Subsystem sftp internal-sftp
Match group chrooted
         ChrootDirectory %h
         X11Forwarding no
         AllowTcpForwarding no

This changes will affect users in group chrooted.

VSFTPD changes in file /etc/vsftpd/vsftpd.conf

#anonymous_enable=YES
anonymous_enable=NO
user_config_dir=/etc/vsftpd/users
chroot_local_user=YES
chroot_list_enable=YES
# for not chrooted users
chroot_list_file=/etc/vsftpd/chroot_list

Each chrooted FTP user should have file:

# cat /etc/vsftpd/users/usertest
local_root=home/user/test

Created chrooted user:

useradd usertest -G chrooted
passwd usertest
/root/create_chroot_env.sh /home/usertest

"create_chroot_env.sh" script automates additional actions.

#!/bin/bash
chrooted_home=$1
user_name=`echo $chrooted_home | awk -F/ '{ print $NF }'`
virtual_home=`echo ${chrooted_home} | sed 's//home/home/'`
echo "local_root=${virtual_home}" > /etc/vsftpd/users/${user_name}

if ! echo $1 | grep -q "^/home/" ; then
    echo "Usage: create_chroot_env.sh </home/username>";
    exit 1;
fi

if [ ! -e $chrooted_home ]; then
    echo "Home directory does not exists.";
    exit 1;
fi

if ! cd $chrooted_home; then
    echo "Failed to change directory";
    exit 1;
fi

chown root:root ${chrooted_home}
chmod 755 ${chrooted_home}
mkdir -p ${virtual_home}
chown $user_name ${virtual_home}
chmod 0700 ${virtual_home}

mkdir dev
mkdir bin
mkdir lib64
mkdir etc
mkdir -p usr/bin
mkdir usr/lib64

# For SCP
grep "^${user_name}:" /etc/passwd > ${chrooted_home}/etc/passwd
cp -p /lib64/libnss_files.so.2 ${chrooted_home}/lib64/libnss_files.so.2

mknod -m 666 ${chrooted_home}/dev/null c 1 3
mknod -m 666 ${chrooted_home}/dev/zero c 1 3
mkdir ${chrooted_home}/dev/pts
mknod -m 666 ${chrooted_home}/dev/tty c 5 0

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

APPS="/bin/bash /bin/cat /bin/cp /bin/grep /bin/ls /bin/mkdir /bin/more /bin/mv /bin/pwd /bin/rm /bin/rmdir /usr/bin/du /usr/bin/head /usr/bin/id /usr/bin/less /usr/bin/scp /usr/bin/tail /usr/bin/rsync"

for prog in $APPS;  do
        cp $prog ${chrooted_home}${prog}
        ldd $prog > /dev/null
        if [ "$?" = 0 ] ; then
                LIBS=`ldd $prog | grep '/lib' | sed 's/t/ /g' | sed 's/ /n/g' | grep "/lib"`
                for l in $LIBS; do
                        mkdir -p ./`dirname $l` > /dev/null 2>&1
                        cp $l ./$l  > /dev/null 2>&1
                done
        fi
done

echo "Chrooted environment created in ${chrooted_home}"