solidity re-entrancy attack explanation

Viewed 234

Hey I have a question about re-entrancy, I get the logic but how come the attacker manages to withdraw again before the balance is set to 0, taking into account transaction time and that both functions in A and B are on the next line

re-entrancy

1 Answers

Let's say we have 2 contracts. target contract which holds some ether belongs to the attacker contract. And now attacker contract wants to withdraw its money

Attacker contract has 2 functions: fallback and withdraw

// this gets triggered when ether is receive
fallback(){
  A.withdraw()
}

attack(){
  A.withdraw()
}

Let's say attacker contract calls attack function. This will call the withdraw inside target contract:

target contract:

withdraw(){
  require balance>0
  send ether
  // before balance gets updated attacker's fallback triggers another withdraw
  // send function will give the control to the attacker's contract
  set balance of attacker =0
}

Now target contract will send the ether to attacker's contract. When it does, inside attacker's contract fallback function is triggered. fallback gets executed every time ether is received. I explained fallback functions in detail

Now attacker's contract is received ether and immediately calls withdraw inside target contract. So target contract's withdraw function is in a loop till target contract's balance reaches to 0

If a contract uses call, send or transfer which may cause control flow to the attacker contract, because those functions delegate enough gas for the fallback function. Once the control is passed to the attacker's contract, the state of the target contract will incomplete. target contract lost the contrrol.

Prevent reentrancy attacks

Related