Smart Contracts: Common Vulnerabilities and Real-World Cases
Smart contracts are self-executing programs that facilitate blockchain transactions. When the predetermined, hard-coded conditions of the contract are met, the program will automatically execute certain actions such as minting tokens, withdrawing and depositing funds or transferring asset ownership between parties.
These digital agreements do not rely on a central authority and reduce the time delays and fees commonly associated with traditional documents that require manual processing. However, although smart contracts provide a digital alternative to the analog method, they are also vulnerable to numerous security issues. Due to the transparent nature of smart contracts, attackers are meticulously searching for coding errors that they can profit from.
Access Control Vulnerabilities
Access control vulnerabilities arise due to a lack of sufficient permission controls, allowing unauthorized users to access or modify critical functions or data of a smart contract. Exploitation of this vulnerability class can result in stolen funds or assets.
In 2017, the Parity Multisig Wallet suffered from an access control vulnerability that allowed an attacker to steal over 150,000 Ethereum. At the time, the market value of the heist was equivalent to ~$30 million. The vulnerability existed due to publicly exposed functions, including the smart contract's initialization function that could change the contract's ownership. Since there was a lack of checks to prevent unauthorized calls, the attacker changed the ownership state variable to only include their wallet address. The attacker then authorized the transfer of all contract funds.
To mitigate access control vulnerabilities, it is essential to implement robust authorization mechanisms, such as role-based access control (RBAC) or attribute-based access control (ABAC). These strategies ensure that only authorized entities can conduct specific contract actions by verifying their granted permissions. Additionally, the principle of least privilege should be followed, which states that entities should only be granted the permissions absolutely necessary to perform their tasks.
Price Oracle Manipulation
A price oracle is an external data source that provides price information to smart contracts. If the data is susceptible to manipulation, attackers can inflate the value of an asset for personal gain. This tampering can also result in downstream consequences such as false collateral calculations, leading to liquidations.
Price oracle manipulation led to the theft of $112 million in digital assets in an attack on Mango Markets back in 2022. The hacker responsible was allowed to manipulate their collateral value and take out a massive loan after altering the centralized exchanges which Mango referenced.
It is critical that smart contracts are not reliant on a single price oracle and instead query multiple oracles that are independent of each other or use multiple nodes to determine prices themselves. Explicitly defined thresholds and time locks between price updates can further bolster security, to account for unrealistic volatility. Contract developers should also require cryptographic signatures to ensure the integrity of the data.
Logic Errors
Logic error vulnerabilities allow attackers to circumvent the intended behavior of smart contracts. If exploited, logic errors can result in the loss of funds, unrestricted token generation, or execution failure.
In December of 2021, MonoX published an announcement stating that $31 million worth of tokens had been stolen due to a logic error in their smart contract. The contract allowed their native MONO token to be exchanged for itself via the tokenIn and tokenOut functions. As dictated by supply and demand, the price of the sold token decreased, while the price of the bought token increased. However, because the attacker was trading the same token and the contract updated the price based on the tokenOut value, they were able to drastically inflate the value of their holdings by automating the process with a script. With their artificial gains, the attacker then exchanged MONO for other valuable tokens, draining the funds from the MonoX pool.
As these bypasses can be difficult to detect, a comprehensive understanding of the underlying processes of the code is required in order to identify weaknesses. Proactive security testing should be done before release to ensure that the operations only result in the intended outcome.
Lack of Input Validation
Failures to validate user input can result in the processing of malicious payloads. Threat actors can take advantage of this lapse in security to perform unauthorized transactions or operations, which can result in significant financial and operational damages.
In February of 2022, a hacker was able to mint 120,000 Ethereum due to a lack of validation in the signature verification process in multiple nested smart contracts used by the Wormhole bridge. Wormhole relied on "guardian accounts" which are trusted accounts that can approve transactions. These guardians are supposed to verify that transactions are legitimate. However, the hacker created fake guardian accounts, inserted their credentials, and Wormhole did not validate that their signatures were legitimate. At the time, the amount minted had a market value of $324 million.
Strict input validation needs to be performed to ensure data is the expected type, format, length, and within an acceptable range or matches explicitly defined values in an allowlist before any processing occurs. As a fallback, developers should also adopt a deny-by-default approach when inputs or identifiers cannot be confidently validated.
Reentrancy Attacks
Reentrancy attacks occur when a malicious contract repeatedly calls a vulnerable contract's function before the first call is completed. These attacks are similar to race condition attacks in that they duplicate execution. The main concern with this attack is withdrawals being made multiple times, potentially leading to balances being drained completely.
This attack vector was given its name following the attack against the Distributed Autonomous Organization (DAO) in 2016. On June 17th of the same year, less than three months after the DAO's launch and only six days after the public announcement of a discovered "recursive call bug", a hacker siphoned $150 million worth of Ethereum from the DAO's smart contract. By deploying their own malicious contract, the hacker was able to combine the initial withdraw() function and a fallback function that called withdraw() again on their deposited Ethereum multiple times in rapid succession. This created a loop between the hackers contract and the DAO contract because the DAO failed to update the hacker's balance until the entire transaction was completed. However, due to the looping state, the transaction was never considered complete, allowing the hacker to repeatedly withdraw funds.
To mitigate the risk of reentrancy attacks, developers should ensure that state changes are made before external contract calls are executed, preventing unexpected behavior. Additionally, developers should implement reentrancy guards by using flags that mark whether a function is currently executing, preventing recursive calls. Another effective mitigation is to require users to claim their withdrawn funds in a separate transaction, which ensures that balance updates happen before any funds are sent, effectively preventing reentrancy.
Unchecked External Calls
In contrast to reentrancy attacks, unchecked external calls occur when the return value of another contract's function is not checked. In these cases, failures can go unnoticed and the execution will be determined as successful leaving one party bound by the smart contract empty-handed.
During the time period spanning from February 6th to the 8th of 2016, the smart contract of the King of the Ether Throne (KotET) game failed to process certain payments due to an unchecked external call. The contract used its send() function to issue payments to players but only allocated a fixed amount of gas. This processing fee was insufficient for some external contracts to properly process the payments. However, the KotET contract lacked the checks to verify the success of the external calls, leading to players not receiving the Ethereum they were entitled to.
To avoid these failures, return values should always be captured and properly handled before operations proceed. If a failure does occur, the entire transaction should be reverted to ensure consistency. Additionally, receiving contracts should implement fallback functions themselves to handle errors gracefully. Developers should conduct regular reviews and audits in order to identify these issues.
Flash Loan Attacks
Flash loans refer to when smart contracts allow users to borrow large sums, without posting collateral, as long as the loan is repaid in full within the same multi-step transaction.
On April 17th of 2022, a hacker stole $182 million from the Beanstalk Farm project through a flash loan. After borrowing nearly $1 billion worth of assets through the Aave protocol, the hacker exchanged enough to gain a 67% voting stake in the Beanstalk governance system. With their dominating supermajority influence, they then approved their own proposal to transfer all funds from Beanstalk to their own wallet. After repaying the flash loan, the hacker netted a $80 million profit. The attack caused the value of the BEAN stablecoin to plummet, breaking its $1 peg, reaching lows of $0.14 shortly after.
To prevent flash loans from providing an attack vector, critical functions should implement time-based locks to increase the incident response time period. Circuit breakers can also be used to automatically lock protocols if certain suspicious thresholds are met.
Insecure Randomness
The security of cryptographic functions is only as good as its entropy. Any system with low-entropy is repetitive and therefore predictable. If attackers are able to predetermine the outcome, they can leverage this knowledge to gain an advantage.
On December 5th of 2022, an insecure randomness vulnerability in the Roast Football Protocol smart contract was exploited. The lottery in the protocol utilized a random number generator to determine if a token buyer would win. However, this random number generator produced its value using predictable parameters including the block number, block timestamp, buyer's address, and the buyer's balance. With this knowledge, the hacker only bought tokens when they had a higher probability of winning, resulting in 12 Binance Coins (BNB) being awarded due to two successful guesses. At the time, BNB was trading at a high of $288.46, meaning approximately $3,400 was won illegitimately.
To mitigate against predictability, smart contracts should also only incorporate trusted and resilient random number generation methods, while avoiding the inclusion values that are revealed client-side.
Denial of Service Attacks
As computational power is a limited resource, attackers can overwhelm the processing capabilities of a network by creating smart contracts that consume an excessive amount of gas. These denial of service (DoS) campaigns can prevent normal usage, disrupting operations and services that rely on the execution of the affected smart contracts.
In September of 2021, the Grape Protocol's fundraising campaign came under attack by bots spamming the Solana network at a rate of 400,000 transactions per second. This load overwhelmed the network, causing the validator nodes to crash after they ran out of memory. This led to the network being knocked offline for roughly 17 hours.
To harden smart contracts from these resource exhaustion attacks, smart contracts must be able to handle failures gracefully, such as those that may come from failed external calls, loops, and traversals.
HackerOne's Efforts
As companies navigate this explosive new financial world, reputation means everything. Eager investors need the peace-of-mind that their hard-earned money is secure. What used to be a niche market is now a global powerhouse here to stay. The cryptocurrency and blockchain industry has witnessed a significant surge in growth and adoption, but this rapid expansion also brings heightened security risks. As evidenced by numerous real-world cases, security vulnerabilities within this sector can lead to substantial financial losses and operational disruptions, potentially causing irreversible damage to both companies and individual users.
By leveraging the power of crowdsourced security, HackerOne is assisting organizations in the space in their efforts to harden their security through iterative testing.
Leading organizations such as Coinbase, Crypto.com, MetaMask, Chainlink, and Deribit have all established bug bounty programs through HackerOne and the results speak for themselves. Currently, HackerOne's diverse pool of security researchers have reported a combined 1,397 vulnerabilities to the five platforms alone, saving an untold number of end-users from similar attacks to the ones discussed.
"You are only as secure as your weakest link. HackerOne has the largest community of security researchers, all with different skill sets, experience, and expertise, ensuring complete coverage of our assets so that no area is overlooked. Additionally, since its inception, Deribit has advocated for cryptocurrencies and the power and freedom they enable. HackerOne is one of the rare platforms that offers security researchers the possibility of receiving payments in crypto, which aligns with our values." - Xavier Bruni, Application Security Engineer at Deribit
In 2024, HackerOne saw a 147% increase in valid cryptocurrency and blockchain vulnerability reports over the previous year. Of those reports, 24% of them were classified as high or critical issues.
As the cryptocurrency and blockchain industry continues to mature and attract mainstream adoption, maintaining a strong reputation and ensuring the security of user funds becomes paramount. Companies operating in this space must prioritize security and proactively address vulnerabilities to build trust with investors and users. By partnering with HackerOne, organizations gain access to the largest pool of security researchers in the world, adding an additional layer to their security evaluation plans.