K8s Security Policies

作者 wshobson46891e7e60da無授權條款收錄於 2026年10月8日更新於 2026年10月8日

Implement Kubernetes security policies including NetworkPolicy, PodSecurityPolicy, and RBAC for production-grade security. Use when securing Kubernetes clusters, implementing network isolation, or enforcing pod security standards.

AI 產生的概覽

指導實作 Kubernetes 安全政策:NetworkPolicy、Pod 安全標準、RBAC 與准入控制。

功能
此技能提供強化 Kubernetes 叢集的參考指引與 YAML 範例,涵蓋 Pod 安全標準、NetworkPolicy 網路隔離、RBAC 角色與綁定、安全的 Pod 安全情境、OPA Gatekeeper 限制條件,以及 Istio mTLS 授權。它也列出最佳實務、合規框架對照(CIS、NIST)與疑難排解指令。技能附帶一份網路政策範本資產與一份 RBAC 模式參考文件。
適用情境
適用於保護 Kubernetes 叢集、實作網路隔離或分段、強制執行 Pod 安全標準,或設定最小權限 RBAC 的情境。也適合以合規為導向的政策工作與多租戶叢集強化。
執行需求
不含指令碼,僅有說明與 YAML 範例。使用這些範例需要 Kubernetes 叢集與 kubectl;部分章節在使用時涉及 OPA Gatekeeper 或 Istio。

Kubernetes Security Policies

Comprehensive guide for implementing NetworkPolicy, PodSecurityPolicy, RBAC, and Pod Security Standards in Kubernetes.

Purpose

Implement defense-in-depth security for Kubernetes clusters using network policies, pod security standards, and RBAC.

When to Use This Skill

  • Implement network segmentation
  • Configure pod security standards
  • Set up RBAC for least-privilege access
  • Create security policies for compliance
  • Implement admission control
  • Secure multi-tenant clusters

Pod Security Standards

1. Privileged (Unrestricted)

yaml
apiVersion: v1kind: Namespacemetadata:  name: privileged-ns  labels:    pod-security.kubernetes.io/enforce: privileged    pod-security.kubernetes.io/audit: privileged    pod-security.kubernetes.io/warn: privileged

2. Baseline (Minimally restrictive)

yaml
apiVersion: v1kind: Namespacemetadata:  name: baseline-ns  labels:    pod-security.kubernetes.io/enforce: baseline    pod-security.kubernetes.io/audit: baseline    pod-security.kubernetes.io/warn: baseline

3. Restricted (Most restrictive)

yaml
apiVersion: v1kind: Namespacemetadata:  name: restricted-ns  labels:    pod-security.kubernetes.io/enforce: restricted    pod-security.kubernetes.io/audit: restricted    pod-security.kubernetes.io/warn: restricted

Network Policies

Default Deny All

yaml
apiVersion: networking.k8s.io/v1kind: NetworkPolicymetadata:  name: default-deny-all  namespace: productionspec:  podSelector: {}  policyTypes:    - Ingress    - Egress

Allow Frontend to Backend

yaml
apiVersion: networking.k8s.io/v1kind: NetworkPolicymetadata:  name: allow-frontend-to-backend  namespace: productionspec:  podSelector:    matchLabels:      app: backend  policyTypes:    - Ingress  ingress:    - from:        - podSelector:            matchLabels:              app: frontend      ports:        - protocol: TCP          port: 8080

Allow DNS

yaml
apiVersion: networking.k8s.io/v1kind: NetworkPolicymetadata:  name: allow-dns  namespace: productionspec:  podSelector: {}  policyTypes:    - Egress  egress:    - to:        - namespaceSelector:            matchLabels:              name: kube-system      ports:        - protocol: UDP          port: 53

Reference: See assets/network-policy-template.yaml

RBAC Configuration

Role (Namespace-scoped)

yaml
apiVersion: rbac.authorization.k8s.io/v1kind: Rolemetadata:  name: pod-reader  namespace: productionrules:  - apiGroups: [""]    resources: ["pods"]    verbs: ["get", "watch", "list"]

ClusterRole (Cluster-wide)

yaml
apiVersion: rbac.authorization.k8s.io/v1kind: ClusterRolemetadata:  name: secret-readerrules:  - apiGroups: [""]    resources: ["secrets"]    verbs: ["get", "watch", "list"]

RoleBinding

yaml
apiVersion: rbac.authorization.k8s.io/v1kind: RoleBindingmetadata:  name: read-pods  namespace: productionsubjects:  - kind: User    name: jane    apiGroup: rbac.authorization.k8s.io  - kind: ServiceAccount    name: default    namespace: productionroleRef:  kind: Role  name: pod-reader  apiGroup: rbac.authorization.k8s.io

Reference: See references/rbac-patterns.md

Pod Security Context

Restricted Pod

yaml
apiVersion: v1kind: Podmetadata:  name: secure-podspec:  securityContext:    runAsNonRoot: true    runAsUser: 1000    fsGroup: 1000    seccompProfile:      type: RuntimeDefault  containers:    - name: app      image: myapp:1.0      securityContext:        allowPrivilegeEscalation: false        readOnlyRootFilesystem: true        capabilities:          drop:            - ALL

Policy Enforcement with OPA Gatekeeper

ConstraintTemplate

yaml
apiVersion: templates.gatekeeper.sh/v1kind: ConstraintTemplatemetadata:  name: k8srequiredlabelsspec:  crd:    spec:      names:        kind: K8sRequiredLabels      validation:        openAPIV3Schema:          type: object          properties:            labels:              type: array              items:                type: string  targets:    - target: admission.k8s.gatekeeper.sh      rego: |        package k8srequiredlabels        violation[{"msg": msg, "details": {"missing_labels": missing}}] {          provided := {label | input.review.object.metadata.labels[label]}          required := {label | label := input.parameters.labels[_]}          missing := required - provided          count(missing) > 0          msg := sprintf("missing required labels: %v", [missing])        }

Constraint

yaml
apiVersion: constraints.gatekeeper.sh/v1beta1kind: K8sRequiredLabelsmetadata:  name: require-app-labelspec:  match:    kinds:      - apiGroups: ["apps"]        kinds: ["Deployment"]  parameters:    labels: ["app", "environment"]

Service Mesh Security (Istio)

PeerAuthentication (mTLS)

yaml
apiVersion: security.istio.io/v1beta1kind: PeerAuthenticationmetadata:  name: default  namespace: productionspec:  mtls:    mode: STRICT

AuthorizationPolicy

yaml
apiVersion: security.istio.io/v1beta1kind: AuthorizationPolicymetadata:  name: allow-frontend  namespace: productionspec:  selector:    matchLabels:      app: backend  action: ALLOW  rules:    - from:        - source:            principals: ["cluster.local/ns/production/sa/frontend"]

Best Practices

  1. Implement Pod Security Standards at namespace level
  2. Use Network Policies for network segmentation
  3. Apply least-privilege RBAC for all service accounts
  4. Enable admission control (OPA Gatekeeper/Kyverno)
  5. Run containers as non-root
  6. Use read-only root filesystem
  7. Drop all capabilities unless needed
  8. Implement resource quotas and limit ranges
  9. Enable audit logging for security events
  10. Regular security scanning of images

Compliance Frameworks

CIS Kubernetes Benchmark

  • Use RBAC authorization
  • Enable audit logging
  • Use Pod Security Standards
  • Configure network policies
  • Implement secrets encryption at rest
  • Enable node authentication

NIST Cybersecurity Framework

  • Implement defense in depth
  • Use network segmentation
  • Configure security monitoring
  • Implement access controls
  • Enable logging and monitoring

Troubleshooting

NetworkPolicy not working:

bash
# Check if CNI supports NetworkPolicykubectl get nodes -o widekubectl describe networkpolicy <name>

RBAC permission denied:

bash
# Check effective permissionskubectl auth can-i list pods --as system:serviceaccount:default:my-sakubectl auth can-i '*' '*' --as system:serviceaccount:default:my-sa

Related Skills

  • k8s-manifest-generator - For creating secure manifests
  • gitops-workflow - For automated policy deployment

來源與署名

來源:wshobson/agents位於plugins/kubernetes-operations/skills/k8s-security-policies提交46891e7

授權條款: 無授權條款

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架