Skip to content
Smart contracts Audit finding Advanced

Multiplication overflow leading to memory corruption and incorrect register write-back

The MIPS contract's multiplication of two signed 32-bit integers is performed in an unchecked block, which the reporter claims can overflow and cause incorrect values to be written to memory and registers. An attacker could potentially corrupt contract state or break MIPS functionality.

Topmark Follow

Originally disclosed on Code4rena

Submitted by Topmark

https://github.com/code-423n4/2024-07-optimism/blob/main/packages/contracts-bedrock/src/cannon/MIPS.sol#L967 https://github.com/code-423n4/2024-07-optimism/blob/main/packages/contracts-bedrock/src/cannon/MIPS.sol#L763

Impact

The unchecked multiplication of int32 values (rs and rt) and type conversion within the execute function in MIPS contract can result in an overflow, leading to the assignment of an incorrect value to the val variable in the step(…) function. This incorrect value is subsequently written to memory and the destination register in the step function. This can cause data corruption in contract and break of Proper MIPS contract functionality and storage

Proof of Concept

 function step(bytes calldata _stateData, bytes calldata _proof, bytes32 _localContext) public returns (bytes32) {
        unchecked {
...
 uint32 val = execute(insn, rs, rt, mem) & 0xffFFffFF; // swr outputs more than 4 bytes without the mask
...
     // write memory
            if (storeAddr != 0xFF_FF_FF_FF) {
                writeMem(storeAddr, 1, val);
            }

            // write back the value to destination register
            return handleRd(rdReg, val, true);
        }
}

The function provided above shows how step(…) function is implemented in the MIPS.sol contract, it can be noted from the code fragments provided in the function that the value of val is set by making a call to the execute(…) function and this value was used to write memory later in the function to the destination register, it can be noted that this was done within the unchecked region.

function execute(uint32 insn, uint32 rs, uint32 rt, uint32 mem) internal pure returns (uint32 out) {
        unchecked {
...
if (opcode == 0 || (opcode >= 8 && opcode < 0xF)) {
...
} else {

                if (opcode == 0x1C) {
                    uint32 func = insn & 0x3f; // 6-bits
                    // mul
                    if (func == 0x2) {
>>>                        return uint32(int32(rs) * int32(rt)); ❌
                    }
                    // clz, clo
                    else if (func == 0x20 || func == 0x21) {
                    ... }
                 ...}
    ...
    }
...
}

The code above shows how the execute(…) function was implemented, as noted in the pointer above the unchecked multiplication of int32 values (rs and rt) & type conversion to uint32 within the execute function above would lead to an overflow, which would result in incorrect calculation. This is because multiplication of certain values within int32 can go above the max int32 value, the problem with this issue is that the operation was carried out inside an unchecked environment and it was converted to type uint32 even though the value might have gone above it, which means the overflow which would have normally revert would go unnoticed thereby corrupting write memory and sending wrong value data to destination register in the step function.

Scenario Proof:

Assuming rs is 2147483647 (maximum positive value for int32) and rt is 2. The multiplication 2147483647 * 2 should normally result in 4294967294, which exceeds the maximum value for int32, but with an overflow it results to a completely different result.

Recommended Mitigation Steps

To prevent overflow, the multiplication should be checked for overflow before proceeding with the operation. One way to achieve this is by using SafeMath libraries that provide arithmetic operations with built-in overflow checks or by simply doing the validation as provided in the code below by first doing the multiplication within int64 and validating that it is below maximum of int32 before type conversion.

+++  import "@openzeppelin/contracts/utils/math/SafeMath.sol";

function execute(uint32 insn, uint32 rs, uint32 rt, uint32 mem) internal pure returns (uint32 out) {
    ...
    if (opcode == 0x1C) {
        uint32 func = insn & 0x3f; // 6-bits
        // mul
        if (func == 0x2) {
---            return uint32(int32(rs) * int32(rt));
+++            int64 result = int64(int32(rs)) * int64(int32(rt));
+++            require(result <= int32.max && result >= int32.min, "Multiplication overflow");
+++            return uint32(int32(result));
        }
        // clz, clo
        else if (func == 0x20 || func == 0x21) {
            ...
        }
    }
    ...
}

Assessed type

Under/Overflow

clabby (Optimism) confirmed and commented:

This report is partially valid, and points out a divergence from the MIPS specification. However, the mention of disallowing overflow is incorrect, as the specification directly calls for producing a 64-bit result and retaining the low-order 32 bits of it, and never throwing an arithmetic exception.

In the MIPS specification, the MUL instruction description states:

The 32-bit word value in GPR rs is multiplied by the 32-bit value in GPR rt, treating both operands as signed values, to produce a 64-bit result. The least significant 32 bits of the product are sign-extended and written to GPR rd. The contents of HI and LO are UNPREDICTABLE after the operation. No arithmetic exception occurs under any circumstances.

The current implementation does not perform signed 64-bit arithmetic, casting down the result to a 32 bit value. We should not throw an exception, but we should adhere to the MUL spec.

Inphi (Optimism) commented:

Sounds like this should be downgraded to medium in that case. I see no evidence that the Go compiler emits invalid code that would otherwise cause a MIPS exception.

obront (judge) decreased severity to Medium and commented:

Since there is no evidence that the program can be impacted by this divergence from spec, will award in line with other “divergence that could cause problem but isn’t clear exactly how” and downgrade this to Medium.

3docSec (warden) commented:

@obront, in light of the fact that “wrap around on overflow” is indeed the correct behavior as per spec, we believe this report is invalid, because it points out to wrapping as root cause and as mitigation it recommends the very same operation with an added require that throws in case of overflow (which is not compliant).

To make the point that the suggested mitigation is functionally equivalent and doesn’t yield any difference in result, we investigated the difference between the following 2 implementations:

  • current implementation:

    return uint32(int32(rs) * int32(rt));
    
  • proposed implementation without the non-compliant throw:

    int64 result = int64(int32(rs)) * int64(int32(rt))
    return uint32(int32(result));
    

    and found them to be functionally equivalent.

This is because execution only cares about the lower 32-bits of the result, so we don’t need to store the result in int64 and the upper 32 bits therefore can be safely ignored.

The following fuzz test demonstrates the equivalence of the original vs mitigation code:

pragma solidity ^0.8.0;

import "forge-std/Test.sol";

contract PoC is Test {

    function testPoc(uint32 rs, uint32 rt) public {
        unchecked {
            uint32 res1 = uint32(int32(rs) * int32(rt));

            int64 res2i = int64(int32(rs)) * int64(int32(rt));
            uint32 res2 = uint32(int32(res2i));

            assert(res2 == res1);
        }
    }

}

which yields:

Note: to view the provided image, please see the original comment here.

Topmark (warden) commented:

I think there is a misconception, I would like to quote xuwinnie from the discussion channel which should throw more light why this should remain valid.

xuwinnie: ”#15, #82, #85, #89 say VM does not throw an exception when prestate is unexpected, which diverges from the spec.”

The program can be simplified to

outputRoot = run(inputs) if claimedOutputRoot != outputRoot return INVALID else return VALID

We don’t really care about how VM handles unexpected prestate. Even when claimedOutputRoot root is invalid, the program should still run smoothly. so those cases are unreachable.

Even run() cannot properly handle some inputs, it’s the op-program’s (or the complier’s) fault, how MIPS-VM handle these cases doesn’t really matter. Suppose A is the expected result of run (someInputs), but we get another result B.

  • Not Fixed: only claiming B can be defended.
  • Fixed: (The four reports all suggest a fix that revert inside step, this is not good since it will make the game stuck. A better fix would be set the VM to PANIC) the VM panics, according to Issue 54, every claim can be defended. That’s even worse.”

obront (judge) commented:

While this issue was incorrect in its specific understanding of the correct behavior and remediation, it was correct in identifying that the program did not hold to spec for the multiplication of int32 values. For that reason, along with the other “likely can’t be triggered, but deviate from spec in a way that could cause invalid state transitions to be proven” — I will keep it as a Medium.


The original report as published on Code4rena, by Topmark. 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 multiplication of two signed 32-bit integers was performed in an unchecked block, which the reporter believed could overflow and produce an incorrect result, though the specification actually requires wrapping behaviour.

Impact

The reporter claimed this could cause data corruption and break MIPS functionality, but the judge noted there was no evidence the program could be impacted, and the behaviour was later shown to be functionally equivalent to the proposed fix.

What the attacker needed

None

The fix

The reporter suggested using SafeMath or checking for overflow before conversion, but the judge and another commenter noted that the proposed fix was functionally equivalent and that the correct behaviour is to wrap around without throwing.

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.

This report is about a smart contract that emulates a simple processor (MIPS). The processor has a multiply instruction, and the code that implements it does the multiplication in a way that can overflow (wrap around) instead of stopping with an error. The reporter thought this was a bug, but the processor's official specification actually says overflow should wrap around, so the report was only partially correct.

What is Smart contracts?

Flaws in on-chain code that let an attacker drain funds, freeze them or break the protocol's accounting.

More by Topmark

View all

1 more disclosed report, best first.

More from Optimism Superchain

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Smart contract vulnerabilities

The lesson behind this report.

Flaws in on-chain code that let an attacker drain funds, freeze them or break the protocol's accounting.