CA

cairo-vulnerability-scanner

A security scanner for StarkNet that identifies critical vulnerabilities in Cairo smart contracts.

Install

mkdir -p .claude/skills/cairo-vulnerability-scanner && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/3781" && unzip -o skill.zip -d .claude/skills/cairo-vulnerability-scanner && rm skill.zip

Installs to .claude/skills/cairo-vulnerability-scanner

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Scans Cairo/StarkNet smart contracts for 6 critical vulnerabilities including felt252 arithmetic overflow, L1-L2 messaging issues, address conversion problems, and signature replay. Use when auditing StarkNet projects.
218 chars✓ has a “when” trigger
Advanced

Key capabilities

  • Scan Cairo contracts for arithmetic overflow
  • Validate L1-L2 cross-layer message handlers
  • Audit signature verification logic
  • Detect address conversion security risks
  • Review StarkNet storage access patterns

How it works

Uses a static analysis engine to grep for and evaluate specific Cairo security patterns and syscall usage.

Inputs & outputs

You give it
Path to Cairo smart contract codebase
You get back
List of detected security vulnerabilities

When to use cairo-vulnerability-scanner

  • Auditing StarkNet smart contracts
  • Validating L1-L2 bridge messaging
  • Reviewing signature verification logic
  • Pre-launch security assessments

About this skill

Cairo/StarkNet Vulnerability Scanner

1. Purpose

Systematically scan Cairo smart contracts on StarkNet for platform-specific security vulnerabilities related to arithmetic, cross-layer messaging, and cryptographic operations. This skill encodes 6 critical vulnerability patterns unique to Cairo/StarkNet ecosystem.

2. When to Use This Skill

  • Auditing StarkNet smart contracts (Cairo)
  • Reviewing L1-L2 bridge implementations
  • Pre-launch security assessment of StarkNet applications
  • Validating cross-layer message handling
  • Reviewing signature verification logic
  • Assessing L1 handler functions

3. Platform Detection

File Extensions & Indicators

  • Cairo files: .cairo

Language/Framework Markers

// Cairo contract indicators
#[contract]
mod MyContract {
    use starknet::ContractAddress;

    #[storage]
    struct Storage {
        balance: LegacyMap<ContractAddress, felt252>,
    }

    #[external(v0)]
    fn transfer(ref self: ContractState, to: ContractAddress, amount: felt252) {
        // Contract logic
    }

    #[l1_handler]
    fn handle_deposit(ref self: ContractState, from_address: felt252, amount: u256) {
        // L1 message handler
    }
}

// Common patterns
felt252, u128, u256
ContractAddress, EthAddress
#[external(v0)], #[l1_handler], #[constructor]
get_caller_address(), get_contract_address()
send_message_to_l1_syscall

Project Structure

  • src/contract.cairo - Main contract implementation
  • src/lib.cairo - Library modules
  • tests/ - Contract tests
  • Scarb.toml - Cairo project configuration

Tool Support

  • Caracal: Trail of Bits static analyzer for Cairo
  • Installation: cargo install --git https://github.com/crytic/caracal --profile release --force (a Rust tool — not on PyPI)
  • Usage: caracal detect src/
  • cairo-test: Built-in testing framework
  • Starknet Foundry: Testing and development toolkit

4. How This Skill Works

When invoked, I will:

  1. Search your codebase for Cairo files
  2. Analyze each contract for the 6 vulnerability patterns
  3. Report findings with file references and severity, above them a coverage table carrying a verdict for every pattern
  4. Provide fixes for each identified issue
  5. Check L1-L2 interactions for messaging vulnerabilities

5. Example Output

When vulnerabilities are found, you'll get a report like this:

=== CAIRO/STARKNET VULNERABILITY SCAN RESULTS ===

6. Vulnerability Patterns (6 Patterns)

I check for 6 critical vulnerability patterns unique to Cairo/Starknet. For detailed detection patterns, code examples, mitigations, and testing strategies, see VULNERABILITY_PATTERNS.md.

Pattern Summary:

  1. Felt252 Arithmetic Overflow/Underflow ⚠️ HIGH - felt252 wraps silently; use u128/u256
  2. L1 to L2 Address Conversion ⚠️ HIGH - L1 address not validated against STARKNET_FIELD_PRIME
  3. L1 to L2 Message Failure ⚠️ HIGH - No cancellation path when a message cannot be consumed
  4. Overconstrained L1 <-> L2 Interaction ⚠️ MEDIUM - Coupling that can strand funds or block progress
  5. Signature Replay Protection ⚠️ HIGH - No nonce, or a domain separator missing chain/contract
  6. Unchecked from_address in L1 Handler ⚠️ CRITICAL - Any L1 contract can drive the handler

For complete vulnerability patterns with code examples, see VULNERABILITY_PATTERNS.md.

7. Scanning Workflow

Step 1: Platform Identification

  1. Verify Cairo language and StarkNet framework
  2. Check Cairo version (Cairo 1.0+ vs legacy Cairo 0)
  3. Locate contract files (src/*.cairo)
  4. Identify L1-L2 bridge contracts (if applicable)

Step 2: Arithmetic Safety Sweep

# Find felt252 usage in arithmetic
rg "felt252" src/ | rg "[-+*/]"

# Find balance/amount storage using felt252
rg "felt252" src/ | rg "balance|amount|total|supply"

# Should prefer u128, u256 instead

Step 3: L1 Handler Analysis

For each #[l1_handler] function:

  • Validates from_address parameter
  • Checks address != zero
  • Has proper access control
  • Emits events for monitoring

Step 4: Signature Verification Review

For signature-based functions:

  • Includes nonce tracking
  • Nonce incremented after use
  • Domain separator includes chain ID and contract address
  • Cannot replay signatures

Step 5: L1-L2 Bridge Audit

If contract includes bridge functionality:

  • L1 validates address < STARKNET_FIELD_PRIME
  • L1 implements message cancellation
  • L2 validates from_address in handlers
  • Symmetric access controls L1 ↔ L2
  • Test full roundtrip flows

Step 6: Static Analysis with Caracal

# Run Caracal detectors
caracal detect src/

# Specific detectors
caracal detect src/ --detectors unchecked-felt252-arithmetic
caracal detect src/ --detectors unchecked-l1-handler-from
caracal detect src/ --detectors missing-nonce-validation

8. Reporting Format

Coverage Table

Report on every pattern in §6, whether or not it turned anything up. Emit this table above the findings, with all 6 rows present:

#PatternVerdictEvidence
1Felt252 Arithmetic Overflow/Underflowclearbalances are u256; searched felt252 in arithmetic, none
2L1 to L2 Address Conversion
3L1 to L2 Message Failure
4Overconstrained L1 <-> L2 Interaction
5Signature Replay Protection
6Unchecked from_address in L1 Handler

Each verdict is one of:

  • found — cite file:line and write the finding up in full below.
  • clear — the pattern applies to this contract and the contract handles it. Name the function, trait, or check you searched for, so a reader can repeat the search.
  • n/a — the pattern cannot apply here. Give the reason in one clause ("no L1 handlers in this contract"). Not having looked is not n/a.

A table with fewer than 6 rows is an incomplete scan and must be reported as one. A row whose Verdict cell is empty is incomplete in the same way: row 1 above is filled in to show the shape, and every row is filled in the same way before the report is done. Six clear verdicts is a result a reader can act on. A report that covers two patterns and says nothing about the other four reads exactly like a clean contract, and that is the failure this table exists to prevent.

Finding Template

## [CRITICAL] Unchecked from_address in L1 Handler

**Location**: `src/bridge.cairo:145-155` (handle_deposit function)

**Description**:
The `handle_deposit` L1 handler function does not validate the `from_address` parameter. Any L1 contract can send messages to this function and mint tokens for arbitrary users, bypassing the intended L1 bridge access controls.

**Vulnerable Code**:
```rust
// bridge.cairo, line 145
#[l1_handler]
fn handle_deposit(
    ref self: ContractState,
    from_address: felt252,  // Not validated!
    user: ContractAddress,
    amount: u256
) {
    let current_balance = self.balances.read(user);
    self.balances.write(user, current_balance + amount);
}
```

**Attack Scenario**:
1. Attacker deploys malicious L1 contract
2. Malicious contract calls `starknetCore.sendMessageToL2(l2Contract, selector, [attacker_address, 1000000])`
3. L2 handler processes message without checking sender
4. Attacker receives 1,000,000 tokens without depositing any funds
5. Protocol suffers infinite mint vulnerability

**Recommendation**:
Validate `from_address` against authorized L1 bridge:
```rust
#[l1_handler]
fn handle_deposit(
    ref self: ContractState,
    from_address: felt252,
    user: ContractAddress,
    amount: u256
) {
    // Validate L1 sender
    let authorized_l1_bridge = self.l1_bridge_address.read();
    assert(from_address == authorized_l1_bridge, 'Unauthorized L1 sender');

    let current_balance = self.balances.read(user);
    self.balances.write(user, current_balance + amount);
}
```

**References**:
- building-secure-contracts/not-so-smart-contracts/cairo/unchecked_l1_handler_from
- Caracal detector: `unchecked-l1-handler-from`

9. Priority Guidelines

Critical (Immediate Fix Required)

  • Unchecked from_address in L1 handlers (infinite mint)
  • L1-L2 address conversion issues (funds to zero address)

High (Fix Before Deployment)

  • Felt252 arithmetic overflow/underflow (balance manipulation)
  • Missing signature replay protection (replay attacks)
  • L1-L2 message failure without cancellation (locked funds)

Medium (Address in Audit)

  • Overconstrained L1-L2 interactions (trapped funds)

10. Testing Recommendations

Unit Tests

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_felt252_overflow() {
        // Test arithmetic edge cases
    }

    #[test]
    #[should_panic]
    fn test_unauthorized_l1_handler() {
        // Wrong from_address should fail
    }

    #[test]
    fn test_signature_replay_protection() {
        // Same signature twice should fail
    }
}

Integration Tests (with L1)

// Test full L1-L2 flow
#[test]
fn test_deposit_withdraw_roundtrip() {
    // 1. Deposit on L1
    // 2. Wait for L2 processing
    // 3. Verify L2 balance
    // 4. Withdraw to L1
    // 5. Verify L1 balance restored
}

Caracal CI Integration

# .github/workflows/security.yml
- name: Run Caracal
  run: |
    # Rebuilds from source each run; cache ~/.cargo or pin a release binary instead.
    cargo install --git https://github.com/crytic/caracal --profile release --force
    caracal detect src/ --fail-on high,critical

11. Additional Resources


Content truncated.

When not to use it

  • For standard non-StarkNet blockchain projects
  • When the codebase lacks Cairo files

Prerequisites

Caracal static analyzer

Limitations

  • Limited to the 6 predefined vulnerability patterns
  • May produce false positives on complex logic

How it compares

It focuses specifically on StarkNet-unique vulnerabilities like L1/L2 messaging rather than generic Solidity audits.

Compared to similar skills

cairo-vulnerability-scanner side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
cairo-vulnerability-scanner (this skill)13moReviewAdvanced
senior-security318moReviewAdvanced
security-header-generator510moCautionIntermediate
backend-security-coder244moNo flagsIntermediate

Try saying

Example prompts that trigger this skill in your AI assistant.

More by trailofbits

View all by trailofbits

differential-review

trailofbits

Performs security-focused differential review of code changes (PRs, commits, diffs). Adapts analysis depth to codebase size, uses git history for context, calculates blast radius, checks test coverage, and generates comprehensive markdown reports. Automatically detects and prevents security regressions.

3115

code-maturity-assessor

trailofbits

Systematic code maturity assessment using Trail of Bits' 9-category framework. Analyzes codebase for arithmetic safety, auditing practices, access controls, complexity, decentralization, documentation, MEV risks, low-level code, and testing. Produces professional scorecard with evidence-based ratings and actionable recommendations.

416

modern-python

trailofbits

Configures Python projects with modern tooling (uv, ruff, ty). Use when creating projects, writing standalone scripts, or migrating from pip/Poetry/mypy/black.

427

semgrep-rule-creator

trailofbits

Creates custom Semgrep rules for detecting security vulnerabilities, bug patterns, and code patterns. Use when writing Semgrep rules or building custom static analysis detections.

416

ton-vulnerability-scanner

trailofbits

Scans TON (The Open Network) smart contracts for 3 critical vulnerabilities including integer-as-boolean misuse, fake Jetton contracts, and forward TON without gas checks. Use when auditing FunC contracts.

410

cosmos-vulnerability-scanner

trailofbits

Scans Cosmos SDK blockchains for 9 consensus-critical vulnerabilities including non-determinism, incorrect signers, ABCI panics, and rounding errors. Use when auditing Cosmos chains or CosmWasm contracts.

32

You might also like

senior-security

davila7

Comprehensive security engineering skill for application security, penetration testing, security architecture, and compliance auditing. Includes security assessment tools, threat modeling, crypto implementation, and security automation. Use when designing security architecture, conducting penetration tests, implementing cryptography, or performing security audits.

3191

security-header-generator

Dexploarer

Generates security HTTP headers (CSP, HSTS, CORS, etc.) for web applications to prevent common attacks. Use when user asks to "add security headers", "setup CSP", "configure CORS", "secure headers", or "HSTS setup".

599

backend-security-coder

sickn33

Expert in secure backend coding practices specializing in input validation, authentication, and API security. Use PROACTIVELY for backend security implementations or security code reviews.

2446

security-audit

ruvnet

Comprehensive security scanning and vulnerability detection. Includes input validation, path traversal prevention, CVE detection, and secure coding pattern enforcement. Use when: authentication implementation, authorization logic, payment processing, user data handling, API endpoint creation, file upload handling, database queries, external API integration. Skip when: read-only operations on public data, internal development tooling, static documentation, styling changes.

337

security-best-practices

openai

Perform language and framework specific security best-practice reviews and suggest improvements. Trigger only when the user explicitly requests security best practices guidance, a security review/report, or secure-by-default coding help. Trigger only for supported languages (python, javascript/typescript, go). Do not trigger for general code review, debugging, or non-security tasks.

732

pcap-analysis

benchflow-ai

Guidance for analyzing network packet captures (PCAP files) and computing network statistics using Python, with tested utility functions.

713

Search skills

Search the agent skills registry