MaxHeap.sol: Already extracted tokenId may be extracted again
The MaxHeap contract's extractMax function does not clear the heap slot after removing an item, leaving a stale value that maxHeapify can later read as an out-of-bounds entry. This can cause an already extracted tokenId to be extracted again, returning incorrect values.
DanielArmstrong Follow with pep7siup, mojito_auditor and 5 others
Originally disclosed on Code4rena
Submitted by DanielArmstrong, also found by pep7siup, mojito_auditor, MrPotatoMagic, nmirchev8, 0xDING99YA, SpicyMeatball, and bart1e
MaxHeap.sol#extractMax function only decreases the size variable without initializing the heap state variable. On the other hand, MaxHeap.sol#maxHeapify function involves the heap variable for the out-of-bound index which will contain dirty non-zero value. As a result, uncleared dirty value of heap state variable will be used in the process and already extracted tokenId will be extracted again.
Proof of Concept
MaxHeap.sol#extractMax function is following.
File: MaxHeap.sol
156: function extractMax() external onlyAdmin returns (uint256, uint256) {
157: require(size > 0, "Heap is empty");
158:
159: uint256 popped = heap[0];
160: heap[0] = heap[--size];
161: maxHeapify(0);
162:
163: return (popped, valueMapping[popped]);
164: }
As can be seen, the above funcion decreases size state variable by one, but does not initialize the heap[size] value to zero. In the meantime,MaxHeap.sol#maxHeapify function is following.
File: MaxHeap.sol
094: function maxHeapify(uint256 pos) internal {
095: uint256 left = 2 * pos + 1;
096: uint256 right = 2 * pos + 2;
097:
098: uint256 posValue = valueMapping[heap[pos]];
099: uint256 leftValue = valueMapping[heap[left]];
100: uint256 rightValue = valueMapping[heap[right]];
101:
102: if (pos >= (size / 2) && pos <= size) return;
103:
104: if (posValue < leftValue || posValue < rightValue) {
105: if (leftValue > rightValue) {
106: swap(pos, left);
107: maxHeapify(left);
108: } else {
109: swap(pos, right);
110: maxHeapify(right);
111: }
112: }
113: }
For example, if size=2 and pos=0, right = 2 = size holds true. So the heap[right]=heap[size] indicates the value of out-of-bound index which may be not initialized in extractMax function ahead. But in L102 since pos = 0 < (size / 2) = 1 holds true, the function does not return and continue to proceed the below section of function. Thus, abnormal phenomena occurs due to the value that should not be used.
We can verify the above issue by adding and running the following test code to test/max-heap/Updates.t.sol.
function testExtractUpdateError() public {
// Insert 3 items with value 20 and remove them all
maxHeapTester.insert(1, 20);
maxHeapTester.insert(2, 20);
maxHeapTester.insert(3, 20);
maxHeapTester.extractMax();
maxHeapTester.extractMax();
maxHeapTester.extractMax(); // Because all of 3 items are removed, itemId=1,2,3 should never be extracted after.
// Insert 2 items with value 10 which is small than 20
maxHeapTester.insert(4, 10);
maxHeapTester.insert(5, 10);
// Update value to cause maxHeapify
maxHeapTester.updateValue(4, 5);
// Now the item should be itemId=5, value=10
// But in fact the max item is itemId=3, value=20 now.
(uint256 itemId, uint256 value) = maxHeapTester.extractMax(); // itemId=3 will be extracted again
require(itemId == 5, "Item ID should be 5 but 3 now");
require(value == 10, "value should be 10 but 20 now");
}
As a result of test code, the return value of the last extractMax call is not (itemId, value) = (5, 10) but (itemId, value) = (3, 20) which is error. According to READM.md#L313, the above result must not be forbidden.
Recommended Mitigation Steps
Modify the MaxHeap.sol#extractMax function as follows:
function extractMax() external onlyAdmin returns (uint256, uint256) {
require(size > 0, "Heap is empty");
uint256 popped = heap[0];
heap[0] = heap[--size];
++ heap[size] = 0;
maxHeapify(0);
return (popped, valueMapping[popped]);
}
Since the value of heap[size] is initialized to zero, no errors will occur even though the value of out-of-bound index is used in maxHeapify function.
rocketman-21 (Revolution) confirmed, but disagreed with severity and commented:
Think this should be medium, it requires that we make the values of the maxheap less than they were inserted at, which isn’t possible in CultureIndex (which is upvote only)
0xTheC0der (Judge) decreased severity to Medium and commented:
I judged this contest with a strict baseline for Medium severity findings. However, I was “forced” to accept a view-only ERC-721 violation as valid Medium due to historical precedence on C4. As the present issue is similarly deviating from spec without severe impacts on the functionality of the protocol at its current state, it seems fair and consistent to move forward with Medium severity and therefore appropriately value the effort behind uncovering this very valid bug.
Note: For full discussion see here
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 extractMax function decreases the size variable but does not set the vacated heap slot to zero, so maxHeapify can read a stale value at an index equal to the new size.
Impact
An already extracted tokenId could be extracted again, returning incorrect values; the protocol team noted this requires decreasing values, which is not possible in the current upvote-only CultureIndex, so the judge rated it Medium.
What the attacker needed
Admin privileges to call extractMax; ability to insert and update values
The fix
The extractMax function should set the vacated heap slot to zero after decreasing size, as shown in the recommended mitigation.
How it was found
- Insert three items with equal value.
- Extract all three items.
- Insert two items with a smaller value.
- Update one item's value to trigger maxHeapify.
- Extract the maximum and observe that an already removed item is returned.
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 heap is a data structure that keeps the largest item on top. When you remove the top item, the code moves the last item to the top but forgets to erase the old last slot, so a leftover value stays there. Later, the code can accidentally read that leftover value as if it were still part of the heap, causing a removed item to appear again.
What is Smart contracts?
Flaws in on-chain code that let an attacker drain funds, freeze them or break the protocol's accounting.