iT邦幫忙

2025 iThome 鐵人賽

DAY 24
0
DevOps

DevOps 進化論:從全能型戰士到安全守門員系列 第 24

Day 24|SAST 靜態程式碼分析:CI Pipeline 中的自動安全檢查

  • 分享至 

  • xImage
  •  

● 前言

延續前一篇 「Shift Left」 的概念,SAST 是最常見的左移實踐之一。
在程式碼提交階段就進行安全檢查,可以提前發現漏洞。

為什麼要在 CI Pipeline 中自動化?

  • 降低人工成本
  • 確保檢查一致性

● 什麼是 SAST?

  • 定義:Static Application Security Testing,針對「原始碼 / Bytecode / 二進制」進行靜態分析。
  • 核心特點:不需要執行程式 → 掃描規則比對。

🔍 能檢測的問題

  1. 硬編碼密碼 / API Key
  2. SQL Injection 風險
  3. XSS(跨站腳本)相關程式碼
  4. 不安全的函式呼叫

優勢:快、能融入開發流程
限制:可能有誤報,無法檢測執行時的漏洞


● 常見工具

▪ 開源工具

  1. Semgrep:輕量、可自訂規則
  2. Bandit:Python 專用
  3. SonarQube:程式碼品質 + 安全掃描

▪ 雲端 / 商業服務

  1. GitHub CodeQL
  2. Snyk Code

● 專案目錄

https://ithelp.ithome.com.tw/upload/images/20250906/201781566oENTdyu6Q.png

● 實作範例(掃描app.py)

GitHub Actions Pipeline 中整合 SAST 工具(例如:Bandit):

🎯 目標

  • 在 push / PR 觸發掃描
  • 產出可下載的報告(artifact)
  • (可選)有高嚴重度就讓 CI 失敗

🛠️ 步驟

1.建立所需檔案:

📄app.py:

import subprocess

# 故意:硬編碼密碼(Bandit B105)
DB_PASSWORD = "P@ssw0rd!"

def ping(host: str):
    # 故意:shell=True(Bandit B602)
    subprocess.call(f"ping -c 1 {host}", shell=True)

if __name__ == "__main__":
    ping("127.0.0.1")

📄sast.yml:

name: SAST (Bandit)

on:
  push:
  pull_request:

jobs:
  bandit:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Setup Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.12'

      - name: Install Bandit
        run: |
          python -m pip install --upgrade pip
          pip install bandit

      # 只掃 app.py(最小可行示範)
      - name: Run Bandit (single file)
        run: bandit app.py -f txt -o bandit-report.txt

      - name: Upload report artifact
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: bandit-report
          path: bandit-report.txt

📄requirements.txt:

bandit

2.安裝依賴項:

👉指令 : pip install -r requirements.txt

3.建立Github repo(右上方的"+")

https://ithelp.ithome.com.tw/upload/images/20250906/20178156E0xJqD05dS.png

4.推送程式碼到Github觸發CI Pipeline

https://ithelp.ithome.com.tw/upload/images/20250906/20178156fUeG5dFqZr.png

5.下載bandit-report.txt檢視掃描報告

📥至Github repo中的Actions

  • 下方有一塊Artifacts可以點擊下載
    https://ithelp.ithome.com.tw/upload/images/20250906/20178156XWSGZhoHfK.png

📦將壓縮檔解開後便是sast.yml我們設置的.txt檔案

  • 查看掃描檔案之內容
    https://ithelp.ithome.com.tw/upload/images/20250906/201781563wKJjR62G9.png

● 總結

  • SAST = 左移安全的第一步,最適合整合進 CI Pipeline。
  • 它能有效降低修復成本,因為漏洞在開發初期就能被抓出來。
  • 但它並非萬能,必須搭配 DAST / SCA / 測試流程 才能形成完整防護。

👉 下一篇,Day 25|DAST 動態應用測試:模擬真實攻擊的安全驗證


上一篇
Day 23|Shift Left 實務:在開發流程中落實安全的第一步
下一篇
Day 25|DAST 動態應用測試:模擬真實攻擊的安全驗證
系列文
DevOps 進化論:從全能型戰士到安全守門員25
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言