
Scanning Docker Images With Trivy
- 148 installs
- 27.3k repo stars
- Updated August 2, 2026
- mukul975/anthropic-cybersecurity-skills
Helps with devops & ci/cd tasks.
About
scanning-docker-images-with-trivy is a Claude Code skill for devops & ci/cd. It helps solo builders move faster with AI-assisted coding.
- scanning-docker-images-with-trivy
- DevOps & CI/CD
- AI-coding skill
Scanning Docker Images With Trivy by the numbers
- 148 all-time installs (skills.sh)
- +10 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #459 of 1,435 DevOps & CI/CD skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/mukul975/anthropic-cybersecurity-skills --skill scanning-docker-images-with-trivyAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 148 |
|---|---|
| repo stars | ★ 27.3k |
| Last updated | August 2, 2026 |
| Repository | mukul975/anthropic-cybersecurity-skills ↗ |
What it does
Helps with devops & ci/cd tasks.
Files
Scanning Docker Images with Trivy
Overview
Trivy is a comprehensive open-source vulnerability scanner by Aqua Security that detects vulnerabilities in OS packages, language-specific dependencies, misconfigurations, secrets, and license violations within container images. It integrates into CI/CD pipelines and supports multiple output formats including SARIF, CycloneDX, and SPDX.
When to Use
- When conducting security assessments that involve scanning docker images with trivy
- When following incident response procedures for related security events
- When performing scheduled security testing or auditing activities
- When validating security controls through hands-on testing
Prerequisites
- Docker Engine 20.10+
- Trivy v0.50+ installed
- Internet access for vulnerability database updates
- Container registry credentials (for private registries)
Core Concepts
Scanner Types
| Scanner | Flag | Detects |
|---|---|---|
| Vulnerability | --scanners vuln | CVEs in OS packages and libraries |
| Misconfiguration | --scanners misconfig | Dockerfile/K8s manifest misconfigs |
| Secret | --scanners secret | Hardcoded passwords, API keys, tokens |
| License | --scanners license | Software license compliance issues |
Severity Levels
- CRITICAL: CVSS 9.0-10.0 - Immediate action required
- HIGH: CVSS 7.0-8.9 - Fix before production deployment
- MEDIUM: CVSS 4.0-6.9 - Plan remediation
- LOW: CVSS 0.1-3.9 - Accept or fix opportunistically
- UNKNOWN: Unscored - Evaluate manually
Vulnerability Database
Trivy uses multiple vulnerability databases:
- NVD (National Vulnerability Database)
- Red Hat Security Data
- Alpine SecDB
- Debian Security Tracker
- Ubuntu CVE Tracker
- Amazon Linux Security Center
- GitHub Advisory Database
Workflow
Step 1: Install Trivy
# Linux (apt)
sudo apt-get install wget apt-transport-https gnupg lsb-release
wget -qO - https://aquasecurity.github.io/trivy-repo/deb/public.key | gpg --dearmor | sudo tee /usr/share/keyrings/trivy.gpg > /dev/null
echo "deb [signed-by=/usr/share/keyrings/trivy.gpg] https://aquasecurity.github.io/trivy-repo/deb $(lsb_release -sc) main" | sudo tee -a /etc/apt/sources.list.d/trivy.list
sudo apt-get update && sudo apt-get install trivy
# macOS
brew install trivy
# Docker
docker pull aquasecurity/trivy:latestStep 2: Basic Image Scanning
# Scan a public image
trivy image python:3.12-slim
# Scan with severity filter
trivy image --severity CRITICAL,HIGH nginx:latest
# Ignore unfixed vulnerabilities
trivy image --ignore-unfixed alpine:3.19
# Scan local image
docker build -t myapp:latest .
trivy image myapp:latest
# Scan from tar archive
docker save myapp:latest -o myapp.tar
trivy image --input myapp.tarStep 3: Advanced Scanning Options
# All scanners (vuln + misconfig + secret + license)
trivy image --scanners vuln,misconfig,secret,license myapp:latest
# Generate SBOM in CycloneDX format
trivy image --format cyclonedx --output sbom.cdx.json myapp:latest
# Generate SBOM in SPDX format
trivy image --format spdx-json --output sbom.spdx.json myapp:latest
# JSON output for programmatic processing
trivy image --format json --output results.json myapp:latest
# SARIF output for GitHub Security tab
trivy image --format sarif --output results.sarif myapp:latest
# Template-based output
trivy image --format template --template "@contrib/html.tpl" --output report.html myapp:latest
# Scan specific layers only
trivy image --list-all-pkgs myapp:latestStep 4: Scanning Kubernetes Manifests
# Scan Dockerfile for misconfigurations
trivy config Dockerfile
# Scan Kubernetes manifests
trivy config k8s-deployment.yaml
# Scan Helm charts
trivy config ./helm-chart/
# Scan Terraform files
trivy config ./terraform/Step 5: CI/CD Integration
# GitHub Actions
name: Trivy Container Scan
on: push
jobs:
scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Build image
run: docker build -t myapp:${{ github.sha }} .
- name: Run Trivy vulnerability scanner
uses: aquasecurity/trivy-action@master
with:
image-ref: myapp:${{ github.sha }}
format: sarif
output: trivy-results.sarif
severity: CRITICAL,HIGH
exit-code: 1
- name: Upload Trivy scan results
uses: github/codeql-action/upload-sarif@v3
if: always()
with:
sarif_file: trivy-results.sarif
- name: Generate SBOM
uses: aquasecurity/trivy-action@master
with:
image-ref: myapp:${{ github.sha }}
format: cyclonedx
output: sbom.cdx.json# GitLab CI
trivy-scan:
stage: security
image:
name: aquasecurity/trivy:latest
entrypoint: [""]
script:
- trivy image --exit-code 1 --severity CRITICAL,HIGH
--format json --output gl-container-scanning-report.json
$CI_REGISTRY_IMAGE:$CI_COMMIT_SHA
artifacts:
reports:
container_scanning: gl-container-scanning-report.jsonStep 6: Policy Enforcement with .trivyignore
# .trivyignore - Ignore specific CVEs with expiry
# Accepted risk: low-impact vulnerability in dev dependency
CVE-2023-12345 exp:2025-06-01
# False positive: not exploitable in our configuration
CVE-2024-67890
# Vendor will not fix
CVE-2023-11111Step 7: Scan Private Registry Images
# Docker Hub (uses ~/.docker/config.json)
trivy image myregistry.azurecr.io/myapp:latest
# ECR
aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin <account>.dkr.ecr.us-east-1.amazonaws.com
trivy image <account>.dkr.ecr.us-east-1.amazonaws.com/myapp:latest
# GCR
trivy image gcr.io/my-project/myapp:latest
# With explicit credentials
TRIVY_USERNAME=user TRIVY_PASSWORD=pass trivy image registry.example.com/myapp:latestValidation Commands
# Verify Trivy installation
trivy version
# Update vulnerability database
trivy image --download-db-only
# Quick scan with table output
trivy image --severity CRITICAL python:3.12
# Verify no CRITICAL vulnerabilities
trivy image --exit-code 1 --severity CRITICAL myapp:latest
echo "Exit code: $?" # 0 = no vulns, 1 = vulns foundReferences
Trivy Image Scan Report Template
Scan Information
| Field | Value |
|---|---|
| Image | |
| Tag/Digest | |
| Scan Date | |
| Trivy Version | |
| DB Version | |
| Scanners Used | vuln / misconfig / secret / license |
Vulnerability Summary
| Severity | Count | Threshold | Status |
|---|---|---|---|
| CRITICAL | 0 | PASS/FAIL | |
| HIGH | 5 | PASS/FAIL | |
| MEDIUM | 20 | PASS/FAIL | |
| LOW | N/A | INFO | |
| UNKNOWN | N/A | INFO |
Critical Findings
| CVE ID | Package | Installed | Fixed | CVSS | Description |
|---|---|---|---|---|---|
High Findings
| CVE ID | Package | Installed | Fixed | CVSS | Description |
|---|---|---|---|---|---|
Secrets Detected
| Rule ID | Category | Severity | File | Match (redacted) |
|---|---|---|---|---|
Misconfigurations
| ID | Type | Severity | Title | Resolution |
|---|---|---|---|---|
SBOM Summary
| Package Type | Count |
|---|---|
| OS packages | |
| Python packages | |
| Node.js packages | |
| Go modules | |
| Java libraries |
Policy Decision
- [ ] APPROVED for deployment
- [ ] BLOCKED - requires remediation
- [ ] EXCEPTION GRANTED (see risk acceptance below)
Risk Acceptance (if applicable)
| CVE ID | Justification | Expiry Date | Approved By |
|---|---|---|---|
Remediation Actions
| Priority | CVE/Finding | Action | Owner | ETA |
|---|---|---|---|---|
| P1 | ||||
| P2 |
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to the Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by the Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding any notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. Please do not remove or change
the license header comment from a contributed file except when
necessary.
Copyright 2026 mukul975
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
API Reference: Scanning Docker Images with Trivy
Trivy Scanner Types
| Scanner | Flag | Detects |
|---|---|---|
| Vulnerability | --scanners vuln | CVEs in OS packages and libraries |
| Misconfiguration | --scanners misconfig | Dockerfile/K8s misconfigs |
| Secret | --scanners secret | Hardcoded passwords, API keys |
| License | --scanners license | License compliance issues |
Core Commands
| Command | Description |
|---|---|
trivy image <ref> | Scan Docker image |
trivy image --input <tar> | Scan saved tar archive |
trivy image --format json | JSON output |
trivy image --format sarif | SARIF for GitHub Security |
trivy image --format cyclonedx | CycloneDX SBOM |
trivy image --format spdx-json | SPDX SBOM |
trivy image --exit-code 1 --severity CRITICAL | Fail on critical |
trivy image --list-all-pkgs | List all detected packages |
Vulnerability Database Sources
| Source | Coverage |
|---|---|
| NVD | All ecosystems |
| GitHub Advisory Database | Open source packages |
| Alpine SecDB | Alpine Linux |
| Debian Security Tracker | Debian packages |
| Red Hat Security Data | RHEL/CentOS |
| Ubuntu CVE Tracker | Ubuntu packages |
Python Libraries
| Library | Version | Purpose |
|---|---|---|
subprocess | stdlib | Execute trivy CLI |
json | stdlib | Parse scan results |
pathlib | stdlib | File path handling |
References
- Trivy Documentation: https://trivy.dev/docs/
- Trivy GitHub: https://github.com/aquasecurity/trivy
- Aqua Security: https://www.aquasec.com/products/trivy/
Standards Reference - Docker Image Scanning with Trivy
NIST SP 800-190 - Application Container Security Guide
Relevant Controls
- Image Vulnerability Management: Organizations should maintain a pipeline for scanning and remediating container image vulnerabilities
- Image Provenance: Use content trust and signing to verify image source and integrity
- SBOM Generation: Produce Software Bill of Materials for all container images
CIS Docker Benchmark v1.8.0
Section 4: Container Images and Build File
- 4.4: Ensure images are scanned and rebuilt to include security patches
- 4.5: Ensure Content trust for Docker is Enabled
- 4.8: Ensure setuid and setgid permissions are removed
NIST SSDF (Secure Software Development Framework)
PW.4 - Reuse Existing, Well-Secured Software
- PW.4.1: Verify third-party software components have no known vulnerabilities
- PW.4.4: Verify software components are obtained from trusted sources
RV.1 - Identify and Confirm Vulnerabilities
- RV.1.1: Gather information from vulnerability notifications
- RV.1.2: Review, analyze, and/or test code to identify vulnerabilities
OWASP Container Security Verification Standard
V2: Image Security
- 2.1: Verify images are scanned for known vulnerabilities before deployment
- 2.2: Verify base images are from trusted sources
- 2.3: Verify images do not contain embedded secrets
- 2.4: Verify unnecessary packages are removed from images
- 2.5: Verify images use minimal base (distroless/Alpine)
Executive Order 14028 - Improving the Nation's Cybersecurity
SBOM Requirements
- Software producers must provide SBOMs for federal software
- SBOMs must follow NTIA minimum elements
- Supported formats: SPDX, CycloneDX
- Trivy supports both SPDX and CycloneDX SBOM generation
Trivy Vulnerability Scoring
CVSS v3.1 Severity Mapping
| Score Range | Severity | Trivy Flag |
|---|---|---|
| 9.0 - 10.0 | CRITICAL | --severity CRITICAL |
| 7.0 - 8.9 | HIGH | --severity HIGH |
| 4.0 - 6.9 | MEDIUM | --severity MEDIUM |
| 0.1 - 3.9 | LOW | --severity LOW |
| N/A | UNKNOWN | --severity UNKNOWN |
Vulnerability Data Sources
| Source | Coverage |
|---|---|
| NVD | All CVEs |
| GHSA | GitHub ecosystem packages |
| Red Hat OVAL | RHEL, CentOS |
| Debian Security Tracker | Debian |
| Ubuntu CVE Tracker | Ubuntu |
| Alpine SecDB | Alpine Linux |
| Amazon ALAS | Amazon Linux |
| SUSE OVAL | SUSE/openSUSE |
| Wolfi SecDB | Wolfi/Chainguard |
Workflows - Docker Image Scanning with Trivy
Workflow 1: Developer Local Scan
[Developer builds image] --> [trivy image myapp:latest]
| |
v v
Fix Dockerfile Review findings
Update deps |
| +------+------+
| | |
v v v
Rebuild image CRITICAL/HIGH MEDIUM/LOW
| found? found?
| | |
v v v
Re-scan Fix immediately Add to backlog
before commit or .trivyignoreWorkflow 2: CI/CD Gate Scan
# Pipeline stages
Build --> Scan --> Gate Decision --> Deploy/Block
# Gate policy
CRITICAL: Block deployment, fail pipeline (exit-code 1)
HIGH: Block deployment to production
MEDIUM: Warn, allow deployment to staging
LOW: Informational onlyWorkflow 3: Registry Continuous Scanning
[Images in Registry]
|
v
[Scheduled Trivy Scan (daily/weekly)]
|
+--> [New CVE detected in existing image]
| |
| v
| [Create JIRA/GitHub issue]
| |
| v
| [Rebuild and push patched image]
|
+--> [No new CVEs]
|
v
[Log clean scan result]Workflow 4: Full SBOM + Vulnerability Pipeline
#!/bin/bash
IMAGE="myapp:v1.0.0"
# Step 1: Generate SBOM
trivy image --format cyclonedx --output sbom.cdx.json "$IMAGE"
# Step 2: Vulnerability scan
trivy image --format json --output vuln-report.json "$IMAGE"
# Step 3: License scan
trivy image --scanners license --format json --output license-report.json "$IMAGE"
# Step 4: Secret scan
trivy image --scanners secret --format json --output secret-report.json "$IMAGE"
# Step 5: Config scan (if Dockerfile available)
trivy config --format json --output config-report.json Dockerfile
# Step 6: Generate HTML report
trivy image --format template \
--template "@contrib/html.tpl" \
--output report.html "$IMAGE"
# Step 7: Upload to dependency tracking (e.g., Dependency-Track)
curl -X POST "https://dtrack.example.com/api/v1/bom" \
-H "X-Api-Key: $DTRACK_API_KEY" \
-F "project=$PROJECT_UUID" \
-F "bom=@sbom.cdx.json"Workflow 5: Multi-Image Fleet Scanning
#!/bin/bash
# Scan all images in a Kubernetes cluster
# Get unique images
IMAGES=$(kubectl get pods --all-namespaces -o jsonpath='{range .items[*]}{range .spec.containers[*]}{.image}{"\n"}{end}{end}' | sort -u)
echo "Scanning $(echo "$IMAGES" | wc -l) unique images..."
for IMAGE in $IMAGES; do
echo "=== Scanning: $IMAGE ==="
trivy image --severity CRITICAL,HIGH --exit-code 0 \
--format json --output "scan_$(echo $IMAGE | tr '/:' '_').json" \
"$IMAGE" 2>/dev/null
done
# Aggregate results
echo "Generating aggregate report..."
python3 aggregate_trivy_results.py scan_*.json > fleet_report.jsonWorkflow 6: Trivy Operator for Kubernetes
# Install Trivy Operator via Helm
# helm install trivy-operator aquasecurity/trivy-operator \
# --namespace trivy-system --create-namespace
# VulnerabilityReport is created automatically for each workload
apiVersion: aquasecurity.github.io/v1alpha1
kind: VulnerabilityReport
metadata:
name: pod-myapp-myapp
namespace: default
spec:
scanner:
name: Trivy
version: 0.50.0
report:
summary:
criticalCount: 2
highCount: 5
mediumCount: 12
lowCount: 8#!/usr/bin/env python3
"""Agent for scanning Docker images with Trivy.
Performs comprehensive vulnerability scanning of Docker images
including OS packages, language dependencies, misconfigurations,
secrets, and license compliance using Trivy CLI.
"""
import json
import subprocess
import sys
from pathlib import Path
from datetime import datetime
class TrivyDockerAgent:
"""Scans Docker images using Trivy for vulnerabilities and misconfigs."""
def __init__(self, output_dir="./trivy_docker"):
self.output_dir = Path(output_dir)
self.output_dir.mkdir(parents=True, exist_ok=True)
self.scan_results = []
def _run(self, cmd, timeout=300):
try:
result = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
return result.stdout, result.stderr, result.returncode
except FileNotFoundError:
return "", "trivy not found", -1
except subprocess.TimeoutExpired:
return "", "timeout", -2
def scan_image(self, image_ref, scanners="vuln", severity=None,
ignore_unfixed=False):
"""Scan a Docker image with specified scanners."""
cmd = ["trivy", "image", "--format", "json", "--quiet",
"--scanners", scanners]
if severity:
cmd.extend(["--severity", severity])
if ignore_unfixed:
cmd.append("--ignore-unfixed")
cmd.append(image_ref)
stdout, stderr, rc = self._run(cmd)
if rc < 0:
return {"error": stderr}
try:
raw = json.loads(stdout) if stdout.strip() else {}
except json.JSONDecodeError:
return {"error": "Failed to parse trivy output"}
vulns = []
misconfigs = []
secrets = []
for result in raw.get("Results", []):
target = result.get("Target", "")
for v in result.get("Vulnerabilities", []):
vulns.append({
"id": v.get("VulnerabilityID"),
"severity": v.get("Severity"),
"package": v.get("PkgName"),
"installed": v.get("InstalledVersion"),
"fixed": v.get("FixedVersion", ""),
"target": target,
})
for mc in result.get("Misconfigurations", []):
misconfigs.append({
"id": mc.get("ID"),
"severity": mc.get("Severity"),
"title": mc.get("Title"),
"target": target,
})
for s in result.get("Secrets", []):
secrets.append({
"rule_id": s.get("RuleID"),
"severity": s.get("Severity"),
"title": s.get("Title"),
"target": target,
})
summary = {}
for v in vulns:
sev = v["severity"] or "UNKNOWN"
summary[sev] = summary.get(sev, 0) + 1
scan = {
"image": image_ref,
"scan_date": datetime.utcnow().isoformat(),
"scanners": scanners,
"vulnerability_count": len(vulns),
"misconfig_count": len(misconfigs),
"secret_count": len(secrets),
"severity_summary": summary,
"vulnerabilities": vulns,
"misconfigurations": misconfigs,
"secrets": secrets,
}
self.scan_results.append(scan)
return scan
def scan_tar(self, tar_path, severity=None):
"""Scan a saved Docker image tar archive."""
cmd = ["trivy", "image", "--format", "json", "--quiet",
"--input", tar_path]
if severity:
cmd.extend(["--severity", severity])
stdout, stderr, rc = self._run(cmd)
if rc < 0:
return {"error": stderr}
try:
return json.loads(stdout) if stdout.strip() else {}
except json.JSONDecodeError:
return {"error": "Parse error"}
def generate_sbom(self, image_ref, fmt="cyclonedx"):
"""Generate SBOM for image in CycloneDX or SPDX format."""
trivy_fmt = "cyclonedx" if fmt == "cyclonedx" else "spdx-json"
ext = "cdx" if fmt == "cyclonedx" else "spdx"
out_file = self.output_dir / f"sbom.{ext}.json"
cmd = ["trivy", "image", "--format", trivy_fmt,
"--output", str(out_file), image_ref]
_, stderr, rc = self._run(cmd)
if rc == 0:
return {"sbom_path": str(out_file), "format": fmt}
return {"error": stderr}
def check_version(self):
"""Return Trivy version info."""
stdout, _, _ = self._run(["trivy", "version"], timeout=15)
return {"version": stdout.strip()}
def generate_report(self):
report = {
"report_date": datetime.utcnow().isoformat(),
"images_scanned": len(self.scan_results),
"scans": self.scan_results,
}
out = self.output_dir / "trivy_docker_report.json"
with open(out, "w") as f:
json.dump(report, f, indent=2)
print(json.dumps(report, indent=2))
return report
def main():
if len(sys.argv) < 2:
print("Usage: agent.py <image_ref> [--scanners vuln,misconfig,secret]")
sys.exit(1)
image = sys.argv[1]
scanners = "vuln"
if "--scanners" in sys.argv:
idx = sys.argv.index("--scanners")
if idx + 1 < len(sys.argv):
scanners = sys.argv[idx + 1]
agent = TrivyDockerAgent()
agent.scan_image(image, scanners=scanners)
agent.generate_report()
if __name__ == "__main__":
main()
#!/usr/bin/env python3
"""
Trivy Docker Image Scanner - Automated scanning and reporting tool.
Scans Docker images with Trivy, parses results, enforces severity gates,
and generates actionable reports.
"""
import subprocess
import json
import sys
import os
import argparse
from datetime import datetime
from dataclasses import dataclass, field
@dataclass
class ScanPolicy:
fail_on_critical: bool = True
fail_on_high: bool = True
fail_on_medium: bool = False
max_critical: int = 0
max_high: int = 5
max_medium: int = 20
ignore_unfixed: bool = False
scanners: list = field(default_factory=lambda: ["vuln", "secret"])
@dataclass
class VulnSummary:
critical: int = 0
high: int = 0
medium: int = 0
low: int = 0
unknown: int = 0
total: int = 0
def check_trivy_installed() -> bool:
"""Verify Trivy is installed."""
try:
result = subprocess.run(
["trivy", "version"], capture_output=True, text=True, timeout=10
)
if result.returncode == 0:
version_line = result.stdout.strip().split("\n")[0]
print(f"[*] {version_line}")
return True
except (FileNotFoundError, subprocess.TimeoutExpired):
pass
print("[!] Trivy is not installed. Install from https://trivy.dev")
return False
def update_db():
"""Update Trivy vulnerability database."""
print("[*] Updating vulnerability database...")
result = subprocess.run(
["trivy", "image", "--download-db-only"],
capture_output=True, text=True, timeout=300
)
if result.returncode == 0:
print("[+] Database updated successfully")
else:
print(f"[!] Database update warning: {result.stderr}")
def scan_image(image: str, policy: ScanPolicy) -> dict:
"""Scan a Docker image with Trivy and return JSON results."""
cmd = [
"trivy", "image",
"--format", "json",
"--scanners", ",".join(policy.scanners),
]
if policy.ignore_unfixed:
cmd.append("--ignore-unfixed")
cmd.append(image)
print(f"[*] Scanning image: {image}")
print(f"[*] Scanners: {', '.join(policy.scanners)}")
result = subprocess.run(
cmd, capture_output=True, text=True, timeout=600
)
if result.returncode != 0 and not result.stdout:
print(f"[!] Scan failed: {result.stderr}")
return {}
try:
return json.loads(result.stdout)
except json.JSONDecodeError:
print("[!] Failed to parse Trivy JSON output")
return {}
def parse_results(scan_data: dict) -> tuple:
"""Parse Trivy JSON results into vulnerability summary and details."""
summary = VulnSummary()
vulnerabilities = []
secrets = []
misconfigs = []
results = scan_data.get("Results", [])
for result in results:
target = result.get("Target", "unknown")
result_class = result.get("Class", "")
result_type = result.get("Type", "")
# Parse vulnerabilities
for vuln in result.get("Vulnerabilities", []):
severity = vuln.get("Severity", "UNKNOWN").upper()
if severity == "CRITICAL":
summary.critical += 1
elif severity == "HIGH":
summary.high += 1
elif severity == "MEDIUM":
summary.medium += 1
elif severity == "LOW":
summary.low += 1
else:
summary.unknown += 1
summary.total += 1
vulnerabilities.append({
"target": target,
"type": result_type,
"vuln_id": vuln.get("VulnerabilityID", ""),
"pkg_name": vuln.get("PkgName", ""),
"installed_version": vuln.get("InstalledVersion", ""),
"fixed_version": vuln.get("FixedVersion", ""),
"severity": severity,
"title": vuln.get("Title", ""),
"description": vuln.get("Description", "")[:200],
"cvss_score": vuln.get("CVSS", {}).get("nvd", {}).get("V3Score", 0),
"references": vuln.get("References", [])[:3],
})
# Parse secrets
for secret in result.get("Secrets", []):
secrets.append({
"target": target,
"rule_id": secret.get("RuleID", ""),
"category": secret.get("Category", ""),
"severity": secret.get("Severity", ""),
"title": secret.get("Title", ""),
"match": secret.get("Match", "")[:50] + "...",
})
# Parse misconfigurations
for misconfig in result.get("Misconfigurations", []):
misconfigs.append({
"target": target,
"type": misconfig.get("Type", ""),
"id": misconfig.get("ID", ""),
"title": misconfig.get("Title", ""),
"severity": misconfig.get("Severity", ""),
"message": misconfig.get("Message", ""),
"resolution": misconfig.get("Resolution", ""),
})
return summary, vulnerabilities, secrets, misconfigs
def evaluate_policy(summary: VulnSummary, policy: ScanPolicy) -> tuple:
"""Evaluate scan results against policy. Returns (passed, reasons)."""
passed = True
reasons = []
if policy.fail_on_critical and summary.critical > policy.max_critical:
passed = False
reasons.append(
f"CRITICAL vulnerabilities ({summary.critical}) exceed threshold ({policy.max_critical})"
)
if policy.fail_on_high and summary.high > policy.max_high:
passed = False
reasons.append(
f"HIGH vulnerabilities ({summary.high}) exceed threshold ({policy.max_high})"
)
if policy.fail_on_medium and summary.medium > policy.max_medium:
passed = False
reasons.append(
f"MEDIUM vulnerabilities ({summary.medium}) exceed threshold ({policy.max_medium})"
)
return passed, reasons
def generate_report(image: str, summary: VulnSummary, vulnerabilities: list,
secrets: list, misconfigs: list, policy_passed: bool,
policy_reasons: list) -> dict:
"""Generate comprehensive scan report."""
return {
"scan_metadata": {
"tool": "Trivy",
"image": image,
"timestamp": datetime.utcnow().isoformat() + "Z",
"policy_result": "PASS" if policy_passed else "FAIL",
},
"summary": {
"total_vulnerabilities": summary.total,
"critical": summary.critical,
"high": summary.high,
"medium": summary.medium,
"low": summary.low,
"unknown": summary.unknown,
"secrets_found": len(secrets),
"misconfigurations_found": len(misconfigs),
},
"policy_evaluation": {
"passed": policy_passed,
"failure_reasons": policy_reasons,
},
"critical_vulnerabilities": [
v for v in vulnerabilities if v["severity"] == "CRITICAL"
],
"high_vulnerabilities": [
v for v in vulnerabilities if v["severity"] == "HIGH"
],
"secrets": secrets,
"misconfigurations": misconfigs,
"all_vulnerabilities": vulnerabilities,
}
def print_report(report: dict):
"""Print human-readable scan report."""
meta = report["scan_metadata"]
summary = report["summary"]
print("\n" + "=" * 70)
print("TRIVY IMAGE SCAN REPORT")
print("=" * 70)
print(f"Image: {meta['image']}")
print(f"Timestamp: {meta['timestamp']}")
print(f"Policy: {meta['policy_result']}")
print("=" * 70)
print(f"\nVulnerability Summary:")
print(f" CRITICAL: {summary['critical']}")
print(f" HIGH: {summary['high']}")
print(f" MEDIUM: {summary['medium']}")
print(f" LOW: {summary['low']}")
print(f" UNKNOWN: {summary['unknown']}")
print(f" TOTAL: {summary['total_vulnerabilities']}")
if summary["secrets_found"] > 0:
print(f"\n Secrets Found: {summary['secrets_found']}")
if summary["misconfigurations_found"] > 0:
print(f" Misconfigs Found: {summary['misconfigurations_found']}")
# Print critical/high details
for severity in ["critical", "high"]:
vulns = report.get(f"{severity}_vulnerabilities", [])
if vulns:
print(f"\n{severity.upper()} VULNERABILITIES:")
print("-" * 70)
for v in vulns:
fixed = v.get("fixed_version", "not fixed")
print(f" {v['vuln_id']} | {v['pkg_name']} {v['installed_version']} -> {fixed}")
if v.get("title"):
print(f" {v['title']}")
# Print policy result
policy = report["policy_evaluation"]
if not policy["passed"]:
print(f"\nPOLICY FAILURES:")
for reason in policy["failure_reasons"]:
print(f" - {reason}")
print()
def main():
parser = argparse.ArgumentParser(description="Trivy Docker Image Scanner")
parser.add_argument("image", help="Docker image to scan (e.g., nginx:latest)")
parser.add_argument("--output", "-o", default="trivy_report.json", help="Output JSON file")
parser.add_argument("--max-critical", type=int, default=0, help="Max allowed CRITICAL vulns")
parser.add_argument("--max-high", type=int, default=5, help="Max allowed HIGH vulns")
parser.add_argument("--ignore-unfixed", action="store_true", help="Ignore unfixed vulns")
parser.add_argument("--scanners", default="vuln,secret",
help="Comma-separated scanners: vuln,misconfig,secret,license")
parser.add_argument("--update-db", action="store_true", help="Update DB before scan")
args = parser.parse_args()
if not check_trivy_installed():
sys.exit(1)
if args.update_db:
update_db()
policy = ScanPolicy(
max_critical=args.max_critical,
max_high=args.max_high,
ignore_unfixed=args.ignore_unfixed,
scanners=args.scanners.split(","),
)
scan_data = scan_image(args.image, policy)
if not scan_data:
sys.exit(1)
summary, vulnerabilities, secrets, misconfigs = parse_results(scan_data)
policy_passed, policy_reasons = evaluate_policy(summary, policy)
report = generate_report(
args.image, summary, vulnerabilities, secrets, misconfigs,
policy_passed, policy_reasons
)
print_report(report)
with open(args.output, "w") as f:
json.dump(report, f, indent=2)
print(f"[*] Full report saved to {args.output}")
if not policy_passed:
print("[!] Policy check FAILED - image should not be deployed")
sys.exit(1)
print("[+] Policy check PASSED - image approved for deployment")
if __name__ == "__main__":
main()