sast-bandit

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.

242 stars

Best use case

sast-bandit is best used when you need a repeatable AI agent workflow instead of a one-off prompt. It is especially useful for teams working in multi. 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.

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.

Users should expect a more consistent workflow output, faster repeated execution, and less time spent rewriting prompts from scratch.

Practical example

Example input

Use the "sast-bandit" skill to help with this workflow task. Context: 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.

Example output

A structured workflow result with clearer steps, more consistent formatting, and an output that is easier to reuse in the next run.

When to use this skill

  • Use this skill when you want a reusable workflow rather than writing the same prompt again and again.

When not to use this skill

  • Do not use this when you only need a one-off answer and do not need a reusable workflow.
  • Do not use it if you cannot install or maintain the related files, repository context, or supporting tools.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/sast-bandit/SKILL.md --create-dirs "https://raw.githubusercontent.com/aiskillstore/marketplace/main/skills/agentsecops/sast-bandit/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/sast-bandit/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How sast-bandit Compares

Feature / Agentsast-banditStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

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.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

Related Guides

SKILL.md Source

# 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:

```bash
# 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:

```bash
pip install bandit
```

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

```yaml
# .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:

```bash
# 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:

```yaml
# .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:

```bash
# 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:

```bash
# 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:

```bash
# 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:

```python
# 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`:

```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

- [Bandit Documentation](https://bandit.readthedocs.io/)
- [Bandit GitHub Repository](https://github.com/PyCQA/bandit)
- [OWASP Top 10](https://owasp.org/www-project-top-ten/)
- [CWE Database](https://cwe.mitre.org/)
- [Python Security Best Practices](https://python.readthedocs.io/en/stable/library/security_warnings.html)

Related Skills

security-scanning-security-sast

242
from aiskillstore/marketplace

Static Application Security Testing (SAST) for code vulnerability analysis across multiple languages and frameworks

sast-configuration

242
from aiskillstore/marketplace

Configure Static Application Security Testing (SAST) tools for automated vulnerability detection in application code. Use when setting up security scanning, implementing DevSecOps practices, or automating code vulnerability detection.

disaster-recovery

242
from aiskillstore/marketplace

Implement disaster recovery and backup strategies for Proxmox. Create and manage backups, test recovery procedures, and ensure business continuity for your infrastructure.

sast-semgrep

242
from aiskillstore/marketplace

Static application security testing (SAST) using Semgrep for vulnerability detection, security code review, and secure coding guidance with OWASP and CWE framework mapping. Use when: (1) Scanning code for security vulnerabilities across multiple languages, (2) Performing security code reviews with pattern-based detection, (3) Integrating SAST checks into CI/CD pipelines, (4) Providing remediation guidance with OWASP Top 10 and CWE mappings, (5) Creating custom security rules for organization-specific patterns, (6) Analyzing dependencies for known vulnerabilities.

sast-horusec

242
from aiskillstore/marketplace

Multi-language static application security testing using Horusec with support for 18+ programming languages and 20+ security analysis tools. Performs SAST scans, secret detection in git history, and provides vulnerability findings with severity classification. Use when: (1) Analyzing code for security vulnerabilities across multiple languages simultaneously, (2) Detecting exposed secrets and credentials in git history, (3) Integrating SAST into CI/CD pipelines for secure SDLC, (4) Performing comprehensive security analysis during development, (5) Managing false positives and prioritizing security findings.

azure-quotas

242
from aiskillstore/marketplace

Check/manage Azure quotas and usage across providers. For deployment planning, capacity validation, region selection. WHEN: "check quotas", "service limits", "current usage", "request quota increase", "quota exceeded", "validate capacity", "regional availability", "provisioning limits", "vCPU limit", "how many vCPUs available in my subscription".

DevOps & Infrastructure

raindrop-io

242
from aiskillstore/marketplace

Manage Raindrop.io bookmarks with AI assistance. Save and organize bookmarks, search your collection, manage reading lists, and organize research materials. Use when working with bookmarks, web research, reading lists, or when user mentions Raindrop.io.

Data & Research

zlibrary-to-notebooklm

242
from aiskillstore/marketplace

自动从 Z-Library 下载书籍并上传到 Google NotebookLM。支持 PDF/EPUB 格式,自动转换,一键创建知识库。

discover-skills

242
from aiskillstore/marketplace

当你发现当前可用的技能都不够合适(或用户明确要求你寻找技能)时使用。本技能会基于任务目标和约束,给出一份精简的候选技能清单,帮助你选出最适配当前任务的技能。

web-performance-seo

242
from aiskillstore/marketplace

Fix PageSpeed Insights/Lighthouse accessibility "!" errors caused by contrast audit failures (CSS filters, OKLCH/OKLAB, low opacity, gradient text, image backgrounds). Use for accessibility-driven SEO/performance debugging and remediation.

project-to-obsidian

242
from aiskillstore/marketplace

将代码项目转换为 Obsidian 知识库。当用户提到 obsidian、项目文档、知识库、分析项目、转换项目 时激活。 【激活后必须执行】: 1. 先完整阅读本 SKILL.md 文件 2. 理解 AI 写入规则(默认到 00_Inbox/AI/、追加式、统一 Schema) 3. 执行 STEP 0: 使用 AskUserQuestion 询问用户确认 4. 用户确认后才开始 STEP 1 项目扫描 5. 严格按 STEP 0 → 1 → 2 → 3 → 4 顺序执行 【禁止行为】: - 禁止不读 SKILL.md 就开始分析项目 - 禁止跳过 STEP 0 用户确认 - 禁止直接在 30_Resources 创建(先到 00_Inbox/AI/) - 禁止自作主张决定输出位置

obsidian-helper

242
from aiskillstore/marketplace

Obsidian 智能笔记助手。当用户提到 obsidian、日记、笔记、知识库、capture、review 时激活。 【激活后必须执行】: 1. 先完整阅读本 SKILL.md 文件 2. 理解 AI 写入三条硬规矩(00_Inbox/AI/、追加式、白名单字段) 3. 按 STEP 0 → STEP 1 → ... 顺序执行 4. 不要跳过任何步骤,不要自作主张 【禁止行为】: - 禁止不读 SKILL.md 就开始工作 - 禁止跳过用户确认步骤 - 禁止在非 00_Inbox/AI/ 位置创建新笔记(除非用户明确指定)