Back to Security & Vulnerability Analysis

variant-analysis

security auditvulnerability analysisbug huntingcodeqlsemgreppattern matchingcode analysisstatic analysis
⭐ 5.7kπŸ“„ CC-BY-SA-4.0πŸ•’ 2026-06-15Source β†—

Install this skill

npx skills add trailofbits/skills

Works across Claude Code, Cursor, Codex, Copilot & Antigravity

Variant analysis acts as a force multiplier for security audits by locating look-alike bugs throughout an entire codebase. Once a vulnerability is confirmed, this skill transitions into a systematic hunt to identify every instance where the same flawed logic or insecure pattern exists. It focuses on the root cause rather than symptoms, requiring a structured approach of initial pattern capture followed by intentional, incremental generalization. By using tools like Semgrep and CodeQL, the process maps the abstract vulnerability signature against the full project structure. This methodology prevents the narrow focus that often leaves secondary vulnerabilities hidden in obscure modules or disparate code paths, ensuring that a single discovery transforms into a full-scale audit of the application's security posture.

When to Use This Skill

  • β€’Identifying similar buffer overflows after discovering an initial overflow in a string handling function
  • β€’Finding missing authentication checks across multiple API endpoints following an authorization bypass report
  • β€’Tracing input sanitization failures that recur across different data processing modules
  • β€’Detecting inconsistent error handling logic that could lead to information disclosure

How to Invoke This Skill

Example prompts that trigger this skill in Claude Code, Cursor, or Antigravity:

  • β€œFind similar vulnerabilities based on this code pattern
  • β€œIdentify other instances of this root cause in the repository
  • β€œGeneralize this Semgrep rule to cover related variants
  • β€œAudit the codebase for bugs matching the logic of this specific vulnerability
  • β€œWhere else does this security flaw appear in the project?

Pro Tips

  • πŸ’‘Always start by deeply understanding the root cause, not just the symptom, of the initial vulnerability before asking the agent to search for variants.
  • πŸ’‘Provide specific examples of the 'bad' pattern and, if possible, 'good' safe patterns to guide the agent in distinguishing true positives.
  • πŸ’‘Iteratively refine your search criteria with the agent, providing feedback on false positives or missed instances to improve its pattern recognition.

What this skill does

  • β€’Abstracting specific code constructs into generalized query patterns
  • β€’Identifying interprocedural data flow issues using automated analysis
  • β€’Filtering search results to maintain a low false-positive rate
  • β€’Mapping single root causes to multiple architectural manifestations
  • β€’Validating pattern reachability across diverse code components

When not to use it

  • βœ•Initial discovery of an unknown vulnerability class
  • βœ•Providing automated remediation or code refactoring for found issues
  • βœ•General static analysis without a known reference bug

Example workflow

  1. Isolate the root cause of the known vulnerability.
  2. Execute an exact-match search to confirm the baseline instance.
  3. Introduce incremental abstractions to the search pattern.
  4. Evaluate match results to verify true positives.
  5. Stop generalization when the false positive rate exceeds 50%.
  6. Triage identified variants by reachability and impact.

Prerequisites

  • –Confirmed vulnerability pattern
  • –Access to static analysis tools like Semgrep or CodeQL

Pitfalls & limitations

  • !Generalizing too quickly, resulting in overwhelming noise or false positives
  • !Limiting searches to the directory of origin instead of the entire project
  • !Ignoring related vulnerability manifestations that stem from the same root error

FAQ

How do I know when to stop generalizing my pattern?
Stop when the false-positive rate exceeds 50%. If more than half of your matches are irrelevant, your pattern is likely too broad.
Should I use this for initial bug hunting?
No. Use specific audit context-building techniques for discovery; reserve this skill for after you have a confirmed bug pattern to replicate.
Does this replace manual code review?
It complements manual review by automating the search for specific known patterns, allowing you to cover more ground than manual inspection alone.

How it compares

Unlike manual grepping or generic prompting, this skill enforces a rigorous scientific method of incremental generalization and result validation to minimize noise.

Source & trust

⭐ 5.7k starsπŸ“„ CC-BY-SA-4.0πŸ•’ Updated 2026-06-15
πŸ“„ Full skill instructions β€” original source: trailofbits/skills
# Variant Analysis

You are a variant analysis expert. Your role is to help find similar vulnerabilities and bugs across a codebase after identifying an initial pattern.

## When to Use

Use this skill when:
- A vulnerability has been found and you need to search for similar instances
- Building or refining CodeQL/Semgrep queries for security patterns
- Performing systematic code audits after an initial issue discovery
- Hunting for bug variants across a codebase
- Analyzing how a single root cause manifests in different code paths

## When NOT to Use

Do NOT use this skill for:
- Initial vulnerability discovery (use audit-context-building or domain-specific audits instead)
- General code review without a known pattern to search for
- Writing fix recommendations (use issue-writer instead)
- Understanding unfamiliar code (use audit-context-building for deep comprehension first)

## The Five-Step Process

### Step 1: Understand the Original Issue

Before searching, deeply understand the known bug:
- **What is the root cause?** Not the symptom, but WHY it's vulnerable
- **What conditions are required?** Control flow, data flow, state
- **What makes it exploitable?** User control, missing validation, etc.

### Step 2: Create an Exact Match

Start with a pattern that matches ONLY the known instance:
rg -n "exact_vulnerable_code_here"

Verify: Does it match exactly ONE location (the original)?

### Step 3: Identify Abstraction Points

| Element | Keep Specific | Can Abstract |
|---------|---------------|--------------|
| Function name | If unique to bug | If pattern applies to family |
| Variable names | Never | Always use metavariables |
| Literal values | If value matters | If any value triggers bug |
| Arguments | If position matters | Use ... wildcards |

### Step 4: Iteratively Generalize

**Change ONE element at a time:**
1. Run the pattern
2. Review ALL new matches
3. Classify: true positive or false positive?
4. If FP rate acceptable, generalize next element
5. If FP rate too high, revert and try different abstraction

**Stop when false positive rate exceeds ~50%**

### Step 5: Analyze and Triage Results

For each match, document:
- **Location**: File, line, function
- **Confidence**: High/Medium/Low
- **Exploitability**: Reachable? Controllable inputs?
- **Priority**: Based on impact and exploitability

For deeper strategic guidance, see [METHODOLOGY.md](METHODOLOGY.md).

## Tool Selection

| Scenario | Tool | Why |
|----------|------|-----|
| Quick surface search | ripgrep | Fast, zero setup |
| Simple pattern matching | Semgrep | Easy syntax, no build needed |
| Data flow tracking | Semgrep taint / CodeQL | Follows values across functions |
| Cross-function analysis | CodeQL | Best interprocedural analysis |
| Non-building code | Semgrep | Works on incomplete code |

## Key Principles

1. **Root cause first**: Understand WHY before searching for WHERE
2. **Start specific**: First pattern should match exactly the known bug
3. **One change at a time**: Generalize incrementally, verify after each change
4. **Know when to stop**: 50%+ FP rate means you've gone too generic
5. **Search everywhere**: Always search the ENTIRE codebase, not just the module where the bug was found
6. **Expand vulnerability classes**: One root cause often has multiple manifestations

## Critical Pitfalls to Avoid

These common mistakes cause analysts to miss real vulnerabilities:

### 1. Narrow Search Scope

Searching only the module where the original bug was found misses variants in other locations.

**Example:** Bug found in api/handlers/ β†’ only searching that directory β†’ missing variant in utils/auth.py

**Mitigation:** Always run searches against the entire codebase root directory.

### 2. Pattern Too Specific

Using only the exact attribute/function from the original bug misses variants using related constructs.

**Example:** Bug uses isAuthenticated check β†’ only searching for that exact term β†’ missing bugs using related properties like isActive, isAdmin, isVerified

**Mitigation:** Enumerate ALL semantically related attributes/functions for the bug class.

### 3. Single Vulnerability Class

Focusing on only one manifestation of the root cause misses other ways the same logic error appears.

**Example:** Original bug is "return allow when condition is false" β†’ only searching that pattern β†’ missing:
- Null equality bypasses (null == null evaluates to true)
- Documentation/code mismatches (function does opposite of what docs claim)
- Inverted conditional logic (wrong branch taken)

**Mitigation:** List all possible manifestations of the root cause before searching.

### 4. Missing Edge Cases

Testing patterns only with "normal" scenarios misses vulnerabilities triggered by edge cases.

**Example:** Testing auth checks only with valid users β†’ missing bypass when userId = null matches resourceOwnerId = null

**Mitigation:** Test with: unauthenticated users, null/undefined values, empty collections, and boundary conditions.

## Resources

Ready-to-use templates in resources/:

**CodeQL** (resources/codeql/):
- python.ql, javascript.ql, java.ql, go.ql, cpp.ql

**Semgrep** (resources/semgrep/):
- python.yaml, javascript.yaml, java.yaml, go.yaml, cpp.yaml

**Report**: resources/variant-report-template.md

How to Use This Skill Unit

Option A: Project-Specific (Recommended)

  1. Click "Download" above
  2. In your project, create the directory: .agent/skills/variant-analysis/
  3. Save the file as SKILL.md
  4. The agent will automatically discover the skill based on its description.

Option B: Global Installation (All Agents)

Save the file to these locations to make it available across all projects:

  • Claude Code: ~/.claude/skills/trailofbits/skills/variant-analysis/SKILL.md
  • Cursor: ~/.cursor/skills/trailofbits/skills/variant-analysis/SKILL.md
  • Antigravity: ~/.gemini/antigravity/skills/trailofbits/skills/variant-analysis/SKILL.md

πŸš€ Install with CLI:
npx skills add trailofbits/skills

Read the Master Guide: Mastering Agent Skills β†’

Related Skill Units

Recommended Rules

View more rules β†’

Recommended Workflows

View more workflows β†’

Recommended MCP Servers

View more MCP servers β†’

Take It Further

Maximize your productivity with these powerful resources

πŸ“‹

Define Your Standards

Set up coding standards to ensure this workflow produces consistent, high-quality results.

Browse Rules Library
πŸ“–

Master Workflows

Learn how to create custom workflows, use Turbo Mode, and build your automation library.

Complete Guide

How to use this Skill in Claude Code & Cursor

For Claude Code (CLI)

To use this skill in Claude Code, copy the rule content into your project's custom instructions or follow our Add-Skill CLI guide. This ensures Claude follows your standards during every code generation.

For Cursor & Windsurf

For Cursor or Windsurf, individual skills are best used in the "Rules for AI" section. This specific unit helps the agent avoid security & vulnerability analysis issues, leading to cleaner, more efficient code.

Why the skill format matters: the standardized Agent Skills format lets your AI agent load detailed instructions only when they are relevant, keeping your prompt clean while improving results.

Source & attribution

This skill is categorized under Security & Vulnerability Analysis and is published by Trail of Bits, maintained in trailofbits/skills.

← Browse All Agent Skills
Sponsored AI assistant. Recommendations may be paid.