
Cobo DeFi Security Class (Part 2): Common DeFi Security Vulnerabilities and Prevention
TechFlow Selected TechFlow Selected

Cobo DeFi Security Class (Part 2): Common DeFi Security Vulnerabilities and Prevention
Analysis of the causes of major security incidents in the Web3 industry over the past year and how to avoid them.
Author: Max Cobo, Security Director
This is the 24th article from Cobo Global.
Invited by Moledao, Max, Security Director at Cobo, recently delivered an online DeFi security session for community members. Max reviewed major security incidents that occurred in the Web3 industry over the past year, focusing on their root causes and how to avoid them. He summarized common smart contract vulnerabilities and preventive measures, and provided security recommendations for both project teams and general users. Here, we've split Max’s presentation into two parts for DeFi enthusiasts to save and reference.
Part 1: "Cobo DeFi Security Class (Part 1): Reviewing Major DeFi Security Incidents of 2022"
Common types of DeFi vulnerabilities include flash loans, price manipulation, function permission issues, arbitrary external calls, fallback function issues, business logic flaws, private key leaks, and reentrancy attacks.

Security Incident Statistics: November–December 2022
Let’s focus on three main attack types: flash loans, price manipulation, and reentrancy attacks.
Flash Loans
-
Flash loans are commonly exploited in attacks—attackers use them to borrow large sums of capital instantly, manipulate prices, or exploit business logic within a single transaction.
-
Developers must consider whether their contract functions could malfunction when exposed to massive capital inflows, or if attackers might interact with multiple functions in one transaction to extract rewards.
-
Many contracts calculate rewards based on token balances or use DEX pool reserves in critical computations. If developers fail to anticipate that attackers can manipulate these values via flash loans, funds may be drained.
Flash loans themselves represent a DeFi innovation, but when abused, attackers can borrow substantial funds without upfront cost, execute arbitrage or exploitation strategies, repay the loan within the same transaction, and keep the profit—all they pay is a small gas fee.
Over the past two years, numerous issues have emerged around flash loans. Many DeFi projects promise high returns, but the quality of development varies significantly. Some codebases are purchased rather than built in-house. Even if the code itself has no direct vulnerabilities, logical flaws may still exist. For example, we once encountered a project that distributed rewards based on token holdings at a fixed time. Attackers used flash loans to temporarily acquire large amounts of tokens, capturing most of the reward. Similarly, projects using token balances to determine prices are vulnerable to manipulation via flash loans. Project teams should remain vigilant about such risks.
Price Manipulation
Price manipulation is closely linked to flash loans. The core issue arises when pricing calculations rely on parameters that users can influence. Two common scenarios lead to this vulnerability:
-
Using third-party data sources incorrectly or without proper validation, allowing malicious actors to manipulate reported prices.
-
Relying on token balances from specific addresses as variables in price calculations, where those balances can be temporarily inflated or deflated.
Reentrancy Attacks
One of the primary dangers of calling external contracts is that they can take control of the execution flow and make unexpected changes to your data.
```
mapping (address => uint) private userBalances; function withdrawBalance() public {
uint amountToWithdraw = userBalances[msg.sender];
(bool success, ) = msg.sender.call.value(amountToWithdraw)(""); // If msg.sender is a contract, its fallback function executes and can re-enter withdrawBalance
require(success);
userBalances[msg.sender] = 0;
}
```
Since the user's balance isn't set to zero until the end of the function, subsequent calls during reentrancy will succeed repeatedly, draining funds multiple times.
Reentrancy can manifest in various forms across different functions or even multiple contracts. When addressing reentrancy, keep the following in mind:
- Prevent reentrancy not just within a single function, but across all entry points.
- Follow the Checks-Effects-Interactions pattern in coding.
- Use well-tested, proven reentrancy protection modifiers.
The biggest risk is reinventing the wheel. There are many established security best practices available—we should leverage them instead of writing everything from scratch. A newly created mechanism hasn’t undergone sufficient real-world testing, making it far more likely to fail compared to mature, battle-tested solutions.
Omni Protocol was compromised due to a reentrancy vulnerability—and there’s an even more dramatic story behind it:
The Story Behind the Omni Protocol Vulnerability — A Battle Among Four Hackers
Ethereum’s mempool is constantly monitored by numerous hackers who analyze transactions and front-run profitable ones for profit. When the discoverer of the Omni Protocol vulnerability submitted their attack transaction, two hackers detected it. Using frontrunning bots, they submitted competing transactions via Flashbots and stole 1,200 ETH from the Omni Protocol, leaving the original attacker with only 480 ETH. Meanwhile, a third hacker noticed the frontrunners’ attack transaction on Flashbots and executed a sandwich attack by exploiting the need to purchase Doodle ERC20 tokens, profiting 151 ETH.
The person who discovered the vulnerability didn’t earn the most. Instead, others lurking in the dark forest captured greater profits. In this ecosystem, hunters are everywhere—and often hunt each other. Even the initiator of an attack might not get away with most of the funds unless they drain everything in one move. Many others may outbid with higher gas fees to execute transactions first. If the process involves buying or selling tokens on DEXs, sandwich attacks become possible, creating a chaotic environment.
Security Recommendations
Finally, here are security tips for both project teams and regular users.
Security Tips for Project Teams
1. Follow Smart Contract Security Best Practices.
2. Enable Contract Upgradability and Pausing: Many attacks don’t drain all funds in one transaction but occur across multiple transactions. With a robust monitoring system, suspicious activity can be detected early. If the contract supports pausing, losses can be significantly reduced.
3. Implement Time Locks: Take Ankr as an example—if a time lock had been implemented (e.g., 48 hours), users would have had time to notice when the creator updated the mint function to allow anyone to mint. Monitors could then alert the team. Even if the team ignored the warning, users could at least withdraw their own funds to protect their assets. A project without time locks inherently increases the risk of loss.
4. Increase Security Investment and Build a Comprehensive Security System: Security isn't a single point or linear process—it's systemic. Don’t assume that passing audits from multiple firms guarantees safety. North Korean hackers could still steal private keys—even multi-sig setups aren't immune if all keys are compromised. Economic model flaws, business logic errors, and countless other vectors can lead to fund loss. Conduct thorough risk modeling to mitigate as many threats as possible, reducing residual risks to acceptable levels. Security and efficiency cannot always coexist—you must make trade-offs. But ignoring security altogether makes breaches inevitable.
5. Enhance Employee Security Awareness: Strong security awareness doesn’t require deep technical knowledge. On Twitter, we frequently see people lose NFTs to phishing scams—these attacks exploit human psychology. Being slightly more cautious and asking “why?” more often can prevent many issues.
6. Prevent Internal Malicious Actions While Improving Efficiency and Risk Control: Again using Ankr as an example: First, the contract owner was a single signer, not multi-sig—once the private key was lost, the entire project was compromised. Second, no time lock was used, so critical updates took effect immediately without transparency, which is unfair to protocol participants. Lastly, internal controls failed completely.
How can on-chain protocols improve security without sacrificing too much efficiency? Let me give a quick plug: We recommend Cobo Safe. If a project uses multi-sig, operations may slow down slightly. With Cobo Safe, you can designate specific individuals to perform certain actions—e.g., 3-of-5 approvals. You can grant specific permissions to trusted parties—for instance, assigning a reliable node to monitor security risks. If an attack is detected and funds are being transferred to a hacker address, and the contract has a pause function, that designated person can trigger it immediately.
For example, market makers providing liquidity to DEXs: if Owner privileges aren’t restricted, the Owner could transfer funds elsewhere. With Cobo Safe, you can restrict withdrawal addresses, limit operations to specific token pairs, or only allow withdrawals to whitelisted addresses. Cobo Safe enhances security while maintaining operational efficiency.
7. Exercise Caution When Integrating Third-Party Contracts: As part of the ecosystem, every project has upstream and downstream dependencies. A key security principle is to assume all third parties are untrusted. Always validate both upstream and downstream integrations. Since third-party code is beyond your control, the potential attack surface is large. Only integrate open-source contracts—you must be able to audit their logic. Never use closed-source contracts because you can’t verify their behavior. Also avoid integrating upgradeable contracts unless you fully trust the upgrade mechanism, as they could suddenly turn malicious after an update—an uncontrollable risk.
How Can Users/LPs Assess Smart Contract Security?
For ordinary users, here are six key factors to evaluate a project’s safety:
1. Is the Contract Open Source? Avoid any project with closed-source contracts—you have no way of knowing what the code does.
2. Does the Owner Use Multi-Sig, and Is It Decentralized? Without multi-sig, you can’t verify whether a security incident was caused by hackers or insider actions. Even with multi-sig, assess whether signers are truly decentralized.
3. Review Historical Transaction Activity: Many phishing scams deploy fake contracts resembling legitimate ones. Check deployment time, number of interactions, and transaction history—these are indicators of legitimacy.
4. Is the Contract a Proxy? Is It Upgradeable? Does It Have a Time Lock? Fully non-upgradeable contracts are too rigid. We recommend upgradeable designs—but upgrades must be handled responsibly. Critical changes should include a time lock to provide a review window for users to assess whether the upgrade benefits or harms them—a practice promoting transparency.
5. Has the Contract Been Audited by Multiple Firms? (Don’t Blindly Trust Audit Companies) Is Owner Authority Excessive? Relying on a single auditor is risky—different auditors and firms examine code from different angles. Projects audited by multiple reputable firms and that fix identified issues are generally safer. Responsible teams seek cross-audits from multiple providers.
Also scrutinize Owner permissions. Some scam ("rug pull") projects allow Owners to fully control user funds—normal trading works with small volumes, but large purchases trigger Owner-controlled locks, freezing assets. The same applies to some NFT projects. In legitimate projects, Owner powers should be limited and transparent, with high-risk actions protected by time locks so users are informed in advance. Especially during bear markets, many exit scams emerge—always pay close attention to Owner authority.
6. Pay Attention to Oracles: Projects using top-tier, widely trusted oracles are generally safe. However, caution is needed with self-built oracles or those allowing price feeds from随意 staked tokens. If an oracle appears vulnerable or manipulatable, avoid the project—even if returns seem attractive.
Join TechFlow official community to stay tuned
Telegram:https://t.me/TechFlowDaily
X (Twitter):https://x.com/TechFlowPost
X (Twitter) EN:https://x.com/BlockFlow_News













