Ir al contenido
  1. Cheatsheets/
  2. Docker/

Trivy

Tabla de contenido

Escaneo rápido

Ejecutar un escaneo rápido de una imagen local y obtener reportes para revisión manual o CI.

# Tabla legible en terminal
trivy image --format table myapp:latest
# JSON para procesar/guardar
trivy image --format json -o report.json myapp:latest
# SARIF para GitHub Code Scanning
trivy image --format sarif -o report.sarif myapp:latest

Ejemplo practico

docker pull alpine:3.20
trivy image --severity CRITICAL,HIGH --format table alpine:3.20

Flags útiles

  • --severity CRITICAL,HIGH filtra ruido
  • --vuln-type os,library selecciona tipo de findings
  • --ignore-unfixed quita CVEs sin fix disponible

Integración CI (snippet)

trivy image \
    --format sarif \
    -o reports/myapp.sarif \
    --severity CRITICAL,HIGH myapp:latest

Errores comunes

  • No usar “extended”: instala Trivy correctamente y verifica trivy -v.
  • Imagen sin tag: usa :latest o tag explícito.

Referencias

Escaneo masivo

Escanear todas las imágenes de contenedores activos en un host.

#!/usr/bin/env bash

set -euo pipefail
OUT=./reports
mkdir -p "$OUT"
for image in $(cat images.txt); do
    # get the name of the file
    file=$(echo $image | awk -F'/' '{print $NF}' | awk -F'/' '{print $1}')
    trivy --cache-dir $HOME/.cache/trivy
        --timeout 1500m image
        --scanners vuln
        --ignore-unfixed -f json -o "$file.json" $image
done

Github Actions

Automatizar el escaneo en PRs y en main con reporte SARIF.

name: Trivy scan
on:
  pull_request:
  push: { branches: [ main ] }

jobs:
  scan:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Set up Trivy
        uses: aquasecurity/trivy-action@v1
      - name: Build image
        run: docker build -t myapp:${{ github.sha }} .
      - name: Scan image (SARIF+JSON)
        run: |
          mkdir -p reports
          trivy image --format sarif -o reports/report.sarif --severity CRITICAL,HIGH myapp:${{ github.sha }} || true
          trivy image --format json -o reports/report.json --severity CRITICAL,HIGH myapp:${{ github.sha }} || true
      - name: Upload SARIF
        if: always()
        uses: github/codeql-action/upload-sarif@v3
        with: { sarif_file: reports/report.sarif }
      - name: Upload artifacts
        if: always()
        uses: actions/upload-artifact@v4
        with: { name: trivy-reports, path: reports/ }

Política de fallo

  • Para bloquear PRs si hay CRITICAL/HIGH, quita los || true y añade --exit-code 1.

Errores comunes

  • No subir SARIF → no verás findings en “Security/Code scanning alerts”.

Formatos de reporte

Entender qué formato usar y cómo almacenarlo como artefacto.

# Tabla (lectura rápida)
trivy image --format table alpine:3.20

# JSON (post-proceso con jq, guardar histórico)
trivy image --format json -o reports/alpine.json alpine:3.20

# SARIF (subir a GitHub Code Scanning)
trivy image --format sarif -o reports/alpine.sarif alpine:3.20
mkdir -p reports
trivy image --format json -o reports/app.json myapp:latest
jq '.[].Results' reports/app.json | head -n 20

Buenas prácticas

  • Guarda JSON+SARIF por build.
  • Nombra archivos con timestamp o commit SHA.

Errores comunes

  • Generar solo table: no sirve para CI.

Referencias

Contenedores en ejecucion

Escanear todas las imágenes de contenedores activos en un host.

Script rápido

#!/usr/bin/env bash

set -euo pipefail
OUT=./reports
mkdir -p "$OUT"
for cid in $(docker ps -q); do
	img=$(docker inspect --format='{{.Config.Image}}' "$cid")
	echo "==> $cid ($img)"
	trivy image --severity CRITICAL,HIGH --format table -o "$OUT/$(echo "$img" | tr '/:' '__').txt" "$img" || true
done

Tips

  • Usa --cache-dir para acelerar.
  • Si ves IDs sin tag, reasigna o usa el ID directo.

Errores comunes

  • Falta permisos Docker → añade tu usuario al grupo docker.

.trivyignore

Ignorar findings específicos de forma documentada y reversible.

Uso básico

Crea .trivyignore en la raíz del repo:

# Ignorar CVE puntual (usa con moderación y motivo)
CVE-2024-12345

# Ignorar por paquete+versión (ejemplo)
pkg:debian/openssl@1.1.1w-1

Política recomendada

  • Cada entrada debe tener ticket/razón/fecha de revisión en comentarios.
  • Revisión quincenal del archivo para evitar “deuda de seguridad”.

Integración CI

Falla solo con severidades altas:

trivy image --severity CRITICAL,HIGH \
    --exit-code 1 --ignore-unfixed \
    --format sarif -o report.sarif myapp:latest

Errores comunes

  • Poner un “catch-all” que silencie todo → basura. Sé quirúrgico.