Chroot restrict SSH or SFTP users

Only allow some users restricted access to your server, description for both a complete chroot environment or just simple sftp.

Edit /etc/ssh/sshd_config

     Subsystem sftp /usr/lib/openssh/sftp-server -u 077
         Match Group chroot_public
         ChrootDirectory /opt/chroot_public
         AllowTCPForwarding no
         X11Forwarding no
         ForceCommand internal-sftp

Then create a script:

#!/bin/bash
#
# Add SFTP Chroot User Script
# Copyleft 2019 ASBRA AB <j@asbra.nu>
#
# Add to /etc/sshd_config:
#
#     Subsystem sftp /usr/lib/openssh/sftp-server -u 077
#         Match Group chroot_public
#         ChrootDirectory /opt/chroot_public
#         AllowTCPForwarding no
#         X11Forwarding no
#         ForceCommand internal-sftp

# Directory for public chroot jail
chroot="/opt/chroot_public"

# Check for username, else return script syntax
[[ $# -lt 1 ]] && echo "Syntax: $0 username" && exit 1

# Create chroot directory if not exists
mkdir -p ${chroot} &> /dev/null
chown root:root ${chroot} && chmod 755 ${chroot}

# Add user with $HOME relative to Chroot
adduser --no-create-home $1

# Check if adduser script was successfull, else abort with errorlevel 1
[[ $? -gt 0 ]] && echo "* adduser failed..." && exit 1

# Add shared group for chroot jail
addgroup chroot_public &> /dev/null

# Add user to new chroot group
usermod $1 -a -G chroot_public

# Create user home dir
mkdir ${chroot}/${1}

#Change owner and mode on users home directory
chown ${1}:${1} ${chroot}/${1} && chmod 700 ${chroot}/${1}

# Give user new $HOME based on relative chroot path
usermod --home /${1}/ ${1}

Leave a comment

Your email address will not be published. Required fields are marked *