A reentrancy attack is a critical vulnerability in Solidity smart contracts where an attacker exploits the order of operations in withdrawal functions by sending Ether first and updating balances afterward; when a malicious contract receives funds, its fallback function recursively calls the withdrawal function again before the original contract's state is updated, allowing attackers to drain funds repeatedly in an endless loop. To prevent this, developers should always update state variables before making external calls or sending Ether, or use reentrancy guards (mutex locks) to block recursive function calls.
Reentrancy Attack in Solidity: Smart Contract Security Explained
Added:hello guys it's johnny time now you probably know me of the one who educates you about defy and crypto and blockchain and today i'm excited to educate you about something new smart contract hacking and security and today we're gonna learn everything about re-entrancy attack one of the most destructive attacks on crypto and d5 with millions of dollars lost it all started in the dao in 2017 150 million dollars were lost but it's also actively exploited attack these days that many defy protocols suffer from if it's the rari capital on april 2022 where 80 million dollars were stolen or revised finance on march 22 when 11 million dollars were stolen so today you're going to learn everything about 350 attacks how it works what you can do with it now i hope that you're gonna use it for good purposes this is only this video is for educational purposes only and i hope you're gonna take this knowledge in order to become a white hat hacker that help the help projects to protect their smart contracts rather than the ones who hug them and still steal innocence people money we will also in this tutorial simulate this attack ourself and execute it with audit and solidity so you can learn the best the practical way how to exploit this kind of attack yourself and eventually we will finish up by learning how to secure our smart contracts and write secure code that is immune to re-entry attacks so i'm super excited and without further ado let's get started all right so what is reentrus attack so exactly like the name says reentry c means re-enter it's a vulnerability in solidity and smart contracts that lets you an attacker re-enter the same function before it finished its execution and the best way to understand it is by example that's why i created this drawing here for you so imagine you have a smart contract that represents a bank it lets users deposit and withdraw ether from the smart contract and of course it's gonna save their balances in a storage variable in a mapping that maps between addresses to integers so if bob deposits a tree heater the smart contract will know that now bob's has three heater and later on when bob comes and tries to withdraw later the smart contract will send him the eater back how the smart contract send him the eater back is basically sending the eater first and then he updates the balance of bob the message sender to zero so bob can send multiple times one eater plus two plus four and then later on come and try to withdraw all so the smart contract know that during this time bob deposited in total seven eater so it's gonna send him the seven eater and change the balance of bob from seven to zero quite simple right but something is wrong with this withdrawal function now try to pause the video take a look at the function and let me know in the comments below if you spotted what's wrong all right so the withdrawal function the first thing that it does it sends the eater to the user that's where the problem relies the smart contract the bank it thinks that bob is a normal account but what if bob is not a normal ethereum account but a smart contract itself right because smart contract can also be a user that deposit it to the bank and then wants to withdraw it and in smart contracts there is something called fallback function this function will be executed when the smart contract receives ether automatically and now you can connect the talks and understand that when the smart contract the malicious smart contract we can deploy a malicious smart contract that deposits let's say one eighth and then calls the withdrawal function from the bank with one if but when this line of code will be executed when the bank will send the one in to the smart contract it will trigger here in the malicious contract a fullback function okay so this fallback function we can then use it in order to call again that it withdraw function and guess what happens now the banks it doesn't know that it already sent us the heath because he didn't update yet the balance our balance because he sent the heat first so it's basically endless oop that loop that let us the attackers to drain the heat from the ether bank smart contract so the withdrawal function will be called then he will send us the heat that will trigger our malicious fallback function that will call again the withdrawal now he still thinks that we have one eater or seven or whatever and he sends it again and then again fallback and then again re-enter until the balance of the interbank is zero and then okay you can update the balance to zero but instead of withdrawing one if we withdrawn i don't know maybe hundred 100 maybe thousands of feet depends how much it exists in the smart contract so now that we understand the concept of free interest reentry attack it's time to some in practice to make our hands dirty and read some solidity code so here is the implementation of the ether bank it's an updated solidity version ether bank here you can see the mapping of the balances that stores the mapping between address to its balance this is the deposit it functions very straightforward it's a payable function that receives a message value which is if and stores it in the balance storage variable now this is the problematic withdrawal function as you can see it's a public function that any user can come and claim back and we draw its balance now here we have a variable that represents the balance of the user and then we send the if okay we verify the descent was successful that the transfer was successful and then we update the balance now here realize the problem we send it first and then we update the balance later that's where the problem starts now let's try to deploy the smart contracts in order to simulate it and create our own environment guys i wanted to share with you something super exciting and new i've created a complete practical smart contract hacking course accumulating 12 years of my cyber security and blockchain experience without exaggerating this is your holy grail all-in-one course which will instantly help you kick-start your career in smart contract hacking and security making you the most demanded professional with insanely high salaries get exposed to tons of knowledge by signing up in the description below by the way guys all the code that i'm going to show you over here going to be in github in my public github so feel free to clone it to play with it to practice reentry attack the link will be in the description below now i'm using hearth in order to simulate and local blockchain it's basically gonna simulate like ethereum but on my localhost running a local simulated blockchain and we can that way simulate all the attack and in order to start the local blockchain we're gonna write npx hard hat node and it will take several seconds and there you can see you have all the accounts of the local blockchain injustice simulation a demo now i created some scripts that will help you deploy the smart contracts and make some activity in the network of like simulating users that deposit money to the bank so the first script will be deploy bank we're gonna execute it right now that will deploy the bank smart contract let's run it npx hard hat run scripts deploy bank and network make sure you add the local lost so it will deploy it locally to the node and as you can see the ether bank was deployed to this kind of address and if you go here to the node you see that the transaction was simply submitted and there was a contract deployment of ether bank very easy very straightforward now the next trip you want to run is the use bank that basically going to simulate some activity of the bank it's going to deposit some it's from account zero then it deposits five eight from account one twelve from account two so the bank will be realistic and users will deposit some etherid so we're gonna do the exact same thing but this time just change the script from deploy bank to use bank all right and you can see the script will write depositing three depositing uh five eight etc and it will show that the now the bank has 20 in the balance and this is the balance storage variable that's what the banknote that account zero has three one has five two has 12 and three which is the attacker has zero so in our simulation the country will represent the attacker and as you can see in the initial state it has zero you can any time check out the status of the bank by running the script check check bank okay and then you can see the balances again now it's time to write the smart contract that is going to exploit the bank all right so before jumping into riding on let's try to plan our attacks so we want to attack this eater bank dot soul smart contract and in order to do so we need to deploy our own smart contract we'll call it attacker dot sol attack bank that sold doesn't really matter this month contract will have two main functions one will be execute which will start execution of the attack what it's supposed to do it's supposed to deposit first one eth to the to the bank so the bank will see that we have some balance and then right after it will call the withdraw function to ask to withdraw this one it now once the withdrawal function will be executed it will send a smart contract back back the if that will trigger the fallback function that will call again the withdrawal and then trigger then fallback until we drain the smart contract completely even though we deposited one it will we will be able to drain it to all the 20 ether deposited by other users and now let's get started with the code and this is the attack bank dot sol file okay so it's a solidity smart contract we declare here the interface of the ether bank the original smart contract the deposit and the withdrawal function so the attack bank smart contract will be able to interact with the ether bank smart contract and here we create a new contract called ether bank we cr we set some uh variables the item bank smart contracts that we're gonna attack and the owner we want to know who is the owner who deployed this malicious smart contract circuit once all the logic will be done all the execution will be done we can send all the stolen heath to the owner to the attacker who deployed this smart contract now this is the constructor this is the function that will be executed when the smart contract will be deployed when it will be deployed we need to tell him uh only what is the address of the the contract that we want to attack in our case the interbank address and as you can see here we are setting the owner the attacker the one who deployed the smart contract he will be the owner and we save the ether bank smart contracts by the address that we got upon deployment now this is the execute or attack smart function that we planned before as you can see it's external payable and it's first gonna call the deposit if function okay with one is so we're gonna send from this malicious smart contract one eth to the bank smart contract of course that will have to send with the transaction one eighth or load it up with one ether in advance so it will have the it to send to the original bank smart contract and then right after we'll call the withdrawal if so it will ask the bank to withdraw all the one is that we deposited one line before now this where the magic begins the receive smart contract this receive function this is the fallback function that's how we write fallback functions in solidity and here we check if the interbank balance is greater than one is we're gonna call the withdraw it function again so the bank is calling the withdrawal function and will trigger this kind of function and here we check did we already drain the bank or is there any if left if there is an eighth left we're gonna call that we draw it again and we draw another one is else which means that we already got all the it from the bank smart contract we're gonna simply send all the ether of this malicious contract to the owner which is the attacker who deployed the smart contract so it's quite simple around 40 lines of code and this is how we can create a re-interesting attack super super simple feel free to clone the code on github i'll put a link in the description and now it's time to start and deploy and execute the attacks so first we want to deploy the malicious smart contracts so we're gonna run the script solution and deploy attack contract okay so we're deploying first our malicious smart contract to the local blockchain let's click enter and the malicious contract has been deployed to whatever and here we can verify that the attack bank contract has been deployed now we want to run the script attack this script is simple simply gonna take the malicious smart contract that we just deployed and call the attack function that will execute all the logic that we just created in the smart contract let's do it so we'll run script attack on localhost and as you can see over here after the attack this is my balance before the attack around 10 000 eth bank balance before the attack 20th and executing the attack attack down my balance after the attack is 1018 east so we were able to withdraw a lot of it from the bank and in order to verify that the attack was successful we can run the script check bank again and here we will see that the bank balance has have left only with one ether okay we went easy on him we left one either for the bank so we were able to withdraw 19th even though we just deposited one thanks to re-entrancy attack now you might ask oh my god this is so simple did you know that reentry attack that millions of dollars were stolen just because of this kind of simple and stupid vulnerability yes you're right but now let's try to understand how we can write better smart contracts that will not be vulnerable to re-entry attacks and people will not hack them so the first important thing that you need to learn about a reentry attack and in general about writing smart contracts that always but always update the state variables first the storage variables of the smart contracts before sending ith or calling as senate functions in other smart contracts so by simply replacing the lines of the update and the transfer okay in the contract in the withdrawal function we would avoid this kind of free entry attack because we would first update the balance of the user to zero and only after we would send the if which will trigger the fallback function so this is first way to protect against re-entrance attacks another way is to create some kind of mutex that will lock the smart contract so we can create a variable a boolean variable that will be called locked it's an internal variable and we create a modifier that's called re-entry guards so we will apply to this modifier before every function that might be available to re-entry the attack and simply this modifier just check if this locked mutex is true or false so we're gonna change it to true once we enter to the function so we'll do something like locked equals true and then the next time when we get into the smart contract again okay which will be protected by the re-interesting guard modifier we will check again this modifier will be executed and we will see that the locked is true so it will revert the transaction because this require will be executed so you have some kind of variable that knows all the time if someone is trying to re-enter to the same function over and over again so this is the second way of protecting against re-entries attack by using a re-entry cigarette modifier now if you want it even more simpler in a more simple way you don't have to implement this kind of function yourself you can just use open zeppelin re-entry guard smart contract this is basically a conflict that you can inherit from and automatically it will let you use this kind of non-re-entrant modifier which does the exact same thing exactly like reentry guard just they implement it for you so you can simply just import the re-interesting guard smart contract by open zeppelin and then inherit from this smart contract in your smart contract and now this non re-entrance modifier will be available and you can place it in every sensitive function that might be vulnerable to re entry c attack all right so this is the re-entry c attack tutorial i hope you guys enjoyed it and learned something new if you did make sure to smash the like button and subscribe to the channel and if you have any more ideas about other videos that you want me to create about d5 about crypto about hacking let me know in the comments below thank you so much and i will see you in the next videos bye bye
Up Next

Flash Loan Attacks: Anatomy and Prevention in DeFi Security
@TheDefiant
16.9K views•2020-11-20

Torrent File Format & Bencoding: A Technical Deep Dive
@AsliEngineering
12.5K views•2022-08-08

Operational Security Essentials: A Guide for Hacktivists (OPSEC)
@hitbsecconf
157.4K views•2012-11-26

Understanding Ethereum: A Comprehensive Beginner's Overview
@99Bitcoins
3.1M views•2018-06-26
Related Study Plans & Knowledge Roadmaps
Structured learning paths in Blockchain & Crypto





































