0

I'm stuck with Ethernaut Alien Codex problem. I understood underflow attack except that codex[2²⁵⁶ - 1 - uint(keccak256(1)) + 1] corresponds to slot 0. I referred to the below tables.


Slot # Variable
0 contact bool(1 bytes] & owner address (20 bytes), both fit on one slot
1 codex.length
keccak256(1) codex[0]
keccak256(1) + 1 codex[1]
2²⁵⁶ - 1 codex[2²⁵⁶ - 1 - uint(keccak256(1))]
0 codex[2²⁵⁶ - 1 - uint(keccak256(1)) + 1] --> can write slot 0!

All I know is Storage has 2²⁵⁶ slots and a dynamic array that had been attacked can control every slot in the Storage. What am I missing? The source code is below.


// SPDX-License-Identifier: MIT
pragma solidity ^0.5.0;

import '../helpers/Ownable-05.sol';

contract AlienCodex is Ownable {

  bool public contact;
  bytes32[] public codex;

  modifier contacted() {
    assert(contact);
    _;
  }
  
  function make_contact() public {
    contact = true;
  }

  function record(bytes32 _content) contacted public {
    codex.push(_content);
  }

  function retract() contacted public {
    codex.length--;
  }

  function revise(uint i, bytes32 _content) contacted public {
    codex[i] = _content;
  }
}

1 Answer 1

3

So, we know codex[a] writes to slot a + keccak(1), for every number a, since that's how solidity saves a dynamic variable.

The number 2**256 - 1 - uint(keccak256(1)) + 1 can be simplified into 2**256 - keccak(1), since -1+1 = 0. Also since 2**256 = 0 (thinking modulo 2**256), the number becomes -keccak(1).

Using a = -keccak(1), we get:

codex[a] --->   a + keccak(1) = -keccak(1) + keccak(1) = 0

so we're writing to slot 0.

2
  • Can we assume that the end and the beginning of the array are connected? It's not clear for me to understand why 2**256 = 0.
    – Shift_that
    Commented Oct 11, 2022 at 20:29
  • 1
    It's more than when it's calculating the slot it overflows. Since a number can only have 256 bits, 2**256 becomes 0. Thinking about the array may be confusing, but yeah you can say it's biting its own tail: there are only 2**256 slots, so when you go over that number you start overwriting over previous slots.
    – 0xSanson
    Commented Oct 12, 2022 at 12:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.