Skip to main content
ClaudeWave
Skill109 estrellas del repoactualizado 2mo ago

semantic-guard-analysis

Detects logic vulnerabilities in smart contracts by analyzing guard-state consistency patterns. Identifies functions that bypass security checks (require, modifiers) that other functions consistently apply. Uses the Consistency Principle — a contract is its own specification. Use when auditing smart contracts for missing access controls, inconsistent pause checks, logic bugs, forgotten modifiers, or when traditional tools report no issues but logic errors may exist.

Instalar en Claude Code
Copiar
git clone --depth 1 https://github.com/quillai-network/quillshield_skills /tmp/semantic-guard-analysis && cp -r /tmp/semantic-guard-analysis/plugins/semantic-guard-analysis/skills/semantic-guard-analysis ~/.claude/skills/semantic-guard-analysis
Después abre una sesión nueva de Claude Code; el skill carga automáticamente.

SKILL.md

# Semantic Guard Analysis

Detect logic vulnerabilities by finding functions that **violate the contract's own internal guard patterns**. Unlike pattern-matching tools, this approach uses the contract's consistent behavior as its specification.

## When to Use

- Auditing smart contracts where traditional tools find nothing suspicious
- Looking for missing `require` checks, forgotten modifiers, inconsistent access control
- Analyzing contracts with emergency/admin functions that might bypass safety mechanisms
- Detecting logic bugs that are syntactically correct but semantically dangerous
- When you suspect "forgotten check" vulnerabilities

## When NOT to Use

- Pure state-state invariant analysis (use state-invariant-detection)
- Full multi-dimensional audit (use behavioral-state-analysis)
- Code quality or gas optimization reviews

## Core Principle: The Consistency Hypothesis

> **"A smart contract is its own specification."**

Instead of checking against external rules, analyze what the contract **claims to enforce**, then find where it **breaks its own rules**.

> If a critical state variable (like user balances) is protected by a security check (like a pause mechanism) in 90% of functions, the 10% without that check are likely vulnerabilities.

## The Three-Phase Detection Architecture

### Phase 1: AST Extraction & State Mapping

Parse the Solidity code and build a **State Interaction Matrix**.

**For each state variable, track every function that touches it:**

```
State Variable: balance
├─ deposit()        → [WRITE] + Guards: [paused, initialized]
├─ withdraw()       → [WRITE] + Guards: [paused, initialized]
├─ transfer()       → [WRITE] + Guards: [paused]
└─ emergencyWithdraw() → [WRITE] + Guards: [] ⚠️
```

**For each function-variable interaction, record:**

| Attribute | Description |
|-----------|-------------|
| Write Access | Does the function modify this variable? |
| Guard Access | Does the function check this variable in `require()` or `if()`? |
| Read Access | Does the function only read this variable? |

**Extract guard sources:**
- Modifier chains (`onlyOwner`, `nonReentrant`, `whenNotPaused`)
- Explicit `require` statements
- Conditional branches gating state changes
- External calls affecting state
- Event emissions signaling state changes

### Phase 2: Dependency Graph Construction

Build a mathematical model of how variables protect each other.

**Guard Relationship:** If Variable A is checked before Variable B is modified:

```
A → B (A guards B)
```

**Example:**

```
paused ──────┐
             ├──→ balance
initialized ─┘

owner ───→ paused
owner ───→ totalSupply
```

**Frequency Weighting:** Each guard relationship gets a confidence score:

```
Confidence(guard → state) = |functions applying guard| / |functions modifying state|
```

- `paused` guards `balance` in 9/10 functions → 90% confidence
- `owner` guards `totalSupply` in 3/10 functions → 30% confidence (weak)

**Composite Dependencies:** Track multi-variable guards:

```
(owner AND timeLock) → criticalFunction
(paused OR emergency) → userAccess
```

### Phase 3: Anomaly Detection (The Solver)

Identify functions that violate established patterns.

**Algorithm:**

```
For each state variable S that can be modified:
  1. M = all functions that write to S
  2. G = common guards across those functions (above threshold)
  3. V = M \ G (functions that modify without guards)
  4. V is the vulnerability set
```

**Threshold-Based Inference:**

| Guard Frequency | Classification | Action |
|-----------------|---------------|--------|
| ≥ 80% | Strong Invariant | Flag violations as HIGH/CRITICAL |
| 50-79% | Weak Invariant | Flag violations as MEDIUM |
| < 50% | No Pattern | Ignore (too inconsistent) |

**Severity Classification:**

| Bypass Type | Severity |
|-------------|----------|
| Strong invariant on financial state (`balance`, `totalSupply`) | **Critical** |
| Strong invariant on access control (`owner`, admin roles) | **High** |
| Weak invariant on any state | **Medium** |
| Inconsistent pattern with no security implications | **Low/Info** |

**Context-Aware Filtering:**
- Constructor and `initialize()` functions may legitimately bypass patterns
- `view`/`pure` functions cannot modify state — skip
- Proxy pattern `delegatecall` requires special handling
- Emergency functions may intentionally bypass some guards

## Workflow

```
Task Progress:
- [ ] Step 1: Parse contract AST and build State Interaction Matrix
- [ ] Step 2: Identify all state variables and their modifying functions
- [ ] Step 3: Map guards (requires, modifiers) for each function-state pair
- [ ] Step 4: Build dependency graph with frequency weighting
- [ ] Step 5: Run anomaly detection (identify V = M \ G)
- [ ] Step 6: Apply privilege overlay (filter legitimate bypasses)
- [ ] Step 7: Score and report findings
```

## Privilege Overlay System

Not all "bypasses" are vulnerabilities. Apply role-based filtering:

**Role Classification:**

| Role Level | Scrutiny | Rationale |
|------------|----------|-----------|
| Public functions | Highest | Must follow all established patterns |
| Owner/Admin functions | Medium | May bypass operational guards, must be consistent with each other |
| Emergency functions | Lower | Designed for exceptional cases |
| Internal functions | Context-dependent | Analyze based on callers |

**Filtering Rule:**

```
For each function f in vulnerability set V:
  1. Identify function privileges (modifiers, access controls)
  2. Compare with other functions at the SAME privilege level
  3. Flag only if bypass is inconsistent WITHIN privilege tier
```

## Output Format

```markdown
## Guard-State Anomaly Report

### Finding: [Title]

**Function:** `functionName()` at `Contract.sol:L145`
**Severity:** [CRITICAL | HIGH | MEDIUM | LOW]
**Confidence:** [Percentage]

**Issue:** Modifies `[state variable]` without checking `[guard]`

**Pattern Evidence:**
- `function1()` checks `[guard]` before modifying `[state]` ✓
-
behavioral-state-analysisSkill

Token-efficient smart contract security auditing via Behavioral State Analysis (BSA). Scopes analysis to contract type, runs only relevant threat engines, and uses tiered output depth. Use for auditing smart contracts, security reviews, or DeFi threat modeling.

defenderSkill

Blue-team release-gate analysis for smart contract deployment and upgrade readiness. Classifies repositories, checks deploy/upgrade execution paths, CI/CD trust boundaries, config drift, secrets/signer operational security, and outputs evidence-backed release verdicts.

dos-griefing-analysisSkill

Detects Denial of Service and griefing vulnerabilities in smart contracts. Covers unbounded loop DoS, block gas limit exhaustion, external call failure DoS, insufficient gas griefing (63/64 rule), storage bloat attacks, timestamp griefing, self-destruct force-feeding, and push vs pull payment pattern analysis. Use when auditing contracts with batch operations, loops over user data, reward distribution, dividend systems, or any logic that depends on address(this).balance or iterates over growing collections.

external-call-safetySkill

Detects unsafe external call patterns and token integration vulnerabilities in smart contracts. Covers unchecked call/delegatecall/staticcall return values, fee-on-transfer tokens, rebasing tokens, tokens with missing return values (USDT), ERC-777 callback risks, unsafe approve race conditions, return data bombs, gas stipend limitations, and push vs pull payment patterns. Use when auditing contracts that interact with external contracts, integrate arbitrary ERC20 tokens, distribute payments, or make low-level calls.

input-arithmetic-safetySkill

Detects input validation failures and arithmetic vulnerabilities in smart contracts. Covers missing zero-address and zero-amount checks, division-before-multiplication precision loss, rounding direction exploitation, ERC4626 vault share inflation attacks, unsafe integer casting, dust amount exploitation, and Solidity 0.8+ unchecked block edge cases. Use when auditing contracts with fee calculations, share pricing, exchange rates, unchecked blocks, or any public-facing functions that accept user input.

oracle-flashloan-analysisSkill

Detects price oracle manipulation and flash loan attack vectors in DeFi smart contracts. Classifies oracle trust models (Chainlink, TWAP, spot price, custom), identifies stale price risks, circular price dependencies, and flash loan atomicity exploitation patterns. Use when auditing DeFi protocols that depend on price data, oracle integrations, lending protocols, DEXs, derivatives, or any contract where flash loans could manipulate state within a single transaction.

proxy-upgrade-safetySkill

Detects vulnerabilities in upgradeable proxy smart contracts including storage layout collisions, uninitialized implementations, function selector clashing, delegatecall context issues, and upgrade path safety. Covers Transparent Proxy, UUPS (EIP-1822), Beacon, Diamond (EIP-2535), and Minimal Proxy (EIP-1167) patterns. Use when auditing upgradeable contracts, reviewing implementation upgrades, analyzing delegatecall architectures, or verifying proxy pattern compliance.

reentrancy-pattern-analysisSkill

Systematically detects all reentrancy vulnerability variants in smart contracts — classic, cross-function, cross-contract, and read-only reentrancy. Builds call graphs, verifies CEI (Checks-Effects-Interactions) pattern compliance, traces state changes relative to external calls, and identifies callback vectors through ERC-777/ERC-1155 hooks. Use when auditing contracts that make external calls, transfer ETH or tokens, interact with callback-enabled standards, or have complex multi-contract architectures.