安全
ns-level-pss

在命名空间级别应用 Pod 安全标准

注意:本教程仅适用于新集群。

Pod 安全准入是一种准入控制器,它在创建 Pod 时应用 Pod 安全标准。这是一个在 v1.25 版本中达到稳定版本(GA)的功能。在本教程中,你将一次为一个命名空间强制实施基线 Pod 安全标准。

你也可以在集群级别同时将 Pod 安全标准应用于多个命名空间。有关说明,请参考 “在集群级别应用 Pod 安全标准”。

开始之前

在你的工作站上安装以下工具:

  • kind
  • kubectl

1.按如下方式创建一个 kind 集群:

kind create cluster --name psa-ns-level

输出类似如下:

Creating cluster "psa-ns-level" ...
 ✓ Ensuring node image (kindest/node:v1.32.0) 🖼 
 ✓ Preparing nodes 📦  
 ✓ Writing configuration 📜 
 ✓ Starting control-plane 🕹️ 
 ✓ Installing CNI 🔌 
 ✓ Installing StorageClass 💾 
Set kubectl context to "kind-psa-ns-level"
You can now use your cluster with:

kubectl cluster-info --context kind-psa-ns-level

Not sure what to do next? 😅  Check out https://kind.sigs.k8s.io/docs/user/quick-start/

2.设置 kubectl 上下文为新集群

kubectl cluster-info --context kind-psa-ns-level

输出类似如下:

Kubernetes control plane is running at https://127.0.0.1:50996
CoreDNS is running at https://127.0.0.1:50996/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy

To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.

3.创建一个名为 example 的新命名空间:

kubectl create ns example

输出类似如下:

namespace/example created

为该命名空间启用 Pod 安全标准检查 使用内置 Pod 安全准入支持的标签在这个命名空间上启用 Pod 安全标准。在这一步中,你将配置一个检查,对于不符合最新版本基线 Pod 安全标准的 Pod 发出警告。

kubectl label --overwrite ns example \
   pod-security.kubernetes.io/warn=baseline \
   pod-security.kubernetes.io/warn-version=latest

你可以使用标签在任何命名空间上配置多个 Pod 安全标准检查。以下命令将强制实施基线 Pod 安全标准,但根据最新版本(默认值)对受限 Pod 安全标准进行警告和审计:

kubectl label --overwrite ns example \
  pod-security.kubernetes.io/enforce=baseline \
  pod-security.kubernetes.io/enforce-version=latest \
  pod-security.kubernetes.io/warn=restricted \
  pod-security.kubernetes.io/warn-version=latest \
  pod-security.kubernetes.io/audit=restricted \
  pod-security.kubernetes.io/audit-version=latest

验证 Pod 安全标准的实施情况 在 example 命名空间中创建一个基线 Pod:

kubectl apply -n example -f https://k8s.io/examples/security/example-baseline-pod.yaml

该 Pod 确实可以正常启动;输出中包含一个警告。例如:

Warning: would violate PodSecurity "restricted:latest": allowPrivilegeEscalation != false (container "nginx" must set securityContext.allowPrivilegeEscalation=false), unrestricted capabilities (container "nginx" must set securityContext.capabilities.drop=["ALL"]), runAsNonRoot != true (pod or container "nginx" must set securityContext.runAsNonRoot=true), seccompProfile (pod or container "nginx" must set securityContext.seccompProfile.type to "RuntimeDefault" or "Localhost")
pod/nginx created

在 default 命名空间中创建一个基线 Pod:

kubectl apply -n default -f https://k8s.io/examples/security/example-baseline-pod.yaml

输出类似如下:

pod/nginx created

Pod 安全标准的实施和警告设置仅应用于 example 命名空间。你可以在 default 命名空间中创建相同的 Pod 而不会收到警告。

清理操作

现在,通过运行以下命令删除你在上述步骤中创建的集群:

kind delete cluster --name psa-ns-level