Skip to content
Business logic Audit finding Intermediate

Incorrect handling of last nominee removal in removeNominee function

The removeNominee function incorrectly reassigns the ID of the last nominee when that nominee is the one being removed, leaving a stale entry in the mapNomineeIds mapping. This can cause the contract to treat a removed nominee as still existing, leading to data corruption and unexpected behaviour in nominee management.

Limbooo Follow with LinKenji, c0pp3rscr3w3r and 2 others

Originally disclosed on Code4rena

Submitted by Limbooo, also found by LinKenji, c0pp3rscr3w3r, AvantGard, and Sparrow

A vulnerability was discovered in the removeNominee function of the VoteWeighting.sol contract. The issue arises when removing the last nominee from the list, resulting in an incorrect update of the mapNomineeIds mapping. This can lead to inconsistencies in nominee management, potentially causing data corruption and unexpected behavior in the contract.

Impact

The vulnerability impacts the integrity of the mapNomineeIds mapping. When the last nominee in the setNominees array is removed, its ID is incorrectly reassigned, leaving a stale entry in mapNomineeIds. This can lead to:

  • Inability to clear the ID of the removed nominee.
  • Potential data corruption if new nominees are added and removed subsequently.
  • Unexpected behavior when querying or managing nominees.

Proof of Concept

In the removeNominee function, the following code is responsible for updating the mapNomineeIds mapping and handling the removal of the nominee:

contracts/VoteWeighting.sol:
  618:         // Remove nominee from the map
  619:         mapNomineeIds[nomineeHash] = 0;
  620:
  621:         // Shuffle the current last nominee id in the set to be placed to the removed one
  622:         nominee = setNominees[setNominees.length - 1];
  623:         bytes32 replacedNomineeHash = keccak256(abi.encode(nominee));
  624:         mapNomineeIds[replacedNomineeHash] = id;
  625:         setNominees[id] = nominee;
  626:         // Pop the last element from the set
  627:         setNominees.pop();

The above code aims to remove a nominee by zeroing out its ID in the mapNomineeIds mapping and then reassigning the ID of the last nominee in the setNominees array to fill the gap left by the removed nominee. However, this logic fails to handle the case where the nominee being removed is the last one in the setNominees array. In such cases:

  1. Line 619 correctly sets the nominee’s ID to 0 in mapNomineeIds.
  2. Lines 621-623 fetch the last nominee in the setNominees array.
  3. Lines 624-625 incorrectly reassign the ID of the last nominee, which is the nominee being removed, back to the mapNomineeIds mapping.

This results in a stale ID entry in mapNomineeIds, leaving the system in an inconsistent state. The following code snippet checks for nominee existence, which demonstrates the impact of the stale ID:

contracts/VoteWeighting.sol:
  805:             // Check for nominee existence
  806:             if (mapNomineeIds[nomineeHash] == 0) {
  807:                 revert NomineeDoesNotExist(accounts[i], chainIds[i]);
  808:             }

If the stale ID remains in mapNomineeIds, this check will fail to correctly identify that the nominee no longer exists, potentially leading to unexpected behavior or errors in other contract functions.

Test Case (Hardhat)

The following PoC demonstrates the issue using Hardhat. Add it as part of governance/test test suit (governance/test/VoteWeightingPoC.js).

/*global describe, context, beforeEach, it*/

const { expect } = require("chai");
const { ethers } = require("hardhat");
const helpers = require("@nomicfoundation/hardhat-network-helpers");

describe("Vote Weighting PoC", function () {
    let olas;
    let ve;
    let vw;
    let signers;
    let deployer;
    const initialMint = "1000000000000000000000000"; // 1_000_000
    const chainId = 1;

    function convertAddressToBytes32(account) {
        return ("0x" + "0".repeat(24) + account.slice(2)).toLowerCase();
    }

    beforeEach(async function () {
        const OLAS = await ethers.getContractFactory("OLAS");
        olas = await OLAS.deploy();
        await olas.deployed();

        signers = await ethers.getSigners();
        deployer = signers[0];
        await olas.mint(deployer.address, initialMint);

        const VE = await ethers.getContractFactory("veOLAS");
        ve = await VE.deploy(olas.address, "Voting Escrow OLAS", "veOLAS");
        await ve.deployed();

        const VoteWeighting = await ethers.getContractFactory("VoteWeighting");
        vw = await VoteWeighting.deploy(ve.address);
        await vw.deployed();
    });

    context("Remove nominee", async function () {

        it("Removing last element in nominee list, will leave its id in the `mapNomineeIds`", async function () {
            // Take a snapshot of the current state of the blockchain
            const snapshot = await helpers.takeSnapshot();

            const numNominees = 2;
            // Add nominees and get their bytes32 addresses
            let nominees = [signers[1].address, signers[2].address];
            for (let i = 0; i < numNominees; i++) {
                await vw.addNomineeEVM(nominees[i], chainId);
                nominees[i] = convertAddressToBytes32(nominees[i]);
            }

            // Get the first nominee id
            let id = await vw.getNomineeId(nominees[1], chainId);
            // The id must be equal to 1
            expect(id).to.equal(2);

            // Remove the last nominee in the list
            await vw.removeNominee(nominees[1], chainId);

            // The id did not cleared
            id = await vw.getNomineeId(nominees[1], chainId);
            // The id must be equal to 1
            expect(id).to.equal(2);

            // Now, when user call `getNextAllowedVotingTimes` with removed nominee,
            // it should revert with `NomineeDoesNotExist` error, but the call success without reverts
            await vw.getNextAllowedVotingTimes(
                [nominees[0], nominees[1]],
                [chainId, chainId],
                [deployer.address, deployer.address]
            );

            // However, there is no way to clear it from the `mapNomineeIds`
            // If owner try to remove it again it will revert, since there is no nominee in its index
            await expect(
                vw.removeNominee(nominees[1], chainId)
            ).to.be.revertedWithPanic(0x32); //"Array accessed at an out-of-bounds or negative index"

            // But if the owner try to remove it after adding a new nominee in-place
            // It will remove another nominee account where it will make more data corruption
            nominees[2] = signers[3].address;
            await vw.addNomineeEVM(nominees[2], chainId);
            nominees[2] = convertAddressToBytes32(nominees[2]);

            let nominees1Id = await vw.getNomineeId(nominees[1], chainId);
            let nominees2Id = await vw.getNomineeId(nominees[2], chainId);
            expect(nominees1Id).to.equal(nominees2Id);

            // Remove the removed nominee will not revert now
            await vw.removeNominee(nominees[1], chainId);

            // The actual removed nominee (in setNominees) is the nominees[2]
            await expect(
                vw.getNominee(nominees2Id)
            ).to.be.revertedWithCustomError(vw, "Overflow");

            // Restore to the state of the snapshot
            await snapshot.restore();
        });
    });
});

Tools Used

Hardhat

Recommended Mitigation Steps

To mitigate this vulnerability, an additional check should be implemented to ensure that the nominee being removed is not the last one in the setNominees array. If it is, the reassignment of the nominee ID should be skipped. Here is a proposed fix in the form of a git diff:

     // Shuffle the current last nominee id in the set to be placed to the removed one
+    if (id != setNominees.length - 1) {
         nominee = setNominees[setNominees.length - 1];
         bytes32 replacedNomineeHash = keccak256(abi.encode(nominee));
         mapNomineeIds[replacedNomineeHash] = id;
         setNominees[id] = nominee;
+    }
     // Pop the last element from the set
     setNominees.pop();

This fix ensures that the ID reassignment is only performed if the removed nominee is not the last one in the array, thus preserving the integrity of the mapNomineeIds mapping.

kupermind (Olas) confirmed

Olas mitigated

Varun_05 (warden) commented:

Fixed.


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

The code unconditionally copies the last nominee into the removed nominee's slot, even when the removed nominee is itself the last element, so it reassigns the ID it just cleared.

Impact

The stale mapping entry can cause the contract to fail to recognise that a nominee no longer exists, leading to data corruption and unexpected behaviour when adding or removing nominees.

What the attacker needed

Contract deployed with at least one nominee; caller has permission to remove nominees

The fix

The code should skip the ID reassignment when the removed nominee is the last element in the array, and the report notes the issue was mitigated.

How it was found

  1. Add two nominees to the contract.
  2. Remove the second (last) nominee from the list.
  3. Query the removed nominee's ID and observe it is still non-zero.
  4. Call a function that checks nominee existence and see it does not revert.
  5. Try to remove the same nominee again and observe a panic due to out-of-bounds access.
  6. Add a new nominee and remove the stale one, which then removes the wrong nominee.

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 keeps a list of nominees and a lookup table that maps each nominee to its position in the list. When you remove the last nominee, the code mistakenly writes that nominee's position back into the lookup table, so the contract still thinks the nominee exists. This can confuse later checks and cause errors when managing nominees.

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 Limbooo

View all

12 more disclosed reports, best first.

More from Olas

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.