Cairo Vulnerability Scanner

Cairo Vulnerability Scanner

Cairo Vulnerability Scanner automation and integration

Category: productivity Source: trailofbits/skills

Cairo Vulnerability Scanner is a community skill for detecting security vulnerabilities in Cairo smart contracts on StarkNet, covering static analysis, common vulnerability patterns, reentrancy detection, access control verification, and automated security auditing for Cairo-based blockchain applications.

What Is This?

Overview

Cairo Vulnerability Scanner provides patterns for analyzing Cairo smart contracts for security issues. It covers static analysis that parses Cairo source code to identify risky patterns without execution, common vulnerability patterns that detect issues like integer overflow, unchecked return values, and unsafe storage access, reentrancy detection that identifies functions vulnerable to recursive call exploits, access control verification that checks authorization guards on privileged functions, and automated auditing that runs a full scan and generates a findings report. The skill enables security review of Cairo contracts before deployment to StarkNet, helping teams catch critical issues early in the development lifecycle.

Who Should Use This

This skill serves smart contract developers building on StarkNet, security auditors reviewing Cairo codebases for vulnerabilities, and DeFi teams preparing contracts for mainnet deployment. It is also valuable for protocol teams conducting internal security reviews before engaging external auditors.

Why Use It?

Problems It Solves

Cairo has unique syntax and semantics where traditional Solidity security patterns do not apply. Manual code review for Cairo contracts is slow and prone to missing subtle issues. StarkNet contracts handle real financial value making undetected vulnerabilities costly. The Cairo ecosystem has fewer mature security tools compared to EVM-based chains, making automated scanning particularly important for teams without dedicated security specialists.

Core Highlights

Pattern matcher detects known vulnerability signatures in Cairo AST. Reentrancy analyzer traces external call paths for recursive exploitation risks. Access checker verifies authorization decorators on state-modifying functions. Report generator produces structured findings with severity ratings.

How to Use It?

Basic Usage

import re
from dataclasses\
  import dataclass
from pathlib import Path

@dataclass
class Finding:
  severity: str
  title: str
  location: str
  description: str

class CairoScanner:
  def __init__(self):
    self.findings:\
      list[Finding] = []

  def scan_file(
    self, path: str
  ) -> list[Finding]:
    code = Path(path)\
      .read_text()
    self.findings = []
    self._check_access(
      code, path)
    self._check_overflow(
      code, path)
    self._check_reentrancy(
      code, path)
    return self.findings

  def _check_access(
    self, code: str,
    path: str
  ):
    funcs = re.findall(
      r'#\[external\(v0\)]'
      r'\s+fn (\w+)',
      code)
    for fn in funcs:
      pattern = (
        f'fn {fn}'
        f'[^{{]*assert_only'
        f'_owner')
      if not re.search(
          pattern, code,
          re.DOTALL):
        self.findings.append(
          Finding(
            'HIGH',
            'Missing access'
            ' control',
            f'{path}:{fn}',
            f'{fn} lacks'
            f' owner check'))

Real-World Examples

from pathlib import Path
import json

def scan_project(
  project_dir: str,
  output: str
) -> dict:
  scanner = CairoScanner()
  all_findings = []

  for cairo_file in Path(
      project_dir).rglob(
        '*.cairo'):
    findings = scanner\
      .scan_file(
        str(cairo_file))
    all_findings.extend(
      findings)

  report = {
    'total': len(
      all_findings),
    'high': sum(
      1 for f
      in all_findings
      if f.severity
        == 'HIGH'),
    'findings': [
      {'severity':
        f.severity,
       'title': f.title,
       'location':
        f.location}
      for f
      in all_findings]}

  Path(output).write_text(
    json.dumps(
      report, indent=2))
  return report

Advanced Tips

Build custom detection rules for project-specific patterns like non-standard access control mechanisms. Run the scanner as a pre-commit hook to catch issues before code review. Combine static analysis with formal verification tools for high-value contracts holding significant funds. Maintaining a versioned rule library alongside your codebase ensures detection logic stays synchronized with contract changes over time.

When to Use It?

Use Cases

Scan a StarkNet DeFi protocol before mainnet deployment for known vulnerability patterns. Integrate automated scanning into a Cairo CI pipeline for continuous security checks. Generate a security audit report for a Cairo contract review engagement.

Related Topics

Smart contract security, Cairo language, StarkNet, static analysis, and blockchain auditing.

Important Notes

Requirements

Python with regex support for pattern matching. Access to Cairo source files for the target project. Understanding of Cairo-specific vulnerability patterns for rule tuning.

Usage Recommendations

Do: update vulnerability patterns as the Cairo language evolves and new attack vectors emerge. Run scans on every contract version before deployment. Combine automated scanning with manual expert review for thorough coverage.

Don't: treat a clean scanner report as proof of security since automated tools miss logic bugs. Deploy contracts without any security review even if the scanner finds no issues. Ignore low-severity findings as they may combine into exploitable attack chains.

Limitations

Static analysis cannot detect all logic vulnerabilities that require understanding business intent. Pattern-based detection misses novel attack vectors not in the rule database. Cairo language updates may change syntax in ways that break existing detection rules. False positives are common in heuristic-based scanning and each finding requires manual verification before reporting. Teams should track false positive rates over time to improve rule precision and reduce unnecessary investigation overhead.