← All talks

Iman Sharafaldin: Securing Smart Contracts

BSides Calgary · 202149:2936 viewsPublished 2021-12Watch on YouTube ↗
Speakers
Tags
CategoryTechnical
StyleTalk
Show transcript [en]

[Music]

[Music] hello everyone my name is iman and today i want to talk about blockchain smart contract security for the b-sides calgary and uh this is the outline of the talk and first we will talk about what is blockchain and we will talk about smart contracts and then we will talk about the importance of the defy and nfts and uh you know smart contact security is important we will investigate why and then we will discuss solidity problems and other than that the talk uh the main focus of this talk is on smart contact security issues while i'm talking about different issues uh i'm i will talk about the secure design patterns also and then i'm going to conclude the talk

and then we will have a q a who am i my name is iman scharfelden and i'm an application security lead at forward security also i'm a phd candidate in computer science and i have published like dozens of papers and i have like uh more than one 1 000 citations and my main top topic for i mean my main interest uh was cyber security or e-cyber security and other than that uh those papers that you can see that are highly cited are related to intrusion detection and visualization other than that i was involved in some projects that were related to smart contract security what is blockchain blockchain actually is a ch is a chain of blocks

you can consider the chain of blocks and each block can contain some transactions you can consider it as a book or as a notebook and each page could be a block and you can write some imaginary transaction inside that like i don't know iman has sent some ether to us or some bitcoin to alex and etc and each page is a block and the whole thing is a ledger or blockchain and why it is very revolutionary the main reason is that for the first time in history we don't need a third party uh to transfer value from person a to person b uh thanks to the algorithms that we are using and uh in the blockchain environment

what is a smart what is a smart contract the smart contacts are agreements that have been codified inside blockchain and here when we talk about smart contracts in this stock we're talking about some solidity codes that are running on the ethereum network and they have some main characteristics some of them are censorship resistance being immutable and being decentralized and uh you know the reason that is the smart contracts are revolutionary is that uh they are you know these are all the reasons like for example censorship resistant uh let's assume that we want to run another website and tomorrow maybe government can come after us and bring down the website and actually arrest us or something like

that and stop the back end and the site will never work again but you can easily write the smart contract code to implement this lottery application and let's assume that this is a simple lottery like if anyone can send some eater to that address which is a smart contract and at i don't know 6 p.m every day the smart contract i would select a random person and deposit all the ethereum to that address and just deduct a small fee a small percentage of the fee and after that no one can stop that if for example the developer didn't provide any stop function for that even the developer cannot stop that along the government and this is

i'm not talking about like criminal aspects but this is something beautiful we can run a code that no one can stop it and because it is running on a decentralized way and other than that we can talk about decentralized finance or defile and you know this is a huge uh thing a defy and is this it is disruptor of financial intermediaries and i believe in five to ten years in the next five to ten years we don't need bank anymore we don't need any banks anymore and the reason is that in a cashless society a smart contract can do everything for us without need without any needs to any human or something like that this is

this could be fully automated and defy uh is a very young sector and you know first i remember like one and a half years ago or two years ago like the transaction into d5 or the total value luck in default was less than one million dollar and now when i'm talking today about d5 is more than 50 i mean the value that is locked in d5 projects is more than 50 billion and here is an example a real world application of a smart contract the name is aav or other and you can see that you can uh deposit your uh here for example you can see usdt usd coin these are stable coins these are some tokens

that can be like on an ethereum network or thrown network or something like that and uh each token represents a us dollar and because of that it is a stable and you can deposit your money into those smart car into those uh defy smart contracts here of it and also you can borrow money and you can see all the rates here the next interesting topic uh that smart contracts is the reason that we have that is nft or non-fungible tokens and nft is uh all about you know tokenizing assets on the blockchain and when we are talking about non-fungible for example bitcoin is fungible it means that if i have one bitcoin and if you have one bitcoin

uh you know these bitcoins the values are the value are the same i mean for example if we want to sell it if the price today is a 50k or 60k uh then they they will pay 50k or 60k to you and also to me but for non-fungible tokens uh there are tokens on a smart contract that is running for example on ethereum blockchain and each token has different value and maybe you ask yourself what are those cats that i put on my slides and here actually these are uh cryptokitties cats uh like one of the pioneers of nfts we have a very like awesome company here in vancouver called dapper labs that they have outstanding job and a

world-class job and they launched two products one is cryptokitty that is launched a few years ago and the other is uh nba top shot and both of them are nft projects and you can see some of those cats uh they have been sold for crazy amount of money like more than 100k and you could and you can read the cats together and these are on blockchain the images are not on blockchain i mean uh you know the attributes of the cats are on the blockchain and based on the attributes the image can be generated and here actually you can see another project called nba topshop and this is actually my account on nba top shot i put like a couple of hundred

dollars into that and now after six seven months like those uh that two or three hundred dollar is worth more than 50k actually and uh you know for example here you can see a moment of lebron james playing rebel basketball and someone has paid 7k for that moment and this is the beauty of nft nft can conquer different worlds such as artwork and collectible words and this is a super nice thing that we have and this is one of those applications of a smart contract in the real world and why is smart contract security is important you know every week or every month or sometimes every day we hear like a news or attack uh that

and those amounts are crazy like there are millions of reasons that we should secure smart contracts we can see like finance smart chain before this is like this happened recently and they lost 31 million dollar and you can see all the news around the world and i believe uh you know these uh vulnerabilities uh you know the heists are are bigger than the real world highs and this is crazy because you know there are some small problems in those smart contracts and those problems can bring us a huge disaster and in this talk we are going to talk about all those problems all the important ones issue solidity actually is a language is an object-oriented language

and that you can use that to develop the smart contracts solidity was initially proposed by uh solidity was initially served [Music] initially proposing august 2014 and you know the language is similar to java and javascript i wish i could say that it's a beautiful language but it's a it's a messy and black pro language and one of the reason that we have so many hacks is the limitation that we have is the limitations that we have in this language and it has like a different object type that we have in like common languages such as integer string hashmap and all those

and ethereum transaction actually if you want to talk about uh like ethereum transaction each transaction has some attributes i'm gonna go over some of those attributes nonce is a number that determines how many transactions were broadcasted by the sender before this transaction and it uniquely identifies the order of transactions sent by the same sender and is it is used to avoid represented execution of transactions other than that gas price is related to the concept of gas gas is a virtual currency unit that the sender needs to pay for executing a transaction that modifies this the state of the blockchain every instruction in the evm specifies how much gas the user has to pay for its

execution gas price then determines how much ether the user is willing to pay for one gas and this can be any non-negative number including zero the total price of the transaction in ether is then determined by multiplying the gas price by the cost of all executed instructions data is an optional string of buys that encodes the smart contract method called this transaction and the arguments passed to the call value is an optional number that determines how much ether is sent along with this transaction chain id is a constant numeric identifier of the ethereum network that allows for distinguishing the network type for example e-t-h-e-t-c and the chain id of e-t-h is one v-r and s

actually there are cryptographic cryptographic values that determine the transaction signature from these ones from these ones one can drive the public key of the sender and from the public key one can generate the ethereum address of the sender two actually is the address in the ethereum network that determines the recipient of the transaction if the purpose of the transaction is creating a new smart contract the recipient is a special address which is zero another special receipt recipient is the address zero extent that is used for burning ether and gas limits also is related to the fact that how much gas you want to pay for that transaction the max reset the maximum gas here are the main uh smart uh contact

security issues um the list is might not be complete but these are the main ones and are the important ones and we're gonna go through all of them arithmetic bugs green currency attack race conditions exception handling rick random generator and the next two ones are related to time stamp dependency and transaction ordering dependence and phone running and the next one is related to the problems in the library's library design flow a zero initial balance assumption and denial of service and the arithmetic bug actually we have this problem in uh like common languages this let's assume that we have a car with an audi autometer and they assume that it has just six digits and if we drive uh

around one million uh kilometer uh or mile here based on the ultimate server then we will have like an overflow and here you can see a function decrease allowance in solidity and this is vulnerable actually because you know about this function we're going to talk about that on the next slide and we're talking about erc 20s but if for example the victim set an allowance for other guy or an attacker as 15 and if the attacker convinces the user or the victim to reduce it to 16 then you know the amount of allowance that the attacker has uh to actually it's a privilege to withdraw ether from another account it would be like a huge number

and the attacker can withdraw all the eater that the victim has and this is actually we're going to talk about that but uh you know we have on this is an integer on the floor we have integer flow we have integer on the floor and uh the way that we can protect our code against these kinds of attack is we can check the results of arithmetic operations for the valid operation and other than that uh we should use a open zoolin framework and there is a library called safemass we can use that to avoid these problems because the library actually can check the validity of the results and can avoid those situations for us we intransi attack uh is another attack

that it's one of the famous one and a decentralized autonomous organization or daw was like a smart contract that was very famous in 2016 and the attacker was able to withdraw 3.6 billion ether like with the value the today's value of ether this is billions of dollars but that was the reason that we had a fork back then actually we had four smart i mean ethereum classic and the ethereum that we have right now and the way it works is that you can see uh you know the reincurrency attack you can see the diagram here and the act like a first what is re-intrinsic reintroduction by itself is not an attack it's like a definition

let's assume you want to send an email to your friend and in between like you can put the email as a draft and go and send an email to another friend and come back and write the or complete or finish the email to the first for the first friend and send that to the first friend and you know this is this called reentrancy i mean in computer science uh but i'm gonna assume that we have a vulnerable bank application that allows you in trancy and uh but you know the problem is that before uh you know it doesn't it changed the states after sending the balance to the users and that is the problematic situation

that we could have here we can see the same problem in like a smart contract the attacker can write a malicious proxy smart contract and here we have uh withdrawal balance that you can withdraw the amount of money that you have already deposited to the smart contract and uh you know here we have a function called fallback in ethereum smart contracts the fallback function is you can consider it such as such an uh you know it is like an event in javascript or something like that whenever a smart contract receives any ether the fallback function would be called and you know the way it works is that the proxy the malicious proxy smart contract calls the initiate or initiates the

withdrawal and in this function the daw actually starts to withdraw the balance and then it starts to transfer the ether back to the malicious smart contract and in the fallback actually you can see that you know we have another recursive call which is like a loop right now and if we call the withdrawal balance again but the problem here is that uh the developer forgot to update balance before sending the ether and because of that still the user has some balance even though we have already sent some meter to the user or the attacker and because of that we can have a loop here and then for example it could have a condition and after the condition has been met

we can stop and they can still near all ethereum that this smart contract has actually and after that it starts to update balance but already the money has gone and you can see you know there are different methods that we can avoid that this is like a serious problem in smart contracts we had many smart contracts with very interesting problem and one of the methods is that never ever update the state of blockchain after uh you know you're sending anything you're calling the send method i mean we have different method to send value uh to another smart contacts or another address we're going to talk about that and the other way that we can avoid that

is that here the problem was that the attack the developer was using at address that called the value function and because of uh you know you can see these functions we have these three functions send transfer now just call the value and you can see this has adjustable gas it means that you know as long as you have gas if you don't set any limit for that it can uh you know execute this uh loop or these recursive calls actually and other you know the developer at least could uh set some limits here or if the developer was using these two i understand another transfer because this fallback has some code inside that it requires more gas and

these functions would fail and then the attacker was not able to attack actually and other than that uh you know you can see different behave behavior on their in case that we have any error these two functions return false but these functions this address.transfer returns an exception and this exception actually reverse the transaction we have also uh race conditions in erc 20 tokens and the reason is that we cannot synchronize the states and in ethereum blockchain and what is erc2a i believe you have heard of unheard uh you have heard names of different tokens on new york city i mean on the ethereum blockchain we have many such as vets or uh prior to that bmb was even

on the erc and was an erc token right now it has its own main net uh you know the way it works is that erc is ethereum request for comments and these are like rfcs in network and erc20 is an interface that if you implement that you can easily create your own token under five minutes i don't know like for what sec token or forward second anything that you want and uh you know that interface to implement the interface there are different functions and here you can see one of the functions approved and the approve function actually uh if like anyone for example if i have an ethereum at this you know if and if i

approve uh like any value and any other other address that address can withdraw that value out of my account actually and here we have elise and mallory and as you can see alice said you know let's assume that mallory is working is a developer that is working in another country and alice wants to pay her 10 tokens and set the allowance of the mallory to 10 and then actually uh mallory convinces the alice that you should set it 15 because i've done more and you should pay me more and maybe mallory uh wants it wanted to do that and she can set like the approve to 15 and but mallory can use you know a race condition scenario here

index and you know we draw 10 token immediately before alice calls the approve function and then mallory can again call uh transfer from a function and we draw 15 more tokens and now the mallory was able to withdraw 25 tokens instead of 10 tokens or even after that 15 tokens and this is like a classic uh race condition scenario in erc 20s and the ways that we can you know stop this is that these are the two recommended ways we can reset the yellow ones to zero or we can implement safe methods for increasing and decreasing the elements and that can help us that can help us actually exception handling this is another scenario we have

i mean we had a king of ether smart contract which was a ponzi scheme and the way it was working was that uh you know at each moment we could have one king and anyone could be the king and the king would own the pot and in order to be the king you should send more ether than the previous person other than that one of the rules in the game was that when we are changing the king for example first user could send a one eater to this to this smart contract responsive scheme and the smart contract could set him as like a new king and the second user in order to be the king

could deposit to each other and then you know in order to alleviate the pain of this first user the smart contract would compensate some amount of money back to him and would set the user to as a new king but here is the catch in their code they didn't check for the exceptions that could happen and the exceptions we were talking about that if for example we use that send function uh then uh if the smart contract let's assume that this second user is not a real user it is using a proxy smart contract then in the fallback function this user can put some malicious code or even some other code and then let's assume that king of ether is

using that send function because uh now it should execute that fallback and it doesn't have enough gas then it will fail but they were not checking that it is failing or not then the user one uh would not be compensated and you know there would be that is a loss for user one and the other problem was that user two would be the new king there would be no problem but the owner of this smart contract would down the compensation amount of to user one which is not fair then the owner of the smart contract would be this attacker that you can see here because you can uh you know he has some profit that he can make here

and always we need to check for exceptions uh and handle the exceptions correctly when we actually encounter these situations the other problem that we see in smart contracts is that uh now the problem is that we don't have a real random number generator and uh you know we have a pseudo random number generator and you know the seat the other the the other problem is that the seat could be predictable and that is a huge problem because if we want to base our decision on the unchained data such as block number or block id or i don't know the time stamp all of them are predictable and can be seen by that can by attacker

and here we have a lottery smart contract as you can see and the weak team actually can deposit some ether and the attacker is the owner of this smart this is a smart contract also and the the attacker also can deposit some ether now the owner of the smart contract can call a function which is call the function name is choose the lucky one and whenever like in in a normal world whenever the owner call this a smart contract i mean this is a smart contract function then without any problem one of the users could be randomly selected and i can have all the money but in this scenario uh you know the attacker can write a

smart contract as a proxy smart contract and deposit ether using that one and the attacker is also the owner of the smart contract and have a loop here and evaluate the random condition i mean timestamp or the block number or anything like that and whenever it was in his favor he could call the choose the lucky one function and he can have all the money and this is a huge issue actually and the the way that we can avoid that is we can use a secure random generator uh in using one of the oracles such as chain link chain link has vrf verifiable random function and then we can be safe actually and the oracles they're providing data

from off chain to unchained and they're very useful and practical and the other problem the smart contracts is uh like some of the smart contracts is dependent on the timestamps and this is bad actually and the reason that this is bad is that the miner can set the timer stamp you know the miner cannot set like an outrageous uh timestamp that he wants but you know there is like a 15 seconds toleration there and uh let's assume that that we have a ponzi smart contract that anyone can invest some ether inside that and you know the way that it works is that the last person who has invested in the smart contract would on the pot

uh it needs like 30 seconds to then after 30 seconds if no one uh sends any ether to this smart contract then uh you know the owner can withdraw all the parts and here the malicious miner can wait for like well for one exact moment that for example for 15 seconds no one has sensed anything but they have a lot of 30 seconds and then the malicious miner can set the time and the time stamp with specific time stamp and win their smart contract actually and reset the investments and then deposit the ether actually the function reset the investments can be called by the owner of the pot and after that it's easy to uh i mean

retrieve all literature that is it is in this smart country and transaction ordering dependence and transforming is another problem the other problem is that developers they assume that uh like or transactions order are fixed and cannot be manipulated but in fact uh whenever uh you know it's the transaction works in this way that you can sign a transaction and send it to the nodes and there would be a mempool and all transactions are there and the miner when the miner finds block or mines a block then the miner can reorder the transactions in any way that he wants and let's assume that we have a puzzle solver a small contract that for example i don't know a very

specific problem in physics or science and when everyone uh are challenged to solve this to achieve some meter and the victim is a like a smart guy he submits the solution to this smart contract and here the miner uh let's assume the miner finds the block or wants to mine the block and now the miner can see all the transactions in memphis and can see the value that the victim has submitted and can check that the value is correct and then reorder transactions and put his transactions in front of victim transaction and receives the reward because of that we shouldn't depend on the orders of the transaction and we should take care of that the other problem is that

library design flaws and you know valid library is one of the problem you know one of the vulnerable smart contracts that we had and the way it works is that we can use different libraries on the ethereum blockchain but the problem is that whenever a library has a problem and we are using that library the problem is that we are trusting that library and because smart contracts are immutable we cannot use another version of that library and then our smart contract would be vulnerable here actually the problem was that uh you know the developers of this smart contract they forgot to initial valid and someone else actually and the people were using this smart contract and

you know the init valid was executing in the context of those smart contacts not them the context of the father or parent the smart contract and after that you know someone finds that and called the init valid and changed himself to honor and after that he killed the smart contract you can actually destroy a smart contract from blockchain by calling a specific function and the problem here was that if uh you know you will kill a blockchain or terminator not killable blockchain clear smart contact or chairman a smart contract after that actually no one uh can find that the smart contract that library that we are using and all those smart contracts that are using this library are

frozen after that and this is a huge problem and right now there are hundreds of thousands of ether are locked due to these kinds of bugs and the other thing is that we should never assume that uh we have an is a zero initial balance and this is a simple a simple callback fallback sorry function and as you see as you can see it's payable and as you can see like the here we have a required it's like an assertion that checks amount phrases more than this balance and then it continues the developer doesn't know that uh you know the developer assumes that whenever we send ether uh to a smart contract this function would be called for 100 but this is not

true there are some cases that this function this fallback would not be called one of them is uh when a miner mines a block the miner can send ether to a smart contract then this function would not be executed the other way is that whenever we want to terminate a smart contract we can send their like the remaining amount to another smart contract and you know that is the the other way that if we use that method this fallback would not be executed this could i mean this might not be a huge issue but always uh please always know that it is possible that you send i mean and you can send some ether to a

smart contract without fall back being college denial of service uh you know we have two types of main uh two main types of denial of service the first one is exceeding block gas limit and the second one is the transaction river assume that we have a smart contract that now we have selected like a winner or something like that and now we need to refund the remaining balance to the owners of those balance and here you can see there is a loop there is no problem if you see the loop like it starts it goes through all the addresses and start to transfer the value and to the to those addresses the remaining balance that they have but the

problem arising for example for 100 user there is no problem or 1000 user but they assume that i don't know 10 000 users or twenty thousand users are involved in this smart contract and you know each instruction that is running in this code costs us money and uh even the block each block has a limitation of like the gas fee like uh i don't know we cannot have more than 12 million gas or something or 15 million there's a limit that they update every year and let's assume we have that amount of users that we over i mean we over we go over the limitation of the block then we could never execute this function and

it will stop forever here and this is a very bad design pattern actually you shouldn't use this pattern you should use this pattern this uh sorry i've actually put all the images in this one slide but you shouldn't use this pattern because this is very costly and on the other hand you should use this pattern and each person should be responsible to claim the refund and now we don't need any loop and then there will be no problem the other problem with this pattern is that we could have some malicious guy that send us some uh like peter and he can use the proxy smart contract and as you can see he can put like a revert

in function in that smart contract and whenever we want to refund the remaining balance forever we will be stuck because because always the transaction would be reward but this pattern saves us and secure design pattern actually these are some tips and tricks uh for example we should check all preconditions before any calls to external smart contracts and updated states variables before the call we should use require to validate inputs because require refunds all the remaining gas we should make all important function possible because in case of any attack or any problem we should be able to pause that function and we should use safe mass to avoid integer flows and underflows we should avoid using timestamps in

conditionals and also we should check the results of any calls and or transfer because of the reasons that i was talking about the exception handling slide and we should always choose the most strict modifiers available and other than that this is good that we can always uh you know out of all those attacks that we have seen many of them the attacker was using a proxy smart contract one of the best way is to avoid the smart contracts call our smart contract you can see one way which is which you shouldn't use this way because it will fail in some cases and we have a function check for human here we can check the size of code of

the address on that at this smart contract addresses they have some code because of that but like human addresses they don't have code because of that there's there should be some value but there is one case that can bypass this and if a smart contract call another function inside the constructor didn't fail actually and this method is not good but the proven method is this one we should put uh like require message.sender equal to tx origin and you know tx origin is the person who is in who has initiated the transaction and if the sender is equal to the tx origin it means that it's not a smart contract but the problem is that when we do such

a stuff then uh multi we cannot have uh multi-stick wallets and they would fail because multisig wallets is not supported natively by ethereum and we need some smart contracts in conclusion i believe the smart contracts are going to change the future and also d5 and nfts are so big and they're going to change our world forever and it is completely visible that if there is a bug in a smart con in a smart contract that is handling and a d5 protocol or an nft project it can be devastating and other than that i believe uh currently developers are not trained very well to quote securely and that is one of the reason that we can see

a lot of hacks around and a lot of money or is being stolen and these are my references other than that i'm ready to answer the questions

okay let me please share my screen back here [Music] okay i can see a few questions here first of all uh i mean the last question is that uh how can we prevent complex reintendency attacks such as cross-functional intensity attacks the thing is that open zipline uh it has provided you you need to use mutexes and there is something called re-intransiguard and uh there is a modifier called non-reentrant uh you can use that to define your function and uh that by using that you can prevent that and the other question safe mass actually safe mass is for open cipillin but the thing is that from if you're from solidity version 0.8 uh they have integrated that safe mass

inside the solidity and because of that we can have a fewer problems and uh before going for the next question actually you can see our carriers mentorship page on the background and you know you can join us uh we have a cool company called uh forward security and we have some positions for you and you can find the website there actually and other than that ralph has asked that uh is the how we can identify ponzi schemes those are not cryptocurrencies those are some smart contracts and by reading their code is obvious but prior to that you know they're gonna advertise themselves as uh like a ponzi scheme and other than that what are what other languages are used for smart

contracts aside from solidity c and c plus plus and rust these are the other languages on other you know it depends on the blockchain you know for example for solana you can code using c or rust and but also for polka dot you can use you can use rust and other than that for cardono you can use haskell but i haven't seen anything with java but yeah i mean other than solidity rust is the second language that you can use actually and what is the dap the app is like a distributed application that is running over like ethereum or any other blockchain that is supporting smart contracts and you know majority of them are a

smart contract that is running on that blockchain and uh this is it thank you very much guys and have a nice day bye

[ feedback ]