Skip to content

Instantly share code, notes, and snippets.

@jdmichaud
Last active April 14, 2017 13:55
Show Gist options
  • Save jdmichaud/ca8e103c3f2d1f199fc25302e6081944 to your computer and use it in GitHub Desktop.
Save jdmichaud/ca8e103c3f2d1f199fc25302e6081944 to your computer and use it in GitHub Desktop.
Launch a bash in a Jail
#!/bin/bash
# With some help from
# https://unix.stackexchange.com/questions/198590/what-is-a-bind-mount?newreg=977065634e454f7eaf4ec14c024033cf
set -e
function usage() {
echo "usage: jail folder"
echo "Create and launch a jail in the provided folder"
}
# Unmount and remove the the system folder so that we only
# keep the user created files and folders
function deinit() {
sudo umount bin
sudo umount lib
sudo umount lib64
sudo umount usr/lib
sudo umount usr/bin
sudo umount usr/sbin
sudo umount etc
rm -fr bin lib lib64 usr etc
# rm -fr dev proc
}
##
## Main
##
# Open a subshell
(
# Check arguments
if [[ $# -ne 1 ]]
then
usage
exit 1
fi
TARGET=$1
# Execute deinit or exit
trap deinit 0
# Mount all the standard folder necessary for a functionning system
cd $TARGET
mkdir -p bin lib lib64 usr/lib usr/bin usr/sbin etc
sudo mount --bind /bin bin
sudo mount --bind /lib lib
sudo mount --bind /lib64 lib64
sudo mount --bind /usr/lib usr/lib
sudo mount --bind /usr/bin usr/bin
sudo mount --bind /usr/sbin usr/sbin
sudo mount --bind /etc etc
# And remount them as readonly
sudo mount -o remount,ro,bind bin
sudo mount -o remount,ro,bind lib
sudo mount -o remount,ro,bind lib64
sudo mount -o remount,ro,bind usr/lib
sudo mount -o remount,ro,bind usr/bin
sudo mount -o remount,ro,bind usr/sbin
sudo mount -o remount,ro,bind etc
# mkdir -p dev proc
# sudo mount --bind /dev dev
# sudo mount --bind /proc proc
mkdir -p home/$(whoami)
sudo USER=$(whoami) HOME=/home/$(whoami) PWD=/home/$(whoami) chroot --userspec=$(whoami):$(id -g) .
# Close the subshell
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment