Skip to content

Instantly share code, notes, and snippets.

@blackandred
Created January 21, 2023 15:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blackandred/1748aba6ea775cb45a395d709debaf2d to your computer and use it in GitHub Desktop.
Save blackandred/1748aba6ea775cb45a395d709debaf2d to your computer and use it in GitHub Desktop.
Helper script to create a chroot environment
#!/bin/bash
# ------------------------------------------------------------------------------------------------
# Creates a minimum operating system environment required for selected binaries to run
# Usage: chroot-create.sh "/path/where/to/store/environment" list-of-binaries psql pg_restore
#
# After the environment is created just do as the regular user: fakechroot fakeroot chroot /path/where/to/store/environment /bin/sh
# or directly: fakechroot fakeroot chroot /path/where/to/store/environment psql --help
# ------------------------------------------------------------------------------------------------
set -e
CHROOT_DIR=$1
BINARIES=$@
BINARIES=${BINARIES[@]:${#CHROOT_DIR}:200}
echo " >> Chroot directory: ${CHROOT_DIR}"
echo " >> Binaries to copy: ${BINARIES}"
copyBinary() {
for b in $*; do
echo " >> Copying binary ${b}"
cp --parents $b $CHROOT_DIR
done
for i in $(ldd $*|grep -v dynamic|cut -d " " -f 3|sed 's/://'|sort|uniq); do
echo " >> Copying ${i}"
cp --parents $i $CHROOT_DIR
done
}
setupPasswd() {
echo " >> Setting up /etc/group and /etc/passwd"
cp --parents /etc/passwd $CHROOT_DIR
cp --parents /etc/group $CHROOT_DIR
if [[ $(cat $CHROOT_DIR/etc/passwd) != *"$(id -u):$(id -g)"* ]]; then
echo "$(whoami):x:$(id -u):$(id -g)::/home:/bin/sh" >> $CHROOT_DIR/etc/passwd
fi
if [[ $(cat $CHROOT_DIR/etc/group) != *"$(whoami):"* ]]; then
echo "$(whoami):x:$(id -g):" >> $CHROOT_DIR/etc/group
fi
echo "$(whoami):!!:11111:0:99999:7:::" >> $CHROOT_DIR/etc/shadow
}
mkdir -p $CHROOT_DIR
mkdir -p $CHROOT_DIR/{dev,etc,home,tmp,proc,root,var}
cp --parents /etc/nsswitch.conf $CHROOT_DIR
echo "nameserver 1.1.1.1" > $CHROOT_DIR/etc/resolv.conf
cp --parents /etc/hosts $CHROOT_DIR
cp --parents /lib/libnss_* $CHROOT_DIR || true
cp -r --parents /usr/share/terminfo $CHROOT_DIR || true
cp --parents /lib64/ld-linux-* $CHROOT_DIR
setupPasswd
ls -la /usr/lib/postgresql/
for binName in ${BINARIES[@]}; do
echo " >> Checking '${binName}'"
binPath="${binName}"
if [[ ! -f "${binPath}" ]]; then
echo " .. checking with which"
binPath=$(which ${binName} || true)
if [[ ! -f "${binPath}" ]]; then
echo " .. checking with find"
binPath=$((find / -name "${binName}" 2>/dev/null | tail -n -1) || true)
fi
fi
if [[ ! -f "${binPath}" ]]; then
echo " >> Cannot find ${binName}"
exit 1
fi
echo " >> copyBinary ${binPath}"
copyBinary $binPath
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment