Skip to content
Business logic Audit finding Advanced

Reserves can be stolen by settling artificially created bad debt from them

The protocol's collateral withdrawal check relies solely on the LUP (lowest utilized price), which can be artificially inflated by adding quote tokens to a high-priced bucket. An attacker controlling both lender and borrower accounts can withdraw most collateral, then kick the loan and settle the resulting bad debt from pool reserves, stealing those reserves.

hyh Follow

Originally disclosed on Sherlock

Source: https://github.com/sherlock-audit/2023-09-ajna-judging/issues/71

Found by

hyh

It is possible to inflate LUP and pull almost all the collateral from the loan, then settle this artificial bad debt off reserves, stealing all of them by repeating the attack.

Vulnerability Detail

LUP is determined just in time of the execution, but removeQuoteToken() will check for LUP > HTP = Loans.getMax(loans).thresholdPrice, so the attack need to circumvent this.

Attacker acts via 2 accounts under control, one for lending part, one for borrowing, having no previous positions in the given ERC20 pool. Let's say that pool state is as follows: 100 units of quote token utilized, and another 100 not utilized, for simplicity let's say all 100 are available, no auctions and no bad debt.

  1. Get 100 loan at TP = new HTP just below LUP (let's name this loan the manipulated_loan, ML), let's say LUP is such that 150 quote token units worth of collateral was provided (at market price)
  2. Add quote funds with amount = {total utilized deposits} = 200 to a bucket significantly above the market (let's name it ultra_high_bucket, UHB)
  3. Remove collateral from the ML up to allowed by elevated LUP = UHB price, say it's 10x market one. I.e. almost all, say remove 140, leaving 10 quote token units worth of collateral (at market price)
  4. Lender kick ML (removing funds from UHB will push LUP low and lender kick will be possible) to revive HTP reading
  5. Remove all from UHB except quote funds frozen by the auction, i.e. remove 100, leave 100

1-5 go atomically in one tx.

No outside actors will be able to immediately benefit from the resulting situation as: a. UHB remove quote token is blocked due to the frozen debt b. take is unprofitable while auction price is above market c. bucket take is unprofitable while auction price is above UHB price

At this point attacker accounting in net quote tokens worth is:

  1. +100, -150
  2. -200
  3. +140
  4. +100

Attacker has net 10 units of own capital still invested in the pool.

  1. Attacker wait for auction price reaching UHB price, calls takeBucket with depositTake == true.

The call can go with normal gas price as outside actors will not benefit from the such call and there will be no competition. 10 quote tokens worth of collateral will be placed to UHB and 98.482 units of quote token removed to cover the debt, 1.518 is the kicker's reward 7. Attacker calls settlePoolDebt() which settles the remaining 1.518 of debt from pool reserves as ML has this amount of debt and no collateral 8. Attacker removes all the funds from UHB with both initial and awarded LP shares, receiving 10 quote tokens worth of collateral and 1.518 quote token units of profit

6-8 go atomically in one tx.

At this point attacker accounting in quote tokens is:

  1. (+kicker reward of ML stamped NP vs auction clearing UHB price in LP form)
  2. +11.518

Attacker has net 0 units of own capital still invested in the pool, and receives 1.518 quote token units of profit.

Profit part is a function of the pool's state, for the number above, assuming auctionPrice == thresholdPrice = UHB price and poolRate_ = 0.05: 1.518 = bondFactor * 100 = (npTpRatio - 1) / 10 * 100 = (1.04 + math.sqrt(0.05) / 2 - 1) / 10 * 100, bpf = bondFactor = takePenaltyFactor.

Impact

It can be repeated to drain the whole reserves from the pool over time, i.e. reserves of any pool can be stolen this way.

Code Snippet

LUP is the only guardian for removing the collateral:

https://github.com/sherlock-audit/2023-09-ajna/blob/main/ajna-core/src/libraries/external/BorrowerActions.sol#L287-L307

Solidity
        if (vars.pull) {
            // only intended recipient can pull collateral
            if (borrowerAddress_ != msg.sender) revert BorrowerNotSender();

            // calculate LUP only if it wasn't calculated in repay action
            if (!vars.repay) result_.newLup = Deposits.getLup(deposits_, result_.poolDebt);

>>          uint256 encumberedCollateral = Maths.wdiv(vars.borrowerDebt, result_.newLup);
            if (
                borrower.t0Debt != 0 && encumberedCollateral == 0 || // case when small amount of debt at a high LUP results in encumbered collateral calculated as 0
                borrower.collateral < encumberedCollateral ||
                borrower.collateral - encumberedCollateral < collateralAmountToPull_
            ) revert InsufficientCollateral();

            // stamp borrower Np to Tp ratio when pull collateral action
            vars.stampNpTpRatio = true;

            borrower.collateral -= collateralAmountToPull_;

            result_.poolCollateral -= collateralAmountToPull_;
        }

The root cause is that bad debt is artificially created, with lender, borrower and kicker being controlled by the attacker, bad debt is then settled from the reserves:

https://github.com/sherlock-audit/2023-09-ajna/blob/main/ajna-core/src/libraries/external/SettlerActions.sol#L143-L146

Solidity
            // settle debt from reserves (assets - liabilities) if reserves positive, round reserves down however
            if (assets > liabilities) {
                borrower.t0Debt -= Maths.min(borrower.t0Debt, Maths.floorWdiv(assets - liabilities, poolState_.inflator));
            }

Kicking will revive the HTP as _kick() removing target borrower from loans:

https://github.com/sherlock-audit/2023-09-ajna/blob/main/ajna-core/src/libraries/external/KickerActions.sol#L340-L341

Solidity
        // remove kicked loan from heap
        Loans.remove(loans_, borrowerAddress_, loans_.indices[borrowerAddress_]);

https://github.com/sherlock-audit/2023-09-ajna/blob/main/ajna-core/src/base/Pool.sol#L225-L249

Solidity
    function removeQuoteToken(
        ...
    ) external override nonReentrant returns (uint256 removedAmount_, uint256 redeemedLP_) {
        ...

        uint256 newLup;
        (
            removedAmount_,
            redeemedLP_,
            newLup
        ) = LenderActions.removeQuoteToken(
            ...
            RemoveQuoteParams({
                maxAmount:      Maths.min(maxAmount_, _availableQuoteToken()),
                index:          index_,
>>              thresholdPrice: Loans.getMax(loans).thresholdPrice
            })
        );

https://github.com/sherlock-audit/2023-09-ajna/blob/main/ajna-core/src/libraries/external/LenderActions.sol#L434-L436

Solidity
        lup_ = Deposits.getLup(deposits_, poolState_.debt);

>>      uint256 htp = Maths.wmul(params_.thresholdPrice, poolState_.inflator);

Tool used

Manual Review

Recommendation

Consider introducing a buffer representing the expected kicker reward in addition to LUP, so this part of the loan will remain in the pool.

Discussion

kadenzipfel

Escalate Should be medium.

According to the judging docs:

The profit margin from the provided example is ~0.4% (1.518 / (150 quote tokens worth of collateral at ML + 200 quote tokens at UHB) * 100%). This is consistent with the medium issue criteria ("minimal profit").

The minimum cost of the attack is greater than the total utilized deposits of the pool (Note: it's noted that the UHB is funded with the total utilized deposits of the pool, but the actual amount used in the example is 200, 2x the total utilized deposits and actually equal to the total utilized and unutilized deposits of the pool). Also note that it's not possible to use a flashloan in this circumstance since the attack requires multiple transactions across two EOAs. This is also consistent with the medium issue criteria ("considerable cost").

sherlock-admin2

Escalate Should be medium.

According to the judging docs:

The profit margin from the provided example is ~0.4% (1.518 / (150 quote tokens worth of collateral at ML + 200 quote tokens at UHB) * 100%). This is consistent with the medium issue criteria ("minimal profit").

The minimum cost of the attack is greater than the total utilized deposits of the pool (Note: it's noted that the UHB is funded with the total utilized deposits of the pool, but the actual amount used in the example is 200, 2x the total utilized deposits and actually equal to the total utilized and unutilized deposits of the pool). Also note that it's not possible to use a flashloan in this circumstance since the attack requires multiple transactions across two EOAs. This is also consistent with the medium issue criteria ("considerable cost").

You've created a valid escalation!

To remove the escalation from consideration: Delete your comment.

You may delete or edit your escalation comment anytime before the 48-hour escalation window closes. After that, the escalation becomes final.

neeksec

Agree with Escalation to downgrade severity to Medium.

dmitriia

The use of flash loans is possible as borrower and lender can have the same address of the attacking smart contract, there is no restrictions in this regard. 0.4% is the immediate, atomic profit margin. The funds that are required to stay in the contract for auction are 10, not 200. If flash loans are free, for example obtained from Ajna itself, where it is zero, the total profit for the attacker in abstract quote token units is 1.518 - {2 days funding for 10} - total gas.

This can be quite significant, say if 1 unit here is USDC 10k, the profit is 15.18k - USDC_rate*2.0/365 * 100k - gas. If we assume that USDC borrow rate is 10% and total gas is 1 ETH = USD 2k, it becomes USDC 15.18 - 0.1*2.0/365*100 - 2 = 13.12k. There is basically no market risk involved here, so it's arbitrage profit significant enough to compensate attacker for the efforts. This is for one pool and the attacking contract can be immediately reused for all the others.

As reserves of any pool can be drained this way fully, the reserves from all pools on all chains can be stolen. Since reserves burning is core monetization mechanics for protocl token this basically means that Ajna token will be worthless once this vector becomes public. Also, lack of reserves over time will move the growing share of pools to be insolvent as reserves also serve for bad debt coverage. Insolvency will render the pools unusable. The actual severity here is critical, but given the lack of this grade it is marked as high.

kadenzipfel

0.4% is the immediate, atomic profit margin.

No. As you explained in your example, steps 1-5 are atomic and by the end of step 5 the attacker is at a loss of 10 units of collateral. Profit doesn't occur until the attacker completes steps 6-8, and only if auction price gets low enough for attacker to execute these steps.

There is basically no market risk involved here

This is false. The attacker is at a 10 unit loss (10% of the entire total utilized deposits) for, by your estimation, 2 days. They only ever profit if the auction price reaches the UHB. The Ajna team thus has 2 days to assess a highly suspicious auction and prevent further losses, in which they can simply take the quote tokens before the attacker, griefing the attacker into a significant loss and disincentivizing the attack entirely.

In summary, regardless of flashloans, as noted in escalation:

  • The cost of the attack is still high (10% of the entire utilized deposits)
  • The attacker profit is low (best case ~13% by your example: 100k risk, 13.12k profit) or possibly negative if intervention.
  • The loss of funds incurred by the pool is also quite low at a maximum of ~0.76% (1.518 quote tokens lost / total pool size of 200 quote tokens * 100%)

kadenzipfel

This issue should also be invalid until a valid proof of concept is provided considering this attack is highly complex and far from obvious. See: In case of non-obvious issues with complex vulnerabilities/attack paths, Watson must submit a valid POC for the issue to be considered valid and rewarded.

dmitriia

Market risk is risk that stems from movements of the market, it is absent in this scenario. Ajna team has little means to prevent the attack as the protocol is permissionless, while take() requires paying for collateral at prices substantially above the market, i.e. it is a material external investment that will be needed for all the pools. Also, if anyone takes before the attacker it will benefit them substantially (they are also a borrower, which will have their collateral priced even higher than they manipulated it themselves), resulting in even higher profitability, which will not disincentivize the attack.

  • 10 units is not a cost of attack, it is a short-term investment, which funding costs are taken into account,

  • 13% for 2 days is (1.13) ^ (365 / 2) = 4 862 010 984 % APY which is significantly above market rates and is attractive for the wide range of attackers,

  • This is loss per step. The reserves will be drained in full as nothing prevents attack to be immediately repeated. Also, it can be carried out simultaneously for many pools.

Again, this is critical severity vulnerability, having no low probability prerequisites and inflicting direct loss for the Ajna holders and pool's depositors (when reserves are lacking bad debt is written off from user's deposits starting with HPB).

dmitriia

This issue should also be invalid until a valid proof of concept is provided considering this attack is highly complex and far from obvious

Protocol team has already run PoC for this, @ith-harvey, please confirm.

Czar102

From my understanding, this bug makes it possible for the attacker to immediately create bad debt. Even if the earnings/losses are a small fraction of the whole TVL of the pool, it is extremely severe for a lending protocol. Planning to keep it a high severity issue unless I'm misinterpreting or missing something.

Czar102

Result: High Unique

sherlock-admin2

Escalations have been resolved successfully!

Escalation status:

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 collateral withdrawal check uses only the LUP, which can be manipulated by adding quote tokens to a high-priced bucket, and the resulting bad debt is settled from reserves without a buffer for the kicker reward.

Impact

The attacker could steal pool reserves, and the attack can be repeated to drain all reserves from any pool.

What the attacker needed

Control of two accounts (lender and borrower); sufficient capital to fund high bucket; wait for auction price to drop

The fix

The protocol should introduce a buffer representing the expected kicker reward in addition to LUP, so that part of the loan remains in the pool.

How it was found

  1. Create a loan with threshold price just below the current LUP.
  2. Add quote tokens to a bucket significantly above market price to inflate LUP.
  3. Remove most collateral from the loan, allowed by the inflated LUP.
  4. Kick the loan to revive the threshold price reading.
  5. Remove all but the frozen quote tokens from the high bucket.
  6. Wait for auction price to reach the high bucket price, then call takeBucket with depositTake.

Explained by bugbounty.wiki with AI from the original and checked against quotes from it; it can still be wrong. Read the original before relying on a detail.

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

In a lending pool, you can only take back your collateral if the pool's lowest utilized price (LUP) is high enough. The attacker tricks the system by temporarily pushing that price up, takes back almost all collateral, then lets the loan default and uses the pool's savings (reserves) to cover the bad debt. This steals the reserves.

What is Business logic?

The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.

More by hyh

View all

137 more disclosed reports, best first.

More from Ajna #2

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Business logic flaws

The lesson behind this report.

The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.