The classic Solana exploits
Suggest an editOn Solana the caller chooses every account and every program an instruction touches. Each exploit in this lesson is one question about one of those inputs that the program did not ask.
The caller chooses every account
A Solana program cannot look anything up by itself. The instruction lists the accounts, and the runtime hands the program those accounts and nothing else. The vault, the config, and the token program you call all sit in slots that the caller filled.
So before a handler uses an account, it has to establish four things about it: which program owns it, what type of data it holds, whether it sits at the address you expect, and whether the right key signed. For an account the handler initializes, it also has to establish whether the account is new or already holds state. Before it calls another program, it has to establish that this is the program it meant to call. Anchor's typed accounts and constraints do these checks when you use them. The bugs below come from skipping a constraint, weakening it, or using an untyped account to begin with.
Two hacks, one missing check each
Cashio, a stablecoin, lost about 50 million dollars. To mint, the caller passed a bank account that says which collateral is accepted. The program checked that the collateral matched the bank, but never checked that the bank was one of the protocol's own, and anyone could create a bank. The attacker created a bank with matching collateral accounts and minted CASH, the stablecoin, with no real collateral behind it.
Wormhole, a bridge, lost about 320 million dollars. Signatures on Solana are verified by a built-in program in a separate instruction, so the bridge read the transaction's list of instructions to confirm that the check had run. It read that list from whatever account the caller passed in the sysvar slot and never compared that account's address with the real sysvar address. The caller passed an ordinary account with a fake successful check inside.
Both programs ran many checks, and every one of them relied on an account that came from the caller. The root of trust lesson in Solana PRO goes through both hacks in detail.
Type confusion: the handler reads bytes nobody verified
A handler that accepts an UncheckedAccount or AccountInfo where it should accept a typed Account<'info, T> trusts whatever the caller passes. There is no discriminator check, no owner check, and no verification that the bytes mean what your code thinks they mean.
#[derive(Accounts)]
pub struct Withdraw<'info> {
/// CHECK: trust me, it's the vault
#[account(mut)]
pub vault: UncheckedAccount<'info>,
#[account(mut)]
pub recipient: Signer<'info>,
}
pub fn withdraw(ctx: Context<Withdraw>, amount: u64) -> Result<()> {
let vault_data = ctx.accounts.vault.try_borrow_data()?;
let total = u64::from_le_bytes(vault_data[8..16].try_into().unwrap());
require!(total >= amount, VaultError::Insufficient);
// ... transfer lamports out
Ok(())
}The caller can pass any account at all. The handler reads bytes 8 through 16 and interprets them as a u64 total, so the attacker passes an account they control whose bytes decode to whatever number suits them.
#[derive(Accounts)]
pub struct Withdraw<'info> {
#[account(mut, seeds = [b"vault"], bump = vault.bump)]
pub vault: Account<'info, Vault>,
#[account(mut)]
pub recipient: Signer<'info>,
}Account<'info, Vault> checks that the account's first 8 bytes match the discriminator of the Vault struct and that the account's owner is the current program. The seeds constraint checks that the address derives from your program with the expected seeds. Any non-Vault account, any Vault owned by another program, and any account at the wrong address fails validation before your handler runs.
The address check is the one Cashio lacked. A bank created by the attacker had the right type and the right owner, because the program's own instruction had created it. The protocol's account can be told apart from one the caller made only by an address the caller cannot choose, such as a PDA with fixed seeds or an address stored in an account that is already verified.
Never accept UncheckedAccount for an account whose data you intend to read or whose lamports you intend to move. Reserve it for accounts your code only passes through, such as a seed source or an opaque destination for a token transfer.
The same applies to signatures. A slot typed Signer<'info> requires that key to have signed the transaction. If the slot is typed AccountInfo by mistake, the handler only learns which key the caller named.
#[derive(Accounts)]
pub struct AdminWithdraw<'info> {
#[account(mut, has_one = admin)]
pub vault: Account<'info, Vault>,
/// CHECK: has_one compares it with vault.admin
pub admin: AccountInfo<'info>,
#[account(mut)]
pub recipient: SystemAccount<'info>,
}
pub fn admin_withdraw(ctx: Context<AdminWithdraw>, amount: u64) -> Result<()> {
ctx.accounts.vault.sub_lamports(amount)?;
ctx.accounts.recipient.add_lamports(amount)?;
Ok(())
}has_one = admin checks that the key in the admin slot equals the admin field stored in the vault. That key is public, so the caller puts it in the slot, puts their own wallet in recipient, and signs with their own key only. The has_one check passes, and the vault pays them. With pub admin: Signer<'info> the same call fails validation with AccountNotSigner, because the admin did not sign.
Reinitialization: the initializer runs on a live account
Running initialization logic on an account that is already initialized lets the caller overwrite state that should be permanent. This shows up when someone handles account creation without the init constraint, usually because they want custom behavior the macro doesn't expose.
#[derive(Accounts)]
pub struct InitializeVault<'info> {
/// CHECK: manual init, no constraint
#[account(mut)]
pub vault: UncheckedAccount<'info>,
pub payer: Signer<'info>,
pub system_program: Program<'info, System>,
}
pub fn initialize(ctx: Context<InitializeVault>) -> Result<()> {
let vault = &mut ctx.accounts.vault;
let mut data = vault.try_borrow_mut_data()?;
// Write discriminator + admin + counters manually...
data[8..40].copy_from_slice(ctx.accounts.payer.key().as_ref());
Ok(())
}Any caller can invoke initialize on the existing vault and overwrite the stored admin pubkey with their own. The attacker now controls every privileged operation that checks the vault's admin field.
#[derive(Accounts)]
pub struct InitializeVault<'info> {
#[account(
init,
payer = payer,
space = 8 + Vault::INIT_SPACE,
seeds = [b"vault"],
bump,
)]
pub vault: Account<'info, Vault>,
#[account(mut)]
pub payer: Signer<'info>,
pub system_program: Program<'info, System>,
}The init constraint fails at validation if the vault account already exists, so the same account cannot be initialized twice. Use init and put the custom behavior elsewhere. If you need a re-initialization path on purpose, make it a separate instruction that requires the existing admin's signature.
Arbitrary CPI: the caller chooses the program you call
When your handler invokes another program through a CPI, the program to call is also an account in a slot. If your code uses that slot without verifying it, the caller decides which code runs. The handler below builds the SPL Token transfer instruction itself and takes the program ID from the token_program slot.
#[derive(Accounts)]
pub struct Deposit<'info> {
#[account(mut)]
pub user_token: Account<'info, TokenAccount>,
#[account(mut)]
pub vault_token: Account<'info, TokenAccount>,
pub user: Signer<'info>,
/// CHECK: token program
pub token_program: UncheckedAccount<'info>,
}
pub fn deposit(ctx: Context<Deposit>, amount: u64) -> Result<()> {
let ix = Instruction {
program_id: ctx.accounts.token_program.key(),
accounts: vec![
AccountMeta::new(ctx.accounts.user_token.key(), false),
AccountMeta::new(ctx.accounts.vault_token.key(), false),
AccountMeta::new_readonly(ctx.accounts.user.key(), true),
],
data: TokenInstruction::Transfer { amount }.pack(),
};
invoke(&ix, &ctx.accounts.to_account_infos())?;
Ok(())
}The caller passes their own program in place of the SPL Token program. That program receives the CPI, does nothing, and returns success. No tokens moved, but the handler continues as if amount tokens had arrived in the vault, and a real deposit handler would now credit the caller with amount.
The fix is to pin the program:
pub token_program: Program<'info, Token>,Program<'info, Token> checks that the account in this slot has the SPL Token program's exact pubkey, and any other program fails validation. Do the same for every program you call: Program<'info, AssociatedToken>, Program<'info, System>, or for custom programs Program<'info, MyOtherProgram>, where MyOtherProgram is the IDL type emitted by the other program's build.
Not every CPI helper reads the slot. anchor_spl::token::transfer always builds its instruction for the SPL Token program's fixed ID and ignores the program in CpiContext, so a handler that calls it cannot be redirected this way. The CPI functions Anchor generates for calling another Anchor program take the program ID from CpiContext, so their slot needs the same pin.
Wormhole is the same mistake with data instead of code. The instructions sysvar is a well-known account at a fixed address, and the program read it from a slot it had not compared with that address.
init_if_needed: the handler runs on an account that already has state
With init_if_needed the account is created if it doesn't exist and reused if it does. So the handler runs in two different situations: on a fresh account where every field is zero, and on an existing account whose fields hold whatever earlier calls wrote. A handler written only for the first case is wrong in the second.
#[derive(Accounts)]
pub struct CreateOffer<'info> {
#[account(
init_if_needed,
payer = maker,
space = 8 + Offer::INIT_SPACE,
seeds = [b"offer", maker.key().as_ref()],
bump,
)]
pub offer: Account<'info, Offer>,
#[account(mut)]
pub maker: Signer<'info>,
pub system_program: Program<'info, System>,
}
pub fn create_offer(ctx: Context<CreateOffer>, price: u64) -> Result<()> {
let offer = &mut ctx.accounts.offer;
offer.maker = ctx.accounts.maker.key();
offer.price = price;
// assumes offer.accepted is still false (default)
// but if this is a re-use, it might already be true...
Ok(())
}
pub fn accept_offer(ctx: Context<AcceptOffer>) -> Result<()> {
let offer = &mut ctx.accounts.offer;
require!(!offer.accepted, OfferError::AlreadyAccepted);
offer.accepted = true;
Ok(())
}The maker creates an offer and someone accepts it, so offer.accepted is now true. The maker calls create_offer again with a new price. The account exists, the handler writes the new price, and accepted stays true from the previous offer. The new offer can never be accepted. Nothing is stolen in this example, but the maker's offer account is stuck until it is closed. If the handler reset accepted to false instead, it would erase the record that the first offer was taken.
The fix is to detect first use explicitly:
pub fn create_offer(ctx: Context<CreateOffer>, price: u64) -> Result<()> {
let offer = &mut ctx.accounts.offer;
// detect first-use: a freshly init'd account has maker == default()
let is_new = offer.maker == Pubkey::default();
require!(is_new, OfferError::OfferExists);
offer.maker = ctx.accounts.maker.key();
offer.price = price;
// No need to reset accepted; is_new guarantees the account was just created.
Ok(())
}offer.maker == Pubkey::default() is true only when the account was zero-initialized by this instruction. If the account already exists, the require fails and the handler refuses to overwrite it. To create a new offer, the user has to close the old account first. When you can, prefer plain init with a separate instruction that the user calls once.
Two checks on numbers: overflow and rent
These two bugs are about numbers, not about which account the caller passed.
Rust's debug builds panic on integer overflow and release builds wrap. Solana programs are built in release mode, but a workspace created with anchor init sets overflow-checks = true for release builds in its Cargo.toml, so there an overflowing += panics and the transaction fails. If your program is built in the wrapping mode, an unchecked += on a u64 that passes u64::MAX leaves a small number in the field with no error and no log. Use checked arithmetic on every amount, so that the result does not depend on the build settings and an overflow aborts the handler with an error:
pub fn deposit(ctx: Context<Deposit>, amount: u64) -> Result<()> {
let vault = &mut ctx.accounts.vault;
vault.total_deposits = vault
.total_deposits
.checked_add(amount)
.ok_or(VaultError::Overflow)?;
Ok(())
}A withdrawal that checks only amount <= lamports lets the caller take the whole balance, including the rent-exempt minimum the account needs to stay alive. An account left with zero lamports is removed at the end of the transaction (account closure), so the vault disappears. A withdrawal that leaves more than zero but less than the minimum does not go through, because the runtime rejects the whole transaction with InsufficientFundsForRent. Subtract the minimum first and check the request against what is left:
let vault_info = ctx.accounts.vault.to_account_info();
let rent = Rent::get()?;
let rent_exempt_minimum = rent.minimum_balance(vault_info.data_len());
let available = vault_info
.lamports()
.checked_sub(rent_exempt_minimum)
.ok_or(VaultError::BelowRentExempt)?;
require!(amount <= available, VaultError::Insufficient);The question to ask of every input
When you write or review a handler, go through its inputs one by one and ask what the caller could put there.
- Every account: did something check its type, its owner, and its address? If a signature matters, is the slot a
Signer? - Every program you call: is it pinned with
Program<'info, T>? - Every numeric argument: is the arithmetic checked?
- Every field of an account behind
init_if_needed: is the case where the account already exists handled?
Default to typed Anchor accounts: Account<'info, T>, Signer<'info>, Program<'info, T>. Use UncheckedAccount only when you have decided that you don't need the check, and write the reason in the /// CHECK: comment. If the answer to "what could the caller put here?" is "I'd have to look at how this is called elsewhere", look there before you move on.