Skip to content
Business logic Audit finding Intermediate

When calling LeverageMacroBase.doOperation to open a CDP, the POST CALL CHECK may use the wrong cdpId

The contract assumes the newly opened CDP is the last in the sorted list, but because the list is ordered by NICR, the new CDP may not be last. This can cause the post-call check to validate the wrong CDP, potentially passing incorrect checks or reverting.

nobody2018 Follow with Stormy, 0xRobocop and 1 other

Originally disclosed on Code4rena

Submitted by nobody2018, also found by Stormy, 0xRobocop, and BARW

After LeverageMacroBase.doOperation is used to open a new CDP, there will be a POST CALL CHECK, which is used to check the new CDP. However, the current implementation incorrectly assumes that the index of the new CDP is the last one. In this case, there may be two impacts:

  1. The check that should be passed cannot be passed, causing tx revert and waste of gas.
  2. The check that should not have been passed was passed, which may result in funds losses from this contract or caller.

Proof of Concept

doOperation is used to open a new CDP, and there are roughly three steps: setup for POST CALL CHECK, openCdp, POST CALL CHECK for the created CDP.

File: packages\contracts\contracts\LeverageMacroBase.sol
118:     function doOperation(
119:         FlashLoanType flType,
120:         uint256 borrowAmount,
121:         LeverageMacroOperation calldata operation,
122:         PostOperationCheck postCheckType,
123:         PostCheckParams calldata checkParams
124:     ) external {
......
139:         uint256 initialCdpIndex;
140:         if (postCheckType == PostOperationCheck.openCdp) {
141:             // How to get owner
142:             // sortedCdps.existCdpOwners(_cdpId);
143:->           initialCdpIndex = sortedCdps.cdpCountOf(address(this));
144:         }

......//do the operation

169:         if (postCheckType == PostOperationCheck.openCdp) {
170:             // How to get owner
171:             // sortedCdps.existCdpOwners(_cdpId);
172:             // initialCdpIndex is initialCdpIndex + 1
173:->           bytes32 cdpId = sortedCdps.cdpOfOwnerByIndex(address(this), initialCdpIndex);.
174:
175:             // Check for param details
176:             ICdpManagerData.Cdp memory cdpInfo = cdpManager.Cdps(cdpId);
177:->           _doCheckValueType(checkParams.expectedDebt, cdpInfo.debt);
178:->           _doCheckValueType(checkParams.expectedCollateral, cdpInfo.coll);
179:             require(
180:                 cdpInfo.status == checkParams.expectedStatus,
181:                 "!LeverageMacroReference: openCDP status check"
182:             );
183:         }
......
211:     }

L143, initialCdpIndex = sortedCdps.cdpCountOf(address(this)), which is used to count the number of CDPs already owned by this.

L145-168, Creats a CDP, the code here is not helpful in describing the issue and is therefore omitted.

L173, sortedCdps.cdpOfOwnerByIndex(address(this), initialCdpIndex) is used to get the id of the initialCdpIndex-th CDP owned by this. That’s the problem. Because initialCdpIndex is the number of CDPs owned before the new CDP was created (from L143), that is to say, the index of the created CDP is considered to be the last one.

Let’s look at the code of cdpOfOwnerByIndex:

File: packages\contracts\contracts\SortedCdps.sol
140:     function cdpOfOwnerByIndex(
141:         address owner,
142:         uint256 index
143:     ) external view override returns (bytes32) {
144:->       (bytes32 _cdpId, ) = _cdpOfOwnerByIndex(owner, index, dummyId, 0);
145:         return _cdpId;
146:     }
......
173:     function _cdpOfOwnerByIndex(
174:         address owner,
175:         uint256 index,
176:         bytes32 startNodeId,
177:         uint maxNodes
178:     ) internal view returns (bytes32, bool) {
179:         // walk the list, until we get to the indexed CDP
180:         // start at the given node or from the tail of list
181:->       bytes32 _currentCdpId = (startNodeId == dummyId ? data.tail : startNodeId);
182:->       uint _currentIndex = 0;
183:         uint i;
184:
185:         while (_currentCdpId != dummyId) {
186:             // if the current CDP is owned by specified owner
187:             if (getOwnerAddress(_currentCdpId) == owner) {
188:                 // if the current index of the owner CDP matches specified index
189:->               if (_currentIndex == index) {
190:->                   return (_currentCdpId, true);
191:                 } else {
192:                     // if not, increment the owner index as we've seen a CDP owned by them
193:->                   _currentIndex = _currentIndex + 1;
194:                 }
195:             }
196:             ++i;
197:
198:             // move to the next CDP in the list
199:             _currentCdpId = data.nodes[_currentCdpId].prevId;
200:
201:             // cut the run if we exceed expected iterations through the loop
202:             if (maxNodes > 0 && i >= maxNodes) {
203:                 break;
204:             }
205:         }
206:         // if we reach maximum iteration or end of list
207:         // without seeing the specified index for the owner
208:         // then maybe a new pagination is needed
209:         return (_currentCdpId, false);
210:     }

L144, _cdpOfOwnerByIndex(owner, index, dummyId, 0) is called.

L181, _currentCdpId = data.tail due to startNodeId = dummyId.

L189-194, If _currentIndex == index, the target cdpId is found and the loop exits. Otherwise, _currentIndex is increased by 1.

To better describe the problem, consider the following scenario:

this already has 1 CDP: A, and the entire linked list currently has 10 CDPs. Its topology is as follows:

head                      tail
cdp1->A->cdp2->...->cdp8->cdp9

New CDP is created via doOperation:

  1. initialCdpIndex = 1, which is from sortedCdps.cdpCountOf(address(this)).

  2. open a new Cdp: B.

  3. The current linked list has 11 CDPs, and its topology is as follows:

    head                         tail
    cdp1->A->cdp2->cdp3->B->...->cdp9
    
  4. cdpId = sortedCdps.cdpOfOwnerByIndex(address(this), 1). cdpId was expected to be B’s id, but A’s id was returned.

The root cause of this case is that the linked list is in descending order of NICR, and the NICR of the newly created CDP may be lower than the NICR of the already created CDP. In this case, the wrong cdpId will be returned.

Recommended Mitigation Steps

In _openCdpCallback, borrowerOperations.openCdp returns the created cdpId, and we should specify a slot to store this value. Afterwards, read this slot directly in POST CALL CHECK and reset it to byte32(0). The slot can be obtained by using a method similar to keccak256("Badger.LeverageMacroBase.OpenCdpId").

Alex the Entreprenerd (Badger) confirmed and commented:

Would have liked a coded POC of 2 cdps and the last one not being last.

Team says that to find the specific CdpID we would need to use something like this:

cdpID = sorted.Cdps.toCdpID(msg.sender, block.number, sortedCdps.nextCdpNonce());

The finding seems valid, but I believe it would result in reverts on usage (no loss of funds). And I believe it was missed because the check always works for the first Cdp, it will cause issue for the 2nd cdp onwards.


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

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 code uses the owner's CDP count before opening as the index of the new CDP, but the sorted list order by NICR means the new CDP may not be at that index.

Impact

The check may revert, wasting gas, or may pass incorrectly, potentially leading to fund losses from the contract or caller; the team believes it would result in reverts on usage (no loss of funds).

What the attacker needed

Contract already owns at least one CDP; new CDP's NICR is lower than existing CDP's

The fix

The fix should store the newly created cdpId in a slot during _openCdpCallback and read it in the post-call check, then reset it.

How it was found

  1. The contract already owns one CDP (A) and the sorted list has 10 CDPs.
  2. doOperation is called to open a new CDP (B).
  3. initialCdpIndex is set to 1 (the number of CDPs owned before).
  4. The new CDP B is created and inserted into the sorted list, but not necessarily at the end.
  5. cdpOfOwnerByIndex is called with index 1, which returns A's id instead of B's id.

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 smart contract opens a new collateralized debt position (CDP) and then checks it. The check assumes the new CDP is always the last one in a list sorted by a value called NICR. If the new CDP is not last, the check looks at the wrong CDP, which can cause the transaction to fail or pass when it should not.

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 nobody2018

View all

7 more disclosed reports, best first.

More from eBTC Zap Router

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.