Kubernetes Vulnerability Scanning 🔍

Scan container images at build time and enforce admission controls to prevent vulnerable images from running.

Tools

ToolTypeNotes
TrivyOpen source, CI/CD nativeYour primary tool
GrypeOpen source, SBOM supportGood alternative
SnykCommercial, deeper analysisTrial for enterprise
ClairOpen source, air-gappedFor disconnected environments

Trivy in CI/CD

# Scan an image before deploying
trivy image --severity HIGH,CRITICAL my-app:latest
 
# Fail the build on critical vulnerabilities
trivy image --exit-code 1 --severity CRITICAL my-app:latest
 
# Generate SBOM
trivy image --format spdx-json --output sbom.json my-app:latest

GitHub Actions Integration

- name: Scan image
  run: |
    trivy image --severity HIGH,CRITICAL ${{ env.IMAGE_TAG }}
  env:
    IMAGE_TAG: my-registry/my-app:latest

OPA Gatekeeper Admission Control

Block images with critical CVEs at admission time:

apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sVulnClusterConstraint
metadata:
  name: trivy-image-scan
spec:
  match:
    kinds:
    - apiGroups: [""]
      kinds: ["Pod"]
  parameters:
    imageRegistryRegex: ".*"
    severityThreshold: CRITICAL
    maxAge: 24h

Scanning Running Pods

# Find images with vulnerabilities in the cluster
kubectl get pods -A -o json | jq -r '.items[] |
  "\(.metadata.namespace)/\(.metadata.name): \(.spec.containers[].image)"' | \
  while read img; do
    trivy image --severity HIGH,CRITICAL "$img"
  done