9 Most Common Smart Contract Vulnerabilities
Smart contracts are specialized programs stored on a blockchain typically used to automate the execution of an agreement so that all parties can be certain of the outcome without the need to trust one another or any intermediaries. A smart contract guarantees that its execution will correspond exactly to the logic that was originally written in it. And after the execution of said predetermined logic, the final state on the network will stay immutable.
But unfortunately, the correct execution of the smart contract code cannot guarantee its complete safety. In fact, analysis of existing smart contracts shows that a significant part of them are indeed vulnerable. In this article, we will talk about the most common smart contract security issues and weaknesses and the ways to deal with them to boost the security of your protocol.
Money loss is undoubtedly the most visible consequence of a hack since it’s easy to calculate how much the protocol and its users have lost. However, another less obvious but, at times, much more impactful effect of any exploit is loss of credibility.
All smart contracts security vulnerabilities eventually lead to exploits, which negatively affects the reputation of the protocol, its owners, and the project team. Moreover, it lowers the overall level of trust to the industry, creating more concern and doubt.
That’s why it is essential to take good care of smart contract security. And one of the crucial steps in doing so is a security audit. A proper security audit done by a reputable, experienced company will allow you to detect any possible risks and vulnerabilities in your smart contracts and efficiently eliminate them. Thus, you will boost the security of your protocol and prevent potential exploits.
WHY SHOULD YOU CARE ABOUT SMART CONTRACTS SECURITYÂ
Vulnerabilities in smart contracts are serious enough for several reasons:
- Most of the smart contracts deal with financial assets.
- Errors in smart contracts, once published, cannot be corrected due to the immutable nature of the blockchain.
- Changes in blockchain’s state generated by transactions of faulty or fraudulent contracts cannot be rolled back.
We are sure that you understand all the risks associated with bugs and other smart contract vulnerabilities, considering the unsettling statistics of recent years.
In Q1-Q2 2023, the DeFi industry lost about $735 million due to exploits. Some of the DeFi protocols got hacked because of a simple code error, and others – due to inefficient contract logic or incorrect calculations.
Find out more about DeFi security in our article: How to Prevent Your DeFi Project From Hacking.
As we have mentioned before, any smart contract vulnerability can be detected by an experienced team during a smart contract audit. Here’s a brief list of the most common risks Blaize experts check the protocol for:
- fake token and dust attacks;
- timestamp dependence;
- reentrancy;
- incorrect storage initialization;
- inefficient gas spendings;
- transaction-ordering dependence;
- unchecked external calls;
- unsafe type inference, incorrect calculations and accuracy loss;
- DDoS vulnerabilities;
- hidden backdoors in the code;
- lack of randomness (entropy illusion);
- malicious libraries and code injections;
- ERC20 API violation;
- signatures replay;
- access control violation.
Below, we’ll elaborate on the several most widespread issues with smart contracts that our team encounters while conducting smart contract security audits.
See the full list of smart contract security services on the Blaize.Security webpage.
THE LIST OF SMART CONTRACT VULNERABILITIES
1. VULNERABLE PRICE FEED
Smart contracts are only as reliable as the data sources they use. When these contracts interact with vulnerable oracles or compromised price feeds, the outcome can be detrimental. One of the most underestimated threats is the usage of stale prices in the feed, which could lead to considerable financial implications for DeFi platforms and their users. Moreover, if the price source is susceptible to flash loans, it further amplifies the risk.
Understanding the Impact of Compromised Price Feeds and Flashloan Attacks
At its core, a smart contract’s logic is predefined and automated. However, for certain actions, they require external data like price feeds, especially in the world of DeFi. When this external data is manipulated, it can lead to unintended actions within the smart contract. For instance, a manipulated price feed can cause a loan platform to either over-collateralize or under-collateralize loans, leading to unfair liquidations or insolvencies.
Flashloan attacks, on the other hand, exploit the vulnerabilities in price feeds by borrowing large sums of cryptocurrency and manipulating prices on one decentralized exchange to profit on another, all within a single blockchain transaction. By doing this, attackers can trick DeFi platforms into believing an asset’s price has changed drastically, leading to undeserved profits for the attackers.
Examples of Breaks via Compromised Oracles:
- Platypus Attack: On October 12, 2023, decentralized finance (DeFi) protocol Platypus suffered a flash loan exploit resulting in a loss of over $2 million. In response to the attack, Platypus suspended all its pools. The platform experienced three distinct attacks on the same day, with assets totaling $2.23 million being siphoned off across these exploits.
- Euler Finance Attack: Euler Finance, a DeFi lending and borrowing protocol, suffered a flash loan attack that resulted in a loss of $197 million. Although the exact date of this attack within 2023 was not provided, it highlights the severe financial implications flash loan attacks can have on DeFi platforms.
Beanstalk Farms Attack: Happened on April 17, 2022. Hackers exploited the DeFi platform Aave to attack the stablecoin protocol known as Beanstalk Farms. This flash loan attack led to total losses amounting to $182 million. The attackers escaped with $80 million worth of crypto gains and additionally diverted $250,000 as donations​1​. This attack was facilitated through the Avalanche blockchain protocol, specifically targeting Beanstalk Farm’s recently implemented governance mechanism – Curve LP Silos.
2. REENTRANCY
Reentrancy is one of the common Ethereum smart contract vulnerabilities. The thing is that in Ethereum, calls to functions of other smart contracts occur synchronously. That is, the calling code waits for the end of the execution of the external method before continuing its own work. This can cause the called contract to use the intermediate state of the calling contract.
This situation is not always obvious during the development process if all the possible fraudulent actions on the part of the called contract are not taken into account.
Reentrancy has long been a well-known vulnerability in smart contract development, with its dangers becoming increasingly prominent since the infamous DAO hack. However, as the blockchain space evolves, so too do the types of reentrancy attacks and the nuances associated with them.
Read-Only Reentrancy
Traditionally, reentrancy attacks involved malicious contracts that took advantage of the call order in another contract to withdraw funds repeatedly. However, a newer variation of this attack has surfaced, known as read-only reentrancy. In this attack, the malicious contract doesn’t directly change the state but influences other contract’s state indirectly. One of the key distinctions here is the exploitation of gas usage for specific calls, particularly how they can be manipulated to modify the return values of certain functions. By doing so, attackers can extract significant financial gains without directly tampering with a contract’s state.
This method was detailed in the theoretical breakdown of potential vulnerabilities in the Balancer smart contract. While it didn’t lead to an actual exploit on Balancer, the revelation of such a vulnerability underscores the need for developers to be ever-vigilant and updated with newer attack vectors.
Language-level Reentrancy in Vyper
Another recent evolution of the reentrancy attack is associated with the Vyper programming language, an alternative to Solidity for Ethereum smart contracts. The Curve Finance hack serves as an exemplar case for this. In this incident, the attacker exploited a function in the Vyper-written contract of Curve Finance, which allowed them to initialize the contract multiple times. By cleverly leveraging the discrepancies between the state variables and their actual values, the attacker was able to manipulate the system into thinking more assets were present than there actually were, enabling them to extract a profit.
The Curve Finance incident was a stark reminder that while newer programming languages might promise better security features, they aren’t devoid of vulnerabilities, and continuous auditing and vigilance remain paramount.
While the DAO hack was a significant event in the crypto world that thrust reentrancy into the limelight, it’s crucial to understand that reentrancy has evolved. The newer manifestations of this attack vector, as showcased in the examples above, emphasize the need for continuous research, adaptation, and rigorous testing in smart contract development.
Read also: Basics of Liquidity Vampire Attacks.
3. INCORRECT DEPLOY AND POST-DEPLOY SETTINGS
Incorrect settings in smart contracts have been a recurrent culprit behind many hacks in the blockchain space. This vulnerability usually arises when configurations or settings within the contract, which are set during or post-deployment, are not thoroughly vetted or are mistakenly overlooked.
Yearn Finance Hack
A notable example of this is the Yearn Finance hack. Here’s a breakdown of what transpired:
Yearn Finance, a leading DeFi protocol, suffered a significant setback when attackers exploited a vulnerability in one of its DAI lending pools. The exploit allowed the hacker to make off with $11 million. At the heart of this exploit was an incorrect setting in its v1 DAI vault.
The attacker cleverly manipulated the settings and integrated flash loans, ensuring that during each transaction, more DAI would be withdrawn than was supposed to be. They repeated this multiple times until a substantial amount was siphoned off.
The Yearn Finance hack serves as a stark reminder of how even seemingly minor oversights or incorrect configurations can lead to substantial financial loss. It also emphasizes the significance of ensuring all settings are correctly configured and double-checked before going live.
Incorrect settings, while seemingly trivial, can have catastrophic consequences. It underlines the importance of meticulous code review, thorough testing, and being wary of all configurations when deploying or updating smart contracts in a live environment.
4. INFLATION ATTACK
Inflation attacks exploit the flaws in the monetary policy of a token or contract, leading to unintended minting or burning of tokens, thereby manipulating their value and supply. It’s crucial to understand that while ERC4626 tokenized vaults are susceptible to this kind of attack, the concept of an inflation attack is broad and extends beyond just this specific token standard.
Generalized Inflation Attacks
The generalized version of inflation attacks can be applied to various contract types and scenarios. This form of attack focuses on vulnerabilities within smart contracts that allow for unauthorized minting, creation, or allocation of tokens. Attackers exploit these vulnerabilities to flood the market with tokens, devaluing the existing ones or to siphon off assets indirectly.
For instance, attackers might exploit a flaw in a contract’s logic that allows to “inflate” the minting condition, e.g. of voting tokens to protocol tokens. This might enable them to mint an enormous amount of dependable tokens at will, diluting the token’s value and allowing them to sell these tokens in exchanges for other valuable assets.
In the context of ERC4626
ERC4626, or the “Tokenized Vault Standard”, was introduced to create a structured representation for tokenized debt. This standard, while revolutionary in its approach, has inherent vulnerabilities if not implemented with care. Potential flaws in the logic or setup of such vaults can be exploited in inflation attacks, leading to unintended consequences.
The inflation attack is a potent reminder of the complex nature of smart contract vulnerabilities. As token standards evolve and adapt, it’s crucial for developers and organizations to stay ahead of potential threats and ensure robust security measures are in place.
5. RELATED TO STOLEN PRIVATE KEYS
In the ever-evolving landscape of blockchain and smart contract attacks, a notable shift is apparent: hackers are adopting techniques more synonymous with traditional cybersecurity. The theft of private keys, especially those belonging to owners or administrators of decentralized protocols, has become a preferred method for malevolent actors.
Closer to Traditional Cybersecurity
Recent attacks highlight the blurring line between traditional cybersecurity and the decentralized world. Rather than exploiting code vulnerabilities, hackers are now targeting the human element, trying to get their hands on private keys. These keys, especially when they belong to an owner or admin, can give an attacker complete control over a smart contract and the assets associated with it.
The Risks of Centralized Design
While the decentralized nature of blockchain is often hailed for its security benefits, many smart contracts are designed with centralized elements. This centralized design approach inadvertently creates a “single point of failure.” In cases where a single private key controls significant functionalities or assets, its theft can be catastrophic. Once this key is compromised, attackers can potentially drain all associated funds in a single transaction, leaving no room for recourse.
The theft of private keys serves as a stark reminder that the vulnerabilities of the human element cannot be overlooked. A combination of code-based and human-centric security measures is paramount to ensure the holistic safety of smart contract ecosystems.
6. ATTACK WITH FAKE CONTRACT
Smart contracts often incorporate protective mechanisms to ensure security and authenticity. One such mechanism is the isContract call, which checks whether the method caller is another contract. This was initially conceived as a way to restrict or manage interactions between smart contracts and thereby reduce vulnerabilities that can be exploited by fake smart contracts, mimicking the user’s account or legitimate protocol.
The Pitfall of the isContract Call
While the intention behind the isContract call is commendable, it has been discovered that such protection can be bypassed. Specifically, if a contract calls the method during its construction phase, the isContract function fails to detect and manage it appropriately. This loophole can be exploited by malicious actors to execute unintended actions.
OpenZeppelin’s Action
Recognizing the limitation and potential risk associated with the isContract function, renowned smart contract security company OpenZeppelin decided to eliminate it from their library. By doing so, they’ve emphasized the importance of relying on proven, robust security mechanisms rather than those that can be easily circumvented.
As smart contract development continues to evolve, the discovery of such vulnerabilities underscores the need for continuous research, development, and iteration. Ensuring that protective measures are not only robust but also free from potential bypasses is vital for the blockchain ecosystem’s overall health and security.
7. INCORRECT CALCULATIONS & ACCURACY LOSS
In the realm of smart contracts, every calculation needs to be precise, considering the high stakes involved. The nature of smart contract programming requires developers to work exclusively with integers, which has its share of challenges, especially when it comes to mathematical computations like division.
The Challenge of Integer Division
Every division operation in smart contracts is essentially an integer division. Due to this, there is no inherent mechanism to handle floating-point numbers or decimals. This limitation can lead to errors, misrepresentations, or losses if not properly addressed.
The ‘muldiv’ Pattern
To circumvent the challenges posed by integer division, the ‘muldiv’ pattern is often utilized. Instead of performing a direct division as a/b, developers first multiply the dividend by a predefined accuracy multiplier: a * ACCURACY. The division is then carried out as (a * ACCURACY) / b. This result, which now accounts for the required precision, is further divided back by the accuracy multiplier to retrieve the desired output.
Edge Cases and Their Implications
The complications arise when, due to accuracy loss in computations, the end result is ‘0’. These extreme edge cases can have significant implications. If the ‘0’ affects price calculations, the monetary representation can be grossly misrepresented. In cases where it affects withdrawal amounts, a user might end up losing all their money from the protocol due to the system reading it as a zero balance.
Accuracy in financial computations, especially in decentralized systems, is paramount. Developers need to be aware of these nuances and develop mechanisms to avoid potential pitfalls. As the DeFi space grows, it’s imperative that such challenges are addressed head-on to maintain user trust and the overall integrity of the blockchain ecosystem.
8. RACE CONDITION – DEPENDENCY ON THE ORDER
Race conditions, particularly those arising from transaction order dependencies, pose a unique set of challenges in the blockchain and DeFi landscapes. This type of vulnerability hinges on the order in which transactions are processed by the network, making them susceptible to a range of attacks.
Understanding the Dependency
In a race condition, multiple transactions compete to be the first to be included in a block, and the outcome of one transaction can affect the result of another. Since miners choose which transactions to include in a block, and in which order, this creates an avenue for manipulative behaviors.
Frontrunning: The Foremost Exploit
Frontrunning is a tactic where malicious actors observe a transaction waiting in the mempool and quickly create another transaction with a higher gas fee, ensuring that their transaction is processed first. By doing so, they can capitalize on the information they gathered from the original transaction, often to the detriment of other users.
Sandwich Attacks: A Layered Threat
In a sandwich attack, the attacker spots a user’s transaction in the mempool and places a transaction both before and after the target transaction. This effectively “sandwiches” the user’s transaction. For example, in a DeFi setting, this can manipulate token prices temporarily, allowing the attacker to buy low and sell high.
Mitigating the Threat
Protecting against these types of attacks requires both individual caution and platform-level measures. Users should be wary of broadcasting large trades or other potentially lucrative transactions during times of high network congestion. On the platform side, developers can implement mechanisms like randomized transaction ordering or commit-reveal schemes to reduce the risk.
Race conditions underscore the importance of being attuned to the intricacies of transaction processing in the blockchain. As the sector evolves, understanding and addressing these vulnerabilities will be crucial in ensuring a secure and equitable decentralized ecosystem.
9. INCORRECT WORK WITH ERC20 TOKEN
The ERC20 token standard provides a common list of rules that an Ethereum token has to implement, granting consistency across different token contracts on the Ethereum platform. However, deviations from or misunderstandings of this standard can lead to various vulnerabilities and integration issues.
Deviations from the Standard: A Case Study with USDT
Tokens like USDT have exhibited deviations from the standard ERC20 interface, particularly with their transfer() and approve() functions. Such discrepancies can lead to interoperability issues when integrating with other platforms or dApps expecting standard ERC20 behavior. This very challenge led to the creation of libraries like SafeERC20, which aim to handle tokens that deviate from the expected standard, ensuring smoother interactions in a wider range of scenarios.
Initial Minting Missteps
The minting process is crucial for defining the initial supply of a token. However, errors during this phase, such as setting an unintended supply, can have long-term ramifications for the token’s economics and its holders.
The Allowance Conundrum
Functions like increaseAllowance and decreaseAllowance aim to adjust the token allowance without the need for two separate transactions. However, mishandling these functions can lead to unexpected outcomes. Due to complexities and potential pitfalls in their implementation, these functions have even been removed from the OpenZeppelin version of the standard.
Decimal Discrepancies
The decimals function in the ERC20 standard specifies the token’s divisibility, determining how many decimal places a token can have. Incorrect configurations or misunderstandings can lead to valuation discrepancies or hinder token usability.
Adhering to the ERC20 standard isn’t just a matter of compliance – it’s about ensuring broad compatibility, predictability, and minimizing potential points of failure. As the blockchain space continues to evolve, adherence to tried-and-tested standards becomes even more pivotal to the success and security of token-based endeavors.
Even though such errors might be very small, they may lead to the non-functional method of the contract since it will not be able to recognize the interface. It is a tiny mistake, almost not noticeable during testing, but in production, it leads to stuck funds and blocked contracts. Are you familiar with the benefits of adopting smart contracts? If not, please open and read.
BLAIZE SECURITY EXPERIENCE DEALING WITH SMART CONTRACT VULNERABILITIES
Over the course of the last 5 years, the Blaize team has conducted over 200 audits with 80% of them having Critical or High-risk vulnerabilities.. Based on our experience of auditing DeFi, NFT platforms, bridges, exchanges, GameFi projects, and other decentralized protocols, we can ensure that the price of the audit will save hundreds of times more funds, and have an unmeasurably higher impact on trust and reliability.
Unfortunately, we cannot publish all our cases due to client privacy, but you can still see multiple case studies on our website. Make sure to look them through – you’ll find a few familiar names (including Aurora, Everstake, Cosmos, Avalanche, etc.).
THE BOTTOM LINE
Writing a completely secure smart contract is a complex and painstaking task. Yet, however perfect the contract may seem, it still requires a thorough security audit before being published on the network.Â
The reason for that is many smart contract vulnerabilities that can be easily overseen even by experienced smart contract developers. Yet, even minor bugs may lead to massive protocol exploits and money loss. That is why we highly recommend you conduct at least two smart contract audits to boost your protocol security and prevent potential hacks.
What if collaborate with a company with such well-known projects as Everstake, 01node, and Aurora in our portfolio? Let’s build secure projects together with Blaize!
FAQ
What are the most common smart contract security vulnerabilities?
The most common smart contract weaknesses include unsafe type inference, timestamp dependency, reentrancy, implicit visibility level, gas limit and loops, and much more. See the full list in the article above.
How do I boost the security of my smart contracts?
To boost your protocol security, we highly recommend you hire a reputable team of auditors to conduct a smart contract audit. This way, you’ll be able to find vulnerabilities in smart contracts and eliminate them before deploying the contract, thus, preventing a potential hack.
What is a smart contract audit?
A smart contract audit is a thorough analysis of the protocol’s smart contracts in order to find and eliminate any potential threats and vulnerabilities. A proper audit should include not only automatic testing but also manual testing, business logic review, a detailed review of the code against all known vulnerabilities, comprehensive recommendations on how to eliminate bugs and vulnerabilities, and much more.
How can I find security vulnerabilities in Ethereum smart contracts?
You should hire reputable contractors to conduct a couple of smart contract security audits. As a result, you will get a report containing all detected vulnerabilities and recommendations on how to eliminate them.
How to eliminate all smart contract vulnerabilities?
When hiring an experienced team of smart contract auditors, you get an elaborate report containing all detected vulnerabilities and recommendations on their elimination.