Building vulnerability scanning into GitLab

With GitLab Auto DevOps, the container scanning job uses CoreOS Clair to analyze Docker images for vulnerabilities. However, it is not a complete database of all security issues for Alpine-based images. Aqua Trivy has nearly double the number of vulnerabilities and is more suitable for CI. For a detailed comparison, please refer to the Trivy Comparison link in the See also section. This recipe will take you through adding a test stage to a GitLab CI pipeline.

Let's perform the following steps to add Trivy vulnerability checks in GitLab:

  1. Edit the CI/CD pipeline configuration .gitlab-ci.yml file in your project:
$ vim .gitlab-ci.yml
  1. Add a new stage to your pipeline and define the stage. You can find an example in the src/chapter9/devsecops directory. In our example, we're using the vulTest stage name:
stages:
- build
- vulTest
- staging
- production
#Add the Step 3 here
  1. Add the new stage, that is, vulTest. When you define a new stage, you specify a stage name parent key. In our example, the parent key is trivy. The commands in the before_script section will download the trivy binaries:
trivy:
stage: vulTest
image: docker:stable-git
before_script:
- docker build -t trivy-ci-test:${CI_COMMIT_REF_NAME} .
- export VERSION=$(curl --silent "https://api.github.com/repos/aquasecurity/trivy/releases/latest" | grep '"tag_name":' | sed -E 's/.*"v([^"]+)".*/\1/')
- wget https://github.com/aquasecurity/trivy/releases/download/v${VERSION}/trivy_${VERSION}_Linux-64bit.tar.gz
- tar zxvf trivy_${VERSION}_Linux-64bit.tar.gz
variables:
DOCKER_DRIVER: overlay2
allow_failure: true
services:
- docker:stable-dind
#Add the Step 4 here
  1. Finally, review and add the Trivy scan script and complete the vulTest stage. The following script will return --exit-code 1 for the critical severity vulnerabilities, as shown here:
  script:
- ./trivy --exit-code 0 --severity HIGH --no-progress --auto-refresh trivy-ci-test:${CI_COMMIT_REF_NAME}
- ./trivy --exit-code 1 --severity CRITICAL --no-progress --auto-refresh trivy-ci-test:${CI_COMMIT_REF_NAME}
cache:
directories:
- $HOME/.cache/trivy

Now, you can run your pipeline and the new stage will be included in your pipeline. The pipeline will fail if a critical vulnerability is detected. If you don't want the stage to fail your pipeline, you can also specify --exit-code 0 for critical vulnerabilities.