遵循 Pod Security Restricted 标准

功能概述

pod-security.kubernetes.io/enforce=restricted 标准是限制最严格的 Pod Security Standard,执行当前 Pod 加固最佳实践。当命名空间使用此标准标记时,在该命名空间中创建的所有 Pod 都必须符合严格的安全要求。

本指南介绍如何配置 Tekton Pipelines 以满足 restricted 安全标准,确保 Tasks 中的所有容器都能在受限命名空间中成功运行。

使用场景

  • 在带有 pod-security.kubernetes.io/enforce=restricted 标签的命名空间中运行 Tekton Pipelines
  • 满足组织的安全合规要求
  • 增强 CI/CD 流水线的安全态势
  • 在高度监管的环境中运行工作负载

前提条件

  • Tekton Pipelines 通过 TektonConfig CR 安装,或通过不受 TektonConfig 管理的 TektonPipeline CR 安装
  • 你有权修改 TektonConfig 资源,或者在其不受 TektonConfig 管理时修改 TektonPipeline 资源
  • 你可以创建或编辑 Task 定义
  • 对于自定义镜像,你有权限修改 Containerfiles 并重新构建镜像
  • 若要在工作站上检查镜像(第 3 步),需要使用能够拉取镜像的容器 CLI,例如 podman 或 docker

了解 Restricted 标准

pod-security.kubernetes.io/enforce=restricted 标准要求 Pod 中的以下三类容器满足相应的安全上下文要求:

  • 常规容器(containers)
  • Init 容器(initContainers)
  • 临时容器(ephemeralContainers)

每个容器都必须设置 allowPrivilegeEscalation: false,并删除 ALL 功能。可以在每个容器上设置 runAsNonRoot: true 和类型为 RuntimeDefault 或 Localhost 的 seccompProfile,也可以在 Pod securityContext 中统一设置。以下容器安全上下文设置了全部四个字段,正如本页步骤示例中所示:

securityContext:
  allowPrivilegeEscalation: false
  runAsNonRoot: true
  capabilities:
    drop:
      - "ALL"
  seccompProfile:
    type: RuntimeDefault

配置说明

字段值用途影响
allowPrivilegeEscalationfalse防止进程获得比其父进程更多的权限阻止恶意代码通过 setuid 二进制文件或文件功能提升权限
runAsNonRoottrue要求容器以非 root 用户(UID ≠ 0)运行防止容器以 root 身份运行,降低容器逃逸漏洞的影响
capabilities.drop仅包含 ALL 的列表删除容器的所有 Linux 功能限制容器执行特权操作的能力(例如配置网络、加载内核模块)
seccompProfile.typeRuntimeDefault应用容器运行时的默认 seccomp 配置文件限制容器可用的系统调用,减少内核攻击面

步骤

1. 配置 Tekton 为 Init 容器添加安全上下文

Tekton 会为其管理的每个 Pod 创建 Init 容器。为符合 restricted 标准,这些 Init 容器需要配置所需的安全上下文;当 set-security-context 为 true 时,Tekton 会添加该安全上下文。在 Alauda DevOps Pipelines 4.15.1 中,set-security-context 默认设置为 true。以下命令仅在其被设置为 false 时重新启用;在默认安装中,这些命令会报告 patched (no change)。

选项 A:通过 TektonPipeline 配置

如果直接通过 TektonPipeline CR 管理 Tekton:

注意:在默认安装中,名为 config 的 TektonConfig 管理名为 pipeline 的 TektonPipeline,且 operator 会在几秒内覆盖对 TektonPipeline spec 的直接更改。请通过 TektonConfig(选项 B)进行配置。仅当 TektonPipeline 不由 TektonConfig 管理时,选项 A 才适用。

apiVersion: operator.tekton.dev/v1alpha1
kind: TektonPipeline
spec:
  set-security-context: true

应用配置:

$ kubectl patch tektonpipeline pipeline \
  --type merge \
  -p '{"spec":{"set-security-context":true}}'

tektonpipeline.operator.tekton.dev/pipeline patched (no change)

选项 B:通过 TektonConfig 配置

如果通过 TektonConfig CR 管理 Tekton:

apiVersion: operator.tekton.dev/v1alpha1
kind: TektonConfig
spec:
  pipeline:
    set-security-context: true

应用配置:

$ kubectl patch tektonconfig config \
  --type merge \
  -p '{"spec":{"pipeline":{"set-security-context":true}}}'

tektonconfig.operator.tekton.dev/config patched (no change)

注意:此配置更改会立即生效,无需重启 Tekton controller。更改后创建的新 TaskRuns 和 PipelineRuns 会自动为 Init 容器应用所需的安全上下文。

2. 在自定义 Task 定义中添加安全上下文

对于自定义 Tasks(不是平台提供的内置 Tasks),需要在 sidecars 中为每个步骤和每个 sidecar 显式添加安全上下文。步骤和 sidecar 作为容器运行在 TaskRun Pod 中。set-security-context(步骤 1)会为 Tekton 添加到 Pod 中的 Init 容器以及其添加的 results sidecar 添加安全上下文,但不会为您的 Task 的步骤和 sidecar 添加安全上下文。缺少该安全上下文的 sidecar 会导致 restricted 标准拒绝该 Pod,并导致 TaskRun 失败,原因是 PodAdmissionFailed。

带安全上下文的 Task 示例:

apiVersion: tekton.dev/v1
kind: Task
metadata:
  name: custom-build-task
spec:
  steps:
    - name: build
      image: registry.example.com/builder:latest
      securityContext:
        allowPrivilegeEscalation: false
        runAsNonRoot: true
        capabilities:
          drop:
            - "ALL"
        seccompProfile:
          type: RuntimeDefault
      script: |
        #!/bin/sh
        echo "Building application..."

注意:请将本页中的示例镜像替换为集群可以拉取的镜像,例如内部 registry 中的镜像。registry.example.com/... 镜像代表您自己的镜像。

重要:此步骤适用于自定义 Tasks。平台提供的内置 Tasks(buildah 除外,参见内置 Task 和 Restricted 标准)已经在其步骤中声明了符合 restricted 的 securityContext,因此无需添加。

3. 配置容器镜像以使用非 root 用户

必须将容器镜像配置为以非 root 用户运行。必须使用数字 UID 而不是用户名指定该用户。

在您的 Containerfile 中添加非 root 用户,并将其设置为默认用户。以下是基于 Alpine 的镜像示例:

# Add a non-root user with UID 65532 (Alpine syntax)
RUN adduser -u 65532 -h /home/nonroot -D nonroot

# Set appropriate permissions for working directories
RUN chown -R 65532:65532 /app

# Switch to the non-root user (use numeric UID)
USER 65532

注意:adduser 命令语法因基础镜像而异。有关其他基础镜像的示例,请参阅下面引用的文档。

使用 podman 验证镜像配置,或使用参数相同的 docker 进行验证。将 <image> 替换为您构建的镜像。--entrypoint id 会运行镜像的 id 命令,而不是其 ENTRYPOINT;如果不使用该参数,对于设置了 ENTRYPOINT 的镜像,id 将作为该 ENTRYPOINT 的参数传入:

# Check that the image runs as non-root
$ podman run -it --rm --entrypoint id <image>

uid=65532(nonroot) gid=65532(nonroot) groups=65532(nonroot)

有关调整 catalog Task 镜像的详细指导,请参阅 调整 Containerfile 以构建兼容 Task 的自定义镜像。

操作结果

完成上述步骤后:

  1. Init 容器:由 Tekton 创建的 init 容器将自动符合 restricted 标准
  2. 自定义 Task:您的自定义 Tasks 的步骤和 sidecar 将具有所需的安全上下文
  3. 容器镜像:镜像将以非 root 用户运行,并仅具有最小权限

您可以通过在受限命名空间中创建 TaskRun 来验证合规性。请使用新的测试命名空间:该标签适用于命名空间中的每个 Pod,因此请勿将其添加到其他工作负载正在使用的命名空间。

将以下 TaskRun 保存为 taskrun.yaml。由于新命名空间中不存在步骤 2 中的 custom-build-task Task,因此 TaskRun 将同一个步骤作为内联 taskSpec 保存。Tekton webhook 会在集群设置 disable-inline-spec 包含 taskrun 时拒绝带有内联 taskSpec 的 TaskRun(请参阅 使用 Kyverno 约束 Tekton Pipeline 执行);在此类集群中,请在新命名空间中创建步骤 2 的 Task,并改用 taskRef 引用它。请使用以非 root 用户运行的镜像(步骤 3):

apiVersion: tekton.dev/v1
kind: TaskRun
metadata:
  name: example-taskrun
spec:
  taskSpec:
    steps:
      - name: build
        image: registry.example.com/builder:latest
        securityContext:
          allowPrivilegeEscalation: false
          runAsNonRoot: true
          capabilities:
            drop:
              - "ALL"
          seccompProfile:
            type: RuntimeDefault
        script: |
          #!/bin/sh
          echo "Building application..."
# Create a test namespace and label it with the restricted standard
$ kubectl create namespace test-ns

namespace/test-ns created

$ kubectl label namespace test-ns pod-security.kubernetes.io/enforce=restricted

namespace/test-ns labeled

# Create a TaskRun in the restricted namespace
$ kubectl -n test-ns create -f taskrun.yaml

taskrun.tekton.dev/example-taskrun created

# Verify the TaskRun succeeds
$ kubectl -n test-ns get taskrun

NAME              SUCCEEDED   REASON      STARTTIME   COMPLETIONTIME
example-taskrun   True        Succeeded   2m          1m

# Delete the test namespace when the check is done
$ kubectl delete namespace test-ns

namespace "test-ns" deleted

成功的 TaskRun 会显示 SUCCEEDED 为 True,并显示 REASON 为 Succeeded,这表明所有容器均已在所需的安全约束下成功运行。

使用策略强制工具

如需采用更加自动化的方法,您可以使用 Kyverno 等策略强制工具,自动将所需的安全上下文注入所有容器。通过创建 Kyverno Policy(使用 apiVersion: kyverno.io/v1 和 kind: Policy),您可以自动修改 Pods,以添加必要的安全上下文配置。

有关更多信息,请参阅 场景 4:指定命名空间安全上下文强制。

Buildah 限制

这种基于 Kyverno 的方法无法使内置的 buildah Task 兼容 restricted 标准。有关 buildah 限制,请参阅下方的内置 Task 与 Restricted 标准。

此方法无需为每个 Task 手动配置安全上下文,从而简化合规性管理。

有关为此目的配置 Kyverno 策略的详细指导,请参阅:

故障排除

内置 Task 与 Restricted 标准

在平台提供的内置 Tasks 中,只有 buildah Task 无法在 restricted 标准下运行。这是因为 buildah 需要提升的权限才能构建容器镜像。

即使使用 Kyverno 自动将所需的 restricted 安全上下文注入 Pod,这一限制仍然适用。Kyverno 可以添加 restricted 标准所需的字段,但无法使内置 buildah Task 与 restricted 兼容,因为 buildah 需要该标准所禁止的权限。

buildah Task 需要以下安全上下文:

securityContext:
  # allowPrivilegeEscalation: false  # Cannot be set to false - buildah needs to escalate privileges to use the SETFCAP capability for setting file capabilities during container image builds; forcing false also blocks newuidmap/newgidmap, causing rootless to fall back to single UID/GID mapping with warnings and potentially incorrect file ownership
  runAsNonRoot: true
  capabilities:
    # drop:  # Cannot drop ALL capabilities - buildah requires SETFCAP capability to set file capabilities (e.g., cap_net_bind_service) on files within container images during the build process
    #   - "ALL"
    add:
      - "SETFCAP"
  # seccompProfile:
  #   type: RuntimeDefault  # Cannot use RuntimeDefault - default seccomp blocks unshare/clone(CLONE_NEWUSER)/setns needed by buildah, leading to build failure; the baseline standard rejects an explicit Unconfined, so use a Localhost profile that allows these syscalls instead

解决方案:

  1. 在单独的命名空间中使用 buildah Task,并将模式设置为 baseline,而不是 restricted 模式。

    若要允许 buildah 工作负载运行,必须将 pod-security.kubernetes.io/enforce 更改为 baseline。warn 和 audit 标签不会阻止准入。请先读取并保存标签的当前值,并按照推荐设置中的说明稍后恢复该值。

    # Required: change enforce to baseline for buildah workloads
    $ kubectl label namespace <build-namespace> \
      pod-security.kubernetes.io/enforce=baseline \
      --overwrite
    
    namespace/<build-namespace> labeled

    重新标记命名空间后,创建新的 TaskRun 或 PipelineRun,使其在该命名空间中使用 buildah Task。正确配置 registry 凭据、Containerfile 和工作区后,buildah Task 即可在 baseline 标准下正常运行。

    可选:如果命名空间必须为 buildah 使用 baseline 模式,但您仍希望阻止同一命名空间中的其他 Pod 请求更广泛的权限,请启用 Tekton Pipelines ValidatingAdmissionPolicy 防护机制。此防护机制不会使内置 buildah Task 与 restricted 模式兼容。它适用于带有 buildah.alauda.io/enabled=true 标签的命名空间中的所有 Pod:仅允许 buildah 所需的 SETFCAP 添加能力,并拒绝特权容器、主机命名空间、hostPath 卷以及除 SETFCAP 之外的其他添加能力。

    编辑 TektonConfig 资源以启用该策略:

    kubectl edit tektonconfig config

    在 spec.pipeline.params 下添加或更新以下条目。如果 params 已包含其他条目,请保留这些条目,仅添加或更新 enable-validating-admission-policy。

    apiVersion: operator.tekton.dev/v1alpha1
    kind: TektonConfig
    metadata:
      name: config
    spec:
      pipeline:
        params:
          - name: enable-validating-admission-policy
            value: "true"

    等待 TektonConfig 就绪:

    $ kubectl get tektonconfig config \
      -o jsonpath='{.status.conditions[?(@.type=="Ready")].status}{"\n"}'
    
    True

    验证策略资源是否已安装:

    kubectl get validatingadmissionpolicy pipelines-restricted
    kubectl get validatingadmissionpolicybinding pipelines-restricted

    两条命令都应返回名为 pipelines-restricted 的资源。

    # Enable the guardrail for the build namespace.
    $ kubectl label namespace <build-namespace> \
      buildah.alauda.io/enabled=true \
      --overwrite
    
    namespace/<build-namespace> labeled

    验证该防护机制是否会拒绝请求超出 buildah 例外范围的权限的工作负载。以下服务器端试运行不会创建 Pod,但仍会经过准入流程。由于 NET_BIND_SERVICE 虽被 baseline 标准允许,但不被此防护机制允许,因此该操作应被拒绝:

    $ kubectl -n <build-namespace> create -f - --dry-run=server <<'EOF'
    apiVersion: v1
    kind: Pod
    metadata:
      name: vap-extra-capability-check
    spec:
      restartPolicy: Never
      containers:
        - name: check
          image: registry.k8s.io/pause:3.9
          securityContext:
            capabilities:
              add:
                - NET_BIND_SERVICE
    EOF
    
    The pods "vap-extra-capability-check" is invalid: : ValidatingAdmissionPolicy 'pipelines-restricted' with binding 'pipelines-restricted' denied request: only SETFCAP capability may be added
  2. 研究可能具有不同安全要求的替代容器镜像构建方法。

TaskRun 因容器用户错误而失败

您可能会遇到以下错误之一:

  • “container has runAsNonRoot and image will run as root” - 容器镜像在 Containerfile 中没有 USER 指令(默认为 root),或者显式设置了 USER 0
  • “container has runAsNonRoot and image has non-numeric user” - 容器镜像使用符号用户名(例如 USER appuser 或 USER root),而不是数字 UID

解决方案:

  1. 按照步骤 3 中的说明,使用数字非 root 用户 ID 重新构建镜像。例如,使用 USER 65532,而不是 USER appuser 或 USER root。

  2. 在 Task securityContext 中指定用户:

    apiVersion: tekton.dev/v1
    kind: Task
    metadata:
      name: example-task
    spec:
      steps:
        - name: step1
          image: registry.example.com/myimage:latest
          securityContext:
            runAsUser: 65532
            runAsNonRoot: true
            allowPrivilegeEscalation: false
            capabilities:
              drop:
                - "ALL"
            seccompProfile:
              type: RuntimeDefault
          script: |
            #!/bin/sh
            echo "Running as user $(id -u)"
  3. 在 TaskRun podTemplate 中指定用户:

    apiVersion: tekton.dev/v1
    kind: TaskRun
    metadata:
      name: example-taskrun
    spec:
      taskRef:
        name: example-task
      podTemplate:
        securityContext:
          runAsUser: 65532
          runAsNonRoot: true
          fsGroup: 65532
          fsGroupChangePolicy: "OnRootMismatch"

注意:podTemplate.securityContext 设置 Pod 级别的安全上下文,除非在容器级别被覆盖,否则所有容器都会继承该上下文。它会整体替换默认 Pod 模板的 securityContext,因此示例中会重复随附的 fsGroupChangePolicy: "OnRootMismatch"。

当您无法修改容器镜像时,选项 2 和 3 很有用。

TaskRun 因 violates PodSecurity "restricted:latest": unrestricted capabilities 而失败

TaskRun 会因 PodAdmissionFailed 原因而失败,并显示类似 pods "<taskrun-name>-pod" is forbidden: violates PodSecurity "restricted:latest": unrestricted capabilities (container "step-<step-name>" must not include "SYS_ADMIN" in securityContext.capabilities.add) 的消息。restricted 标准会拒绝 securityContext.capabilities.add 中除 NET_BIND_SERVICE 之外的任何能力,即使该步骤同时删除了 ALL。

解决方案:从 capabilities.add 中删除该能力,并在 capabilities.drop 中保留 ALL。restricted 标准唯一允许您重新添加的能力是 NET_BIND_SERVICE。

Pod 模板设置 runAsUser: 0 后 TaskRun 因 CreateContainerConfigError 而失败

如果 TaskRun 因 CreateContainerConfigError 而失败,且 Pod 事件显示 Error: container's runAsUser breaks non-root policy (pod: "<pod-name>_<namespace>(<pod-uid>)", container: prepare),则表示 Pod 模板设置了 runAsUser: 0。使用 set-security-context: true 时,Tekton 会以 runAsNonRoot: true 启动其 init 容器(例如 prepare),且不会设置 runAsUser,因此这些容器会继承 Pod 级别的 UID 0。在强制执行 restricted 的命名空间中,Pod 会在准入阶段被拒绝,而 TaskRun 会因 PodAdmissionFailed 而失败。

解决方案:从 TaskRun、PipelineRun 的 Pod 模板或全局默认设置中删除 runAsUser: 0,并按照TaskRun 因容器用户错误而失败中的选项 3 使用非 root UID。

启用时机。当多个项目共享一个集群,并且需要为其流水线 Pod 设置一个统一的最低安全级别时,启用 restricted 标准。

建议值。为每个流水线工作负载命名空间添加标签 pod-security.kubernetes.io/enforce=restricted。在内置的 Tasks 中,只有 buildah Task 无法在 restricted 下运行(请参阅内置 Task 和 Restricted 标准);按照该部分中的说明,在标记为 pod-security.kubernetes.io/enforce=baseline 的单独命名空间中运行镜像构建。该部分还介绍了可选的 ValidatingAdmissionPolicy 防护措施,可用于此类命名空间。

更改标签需要具有修补 Namespace 对象的权限。该对象的作用域为集群级别,因此通常由集群管理员执行此操作。在更改命名空间的标签之前,请读取其当前值并保存输出。输出为空表示未设置该标签:

kubectl get namespace <namespace> -o jsonpath='{.metadata.labels.pod-security\.kubernetes\.io/enforce}'

然后设置标签。当标签已有值时需要使用 --overwrite;如果不使用该参数,kubectl 会因 error: 'pod-security.kubernetes.io/enforce' already has a value (<value>), and --overwrite is false 而停止:

kubectl label namespace <namespace> pod-security.kubernetes.io/enforce=restricted --overwrite

要撤销更改,请再次设置已保存的值:

kubectl label namespace <namespace> pod-security.kubernetes.io/enforce=<saved-value> --overwrite

如果保存的输出为空,则改为删除该标签:

kubectl label namespace <namespace> pod-security.kubernetes.io/enforce-

在 TektonConfig 中,对于 init 容器,将 set-security-context 保持为其默认值 true(Steps 部分中的步骤 1),并按照方法 4:全局默认配置(TektonConfig)中的说明,一次性设置非 root 默认 Pod 模板:

apiVersion: operator.tekton.dev/v1alpha1
kind: TektonConfig
metadata:
  name: config
spec:
  pipeline:
    set-security-context: true
    default-pod-template: |
      securityContext:
        runAsNonRoot: true
        runAsUser: 65532
        fsGroup: 65532
        fsGroupChangePolicy: "OnRootMismatch"

default-pod-template 值会整体替换当前默认 Pod 模板,并应用于集群中每个新建的 TaskRun。首先读取生效的值以及 TektonConfig 中设置的值,并保存这两个输出;保留示例中的默认字段。在默认安装中,生效的值是随附的模板,其中包含 fsGroup: 65532 和 fsGroupChangePolicy: "OnRootMismatch",示例中会重复这些字段:

kubectl get configmap -n tekton-pipelines config-defaults -o jsonpath='{.data.default-pod-template}'
kubectl get tektonconfig config -o jsonpath='{.spec.pipeline.default-pod-template}'

tekton-pipelines 是 TektonConfig spec.targetNamespace 的默认值;如果您的安装使用其他命名空间,请在命令中替换该值。

将示例保存为 tektonconfig-security.yaml,然后按照步骤 1 中的相同方式,将其合并到现有的 TektonConfig 中:

kubectl patch tektonconfig config --type merge --patch-file tektonconfig-security.yaml

不要对这个部分示例使用 kubectl apply -f。它会警告 tektonconfigs/config 缺少 kubectl.kubernetes.io/last-applied-configuration 注解,然后使用文件内容添加该注解;之后对另一个部分 TektonConfig 文件执行 kubectl apply -f 时,会删除该文件设置而后续文件未包含的字段,例如此处的 default-pod-template。

要撤销更改:如果保存的 TektonConfig 输出为空,请从 TektonConfig 中删除该字段,以恢复随附的默认 Pod 模板:

kubectl patch tektonconfig config --type json \
  -p '[{"op":"remove","path":"/spec/pipeline/default-pod-template"}]'

否则,请再次设置已保存的 TektonConfig 值。

如果自定义镜像需要,单个 TaskRuns 或 PipelineRuns 仍可以覆盖默认 Pod 模板;请参阅 Pod 模板配置指南。覆盖会整体替换默认 Pod 模板的 securityContext,因此在 restricted 命名空间中,除非 Task 的每个步骤和每个 sidecar 都设置了 runAsNonRoot: true,否则请在覆盖中重复设置该值。

先决条件。需要具有修改 TektonConfig 以及修补要添加标签的命名空间的权限;两者都是集群级别的对象,因此通常由集群管理员执行。自定义 Tasks 必须在每个步骤和每个 sidecar 上声明容器安全上下文,并使用以数字形式的非 root UID 运行的镜像(上方默认 Pod 模板中的 runAsUser 也满足此检查,但镜像随后必须能够以该 UID 运行),如 Steps 部分中的步骤 2 和 3 所述;在将命名空间迁移到 restricted 之前,请按照 调整 Containerfile 以构建兼容 Task 的自定义镜像 中的说明构建自定义 Task 镜像。

了解更多