Implements Open Policy Agent (OPA) and Gatekeeper for policy-as-code in Kubernetes and CI/CD pipelines. Covers writing Rego policies, deploying as admission controller, local testing, and pipeline integration for enforcing security rules.
npx claudepluginhub killvxk/cybersecurity-skills-zhThis skill uses the workspace's default tool permissions.
- 以编程方式跨 Kubernetes 集群强制执行组织安全策略时
Implements Open Policy Agent (OPA) and Gatekeeper for policy-as-code enforcement in Kubernetes clusters and CI/CD pipelines using Rego policies, admission control, testing, and integration.
Implements OPA and Gatekeeper for policy-as-code enforcement in Kubernetes and CI/CD pipelines, including Rego policies, admission control deployment, testing, and pipeline integration.
Enforces policy-as-code in Kubernetes using OPA Gatekeeper or Kyverno to validate/mutate resources, prevent security misconfigurations, ensure compliance, and integrate with CI/CD.
Share bugs, ideas, or general feedback.
不适用于漏洞扫描(使用 Trivy/Checkov)、运行时威胁检测(使用 Falco)或网络策略执行(使用 Kubernetes NetworkPolicy 或 Calico)。
# 通过 Helm 安装 Gatekeeper
helm repo add gatekeeper https://open-policy-agent.github.io/gatekeeper/charts
helm install gatekeeper gatekeeper/gatekeeper \
--namespace gatekeeper-system --create-namespace \
--set replicas=3 \
--set audit.replicas=1 \
--set audit.writeToRAMDisk=true
# templates/k8s-required-labels.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}] {
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])
}
---
# templates/k8s-container-limits.yaml
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
name: k8scontainerlimits
spec:
crd:
spec:
names:
kind: K8sContainerLimits
validation:
openAPIV3Schema:
type: object
properties:
cpu:
type: string
memory:
type: string
targets:
- target: admission.k8s.gatekeeper.sh
rego: |
package k8scontainerlimits
violation[{"msg": msg}] {
container := input.review.object.spec.containers[_]
not container.resources.limits.cpu
msg := sprintf("Container %v has no CPU limit", [container.name])
}
violation[{"msg": msg}] {
container := input.review.object.spec.containers[_]
not container.resources.limits.memory
msg := sprintf("Container %v has no memory limit", [container.name])
}
---
# templates/k8s-block-privileged.yaml
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
name: k8sblockprivileged
spec:
crd:
spec:
names:
kind: K8sBlockPrivileged
targets:
- target: admission.k8s.gatekeeper.sh
rego: |
package k8sblockprivileged
violation[{"msg": msg}] {
container := input.review.object.spec.containers[_]
container.securityContext.privileged == true
msg := sprintf("Privileged container not allowed: %v", [container.name])
}
violation[{"msg": msg}] {
container := input.review.object.spec.initContainers[_]
container.securityContext.privileged == true
msg := sprintf("Privileged init container not allowed: %v", [container.name])
}
# constraints/require-labels.yaml
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels
metadata:
name: require-team-labels
spec:
enforcementAction: deny
match:
kinds:
- apiGroups: [""]
kinds: ["Namespace"]
- apiGroups: ["apps"]
kinds: ["Deployment", "StatefulSet"]
excludedNamespaces:
- kube-system
- gatekeeper-system
parameters:
labels:
- "team"
- "environment"
- "cost-center"
---
# constraints/block-privileged.yaml
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sBlockPrivileged
metadata:
name: block-privileged-containers
spec:
enforcementAction: deny
match:
kinds:
- apiGroups: [""]
kinds: ["Pod"]
- apiGroups: ["apps"]
kinds: ["Deployment", "DaemonSet", "StatefulSet"]
excludedNamespaces:
- kube-system
# 安装 conftest
brew install conftest
# 在本地针对 OPA 策略测试 Kubernetes 清单
conftest test deployment.yaml --policy policies/ --output json
# 针对 OPA 策略测试 Terraform
conftest test terraform/main.tf --policy policies/terraform/ --parser hcl2
# 测试 Dockerfile
conftest test Dockerfile --policy policies/docker/
# policies/kubernetes/deny_latest_tag.rego
package kubernetes
deny[msg] {
input.kind == "Deployment"
container := input.spec.template.spec.containers[_]
endswith(container.image, ":latest")
msg := sprintf("Container %v uses :latest tag. Pin to specific version.", [container.name])
}
deny[msg] {
input.kind == "Deployment"
container := input.spec.template.spec.containers[_]
not contains(container.image, ":")
msg := sprintf("Container %v has no tag. Pin to specific version.", [container.name])
}
# .github/workflows/policy-test.yml
name: Policy Validation
on:
pull_request:
paths: ['k8s/**', 'terraform/**', 'policies/**']
jobs:
conftest:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install conftest
run: |
wget -q https://github.com/open-policy-agent/conftest/releases/download/v0.50.0/conftest_0.50.0_Linux_x86_64.tar.gz
tar xzf conftest_0.50.0_Linux_x86_64.tar.gz
sudo mv conftest /usr/local/bin/
- name: Test K8s manifests
run: conftest test k8s/**/*.yaml --policy policies/kubernetes/ --output json
- name: Test Terraform
run: conftest test terraform/*.tf --policy policies/terraform/ --parser hcl2
| 术语 | 定义 |
|---|---|
| OPA | Open Policy Agent — 使用 Rego 语言进行策略决策的通用策略引擎 |
| Rego | OPA 用于编写策略规则的声明性查询语言 |
| Gatekeeper | 实现通过 ConstraintTemplates 进行准入控制的 Kubernetes 原生 OPA 集成 |
| ConstraintTemplate | 定义 Rego 策略逻辑和约束类参数模式的 CRD |
| Constraint | ConstraintTemplate 的实例,包含特定参数和范围(检查哪些资源) |
| 准入控制器 | 在持久化之前拦截 API 请求并可允许或拒绝的 Kubernetes 组件 |
| conftest | 用于针对 OPA 策略测试结构化数据(YAML、JSON、HCL)的 CLI 工具 |
背景:多个开发团队部署到共享的 Kubernetes 集群。部分团队运行特权容器和没有资源限制的镜像,导致安全和稳定性问题。
方法:
enforcementAction: warn 开始,识别违规而不阻止部署enforcementAction: denyexcludedNamespaces注意事项:立即以 deny 模式部署 Gatekeeper 可能会破坏现有工作负载。始终从 warn 模式开始。过于严格且没有系统命名空间豁免的策略可能阻止集群组件正常运行。
OPA 策略评估报告
==============================
集群:production-east
日期:2026-02-23
Gatekeeper 版本:3.16.0
约束摘要:
K8sRequiredLabels: 12 个违规(warn)
K8sBlockPrivileged: 0 个违规(deny)
K8sContainerLimits: 8 个违规(deny)
K8sBlockLatestTag: 3 个违规(deny)
已拦截部署(deny):
[K8sContainerLimits] deployment/api-server in ns/payments
- 容器 'api' 没有内存限制
[K8sBlockLatestTag] deployment/frontend in ns/web
- 容器 'nginx' 使用 :latest 标签
审计违规(warn):
[K8sRequiredLabels] namespace/staging
- 缺少标签:{cost-center}