TL;DR
- Security remains a critical and ongoing challenge in DeFi, with billions of dollars lost annually.
- Security measures for a DeFi protocol should span its entire lifecycle, securing both inherent and operational aspects from pre-launch to post-launch. It's crucial to implement preventative strategies and contingency plans to mitigate potential attacks.
- Pre-launch security centered around code auditing has become a community consensus. However, despite the emergence of post-launch security solutions (e.g., attack monitoring & blocking), their importance has not yet been fully recognized by the community.
- Continuous improvement of security practices and a shift towards a security-first culture are essential to protect user assets and enhance trust in the ecosystem.
Introduction
As DeFi continues to revolutionize the financial landscape, security remains a significant concern within the ecosystem, with billions of dollars in losses every year.
According to the data from Chainalysis, DeFi hacks in 2023 caused more than $1.1 billion losses. Though this number decreased compared with 2022, there are multiple new trends in the DeFi hacks in 2023. For instance, reputable protocols e.g., Curve and KyberSwap, that have been running securely for years have been hacked. Besides, sophisticated hacks towards infrastructure vulnerabilities, e.g., Flashbots relay, have been exposed.
In the first half of 2024, more than fifty hacks causing losses exceeding $100K occurred, according to the Security Incident Dashboard.
Security is a crucial factor for the prosperity and massive adoption of DeFi applications. This is because DeFi protocols manage billions of dollars in user assets, and any hacks targeting these protocols can result in significant losses for the affected users. Though in some cases, the hacked funds can be (partially) recovered (such as in the Euler security incident), we cannot count on this every time. Each attack erodes people's confidence in DeFi.
Even though multiple methods have been proposed to enhance DeFi security, there is still much room for improvement.
- On the positive side, code auditing has become a community consensus for ensuring security. Most protocols undergo code audits before launch, which helps reduce attack surfaces caused by vulnerabilities in the smart contracts.
- However, code auditing alone is far from enough to address all security issues. It cannot prevent hacks resulting from vulnerabilities introduced during smart contract upgrades, configuration changes, and runtime dependencies across different protocols.
Due to these limitations, more proactive solutions such as operational monitoring or attack detection systems have emerged and been adopted by some protocols.
In this blog, we will explore the DeFi Security Landscape by tracing a protocol's security journey at different stages, from its pre-launch phase, through its operational stage, and to attack response. We will elaborate on various types of security measures and highlight the main vendors (products) at each stage, discussing their pros and cons. We hope our insights can help the community better understand the state of the art, and what’s more important, to inspire innovative solutions in the future.
DeFi Security Landscape
Security measures for a DeFi protocol must encompass its entire lifecycle, from the pre-launch stage to the post-launch stage, ensuring both the protocol's inherent and operational security. Additionally, it is essential to have preventative measures and contingency plans in place to address potential attacks. To help readers understand the solutions available, we clarify DeFi security vendors (products) into the following categories.
Pre-Launch Security
The category consists of the security measures that are conducted before launching a protocol, including code auditing, formal verification, and security testing.
Code Auditing Service and Contest
Code auditing is a well-accepted security practice in the community to secure a protocol. During this process, the code will be reviewed by security companies in a semi-automatic manner, i.e., by automatically scanning the code for common vulnerabilities and manually reviewing the code for complicated ones. Representative companies include OpenZeppelin, ChainSecurity, BlockSec, etc.
Besides, there are auditing contest platforms, which differ from security auditing companies in the way the audit is performed. These platforms initiate the audit contest, involve security researchers from the community to conduct the audit contest, and distribute the rewards to the one who found issues in the protocol. Of course, platforms may have some subtle differences in the way to evaluate the severity, the algorithm to distribute the rewards, and the criteria to involve the security researcher. Such platforms include Code4rena, SHERLOCK, Cantina, and Secure3.
Code auditing (and contest) is the primary line of defense for protocol security. However, it has practical limitations, which explains why many protocols audited by reputable companies are still being hacked.
- First, static code auditing cannot fully evaluate the security issues caused by protocol dependencies, especially due to the composability of DeFi protocols.
- Second, the security impacts of some issues were underestimated during the code audit. For instance, precision loss is a common issue and may be neglected by both auditors and protocols. Its security impact was not fully recognized by the community until the Hundred Finance and Channels Finance incidents.
- Last but not least, high-quality code auditing remains a prestigious and scarce resource, which requires multidisciplinary talent proficient in security, finance, and computer science. Few universities can provide such talent consistently and on a large scale at present. Thus, protocols may be audited by companies that are not qualified to do the business.
Formal Verification
“Formal verification is the act of proving or disproving the correctness of a system with respect to a certain formal specification or property, using formal methods of mathematics”. Because it can prove the correctness of systems, formal verification has been applied to DeFi protocols. Specifically, it can ensure the behavior of a DeFi protocol satisfies the formal specification. The representative of formal verification products for DeFi protocols is Prover developed by Certora. Developers provide the rules (specification) and Prover will compare the results with the rules to identify bugs by exploring every possible program state.
The most promising aspect of formal verification is that it mathematically proves the correctness of the DeFi protocol. However, in practice, it still has some limitations that obstacle its wide adoption.
- First, the specification should be provided by the developers, which requires the developers to have a well-documented specification of the expected behavior of the protocol. This is not easy, considering the fact that most developers are not experts in this area.
- Second, the frequent upgrade of a protocol may require updated specifications and reevaluating the protocol. Some protocols may not afford the time and effort.
Nevertheless, formal verification should be conducted by protocols, particularly the new ones that have not yet been battle-tested and managing substantial user assets. However, enhancing the usability and increasing the adoption rate of formal verification remains a continuous challenge.
Security Testing
Security testing refers to the process of using test cases to find the bugs in a protocol. Compared with the formal verification that mathematically proves the protocol’s correctness, security testing usually uses concrete inputs instead of the symbolic ones in formal verification, thus is much more efficient but less sound.
- Foundry is one of the popular development and testing frameworks for smart contracts. Developers can run the tests in Foundry. It also provides the capabilities to perform fuzz testing, invariant testing, and differential testing on DeFi protocols.
- Other security testing tools include Tenderly and Hardhat.
Post-Launch Security
The category consists of the security measures that are conducted after a protocol is launched (or alive on the mainnet), including bug bounty, attack detection and operational monitoring.
Bug Bounty
Bug bounty programs create a bridge between protocols and security researchers. The fundamental concept is to incentivize researchers to report zero-day vulnerabilities in exchange for rewards. Specifically, protocols can list their bounties on bug bounty platforms, detailing the scope of the bounty and the reward amount for reported bugs. Immunefi is one representative Web3 bug bounty platform.
Attack Detection
Attack detection platforms scan transactions to locate the malicious ones. Specifically, these platform vets the transaction interacted with a protocol for malicious behaviors. If such a transaction happens, an alert will be triggered.
- For instance, BlockSec Phalcon scans the transactions and takes a behavior-based detection engine to detect malicious activities (such as malicious contracts or proposals). Think of it as a virtual security guard that observes every step of a financial transaction, looking for any suspicious behavior. It extracts the behavior patterns from these transactions, much like a detective analyzing clues, and then uses financial models—similar to those used by banks to detect fraud—to identify potential attacks.
- Similar systems include the products provided by Hypernative and Hexagate.
- Besides, Venn Security network from Ironblocks provides a decentralized infrastructure to combine the detection results from multiple sources together.
Operational Monitoring
Operational monitoring frameworks provide a way to implement operational security for DeFi protocols. For instance, the DeFi protocol needs to know the admin key change, perform smart contract deployment and upgrade, and automatically scan pull requests for security vulnerabilities.
- OpenZeppelin Defender provides a platform that allows developers to securely code, deploy, and operate smart contracts.
- BlockSec Phalcon can monitor risks associated with contract upgrades, Safe wallet transactions creation, new signings & execution, access control, and governance.
- Forta Network has an infrastructure to let users build their own bots to monitor their protocols or subscribe to existing bots for phishing or threat alerts.
Attack Response
The category consists of the security measures that are triggered when an attack happens, including attack blocking, automatic action, war room, root cause analysis, and attacker’s fund flow tracking.
Among the five measures in Attack Response, attack blocking is particularly notable because it allows project teams to deploy preventive measures in advance, successfully blocking attacks before execution and minimizing losses to zero. Automatic response platforms also help to reduce the damage caused by attacks.
Establishing a war room, conducting root cause analysis, and tracking stolen funds are reactive steps taken after an attack has occurred. While these strategies can mitigate some damage and help prevent similar attacks in the future, losses may have already occurred and could be challenging to recover. Besides, the harm to the project's reputation and the resulting loss of user confidence can be profound.
Risks are everywhere and often beyond control, yet choosing to deploy preemptive defense measures is well within reach and highly recommended.
Attack Blocking
Attack detection is not enough when combating hacks in practice. This is because, without the ability to automatically block hacks, manual responses are not fast enough. In some cases (KyberSwap, Gamma Strategies, and Telcoin in the following table), it takes a couple of minutes and even hours for the protocol to take manual action, which is too late to save the assets in the protocol. In recent hacks to Velocore and Rho, the whole Linea and Scroll chain was paused, respectively, which raises the centralization concern for the L2 chain.
Attack blocking is the capability to automatically prevent hacks, requiring two key techniques: early detection and automatic frontrunning of hacks.
- Early detection means the system can identify attack transactions before they are finalized on the blockchain, specifically while they are still pending in the mempool.
- Frontrunning the attack involves placing a transaction on the chain ahead of the attack transaction to pause the protocol, effectively stopping the attack before it can be executed.
In this category, BlockSec Phalcon is the only product that has these key techniques. After a hacker initiates an attack transaction, Phalcon's attack monitoring engine can detect this transaction immediately, send attack alerts to users, and automatically front-run to pause the protocol, reducing losses to zero. Its key techniques have been battle-tested with more than twenty rescues of more than 20 million USD.
Automatic Action
Platforms like Phalcon, Hexagate, and Hypernative can also respond automatically when an attack occurs.
After subscribing to such platforms, users can set up monitoring and response measures for various protocol risks. If a transaction meets the monitoring rules, the system will automatically initiate the response actions pre-set by the user (such as pausing the protocol), thereby reducing losses.
However, some platforms do not have an attack detection engine, and the system cannot directly recognize attack transactions and notify the user. Instead, it requires users to customize under which conditions a transaction can be considered an attack. Since the characteristics of attack transactions are very complex, and users (often contract developers) may not have sufficient security knowledge, this can be quite challenging for them.
War Room
Establishing a war room is needed when a protocol is under attack. This can help the protocol to understand what’s going on, share the intelligence in the community, and leverage the resources for further actions. This usually involves experts from different perspectives.
SEAL 911 is a project to “give users, developers, and security researchers an accessible way to connect with a small group of highly trusted security professionals in case of emergency.” It can be reached from the SEAL 911 Telegram Bot. In case of a project under the hack, a war room can be established to assist the protocol.
Root Cause Analysis
When an attack occurs, the protocol needs to understand the root cause, such as the vulnerability within the smart contracts and how it was exploited. This needs some useful tools to analyze the attack transactions. Phalcon Explorer, OpenChain, and Tenderly can be used for this purpose.
Fund Flow Tracking
Fund flow tracking is to track the attacker’s initial funds and the attack profits on the blockchain to locate the related addresses and entities. If the assets are flowing into centralized entities (e.g., centralized exchanges and other institution-level entities), law enforcement can be contacted to help freeze the funds.
A couple of companies and tools are in this category, including Chainalysis, TRM Labs, ARKHAM, ELLIPTIC, MetaSleuth and others.
- For instance, MetaSleuth developed by BlockSec can automatically trace the funds across different chains with rich labels of wallet addresses.
- ARKHAM has a community where the protocol can put a bounty on the investigation, which incentivizes the community to help track the attacker’s funds.
Security Educational Resources
Informed minds build stronger defenses. Beyond the security vendors and products mentioned above, there is another crucial component of DeFi security: educational platforms.
These platforms provide essential resources for DeFi practitioners and users to understand security insights, enhance awareness, and develop security skills. They play a vital role in the advancement of DeFi security. We extend our appreciation to these educational platforms and list a few noteworthy examples.
- SΞCURΞUM: A Discord community focusing on Ethereum security. It also hosts a monthly smart contract security quiz, the “Secureum RACE.”
- Security Incidents Dashboard: This platform collects all attack incidents causing losses over $100k, detailing losses, affected chains, vulnerabilities, root causes, and PoCs.
- Rekt: Known as the dark web of DeFi journalism, Rekt provides in-depth analyses of exploits, hacks, and scams within the ecosystem.
- RugDoc: A DeFi safety and education community that assesses project risks. It also features a platform called RugDocWiKi, which introduces the DeFi ecosystem and technology.
- DeFiHackLabs: A Web3 security community with over 2,600 members and nearly 200 white-hat hackers, aiming to bridge Web2 and Web3 security expertise.
- Solodit: A platform that compiles historical reports from various Web3 auditing companies, serving as a valuable resource for smart contract auditors.
- Ethernaut: A Web3/Solidity-based game where players identify Ethereum contract vulnerabilities, similar to CTF challenges.
Conclusion
Security is still an ongoing and serious threat to the DeFi ecosystem, causing billions of losses each year. Currently, most of the security measures are performed in the pre-launch stage. However, there is no silver bullet in security, and different methods should be performed in the whole lifetime of a DeFi protocol. We expect that the industry will adopt post-launch security solutions, to monitor, and what’s more important, automatically block attacks. We anticipate that the security-first culture will be established in the ecosystem to fully protect users' assets.