Smart contract vulnerabilities, the 10 most common vulnerabilities in Web3 in 2023

Smart contract vulnerabilities, the 10 most common vulnerabilities in Web3 in 2023

introduce

Smart contracts powered by blockchain technology have revolutionized various industries by providing decentralization and automation. However, they also introduce new types of security challenges to the operation and design of decentralized applications. In this article, we’ll explore the ten most common smart contract vulnerabilities that
developers and auditors should be aware of in order to build secure, robust smart contracts. NOTE: Most projects and bugs submitted through Immunefi use the EVM-based blockchain*. Therefore, this article will focus on these technologies. However, these classifications can be generally extended to any blockchain technology. * Vulnerabilities that made it to this list were identified through analysis of hacks in Q1 2023 and bug fixes discovered through Immunefi.

V01: Incorrect input validation

Overview

Improper input validation is the main reason for the large number of confirmed vulnerability reports filed through Immunefi and exploited out there. Input validation is a key security practice that involves verifying the completeness, accuracy, and security of data input to a system. Failure to properly validate input can open avenues for attackers to exploit and manipulate system behavior.

describe

Improper input validation occurs when smart contracts fail to adequately validate and sanitize user input, making them vulnerable to various types of attacks. Such vulnerabilities can be exploited to manipulate contract logic, inject malicious data, or cause unexpected behavior. Proper input validation ensures that contracts only process valid and expected data, reducing the risk of exploitation.

prevention

To prevent such vulnerabilities, developers should implement comprehensive input validation routines. This includes validating data types, checking boundary conditions, and sanitizing user input to prevent unexpected situations. To ensure robust input validation, all possible input scenarios must be considered, including edge cases and unexpected inputs. Some tools and techniques that can help developers prevent edge cases from being missed are fuzz testing or symbolic execution . These tools can help developers test various inputs to ensure that malicious input does not break the smart contract’s invariants or execution.

example

Beanstalk Logic bug fix audit shows an example of a missing input validation vulnerability. There is a vulnerability in the transferTokenFrom() function of the Beanstalk Token Facet contract, in which the authorization amount of msg.sender is not correctly verified in EXTERNAL mode. The flaw allows an attacker to transfer funds from a victim account that has previously approved a Beanstalk contract.

reference article

V02: Calculation error

Overview

Calculation errors follow closely among the confirmed bug reports we've seen on Immunefi.
Incorrect or inconsistent calculations in smart contracts can lead to unintended consequences, such as inaccurate token balances, incorrect reward distribution, or unexpected results during contract execution. Incorrect calculations are often paired with underexplored code paths and are closely related to incorrect input validation errors. However, incorrect calculations deal with vulnerabilities where a user is intended to be able to perform certain actions, but due to incorrect calculations, the user may receive more reward from that action than expected.

describe

In smart contracts, miscalculations occur when mathematical operations are performed incorrectly, leading to unexpected or incorrect results. These vulnerabilities can arise from a variety of reasons, such as incorrect assumptions about precision, value ranges, or inconsistent calculations in different parts of the contract. Miscalculations can also occur when a contract fails to account for edge cases or handle edge cases correctly. In some cases, a contract may fail to account for extreme values, or may not handle overflows or underflows, leading to unexpected behavior or security risks. Attackers can exploit these vulnerabilities to manipulate calculations or gain unauthorized advantage in contracts. Appropriate mathematical precision and careful consideration of corner cases are critical to preventing such vulnerabilities.

prevention

Unit testing along with fuzzing or symbolic execution can help infiltrate missing edge cases into the codebase. Additionally, formal verification of mathematical equations will help provide guarantees for possible states. Perform calculations accurately using well-tested and secure math libraries or built-in functions provided by blockchain platforms. These libraries often have built-in protection against common computational errors such as overflow or underflow.

example

88MPH Stealing Unclaimed MPH Rewards Bugfix Review demonstrates an incorrect calculation scenario where MPH rewards are calculated using an incorrect rewardPerToken, which would allow an attacker to completely drain the MPH reward contract of unclaimed funds.

reference article

V03: Oracle/Price Manipulation

Overview

Smart contracts often rely on external data sources called oracles to make informed decisions. If these oracles are compromised or manipulated, it could result in incorrect pricing of exchanges, incorrect reward calculations, borrowing more assets than collateralization ratios allow, or other general issues with financial transactions. The manipulation of these external data sources is one of the main reasons why DeFi attacks occur on the chain. Selecting trusted oracles and implementing secure data verification mechanisms are critical to mitigating the risks associated with oracles/price manipulation.

describe

Since many protocols update asset pricing based on user actions, this may be an obvious but easily overlooked vulnerability since prices are expected to update based on user interaction. However, when a protocol relies on these internal or external pricing mechanisms, careful consideration should be made to ensure that spot prices are not abused. Whether price manipulation can be effectively executed also largely depends on the current on-chain conditions. Less liquid pools face higher manipulation risks than more liquid pools. Carefully selecting trusted oracles and implementing secure data verification mechanisms is critical. Expiration checks, average pricing mechanisms, and read-only reentrancy protection can be important features for robust integration of external pricing mechanisms. Diversification of data sources also prevents vulnerabilities in a single protocol from wreaking havoc on the entire blockchain ecosystem.

prevention

To prevent oracle/price manipulation vulnerabilities, developers should carefully select trusted oracles with a proven track record. Implementing secure data verification mechanisms, such as cryptographic proofs or aggregation of multiple data sources, can help ensure the accuracy and integrity of data received. Regularly auditing and monitoring oracle contracts and their interactions with smart contracts can also help identify potential vulnerabilities. No assumptions should be made about the accuracy of data returned from external oracles, and safeguards should be in place to prevent temporary price manipulation or stale data from affecting the operation of the protocol.

example

BonqDAO experienced a price oracle manipulation attack where an attacker could temporarily inflate the price of the WALBT token in order to borrow more stablecoins (BEUR) than they were entitled to. The attacker then manipulated the price again, reducing it to a very small value in order to liquidate more than 30 undercollateralized positions. What makes BonqDAO vulnerable is not the permissionless nature of its price reporting mechanism, but rather that it treats the spot price of the protocol contract as the last recorded value. Therefore, anyone can temporarily inflate or deflate the value of a given price feed.

reference article

V04: Weak access control

Overview

Weak access control mechanisms may allow unauthorized users or malicious actors to gain unauthorized access to critical functionality or data in smart contracts. Access control is critical to ensure that only authorized entities can interact with specific functions or modify critical parameters.

describe

Appropriate access control measures, such as role-based permissions and strong authentication mechanisms, must be implemented to prevent unauthorized access. Clearly documenting these limitations and capabilities of actors within a system can help highlight which operations are at risk of critical vulnerabilities. Such documentation can facilitate improved unit testing and identification of potential conflicts, ensuring the system operates as expected and minimizing the risk of critical vulnerabilities resulting from a single missing check. Projects should also ensure that roles are as restricted as possible in allowed operations to prevent risks from the web2 world from causing irreparable damage to the entire system. If the roles are not granular enough, or the protocol relies heavily on centralization as a security model, then the theft of private keys can be extremely damaging.

prevention

To prevent weak access control vulnerabilities, developers should implement role-based access control mechanisms. Clearly define roles and their associated permissions in the contract document. Implement strong signature verification and use proven and tested libraries. Regularly review and update access control mechanisms to account for any changes in system requirements or user roles.

example

Enzyme Finance has rewarded a researcher for discovering a vulnerability resulting from integration with an external component called "Gas Station Network." Gas Station Network is a decentralized relay network that allows dApps to pay transaction fees on behalf of individual users. The Paymaster (the role that initiates transactions on behalf of the user) is missing verification of a trusted forwarder that returns the amount of funds used by the relay to be refunded. If you like videos, we recommend you watch our analysis of Sense Finance’s $50,000 bounty payout .

reference article

V05: Replay Attack/Signature Malleability

Overview

Cryptography is at the core of all smart contract functionality. The cryptographic primitives implemented in the protocol are often based on the same primitives on which the chain operates in a permissionless manner. However, they can sometimes be used incorrectly, causing operations to be performed more times than expected, resulting in financial losses or incorrect contract status.

describe

A replay attack occurs when an attacker replays a valid transaction or message to trick a smart contract into performing an action multiple times. EVM-based chains have access to the ecrecover primitive, which allows smart contracts to verify that certain data has been verified and signed by a recovered address. However, this function does not implement any kind of replay protection.
Typically, replay protection is achieved by introducing a nonce (a number used once) that is incremented when a signature is used, preventing the original signature from being used again once the nonce is updated. Signature malleability refers to the ability to modify a signature without invalidating it, allowing the signature to be used twice. Signature malleability may be used when encoding data or converting between types, where certain parts or bits of a value are ignored when checking the signature, but used in its entirety to prevent replay attacks.

prevention

To prevent replay attacks and signature malleability vulnerabilities, developers should implement nonce-based transaction management. Nonce ensures that each transaction is unique and prevents replay attacks. Additionally, implementing appropriate signature verification checks (such as verifying signature integrity and authenticity) can help prevent signature malleability attacks. Contract design should also include mechanisms to prevent repeated unintended actions, such as single-use tokens or unique transaction identifiers.

example

The highest paid bounty in history at the time, Polygon's Double Spend vulnerability, dealt with a bug in Polygon's WithdrawManager that verified the inclusion and uniqueness of burn transactions in previous blocks. The encoding method branchMask allows encoding multiple unique branch masks to the same exit ID. The malleability of this signature allowed an attacker to deposit just $100,000 and reuse the signature, resulting in a loss of $22.3 million.

reference article

V06: Rounding error

Overview

Improper handling of floating point arithmetic and rounding errors can lead to financial discrepancies or contract logic being exploited. Precise handling of numerical operations, using fixed-point arithmetic where applicable, is critical to avoiding such vulnerabilities. Typically, these vulnerabilities may arise in permissionless exchange protocols, where non-standard decimal values ​​may have unforeseen consequences.

describe

Rounding errors occur when a smart contract performs calculations that involve floating point arithmetic and cannot account for precision or rounding. These errors may result in financial discrepancies, loss of funds, or incorrect rewards calculated in the contract. Smart contracts should use fixed-point arithmetic or alternative mechanisms to accurately handle decimal calculations, ensuring rounding errors are minimized or eliminated.

prevention

To prevent rounding errors, developers should use fixed-point arithmetic or a library that provides precise numerical operations. Fixed-point arithmetic uses integer values ​​to represent decimals, avoiding the inaccuracies associated with floating-point arithmetic. Additionally, thorough testing and verification of numerical operations, including boundary conditions and edge cases, can help identify and resolve potential rounding errors.

example

Notably, DFX Finance fixed a bug that included a rounding error in the EURS token due to a non-standard number of decimal places (2 digits). Assimilators are necessary for DFX Finance's automated market maker as all assets are paired with USDC. The Assimilator V2 contract is responsible for converting all amounts into units of account, or base values ​​for cross-protocol calculations. Problems arise when integer division results in zero tokens being transferred from the user, although the user still receives Curve tokens representing their portion of the Curve pool.

reference article

V07: Re-entrancy attack

Overview

Reentrancy attacks have a long history in Ethereum and were the class of vulnerability responsible for The DAO Hack, one of the largest attacks on the Ethereum network in early 2016. Reentrancy allows an attacker to repeatedly call a vulnerable contract before the previous call completes, causing unexpected behavior. Status changes and unauthorized fund transfers.

describe

Reentrancy vulnerabilities occur when a contract allows external calls to it during execution without properly managing state changes and execution flow. A reentrancy attack allows an attacker to repeatedly call a vulnerable contract before the previous call has completed, leading to unexpected state changes and unauthorized transfers of funds. Implementing a secure state management pattern and applying mutex locks can reduce the risk of reentrancy attacks. Some tools that can help you identify possible reentrancy in your contracts include Slither , Mythril , and Pyrometer . You can read more about reentrancy in this article , The Ultimate Guide to Reentrancy .

prevention

To prevent re-entrancy vulnerabilities, developers should follow security state management patterns such as the Check-Effect-Interact (CEI) pattern. This mode ensures that all state changes are made before any external calls are made, thus preventing reentrancy attacks. Additionally, implementing a mutex or using the " ReentrancyGuard " pattern can further prevent reentrancy by blocking reentrant calls.

example

Omni Protocol suffered a hacker attack, resulting in a $1.4 million loss due to a re-entry attack on its Ethereum smart contract. The vulnerable code uses ERC721's safeTransferFrom method, which calls a smart contract that implements the onERC721Received interface. This external call hands over execution to the receiver and introduces a reentrancy vulnerability.

reference article

V08: Jump ahead

Overview

Frontrunning is a technique where an attacker exploits the time delay between observing a pending transaction and including it in a block. By setting his own transaction to a higher gas price before the victim's transaction, the attacker can manipulate the outcome of certain contract interactions to his own benefit. Front running is a problem with decentralized exchanges, auctions, or any scenario that involves the order of trades.

describe

Front-running transactions occur when an attacker gains an advantage by executing a transaction before others, especially when they know of pending transactions that are about to be included in a block. In the context of smart contracts, front-running transactions can be harmful in situations where the order of transactions affects the outcome. For example, on a decentralized exchange, an attacker can observe the victim's pending transactions aimed at purchasing a specific coin at a specific price. They can then quickly submit their own transaction with a higher gas price to purchase the same tokens at a lower price before the victim's transaction is executed. This allows the attacker to benefit from the price difference at the expense of the victim. Front-running transactions can be performed by anyone observing the mempool, but can also originate from the block producers themselves. Some chains have private RPCs that reduce risk, but validators and block producers in private mempools may also have faulty trust assumptions. Developers should reduce potential front-running transaction opportunities at the smart contract level rather than relying on external mitigations, which rely in part on trust or aligned incentives to protect their protocols.

prevention

Preventing front-running requires a combination of technical and design considerations. Some preventive measures include using secret or commit disclosure schemes, implementing schemes that keep sensitive information like prices or bids confidential until trades are confirmed, off-chain order matching, using flashbots that allow users to bundle transactions together and submit them directly to miners, Reduce the opportunity for front-runners, and optimize fees to reduce the likelihood of being outbid by front-runners.

example

Front-running trading attacks have been observed in various DeFi protocols. RocketPool and Lido have been informed of a vulnerability that may affect both staking services. Malicious node operators can steal user deposits by using the same validator bls key to preemptively deposit using previously prepared deposit data and the required minimum deposit value.

reference article

V09: Uninitialized agent

Overview

Using a proxy contract without proper initialization can introduce vulnerabilities, as an attacker can manipulate uninitialized stored variables. Implementing the secure proxy pattern and performing thorough initialization checks is critical to preventing unauthorized access to uninitialized contract state. An uninitialized proxy bug has resulted in the largest bounty payout to date of $10 million.

describe

An uninitialized proxy contract is a situation where the state variables of the proxy contract are not properly initialized before being used. This can create security holes, as uninitialized storage variables could contain sensitive data or control critical contract behavior. An attacker could exploit these vulnerabilities by manipulating uninitialized storage variables to gain unauthorized access or perform unexpected operations. To mitigate this risk, it is critical to ensure that proxy contracts are properly initialized before being used in production.

prevention

To prevent uninitialized proxy vulnerabilities, developers should ensure that all stored variables in the proxy contract are properly initialized before deploying and using the proxy. This includes initializing sensitive data, access control permissions, and any other critical state variables. Developers should also implement comprehensive initialization checks in the agent contract to verify that all required variables and dependencies are initialized correctly. They should also implement monitoring tools to provide secondary verification that initialization has occurred correctly. This can be achieved through constructors or initialization functions that are called after deployment through automation scripts or transaction bundles.

example

The Wormhole Uninitialized Agent bug report has the highest paid bounty in history to date: $10 million was paid to the white hat hacker who submitted the report. When deploying a UUPS proxy contract, the "constructor" is a regular Solidity function present in the implementation. The implementation provides an initialize() function that initializes the owner. Wormholes do not initialize their implementation's implementation contract, which would allow an attacker to gain control of the implementation contract and self-destruct the contract, which would cause the proxy contracts to be unable to continue executing because the logical contracts they point to no longer exist.

reference article

V10: Governance Attack

Overview

Governance attacks refer to the manipulation or exploitation of governance mechanisms in decentralized protocols or smart contract systems. These attacks are designed to disrupt the decision-making process, voting system or parameter adjustment of the governance system, allowing the attacker to gain improper control or benefit from the protocol.

describe

Governance attacks can take many forms, including allowing proposals to be executed without a quorum, allowing proposals to be executed without any voting steps, or directly manipulating the votes of other participants. These attacks could compromise the decentralized nature of the protocol and lead to a concentration of power, or result in financial gain for the attacker. Governance attacks are particularly important in decentralized autonomous organizations (DAOs) because decision-making power is distributed among token holders.

prevention

To prevent governance attacks, it is important to establish a strong, well-defined and transparent governance framework that outlines decision-making processes, voting mechanisms and rules of engagement. Implement a secure, tamper-proof voting system to ensure the integrity of the vote. This may involve using cryptography, zero-knowledge proofs, or multi-signature schemes to enhance security. Ensure fair and decentralized distribution of tokens and avoid concentration of voting power in the hands of a few entities. Consider using mechanisms such as token vesting or lock-up periods to deter short-term manipulation. Ensure that the majority of governance tokens are not distributed across exchanges so that malicious actors can obtain enough tokens to pass proposals unanimously.

example

A well-known example of a governance attack is the attack on Beanstalk, a permissionless FIAT stablecoin protocol. Hackers submitted two Beanstalk improvement proposals: BIP18 and BIP19. The first proposal suggests transferring all funds to the attackers, while the second proposes sending $250,000 worth of $BEAN tokens to an official crypto donation address in Ukraine. Attackers lent over $1 billion from Aave, Uniswap, and SushiSwap to gain enough voting power (at least ⅔ majority) to trigger emergency governance enforcement.

reference article

in conclusion

As smart contracts continue to evolve and gain widespread adoption, it is critical that developers and auditors stay up to date on the latest vulnerabilities and security best practices. By addressing these top ten smart contract vulnerabilities, stakeholders can enhance the security posture of their smart contracts and contribute to the overall trust and reliability of blockchain-based systems.

Guess you like

Origin blog.csdn.net/weixin_28733483/article/details/132756257