源代码仓库验证
在 Tekton Chains 中,它可以从 PipelineRun 收集特定输入和输出,并将其记录到 SLSA Provenance 中。
我们可以利用此功能将代码仓库信息包含到 SLSA Provenance 信息中。然后,我们可以在 kyverno 中验证代码仓库。
功能概述
此方法使用 Chains 为构建的镜像自动生成 SLSA Provenance,然后使用 Kyverno 验证 provenance:
- 配置 Tekton Chains,为构建的镜像自动生成 SLSA Provenance。
- 使用
git Tekton Task 获取源代码仓库。
- 使用
buildah Tekton Task 构建镜像。
- 在 Pipeline 的 results 中声明
git 和 buildah 的结果信息。这样便于记录镜像的源代码仓库和 commit 信息。
- 配置 Kyverno 规则以验证源代码仓库。
- 使用该镜像创建 Pod 以验证源代码仓库。
使用场景
以下场景需要参考本文档中的指导:
- 在 Kubernetes 集群中使用 Kyverno 实现源代码仓库验证
- 强制安全策略,只允许部署由特定源代码仓库构建的镜像
- 在 CI/CD pipeline 中设置自动化源代码仓库验证
- 在生产环境中确保镜像 provenance 和源代码真实性
- 通过验证容器镜像的源代码来源来实现供应链安全控制
前提条件
- 已安装 Tekton Pipelines、Tekton Chains 和 Kyverno 的 Kubernetes 集群
- 已启用镜像推送的 registry
- 已安装并配置好用于访问集群的
kubectl CLI
- 已安装
cosign CLI 工具
- 已安装
jq CLI 工具
流程概览
分步说明
步骤 1-3:基础设置
这些步骤与 Quick Start: Signed Provenance 指南完全相同。请按照该指南完成以下操作:
步骤 4:创建示例 Pipeline
在前面的 镜像构建 pipeline 中,添加一个 git clone task,并将 git task 的输出保存到 PipelineRun 的 results 中。
apiVersion: tekton.dev/v1
kind: Pipeline
metadata:
name: chains-demo-3
spec:
params:
- default: |-
echo "Simulate cloning the code and write the repository URL and commit message into the results."
# This commit sha must be a valid commit sha [0-9a-f]{40}.
cat << 'EOF' > $(results.array-result.path)
[
"https://github.com/tektoncd/pipeline",
"cccccaaaa0000000000000000000000000000000"
]
EOF
echo -e "\nResults:"
echo "-------------------"
cat $(results.array-result.path)
echo "-------------------"
echo -e "\nClone successfully!"
description: A script to simulate cloning the code and write the repository URL and commit message into the results.
name: generate-git-clone-results
type: string
- default: |-
echo "Generate a Containerfile for building an image."
cat << 'EOF' > Containerfile
FROM ubuntu:latest
ENV TIME=1
EOF
echo -e "\nContainerfile contents:"
echo "-------------------"
cat Containerfile
echo "-------------------"
echo -e "\nContainerfile generated successfully!"
description: A script to generate a Containerfile for building an image.
name: generate-containerfile
type: string
- default: <registry>/test/chains/demo-3:latest
description: The target image address built
name: image
type: string
results:
- description: first image artifact output
name: first_image_ARTIFACT_OUTPUTS
type: object
value:
digest: $(tasks.build-image.results.IMAGE_DIGEST)
uri: $(tasks.build-image.results.IMAGE_URL)
- description: first repo artifact input
name: source_repo_ARTIFACT_INPUTS
type: object
value:
digest: sha1:$(tasks.git-clone.results.array-result[1])
uri: $(tasks.git-clone.results.array-result[0])
tasks:
- name: git-clone
params:
- name: script
value: $(params.generate-git-clone-results)
taskRef:
params:
- name: kind
value: task
- name: catalog
value: catalog
- name: name
value: run-script
- name: version
value: "0.1"
resolver: hub
timeout: 30m0s
workspaces:
- name: source
workspace: source
- name: generate-containerfile
params:
- name: script
value: $(params.generate-containerfile)
runAfter:
- git-clone
taskRef:
params:
- name: kind
value: task
- name: catalog
value: catalog
- name: name
value: run-script
- name: version
value: "0.1"
resolver: hub
timeout: 30m0s
workspaces:
- name: source
workspace: source
- name: build-image
params:
- name: IMAGES
value:
- $(params.image)
- name: TLS_VERIFY
value: "false"
runAfter:
- generate-containerfile
taskRef:
params:
- name: kind
value: task
- name: catalog
value: catalog
- name: name
value: buildah
- name: version
value: "0.9"
resolver: hub
timeout: 30m0s
workspaces:
- name: source
workspace: source
- name: registryconfig
workspace: registryconfig
workspaces:
- name: source
description: The workspace for source code.
- name: registryconfig
description: The workspace for distribution registry configuration.
TIP
本教程通过在 pipeline 中直接生成 Containerfile 和 git-clone task 输出,演示了一个简化后的工作流。
在生产环境中,通常会:
- 使用
git-clone task 从你的仓库获取源代码
- 使用源代码中已存在的 Containerfile 构建镜像
- 这种方式可确保正确的版本控制,并保持代码与 pipeline 配置之间的分离
YAML 字段说明
- 大多数字段与 步骤 4:创建示例 Pipeline 中相同。下面仅介绍差异部分。
params
generate-git-clone-results:用于模拟克隆代码并将仓库 URL 和 commit 信息写入 results 的脚本。
results
source_repo_ARTIFACT_INPUTS:源代码仓库 URL 和 commit 信息。
digest:源代码仓库的 commit sha。
- 该格式与 Tekton Chains 兼容,更多详细信息请参阅上文中的 Tekton Chains Type Hinting。
需要调整的配置
params:
generate-containerfile
default:调整 from image 地址。
image:
将其保存为名为 chains.demo-3.pipeline.yaml 的 yaml 文件,并执行:
$ export NAMESPACE=<default>
$ kubectl apply -n $NAMESPACE -f chains.demo-3.pipeline.yaml
步骤 5:运行示例 Pipeline
这是一个 PipelineRun 资源,用于运行该 pipeline。
apiVersion: tekton.dev/v1
kind: PipelineRun
metadata:
generateName: chains-demo-3-
spec:
pipelineRef:
name: chains-demo-3
taskRunTemplate:
serviceAccountName: <default>
workspaces:
- name: registryconfig
secret:
secretName: <registry-credentials>
- name: source
volumeClaimTemplate:
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 1Gi
storageClassName: <nfs>
YAML 字段说明
将其保存为名为 chains.demo-3.pipelinerun.yaml 的 yaml 文件并执行:
$ export NAMESPACE=<default>
# create the pipeline run resource in the namespace
$ kubectl create -n $NAMESPACE -f chains.demo-3.pipelinerun.yaml
等待 PipelineRun 完成。
$ kubectl get pipelinerun -n $NAMESPACE -w
chains-demo-3-<xxxxx> True Succeeded 2m 2m
步骤 6:等待 PipelineRun 完成签名
等待 PipelineRun 出现 chains.tekton.dev/signed: "true" 注解。
$ export NAMESPACE=<default>
$ export PIPELINERUN_NAME=<chains-demo-3-xxxxx>
$ kubectl get pipelinerun -n $NAMESPACE $PIPELINERUN_NAME -o yaml | grep "chains.tekton.dev/signed"
chains.tekton.dev/signed: "true"
一旦 PipelineRun 具有 chains.tekton.dev/signed: "true" 注解,就表示镜像已签名。
步骤 7:从 PipelineRun 中获取镜像
# Get the image URI
$ export IMAGE_URI=$(kubectl get pipelinerun -n $NAMESPACE $PIPELINERUN_NAME -o jsonpath='{.status.results[?(@.name=="first_image_ARTIFACT_OUTPUTS")].value.uri}')
# Get the image digest
$ export IMAGE_DIGEST=$(kubectl get pipelinerun -n $NAMESPACE $PIPELINERUN_NAME -o jsonpath='{.status.results[?(@.name=="first_image_ARTIFACT_OUTPUTS")].value.digest}')
# Combine the image URI and digest to form the full image reference
$ export IMAGE=$IMAGE_URI@$IMAGE_DIGEST
# Print the image reference
$ echo $IMAGE
<registry>/test/chains/demo-3:latest@sha256:93635f39cb31de5c6988cdf1f10435c41b3fb85570c930d51d41bbadc1a90046
该镜像将用于验证源代码仓库。
步骤 8:(可选)获取 SLSA Provenance 证明
TIP
如果你对 SLSA Provenance 证明内容感兴趣,可以继续阅读以下内容。
有关 SLSA Provenance 证明的更多详细信息,请参考 SLSA Provenance
根据 获取签名公钥 章节获取签名公钥。
# Disable tlog upload and enable private infrastructure
$ export COSIGN_TLOG_UPLOAD=false
$ export COSIGN_PRIVATE_INFRASTRUCTURE=true
$ export IMAGE=<<registry>/test/chains/demo-3:latest@sha256:db2607375049e8defa75a8317a53fd71fd3b448aec3c507de7179ded0d4b0f20>
$ cosign verify-attestation --key cosign.pub --type slsaprovenance $IMAGE | jq -r '.payload | @base64d' | jq -s
输出将类似如下内容,其中包含 SLSA Provenance 证明。
SLSA Provenance 证明
{
"_type": "https://in-toto.io/Statement/v0.1",
"subject": [
{
"name": "<registry>/test/chains/demo-3:latest",
"digest": {
"sha256": "db2607375049e8defa75a8317a53fd71fd3b448aec3c507de7179ded0d4b0f20"
}
}
],
"predicateType": "https://slsa.dev/provenance/v0.2",
"predicate": {
"buildConfig": {
"tasks": null
},
"buildType": "tekton.dev/v1beta1/PipelineRun",
"builder": {
"id": "https://alauda.io/builders/tekton/v1"
},
"invocation": {
"parameters": {
"image": "<registry>/test/chains/demo-3:latest"
}
},
"materials": [
{
"digest": {
"sha256": "bad5d84ded24307d12cacc9ef37fc38bce90ea5d00501f43b27d0c926be26f19"
},
"uri": "oci://<registry>/devops/tektoncd/hub/run-script"
},
{
"digest": {
"sha1": "cccccaaaa0000000000000000000000000000000"
},
"uri": "https://github.com/tektoncd/pipeline"
}
],
"metadata": {
"buildFinishedOn": "2025-06-06T10:28:21Z",
"buildStartedOn": "2025-06-06T10:27:34Z"
}
}
}
字段说明
predicateType:predicate 的类型。
predicate:
buildConfig:
buildType:构建类型,这里是 tekton.dev/v1beta1/PipelineRun。
builder:
id:builder 的 id,这里是 https://alauda.io/builders/tekton/v1。
invocation:
materials:构建所使用的材料。
uri:
oci://<registry>/devops/tektoncd/hub/run-script:所使用 task 的镜像。
https://github.com/tektoncd/pipeline:task 的源代码仓库。
metadata:构建元数据。
buildFinishedOn:构建完成时间。
buildStartedOn:构建开始时间。
步骤 9:使用 Kyverno 验证镜像源仓库限制
步骤 9.1:创建一个 Kyverno policy,仅允许部署由特定源代码仓库构建的镜像
policy 如下:
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: verify-code-repository-material
spec:
webhookConfiguration:
failurePolicy: Fail
timeoutSeconds: 30
background: false
rules:
- name: check-image
match:
any:
- resources:
kinds:
- Pod
namespaces:
- policy
verifyImages:
- imageReferences:
- "*"
# - "<registry>/test/*"
skipImageReferences:
- "ghcr.io/trusted/*"
failureAction: Enforce
verifyDigest: false
required: false
useCache: false
imageRegistryCredentials:
allowInsecureRegistry: true
secrets:
# The credential needs to exist in the namespace where kyverno is deployed
- registry-credentials
attestations:
- type: https://slsa.dev/provenance/v0.2
attestors:
- entries:
- keys:
publicKeys: |- # <- The public key of the signer
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEFZNGfYwn7+b4uSdEYLKjxWi3xtP3
UkR8hQvGrG25r0Ikoq0hI3/tr0m7ecvfM75TKh5jGAlLKSZUJpmCGaTToQ==
-----END PUBLIC KEY-----
ctlog:
ignoreSCT: true
rekor:
ignoreTlog: true
conditions:
- all:
- key: "{{ buildType }}"
operator: Equals
value: "tekton.dev/v1beta1/PipelineRun"
message: "The buildType must be equal to tekton.dev/v1beta1/PipelineRun, not {{ buildType }}"
- key: "{{ materials[?starts_with(uri, 'https://github.com/tektoncd/')] | length(@) }}"
operator: GreaterThan
value: 0
message: "The materials must have at least one entry starts with https://github.com/tektoncd/, {{ materials }}"
YAML 字段说明
- 该 policy 与 Image Signature Verification 中的 policy 基本一致
spec.rules[].verifyImages[].attestations[].conditions:用于验证的条件。
all:必须满足所有条件。
key: "{{ buildType }}":build type 必须等于 tekton.dev/v1beta1/PipelineRun。
key: "{{ materials[?starts_with(uri, 'https://github.com/tektoncd/')] | length(@) }}":materials 中必须至少有一项以 https://github.com/tektoncd/ 开头。
将其保存为名为 verify-code-repository-material.yaml 的 yaml 文件并执行:
$ kubectl create -f verify-code-repository-material.yaml
clusterpolicy.kyverno.io/verify-code-repository-material created
步骤 9.2:验证 policy
在定义该 policy 的 policy namespace 中,创建一个 Pod 以验证 policy。
使用构建好的镜像创建 Pod。
$ export NAMESPACE=<policy>
$ export IMAGE=<<registry>/test/chains/demo-3:latest@sha256:db2607375049e8defa75a8317a53fd71fd3b448aec3c507de7179ded0d4b0f20>
$ kubectl run -n $NAMESPACE built-from-specific-repo --image=${IMAGE} -- sleep 3600
pod/built-from-specific-repo created
Pod 将成功创建。
$ kubectl get pod -n $NAMESPACE built-from-specific-repo
NAME READY STATUS RESTARTS AGE
built-from-specific-repo 1/1 Running 0 10s
将 ClusterPolicy 中的代码仓库更改为另一个值 https://gitlab.com/,然后再次验证。
conditions:
- all:
- key: "{{ buildType }}"
operator: Equals
value: "tekton.dev/v1beta1/PipelineRun"
message: "The buildType must be equal to tekton.dev/v1beta1/PipelineRun, not {{ buildType }}"
- key: "{{ materials[?starts_with(uri, 'https://gitlab.com/')] | length(@) }}"
operator: GreaterThan
value: 0
message: "The materials must have at least one entry starts with https://gitlab.com/, {{ materials }}"
$ kubectl run -n $NAMESPACE unbuilt-from-specific-repo --image=${IMAGE} -- sleep 3600
如果收到如下输出,则表示 Pod 已被 policy 阻止。
Error from server: admission webhook "mutate.kyverno.svc-fail" denied the request:
resource Pod/policy/unbuilt-from-specific-repo was blocked due to the following policies
verify-code-repository-material:
check-image: 'image attestations verification failed, verifiedCount: 0, requiredCount:
1, error: .attestations[0].attestors[0].entries[0].keys: attestation checks failed
for <registry>/test/chains/demo-3:latest and predicate https://slsa.dev/provenance/v0.2:
The materials must have at least one entry starts with https://gitlab.com/,
[{"digest":{"sha256":"bad5d84ded24307d12cacc9ef37fc38bce90ea5d00501f43b27d0c926be26f19"},"uri":"oci://<registry>/devops/tektoncd/hub/run-script"},{"digest":{"sha256":"7a63e6c2d1b4c118e9a974e7850dd3e9321e07feec8302bcbcd16653c512ac59"},"uri":"http://tekton-hub-api.tekton-pipelines:8000/v1/resource/catalog/task/run-script/0.1/yaml"},{"digest":{"sha256":"8d5ea9ecd9b531e798fecd87ca3b64ee1c95e4f2621d09e893c58ed593bfd4c4"},"uri":"oci://<registry>/devops/tektoncd/hub/buildah"},{"digest":{"sha256":"3225653d04c223be85d173747372290058a738427768c5668ddc784bf24de976"},"uri":"http://tekton-hub-api.tekton-pipelines:8000/v1/resource/catalog/task/buildah/0.9/yaml"},{"digest":{"sha1":"cccccaaaa0000000000000000000000000000000"},"uri":"https://github.com/tektoncd/pipeline"}]'
步骤 10:清理资源
删除前面步骤中创建的 Pod。
$ export NAMESPACE=<policy>
$ kubectl delete pod -n $NAMESPACE built-from-specific-repo
删除 policy。
$ kubectl delete clusterpolicy verify-code-repository-material
预期结果
完成本指南后:
- 你将拥有一个可工作的环境,使用 Tekton Chains 进行 SLSA Provenance 生成,并使用 Kyverno 进行源代码仓库验证
- 你的容器镜像会在其 SLSA Provenance 中自动包含源代码仓库信息
- 只有由允许的源代码仓库构建的镜像才能在指定 namespace 中部署
- 由未授权源代码仓库构建的镜像会被 Kyverno policy 自动阻止
- 你已经通过验证容器镜像的源代码来源,实现了基础的供应链安全控制
本指南为在 CI/CD pipeline 中实现供应链安全提供了基础。在生产环境中,你还应:
- 配置正确的 namespace 隔离和访问控制
- 为签名密钥实现安全的密钥管理
- 为 policy 违规设置监控和告警
- 定期轮换签名密钥并更新安全 policy
- 考虑实现额外的安全控制,例如漏洞扫描
参考资料