🔒 Security

Trivy

Comprehensive security vulnerability scanner (Aqua Security)

An open-source vulnerability scanner developed by Aqua Security. Detects security vulnerabilities (CVE), misconfigurations, and secrets in container images, file systems, Git repositories, Kubernetes, and IaC (Terraform, CloudFormation). Fast and easy to use, it is a core tool in DevSecOps pipelines.

📖 Detailed Explanation

Trivy is an open-source security scanner developed by Aqua Security and hosted by the CNCF (Cloud Native Computing Foundation). The name is a portmanteau of "tri" (three) and "vy" (vulnerabilities); it originally started by scanning three targets (OS packages, application dependencies, IaC), but it has since evolved into a comprehensive scanner that supports a variety of targets, including containers, filesystems, Git repositories, VM images, and Kubernetes.

Trivy has four main scan targets. Vulnerabilities detects known CVEs by referencing NVD, the GitHub Advisory Database, and others. Misconfigurations checks Terraform, Dockerfile, and Kubernetes manifests for violations of security best practices. Secrets detects whether API keys, passwords, certificates, and the like are exposed in code. Licenses checks whether open-source components comply with their licenses.

Trivy is very simple to install and use. It is distributed as a single binary that runs without dependencies, and you can scan immediately with a simple command such as trivy image nginx:latest. It can download and use the vulnerability DB even in offline environments, and supports various output formats (JSON, SARIF, CycloneDX SBOM). It integrates easily with all major CI/CD platforms such as GitHub Actions, GitLab CI, and Jenkins.

Trivy Operator is a component that continuously performs security scans inside a Kubernetes cluster. It automatically scans all workloads deployed to the cluster and stores the results as Kubernetes CRDs (Custom Resource Definitions). This lets you monitor security posture with kubectl or Prometheus/Grafana. Trivy is rated highly for speed, accuracy, and ease of use compared with other scanners such as Clair and Grype.

💻 Code Example

# Trivy 설치 및 기본 사용법

# 1. 설치
# macOS
brew install trivy

# 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 | sudo apt-key add -
echo deb 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

# Docker로 실행
docker run aquasec/trivy image nginx:latest

# 2. 컨테이너 이미지 스캔
trivy image nginx:latest
trivy image python:3.9-slim
trivy image myregistry.com/myapp:v1.0

# 특정 심각도만 표시
trivy image --severity HIGH,CRITICAL nginx:latest

# 수정 가능한 취약점만 표시
trivy image --ignore-unfixed nginx:latest

# 3. 파일시스템 스캔 (프로젝트 디렉토리)
trivy fs /path/to/project
trivy fs .  # 현재 디렉토리

# 4. Git 저장소 스캔
trivy repo https://github.com/aquasecurity/trivy
trivy repo .  # 로컬 Git 저장소

# 5. SBOM 생성
trivy image --format cyclonedx -o sbom.json nginx:latest
trivy image --format spdx-json -o sbom.spdx.json nginx:latest

# 6. 비밀 정보 스캔
trivy fs --scanners secret /path/to/project
trivy repo --scanners secret https://github.com/org/repo

# 7. 라이선스 스캔
trivy image --scanners license nginx:latest
trivy fs --scanners license /path/to/project

# 8. 출력 형식
trivy image -f json nginx:latest > results.json   # JSON
trivy image -f table nginx:latest                  # 테이블 (기본)
trivy image -f sarif nginx:latest > results.sarif # SARIF (GitHub 연동)
trivy image -f template --template "@html.tpl" nginx:latest > report.html

# 9. 취약점 DB 관리
trivy image --download-db-only              # DB만 다운로드
trivy image --skip-db-update nginx:latest   # DB 업데이트 스킵
trivy image --offline-scan nginx:latest     # 오프라인 모드

# 10. 특정 취약점 무시 (.trivyignore)
# echo "CVE-2023-12345" > .trivyignore
trivy image --ignorefile .trivyignore nginx:latest

# 11. 빌드 실패 조건 설정
trivy image --exit-code 1 --severity CRITICAL nginx:latest
# CRITICAL 취약점이 있으면 exit code 1 반환 (CI/CD에서 빌드 실패)
# Trivy IaC (Infrastructure as Code) 및 설정 스캔

# 1. Terraform 스캔
trivy config /path/to/terraform/
trivy config --tf-vars terraform.tfvars /path/to/terraform/

# 2. Kubernetes 매니페스트 스캔
trivy config /path/to/k8s-manifests/
trivy config deployment.yaml

# 3. Dockerfile 스캔
trivy config --file-patterns "Dockerfile" /path/to/project/

# 4. Helm 차트 스캔
trivy config /path/to/helm-chart/

# 5. CloudFormation 스캔
trivy config /path/to/cloudformation/

# 6. 모든 설정 오류 종류 표시
trivy config --severity LOW,MEDIUM,HIGH,CRITICAL /path/to/config/

# 예시: 발견되는 설정 오류
# - Dockerfile에서 root 사용자로 실행
# - Kubernetes에서 privileged 컨테이너
# - Terraform에서 S3 버킷 암호화 미설정
# - 민감한 환경 변수 하드코딩

# 7. 커스텀 정책 적용 (Rego)
# policies/custom-policy.rego
cat << 'EOF' > policies/no-latest-tag.rego
package appshield.kubernetes.KS001

deny[msg] {
    input.kind == "Deployment"
    container := input.spec.template.spec.containers[_]
    endswith(container.image, ":latest")
    msg := sprintf("Container '%s' uses 'latest' tag", [container.name])
}
EOF

trivy config --policy policies/ /path/to/k8s-manifests/

# 8. 특정 체크 비활성화
trivy config --skip-files "*.test.yaml" /path/to/config/
trivy config --skip-dirs "tests/" /path/to/config/

# 9. Kubernetes 클러스터 직접 스캔
trivy k8s --report summary cluster
trivy k8s --report all --namespace default cluster

# 10. 취약한 Dockerfile 예시와 수정

# 취약한 Dockerfile:
# FROM ubuntu:latest
# RUN apt-get update && apt-get install -y curl
# COPY app /app
# USER root
# CMD ["/app"]

# Trivy 결과:
# - DS001: 'latest' 태그 사용
# - DS002: root 사용자로 실행
# - DS006: apt-get update 후 별도 레이어에서 install

# 수정된 Dockerfile:
# FROM ubuntu:22.04
# RUN apt-get update && apt-get install -y --no-install-recommends curl \
#     && rm -rf /var/lib/apt/lists/*
# RUN useradd -m appuser
# COPY --chown=appuser:appuser app /app
# USER appuser
# CMD ["/app"]
# GitHub Actions - Trivy 통합

name: Security Scan with Trivy

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  trivy-scan:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      security-events: write

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Build Docker image
        run: docker build -t myapp:${{ github.sha }} .

      # 컨테이너 이미지 취약점 스캔
      - name: Scan image for vulnerabilities
        uses: aquasecurity/trivy-action@master
        with:
          image-ref: 'myapp:${{ github.sha }}'
          format: 'sarif'
          output: 'trivy-image-results.sarif'
          severity: 'CRITICAL,HIGH'

      # IaC 스캔 (Terraform, Kubernetes 등)
      - name: Scan IaC for misconfigurations
        uses: aquasecurity/trivy-action@master
        with:
          scan-type: 'config'
          scan-ref: '.'
          format: 'sarif'
          output: 'trivy-config-results.sarif'

      # 파일시스템 스캔 (의존성 취약점)
      - name: Scan filesystem for vulnerabilities
        uses: aquasecurity/trivy-action@master
        with:
          scan-type: 'fs'
          scan-ref: '.'
          format: 'sarif'
          output: 'trivy-fs-results.sarif'

      # GitHub Security 탭에 결과 업로드
      - name: Upload scan results to GitHub Security
        uses: github/codeql-action/upload-sarif@v3
        if: always()
        with:
          sarif_file: 'trivy-image-results.sarif'

      # SBOM 생성
      - name: Generate SBOM
        uses: aquasecurity/trivy-action@master
        with:
          image-ref: 'myapp:${{ github.sha }}'
          format: 'cyclonedx'
          output: 'sbom.json'

      - name: Upload SBOM
        uses: actions/upload-artifact@v4
        with:
          name: sbom
          path: sbom.json

---
# GitLab CI - Trivy 통합

stages:
  - build
  - scan

variables:
  IMAGE_NAME: $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA

build:
  stage: build
  script:
    - docker build -t $IMAGE_NAME .
    - docker push $IMAGE_NAME

trivy-scan:
  stage: scan
  image:
    name: aquasec/trivy:latest
    entrypoint: [""]
  script:
    # 이미지 취약점 스캔
    - trivy image --exit-code 0 --severity HIGH,CRITICAL $IMAGE_NAME
    - trivy image --exit-code 1 --severity CRITICAL $IMAGE_NAME
  allow_failure: false

trivy-config-scan:
  stage: scan
  image:
    name: aquasec/trivy:latest
    entrypoint: [""]
  script:
    - trivy config --exit-code 1 --severity HIGH,CRITICAL .
  allow_failure: true  # 설정 오류는 경고만

---
# Trivy Operator (Kubernetes)

# 1. 설치
helm repo add aqua https://aquasecurity.github.io/helm-charts/
helm repo update
helm install trivy-operator aqua/trivy-operator \
  --namespace trivy-system \
  --create-namespace

# 2. VulnerabilityReport 조회
kubectl get vulnerabilityreports -A

# 3. 특정 워크로드의 취약점 확인
kubectl get vulnerabilityreport -n default -l trivy-operator.resource.name=nginx

# 4. ConfigAuditReport 조회 (설정 오류)
kubectl get configauditreports -A

# 5. RBAC 리포트
kubectl get rbacassessmentreports -A

🗣️ Say It Like This in Practice

💬 In establishing a container security policy
"Every container image must pass a Trivy scan before production deployment. If there is a CRITICAL vulnerability, the build fails, and for HIGH ones a remediation plan must be submitted within 7 days. We automated this by adding trivy image --exit-code 1 --severity CRITICAL to the CI/CD pipeline."
💬 In a vulnerability response meeting
"The Trivy scan found 47 vulnerabilities in total. The 3 CRITICAL ones are openssl vulnerabilities in the base image, which upgrading to alpine:3.19 will fix. 12 of the HIGH ones are application dependencies and can be fixed with npm update. The rest are ones with no fixed version yet, handled with the --ignore-unfixed option."
💬 In an IaC security review
"The Trivy config scan found 15 misconfigurations in the Terraform code, including S3 buckets without encryption, IAM policies with excessive permissions, and security groups allowing 0.0.0.0/0. We also added custom Rego policies to check our organization's security requirements. Since it scans automatically on every PR, we can stop bad configurations from being merged into main."

⚠️ Cautions & Best Practices

❌
Scanning without updating the vulnerability DB

Trivy's vulnerability DB is updated daily. Scanning with an old DB cannot detect the latest CVEs. In CI/CD, manage the cache appropriately and use --skip-db-update only in network-restricted environments.

❌
Ignoring all vulnerabilities

If you add every vulnerability to .trivyignore, the scan becomes meaningless. When ignoring, always document the reason and review regularly. It is good to use VEX (Vulnerability Exploitability eXchange) to explicitly record that "this vulnerability cannot be exploited in our environment."

❌
Scanning only images and skipping IaC/secret scanning

Trivy supports not only vulnerability scanning but also detection of misconfigurations and secrets. Run a comprehensive scan with the --scanners vuln,secret,config option. API keys or passwords hardcoded in Git repositories in particular are a major security threat.

✅
Trivy best practices

Integrate Trivy into every stage of the CI/CD pipeline. Scan images at build time, scan IaC in PRs, and scan periodically in the registry. Monitor Kubernetes clusters continuously with Trivy Operator, and generate SBOMs to track dependencies. Exporting results as SARIF and managing them consistently in the GitHub Security tab is recommended.

🔗 Related Terms

📚 Learn More