mcpField
S
securing-kubernetes-on-cloud

securing-kubernetes-on-cloud

github.com/mukul975安全35.2k83 次安装8 周前更新
代码仓库

关于 securing-kubernetes-on-cloud

面向云托管 Kubernetes 集群管理员的安全加固技能,提供从 Pod 安全标准、工作负载身份到运行时监控的配置流程。

主要功能

  1. 01强制执行 Pod 安全标准
  2. 02配置云原生工作负载身份
  3. 03以网络策略限制 Pod 通信
  4. 04按最小权限配置 RBAC
  5. 05部署镜像准入与运行时监控

适用场景

  1. 01加固 EKS、AKS 或 GKE 集群
  2. 02为 Pod 配置云 IAM 身份
  3. 03限制命名空间间的网络访问
  4. 04检测容器中的异常行为

安装

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

$npx skills add https://github.com/mukul975/anthropic-cybersecurity-skills --skill securing-kubernetes-on-cloud

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

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

LICENSE
references/
api-reference.md
scripts/
agent.py

详细介绍

在云上保护 Kubernetes 安全

何时使用

  • 在生产环境中部署新的托管 Kubernetes 集群且有安全要求时
  • 在安全审计或渗透测试发现问题后,加固现有的 EKS、AKS 或 GKE 集群时
  • 实施工作负载身份以消除 Pod 中的静态云凭证时
  • 跨命名空间强制执行 Pod 安全策略以防止容器逃逸时
  • 集成运行时安全监控以检测容器级威胁时

不要使用于非 Kubernetes 的容器部署(如 ECS Fargate 或 Azure Container Instances)、容器内的应用级安全(参见 securing-serverless-functions)或 CI/CD 流水线安全(参见 implementing-cloud-devsecops)。

前提条件

  • 已在 EKS、AKS 或 GKE 上预配托管 Kubernetes 集群并具有管理员访问权限
  • kubectl 已配置集群管理员凭证
  • 熟悉 Kubernetes RBAC、命名空间和安全上下文
  • 支持网络策略的容器网络接口插件(Calico、Cilium)

工作流

步骤 1:强制执行 Pod 安全标准

在命名空间级别应用 Pod Security Admission 标签,以在生产命名空间中强制执行 Restricted 配置文件。Pod Security Policies 已在 Kubernetes v1.25 中移除,并由 Pod Security Admission 取代。

# Production namespace with restricted Pod Security Standard
apiVersion: v1
kind: Namespace
metadata:
  name: production
  labels:
    pod-security.kubernetes.io/enforce: restricted
    pod-security.kubernetes.io/enforce-version: latest
    pod-security.kubernetes.io/audit: restricted
    pod-security.kubernetes.io/warn: restricted
---
# Staging namespace with baseline enforcement
apiVersion: v1
kind: Namespace
metadata:
  name: staging
  labels:
    pod-security.kubernetes.io/enforce: baseline
    pod-security.kubernetes.io/audit: restricted
    pod-security.kubernetes.io/warn: restricted
# Pod spec compliant with restricted profile
apiVersion: v1
kind: Pod
metadata:
  name: secure-app
  namespace: production
spec:
  automountServiceAccountToken: false
  securityContext:
    runAsNonRoot: true
    runAsUser: 1000
    fsGroup: 1000
    seccompProfile:
      type: RuntimeDefault
  containers:
    - name: app
      image: company/app:v2.1@sha256:abc123...
      securityContext:
        allowPrivilegeEscalation: false
        readOnlyRootFilesystem: true
        capabilities:
          drop: ["ALL"]
      resources:
        limits:
          cpu: "500m"
          memory: "256Mi"
        requests:
          cpu: "100m"
          memory: "128Mi"
步骤 2:配置云原生工作负载身份

通过将 Kubernetes 服务账号绑定到云 IAM 角色,消除 Pod 中的静态云凭证。

# EKS: IAM Roles for Service Accounts (IRSA)
eksctl create iamserviceaccount \
  --cluster production-cluster \
  --namespace production \
  --name web-app-sa \
  --attach-policy-arn arn:aws:iam::123456789012:policy/WebAppS3ReadOnly \
  --approve

# GKE: Workload Identity
gcloud iam service-accounts create web-app-sa \
  --project=my-gcp-project

gcloud iam service-accounts add-iam-policy-binding \
  [email protected] \
  --role roles/storage.objectViewer \
  --member "serviceAccount:my-gcp-project.svc.id.goog[production/web-app-sa]"

kubectl annotate serviceaccount web-app-sa \
  --namespace production \
  iam.gke.io/gcp-service-account=web-app-sa@my-gcp-project.iam.gserviceaccount.com

# AKS: Azure AD Workload Identity
az identity create --name web-app-identity --resource-group production-rg
az identity federated-credential create \
  --name web-app-federation \
  --identity-name web-app-identity \
  --resource-group production-rg \
  --issuer "$(az aks show -n production-cluster -g production-rg --query oidcIssuerProfile.issuerUrl -o tsv)" \
  --subject system:serviceaccount:production:web-app-sa
步骤 3:实施网络策略

部署网络策略,按照最小权限原则限制 Pod 之间的通信。默认情况下,Kubernetes 允许所有 Pod 相互通信。

# Default deny all ingress and egress in production namespace
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny-all
  namespace: production
spec:
  podSelector: {}
  policyTypes:
    - Ingress
    - Egress
---
# Allow web-app to receive traffic from ingress controller only
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-ingress-to-web
  namespace: production
spec:
  podSelector:
    matchLabels:
      app: web-app
  policyTypes:
    - Ingress
  ingress:
    - from:
        - namespaceSelector:
            matchLabels:
              name: ingress-nginx
      ports:
        - protocol: TCP
          port: 8080
---
# Allow web-app to connect to database only
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-web-to-db
  namespace: production
spec:
  podSelector:
    matchLabels:
      app: web-app
  policyTypes:
    - Egress
  egress:
    - to:
        - podSelector:
            matchLabels:
              app: postgres
      ports:
        - protocol: TCP
          port: 5432
    - to:
        - namespaceSelector: {}
          podSelector:
            matchLabels:
              k8s-app: kube-dns
      ports:
        - protocol: UDP
          port: 53
步骤 4:配置最小权限 RBAC

将 Kubernetes RBAC 角色限定到特定命名空间和资源。避免为非管理用户使用 ClusterRoleBindings。

# Developer role scoped to specific namespace
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: developer-role
  namespace: staging
rules:
  - apiGroups: [""]
    resources: ["pods", "pods/log", "services", "configmaps"]
    verbs: ["get", "list", "watch"]
  - apiGroups: ["apps"]
    resources: ["deployments"]
    verbs: ["get", "list", "watch", "update", "patch"]
  # Explicitly deny secrets access
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: developer-binding
  namespace: staging
subjects:
  - kind: Group
    name: developers
    apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: Role
  name: developer-role
  apiGroup: rbac.authorization.k8s.io
步骤 5:部署镜像准入控制

使用准入控制器强制执行仅部署来自受信任仓库的已签名镜像。实施 OPA/Gatekeeper 或 Kyverno 进行策略执行。

# Kyverno policy: require images from approved registries
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: restrict-image-registries
spec:
  validationFailureAction: Enforce
  rules:
    - name: validate-registries
      match:
        any:
          - resources:
              kinds: ["Pod"]
      validate:
        message: "Images must come from approved registries"
        pattern:
          spec:
            containers:
              - image: "123456789012.dkr.ecr.us-east-1.amazonaws.com/* | gcr.io/my-gcp-project/*"
---
# Kyverno policy: require image digest (no mutable tags)
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: require-image-digest
spec:
  validationFailureAction: Enforce
  rules:
    - name: require-digest
      match:
        any:
          - resources:
              kinds: ["Pod"]
      validate:
        message: "Images must use digest references, not tags"
        pattern:
          spec:
            containers:
              - image: "*@sha256:*"
步骤 6:启用运行时安全监控

部署运行时安全工具,以检测容器内的异常行为,包括进程执行、文件系统修改和网络连接。

# Deploy Falco for runtime threat detection
helm repo add falcosecurity https://falcosecurity.github.io/charts
helm install falco falcosecurity/falco \
  --namespace falco-system --create-namespace \
  --set falcosidekick.enabled=true \
  --set falcosidekick.config.slack.webhookurl="https://hooks.slack.com/services/xxx"

# Run kube-bench for CIS Kubernetes Benchmark assessment
kubectl apply -f https://raw.githubusercontent.com/aquasecurity/kube-bench/main/job-eks.yaml
kubectl logs -l app=kube-bench

关键概念

术语定义
Pod 安全标准通过 Pod Security Admission 强制执行的三种配置文件(Privileged、Baseline、Restricted),用于控制 Pod 安全上下文的能力
工作负载身份将 Kubernetes 服务账号绑定到云 IAM 角色的云原生机制,用于无凭证访问云 API(IRSA、GKE WI、AKS MI)
网络策略定义 Pod 之间允许的入口和出口流量流的 Kubernetes 资源,由 CNI 插件强制执行
准入控制器在持久化之前拦截 API 请求的 Kubernetes 插件,用于根据安全策略验证或修改资源
RBACKubernetes 中基于角色的访问控制,定义身份可以在哪些命名空间中对哪些资源执行哪些操作(动词)
Seccomp 配置文件Linux 内核功能,限制容器进程可以进行的系统调用,减少内核攻击面
服务网格基础设施层(Istio、Linkerd),为服务间通信提供双向 TLS、流量策略和可观测性

工具与系统

  • Falco:开源运行时安全引擎,通过内核级系统调用监控检测容器中的异常行为
  • Kyverno:Kubernetes 原生策略引擎,用于基于安全策略对资源进行准入控制、变更和生成
  • kube-bench:CIS Kubernetes Benchmark 评估工具,根据安全最佳实践检查集群配置
  • Trivy:面向容器镜像、文件系统和 Kubernetes 资源的漏洞扫描器,支持生成 SBOM
  • Calico/Cilium:CNI 插件,提供网络策略执行和高级网络安全功能,包括基于 eBPF 的监控

常见场景

场景:通过被入侵的容器镜像部署挖矿程序

背景:GuardDuty Extended Threat Detection 生成 AttackSequence:EKS/CompromisedCluster 发现。一名开发者拉取了一个公共 Docker 镜像,其中包含在容器启动时执行的嵌入式 XMRig 挖矿程序。

处理方法:

  1. 通过应用针对其标签的 deny-all 网络策略来隔离受影响的 pod
  2. 捕获容器镜像摘要,并使用 Trivy 扫描以识别嵌入的二进制文件
  3. 查看 Kubernetes 审计日志,以确定是谁在何时部署了被入侵的镜像
  4. 部署 Kyverno ClusterPolicy,要求镜像仅来自批准的私有仓库
  5. 启用镜像摘要固定,以防止标签篡改攻击
  6. 部署 Falco,并使用检测加密货币挖矿进程特征的规则(/usr/bin/xmrig、stratum+tcp 连接)

陷阱:在捕获镜像摘要和审计日志之前删除 pod 会破坏取证证据。仅阻止特定镜像标签会让攻击者能够用不同标签重新推送。

输出格式

Kubernetes Security Assessment Report
=======================================
Cluster: production-cluster (EKS 1.29)
Provider: AWS (us-east-1)
Assessment Date: 2025-02-23
Tool: kube-bench v0.8.0 + manual review

CIS KUBERNETES BENCHMARK RESULTS:
  Total Controls: 124
  Passed: 98 (79%)
  Failed: 18 (15%)
  Warnings: 8 (6%)

CRITICAL FINDINGS:
  [K8S-001] 3 namespaces lack Pod Security Standards enforcement
    Namespaces: monitoring, logging, default
    Remediation: Apply restricted PSA labels

  [K8S-002] Default service account tokens auto-mounted in 12 deployments
    Risk: Credential theft if container is compromised
    Remediation: Set automountServiceAccountToken: false

  [K8S-003] No network policies in production namespace
    Risk: Unrestricted lateral movement between all pods
    Remediation: Deploy default-deny policy with explicit allow rules

HIGH FINDINGS:
  [K8S-004] 5 pods running as root with privileged security context
  [K8S-005] Images deployed using mutable tags (:latest) in 8 deployments
  [K8S-006] RBAC ClusterRoleBinding grants cluster-admin to developers group

评论

支持 Markdown