← Back to DevBytes

Trivy Vulnerability Scanner: Complete Implementation Guide

Introduction to Trivy

Trivy is an open-source, comprehensive vulnerability scanner designed for modern DevOps workflows. Created by Aqua Security, Trivy scans container images, file systems, Git repositories, Kubernetes clusters, and Infrastructure as Code (IaC) files for vulnerabilities, misconfigurations, secrets, and license issues. It is fast, easy to integrate, and supports a wide range of ecosystems, making it a popular choice for security-conscious development teams.

Why Vulnerability Scanning Matters

In today's software supply chain, applications rely heavily on third-party dependencies, base images, and open-source libraries. Each of these components can introduce vulnerabilities that attackers may exploit. Without automated scanning, these risks often go unnoticed until it is too late. Trivy helps teams identify and remediate vulnerabilities early in the development lifecycle, reducing the attack surface and improving overall security posture.

Key Features of Trivy

Installing Trivy

Trivy is available on multiple platforms. Below are installation instructions for common operating systems.

Installing on macOS

brew install trivy

Installing on Linux (Debian/Ubuntu)

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

Installing via Docker

docker pull aquasec/trivy:latest

Verifying the Installation

trivy --version

After running the command, you should see the Trivy version printed to the terminal, confirming a successful installation.

Scanning Container Images

The most common use case for Trivy is scanning container images. Trivy examines the image layers, identifies installed packages and dependencies, and compares them against known vulnerability databases.

Basic Image Scan

trivy image nginx:latest

This command pulls the nginx:latest image (if not already present), analyzes its contents, and reports any vulnerabilities found. The output includes severity levels (UNKNOWN, LOW, MEDIUM, HIGH, CRITICAL), package names, vulnerability IDs, and fixed versions where available.

Filtering by Severity

To focus on the most critical issues, you can filter results by severity level:

trivy image --severity HIGH,CRITICAL nginx:latest

Ignoring Unfixed Vulnerabilities

Some vulnerabilities do not yet have a fix available. You can exclude these from results to reduce noise:

trivy image --ignore-unfixed nginx:latest

Scanning a Local Image

docker build -t myapp:1.0 .
trivy image myapp:1.0

Scanning File Systems and Repositories

Trivy can scan local file systems to find vulnerabilities in project dependencies and detect hardcoded secrets.

Scanning a Project Directory

trivy fs .

This command scans the current directory for lock files (such as package-lock.json, requirements.txt, go.sum) and reports vulnerabilities in the listed dependencies.

Scanning a Git Repository

trivy repo https://github.com/aquasecurity/trivy

Scanning for Secrets

trivy fs --scanners secret .

This command specifically looks for secrets such as AWS access keys, private keys, and API tokens within the files of the current directory.

Scanning Infrastructure as Code

Misconfigurations in infrastructure code can lead to serious security incidents. Trivy supports scanning Terraform, CloudFormation, Kubernetes manifests, and Dockerfiles.

Scanning a Terraform Project

trivy config ./terraform/

Scanning Kubernetes Manifests

trivy config ./k8s-manifests/

Scanning a Dockerfile

trivy config Dockerfile

Trivy checks for best practices such as running as a non-root user, avoiding the use of :latest tags, and not exposing sensitive ports unnecessarily.

Generating SBOM Reports

A Software Bill of Materials (SBOM) is a formal record of the components and dependencies in a software project. Trivy can generate SBOMs in CycloneDX and SPDX formats.

Generating a CycloneDX SBOM

trivy image --format cyclonedx --output sbom.json myapp:1.0

Generating an SPDX SBOM

trivy image --format spdx-json --output sbom.spdx.json myapp:1.0

Scanning from an SBOM

You can also scan an existing SBOM file for vulnerabilities:

trivy sbom sbom.json

Output Formats and Reporting

Trivy supports multiple output formats, making it easy to integrate with other tools and generate human-readable reports.

JSON Output

trivy image --format json --output report.json myapp:1.0

HTML Report

trivy image --format template --template "@contrib/html.tpl" --output report.html myapp:1.0

SARIF Output for GitHub Integration

trivy image --format sarif --output trivy-results.sarif myapp:1.0

Integrating Trivy into CI/CD Pipelines

Integrating Trivy into your CI/CD pipeline ensures that vulnerabilities are caught before code reaches production. Below are examples for popular CI/CD platforms.

GitHub Actions

name: Trivy Scan

on:
  push:
    branches:
      - main
  pull_request:

jobs:
  trivy-scan:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        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'

      - name: Upload Trivy results to GitHub Security tab
        uses: github/codeql-action/upload-sarif@v3
        with:
          sarif_file: 'trivy-results.sarif'

GitLab CI

trivy_scan:
  image: 
    name: aquasec/trivy:latest
    entrypoint: [""]
  script:
    - trivy fs --severity HIGH,CRITICAL --exit-code 1 .
  allow_failure: true

Jenkins Pipeline

pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                sh 'docker build -t myapp:latest .'
            }
        }
        stage('Trivy Scan') {
            steps {
                sh 'trivy image --severity HIGH,CRITICAL --exit-code 1 myapp:latest'
            }
        }
    }
}

Using the Trivy Server Mode

In environments where multiple clients need to scan images, running Trivy in server mode reduces redundant database downloads and improves performance.

Starting the Server

trivy server --listen 0.0.0.0:4954

Connecting a Client

trivy image --server http://trivy-server:4954 myapp:1.0

This setup is particularly useful in CI/CD environments where many pipelines run concurrently and each would otherwise download the full vulnerability database.

Scanning Kubernetes Clusters

Trivy can scan a live Kubernetes cluster to identify vulnerabilities in running images and misconfigurations in deployed resources.

Cluster Scan

trivy k8s --report summary cluster

Scanning a Specific Namespace

trivy k8s -n production --report summary all

Detailed Resource Scan

trivy k8s deployment/my-app -n default

Best Practices for Using Trivy

Example .trivyignore File

# CVE-2023-1234 - Accepted risk, no fix available yet
CVE-2023-1234

# CVE-2022-5678 - Compensating control in place
CVE-2022-5678

Automating with Trivy in a DevSecOps Workflow

A robust DevSecOps workflow incorporates Trivy at multiple stages. Below is an example script that demonstrates a comprehensive scanning approach.

#!/bin/bash
set -e

IMAGE_NAME="myapp"
IMAGE_TAG="1.0.0"
FULL_IMAGE="${IMAGE_NAME}:${IMAGE_TAG}"

echo "Building Docker image..."
docker build -t "${FULL_IMAGE}" .

echo "Scanning image for vulnerabilities..."
trivy image --severity HIGH,CRITICAL --exit-code 1 --ignore-unfixed "${FULL_IMAGE}"

echo "Scanning for secrets in source code..."
trivy fs --scanners secret --exit-code 1 .

echo "Scanning Infrastructure as Code..."
trivy config --exit-code 1 ./infra/

echo "Generating SBOM..."
trivy image --format cyclonedx --output "sbom-${IMAGE_TAG}.json" "${FULL_IMAGE}"

echo "All scans passed successfully!"

Conclusion

Trivy is a powerful and versatile vulnerability scanner that fits naturally into modern development workflows. By scanning container images, file systems, infrastructure code, and Kubernetes clusters, it provides comprehensive visibility into security risks across the entire software lifecycle. When integrated into CI/CD pipelines and combined with best practices such as severity filtering, SBOM generation, and secret detection, Trivy becomes an essential tool for any team committed to building secure software. Start incorporating Trivy into your workflow today to catch vulnerabilities early, reduce risk, and maintain a strong security posture throughout your development process.

— Ad —

Google AdSense will appear here after approval

← Back to all articles