搬瓦工 VPS Cosign 容器签名验证教程
Cosign 是 Sigstore 项目的核心组件,专门用于容器镜像的数字签名和验证。通过对容器镜像进行签名,可以确保镜像在传输和部署过程中未被篡改,是容器供应链安全的关键环节。Cosign 支持传统的密钥对签名和创新的 Keyless 签名模式(基于 OIDC 身份的短期证书),极大地简化了签名密钥的管理工作。
一、安装 Cosign
# 下载安装
wget https://github.com/sigstore/cosign/releases/latest/download/cosign-linux-amd64
mv cosign-linux-amd64 /usr/local/bin/cosign
chmod +x /usr/local/bin/cosign
# 验证安装
cosign version
二、密钥对签名
2.1 生成密钥对
# 生成签名密钥对
cosign generate-key-pair
# 生成 cosign.key(私钥)和 cosign.pub(公钥)
2.2 签名容器镜像
# 先将镜像推送到注册表
docker push registry.example.com/myapp:v1.0
# 使用私钥签名
cosign sign --key cosign.key registry.example.com/myapp:v1.0
2.3 验证签名
# 使用公钥验证
cosign verify --key cosign.pub registry.example.com/myapp:v1.0
# 在部署前验证(CI/CD 中使用)
cosign verify --key cosign.pub registry.example.com/myapp:v1.0 || exit 1
三、Keyless 签名
Keyless 模式无需管理长期密钥,通过 OIDC 身份(如 GitHub、Google 账户)获取短期签名证书:
# Keyless 签名(会打开浏览器进行身份验证)
cosign sign registry.example.com/myapp:v1.0
# 在 CI/CD 中使用 Keyless 签名(无需浏览器)
COSIGN_EXPERIMENTAL=1 cosign sign registry.example.com/myapp:v1.0
# 验证 Keyless 签名
cosign verify \
--certificate-identity user@example.com \
--certificate-oidc-issuer https://accounts.google.com \
registry.example.com/myapp:v1.0
四、附加签名元数据
# 签名时附加注释
cosign sign --key cosign.key \
-a "build_id=12345" \
-a "git_commit=abc123" \
-a "pipeline=production" \
registry.example.com/myapp:v1.0
# 附加 SBOM 到签名
cosign attach sbom --sbom sbom.spdx registry.example.com/myapp:v1.0
# 附加漏洞扫描结果
cosign attest --key cosign.key \
--predicate scan-results.json \
--type vuln \
registry.example.com/myapp:v1.0
五、CI/CD 集成示例
cat > /opt/build-sign-push.sh <<'EOF'
#!/bin/bash
IMAGE="registry.example.com/myapp"
TAG="v$(date +%Y%m%d%H%M%S)"
# 构建镜像
docker build -t $IMAGE:$TAG .
# 安全扫描
trivy image --exit-code 1 --severity CRITICAL $IMAGE:$TAG
if [ $? -ne 0 ]; then
echo "Critical vulnerabilities found, aborting"
exit 1
fi
# 推送镜像
docker push $IMAGE:$TAG
# 签名镜像
cosign sign --key /opt/keys/cosign.key $IMAGE:$TAG
echo "Image $IMAGE:$TAG built, scanned, pushed and signed"
EOF
chmod +x /opt/build-sign-push.sh
六、部署前验证
cat > /opt/verified-deploy.sh <<'EOF'
#!/bin/bash
IMAGE=$1
# 验证签名
cosign verify --key /opt/keys/cosign.pub $IMAGE
if [ $? -ne 0 ]; then
echo "Signature verification failed! Refusing to deploy."
exit 1
fi
echo "Signature verified. Deploying $IMAGE..."
docker pull $IMAGE
docker compose up -d
EOF
chmod +x /opt/verified-deploy.sh
七、密钥安全管理
- 将签名私钥存储在 HashiCorp Vault 中,而非文件系统。
- 生产环境优先使用 Keyless 签名,避免私钥泄露风险。
- 定期轮转签名密钥。
- 在 CI/CD 中使用环境变量传递密钥密码,不在脚本中硬编码。
总结
Cosign 是容器供应链安全的最后一道防线,确保部署到搬瓦工 VPS 上的每个容器镜像都经过验证。配合 Trivy 和 Grype 的漏洞扫描,可以实现从构建到部署的全链路安全保障。选购搬瓦工 VPS 请参考 全部方案,购买时使用优惠码 NODESEEK2026 可享受 6.77% 的折扣,通过 bwh81.net 进入官网购买。