The LabDetection
Trivy
Weekly scans of container images and configuration for vulnerabilities, misconfigurations and secrets.
How it connects
Sends to Trivy
- ForgejoThe configuration repositories to scan
- Container registriesThe images those repositories deploy
- Vulnerability databasePublished vulnerabilities, downloaded before each scan
Receives from Trivy
- PrometheusFindings and scan health as metrics, through a Pushgateway
What it does here
Trivy is a scanner. It reads container images and files and reports three kinds of problem: known vulnerabilities in the software an image contains, misconfigurations in infrastructure files, and secrets such as passwords or API tokens left in files.
A known vulnerability is a published weakness in a specific version of a program, usually listed under a CVE number (Common Vulnerabilities and Exposures). Trivy does not test the software. It compares the name and version of every package in an image with a database of published vulnerabilities. Each entry in the database has a severity: low, medium, high or critical.
In the lab, a systemd timer starts a scan script once a week. The script does the work around Trivy and runs it three ways:
- The script fetches the latest state of each configuration repository from Forgejo.
- Trivy checks the Dockerfiles in them for misconfigurations, such as an image that runs its program as root.
- Trivy searches the files of each repository for secrets.
- The script collects every container image named in the Compose files, and Trivy scans each one for known vulnerabilities.
# Misconfigurations in a repository's Dockerfiles.trivy config --format json --output misconfig.json ./repo
# Secrets in the repository's files. The .git folder is skipped.trivy fs --scanners secret --skip-dirs ./repo/.git \ --format json --output secret.json ./repo
# Known vulnerabilities in one image, read from its registry.trivy image --image-src remote --scanners vuln \ --format json --output image.json registry.example.com/app:1.2.3Trivy runs for a while and exits, so Prometheus cannot collect from it the usual way. The script hands its numbers to a Pushgateway, a small service that holds the metrics of short-lived jobs until Prometheus collects them. Alert rules in Prometheus decide what is worth a notification, and a Grafana dashboard shows the full list.
The scan has two limits. It covers what the repositories say should run: a server that still runs an older image than its repository names is not what gets scanned. And Docker Compose files are not among the file types that Trivy’s misconfiguration checks support.
Why Trivy
The three detection tools answer different questions. Trivy lists the known weaknesses in what is deployed, Falco shows what is happening on the servers, and the rules in Loki watch what the logs say.
Trivy suits a small lab:
- One tool for three kinds of finding. Vulnerabilities, misconfigurations and secrets come from one program in one report format.
- No service to keep running. Trivy is a single program that runs and exits. It downloads its vulnerability database when a scan starts, and it reads an image straight from its registry, so the image does not have to be pulled onto a server first.
- Results as JSON. Every report can be written as JSON, which makes the next step possible: comparing this week’s findings with last week’s.
The cost is that a scanner reports everything it finds, every time. The images of a lab carry a long list of known vulnerabilities at any moment, most of them of low severity or without a fix. A finding also says only that a version is on the list, not that the weakness can be used in this setup. Sent as notifications as they are, the findings would soon be ignored. Most of the work is therefore not the scan but deciding what deserves an alert.
From findings to alerts
Only new findings alert
After each scan, the script compares the results with those of the previous scan. A finding counts as the same one when the repository, the image name without its tag, the package, its version and the CVE all match. Leaving the tag out matters: an image that was rebuilt or tagged again and still contains the same package is not news.
A finding is new when one of these is true:
- it was not in the previous scan;
- its severity has gone up, which happens when a rating is revised;
- a fix (a newer version of the package without the weakness) has become available, or the fixed version has changed.
The script publishes the number of new findings as a metric of its own, and the alert rules use only that metric:
# Two rules from a Prometheus rule file.# The scan script publishes trivy_new_vulnerabilities; Trivy does not.- alert: TrivyNewCriticalVuln # One alert for each repository and image with new critical findings. expr: > sum by (repo, image, severity) (trivy_new_vulnerabilities{severity="CRITICAL"}) > 0 # The condition has to hold for 5 minutes before the alert fires. for: 5m
- alert: TrivyNewHighVulnFixable # High severity alerts only when a fix exists. # Without one there is nothing to do yet. expr: > sum by (repo, image, severity) (trivy_new_vulnerabilities{severity="HIGH", has_fix="true"}) > 0 for: 5mAlertmanager collects the alerts of one scan into one message per severity and posts it once. New misconfigurations of critical severity alert the same way.
A finding therefore alerts a single time. In the following scans it is no longer new, so it stays on the dashboard without another message, unless its severity rises or a fix appears. On the first scan, and for an image that is new to the lab, every finding is new.
The dashboard shows all current findings, including those that never alert: findings of medium and low severity, and high ones without a fix.
A secret always alerts
Secrets do not go through the comparison. A secret in a repository’s files raises a critical alert as soon as a scan finds it, and the alert repeats every day until a scan no longer finds it.
The scan reads the files of the latest revision, not the repository’s history. A secret that was committed and removed again is no longer found, but it is still in the history. The fix is therefore to replace the credential, not only to delete the line.
A failed scan must not look like a clean one
If a scan stops halfway and its partial results are published, the findings it never reached look like fixed ones.
The script therefore first lists every report it expects: one for each image, and two for each repository (misconfigurations and secrets). Only when every report exists and is valid are the results published and kept as the baseline for the next comparison. Otherwise the previous results stay in place and the scan is marked as failed.
Two alerts watch the scan itself. One fires when a scan fails or runs longer than its two-hour limit. The other fires when no scan has completed for eight days, or when the metric is missing, for example after the Pushgateway lost its data:
- alert: TrivyScanStale # trivy_scan_timestamp_seconds is the time of the last completed scan. # absent() covers a metric that is gone, not only one that is old. # 86400 * 8 is eight days in seconds. expr: > absent(trivy_scan_timestamp_seconds) or (time() - trivy_scan_timestamp_seconds) > 86400 * 8 for: 1hNotes from running it
One database download for the whole scan
Trivy keeps its vulnerability database up to date on its own when a scan starts. For a run over many images, the script downloads the database once and tells every scan to skip the update, so that all images are judged against the same copy.
This is the complete image scan as the lab runs it. The next note explains three of its options.
# Download the vulnerability database once.trivy image --download-db-only
# Scan one image against that copy: scan_image <image> <report file>scan_image() { trivy image --image-src remote --scanners vuln --skip-db-update \ --parallel 1 --timeout 20m \ --format json --output "$2" "$1"}
scan_image registry.example.com/app:1.2.3 report.jsonOptions for a small scanning machine
Three options of the image scan matter on a machine with little memory:
| Option | Why |
|---|---|
--image-src remote |
Goes straight to the registry. By default Trivy first tries the local Docker, containerd and Podman. |
--parallel 1 |
Works on one thing at a time. With the default of 5, several large image layers were held in memory at once. |
--timeout 20m |
A large image takes longer than the default of 5 minutes. |
The temporary directory matters as well. On many systems /tmp is kept in memory and is
small. Trivy keeps a second database for Java packages, which it fetches when an image
needs it, and in this lab that database did not fit in /tmp. Pointing TMPDIR at a
directory on disk solved it, for example export TMPDIR="$HOME/.cache/trivy/tmp".
Registries are busy at the full hour
A scan that starts exactly on the hour arrives together with everyone else’s scheduled
jobs. One public registry answered 429 Too Many Requests in the first minutes of the
hour on several weekends, and one failed image fails the whole weekly scan.
The script tries each image up to five times, with a longer pause each time. It uses
scan_image from the first note:
# scan_with_retry <image> <report file># Any failure is retried, not only a 429.scan_with_retry() { # Pauses before the second to fifth attempt, in seconds. local delays=(15 30 60 120) attempt=0 until scan_image "$1" "$2"; do # Give up after the last pause has been used. (( attempt < ${#delays[@]} )) || return 1 sleep "${delays[attempt]}" attempt=$(( attempt + 1 )) done}If the retries turn out not to be enough, the next step is to start the scan a few minutes past the hour.
Keep the token out of the command line
The scan clones private repositories with an access token. A token in the clone URL or in an argument is part of the command line, which other users on the machine can see and which often ends up in logs.
Git can take a setting from environment variables instead:
# Defines TOKEN. Only the scan's user can read this file (mode 0600).source ~/.config/scan/env
# Basic authentication with the token as the password.# -w0 keeps the encoded text on one line.# printf is built into the shell, so the token is not an argument of a# new process.auth="$(printf 'x-access-token:%s' "$TOKEN" | base64 -w0)"
# One setting for this command only. http.<URL>.extraheader adds an HTTP# header to requests to that server and to no other.GIT_CONFIG_COUNT=1 \GIT_CONFIG_KEY_0="http.https://git.example.com/.extraheader" \GIT_CONFIG_VALUE_0="AUTHORIZATION: basic ${auth}" \ git clone --quiet --depth=1 --branch main \ https://git.example.com/org/repo.gitAn image that is in no registry
One image in the lab is built on the server that runs it, so there is no registry entry to scan. For that image, the script asks the server which image the running container was started from, exports exactly that image and scans the archive:
# docker-host is the server, "app" the name of the running container.image_id=$(ssh docker-host 'docker inspect --format {{.Image}} app')
# Export that image and scan the archive.ssh docker-host "docker image save $image_id" > app.tartrivy image --input app.tar --scanners vuln --skip-db-update \ --parallel 1 --timeout 20m \ --format json --output report.json