Ce produit n'est pas pris en charge par le site Datadog que vous avez sélectionné. ().

Code Security n'est pas disponible pour le site.

Présentation

Pour configurer Datadog SAST dans l’application, accédez à Security > Code Security.

Sélectionnez l’endroit où exécuter les analyses de code statique

Analyser avec l’analyse hébergée par Datadog

Vous pouvez exécuter Datadog Static Code Analysis (SAST) directement sur l’infrastructure Datadog. Les types de référentiels pris en charge incluent :

Pour commencer, accédez à la Code Security page.

Analyser dans les pipelines CI

Datadog Static Code Analysis s’exécute dans vos pipelines CI à l’aide de la datadog-ci CLI.

Configurez d’abord vos clés d’API et d’application Datadog. Ajoutez DD_APP_KEY et DD_API_KEY en tant que secrets. Veuillez vous assurer que votre clé d’application Datadog dispose du périmètre code_analysis_read.

Ensuite, exécutez l’analyse de code statique en suivant les instructions ci-dessous pour le fournisseur CI de votre choix.

Consultez les instructions en fonction de votre fournisseur CI :


Sélectionnez votre fournisseur de gestion de code source

Datadog Static Code Analysis prend en charge tous les fournisseurs de gestion de code source, avec une prise en charge native pour GitHub, GitLab, Azure DevOps et Bitbucket Cloud Premium.

Configurez une application GitHub avec la tuile d’intégration GitHub et configurez l’intégration du code source pour activer les extraits de code en ligne et les commentaires sur les demandes de tirage.

Lors de l’installation d’une application GitHub, les autorisations suivantes sont requises pour activer certaines fonctionnalités :

  • Content: Read, ce qui vous permet de voir les extraits de code affichés dans Datadog
  • Pull Request: Read & Write, ce qui permet à Datadog d’ajouter des commentaires sur les violations directement dans vos demandes de tirage à l’aide de commentaires sur les demandes de tirage, ainsi que d’ouvrir des demandes de tirage pour corriger les vulnérabilités
  • Checks: Read & Write, ce qui vous permet de créer des vérifications sur les violations SAST pour bloquer les demandes de tirage

Consultez les instructions de configuration du code source GitLab pour connecter des dépôts GitLab à Datadog. Les instances GitLab.com et autogérées sont prises en charge.

Remarque : Vos intégrations Azure DevOps doivent être connectées à un locataire Microsoft Entra. Azure DevOps Server n’est pas pris en charge.

Consultez les instructions de configuration du code source Azure pour connecter des dépôts Azure DevOps à Datadog.

Consultez les instructions de configuration du code source Bitbucket pour connecter des espaces de travail Bitbucket Cloud à Datadog.

Si vous utilisez un autre fournisseur de gestion de code source, configurez l’analyse de code statique pour qu’elle s’exécute dans vos pipelines CI à l’aide de l’outil CLI datadog-ci et téléchargez les résultats vers Datadog. Vous devez exécuter une analyse de votre dépôt sur la branche par défaut avant que les résultats ne puissent commencer à apparaître sur la page Code Security.

Personnalisez votre configuration

Par défaut, l’analyse de code statique (SAST) de Datadog analyse vos dépôts avec les ensembles de règles par défaut de Datadog pour chaque langage de programmation. Vous pouvez personnaliser les ensembles de règles ou les règles qui s’exécutent, ainsi que d’autres paramètres, dans Datadog ou dans un fichier code-security.datadog.yaml. Pour obtenir la référence complète de la configuration, consultez Configuration de l’analyse de code statique (SAST).

Datadog associates code and library scan results with Datadog services and teams to automatically route findings to the appropriate owners. This enables service-level visibility, ownership-based workflows, and faster remediation.

To determine the service where a vulnerability belongs, Datadog evaluates several mapping mechanisms in the order listed in this section.

Each vulnerability is mapped with one method only: if a mapping mechanism succeeds for a particular finding, Datadog does not attempt the remaining mechanisms for that finding.

Using service definitions that include code locations in the Software Catalog is the only way to explicitly control how static findings are mapped to services. The additional mechanisms described below, such as Error Tracking usage patterns and naming-based inference, are not user-configurable and depend on existing data from other Datadog products. Consequently, these mechanisms might not provide consistent mappings for organizations not using these products.

Services in the Software Catalog identify their codebase content using the codeLocations field. This field is available in the Software Catalog schema version v3 and allows a service to specify:

  • a repository URL
apiVersion: v3
kind: service
metadata:
  name: billing-service
  owner: billing-team
datadog:
  codeLocations:
    - repositoryURL: https://github.com/org/myrepo.git
  • one or more code paths inside that repository
apiVersion: v3
kind: service
metadata:
  name: billing-service
  owner: billing-team
datadog:
  codeLocations:
    - repositoryURL: https://github.com/org/myrepo.git
      paths:
        - path/to/service/code/**

If you want all the files in a repository to be associated with a service, you can use the glob ** as follows:

apiVersion: v3
kind: service
metadata:
  name: billing-service
  owner: billing-team
datadog:
  codeLocations:
    - repositoryURL: https://github.com/org/myrepo.git
      paths:
        - path/to/service/code/**
    - repositoryURL: https://github.com/org/billing-service.git
      paths:
        - "**"

The schema for this field is described in the Software Catalog entity model.

Datadog goes through all Software Catalog definitions and checks whether the finding’s file path matches. For a finding to be mapped to a service through codeLocations, it must contain a file path.

Some findings might not contain a file path. In those cases, Datadog cannot evaluate codeLocations for that finding, and this mechanism is skipped.

Services defined with a Software Catalog schema v2.x do not support codeLocations. Existing definitions can be upgraded to the v3 schema in the Software Catalog. After migration is completed, changes might take up to 24 hours to apply to findings. If you are unable to upgrade to v3, Datadog falls back to alternative linking techniques (described below). These rely on less precise heuristics, so accuracy might vary depending on the Code Security product and your use of other Datadog features.

Example (v3 schema)

apiVersion: v3
kind: service
metadata:
  name: billing-service
  owner: billing-team
datadog:
  codeLocations:
    - repositoryURL: https://github.com/org/myrepo.git
      paths:
        - path/to/service/code/**
    - repositoryURL: https://github.com/org/billing-service.git
      paths:
        - "**"

SAST finding

If a vulnerability appeared in github.com/org/myrepo at /src/billing/models/payment.py, then using the codeLocations for billing-service Datadog would add billing-service as an owning service. If your service defines an owner (see above), then Datadog links that team to the finding too. In this case, the finding would be linked to the billing-team.

SCA finding

If a library was declared in github.com/org/myrepo at /go.mod, then Datadog would not match it to billing-service.

Instead, if it was declared in github.com/org/billing-service at /go.mod, then Datadog would match it to billing-service due to the “**” catch-all glob. Consequently, Datadog would link the finding to the billing-team.

Datadog attempts to map a single finding to as many services as possible. If no matches are found, Datadog continues onto the next linking method.

When the Software Catalog cannot determine the service

If the Software Catalog does not provide a match, either because the finding’s file path does not match any codeLocations, or because the service uses the v2.x schema, Datadog evaluates whether Error Tracking can identify the service associated with the code. Datadog uses only the last 30 days of Error Tracking data due to product data-retention limits.

When Error Tracking processes stack traces, the traces often include file paths. For example, if an error occurs in: /foo/bar/baz.py, Datadog inspects the directory: /foo/bar. Datadog then checks whether the finding’s file path resides under that directory.

If the finding file is under the same directory:

  • Datadog treats this as a strong indication that the vulnerability belongs to the same service.
  • The finding inherits the service and team associated with that error in Error Tracking.

If this mapping succeeds, Datadog stops here.

Service inference from file paths or repository names

When neither of the above strategies can determine the service, Datadog inspects naming patterns in the repository and file paths.

Datadog evaluates whether:

  • The file path contains identifiers matching a known service.
  • The repository name corresponds to a service name.

When using the finding’s file path, Datadog performs a reverse search on each path segment until it finds a matching service or exhausts all options.

For example, if a finding occurs in github.com/org/checkout-service at /foo/bar/baz/main.go, Datadog takes the last path segment, main, and sees if any Software Catalog service uses that name. If there is a match, the finding is attributed to that service. If not, the process continues with baz, then bar, and so on.

When all options have been tried, Datadog checks whether the repository name, checkout-service, matches a Software Catalog service name. If no match is found, Datadog is unsuccessful at linking your finding using Software Catalog.

This mechanism ensures that findings receive meaningful service attribution when no explicit metadata exists.

If Datadog is able to link your finding to a service using the above strategies, then the team that owns that service (if defined) is associated with that finding automatically.

Regardless of whether Datadog successfully links a finding to a service (and a Datadog team), Datadog uses the CODEOWNERS information from your finding’s repository to link Datadog and GitHub teams to your findings.

You must accurately map your Git provider teams to your Datadog Teams for team attribution to function properly.

Analyse différentielle

L’analyse différentielle permet à l’analyseur statique de Datadog de n’analyser que les fichiers modifiés par un commit dans une branche de fonctionnalité. Elle accélère considérablement le temps d’analyse en évitant d’exécuter l’analyse sur chaque fichier du dépôt à chaque scan. Pour activer l’analyse différentielle dans votre pipeline CI, suivez ces étapes :

  1. Assurez-vous que vos variables DD_APP_KEY, DD_SITE et DD_API_KEY sont définies dans votre pipeline CI.
  2. Ajoutez un appel à datadog-ci git-metadata upload avant d’invoquer l’analyseur statique. Cette commande garantit que les métadonnées Git sont disponibles pour le backend Datadog. Les métadonnées Git sont nécessaires pour calculer le nombre de fichiers à analyser.
  3. Assurez-vous que le datadog-static-analyzer est invoqué avec l’indicateur --diff-aware.

Exemple de séquence de commandes (ces commandes doivent être invoquées dans votre dépôt Git) :

datadog-ci git-metadata upload

datadog-static-analyzer -i /path/to/directory -g -o sarif.json -f sarif –-diff-aware <...other-options...>

Remarque : Lorsqu’une analyse différentielle ne peut pas être effectuée, le répertoire entier est analysé.

Téléverser les résultats d’analyse statique tiers vers Datadog

L'importation SARIF a été testée pour Snyk, CodeQL, Semgrep, Gitleaks et Sysdig. Contactez le support Datadog si vous rencontrez des problèmes avec d'autres outils compatibles SARIF.

Vous pouvez envoyer les résultats d’outils d’analyse statique tiers à Datadog, à condition qu’ils soient au format interopérable Static Analysis Results Interchange Format (SARIF) Format. Node.js version 14 ou ultérieure est requis.

Pour importer un rapport SARIF, procédez comme suit :

  1. Assurez-vous que les variables DD_API_KEY et DD_APP_KEY sont définies.

  2. Optionnellement, définissez une DD_SITE variable (la valeur par défaut est datadoghq.com).

  3. Installez l’utilitaire datadog-ci :

    npm install -g @datadog/datadog-ci
    
  4. Exécutez l’outil d’analyse statique tiers sur votre code et générez les résultats au format SARIF.

  5. Téléversez les résultats vers Datadog :

    datadog-ci sarif upload $OUTPUT_LOCATION
    

Directives de prise en charge SARIF

Datadog prend en charge l’ingestion de fichiers SARIF tiers conformes au schéma SARIF 2.1.0. Le SARIF schéma est utilisé différemment par les outils d’analyse statique. Si vous souhaitez envoyer des fichiers SARIF tiers à Datadog, veuillez vous assurer qu’ils respectent les détails suivants :

  • L’emplacement de la violation est spécifié via l’objet physicalLocation d’un résultat.
    • Le artifactLocation et son uri doivent être relatifs à la racine du dépôt.
    • L’objet region est la partie du code mise en évidence dans l’interface utilisateur de Datadog.
  • Le partialFingerprints est utilisé pour identifier de manière unique une découverte dans un dépôt.
  • properties et tags ajoutent plus d’informations :
    • Le tag DATADOG_CATEGORY spécifie la catégorie de la découverte. Les valeurs acceptables sont SECURITY, PERFORMANCE, CODE_STYLE, BEST_PRACTICES, ERROR_PRONE.
    • Les violations annotées avec la catégorie SECURITY sont affichées dans le Vulnerabilities Explorer et l’onglet Security de la vue du dépôt.
  • La section tool doit comporter une section driver valide avec des attributs name et version.

Par exemple, voici un exemple de fichier SARIF traité par Datadog :


{
    "runs": [
        {
            "results": [
                {
                    "level": "error",
                    "locations": [
                        {
                            "physicalLocation": {
                                "artifactLocation": {
                                    "uri": "missing_timeout.py"
                                },
                                "region": {
                                    "endColumn": 76,
                                    "endLine": 6,
                                    "startColumn": 25,
                                    "startLine": 6
                                }
                            }
                        }
                    ],
                    "message": {
                        "text": "timeout not defined"
                    },
                    "partialFingerprints": {
                        "DATADOG_FINGERPRINT": "b45eb11285f5e2ae08598cb8e5903c0ad2b3d68eaa864f3a6f17eb4a3b4a25da"
                    },
                    "properties": {
                        "tags": [
                            "DATADOG_CATEGORY:SECURITY",
                            "CWE:1088"
                        ]
                    },
                    "ruleId": "python-security/requests-timeout",
                    "ruleIndex": 0
                }
            ],
            "tool": {
                "driver": {
                    "informationUri": "https://www.datadoghq.com",
                    "name": "<tool-name>",
                    "rules": [
                        {
                            "fullDescription": {
                                "text": "Access to remote resources should always use a timeout and appropriately handle the timeout and recovery. When using `requests.get`, `requests.put`, `requests.patch`, etc. - we should always use a `timeout` as an argument.\n\n#### Learn More\n\n - [CWE-1088 - Synchronous Access of Remote Resource without Timeout](https://cwe.mitre.org/data/definitions/1088.html)\n - [Python Best Practices: always use a timeout with the requests library](https://www.codiga.io/blog/python-requests-timeout/)"
                            },
                            "helpUri": "https://link/to/documentation",
                            "id": "python-security/requests-timeout",
                            "properties": {
                                "tags": [
                                    "CWE:1088"
                                ]
                            },
                            "shortDescription": {
                                "text": "no timeout was given on call to external resource"
                            }
                        }
                    ],
                    "version": "<tool-version>"
                }
            }
        }
    ],
    "version": "2.1.0"
}

Mappage de la sévérité SARIF vers CVSS

Le format SARIF définit quatre niveaux de sévérité : none, note, warning et error. Cependant, Datadog rapporte la sévérité des violations et des vulnérabilités en utilisant le Common Vulnerability Scoring System (CVSS), qui définit cinq niveaux de sévérité : critical, high, medium, low et none.

Lors de l’ingestion de fichiers SARIF, Datadog mappe les sévérités SARIF vers les sévérités CVSS en utilisant les règles de mappage ci-dessous.

Sévérité SARIFSévérité CVSS
ErreurCritique
AvertissementÉlevé
RemarqueMoyen
AucunFaible

Conservation des données

Datadog conserve les résultats conformément à nos Périodes de conservation des données . Datadog ne stocke ni ne conserve le code source des clients .

<!– Lectures complémentaires

Documentation, liens et articles supplémentaires utiles:

–>