#!/usr/bin/env sh # This script is primarily designed to create a chroot jail to be used by an SSH user. # My primary use case for this script is that I have a bastion server that I want users # to be able to use for port forwarding to access a database behind a firewall. # I want these users to have as little permissions as possible. This script has been tested # on Ubuntu 22.02 # Define a directory for our jail and a user. JAIL_DIRECTORY=/BASTIONJAIL JAIL_USER=batchtesting JAIL_GROUP=bastionusers JAIL_HOME=$JAIL_DIRECTORY/home/$JAIL_USER # Run some cleanup functions. rm -rf $JAIL_HOME userdel $JAIL_USER rm -rf $JAIL_DIRECTORY/etc/hosts # Create the necessary directories. mkdir -p $JAIL_DIRECTORY/{etc,bin,lib64,lib/x86_64-linux-gnu,dev/urandom,dev/tty} cp /usr/bin/sh $JAIL_DIRECTORY/bin cp /bin/sleep $JAIL_DIRECTORY/bin cp /bin/ssh $JAIL_DIRECTORY/bin cp /dev/null $JAIL_DIRECTORY/dev/ # Link our hosts file for any network needs. sudo cp /etc/hosts $JAIL_DIRECTORY/etc/hosts Copy_Dependencies(){ # Get a list of libraries and parse out just the pathnames. list="$(ldd "$1" | grep -E -o '/lib.*\.[0-9]')" for i in $list; do cp -v "$i" "${JAIL_DIRECTORY}${i}"; done } # These are the minimum requirements for setting up an SSH tunnel. Copy_Dependencies "/bin/bash" Copy_Dependencies "/bin/sleep" Copy_Dependencies "/bin/ssh" # Now make sure that the user has an entry in /etc/passwd. # Shell should be /bin/bash. # Add the following to /etc/sshd_config # Match User batchtesting # ChrootDirectory /BASTIONJAIL # Banner none # Create special devices mknod -m 666 $JAIL_DIRECTORY/null c 1 3 mknod -m 666 $JAIL_DIRECTORY/zero c 1 5 chown root:root $JAIL_DIRECTORY/null $JAIL_DIRECTORY/zero # Create our user # Don't remove the group as it could be in use by other users. groupadd --force "$JAIL_GROUP" useradd $JAIL_USER --home-dir $JAIL_HOME --create --shell /bin/sh -g $JAIL_GROUP mkdir -p $JAIL_HOME/.ssh chown :$JAIL_GROUP $JAIL_DIRECTORY/dev/null # Update ssh config cat < "/tmp/ssh_config" Match Group $JAIL_GROUP ChrootDirectory $JAIL_DIRECTORY Banner none ClientAliveInterval 30 ClientAliveCountMax 0 EOF mv /tmp/ssh_config /etc/ssh/sshd_config.d/00-"$JAIL_GROUP".conf systemctl restart sshd rm -rf "/tmp/$JAIL_USER/sshkey" rm -rf $JAIL_HOME/.ssh/authorized_keys mkdir -p "/tmp/$JAIL_USER" ssh-keygen -b 2048 -t rsa -f "/tmp/$JAIL_USER/sshkey" cat "/tmp/$JAIL_USER/sshkey.pub" >> $JAIL_HOME/.ssh/authorized_keys printf "Here is the needed private key:\n%s" "$(cat /tmp/$JAIL_USER/sshkey)" if az; then az keyvault secret set --name BatchTestingSSHKey --vault-name EngineeringTesting --file /tmp/$JAIL_USER/sshkey else echo "No az cli" fi