AgentSkillsCN

bandit-security-scan

借助 Bandit AST 分析工具,对 Python 源代码(.py、setup.py、pyproject.toml)进行全面安全审计,识别潜在的安全漏洞。(1)可检测 exec/eval 代码执行、pickle/yaml 反序列化、子进程 Shell 注入、SQL 注入、硬编码凭据、弱加密算法,以及 OWASP Top 10 Python 安全问题。此工具适用于 Python 安全审计、Django/Flask 应用程序的安全评估、恶意 Python 代码的分类与处置,以及 CI/CD 流水线的集成。请注意,本工具不适用于依赖项/软件包审计(建议使用 guarddog)、非 Python 代码(建议使用 graudit)或 Shell 脚本(建议使用 shellcheck)。对于混合语言的 Python 项目,可结合 graudit -d secrets 使用,以实现全面覆盖。

SKILL.md
--- frontmatter
name: bandit-security-scan
description: Security audit of Python source code (.py, setup.py, pyproject.toml) for security vulnerabilities using Bandit AST analysis. (1) Detects exec/eval code execution, pickle/yaml deserialization, subprocess shell injection, SQL injection, hardcoded credentials, weak cryptography, OWASP Top 10 Python issues. Use for Python security audits, Django/Flask apps, malicious Python code triage, CI/CD pipelines. NOT use for dependency/package audits (use guarddog), non-Python code (use graudit), shell scripts (use shellcheck). For mixed Python projects, combine with graudit -d secrets for comprehensive coverage.

Bandit Security Scanner Skill

Bandit is a security linter designed to find common security issues in Python code. It processes each file, builds an AST, and runs appropriate plugins against the AST nodes.

When to Use This Skill

Use this skill when:

  • Scanning Python code for security vulnerabilities
  • Auditing Python projects for hardcoded secrets or credentials
  • Detecting dangerous function calls (eval, exec, pickle)
  • Finding SQL injection or command injection vulnerabilities
  • Checking for weak cryptographic practices
  • Reviewing Python packages for malicious patterns
  • Performing security code review on Python applications

Decision Tree: Choosing the Right Tool

code
What are you scanning?
│
├── Python source code (.py files)?
│   ├── Own code security audit → bandit -r /path (THIS SKILL)
│   ├── Untrusted/malicious Python → bandit + graudit -d exec,secrets
│   └── Django/Flask app → bandit -r . -t B201,B701,B703,B610,B611
│
├── Python dependencies (requirements.txt)?
│   └── Use guarddog instead: guarddog pypi verify requirements.txt
│
├── Mixed languages or non-Python?
│   └── Use graudit instead (multi-language support)
│
└── Shell scripts?
    └── Use shellcheck instead

Malicious Code Detection Priority

When scanning for potentially malicious or compromised Python code, prioritize these test IDs:

Critical - Immediate Red Flags

Test IDDetectionWhy It's Dangerous
B102exec() usageArbitrary code execution
B307eval() usageArbitrary code execution
B602subprocess(shell=True)Reverse shells, command injection
B605os.system()Command injection
B301pickle.load()Code execution via deserialization

High - Data Exfiltration & Backdoors

Test IDDetectionMITRE ATT&CK
B310urllib.urlopenT1071 - C2 communication
B312telnetlibT1071 - Unencrypted backdoor
B321ftplibT1071 - Data exfiltration
B105-B107Hardcoded passwordsT1552.001 - Embedded credentials
B506yaml.load()T1059 - Deserialization attack

Recommended Command for Malicious Code Triage

bash
# Critical patterns first (< 30 seconds)
bandit -r . -t B102,B307,B602,B605,B301 -lll --format json

# Full malicious scan with context
bandit -r . -t B102,B105,B106,B107,B301,B307,B310,B312,B321,B506,B602,B605,B608 -f json -o malicious-scan.json

Prerequisites

Install Bandit using pip:

bash
# Install via pip
pip install bandit

# Or with TOML support for pyproject.toml configuration
pip install bandit[toml]

# Verify installation
bandit --version

Core Commands

Basic Scanning

bash
# Scan a single file
bandit target_file.py

# Scan a directory recursively
bandit -r /path/to/project

# Scan with specific severity level (LOW, MEDIUM, HIGH)
bandit -r . -ll  # Only MEDIUM and above
bandit -r . -lll # Only HIGH severity

# Scan with specific confidence level
bandit -r . -ii  # MEDIUM confidence and above
bandit -r . -iii # Only HIGH confidence

Output Formats

bash
# JSON output (recommended for parsing)
bandit -r . -f json -o bandit-results.json

# SARIF output (for IDE integration)
bandit -r . -f sarif -o bandit-results.sarif

# HTML report
bandit -r . -f html -o bandit-report.html

# CSV output
bandit -r . -f csv -o bandit-results.csv

# Custom format with line numbers
bandit -r . -f custom --msg-template "{relpath}:{line}: {test_id}[{severity}]: {msg}"

Selective Scanning

bash
# Run only specific tests
bandit -r . -t B101,B102,B103

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

# Scan specific file patterns
bandit -r . --include "*.py"
bandit -r . --exclude "*/tests/*,*/venv/*"

Configuration File

bash
# Generate sample config
bandit-config-generator -o .bandit

# Use configuration file
bandit -r . -c .bandit

# Use pyproject.toml
bandit -r . -c pyproject.toml

Available Rules/Checks

Dangerous Function Calls

Test IDDescriptionSeverityMITRE ATT&CK
B101assert usedLOW-
B102exec usedMEDIUMT1059 (Command Execution)
B103set_bad_file_permissionsMEDIUMT1222 (File Permission Modification)
B104hardcoded_bind_all_interfacesMEDIUMT1071 (Application Layer Protocol)
B105hardcoded_password_stringLOWT1552.001 (Credentials in Files)
B106hardcoded_password_funcargLOWT1552.001 (Credentials in Files)
B107hardcoded_password_defaultLOWT1552.001 (Credentials in Files)
B108hardcoded_tmp_directoryMEDIUMT1074 (Data Staged)
B110try_except_passLOW-
B112try_except_continueLOW-

Injection Vulnerabilities

Test IDDescriptionSeverityMITRE ATT&CK
B201flask_debug_trueHIGHT1190 (Exploit Public-Facing Application)
B301pickleMEDIUMT1059 (Deserialization)
B302marshalMEDIUMT1059 (Deserialization)
B303md5/sha1MEDIUMT1600 (Weaken Encryption)
B304insecure_cipherHIGHT1600 (Weaken Encryption)
B305insecure_cipher_modeMEDIUMT1600 (Weaken Encryption)
B306mktemp_qMEDIUMT1074 (Data Staged)
B307evalMEDIUMT1059 (Command Execution)
B308mark_safeMEDIUMT1059.007 (JavaScript)
B310urllib_urlopenMEDIUMT1071 (Application Layer Protocol)
B311randomLOWT1600 (Weaken Encryption)
B312telnetlibHIGHT1071 (Application Layer Protocol)
B313-B320xml vulnerabilitiesMEDIUMT1059 (XXE)
B321ftplibHIGHT1071 (Application Layer Protocol)
B323unverified_contextMEDIUMT1557 (MITM)
B324hashlib_insecureMEDIUMT1600 (Weaken Encryption)

Shell Injection

Test IDDescriptionSeverityMITRE ATT&CK
B601paramiko_callsMEDIUMT1021.004 (SSH)
B602subprocess_popen_shellHIGHT1059.004 (Unix Shell)
B603subprocess_without_shellLOWT1059 (Command Execution)
B604any_other_function_shellMEDIUMT1059.004 (Unix Shell)
B605start_process_shellHIGHT1059.004 (Unix Shell)
B606start_process_no_shellLOWT1059 (Command Execution)
B607start_process_partial_pathLOWT1059 (Command Execution)
B608hardcoded_sql_expressionsMEDIUMT1190 (SQL Injection)
B609linux_commands_wildcardHIGHT1059.004 (Unix Shell)
B610django_extra_usedMEDIUMT1190 (SQL Injection)
B611django_rawsql_usedMEDIUMT1190 (SQL Injection)

Cryptographic Issues

Test IDDescriptionSeverityMITRE ATT&CK
B501request_with_no_cert_validationHIGHT1557 (MITM)
B502ssl_with_bad_versionHIGHT1600 (Weaken Encryption)
B503ssl_with_bad_defaultsMEDIUMT1600 (Weaken Encryption)
B504ssl_with_no_versionMEDIUMT1600 (Weaken Encryption)
B505weak_cryptographic_keyHIGHT1600 (Weaken Encryption)
B506yaml_loadMEDIUMT1059 (Deserialization)
B507ssh_no_host_key_verificationHIGHT1557 (MITM)
B508snmp_insecure_versionMEDIUMT1071 (Application Layer Protocol)
B509snmp_weak_cryptographyMEDIUMT1600 (Weaken Encryption)

Network Security

Test IDDescriptionSeverityMITRE ATT&CK
B701jinja2_autoescape_falseHIGHT1059.007 (XSS)
B702use_of_mako_templatesMEDIUMT1059.007 (XSS)
B703django_mark_safeMEDIUMT1059.007 (XSS)

Recommended Scanning Workflows

Quick Triage (< 30 seconds)

For rapid assessment of unknown or suspicious Python code:

bash
# Check for obvious malicious patterns only
bandit -r . -t B102,B307,B602,B605 -lll

Standard Security Audit (1-2 minutes)

For routine code review:

bash
# Step 1: High-severity issues
bandit -r . -lll -f json -o high-severity.json

# Step 2: Medium and above with exclusions
bandit -r . -ll --exclude "*/tests/*,*/venv/*"

Deep Malicious Code Scan (5-10 minutes)

For untrusted code or incident response:

bash
# Comprehensive scan with all context
bandit -r . -f json -o full-scan.json

# Then combine with graudit for non-Python embedded code
graudit -d exec . && graudit -d secrets .

Baseline Workflow

For tracking security improvements over time:

bash
# Create baseline for existing code
bandit -r . -f json -o baseline.json

# Later scans compare against baseline
bandit -r . -b baseline.json

CI/CD Integration

bash
# Fail pipeline on HIGH severity with HIGH confidence
bandit -r . -lll -iii || exit 1

# Don't fail on findings (reporting only)
bandit -r . -ll --exit-zero

# Fail on MEDIUM+ findings
bandit -r . -ll

Framework-Specific Scanning

Django Applications

bash
bandit -r . -t B201,B608,B610,B611,B701,B703 -f json
# Checks: Debug mode, SQL injection, XSS via mark_safe, raw SQL

Flask Applications

bash
bandit -r . -t B104,B201,B310,B701 -f json
# Checks: Debug mode, bind all interfaces, Jinja2 XSS

Data Processing / ML Pipelines

bash
bandit -r . -t B301,B302,B506 -f json
# Checks: pickle, marshal, yaml deserialization

API Services

bash
bandit -r . -t B105,B106,B107,B501,B502,B503 -f json
# Checks: Hardcoded creds, SSL/TLS issues

Interpreting Results

Severity Levels

  • HIGH: Critical security issues requiring immediate attention
  • MEDIUM: Significant issues that should be addressed
  • LOW: Minor issues or potential concerns

Confidence Levels

  • HIGH: Very confident this is a real issue
  • MEDIUM: Likely an issue but may need verification
  • LOW: Possible issue, manual review recommended

Example Output

code
>> Issue: [B102:exec_used] Use of exec detected.
   Severity: Medium   Confidence: High
   CWE: CWE-78 (https://cwe.mitre.org/data/definitions/78.html)
   Location: ./malicious.py:15:0
   More Info: https://bandit.readthedocs.io/en/latest/plugins/b102_exec_used.html

Verifying Findings

For each Bandit finding, verify:

  • Is user/external input involved? (not hardcoded safe values)
  • Can an attacker control the input path?
  • Is there sanitization/validation before the dangerous call?
  • Is this production code? (not tests/examples/documentation)
  • Does the confidence level match manual assessment?

Common False Positives

Test IDFalse Positive ScenarioRecommendation
B101assert in test filesSkip with --exclude "*/tests/*"
B311random used for non-security purposes (UI, games)Skip with -s B311 if confirmed safe
B105Variables named password that aren't credentialsManual review, consider renaming
B602subprocess(shell=True) with hardcoded commandsVerify no user input reaches command
B108/tmp usage in containerized environmentsContext-dependent, may be acceptable

Integration with Other Security Tools

For comprehensive security analysis, combine Bandit with other skills:

Code TypePrimary ToolSecondary Scan
Python source (.py)Bandit (this skill)graudit -d secrets
Python packagesguarddogExtract then Bandit
Mixed Python + ShellBandit + ShellCheckgraudit -d exec
Django/Flask + JSBanditgraudit -d js,xss

Recommended Multi-Tool Workflow

bash
# 1. Python-specific deep analysis
bandit -r . -f json -o bandit-results.json

# 2. Secrets scan (catches patterns Bandit might miss)
graudit -d secrets .

# 3. Dependency audit
guarddog pypi verify requirements.txt

Additional Resources

  • Malicious Patterns Reference - Educational examples of dangerous code patterns that Bandit detects, including exec(), eval(), pickle, shell injection, SQL injection, and hardcoded credentials. Use this reference to understand detection capabilities and educate developers about secure coding.

Limitations

  • Static Analysis Only: Cannot detect runtime vulnerabilities or dynamic code execution patterns
  • Python Only: Does not scan other languages in polyglot projects
  • AST-Based: May miss vulnerabilities in string-constructed code
  • False Positives: Some patterns (like random for non-security uses) may trigger warnings
  • No Data Flow: Limited taint tracking compared to commercial SAST tools
  • Configuration Required: May need tuning to reduce noise in large codebases
  • No Dependency Scanning: Does not check for vulnerable dependencies (use pip-audit or safety for that)