Back to skills
SkillHub ClubRun DevOpsFull StackSecurity

vulnhunter

Security vulnerability detection and variant analysis skill. Use when hunting for dangerous APIs, footgun patterns, error-prone configurations, and vulnerability variants across codebases. Combines sharp edges detection with variant hunting methodology.

Packaged view

This page reorganizes the original catalog entry around fit, installability, and workflow context first. The original raw source lives below.

Stars
67
Hot score
92
Updated
March 20, 2026
Overall rating
C3.5
Composite score
3.5
Best-practice grade
B73.6

Install command

npx @skill-hub/cli install sendaifun-skills-vulnhunter

Repository

sendaifun/skills

Skill path: skills/vulnhunter

Security vulnerability detection and variant analysis skill. Use when hunting for dangerous APIs, footgun patterns, error-prone configurations, and vulnerability variants across codebases. Combines sharp edges detection with variant hunting methodology.

Open repository

Best for

Primary workflow: Run DevOps.

Technical facets: Full Stack, Security.

Target audience: everyone.

License: Unknown.

Original source

Catalog source: SkillHub Club.

Repository owner: sendaifun.

This is still a mirrored public skill entry. Review the repository before installing into production workflows.

What it helps with

  • Install vulnhunter into Claude Code, Codex CLI, Gemini CLI, or OpenCode workflows
  • Review https://github.com/sendaifun/skills before adding vulnhunter to shared team environments
  • Use vulnhunter for development workflows

Works across

Claude CodeCodex CLIGemini CLIOpenCode

Favorites: 0.

Sub-skills: 0.

Aggregator: No.

Original source / Raw SKILL.md

---
name: vulnhunter
description: Security vulnerability detection and variant analysis skill. Use when hunting for dangerous APIs, footgun patterns, error-prone configurations, and vulnerability variants across codebases. Combines sharp edges detection with variant hunting methodology.
---

# VulnHunter - Security Vulnerability Detection & Analysis

A comprehensive security audit skill for identifying dangerous APIs, footgun patterns, error-prone configurations, and hunting for vulnerability variants across codebases. Inspired by Trail of Bits' sharp-edges and variant-analysis methodologies.

## Overview

VulnHunter combines two powerful security analysis techniques:
1. **Sharp Edges Detection** - Identify error-prone APIs, dangerous defaults, and footgun designs
2. **Variant Analysis** - Find similar vulnerabilities across codebases using pattern-based analysis

### When to Use VulnHunter

**Activate this skill when:**
- Conducting security code reviews or audits
- Reviewing third-party dependencies for dangerous patterns
- Hunting for variants of known vulnerabilities
- Assessing API design for security footguns
- Pre-audit reconnaissance of unfamiliar codebases

## Sharp Edges Detection

### Categories of Sharp Edges

#### 1. Dangerous Default Configurations
Look for configurations that are insecure by default:

```
- CORS: Access-Control-Allow-Origin: *
- Debug modes enabled in production
- Default credentials or API keys
- Permissive file permissions (777, 666)
- SSL/TLS verification disabled
- Insecure deserialization settings
```

#### 2. Error-Prone APIs

**Memory Safety:**
```c
// Dangerous: No bounds checking
strcpy(), strcat(), sprintf(), gets()
memcpy() without size validation

// Safer alternatives
strncpy(), strncat(), snprintf(), fgets()
memcpy_s() with explicit size
```

**Cryptography Footguns:**
```
- ECB mode encryption
- MD5/SHA1 for security purposes
- Hardcoded IVs or salts
- Custom crypto implementations
- Random without CSPRNG (Math.random for tokens)
```

**Concurrency Issues:**
```
- Race conditions in file operations
- Time-of-check to time-of-use (TOCTOU)
- Double-checked locking anti-patterns
- Non-atomic increment/decrement operations
```

#### 3. Language-Specific Footguns

**JavaScript/TypeScript:**
```javascript
// Dangerous patterns
eval(), new Function(), setTimeout(string)
innerHTML, outerHTML, document.write()
Object.assign() for deep clone (shallow only!)
== instead of === (type coercion)
```

**Python:**
```python
# Dangerous patterns
pickle.loads(untrusted)  # RCE vector
yaml.load(untrusted)     # Use safe_load
exec(), eval()
os.system(), subprocess with shell=True
```

**Rust:**
```rust
// Patterns requiring extra scrutiny
unsafe { }
.unwrap() in production code
mem::transmute()
raw pointer dereference
```

**Solidity/Smart Contracts:**
```solidity
// High-risk patterns
tx.origin for authentication  // Phishing vulnerable
delegatecall to untrusted     // Storage collision
selfdestruct                  // Permanent destruction
block.timestamp for randomness // Miner manipulable
```

### Sharp Edges Checklist

When reviewing code, systematically check for:

- [ ] **Authentication bypasses** - Missing auth checks, default credentials
- [ ] **Authorization flaws** - Privilege escalation, IDOR patterns
- [ ] **Injection vectors** - SQL, Command, Template, XSS
- [ ] **Cryptographic weaknesses** - Weak algorithms, improper key handling
- [ ] **Resource exhaustion** - Unbounded loops, memory allocation
- [ ] **Race conditions** - TOCTOU, concurrent state modification
- [ ] **Information disclosure** - Verbose errors, debug endpoints
- [ ] **Deserialization** - Untrusted data unmarshaling
- [ ] **Path traversal** - User-controlled file paths
- [ ] **SSRF vectors** - User-controlled URLs, redirects

## Variant Analysis

### The Variant Hunting Process

1. **Identify the Root Cause** - Understand WHY a vulnerability exists
2. **Extract the Pattern** - What code structure enables it?
3. **Generalize the Pattern** - Create regex/AST patterns
4. **Search Codebase** - Hunt for similar structures
5. **Validate Findings** - Confirm each variant is exploitable

### Pattern Extraction Templates

#### Template 1: Missing Validation Pattern
```
Original bug: User input flows to SQL query without sanitization
Pattern: [user_input] -> [sink_function] without [validation_function]

Search for:
- Direct database calls with string concatenation
- ORM raw query methods with user parameters
- Similar data flows in adjacent modules
```

#### Template 2: Authentication Bypass
```
Original bug: Endpoint missing auth middleware
Pattern: Route definition without auth decorator/middleware

Search for:
- Routes defined after the vulnerable one
- Similar API patterns in other modules
- Admin/internal endpoints
```

#### Template 3: Race Condition
```
Original bug: Check-then-act without atomicity
Pattern: if (check_condition()) { act_on_condition() }

Search for:
- File existence checks followed by file operations
- Permission checks followed by privileged actions
- Balance checks followed by transfers
```

### Search Strategies

#### Grep-Based Search
```bash
# Find potential SQL injection
grep -rn "execute.*%s" --include="*.py"
grep -rn "query.*\+" --include="*.js"

# Find dangerous deserialize
grep -rn "pickle.loads\|yaml.load\|eval(" --include="*.py"

# Find command injection vectors
grep -rn "os.system\|subprocess.*shell=True" --include="*.py"
```

#### Semantic Search (AST-Based)
For more precise matching, use AST-based tools:
- **Semgrep** - Cross-language semantic grep
- **CodeQL** - GitHub's semantic analysis
- **tree-sitter** - Universal parser

### Variant Analysis Report Template

```markdown
## Variant Analysis Report

### Original Finding
- **ID**: FINDING-001
- **Severity**: High
- **Root Cause**: [Description]
- **Affected File**: path/to/file.ext:line

### Pattern Extracted
[Code pattern or regex]

### Variants Discovered

| # | Location | Severity | Status | Notes |
|---|----------|----------|--------|-------|
| 1 | file.ext:42 | High | Confirmed | Same root cause |
| 2 | other.ext:100 | Medium | Suspected | Needs validation |

### Recommendations
[Systematic fix approach]
```

## Workflow

### Phase 1: Reconnaissance
1. Identify technology stack and languages
2. Map entry points (APIs, CLI, file inputs)
3. Locate authentication/authorization logic
4. Find cryptographic operations
5. Identify external integrations

### Phase 2: Sharp Edges Scan
1. Run through sharp edges checklist
2. Focus on security-critical paths
3. Document all suspicious patterns
4. Cross-reference with known CVEs

### Phase 3: Variant Hunting
1. For each finding, extract pattern
2. Search for variants systematically
3. Validate each potential variant
4. Assess aggregate risk

### Phase 4: Reporting
1. Consolidate findings by category
2. Assign severity ratings
3. Provide remediation guidance
4. Highlight systemic issues

## Integration with Static Analysis

### Semgrep Rules for Common Patterns

```yaml
# Example: Detect SQL injection in Python
rules:
  - id: sql-injection-format
    patterns:
      - pattern: $CURSOR.execute($QUERY % ...)
    message: "Potential SQL injection via string formatting"
    severity: ERROR
    languages: [python]
```

### CodeQL Queries

```ql
// Find tainted data flowing to dangerous sinks
import python
import semmle.python.dataflow.TaintTracking

from DataFlow::PathNode source, DataFlow::PathNode sink
where TaintTracking::localTaint(source.getNode(), sink.getNode())
  and sink.getNode().asExpr().(Call).getTarget().getName() = "execute"
select sink, source, sink, "Tainted input reaches SQL execution"
```

## Examples

See the `/examples` folder for:
- Real-world sharp edges examples by language
- Variant analysis case studies
- Pattern extraction walkthroughs

## Resources

- `resources/sharp-edges-catalog.md` - Comprehensive catalog of dangerous patterns
- `resources/variant-patterns.md` - Common vulnerability pattern templates
- `templates/variant-report.md` - Report template for variant analysis

## Guidelines

1. **Always verify** - Don't report theoretical issues as confirmed vulnerabilities
2. **Context matters** - A pattern may be safe in one context, dangerous in another
3. **Prioritize exploitability** - Focus on patterns that lead to real impact
4. **Document assumptions** - Note any threat model assumptions
5. **Systemic over point fixes** - Recommend architectural improvements when patterns repeat

## Skill Files

```
vulnhunter/
├── SKILL.md                          # This file
├── resources/
│   ├── sharp-edges-catalog.md        # Categorized dangerous patterns
│   └── variant-patterns.md           # Vulnerability pattern templates
├── examples/
│   ├── smart-contracts/              # Solidity/blockchain examples
│   ├── web-apps/                     # Web application examples
│   └── native-code/                  # C/C++/Rust examples
├── templates/
│   └── variant-report.md             # Analysis report template
└── docs/
    └── methodology.md                # Detailed methodology guide
```


---

## Referenced Files

> The following files are referenced in this skill and included for context.

### resources/sharp-edges-catalog.md

```markdown
# Sharp Edges Catalog

Comprehensive catalog of dangerous patterns, footguns, and security anti-patterns organized by category.

## Memory Safety

### C/C++

| Function | Risk | Safer Alternative |
|----------|------|-------------------|
| `strcpy()` | Buffer overflow | `strncpy()`, `strlcpy()` |
| `strcat()` | Buffer overflow | `strncat()`, `strlcat()` |
| `sprintf()` | Buffer overflow | `snprintf()` |
| `gets()` | Buffer overflow (unbounded) | `fgets()` |
| `scanf("%s")` | Buffer overflow | `scanf("%Ns")` with limit |
| `memcpy()` | No bounds check | Validate size first |
| `alloca()` | Stack overflow | `malloc()` with checks |

### Use-After-Free Patterns
```c
// Dangerous: pointer used after free
free(ptr);
ptr->field = value;  // UAF

// Dangerous: double free
free(ptr);
// ... code ...
free(ptr);  // Double free

// Safe: null after free
free(ptr);
ptr = NULL;
```

## Cryptography

### Weak Algorithms (DO NOT USE)

| Algorithm | Risk | Replacement |
|-----------|------|-------------|
| MD5 | Collision attacks | SHA-256+ |
| SHA1 | Collision attacks | SHA-256+ |
| DES | Key size too small | AES-256 |
| 3DES | Performance + deprecation | AES-256 |
| RC4 | Multiple weaknesses | ChaCha20 |
| ECB mode | Pattern preservation | GCM, CBC |

### Cryptographic Footguns

```python
# BAD: Hardcoded IV
iv = b'\x00' * 16
cipher = AES.new(key, AES.MODE_CBC, iv)

# GOOD: Random IV
iv = os.urandom(16)
cipher = AES.new(key, AES.MODE_CBC, iv)
```

```python
# BAD: Predictable random for tokens
import random
token = random.randint(0, 2**32)

# GOOD: Cryptographically secure
import secrets
token = secrets.token_hex(32)
```

```javascript
// BAD: Math.random for security
const token = Math.random().toString(36);

// GOOD: Crypto API
const token = crypto.randomBytes(32).toString('hex');
```

## Authentication & Authorization

### Session Management
```python
# BAD: Predictable session IDs
session_id = str(user_id) + str(timestamp)

# BAD: Session fixation vulnerable
session_id = request.cookies.get('session')  # Use existing

# GOOD: Regenerate on auth state change
session.regenerate()
session_id = secrets.token_urlsafe(32)
```

### Authorization Bypass Patterns
```python
# BAD: Client-controlled authorization
is_admin = request.json.get('is_admin', False)

# BAD: Insecure direct object reference
def get_document(doc_id):
    return Document.query.get(doc_id)  # No ownership check

# GOOD: Always verify ownership
def get_document(doc_id, user):
    doc = Document.query.get(doc_id)
    if doc.owner_id != user.id:
        raise Forbidden()
    return doc
```

### Timing Attacks
```python
# BAD: Early return reveals validity
def check_token(token):
    if len(token) != 32:
        return False
    return token == expected_token  # String compare varies

# GOOD: Constant-time comparison
import hmac
def check_token(token):
    return hmac.compare_digest(token, expected_token)
```

## Injection Vulnerabilities

### SQL Injection
```python
# BAD: String concatenation
query = "SELECT * FROM users WHERE id = " + user_id
cursor.execute(query)

# BAD: Format strings
cursor.execute("SELECT * FROM users WHERE name = '%s'" % name)

# GOOD: Parameterized queries
cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,))
```

### Command Injection
```python
# BAD: Shell with user input
os.system(f"ping {user_input}")
subprocess.call(f"convert {filename}", shell=True)

# GOOD: No shell, array arguments
subprocess.run(["ping", "-c", "4", validated_host], shell=False)
```

### Template Injection
```python
# BAD: User input in template
template = Template(user_input)
template.render()

# BAD: Format string injection
"Hello, {name}".format(**user_dict)

# GOOD: Sandboxed templates with escaping
env = Environment(autoescape=True)
template = env.from_string(static_template)
template.render(name=user_input)
```

## Deserialization

### Dangerous Deserializers

| Language | Dangerous | Safer |
|----------|-----------|-------|
| Python | `pickle.loads()` | JSON, `yaml.safe_load()` |
| Python | `yaml.load()` | `yaml.safe_load()` |
| Java | `ObjectInputStream` | JSON with allow-list |
| Ruby | `Marshal.load()` | JSON |
| PHP | `unserialize()` | `json_decode()` |
| .NET | `BinaryFormatter` | JSON with type validation |

```python
# BAD: Arbitrary code execution
import pickle
data = pickle.loads(untrusted_bytes)  # RCE!

# BAD: YAML code execution
import yaml
data = yaml.load(untrusted_string)  # RCE!

# GOOD: Safe alternatives
import json
data = json.loads(untrusted_string)

import yaml
data = yaml.safe_load(untrusted_string)
```

## Web Security

### Cross-Site Scripting (XSS)
```javascript
// BAD: Direct innerHTML
element.innerHTML = userInput;

// BAD: document.write
document.write(userInput);

// BAD: jQuery html()
$(element).html(userInput);

// GOOD: textContent (no parsing)
element.textContent = userInput;

// GOOD: DOMPurify for rich content
element.innerHTML = DOMPurify.sanitize(userInput);
```

### Cross-Origin Issues
```javascript
// BAD: Overly permissive CORS
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true  // Together = vulnerability

// BAD: postMessage without origin check
window.addEventListener('message', (e) => {
  handleData(e.data);  // No origin verification!
});

// GOOD: Verify origin
window.addEventListener('message', (e) => {
  if (e.origin !== 'https://trusted.com') return;
  handleData(e.data);
});
```

## Smart Contracts (Solidity)

### Access Control
```solidity
// BAD: tx.origin for auth (phishable)
require(tx.origin == owner);

// GOOD: msg.sender
require(msg.sender == owner);
```

### Reentrancy
```solidity
// BAD: External call before state update
function withdraw() external {
    uint amount = balances[msg.sender];
    (bool success,) = msg.sender.call{value: amount}("");
    balances[msg.sender] = 0;  // Too late!
}

// GOOD: Checks-Effects-Interactions
function withdraw() external {
    uint amount = balances[msg.sender];
    balances[msg.sender] = 0;  // State update FIRST
    (bool success,) = msg.sender.call{value: amount}("");
    require(success);
}
```

### Integer Overflow (pre-0.8.0)
```solidity
// BAD (Solidity < 0.8): Overflow
uint256 balance = type(uint256).max;
balance += 1;  // Wraps to 0!

// GOOD: SafeMath or Solidity 0.8+
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
balance = balance.add(1);  // Reverts on overflow
```

### Frontrunning
```solidity
// VULNERABLE: Visible pending transactions can be frontrun
function buyToken(uint maxPrice) external {
    require(tokenPrice <= maxPrice);  // Attacker can sandwich
    // ...
}

// MITIGATION: Commit-reveal or private mempools
```

## Concurrency

### Race Conditions
```python
# BAD: TOCTOU (Time-of-check to time-of-use)
if os.path.exists(filepath):
    with open(filepath) as f:  # File could be changed!
        return f.read()

# GOOD: Handle atomically
try:
    with open(filepath) as f:
        return f.read()
except FileNotFoundError:
    return None
```

```python
# BAD: Non-atomic check-then-act
if balance >= amount:
    balance -= amount  # Race condition!

# GOOD: Atomic operation or lock
with balance_lock:
    if balance >= amount:
        balance -= amount
```

## Configuration

### Dangerous Defaults

| Setting | Dangerous Value | Secure Value |
|---------|-----------------|--------------|
| Debug mode | `DEBUG=True` | `DEBUG=False` in prod |
| Secret key | Hardcoded/default | Environment variable |
| CORS | `*` | Specific origins |
| Cookie | `Secure=False` | `Secure=True; HttpOnly; SameSite=Strict` |
| TLS verify | `verify=False` | `verify=True` |
| File permissions | `777` | Least privilege |

### Environment Exposure
```bash
# BAD: Secrets in code
API_KEY = "sk-abc123..."

# BAD: Secrets in docker-compose.yml (committed)
environment:
  - API_KEY=sk-abc123

# GOOD: External secret management
API_KEY = os.environ['API_KEY']
# Or use: AWS Secrets Manager, Vault, etc.
```

```

### resources/variant-patterns.md

```markdown
# Variant Analysis Patterns

Reusable templates for hunting vulnerability variants across codebases.

## Pattern Extraction Framework

### Step 1: Decompose the Vulnerability

```
┌─────────────────────────────────────────────────────────────┐
│                    VULNERABILITY                            │
├─────────────────────────────────────────────────────────────┤
│  SOURCE      │  Where does attacker-controlled data enter?  │
│  TRANSFORM   │  How is the data processed/modified?         │
│  SINK        │  Where does the data cause harm?             │
│  MISSING     │  What validation/sanitization is absent?     │
└─────────────────────────────────────────────────────────────┘
```

### Step 2: Create Search Patterns

#### Regex Patterns
```
# General template
[source_pattern].*[transform_pattern]?.*[sink_pattern]

# Without [validation_pattern] between source and sink
```

#### AST Patterns (Semgrep style)
```yaml
patterns:
  - pattern: |
      $SOURCE = request.$METHOD(...)
      ...
      $SINK($SOURCE)
  - pattern-not: |
      $SOURCE = request.$METHOD(...)
      ...
      $SANITIZED = sanitize($SOURCE)
      ...
      $SINK($SANITIZED)
```

## Common Vulnerability Patterns

### Pattern 1: SQL Injection Variants

**Original Finding:**
```python
cursor.execute("SELECT * FROM users WHERE id = " + request.args['id'])
```

**Pattern Abstraction:**
```
user_input -> string_concat/format -> sql_execute
```

**Search Patterns:**
```python
# Pattern A: String concatenation
r'execute\([^)]*\+.*request'
r'execute\([^)]*\+.*params'

# Pattern B: Format strings
r'execute\([^)]*%.*%'
r'execute\([^)]*\.format'

# Pattern C: f-strings
r'execute\(f["\'].*\{'
```

**Variant Locations to Check:**
- Other database methods: `fetchone`, `fetchall`, `executemany`
- ORM raw queries: `Model.objects.raw()`, `session.execute()`
- Different input sources: POST body, headers, cookies

---

### Pattern 2: Command Injection Variants

**Original Finding:**
```python
os.system(f"ping {user_host}")
```

**Pattern Abstraction:**
```
user_input -> command_string -> shell_execution
```

**Search Patterns:**
```python
# Direct execution
r'os\.system\([^)]*\{'
r'subprocess\..*shell\s*=\s*True'
r'Popen\([^)]*shell\s*=\s*True'

# Backtick/eval equivalents
r'eval\(.*request'
r'exec\(.*input'
```

**Variant Locations:**
- CI/CD configurations (shell commands)
- Build scripts
- System utilities
- Log processing

---

### Pattern 3: Path Traversal Variants

**Original Finding:**
```python
file_path = os.path.join("/uploads", user_filename)
open(file_path)
```

**Pattern Abstraction:**
```
user_input -> path_construction -> file_operation
```

**Search Patterns:**
```python
# Path operations with user input
r'os\.path\.join\([^)]*request'
r'open\([^)]*\+.*input'
r'Path\([^)]*request'
r'send_file\(.*filename'

# Archive extraction
r'extractall\('
r'ZipFile.*extract'
r'tarfile.*extract'
```

**Variants:**
- Download endpoints
- File upload handling
- Template loading
- Static file serving
- Log file access

---

### Pattern 4: SSRF Variants

**Original Finding:**
```python
requests.get(user_url)
```

**Pattern Abstraction:**
```
user_input -> url_construction -> http_request
```

**Search Patterns:**
```python
# HTTP libraries
r'requests\.(get|post|put)\([^)]*request'
r'urllib\..*open\([^)]*user'
r'http\.client.*request'
r'aiohttp.*session\.(get|post)'

# URL in redirects
r'redirect\(.*request'
r'HttpResponseRedirect\([^)]*input'
```

**Variants:**
- Webhook configurations
- OAuth callbacks
- PDF generation (URL fetching)
- Image proxy services
- Link preview features

---

### Pattern 5: Insecure Deserialization

**Original Finding:**
```python
data = pickle.loads(request.data)
```

**Pattern Abstraction:**
```
untrusted_bytes -> deserialize -> object_instantiation
```

**Search Patterns:**
```python
# Python
r'pickle\.loads?\('
r'yaml\.load\([^)]*$'  # Without safe_load
r'marshal\.loads?\('

# Java patterns
r'ObjectInputStream'
r'readObject\(\)'
r'XMLDecoder'

# PHP
r'unserialize\('
```

**Variants:**
- Session storage backends
- Cache systems (Redis, Memcached)
- Message queues
- RPC mechanisms
- Cookie values

---

### Pattern 6: Hardcoded Secrets

**Original Finding:**
```python
API_KEY = "sk-live-abc123"
```

**Pattern Abstraction:**
```
literal_string -> assignment -> sensitive_variable
```

**Search Patterns:**
```python
# API keys and tokens
r'(api[_-]?key|apikey)\s*[=:]\s*["\'][^"\']+["\']'
r'(secret|token|password)\s*[=:]\s*["\'][^"\']+["\']'
r'(aws[_-]?access|aws[_-]?secret).*[=:]\s*["\'][A-Za-z0-9/+]+["\']'

# Connection strings
r'(mysql|postgres|mongodb)://[^@]+:[^@]+@'
r'redis://:[^@]+@'
```

**Variants:**
- Test/fixture files
- Docker configurations
- CI/CD configs
- Mobile app configs
- Frontend code (API keys)

---

### Pattern 7: Missing Authentication

**Original Finding:**
```python
@app.route('/admin/delete_user/<id>')
def delete_user(id):  # No @login_required!
    User.delete(id)
```

**Pattern Abstraction:**
```
route_definition -> handler -> sensitive_operation (missing: auth_decorator)
```

**Search Patterns:**
```python
# Flask/Django routes without auth
r'@app\.route.*\n(?!.*@login_required).*def'
r'@api_view.*\n(?!.*@permission_classes).*def'

# Express routes
r'app\.(get|post|put|delete)\([^,]+,\s*\([^)]*\)\s*=>'  # Check no middleware
```

**Variants:**
- Admin endpoints
- API endpoints
- Internal tools
- Debug endpoints
- Health checks exposing sensitive info

---

### Pattern 8: Race Conditions (TOCTOU)

**Original Finding:**
```python
if user.balance >= amount:
    user.balance -= amount
    transfer(amount)
```

**Pattern Abstraction:**
```
check_condition -> gap -> act_on_condition (missing: atomic/lock)
```

**Search Patterns:**
```python
# Balance/resource checks
r'if.*balance.*>=.*\n.*balance.*-='
r'if.*count.*>.*\n.*count.*-='

# File operations
r'if.*exists\(.*\).*\n.*open\('
r'if.*isfile\(.*\).*\n.*remove\('
```

**Variants:**
- Financial operations
- Inventory management
- Rate limiting
- File locking
- Session handling

---

## Variant Discovery Workflow

```
┌─────────────────────────────────────────────────────────────┐
│  1. ANALYZE ORIGINAL FINDING                                │
│     - What's the root cause?                                │
│     - What makes it exploitable?                            │
├─────────────────────────────────────────────────────────────┤
│  2. EXTRACT ABSTRACT PATTERN                                │
│     - Source → Transform → Sink                             │
│     - What's missing (validation)?                          │
├─────────────────────────────────────────────────────────────┤
│  3. CREATE SEARCH QUERIES                                   │
│     - Regex for quick grep                                  │
│     - Semgrep/CodeQL for precision                          │
├─────────────────────────────────────────────────────────────┤
│  4. EXPAND SEARCH SCOPE                                     │
│     - Same pattern, different source                        │
│     - Same pattern, different sink                          │
│     - Same pattern, different language/framework            │
├─────────────────────────────────────────────────────────────┤
│  5. VALIDATE EACH FINDING                                   │
│     - Is it reachable?                                      │
│     - Is input controllable?                                │
│     - Is impact significant?                                │
└─────────────────────────────────────────────────────────────┘
```

## Cross-Language Pattern Mapping

| Vulnerability | Python | JavaScript | Go | Rust |
|--------------|--------|------------|-----|------|
| SQL Injection | `cursor.execute()` | `query()` | `db.Query()` | `query()` |
| Command Injection | `os.system()` | `exec()` | `exec.Command()` | `Command::new()` |
| Path Traversal | `open(path)` | `fs.readFile()` | `os.Open()` | `File::open()` |
| Deserialize | `pickle.loads()` | `JSON.parse()` | `json.Unmarshal()` | `serde::from_*()` |
| Template Injection | `Template()` | `eval()` | `template.Execute()` | N/A |

## Semgrep Rule Templates

### Generic Taint Tracking
```yaml
rules:
  - id: generic-injection
    mode: taint
    pattern-sources:
      - pattern: request.$METHOD(...)
      - pattern: $PARAM = request.params[...]
    pattern-sinks:
      - pattern: dangerous_function($SINK)
    pattern-sanitizers:
      - pattern: sanitize(...)
    message: "Tainted data flows to dangerous sink"
    languages: [python, javascript]
    severity: ERROR
```

### Missing Security Control
```yaml
rules:
  - id: missing-auth-check
    patterns:
      - pattern: |
          @app.route($PATH)
          def $FUNC(...):
            ...
      - pattern-not: |
          @app.route($PATH)
          @login_required
          def $FUNC(...):
            ...
    message: "Route may be missing authentication"
    languages: [python]
    severity: WARNING
```

```

### templates/variant-report.md

```markdown
# Variant Analysis Report Template

## Engagement Information

| Field | Value |
|-------|-------|
| Project | [PROJECT_NAME] |
| Date | [DATE] |
| Analyst | [ANALYST_NAME] |
| Original Finding | [FINDING_ID] |

---

## Original Vulnerability

### Summary
[Brief description of the original finding]

### Location
```
File: [path/to/file.ext]
Line: [LINE_NUMBER]
Function: [function_name]
```

### Code Snippet
```[language]
// Original vulnerable code
```

### Root Cause Analysis
[Explain WHY this vulnerability exists - the underlying pattern or mistake]

### Impact
[What can an attacker achieve by exploiting this?]

---

## Pattern Extraction

### Abstract Pattern
```
SOURCE: [Where does attacker-controlled data enter?]
   ↓
TRANSFORM: [How is data processed?]
   ↓
SINK: [Where does data cause harm?]

MISSING: [What validation/sanitization is absent?]
```

### Search Pattern

**Regex:**
```
[regex pattern]
```

**Semgrep Rule (if applicable):**
```yaml
rules:
  - id: variant-[finding-id]
    patterns:
      - pattern: |
          [pattern]
    message: "[message]"
    languages: [[languages]]
    severity: [severity]
```

---

## Variant Discovery Results

### Search Methodology
1. [Search method 1 - e.g., grep for pattern X]
2. [Search method 2 - e.g., Semgrep rule scan]
3. [Search method 3 - e.g., Manual review of module Y]

### Raw Matches
```
[tool output showing all matches]
```

### Validated Variants

#### Variant 1: [Short Description]

| Attribute | Value |
|-----------|-------|
| File | `path/to/file.ext` |
| Line | [LINE] |
| Severity | [Critical/High/Medium/Low] |
| Status | [Confirmed/Suspected/False Positive] |

**Code:**
```[language]
// Variant code
```

**Analysis:**
[Why this is a true positive - explain the data flow and exploitability]

---

#### Variant 2: [Short Description]

| Attribute | Value |
|-----------|-------|
| File | `path/to/file2.ext` |
| Line | [LINE] |
| Severity | [Critical/High/Medium/Low] |
| Status | [Confirmed/Suspected/False Positive] |

**Code:**
```[language]
// Variant code
```

**Analysis:**
[Why this is a true positive]

---

### False Positives

| Location | Reason for FP |
|----------|---------------|
| `file.ext:123` | [Why this match is not vulnerable] |
| `file2.ext:456` | [Why this match is not vulnerable] |

---

## Summary

### Statistics

| Category | Count |
|----------|-------|
| Total Matches | [N] |
| Confirmed Variants | [N] |
| Suspected (needs review) | [N] |
| False Positives | [N] |

### Severity Distribution

| Severity | Count |
|----------|-------|
| Critical | [N] |
| High | [N] |
| Medium | [N] |
| Low | [N] |

---

## Remediation

### Systemic Fix
[Recommend an architectural or framework-level fix that addresses all variants]

### Individual Fixes
[If no systemic fix is possible, provide specific fix guidance for each variant]

### Prevention
[How to prevent this class of vulnerability in future development]

---

## Appendix

### All Findings Table

| # | Location | Severity | Status | Description |
|---|----------|----------|--------|-------------|
| 1 | `file1.ext:100` | High | Confirmed | [Brief desc] |
| 2 | `file2.ext:200` | Medium | Confirmed | [Brief desc] |
| 3 | `file3.ext:300` | Low | Suspected | [Brief desc] |

### Search Commands Used

```bash
# Command 1
[command]

# Command 2
[command]
```

### References
- [Link to original finding/ticket]
- [Relevant documentation]
- [Related CVEs or security advisories]

```

vulnhunter | SkillHub