jpskill.com
🛠️ 開発・MCP コミュニティ

sast-bandit

Bandit SASTを活用し、Pythonコードのセキュリティ脆弱性や問題点を検出し、CWEやOWASPに沿ってセキュリティレポートを生成、修正ガイダンスを提供することで、開発ワークフローにおけるセキュリティ対策を強化するSkill。

📜 元の英語説明(参考)

Python security vulnerability detection using Bandit SAST with CWE and OWASP mapping. Use when: (1) Scanning Python code for security vulnerabilities and anti-patterns, (2) Identifying hardcoded secrets, SQL injection, command injection, and insecure APIs, (3) Generating security reports with severity classifications for CI/CD pipelines, (4) Providing remediation guidance with security framework references, (5) Enforcing Python security best practices in development workflows.

🇯🇵 日本人クリエイター向け解説

一言でいうと

Bandit SASTを活用し、Pythonコードのセキュリティ脆弱性や問題点を検出し、CWEやOWASPに沿ってセキュリティレポートを生成、修正ガイダンスを提供することで、開発ワークフローにおけるセキュリティ対策を強化するSkill。

※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。

⚡ おすすめ: コマンド1行でインストール(60秒)

下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。

🍎 Mac / 🐧 Linux
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o sast-bandit.zip https://jpskill.com/download/17037.zip && unzip -o sast-bandit.zip && rm sast-bandit.zip
🪟 Windows (PowerShell)
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/17037.zip -OutFile "$d\sast-bandit.zip"; Expand-Archive "$d\sast-bandit.zip" -DestinationPath $d -Force; ri "$d\sast-bandit.zip"

完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して sast-bandit.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → sast-bandit フォルダができる
  3. 3. そのフォルダを C:\Users\あなたの名前\.claude\skills\(Win)または ~/.claude/skills/(Mac)へ移動
  4. 4. Claude Code を再起動

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-18
取得日時
2026-05-18
同梱ファイル
5

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

Bandit Python SAST

概要

Bandit は、一般的なセキュリティ脆弱性やコーディングのアンチパターンを特定する、Python 向けのセキュリティに重点を置いた静的解析ツールです。Python コードを抽象構文木 (AST) に解析し、セキュリティプラグインを実行して、ハードコードされた認証情報、SQL インジェクション、コマンドインジェクション、脆弱な暗号化、安全でない API の使用などの問題を検出します。Bandit は、業界のセキュリティ標準に沿った重大度分類を含む、実用的なレポートを提供します。

クイックスタート

Python ファイルまたはディレクトリをスキャンして、セキュリティ脆弱性を検出します。

# Bandit のインストール
pip install bandit

# 単一ファイルの走査
bandit suspicious_file.py

# ディレクトリ全体を再帰的に走査
bandit -r /path/to/python/project

# JSON レポートの生成
bandit -r project/ -f json -o bandit_report.json

# カスタム設定での走査
bandit -r project/ -c .bandit.yaml

コアワークフロー

ステップ 1: Bandit のインストールと設定

pip を使用して Bandit をインストールします。

pip install bandit

設定ファイル .bandit または .bandit.yaml を作成して、スキャンをカスタマイズします。

# .bandit.yaml
exclude_dirs:
  - /tests/
  - /venv/
  - /.venv/
  - /node_modules/

skips:
  - B101  # テストファイル内の assert_used チェックをスキップ

tests:
  - B201  # debug=True での Flask アプリの実行
  - B301  # Pickle の使用
  - B601  # シェルインジェクション
  - B602  # subprocess 内の Shell=True

ステップ 2: セキュリティスキャンの実行

Python コードベースに対して Bandit を実行します。

# 重大度閾値を使用した基本的なスキャン
bandit -r . -ll  # 中/高の重大度のみを報告

# 詳細な出力による包括的なスキャン
bandit -r . -f json -o report.json -v

# 信頼度フィルタリングによるスキャン
bandit -r . -i  # 信頼度の高い検出結果のみを表示

# 特定のテストを除外
bandit -r . -s B101,B601

ステップ 3: 結果の分析

Bandit は、次の情報を含む検出結果を報告します。

  • Issue Type: 脆弱性のカテゴリ (例: hardcoded_password, sql_injection)
  • Severity: LOW, MEDIUM, HIGH
  • Confidence: LOW, MEDIUM, HIGH
  • CWE: Common Weakness Enumeration 参照
  • Location: ファイルパスと行番号

出力例:

>> Issue: [B105:hardcoded_password_string] Possible hardcoded password: 'admin123'
   Severity: Medium   Confidence: Medium
   CWE: CWE-259 (Use of Hard-coded Password)
   Location: app/config.py:12

ステップ 4: 検出結果の優先順位付け

次の優先順位マトリックスを使用して、修正作業に焦点を当てます。

  1. Critical: HIGH の重大度 + HIGH の信頼度
  2. High: HIGH の重大度 OR MEDIUM の重大度 + HIGH の信頼度
  3. Medium: MEDIUM の重大度 + MEDIUM の信頼度
  4. Low: LOW の重大度 OR LOW の信頼度

ステップ 5: 脆弱性の修正

各検出結果について、バンドルされている references/remediation_guide.md で安全なコーディングパターンを参照してください。一般的な修正戦略:

  • ハードコードされたシークレット (B105, B106): 環境変数またはシークレット管理サービスを使用します
  • SQL インジェクション (B608): SQLAlchemy または psycopg2 でパラメータ化されたクエリを使用します
  • コマンドインジェクション (B602, B605): shell=True を避け、引数解析には shlex.split() を使用します
  • 脆弱な暗号化 (B303, B304): MD5/SHA1 を SHA256/SHA512 または bcrypt でパスワードを置き換えます
  • 安全でないデシリアライゼーション (B301): pickle を避け、スキーマ検証を使用して JSON または MessagePack を使用します

ステップ 6: CI/CD への統合

Bandit を CI/CD パイプラインに追加して、セキュリティゲートを適用します。

# .github/workflows/security-scan.yml
name: Security Scan
on: [push, pull_request]

jobs:
  bandit:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-python@v4
        with:
          python-version: '3.11'
      - name: Install Bandit
        run: pip install bandit
      - name: Run Bandit
        run: bandit -r . -f json -o bandit-report.json
      - name: Check for high severity issues
        run: bandit -r . -ll -f txt || exit 1

バンドルされているスクリプト scripts/bandit_analyzer.py を使用して、OWASP マッピングによる拡張レポートを作成します。

セキュリティに関する考慮事項

  • 機密データの取り扱い: Bandit レポートには、ハードコードされた認証情報を含むコードスニペットが含まれている場合があります。レポートが安全に保存され、アクセスが制限されていることを確認してください。レポートからコードスニペットを除外するには、--no-code フラグを使用します。

  • アクセス制御: ソースコードへの読み取り専用アクセス権を持つサンドボックス化された CI/CD 環境で Bandit を実行します。セキュリティ構成の改ざんを防ぐために、書き込み権限を制限します。

  • 監査ログ: セキュリティ監査およびコンプライアンスのために、タイムスタンプ、スキャン範囲、検出結果数、およびオペレーター ID を含むすべての Bandit 実行をログに記録します。

  • コンプライアンス: Bandit は、セキュリティの弱点を特定することにより、SOC2、PCI-DSS、および GDPR コンプライアンスをサポートします。監査証跡のために、スキャン頻度、修正タイムライン、および例外承認を文書化します。

  • 誤検知: LOW の信頼度の検出結果を手動で確認します。インライン # nosec コメントは控えめに使用し、コードレビュープロセスで正当性を文書化します。

バンドルされたリソース

スクリプト (scripts/)

  • bandit_analyzer.py - JSON 出力を解析し、検出結果を OWASP Top 10 にマッピングし、HTML レポートを生成し、チケット発行システムと統合する、拡張された Bandit ラッパー。包括的なセキュリティレポートに使用します。

参照 (references/)

  • remediation_guide.md - SQLAlchemy パラメータ化、安全なサブプロセス使用法、および暗号化のベストプラクティスのコード例など、一般的な Bandit 検出結果に関する詳細な安全なコーディングパターン。特定の脆弱性タイプを修正するときに参照してください。

  • cwe_owasp_mapping.md - Bandit の問題コード、CWE 識別子、および OWASP Top 10 カテゴリ間の完全なマッピング。セキュリティフレームワークの調整およびコンプライアンスレポートに使用します。

アセット (assets/)

  • bandit_config.yaml - 最適化されたテスト選択、一般的な誤検知の除外パターン、および重大度閾値を含む、本番環境対応の Bandit 構成。プロジェクトのベースライン構成として使用します。

  • pre-commit-config.yaml - Bandit 統合用の Pre-commit フック構成。HIGH の重大度の検出結果を含むコミットを防止します。

一般的なパターン

パターン 1: ベースラインセキュリティ

(原文がここで切り詰められています)

📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

Bandit Python SAST

Overview

Bandit is a security-focused static analysis tool for Python that identifies common security vulnerabilities and coding anti-patterns. It parses Python code into Abstract Syntax Trees (AST) and executes security plugins to detect issues like hardcoded credentials, SQL injection, command injection, weak cryptography, and insecure API usage. Bandit provides actionable reports with severity classifications aligned to industry security standards.

Quick Start

Scan a Python file or directory for security vulnerabilities:

# Install Bandit
pip install bandit

# Scan single file
bandit suspicious_file.py

# Scan entire directory recursively
bandit -r /path/to/python/project

# Generate JSON report
bandit -r project/ -f json -o bandit_report.json

# Scan with custom config
bandit -r project/ -c .bandit.yaml

Core Workflow

Step 1: Install and Configure Bandit

Install Bandit via pip:

pip install bandit

Create a configuration file .bandit or .bandit.yaml to customize scans:

# .bandit.yaml
exclude_dirs:
  - /tests/
  - /venv/
  - /.venv/
  - /node_modules/

skips:
  - B101  # Skip assert_used checks in test files

tests:
  - B201  # Flask app run with debug=True
  - B301  # Pickle usage
  - B601  # Shell injection
  - B602  # Shell=True in subprocess

Step 2: Execute Security Scan

Run Bandit against Python codebase:

# Basic scan with severity threshold
bandit -r . -ll  # Report only medium/high severity

# Comprehensive scan with detailed output
bandit -r . -f json -o report.json -v

# Scan with confidence filtering
bandit -r . -i  # Show only high confidence findings

# Exclude specific tests
bandit -r . -s B101,B601

Step 3: Analyze Results

Bandit reports findings with:

  • Issue Type: Vulnerability category (e.g., hardcoded_password, sql_injection)
  • Severity: LOW, MEDIUM, HIGH
  • Confidence: LOW, MEDIUM, HIGH
  • CWE: Common Weakness Enumeration reference
  • Location: File path and line number

Example output:

>> Issue: [B105:hardcoded_password_string] Possible hardcoded password: 'admin123'
   Severity: Medium   Confidence: Medium
   CWE: CWE-259 (Use of Hard-coded Password)
   Location: app/config.py:12

Step 4: Prioritize Findings

Focus remediation efforts using this priority matrix:

  1. Critical: HIGH severity + HIGH confidence
  2. High: HIGH severity OR MEDIUM severity + HIGH confidence
  3. Medium: MEDIUM severity + MEDIUM confidence
  4. Low: LOW severity OR LOW confidence

Step 5: Remediate Vulnerabilities

For each finding, consult the bundled references/remediation_guide.md for secure coding patterns. Common remediation strategies:

  • Hardcoded Secrets (B105, B106): Use environment variables or secret management services
  • SQL Injection (B608): Use parameterized queries with SQLAlchemy or psycopg2
  • Command Injection (B602, B605): Avoid shell=True, use shlex.split() for argument parsing
  • Weak Cryptography (B303, B304): Replace MD5/SHA1 with SHA256/SHA512 or bcrypt for passwords
  • Insecure Deserialization (B301): Avoid pickle, use JSON or MessagePack with schema validation

Step 6: Integrate into CI/CD

Add Bandit to CI/CD pipelines to enforce security gates:

# .github/workflows/security-scan.yml
name: Security Scan
on: [push, pull_request]

jobs:
  bandit:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-python@v4
        with:
          python-version: '3.11'
      - name: Install Bandit
        run: pip install bandit
      - name: Run Bandit
        run: bandit -r . -f json -o bandit-report.json
      - name: Check for high severity issues
        run: bandit -r . -ll -f txt || exit 1

Use the bundled script scripts/bandit_analyzer.py for enhanced reporting with OWASP mapping.

Security Considerations

  • Sensitive Data Handling: Bandit reports may contain code snippets with hardcoded credentials. Ensure reports are stored securely and access is restricted. Use --no-code flag to exclude code snippets from reports.

  • Access Control: Run Bandit in sandboxed CI/CD environments with read-only access to source code. Restrict write permissions to prevent tampering with security configurations.

  • Audit Logging: Log all Bandit executions with timestamps, scan scope, findings count, and operator identity for security auditing and compliance purposes.

  • Compliance: Bandit supports SOC2, PCI-DSS, and GDPR compliance by identifying security weaknesses. Document scan frequency, remediation timelines, and exception approvals for audit trails.

  • False Positives: Review LOW confidence findings manually. Use inline # nosec comments sparingly and document justifications in code review processes.

Bundled Resources

Scripts (scripts/)

  • bandit_analyzer.py - Enhanced Bandit wrapper that parses JSON output, maps findings to OWASP Top 10, generates HTML reports, and integrates with ticketing systems. Use for comprehensive security reporting.

References (references/)

  • remediation_guide.md - Detailed secure coding patterns for common Bandit findings, including code examples for SQLAlchemy parameterization, secure subprocess usage, and cryptographic best practices. Consult when remediating specific vulnerability types.

  • cwe_owasp_mapping.md - Complete mapping between Bandit issue codes, CWE identifiers, and OWASP Top 10 categories. Use for security framework alignment and compliance reporting.

Assets (assets/)

  • bandit_config.yaml - Production-ready Bandit configuration with optimized test selection, exclusion patterns for common false positives, and severity thresholds. Use as baseline configuration for projects.

  • pre-commit-config.yaml - Pre-commit hook configuration for Bandit integration. Prevents commits with HIGH severity findings.

Common Patterns

Pattern 1: Baseline Security Scan

Establish security baseline for legacy codebases:

# Generate baseline report
bandit -r . -f json -o baseline.json

# Compare future scans against baseline
bandit -r . -f json -o current.json
diff <(jq -S . baseline.json) <(jq -S . current.json)

Pattern 2: Security Gating in Pull Requests

Block merges with HIGH severity findings:

# Exit with error if HIGH severity issues found
bandit -r . -lll -f txt
if [ $? -ne 0 ]; then
    echo "HIGH severity security issues detected - blocking merge"
    exit 1
fi

Pattern 3: Progressive Security Hardening

Incrementally increase security standards:

# Phase 1: Block only CRITICAL (HIGH severity + HIGH confidence)
bandit -r . -ll -i

# Phase 2: Block HIGH severity
bandit -r . -ll

# Phase 3: Block MEDIUM and above
bandit -r . -l

Pattern 4: Suppressing False Positives

Document exceptions inline with justification:

# Example: Suppressing pickle warning for internal serialization
import pickle  # nosec B301 - Internal cache, not user input

def load_cache(file_path):
    with open(file_path, 'rb') as f:
        return pickle.load(f)  # nosec B301

Integration Points

  • CI/CD: Integrate as GitHub Actions, GitLab CI, Jenkins pipeline stage, or pre-commit hook. Use scripts/bandit_analyzer.py for enhanced reporting.

  • Security Tools: Combine with Semgrep for additional SAST coverage, Safety for dependency scanning, and SonarQube for code quality metrics.

  • SDLC: Execute during development (pre-commit), code review (PR checks), and release gates (pipeline stage). Establish baseline scans for legacy code and enforce strict checks for new code.

  • Ticketing Integration: Use scripts/bandit_analyzer.py to automatically create Jira/GitHub issues for HIGH severity findings with remediation guidance.

Troubleshooting

Issue: Too Many False Positives

Solution:

  1. Use confidence filtering: bandit -r . -i (HIGH confidence only)
  2. Exclude test files: bandit -r . --exclude /tests/
  3. Customize .bandit.yaml to skip specific tests for known safe patterns
  4. Review and suppress with inline # nosec comments with justification

Issue: Scan Performance on Large Codebases

Solution:

  1. Exclude dependencies: Add /venv/, /.venv/, /site-packages/ to .bandit.yaml exclude_dirs
  2. Use multiprocessing: Bandit automatically parallelizes for directories
  3. Scan only changed files in CI/CD: git diff --name-only origin/main | grep '.py$' | xargs bandit

Issue: Missing Specific Vulnerability Types

Solution:

  1. Check enabled tests: bandit -l (list all tests)
  2. Ensure tests are not skipped in .bandit.yaml
  3. Combine with Semgrep for additional coverage (e.g., business logic vulnerabilities)
  4. Update Bandit regularly: pip install --upgrade bandit

Issue: Integration with Pre-commit Hooks

Solution: Use the bundled assets/pre-commit-config.yaml:

- repo: https://github.com/PyCQA/bandit
  rev: '1.7.5'
  hooks:
    - id: bandit
      args: ['-ll', '--recursive', '--configfile', '.bandit.yaml']

Install hooks: pre-commit install

References

同梱ファイル

※ ZIPに含まれるファイル一覧。`SKILL.md` 本体に加え、参考資料・サンプル・スクリプトが入っている場合があります。