Tuesday, January 2, 2018

sftp chroot environment - config and script

sftp chroot environment


Of course, sshd service should be enabled.


Sample Config:

#/etc/ssh/sshd_config
#
Protocol 2
SyslogFacility AUTHPRIV
MaxAuthTries 5
PubkeyAuthentication yes
PasswordAuthentication yes
ChallengeResponseAuthentication no
GSSAPIAuthentication yes
GSSAPICleanupCredentials yes
UsePAM yes
AcceptEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES
AcceptEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT
AcceptEnv LC_IDENTIFICATION LC_ALL
X11Forwarding yes
Ciphers aes128-ctr,aes192-ctr,aes256-ctr
MACs hmac-sha1,hmac-ripemd160
Subsystem       sftp    internal-sftp

Match Group sftpusers
        ChrootDirectory /home/sftpusers/%u
        ForceCommand internal-sftp
###EOF



Sample sftp adduser script

#/usr/local/sbin/sftp_adduser.sh
#!/bin/bash
#
if [ $# -lt 1 ]; then
        echo "Usage: `basename $0`" sftp username
        echo "   eg. `basename $0` "sftp_something
        exit 1
fi
RANPASS=`date +%s | sha256sum | base64 | head -c 8 ; echo`
USERNAME=$1
SFTPHOME=/home/sftpusers
SFTPSHELL=/usr/libexec/openssh/sftp-server

id $USERNAME 2> /dev/null 1>  /dev/null
if [ $? -eq 0 ]
then
echo "$1 already exist, please try again using another name"
exit

else
        useradd -d $SFTPHOME/$USERNAME -s $SFTPSHELL -p $RANPASS $USERNAME
        echo $RANPASS > /tmp/passwd.tmp001
        sleep 1
        passwd --stdin < /tmp/passwd.tmp001 $USERNAME
        echo $USERNAME >> /etc/listfile/sshusers

        #set permission
        usermod -g sftpusers $USERNAME
        usermod -G sftpusers $USERNAME

        #This is the default folder for sftp users
        mkdir $SFTPHOME/$USERNAME/FILES
     
        #set permissions
        chown root $SFTPHOME/$USERNAME
        chmod go-w $SFTPHOME/$USERNAME
        chown $USERNAME:sftpusers $SFTPHOME/$USERNAME/FILES
        chmod u+rwX $SFTPHOME/$USERNAME
        chmod 755 $SFTPHOME/$USERNAME
        chmod g+rx $SFTPHOME/$USERNAME

        #Details
        echo USER CREATED: $USERNAME
        echo USER DEFINED PASSWORD: $RANPASS
        echo FTP INTERNAL IP: 1.2.3.4
        echo FTP EXTERNAL IP: 111.222.112.221
        echo USER: $USERNAME has been created at ftp 1.2.3.4 | mail -s "created at sftp 1.2.3.4 on `date`" admin@myhost.com
fi