# 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.

- **Kind:** skill
- **Source:** https://github.com/quillai-network/qs_skills
- **Page:** https://forefy.com/skills/bee11b72-c6f3-4e03-b4b6-3d6c6168bbda
- **API (JSON + files):** https://forefy.com/api/asr/bee11b72-c6f3-4e03-b4b6-3d6c6168bbda

---

## SKILL.md

---
name: semantic-guard-analysis
description: 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.
---

# 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]` ✓
- `function2()` checks `[guard]` before modifying `[state]` ✓
- `functionName()` does NOT check `[guard]` before modifying `[state]` ✗

**Guard Frequency:** X out of Y functions (Z%)

**Security Impact:**
[Explanation of what an attacker can do by exploiting this inconsistency]

**Attack Scenario:**
1. [Step-by-step exploit]

**Recommendation:**
Add `require([guard], "[message]")` before modifying `[state]`,
or document why this function intentionally bypasses the check.
```

## Case Study: The "Forgotten Check"

```solidity
contract Vault {
    mapping(address => uint256) public balance;
    bool public paused;

    function deposit() public payable {
        require(!paused, "Contract paused");       // ✓ checks paused
        balance[msg.sender] += msg.value;
    }

    function withdraw(uint256 amount) public {
        require(!paused, "Contract paused");       // ✓ checks paused
        balance[msg.sender] -= amount;
        payable(msg.sender).transfer(amount);
    }

    function adminWithdraw(address user) public onlyOwner {
        // ✗ Missing paused check!
        uint256 amount = balance[user];
        balance[user] = 0;
        payable(owner).transfer(amount);
    }
}
```

**Detection:**

```
M_balance = {deposit, withdraw, adminWithdraw}
G_paused = {deposit, withdraw}
V = {adminWithdraw}

Result: adminWithdraw() modifies balance without checking paused
Confidence: 66.7% (2/3 functions check paused)
Severity: HIGH (financial state + admin bypass of safety mechanism)
```

For more case studies, see [{baseDir}/references/case-studies.md]({baseDir}/references/case-studies.md).
For the full detection algorithm, see [{baseDir}/references/detection-algorithm.md]({baseDir}/references/detection-algorithm.md).

## Rationalizations to Reject

- "The admin is trusted, so skipping the check is fine" → Compromised admin + missing pause check = unstoppable drain
- "This function is only called internally" → Verify all callers; internal doesn't mean safe
- "The pattern only appears in 2 functions" → Even 2/3 consistency is a signal worth investigating
- "It's an emergency function" → Emergency functions should be MORE carefully guarded, not less
- "Traditional tools said it's fine" → Traditional tools check syntax, not semantic consistency

## references

```

```

## references/case-studies.md

# Guard-State Analysis Case Studies

## Case Study 1: The Forgotten Pause Check

### Contract

```solidity
contract Vault {
    mapping(address => uint256) public balance;
    bool public paused;
    address public owner;

    modifier onlyOwner() {
        require(msg.sender == owner);
        _;
    }

    function deposit() public payable {
        require(!paused, "Contract paused");
        balance[msg.sender] += msg.value;
    }

    function withdraw(uint256 amount) public {
        require(!paused, "Contract paused");
        require(balance[msg.sender] >= amount);
        balance[msg.sender] -= amount;
        payable(msg.sender).transfer(amount);
    }

    function adminWithdraw(address user) public onlyOwner {
        // VULNERABILITY: Missing paused check
        uint256 amount = balance[user];
        balance[user] = 0;
        payable(owner).transfer(amount);
    }
}
```

### Analysis

**Phase 1: State Interaction Matrix**

```
State Variable: balance
├─ deposit()        → WRITE + Guards: [paused]
├─ withdraw()       → WRITE + Guards: [paused]
└─ adminWithdraw()  → WRITE + Guards: [owner]
```

**Phase 2: Pattern Recognition**

```
Functions modifying 'balance': {deposit, withdraw, adminWithdraw}
Guard frequency:
  - paused: 2/3 functions (66.7%)
  - owner: 1/3 functions (33.3%)

Inferred: balance → paused (Moderate confidence)
```

**Phase 3: Solver**

```
M_target = {deposit, withdraw, adminWithdraw}
G_required = {deposit, withdraw}
V = {adminWithdraw}
```

**Result:**

```
VULNERABILITY DETECTED
Function: adminWithdraw()
Severity: HIGH
Issue: Modifies 'balance' without checking 'paused'
Confidence: 66.7%
```

**Attack Scenario:**
1. Security team detects an active exploit
2. Contract is paused to stop operations
3. Attacker (with compromised admin access) uses `adminWithdraw()` to drain funds
4. Pause mechanism rendered useless

---

## Case Study 2: Inconsistent Role Checks in Governance

### Contract

```solidity
contract Governance {
    mapping(uint256 => Proposal) public proposals;
    mapping(address => bool) public isVoter;
    uint256 public quorum;
    address public admin;

    function createProposal(bytes calldata data) public {
        require(isVoter[msg.sender], "Not a voter");
        // Creates proposal...
    }

    function vote(uint256 proposalId) public {
        require(isVoter[msg.sender], "Not a voter");
        // Records vote...
    }

    function executeProposal(uint256 proposalId) public {
        require(isVoter[msg.sender], "Not a voter");
        require(proposals[proposalId].votes >= quorum, "No quorum");
        // Executes...
    }

    function cancelProposal(uint256 proposalId) public {
        // VULNERABILITY: Missing voter check!
        // Anyone can cancel any proposal
        proposals[proposalId].cancelled = true;
    }

    function setQuorum(uint256 newQuorum) public {
        require(msg.sender == admin, "Not admin");
        quorum = newQuorum;
    }
}
```

### Analysis

```
State Variable: proposals
├─ createProposal()  → WRITE + Guards: [isVoter]
├─ vote()           → WRITE + Guards: [isVoter]
├─ executeProposal() → WRITE + Guards: [isVoter, quorum]
└─ cancelProposal()  → WRITE + Guards: [] ⚠️

Guard frequency for isVoter → proposals:
  3/4 functions = 75% (Weak-to-Moderate invariant)

VULNERABILITY: cancelProposal() bypasses voter check
Severity: HIGH (governance manipulation)
Impact: Any address can cancel any proposal, blocking governance
```

---

## Case Study 3: Multi-Guard Composite Bypass

### Contract

```solidity
contract TimelockVault {
    mapping(address => uint256) public locked;
    mapping(address => uint256) public unlockTime;
    bool public paused;
    address public owner;

    function lock(uint256 amount, uint256 duration) public {
        require(!paused, "Paused");
        locked[msg.sender] += amount;
        unlockTime[msg.sender] = block.timestamp + duration;
    }

    function unlock() public {
        require(!paused, "Paused");
        require(block.timestamp >= unlockTime[msg.sender], "Still locked");
        uint256 amount = locked[msg.sender];
        locked[msg.sender] = 0;
        payable(msg.sender).transfer(amount);
    }

    function adminUnlock(address user, uint256 amount) public {
        require(msg.sender == owner, "Not owner");
        // VULNERABILITY: Skips BOTH paused AND timelock checks
        locked[user] -= amount;
        payable(user).transfer(amount);
    }
}
```

### Analysis

```
State Variable: locked
├─ lock()        → WRITE + Guards: [paused]
├─ unlock()      → WRITE + Guards: [paused, unlockTime]
└─ adminUnlock() → WRITE + Guards: [owner]

Composite guard analysis:
  paused → locked: 2/3 = 66.7%
  unlockTime → locked: 1/3 = 33.3% (weak, timelock only for user unlock)

VULNERABILITY: adminUnlock() bypasses paused check
Severity: HIGH
Note: Timelock bypass may be intentional for admin override,
      but paused bypass is dangerous — admin can drain during emergency pause
```

---

## Pattern: Traditional Tool vs Semantic Analysis

| Scenario | Traditional Tool Result | Semantic Guard Analysis |
|----------|----------------------|------------------------|
| Missing pause in admin function | PASS (valid syntax) | VULNERABILITY (inconsistent guard) |
| Missing voter check in cancel | PASS (no known pattern) | VULNERABILITY (breaks 75% pattern) |
| Admin bypassing timelock + pause | PASS (has onlyOwner) | VULNERABILITY (breaks composite guard) |

## references/detection-algorithm.md

# Guard-State Detection Algorithm — Detailed Reference

## Formal Definition

### Universe of Functions

Let F = {f1, f2, ..., fn} be all functions in the contract.

### State Variable

Let s be a critical state variable (balance, owner, etc.).

### Modifying Functions

```
M_target = {f ∈ F | f writes to s}
```

### Guard Functions

```
G_required = {g1, g2, ..., gk}
```

Where each guard gi represents a security check (require statement, modifier, conditional).

## The Consistency Invariant

**For a logically consistent contract:**

```
∀f ∈ M_target : f applies all guards in G_required
```

**Formal notation:**

```
M_target ⊆ G_required
```

## Vulnerability Detection

**The Vulnerability Set:**

```
V = M_target \ G_required

Where:
- M_target = All functions modifying a critical variable
- G_required = Guards that should protect it (inferred from patterns)
- V = Vulnerability set (functions that bypass guards)
```

**Interpretation:**

- If V = ∅ (empty set): Contract is internally consistent
- If V ≠ ∅: Functions in V are potential vulnerabilities

## Confidence Score Formula

```
Confidence(g → s) = |{f ∈ M_s | f applies g}| / |M_s|

Where:
- M_s = functions that modify state s
- Confidence ranges from 0.0 to 1.0
```

## Vulnerability Severity Score

```
Severity(v) = Confidence(g → s) × Impact(s)

Where:
- v is a function in vulnerability set V
- Impact(s) is the criticality of state variable s (1-10 scale)
```

### Impact Scale for State Variables

| Variable Type | Impact Score | Examples |
|---------------|-------------|----------|
| Financial balances | 10 | `balance`, `deposits`, `stakes` |
| Supply controls | 9 | `totalSupply`, `mintable` |
| Access control | 8 | `owner`, `admin`, `roles` |
| Protocol parameters | 7 | `feeRate`, `interestRate` |
| Operational state | 6 | `paused`, `initialized` |
| Configuration | 4 | `maxLimit`, `threshold` |
| Metadata | 2 | `name`, `symbol`, `uri` |

## Handling Complex Scenarios

### Multi-Guard Dependencies

Real contracts often require multiple guards simultaneously:

```solidity
function criticalOperation() public {
    require(msg.sender == owner, "Not owner");        // Guard 1
    require(block.timestamp >= unlockTime, "Locked");  // Guard 2
    require(!paused, "Contract paused");               // Guard 3
    // Perform operation
}
```

**Composite Intersection:**

```
G_composite = G_owner ∩ G_time ∩ G_paused
```

A function is flagged only if it fails to satisfy ALL guards in the composite set.

### Guard Hierarchy Detection

```
Level 1: Critical Guards (must always apply)
  - paused
  - initialized

Level 2: Context Guards (apply in specific scenarios)
  - owner (for admin functions)
  - timelock (for financial operations)

Level 3: Situational Guards (optional)
  - cooldown periods
  - rate limits
```

### Dependency Chain Analysis

```
If function modifies: balance
Then check for guards in order:
  1. Is contract paused? (Critical)
  2. Is sender authorized? (Context)
  3. Has cooldown passed? (Situational)
```

## Cross-Contract Analysis Extension

```
Contract A calls Contract B.updateState()
  ↓
Analyze if guards in A should propagate to B
  ↓
Detect if B performs unguarded operations on behalf of A
```

**Use Cases:**
- Proxy pattern security
- Upgradeable contract consistency
- Multi-contract protocol analysis
- Library safety verification

