// inside head tag

Smart Contract Vulnerabilities and Mitigation Strategies

Security

November 18, 2024

Top 10 Common Smart Contract Vulnerabilities and Mitigation Strategies

Smart contracts are self-executing code that runs on the blockchain, automating tasks based on an “if-this-then-that” logic. They support DeFi applications by enabling trustless, autonomous transactions without intermediaries.

However, because smart contracts are deployed on an immutable blockchain, any coding errors or vulnerabilities become permanent, making them susceptible to various attack vectors.

According to data from the Defillama hacks page, a staggering $9.04 billion has been stolen from DeFi platforms due to various smart contract vulnerabilities.

This article explores common smart contract vulnerabilities and DeFi hacks, with general mitigation strategies for these attack vectors.

What are Smart Contract Vulnerabilities and Attack Vectors?

Smart contract vulnerabilities are flaws in the code or design of a smart contract that attackers could exploit. These are inherent risks within the contract’s code, often arising from programming errors, poor design choices, or overlooked security practices.

While vulnerabilities represent potential risks, they do not mean an attack will occur. Essentially, they create “attack surfaces” within the code that could be exploited if left unaddressed.

Attack vectors, on the other hand, refer to the methods or techniques that attackers use to exploit these vulnerabilities. In other words, an attack vector is the specific path or strategy a malicious actor uses to take advantage of a vulnerability.

Common Types of Smart Contract Vulnerabilities and Attack Vectors

Below are the common vulnerabilities that we will cover in this article.

  1. Reentrancy Attack
  2. Flash loan Attack
  3. Governance Attack
  4. Oracle Manipulation
  5. Access Control Vulnerabilities
  6. Signature Verification Exploits
  7. Math Errors
  8. Initialization Bugs
  9. Denial of Service (DoS)
  10. Sybil Attack

In the following sections, we examine these vulnerabilities and provide best security practices to prevent them.

1. Reentrancy Attack

Reentrancy attacks exploit external calls made by smart contracts before they update their own state. The called contract can recursively call back into the caller contract’s function, repeating the same function in a loop. This can result in significant financial losses as the attacker drains the contract’s funds through repeated withdrawals.

The infamous DAO hack in 2016 is one of the earliest examples of reentrancy attacks. The DAO, a decentralized investment fund, had raised over $150 million in Ether before the reentrancy attack. A reentrancy vulnerability allowed the attacker to recursively call the withdrawal function and withdraw around 3.6 million Ether.

The hack was later resolved with a hard fork in the Ethereum blockchain to restore stolen funds, resulting in two separate chains: Ethereum (ETH) and Ethereum Classic (ETC).

Mitigation Strategies:

  • Implement the CEI (checks-effects-interactions) security pattern to ensure that the contract makes state changes before calling external contracts.
  • Reentrancy guards like OpenZeppelin’s nonReentrant modifier can further prevent recursive calls by locking the contract during function execution.
  • Carry out smart contract audits to help identify and rectify potential reentrancy vulnerabilities before deployment.

2. Flash Loan Attack

Flash loan attacks exploit the ability to borrow large amounts of crypto without collateral, provided the loan is repaid within the same transaction. Attackers use these loans to manipulate on-chain data, like prices or governance votes, executing complex transactions that exploit vulnerabilities in the contract’s logic.

The flash loan attack vector is different from one protocol to another based on each smart contract’s logic. Because of this, we will not go deeper into this attack vector, but we will give you some pointers about how it usually happens.

  • The attacker borrows a large amount of tokens.
  • Executes a series of transactions that alter a contract’s state.
  • Deposits and withdraws assets in sequence exploiting the flawed logic.
  • Repays the loan, benefiting from any faulty logic.

An example is the PrismaFi flash loan attack. In this case, the attacker used a flash loan to manipulate the price of a specific asset within the protocol, allowing them to artificially inflate the asset’s value in the contract. You can read more about it on Rekt News.

Mitigation Strategies

  • Use decentralized oracles like Chainlink or Uniswap’s TWAPs to reduce price manipulation risks.
  • Set slippage limits on transactions to prevent significant price deviations.
  • Implement reentrancy guards to protect against reentrancy-based flash loan exploits.

Note that there is no universal solution for flash loan attacks; the important thing is to be mindful of this attack vector during development and try to implement checks and rules against it. Keep in mind that these rules will differ from one protocol to another.

3. Governance Attack

Governance attacks target DAOs (decentralized autonomous organizations). In this attack vector, an attacker tries to accumulate a significant amount of governance tokens to manipulate the voting process to gain control over protocol decisions.

Governance attacks include altering key parameters of the protocol, redirecting funds, or even taking over the entire protocol, depending on the governance model in place.

One instance of a governance attack is the Beanstalk governance exploit. The attacker submitted two proposals, a malicious proposal that would drain the funds, and another proposal to donate some funds to a good cause. The attacker was able to mislabel the malicious proposal, and people thought that they were voting for the “donate funds” proposal. They then manipulated the voting through a flash loan to make the proposal pass and executed the transaction to drain the protocol, stealing $181 million in the process.

Mitigation Strategies

  • Implement a time-lock security pattern for significant changes. This way, there is enough time for the community to react to and potentially counteract malicious proposals.

4. Oracle Manipulation

Oracle manipulation attacks usually target the data sources that smart contracts rely on to execute their logic. Since oracles provide off-chain data to smart contracts, their integrity and accuracy are crucial for the contract's functionality.

By tampering with these data feeds, attackers can manipulate contract behavior, often leading to financial losses.

An example of the Oracle price manipulation attack is UwULend. In this attack, the protocol did not use an established source like Chainlink to retrieve the price of the assets. Rather, they used the Curve liquidity pools when calculating the price, which introduced a potential vulnerability because liquidity pool prices can be manipulated.

To exploit this vulnerability, the attacker leveraged a flash loan to manipulate the price of the pools by changing the price of sUSDe to create an imbalance. The attacker then borrowed sUSDe at a rate of 0.99$ and liquidated this position at a manipulated rate of 1.03$ and got away with 19.4 million.

Mitigation Strategies

  • Reduce reliance on a single source and use multiple oracles to cross-verify data.
  • Consider using decentralized price feeds like Chainlink’s price feeds to retrieve the data. Since they aggregate data from multiple trusted sources, they reduce the risk of single points of failure and protect against price manipulation.
  • Don’t rely on liquidity pools to calculate the price of an asset as these can be easily manipulated.

5. Access Control Vulnerabilities

Access control vulnerabilities arise when smart contracts lack proper mechanisms to restrict unauthorized access to critical functions. This leaves the contract open for malicious actors to execute restricted functions, potentially leading to unauthorized fund transfers, changes in contract logic, or other detrimental actions.

The Visor Finance exploit in 2022 shows the potential impact of access control vulnerabilities. According to the post-mortem, the attacker contract implemented the IVisor delegateTransferERC20 interface and called the staking contract’s withdraw function with the desired amount. The protocol’s dependence on an arbitrary IVisor delegateTransferERC20 implementation by the caller enabled this attack.

Mitigation Strategies

  • It is recommended to guard the critical functions of your protocol with access controls. Ensure you properly label roles and role-based permissions and use the onlyOwner modifier.
  • Get detailed testing and code reviews to ensure that all critical functions are properly secured.

6. Signature Verification Exploits

Signature verification exploits occur when there are flaws in the process of validating signatures, which allows attackers to forge or replay valid signatures. These exploits lead to unauthorized transactions, as the system incorrectly verifies the signature’s authenticity.

The Wormhole Bridge hack in 2022 exemplifies how signature verification works. In this attack, the actor forged a valid signature to exploit the bridge.

To do this, the attacker created their own account which stored the same data as Instructions sysvar and was able to impersonate a valid signature. This thread goes into detail about how the attacker manipulated the contract.

Mitigation Strategies

  • Use a secure signature scheme like EIP-712 to reduce the risk of signature verification vulnerability.
  • Implement strong input validation checks for signatures.
  • Use nonces to prevent replay attacks.

7. Math Errors

Math errors in smart contracts are a result of incorrect calculations, including overflow and underflow issues, rounding, and other logic or accounting errors. These errors can lead to incorrect contract behavior, such as miscalculating balances, interest, or fees, which attackers can exploit.

An example of a math error attack is the Uranium Finance in 2021. In this case, the protocol team introduced a syntax error after a code change. This error allowed a user to swap 1 wei of the input token for 98% of the supply of the output token.

Mitigation Strategies

  • Use Solidity version 0.8 and above, as this automatically checks for integer overflow and underflow.
  • In the case of an earlier version of Solidity, use math libraries like OpenZeppelin's SafeMath with built-in checks for overflows and underflows.

8. Initialization Bugs

Initialization bugs occur when smart contracts are not properly initialized during deployment. These bugs allow attackers to take control of the implementation contract to manipulate its state, leading to unauthorized actions and financial losses.

An example of this vulnerability is the Parity Wallet hack, where an attacker was able to set their address as the owner state variable and disabled the contract, freezing ~$150 million.

Mitigation Strategies

  • Ensure all contracts are properly initialized during deployment. Double-check that they can not be reinitialized or initialized by any unauthorized third party.
  • We recommend using OpenZeppelin’s library when developing upgradable protocols to keep track of initialization.

9. Denial of Service (DoS)

Denial of Service (DoS) attacks aim to make a smart contract unusable. A DoS attack can take many shapes and can be any type of vulnerability that can render the whole protocol or parts of it unusable. These attacks prevent legitimate users from accessing or interacting with the contract, disrupting normal operations.

For example, in the King of Ether game, a user becomes “king” by sending the highest ETH amount to the contract. A malicious king could exploit this by deploying a contract with a receive()  function that always reverts. When another player attempts to overthrow the king, the transaction fails as the ETH cannot be sent back, effectively locking in the malicious king and causing a denial-of-service (DoS) attack that prevents others from playing. For a hands-on example, see Ethernaut’s challenge level 9.

Mitigation Strategy

  • DoS vulnerability can come in different forms and there isn’t a one-size-fits-all solution to prevent them. The best way to prevent DoS is through regular code reviews and smart contract audits to deal with any security loophole.

10. Sybil Attack

Sybil attacks in the context of Web3 involve creating multiple addresses to gain an unfair advantage in a decentralized context. By using numerous addresses, an attacker can manipulate voting mechanisms, airdrop distributions, or other processes that rely on user participation.

In a Sybil attack, a malicious actor creates multiple accounts/addresses to gain a larger share of the protocol/rewards, skewing the results in their favor.

For example, a voting function with no access controls can be Sybil attacked by a user that creates 1000 addresses and votes with all of them instead of using a single address, as expected.

Mitigation Strategy

  • Implement a mechanism that forces users to incur some cost when calling critical functions in the system. By adding a cost to the transactions, malicious actors are disincentivized to create multiple addresses, because they will incur the cost multiple times.

Again, this is not an all-in-one solution, and mitigating it will require a personalized solution for your protocol.

Conclusion

Smart contract vulnerabilities pose significant risks to the DeFi ecosystem. So, understanding these vulnerabilities and implementing robust mitigation strategies is essential for the stability of a protocol.

In this article, we’ve covered common vulnerabilities and smart contract attack vectors with tips on how to avoid them. Regardless of how secure you think your smart contract is, it is important to get a smart contract audit.

Remember, regular audits, implementing security best practices in your coding, and staying updated with the latest security trends can help you prevent most of these threats.

For more pointers about how to write secure code, check out our articles about the best practices for writing secure smart contracts and Onchain Security.

Stay secure and informed by following our blog for the latest updates on smart contract security. Not sure how to handle your security review, you can book a consultation with us to discuss your project’s security needs.

Disclaimer: This article has been prepared for the general information and understanding of the readers. No representation or warranty, express or implied, is given by Nethermind or Nethermind Security as to the accuracy or completeness of the information or opinions contained in the above article, or as to the quality of any code or project that may be developed by the reader.

Latest articles