SFTP server on CentOS Linux with chrooted RW and chrooted RO user

SFTP (SSH File Transfer Protocol or Secure File Transfer Protocol) is network protocol for fafe transfer and access to files over network – so nobody cannot sniff traffic between you and server in ManInTheMiddle scenario.

In this task we need to create SFTP server on CentOS 7 Minimal Linux, with two chrooted SFTP users with no shell access, one user need to have only read-only (RO) access and second need to have read-write (RW) access. Everything need to be configured without ACL (access control list) feature.

We will do everything using temporarily variables because it’s easier to use for any other users which we need to create, so you need only in first step to configure RW and RO user, SFTP location and name of a folder for SFTP (in this example name will be Files). You can use copy-paste for your server but, of course bee careful if you use this on some of your proportional servers.

################## FIRST STEP ###################
#--------- VARIABLES(by you own hands) ---------#
RW_USER=NarodSrbije
RO_USER=VladaSrbije
SFTP_LOCATION="/home/SFTP/Project001" #for example
SFTP_FOLDER="Files"
#------------------------------------------------#
############### DRUGI KORAK ###############
CHROOT_FOLDER="${SFTP_LOCATION}/${RW_USER}_sftp"
mkdir -p ${CHROOT_FOLDER}

groupadd ${RW_USER}_sftp
useradd -g ${RW_USER}_sftp ${RW_USER} -d ${CHROOT_FOLDER}/${SFTP_FOLDER} --shell=/sbin/nologin
useradd -g ${RW_USER}_sftp ${RO_USER} -d ${CHROOT_FOLDER}/${SFTP_FOLDER} --shell=/sbin/nologin #Ignore error

#################################################################
CHECK=`grep "#Subsystem" /etc/ssh/sshd_config | wc -l`
if [ ${CHECK} -eq 0 ] ; then $(sed -i s/"Subsystem"/"#Subsystem"/g /etc/ssh/sshd_config) ; fi
if [ ${CHECK} -eq 0 ] ; then $(echo "#--------------------------#" >> /etc/ssh/sshd_config) ; fi
if [ ${CHECK} -eq 0 ] ; then $(echo "Subsystem sftp internal-sftp" >> /etc/ssh/sshd_config) ; fi
if [ ${CHECK} -eq 0 ] ; then $(echo "#--------------------------#" >> /etc/ssh/sshd_config) ; fi
##################################################################

echo "Match Group ${RW_USER}_sftp" >> /etc/ssh/sshd_config
echo " X11Forwarding no" >> /etc/ssh/sshd_config
echo " AllowTcpForwarding no" >> /etc/ssh/sshd_config
echo " ChrootDirectory ${CHROOT_FOLDER}" >> /etc/ssh/sshd_config
echo " ForceCommand internal-sftp" >> /etc/ssh/sshd_config

chown ${RW_USER}:${RW_USER}_sftp ${CHROOT_FOLDER}/${SFTP_FOLDER}
chmod g=rx ${CHROOT_FOLDER}/${SFTP_FOLDER}
 
systemctl restart sshd
passwd ${RW_USER} ; passwd ${RO_USER} ;

After first log-off all temproarly variables will be deleted. I recommend to you to change SSH port if this SFTP server will be public and to safe him with Fail2Ban software.