Trivy Security Scanner

repository·main·Indexed 12 days ago

https://github.com/aquasecurity/trivy

A comprehensive security scanner for identifying vulnerabilities, misconfigurations, and secrets across container images, filesystems, and Kubernetes clusters. Includes support for Wasm modules, Helm chart deployment for Kubernetes, and a robust testing framework using golden files for integration and E2E validation.

Tokens
132.8K
Snippets
426
Records
573
Agent score
99%

What's inside Trivy

  1. Compare Trivy Open Source and Aqua Commercial

    main

    Trivy Open Source (OSS) is a CLI-based scanner, while Aqua is a commercial security management platform built on top of Trivy. Use the following comparison to decide between the two based on your organizational needs:

    Key Differences

    User Experience & Scalability

    • Interface: Trivy OSS is a CLI tool. Aqua provides a CLI tool plus an enterprise-grade web application (SaaS or on-prem).
    • Management: Aqua includes Multi-account support, Granular RBAC, and SSO, which are not available in Trivy OSS.
    • Scalability: Trivy OSS performs single scans at a time. Aqua provides a centralized scanning service for concurrent scans with highly available architecture.
    • Support: Trivy OSS relies on community support. Aqua provides personal onboarding and SLA-backed professional support.

    Vulnerability Scanning

    • Feeds: Trivy OSS uses open-source feeds. Aqua uses both open-source and commercial feeds with a commercial SLA.
    • Prioritization: Trivy OSS requires manual triage by severity. Aqua offers advanced prioritization based on resource accessibility, exploitability, package health, and affected image layers.
    • Analysis: Aqua provides reachability analysis (to eliminate unused dependencies) and contextual vulnerability analysis (e.g., checking JDK versions).
    • Package Management: Trivy OSS finds packages in lock files. Aqua finds packages in lock files or reconstructed lock files.

    Container & Advanced Scanning

    • Container Support: Aqua supports Windows containers and automatic scanning of connected container registries. Aqua also supports Cloud authentication (ECR, GCR, ACR) and scalable Cloud caching.
    • Advanced Security: Aqua includes Malware scanning, Sandbox scanning (Dynamic Threat Analysis), and SAST (Static Application Security Testing).

    Policy, Secrets, and IaC/CSPM

    • Enforcement: Trivy OSS can fail CI/CD builds on findings. Aqua provides granular policies, Kubernetes Admission control, and the ability to block non-compliant images at the container engine level or via vShield.
    • Secrets: Trivy OSS uses basic patterns. Aqua uses advanced patterns and automatically validates if leaked secrets are usable.
    • IaC/CSPM: Trivy OSS supports many languages and custom Rego checks. Aqua adds Build Pipeline configuration scanning, a no-code interface for custom checks, and support for more cloud providers (Azure, GCP, Alibaba, Oracle) and 25+ compliance programs.

    Kubernetes Scanning

    • Discovery: Trivy OSS uses Kubeconfig. Aqua uses automatic discovery through cloud onboarding.
    • Execution: Trivy OSS scans in-cluster (limited by etcd storage). Aqua offloads scanning to its service to minimize impact on scanned clusters and uses cloud-based storage for unlimited scalability.
  2. Explore Trivy integrations

    main

    Trivy is integrated into various tools and applications to enable security scanning within existing workflows. Integrations are categorized into two types:

    • Official Integrations: Developed and supported by the core Trivy team.
    • Community Integrations: Developed by the community. For support or questions regarding these, you should contact the original developers of the specific integration.

    To browse specific integrations, use the side-navigation menu in the documentation.

  3. Overview of Trivy vulnerability data repositories

    main

    The vulnerability data pipeline is distributed across four distinct components:

    RepositoryPurpose
    vuln-list-updateContains scripts to fetch, validate, and save advisories from upstream sources into vuln-list.
    vuln-listA storage repository for raw JSON advisory data. Note: Direct manual pull requests are not accepted here.
    trivy-dbContains parsers and handlers that map raw advisory fields to the Trivy schema and build the database.
    trivyThe main scanner repository containing OS/package analyzers and the core detection logic.
  4. Understand Trivy telemetry data collection and privacy

    main

    Trivy collects anonymous environmental and scan-related information.

    Collected Data:

    • Environmental information: Installation identifier (a one-way hash of a machine fingerprint), Trivy version, and Operating system.
    • Scan options: Specific non-revealing scan flags and their values.

    Privacy Protections:

    • No sensitive data: Trivy does not collect personal information, scan results, or sensitive data.
    • Omitted options: Any user-controlled option that could reveal sensitive information (e.g., file paths, image names, etc.) is explicitly omitted from collection.

    Note on Updates: Disabling telemetry stops usage data collection, but Trivy will still attempt to connect to check.trivy.dev to check for updates unless you also specify the --skip-version-check flag.

  5. Write custom Rego checks for raw Terraform configurations

    main

    When writing custom Rego checks for raw Terraform, you must specify the schema in the metadata section of your Rego file. Use schema["terraform-raw"] to target the raw configuration.

    In your Rego logic, you can then access the raw structure (e.g., input.modules) to perform specific validations that might not be available in the unified structure.

    # METADATA
    # title: AWS required resource tags
    # description: Ensure required tags are set on AWS resources
    # scope: package
    # schemas:
    #   - input: schema["terraform-raw"]
    # custom:
    #   id:  USR-TFRAW-0001
    #   severity: CRITICAL
    #   short_code: required-aws-resource-tags
    #   recommended_actions: Add the required tags to AWS resources.
    #   input:
    #     selector:
    #     - type: terraform-raw
    package user.terraform.required_aws_tags
    
    import rego.v1
    
    resource_types_to_check := {"aws_s3_bucket"}
    
    resources_to_check := {block | 
    	some module in input.modules
    	some block in module.blocks
    	block.kind == "resource"
    	block.type in resource_types_to_check
    }
    
    required_tags := {"Access", "Owner"}
    
    deny contains res if {
    	some block in resources_to_check
    	not block.attributes.tags
    	res := result.new(
    		sprintf("The resource %q does not contain the following required tags: %v", [block.type, required_tags]),
    		block,
    	)
    }
    
    deny contains res if {
    	some block in resources_to_check
    	tags_attr := block.attributes.tags
    	tags := object.keys(tags_attr.value)
    	missing_tags := required_tags - tags
    	count(missing_tags) > 0
    	res := result.new(
    		sprintf("The resource %q does not contain the following required tags: %v", [block.type, missing_tags]),
    		tags_attr,
    	)
    }
  6. Naming conventions for Trivy plugins

    main

    To ensure discoverability and avoid conflicts, follow these naming guidelines:

    • Prefix: Repository names must start with trivy-plugin-.
    • Format: Use kebab-case (all lowercase with hyphens). Do not use camelCase, PascalCase, or snake_case.
    • Specificity: Avoid generic names like trivy sast. Use specific names like trivy govulncheck.
    • Uniqueness: Ensure the name doesn't overlap with built-in commands (e.g., use trivy registry-images instead of trivy images).
    • Vendor Prefixing: For vendor-specific plugins, use the vendor name as a prefix (e.g., trivy aws-security-hub instead of trivy security-hub-aws) to group them together in searches.
  7. How Trivy license scanning works

    main

    Trivy scans container images and filesystems for license files and provides an opinionated risk assessment. It uses the Google License Classification to categorize licenses into several levels, which are then mapped to specific severities.

    License Classifications and Severities

    ClassificationSeverity
    ForbiddenCRITICAL
    RestrictedHIGH
    ReciprocalMEDIUM
    NoticeLOW
    PermissiveLOW
    UnencumberedLOW
    UnknownUNKNOWN

    Note: Licenses that Trivy fails to recognize are classified as UNKNOWN. It is recommended to manually check these as they may be in violation.

  8. How golden files and canonical sources work

    main

    Trivy's integration testing framework uses a Canonical Source vs. Consumer model to manage golden files and prevent unstable test outputs.

    Canonical Source Tests

    These are the only tests allowed to update golden files. They generate the ground-truth output.

    • Identification: Look for the override: nil comment in the test code.
    • Behavior: They do not use t.Skipf() when the -update flag is present.
    • Constraint: They must not use override functions, as this would bake modified data into the canonical source.

    Consumer Tests

    These tests verify that different inputs or modes (e.g., local path vs. remote URL) produce the same results as the canonical source.

    • Identification: They contain if *update { t.Skipf(...) } at the start of the function.
    • Behavior: They reuse existing golden files in read-only mode.
    • Mechanism: They use override functions to adjust for minor differences like ArtifactName, ReportID, or path separators (Windows vs. Unix) while keeping the core vulnerability data identical.

    Why this pattern exists

    Each golden file must be updated by exactly one test function. If multiple tests update the same file, the output becomes unstable and changes depending on which test ran last.

  9. Configure Storage and Caching for Trivy

    main

    Storage

    This chart utilizes a PersistentVolumeClaim to store the vulnerability database. This reduces the frequency of database downloads during Pod restarts or updates. Requirement: The storageclass used should have a reclaim policy of Retain.

    Caching with Redis

    You can enable Redis as a caching backend to improve performance.

    • The Redis server must be pre-existing (e.g., installed via the Bitnami Redis chart).
    • Use the trivy.cache.redis.* parameters to configure the connection.

    Relevant Redis Parameters:

    • trivy.cache.redis.enabled: Set to true to enable.
    • trivy.cache.redis.url: The connection string (e.g., redis://redis.redis.svc:6379).
    • trivy.cache.redis.ttl: Time-to-live for cache entries (e.g., 3600s or 24h).
    • trivy.cache.redis.tls: Enable TLS with public certificates.
  10. Structure of a Trivy Rego Check

    main

    Trivy checks are written in OPA Rego and consist of two main parts: a # METADATA section and the Rego logic.

    Metadata Section

    The metadata is a YAML-formatted block within Rego comments at the top of the file. While optional for local custom checks, it is required for contributing to the official trivy-checks repository. Key fields include:

    • title: A human-readable name for the check.
    • description: A summary of what the check ensures.
    • scope: The scope of the check (e.g., package).
    • schemas: Defines how to map input to specific objects using input: schema["..."].
    • related_resources: Links to external documentation.
    • custom: Contains unique identifiers and provider details such as id, avd_id, provider, service, severity, short_code, recommended_action, and an input.selector.

    Rego Logic

    The logic uses the deny[res] pattern. The rule must return a result using the built-in result.new(message, resource) function. This function does not require an import as it is provided at runtime.

    • First argument: The error message string.
    • Second argument: The resource object where the issue was detected.
    # METADATA
    # title: "RDS IAM Database Authentication Disabled"
    # description: "Ensure IAM Database Authentication is enabled for RDS database instances to manage database access"
    # scope: package
    # schemas:
    # - input: schema["aws"]
    # related_resources:
    # - https://docs.aws.amazon.com/neptune/latest/userguide/iam-auth.html
    # custom:
    #   id: AVD-AWS-0176
    #   avd_id: AVD-AWS-0176
    #   provider: aws
    #   service: rds
    #   severity: MEDIUM
    #   short_code: enable-iam-auth
    #   recommended_action: "Modify the PostgreSQL and MySQL type RDS instances to enable IAM database authentication."
    #   input:
    #     selector:
    #     - type: cloud
    #       subtypes:
    #         - service: rds
    #           provider: aws
    
    package builtin.aws.rds.aws0176
    
    deny[res] {
    	instance := input.aws.rds.instances[_]
    	instance.engine.value == ["postgres", "mysql"][_]
    	not instance.iamauthenabled.value
    	res := result.new("Instance does not have IAM Authentication enabled", instance.iamauthenabled)
    }
  11. How Trivy handles OS packages and unspecified versions

    main

    Trivy's detection behavior is designed to prioritize precision, which impacts how it handles two specific scenarios:

    OS Packages

    For files installed via OS package managers (like apt or dnf), Trivy exclusively uses advisories from the OS vendor. This prevents false positives caused by OS vendors backporting security fixes to older version numbers (e.g., Red Hat backporting a fix to a version that upstream considers vulnerable).

    • To reduce false negatives (if vendor advisories are missing), use --detection-priority comprehensive to include upstream advisories.

    Unspecified Versions

    When a package version cannot be uniquely determined (e.g., package-a: ">=3.0"), Trivy typically skips detection to avoid false positives. If a lock file is present, Trivy will use the fixed versions from that lock file.

    • To detect potential vulnerabilities in these cases, use --detection-priority comprehensive, which forces Trivy to use the minimum version in the specified range.