Back to Security & Vulnerability Analysis

cairo-vulnerability-scanner

cairostarknetsmart contractvulnerabilityauditblockchainsecurity scannerl1-l2 bridge
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

The cairo-vulnerability-scanner skill automates the security review of Cairo-based smart contracts within the StarkNet ecosystem. It specifically targets security flaws unique to the StarkNet architecture, including L1-L2 cross-layer messaging vulnerabilities, unchecked arithmetic operations, and storage collisions. By analyzing Cairo 1.0 codebases, the tool identifies risks such as improper felt252 boundary validation, missing access controls in L1 handlers, and signature replay vectors. The skill integrates static analysis through Caracal to pinpoint code-level vulnerabilities, providing specific file references and mitigation strategies for each finding. It ensures that developers follow best practices for StarkNet development, particularly when handling cryptographic operations or bridge logic, preventing common exploits before deployment. This scanner acts as an automated auditor for developers prioritizing secure contract deployments in a L2 environment.

When to Use This Skill

  • Auditing StarkNet smart contracts before mainnet deployment
  • Reviewing secure implementation of L1-L2 bridge logic
  • Verifying signature verification and nonce tracking in custom wallets
  • Assessing contract storage safety and variable mapping

How to Invoke This Skill

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

  • Scan my Cairo smart contracts for security vulnerabilities
  • Check my StarkNet project for L1-L2 message handling errors
  • Run a security audit on these Cairo 1.0 files
  • Are there any storage collisions in my Cairo contract?
  • Review the l1_handler security in my bridge implementation

Pro Tips

  • 💡Combine this scanner with a general Solidity vulnerability scanner (if applicable) for a holistic security review across your L1 and L2 components.
  • 💡Always run this skill as part of your CI/CD pipeline for every pull request touching Cairo contract code to catch regressions early.
  • 💡After running the scan, prioritize issues by severity and always manually review flagged areas, especially complex custom logic not covered by standard patterns.

What this skill does

  • Identifies unchecked felt252 arithmetic patterns
  • Detects missing access control on #[l1_handler] functions
  • Validates L1-L2 cross-layer message integrity
  • Checks for signature replay risks using nonce analysis
  • Scans for storage collisions and improper address validation

When not to use it

  • Analyzing contracts written in Solidity for EVM-based chains
  • Replacing a professional third-party manual security audit
  • Reviewing non-Cairo based smart contract languages

Example workflow

  1. Navigate to the root directory of the StarkNet project
  2. Identify entry points such as src/lib.cairo or specific contract files
  3. Invoke the vulnerability scanner to execute static analysis via Caracal
  4. Review the generated report for CRITICAL or HIGH severity findings
  5. Apply suggested code mitigations to the identified files
  6. Re-run the scan to verify the resolution of identified vulnerabilities

Prerequisites

  • Cairo 1.0 development environment
  • Scarb installed for project management
  • Caracal static analyzer installed via pip

Pitfalls & limitations

  • !Static analysis may produce false positives in complex macro-heavy code
  • !Does not replace the need for comprehensive unit and integration testing
  • !Limited coverage for logic flaws that involve off-chain off-site integrations

FAQ

Does this tool work for Cairo 0 contracts?
This scanner is optimized for Cairo 1.0 and StarkNet framework syntax. Legacy Cairo 0 contracts may not be fully supported.
Is a static scan sufficient for mainnet security?
No, static analysis is a component of a security lifecycle. You should combine this with comprehensive testing and manual code audits.
What does the scanner specifically look for in L1 handlers?
It checks for proper validation of the from_address parameter, ensures non-zero address checks, and validates that proper access control modifiers are present.

How it compares

Unlike generic LLM prompts that offer high-level security advice, this skill applies specific Cairo-contextual scanners and industry-standard detectors like Caracal to identify precise vulnerabilities.

Source & trust

5.7k stars📄 CC-BY-SA-4.0🕒 Updated 2026-06-15
📄 Full skill instructions — original source: trailofbits/skills
# 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: pip install caracal
- 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
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 ===


---

## 5. 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](resources/VULNERABILITY_PATTERNS.md).

### Pattern Summary:

1. **Unchecked Arithmetic** ⚠️ CRITICAL - Integer overflow/underflow in felt252
2. **Storage Collision** ⚠️ CRITICAL - Conflicting storage variable hashes
3. **Missing Access Control** ⚠️ CRITICAL - No caller validation on sensitive functions
4. **Improper Felt252 Boundaries** ⚠️ HIGH - Not validating felt252 range
5. **Unvalidated Contract Address** ⚠️ HIGH - Using untrusted contract addresses
6. **Missing Caller Validation** ⚠️ CRITICAL - No get_caller_address() checks

For complete vulnerability patterns with code examples, see [VULNERABILITY_PATTERNS.md](resources/VULNERABILITY_PATTERNS.md).
## 5. 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
bash
# 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
bash
# 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
---

## 6. Reporting Format

### Finding Template
markdown
## [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**:
// 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:
#[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
---

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

---

## 8. Testing Recommendations

### Unit Tests
rust
#[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)
rust
// 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
yaml
# .github/workflows/security.yml
- name: Run Caracal
run: |
pip install caracal
caracal detect src/ --fail-on high,critical
``

---

## 9. Additional Resources

- **Building Secure Contracts**:
building-secure-contracts/not-so-smart-contracts/cairo/
- **Caracal**: https://github.com/crytic/caracal
- **Cairo Documentation**: https://book.cairo-lang.org/
- **StarkNet Documentation**: https://docs.starknet.io/
- **OpenZeppelin Cairo Contracts**: https://github.com/OpenZeppelin/cairo-contracts

---

## 10. Quick Reference Checklist

Before completing Cairo/StarkNet audit:

**Arithmetic Safety (HIGH)**:
- [ ] No felt252 used for balances/amounts (use u128/u256)
- [ ] OR felt252 arithmetic has explicit bounds checking
- [ ] Overflow/underflow scenarios tested

**L1 Handler Security (CRITICAL)**:
- [ ] ALL
#[l1_handler] functions validate from_address`
- [ ] from_address compared against stored L1 contract address
- [ ] Cannot bypass by deploying alternate L1 contract

**L1-L2 Messaging (HIGH)**:
- [ ] L1 bridge validates addresses < STARKNET_FIELD_PRIME
- [ ] L1 bridge implements message cancellation
- [ ] L2 handlers check from_address
- [ ] Symmetric validation rules L1 ↔ L2
- [ ] Full roundtrip flows tested

**Signature Security (HIGH)**:
- [ ] Signatures include nonce tracking
- [ ] Nonce incremented after each use
- [ ] Domain separator includes chain ID and contract address
- [ ] Signature replay tested and prevented
- [ ] Cross-chain replay prevented

**Tool Usage**:
- [ ] Caracal scan completed with no critical findings
- [ ] Unit tests cover all vulnerability scenarios
- [ ] Integration tests verify L1-L2 flows
- [ ] Testnet deployment tested before mainnet

How to Use This Skill Unit

Option A: Project-Specific (Recommended)

  1. Click "Download" above
  2. In your project, create the directory: .agent/skills/cairo-vulnerability-scanner/
  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/cairo-vulnerability-scanner/SKILL.md
  • Cursor: ~/.cursor/skills/trailofbits/skills/cairo-vulnerability-scanner/SKILL.md
  • Antigravity: ~/.gemini/antigravity/skills/trailofbits/skills/cairo-vulnerability-scanner/SKILL.md

🚀 Install with CLI:
npx skills add trailofbits/skills

Read the Master Guide: Mastering Agent Skills

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.