A reentrancy attack is a security vulnerability in smart contracts where an attacker creates a malicious smart contract that calls a vulnerable function (like withdrawal) while it is still executing, allowing the attacker to repeatedly call the same function within a single transaction and drain the entire contract balance. This occurs because smart contracts can execute multiple steps within one transaction, unlike regular users who can only call a function once. The attack exploits the fact that the contract sends funds before updating the balance mapping, enabling the attacker to receive funds and immediately call the function again. To prevent reentrancy attacks, developers should use OpenZeppelin's Reentrancy Guard library, which tracks whether a function is currently executing and prevents re-entry by applying a modifier to vulnerable functions.
Reentrancy Attacks in Smart Contracts: Exploit & Prevention Guide
Added:all right so in this video i'm going to teach you how to hack smart contracts on the blockchain all right this is such a huge topic people have asked me about this a lot so i'm finally making this video for you all because you know there's so much money out there secured by blockchains and many of these smart contracts are vulnerable to hacks and we've seen lots of cases where people take millions of dollars out of smart contract with the exact technique that i'm going to show you in this video so this is something called re-entrancy it's the most common ways that smart contracts get hacked and so i'm going to teach you everything you need to know about in this video so if when you're around here hey i'm gregory on this channel i turn you into a blockchain master so if that's something you're interested in then smash that like button down below for the youtube algorithm and subscribe to this channel and if you want how to master blockchain step by step start to finish then head on over to dap university dot com forward slash camp to get started today all right so let's talk about this reentrancy hack and why you need to understand it so first of all i'm not teaching you this that you can actually go and steal somebody else's money it's not on making this video this information is useful for two big reasons if you can do this you can disclose this vulnerability to other people for in terms of bug bounties and in many cases you can make a lot of money for doing this we've seen lots of stories of developers making over a million dollars in a day just for disclosing smart contract security vulnerabilities so it also pays to be honest when you find this stuff the other reason is to protect yourself and your own smart contracts or your teams smart contracts for putting them out there because you have to be understand what security vulnerabilities are and think like a bad guy so you don't fall victim to this attack yourself so that being said let's go over the shoulder and get started alright so let's look at how this reentrancy attack works so essentially let's think about a bank smart contract as an example so what does this bank smart contract let people do well let's people deposit funds into the smart contract and also withdraw them and inside the smart contract it keeps track of you know the entire balance of everybody who's ever deposited okay you can see this right here this is like a hundred we'll just call this ether for now it's a pretty good easy example of a cryptocurrency that can be deposited here so 100 ether in total you know let's just say spread across 10 different depositors but here you can see this external wallet who's interacting with it they can deposit withdrawal this will be the user in this case and they've only deposited 10 ether okay so essentially you know in this case an external wallet should only be able to call this withdrawal function once they've deposited to deduct their balance of 10 ether and there's really no way for an individual wallet let's say somebody who just got their metamask wallet connected to the blockchain to hack this smart contract and you know manipulate this or exploit this withdrawal function in any way however if they create a smart contract and perform a reentrancy attack then they could attack the smart contract and drain the entire smart contract balance of 100 ether instead of their balance which is 10 ether if they use an external smart contract and if the bank smart contract has a reentrancy vulnerability so what is it what is re-intrinsic well it is basically what it sounds like you're essentially let's just look at the withdrawal function in this case you know this is the this is the function that's potentially vulnerable to a re-intrinsic attack so reentry means you re-enter this function while you're still calling it so basically you can see this here where in a normal scenario whenever the user calls this function they shouldn't be able to call it once and you know say withdraw their entire balance which is 10 ether in this case well you know a normal user showed me to call this once and whenever they call the transaction on the blockchain it just does one instruction does withdraw however if you use a smart contract you can re-enter this function in some cases and keep withdrawing the balance while the withdrawal function is still being called and basically call this in loop so that you know you keep withdrawing the entire balance in increments of 10 which is your deposit uh over and over again until the entire smart contract is drained you're re-entering this function while you're still calling it okay so it that's what it looks like from a high level you have this bank contract that has this withdrawal function it has a reentrancy vulnerability which lets an external wallet you know the attacker in this case use another smart contract to call this withdrawal function and then keep calling it while it's still being called in loop until it drains the entire balance from the bank contract so that's just a high level overview of what it looks like uh you know right here let's go ahead and jump into the code so you can actually visualize this see how it works you know see if your smart contracts are potentially vulnerable to this and how you can fix it now let's go ahead and grab the coding solution for this project so you can see how intrinsic attacks are work so uh head on down to the description below this video you're gonna find a github repository that has a coding sample here so go ahead and grab that link all right go to your terminal and say get clone all right then paste in the url so i've already done this it's going to give me an error here but uh whenever you you do it you should see a success message so i'm going to enter into this newly cloned directory like this a cd re-entrancy all right and then next we need to install the dependencies for the project okay we can install your dependencies with node like this so npm install all right i've already done this step as well but you should wait for your dependency to finish you'll you'll see them there all right and then uh you need to make sure you have some basic dependencies your computer before you can run this example even if you don't you know run it completely okay you can still grab the code you can still make sense of it but you need solidity which is going to be installed through hard hat okay which is going to get installed with that npm install like this so the really the biggest defense you need is um let's see node.js for managing your packages and once you run node.js you'll get uh solidity you'll get hard hat uh you'll get ethers js okay so make sure on npm install uh that's going to give you hard hat like i was saying before we're gonna use hard hat for the contracts here uh so you can do uh mpx uh hard hat compile just to make sure everything's working properly okay i've already done this step as well so you shouldn't see too much you might see this license identifier uh we can fix that here in a second but uh that will ensure everything's working properly so i'm gonna go ahead and open up this code in my text editor here i'm choosing sublime text you can use whatever text editor you'd like and you can see you've got all our basic hardhat configuration inside of here we've got this hard hat config file uh i've got our package.json file right scholar dependencies that we need uh but the smart contracts where we can actually visualize this re-entrance the attack is inside of here okay so uh excuse me in here contracts directory so here's the bank smart contract that's exactly what i was talking about here okay where you know the user should be able to just theoretically deposit funds and then withdraw and then you know in this scenario we have an attacker smart contract which is this exploit right here that's going to be this attacker.soul so let's start with the bank and see how it works see how it's vulnerable to this reentrancy attack and then how we can fix that problem okay so uh the bank is really simple it's really really simple it's just a simple smart contract that's called bank um what it does is it has a mapping inside of it that keeps track of you know the balances it lets people send ether to the smart contract either theorem cryptocurrency or ether and then it keeps track of everybody inside this balance mapping if you're not familiar with mappings basically they just store key value pairs in the blockchain you can kind of treat it like a database in this sense where you give it the address and then it returns a number which corresponds to the balance of the person who deposited and they call this deposit function so they basically just say deposit it updates this balance of message sender that's what msg.sender stands for this is the amount of ether sent in with the transaction and it just increments it by message value so msg message value is the amount of ether assigned to the transaction as well so this message senders the address of the person sending message values the ether amount and so that gets stored here all right and then this uh let's just see here this withdrawal function is how the person uh withdraws from the bank all right so it's got two functions deposit withdraw so they deposit and this this is where the vulnerability lies right this is what you really want to pay attention to i'll even bump this up so you can see it so the withdrawal takes a deposited amount so essentially it gets their balance from this mapping and then it says basically their address whoever's calling this function send ether okay take your balance out of the mapping and then send ether uh you know the deposited amount to the person calling this function and then it resets their balance to zero now here's the function that has re-intrinsic vulnerability because what can happen is essentially while this function is being called okay by another smart contract if message center is a smart contract in this case and not an externally owned account like a metamask wallet then that smart contract can essentially call this deposit function and the withdraw function at the same time okay and over and over again and when it does that it can essentially drain the entire smart contract balance so why is that because if it calls deposit all right then essentially it's updated the mapping and essentially you can uh just withdraw the amount from that over and over again okay so i'll show what that looks like inside the attacker this is the second smart contract all right so you can see it here essentially that's what you're gonna do this the attacker can call the banks withdrawal function deposit withdrawal at the same time induct this balance you know it can it's let's say deposited 10 ether well it can just keep depositing 10 withdrawal 10 over and over and over and over again until it's drained this entire balance of 100 ether so that's what it looks like right here so the attacker essentially understands the interface for the bank contract that's what this is we import the interface um for the bank right here we don't actually import in the file we just create an interface that understands the functions like deposit withdrawal that's what a smart contract interface is it's kind of like a skeleton for the smart contract that tells you what the functions look like and what their arguments are okay so um we set the smart contract up to understand where the bank contract is and how it works and so basically attack is this it says uh bank contract deposit message value and then do the withdraw at the same time okay and then when it receives basically receives the ether it can call this withdraw function okay so it's it's doing this on a loop because the receive function is the function that gets called whenever the smart contract receives ether so like if i were to take a medi-mask wallet and just send a transaction to the smart contract's address it's going to call this logic okay so basically it's calling deposit of 10 ether withdrawal of 10 ether and then whenever this smart contract sends the ether to the smart contract inside of this all right this line here on 22 payable message sender which is a smart control in this case this function is going to get called so what does this function do it basically says if the account balance is greater than 0 then call the withdrawal function again this is where it re-enters the withdrawal function before you know it's it's just it's doing it over and over again inside the same transaction that that's the key a smart contract lets you do multiple steps inside the same transaction and so if you keep calling this instruction over and over and over again it's essentially creating a loop okay um and then when it's done once it's drained uh then it's going to send the owner the entire balance and that's good all the funds are going to get transferred to the attacker in this case so we can see this play out in real time okay there's a test inside of here so this sample test this is a hard hat test so basically it shows how this works so basically we have some basic tests inside of here that says you know test deposits withdraw the bank account so it's basic test to make sure that deposits work that withdrawals work and then it shows you how the attack works so essentially we do some console logging i'll close this down so you can see it turned out a little bit to see what the balance is of the bank all right and then the attacker's balance and then we call the attack function okay and we do this with 10 ether okay and so we can watch the attack function get called in real time whenever the attack functions finish calling you're going to see what the actual balance is so you're going to see that it essentially drains the entire bank balance and it increases the attacker's balance so let's just run that you can see the instructions here inside the github repository okay npx hard hat test is what you do to run the tests mpx hard hat test all right pull this over a little bit all right there you go so you can see the first test pass accepts deposit except withdrawals the basic test but then you can see what's happening inside the attack test so the bank's balance before is 150 so it's a little bit higher than our initial example this is the attacker's balance that's just the standard balance that comes with hard hat accounts okay so the bank's balance after is zero it's successfully drained all the bank's funds all right and then the attacker's balance is now this all right so that's an illustration of how the actual hack works so if you're going to perform a reentrancy attack which i'm not advocating that you go steal anybody's money but that's that's basically how you would do it okay you would create a smart contract that calls the function uh that is vulnerable to re-intrinsi and then you have some way to receive the funds and then keep calling that function while it's still inside the same transaction okay so now how can you protect your smart contracts against this reentrancy attack well you can use a special library inside of open zeppelin called the reentrancy guard okay so opens up one's a great you know library set of tools for security purposes you know you can you can get templates for certain um you know smart contracts that are community audited like erc 20 tokens nfts erc 721s all that stuff but they also have some great uh utilities that helps you know safeguard any smart contracts so in particular they have you know reentrancy guard which you can see here you import the opens up literally interesting guard and then you have these modifiers which you can attach your solidity functions like this so you know non-re-entrant all right you can just attach this all right uh to the actual the actual smart contract so step one you know to fix this is you would you know if you first need opens up one inside your project you can see that into the package.json file here okay uh we've got opensup unsaved here so you make sure you want to install that and then you can import the library inside your smart contract like this opens up link contract security reentrancy guard and then you want to inherit from the reentrancy guard okay you can you can do like this you can say is and then just copy this before the sol you can say is oh sorry this one's all right this uh is reentrancy guard okay that's just that's the that's the smart contract uh library from this file so that's how you use inheritance and solidity you say your contract bank you know is reentrancy guard and then you want to imply excuse me you want to apply the modifier that comes with that smart contract so you can see that's the documentation here you can see the the modifier um is non-re-entrant all right so you can just copy this and then this is how you apply a modifier your solidity function you say function withdraw you know external is visibility then you can place your modifier here you can say just non re-entrant you just add that to your function name for the curly braces and that will get all the behavior that's uh you know included inside this re-intrinsic guard and if you're really curious you can check out the source code to see what it does you can see inside of here that it basically just keeps track of the function whether it's been entered already and if it has been injured already then it just like doesn't let you do it again okay so it basically keeps track of the status if the status is entered um then it won't let you enter it again so you could code this out yourself if you really wanted to but i would just you know probably use a library in this case so um let's let's see this in action let's go to our terminal and let's just do mpx hard hat compile okay let's make sure our smart contracts don't compile properly i actually just did this off screen so you'll you'll see it compiled properly but um now we can run the test so you can say mpx hard hat test and what i expect to happen is that the the first two tests that you know check for the initial deposit and withdrawal behavior to pass but the second test where we try to actually do it and attack should fail and if that happens then we know uh that our our our solution here was successful so let's run the test all right now boom that's exactly what happened so we can see uh the first test should pass it accepts basic deposits and it accepts withdrawals so the the withdrawal functionality didn't change whenever we inherited this and applied the new uh you know safeguard the reentrancy guard however you can see when it was trying to perform the attack that it failed so error vm exception while processing transaction reverted with reason string you know address able to send value recipient may have reverted um it worked all right so that's an overview of reentrancy attacks inside solidity how to perform one if you can spot a reentrancy vulnerability as always i don't uh advocate for anybody stealing money on the blockchain it's your responsibility to disclose a reentrancy vulnerability to a project hopefully you can get a bounty for doing that okay and then that's how you also protect your own smart contracts against re-entrancy attacks so i hope you like this video as always smash that like button down below for the youtube algorithm subscribe to this channel if you haven't already if you like this video and you want to see more videos just like this on how to code blockchain applications then definitely check out my youtube home page you can find my free courses there like udemy courses but they're totally free and if you like those and you want to take the next step or hey maybe you don't take a massive shortcut entirely actually become a blockchain master step by step start to finish over at dap university dot com forward to last boot camp you have to be an expert to get started today i've helped people with zero coding experience become real world blockchain developers in a matter of months so that's all i've got that's next time thanks for watching dap university
Up Next

Read-Only Reentrancy Explained | Solidity Security (0.8)
@smartcontractprogrammer
14K views•2022-10-30

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

Solidity Programming: Complete Blockchain Developer Course
@DappUniversity
156.2K views•2020-05-22

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












![[Curso de Solidity - 2023] Aula 12: Manipulando ETH](https://i.ytimg.com/vi/ebpe0aXSrPI/maxresdefault.jpg)
























