Explain in detail the security vulnerabilities of Ethereum smart contracts, how to effectively reduce DeFi attacks?

0

 272 total views

What are the smart contract vulnerabilities in the Ethereum application layer, data layer, consensus layer, and network layer?

Title of the original text: “Exploring the Vulnerabilities of Decentralized Finance (DeFi) Blockchain Smart Contracts”
Written by: Abba Garba, WeBlock CTO
Translation: HAO

Blockchain is a new type of distributed system system, which uses P2P peer-to-peer network communication, block storage, distributed algorithm consensus and encryption algorithm to prevent tampering. In essence, the blockchain can be seen as a distributed database maintained by all network nodes. Compared with traditional distributed databases, blockchain is more suitable for applications that have clear requirements for decentralized trust due to its complete data backup, open and transparent network, no tampering, complete information traceability and weak trust model Scenes. In particular, typical blockchain application scenarios include digital payment, product traceability, copyright protection, supply chain finance, etc. In the blockchain system, smart contracts play an extremely important role in implementing distributed application deployment and expanding application functions. Compared with traditional applications, the blockchain system has the characteristics of openness, transparency, execution, non-tamperability, and non-reliance on third parties, and the smart contracts running on the blockchain system architecture can satisfy various decentralized applications. The needs of the scene, including the rapid development of decentralized finance (DeFi) projects in recent years.

As of January 15, 2021, Decentralized Finance (DeFi) has become a successful financial paradigm with more than US$4.5 billion in capital. It uses blockchain-based smart contracts to ensure its integrity and security. Decentralized finance is a new development area for the exchange, lending or borrowing of tokens. Usually, these instructions are regulated by smart contracts (rather than a single centralized legal person or individual) and/or controlled by a multi-party, decentralized governance mechanism (such as DAO) to control the “revenue” or income flow. Decentralized Finance (DeFi)-gradually emerging on top of the existing blockchain platform. The components of this new field include those related to loans, asset trading and derivatives markets. As a decentralized application, smart contracts manage a large number of digital assets, which also makes them vulnerable to various attacks.

This article will elaborate on the security of smart contracts from three dimensions: First, the security of smart contracts due to loopholes in each layer of the Ethereum architecture. Secondly, various recent attacks on DeFi and smart contracts will also be discussed. Finally, we will discuss how existing feasible tools and other effective practices can minimize such attacks.

Smart contract vulnerabilities in different layers of the Ethereum architecture

Ethereum architecture overview

Before discussing the vulnerabilities of smart contracts, let us briefly outline the architecture of Ethereum smart contracts.

The blockchain network can deploy and automatically execute programming script tasks. These programs are called smart contracts and are used to define custom functions and rules to be called during the transaction. Blockchain technology based on smart contracts has been applied to various industries, such as finance, supply chain management, healthcare energy, and government services. Only certain blockchain platforms support smart contracts: Ethereum is the first to support smart contracts. Other blockchain platforms (such as EOS, Lisk, Bitcoin and Hyperledger Fabric) are compatible with the deployment and execution of smart contracts. A script type language called Solidity is used to develop smart contracts in the Ethereum platform. In this part, we introduced the security vulnerabilities related to the implementation of smart contracts on the Ethereum platform. Smart contracts can hold and manage the corresponding function Credit (address) {a large number of virtual currencies that may be worth thousands of dollars. Therefore, opponents constantly try to manipulate the execution of smart contracts to support their activities. Essentially, smart contracts run on a distributed and permissionless network, which inherits many vulnerabilities. In traditional systems, this small part of the centralized application can be re-developed or patched.

On the contrary, in a decentralized blockchain network, unless extreme measures are taken, the deployed smart contract cannot be modified or upgraded in the real-time network. The unchanging feature of smart contracts is their security advantages and disadvantages. Because of this immutability, hackers cannot change or modify the contract for their own benefit. However, developers cannot modify the smart contract application after deployment. They can cancel or terminate the contract and create a new smart contract, and then deploy it again. Therefore, due to security considerations, a large-scale test of the smart contract should be carried out before deploying the smart contract. We focused on the basic building blocks of the Ethereum smart contract architecture, as shown in Figure 1, which includes the Ethereum architecture.

Figure 1: The environment used to run the Ethereum blockchain is to interact with the four layers of the Ethereum architecture service through a Web user interface. The application layer is a database for storing blockchain data and supporting consensus protocols. Encryption mechanism and Internet services used at the network layer [20]

Application layer: The Ethereum client executes smart contracts in the EVM, where the smart contract is associated with the Ethereum account. Ethereum supports two types of accounts: externally owned accounts (EOA) and contract accounts. EOA is used to store user funds in Wei, which is the smallest sub-denomination of Ether and is worth 10-18 Ether. EOA is associated with the public key and resolved by the public key; access to EOA is verified by showing the ownership of the corresponding private key. Instead, a contract account is associated with a piece of executable bytecode (ie, a smart contract), which defines some interesting business logic. Smart contracts are the cornerstone of DApps. DApp usually uses the user interface as its front end and some smart contracts as its back end. Some DApps will issue their own cryptocurrencies called tokens for initial coin offering (ICO) and exchanges. Ethereum-based tokens are a special type of smart contract (such as ERC-20) [20]. Smart contracts are executed in EVMs, which are quasi-Turing complete machines using a stack-based architecture. The term “quasi” means that the execution is limited by the gas provided by the transaction. In the application layer of Ethereum, various vulnerabilities occur, leading to many attacks, as shown in the diagram in the application layer.

Data layer: contains the blockchain data structure. A transaction is an interaction between an EOA (called the sender) and another EOA or contract account (called the recipient). The transaction is specified in the following way:

  1. nonce, which is a counter used to track the total number of transactions initiated by the sender;
  2. Recipient, the recipient specifies the target EOA or contract account of the transaction;
  3. Value, that is, the amount transferred from the sender to the payee (unit: Wei) (if applicable);
  4. Input is the bytecode or data corresponding to the purpose of the transaction;
  5. gasPrice and gasLimit, respectively specify the unit price and the maximum amount of gas that the sender is willing to pay to the winning miner of the block containing the transaction;
  6. (V, r, s), it is the sender’s elliptic curve digital signature algorithm (ECDSA) signature. Executing the transaction will update the state of the account involved, thereby updating the blockchain.

Consensus layer: to ensure that the state of the blockchain is consistent. At the time of writing, Ethereum takes approximately 12-14 seconds to create a block, which means that multiple miners can create valid blocks at the same time, and there may be many blocks. Ethereum uses a variant of the GHOST consensus protocol to select the “heaviest” branch as the main chain, where the “heaviest” branch is rooted in the subtree of the fork in question, and has the highest cumulative block difficulty, while noting the obsolescence The block is not on the main chain. But note that Ethereum uses Proof of Stake (PoS) to replace its current Proof of Work (PoW).

Network layer: An Ethereum peer-to-peer (P2P) network that manages nodes or clients, so that nodes can always obtain the updated status of the blockchain from certain active nodes. The Ethereum network is a structured P2P network in which each node (i.e. client) stores a copy of the entire blockchain. For node discovery and routing, each node maintains a dynamic routing table, which contains 160 buckets, and each bucket contains up to 16 other node IDs, IP addresses, and UDP/TCP port entries. Ethereum uses the RLPx protocol to discover the target client, and uses the Ethereum wire protocol to facilitate the exchange of Ethereum blockchain information (such as transactions, blocks) between the clients.

Ethereum blockchain environment: running in the following four-layer environment: the web interface for users to interact with the Ethereum blockchain; the database of Ethereum customers, which is used to store blockchain data; the encryption mechanism for security purposes ; And the Internet infrastructure that supports blockchain communication between Ethereum nodes. We distinguish the Ethereum blockchain architecture from the environment, because attacks on the Ethereum blockchain may come from the environment, and these attacks may be better solved in the environment instead of being solved by Ethereum.

Ethereum smart contract vulnerabilities

It focuses on the smart contract vulnerabilities in each layer of the Ethereum system, as shown in Figure 2.

Explain in detail the security vulnerabilities of Ethereum smart contracts. How to effectively reduce DeFi attacks?Figure 2: Classification of vulnerabilities in each layer of Ethereum

Ethereum application layer

  • Reentrancy: This vulnerability was originally discovered from the DAO attack[1]. When the external callee contract calls back the function in the caller contract before the user contract is completed (that is, it is a cyclic call in a sense), it will This vulnerability occurs. This allows the attacker to bypass appropriate validity checks until the caller’s contract is exhausted or the transaction runs out.

  • Delegated call injection: This vulnerability was first discovered from the attack on Parity Wallet [2]. In order to promote code reuse, EVM provides an opcode delegation call, which is used to insert the bytecode of the callee contract into the bytecode of the caller contract. As a result, the malicious callee contract can directly modify (or manipulate) the state variables of the caller contract. This vulnerability is caused by the fact that the callee contract can update the state variables of the caller contract. The statement aims to call a stateless contract shared as a library through delegated calls, which can completely prevent this vulnerability.

  • Frozen Ether: This vulnerability was discovered for the first time from the attack on Parity Wallet [3]. The vulnerability occurred because users were unable to deposit money into their contract accounts and were unable to spend funds from these accounts, effectively freezing their funds.

  • Upgrade contract: The idea of ​​introducing contract upgrade is to alleviate the problem that smart contracts cannot be modified once deployed, even if they are found to have loopholes in the future. In order to allow contract upgrades, there are two methods: (i) divide the contract into proxy contracts and logical contracts so that developers can upgrade the latter instead of the former; (ii) use registry contracts to save the updated contracts. Although these methods are effective, they introduce a new vulnerability: when the contract developer becomes malicious, the updated contract may be malicious. This vulnerability (ie, insecure contact update) is still an unresolved issue.

  • DoS with accidental restoration: This happens because the calling party contract encounters an external call failure and the transaction is restored, or the called party contract deliberately performs a restoration operation to interrupt the execution of the calling party contract. This vulnerability is caused by the execution of the caller contract restored by the caller contract. By enabling the receiver to call the transaction to “extract” the funds reserved by the sender for the receiver, this loophole can be prevented, thereby effectively preventing the sender’s transaction from being restored.

  • Integer overflow and underflow: This vulnerability was discovered for the first time in an attack against BEC tokens [4]. This happens when the result of the operation exceeds the range of the Solidity data type, for example, leading to unauthorized manipulation of the attacker’s balance or other state variables. The vulnerability is caused by the Solidity source code not performing correct verification on digital inputs, and neither the Solidity compiler nor the EVM provides integer overflow/underflow detection. This vulnerability can be prevented by using the SafeMath library to deal with these problems.

  • Manipulating balance: This vulnerability occurs when the control flow decision of the contract depends on this value. To balance or balance the balance, an attacker can use it to make himself the only person who can get money. This vulnerability can be prevented by not using any contract balance in the condition statement [5]. Authentication via tx.origin: tx.origin is a global variable in Solidity, which refers to the original EOA that initiated the problematic transaction. This vulnerability occurs when the contract uses tx.origin for authorization, which may be compromised by phishing attacks. This vulnerability can be prevented by using msg.sender instead of tx.origin for authentication, because msg.sender returns the account that caused the message.

  • Incorrect visibility: The visibility of features is incorrectly specified, allowing unauthorized access.

  • Unprotected suicide: The owner of the contract (or an entrusted third party) can use suicide or self-destruction methods to destroy the contract. When the contract is cancelled, its associated bytecode and storage will be deleted. The vulnerability is caused by insufficient identity verification enforced by the contract. This vulnerability can be mitigated by enforcing, for example, multi-factor authentication, which means that suicide operations must be approved by multiple parties.

  • Leaking Ether to any address: When any caller can withdraw funds from the contract, the loophole will not occur. The caller is neither the owner of the contract nor the investor who deposits funds into the contract. This vulnerability is caused by the inability to check the identity of the caller when the caller invokes the function of sending ether to an arbitrary address. This vulnerability can be prevented by proper authentication of the function of sending funds.

  • Confidentiality failure: In the blockchain, due to the public nature of the blockchain (that is, the transaction details are well-known), restricting the visibility of variables or functions does not ensure that the variables or functions are confidential. One possible solution to prevent this vulnerability is to use encryption techniques, such as timing commitments [6].

  • Insufficient signature information: This vulnerability occurs when the digital signature is valid for multiple transactions. When a sender (such as Alice) sends money to multiple recipients through a proxy contract (rather than initiate multiple transactions), it may This vulnerability can occur. This vulnerability was originally exploited in a replay attack against smart contracts. This vulnerability can be prevented by incorporating appropriate information (such as current value and timestamp) in each message.

  • DoS with unrestricted operations: This vulnerability was first observed in the Govern Mental contract [7].

  • Unchecked call return value: This vulnerability is also known as an exception for handling errors. It has two variants, called gas-less sending and unchecked sending. This situation occurs when the return value of the low-level call is not checked, and execution may continue even if the function call throws an error [8].

  • Uninitialized storage pointer: Looking back, in Solidity, contract state variables are always placed in storage continuously starting from slot 0. For compound local variables (for example, struct, array, or mapping), assign references to slots in unoccupied object storage to point to state variables.

  • Wrong constructor function name: This vulnerability was originally observed from the Rubixi contract [9]. The name of the constructor function is incorrect. It allows anyone to become the owner of the contract. Before Solidity 0.4.22, a function declared with the same name as the contract was regarded as a contract constructor, and this function was only executed when the contract was created.

  • Type conversion: This vulnerability was first discovered in [10]. A contract written in Solidity language can call another contract by directly referencing an instance of the callee contract.

  • Outdated compiler version: Occurs when a contract uses an outdated compiler, which contains errors, thus making the compiled contract vulnerable to attack. This vulnerability can be prevented by using the latest compiler.

  • Short address: This vulnerability was first implemented in [11] and has been extensively discussed.

  • Ether lost to an isolated address: Ether lost to isolation occurs when remittances, Ethereum only checks that the length of the recipient’s address does not exceed 160 digits, and does not check the validity of the recipient’s address. If money is sent to an isolated address that does not exist, Ethereum will automatically register the address instead of terminating the transaction. Since the address is not associated with any EOA or contract account, no one can withdraw the transferred funds, which is actually lost. This vulnerability is caused by the inability of EVM to isolate protection. At the time of writing, this vulnerability can only be prevented by manually ensuring the correctness of the recipient address.

  • Call stack depth limitation: This vulnerability is caused by the insufficient execution model of EVM and has been eliminated by the hard fork of EIP-150, which redefines the fuel consumption rules of external calls, making it impossible to reach 1,024 in Call stack depth.

  • Underestimated opcode: This vulnerability was first discovered from two DoS attacks [12] [13].

  • Transaction order dependency (also known as front-end operation): This refers to concurrency issues, that is, the upcoming state of the blockchain depends on the execution order of transactions, but is determined by the miners.

  • Time dependency: This vulnerability occurs when the contract uses block.timestamp as part of the trigger condition or as a source of randomness that can be manipulated by malicious miners when performing key operations (such as remittances). The vulnerability is caused by Ethereum, which only requires the timestamp to be greater than the timestamp of its parent block and within 900 seconds of the current clock.

  • Generate randomness: For example, many gambling and lottery contracts randomly select winners. The usual practice is to generate pseudo-random numbers based on some initial private seeds (such as block.number, block.timestamp, block.difficulty or blockhash). However, these seeds are fully controlled by miners, which means that malicious miners can manipulate these variables to make themselves a winner. This vulnerability is caused by a manipulable entropy source.

Data layer vulnerabilities

  • Indistinguishable chains: When Ethereum was divided into two chains, ETH and ETC [13], this vulnerability was first observed from cross-chain replay attacks. Recall that Ethereum uses ECDSA to sign transactions. Before the EIP-155 [7] hard fork, each transaction contained six fields (ie, random number, recipient, value, input, gasPrice and gasLimit). However, digital signatures are not chain-specific, because chain-specific information is not even known at that time. As a result, transactions created for one chain can be reused by another chain. This vulnerability has been eliminated by merging the chainID into the field.

  • “Empty Account” in State Trie: This vulnerability was first discovered from a DoS attack reported in References [12] [13].

Vulnerabilities in the consensus layer

  • The problem that can be outsourced: Recall that Ethereum adopted a PoW problem called Ethash, which is designed to resist ASICs and limit the use of parallel computing (due to the fact that most of the work of miners will be reading data sets. Passing limited Memory bandwidth). However, cunning miners can still divide the task of searching for solutions to difficult problems into multiple smaller tasks and then outsource them. The vulnerability is caused by Ethash, which only makes the puzzle solution partially sequential in the original image search, instead of relying on sequential PoW.

  • Probabilistic finality: This vulnerability is caused by the design of the Ethereum blockchain that prefers availability rather than consistency, which is selected according to the CAP theorem [14].

  • DoS with block padding: This vulnerability was first observed in the Fomo3D contract [15]. The vulnerability only caused the attacker’s transaction to be included in the newly mined block, while other transactions were abandoned by the miners for a period of time. This can happen when the attacker provides a higher gasPrice to incentivize miners to choose the attacker’s transaction. This vulnerability is caused by a greedy mining incentive mechanism. At the time of writing, there is no solution to prevent this vulnerability.

  • Honest mining assumption: This vulnerability is caused by the consensus protocol because it is incompatible with incentives, see [16]. At the time of writing, this vulnerability is still an unresolved issue.

  • Block reward: It refers to the block reward mechanism, which is used to deal with the increase of stale blocks due to the rapid generation of blocks. However, this mechanism has a side effect, that is, allowing selfish miners to turn old blocks into blocks and get rewards, thereby effectively incentivizing selfish mining and double spending.

  • Verifier’s dilemma: This vulnerability was first reported in Reference [17] and refers to when a new transaction requires effortless calculations, regardless of whether the miner chooses to verify the transaction, it will be attacked. If the miners verify the computationally intensive transactions, they will spend a lot of time and provide an advantage to the attacker in the next block competition; if the miners accept the transaction without verification, the blockchain may contain incorrect transactions. This vulnerability is caused by the high cost of validating resource demand transactions in Ethereum. This vulnerability can be mitigated by limiting the amount of computation required to verify all transactions in the block [17]. However, it is not clear how to eliminate this vulnerability.

Vulnerabilities in the network layer

  • Creation of infinite nodes: This vulnerability is for Geth client versions prior to 1.8. In the Ethereum network, each node is identified by a unique ID, which is a 64-byte ECDSA public key. An attacker can create an unlimited number of nodes (that is, with the same IP address) on a computer, and then use these nodes to monopolize the incoming and outgoing connections of certain victim nodes, thereby effectively connecting the victim to the network. Isolate other peer nodes. This vulnerability is caused by weak restrictions on the node generation process. This vulnerability can be eliminated by using a combination of IP address and public key as the node ID. The Geth developers have not yet adopted this countermeasure, which they believe has a negative impact on the usability of the client.

  • Unrestricted incoming connections: This vulnerability is in the Geth client prior to version 1.8 [18]. Each node can have a total of maxpeers connections (the default value is 25) at any point in time, and can initiate up to 1 (1 + maxpeers)/2⌋ outbound TCP connections with other nodes. However, there is no upper limit on the number of incoming TCP connections initiated by other nodes. By establishing many incoming connections for maxpeers to victim nodes that do not have outbound connections, the attacker has the opportunity to overshadow the victim. In Geth v1.8, by imposing an upper limit on the number of incoming TCP connections to the node, the default value is ⌊maxpeers/3⌋= 8, which eliminates this vulnerability.

  • Public peer selection: This vulnerability was detected in Geth client versions prior to 1.8 [18].

  • Peer selection: This vulnerability refers to the fact that when the Geth client selects a node from its routing table to establish an outbound connection, it always obtains the header of a randomly selected bucket. Since the nodes in each bucket are sorted by activity, an attacker can send a message to the Geth client regularly to keep the node in front of other nodes. By randomly selecting a uniform node from the set of all nodes in the routing table, instead of randomly selecting a node from the header of each bucket, this vulnerability has been eliminated in Geth v1.9.

  • Independent block synchronization: It allows attackers to partition the Ethereum P2P network without monopolizing the connection of the victim’s client. Recall that each block header contains a difficulty field, which records the difficulty of mining the block. The total difficulty of the blockchain is represented by totalDifficulty, which is the sum of the difficulty up to the current block.

  • RPC API exposure: This vulnerability was originally discovered through attacks on Geth and Parity clients [19].

Explain in detail the security vulnerabilities of Ethereum smart contracts. How to effectively reduce DeFi attacks?

Quote:

[1] https://www.coindesk.com/understanding-dao-hack-journalists

[2] https://www.freecodecamp.org/news/a-hacker-stole-31m-of-ether-how-it-happened-and-what-it-means-for-ethereum-9e5dc29e33ce/

[3] https://medium.com/blockcat/on-the-parity-multi-sig-wallet-attack-83fb5e7f4b8c

[4] https://nvd.nist.gov/vuln/detail/CVE-2018-10299

[5] https://medium.com/loom-network/how-to-secure-your-smart-contracts-6-solidity-vulnerabilities-and-how-to-avoid-them-part-2-730db0aa4834

[6] https://eprint.iacr.org/2016/1007.pdf

[7] https://www.reddit.com/r/ethereum/comments/4ghzhv/governmentals_1100_eth_jackpot_payout_is_stuck/

[8] https://github.com/KadenZipfel/smart-contract-attack-vectors/blob/master/vulnerabilities/unchecked-call-return-value.md

[9] https://medium.com/hackernoon/hackpedia-16-solidity-hacks-vulnerabilities-their-fixes-and-real-world-examples-f3210eba5148

[10] https://medium.com/golem-project/how-to-find-10m-by-just-reading-blockchain-6ae9d39fcd95

[11] https://medium.com/loom-network/how-to-secure-your-smart-contracts-6-solidity-vulnerabilities-and-how-to-avoid-them-part-2-730db0aa4834

[12] https://blog.ethereum.org/2016/09/22/transaction-spam-attack-next-steps/

[13]https://blog.comae.io/the-280m-ethereums-bug-f28e5de43513?gi=3b0603be9186

[14] https://dl.acm.org/doi/10.1145/3149.214121

[15] https://medium.com/coinmonks/how-the-winner-got-fomo3d-prize-a-detailed-explanation-b30a69b7813f

[16] https://dl.acm.org/doi/10.1145/3212998

[17] https://dl.acm.org/doi/10.1145/2810103.2813659

[18] https://ljk.imag.fr/membres/Jean-Guillaume.Dumas/Enseignements/ProjetsCrypto/Ethereum/236.pdf

[19] https://mp.weixin.qq.com/s/ia9nBhmqVEXiiQdFrjzmyg

[20] https://dl.acm.org/doi/fullHtml/10.1145/3391195

Disclaimer: As a blockchain information platform, the articles published on this site only represent the author’s personal views, and have nothing to do with the position of ChainNews. The information, opinions, etc. in the article are for reference only, and are not intended as or regarded as actual investment advice.