diff --git a/custom_theme/partials/footer.html b/custom_theme/partials/footer.html index 4eaa379af..aa75dc3aa 100644 --- a/custom_theme/partials/footer.html +++ b/custom_theme/partials/footer.html @@ -103,7 +103,7 @@ const primaryNav = document.querySelector(".md-sidebar--primary nav"); if (primaryNav) { const closeNavViaKeyboardNavigationLink = document.createElement("button"); - closeNavViaKeyboardNavigationLink.className = ".close-sidebar-link"; + closeNavViaKeyboardNavigationLink.className = "close-sidebar-link"; closeNavViaKeyboardNavigationLink.innerText = "Close Navigation" closeNavViaKeyboardNavigationLink.addEventListener("click", (e) => { e.preventDefault(); diff --git a/mkdocs.yml b/mkdocs.yml index 187a55d27..95e910f7a 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -36,6 +36,7 @@ extra_css: - assets/stylesheets/bootstrap.min.css - assets/stylesheets/extra.css markdown_extensions: + - admonition - pymdownx.highlight - pymdownx.superfences - pymdownx.tabbed: @@ -65,7 +66,6 @@ plugins: htmlmin_opts: remove_comments: true js_files: - - assets/js/dashboard.js - assets/js/os-detector.js css_files: - assets/stylesheets/dashboard.css diff --git a/src/.pages b/src/.pages index 396ef2758..20f7120c2 100644 --- a/src/.pages +++ b/src/.pages @@ -5,4 +5,5 @@ nav: - unleashed - boxes - blog + - security - community \ No newline at end of file diff --git a/src/security/.pages b/src/security/.pages new file mode 100644 index 000000000..d9e9e8d6d --- /dev/null +++ b/src/security/.pages @@ -0,0 +1,7 @@ +nav: + - Home: index.md + - Secure Thyself: secure-thyself.md + - Security Harden ALL The Things: harden-all-the-things.md + - What Could Go Wrong?: what-could-go-wrong.md + - Hands On: hands-on.md + - Tools & Resources: tools-and-resources.md diff --git a/src/security/hands-on.md b/src/security/hands-on.md new file mode 100644 index 000000000..ba2e864bf --- /dev/null +++ b/src/security/hands-on.md @@ -0,0 +1,15 @@ +# Hands On + +In this section we get hands on, exploring real vulnerabilities and their associated mitigations. We also start to explore a number of tools and services that are a critical part of the Dapp security lifecycle. + +Note that the goal isn’t meant to be 100% comprehensive, but to start building your intuition and add new tools to your arsenal. This is also a “living” collection so we’ll be adding new vulnerability examples as and when they are discovered. We also very much welcome contributions! + +## Introducing the Web3 Security Starter Box + +You can get started by going to [truffle-box/security-starter-box](https://github.com/truffle-box/security-starter-box) and following the steps in the accompanying [README](https://github.com/truffle-box/security-starter-box/blob/main/README.md). + +The repo uses a monorepo wherein each workspace is a standalone project. + +- **hackd-dapp** - A tutorial on how hacked code or front end deps can be bad for your health and wallet balances +- **vulnerable-defi** - Examples of defi (courtesy of DamnVulnerableDeFi) contracts with vulnerabilities with different tests and examples of mitigation +- **common-contracts** - A collection of vulnerable contracts with accompanying mitigations diff --git a/src/security/harden-all-the-things.md b/src/security/harden-all-the-things.md new file mode 100644 index 000000000..1ac4af4c8 --- /dev/null +++ b/src/security/harden-all-the-things.md @@ -0,0 +1,44 @@ +# Security Harden ALL The Things + +So you’re ready to start writing code? Hold on just one moment! Building on “[Secure thyself (aka the basics)](/secure-thyself)”, here are some important practices to begin establishing your project’s security posture and get it off to a secure footing. + +## Assemble your (virtual) security team + +- Wherever possible find a trusted forum in which you can share your ideas and get input on your code (high-level design, choice of tools, libraries, etc). This is particularly important as your project begins to grow in complexity. And just to be clear. This doesn’t mean asking for advice on Reddit or Stack Overflow or public forums. If you do, you need to understand the risks associated with doing so. Try to find one or two people you really trust and have experience and work with them if at all possible +- Budget permitting, bug bounties (via platforms such as [Immunefi](https://immunefi.com)) can be a great way to incentivise people to work on your codebase for a reward/payment +- Depending on what’s at stake (and your budget), you might also want to consider getting your code audited by a 3rd party to surface the more subtle issues / attack vectors that you might have missed. If you do decide to go this route, note there can be a sizable lead time so reach out to prospective auditors early. Also consider a [TURN Token](https://consensys.net/blog/diligence/smart-contract-auditing-with-turn-token/) if you’re short on time and want to jump the line + +## Secure your environments + +- In CI/CD environments there are many ways to secure these values and it's outside the scope of this to list them all. Be very wary of keeping private keys, etc on CI servers even as secured keys +- Use version control and only commit/build/deploy code from tested source code +- Consider keeping repos private +- Be very careful with commit history and what you commit. Remember, once it’s on Github, it’s very hard to remove it and even if you do, it will most likely have been indexed and harvested/analyzed before you can run a history rewrite script to remove it +- Ensure you don’t commit secrets to public repositories and have your information harvested +- Consider using anonymous commits in Github to obfuscate your git details +- Use a [good git ignore file](https://www.toptal.com/developers/gitignore) to not commit any environment or dotfiles you are using in your project +Be aware of attack vectors such as [supply chain hacks](https://www.crowdstrike.com/cybersecurity-101/cyberattacks/supply-chain-attacks/) + +## Prepare to test, test, and test some more + +- Testing your code often and in an automated way can give you some level of comfort that your code will behave the way you intend it to. With the caveat that behaviour can only be guaranteed by the test cases +- There are many facets to testing: + - Testing your code at a unit level, low level functionality is tested in isolation + - Testing your code's behaviour at a higher level. Does it perform this function with these params as I intend? + - And sometimes something in between. Searching for edge cases you know could be problematic + - There are other testing methodologies you can use like fuzzing: https://docs.scribble.codes + - Load and Automated Testing. These are more likely to be considerations for a front end/DAPP more than smart contract code but should definitely be considered +- Most of these testing ideas are across the board, from your solidity code, deployment scripts and the actual front end dapp you will write to interface with them +- Test your deployments work as expected. Also test what happens when you want to run updates or subsequent deployments/fixes +- Ensure your deployment platform/provider is secure and is resilient enough to handle attacks + +## Prepare to monitor + +- Security is a journey, not a destination. You can’t just do security once and then forget about it, things change, new exploits are coming out weekly. You need to monitor your site and code for possible issues +- You also need to know how your application is behaving. Look at tools to watch the logs of your smart contract and or the web application to ensure they are working properly +- Use a dashboard tool to analyse/collate this information for your smart contract +- Tools like [OpenZeppelin's Defender](https://www.openzeppelin.com/defender) try to do this as an all in one solution and are worth looking at + +## Plan for worst case scenarios + +While it might seem pessimistic, modelling worst case scenarios will allow you to start thinking about mitigations early in the project’s life (vs a panicked response when the SHTF). It will also help you sleep at night if you’re lucky enough to have your project moon 🚀 diff --git a/src/security/index.md b/src/security/index.md new file mode 100644 index 000000000..1ea29cabd --- /dev/null +++ b/src/security/index.md @@ -0,0 +1,55 @@ +# Truffle+Security + +![truffle+security logo](./truffle-plus-security-sm.jpeg) + +Welcome to Truffle + Security, our living guide to helping individuals and teams building on web3 get, and stay, secure. Contained within, you’ll find a range of best practices on securing individuals, teams, environments and code. + +We’ve built this guide to breadth-focused (which was something we felt lacking in the ecosystem), with the goal being a holistic appreciation of all aspects of web3 security. It’s also designed for technical and non-technical users alike, with clear labels specifying the audience a given section is intended for. + +For technical users (such as developers, auditors, etc), while we do cover common contract vulnerabilities and mitigations, broader attack vectors, and security tooling, we do not try to be completely comprehensive. Instead we aim to fill in knowledge gaps and provide links in our Tools & Resources section to enable you to go deeper on a given topic. + +Lastly, as stated, this is very much intended to be a “living guide” and we’d love [feedback](https://github.com/orgs/trufflesuite/discussions/categories/security) or contributions. With that let’s dive right into our manifesto on web3 security. + +## Manifesto on Web3 Security + +!!! quote "Manifesto on Web3 Security" + + Dear web3 builder, + + At Truffle, it’s our ongoing mission to create best-in-class tools and services that make the decentralized application (dapp) development process as simple and efficient as possible. While security is always at the forefront of our minds in everything we do, a confluence of factors have led us to decide it was time to double down on that commitment. + + These factors have included, although are by no means limited to, the following: + + - **More at stake** - projects (and their underlying contracts) are storing larger amounts of value making them [increasingly attractive targets](https://www.theverge.com/2022/7/7/23199148/web3-lost-2-billion-hacks-flash-loan-certik-cryptocurrency) + - **More hacks** - sadly it’s often feels like hardly a day goes by without a hack or exploit [making the headlines](https://rekt.news/) + - **More developers** - while this is an undeniably positive trend, it also means there’s new people entering the ecosystem with minimal experience with securing their projects + - **More complexity** - increased complexity (scaling solutions, bridges, etc) is resulting in more attack vectors + - **Loss of Credibility** - The more hacks and money stolen feeds into the media’s negative portrayal of the blockchain industry. + + So what does this commitment mean? Firstly, we are committed to being the most secure suite of tools in the ecosystem. This might not mean you use Truffle for every stage of your workflow (although of course it’s fine if you do), but if we’re successful, we’ll make it as easy as it can be to ensure that every aspect of your project is adequately hardened. We’ll be doing this in a number of ways: + + - **Content** - As this section highlights, we’ll be creating new content focusing on a range of areas from securing yourself and your team in more “traditional” terms through to something we’re calling the 12 Factor Dapp in a nod to [the SaaS equivalent](https://12factor.net/) + - **Tooling** - We’ll be reviewing all our tools to see how we can appropriately surface all the major aspects of the security lifecycle into the workflow + - **Integrations** - We’ll be partnering with teams across industry (starting with [ConsenSys Diligence](https://consensys.net/diligence/)) to more seamlessly integrate their tools and services into the Dapp SDLC + - **Community** - That includes you :) We’d love to start the conversation around any ideas you might have on improving the status quo + + As mentioned, we’d love to hear your ideas. If anything jumps out, head on over to our Github Discussion on this topic and share your thoughts. Beyond that, feel free to dive into the content below and let's make hacks, exploits, and vulnerabilities a thing of the past! + + Yours securely, + The Truffle Team + +## Sections + +### Securing Yourself and Your Project + +- [Secure Thyself (aka The Basics)](./secure-thyself) +- [Security Harden ALL The Things](harden-all-the-things) + +### Understanding the Risks + +- [What Could Go Wrong](./what-could-go-wrong) + +### Hands-on + +- [Web3 Security Starter Box](./hands-on) +- [Tools & Resources](./tools-and-resources) diff --git a/src/security/secure-thyself.md b/src/security/secure-thyself.md new file mode 100644 index 000000000..85d844e42 --- /dev/null +++ b/src/security/secure-thyself.md @@ -0,0 +1,35 @@ +# Secure Thyself (aka The Basics) + +As the saying goes _"security is only as good as the weakest link”_ so what better place to start than with securing yourself and your team. This document goes back to the basics and outlines some of the good security practices you should personally strive to implement throughout the life of your projects. Also remember that security is very much a “journey”, so be sure to revisit and reassess regularly. + +## Secure your data + +- Use a password manager such as [1Password](https://1password.com/) or [Bitwarden](https://bitwarden.com/) with a healthy amount of entropy for the generated passwords +- If any of the aforementioned passwords need to be shared with your team, consider a team-based version of the above. In other words, never send a password in plaintext. Oh and never share your private keys or mnemonics via any medium, period. +- Use a second factor (2FA) for all logins associated with any service used in conjunction with your dapps. +- Keep (securely stored) offline backups +- Use a hardware wallet, such as a Ledger or Trezor, for important accounts +- Encrypt your hard drive. This is inbuilt into most modern operating systems and is easy to set up. Ensure you backup your recovery key safely. +- Keep your software up-to-date, your OS patched, etc + +## Working with secrets + +- During the life of your projects it’s likely you will be using secrets, such as private keys or mnemonics, as part of certain workflows. Create and use a separate account when doing this (with the necessary amounts of test currency) to avoid costly mistakes +- When deploying your contracts to public networks, tools like [Truffle Dashboard](https://trufflesuite.com/docs/truffle/getting-started/using-the-truffle-dashboard/) allow you to keep your keys in a wallet like [Metamask](https://metamask.io/), which in turn allows you to use your hardware wallet(s) +- Use dotfiles and environment variables as an alternative, but be careful with how you manage these. Using [.gitignore](https://git-scm.com/docs/gitignore) files is a viable option to stop these being committed inadvertently +- Where possible use multi-signature wallets, such as [Gnosis Safe](https://gnosis-safe.io/), for team-based transactions + +## Secure your workflow + +- Irrespective of your role, you’re going to be establishing a number of workflows (most likely leveraging 3rd party services) between the members of your team. Recognize that each of these introduces additional attack surfaces to your project and should never be blindly trusted. Think about the implications if a given service were to be compromised +- Adopt the [principle of least privilege](https://en.wikipedia.org/wiki/Principle_of_least_privilege) when granting permissions to users, processes, or 3rd party systems to ensure they can “access only the information and resources that are necessary” + +## Trust but verify + +- Be prepared to scrutinize any form of external contribution to your project(s), however seemingly small. For example, in the case of contributions to your code, changes to dependencies or core elements of your codebase could easily inject something malicious +- The same goes for 3rd party collaborators with whom you have limited working history, and by extension, limited trust. As outlined in the next section, scams can come in many forms + +## If it’s too good to be true... + +- Discord and Twitter are full of people masquerading as others/friends/celebrities who will offer you free mints/airdrops and all manner of enticements to make you send ETH or do funky approvals with all your tokens. As always, if it sounds too good to be true, it most certainly is +- Taking this one step further, it’s arguably sensible to turn up your “skepticism radar” to its highest setting with all your online interactions. Phishing attempts have gotten steadily more creative / advanced as the space has evolved and new patterns of attack are emerging daily diff --git a/src/security/tools-and-resources.md b/src/security/tools-and-resources.md new file mode 100644 index 000000000..b92955c0f --- /dev/null +++ b/src/security/tools-and-resources.md @@ -0,0 +1,26 @@ +# Tools & Resources + +In this section we aggregate a collection of security focused guides, tools, and registries. As with everything in this guide, it’s designed to be a living list and we very much welcome suggestions or contributions. + +## Smart Contract Security + +- [Smart Contract Weakness (SWC) Classification Registry](https://swcregistry.io) - These SWC codes are used in Mythril and Scribble to classify issues with your Smart Contracts +- [Ethereum Foundations’s guide to Smart Contract Security](https://ethereum.org/en/developers/docs/smart-contracts/security/) +- Halborn’s series on DeFi security + - [Part #1 - Data Security Vulnerabilities](https://halborn.com/defi-security-part-1-data-security-vulnerabilities/) + - [Part #2 - Consensus Vulnerabilities](https://halborn.com/defi-security-part-2-consensus-vulnerabilities/) + - [Part #3 - Smart Contract Vulnerabilities](https://halborn.com/defi-security-part-3-smart-contract-vulnerabilities/) +- [Ethereum Smart Contract Best Practices](https://consensys.github.io/smart-contract-best-practices/) - Written by ConsenSys Diligence this reference gives you a lot of good information to start you on your journey + +## Tools + +- [Diligence Security Tooling Guide](https://consensys.net/diligence/resources/security-tooling-guide/) - An in-depth overview of ConsenSys Diligence’s toolset (and beyond).Scribble runs checks on your smart contract code and looks for possible issues that might not always be caught with normal tests. Scribble uses a technique called Fuzzing which runs lots of tests in focused ways across your code that has been annotated with special Scribble commands/assertions +- [Vertigo](https://github.com/JoranHonig/vertigo) - Vertigo is a mutation testing framework designed to work specifically for smart contracts. This mutation testing framework implements a range of mutation operators that are either selected from previous works or tailored to solidity. + +## Personal & Team Security + +- [Metamask - Common scams and how to avoid them](https://metamask.zendesk.com/hc/en-us/articles/4412217080091-Common-scams-and-how-to-avoid-them) + +## News + +- [Rekt News](https://rekt.news) - A website showing you what can really go wrong. It’s quite amusing to read but I’m sure the people they write about don’t really see it that way, nor the people who got rugged or their money drained from poorly written code. Please read a few and see how bad things can get diff --git a/src/security/truffle-plus-security-sm.jpeg b/src/security/truffle-plus-security-sm.jpeg new file mode 100644 index 000000000..48586c190 Binary files /dev/null and b/src/security/truffle-plus-security-sm.jpeg differ diff --git a/src/security/what-could-go-wrong.md b/src/security/what-could-go-wrong.md new file mode 100644 index 000000000..ba069954c --- /dev/null +++ b/src/security/what-could-go-wrong.md @@ -0,0 +1,42 @@ +# WCGW (aka What Could Go Wrong)? + +There are many things that can go wrong in software development and dapps are no different. If anything, given the public nature of the blockchain networks and the amounts of value at stake, the risks are often higher than with previous computing paradigms. So the short answer to #WCGW is a LOT. + +Mitigating the risks starts with understanding what they are so let’s dive right in. Thematically we’ve broken them down into the following areas: + +- Interface considerations 💻 +- Smart Contract vulnerabilities 🔐 +- Human factors 🤦‍♀️ +- 3rd Party Code 📝 + +## Interface considerations 💻 + +A dapp’s interface is often overlooked as an attack vector, but there’s a number of considerations and more subtle vulnerabilities that should very much be on your radar. + +- **Denial of Service** - Quite simply this is when a malicious actor renders your service (your dapp’s front-end in this case) inaccessible to users. While the implications may not be as severe as other types of attacks, at a minimum it’s an inconvenience and could significantly damage your credibility in the eyes of users. If you’re hosting your front-end central via a provider such as Cloudflare they have a number of prevention mechanisms built-in. Conversely if you’re choosing to host it decentrally via IPFS (or equivalent) then you’ve got some more intrinsic protection given its decentralized nature +- **Hosting provider account compromise** - However this happens (password leakage, social engineering, etc) this is a potentially catastrophic issue. As highlighted in the [BadgerDAO’s exploit post mortem](https://badger.com/technical-post-mortem) an attacker was able to inject a malicious script into the transaction which “prompted users to allow a foreign address approval to operate on ERC-20 tokens in their wallet.” In other words, users were inadvertently allowing the attacker to transfer assets out of their wallets. Mitigations for this really just come down to hardened environment security as highlighted in the [Security Harden ALL The Things](./harden-all-the-things) section +**DNS/DNSLink hijacking** - In a similar manner to that of a hosting provider compromise, a DNS/DNSLink hijack enables an attacker to direct users to a malicious version of your front-end with equally catastrophic results Suddenly everyone thinks they are using your contract (via the fake front-end) when they are in fact sending funds to the hackers account +**Fake / spoofed front-ends** - If you’re lucky enough to have your dapp grow in popularity, then there’s a reasonable chance you’ll start to see malicious copycats emerge (often with subtle variations on the domain name). To a large degree this is out of your control, although you could notify your users via social channels and create an Issue / PR on Metamask’s [​​eth-phishing-detector](https://github.com/MetaMask/eth-phishing-detect) which maintains a list of malicious domains + +## Smart Contract vulnerabilities 🔐 + +This is of course the big one and will be covered in more depth in the next section, but to give you a flavor of the types of vulnerabilities let’s look at a few infamous hacks from over the years. + +- **The DAO hack (Reentrancy Attack)** - An early, and sadly ill-fated, attempt at a DAO (Decentralized Autonomous Organization) wherein what’s now known as a “reentrancy attack” was exploited to drain nearly $150m of the DAO’s treasury. Chainlink has a [great post mortem](https://blog.chain.link/reentrancy-attacks-and-the-dao-hack/), with example code, if you want to dig in further. +- **Wormhole Bridge Hack (Improper Input Validation)** - A failure to properly validate input enabled an attacker to spoof “guardian” accounts and mint the equivalent of $320m in wrapped ETH. A summary by [Elliptic](https://www.elliptic.co/blog/325-million-stolen-from-wormhole-defi-service) +- **Parity Multisig Wallet hack (Fallback Function Delegatecall to Library)** - Another infamous hack on an early multisignature wallet implementation wherein the attacker was able to make themselves the “owner” via a vulnerability in a shared library used by the wallet’s contract implementation. [Technical deep dive](https://hackingdistributed.com/2017/07/22/deep-dive-parity-bug/) +- **Hospowise Token Burn (Incorrect Access Control)** - Incorrect access control on a ERC20 token implementation enabled an attacker to burn tokens held by any address, including ones they didn’t own. This allowed them to do just that for the tokens held by Uniswap pools thus increasing inflation (and thus the token’s value which they subsequently exchanged back to ETH) until the pool was exhausted. [More](https://blog.solidityscan.com/access-control-vulnerabilities-in-smart-contracts-a31757f5d707) + +## Human factors 🤦‍♀️ + +According to a 2013 study by IBM, human factors were cited as the cause of 95% of the security breaches analyzed. While Dapps have considerably different risk profiles to more “traditional” applications and services, the human factor should not be underestimated. Let’s take a look at some of the common pitfalls. + +- **Social Engineering** - If a hacker can impersonate you or steal your credentials/sim/mobile phone number porting then it's quite probable that you're going to have all your passwords compromised and any personal information could be leaked or used for their advantage/gain. If they can login to your social media accounts then it's quite easy for them to then dupe people into sending information to them thinking that it's you they are speaking to +- **You inadvertently commit private keys to your source control** - If you commit a public key to a public source control repo. You are more than likely to have had that account drained within 24hrs if it had anything of value in it. People have bots that scan all the commits into Github et al looking for mnemonics/private keys/ssh keys etc constantly. If those accounts controlled or owned some smart contracts online. Well yeah, ditto +- **Your passwords are leaked/using common passwords** - If your favourite password is pastebinned from some site that got hacked along with your email address then, again, most likely some automated hackerman script kiddie is going to try it across a number of different sites and platforms to see if they get a hit/access. If they do, yeah, big trouble +- **You Get Ransomware’d (new word)** - Your computer gets hacked/ransomware. Not much to say on this, if that happens it’s a real problem. If you have good backups and strong passwords you could be ok but you have to figure out how things like that have happened + +## 3rd Party Code 📝 + +- **Supply chain hack** - Some nice person makes a commit/pr to your repo and they change the package lock file for NPM or YARN. Only thing is, instead of bumping that package that had all the bugs in it to the latest version on NPM, they changed the lock file to point to their hacked version on github instead. Or, they made a typo-like name and published it onto NPM. Now you're suddenly running hacked code and if that's doing something like injecting new scripts onto your website or changing the code that sends to your web3 wallet to sign transactions… In this case, you might be signing all your ERC20 stablecoins away to a hacker to drain from your wallet and not buying that super cool NFT you wanted + - [Wired has a really good article](https://www.wired.com/story/github-code-signing-sigstore/) explaining the risk opensource projects face with hackers posing as legitimate contributors who inject malicious code into these packages used by 100’s of other projects