trivy-offline-vulnerability-scanning

6
1
Source

Use Trivy vulnerability scanner in offline mode to discover security vulnerabilities in dependency files. This skill covers setting up offline scanning, executing Trivy against package lock files, and generating JSON vulnerability reports without requiring internet access.

Install

mkdir -p .claude/skills/trivy-offline-vulnerability-scanning && curl -L -o skill.zip "https://mcp.directory/api/skills/download/3247" && unzip -o skill.zip -d .claude/skills/trivy-offline-vulnerability-scanning && rm skill.zip

Installs to .claude/skills/trivy-offline-vulnerability-scanning

About this skill

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

Why Offline Mode?

Challenges with Online Scanning

  • Network dependency introduces failure points
  • Database updates can cause inconsistent results across runs
  • Slower execution due to download times
  • Security policies may restrict external connections

Benefits of Offline Scanning

  • Reproducibility: Same database = same results
  • Speed: No network overhead
  • Reliability: No external dependencies
  • Compliance: Works in restricted environments

Trivy Database Structure

Trivy's vulnerability database consists of:

  • trivy.db: SQLite database containing CVE information
  • metadata.json: Database version and update timestamp

Database location: <cache-dir>/db/trivy.db

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:

FlagPurpose
fs <target>Scan filesystem/file (e.g., package-lock.json)
--format jsonOutput in JSON format for parsing
--output <file>Save results to file
--scanners vulnScan only for vulnerabilities (not misconfigs)
--skip-db-updateCritical: Do not update database
--offline-scanEnable offline mode
--cache-dir <path>Path to pre-downloaded database
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://aquasecurity.github.io/trivy/latest/getting-started/installation/")
    sys.exit(1)

Complete Example

import os
import sys
import subprocess

def run_trivy_offline_scan(target_file, output_file, cache_dir='./trivy-cache'):
    """
    Execute Trivy vulnerability scan in offline mode.
    
    Args:
        target_file: Path to file to scan (e.g., package-lock.json)
        output_file: Path to save JSON results
        cache_dir: Path to Trivy offline database
    """
    print(f"[*] Starting Trivy offline scan...")
    print(f"    Target: {target_file}")
    print(f"    Database: {cache_dir}")
    
    # Verify database exists
    db_path = os.path.join(cache_dir, "db", "trivy.db")
    if not os.path.exists(db_path):
        print(f"[!] Error: Database not found at {db_path}")
        sys.exit(1)
    
    # Build command
    command = [
        "trivy", "fs", target_file,
        "--format", "json",
        "--output", output_file,
        "--scanners", "vuln",
        "--skip-db-update",
        "--offline-scan",
        "--cache-dir", cache_dir
    ]
    
    # Execute
    try:
        result = subprocess.run(command, capture_output=True, text=True)
        
        if result.returncode != 0:
            print("[!] Scan failed:")
            print(result.stderr)
            sys.exit(1)
        
        print("[*] Scan completed successfully")
        return output_file
        
    except FileNotFoundError:
        print("[!] Trivy not found. Install from:")
        print("    https://aquasecurity.github.io/trivy/")
        sys.exit(1)

# Usage
if __name__ == "__main__":
    run_trivy_offline_scan(
        target_file='package-lock.json',
        output_file='trivy_report.json'
    )

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
    # Installation (example for Debian/Ubuntu)
    wget -qO - https://aquasecurity.github.io/trivy-repo/deb/public.key | apt-key add -
    echo "deb https://aquasecurity.github.io/trivy-repo/deb $(lsb_release -sc) main" | tee -a /etc/apt/sources.list.d/trivy.list
    apt-get update
    apt-get install trivy
    

Python Modules

  • subprocess (standard library)
  • os (standard library)
  • sys (standard library)

References

latex-writing

benchflow-ai

Guide LaTeX document authoring following best practices and proper semantic markup. Use proactively when: (1) writing or editing .tex files, (2) writing or editing .nw literate programming files, (3) literate-programming skill is active and working with .nw files, (4) user mentions LaTeX, BibTeX, or document formatting, (5) reviewing LaTeX code quality. Ensures proper use of semantic environments (description vs itemize), csquotes (\enquote{} not ``...''), and cleveref (\cref{} not \S\ref{}).

569441

polyglot-rust-c

benchflow-ai

Guidance for creating polyglot source files that compile and run correctly as both Rust and C or C++. This skill applies when tasks require writing code that is valid in multiple languages simultaneously, exploiting comment syntax differences or preprocessor directives to create dual-language source files. Use this skill for polyglot programming challenges, CTF tasks, or educational exercises involving multi-language source compatibility.

135428

python-programming

benchflow-ai

Master Python fundamentals, OOP, data structures, async programming, and production-grade scripting for data engineering

6734

pytorch

benchflow-ai

Building and training neural networks with PyTorch. Use when implementing deep learning models, training loops, data pipelines, model optimization with torch.compile, distributed training, or deploying PyTorch models.

6931

search-flights

benchflow-ai

Search flights by origin, destination, and departure date using the bundled flights dataset. Use this skill when proposing flight options or checking whether a route/date combination exists.

19628

marker

benchflow-ai

Convert PDF documents to Markdown using marker_single. Use when Claude needs to extract text content from PDFs while preserving LaTeX formulas, equations, and document structure. Ideal for academic papers and technical documents containing mathematical notation.

6726

You might also like

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

2,2693,963

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

3,6643,346

pdf-to-markdown

aliceisjustplaying

Convert entire PDF documents to clean, structured Markdown for full context loading. Use this skill when the user wants to extract ALL text from a PDF into context (not grep/search), when discussing or analyzing PDF content in full, when the user mentions "load the whole PDF", "bring the PDF into context", "read the entire PDF", or when partial extraction/grepping would miss important context. This is the preferred method for PDF text extraction over page-by-page or grep approaches.

4,7092,237

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

2,2861,724

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

2,4891,553

youtube-transcribe-skill

feiskyer

Extract subtitles/transcripts from a YouTube video URL and save as a local file. Use when you need to extract subtitles from a YouTube video.

3691,450