Skip to content
| Marketplace
Sign in
Visual Studio Code>Linters>PyGuardNew to Visual Studio Code? Get it now.
PyGuard

PyGuard

Enver

|
26 installs
| (0) | Free
AST-based security vulnerability scanner for Python and other languages
Installation
Launch VS Code Quick Open (Ctrl+P), paste the following command, and press enter.
Copied to clipboard
More Info

PyGuard

AST-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).

Publisher: eenverylmz  |  Repository: github.com/eenverylmz/PyGuard


Features

  • AST-based analysis — structural code analysis, not text scanning
  • 49 rule modules (23 Python, 26 tree-sitter) plus 2 pattern scanners and an OSV dependency check, covering OWASP Top 10 and CWEs
  • CWE-driven auto-rule generator — synthesize new rules from CWE definitions
  • Modular rule engine — add custom rules as standalone .py files
  • Intra-function taint tracking (Python) — a finding's confidence says whether the value is user input, unknown or constant
  • AI explanations — Ollama (local), Gemini, OpenRouter, OpenAI or Anthropic (cloud) powered remediation suggestions
  • Multi-language support — Python (AST), C/C++/C#, JS/TS, Java, Go (tree-sitter), PHP, Rust (pattern-based)
  • Project config — .pyguard.toml for disabled rules, excludes and thresholds
  • SARIF output — for GitHub/Gitea code scanning and CI
  • VS Code extension — real-time scanning with sidebar panel and Problems pane
  • Persistent bridge — zero startup overhead after first activation
  • Debounced auto-scan — 400ms debounce prevents rapid re-analysis storms

Installation

git clone https://github.com/eenverylmz/PyGuard.git
cd PyGuard
python -m venv venv
source venv/bin/activate
pip install -r requirements.txt   # or: pip install .   (adds the pyguard command)

VS Code Extension: Search PyGuard in the Extensions panel or visit the Marketplace.


CLI Usage

# Scan a single file
python cli.py path/to/your_file.py

# Scan a directory
python cli.py path/to/project/

# JSON output
python cli.py path/to/your_file.py --json

# HTML report (written to html/pyguard_report.html)
# Terminal, --json and --html output mask secrets: hardcoded-secret lines become
# <redacted secret>, token formats, URL credentials and named assignments are masked
python cli.py path/to/your_file.py --html

# With AI explanations (uses provider from PYGUARD_AI_PROVIDER env var, default ollama)
python cli.py path/to/your_file.py --ai

# Force Ollama
PYGUARD_AI_PROVIDER=ollama python cli.py path/to/your_file.py --ai

# Force Gemini
PYGUARD_AI_PROVIDER=gemini python cli.py path/to/your_file.py --ai

# Force OpenRouter
PYGUARD_AI_PROVIDER=openrouter python cli.py path/to/your_file.py --ai

# Filter results
python cli.py path/to/project/ --severity high --min-confidence 0.5 --exclude "tests,*.min.js"

# Also write a SARIF 2.1.0 report
python cli.py path/to/project/ --sarif pyguard.sarif

# Check pinned requirements.txt versions against OSV
# (sends package names and versions to api.osv.dev; nothing else uses the network without --ai)
python cli.py path/to/project/ --deps

# Ignore .pyguard.toml
python cli.py path/to/project/ --no-config

Exit codes: 0 clean, 1 findings, 2 tool error or a file that could not be analyzed.

Project config

PyGuard reads the nearest .pyguard.toml, looking upward from the scan target and stopping at the directory that holds .git. The extension reads it too.

disable = ["PYG010", "CWE-338"]      # rule IDs or CWEs
exclude = ["tests", "**/vendor"]     # globs relative to the scan target
min_confidence = 0.5                 # 0.0 to 1.0
severity = "medium"                  # low, medium, high or critical

An unknown key or invalid value is a tool error. Command-line --severity and --min-confidence override the file, --exclude adds to it. A file named directly on the command line is always scanned. PYGERR findings (a file or rule that could not run) are never hidden, by config or by pyguard: disable comments.


AI Backend

PyGuard 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 open("config.txt"). The sidebar is local and shows the original code. SARIF has no code snippets.

Ollama (Local — Default)

No API key needed. Runs entirely on your machine.

  1. Install Ollama: https://ollama.com
  2. Pull a model: ollama pull llama3.2
  3. Start Ollama: ollama serve
  4. Set in VS Code: pyguard.aiProvider → ollama

Environment variables:

  • PYGUARD_AI_PROVIDER=ollama
  • PYGUARD_OLLAMA_MODEL=llama3.2 (default)
  • PYGUARD_OLLAMA_URL=http://localhost:11434 (default)

Gemini (Cloud)

Requires a Google AI Studio API key.

  1. Get a key from https://aistudio.google.com/apikey
  2. Set in VS Code: pyguard.aiProvider → gemini
  3. Run PyGuard: Set AI API Key from the command palette

Environment variables:

  • PYGUARD_AI_PROVIDER=gemini
  • GEMINI_API_KEY=...
  • GEMINI_MODEL=models/gemini-2.5-flash-lite (default)

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 pip install anthropic (in requirements.txt).

PYGUARD_AI_PROVIDER=openai    OPENAI_API_KEY=...    pyguard app.py --ai   # PYGUARD_OPENAI_MODEL, default gpt-5-mini
PYGUARD_AI_PROVIDER=anthropic ANTHROPIC_API_KEY=... pyguard app.py --ai   # PYGUARD_ANTHROPIC_MODEL, default claude-opus-5-5

OpenRouter (Cloud)

Requires an OpenRouter API key.

  1. Get a key from https://openrouter.ai/keys
  2. Set in VS Code: pyguard.aiProvider → openrouter
  3. Run PyGuard: Set AI API Key from the command palette

Environment variables:

  • PYGUARD_AI_PROVIDER=openrouter
  • OPENROUTER_API_KEY=...
  • PYGUARD_OPENROUTER_MODEL=openrouter/auto (default)

Keys and .env

Environment variables always work. A .env file is read only from the PyGuard install directory, never from the current directory or its parents, so a .env in the directory you scan is never loaded. A pip install has no such file: use environment variables there.


Detected Vulnerability Classes (49 rule modules)

Python Rules (AST)

# 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 Workspace or 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, remove verify=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 node param (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 of O(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 report CWE 89)

v1.4.0 — 2026-11-02

New rules:

  • PYG204 (JS/TS): XSS in Express/Node responses: res.send/write/end with a string built from runtime data or a req.* field
  • PYG253 (Java): path traversal: Paths.get, Path.of, new File and file streams with a path built from runtime data; a method that checks normalize() + 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/spawnSync from child_process when the options object sets a truthy shell (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.toml project 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.toml hid
  • pyproject.toml packaging with a pyguard command; GitHub Actions CI

Changed:

  • CLI exit codes: 0 clean, 1 findings, 2 tool error; a file or rule that could not run yields a PYGERR finding that cannot be suppressed
  • Terminal, --json and --html output 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.py routes to Ollama or Gemini via PYGUARD_AI_PROVIDER
  • AI provider selection — new PyGuard: Select AI Provider command in VS Code
  • New settings — pyguard.aiProvider, pyguard.ollamaModel, pyguard.ollamaUrl, pyguard.geminiModel
  • pyguard.aiEnabled default changed to false (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.


Author

Enver Yilmaz LinkedIn | GitHub

  • Contact us
  • Jobs
  • Privacy
  • Manage cookies
  • Terms of use
  • Trademarks
  • Your Privacy Choices
  • Consumer Health Privacy
© 2026 Microsoft