mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-12-06 07:34:00 +00:00
Each trivy scan updated the vulnerability database when the database was stale. Six concurrent rescans then downloaded it at the same time. A download took about 11 seconds alone and 38 seconds under contention. Five of six trivy processes crashed with SIGBUS, because they read a database that another process replaced. The other scans hit their timeout. Scans now run with --skip-db-update. A refresh loop updates the database every 6 hours (trivy.db_update_interval). Scans hold a read lock and an update holds the write lock, so an update never replaces the database under a running scan. A scan that finds no database downloads it once before it scans. The grype refresh loop moves to the dbrefresh package, which both scanners use.
334 lines
10 KiB
Go
334 lines
10 KiB
Go
// Package trivy wraps the Aqua Security `trivy` CLI to scan packages for
|
|
// known vulnerabilities and license issues.
|
|
package trivy
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
|
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
|
"github.com/lukaszraczylo/gohoarder/pkg/scanner/dbrefresh"
|
|
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanerr"
|
|
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanver"
|
|
"github.com/lukaszraczylo/gohoarder/pkg/scanner/workdir"
|
|
"github.com/lukaszraczylo/gohoarder/pkg/uuid"
|
|
"github.com/rs/zerolog/log"
|
|
)
|
|
|
|
// ScannerName is the name of this scanner
|
|
const ScannerName = "trivy"
|
|
|
|
// A full download takes about 11s; this bounds a hung one, during which scans wait.
|
|
const dbUpdateTimeout = 10 * time.Minute
|
|
|
|
// Scanner implements the Scanner interface using Trivy
|
|
type Scanner struct {
|
|
version scanver.Cache
|
|
config config.TrivyConfig
|
|
// Scans hold the read lock, updates the write lock: trivy processes that read the database
|
|
// while another replaced it crashed with SIGBUS.
|
|
dbMu sync.RWMutex
|
|
}
|
|
|
|
// TrivyResult represents Trivy JSON output structure
|
|
type TrivyResult struct {
|
|
Metadata TrivyMetadata `json:"Metadata"`
|
|
ArtifactName string `json:"ArtifactName"`
|
|
ArtifactType string `json:"ArtifactType"`
|
|
Results []TrivyVulnResult `json:"Results"`
|
|
SchemaVersion int `json:"SchemaVersion"`
|
|
}
|
|
|
|
type TrivyMetadata struct {
|
|
OS *TrivyOS `json:"OS,omitempty"`
|
|
ImageConfig *TrivyImageConfig `json:"ImageConfig,omitempty"`
|
|
RepoTags []string `json:"RepoTags,omitempty"`
|
|
RepoDigests []string `json:"RepoDigests,omitempty"`
|
|
}
|
|
|
|
type TrivyOS struct {
|
|
Family string `json:"Family"`
|
|
Name string `json:"Name"`
|
|
}
|
|
|
|
type TrivyImageConfig struct {
|
|
Architecture string `json:"architecture"`
|
|
Created string `json:"created"`
|
|
}
|
|
|
|
type TrivyVulnResult struct {
|
|
Target string `json:"Target"`
|
|
Class string `json:"Class"`
|
|
Type string `json:"Type"`
|
|
Vulnerabilities []TrivyVulnerability `json:"Vulnerabilities"`
|
|
}
|
|
|
|
type TrivyVulnerability struct {
|
|
VulnerabilityID string `json:"VulnerabilityID"`
|
|
PkgName string `json:"PkgName"`
|
|
InstalledVersion string `json:"InstalledVersion"`
|
|
FixedVersion string `json:"FixedVersion"`
|
|
Severity string `json:"Severity"`
|
|
Title string `json:"Title"`
|
|
Description string `json:"Description"`
|
|
PrimaryURL string `json:"PrimaryURL"`
|
|
References []string `json:"References"`
|
|
}
|
|
|
|
// New creates a new Trivy scanner
|
|
func New(cfg config.TrivyConfig) *Scanner {
|
|
return &Scanner{
|
|
config: cfg,
|
|
}
|
|
}
|
|
|
|
// Name returns the scanner name
|
|
func (s *Scanner) Name() string {
|
|
return ScannerName
|
|
}
|
|
|
|
// UpdateDatabase updates Trivy's vulnerability database. It waits for running scans, and
|
|
// scans wait for it.
|
|
func (s *Scanner) UpdateDatabase(ctx context.Context) error {
|
|
s.dbMu.Lock()
|
|
defer s.dbMu.Unlock()
|
|
return s.download(ctx)
|
|
}
|
|
|
|
// RefreshDatabase updates the database every interval until stop closes. immediate runs
|
|
// the first update at once; otherwise it waits one interval. interval 0 means 6h.
|
|
func (s *Scanner) RefreshDatabase(stop <-chan struct{}, interval time.Duration, immediate bool) {
|
|
dbrefresh.Run(stop, interval, immediate, ScannerName, s.UpdateDatabase)
|
|
}
|
|
|
|
// ensureDatabase downloads the database when the cache has none: a scan never updates it.
|
|
func (s *Scanner) ensureDatabase(ctx context.Context) error {
|
|
if s.hasDatabase() {
|
|
return nil
|
|
}
|
|
s.dbMu.Lock()
|
|
defer s.dbMu.Unlock()
|
|
if s.hasDatabase() {
|
|
return nil
|
|
}
|
|
return s.download(ctx)
|
|
}
|
|
|
|
// hasDatabase reports whether trivy's cache dir holds a vulnerability database.
|
|
func (s *Scanner) hasDatabase() bool {
|
|
dir := s.config.CacheDB
|
|
if dir == "" {
|
|
dir = os.Getenv("TRIVY_CACHE_DIR")
|
|
}
|
|
if dir == "" {
|
|
cache, err := os.UserCacheDir()
|
|
if err != nil {
|
|
return false
|
|
}
|
|
dir = filepath.Join(cache, "trivy")
|
|
}
|
|
_, err := os.Stat(filepath.Join(dir, "db", "trivy.db")) // #nosec G703 -- cache dir from config or env
|
|
return err == nil
|
|
}
|
|
|
|
// download runs the database update. The caller holds the write lock.
|
|
func (s *Scanner) download(ctx context.Context) error {
|
|
log.Info().Msg("Updating Trivy vulnerability database")
|
|
|
|
wd, err := workdir.New(ScannerName)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer wd.Remove()
|
|
ctx, cancel := context.WithTimeout(ctx, dbUpdateTimeout)
|
|
defer cancel()
|
|
cmd := exec.CommandContext(ctx, "trivy", "image", "--download-db-only")
|
|
cmd.Env = s.env(wd)
|
|
|
|
output, err := cmd.CombinedOutput()
|
|
if err != nil {
|
|
return fmt.Errorf("failed to update Trivy database: %w (output: %s)", err, string(output))
|
|
}
|
|
|
|
log.Info().Msg("Trivy vulnerability database updated successfully")
|
|
return nil
|
|
}
|
|
|
|
// Scan scans a package for vulnerabilities using Trivy
|
|
func (s *Scanner) Scan(ctx context.Context, registry, packageName, version string, filePath string) (*metadata.ScanResult, error) {
|
|
if err := s.ensureDatabase(ctx); err != nil {
|
|
return nil, fmt.Errorf("%w: %w", scanerr.ErrInfrastructure, err)
|
|
}
|
|
s.dbMu.RLock()
|
|
defer s.dbMu.RUnlock()
|
|
|
|
// Set timeout
|
|
if s.config.Timeout > 0 {
|
|
var cancel context.CancelFunc
|
|
ctx, cancel = context.WithTimeout(ctx, s.config.Timeout)
|
|
defer cancel()
|
|
}
|
|
|
|
wd, err := workdir.New(ScannerName)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer wd.Remove()
|
|
|
|
scanType := s.determineScanType(registry, filePath)
|
|
target := filePath
|
|
if registry == "npm" {
|
|
// trivy does not unpack archives; the node-pkg analyzer needs an installed tree.
|
|
if target, err = unpackNPM(wd.Path(), filePath, packageName); err != nil {
|
|
return nil, fmt.Errorf("prepare npm package for trivy: %w", err)
|
|
}
|
|
}
|
|
|
|
args := []string{
|
|
scanType,
|
|
"--format", "json",
|
|
"--quiet",
|
|
"--skip-db-update", // RefreshDatabase owns updates
|
|
target,
|
|
}
|
|
|
|
cmd := exec.CommandContext(ctx, "trivy", args...) // #nosec G204 -- trivy command with controlled arguments
|
|
cmd.Env = s.env(wd)
|
|
|
|
// Execute scan
|
|
output, err := cmd.Output()
|
|
if err != nil {
|
|
// Check if it's a timeout
|
|
if ctx.Err() == context.DeadlineExceeded {
|
|
return &metadata.ScanResult{
|
|
ID: uuid.New().String(),
|
|
Registry: registry,
|
|
PackageName: packageName,
|
|
PackageVersion: version,
|
|
Scanner: s.Name(),
|
|
ScannedAt: time.Now(),
|
|
Status: metadata.ScanStatusError,
|
|
Details: scanerr.ErrorDetails("scan timeout", true),
|
|
}, nil
|
|
}
|
|
|
|
return nil, fmt.Errorf("trivy scan failed: %w", err)
|
|
}
|
|
|
|
// Parse Trivy output
|
|
var trivyResult TrivyResult
|
|
if err := json.Unmarshal(output, &trivyResult); err != nil {
|
|
return nil, fmt.Errorf("failed to parse Trivy output: %w", err)
|
|
}
|
|
|
|
// Convert to metadata.ScanResult
|
|
return s.convertTrivyResult(&trivyResult, registry, packageName, version), nil
|
|
}
|
|
|
|
// env runs trivy in wd, with the configured cache dir.
|
|
func (s *Scanner) env(wd *workdir.Dir) []string {
|
|
env := wd.Env(os.Environ())
|
|
if s.config.CacheDB != "" {
|
|
env = append(env, "TRIVY_CACHE_DIR="+s.config.CacheDB)
|
|
}
|
|
return env
|
|
}
|
|
|
|
// determineScanType determines the appropriate Trivy scan type
|
|
func (s *Scanner) determineScanType(registry, filePath string) string {
|
|
// For now, use filesystem scan for packages
|
|
// Container image scanning would need different handling
|
|
ext := strings.ToLower(filePath[strings.LastIndex(filePath, ".")+1:])
|
|
|
|
switch registry {
|
|
case "npm":
|
|
return "rootfs" // rootfs enables the node-pkg analyzer; fs reads lockfiles only
|
|
case "pypi":
|
|
return "fs" // Filesystem scan for Python packages
|
|
case "go":
|
|
return "fs" // Filesystem scan for Go modules
|
|
default:
|
|
// Check file extension
|
|
if ext == "tar" || ext == "tgz" || ext == "gz" {
|
|
return "fs"
|
|
}
|
|
return "fs"
|
|
}
|
|
}
|
|
|
|
// convertTrivyResult converts Trivy result to metadata.ScanResult
|
|
func (s *Scanner) convertTrivyResult(trivyResult *TrivyResult, registry, packageName, version string) *metadata.ScanResult {
|
|
vulnerabilities := make([]metadata.Vulnerability, 0)
|
|
severityCounts := make(map[string]int)
|
|
|
|
// Aggregate all vulnerabilities from all results
|
|
for _, result := range trivyResult.Results {
|
|
for _, vuln := range result.Vulnerabilities {
|
|
// Normalize severity to standard values (CRITICAL, HIGH, MODERATE, LOW)
|
|
normalizedSeverity := metadata.NormalizeSeverity(vuln.Severity)
|
|
|
|
// Count by severity
|
|
severityCounts[normalizedSeverity]++
|
|
|
|
// Add to vulnerabilities list
|
|
vulnerabilities = append(vulnerabilities, metadata.Vulnerability{
|
|
ID: vuln.VulnerabilityID,
|
|
Severity: normalizedSeverity,
|
|
Title: vuln.Title,
|
|
Description: vuln.Description,
|
|
References: vuln.References,
|
|
FixedIn: vuln.FixedVersion,
|
|
Aliases: metadata.NormalizeAliases(vuln.VulnerabilityID, metadata.ExtractAdvisoryIDs(append([]string{vuln.PrimaryURL}, vuln.References...)...)...),
|
|
})
|
|
}
|
|
}
|
|
|
|
// Determine overall status
|
|
status := metadata.ScanStatusClean
|
|
if len(vulnerabilities) > 0 {
|
|
status = metadata.ScanStatusVulnerable
|
|
}
|
|
|
|
return &metadata.ScanResult{
|
|
ID: uuid.New().String(),
|
|
Registry: registry,
|
|
PackageName: packageName,
|
|
PackageVersion: version,
|
|
Scanner: s.Name(),
|
|
ScannedAt: time.Now(),
|
|
Status: status,
|
|
VulnerabilityCount: len(vulnerabilities),
|
|
Vulnerabilities: vulnerabilities,
|
|
Details: map[string]interface{}{
|
|
"artifact_name": trivyResult.ArtifactName,
|
|
"artifact_type": trivyResult.ArtifactType,
|
|
"severity_counts": severityCounts,
|
|
},
|
|
}
|
|
}
|
|
|
|
// Health checks if Trivy is available and working
|
|
func (s *Scanner) Health(ctx context.Context) error {
|
|
// Check if trivy command exists
|
|
cmd := exec.CommandContext(ctx, "trivy", "--version")
|
|
output, err := cmd.CombinedOutput()
|
|
if err != nil {
|
|
return fmt.Errorf("trivy not available: %w (output: %s)", err, string(output))
|
|
}
|
|
|
|
s.version.Record(string(output))
|
|
log.Debug().Str("version", strings.TrimSpace(string(output))).Msg("Trivy health check passed")
|
|
return nil
|
|
}
|
|
|
|
// Version returns the version the last successful health check reported.
|
|
func (s *Scanner) Version() string { return s.version.Version() }
|