audit-solana
Security audit for Solana programs (Anchor/native)
mkdir -p ~/.claude/commands && curl -fsSL https://raw.githubusercontent.com/solanabr/solana-ai-kit/HEAD/.claude/commands/audit-solana.md -o ~/.claude/commands/audit-solana.mdaudit-solana.md
You are conducting a security audit for Solana programs. This is CRITICAL - take your time.
## Related Skills
- [security.md](../skills/security.md) - Comprehensive security checklist
- [programs/anchor.md](../skills/ext/solana-dev/skill/references/programs/anchor.md) - Anchor security patterns
- [programs/pinocchio.md](../skills/ext/solana-dev/skill/references/programs/pinocchio.md) - Pinocchio security patterns
- [testing.md](../skills/testing.md) - Fuzz testing with Trident
## Pre-Audit Checklist
- [ ] All tests passing
- [ ] Code compiles without warnings
- [ ] Documentation complete
- [ ] No hardcoded keys or secrets
## Step 1: Automated Analysis
```bash
echo "🔍 Running automated security analysis..."
# Dependency audit (check for known vulnerabilities)
echo " 📦 Checking dependencies..."
cargo audit
# Supply chain security (check for malicious dependencies)
if command -v cargo-geiger >/dev/null 2>&1; then
echo " ☢️ Checking unsafe code usage..."
cargo geiger
fi
# Clippy with strict security lints
echo " 🔎 Running clippy security lints..."
cargo clippy --all-targets -- \
-W clippy::all \
-W clippy::pedantic \
-W clippy::unwrap_used \
-W clippy::expect_used \
-W clippy::panic \
-W clippy::arithmetic_side_effects \
-D warnings
# Format check
echo " 📝 Checking format..."
cargo fmt --check
# Run full test suite
echo " 🧪 Running tests..."
if [ -f "Anchor.toml" ]; then
anchor build && anchor test
else
cargo build-sbf && cargo test
fi
echo "✅ Automated analysis complete"
```
## Step 2: Account Validation Review
**CRITICAL**: Every account MUST be validated. Check each instruction:
### Owner Checks
```rust
// ✓ CORRECT: Validate account owner
if *account.owner != expected_program_id {
return Err(ProgramError::IncorrectProgramId);
}
// ✗ WRONG: Assuming owner without check
```
### Signer Checks
```rust
// ✓ CORRECT: Verify signer
if !authority.is_signer {
return Err(ProgramError::MissingRequiredSignature);
}
// ✗ WRONG: Privileged operation without signer check
```
### PDA Validation
```rust
// ✓ CORRECT: Use stored canonical bump
let seeds = &[
b"vault",
authority.key.as_ref(),
&[vault.bump], // stored bump
];
// ✗ WRONG: Recalculating bump or accepting user-provided bump
let (pda, _) = Pubkey::find_program_address(seeds, program_id);
```
## Step 3: Arithmetic Safety Review
Check ALL arithmetic operations:
```rust
// ✓ CORRECT: Checked arithmetic
let total = amount_a
.checked_add(amount_b)
.ok_or(ErrorCode::Overflow)?;
// ✗ WRONG: Unchecked arithmetic (can panic/overflow)
let total = amount_a + amount_b;
```
**Checklist**:
- [ ] All additions use `checked_add`
- [ ] All subtractions use `checked_sub`
- [ ] All multiplications use `checked_mul`
- [ ] All divisions use `checked_div`
- [ ] No unwrap() in arithmetic operations
## Step 4: Common Attack Vectors
### Type Cosplay
```rust
// ✓ CORRECT: Check discriminator
if account.data.borrow()[0..8] != User::DISCRIMINATOR {
return Err(ProgramError::InvalidAccountData);
}
// In Anchor, Account<'info, T> does this automatically
```
### Account Revival
```rust
// ✓ CORRECT: Zero data AND set closed discriminator
let mut data = account.data.borrow_mut();
data.fill(0);
data[0..8].copy_from_slice(&CLOSED_ACCOUNT_DISCRIMINATOR);
// Anchor's `close` constraint handles this
#[account(mut, close = destination)]
```
### Arbitrary CPI
```rust
// ✓ CORRECT: Validate program ID
if cpi_program.key() != spl_token::ID {
return Err(ErrorCode::InvalidProgram.into());
}
// ✗ WRONG: Accepting any program from user
invoke(&instruction, accounts)?;
```
### Missing Reload After CPI
```rust
// ✓ CORRECT: Reload account after CPI
token::transfer(cpi_ctx, amount)?;
ctx.accounts.token_account.reload()?;
// ✗ WRONG: Using stale data after CPI
token::transfer(cpi_ctx, amount)?;
// ... using token_account without reload
```
### PDA Seed Collision
```rust
// ✓ CORRECT: Unique prefixes per account type
let user_seeds = [b"user_vault", user.key().as_ref()];
let admin_seeds = [b"admin_config", admin.key().as_ref()];
// ✗ WRONG: Shared PDA space
let seeds = [b"vault", key.as_ref()]; // collision possible
```
## Step 5: CPI Security
Check all cross-program invocations:
- [ ] Target program ID is validated (hardcoded or checked)
- [ ] Signer privileges not blindly forwarded
- [ ] Accounts reloaded after CPI if modified
- [ ] Return values checked
- [ ] Error handling proper
## Step 6: Economic Security
For financial operations:
- [ ] Slippage protection implemented
- [ ] Oracle data validated (staleness, confidence)
- [ ] No price manipulation vectors
- [ ] Proper fee accounting
- [ ] Inflation attack prevention (for vaults)
## Step 7: Error Handling
- [ ] No `unwrap()` or `expect()` in program code
- [ ] All error codes defined
- [ ] Descriptive error messages
- [ ] All errors propagated correctly
## Step 8: CU (Compute Units) Optimization
Check for CU waste:
- [ ] Minimal logging (use feature flags for debug logs)
- [ ] PDA bumps stored and reused (not recalculated)
- [ ] Efficient data access patterns
- [ ] No unnecessary account loads
## Step 9: Testing Requirements
Verify comprehensive test coverage:
- [ ] All instructions tested (success paths)
- [ ] All error conditions tested
- [ ] Account validation failures tested
- [ ] Arithmetic edge cases tested (max values, overflow)
- [ ] PDA derivation tested
- [ ] CPI success and failure paths tested
- [ ] Fuzz testing with Trident (REQUIRED for mainnet)
### Fuzz Testing with Trident
```bash
# Setup Trident (if not already)
if [ ! -d "trident-tests" ]; then
echo "Setting up Trident fuzz testing..."
trident init
fi
# Run fuzz tests for at least 10 minutes (Trident v0.7+)
echo "🔍 Running fuzz tests (10 minutes minimum)..."
cd trident-tests
trident fuzz run --timeout 600
# Review any crashes found
if [ -d "hfuzz_workspace" ]; then
echo "⚠️ Review crash reports in hfuzz_workspaceAnchor framework specialist for rapid Solana program development. Use for building programs with Anchor macros, IDL generation, account validation, and standardized patterns. Prioritizes developer experience while maintaining security.\\n\\nUse when: Building new programs quickly, team projects needing standardization, projects requiring IDL for client generation, or when developer experience is prioritized over maximum CU optimization.
DeFi integration specialist for composing with Solana protocols including Jupiter, Drift, Kamino, Raydium, Orca, Meteora, Marginfi, and Sanctum. Handles swap routing, lending/borrowing, staking, liquidity provision, and oracle price feeds.\n\nUse when: Integrating DeFi protocols, building swap interfaces, implementing lending/borrowing, setting up yield strategies, working with Pyth/Switchboard oracles, or composing multi-protocol transactions.
CI/CD, infrastructure, and deployment specialist for Solana projects. Handles GitHub Actions, Docker, monitoring, RPC management, and Cloudflare Workers edge deployment.\n\nUse when: Setting up CI/CD pipelines, containerizing Solana validators or programs, configuring monitoring and alerting, managing RPC infrastructure, deploying edge workers, or automating build and deploy workflows.
Senior Solana game architect for game system design, Unity/C# architecture, on-chain game state, player progression, NFT integration, and PlaySolana ecosystem. Use for high-level game design decisions, architecture reviews, and planning complex game systems.\n\nUse when: Designing new Solana games from scratch, planning game state on-chain, Unity project architecture, integrating with PlaySolana/PSG1, or deciding between implementation approaches.
React Native and Expo specialist for building Solana mobile dApps. Handles mobile wallet adapter integration, transaction signing UX, deep linking, and mobile-specific performance optimization.\n\nUse when: Building React Native or Expo mobile apps with Solana integration, implementing mobile wallet adapter flows, setting up deep links for transaction signing, or optimizing mobile dApp performance.
CU optimization specialist using Pinocchio framework. Use for performance-critical programs requiring 80-95% CU reduction vs Anchor. Specializes in zero-copy access, manual validation, and minimal binary size.\\n\\nUse when: CU limits are being hit, transaction costs are significant at scale, binary size must be minimized, or maximum throughput is required.
Rust backend specialist for building async services that interact with Solana blockchain. Builds APIs, indexing services, and off-chain processing using Axum, Tokio, and modern async patterns.\n\nUse when: Building REST/WebSocket APIs for Solana dApps, implementing transaction indexers, creating webhook services, or any Rust backend that interacts with Solana.
Senior Solana program architect for system design, account structures, PDA schemes, token economics, and cross-program composability. Use for high-level design decisions, architecture reviews, and planning complex multi-program systems.\n\nUse when: Designing new programs from scratch, planning account structures, optimizing PDA schemes, reviewing architecture for security, or deciding between implementation approaches.