2024-02-20|閱讀時間 ‧ 約 25 分鐘

如何將 Semgrep 整合到 GitLab Pipeline 以進行 SAST 掃描

CI/CD Pipeline 中,SAST(Static Application Security Testing)是一種重要的安全檢查步驟,可以幫助開發人員及早發現程式碼中的潛在安全漏洞。Semgrep 是一款功能強大的 SAST 工具,可以掃描程式碼並檢查各種安全問題,例如寫死的密碼、SQL Injection。

本文將介紹如何將 Semgrep 整合到 GitLab Pipeline 以進行 SAST 掃描。


整合步驟

  1. 在 Semgrep Cloud Platform 建立 Project。
  2. 建立 Semgrep App Token。(只需要 1 個,讓 GitLab 有權限將掃描結果送到 Semgrep Cloud Platform)
  3. GitLab CI/CD Pipeline 加入以下 Job:
    semgrep:
    image: returntocorp/semgrep
    stage: test
    script: semgrep ci
    rules:
    - if: $CI_PIPELINE_SOURCE == "web" # allow triggering a scan manually from the gitlab UI
    - if: $CI_MERGE_REQUEST_IID # This rule triggers Semgrep if the scan is part of a merge request review process. The $CI_MERGE_REQUEST_IID variable holds the ID of the associated merge request, indicating its involvement.
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH # This rule triggers Semgrep if the scan is run on the default branch (likely master or main). The $CI_COMMIT_BRANCH variable specifies the branch where the commit is being pushed, and comparing it to the $CI_DEFAULT_BRANCH variable checks for alignment.
    variables:
    SEMGREP_APP_TOKEN: $SEMGREP_APP_TOKEN
    # To configure MR comments on gitlab.com, see <https://semgrep.dev/docs/semgrep-cloud-platform/gitlab-mr-comments/#enabling-gitlab-merge-request-comments>
    GITLAB_TOKEN: $PAT
  4. 建立 GitLab Access Token,必須要有 api 權限。(Semgrep Cloud Platform 才可以將報告送到 GitLab Merge Request)
  5. 在 GitLab Pipeline 加上 SEMGREP_APP_TOKEN, PAT 變數。
  6. 到 Semgrep Cloud Platform | Rules | Policy,將全部的規則的 Mode 都改為 Comment。
  7. 加上 .semgrepignore,排除不需要掃描的目錄。
    • # Common large paths
      node_modules/
      build/
      dist/
      vendor/
      .env/
      .venv/
      .tox/
      *.min.js
      .npm/
      .yarn/

      # Common test paths
      test/
      tests/
      *_test.go

      # Semgrep rules folder
      .semgrep

      # Semgrep-action log folder
      .semgrep_logs/


使用心得

將 Semgrep 整合到 GitLab Pipeline 後,可以將 SAST 掃描完全整合到開發工作流程中。在 Merge Request 中,開發人員可以直接看到掃描報告,並根據報告中的資訊及早修正程式碼中的安全漏洞。

以下是使用 Semgrep 的一些心得:

  • 整合過程簡單,只需幾個步驟即可完成。
  • 掃描速度快,可以快速發現程式碼中的安全漏洞。
  • 報告詳細,可以幫助開發人員快速理解安全漏洞的風險。


分享至
成為作者繼續創作的動力吧!
© 2024 vocus All rights reserved.