PyGuardAST-based static security analysis tool for Python and more — with AI-powered explanations. PyGuard scans source code for security vulnerabilities without executing it. It combines deterministic rule-based detection with optional AI-assisted remediation suggestions via local Ollama, Google Gemini, OpenRouter, OpenAI (ChatGPT models) or Anthropic (Claude models).
Features
Installation
VS Code Extension: Search CLI Usage
Exit codes: Project configPyGuard reads the nearest
An unknown key or invalid value is a tool error. Command-line AI BackendPyGuard supports three AI backends for vulnerability explanations. Before any prompt, every code snippet is masked (known token formats, URL credentials, quoted values), and findings on a hardcoded-secret line are fully redacted. AI report files get the same text. Terminal, JSON and HTML output mask secrets the same way but keep unnamed literals such as Ollama (Local — Default)No API key needed. Runs entirely on your machine.
Environment variables:
Gemini (Cloud)Requires a Google AI Studio API key.
Environment variables:
OpenAI / Anthropic (Cloud)ChatGPT and Claude models through their own APIs. Both need an API key (platform.openai.com, platform.claude.com); a ChatGPT Plus or Claude Pro subscription does not include API access. Anthropic needs
OpenRouter (Cloud)Requires an OpenRouter API key.
Environment variables:
Keys and
|
| # | ID | Name | Severity | CWE |
|---|---|---|---|---|
| 1 | PYG001 | Hardcoded credential | High | CWE-798 |
| 2 | PYG003 | Unsafe yaml.load() |
High | CWE-94 |
| 3 | PYG004 | Unsafe subprocess shell=True |
High | CWE-78 |
| 4 | PYG006 | Insecure random | Medium | CWE-338 |
| 5 | PYG007 | Bare except clause | Low | CWE-703 |
| 6 | PYG009 | Unsafe os.system() |
High | CWE-78 |
| 7 | PYG010 | Weak crypto hash (MD5/SHA1) | Medium | CWE-328 |
| 8 | PYG011 | Unsafe builtins (globals, locals) |
Medium | CWE-94 |
| 9 | PYG013 | Path Traversal | High | CWE-22 |
| 10 | PYG014 | SSRF | High | CWE-918 |
| 11 | PYG015 | XXE Injection | High | CWE-611 |
| 12 | PYG016 | Insecure JWT | Critical | CWE-347 |
| 13 | PYG020 | Dangerous builtins (eval/exec/compile/__import__) |
Critical | CWE-94 |
| 14 | PYG021 | SQL Injection (f-string / dynamic) | Critical | CWE-89 |
| 15 | PYG022 | Unsafe deserialization (pickle) | Critical | CWE-502 |
| 16 | PYG023 | Server-Side Template Injection | Critical | CWE-1336 |
| 17 | PYG025 | SSL/TLS verification disabled | High | CWE-295 |
| 18 | PYG026 | Unsafe os.popen() |
High | CWE-78 |
| 19 | PYG027 | Weak ciphers (DES/RC4/ECB) | High | CWE-327 |
| 20 | PYG028 | Misc security (input/mktemp/urlretrieve) | Medium | CWE-20/377/918 |
| 21 | PYG029 | Open redirect / header injection | Medium | CWE-601/113/614 |
| 22 | PYG030 | Deprecated module (crypt/imp) |
Low | CWE-477 |
| 23 | PYG040 | Django/Flask debug mode enabled | High | CWE-489 |
| 23 | PYG041 | CSRF protection disabled | High | CWE-352 |
| 23 | PYG042 | mark_safe/Markup on non-constant value |
High | CWE-79 |
| 23 | PYG043 | ALLOWED_HOSTS allows any host |
Medium | CWE-346 |
PYG040 to PYG043 come from one module, rules/web_framework.py.
Retired IDs: PYG002 and PYG008 merged into PYG020, PYG005 into PYG022, PYG024 into PYG001. The old IDs still work in pyguard: disable comments.
Tree-sitter Rules
| # | ID | Language | Name | Severity | CWE |
|---|---|---|---|---|---|
| 24 | PYG100 | C/C++ | Buffer overflow | Critical | CWE-120 |
| 25 | PYG101 | C/C++ | Command injection | Critical | CWE-78 |
| 26 | PYG102 | C/C++ | Format string | High | CWE-134 |
| 27 | PYG103 | C/C++ | Insecure crypto | High | CWE-327 |
| 28 | PYG104 | C/C++ | Integer overflow in allocation | High | CWE-190 |
| 29 | PYG105 | C/C++ | Hardcoded key / credential | High | CWE-798 |
| 30 | PYG110 | C++ | Unsafe cast | High | CWE-704/843 |
| 31 | PYG111 | C/C++ | Use-after-free | Critical | CWE-416 |
| 32 | PYG112 | C/C++ | Insecure random | Medium | CWE-330 |
| 33 | PYG113 | C/C++ | Path traversal | High | CWE-22 |
| 34 | PYG120 | C# | SQL Injection | Critical | CWE-89 |
| 35 | PYG121 | C# | XSS | High | CWE-79 |
| 36 | PYG122 | C# | Insecure deserialization | Critical | CWE-502 |
| 37 | PYG123 | C# | Path traversal | High | CWE-22 |
| 38 | PYG124 | C# | XXE | High | CWE-611 |
| 39 | PYG125 | C# | Command injection | Critical | CWE-78 |
| 40 | PYG126 | C# | Hardcoded secrets | High | CWE-798 |
| 41 | PYG200 | JS/TS | Code injection (eval, Function) |
Critical | CWE-95 |
| 42 | PYG201 | JS/TS | DOM XSS | High | CWE-79 |
| 43 | PYG202 | JS/TS | Command injection (child_process) |
Critical | CWE-78 |
| 44 | PYG203 | JS/TS | SQL injection | Critical | CWE-89 |
| 45 | PYG204 | JS/TS | XSS in Express/Node responses (res.send/write/end) |
High | CWE-79 |
| 46 | PYG250 | Java | Command injection | Critical | CWE-78 |
| 47 | PYG251 | Java | SQL injection | Critical | CWE-89 |
| 48 | PYG252 | Java | Insecure deserialization | High | CWE-502 |
| 49 | PYG253 | Java | Path traversal (Paths.get, Path.of, new File, file streams) |
High | CWE-22 |
| 50 | PYG300 | Go | Command injection | Critical/High | CWE-78 |
| 51 | PYG301 | Go | SQL injection | Critical | CWE-89 |
Pattern-based and dependency checks
| ID | Detects |
|---|---|
| PYG900 | Hardcoded secrets in all languages (AWS tokens, GitHub PATs, Stripe keys, high-entropy strings) |
| PYG950 | Injection patterns (eval, shell_exec, Command::new): always for PHP and Rust; for JS/TS, Java, Go, C and C++ only when the tree-sitter grammar is missing, and that file also gets a PYGERR |
| PYG400 | Known-vulnerable pinned dependency, only with --deps |
VS Code Extension
Install: Search PyGuard in the Extensions panel.
Features:
- Auto-scan on save (configurable via
pyguard.analyzeOnSave) - Manual scan via
Ctrl+Shift+P→PyGuard: Analyze Current File - Workspace scan via
PyGuard: Scan Workspaceor the sidebar button; it can be cancelled - Findings in the Problems pane with inline highlights
- Sidebar panel with severity badges, CWE references, code snippets, and a count of findings hidden by
.pyguard.toml - Click any finding to jump to the exact line
- Quick Fix: suppress a rule on a line,
yaml.load→yaml.safe_load, removeverify=False - AI provider selection via
Ctrl+Shift+P→PyGuard: Select AI Provider
Settings:
| Setting | Default | Description |
|---|---|---|
pyguard.analyzeOnSave |
true |
Auto-analyze on file save |
pyguard.pythonPath |
python3 |
Python interpreter path |
pyguard.aiEnabled |
false |
Enable AI-powered explanations |
pyguard.aiProvider |
ollama |
AI backend: ollama (local), gemini or openrouter (cloud) |
pyguard.ollamaModel |
llama3.2 |
Ollama model name |
pyguard.ollamaUrl |
http://localhost:11434 |
Ollama server URL |
pyguard.geminiModel |
models/gemini-2.5-flash-lite |
Gemini model name |
pyguard.openrouterModel |
openrouter/auto |
OpenRouter model name |
pyguard.openaiModel |
gpt-5-mini |
OpenAI model name |
pyguard.anthropicModel |
claude-opus-5-5 |
Anthropic model name |
pyguard.minConfidence |
0 |
Hide findings below this confidence |
pyguard.pythonPath, pyguard.ollamaUrl and pyguard.aiProvider are machine-scoped: set them in user settings, a workspace cannot override them.
Architecture
VS Code (TypeScript)
extension.ts → persistent bridge, debounce, activate/deactivate
SidebarProvider.ts → WebView with postMessage incremental updates
aiKey.ts → AI provider selection, cloud API key management
│
│ spawn / JSON stdin/stdout
▼
vscode_bridge.py → persistent process (stays alive across saves)
│
▼
Python Engine
core/analyzer.py → pipeline, suppression, dedupe
core/language_parser.py → language detection, parser selection
core/AST_parser.py → import alias collection, call resolution
core/taint.py → intra-function taint tracking (Python)
core/config.py → .pyguard.toml
core/generic_scanner.py → regex-based secret/injection scanning
core/sarif.py, core/deps.py → SARIF report, OSV lookup
engine/rule_engine.py → node-type dispatch, ctx injection, rule running
rules/ → 49 security rule modules (PYG001–PYG301)
rules/auto_rule_generator.py → CWE-driven rule synthesis (23 CWEs)
core/redact.py → secret redaction for AI prompts and reports
ai/client.py → AI provider router, Gemini
ai/ollama_client.py → local LLM inference via Ollama
ai/openrouter_client.py → OpenRouter chat API
Writing Custom Rules
Drop a .py file in rules/ — PyGuard picks it up automatically:
# rules/my_rule.py
import ast
from core.result import Vulnerability
RULE_ID = "PYG031"
def check(node: ast.Call, ctx=None) -> list:
findings = []
if isinstance(node, ast.Call):
# detection logic
findings.append(Vulnerability(
rule_id=RULE_ID, name="My Rule",
severity="high", description="...",
line=getattr(node, "lineno", 1),
cwe="CWE-XXX", code="",
))
return findings
Tips:
- Type-annotate the
nodeparam (e.g.,node: ast.Call) for faster dispatch - Tree-sitter rules set
check.__ts_types__and, for anything outside C/C++/C#,check.__ts_langs__ - Use
ctx.get("import_aliases", {})for resolved import aliases - Return empty list for no findings (never return
None)
Auto-Rule Generator
Generate rules from CWE definitions:
# Generate one rule into a review directory (the default --output-dir is ../rules/ relative to the current directory)
python3 rules/auto_rule_generator.py --cwe CWE-89 --output-dir generated/
# Generate all 23 CWE rules
python3 rules/auto_rule_generator.py --all --output-dir generated/
# List available CWEs
python3 rules/auto_rule_generator.py --list-cwes
# Validate a generated rule (run from the repo root)
PYTHONPATH=. python3 rules/auto_rule_generator.py --validate generated/sql_injection.py
Warning: do not generate into rules/ with --overwrite. It replaces the hand-tuned open_redirect, path_traversal, server_side_template_injection and sql_injection modules and adds 19 modules that overlap existing rules, with IDs in another format (PYG0094).
Add new CWEs by editing the CWE_DATABASE dict in rules/auto_rule_generator.py.
Performance
- Persistent bridge — Python process stays alive (no 200-500ms startup per save)
- 400ms debounce — prevents rapid re-analysis storms
- postMessage sidebar — incremental DOM updates instead of full HTML regeneration
- Node-type dispatch — rules pre-categorized by AST node type at load time (
O(nodes * relevant_rules)instead ofO(nodes * all_rules)) - Cached signatures —
inspect.signature()called once at module load, not per-node-per-rule
Requirements
- Python 3.11+
- VS Code 1.80+ (for extension)
- Dependencies:
pip install -r requirements.txt - Ollama (optional, for local AI): https://ollama.com
- Gemini API key (optional, for cloud AI): https://aistudio.google.com/apikey
- OpenRouter API key (optional, for cloud AI): https://openrouter.ai/keys
Project Structure
PyGuard/
├── src/ # VS Code extension (TypeScript)
│ ├── extension.ts # Persistent bridge, debounce, activate
│ ├── SidebarProvider.ts # WebView panel via postMessage
│ └── aiKey.ts # AI provider selection, cloud API key management
├── ai/ # AI backends
│ ├── client.py # Provider router, Gemini
│ ├── background_ai.py # AI report files for the CLI
│ ├── ollama_client.py # Local LLM via Ollama
│ ├── openrouter_client.py # OpenRouter chat API (shared OpenAI-compatible call)
│ ├── openai_client.py # OpenAI chat API
│ └── anthropic_client.py # Anthropic Messages API (official SDK)
├── core/ # Analysis core
│ ├── analyzer.py # Pipeline, suppression, dedupe
│ ├── language_parser.py # Language detection, parser selection
│ ├── AST_parser.py # Alias collection, call resolution
│ ├── *_parser.py # tree-sitter adapters (C, C++, C#, JS, TS, Java, Go)
│ ├── taint.py # Intra-function taint tracking
│ ├── config.py # .pyguard.toml
│ ├── sarif.py # SARIF report
│ ├── deps.py # OSV dependency check
│ ├── generic_scanner.py # Multi-language secret/injection scanning
│ ├── redact.py # Secret redaction for AI prompts and reports
│ └── result.py # Vulnerability dataclass
├── engine/ # Rule engine
│ └── rule_engine.py # Node-type dispatch, ctx injection
├── output/ # HTML report
│ └── html_reporter.py
├── rules/ # 49 security rules + auto-generator
│ ├── unsafe_os_system.py
│ ├── sql_injection.py
│ ├── auto_rule_generator.py
│ └── ... (47 more)
├── samples/ # Deliberately vulnerable files for all languages
├── tests/ # pytest suite: run `pytest tests`, never bare `pytest`
├── assets/ # Extension icons
├── cli.py # CLI entry point
├── vscode_bridge.py # Persistent JSON bridge
├── ai_on_save.py # AI process for the extension
├── package.json # Extension manifest
├── tsconfig.json # TypeScript config
├── requirements.txt # Python dependencies
├── requirements-dev.txt # Adds pytest
└── pyproject.toml # Python package, pyguard command
Changelog
v1.4.2 — 2026-11-02
Changed:
- Suggest fix sends the whole function around the finding (when the language reports one), so a fix can also change the line that built the value, e.g. a SQL string above
db.execute(query) - Suggest fix prompt: keep the first line, change only what the issue needs, use placeholders instead of string formatting
Fixed:
- Reports and fix prompts no longer mask every
name = "..."assignment, only values the secret scanner treats as secrets; a SQL query sent for a fix used to arrive as<redacted secret>. AI explanations keep masking every assigned value
v1.4.1 — 2026-11-02
Changed:
- CWE IDs are always written as
CWE-89(some rules used to reportCWE 89)
v1.4.0 — 2026-11-02
New rules:
- PYG204 (JS/TS): XSS in Express/Node responses:
res.send/write/endwith a string built from runtime data or areq.*field - PYG253 (Java): path traversal:
Paths.get,Path.of,new Fileand file streams with a path built from runtime data; a method that checksnormalize()+startsWith()is not reported
v1.3.0 — 2026-11-02
New languages: JavaScript, TypeScript, Java and Go via tree-sitter (PYG200–203, PYG250–252, PYG300–301).
New rules: Django/Flask checks (PYG040–043: DEBUG, CSRF, mark_safe/Markup, ALLOWED_HOSTS); OSV dependency check for pinned requirements.txt versions (PYG400, --deps).
New sinks:
- PYG202:
spawn/spawnSyncfromchild_processwhen the options object sets a truthyshell(including a shell path) and the command or any of its arguments is not constant - PYG203:
.raw(...)(knex) alongside.query(...) - PYG201:
insertAdjacentHTML(position, html)with non-constant HTML;*.sanitize()output is exempt - PYG251: JPA
createQuery/createNativeQuery
New features:
- Intra-function taint tracking for Python: a finding's confidence says whether the value is user input, unknown or constant
- SARIF 2.1.0 output (
--sarif PATH) .pyguard.tomlproject config (disable,exclude,min_confidence,severity),--no-config- OpenRouter, OpenAI and Anthropic AI providers; model picker with prices in the sidebar; Full report and Suggest fix buttons
- VS Code: workspace scan (cancellable), Quick Fix to suppress a rule on a line, sidebar shows how many findings
.pyguard.tomlhid pyproject.tomlpackaging with apyguardcommand; GitHub Actions CI
Changed:
- CLI exit codes:
0clean,1findings,2tool error; a file or rule that could not run yields aPYGERRfinding that cannot be suppressed - Terminal,
--jsonand--htmloutput now mask secrets (previously only AI prompts and AI report files did)
v1.0.1 — 2026-06-01
New features:
- Ollama (local AI) support — use local LLMs instead of Gemini cloud API
- Unified AI provider router —
ai/client.pyroutes to Ollama or Gemini viaPYGUARD_AI_PROVIDER - AI provider selection — new
PyGuard: Select AI Providercommand in VS Code - New settings —
pyguard.aiProvider,pyguard.ollamaModel,pyguard.ollamaUrl,pyguard.geminiModel pyguard.aiEnableddefault changed tofalse(opt-in AI)
v1.0.0 — 2026-06-01
New rules (11): SQL injection, dangerous builtins, unsafe deserialization, SSTI, hardcoded credentials, SSL bypass, os.popen(), weak ciphers, misc security (input/PRNG/tempfile), open redirect/header injection, deprecated modules.
New features:
- Persistent bridge process (zero startup overhead on save)
- 400ms debounced auto-scan
- postMessage-based incremental sidebar updates
- Click-to-navigate from sidebar to source line
- CWE-driven auto-rule generator (23 CWEs)
- Node-type dispatch in rule engine
- Import alias resolution in auto-generated rules
Performance: 10x faster analysis after first activation (persistent bridge).
Disclaimer
PyGuard is for educational and defensive security purposes only. Scan only code you own or have permission to analyze.