Best Practices for Secure Smart Contracts

EDCON 2021 · 29 Aug 2021 · 13:18

Michael Lewellen of OpenZeppelin describes smart-contract security before and after deployment. He connects lessons from reentrancy exploits with reusable contract libraries, internal review, audits and bug bounties, then explains operational monitoring and administration through Defender as contracts become more complex and interconnected.

Speakers

Topics

From EDCON 2021, hosted by EDCON.

Transcript

hello everyone my name is michael lewellen from open zeppelin i am the uh project manager for the audit team uh and i'm here to share some best practices for smart contracts in a quick 10-minute format um so without further ado i'm going to go ahead and get started uh first of all for those who haven't heard open zeppelin is a company that has been in the ethereum space for many years now we're focusing on protecting the open economy we do that through our contracts library security audits and several products that we're coming out with and we've worked with a lot of big uh parties in the space including compound ethereum foundation coinbase and many others um our focus is on three different areas we are first of all of course have the open source contracts library which we

encourage uh anyone using standards to make use of for erc20 721 and many others i'll talk about that in a second we have our audit team which perform audits for many of the big projects out there and we have a new tool that has come out called defender which actually lets you use security operations and i'll talk about all three of these in more detail but these are the three most important legs on the part of what we think are critical for securing smart contracts so first i'm going to do a quick history lesson because i think it's understand important to understand why we got here um the dow hack of course is where everyone started thinking about security and it's only become more important since so it was an early uh you know decentralized autonomous organization

meant to do crowdfunding for ethereum development projects uh on june 17th that dow suffered a hack of 11.5 million ether or 50 million dollars and this was uh quite a stink the reason this occurred is there is an ability to exploit a reentrancy bug that allowed the attacker to call the send function before balances were updated in a recursive manner and essentially bleed the contract dry this attack actually prompted a community hardworking ethereum to return those funds to users which resulted in the contentious split of ethereum classic and we all know that from there um you know this continued to be kind of a source of uh critique for the ethereum you know community primarily because it

was kind of an exception to the rule of censorship resistance and immutability and something we certainly do not want to repeat and have not repeated since uh but that also means that there is no you know source of protection and you need to know these sorts of bugs and be able to protect against them so very quickly an example of that bug is you can see a simple function you can see that there is a check for the amount of this message.sender to see if their balance is correct for the amount they want to withdraw and then it calls the message.call.value function which is a fallback function and what an attacker could do in this case as a simple example is call the withdrawal function again because this actually delegates call um permissions to the attacker contract for a brief moment and rather than returning quickly and

then decrementing the balance uh it actually will just call again call the withdrawal function again the balance has not yet been decremented which means it can continue to do withdrawals very simple example but this gives you an idea of the sort of attack that was possible and uh part of this was because the smart contracts were not written with this sort of attack in mind uh and the solution to this is to ultimately use smart contracts that have been written for that whether that is writing your own smart contracts with a high degree of certainty or preferably using an existing set of smart contracts so with open zeppelin we have a battle tested open source library of smart contracts for ethereum and other evm blockchains this includes token standards we all know like erc20 721 erc1155 um and then also many extensions and

properties adding in possibility mintability snapshots and anything else you might want to do with the set of smart contracts uh or or erc tokens we also have the ability to do upgradability so you can upgrade your smart contracts quickly uh we have access control so not only making them honorable but also having specific roles for mentors for delegators for burning et cetera uh we have governance which we actually just added a new uh set of governance contracts from uh compound governor bravo uh we have many different utilities uh some automated plug-ins for hard hat and truffle and then also some security modules that specifically address reintroduced scenarios so very quickly to prevent some of these exploits you could either use a

reentrance cigar it will add a function modifier on top of a function to make it impossible to actually have the internship on top however that doesn't work for some payments because you might actually need for example in your c20 token to do some balances on another contract before returning control so you might also use a pull payment method which basically means that someone will initiate a withdrawal it'll be set aside in an escrow and then someone can withdraw it again in a separate transaction by virtue of having a separate transaction for internship is impossible and out by the way there are links on the bottom of every each slide that i encourage you to go to for more details um so second of all you know after contracts you also want to get audited because even if you use a contract there might be many changes you make or

different um logic you add in and you definitely want to get that audited so we're one of the top audit firms in the space um although i would encourage you to get an audit anywhere you can even if it's not us and that process usually goes where you submit the code it's available from some frozen commit we look through it we provide a list of vulnerabilities in a report and then you fix them and then we do a final report that you can then publish to say here are the issues that have occurred that they have been fixed and you go from there and typically getting reoccurring audits is a good idea every time you have a big release so that's important but there's many other things you should do outside of an audit for quality assurance um especially because auditors are in

limited supply um i know we're back logged out for the year i know a lot of other firms are in the same position so uh having a qa process within your team or within um your company is very critical so first of all having discipline git flow having prs getting them approved by someone else always having reviews occurring is very important as well as knowing you know what changes occurred for what reason where were they which which changes have been audited which ones aren't that's all very important um adding that spec comments to all contract code and keeping it clean so it's very clear what's going on having documentation for the architecture and relevant protocols so people know how to use them and people understand what's going on uh having an exhaustive suite of tests

using either hard hat or truffle or anything else that you can um build but aiming for 100 code coverage especially because you want to be able to test against changes you make and know that the assumptions are still correct uh using code libraries open zeppelin but also genosis multisig and many others uh and specifically importing them through npm packages or something similar so that you're not copy pasting code and potentially introducing vulnerabilities in that way and then finally just doing your own internal security reviews taking time aside to just focus on that and then run bug boundaries regularly to ensure that if someone does find a bug in your code outside of your team they're encouraged to report it to you and get paid rather than having to monetize that uh through a hack of their own and potentially

causing a lot more damage so well the final tool throughout there is kind of your post deployment security once you've secured your smart contracts and you've gone through all the checks necessary when you deploy them how you deploy them and how you manage them after that's really important um so we have a tool called opensup when defender does ops automation and secure app infrastructure first of all we have an admin interface for contracts administration that means you can you know do deployments with multi-sig arrangements and you can use your own keys through metamask or hardware wallet or use our own hosted key solution whichever you prefer we also have a relayer which does that hosted key solution but it also does reliable transaction delivery so you don't have to worry about gas fees or um you know resubmitting it make sure it gets

delivered on time especially if it's it's important to get that out there in a timely manner we have auto tasks which are basically just serverless code for automated tasks and opportune logic so if you run some scripts on a recurring basis up to the smart contracts or you want to be able to respond to things immediately auto tasks are really handy for that we also have sentinels which monitor transactions and events and then triggering notifications and auto tasks based on those events so if you have specific metrics you want to be aware of immediately that's a great tool to have and then finally advisor which contained a lot of blockchain best practices so an example i'll throw out there is an exploit that occurred with urine y divult um they had an issue where um basically someone was able to use a

flash loan to manipulate a pool uh and leave the contract of a lot of money uh so you can read the x the postmortem from urine in more detail but basically uh this attack was noticed because there was a complex transaction pattern occurring one of the developers made note of that and then immediately moved into response so they were able to mitigate it by pausing deposits within 11 minutes uh so you can see that time was really crucial here they managed to save millions of dollars by responding quickly and many millions could have been saved if they could respond even quicker in an automated way so if you look at the metrics really notice you know they manually noticed hey there's a large transaction going on a lot of gas is being used there's you know withdrawals and deposits occurring

very quickly and we're noticing that a lot of funds are leaving the smart contract quickly these are all things that you can automate in a script to notice uh and respond to quickly so using our tool you can put together a very um you know robust solution that can respond and you know i think our tools were going to do this you could do this with your own scripts but i think in any case these these are sorts of things you should have set up and be able to respond to if you're managing a large smart contract with millions of dollars um so first have an admin interface that deploys uh canosa safe for a multi-sig wallet that then manages the vault contract uh that contract has a lot of different functions that are admin specific um so hopefully lock down uh and then you'll use a sentinel to

monitor the function call and events and when that the function calls uh are are basically you know triggering things you want to know about you can get that in an email go to slack or discord telegram data dog whatever you prefer um so specifically let's you know trigger signal for high gas if we see a lot of gas being used in transaction um far more than as usual then we know that something strange is occurring that could be an attack so when we see that we want a sentinel to trigger and we want to potentially also invoke an auto task an auto task could do uh more custom code execution which again it could be triggered also by a scheduling or web hook but in this case it'll actually be invoked by a sentinel um and it will determine you know

through those high gas transactions is there some sort of loss like is there a loss occurring in the vault contract that we might consider to pack and if so let's send an immediate alert notification uh to the team if it exceeds that threshold then the team knows that they need to react quickly um and in another scenario let's say that we also want to be able to respond without a manual intervention let's also trigger a mitigation transaction so using the relayer which does private transaction delivery we can actually send a pause function to the vault contract and immediately pause it in response to that so this is kind of a robust solution for responding to these sort of events uh urine's already a defender customer and we also have a lot of other teams in the space using this tool set to

manage your smart contracts in an easier manner and also uh have better security especially in post deployment we're now into an area where flash loans and um economic attacks are becoming more common in addition to just normal logic bugs being exploited so having a strategy to respond to these sort of incidents is crucial so in summary there's a quick 10 minute talk uh we should be using simple modular code built with ethereum security in mind opens up in contracts is one of them as a library but you should also keep this in mind when either using other libraries out there or writing your own code in a way that should be easy and simple to understand and always have security in mind when you're writing you should be doing audits and bug bounties along with an internal qa process to ensure your smart contracts

are secure especially as you make new changes and then finally you need to have an operational security practice in mind and be able to to uh plan for incident response because when you have a lot of money uh it's just going to be inevitable that someone tries to take it um so it's critical to mitigate unforeseen attack factors uh there's a lot of things that we will notice you know in pre-deployment but post deployment there's always something that might be this so ultimately what we're seeing at open zeppelin and throughout security and space is that smart contract systems are growing in complexity and integration with other protocols that could also add in new attack vectors are increasing defi is composable which means that security is also you know shared amongst different systems in some cases so really what developers need to do is just practice

good security both before and after deployment and always keep it in mind so that was a talk very quick very rapid um but if you are curious to learn more i highly encourage you to check out open zeppelin um all the tools are listed here as well as a forum where you can ask questions and documentation to understand how to integrate it and if anyone is curious i highly encourage you reach out to me to learn more about our audit practices and just general good security practices um available on twitter linkedin and by email and that is it for the talk