Kubernetes Security : Trivy to Scan Docker Images

In this article, we’ll explore how to use Trivy to scan Docker images, ensuring a secure environment for your Kubernetes deployments.

Kubernetes has become a popular choice for container orchestration, enabling organizations to build, deploy, and manage applications with ease. However, the security of containerized applications is crucial, as vulnerabilities can lead to devastating consequences.

Trivy is an open-source vulnerability scanner for Docker images that can help you identify and address security issues.

Docker Image

Before diving into our guide on how to use Trivy to scan Docker images , lets introduce briefly what’s a docker Image :

A Docker image functions as a blueprint for crafting Docker containers. Crafting these images is a flexible process, defined in a Dockerfile, where requirements are specified. Typically, Docker images comprise a foundational base layer, with additional layers as outlined in the Dockerfile.

After executing the ‘Docker run’ command based on a Dockerfile, the resulting image becomes immutable, encapsulating everything necessary for an application to operate, including source code, tools, dependencies, libraries, and essential files.

dockerfile docker image container

An example of a Dockerfile :

FROM python:3.11-slim as build


RUN pip install "poetry==$POETRY_VERSION" \
&& poetry install --no-root --no-ansi --no-interaction \
&& poetry export -f requirements.txt -o requirements.txt


### Final stage
FROM python:3.11-slim as final

WORKDIR /app

COPY --from=build /app/requirements.txt .

RUN pip install -r requirements.txt

Example commands to build our Image and run it :

docker build -t my-docker-build .
docker container run my-docker-build

What is a Vulnerability?

Wikipedia defines a vulnerability as a susceptibility that can be leveraged by a malicious entity, like an attacker, to breach privilege boundaries within a computer system. One of the most well-known identifiers for vulnerabilities is CVE (Common Vulnerability and Exposure). You can find comprehensive information about CVE here.

Examples of CVE :

  1. CVE-2021-34527: This vulnerability affected the Microsoft Windows Print Spooler service and allowed remote attackers to execute malicious code on a target system.
  2. CVE-2020-3452: This vulnerability impacted Cisco devices and involved a path traversal flaw in the web services interface of Cisco Adaptive Security Appliance (ASA) software, allowing unauthorized access to sensitive files.
  3. CVE-2019-0708: Also known as “BlueKeep,” this vulnerability was found in Microsoft Windows Remote Desktop Services and could enable remote code execution without user interaction.
  4. CVE-2017-0144: Commonly referred to as “EternalBlue,” this vulnerability was exploited in the WannaCry ransomware attack. It affected Microsoft Windows systems and allowed for remote code execution.
  5. CVE-2014-0160: Dubbed “Heartbleed,” this OpenSSL vulnerability allowed attackers to read sensitive data from the memory of a web server, potentially exposing user credentials.

There are two primary categories of vulnerabilities: known and unknown. Known Vulnerabilities are those that have been identified and assigned a CVE ID, whereas Unknown Vulnerabilities have not been disclosed or documented yet. Consequently, two types of scanners exist to address these vulnerabilities.

One type scans for components with known vulnerabilities, examples of which include Trivy, Clair, and Aqua. Additionally, we have unknown vulnerability scanners like OWASP ZAP and OSS-Fuzz.

Docker Image Vulnerabilities

Containers have gained prominence in modern application development, surpassing many older technologies. While they are indeed impressive, it’s essential to remember that they are not without their flaws. According to best practices, making assumptions can be risky. Docker images, in particular, can contain vulnerabilities and are not inherently secure.

These vulnerabilities may stem from the packages within the image, the libraries utilized by the user, or even the base image itself. The good news is that most of these issues can be readily addressed , we can many tools such as Trivy to scan Docker images

Here are some examples of Docker image CVEs:

  • CVE-2022-21449: This vulnerability exists in the OpenSSL library, which is used by many Docker images. It allows an attacker to execute arbitrary code on the host machine by exploiting a buffer overflow in the SSL/TLS protocol.
  • CVE-2022-20885: This vulnerability exists in the Nginx web server, which is used by many Docker images. It allows an attacker to execute arbitrary code on the host machine by exploiting a buffer overflow in the HTTP/2 protocol.
  • CVE-2022-1258: This vulnerability exists in the Log4j logging library, which is used by many Docker images. It allows an attacker to execute arbitrary code on the host machine by exploiting a remote code execution vulnerability.
  • CVE-2022-22947: This vulnerability exists in the MySQL database server, which is used by many Docker images. It allows an attacker to gain unauthorized access to the database by exploiting a privilege escalation vulnerability.
  • CVE-2022-22965: This vulnerability exists in the Redis key-value store, which is used by many Docker images. It allows an attacker to execute arbitrary code on the host machine by exploiting a memory corruption vulnerability.

Trivy to scan Docker images

Trivy is a simple and comprehensive vulnerability scanner developed by Aqua Security. It supports scanning for multiple container image formats, including Docker and OCI images, and can be easily integrated into your CI/CD pipeline.

Trivy boasts a high detection rate, low false positives, and support for multiple vulnerability databases, making it an excellent choice for container security.

Features of Trivy Scanner

Trivy holds the following features that you will enjoy using it:

  • Easy installation – apt, yum, apk, Bundler, Composer, pipenv, Poetry, etc.
  • Highly Accurate
  • Detect comprehensive vulnerabilities
  • Simple – Specify only an image name or artefact name
  • Quick – The first scan will finish within 10 seconds (depending on your network). As the consequent scans will finish in single seconds
  • DevSecOps – Appropriate for CI such as Jenkins, Travis CI, GitLab CI, etc
  • Support multiple formats – Including container image, local filesystem, remote git repository

Check our last updated Kubernetes Exam Guides (CKAD , CKA , CKS) :

Installation of Trivy Scanner

Before using Trivy to scan Docker images , let’s install it :

Trivy is available for a variety of platforms, including macOS, Linux, and Windows. In this section, we’ll go through the installation process for each platform and provide examples of installation scripts.

  1. macOS Installation

To install Trivy on macOS, you can use Homebrew, a popular package manager. Run the following command in your terminal:

brew install aquasecurity/trivy/trivy

This command installs Trivy from the Aqua Security Homebrew tap.

  1. Linux Installation

For Linux users, you can use the following script to install Trivy:

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

This script downloads the Trivy installer and places the Trivy binary in /usr/local/bin.

To check run the below command, on successful installation you will get the following output:

 $ trivy
  1. Windows Installation

On Windows, you can install Trivy using the Scoop package manager. First, ensure that you have Scoop installed on your system. If you don’t have Scoop installed, follow the instructions on the Scoop website.

Once Scoop is installed, run the following command in PowerShell:

scoop install trivy

This command installs Trivy using the Scoop package manager.

  1. Docker Installation

Alternatively, you can also use Trivy as a Docker container. To do this, run the following command:

docker pull aquasec/trivy

This command pulls the Trivy Docker image from the Aqua Security Docker repository.

After pulling the Docker image, you can run Trivy as a Docker container using the following command:

docker run --rm -v /path/to/your/cache:/root/.cache/ aquasec/trivy [options] IMAGE_NAME:TAG

Replace /path/to/your/cache with the desired path for Trivy’s cache on your host machine, and replace IMAGE_NAME:TAG with the name and tag of the image you want to scan.

By following these installation steps, you can have Trivy up and running on your preferred platform. Once installed, you can start scanning container images for vulnerabilities and integrate Trivy into your CI/CD pipelines to ensure a secure Kubernetes environment.

Trivy to scan Docker images

Trivy Scan Docker Images

Utilizing Trivy’s open-source container scanner, we’ll identify HIGH and CRITICAL vulnerabilities in Docker images used by pods within the ‘teckbootcamps’ namespace. For this demonstration, I have created several pods as a test.

controlplane $ k get pods -n teckbootcamps 
NAME READY STATUS RESTARTS AGE
busy 0/1 Completed 0 2s
nginx 1/1 Running 0 2m59s

We’ll identify images containing High or Critical severity vulnerabilities and enumerate the Pods that utilize those affected images:

Examine both images individually using Trivy:

  • Busybox Pod :
controlplane $ trivy image -s HIGH,CRITICAL "busybox:1.31.1"

From output , our busybox pod does not exhibit any HIGH or CRITICAL vulnerabilities.

  • Nginx pod : Now let us scan an image for vulnerability in it. In the below scan we are going to scan an nginx image of version 1.19. Therefore perform the below command:
controlplane $ trivy image -s HIGH,CRITICAL "nginx:1.19"

As we can see from the above output, there are a total of 177 vulnerabilities as of the time of scanning (HIGH: 129, CRITICAL: 49).

Trivy to scan Docker images

Trivy K8s command

Trivy Kubernetes scanning is great to get an overview of all the vulnerabilities and misconfiguration issues or to scan specific workloads that are running in your cluster. You would want to use the Trivy K8s command either on your own local cluster or in your CI/CD pipeline post deployments.

The Trivy K8s command is part of the Trivy CLI:

Trivy k8s command

With the following command, we can scan our entire Kubernetes cluster for vulnerabilities and get a summary of the scan: 

❯ trivy k8s --report summary cluster
Trivy k8s scan

To get detailed information for all your resources, replace “summary” with “all”:

trivy k8s –-report all cluster

However, we recommend displaying all information only if you scan a specific namespace or resource, because you can get overwhelmed with additional details.

Furthermore, we can specify the namespace that Trivy is supposed to scan to focus on specific resources in the scan result:

❯ trivy k8s --namespace kube-system --report summary all

Trivy k8s scan

You can use any of the Trivy flags on the Trivy K8s command.

With the Trivy K8s command, you can also scan specific workloads that are running in your cluster, such as our deployment:

trivy k8s --report summary deployment/my-funny-application

Trivy Scan DockerFile

To examine your Dockerfile directly with Trivy, you can execute the following command:

trivy config .

Filter Trivy Scan Results

Trivy offers a range of options for filtering scan results, enabling you to concentrate on specific vulnerabilities or severity levels. This helps streamline the scanning process, allowing you to address the most critical issues first. In this section, we’ll discuss various filtering options provided by Trivy, including filtering by severity, ignoring specific vulnerabilities, and using templates for custom output formats.

  1. Filtering by Severity

To display only vulnerabilities with a specified severity level, such as ‘HIGH’ or ‘CRITICAL’, use the --severity option followed by a comma-separated list of severity levels:

trivy image --severity HIGH,CRITICAL IMAGE_NAME:TAG

For example, to scan an nginx:latest image for ‘HIGH’ and ‘CRITICAL’ vulnerabilities:

trivy image --severity HIGH,CRITICAL nginx:latest

Trivy will display only the vulnerabilities that match the specified severity levels, allowing you to prioritize your security efforts.

2. Ignoring Specific Vulnerabilities

Trivy allows you to ignore specific vulnerabilities using a .trivyignore file. This file should be located in the same directory from which you run the Trivy command. To ignore certain vulnerabilities, list their IDs (e.g., CVE-2020-12345) in the .trivyignore file, one per line:

CVE-2020-12345
CVE-2021-23456

Filtering Scan Results with Trivy

Trivy offers a range of options for filtering scan results, enabling you to concentrate on specific vulnerabilities or severity levels. This helps streamline the scanning process, allowing you to address the most critical issues first. In this section, we’ll discuss various filtering options provided by Trivy, including filtering by severity, ignoring specific vulnerabilities, and using templates for custom output formats.

  1. Filtering by Severity

To display only vulnerabilities with a specified severity level, such as ‘HIGH’ or ‘CRITICAL’, use the --severity option followed by a comma-separated list of severity levels:

trivy image --severity HIGH,CRITICAL IMAGE_NAME:TAG

For example, to scan an nginx:latest image for ‘HIGH’ and ‘CRITICAL’ vulnerabilities:

trivy image --severity HIGH,CRITICAL nginx:latest

Trivy will display only the vulnerabilities that match the specified severity levels, allowing you to prioritize your security efforts.

  1. Ignoring Specific Vulnerabilities

Trivy allows you to ignore specific vulnerabilities using a .trivyignore file. This file should be located in the same directory from which you run the Trivy command. To ignore certain vulnerabilities, list their IDs (e.g., CVE-2020-12345) in the .trivyignore file, one per line:

Copy codeCVE-2020-12345
CVE-2021-23456

When running Trivy, it will skip the vulnerabilities listed in the .trivyignore file, allowing you to focus on the remaining issues.

  1. Using Templates for Custom Output Formats

Trivy supports custom output formats using Go templates. This feature allows you to tailor the output to your specific needs, focusing on particular information or presenting the results in a specific way.

For example, to display only the vulnerability ID, severity, and package name, you can use the following template:

trivy image --format template --template '{{ range .Vulnerabilities }}{{ .VulnerabilityID }} {{ .Severity }} {{ .PkgName }}\n{{ end }}' IMAGE_NAME:TAG

This command will generate an output that includes only the specified information, making it easier to review and prioritize vulnerabilities.

By leveraging Trivy’s filtering options, you can streamline the scanning process and focus on the most critical security issues. This targeted approach allows you to efficiently secure your Docker images and maintain a robust Kubernetes environment.

Trivy Operator

Trivy Operator is a Kubernetes operator that can be used to scan your Kubernetes cluster for vulnerabilities. It does this by automatically scanning your container images for known vulnerabilities and validating your Kubernetes resources against best practices to ensure that your cluster is configured securely.

To use Trivy Operator, you first need to install it on your Kubernetes cluster. You can do this by following the instructions in the Trivy Operator documentation: https://aquasecurity.github.io/trivy-operator/.

Once Trivy Operator is installed, you can start scanning your cluster for vulnerabilities. You can do this by creating a VulnerabilityReport or ConfigAuditReport custom resource. These custom resources specify the resources that you want to scan and the scan options that you want to use.

Trivy Operator will then scan the specified resources and generate a report of the vulnerabilities that it finds. You can view these reports in the Kubernetes API or by using the kubectl command-line tool.

Trivy Operator is a powerful tool that can help you to improve the security of your Kubernetes cluster. By regularly scanning your cluster for vulnerabilities, you can identify and fix any security issues before they can be exploited by attackers.

Here are some additional resources that you may find helpful:

  • Trivy Operator documentation: https://aquasecurity.github.io/trivy-operator/
  • Trivy Operator tutorial: https://mattermost.com/blog/scanning-kubernetes-workloads-using-trivy-operator/
  • Trivy Operator GitHub repository: https://github.com/aquasecurity/trivy-operator

Integrating Trivy into Your CI/CD Pipeline

To enhance your container security, it’s crucial to incorporate vulnerability scanning into your CI/CD pipeline. Trivy can be effortlessly integrated with popular CI/CD platforms such as Jenkins, CircleCI, and GitHub Actions. By including Trivy in your pipeline, you can automatically scan new images before deployment, addressing potential security concerns promptly. In this section, we’ll provide examples of how to integrate Trivy into Jenkins and GitHub Actions.

Jenkins Integration

To integrate Trivy into your Jenkins pipeline, follow these steps:

a. Install the Docker Pipeline plugin in Jenkins, if not already installed.

b. In your Jenkinsfile, add a stage for scanning your Docker image using Trivy. For example:

pipeline {
agent any
stages {
stage('Build Docker Image') {
steps {
sh 'docker build -t my-image:latest .'
}
}
stage('Scan Docker Image') {
steps {
sh 'docker run --rm -v /var/run/docker.sock:/var/run/docker.sock -v ${WORKSPACE}/trivy-cache:/root/.cache/ aquasec/trivy --exit-code 0 --severity LOW,MEDIUM my-image:latest'
sh 'docker run --rm -v /var/run/docker.sock:/var/run/docker.sock -v ${WORKSPACE}/trivy-cache:/root/.cache/ aquasec/trivy --exit-code 1 --severity HIGH,CRITICAL my-image:latest'
}
}
// Additional stages for deployment, testing, etc.
}
}

This Jenkinsfile example first builds the Docker image and then scans it using Trivy. The scan is run twice: once for LOW and MEDIUM severity vulnerabilities, and then again for HIGH and CRITICAL vulnerabilities. If any HIGH or CRITICAL vulnerabilities are found, the pipeline will fail.

GitHub Actions Integration

Integrating Trivy into your GitHub Actions pipeline can help you identify and address vulnerabilities in your Docker images during the build process. Here’s a step-by-step guide on how to incorporate Trivy into your GitHub Actions workflow:

  1. Create a new GitHub Actions workflow file in your repository. If you haven’t already, create a .github/workflows directory in your repository and add a new YAML file, such as trivy-scan.yml.
  2. Configure the workflow to run on specific events, such as a push or a pull request, by adding the following to your trivy-scan.yml file:
name: Trivy Vulnerability Scan

on:
  push:
    branches:
      - main
  pull_request:
    branches:
      - main

This configuration ensures that the Trivy scan will be triggered for both push and pull request events on the main branch.

  1. Define the steps to build the Docker image and scan it using Trivy. Add the following job definition to your trivy-scan.yml file:
jobs:
build-and-scan:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v2

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

- name: Build Docker Image
run: docker build -t my-image:latest .

- name: Install and run Trivy
run: |
curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh | sh -s -- -b /usr/local/bin
trivy --exit-code 0 --severity LOW,MEDIUM my-image:latest
trivy --exit-code 1 --severity HIGH,CRITICAL my-image:latest

This job definition checks out the code, sets up Docker Buildx, builds the Docker image, and scans it using Trivy. As with the other CI/CD platform examples, the scan is run twice: once for LOW and MEDIUM severity vulnerabilities, and then again for HIGH and CRITICAL vulnerabilities. The pipeline will fail if any HIGH or CRITICAL vulnerabilities are found.

  1. Save the trivy-scan.yml file and push it to your repository. Once the file is pushed, GitHub Actions will start running the new workflow based on the specified events.

By integrating Trivy into your GitHub Actions pipeline, you can improve the security of your Docker images and catch vulnerabilities before they become a problem in your Kubernetes environment. This proactive approach to container security is crucial for maintaining the integrity and safety of your applications.

Conclusion

Trivy is a powerful and easy-to-use tool for scanning Docker images, helping you maintain a secure Kubernetes environment.

If you are preparing for Kubernetes certification, check out all certification guides here :

Check last Kubernetes Exams (CKAD , CKA , CKS) Coupon Page to get discounts on certification registration.

Kubernetes Certification Coupon CKAD CKA CKS

Author

  • Mohamed BEN HASSINE

    Mohamed BEN HASSINE is a Hands-On Cloud Solution Architect based out of France. he has been working on Java, Web , API and Cloud technologies for over 12 years and still going strong for learning new things. Actually , he plays the role of Cloud / Application Architect in Paris ,while he is designing cloud native solutions and APIs ( REST , gRPC). using cutting edge technologies ( GCP / Kubernetes / APIGEE / Java / Python )

0 Shares:
You May Also Like
Scaling Kubernetes (GKE / AKS / EKS )
Read More

Scaling Kubernetes by Examples

Table of Contents Hide Scaling a Kubernetes DeploymentUse CaseSolutionImplementing Horizontal Pod AutoscalingUse CaseSolutionAutomating Cluster Scaling in GKEUse CaseSolutionDiscussionDynamically…