skills/appsec/sast-bandit/SKILL.md
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.
npx skillsauth add agentsecops/secopsagentkit sast-banditInstall this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
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.
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
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
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
Bandit reports findings with:
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
Focus remediation efforts using this priority matrix:
For each finding, consult the bundled references/remediation_guide.md for secure coding patterns. Common remediation strategies:
shell=True, use shlex.split() for argument parsingAdd 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.
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.
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/)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/)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.
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)
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
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
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
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.
Solution:
bandit -r . -i (HIGH confidence only)bandit -r . --exclude /tests/.bandit.yaml to skip specific tests for known safe patterns# nosec comments with justificationSolution:
/venv/, /.venv/, /site-packages/ to .bandit.yaml exclude_dirsgit diff --name-only origin/main | grep '.py$' | xargs banditSolution:
bandit -l (list all tests).bandit.yamlpip install --upgrade banditSolution:
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
testing
Linux privilege escalation enumeration and attack surface analysis using LinPEAS (Linux Privilege Escalation Awesome Script). Automates post-exploitation discovery of escalation vectors, misconfigurations, and credential exposure on Linux targets. Use when: (1) Enumerating privilege escalation vectors after initial access on a Linux system, (2) Identifying SUID/SGID binaries, sudo misconfigurations, and capability abuses, (3) Hunting for credentials in config files, history, and logs, (4) Detecting container breakout opportunities and writable service files, (5) Mapping kernel exploits and CVE exposure for a target system, (6) Conducting authorized CTF, red team, or penetration test post-exploitation phases.
development
Operational Technology (OT) security assessment using a two-stage methodology: (1) Identification/Discovery of OT devices and protocols, and (2) Vulnerability Assessment using online sources and Metasploit. Use when: (1) Conducting authorized OT/ICS security assessments, (2) Identifying and enumerating OT protocols (Modbus, S7, IEC 104, DNP3, BACnet, EtherNet/IP), (3) Discovering industrial control devices and PLCs, (4) Assessing OT protocol vulnerabilities and security weaknesses, (5) Performing compliance scanning aligned with IEC 62443 standards, (6) Validating network segmentation and access controls in OT environments.
tools
Vulnerability management and findings aggregation using DefectDojo. Centralizes security findings from all SecOpsAgentKit scanners (Semgrep, Bandit, ZAP, Trivy, Grype, Gitleaks, Nuclei, Checkov, Horusec) into a unified platform with automatic deduplication, SLA tracking, risk-based prioritization, and compliance reporting. Use when: (1) Aggregating findings from multiple scanners across products and pipelines, (2) Tracking remediation status and SLA compliance against policy thresholds, (3) Deduplicating overlapping findings across security tools, (4) Generating vulnerability reports for compliance audits (SOC2, PCI-DSS, GDPR), (5) Managing security debt and vulnerability backlog across teams and applications.
tools
Python-based threat modeling using pytm library for programmatic STRIDE analysis, data flow diagram generation, and automated security threat identification. Use when: (1) Creating threat models programmatically using Python code, (2) Generating data flow diagrams (DFDs) with automatic STRIDE threat identification, (3) Integrating threat modeling into CI/CD pipelines and shift-left security practices, (4) Analyzing system architecture for security threats across trust boundaries, (5) Producing threat reports with STRIDE categories and mitigation recommendations, (6) Maintaining threat models as code for version control and automation.