Please check gitlab-tutorial

Skip to content

Dependency Scanning

table.ds-table tr:nth-child(even) { background-color: transparent; } table.ds-table td { border-left: 1px solid #dbdbdb; border-right: 1px solid #dbdbdb; border-bottom: 1px solid #dbdbdb; } table.ds-table tr td:first-child { border-left: 0; } table.ds-table tr td:last-child { border-right: 0; } table.ds-table ul { font-size: 1em; list-style-type: none; padding-left: 0px; margin-bottom: 0px; } table.no-vertical-table-lines td { border-left: none; border-right: none; border-bottom: 1px solid #f0f0f0; } table.no-vertical-table-lines tr { border-top: none; }

DETAILS: Tier: Ultimate Offering: GitLab.com, Self-managed, GitLab Dedicated

Dependency Scanning analyzes your application's dependencies for known vulnerabilities. All dependencies are scanned, including transitive dependencies, also known as nested dependencies.

Dependency Scanning is often considered part of Software Composition Analysis (SCA). SCA can contain aspects of inspecting the items your code uses. These items typically include application and system dependencies that are almost always imported from external sources, rather than sourced from items you wrote yourself.

Dependency Scanning can run in the development phase of your application's lifecycle. Every time a pipeline runs, vulnerabilities are identified and compared between the source and target branches. Vulnerabilities and their severity are listed in the merge request, enabling you to proactively address the risk to your application, before the code change is committed. Vulnerabilities can also be identified outside a pipeline by Continuous Vulnerability Scanning.

GitLab offers both Dependency Scanning and Container Scanning to ensure coverage for all of these dependency types. To cover as much of your risk area as possible, we encourage you to use all of our security scanners. For a comparison of these features, see Dependency Scanning compared to Container Scanning.

Dependency scanning Widget

WARNING: Dependency Scanning does not support runtime installation of compilers and interpreters.

Supported languages and package managers

The following languages and dependency managers are supported by Dependency Scanning:

Language Language versions Package manager Supported files Processes multiple files?
.NET All versions NuGet packages.lock.json Y
C#
C All versions Conan conan.lock Y
C++
Go All versions Go
  • go.mod
Y
Java and Kotlin 8 LTS, 11 LTS, 17 LTS, or 21 LTS1 Gradle2
  • build.gradle
  • build.gradle.kts
N
Maven6 pom.xml N
JavaScript and TypeScript All versions npm
  • package-lock.json
  • npm-shrinkwrap.json
Y
yarn yarn.lock Y
pnpm3 pnpm-lock.yaml Y
PHP All versions Composer composer.lock Y
Python 3.117 setuptools8 setup.py N
pip
  • requirements.txt
  • requirements.pip
  • requires.txt
N
Pipenv N
Poetry4 poetry.lock N
Ruby All versions Bundler
  • Gemfile.lock
  • gems.locked
Y
Scala All versions sbt5 build.sbt N
Swift All versions Swift Package Manager Package.resolved N
Cocoapods9 All versions CocoaPods Podfile.lock N
  1. Java 21 LTS for sbt is limited to version 1.9.7. Support for more sbt versions can be tracked in issue 430335. It is not supported when FIPS mode is enabled.

  2. Gradle is not supported when FIPS mode is enabled.

  3. Support for pnpm lockfiles was introduced in GitLab 15.11. pnpm lockfiles do not store bundled dependencies, so the reported dependencies may differ from npm or yarn.

  4. Support for Poetry projects with a poetry.lock file was added in GitLab 15.0. Support for projects without a poetry.lock file is tracked in issue: Poetry's pyproject.toml support for dependency scanning.

  5. Support for sbt 1.0.x was deprecated in GitLab 16.8 and removed in GitLab 17.0.

  6. Support for Maven below 3.8.8 was deprecated in GitLab 16.9 and will be removed in GitLab 17.0.

  7. Support for prior Python versions was deprecated in GitLab 16.9 and removed in GitLab 17.0.

  8. Excludes both pip and setuptools from the report as they are required by the installer.

  9. Only SBOM, without advisories. See spike on CocoaPods advisories research.

Dependency detection

Dependency Scanning automatically detects the languages used in the repository. All analyzers matching the detected languages are run. There is usually no need to customize the selection of analyzers. We recommend not specifying the analyzers so you automatically use the full selection for best coverage, avoiding the need to make adjustments when there are deprecations or removals. However, you can override the selection using the variable DS_EXCLUDED_ANALYZERS.

The language detection relies on CI job rules and searches a maximum of two directory levels from the repository's root. For example, the gemnasium-dependency_scanning job is enabled if a repository contains either Gemfile, api/Gemfile, or api/client/Gemfile, but not if the only supported dependency file is api/v1/client/Gemfile.

For Java and Python, when a supported dependency file is detected, Dependency Scanning attempts to build the project and execute some Java or Python commands to get the list of dependencies. For all other projects, the lock file is parsed to obtain the list of dependencies without needing to build the project first.

When a supported dependency file is detected, all dependencies, including transitive dependencies are analyzed. There is no limit to the depth of nested or transitive dependencies that are analyzed.

Analyzers

Dependency Scanning supports the following official Gemnasium-based analyzers:

  • gemnasium
  • gemnasium-maven
  • gemnasium-python

The analyzers are published as Docker images, which Dependency Scanning uses to launch dedicated containers for each analysis. You can also integrate a custom security scanner.

Each analyzer is updated as new versions of Gemnasium are released. For more information, see the analyzer Release Process documentation.

How analyzers obtain dependency information

GitLab analyzers obtain dependency information using one of the following two methods:

  1. Parsing lockfiles directly.
  2. Running a package manager or build tool to generate a dependency information file which is then parsed.

Obtaining dependency information by parsing lockfiles

The following package managers use lockfiles that GitLab analyzers are capable of parsing directly:

Package Manager Supported File Format Versions Tested Package Manager Versions
Bundler Not applicable 1.17.3, 2.1.4
Composer Not applicable 1.x
Conan 0.4 1.x
Go Not applicable 1.x
NuGet v1, v21 4.9
npm v1, v2, v32 6.x, 7.x, 9.x
pnpm v5, v6, v9 7.x, 8.x 9.x
yarn versions 1, 2, 3, 43 1.x, 2.x, 3.x
Poetry v1 1.x
  1. Support for NuGet version 2 lock files was introduced in GitLab 16.2.

  2. Support for lockfileVersion = 3 was introduced in GitLab 15.7.

  3. Support for Yarn version 4 was introduced in GitLab 16.11.

    The following features are not supported for Yarn Berry:

    Yarn files that contain a patch, a workspace, or both, are still processed, but these features are ignored.

Obtaining dependency information by running a package manager to generate a parsable file

To support the following package managers, the GitLab analyzers proceed in two steps:

  1. Execute the package manager or a specific task, to export the dependency information.
  2. Parse the exported dependency information.
Package Manager Pre-installed Versions Tested Versions
sbt 1.6.2 1.1.6, 1.2.8, 1.3.12, 1.4.6, 1.5.8, 1.6.2, 1.7.3, 1.8.3, 1.9.6, 1.9.7
maven 3.9.8 3.9.81
Gradle 6.7.12, 7.6.42, 8.82 5.6, 6.7, 6.9, 7.6, 8.8
setuptools 70.3.0 >= 70.3.0
pip 24 24
Pipenv 2023.11.15 2023.11.153, 2023.11.15
Go 1.21 1.214
  1. This test uses the default version of maven specified by the .tool-versions file.

  2. Different versions of Java require different versions of Gradle. The versions of Gradle listed in the above table are pre-installed in the analyzer image. The version of Gradle used by the analyzer depends on whether your project uses a gradlew (Gradle wrapper) file or not:

    • If your project does not use a gradlew file, then the analyzer automatically switches to one of the pre-installed Gradle versions, based on the version of Java specified by the DS_JAVA_VERSION variable (default version is 17).

      For Java versions 8 and 11, Gradle 6.7.1 is automatically selected, Java 17 uses Gradle 7.6.4, and Java 21 uses Gradle 8.8.

    • If your project does use a gradlew file, then the version of Gradle pre-installed in the analyzer image is ignored, and the version specified in your gradlew file is used instead.

  3. This test confirms that if a Pipfile.lock file is found, it is used by Gemnasium to scan the exact package versions listed in this file.

  4. Because of the implementation of go build, the Go build process requires network access, a pre-loaded mod cache via go mod download, or vendored dependencies. For more information, refer to the Go documentation on compiling packages and dependencies.

How analyzers are triggered

GitLab relies on rules:exists to start the relevant analyzers for the languages detected by the presence of the Supported files in the repository as shown in the table above.

The current detection logic limits the maximum search depth to two levels. For example, the gemnasium-dependency_scanning job is enabled if a repository contains either a Gemfile.lock, api/Gemfile.lock, or api/client/Gemfile.lock, but not if the only supported dependency file is api/v1/client/Gemfile.lock.

When a supported dependency file is detected, all dependencies, including transitive dependencies are analyzed. There is no limit to the depth of nested or transitive dependencies that are analyzed.

How multiple files are processed

NOTE: If you've run into problems while scanning multiple files, contribute a comment to this issue.

Python

We only execute one installation in the directory where either a requirements file or a lock file has been detected. Dependencies are only analyzed by gemnasium-python for the first file that is detected. Files are searched for in the following order:

  1. requirements.txt, requirements.pip, or requires.txt for projects using Pip.
  2. Pipfile or Pipfile.lock for projects using Pipenv.
  3. poetry.lock for projects using Poetry.
  4. setup.py for project using Setuptools.

The search begins with the root directory and then continues with subdirectories if no builds are found in the root directory. Consequently a Poetry lock file in the root directory would be detected before a Pipenv file in a subdirectory.

Java and Scala

We only execute one build in the directory where a build file has been detected. For large projects that include multiple Gradle, Maven, or sbt builds, or any combination of these, gemnasium-maven only analyzes dependencies for the first build file that is detected. Build files are searched for in the following order:

  1. pom.xml for single or multi-module Maven projects.
  2. build.gradle or build.gradle.kts for single or multi-project Gradle builds.
  3. build.sbt for single or multi-project sbt builds.

The search begins with the root directory and then continues with subdirectories if no builds are found in the root directory. Consequently an sbt build file in the root directory would be detected before a Gradle build file in a subdirectory.

JavaScript

The following analyzers are executed, each of which have different behavior when processing multiple files:

  • Gemnasium

    Supports multiple lockfiles

  • Retire.js

    Does not support multiple lockfiles. When multiple lockfiles exist, Retire.js analyzes the first lockfile discovered while traversing the directory tree in alphabetical order.

The gemnasium analyzer scans supports JavaScript projects for vendored libraries (that is, those checked into the project but not managed by the package manager).

Go

Multiple files are supported. When a go.mod file is detected, the analyzer attempts to generate a build list using Minimal Version Selection. If this fails, the analyzer instead attempts to parse the dependencies within the go.mod file.

As a requirement, the go.mod file should be cleaned up using the command go mod tidy to ensure proper management of dependencies. The process is repeated for every detected go.mod file.

PHP, C, C++, .NET, C#, Ruby, JavaScript

The analyzer for these languages supports multiple lockfiles.

Support for additional languages

Support for additional languages, dependency managers, and dependency files are tracked in the following issues:

Package Managers Languages Supported files Scan tools Issue
Poetry Python pyproject.toml Gemnasium GitLab#32774

Configuration

Enable the dependency scanning analyzer to ensure it scans your application's dependencies for known vulnerabilities. You can then adjust its behavior by using CI/CD variables.

Enabling the analyzer

Prerequisites:

  • The test stage is required in the .gitlab-ci.yml file.
  • With self-managed runners you need a GitLab Runner with the docker or kubernetes executor.
  • If you're using SaaS runners on GitLab.com, this is enabled by default.

To enable the analyzer, either:

Use a preconfigured merge request

This method automatically prepares a merge request that includes the Dependency Scanning template in the .gitlab-ci.yml file. You then merge the merge request to enable Dependency Scanning.

NOTE: This method works best with no existing .gitlab-ci.yml file, or with a minimal configuration file. If you have a complex GitLab configuration file it might not be parsed successfully, and an error might occur. In that case, use the manual method instead.

To enable Dependency Scanning:

  1. On the left sidebar, select Search or go to and find your project.
  2. Select Secure > Security configuration.
  3. In the Dependency Scanning row, select Configure with a merge request.
  4. Select Create merge request.
  5. Review the merge request, then select Merge.

Pipelines now include a Dependency Scanning job.

Edit the .gitlab-ci.yml file manually

This method requires you to manually edit the existing .gitlab-ci.yml file. Use this method if your GitLab CI/CD configuration file is complex.

To enable Dependency Scanning:

  1. On the left sidebar, select Search or go to and find your project.

  2. Select Build > Pipeline editor.

  3. If no .gitlab-ci.yml file exists, select Configure pipeline, then delete the example content.

  4. Copy and paste the following to the bottom of the .gitlab-ci.yml file. If an include line already exists, add only the template line below it.

    include:
      - template: Jobs/Dependency-Scanning.gitlab-ci.yml
  5. Select the Validate tab, then select Validate pipeline.

    The message Simulation completed successfully confirms the file is valid.

  6. Select the Edit tab.

  7. Complete the fields. Do not use the default branch for the Branch field.

  8. Select the Start a new merge request with these changes checkbox, then select Commit changes.

  9. Complete the fields according to your standard workflow, then select Create merge request.

  10. Review and edit the merge request according to your standard workflow, then select Merge.

Pipelines now include a Dependency Scanning job.

Use CI/CD components

  • Introduced in GitLab 17.0. This feature is an experiment.
  • The dependency scanning CI/CD component only supports Android projects.

Use CI/CD components to perform Dependency Scanning of your application. For instructions, see the respective component's README file.

Available CI/CD components

See https://gitlab.com/explore/catalog/components/dependency-scanning

Running jobs in merge request pipelines

See Use security scanning tools with merge request pipelines

Customizing analyzer behavior

To customize Dependency Scanning, use CI/CD variables.

WARNING: Test all customization of GitLab analyzers in a merge request before merging these changes to the default branch. Failure to do so can give unexpected results, including a large number of false positives.

Overriding dependency scanning jobs

To override a job definition (for example, to change properties like variables or dependencies), declare a new job with the same name as the one to override. Place this new job after the template inclusion and specify any additional keys under it. For example, this disables DS_REMEDIATE for the gemnasium analyzer:

include:
  - template: Jobs/Dependency-Scanning.gitlab-ci.yml

gemnasium-dependency_scanning:
  variables:
    DS_REMEDIATE: "false"

To override the dependencies: [] attribute, add an override job as above, targeting this attribute:

include:
  - template: Jobs/Dependency-Scanning.gitlab-ci.yml

gemnasium-dependency_scanning:
  dependencies: ["build"]

Available CI/CD variables

You can use CI/CD variables to customize dependency scanning behavior.

Global analyzer settings

The following variables allow configuration of global dependency scanning settings.

CI/CD variables Description
ADDITIONAL_CA_CERT_BUNDLE Bundle of CA certificates to trust. The bundle of certificates provided here is also used by other tools during the scanning process, such as git, yarn, or npm. For more details, see Custom TLS certificate authority.
DS_EXCLUDED_ANALYZERS Specify the analyzers (by name) to exclude from Dependency Scanning. For more information, see Analyzers.
DS_EXCLUDED_PATHS Exclude files and directories from the scan based on the paths. A comma-separated list of patterns. Patterns can be globs (see doublestar.Match for supported patterns), or file or folder paths (for example, doc,spec). Parent directories also match patterns. This is a pre-filter which is applied before the scan is executed. Default: "spec, test, tests, tmp".
DS_IMAGE_SUFFIX Suffix added to the image name. (GitLab team members can view more information in this confidential issue: https://gitlab.com/gitlab-org/gitlab/-/issues/354796). Automatically set to "-fips" when FIPS mode is enabled.
DS_MAX_DEPTH Defines how many directory levels deep that the analyzer should search for supported files to scan. A value of -1 scans all directories regardless of depth. Default: 2.
SECURE_ANALYZERS_PREFIX Override the name of the Docker registry providing the official default images (proxy).

Analyzer-specific settings

The following variables configure the behavior of specific dependency scanning analyzers.

CI/CD variable Analyzer Default Description
GEMNASIUM_DB_LOCAL_PATH gemnasium /gemnasium-db Path to local Gemnasium database.
GEMNASIUM_DB_UPDATE_DISABLED gemnasium "false" Disable automatic updates for the gemnasium-db advisory database. For usage see Access to the GitLab Advisory Database.
GEMNASIUM_DB_REMOTE_URL gemnasium https://gitlab.com/gitlab-org/security-products/gemnasium-db.git Repository URL for fetching the GitLab Advisory Database.
GEMNASIUM_DB_REF_NAME gemnasium master Branch name for remote repository database. GEMNASIUM_DB_REMOTE_URL is required.
DS_REMEDIATE gemnasium "true", "false" in FIPS mode Enable automatic remediation of vulnerable dependencies. Not supported in FIPS mode.
DS_REMEDIATE_TIMEOUT gemnasium 5m Timeout for auto-remediation.
GEMNASIUM_LIBRARY_SCAN_ENABLED gemnasium "true" Enable detecting vulnerabilities in vendored JavaScript libraries (libraries which are not managed by a package manager). This functionality requires a JavaScript lockfile to be present in a commit, otherwise Dependency Scanning is not executed and vendored files are not scanned.
Dependency scanning uses the Retire.js scanner to detect a limited set of vulnerabilities. For details of which vulnerabilities are detected, see the Retire.js repository.
DS_INCLUDE_DEV_DEPENDENCIES gemnasium "true" When set to "false", development dependencies and their vulnerabilities are not reported. Only projects using Composer, Maven, npm, pnpm, Pipenv or Poetry are supported. Introduced in GitLab 15.1.
GOOS gemnasium "linux" The operating system for which to compile Go code.
GOARCH gemnasium "amd64" The architecture of the processor for which to compile Go code.
GOFLAGS gemnasium The flags passed to the go build tool.
GOPRIVATE gemnasium A list of glob patterns and prefixes to be fetched from source. For more information, see the Go private modules documentation.
DS_JAVA_VERSION gemnasium-maven 17 Version of Java. Available versions: 8, 11, 17, 21.
MAVEN_CLI_OPTS gemnasium-maven "-DskipTests --batch-mode" List of command line arguments that are passed to maven by the analyzer. See an example for using private repositories.
GRADLE_CLI_OPTS gemnasium-maven List of command line arguments that are passed to gradle by the analyzer.
GRADLE_PLUGIN_INIT_PATH gemnasium-maven "gemnasium-init.gradle" Specifies the path to the Gradle initialization script. The init script must include allprojects { apply plugin: 'project-report' } to ensure compatibility.
DS_GRADLE_RESOLUTION_POLICY gemnasium-maven "failed" Controls Gradle dependency resolution strictness. Accepts "none" to allow partial results, or "failed" to fail the scan when any dependencies fail to resolve.
SBT_CLI_OPTS gemnasium-maven List of command-line arguments that the analyzer passes to sbt.
PIP_INDEX_URL gemnasium-python https://pypi.org/simple Base URL of Python Package Index.
PIP_EXTRA_INDEX_URL gemnasium-python Array of extra URLs of package indexes to use in addition to PIP_INDEX_URL. Comma-separated. Warning: Read the following security consideration when using this environment variable.
PIP_REQUIREMENTS_FILE gemnasium-python Pip requirements file to be scanned. This is a filename and not a path. When this environment variable is set only the specified file is scanned.
PIPENV_PYPI_MIRROR gemnasium-python If set, overrides the PyPi index used by Pipenv with a mirror.
DS_PIP_VERSION gemnasium-python Force the install of a specific pip version (example: "19.3"), otherwise the pip installed in the Docker image is used.
DS_PIP_DEPENDENCY_PATH gemnasium-python Path to load Python pip dependencies from.

Other variables

The previous tables are not an exhaustive list of all variables that can be used. They contain all specific GitLab and analyzer variables we support and test. There are many variables, such as environment variables, that you can pass in and they do work. This is a large list, many of which we may be unaware of, and as such is not documented.

For example, to pass the non-GitLab environment variable HTTPS_PROXY to all Dependency Scanning jobs, set it as a CI/CD variable in your .gitlab-ci.yml file like this:

variables:
  HTTPS_PROXY: "https://squid-proxy:3128"

NOTE: Gradle projects require an additional variable setup to use a proxy.

Alternatively we may use it in specific jobs, like Dependency Scanning:

dependency_scanning:
  variables:
    HTTPS_PROXY: $HTTPS_PROXY

As we have not tested all variables you may find some do work and others do not. If one does not work and you need it we suggest submitting a feature request or contributing to the code to enable it to be used.

Custom TLS certificate authority

Dependency Scanning allows for use of custom TLS certificates for SSL/TLS connections instead of the default shipped with the analyzer container image.

Support for custom certificate authorities was introduced in the following versions.

Analyzer Version
gemnasium v2.8.0
gemnasium-maven v2.9.0
gemnasium-python v2.7.0

Using a custom TLS certificate authority

To use a custom TLS certificate authority, assign the text representation of the X.509 PEM public-key certificate to the CI/CD variable ADDITIONAL_CA_CERT_BUNDLE.

For example, to configure the certificate in the .gitlab-ci.yml file:

variables:
  ADDITIONAL_CA_CERT_BUNDLE: |
      -----BEGIN CERTIFICATE-----
      MIIGqTCCBJGgAwIBAgIQI7AVxxVwg2kch4d56XNdDjANBgkqhkiG9w0BAQsFADCB
      ...
      jWgmPqF3vUbZE0EyScetPJquRFRKIesyJuBFMAs=
      -----END CERTIFICATE-----

Authenticate with a private Maven repository

To use a private Maven repository that requires authentication, you should store your credentials in a CI/CD variable and reference them in your Maven settings file. Do not add the credentials to your .gitlab-ci.yml file.

To authenticate with a private Maven repository:

  1. Add the MAVEN_CLI_OPTS CI/CD variable to your project's settings, setting the value to include your credentials.

    For example, if your username is myuser and the password is verysecret:

    Type Key Value
    Variable MAVEN_CLI_OPTS --settings mysettings.xml -Drepository.password=verysecret -Drepository.user=myuser
  2. Create a Maven settings file with your server configuration.

    For example, add the following to the settings file mysettings.xml. This file is referenced in the MAVEN_CLI_OPTS CI/CD variable.

    <!-- mysettings.xml -->
    <settings>
        ...
        <servers>
            <server>
                <id>private_server</id>
                <username>${private.username}</username>
                <password>${private.password}</password>
            </server>
        </servers>
    </settings>

FIPS-enabled images

  • Introduced in GitLab 15.0 - Gemnasium uses FIPS-enabled images when FIPS mode is enabled.

GitLab also offers FIPS-enabled Red Hat UBI versions of the Gemnasium images. When FIPS mode is enabled in the GitLab instance, Gemnasium scanning jobs automatically use the FIPS-enabled images. To manually switch to FIPS-enabled images, set the variable DS_IMAGE_SUFFIX to "-fips".

Dependency scanning for Gradle projects and auto-remediation for Yarn projects are not supported in FIPS mode.

FIPS-enabled images are based on RedHat's UBI micro. They don't have package managers such as dnf or microdnf so it's not possible to install system packages at runtime.

Output

Dependency Scanning produces the following output:

  • Dependency scanning report: Contains details of all vulnerabilities detected in dependencies.
  • CycloneDX Software Bill of Materials: Software Bill of Materials (SBOM) for each supported lock or build file detected.

Dependency scanning report

Dependency scanning outputs a report containing details of all vulnerabilities. The report is processed internally and the results are shown in the UI. The report is also output as an artifact of the dependency scanning job, named gl-dependency-scanning-report.json.

For more details of the dependency scanning report, see:

CycloneDX Software Bill of Materials

  • Generally available in GitLab 15.7.

Dependency Scanning outputs a CycloneDX Software Bill of Materials (SBOM) for each supported lock or build file it detects.

The CycloneDX SBOMs are:

  • Named gl-sbom-<package-type>-<package-manager>.cdx.json.
  • Available as job artifacts of the dependency scanning job.
  • Saved in the same directory as the detected lock or build files.

For example, if your project has the following structure:

.
├── ruby-project/
│   └── Gemfile.lock
├── ruby-project-2/
│   └── Gemfile.lock
├── php-project/
│   └── composer.lock
└── go-project/
    └── go.sum

Then the Gemnasium scanner generates the following CycloneDX SBOMs:

.
├── ruby-project/
│   ├── Gemfile.lock
│   └── gl-sbom-gem-bundler.cdx.json
├── ruby-project-2/
│   ├── Gemfile.lock
│   └── gl-sbom-gem-bundler.cdx.json
├── php-project/
│   ├── composer.lock
│   └── gl-sbom-packagist-composer.cdx.json
└── go-project/
    ├── go.sum
    └── gl-sbom-go-go.cdx.json

Merging multiple CycloneDX SBOMs

You can use a CI/CD job to merge the multiple CycloneDX SBOMs into a single SBOM. GitLab uses CycloneDX Properties to store implementation-specific details in the metadata of each CycloneDX SBOM, such as the location of build and lock files. If multiple CycloneDX SBOMs are merged together, this information is removed from the resulting merged file.

For example, the following .gitlab-ci.yml extract demonstrates how the Cyclone SBOM files can be merged, and the resulting file validated.

stages:
  - test
  - merge-cyclonedx-sboms

include:
  - template: Jobs/Dependency-Scanning.gitlab-ci.yml

merge cyclonedx sboms:
  stage: merge-cyclonedx-sboms
  image:
    name: cyclonedx/cyclonedx-cli:0.25.1
    entrypoint: [""]
  script:
    - find . -name "gl-sbom-*.cdx.json" -exec cyclonedx merge --output-file gl-sbom-all.cdx.json --input-files "{}" +
    # optional: validate the merged sbom
    - cyclonedx validate --input-version v1_4 --input-file gl-sbom-all.cdx.json
  artifacts:
    paths:
      - gl-sbom-all.cdx.json

Contributing to the vulnerability database

To find a vulnerability, you can search the GitLab Advisory Database. You can also submit new vulnerabilities.

Offline environment

For self-managed GitLab instances in an environment with limited, restricted, or intermittent access to external resources through the internet, some adjustments are required for dependency scanning jobs to run successfully. For more information, see Offline environments.

Requirements

To run dependency scanning in an offline environment you must have:

  • A GitLab Runner with the docker or kubernetes executor
  • Local copies of the dependency scanning analyzer images
  • Access to the GitLab Advisory Database

Local copies of analyzer images

To use dependency scanning with all supported languages and frameworks:

  1. Import the following default dependency scanning analyzer images from registry.gitlab.com into your local Docker container registry:

    registry.gitlab.com/security-products/gemnasium:5
    registry.gitlab.com/security-products/gemnasium:5-fips
    registry.gitlab.com/security-products/gemnasium-maven:5
    registry.gitlab.com/security-products/gemnasium-maven:5-fips
    registry.gitlab.com/security-products/gemnasium-python:5
    registry.gitlab.com/security-products/gemnasium-python:5-fips

    The process for importing Docker images into a local offline Docker registry depends on your network security policy. Consult your IT staff to find an accepted and approved process by which external resources can be imported or temporarily accessed. These scanners are periodically updated with new definitions, and you may want to download them regularly.

  2. Configure GitLab CI/CD to use the local analyzers.

    Set the value of the CI/CD variable SECURE_ANALYZERS_PREFIX to your local Docker registry - in this example, docker-registry.example.com.

    include:
      - template: Jobs/Dependency-Scanning.gitlab-ci.yml
    
    variables:
      SECURE_ANALYZERS_PREFIX: "docker-registry.example.com/analyzers"

Access to the GitLab Advisory Database

The GitLab Advisory Database is the source of vulnerability data used by the gemnasium, gemnasium-maven, and gemnasium-python analyzers. The Docker images of these analyzers include a clone of the database. The clone is synchronized with the database before starting a scan, to ensure the analyzers have the latest vulnerability data.

In an offline environment, the default host of the GitLab Advisory Database can't be accessed. Instead, you must host the database somewhere that it is accessible to the GitLab runners. You must also update the database manually at your own schedule.

Available options for hosting the database are:

Use a clone of the GitLab Advisory Database

Using a clone of the GitLab Advisory Database is recommended because it is the most efficient method.

To host a clone of the GitLab Advisory Database:

  1. Clone the GitLab Advisory Database to a host that is accessible by HTTP from the GitLab runners.
  2. In your .gitlab-ci.yml file, set the value of the CI/CD variable GEMNASIUM_DB_REMOTE_URL to the URL of the Git repository.

For example:

variables:
  GEMNASIUM_DB_REMOTE_URL: https://users-own-copy.example.com/gemnasium-db.git

Use a copy of the GitLab Advisory Database

Using a copy of the GitLab Advisory Database requires you to host an archive file which is downloaded by the analyzers.

To use a copy of the GitLab Advisory Database:

  1. Download an archive of the GitLab Advisory Database to a host that is accessible by HTTP from the GitLab runners. The archive is located at https://gitlab.com/gitlab-org/security-products/gemnasium-db/-/archive/master/gemnasium-db-master.tar.gz.

  2. Update your .gitlab-ci.yml file.

    • Set CI/CD variable GEMNASIUM_DB_LOCAL_PATH to use the local copy of the database.
    • Set CI/CD variable GEMNASIUM_DB_UPDATE_DISABLED to disable the database update.
    • Download and extract the advisory database before the scan begins.
    variables:
      GEMNASIUM_DB_LOCAL_PATH: ./gemnasium-db-local
      GEMNASIUM_DB_UPDATE_DISABLED: "true"
    
    dependency_scanning:
      before_script:
        - wget https://local.example.com/gemnasium_db.tar.gz
        - mkdir -p $GEMNASIUM_DB_LOCAL_PATH
        - tar -xzvf gemnasium_db.tar.gz --strip-components=1 -C $GEMNASIUM_DB_LOCAL_PATH

Using a proxy with Gradle projects

The Gradle wrapper script does not read the HTTP(S)_PROXY environment variables. See this upstream issue.

To make the Gradle wrapper script use a proxy, you can specify the options using the GRADLE_CLI_OPTS CI/CD variable:

variables:
  GRADLE_CLI_OPTS: "-Dhttps.proxyHost=squid-proxy -Dhttps.proxyPort=3128 -Dhttp.proxyHost=squid-proxy -Dhttp.proxyPort=3128 -Dhttp.nonProxyHosts=localhost"

Using a proxy with Maven projects

Maven does not read the HTTP(S)_PROXY environment variables.

To make the Maven dependency scanner use a proxy, you can configure it using a settings.xml file (see Maven documentation) and instruct Maven to use this configuration by using the MAVEN_CLI_OPTS CI/CD variable:

variables:
  MAVEN_CLI_OPTS: "--settings mysettings.xml"

Specific settings for languages and package managers

See the following sections for configuring specific languages and package managers.

Python (pip)

If you need to install Python packages before the analyzer runs, you should use pip install --user in the before_script of the scanning job. The --user flag causes project dependencies to be installed in the user directory. If you do not pass the --user option, packages are installed globally, and they are not scanned and don't show up when listing project dependencies.

Python (setuptools)

If you need to install Python packages before the analyzer runs, you should use python setup.py install --user in the before_script of the scanning job. The --user flag causes project dependencies to be installed in the user directory. If you do not pass the --user option, packages are installed globally, and they are not scanned and don't show up when listing project dependencies.

When using self-signed certificates for your private PyPi repository, no extra job configuration (aside from the template .gitlab-ci.yml above) is needed. However, you must update your setup.py to ensure that it can reach your private repository. Here is an example configuration:

  1. Update setup.py to create a dependency_links attribute pointing at your private repository for each dependency in the install_requires list:

    install_requires=['pyparsing>=2.0.3'],
    dependency_links=['https://pypi.example.com/simple/pyparsing'],
  2. Fetch the certificate from your repository URL and add it to the project:

    printf "\n" | openssl s_client -connect pypi.example.com:443 -servername pypi.example.com | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > internal.crt
  3. Point setup.py at the newly downloaded certificate:

    import setuptools.ssl_support
    setuptools.ssl_support.cert_paths = ['internal.crt']

Python (Pipenv)

If running in a limited network connectivity environment, you must configure the PIPENV_PYPI_MIRROR variable to use a private PyPi mirror. This mirror must contain both default and development dependencies.

variables:
  PIPENV_PYPI_MIRROR: https://pypi.example.com/simple

Alternatively, if it's not possible to use a private registry, you can load the required packages into the Pipenv virtual environment cache. For this option, the project must check in the Pipfile.lock into the repository, and load both default and development packages into the cache. See the example python-pipenv project for an example of how this can be done.

Warnings

We recommend that you use the most recent version of all containers, and the most recent supported version of all package managers and languages. Using previous versions carries an increased security risk because unsupported versions may no longer benefit from active security reporting and backporting of security fixes.

Gradle projects

Do not override the reports.html.destination or reports.html.outputLocation properties when generating an HTML dependency report for Gradle projects. Doing so prevents Dependency Scanning from functioning correctly.

Maven Projects

In isolated networks, if the central repository is a private registry (explicitly set with the <mirror> directive), Maven builds may fail to find the gemnasium-maven-plugin dependency. This issue occurs because Maven doesn't search the local repository (/root/.m2) by default and attempts to fetch from the central repository. The result is an error about the missing dependency.

Workaround

To resolve this issue, add a <pluginRepositories> section to your settings.xml file. This allows Maven to find plugins in the local repository.

Before you begin, consider the following:

  • This workaround is only for environments where the default Maven central repository is mirrored to a private registry.
  • After applying this workaround, Maven searches the local repository for plugins, which may have security implications in some environments. Make sure this aligns with your organization's security policies.

Follow these steps to modify the settings.xml file:

  1. Locate your Maven settings.xml file. This file is typically found in one of these locations:

    • /root/.m2/settings.xml for the root user.
    • ~/.m2/settings.xml for a regular user.
    • ${maven.home}/conf/settings.xml global settings.
  2. Check if there's an existing <pluginRepositories> section in the file.

  3. If a <pluginRepositories> section already exists, add only the following <pluginRepository> element inside it. Otherwise, add the entire <pluginRepositories> section:

      <pluginRepositories>
        <pluginRepository>
            <id>local2</id>
            <name>local repository</name>
            <url>file:///root/.m2/repository/</url>
        </pluginRepository>
      </pluginRepositories>
  4. Run your Maven build or dependency scanning process again.

Python projects

Extra care needs to be taken when using the PIP_EXTRA_INDEX_URL environment variable due to a possible exploit documented by CVE-2018-20225:

An issue was discovered in pip (all versions) because it installs the version with the highest version number, even if the user had intended to obtain a private package from a private index. This only affects use of the PIP_EXTRA_INDEX_URL option, and exploitation requires that the package does not already exist in the public index (and thus the attacker can put the package there with an arbitrary version number).

Version number parsing

In some cases it's not possible to determine if the version of a project dependency is in the affected range of a security advisory.

For example:

  • The version is unknown.
  • The version is invalid.
  • Parsing the version or comparing it to the range fails.
  • The version is a branch, like dev-master or 1.5.x.
  • The compared versions are ambiguous. For example, 1.0.0-20241502 can't be compared to 1.0.0-2 because one version contains a timestamp while the other does not.

In these cases, the analyzer skips the dependency and outputs a message to the log.

The GitLab analyzers do not make assumptions as they could result in a false positive or false negative. For a discussion, see issue 442027.

Build Swift projects

Swift Package Manager (SPM) is the official tool for managing the distribution of Swift code. It's integrated with the Swift build system to automate the process of downloading, compiling, and linking dependencies.

Follow these best practices when you build a Swift project with SPM.

  1. Include a Package.resolved file.

    The Package.resolved file locks your dependencies to specific versions. Always commit this file to your repository to ensure consistency across different environments.

    git add Package.resolved
    git commit -m "Add Package.resolved to lock dependencies"
  2. To build your Swift project, use the following commands:

    # Update dependencies
    swift package update
    
    # Build the project
    swift build
  3. To configure CI/CD, add these steps to your .gitlab-ci.yml file:

    swift-build:
      stage: build
      script:
        - swift package update
        - swift build
  4. Optional. If you use private Swift package repositories with self-signed certificates, you might need to add the certificate to your project and configure Swift to trust it:

    1. Fetch the certificate:

      echo | openssl s_client -servername your.repo.url -connect your.repo.url:443 | sed -ne '/-BEGIN CERTIFICATE-/,/-END
      CERTIFICATE-/p' > repo-cert.crt
    2. Add these lines to your Swift package manifest (Package.swift):

      import Foundation
      
      #if canImport(Security)
      import Security
      #endif
      
      extension Package {
          public static func addCustomCertificate() {
              guard let certPath = Bundle.module.path(forResource: "repo-cert", ofType: "crt") else {
                  fatalError("Certificate not found")
              }
              SecCertificateAddToSystemStore(SecCertificateCreateWithData(nil, try! Data(contentsOf: URL(fileURLWithPath: certPath)) as CFData)!)
          }
      }
      
      // Call this before defining your package
      Package.addCustomCertificate()

Always test your build process in a clean environment to ensure your dependencies are correctly specified and resolve automatically.

Build CocoaPods projects

CocoaPods is a popular dependency manager for Swift and Objective-C Cocoa projects. It provides a standard format for managing external libraries in iOS, macOS, watchOS, and tvOS projects.

Follow these best practices when you build projects that use CocoaPods for dependency management.

  1. Include a Podfile.lock file.

    The Podfile.lock file is crucial for locking your dependencies to specific versions. Always commit this file to your repository to ensure consistency across different environments.

    git add Podfile.lock
    git commit -m "Add Podfile.lock to lock CocoaPods dependencies"
  2. You can build your project with one of the following:

    • The xcodebuild command-line tool:

      # Install CocoaPods dependencies
      pod install
      
      # Build the project
      xcodebuild -workspace YourWorkspace.xcworkspace -scheme YourScheme build
    • The Xcode IDE:

      1. Open your .xcworkspace file in Xcode.
      2. Select your target scheme.
      3. Select Product > Build. You can also press +B.
    • fastlane, a tool for automating builds and releases for iOS and Android apps:

      1. Install fastlane:

        sudo gem install fastlane
      2. In your project, configure fastlane:

        fastlane init
      3. Add a lane to your fastfile:

        lane :build do
          cocoapods
          gym(scheme: "YourScheme")
        end
      4. Run the build:

        fastlane build
    • If your project uses both CocoaPods and Carthage, you can use Carthage to build your dependencies:

      1. Create a Cartfile that includes your CocoaPods dependencies.

      2. Run the following:

        carthage update --platform iOS
  3. Configure CI/CD to build the project according to your preferred method.

    For example, using xcodebuild:

    cocoapods-build:
      stage: build
      script:
        - pod install
        - xcodebuild -workspace YourWorkspace.xcworkspace -scheme YourScheme build
  4. Optional. If you use private CocoaPods repositories, you might need to configure your project to access them:

    1. Add the private spec repo:

      pod repo add REPO_NAME SOURCE_URL
    2. In your Podfile, specify the source:

      source 'https://github.com/CocoaPods/Specs.git'
      source 'SOURCE_URL'
  5. Optional. If your private CocoaPods repository uses SSL, ensure the SSL certificate is properly configured:

    • If you use a self-signed certificate, add it to your system's trusted certificates. You can also specify the SSL configuration in your .netrc file:

      machine your.private.repo.url
        login your_username
        password your_password
  6. After you update your Podfile, run pod install to install dependencies and update your workspace.

Remember to always run pod install after updating your Podfile to ensure all dependencies are properly installed and the workspace is updated.