Reentrancy in function leave() leads to halting of bottom up checkpoints
The leave() function in a not-yet-bootstrapped subnet transfers native ETH to the caller before updating state, allowing a malicious contract to reenter and bootstrap the subnet. This causes a later bottom-up checkpoint to revert because the subnet actor no longer holds the funds needed to stake, halting checkpoints.
Originally disclosed on Code4rena
Submitted by sin1st3r__
Prerequisite Knowledge
How stake & unstake operations work in a not yet bootstrapped subnet:
-
In a pre-bootstrap subnet, when a validator joins the subnet using the function
SubnetActorManagerFacet::stake()and then decides to add more stake by calling the functionSubnetActorManagerFacet::stake(), the function will do the following: -
It’ll conduct some validations like check if
msg.senderhas already joined the subnet as a validator, lock the funds he deposited in the contract by calling the functionlock()function stake(uint256 amount) external payable whenNotPaused notKilled { .......... --> s.collateralSource.lock(amount); if (!s.bootstrapped) { LibStaking.depositWithConfirm(msg.sender, amount); LibSubnetActor.bootstrapSubnetIfNeeded(); } else { LibStaking.deposit(msg.sender, amount); } } -
It’ll check if the subnet is bootstrapped. In this case, it isn’t, so it will call the functions
depositWithConfirm(). The functiondepositWithConfirmwill do the following:- It’ll call the functions
depositRequest()andconfirmDeposit()which will simply increase thetotalCollateralassociated with the validator then increase thetotalConfirmedCollateralof the validator and then the validator set gets reshuffled whenincreaseReshuffle()is called byconfirmDeposit(). - Then bootstrap the subnet only if the requirements are met by calling the function
SubnetActorManagerFacet::bootstrapSubnetIfNeeded()(there needs to be a minimum amount of active validators and a staking threshold that needs to be met before a subnet can be bootstrapped)
- It’ll call the functions
-
When a subnet becomes eligible for bootstrapping and the
bootstrapSubnetIfNeeded()function is called, the funds in theSubnetActorManagerFacetwill be transferred to theGatewayManagerFacetcontract.
How stake & unstake operations work in a bootstrapped subnet:
-
When a subnet is already bootstrapped and a validator adds new stake by calling the function
SubnetActorManagerFacet::stake(), the function will lock the funds as usual but then it will call the functiondeposit()instead of callingdepositWithConfirm(). This is because the child bootstrapped subnet needs to be aware of that change in power before the parent confirms that power change. When the functiondeposit()is called, it will do the following:- It’ll create a “deposit request” which will be stored and will later be transferred to the child bootstrapped subnet via a Top-down checkpoint.
- It’ll increase the total
totalCollateralassociated with the validator but it will NOT increase thetotalConfirmedCollateralassociated with the validator yet.
/// @notice Deposit the collateral function deposit(address validator, uint256 amount) internal { SubnetActorStorage storage s = LibSubnetActorStorage.appStorage(); s.changeSet.depositRequest(validator, amount); s.validatorSet.recordDeposit(validator, amount); }/// @notice Perform upsert operation to the deposit changes function depositRequest(StakingChangeLog storage changes, address validator, uint256 amount) internal { bytes memory payload = abi.encode(amount); uint64 configurationNumber = recordChange({ changes: changes, validator: validator, op: StakingOperation.Deposit, payload: payload }); emit NewStakingChangeRequest({ op: StakingOperation.Deposit, validator: validator, payload: payload, configurationNumber: configurationNumber }); } -
When a top -> down checkpoint takes place, we’ll arrive at the child subnet which will need to confirm the deposit request made in the parent before the parent confirms the deposit. This function
LibValidatorTracking::confirmChange(), in the child subnet gateway actor will be executed and it will simply confirm the deposit of the validator and reshuffle the list of validators (increaseReshufflewill be called byconfirmDeposit):
/// @notice Confirm the changes in for a finality commitment
function confirmChange(ParentValidatorsTracker storage self, uint64 configurationNumber) internal {
.............
for (uint64 i = start; i <= configurationNumber; ) {
StakingChange storage change = self.changes.getChange(i);
address validator = change.validator;
if (change.op == StakingOperation.SetMetadata) {
.......
} else if (change.op == StakingOperation.SetFederatedPower) {
.......
} else {
uint256 amount = abi.decode(change.payload, (uint256));
if (change.op == StakingOperation.Withdraw) {
self.validators.confirmWithdraw(validator, amount);
} else {
---> self.validators.confirmDeposit(validator, amount);
}
}
............
}
-
A bottom -> top checkpoint will take place, and we will arrive at the parent subnet again. The following function will be called in the parent
LibStaking::confirmChange(). This function will then confirm the deposit in the parent after the child subnet has already confirmed it./// @notice Confirm the changes in bottom up checkpoint submission, only call this in bottom up checkpoint execution. function confirmChange(uint64 configurationNumber) internal { SubnetActorStorage storage s = LibSubnetActorStorage.appStorage(); StakingChangeLog storage changeSet = s.changeSet; ........................ uint64 start = changeSet.startConfigurationNumber; for (uint64 i = start; i <= configurationNumber; ) { StakingChange storage change = changeSet.getChange(i); address validator = change.validator; ................. } else { uint256 amount = abi.decode(change.payload, (uint256)); address gateway = s.ipcGatewayAddr; if (change.op == StakingOperation.Withdraw) { s.validatorSet.confirmWithdraw(validator, amount); s.releaseQueue.addNewRelease(validator, amount); IGateway(gateway).releaseStake(amount); } else if (change.op == StakingOperation.Deposit) { ------> s.validatorSet.confirmDeposit(validator, amount); ------> uint256 msgValue = s.collateralSource.makeAvailable(gateway, amount); ------> IGateway(gateway).addStake{value: msgValue}(amount); } else { revert("Unknown staking operation"); } } ........................ } }It will do the following:
- It’ll confirm the deposit by calling
confirmDeposit(). - It’ll then call
makeAvailable()to allow for the funds deposited by validator to be moved to the GatewayManagerFacet contract. You can think ofmakeAvailable()as of ERC20’sincreaseAllowance()function. - It’ll move the funds deposited by the validator to the gateway and call the function
addStake():
/// @notice addStake - add collateral for an existing subnet function addStake(uint256 amount) external payable { if (amount == 0) { revert NotEnoughFunds(); } // The fund flow for stake is from Validator -> SubnetActor -> Gateway. // Because msg.sender is actually the subnet actor, this method sends the fund from // the subnet actor caller the gateway. SubnetActorGetterFacet(msg.sender).collateralSource().lock(amount); (bool registered, Subnet storage subnet) = LibGateway.getSubnet(msg.sender); if (!registered) { revert NotRegisteredSubnet(); } subnet.stake += amount; } - It’ll confirm the deposit by calling
-
The funds now will stay in the gateway contract and then the
stakeuint256 state associated with the child subnet will be increased by the amount of funds the depositor has deposited.
Finding description and impact
The function SubnetActorManagerFacet::leave() suffers from a reentrancy vulnerability which if exploited in a not-yet bootstrapped subnet, will halt top -> down checkpoints to the child subnet. Attack will be explained in great detail below:
/// @notice method that allows a validator to leave the subnet.
function leave() external nonReentrant whenNotPaused notKilled {
......................
if (!s.bootstrapped) {
// check if the validator had some initial balance and return it if not bootstrapped
uint256 genesisBalance = s.genesisBalance[msg.sender];
if (genesisBalance != 0) {
delete s.genesisBalance[msg.sender];
s.genesisCircSupply -= genesisBalance;
LibSubnetActor.rmAddressFromBalanceKey(msg.sender);
-----> s.collateralSource.transferFunds(payable(msg.sender), genesisBalance);
}
// interaction must be performed after checks and changes
LibStaking.withdrawWithConfirm(msg.sender, amount);
s.collateralSource.transferFunds(payable(msg.sender), amount);
return;
}
LibStaking.withdraw(msg.sender, amount);
}
The vulnerability exists in the highlighted line and it can be exploited if the function collateralSource (or its correction supplySource) is native ETH.
Exploitation: Halting bottom -> top checkpoints for subnet by exploiting the reentrancy
- Suppose we have a subnet that is not yet bootstrapped, the active validator count threshold has been met but the minimum staking threshold has yet to be met (the moment it’s met, the subnet will become bootstrapped). Suppose that currently there are currently 40 ETH staked and the minimum threshold is 50 ETH, so 10 more ETH need to be staked for the subnet to become bootstrapped.
- The attacker, through a malicious smart contract will join the subnet by calling the function
join()and stake amount of ETH that is quite minimal (10 gwei for ex) or stakes the minimum amount enforced by the validator gater and then deposit a very small amount of ETH like 1 wei of supply source funds using the functionpreFund().preFund()will then increase thegenesisBalanceassociated with the malicious smart contract address.
/// @notice method to add some initial balance into a subnet that hasn't yet bootstrapped.
/// @dev This balance is added to user addresses in genesis, and becomes part of the genesis
/// circulating supply.
function preFund(uint256 amount) external payable {
if (amount == 0) {
revert NotEnoughFunds();
}
if (s.bootstrapped) {
revert SubnetAlreadyBootstrapped();
}
s.supplySource.lock(amount);
if (s.genesisBalance[msg.sender] == 0) {
s.genesisBalanceKeys.push(msg.sender);
}
s.genesisBalance[msg.sender] += amount;
s.genesisCircSupply += amount;
}
- The attacker, through another wallet he owns, will join the subnet and stake a little under what it takes to get the subnet to be bootstrapped by calling the
join()function. So if 10 ETH is left until requirement is met, the attacker will stake~9.99999ETH. - The attacker, through the malicious smart contract he used in step 2 will call the function
leave().
/// @notice method that allows a validator to leave the subnet.
function leave() external nonReentrant whenNotPaused notKilled {
......................
if (!s.bootstrapped) {
// check if the validator had some initial balance and return it if not bootstrapped
uint256 genesisBalance = s.genesisBalance[msg.sender];
if (genesisBalance != 0) {
delete s.genesisBalance[msg.sender];
s.genesisCircSupply -= genesisBalance;
LibSubnetActor.rmAddressFromBalanceKey(msg.sender);
-----> s.collateralSource.transferFunds(payable(msg.sender), genesisBalance);
}
// interaction must be performed after checks and changes
LibStaking.withdrawWithConfirm(msg.sender, amount);
s.collateralSource.transferFunds(payable(msg.sender), amount);
return;
}
LibStaking.withdraw(msg.sender, amount);
}
/// @notice Transfers the specified amount out of our treasury to the recipient address.
function transferFunds(
Asset memory asset,
address payable recipient,
uint256 value
) internal returns (bool success, bytes memory ret) {
if (asset.kind == AssetKind.Native) {
success = sendValue(payable(recipient), value);
return (success, EMPTY_BYTES);
} else if (asset.kind == AssetKind.ERC20) {
return ierc20Transfer(asset, recipient, value);
}
}
function sendValue(address payable recipient, uint256 value) internal returns (bool) {
if (address(this).balance < value) {
revert NotEnoughBalance();
}
(bool success, ) = recipient.call{value: value}("");
return success;
}
-
Since the caller of the
leave()function (malicious smart contract), has a non-zerogenesisBalance, theif genesisBalance != 0code branch will be executed and the highlightedtransferFunds()function will be executed which will attempt to transfer the funds to the caller. Since the funds (in this case,collateralSource) are of type native ETH, the malicious smart contract will hijack the execution flow. -
In the hijacked execution flow, the malicious smart contract will do two things:
-
It’ll stake the amount of ETH left required to meet the minimum threshold (which will be a small amount left, check step 2). Suppose it staked 0.000001 ETH and now the minimum threshold is met and now the subnet will be eligible for bootstrapping.
-
The function
bootstrapSubnetIfNeeded()will be called and then the functionregisterInGateway()will be called.- What the
registerInGateway()function will do is that it will transfer all of the genesis (supply source) funds and all of the staked funds to the GatewayManagerFacet. So the SubnetActorManagerFacet contract will now have zero funds.
- What the
function registerInGateway(uint256 collateral) internal { SubnetActorStorage storage s = LibSubnetActorStorage.appStorage(); uint256 genesisCircSupply = s.genesisCircSupply; uint256 msgValue = 0; msgValue += s.supplySource.makeAvailable(s.ipcGatewayAddr, genesisCircSupply); msgValue += s.collateralSource.makeAvailable(s.ipcGatewayAddr, collateral); IGateway(s.ipcGatewayAddr).register{value: msgValue}(genesisCircSupply, collateral); }- Since we are still in the hijacked execution flow of the
SubnetActorManagerFacet::leave()function and since the function did not yet transfer the staked funds to the caller (malicious smart contract), and since theSubnetActorManagerFacetcontract has zero funds now, the malicious smart contract will stakeamountof ETH whereamountrepresents the very minimal amount of ETH it staked previously in step 1, by calling the functionstake(). This step is required to make the functionleave()not revert when the hijacked execution flow exits and it attempts to transfer staked funds back to the malicious smart contract which is the caller of theleave()function. Look at the highlighted lines:
/// @notice method that allows a validator to leave the subnet. function leave() external nonReentrant whenNotPaused notKilled { // remove bootstrap nodes added by this validator ---> uint256 amount = LibStaking.totalValidatorCollateral(msg.sender); if (amount == 0) { revert NotValidator(msg.sender); } ................ if (!s.bootstrapped) { // check if the validator had some initial balance and return it if not bootstrapped uint256 genesisBalance = s.genesisBalance[msg.sender]; if (genesisBalance != 0) { delete s.genesisBalance[msg.sender]; s.genesisCircSupply -= genesisBalance; LibSubnetActor.rmAddressFromBalanceKey(msg.sender); ----> s.collateralSource.transferFunds(payable(msg.sender), genesisBalance); // <---- We're here still! } // interaction must be performed after checks and changes ----> LibStaking.withdrawWithConfirm(msg.sender, amount); ----> s.collateralSource.transferFunds(payable(msg.sender), amount); return; } LibStaking.withdraw(msg.sender, amount); } -
-
The hijacked execution flow exits and the previously staked funds will be transferred back to the attacker successfully. But now there are two main invariants broken:
- Invariant # 1 - Once a subnet is bootstrapped, the
SubnetActorManagerFacetcontract should NOT ever transfer funds back to the caller ofleave()andunstake(). Transferring those funds back to the caller of those functions is the responsibility of theGatewayManagerFacetcontract, refer to prerequisite knowledge section “Howstake&unstakeoperations work in a bootstrapped subnet”. - Invariant # 2 - Confirmations of withdrawals and deposits should never occur after a subnet has been bootstrapped unless the withdrawal/deposit requests are sent down to the child subnet and are confirmed by it firstly! Here,
withdrawWithConfirm()will be called (after hijacked exec flow exits) despite the subnet being bootstrapped at this point (bootstrapping occurred during reentrancy attack).
- Invariant # 1 - Once a subnet is bootstrapped, the
-
In step 4, the malicious smart contract, after subnet became bootstrapped, had deposited a minimal amount of ETH by calling the
stake()function. So a deposit request was created and it will be included in the next Top -> Bottom checkpoint which will be sent to the child subnet. -
In the child subnet, the checkpoint will get processed and the function
LibValidatorTracking::confirmChange()will end up getting called and the deposit will be confirmed in the child subnet. -
In the parent subnet, the function
submitCheckpoint()will be called to execute the periodic bottom -> up checkpoints. The functionsubmitCheckpoint()will then call the functionLibStaking::confirmChange()which purpose would be to confirm staking & unstaking operation requests in parent subnet after they’ve been confirmed in child subnet in step 9. -
Now in
LibStaking::confirmChange()the parent will confirm the deposit but then it will prepare the staked funds to be transferred from theSubnetActorManagerto be sent to theGatewayManagerFacetand thenGatewayManagerFacert::addStake()will be called which will move the funds to theGatewayManagerFacet, but this operation will revert because theSubnetActorManagerwon’t have any funds to transfer. This situation occurred because invariant 1 in step 7 was broken. The funds which were supposed to be moved in this operation were already given back to the attacker:
/// @notice Confirm the changes in bottom up checkpoint submission, only call this in bottom up checkpoint execution.
function confirmChange(uint64 configurationNumber) internal {
..........................
for (uint64 i = start; i <= configurationNumber; ) {
..........................
} else {
uint256 amount = abi.decode(change.payload, (uint256));
address gateway = s.ipcGatewayAddr;
if (change.op == StakingOperation.Withdraw) {
s.validatorSet.confirmWithdraw(validator, amount);
s.releaseQueue.addNewRelease(validator, amount);
IGateway(gateway).releaseStake(amount);
} else if (change.op == StakingOperation.Deposit) {
------> s.validatorSet.confirmDeposit(validator, amount);
------> uint256 msgValue = s.collateralSource.makeAvailable(gateway, amount);
------> IGateway(gateway).addStake{value: msgValue}(amount);
} else {
revert("Unknown staking operation");
}
}
..............
}
.................
/// @notice addStake - add collateral for an existing subnet
function addStake(uint256 amount) external payable {
if (amount == 0) {
revert NotEnoughFunds();
}
// The fund flow for stake is from Validator -> SubnetActor -> Gateway.
// Because msg.sender is actually the subnet actor, this method sends the fund from
// the subnet actor caller the gateway.
----> SubnetActorGetterFacet(msg.sender).collateralSource().lock(amount);
(bool registered, Subnet storage subnet) = LibGateway.getSubnet(msg.sender);
if (!registered) {
revert NotRegisteredSubnet();
}
subnet.stake += amount;
}
- The function
submitCheckpoint()will end up reverting as a result which should never happen unless it’s a malicious entity calling the function or as a result of a programming error. This is how bottom -> up checkpointing mechanism is halted.
There is a typo bug in the line s.collateralSource.transferFunds(payable(msg.sender), genesisBalance); in the function leave() which was reported separately. However, this bug still persists even if that bug was fixed because both supplySource and collateralSource can be native ETH making this exploitable.
This is a complex bug. I will gladly develop a working PoC for this if needed.
Recommended mitigation steps
Proposed mitigation is as follows:
if (!s.bootstrapped) {
// check if the validator had some initial balance and return it if not bootstrapped
uint256 genesisBalance = s.genesisBalance[msg.sender];
if (genesisBalance != 0) {
delete s.genesisBalance[msg.sender];
s.genesisCircSupply -= genesisBalance;
LibSubnetActor.rmAddressFromBalanceKey(msg.sender);
s.collateralSource.transferFunds(payable(msg.sender), genesisBalance);
}
}
uint256 amount = LibStaking.totalValidatorCollateral(msg.sender);
if (amount == 0) {
revert NotValidator(msg.sender);
}
if (!s.bootstrapped) {
LibStaking.withdrawWithConfirm(msg.sender, amount);
s.collateralSource.transferFunds(payable(msg.sender), amount);
} else {
LibStaking.withdraw(msg.sender, amount);
}
Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.
How it worked
Root cause
Likely the leave() function performs an external call to transfer native ETH before updating the validator's collateral state, allowing reentrancy.
Impact
Bottom-up checkpoints are halted because submitCheckpoint() reverts, disrupting the checkpoint mechanism.
What the attacker needed
Subnet not yet bootstrapped; attacker controls a contract; native ETH as collateral source
The fix
The fix should restructure leave() to update state and check bootstrapped status before transferring funds, and only transfer if still not bootstrapped.
How it was found
- Attacker joins the subnet with a malicious contract and preFunds a small amount to have a non-zero genesisBalance.
- Attacker stakes almost enough to meet the bootstrap threshold using another wallet.
- Attacker calls leave() from the malicious contract, triggering the ETH transfer and reentering.
- In the reentrancy, the attacker stakes the remaining amount to bootstrap the subnet, moving all funds to the gateway.
- The attacker stakes a minimal amount to avoid the leave() transfer reverting.
- Later, a bottom-up checkpoint calls confirmChange() and addStake(), which reverts because the subnet actor has no funds.
Explained by bugbounty.wiki with AI from the original and checked against quotes from it; it can still be wrong. Read the original before relying on a detail.
Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.
A reentrancy bug lets a contract call back into the same function before the first call finishes. Here, the leave() function sends ETH to the caller before updating its records, so the caller can reenter and change the subnet's state. This later causes a checkpoint to fail because the contract no longer has the funds it needs.
What is Smart contracts?
Flaws in on-chain code that let an attacker drain funds, freeze them or break the protocol's accounting.