Setting up a CentOS VPS as an SFTP server using Linux Users and the SFTP shell.
MAKE SURE YOU HAVE KEY BASED AUTH WORKING FIRST
vi /etc/ssh/sshd_config
PasswordAuthentication no PermitRootLogin no RSAAuthentication yes PubkeyAuthentication yes AuthorizedKeysFile .ssh/authorized_keys Subsystem sftp internal-sftp Match Group sftponly ChrootDirectory /home/%u ForceCommand internal-sftp PasswordAuthentication yes AllowTcpForwarding no GatewayPorts no X11Forwarding no
This will enable the sftp group to use password auth and will lock them to their home directory. This also stops them forwarding ports via ssh.
sudo groupadd sftponly
sudo useradd -d /home/USERNAME -s /sbin/nologin -G sftponly USERNAME sudo passwd USERNAME
sudo chown -R root.sftponly USERNAME sudo chmod 750 /home/USERNAME
mkdir /home/USERNAME/files sudo mkdir /home/USERNAME/files sudo chown USERNAME /home/USERNAME/files sudo chmod 750 /home/USERNAME/files
#!/bin/bash genpasswd() { l=$1 [ "$l" == "" ] && l=16 tr -dc A-Za-z0-9 < /dev/urandom | head -c ${l} | xargs } if [ "$(id -u)" != "0" ]; then echo "This script needs root privilages 'sudo ./script.sh'" exit 1 fi username=""; password=`genpasswd`; read -e -p "Enter SFTP username to be created: " -i "" username; while true; do read -e -p "Compulsory are you sure question (y/n/q)? " question case $question in [Yy]* ) break;; [QqNn]* ) exit; esac done echo -e "Creating user with homedir /home/$username"; sudo useradd -d /home/$username -s /sbin/nologin -G sftponly $username echo -e "Setting randomly generated password"; echo "$password" | sudo passwd "$username" --stdin echo -e "Setting root.sftponly as owner.group"; sudo chown -R root.sftponly /home/$username echo -e "Setting folder permission on new home dir"; sudo chmod 750 /home/$username echo -e "Making /home/$username/files"; sudo mkdir /home/$username/files echo -e "Setting $username.$username permissions on /home/$username/files"; sudo chown $username /home/$username/files echo -e "Setting folder permission on files dir"; sudo chmod 750 /home/$username/files echo -e ""; echo -e ""; echo -e ""; echo -e "Setup done please test from another machine with 'sftp $username@`hostname`'"; echo -e "Username : $username"; echo -e "Password : $password"; echo -e "Home Dir : /home/$username/"; echo -e "Writable Dir : /home/$username/files/"
#!/bin/bash if [ "$(id -u)" != "0" ]; then echo "This script needs root privilages 'sudo ./script.sh'" exit 1 fi username=""; read -e -p "Enter SFTP username to be deleted: " -i "" username; while true; do read -e -p "Compulsory are you sure question (y/n/q)? " question case $question in [Yy]* ) break;; [QqNn]* ) exit; esac done sudo userdel $username; while true; do read -e -p "DELETE ALL USER FILES?? (y/n/q)? " question case $question in [Yy]* ) break;; [QqNn]* ) exit; esac done sudo rm -rf /home/$username