Rust Fund

AI First Flight #9
Beginner FriendlyRust
EXP
View results
Submission Details
Severity: medium
Valid

amount_raised drift enables permanent withdraw DoS (“poison pill”) + misleading raised metric

Root + Impact

Description

  • Normal behavior: withdrawable lamports should be derived from escrowed balance, and/or state should reset/close after withdraw.

  • Actual behavior: fund.amount_raised only increments on contribute, is used as the withdraw transfer amount, and is never reset. After one withdraw, any later contribution (even 1 lamport) can make withdraw permanently fail due to insufficient lamports.

// programs/rustfund/src/lib.rs
fund.amount_raised += amount; // @ programs/rustfund/src/lib.rs:50
let amount = ctx.accounts.fund.amount_raised; // @ programs/rustfund/src/lib.rs:91
// withdraw transfers `amount` but never resets `amount_raised` // @ programs/rustfund/src/lib.rs:90

Risk

Likelihood:

  • Occurs after the first successful withdraw; amount_raised stays non-zero forever.

  • Occurs when anyone contributes after a withdraw (including accidental dust); the next withdraw attempts to transfer a historical total that no longer exists in the PDA.

Impact:

  • Creator cannot withdraw again; later donors’ lamports become stuck (no coherent exit path).

  • UIs relying on amount_raised show inflated “raised” values even when escrow is empty.

Proof of Concept

use anchor_lang::{prelude::Pubkey, AccountDeserialize, InstructionData, ToAccountMetas};
use solana_program::{account_info::AccountInfo, entrypoint::ProgramResult};
use solana_program_test::{processor, BanksClientError, ProgramTest, ProgramTestContext};
use solana_sdk::{
signature::{Keypair, Signer},
system_instruction, system_program,
transaction::Transaction,
};
fn process_rustfund_instruction<'a, 'b, 'c, 'd>(
program_id: &'a Pubkey,
accounts: &'b [AccountInfo<'c>],
instruction_data: &'d [u8],
) -> ProgramResult {
let accounts: &'c [AccountInfo<'c>] = unsafe { std::mem::transmute(accounts) };
rustfund::entry(program_id, accounts, instruction_data)
}
fn derive_fund_pda(program_id: &Pubkey, name: &str, creator: &Pubkey) -> Pubkey {
Pubkey::find_program_address(&[name.as_bytes(), creator.as_ref()], program_id).0
}
fn derive_contribution_pda(program_id: &Pubkey, fund: &Pubkey, contributor: &Pubkey) -> Pubkey {
Pubkey::find_program_address(&[fund.as_ref(), contributor.as_ref()], program_id).0
}
async fn send_tx(
ctx: &mut ProgramTestContext,
instructions: Vec<solana_sdk::instruction::Instruction>,
extra_signers: Vec<&Keypair>,
) -> Result<(), BanksClientError> {
let recent_blockhash = ctx.banks_client.get_latest_blockhash().await.unwrap();
let mut signers = vec![&ctx.payer];
signers.extend(extra_signers);
let tx = Transaction::new_signed_with_payer(
&instructions,
Some(&ctx.payer.pubkey()),
&signers,
recent_blockhash,
);
ctx.banks_client.process_transaction(tx).await
}
async fn get_lamports(ctx: &mut ProgramTestContext, address: Pubkey) -> u64 {
ctx.banks_client
.get_account(address)
.await
.unwrap()
.map(|a| a.lamports)
.unwrap_or(0)
}
async fn fetch_fund(ctx: &mut ProgramTestContext, fund: Pubkey) -> rustfund::Fund {
let account = ctx
.banks_client
.get_account(fund)
.await
.unwrap()
.expect("fund account should exist");
rustfund::Fund::try_deserialize(&mut account.data.as_ref()).unwrap()
}
#[tokio::test]
async fn poc_finding2_amount_raised_poison_pill() {
let program_id = rustfund::id();
let mut pt = ProgramTest::new("rustfund", program_id, processor!(process_rustfund_instruction));
let mut ctx = pt.start_with_context().await;
let creator = ctx.payer.pubkey();
let contributor = Keypair::new();
// Fund contributor (rent + donation).
send_tx(
&mut ctx,
vec![system_instruction::transfer(&creator, &contributor.pubkey(), 2_000_000_000)],
vec![],
)
.await
.unwrap();
let name = "poison-pill";
let description = "amount_raised drift/DoS PoC";
let goal = 10_000_000_000u64;
let amount = 2_000_000u64;
let fund = derive_fund_pda(&program_id, name, &creator);
let contribution = derive_contribution_pda(&program_id, &fund, &contributor.pubkey());
// Create fund.
let ix_create = solana_sdk::instruction::Instruction {
program_id,
accounts: rustfund::accounts::FundCreate {
fund,
creator,
system_program: system_program::ID,
}
.to_account_metas(None),
data: rustfund::instruction::FundCreate {
name: name.to_string(),
description: description.to_string(),
goal,
}
.data(),
};
send_tx(&mut ctx, vec![ix_create], vec![]).await.unwrap();
let rent_baseline = get_lamports(&mut ctx, fund).await;
// Contribute `amount`.
let ix_contribute = solana_sdk::instruction::Instruction {
program_id,
accounts: rustfund::accounts::FundContribute {
fund,
contributor: contributor.pubkey(),
contribution,
system_program: system_program::ID,
}
.to_account_metas(None),
data: rustfund::instruction::Contribute { amount }.data(),
};
send_tx(&mut ctx, vec![ix_contribute], vec![&contributor])
.await
.unwrap();
let fund_after_contribute = get_lamports(&mut ctx, fund).await;
assert_eq!(fund_after_contribute, rent_baseline + amount);
let fund_state = fetch_fund(&mut ctx, fund).await;
assert_eq!(fund_state.amount_raised, amount);
// First withdraw succeeds.
let ix_withdraw = solana_sdk::instruction::Instruction {
program_id,
accounts: rustfund::accounts::FundWithdraw {
fund,
creator,
system_program: system_program::ID,
}
.to_account_metas(None),
data: rustfund::instruction::Withdraw {}.data(),
};
send_tx(&mut ctx, vec![ix_withdraw.clone()], vec![]).await.unwrap();
let fund_after_withdraw = get_lamports(&mut ctx, fund).await;
assert_eq!(fund_after_withdraw, rent_baseline);
// BUG: `amount_raised` is not reset/reconciled after withdraw (drifts from actual escrowed lamports).
let fund_state_after_withdraw = fetch_fund(&mut ctx, fund).await;
assert_eq!(fund_state_after_withdraw.amount_raised, amount);
// Later "dust" contribution makes future withdraw impossible.
let ix_contribute_dust = solana_sdk::instruction::Instruction {
program_id,
accounts: rustfund::accounts::FundContribute {
fund,
contributor: contributor.pubkey(),
contribution,
system_program: system_program::ID,
}
.to_account_metas(None),
data: rustfund::instruction::Contribute { amount: 1 }.data(),
};
send_tx(&mut ctx, vec![ix_contribute_dust], vec![&contributor])
.await
.unwrap();
let fund_after_dust = get_lamports(&mut ctx, fund).await;
assert_eq!(fund_after_dust, rent_baseline + 1);
// BUG: second withdraw attempts to transfer historical `amount_raised` again and fails forever.
let err = send_tx(&mut ctx, vec![ix_withdraw], vec![]).await.unwrap_err();
println!("second withdraw error: {err:?}");
}

Recommended Mitigation

split total_raised vs escrow_balance, reset escrow on withdraw, and enforce terminal states

- let amount = fund.amount_raised;
+ let amount = fund.to_account_info().lamports().saturating_sub(rent_exempt_minimum);
Updates

Lead Judging Commences

ai-first-flight-judge Lead Judge 2 days ago
Submission Judgement Published
Validated
Assigned finding tags:

[M-01] Withdrawal doesn't reset amount_raised, leading to locked funds

## Description The `withdraw()` function in the `rustfund` program contains a vulnerability where the `amount_raised` state variable is never reset to zero after a successful withdrawal. This leads to a situation where new contributions after a withdrawal are effectively locked in the contract, as subsequent withdrawal attempts will fail due to insufficient funds. ```rust pub fn withdraw(ctx: Context<FundWithdraw>) -> Result<()> { let amount = ctx.accounts.fund.amount_raised; **ctx.accounts.fund.to_account_info().try_borrow_mut_lamports()? = ctx.accounts.fund.to_account_info().lamports() .checked_sub(amount) .ok_or(ProgramError::InsufficientFunds)?; **ctx.accounts.creator.to_account_info().try_borrow_mut_lamports()? = ctx.accounts.creator.to_account_info().lamports() .checked_add(amount) .ok_or(ErrorCode::CalculationOverflow)?; // Missing: fund.amount_raised = 0; Ok(()) } ``` The key issue is that after transferring the funds to its creator, the function does not reset the `amount_raised` variable. This means that if new contributions are made after a withdrawal, the `amount_raised` value will continue to accumulate. When the creator attempts to withdraw again, the contract will try to transfer the entire `amount_raised` value, which will be larger than the actual balance in the fund account, resulting in an `InsufficientFunds` error. ## Impact 1. **Permanently locked funds**: Any contributions made after a successful withdrawal will be permanently locked in the contract, as the creator cannot withdraw them. 2. **Campaign dysfunction**: The crowdfunding mechanism becomes dysfunctional after the first withdrawal, as any new funds contributed cannot be properly managed. ## Proof of Concept (PoC) The following test demonstrates how funds become locked after a withdrawal due to the amount_raised not being reset: ```javascript import * as anchor from "@coral-xyz/anchor"; import { Program } from "@coral-xyz/anchor"; import { Rustfund } from "../target/types/rustfund"; import { PublicKey } from '@solana/web3.js'; import { expect } from 'chai'; describe("amount_raised is never reset", () => { const provider = anchor.AnchorProvider.env(); anchor.setProvider(provider); const program = anchor.workspace.Rustfund as Program<Rustfund>; const creator = provider.wallet; const otherUser = anchor.web3.Keypair.generate(); const fundName = "0xWithdrawers Fund04"; const description = "VULN-04"; const goal = new anchor.BN(1000000000); // 1 SOL const contribution = new anchor.BN(1000000000); // 1 SOL let fundPDA: PublicKey; let contributionPDA: PublicKey; before(async () => { // Generate PDA for fund [fundPDA] = await PublicKey.findProgramAddress( [Buffer.from(fundName), creator.publicKey.toBuffer()], program.programId ); // Airdrop some SOL to the other user for testing const airdropSignature = await provider.connection.requestAirdrop( otherUser.publicKey, 2 * anchor.web3.LAMPORTS_PER_SOL ); await provider.connection.confirmTransaction(airdropSignature); }); it("Creates a fund", async () => { await program.methods .fundCreate(fundName, description, goal) .accounts({ fund: fundPDA, creator: creator.publicKey, systemProgram: anchor.web3.SystemProgram.programId, }) .rpc(); }); it("Contributes to fund", async () => { // Generate PDA for contribution [contributionPDA] = await PublicKey.findProgramAddress( [fundPDA.toBuffer(), provider.wallet.publicKey.toBuffer()], program.programId ); // Perform a contribution of 1 SOL await program.methods .contribute(contribution) .accounts({ fund: fundPDA, contributor: provider.wallet.publicKey, contribution: contributionPDA, systemProgram: anchor.web3.SystemProgram.programId, }) .rpc(); const fund = await program.account.fund.fetch(fundPDA); expect(fund.amountRaised.toString()).to.equal(contribution.toString()); }); it("Creator withdraws funds", async () => { const fundBalanceBefore = await provider.connection.getBalance(fundPDA); // Creator withdraws all funds await program.methods .withdraw() .accounts({ fund: fundPDA, creator: creator.publicKey, systemProgram: anchor.web3.SystemProgram.programId, }) .rpc(); const fundBalanceAfter = await provider.connection.getBalance(fundPDA); expect(fundBalanceAfter).to.be.below(fundBalanceBefore); // VULNERABILITY: amount_raised is not reset to 0 after withdrawal const fundAfterWithdrawal = await program.account.fund.fetch(fundPDA); expect(fundAfterWithdrawal.amountRaised.toString()).to.equal(contribution.toString()); }); it("New contributions are locked after withdrawal due to VULN-04", async () => { // Generate PDA for otherUser's contribution const [otherUserContributionPDA] = await PublicKey.findProgramAddress( [fundPDA.toBuffer(), otherUser.publicKey.toBuffer()], program.programId ); // Make another contribution from a different user const secondContribution = new anchor.BN(500000000); // 0.5 SOL await program.methods .contribute(secondContribution) .accounts({ fund: fundPDA, contributor: otherUser.publicKey, contribution: otherUserContributionPDA, systemProgram: anchor.web3.SystemProgram.programId, }) .signers([otherUser]) .rpc(); // VULNERABILITY: Since the amount_raised wasn't reset, it now includes both contributions const fundAfterSecondContribution = await program.account.fund.fetch(fundPDA); const expectedTotal = contribution.add(secondContribution); expect(fundAfterSecondContribution.amountRaised.toString()).to.equal(expectedTotal.toString()); // Now try to withdraw the second contribution try { await program.methods .withdraw() .accounts({ fund: fundPDA, creator: creator.publicKey, systemProgram: anchor.web3.SystemProgram.programId, }) .rpc(); // If we reach this point, the test has failed expect.fail("Withdrawal should have failed due to insufficient funds"); } catch (error) { // Verify it's the expected error (insufficient funds) expect(error.message).to.include("InsufficientFunds"); } }); }); ``` Save the above test as `tests/04.ts` in your project's test directory and run the test: ```Solidity anchor test ``` ## Concrete Impact Example To illustrate the real-world impact of this vulnerability, consider this scenario: 1. A creator launches a campaign to fund a 10 SOL project. 2. Contributors donate a total of 10 SOL, reaching the goal. 3. The creator withdraws the 10 SOL (withdrawal succeeds) when goal is reached and deadline past. 4. The `amount_raised` in the contract remains at 10 SOL, though the actual balance is now 0. 5. A new contributor donates 2 SOL to support the ongoing project. 6. The creator tries to withdraw this new contribution. 7. The withdrawal fails with an "InsufficientFunds" error because the contract tries to withdraw 12 SOL (the accumulated `amount_raised`), but only 2 SOL is available in the account. 8. The 2 SOL contribution is now permanently locked in the contract, with no mechanism to withdraw it. ## Recommendation The `withdraw()` function should be modified to reset the `amount_raised` value to zero after a successful withdrawal: ```rust pub fn withdraw(ctx: Context<FundWithdraw>) -> Result<()> { let amount = ctx.accounts.fund.amount_raised; **ctx.accounts.fund.to_account_info().try_borrow_mut_lamports()? = ctx.accounts.fund.to_account_info().lamports() .checked_sub(amount) .ok_or(ProgramError::InsufficientFunds)?; **ctx.accounts.creator.to_account_info().try_borrow_mut_lamports()? = ctx.accounts.creator.to_account_info().lamports() .checked_add(amount) .ok_or(ErrorCode::CalculationOverflow)?; // Reset amount_raised to 0 after successful withdrawal ctx.accounts.fund.amount_raised = 0; Ok(()) } ``` This fix ensures that after each withdrawal, the `amount_raised` is reset to zero, allowing new contributions to be properly accounted for and subsequently withdrawn by the creator.

Support

FAQs

Can't find an answer? Chat with us on Discord, Twitter or Linkedin.

Give us feedback!