Trivy 集成 CI/CD 容器安全扫描
scanning-containers-with-trivy-in-cicd
将 Aqua Security 的 Trivy 扫描器集成到 CI/CD 流水线中,检测操作系统包和应用程序依赖的 CVE、Dockerfile 配置错误以及文件系统或 git 仓库中的问题,并强制实施基于严重性的质量门控,阻止存在漏洞的镜像被部署。在 CI/CD 中构建 Docker 镜像、需要在推送到镜像仓库或生产部署前进行自动化漏洞扫描和通过/失败门控时使用。
- License 许可
- Apache-2.0
- 最近更新
- 2026-08-31
- Stars
- ★ 3.6w
- Forks
- 4.4k
01 前言 Front Matter
- name
- scanning-containers-with-trivy-in-cicd
- tags
- [ "devsecops", "cicd", "trivy", "container-security", "vulnerability-scanning", "secure-sdlc" ]
- author
- mahipal
- domain
- cybersecurity
- license
- Apache-2.0
- version
- 1.0.0
- nist_csf
- [ "PR.PS-01", "GV.SC-07", "ID.IM-04", "PR.PS-04" ]
- subdomain
- devsecops
- description
- Integrates Aqua Security's Trivy scanner into CI/CD pipelines to detect OS package and application dependency CVEs, Dockerfile misconfigurations, and issues in filesystems or git repositories, and to enforce severity-based quality gates that block vulnerable images from being deployed. Use when building Docker images in CI/CD and needing automated vulnerability scanning and pass/fail gates before registry push or production deployment.
- mitre_attack
- [ "T1195", "T1554", "T1059.004", "T1610", "T1611" ]
02 资源文件 8
- 资产文件assets/template.md4.8 KB
- 许可证LICENSE11.0 KB
- 参考文档references/api-reference.md1.9 KB
- 参考文档references/standards.md2.7 KB
- 参考文档references/workflows.md4.2 KB
- 脚本scripts/agent.py6.1 KB
- 脚本scripts/process.py11.7 KB
- 参考文档test-cases.json8.5 KB
03 SKILL.md 正文
Scanning Containers with Trivy in CI/CD
When to Use
- When building Docker container images in CI/CD and needing automated vulnerability scanning before registry push
- When establishing quality gates that prevent images with critical or high CVEs from reaching production
- When compliance requirements mandate vulnerability scanning of all container images before deployment
- When scanning IaC files (Dockerfiles, Kubernetes manifests) alongside container image scanning
- When needing a single tool to scan OS packages, language-specific dependencies, and misconfigurations
Do not use for runtime container security monitoring (use Falco), for scanning running containers in production (use runtime agents), or when only scanning application source code without containerization (use SAST tools).
Prerequisites
- Trivy CLI installed (v0.50+) or access to aquasecurity/trivy-action GitHub Action
- Docker daemon available in CI/CD for building and scanning images
- Container registry credentials for pulling base images and pushing scanned images
- Trivy vulnerability database accessible (downloaded automatically or cached)
Workflow
Step 1: Configure Trivy Scanning in GitHub Actions
Set up a GitHub Actions workflow that builds a Docker image and scans it with Trivy before pushing to a container registry.
# .github/workflows/container-security.yml
name: Container Security Scan
on:
push:
branches: [main]
pull_request:
branches: [main]
paths:
- 'Dockerfile'
- 'docker-compose*.yml'
- 'src/**'
- 'requirements*.txt'
- 'package*.json'
jobs:
build-and-scan:
runs-on: ubuntu-latest
permissions:
security-events: write
contents: read
steps:
- uses: actions/checkout@v4
- name: Build Docker image
run: docker build -t app:${{ github.sha }} .
- name: Run Trivy vulnerability scanner
uses: aquasecurity/trivy-action@0.28.0
with:
image-ref: 'app:${{ github.sha }}'
format: 'sarif'
output: 'trivy-results.sarif'
severity: 'CRITICAL,HIGH'
exit-code: '1'
ignore-unfixed: true
- name: Upload Trivy scan results
uses: github/codeql-action/upload-sarif@v3
if: always()
with:
sarif_file: 'trivy-results.sarif'
category: 'trivy-container'
- name: Run Trivy misconfiguration scanner
uses: aquasecurity/trivy-action@0.28.0
with:
scan-type: 'config'
scan-ref: '.'
format: 'table'
exit-code: '1'
severity: 'CRITICAL,HIGH'
Step 2: Scan Dockerfiles for Misconfigurations
Trivy detects common Dockerfile security issues such as running as root, using latest tags, and exposing unnecessary ports.
# Scan Dockerfile for misconfigurations
trivy config --severity HIGH,CRITICAL ./Dockerfile
# Scan with custom policy directory
trivy config --policy ./security-policies --severity MEDIUM,HIGH,CRITICAL .
# Example secure Dockerfile practices Trivy checks for:
# - USER instruction present (not running as root)
# - HEALTHCHECK instruction defined
# - Base image uses specific tag, not :latest
# - No secrets in ENV or ARG instructions
# - COPY preferred over ADD
Step 3: Integrate with GitLab CI/CD
# .gitlab-ci.yml
stages:
- build
- scan
- push
variables:
TRIVY_CACHE_DIR: .trivycache/
build:
stage: build
script:
- docker build -t $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA .
- docker save $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA -o image.tar
artifacts:
paths:
- image.tar
trivy-scan:
stage: scan
image:
name: aquasec/trivy:latest
entrypoint: [""]
cache:
paths:
- .trivycache/
script:
- trivy image
--input image.tar
--exit-code 1
--severity CRITICAL,HIGH
--ignore-unfixed
--format json
--output trivy-report.json
- trivy image
--input image.tar
--severity CRITICAL,HIGH,MEDIUM
--format table
artifacts:
reports:
container_scanning: trivy-report.json
paths:
- trivy-report.json
allow_failure: false
push:
stage: push
needs: [trivy-scan]
script:
- docker load -i image.tar
- docker push $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA
Step 4: Configure Trivy Ignore and Exception Handling
Manage false positives and accepted risks through Trivy's ignore file and VEX statements.
# .trivyignore.yaml
vulnerabilities:
- id: CVE-2023-44487 # HTTP/2 rapid reset - mitigated at load balancer
statement: "Mitigated by WAF rate limiting at ingress layer"
expires: 2026-06-01
- id: CVE-2024-21626 # runc container escape - patched in base image update
statement: "Tracked in JIRA-SEC-1234, base image update scheduled"
expires: 2026-03-15
misconfigurations:
- id: DS002 # User not set - required for init containers
paths:
- "docker/init-container/Dockerfile"
statement: "Init container requires root for volume permission setup"
Step 5: Implement Database Caching and Offline Scanning
Cache the Trivy vulnerability database in CI/CD to reduce scan times and enable air-gapped environments.
# GitHub Actions with database caching
- name: Cache Trivy DB
uses: actions/cache@v4
with:
path: /tmp/trivy-db
key: trivy-db-${{ hashFiles('.github/workflows/container-security.yml') }}
restore-keys: trivy-db-
- name: Run Trivy with cached DB
uses: aquasecurity/trivy-action@0.28.0
with:
image-ref: 'app:${{ github.sha }}'
cache-dir: /tmp/trivy-db
format: 'json'
output: 'trivy-results.json'
severity: 'CRITICAL,HIGH'
exit-code: '1'
# Air-gapped: Download DB manually and mount
trivy image --download-db-only --cache-dir /path/to/cache
# Transfer cache to air-gapped system
trivy image --skip-db-update --cache-dir /path/to/cache myimage:tag
Step 6: Generate SBOM and Scan for License Compliance
Use Trivy to generate Software Bill of Materials alongside vulnerability scanning.
# Generate SBOM in CycloneDX format
trivy image --format cyclonedx --output sbom.cdx.json app:latest
# Generate SBOM in SPDX format
trivy image --format spdx-json --output sbom.spdx.json app:latest
# Scan SBOM for vulnerabilities (decouple generation from scanning)
trivy sbom sbom.cdx.json --severity CRITICAL,HIGH
# Scan with license detection
trivy image --scanners vuln,license --severity HIGH,CRITICAL app:latest
Key Concepts
| Term | Definition |
|---|---|
| CVE | Common Vulnerabilities and Exposures — standardized identifiers for publicly known security vulnerabilities |
| Vulnerability DB | Trivy's regularly updated database aggregating CVE data from NVD, vendor advisories, and language-specific sources |
| Misconfiguration | Security-relevant configuration issue in Dockerfiles, Kubernetes manifests, or IaC templates |
| SBOM | Software Bill of Materials — complete inventory of all components and dependencies in a container image |
| Ignore Unfixed | Flag to skip CVEs without available patches, reducing noise from vulnerabilities with no actionable fix |
| VEX | Vulnerability Exploitability eXchange — machine-readable statements about whether a vulnerability is exploitable in context |
| Exit Code | Non-zero return code from Trivy when findings exceed the severity threshold, used to fail CI/CD pipelines |
Tools & Systems
- Trivy: Open-source vulnerability scanner by Aqua Security supporting images, filesystems, repos, and IaC
- trivy-action: Official GitHub Action for running Trivy scans in GitHub Actions workflows
- Trivy Operator: Kubernetes operator that continuously scans cluster workloads with Trivy
- Grype: Alternative image scanner by Anchore for comparison and validation of scan results
- Harbor: Container registry with built-in Trivy integration for automatic image scanning on push
Common Scenarios
Scenario: Multi-Stage Build with Separate Scan and Push
Context: A team builds multi-stage Docker images and needs to scan the final production image before pushing to ECR, while also scanning the build stage for supply chain risks.
Approach:
- Build the Docker image with
--target productionfor the final stage - Run Trivy with
--severity CRITICAL,HIGH --exit-code 1 --ignore-unfixedto block on exploitable issues - Generate an SBOM in CycloneDX format and store as a build artifact
- Upload SARIF results to GitHub Security tab for visibility
- Only push to ECR if the Trivy scan exits with code 0
- Tag the pushed image with the scan timestamp and Trivy DB version for audit traceability
Pitfalls: Scanning only the final stage misses vulnerable packages that were present in build stages and may have influenced the build. Run trivy fs on the build context separately. Caching the Trivy DB too aggressively (weekly) means newly published CVEs take days to appear in scans.
Output Format
Trivy Container Scan Report
=============================
Image: app:a1b2c3d4
Base Image: python:3.12-slim-bookworm
Scan Date: 2026-02-23
DB Version: 2026-02-23T00:15:00Z
VULNERABILITY SUMMARY:
Total: 47
Critical: 2
High: 5
Medium: 18
Low: 22
Unfixed: 8 (excluded from gate)
CRITICAL FINDINGS:
CVE-2025-12345 libssl3 3.0.11-1 3.0.13-1 OpenSSL buffer overflow
CVE-2025-67890 curl 7.88.1-10 7.88.1-12 curl HSTS bypass
HIGH FINDINGS:
CVE-2025-11111 zlib1g 1.2.13 1.2.13.1 zlib heap buffer overflow
CVE-2025-22222 python3.12 3.12.1 3.12.3 CPython path traversal
CVE-2025-33333 requests 2.31.0 2.32.0 requests SSRF in redirects
MISCONFIGURATION:
DS002 [HIGH] Dockerfile: USER instruction not set (running as root)
DS026 [MEDIUM] Dockerfile: No HEALTHCHECK defined
QUALITY GATE: FAILED (2 Critical, 5 High findings)
04 同仓库更多 Skills
SLSA 构建来源验证
verifying-build-provenance-with-slsa-sigstore
使用 Sigstore 的 cosign(verify、verify-attestation、verify-blob-attestation)和 slsa-verifier(verify-artifact)验证工件签名和 SLSA 来源(provenance),强制校验 keyless OIDC 构建者身份和源仓库是否符合 SLSA Build 级别。适用于 CI/CD 中部署工件前、消费第三方证明时、建立 SLSA Build L3 管道,或在事件响应或准入控制期间确认来源的场景。
TPM 测量启动验证
validating-tpm-measured-boot-attestation
使用 tpm2-tools 验证 TPM 2.0 测量启动(measured boot)的完整性和远程证明:读取 PCR(tpm2_pcrread)、重放启动事件日志、生成并检查签名报价(tpm2_quote/tpm2_checkquote),以及将机密封印(seal)到 PCR 策略。适用于确认系统已启动可信固件/内核以实现零信任(Zero Trust)设备状态、通过 PCR 漂移检测启动链篡改,或构建黄金值基线用于机群(fleet)证明。
备份完整性验证
validating-backup-integrity-for-recovery
通过加密哈希验证、自动化恢复测试、损坏检测和可恢复性检查来验证备份完整性,确认备份对于灾难恢复和勒索软件响应是可靠的。适用于在依赖备份进行恢复之前、构建备份后验证管道、审计备份基础设施以满足合规要求,或检查不可变/air-gapped(气隙)备份是否存在静默损坏或篡改的场景。
KAPE Windows 取证收集
triaging-windows-with-kape
运行 KAPE(Kroll Artifact Parser and Extractor),通过 Targets 收集目标取证工件(注册表配置单元、$MFT、事件日志、prefetch、浏览器数据),并使用封装 Eric Zimmerman 的 EZ Tools(PECmd、MFTECmd、RECmd)的 Modules 进行解析。适用于事件遏制/分诊早期阶段——此时完整磁盘镜像不切实际,但需要快速获得可采信、可解析的 Windows 工件集,包括大规模远程收集。
SSVC 漏洞优先级分诊
triaging-vulnerabilities-with-ssvc-framework
使用 CISA 的 Stakeholder-Specific Vulnerability Categorization(SSVC,利益相关方特定漏洞分类)决策树对漏洞进行分诊和优先级排序,权衡利用状态(通过 CISA KEV 目录和 FIRST EPSS API)、技术影响、自动化程度和任务普遍性,输出 Track/Track*/Attend/Act 决策。适用于对漏洞扫描结果(OpenVAS、Nessus、Qualys)进行优先级排序以制定修复计划,而不局限于原始 CVSS 分数的场景。
安全事件初步分诊
triaging-security-incident
使用 NIST SP 800-61r3 和 SANS PICERL 框架对安全事件进行初步分诊,分类事件类型、按业务影响分配优先级,并路由到相应的响应团队。适用于 SIEM/EDR 告警需要人工分类、并发告警必须确定优先级,或用户报告或威胁情报 IOC 匹配需要初步事件分类的场景。