Static Application Security Testing (SAST)

Introduced in GitLab Ultimate 10.3.

4 of the top 6 attacks were application based. Download our whitepaper, “A Seismic Shift in Application Security” to learn how to protect your organization.

Overview

If you are using GitLab CI/CD, you can analyze your source code for known vulnerabilities using Static Application Security Testing (SAST).

You can take advantage of SAST by either including the CI job in your existing .gitlab-ci.yml file or by implicitly using Auto SAST that is provided by Auto DevOps.

GitLab checks the SAST report, compares the found vulnerabilities between the source and target branches, and shows the information right on the merge request.

SAST Widget

The results are sorted by the priority of the vulnerability:

  1. Critical
  2. High
  3. Medium
  4. Low
  5. Unknown
  6. Everything else

Use cases

  • Your code has a potentially dangerous attribute in a class, or unsafe code that can lead to unintended code execution.
  • Your application is vulnerable to cross-site scripting (XSS) attacks that can be leveraged to unauthorized access to session data.

Requirements

To run a SAST job, by default, you need GitLab Runner with the docker or kubernetes executor running in privileged mode. If you’re using the shared Runners on GitLab.com, this is enabled by default.

Privileged mode is not necessary if you’ve disabled Docker in Docker for SAST

Caution: Our SAST jobs currently expect a Linux container type. Windows containers are not yet supported.
Caution: If you use your own Runners, make sure that the Docker version you have installed is not 19.03.00. See troubleshooting information for details.

Supported languages and frameworks

The following table shows which languages, package managers and frameworks are supported and which tools are used.

Language (package managers) / frameworkScan toolIntroduced in GitLab Version
.NETSecurity Code Scan11.0
AnyGitleaks and TruffleHog11.9
Apex (Salesforce)pmd12.1
C/C++Flawfinder10.7
Elixir (Phoenix)Sobelow11.10
GoGosec10.7
Groovy (Ant, Gradle, Maven and SBT)SpotBugs with the find-sec-bugs plugin11.3 (Gradle) & 11.9 (Ant, Maven, SBT)
Java (Ant, Gradle, Maven and SBT)SpotBugs with the find-sec-bugs plugin10.6 (Maven), 10.8 (Gradle) & 11.9 (Ant, SBT)
JavaScriptESLint security plugin11.8
Kubernetes manifestsKubesec12.6
Node.jsNodeJsScan11.1
PHPphpcs-security-audit10.8
Python (pip)bandit10.3
ReactESLint react plugin12.5
Ruby on Railsbrakeman10.3
Scala (Ant, Gradle, Maven and SBT)SpotBugs with the find-sec-bugs plugin11.0 (SBT) & 11.9 (Ant, Gradle, Maven)
TypeScriptTSLint config security11.9
Note: The Java analyzers can also be used for variants like the Gradle wrapper, Grails and the Maven wrapper.

Configuration

For GitLab 11.9 and later, to enable SAST, you must include the SAST.gitlab-ci.yml template that’s provided as a part of your GitLab installation. For GitLab versions earlier than 11.9, you can copy and use the job as defined that template.

Add the following to your .gitlab-ci.yml file:

include:
  - template: SAST.gitlab-ci.yml

The included template will create a sast job in your CI/CD pipeline and scan your project’s source code for possible vulnerabilities.

The results will be saved as a SAST report artifact that you can later download and analyze. Due to implementation limitations, we always take the latest SAST artifact available. Behind the scenes, the GitLab SAST Docker image is used to detect the languages/frameworks and in turn runs the matching scan tools.

Customizing the SAST settings

The SAST settings can be changed through environment variables by using the variables parameter in .gitlab-ci.yml.

In the following example, we include the SAST template and at the same time we set the SAST_GOSEC_LEVEL variable to 2:

include:
  - template: SAST.gitlab-ci.yml

variables:
  SAST_GOSEC_LEVEL: 2

Because the template is evaluated before the pipeline configuration, the last mention of the variable will take precedence.

Overriding the SAST template

If you want to override the job definition (for example, change properties like variables or dependencies), you need to declare a sast job after the template inclusion and specify any additional keys under it. For example:

include:
  - template: SAST.gitlab-ci.yml

sast:
  variables:
    CI_DEBUG_TRACE: "true"

Using environment variables to pass credentials for private repositories

Some analyzers require downloading the project’s dependencies in order to perform the analysis. In turn, such dependencies may live in private Git repositories and thus require credentials like username and password to download them. Depending on the analyzer, such credentials can be provided to it via custom environment variables.

Using a variable to pass username and password to a private Maven repository

If you have a private Apache Maven repository that requires login credentials, you can use the MAVEN_CLI_OPTS environment variable to pass a username and password. You can set it under your project’s settings so that your credentials aren’t exposed in .gitlab-ci.yml.

If the username is myuser and the password is verysecret then you would set the following variable under your project’s settings:

TypeKeyValue
VariableMAVEN_CLI_OPTS-Drepository.password=verysecret -Drepository.user=myuser

Disabling Docker in Docker for SAST

You can avoid the need for Docker in Docker by running the individual analyzers. This does not require running the executor in privileged mode. For example:

include:
  - template: SAST.gitlab-ci.yml

variables:
  SAST_DISABLE_DIND: "true"

This will create individual <analyzer-name>-sast jobs for each analyzer that runs in your CI/CD pipeline.

Enabling kubesec analyzer

Introduced in GitLab Ultimate 12.6.

When Docker in Docker is disabled, you will need to set SCAN_KUBERNETES_MANIFESTS to "true" to enable the kubesec analyzer. In .gitlab-ci.yml, define:

include:
  - template: SAST.gitlab-ci.yml

variables:
  SAST_DISABLE_DIND: "true"
  SCAN_KUBERNETES_MANIFESTS: "true"

Pre-compilation

If your project requires custom build configurations, it can be preferable to avoid compilation during your SAST execution and instead pass all job artifacts from an earlier stage within the pipeline. This is the current strategy when requiring a before_script execution to prepare your scan job.

To pass your project’s dependencies as artifacts, the dependencies must be included in the project’s working directory and specified using the artifacts:path configuration. If all dependencies are present, the -compile=false flag can be provided to the analyzer and compilation will be skipped:

image: maven:3.6-jdk-8-alpine

stages:
 - build
 - test

include:
  template: SAST.gitlab-ci.yml

variables:
  SAST_DISABLE_DIND: "true"

build:
  stage: build
  script:
    - mvn package -Dmaven.repo.local=./.m2/repository
  artifacts:
    paths:
      - .m2/
      - target/

spotbugs-sast:
  dependencies: build
  script:
    - /analyzer run -compile=false
  variables:
    MAVEN_REPO_PATH: ./.m2/repository
  artifacts:
    reports:
      sast: gl-sast-report.json
Note: The path to the vendored directory must be specified explicitly to allow the analyzer to recognize the compiled artifacts. This configuration can vary per analyzer but in the case of Java above, MAVEN_REPO_PATH can be used. See Analyzer settings for the complete list of available options.

Available variables

SAST can be configured using environment variables.

Docker images

The following are Docker image-related variables.

Environment variableDescription
SAST_ANALYZER_IMAGESComma separated list of custom images. Default images are still enabled. Read more about customizing analyzers. Not available when Docker in Docker is disabled.
SAST_ANALYZER_IMAGE_PREFIXOverride the name of the Docker registry providing the default images (proxy). Read more about customizing analyzers.
SAST_ANALYZER_IMAGE_TAGOverride the Docker tag of the default images. Read more about customizing analyzers.
SAST_DEFAULT_ANALYZERSOverride the names of default images. Read more about customizing analyzers.
SAST_DISABLE_DINDDisable Docker in Docker and run analyzers individually.
SAST_PULL_ANALYZER_IMAGESPull the images from the Docker registry (set to 0 to disable). Read more about customizing analyzers. Not available when Docker in Docker is disabled.

Vulnerability filters

Some analyzers make it possible to filter out vulnerabilities under a given threshold.

Environment variableDefault valueDescription
SAST_BANDIT_EXCLUDED_PATHS-comma-separated list of paths to exclude from scan. Uses Python’s fnmatch syntax
SAST_BRAKEMAN_LEVEL1Ignore Brakeman vulnerabilities under given confidence level. Integer, 1=Low 3=High.
SAST_FLAWFINDER_LEVEL1Ignore Flawfinder vulnerabilities under given risk level. Integer, 0=No risk, 5=High risk.
SAST_GITLEAKS_ENTROPY_LEVEL8.0Minimum entropy for secret detection. Float, 0.0 = low, 8.0 = high.
SAST_GOSEC_LEVEL0Ignore gosec vulnerabilities under given confidence level. Integer, 0=Undefined, 1=Low, 2=Medium, 3=High.
SAST_EXCLUDED_PATHS-Exclude vulnerabilities from output based on the paths. This is a comma-separated list of patterns. Patterns can be globs, file or folder paths (e.g., doc,spec ). Parent directories will also match patterns.

Timeouts

The following variables configure timeouts.

Environment variableDefault valueDescription
SAST_DOCKER_CLIENT_NEGOTIATION_TIMEOUT2mTime limit for Docker client negotiation. Timeouts are parsed using Go’s ParseDuration. Valid time units are “ns”, “us” (or “µs”), “ms”, “s”, “m”, “h”. For example, “300ms”, “1.5h” or “2h45m”.
SAST_PULL_ANALYZER_IMAGE_TIMEOUT5mTime limit when pulling the image of an analyzer. Timeouts are parsed using Go’s ParseDuration. Valid time units are “ns”, “us” (or “µs”), “ms”, “s”, “m”, “h”. For example, “300ms”, “1.5h” or “2h45m”.
SAST_RUN_ANALYZER_TIMEOUT20mTime limit when running an analyzer. Timeouts are parsed using Go’s ParseDuration. Valid time units are “ns”, “us” (or “µs”), “ms”, “s”, “m”, “h”. For example, “300ms”, “1.5h” or “2h45m”.
Note: Timeout variables are not applicable for setups with disabled Docker In Docker.

Analyzer settings

Some analyzers can be customized with environment variables.

Environment variableAnalyzerDescription
SCAN_KUBERNETES_MANIFESTSkubesecSet to "true" to scan Kubernetes manifests when Docker in Docker is disabled.
ANT_HOMEspotbugsThe ANT_HOME environment variable.
ANT_PATHspotbugsPath to the ant executable.
GRADLE_PATHspotbugsPath to the gradle executable.
JAVA_OPTSspotbugsAdditional arguments for the java executable.
JAVA_PATHspotbugsPath to the java executable.
SAST_JAVA_VERSIONspotbugsWhich Java version to use. Supported versions are 8 and 11. Defaults to 8.
MAVEN_CLI_OPTSspotbugsAdditional arguments for the mvn or mvnw executable.
MAVEN_PATHspotbugsPath to the mvn executable.
MAVEN_REPO_PATHspotbugsPath to the Maven local repository (shortcut for the maven.repo.local property).
SBT_PATHspotbugsPath to the sbt executable.
FAIL_NEVERspotbugsSet to 1 to ignore compilation failure.

Custom environment variables

Introduced in GitLab Ultimate 12.5.

In addition to the aforementioned SAST configuration variables, all custom environment variables are propagated to the underlying SAST analyzer images if the SAST vendored template is used.

Caution: Variables having names starting with these prefixes will not be propagated to the SAST Docker container and/or analyzer containers: DOCKER_, CI, GITLAB_, FF_, HOME, PWD, OLDPWD, PATH, SHLVL, HOSTNAME.

Reports JSON format

Caution: The JSON report artifacts are not a public API of SAST and their format may change in the future.

The SAST tool emits a JSON report report file. Here is an example of the report structure with all important parts of it highlighted:

{
  "version": "2.0",
  "vulnerabilities": [
    {
      "category": "sast",
      "name": "Predictable pseudorandom number generator",
      "message": "Predictable pseudorandom number generator",
      "description": "The use of java.util.Random is predictable",
      "cve": "818bf5dacb291e15d9e6dc3c5ac32178:PREDICTABLE_RANDOM",
      "severity": "Medium",
      "confidence": "Medium",
      "scanner": {
        "id": "find_sec_bugs",
        "name": "Find Security Bugs"
      },
      "location": {
        "file": "groovy/src/main/groovy/com/gitlab/security_products/tests/App.groovy",
        "start_line": 47,
        "end_line": 47,
        "class": "com.gitlab.security_products.tests.App",
        "method": "generateSecretToken2",
        "dependency": {
          "package": {}
        }
      },
      "identifiers": [
        {
          "type": "find_sec_bugs_type",
          "name": "Find Security Bugs-PREDICTABLE_RANDOM",
          "value": "PREDICTABLE_RANDOM",
          "url": "https://find-sec-bugs.github.io/bugs.htm#PREDICTABLE_RANDOM"
        },
        {
          "type": "cwe",
          "name": "CWE-330",
          "value": "330",
          "url": "https://cwe.mitre.org/data/definitions/330.html"
        }
      ]
    },
    {
      "category": "sast",
      "message": "Probable insecure usage of temp file/directory.",
      "cve": "python/hardcoded/hardcoded-tmp.py:4ad6d4c40a8c263fc265f3384724014e0a4f8dd6200af83e51ff120420038031:B108",
      "severity": "Medium",
      "confidence": "Medium",
      "scanner": {
        "id": "bandit",
        "name": "Bandit"
      },
      "location": {
        "file": "python/hardcoded/hardcoded-tmp.py",
        "start_line": 10,
        "end_line": 10,
        "dependency": {
          "package": {}
        }
      },
      "identifiers": [
        {
          "type": "bandit_test_id",
          "name": "Bandit Test ID B108",
          "value": "B108",
          "url": "https://docs.openstack.org/bandit/latest/plugins/b108_hardcoded_tmp_directory.html"
        }
      ]
    },
  ],
  "remediations": []
}

Here is the description of the report file structure nodes and their meaning. All fields are mandatory in the report JSON unless stated otherwise. Presence of optional fields depends on the underlying analyzers being used.

Report JSON nodeFunction
versionReport syntax version used to generate this JSON.
vulnerabilitiesArray of vulnerability objects.
vulnerabilities[].categoryWhere this vulnerability belongs (SAST, Dependency Scanning etc.). For SAST, it will always be sast.
vulnerabilities[].nameName of the vulnerability, this must not include the occurrence’s specific information. Optional.
vulnerabilities[].messageA short text that describes the vulnerability, it may include the occurrence’s specific information. Optional.
vulnerabilities[].descriptionA long text that describes the vulnerability. Optional.
vulnerabilities[].cveA fingerprint string value that represents a concrete occurrence of the vulnerability. Is used to determine whether two vulnerability occurrences are same or different. May not be 100% accurate. This is NOT a CVE.
vulnerabilities[].severityHow much the vulnerability impacts the software. Possible values: Undefined (an analyzer has not provided this info), Info, Unknown, Low, Medium, High, Critical.
vulnerabilities[].confidenceHow reliable the vulnerability’s assessment is. Possible values: Undefined (an analyzer has not provided this info), Ignore, Unknown, Experimental, Low, Medium, High, Confirmed.
vulnerabilities[].solutionExplanation of how to fix the vulnerability. Optional.
vulnerabilities[].scannerA node that describes the analyzer used to find this vulnerability.
vulnerabilities[].scanner.idId of the scanner as a snake_case string.
vulnerabilities[].scanner.nameName of the scanner, for display purposes.
vulnerabilities[].locationA node that tells where the vulnerability is located.
vulnerabilities[].location.filePath to the file where the vulnerability is located. Optional.
vulnerabilities[].location.start_lineThe first line of the code affected by the vulnerability. Optional.
vulnerabilities[].location.end_lineThe last line of the code affected by the vulnerability. Optional.
vulnerabilities[].location.classIf specified, provides the name of the class where the vulnerability is located. Optional.
vulnerabilities[].location.methodIf specified, provides the name of the method where the vulnerability is located. Optional.
vulnerabilities[].identifiersAn ordered array of references that identify a vulnerability on internal or external DBs.
vulnerabilities[].identifiers[].typeType of the identifier. Possible values: common identifier types (among cve, cwe, osvdb, and usn) or analyzer-dependent ones (e.g., bandit_test_id for Bandit analyzer).
vulnerabilities[].identifiers[].nameName of the identifier for display purposes.
vulnerabilities[].identifiers[].valueValue of the identifier for matching purposes.
vulnerabilities[].identifiers[].urlURL to identifier’s documentation. Optional.

Secret detection

GitLab is also able to detect secrets and credentials that have been unintentionally pushed to the repository. For example, an API key that allows write access to third-party deployment environments.

This check is performed by a specific analyzer during the sast job. It runs regardless of the programming language of your app, and you don’t need to change anything to your CI/CD configuration file to turn it on. Results are available in the SAST report.

GitLab currently includes Gitleaks and TruffleHog checks.

Security Dashboard

The Security Dashboard is a good place to get an overview of all the security vulnerabilities in your groups, projects and pipelines. Read more about the Security Dashboard.

Interacting with the vulnerabilities

Once a vulnerability is found, you can interact with it. Read more on how to interact with the vulnerabilities.

Vulnerabilities database update

For more information about the vulnerabilities database update, check the maintenance table.

Troubleshooting

Error response from daemon: error processing tar file: docker-tar: relocation error

This error occurs when the Docker version used to run the SAST job is 19.03.00. You are advised to update to Docker 19.03.01 or greater. Older versions are not affected. Read more in this issue.