/phoenix-sast-rules:opengrep-rule-generatorfrom phoenix-sast-rules
Generates opengrep/semgrep SAST rules through guided Q&A or from CVEs/vulnerability descriptions. Supports search and taint analysis rule modes.
Ships in phoenix-sast-rules. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Generate valid opengrep/semgrep YAML rules through collaborative dialogue. Supports two workflows: guided (interactive Q&A to discover what to detect) and vulnerability-driven (given CVEs, OWASP categories, or vulnerability descriptions, generate rules automatically).
digraph rule_gen {
"User request" [shape=doublecircle];
"Has specific vulnerability?" [shape=diamond];
"Guided Discovery" [shape=box];
"Vulnerability-Driven" [shape=box];
"Gather context" [shape=box];
"Choose rule mode" [shape=diamond];
"Generate Search rule" [shape=box];
"Generate Taint rule" [shape=box];
"Present rule for review" [shape=box];
"User approves?" [shape=diamond];
"Write rule file" [shape=box];
"Generate test file" [shape=box];
"Validate with opengrep" [shape=doublecircle];
"User request" -> "Has specific vulnerability?";
"Has specific vulnerability?" -> "Vulnerability-Driven" [label="yes"];
"Has specific vulnerability?" -> "Guided Discovery" [label="no"];
"Guided Discovery" -> "Gather context";
"Vulnerability-Driven" -> "Gather context";
"Gather context" -> "Choose rule mode";
"Choose rule mode" -> "Generate Search rule" [label="pattern match"];
"Choose rule mode" -> "Generate Taint rule" [label="data flow"];
"Generate Search rule" -> "Present rule for review";
"Generate Taint rule" -> "Present rule for review";
"Present rule for review" -> "User approves?";
"User approves?" -> "Present rule for review" [label="revise"];
"User approves?" -> "Write rule file" [label="yes"];
"Write rule file" -> "Generate test file";
"Generate test file" -> "Validate with opengrep";
}
Before generating any rule, load context from these project docs:
| Doc | Path | Load When |
|---|---|---|
| Rule syntax & templates | docs/ai/RULES_SYNTAX.md | Always — contains all operators, templates, language IDs |
| Rule index | docs/ai/RULES_INDEX.md | When checking for existing similar rules |
| Engine internals | docs/ai/RULES_ENGINE.md | When choosing between search vs taint mode |
Also search existing rules for similar patterns:
semgrep-rules/semgrep-rules/<language>/ — community rulessemgrep-rules-trailbits/<language>/ — Trail of Bits rulesAsk these questions one at a time to scope the rule:
What vulnerability, bug pattern, or coding anti-pattern do you want to detect?
Examples:
- "SQL injection in our Flask app"
- "Hardcoded secrets in config files"
- "Missing null checks after API calls"
- "Insecure deserialization"
- "Race conditions in Go goroutines"
What programming language(s) and frameworks are involved?
I support 30+ languages including: python, javascript, typescript, java, go,
ruby, php, csharp, c, rust, scala, kotlin, swift, terraform/hcl, yaml,
dockerfile, solidity, and more. I also support 'generic' for config files
and 'regex' for raw text matching.
Can you show me an example of the VULNERABLE code you want to catch?
And if possible, also show the SAFE version (the fix)?
This helps me write precise patterns with fewer false positives.
Does this vulnerability involve untrusted user input flowing into a dangerous function?
If yes, I'll use TAINT MODE (tracks data flow from sources to sinks).
If no, I'll use SEARCH MODE (structural pattern matching).
For taint mode, I need to know:
- Sources: Where does untrusted data come from? (HTTP requests, file reads, env vars, etc.)
- Sinks: Where is it dangerous? (SQL queries, system commands, file writes, etc.)
- Sanitizers: What makes the data safe? (escaping, validation, type casting, etc.)
How severe is this issue?
- CRITICAL/ERROR: Exploitable vulnerability, must fix
- WARNING/MEDIUM: Likely vulnerability, should fix
- INFO/LOW: Code smell or audit flag
Should the rule apply to all files, or specific paths only?
When given CVEs, CWEs, OWASP categories, or vulnerability descriptions:
semgrep-rules/ and semgrep-rules-trailbits/ for coverageBefore generating rules, conduct research to ensure comprehensive coverage. Use WebSearch and WebFetch tools.
Phase 1 — Understand the vulnerability:
"<CVE/CWE ID>" vulnerability details to get official descriptions"<vulnerability type>" <language> exploit examples for real-world attack patternshttps://cwe.mitre.org/data/definitions/<ID>.html for taxonomy, related weaknesses, and detection methodshttps://owasp.org/Top10/A03_2021-Injection/)Phase 2 — Map language-specific attack surface:
"<vulnerability>" <framework> cheat sheet site:cheatsheetseries.owasp.org"<vulnerability>" <framework> security best practices"<vulnerable function>" CVE to find real CVEs demonstrating the patternPhase 3 — Study existing detection:
semgrep rule "<vulnerability type>" <language> for community rulessemgrep-rules/ and semgrep-rules-trailbits/ directoriesPhase 4 — Document findings: Write a brief research summary as a YAML comment block at the top of the rule file:
# Research: <vulnerability type> in <language/framework>
# Sources: <where untrusted data enters>
# Sinks: <where data becomes dangerous>
# Sanitizers: <what makes data safe>
# References researched:
# - <url1>
# - <url2>
# Coverage gaps found: <what existing rules miss>
| Vulnerability Type | Rule Mode | Why |
|---|---|---|
| SQL injection | Taint | User input → query function |
| XSS | Taint | User input → HTML output |
| Command injection | Taint | User input → exec/system |
| SSRF | Taint | User input → HTTP request |
| Path traversal | Taint | User input → file operation |
| Hardcoded secrets | Search + regex | Pattern match on literals |
| Insecure config | Search | Structural pattern on config |
| Missing auth checks | Search (inside/not-inside) | Absence of pattern |
| Race conditions | Search (inside + not-inside) | Pattern within goroutine/thread |
| Weak crypto | Search | Specific API calls |
| Deserialization | Search or Taint | Depends on if input-controlled |
| Terraform misconfig | Search | HCL structural patterns |
When generating a rule, always produce this complete structure:
rules:
- id: <company-or-project>-<language>-<vuln-type>
message: >-
<1-3 sentences: what was found, why it's dangerous, how to fix it>
severity: <ERROR|WARNING|INFO>
languages: [<language>]
metadata:
category: <security|correctness|best-practice|performance>
cwe:
- "CWE-XXX: <Description>"
owasp: # include if security rule
- "A0X:2021 - <Category>"
references:
- <url-to-documentation>
technology:
- <framework-or-library>
subcategory:
- <vuln|audit>
confidence: <HIGH|MEDIUM|LOW>
likelihood: <HIGH|MEDIUM|LOW>
impact: <HIGH|MEDIUM|LOW>
# ... pattern operators or taint spec ...
Rule IDs: <scope>-<language>-<vuln-type>[-<variant>]
myapp-python-sql-injectionmyapp-go-race-condition-map-writemyapp-java-spring-ssrfGood messages include:
message: >-
User input from `flask.request` is concatenated into a SQL query string
passed to `cursor.execute()`. This could allow SQL injection, letting an
attacker read or modify database contents. Use parameterized queries instead:
`cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))`.
Always generate a companion test file with:
# === True Positives (MUST trigger) ===
# ruleid: <rule-id>
<vulnerable code example 1>
# ruleid: <rule-id>
<vulnerable code example 2 — different variant>
# === True Negatives (must NOT trigger) ===
# ok: <rule-id>
<safe code — using the recommended fix>
# ok: <rule-id>
<safe code — different safe pattern>
Minimum: 2 true positives + 2 true negatives per rule.
patterns:
- pattern: dangerous_operation(...)
- pattern-not-inside: |
if <... auth_check(...) ...>:
...
mode: taint
pattern-sources:
- pattern: request.args.get(...)
pattern-sinks:
- patterns:
- pattern: |
"$SQLSTR" + ...
- metavariable-regex:
metavariable: $SQLSTR
regex: \s*(?i)(select|delete|insert|create|update|alter|drop)\b.*
patterns:
- pattern-inside: |
resource "aws_s3_bucket" "..." {
...
versioning { days = $DAYS }
...
}
- metavariable-comparison:
metavariable: $DAYS
comparison: $DAYS < 90
patterns:
- pattern-either:
- pattern: $OBJ.$METHOD(...)
- pattern: $MODULE.$METHOD(...)
- metavariable-regex:
metavariable: $METHOD
regex: (eval|exec|compile|unsafe_load)
# Go: match only http.Request types
pattern: ($REQ : *http.Request).$FIELD
mode: taint
pattern-sources:
- patterns:
- pattern: request.get_param(...)
label: USER_INPUT
- patterns:
- pattern: $X + $Y
label: CONCATENATED
requires: USER_INPUT
pattern-sinks:
- patterns:
- pattern: db.execute(...)
requires: CONCATENATED
After generating a rule, always consider adding:
pattern-not: func("...", ...) for literal strings)options: { taint_assume_safe_numbers: true, taint_assume_safe_booleans: true }pattern-not-inside: $LOG.info(...) to avoid flagging loggingBefore finalizing any rule:
languages field matches the target codeopengrep scan --config <rule.yaml> <test-file> if availableWhen asked to generate rules for a class of vulnerabilities (e.g., "OWASP Top 10 for Python Flask"):
semgrep-rules/Follow this systematic process to generate high-quality rules:
Don't just pattern-match on function names. Understand:
Before writing from scratch, search existing rules for similar patterns:
semgrep-rules/semgrep-rules/<language>/<framework>/security/
semgrep-rules-trailbits/<language>/
Read the best-quality rules and adapt their patterns. Existing rules show:
For each language/framework, document:
| Component | Examples |
|---|---|
| Sources (user input entry points) | request.args, req.query, $_GET, params[:] |
| Sinks (dangerous output points) | res.send(), echo, innerHTML, cursor.execute() |
| Sanitizers (safe transformations) | escape(), htmlspecialchars(), parseInt(), template engines |
| Propagators (data structure flow) | StringBuilder.append(), HashMap.put(), array.push() |
Write rules in layers:
dangerouslySetInnerHTML)autoescape off)After initial rule generation:
pattern-not for safe literals, safe types, loggingpattern-not-inside for try/catch, validation wrapperstaint_assume_safe_numbers: true and taint_assume_safe_booleans: truemetavariable-regex to restrict to dangerous method namesWhen generating rules, these docs contain the complete rule schema:
| What You Need | Where to Find It |
|---|---|
| All pattern operators | docs/ai/RULES_SYNTAX.md §3-5 |
| Taint mode spec (sources/sinks/sanitizers/propagators/labels) | docs/ai/RULES_SYNTAX.md §6 |
| Metavariable conditions (regex, comparison, type, pattern) | docs/ai/RULES_SYNTAX.md §4 |
| All supported languages | docs/ai/RULES_SYNTAX.md §9 |
| Rule templates (8 complete examples) | docs/ai/RULES_SYNTAX.md §12 |
| How the engine matches patterns | docs/ai/RULES_ENGINE.md §2 |
| How taint analysis works internally | docs/ai/RULES_ENGINE.md §3 |
| Existing rule coverage by language | docs/ai/RULES_INDEX.md |
| CWE/OWASP metadata conventions | docs/ai/RULES_SYNTAX.md §7 |
| Rule options (engine config) | docs/ai/RULES_SYNTAX.md §8 |
Store generated rules in custom-rules/<vuln-type>/ with companion test files:
custom-rules/
xss/
xss-python-flask.yaml # Rules
xss-python-flask.py # Test file
sqli/
sqli-java-spring.yaml
sqli-java-spring.java
| Mistake | Fix |
|---|---|
Pattern too broad ($FUNC(...)) | Add metavariable-regex or pattern-inside to constrain |
| Missing ellipsis in function bodies | Use ... in function/class bodies for flexible matching |
Forgetting pattern-not for safe variants | Always consider: what does the SAFE code look like? |
| Wrong language ID | Check docs/ai/RULES_SYNTAX.md Section 9 for valid IDs |
| Taint without sanitizers | Always ask: what makes this data safe? Add sanitizers. |
| Hardcoding framework versions | Use ... for version-agnostic patterns |
| Not testing negatives | False positives destroy trust — test safe code paths |
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
sast, static-analysis, vulnerability-detection, rule-generation, semgrep
2 skills in this plugin
npx claudepluginhub security-phoenix-demo/security-skills-claude-code --plugin phoenix-sast-rulesOther plugins' skills for the same job