Skip to content

Instantly share code, notes, and snippets.

@flufy3d
Created September 21, 2026 22:13
Show Gist options
  • Select an option

  • Save flufy3d/2a34f25c79da693d37c293e99681c634 to your computer and use it in GitHub Desktop.

Select an option

Save flufy3d/2a34f25c79da693d37c293e99681c634 to your computer and use it in GitHub Desktop.
Socat-based root tunnel: let an AI agent run root commands without sharing your sudo password
#!/usr/bin/env bash
set -euo pipefail
SOCK="${XDG_RUNTIME_DIR:-/tmp}/sudo-tunnel-$(id -u).sock"
ME="$(id -un)"
if [ "$(id -u)" = "0" ]; then
echo "Run as your normal user, not with sudo/root." >&2
exit 1
fi
if [ -S "$SOCK" ] && printf 'exit\n' | timeout 2 nc -N -U "$SOCK" >/dev/null 2>&1; then
echo "Tunnel already running: $SOCK" >&2
exit 1
fi
rm -f "$SOCK"
echo "Enter your sudo password (it never leaves this terminal):"
sudo -v
if ! command -v socat >/dev/null 2>&1; then
echo "Installing socat ..."
sudo apt-get install -y socat
fi
if ! command -v nc >/dev/null 2>&1; then
echo "Missing nc: sudo apt-get install -y netcat-openbsd" >&2
exit 1
fi
sudo socat "UNIX-LISTEN:$SOCK,fork,mode=600,user=$ME,group=$ME" EXEC:'/bin/bash',stderr </dev/null &
JOB=$!
ready=0
for _ in $(seq 1 50); do
if [ -S "$SOCK" ]; then ready=1; break; fi
[ -e "/proc/$JOB" ] || break
sleep 0.1
done
if [ "$ready" != "1" ]; then
echo "socat failed to start." >&2
sudo -n pkill -f "UNIX-LISTEN:$SOCK" >/dev/null 2>&1 || true
rm -f "$SOCK"
exit 1
fi
if [ "$(printf 'id -u\n' | timeout 5 nc -N -U "$SOCK" 2>/dev/null | tr -d '\r\n ')" != "0" ]; then
echo "Self-test failed: tunnel is not root." >&2
sudo -n pkill -f "UNIX-LISTEN:$SOCK" >/dev/null 2>&1 || true
rm -f "$SOCK"
exit 1
fi
cleanup() {
rm -f "$SOCK"
sudo -n pkill -f "UNIX-LISTEN:$SOCK" >/dev/null 2>&1 || true
echo
echo "Tunnel closed, root access revoked."
}
trap cleanup EXIT
trap 'exit 0' INT TERM
cat <<EOF
============================================================
Root tunnel up: $SOCK
Ctrl+C to close and revoke root access.
============================================================
Paste to agent:
Root tunnel is open (do not use sudo):
printf 'COMMAND\n' | timeout 30 nc -N -U $SOCK
EOF
wait "$JOB" || true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment