Created
February 11, 2026 18:09
-
-
Save nedix/55c3648ed5397bd94fc9cfafc15890e8 to your computer and use it in GitHub Desktop.
sandbox.sh
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env sh | |
| : ${SERVICE_NAME:="sbx-0"} | |
| : ${SERVICE_ID:="${SERVICE_NAME##*-}"} | |
| : ${SERVICE_PATH:="/chroot/${SERVICE_NAME}"} | |
| setup_chroot() { | |
| local TEMP_DIR="/tmp/sandboxes/${SERVICE_NAME}" | |
| mkdir -p \ | |
| "$TEMP_DIR" \ | |
| "${SERVICE_PATH}/dev" \ | |
| "${SERVICE_PATH}/root" \ | |
| "${SERVICE_PATH}/tmp" \ | |
| mknod -m 0666 "${SERVICE_PATH}/dev/null" c 1 3 | |
| mknod -m 0666 "${SERVICE_PATH}/dev/urandom" c 1 9 | |
| mount --bind "$TEMP_DIR" "${SERVICE_PATH}/tmp" | |
| chown nobody \ | |
| "${SERVICE_PATH}/root" \ | |
| "${SERVICE_PATH}/tmp" | |
| } | |
| setup_network() { | |
| local HOST_DEVICE="${SERVICE_NAME//-/}" | |
| local SERVICE_DEVICE="${SERVICE_NAME//-/}-veth" | |
| # Create a network namespace. | |
| ip netns add "$SERVICE_NAME" | |
| # Create a bridge device on the host. | |
| ip link add br0 type bridge 2> /dev/null | |
| ip link set br0 up | |
| ip addr add "10.0.${SERVICE_ID}.1" dev br0 | |
| ip route add "10.0.${SERVICE_ID}.0" dev br0 | |
| # Create a veth pair on the host. | |
| ip link add "$HOST_DEVICE" type veth peer name "$SERVICE_DEVICE" | |
| ip link set "$HOST_DEVICE" master br0 | |
| ip link set "$HOST_DEVICE" up | |
| # Move one end of the veth pair into the namespace. | |
| ip link set "$SERVICE_DEVICE" netns "$SERVICE_NAME" | |
| ip netns exec "$SERVICE_NAME" ip link set "$SERVICE_DEVICE" name eth0 | |
| ip netns exec "$SERVICE_NAME" ip link set eth0 up | |
| ip netns exec "$SERVICE_NAME" ip link set lo up | |
| ip netns exec "$SERVICE_NAME" ip addr add "10.0.${SERVICE_ID}.0/31" dev eth0 | |
| ip netns exec "$SERVICE_NAME" ip route add default via "10.0.${SERVICE_ID}.1" dev eth0 | |
| } | |
| sandbox() { | |
| local CMD="$@" | |
| ip netns exec "$SERVICE_NAME" su -s /bin/sh -c " \ | |
| export HOME=${HOME:-/root} | |
| unshare -r \ | |
| chroot ${SERVICE_PATH} \ | |
| ${CMD} | |
| " nobody | |
| } | |
| if type "$1" | grep -q "function"; then "$1"; else sandbox "$@"; fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment