k8s-security-policies

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Kubernetes Security Policies

Kubernetes 安全策略

Comprehensive guide for implementing NetworkPolicy, PodSecurityPolicy, RBAC, and Pod Security Standards in Kubernetes.
本指南详细介绍如何在Kubernetes中实施NetworkPolicy、PodSecurityPolicy、RBAC以及Pod安全标准。

Purpose

目标

Implement defense-in-depth security for Kubernetes clusters using network policies, pod security standards, and RBAC.
利用网络策略、Pod安全标准和RBAC为Kubernetes集群实施纵深防御安全体系。

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安全标准
  • 基于最小权限原则设置RBAC访问控制
  • 创建符合合规要求的安全策略
  • 实施准入控制
  • 保障多租户集群安全

Pod Security Standards

Pod安全标准

1. Privileged (Unrestricted)

1. 特权模式(无限制)

yaml
apiVersion: v1
kind: Namespace
metadata:
  name: privileged-ns
  labels:
    pod-security.kubernetes.io/enforce: privileged
    pod-security.kubernetes.io/audit: privileged
    pod-security.kubernetes.io/warn: privileged
yaml
apiVersion: v1
kind: Namespace
metadata:
  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)

2. 基线模式(最低限制)

yaml
apiVersion: v1
kind: Namespace
metadata:
  name: baseline-ns
  labels:
    pod-security.kubernetes.io/enforce: baseline
    pod-security.kubernetes.io/audit: baseline
    pod-security.kubernetes.io/warn: baseline
yaml
apiVersion: v1
kind: Namespace
metadata:
  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)

3. 严格模式(最高限制)

yaml
apiVersion: v1
kind: Namespace
metadata:
  name: restricted-ns
  labels:
    pod-security.kubernetes.io/enforce: restricted
    pod-security.kubernetes.io/audit: restricted
    pod-security.kubernetes.io/warn: restricted
yaml
apiVersion: v1
kind: Namespace
metadata:
  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/v1
kind: NetworkPolicy
metadata:
  name: default-deny-all
  namespace: production
spec:
  podSelector: {}
  policyTypes:
    - Ingress
    - Egress
yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny-all
  namespace: production
spec:
  podSelector: {}
  policyTypes:
    - Ingress
    - Egress

Allow Frontend to Backend

允许前端访问后端

yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-frontend-to-backend
  namespace: production
spec:
  podSelector:
    matchLabels:
      app: backend
  policyTypes:
    - Ingress
  ingress:
    - from:
        - podSelector:
            matchLabels:
              app: frontend
      ports:
        - protocol: TCP
          port: 8080
yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-frontend-to-backend
  namespace: production
spec:
  podSelector:
    matchLabels:
      app: backend
  policyTypes:
    - Ingress
  ingress:
    - from:
        - podSelector:
            matchLabels:
              app: frontend
      ports:
        - protocol: TCP
          port: 8080

Allow DNS

允许DNS访问

yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-dns
  namespace: production
spec:
  podSelector: {}
  policyTypes:
    - Egress
  egress:
    - to:
        - namespaceSelector:
            matchLabels:
              name: kube-system
      ports:
        - protocol: UDP
          port: 53
Reference: See
assets/network-policy-template.yaml
yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-dns
  namespace: production
spec:
  podSelector: {}
  policyTypes:
    - Egress
  egress:
    - to:
        - namespaceSelector:
            matchLabels:
              name: kube-system
      ports:
        - protocol: UDP
          port: 53
参考文档: 请查看
assets/network-policy-template.yaml

RBAC Configuration

RBAC配置

Role (Namespace-scoped)

Role(命名空间级)

yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: pod-reader
  namespace: production
rules:
  - apiGroups: [""]
    resources: ["pods"]
    verbs: ["get", "watch", "list"]
yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: pod-reader
  namespace: production
rules:
  - apiGroups: [""]
    resources: ["pods"]
    verbs: ["get", "watch", "list"]

ClusterRole (Cluster-wide)

ClusterRole(集群级)

yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: secret-reader
rules:
  - apiGroups: [""]
    resources: ["secrets"]
    verbs: ["get", "watch", "list"]
yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: secret-reader
rules:
  - apiGroups: [""]
    resources: ["secrets"]
    verbs: ["get", "watch", "list"]

RoleBinding

RoleBinding

yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: read-pods
  namespace: production
subjects:
  - kind: User
    name: jane
    apiGroup: rbac.authorization.k8s.io
  - kind: ServiceAccount
    name: default
    namespace: production
roleRef:
  kind: Role
  name: pod-reader
  apiGroup: rbac.authorization.k8s.io
Reference: See
references/rbac-patterns.md
yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: read-pods
  namespace: production
subjects:
  - kind: User
    name: jane
    apiGroup: rbac.authorization.k8s.io
  - kind: ServiceAccount
    name: default
    namespace: production
roleRef:
  kind: Role
  name: pod-reader
  apiGroup: rbac.authorization.k8s.io
参考文档: 请查看
references/rbac-patterns.md

Pod Security Context

Pod安全上下文

Restricted Pod

受限Pod

yaml
apiVersion: v1
kind: Pod
metadata:
  name: secure-pod
spec:
  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
yaml
apiVersion: v1
kind: Pod
metadata:
  name: secure-pod
spec:
  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

使用OPA Gatekeeper实施策略

ConstraintTemplate

ConstraintTemplate

yaml
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
  name: k8srequiredlabels
spec:
  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])
        }
yaml
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
  name: k8srequiredlabels
spec:
  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

Constraint

yaml
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels
metadata:
  name: require-app-label
spec:
  match:
    kinds:
      - apiGroups: ["apps"]
        kinds: ["Deployment"]
  parameters:
    labels: ["app", "environment"]
yaml
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels
metadata:
  name: require-app-label
spec:
  match:
    kinds:
      - apiGroups: ["apps"]
        kinds: ["Deployment"]
  parameters:
    labels: ["app", "environment"]

Service Mesh Security (Istio)

服务网格安全(Istio)

PeerAuthentication (mTLS)

PeerAuthentication(mTLS)

yaml
apiVersion: security.istio.io/v1beta1
kind: PeerAuthentication
metadata:
  name: default
  namespace: production
spec:
  mtls:
    mode: STRICT
yaml
apiVersion: security.istio.io/v1beta1
kind: PeerAuthentication
metadata:
  name: default
  namespace: production
spec:
  mtls:
    mode: STRICT

AuthorizationPolicy

AuthorizationPolicy

yaml
apiVersion: security.istio.io/v1beta1
kind: AuthorizationPolicy
metadata:
  name: allow-frontend
  namespace: production
spec:
  selector:
    matchLabels:
      app: backend
  action: ALLOW
  rules:
    - from:
        - source:
            principals: ["cluster.local/ns/production/sa/frontend"]
yaml
apiVersion: security.istio.io/v1beta1
kind: AuthorizationPolicy
metadata:
  name: allow-frontend
  namespace: production
spec:
  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
  1. 在命名空间级别实施Pod安全标准
  2. 使用网络策略实现网络分段
  3. 为所有服务账户应用最小权限RBAC
  4. 启用准入控制(OPA Gatekeeper/Kyverno)
  5. 以非root用户运行容器
  6. 使用只读根文件系统
  7. 移除所有不必要的权限
  8. 实施资源配额和限制范围
  9. 启用安全事件审计日志
  10. 定期扫描镜像安全

Compliance Frameworks

合规框架

CIS Kubernetes Benchmark

CIS Kubernetes基准

  • Use RBAC authorization
  • Enable audit logging
  • Use Pod Security Standards
  • Configure network policies
  • Implement secrets encryption at rest
  • Enable node authentication
  • 使用RBAC授权
  • 启用审计日志
  • 使用Pod安全标准
  • 配置网络策略
  • 实施静态加密密钥
  • 启用节点认证

NIST Cybersecurity Framework

NIST网络安全框架

  • Implement defense in depth
  • Use network segmentation
  • Configure security monitoring
  • Implement access controls
  • Enable logging and monitoring
  • 实施纵深防御
  • 使用网络分段
  • 配置安全监控
  • 实施访问控制
  • 启用日志记录和监控

Troubleshooting

故障排查

NetworkPolicy not working:
bash
undefined
NetworkPolicy不生效:
bash
undefined

Check if CNI supports NetworkPolicy

检查CNI是否支持NetworkPolicy

kubectl get nodes -o wide kubectl describe networkpolicy <name>

**RBAC permission denied:**

```bash
kubectl get nodes -o wide kubectl describe networkpolicy <name>

**RBAC权限拒绝:**

```bash

Check effective permissions

检查有效权限

kubectl auth can-i list pods --as system:serviceaccount:default:my-sa kubectl auth can-i '' '' --as system:serviceaccount:default:my-sa
undefined
kubectl auth can-i list pods --as system:serviceaccount:default:my-sa kubectl auth can-i '' '' --as system:serviceaccount:default:my-sa
undefined

Reference Files

参考文件

  • assets/network-policy-template.yaml
    - Network policy examples
  • assets/pod-security-template.yaml
    - Pod security policies
  • references/rbac-patterns.md
    - RBAC configuration patterns
  • assets/network-policy-template.yaml
    - 网络策略示例
  • assets/pod-security-template.yaml
    - Pod安全策略示例
  • references/rbac-patterns.md
    - RBAC配置模式

Related Skills

相关技能

  • k8s-manifest-generator
    - For creating secure manifests
  • gitops-workflow
    - For automated policy deployment
  • k8s-manifest-generator
    - 用于创建安全的清单文件
  • gitops-workflow
    - 用于自动化策略部署