DevSecOps-Series: Trivy Vulnerability Scanner | Part 3

DevSecOps-Series: Trivy Vulnerability Scanner | Part 3

What is Vulnerability?

As per Wikipedia, “In computer security, a vulnerability is a weakness which can be exploited by a threat actor, such as an attacker, to cross privilege boundaries (i.e. perform unauthorized actions) within a computer system.”

As shown in the above diagram, OS packages and language specific dependencies

What is Trivy

Trivyis a comprehensive security scanner. It is reliable, fast, extremely easy to use, and it works wherever you need it. It comes with differentscannersthat look for different security issues, and differenttargetswhere it can find those issues.

From the documentation it says:

Trivy detects two types of security issues:

  • Vulnerabilities(known vulnerabilities (CVEs), OS package and software dependencies in use (SBOM)

  • Misconfigurations(IaC misconfigurations, Sensitive information and secrets)

Trivy can scan four different artifacts:

Installing Trivy

Installing Trivy is easy, on macOS you can use

brew install trivy

Creating a Docker image

Create a new folder mkdir code

Inside that folder, create a new file app.py

from flask import Flaskapp = Flask(__name__)@app.route('/')def hello_world():  return 'Hello, World! Welcome to the Becoming DevOps guide'if __name__ == "__main__":  app.run(host='0.0.0.0', port=5000)

This is a simple Flask application that prints out “Hello, World! Welcome to the Becoming DevOps guide”.

To dockerize this application, create a Dockerfile

The requirements.txt file contains only one dependency,Flask=2.1.0

FROM python:3.7-alpineWORKDIR /appCOPY requirements.txt /appRUN pip3 install -r requirements.txtCOPY . /appEXPOSE 5000CMD ["python", "app.py"]

Build the Dockerfile with: docker build -t pythonapp .

After a little while the image is built:

REPOSITORY   TAG       IMAGE ID       CREATED         SIZE
pythonapp    latest    7190ca863cca   7 seconds ago   57.1MB

You can test the docker image with:

docker run -itd -p 8000:5000 pythonapp

Open web browser on http://127.0.0.1:8000 to see the printed message.

Push the docker image to Docker Hub

To push an image to Docker Hub, you must first name your local image using your Docker Hub username and the repository name that you created through Docker Hub on the web.

Login to Docker Hub with docker login

Tag the image using your Docker Hub login:

docker tag pythonapp redhaanggara/pythonapp:v1

Push the docker image to Docker Hub.

docker push redhaanggara/pythonapp:v1

Trivy

Now that we have a docker image in place, we can continue with Trivy.

If you just type trivy at the prompt, you will see the help page.

Scanner for vulnerabilities in container images, file systems, and Git repositories, as well as for configuration issues and hard-coded secretsUsage:
  trivy [global flags] command [flags] target
  trivy [command]Examples:
  # Scan a container image
  $ trivy image python:3.4-alpine# Scan a container image from a tar archive
  $ trivy image --input ruby-3.1.tar# Scan local filesystem
  $ trivy fs .# Run in server mode
  $ trivy serverAvailable Commands:
  aws         scan aws account
  config      Scan config files for misconfigurations
  filesystem  Scan local filesystem
  help        Help about any command
  image       Scan a container image
  kubernetes  scan kubernetes cluster
  module      Manage modules
  plugin      Manage plugins
  repository  Scan a remote repository
  rootfs      Scan rootfs
  sbom        Scan SBOM for vulnerabilities
  server      Server mode
  version     Print the version

Scan a container image

Let’s try Trivy on the docker image we just built.

trivy image 71

The output should look something like this:

Scan a filesystem

Scan a filesystem (such as a host machine, a virtual machine image, or an unpacked container image filesystem).

trivy fs --security-checks vuln,secret,config ./

The --security-checks can be configured depending on what you want Trivy to detect. Default is vuln and secret, but above we added config as well.

--security-checks strings   comma-separated list of what security issues to detect (vuln,config,secret,license) (default [vuln,secret]

Ok, now Trivy found something

2022-09-18T19:53:51.860+0200    INFO    Vulnerability scanning is enabled
2022-09-18T19:53:51.860+0200    INFO    Misconfiguration scanning is enabled
2022-09-18T19:53:51.860+0200    INFO    Secret scanning is enabled
2022-09-18T19:53:51.860+0200    INFO    If your scanning is slow, please try '--security-checks vuln' to disable secret scanning
2022-09-18T19:53:51.860+0200    INFO    Please see also https://aquasecurity.github.io/trivy/v0.32/docs/secret/scanning/#recommendation for faster secret detection
2022-09-18T19:53:52.199+0200    INFO    Number of language-specific files: 1
2022-09-18T19:53:52.199+0200    INFO    Detecting pip vulnerabilities...
2022-09-18T19:53:52.202+0200    INFO    Detected config files: 1Dockerfile (dockerfile)Tests: 22 (SUCCESSES: 21, FAILURES: 1, EXCEPTIONS: 0)
Failures: 1 (UNKNOWN: 0, LOW: 0, MEDIUM: 0, HIGH: 1, CRITICAL: 0)HIGH: Specify at least 1 USER command in Dockerfile with non-root user as argument
════════════════════════════════════════════════════════════════════
Running containers with 'root' user can lead to a container escape situation. It is a best practice to run containers as non-root users, which can be done by adding a 'USER' statement to the Dockerfile.See https://avd.aquasec.com/misconfig/ds002

Trivy found a HIGH severity. It gives you a description of the severity and link to aquasec vulnerability database to read how you can fix the problem. That’s pretty great.

You can also tell Trivy to only look for issues that contains the severity HIGH.

trivy fs --security-checks vuln,secret,config  --severity HIGH ./

Scan a Git repository

To scan a remote git repository

trivy repo https://github.com/knqyf263/trivy-ci-test

There are many more things you can do with Trivy and I recommend that you check out the documentation to play around with it some more.

As always, if you found this useful, please hit that clap button and followme to get more articles on your feed. :)

Installation

Easily install Trivy depending on your OS and check this for more info. For homebrew users, just execute the following command.

brew install aquasecurity/trivy/trivy

Run the vulnerability scan

As discussed earlier, the scan can be carried out on container images, file systems and git repositories. Let’s see the basic commands to be executed for each scenarios and what is happening behind the scene.

  • Container Images
trivy image [image-name]

Container image scanning steps — source

  • File systems
trivy fs /path/to/project

File systems scanning steps — source

  • Git repository
trivy repo [github-repo-url]

Remote Git repository scanning steps — source

As shown in above diagrams, when the scan is started, a database (trivy-db) consists of known vulnerabilities will be downloaded to cross check the installed packages of your application and finally output a summary of the security issues as shown in above diagrams. You can skip downloading the vulnerability database by the flag--skip-update if you have recent copy of it.

trivy repo --skip-update [github-repo-url]

Also there can be large file systems or repositories to be scanned which caused exceeding the upper limit of open file descriptors. In that case you can set the ulimit by ulimit -n 1024 . The vulnerabilities can be catagorized based on the severity of them like critical, high, medium etc. The Trivy scanner also output the vulnerabilities accordingly and we can filter out the vulnerabilities according to the severity by the flag --severity HIGH,CRITICAL .

trivy repo --severity HIGH, CRITICAL [github-repo-url]

The Trivy scanner traverse through the directories and files of the given file system and it could be configured to skip files or directories if needed.

trivy repo --skip-files "file1" --skip-files "file2" --skip-dirs "dir1" --skip-dirs "dir2" [github-repo-url]

The Trivy scanner exit with code 0 by default and it can be configured the exit code as 1 only if critical vulnerability is detected as follows. These type of configurations are useful when integrating the Trivy scanner with CI/CD pipelines.

trivy repo --exit-code 1 --severity CRITICAL [github-repo-url]

The output report format could be configured to be as tabular (default), json or custom template.

  • Tabular format on the terminal.

trivy repo -f table [repo-url]

  • JSON output

trivy repo -f json -o results.json [repo-url]

  • Custom template.

trivy repo --format template --template "@html.tpl" -o report.html [repo-url]

Find the “html.tpl” file from here.

There are lot more we can do with Trivy scanner like scanning configurations files like IaC files for detecting misconfigurations.

trivy config [path to IaC files]

Referenfces: https://anaisurl.com/trivy-operator/