npx skills add mukul975/Anthropic-Cybersecurity-SkillsMITRE ATT&CK
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
References and resources
Everything below is rendered for inspection. Script files are read-only and never run.
References 3
api-reference.md1.6 KB
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.md2.5 KB
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.md3.6 KB
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: 8Scripts 2
agent.py5.6 KB
#!/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()
process.py10.7 KB
#!/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()