5.5: Container Security with AI

What You'll Learn

  • Understand AI-powered container security scanning tools and techniques
  • Learn how to integrate Docker Scout, Trivy, and Snyk into CI/CD pipelines
  • Master SBOM (Software Bill of Materials) generation for compliance
  • Implement comprehensive security scanning strategies for containerized applications

16.05.1 Docker Scout - AI-Powered Security

Overview

Docker Scout is Docker's official AI-powered vulnerability scanning and policy management tool that provides intelligent security insights for container images.

Note: Docker Scout features and CLI commands evolve. Verify commands with docker scout --help or official documentation.

Official Documentation: https://docs.docker.com/scout/

Key Features

  1. CVE Detection: Automatically scans for known vulnerabilities
  2. AI-Powered Analysis: Intelligent prioritization based on exploitability
  3. Policy Enforcement: Custom security policies for images
  4. SBOM Generation: Software Bill of Materials for compliance
  5. Remediation Guidance: Automated fix recommendations

Installation and Setup

# Install Docker Scout CLI
docker scout version

# Enable Docker Scout (requires Docker Desktop or CLI plugin)
docker scout enroll <organization>

# Quick scan of an image
docker scout cves <image>

# View detailed recommendations
docker scout recommendations <image>

# Compare images
docker scout compare --to <image1> <image2>

Basic Usage

# Analyze vulnerabilities
docker scout cves <image>

# Filter by severity
docker scout cves --only-severity critical,high <image>

# Export SBOM
docker scout sbom --format json <image> > sbom.json

# Policy evaluation
docker scout policy <image>

# Get CVE details
docker scout cves --format markdown <image>

# Quick view
docker scout quickview <image>

Dockerfile Best Practices for Scout

# syntax=docker/dockerfile:1.4

# Use specific version tags (not 'latest')
FROM python:3.11.7-slim-bookworm as base

# Add metadata for Scout
LABEL org.opencontainers.image.source="https://github.com/user/repo"
LABEL org.opencontainers.image.description="Production app"
LABEL org.opencontainers.image.version="1.0.0"

# Non-root user for security
RUN useradd -m -u 1000 appuser

WORKDIR /app

# Update packages to fix known CVEs
RUN apt-get update && apt-get upgrade -y && \
    apt-get install -y --no-install-recommends \
    ca-certificates && \
    rm -rf /var/lib/apt/lists/*

COPY --chown=appuser:appuser requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY --chown=appuser:appuser . .

USER appuser

CMD ["python", "app.py"]

CI/CD Integration

GitHub Actions with Scout

name: Docker Scout Scan

on: [push, pull_request]

jobs:
  scout-scan:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

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

      - name: Docker Scout scan
        uses: docker/scout-action@v1
        with:
          command: cves
          image: myapp:${{ github.sha }}
          only-severities: critical,high
          exit-code: true

      - name: Scout recommendations
        uses: docker/scout-action@v1
        with:
          command: recommendations
          image: myapp:${{ github.sha }}

GitLab CI with Scout

scout:scan:
  stage: security
  image: docker:24
  services:
    - docker:24-dind
  script:
    - docker scout cves $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA --exit-code --only-severity critical,high
    - docker scout recommendations $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA
  allow_failure: false

16.05.2 Trivy - Comprehensive Security Scanner

Overview

Trivy is an open-source, comprehensive security scanner developed by Aqua Security that provides intelligent vulnerability detection for containers, filesystems, and Kubernetes.

Official Documentation: https://aquasecurity.github.io/trivy/

Installation

# Install Trivy
curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh | sh -s -- -b /usr/local/bin

# Scan image for vulnerabilities
trivy image python:3.11

# Scan with severity filtering
trivy image --severity HIGH,CRITICAL python:3.11

# Generate JSON report
trivy image --format json --output results.json myapp:latest

# Scan filesystem
trivy fs --security-checks vuln,config,secret .

# Scan Kubernetes manifests
trivy config k8s-deployment.yaml

# SBOM generation
trivy image --format cyclonedx --output sbom.json myapp:latest

Configuration File

.trivy.yaml:

# Severity levels to report
severity:
  - CRITICAL
  - HIGH
  - MEDIUM

# Vulnerability DB
db:
  repository: ghcr.io/aquasecurity/trivy-db

# Skip certain vulnerabilities
ignore-unfixed: true

# Secret scanning
secret:
  config: trivy-secret.yaml

# Custom policies
policy:
  - policy/my-policy.rego

CI/CD Integration

GitHub Actions - Trivy Scan

name: Trivy Security Scan

on: [push, pull_request]

jobs:
  trivy-scan:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

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

      - name: Run Trivy vulnerability scanner
        uses: aquasecurity/trivy-action@master
        with:
          image-ref: myapp:${{ github.sha }}
          format: 'sarif'
          output: 'trivy-results.sarif'
          severity: 'CRITICAL,HIGH'
          exit-code: '1'

      - name: Upload Trivy results to GitHub Security
        uses: github/codeql-action/upload-sarif@v2
        if: always()
        with:
          sarif_file: 'trivy-results.sarif'

      - 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@v3
        with:
          name: sbom
          path: sbom.json

GitLab CI - Trivy Scan

include:
  - template: Security/Container-Scanning.gitlab-ci.yml

variables:
  CS_IMAGE: $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA

trivy-scan:
  stage: security
  image: aquasec/trivy:latest
  script:
    - trivy image --exit-code 1 --severity HIGH,CRITICAL $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA
  allow_failure: false

Jenkins Pipeline - Trivy Scan

pipeline {
    agent any

    environment {
        IMAGE_NAME = "myapp:${env.BUILD_NUMBER}"
    }

    stages {
        stage('Build') {
            steps {
                sh 'docker build -t ${IMAGE_NAME} .'
            }
        }

        stage('Security Scan - Trivy') {
            steps {
                sh '''
                    trivy image --exit-code 1 \
                        --severity CRITICAL,HIGH \
                        --format json \
                        --output trivy-report.json \
                        ${IMAGE_NAME}
                '''
            }
        }

        stage('Generate SBOM') {
            steps {
                sh 'trivy image --format cyclonedx --output sbom.json ${IMAGE_NAME}'
                archiveArtifacts artifacts: 'sbom.json', fingerprint: true
            }
        }
    }

    post {
        always {
            publishHTML([
                reportDir: '.',
                reportFiles: 'trivy-report.json',
                reportName: 'Trivy Security Scan'
            ])
        }
    }
}

16.05.3 Snyk Container Security

Overview

Snyk Container provides AI-powered container security with intelligent vulnerability detection, prioritization, and automated remediation guidance.

Official Documentation: https://docs.snyk.io/products/snyk-container

Installation and Setup

# Install Snyk CLI
npm install -g snyk

# Authenticate
snyk auth

# Scan Docker image
snyk container test myapp:latest

# Monitor image in Snyk dashboard
snyk container monitor myapp:latest

# Test with Dockerfile analysis
snyk container test myapp:latest --file=Dockerfile

# JSON output
snyk container test myapp:latest --json > snyk-results.json

# Scan for base image recommendations
snyk container test myapp:latest --print-deps

Snyk Policy File

.snyk:

version: v1.22.0
ignore:
  SNYK-PYTHON-PILLOW-12345:
    - '*':
        reason: False positive, not exploitable in our context
        expires: 2025-12-31T00:00:00.000Z

patch: {}

exclude:
  global:
    - test/**
    - docs/**

AI-Enhanced Features

DeepCode AI: Machine learning-based code analysis

Priority Score: AI-calculated risk prioritization

Auto-fix: Automated remediation suggestions

False Positive Reduction: ML-based filtering

CI/CD Integration

GitHub Actions - Snyk Scan

name: Snyk Security Scan

on: [push]

jobs:
  snyk:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Build image
        run: docker build -t myapp:latest .

      - name: Run Snyk to check Docker image
        uses: snyk/actions/docker@master
        env:
          SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
        with:
          image: myapp:latest
          args: --severity-threshold=high --file=Dockerfile

      - name: Upload Snyk results to GitHub Code Scanning
        uses: github/codeql-action/upload-sarif@v2
        with:
          sarif_file: snyk.sarif

GitLab CI - Snyk Scan

snyk-scan:
  stage: security
  image: snyk/snyk:docker
  script:
    - snyk auth $SNYK_TOKEN
    - snyk container test $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA --severity-threshold=high
  allow_failure: true

16.05.4 Grype - Vulnerability Scanner

Overview

Grype is a vulnerability scanner for container images and filesystems, developed by Anchore.

Installation and Usage

# Install Grype
curl -sSfL https://raw.githubusercontent.com/anchore/grype/main/install.sh | sh -s -- -b /usr/local/bin

# Scan image
grype myapp:latest

# Output formats
grype myapp:latest -o json
grype myapp:latest -o cyclonedx > sbom.xml
grype myapp:latest -o table

# Scan by digest
grype registry:myapp@sha256:abc123...

# Scan local directory
grype dir:.

16.05.5 Comprehensive Security Pipeline

Multi-Scanner Approach

name: Comprehensive Security Scan

on: [push, pull_request]

jobs:
  build:
    runs-on: ubuntu-latest
    outputs:
      image-digest: ${{ steps.build.outputs.digest }}
    steps:
      - uses: actions/checkout@v4

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Build image
        id: build
        uses: docker/build-push-action@v5
        with:
          context: .
          tags: myapp:${{ github.sha }}
          outputs: type=docker,dest=/tmp/myapp.tar

      - name: Upload artifact
        uses: actions/upload-artifact@v3
        with:
          name: myapp
          path: /tmp/myapp.tar

  trivy-scan:
    needs: build
    runs-on: ubuntu-latest
    steps:
      - name: Download artifact
        uses: actions/download-artifact@v3
        with:
          name: myapp
          path: /tmp

      - name: Load image
        run: docker load --input /tmp/myapp.tar

      - name: Run Trivy scanner
        uses: aquasecurity/trivy-action@master
        with:
          image-ref: myapp:${{ github.sha }}
          format: 'sarif'
          output: 'trivy-results.sarif'
          severity: 'CRITICAL,HIGH'

      - name: Upload to Security tab
        uses: github/codeql-action/upload-sarif@v2
        with:
          sarif_file: 'trivy-results.sarif'

  snyk-scan:
    needs: build
    runs-on: ubuntu-latest
    steps:
      - name: Download artifact
        uses: actions/download-artifact@v3
        with:
          name: myapp
          path: /tmp

      - name: Load image
        run: docker load --input /tmp/myapp.tar

      - name: Run Snyk scanner
        uses: snyk/actions/docker@master
        env:
          SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
        with:
          image: myapp:${{ github.sha }}
          args: --file=Dockerfile

  scout-scan:
    needs: build
    runs-on: ubuntu-latest
    steps:
      - name: Download artifact
        uses: actions/download-artifact@v3
        with:
          name: myapp
          path: /tmp

      - name: Load image
        run: docker load --input /tmp/myapp.tar

      - name: Docker Scout scan
        uses: docker/scout-action@v1
        with:
          command: cves
          image: myapp:${{ github.sha }}
          only-severities: critical,high
          exit-code: false

  sbom-generation:
    needs: build
    runs-on: ubuntu-latest
    steps:
      - name: Download artifact
        uses: actions/download-artifact@v3
        with:
          name: myapp
          path: /tmp

      - name: Load image
        run: docker load --input /tmp/myapp.tar

      - name: Generate SBOM with Syft
        uses: anchore/sbom-action@v0
        with:
          image: myapp:${{ github.sha }}
          format: cyclonedx-json
          output-file: sbom.json

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

16.05.6 SBOM Generation and Management

What is SBOM?

A Software Bill of Materials (SBOM) is a comprehensive inventory of all components, libraries, and dependencies in a software application.

SBOM Formats

  • CycloneDX: Modern, comprehensive format
  • SPDX: Software Package Data Exchange
  • SWID: Software Identification Tags

Generating SBOMs

Syft (Anchore)

# Install Syft
curl -sSfL https://raw.githubusercontent.com/anchore/syft/main/install.sh | sh -s -- -b /usr/local/bin

# Generate SBOM
syft packages myapp:latest -o cyclonedx-json > sbom.json

# Multiple formats
syft packages myapp:latest -o spdx-json > sbom-spdx.json
syft packages myapp:latest -o table

Trivy SBOM

# Generate CycloneDX SBOM
trivy image --format cyclonedx myapp:latest > sbom.json

# Generate SPDX SBOM
trivy image --format spdx myapp:latest > sbom-spdx.json

Docker Scout SBOM

# Generate SBOM
docker scout sbom --format cyclonedx myapp:latest > sbom.json

SBOM in CI/CD

name: SBOM Generation

on:
  push:
    tags: ['v*']

jobs:
  generate-sbom:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

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

      - name: Generate SBOM
        uses: anchore/sbom-action@v0
        with:
          image: myapp:${{ github.ref_name }}
          format: cyclonedx-json
          output-file: sbom.json

      - name: Attach SBOM to release
        uses: softprops/action-gh-release@v1
        with:
          files: sbom.json

16.05.7 Best Practices

1. Security Scanning Strategy

Multi-Layered Approach:

  • Scan at build time (pre-production)
  • Scan at deploy time (production readiness)
  • Continuous scanning (runtime monitoring)

Severity Thresholds:

# Fail on CRITICAL/HIGH
trivy image --exit-code 1 --severity CRITICAL,HIGH myapp:latest

# Warn on MEDIUM
trivy image --exit-code 0 --severity MEDIUM myapp:latest

2. Policy as Code

Example Policy (OPA/Rego):

package docker.security

deny[msg] {
    input.User == "root"
    msg = "Container should not run as root"
}

deny[msg] {
    not input.Healthcheck
    msg = "Container must have a healthcheck"
}

deny[msg] {
    vulnerability := input.Vulnerabilities[_]
    vulnerability.Severity == "CRITICAL"
    msg = sprintf("Critical vulnerability found: %s", [vulnerability.CVE])
}

3. Continuous Monitoring

# Schedule regular scans
name: Scheduled Security Scan

on:
  schedule:
    - cron: '0 2 * * *'  # Daily at 2 AM

jobs:
  scan:
    runs-on: ubuntu-latest
    steps:
      - name: Pull latest image
        run: docker pull myapp:latest

      - name: Scan for new vulnerabilities
        run: trivy image myapp:latest

4. False Positive Management

Trivy Ignore File (.trivyignore):

# Ignore specific CVEs
CVE-2023-12345

# Ignore by package
pkg:pypi/vulnerable-package@1.0.0

# Ignore with expiration
CVE-2023-67890 # expires: 2025-12-31

5. Integration with Security Tools

SIEM Integration:

# Export to SIEM
trivy image --format json myapp:latest | \
  curl -X POST -H "Content-Type: application/json" \
  -d @- https://siem.example.com/api/vulnerabilities

Summary

Container security is critical for modern application deployment, and AI-powered tools significantly enhance vulnerability detection, prioritization, and remediation. By implementing a multi-scanner approach using Docker Scout, Trivy, and Snyk, teams can achieve comprehensive security coverage with intelligent threat analysis.

Key takeaways:

  • Use multiple scanners for comprehensive coverage
  • Generate and maintain SBOMs for compliance
  • Implement policy-as-code for consistent enforcement
  • Automate security scanning in CI/CD pipelines
  • Continuously monitor deployed containers
  • Prioritize vulnerabilities using AI-powered risk scores

Effective container security requires a defense-in-depth strategy, combining automated scanning, policy enforcement, and continuous monitoring throughout the software development lifecycle.

References