Trivy Offline Vulnerability Scanning
This skill provides guidance on using Trivy, an open-source security scanner, to discover vulnerabilities in software dependencies using offline mode.
Overview
Trivy is a comprehensive vulnerability scanner that can analyze various targets including container images, filesystems, and dependency lock files. Offline scanning is crucial for:
- Air-gapped environments without internet access
- Reproducible security audits with fixed vulnerability databases
- Faster CI/CD pipelines avoiding network latency
- Compliance requirements for controlled environments
Trivy Database Structure
Trivy's vulnerability database consists of:
- trivy.db: BoltDB (bbolt key-value) file containing vulnerability advisories
- metadata.json: Database version and update timestamp
Database location: <cache-dir>/db/trivy.db
Scanning JAR/WAR files uses a separate Java index DB at <cache-dir>/java-db/trivy-java.db. Pre-download both while online:
trivy image --download-db-only --cache-dir ./trivy-cache
trivy image --download-java-db-only --cache-dir ./trivy-cache
Offline Scanning Workflow
Step 1: Verify Database Existence
Before scanning, ensure the offline database is available:
import os
import sys
TRIVY_CACHE_PATH = './trivy-cache'
# Check for database file
db_path = os.path.join(TRIVY_CACHE_PATH, "db", "trivy.db")
if not os.path.exists(db_path):
print(f"[!] Error: Trivy database not found at {db_path}")
print(" Download database first with:")
print(f" trivy image --download-db-only --cache-dir {TRIVY_CACHE_PATH}")
sys.exit(1)
Step 2: Construct Trivy Command
Key flags for offline scanning:
| Flag | Purpose |
|---|---|
fs <target> |
Scan filesystem/file (e.g., package-lock.json) |
--format json |
Output in JSON format for parsing |
--output <file> |
Save results to file |
--scanners vuln |
Scan only for vulnerabilities (not misconfigs) |
--skip-db-update |
Critical: do not download/update the vulnerability DB |
--skip-java-db-update |
Do not download/update the Java DB (needed offline when JARs are scanned) |
--offline-scan |
Make no network requests during analysis (e.g. no Maven Central lookups for JARs) |
--cache-dir <path> |
Path to pre-downloaded database |
--severity HIGH,CRITICAL |
Report only these severities |
--ignore-unfixed |
Skip vulnerabilities that have no fixed version yet |
import subprocess
TARGET_FILE = 'package-lock.json'
OUTPUT_FILE = 'trivy_report.json'
TRIVY_CACHE_PATH = './trivy-cache'
command = [
"trivy", "fs", TARGET_FILE,
"--format", "json",
"--output", OUTPUT_FILE,
"--scanners", "vuln",
"--skip-db-update", # Prevent online updates
"--offline-scan", # Enable offline mode
"--cache-dir", TRIVY_CACHE_PATH
]
Step 3: Execute Scan
try:
result = subprocess.run(
command,
capture_output=True,
text=True,
check=False # Don't raise exception on non-zero exit
)
if result.returncode != 0:
print("[!] Trivy scan failed:")
print(result.stderr)
sys.exit(1)
print("[*] Scan completed successfully")
print(f"[*] Results saved to: {OUTPUT_FILE}")
except FileNotFoundError:
print("[!] Error: 'trivy' command not found")
print(" Install Trivy: https://trivy.dev/latest/getting-started/installation/")
sys.exit(1)
JSON Output Structure
Trivy outputs vulnerability data in this format:
{
"Results": [
{
"Target": "package-lock.json",
"Vulnerabilities": [
{
"VulnerabilityID": "CVE-2021-44906",
"PkgName": "minimist",
"InstalledVersion": "1.2.5",
"FixedVersion": "1.2.6",
"Severity": "CRITICAL",
"Title": "Prototype Pollution in minimist",
"PrimaryURL": "https://avd.aquasec.com/nvd/cve-2021-44906",
"CVSS": {
"nvd": { "V3Score": 9.8 }
}
}
]
}
]
}
Common Issues
Issue: "failed to initialize DB"
Cause: Database not found or corrupted
Solution: Re-download database or check --cache-dir path
Issue: Scan finds no vulnerabilities when they exist
Cause: Database is outdated
Solution: Download newer database (before going offline)
Issue: "command not found: trivy"
Cause: Trivy not installed or not in PATH
Solution: Install Trivy following official documentation
Dependencies
Required Tools
- Trivy: Version 0.40.0 or later recommended
A checksum file from the same release only detects corruption; to verify authenticity, check the release's cosign signature as described in the signature-verification section of the trivy.dev docs.# Option A (Debian/Ubuntu): APT repo with a dedicated keyring (apt-key is deprecated) 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 generic main" \ | sudo tee /etc/apt/sources.list.d/trivy.list sudo apt-get update apt-cache madison trivy # list available versions sudo apt-get install trivy=<x.y.z> # pin the version sudo apt-mark hold trivy # Option B: pinned release binary with checksum verification V=<x.y.z> # check the aquasecurity/trivy release notes and security advisories before choosing base=https://github.com/aquasecurity/trivy/releases/download/v$V curl -fsSLO "$base/trivy_${V}_Linux-64bit.tar.gz" curl -fsSLO "$base/trivy_${V}_checksums.txt" sha256sum --ignore-missing -c "trivy_${V}_checksums.txt" tar -xzf "trivy_${V}_Linux-64bit.tar.gz" trivy
Python Modules
subprocess(standard library)os(standard library)sys(standard library)