Exec as root user in Kubernetes

  • 1 minute read
  • 5 code samples

Also available in Română

On this page

Hi 👋,

In this short tutorial I will show you a way of getting a root shell in containers running inside a modern Kubernetes cluster.

Prerequisites:

  • Root access to the cluster node in which the container is running.

Problem Statement

We wan’t root access into a running container, exec gives us non-root user.

➜  Downloads k get podsNAME                     READY   STATUS    RESTARTS   AGEmy-release-cassandra-0   1/1     Running   0          2m9s➜  Downloads k exec -it pod/my-release-cassandra-0 -- /bin/bashI have no name!@my-release-cassandra-0:/$ whoamiwhoami: cannot find name for user ID 1001I have no name!@my-release-cassandra-0:/$ touch testtouch: cannot touch 'test': Permission deniedI have no name!@my-release-cassandra-0:/$ 

Solution

To obtain root access. First grab the Container ID from inside the pod.

k describe pod my-release-cassandra-0
Containers:  cassandra:    Container ID:  containerd://8fa7af3900d556aa8a91b1ac4cbe46335e8df233f8645b0a2329b2f0e6d76177    Image:         docker.io/bitnami/cassandra:4.0.7-debian-11-r0

Then if it the id starts with containerd:// run the following command on the node the pod is running:

Warning

This uses privileged access on the Kubernetes node to enter the live container as root, outside the normal kubectl exec path. Use it only on a node and workload you’re authorized to administer.

sudo runc --root /run/containerd/runc/k8s.io/ exec -t -u 0 8fa7af3900d556aa8a91b1ac4cbe46335e8df233f8645b0a2329b2f0e6d76177 /bin/bash

You should get a root shell into the Cassandra container:

root@my-release-cassandra-0:/# whoamirootroot@my-release-cassandra-0:/# touch testroot@my-release-cassandra-0:/# lsbin	 boot  docker-entrypoint-initdb.d  etc	 lib	media  opt   root  run.sh  srv	test  usrbitnami  dev   entrypoint.sh		   home  lib64	mnt    proc  run   sbin    sys	tmp   var

Thanks for reading and happy cloud surfing! 🏄