State changes are overwritten during anchor serialization when two accounts are the same
When a swap passes the same account for two of the three pool parameters, Anchor serialises the account twice and the second write overwrites the first, so one of the reserve updates is lost. This leaves the quote pool's reserve value incorrect, which can block valid swaps or prevent the admin from claiming fees.
Source: https://github.com/sherlock-audit/2024-08-woofi-solana-deployment-judging/issues/73
Found by
S3v3ru5
Summary
The swap operation takes in 3 pool accounts:
- woopool_from
- woopool_to
- woopool_quote
Case 1:
In Base-to-Quote Swap, woopool_from is base token pool. woopool_to, woopool_quote will be the quote token pool and both are same accounts woopool_to == woopool_quote.
Case 2:
In Quote-to-Base Swap, woopool_to is base token pool. woopool_from, woopool_quote will be the quote token pool and both are same accounts woopool_from == woopool_quote.
Case 3: In the case of Base-to-Base all three pools will be different.
In case 1 and case 2, two of the passed-in accounts are same. Because of how anchor works, at the end of the execution, changes of only one pool will be saved. For example in case 1 when woopool_to, woopool_quote are same, at the end of the program execution, updates to either woopool_to or woopool_quote are recorded.
Anchor #[derive(Accounts)] macro works by creating a in-memory copy of the account data, modifying the memory and then writing back into the account data:
- For each of the account, Anchor performs required checks based on the type
Account<'info, WooConfig>,Program<'info, Token>, etc. - For
Account<'a, T>type accounts, Anchor deserializes theAccountInfo.dataintoT. For e.g, if account X is passed forAccount<'a, WooPool>then Anchor deserializesX.datainto typeWooPooland keeps the copy in memory.- Same as
memorycopies of state variables in Solidity.
- Same as
- The deserialized in-memory copies of the accounts are passed to the instruction-handler: for example
swapfunction is an instruction handler. - After the instruction handler finishes execution, Anchor serializes the accounts and writes into the account data.
- The account data is persistent and hence the state changes are saved.
Consider a Solidity function which copies a struct state variable into memory, changes the values in memory and at the end of the function copies the memory values into the state variable. Anchor does the same thing.
This leads to a storage overwrite issue when two of the passed-in accounts are same. When the second struct written into account data, it will overwrite any changes that are present in the first struct.
The swap instruction handler performs the following updates to the pools:
- Add
from_amounttowoopool_fromreserve - Subtract
to_amountfromwoopool_toreserve - Subtract
swap_feefromwoopool_quotereserve - Add
swap_feeto unclaimed fee
woopool_quote is serialized last hence it will overwrite any previous changes if they are same accounts.
- If
woopool_from==woopool_quote:- Update in
1will be overwritten by3and4. from_amountwill not be added towoopool_from(quote pool) reserves
- Update in
- if
woopool_to==woopool_quote:- Update in
2will be overwritten by3and4. to_amountwill not be deducted from thewoopool_to(quote pool) reserves
- Update in
Root Cause
The swap function tries to handle all type of swaps in a single instruction allowing for cases where two writable accounts are the same leading to storage overwrite issues
Internal pre-conditions
No response
External pre-conditions
No response
Attack Path
User performs a swap: either Base to quote or quote to base. The reserves of the quote will not be updated correctly.
Impact
- If swap sells quote:
from_amountwill not be added towoopool_from(quote pool) reserves
- if swap sells base for quote:
to_amountwill not be deducted from thewoopool_to(quote pool) reserves
This leads to incorrect accounting of quote pool reserves variable.
- The reserve will be higher than the quote pool token vault balance Or
- The reserve will be lower than the quote pool token vault balance
Additional to incorrect state, because balance is checked before transfering tokens in claim_fee, the issue might prevent admin from claiming fees. The issue might have additional implications that aren't noted here.
PoC
In the 1_woofi_swap.ts test file, update the swap_from_sol_to_usdc test to print the reserve values of the toPool before and after the swap.
Add the following at line 265 in tests/1_woofi_swap.ts:
let toPoolDataBefore = null;
try {
toPoolDataBefore = await program.account.wooPool.fetch(toPoolParams.woopool);
} catch (e) {
console.log(e);
console.log("fetch failed");
return;
}
console.log("toPool reserve before swap:" + toPoolDataBefore.reserve);
console.log("toPool unclaimed fee before swap:" + toPoolDataBefore.unclaimedFee);
and Add the following at line 357 at the end of the that test (after swap is called`:
let toPoolDataAfter = null;
try {
toPoolDataAfter = await program.account.wooPool.fetch(toPoolParams.woopool);
} catch (e) {
console.log(e);
console.log("fetch failed");
return;
}
console.log("toPool reserve after swap:" + toPoolDataAfter.reserve);
console.log("toPool unclaimed fee after swap:" + toPoolDataAfter.unclaimedFee);
The output will be:
#swap_between_sol_and_usdc
fromWallet PublicKey:Cybv9pDy9MoysaTk3gkRi3RCtW5gz1jRzZouF47TyfnB
solWalletTokenAccount:GCGi8N26WRcwBedHCFoRo8iycWwLadaNYJx1CW7PyJQ
usdcWalletTokenAccount:Aynux9Ei1FczuPNb5i4Z6cgJisABx3Ty5xNZUfsR6Gst
fromWallet Balance:0
fromTokenAccount amount:1000000
fromTokenAccount decimals:9
toPool reserve before swap:200000
toPool unclaimed fee before swap:0
price - 14597424250
feasible - 1
price - 0
feasible - 0
toAmount:136775
swapFee:4231
toTokenAccount amount:136775
toTokenAccount decimals:6
toPool reserve after swap:195769
toPool unclaimed fee after swap:4231
✔ swap_from_sol_to_usdc (3274ms)
In the test, woopool_to == woopool_quote == USDC pool. The reserve of the USDC pool should be
usdcPool.reserve = usdcPool.reserve - toAmount - swapFee = 200000 - 136775 - 4231
However, in the output it can be seen that, the usdcPool.reserve is equal to reserve - swap_fee = 200000 - 4231 = 195769
The deduction of to_amount from the woopool_to.reserve is not present:
Only the swap_fee deduction is preserved because it was deducted from woopool_quote:
When Anchor serialized the accounts at the end, the woopool_to is first written to the account data and then the woopool_quote. Because both are same accounts, the changes in woopool_to are overwritten when woopool_quote is serialized and written to account data.
In case of swap usdc to sol, the changes in woopool_from will be overwritten by the woopool_quote.
Mitigation
Divide the swap functions into individual sell_base, sell_quote, and sell_base_to_base functions.
Discussion
toprince
Oh....anchor...
S3v3ru5
The judging comments include "No loss of funds" as a reason for the medium severity. The incase_token_got_stuck can be used to retrieve any tokens from the vaults.
I do not think only loss of funds issues can be consider as High.
The reserves variable is a core state variable and it will be wrong because of the above issue. There are multiple implications of the incorrect reserves variable
- The issue #68 lists one such impact of this issue.
- The vault token-balance could be greater than reserves when Quote to Base swap is performed. The valid swaps will be rejected even when vault has enough tokens for the swap.
- Pool admin cannot use the
withdrawfunction to withdraw thetoken balance - reservestokens if token-balance is greater than the reserve.
sherlock-admin2
The protocol team fixed this issue in the following PRs/commits: https://github.com/woonetwork/WOOFi_Solana/pull/33
gjaldon
Case woopool_from == woopool_quote:
- This change fixes the issue because only the
woopool_quoteis modified. The changes to the from_pool and the quote pool are applied to only the quote pool because they are the same.
Case woopool_to == woopool_quote:
- This change fixes the issue because only
woopool_quoteis modified . The changes to the to_pool and the quote are applied to only the quote pool because they are the same.
Case where all 3 pools are different:
- The previous behavior was retained since this case was unaffected by the issue.
Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.
How it worked
Root cause
The swap instruction accepts the same writable account for two different pool parameters, and Anchor serialises each parameter separately, so the later serialisation overwrites the earlier one.
Impact
The quote pool's reserve becomes incorrect, which could cause valid swaps to be rejected or prevent the admin from withdrawing or claiming fees; the text notes the protocol team fixed it.
What the attacker needed
A swap where two pool accounts are the same
The fix
The swap logic was changed so that when the from or to pool is the same as the quote pool, only the quote pool is modified, and the protocol team fixed it in a pull request.
How it was found
- Run the existing swap test that swaps SOL for USDC, where the to pool and quote pool are the same account.
- Print the to pool's reserve and unclaimed fee before the swap.
- Call swap.
- Print the to pool's reserve and unclaimed fee after the swap.
- Observe that the reserve only decreased by the swap fee, not by the to amount plus the swap fee.
Explained by bugbounty.wiki with AI from the original and checked against quotes from it; it can still be wrong. Read the original before relying on a detail.
Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.
In Solana programs, the framework Anchor loads each account into memory, lets the program change it, then saves it back at the end. If the same account is passed twice, it is saved twice, and the second save wipes out the first save's changes. Here a swap passes the quote pool twice, so one of the reserve updates disappears.
What is Business logic?
The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.