Using SSH is great for remote access, and using SCP or SFTP is better than using plain-old FTP. However, for the most part, if you grant SFTP and SCP access to your server, you're granting SSH access as well, which means that a person can log into and execute commands on your system. Even if you limit access to only SFTP, the user will have full access to the entire system.

This can be changed using a program called restricted SSH (RSSH), which can be downloaded from pizzashack.org or installed on your Linux system from your vendor's package repositories, if they provide it. Using RSSH, you can not only restrict the user to using SCP and SFTP (and programs that use SSH as a transport, such as rsync and cvs), but you can also chroot the user to a directory to prevent them from traversing your entire filesystem.

Creating chroots is often the tricky part, so the below bash script (mkchroot) can be used to create the initial chroot.

#!/bin/sh
 
chroot="${1}"
if [ "${chroot}" == "" ]; then
    echo "FATAL: I need a location to create the chroot!"
    exit 1
fi
if [ -e ${chroot} ]; then
    echo "FATAL: ${chroot} already exists!"
    exit 1
fi
mkdir -p ${chroot}/{usr/bin,lib,usr/lib/ssh,dev,etc}
for bin in /usr/bin/scp /usr/bin/rssh /usr/lib/rssh_chroot_helper
/usr/lib/ssh/sftp-server;
do
    cp ${bin} ${chroot}${bin}
 
    for lib in `ldd ${bin} | awk '{print $3}'`;
    do
        if [ -f ${lib} ]; then
            cp ${lib} ${chroot}/${lib}
        fi
    done
done
cp /lib/ld-linux.so.2 ${chroot}/lib/
cp /lib/libcrypt.so.1 ${chroot}/lib/
cp /lib/libnss_compat.so.2 ${chroot}/lib/
mknod -m 0666 ${chroot}/dev/null c 1 3

The above script would be executed as:

# mkchroot /chroot/user

The next step is to do a few user-specific things like creating a passwd file for the user:

# getent passwd user >/chroot/user/etc/passwd

You will also need to change their login shell:

# usermod -s /usr/bin/rssh user

Finally, edit /etc/rssh.conf and add an entry for the user:

user = "user:022:00011:/chroot/user"

This will set the default umask for the user to 022, chroot them into /chroot/user, and provide SCP and SFTP access (the five bits indicate what capabilities are permitted: rsync, rdist, cvs, sftp, and scp; 0 indicates the capability is disabled; 1 indicates it is enabled).

Finally, make sure that the keywords are enabled in rssh.conf:

allowscp
allowsftp

With this, you can provide secure FTP and file copying to your system without exposing the entire filesystem or providing shell access.

Delivered each Tuesday, TechRepublic's free Linux NetNote provides tips, articles, and other resources to help you hone your Linux skills. Automatically sign up today!