Skip to content
Race condition Audit finding Advanced

An attacker can gain an inflated amount of Sherlock shares by staking when TrueFiPool2 pool has its value temporary reduced during loan closure

A permissionless loan reclaim function in TrueFi temporarily reduces the pool's reported value while it performs a user-supplied 1inch swap call. An attacker can use that swap call to reenter Sherlock's staking and receive an inflated number of shares, later stealing value from other stakers.

hyh Follow

Originally disclosed on Sherlock

Source: https://github.com/sherlock-audit/2022-09-sherlock-judging/tree/main/018-H

Found by

hyh

Summary

Sherlock's initial staking can be performed while TrueFiStrategy balance is reduced with TrueFi's FixedTermLoanAgency loan token reclaim call. This is possible as the 1inch fee swapping call with user-supplied parameters is performed when the system is in the reduced pool value state, while FixedTermLoanAgency's reclaim() has no access controls, and the functions involved allow reentrancy. The net result is an artificially increased number of Sherlock shares being issued to the attacker.

Vulnerability Detail

TrueFiStrategy balance is based on TrueFiPool2 poolValue(), which drops on FixedTermLoanAgency loan reclaiming as the loan token is being removed from the active tokens array. Right after that and before reclaimed tokens end up on the TrueFiPool2 balance, the 1inch call is performed aimed to swap the corresponding fees.

FixedTermLoanAgency's reclaim() is permissionless, 1inch call uses user supplied parameters, so an attacker can supply a pre-cooked contract instead of DEX pool, which does the swap, so all the corresponding checks pass, i.e. proper amount of tokens needed are placed on the target balance, but also performs initial Sherlock staking, which issues inflated number of the shares for the attacker as TrueFiPool2 poolValue() is reduced during this call by the value of the loan being closed. Right after that the reclaimed token less fees are transferred to the TrueFiPool2 balance, so TrueFiStrategy _balanceOf() display the full value, and the attacker's shares are priced with a premium compared to her investment. This premium is proportional to the value of the closed loan, and is effectively stolen from all other stakers.

Impact

As a result of increased issuance of the shares, the attacker will steal from the all other stakers proportionally to the size of a loan she be able to run reclaim for.

Code Snippet

The call sequence is: FixedTermLoanAgency.reclaim() -> _redeemAndRepay() -> _swapFee() -> OneInchExchange.exchange() -> AggregationRouterV4.swap().

FixedTermLoanAgency's reclaim() removes the loan token and calls _redeemAndRepay():

https://github.com/trusttoken/contracts-pre22/blob/986fefb91fb0619217d17ecf0b4c5b7b921130ed/contracts/truefi2/FixedTermLoanAgency.sol#L384-L407

Solidity
    function reclaim(IFixedTermLoan loanToken, bytes calldata data) external {
        IFixedTermLoan.Status status = loanToken.status();
        require(
            status == IFixedTermLoan.Status.Settled || status == IFixedTermLoan.Status.Defaulted,
            "FixedTermLoanAgency: LoanToken is not closed yet"
        );
        if (status == IFixedTermLoan.Status.Defaulted) {
            require(msg.sender == owner(), "FixedTermLoanAgency: Only owner can reclaim from defaulted loan");
        }

        // find the token, repay loan and remove loan from loan array
        ITrueFiPool2 pool = loanToken.pool();
        IFixedTermLoan[] storage _loans = poolLoans[pool];
        uint256 loansLength = _loans.length;
        for (uint256 index = 0; index < loansLength; index++) {
            if (_loans[index] == loanToken) {
                _loans[index] = _loans[loansLength - 1];
                _loans.pop();

                uint256 fundsReclaimed = _redeemAndRepay(loanToken, pool, data);
                emit Reclaimed(address(pool), address(loanToken), fundsReclaimed);
                return;
            }
        }

At that moment FixedTermLoanAgency's value() drops by the currentValue() of the removed loan token, let's denote it loan_value = loanToken.currentValue(address(ftlAgency)):

https://github.com/trusttoken/contracts-pre22/blob/986fefb91fb0619217d17ecf0b4c5b7b921130ed/contracts/truefi2/FixedTermLoanAgency.sol#L371-L378

Solidity
    function value(ITrueFiPool2 pool) external view override returns (uint256) {
        IFixedTermLoan[] memory _loans = poolLoans[pool];
        uint256 totalValue;
        for (uint256 index = 0; index < _loans.length; index++) {
            totalValue = totalValue.add(_loans[index].currentValue(address(this)));
        }
        return totalValue;
    }

Which means TrueFiPool2's loansValue() and poolValue() drop by the same loan_value:

https://github.com/trusttoken/contracts-pre22/blob/986fefb91fb0619217d17ecf0b4c5b7b921130ed/contracts/truefi2/TrueFiPool2.sol#L419-L428

Solidity
    function loansValue() public view returns (uint256) {
        if (inSync) {
            return loansValueCache;
        }
        uint256 lenderLoansValue = 0;
        if (address(lender) != address(0)) {
            lenderLoansValue = lender.value(this);
        }
        return lenderLoansValue.add(ftlAgency.value(this));
    }

https://github.com/trusttoken/contracts-pre22/blob/986fefb91fb0619217d17ecf0b4c5b7b921130ed/contracts/truefi2/TrueFiPool2.sol#L382-L390

Solidity
    /**
     * @dev Calculate pool value in underlying token
     * "virtual price" of entire pool - LoanTokens, UnderlyingTokens, strategy value
     * @return pool value denominated in underlying token
     */
    function poolValue() public view override returns (uint256) {
        // this assumes defaulted loans are worth their full value
        return liquidValue().add(loansValue()).add(deficitValue()).add(creditValue()).add(debtValue);
    }

_redeemAndRepay() first calls _swapFee(), and only then repays the fundsReclaimed.sub(feeAmount) to the pool, reimbursing the token removal skew:

https://github.com/trusttoken/contracts-pre22/blob/986fefb91fb0619217d17ecf0b4c5b7b921130ed/contracts/truefi2/FixedTermLoanAgency.sol#L455-L475

Solidity
    function _redeemAndRepay(
        IFixedTermLoan loanToken,
        ITrueFiPool2 pool,
        bytes calldata data
    ) internal returns (uint256) {
        // call redeem function on LoanToken
        uint256 balanceBefore = pool.token().balanceOf(address(this));
        loanToken.redeem();
        uint256 balanceAfter = pool.token().balanceOf(address(this));

        // gets reclaimed amount and pays back to pool
        uint256 fundsReclaimed = balanceAfter.sub(balanceBefore);

        uint256 feeAmount;
        if (address(feeToken) != address(0)) {
            // swap fee for feeToken
            feeAmount = _swapFee(pool, loanToken, data);
        }

        pool.token().safeApprove(address(pool), fundsReclaimed.sub(feeAmount));
        pool.repay(fundsReclaimed.sub(feeAmount));

This way when _swapFee() is called the TrueFiPool2's poolValue() is still reduced by loan_value.

This allows Megan the attacker to enter Sherlock's pool at a depressed valuation.

Notice, that _swapFee() and all the previous function calls just redirect user-supplied data, that is finally passed to the 1inch's exchange():

https://github.com/trusttoken/contracts-pre22/blob/986fefb91fb0619217d17ecf0b4c5b7b921130ed/contracts/truefi2/FixedTermLoanAgency.sol#L484-L511

Solidity
    /// @dev Swap `token` for `feeToken` on 1inch
    function _swapFee(
        ITrueFiPool2 pool,
        IFixedTermLoan loanToken,
        bytes calldata data
    ) internal returns (uint256) {
        uint256 feeAmount = loanToken.interest().mul(fee).div(BASIS_RATIO);
        IERC20WithDecimals token = IERC20WithDecimals(address(pool.token()));
        if (token == feeToken) {
            return feeAmount;
        }
        if (feeAmount == 0) {
            return 0;
        }
        (I1Inch3.SwapDescription memory swap, uint256 balanceDiff) = _1inch.exchange(data);
        uint256 expectedDiff = pool.oracle().tokenToUsd(feeAmount).mul(uint256(10)**feeToken.decimals()).div(1 ether);

        require(swap.srcToken == address(token), "FixedTermLoanAgency: Source token is not same as pool's token");
        require(swap.dstToken == address(feeToken), "FixedTermLoanAgency: Destination token is not fee token");
        require(swap.dstReceiver == address(this), "FixedTermLoanAgency: Receiver is not agency");
        require(swap.amount == feeAmount, "FixedTermLoanAgency: Incorrect fee swap amount");
        require(swap.flags & ONE_INCH_PARTIAL_FILL_FLAG == 0, "FixedTermLoanAgency: Partial fill is not allowed");
        require(
            balanceDiff >= expectedDiff.mul(BASIS_RATIO.sub(swapFeeSlippage)).div(BASIS_RATIO),
            "FixedTermLoanAgency: Fee returned from swap is too small"
        );

        return feeAmount;

OneInchExchange's exchange() uses user supplied data, filling the basic swap description from it.

_swapFee() then verify tokens, amounts and receiving address from the filled swap structure.

However, data also contains the route, whom to call with what parameters to perform the swap, which is passed to _1inchExchange:

https://github.com/trusttoken/contracts-pre22/blob/986fefb91fb0619217d17ecf0b4c5b7b921130ed/contracts/truefi2/libraries/OneInchExchange.sol#L34-L70

Solidity
    function exchange(I1Inch3 _1inchExchange, bytes calldata data)
        internal
        returns (I1Inch3.SwapDescription memory description, uint256 returnedAmount)
    {
        if (data[0] == 0x7c) {
            // call `swap()`
            (, description, ) = abi.decode(data[4:], (address, I1Inch3.SwapDescription, bytes));
        } else {
            // call `unoswap()`
            (address srcToken, uint256 amount, uint256 minReturn, bytes32[] memory pathData) = abi.decode(
                data[4:],
                (address, uint256, uint256, bytes32[])
            );
            description.srcToken = srcToken;
            description.amount = amount;
            description.minReturnAmount = minReturn;
            description.flags = 0;
            uint256 lastPath = uint256(pathData[pathData.length - 1]);
            IUniRouter uniRouter = IUniRouter(address(lastPath & ADDRESS_MASK));
            bool isReverse = lastPath & REVERSE_MASK > 0;
            description.dstToken = isReverse ? uniRouter.token0() : uniRouter.token1();
            description.dstReceiver = address(this);
        }

        IERC20(description.srcToken).safeApprove(address(_1inchExchange), description.amount);
        uint256 balanceBefore = IERC20(description.dstToken).balanceOf(description.dstReceiver);
        // solhint-disable-next-line avoid-low-level-calls
        (bool success, ) = address(_1inchExchange).call(data);
        if (!success) {
            // Revert with original error message
            assembly {
                let ptr := mload(0x40)
                let size := returndatasize()
                returndatacopy(ptr, 0, size)
                revert(ptr, size)
            }
        }

For 1inch the data above contains not only swap description, but calls array (also named data in the docs), which is used by 1inch as is to perform the swapping, i.e. 1inch calls the supplied addresses with the supplied parameters, only checking the destination address has received the required number of output tokens:

https://docs.1inch.io/docs/aggregation-protocol/smart-contract/AggregationRouterV4#swap

Solidity
function swap(
  contract IAggregationExecutor caller,
  struct AggregationRouterV4.SwapDescription desc,
  bytes data
) external returns (uint256 returnAmount, uint256 gasLeft)

https://github.com/1inch/1inch-v2-contracts/blob/master/contracts/OneInchExchange.sol#L92-L127

Solidity
    function swap(
        IOneInchCaller caller,
        SwapDescription calldata desc,
        IOneInchCaller.CallDescription[] calldata calls
    )
        external
        payable
        whenNotPaused
        returns (uint256 returnAmount)
    {
        require(desc.minReturnAmount > 0, "Min return should not be 0");
        require(calls.length > 0, "Call data should exist");

        uint256 flags = desc.flags;
        IERC20 srcToken = desc.srcToken;
        IERC20 dstToken = desc.dstToken;

        if (flags & _REQUIRES_EXTRA_ETH != 0) {
            require(msg.value > (srcToken.isETH() ? desc.amount : 0), "Invalid msg.value");
        } else {
            require(msg.value == (srcToken.isETH() ? desc.amount : 0), "Invalid msg.value");
        }

        if (flags & _SHOULD_CLAIM != 0) {
            require(!srcToken.isETH(), "Claim token is ETH");
            _claim(srcToken, desc.srcReceiver, desc.amount, desc.permit);
        }

        address dstReceiver = (desc.dstReceiver == address(0)) ? msg.sender : desc.dstReceiver;
        uint256 initialSrcBalance = (flags & _PARTIAL_FILL != 0) ? srcToken.uniBalanceOf(msg.sender) : 0;
        uint256 initialDstBalance = dstToken.uniBalanceOf(dstReceiver);

        caller.makeCalls{value: msg.value}(calls);

        uint256 spentAmount = desc.amount;
        returnAmount = dstToken.uniBalanceOf(dstReceiver).sub(initialDstBalance);

This way Megan can supply pre-cooked contract that will do the swap (so all the conditions above be satisfied) and call Sherlock to enter the deposit in the same time.

I.e. only passing the control is needed here so an additional action, Sherlock deposit, can be performed while TrueFiPool2 poolValue() and TrueFiStrategy's _balanceOf() are depressed.

As Sherlock's shares are constant, this will mean that USDC amount supplied by Megan to Sherlock's initialStake() will be credited with an inflated number fo shares:

https://github.com/sherlock-audit/2022-09-sherlock/blob/main/sherlock-v2-core/contracts/Sherlock.sol#L523-L553

I.e. inflated stakeShares_ = (_amount * totalStakeShares_) / (totalTokenBalanceStakers() - _amount) to be issued as part of totalTokenBalanceStakers() is strategy's balanceOf():

https://github.com/sherlock-audit/2022-09-sherlock/blob/main/sherlock-v2-core/contracts/Sherlock.sol#L159-L164

Which uses current TrueFiPool2 poolValue():

https://github.com/sherlock-audit/2022-09-sherlock/blob/main/sherlock-v2-core/contracts/strategy/TrueFiStrategy.sol#L131-L147

Tool used

Manual Review

Recommendation

Consider adding reentrancy guarding modifiers to TrueFi's reclaim() and liquidValue().

The original report as published on Sherlock, by hyh. 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

Likely the loan reclaim flow performs an external call with user-supplied data while the pool's value is temporarily reduced, and neither the reclaim function nor the value calculation is protected against reentrancy.

Impact

The attacker could steal from all other stakers proportionally to the size of the loan they are able to reclaim.

What the attacker needed

A settled or defaulted loan token; ability to submit crafted swap data; an attacker-controlled contract

The fix

Reentrancy guards should be added to TrueFi's reclaim and liquidValue functions.

How it was found

  1. Call the permissionless reclaim function on a settled or defaulted loan token.
  2. Supply crafted swap data so the 1inch call invokes an attacker-controlled contract.
  3. From that contract, call Sherlock's initial staking while the pool value is still reduced.
  4. Let the swap complete so the reclaimed tokens are returned to the pool, restoring its value.

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 pool's value is used to decide how many shares a deposit buys. During a loan closure the pool briefly reports a lower value, and a user-controlled call happens at that moment. The attacker uses that call to deposit, getting more shares than they should, which dilutes everyone else.

What is Race condition?

Parallel requests reach a state the code assumed could not happen: a coupon used twice, a limit overrun, a check skipped.

More by hyh

View all

137 more disclosed reports, best first.

More from Sherlock

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Race conditions

The lesson behind this report.

Parallel requests reach a state the code assumed could not happen: a coupon used twice, a limit overrun, a check skipped.