Preventative Techniques
Solidity provides the library keyword for implementing library contracts (see the docs for further details). This ensures the library contract is stateless and non-self-destructable. Forcing libraries to be stateless mitigates the complexities of storage context demonstrated in this section. Stateless libraries also prevent attacks wherein attackers modify the state of the library directly in order to affect the contracts that depend on the library’s code. As a general rule of thumb, when using DELEGATECALL pay careful attention to the possible calling context of both the library contract and the calling contract, and whenever possible build stateless libraries.
Real-World Example: Parity Multisig Wallet (Second Hack)
The Second Parity Multisig Wallet hack is an example of how well-written library code can be exploited if run outside its intended context. There are a number of good explanations of this hack, such as “Parity Multisig Hacked. Again” and “An In-Depth Look at the Parity Multisig Bug”.
To add to these references, let’s explore the contracts that were exploited. The library and wallet contracts can be found on GitHub.
The library contract is as follows:
contract WalletLibrary is WalletEvents { ... // throw unless the contract is not yet initialized. modifier only_uninitialized { if (m_numOwners > 0) throw; _; } // constructor - just pass on the owner array to multiowned and // the limit to daylimit function initWallet(address[] _owners, uint _required, uint _daylimit) only_uninitialized { initDaylimit(_daylimit); initMultiowned(_owners, _required); } // kills the contract sending everything to `_to`. function kill(address _to) onlymanyowners(sha3(msg.data)) external { suicide(_to); } ... }
And here's the wallet contract:
contract Wallet is WalletEvents { ... // METHODS // gets called when no other function matches function() payable { // just being sent some cash? if (msg.value > 0) Deposit(msg.sender, msg.value); else if (msg.data.length > 0) _walletLibrary.delegatecall(msg.data); } ... // FIELDS address constant _walletLibrary = 0xcafecafecafecafecafecafecafecafecafecafe; }
Notice that the Wallet contract essentially passes all calls to the WalletLibrary contract via a delegate call. The constant _walletLibrary address in this code snippet acts as a placeholder for the actually deployed WalletLibrary contract (which was at 0x863DF6BFa4469f3ead0bE8f9F2AAE51c91A907b4).
The intended operation of these contracts was to have a simple low-cost deployable Wallet contract whose codebase and main functionality were in the WalletLibrary contract. Unfortunately, the WalletLibrary contract is itself a contract and maintains its own state. Can you see why this might be an issue?
It is possible to send calls to the WalletLibrary contract itself. Specifically, the WalletLibrary contract could be initialized and become owned. In fact, a user did this, calling the initWallet function on the WalletLibrary contract and becoming an owner of the library contract. The same user subsequently called the kill function. Because the user was an owner of the library contract, the modifier passed and the library contract self-destructed. As all Wallet contracts in existence refer to this library contract and contain no method to change this reference, all of their functionality, including the ability to withdraw ether, was lost along with the WalletLibrary contract. As a result, all ether in all Parity multisig wallets of this type instantly became lost or permanently unrecoverable.
Default Visibilities
Functions in Solidity have visibility specifiers that dictate how they can be called. The visibility determines whether a function can be called externally by users, by other derived contracts, only internally, or only externally. There are four visibility specifiers, which are described in detail in the Solidity docs. Functions default to public, allowing users to call them externally. We shall now see how incorrect use of visibility specifiers can lead to some devastating vulnerabilities in smart contracts.
The Vulnerability
The default visibility for functions is public, so functions that do not specify their visibility will be callable by external users. The issue arises when developers mistakenly omit visibility specifiers on functions that should be private (or only callable within the contract itself).
Let's quickly explore a trivial example:
contract HashForEther { function withdrawWinnings() { // Winner if the last 8 hex characters of the address are 0 require(uint32(msg.sender) == 0); _sendWinnings(); } function _sendWinnings() { msg.sender.transfer(this.balance); } }
This simple contract is designed to act as an address-guessing bounty game. To win the balance of the contract, a user must generate an Ethereum address whose last 8 hex characters are 0. Once achieved, they can call the withdrawWinnings function to obtain their bounty.
Unfortunately, the visibility of the functions has not been specified. In particular, the _sendWinnings function is public (the default), and thus any address can call this function to steal the bounty.
Preventative Techniques
It is good practice to always specify the visibility of all functions in a contract, even if they are intentionally public. Recent versions of solc show a warning for functions that have no explicit visibility set, to encourage this practice.
Real-World Example: Parity Multisig Wallet (First Hack)
In the first Parity multisig hack, about $31M worth of Ether was stolen, mostly from three wallets. A good recap of exactly how this was done is given by Haseeb Qureshi.
Essentially, the multisig wallet is constructed from a base Wallet contract, which calls a library contract containing the core functionality (as described in Real-World Example: Parity Multisig Wallet (Second Hack)). The library contract contains the code to initialize the wallet, as can be seen from the following snippet:
contract WalletLibrary is WalletEvents { ... // METHODS ... // constructor is given number of sigs required to do protected // "onlymanyowners" transactionsas well as the selection of addresses // capable of confirming them function initMultiowned(address[] _owners, uint _required) { m_numOwners = _owners.length + 1; m_owners[1] = uint(msg.sender); m_ownerIndex[uint(msg.sender)] = 1; for (uint i = 0; i < _owners.length; ++i) { m_owners[2 + i] = uint(_owners[i]); m_ownerIndex[uint(_owners[i])] = 2 + i; } m_required = _required; } ... // constructor - just pass on the owner array to multiowned and // the limit to daylimit function initWallet(address[] _owners, uint _required, uint _daylimit) { initDaylimit(_daylimit); initMultiowned(_owners, _required); } }
Note that neither of the functions specifies their visibility, so both default to public. The initWallet function is called in the wallet's constructor, and sets the owners for the multisig wallet as can be seen in the initMultiowned function. Because these functions were accidentally left public, an attacker was able to call these functions on deployed contracts, resetting the ownership to the attacker's address. Being the owner, the attacker then drained the wallets of all their ether.
Entropy Illusion
All transactions on the Ethereum blockchain are deterministic state transition operations. This means that every transaction modifies the global state of the Ethereum ecosystem in a calculable way, with no uncertainty. This has the fundamental implication that there is no source of entropy or randomness in Ethereum. Achieving decentralized entropy (randomness) is a well-known problem for which many solutions have been proposed, including RANDAO, or using a chain of hashes, as described by Vitalik Buterin in the blog post “Validator Ordering and Randomness in PoS”.
The Vulnerability
Some of the first contracts built on the Ethereum platform were based around gambling. Fundamentally, gambling requires uncertainty (something to bet on), which makes building a gambling system on the blockchain (a deterministic system) rather difficult. It is clear that the uncertainty must come from a source external to the blockchain. This is possible for bets between players (see for example the commit–reveal technique); however, it is significantly more difficult if you want to implement a contract to act as “the house” (like in blackjack or roulette). A common pitfall is to use future block variables—that is, variables containing information about the transaction block whose values are not yet known, such as hashes, timestamps, block numbers, or gas limits. The issue with these are that they are controlled by the miner who mines the block, and as such are not truly random. Consider, for example, a roulette smart contract with logic that returns a black number if the next block hash ends in an even number. A miner (or miner pool) could bet $1M on black. If they solve the next block and find the hash ends in an odd number, they could happily not publish their block and mine another, until they find a solution with the block hash being an even number (assuming the block reward and fees are less than $1M). Using past or present variables can be even more devastating, as Martin Swende demonstrates in his excellent blog post. Furthermore, using solely block variables means that the pseudorandom number will be the same for all transactions in a block, so an attacker can multiply their wins by doing many transactions within a block (should there be a maximum bet).
Preventative Techniques
The source of entropy (randomness) must be external to the blockchain. This can be done among peers with systems such as commit–reveal, or via changing the trust model to a group of participants (as in RandDAO). This can also be done via a centralized entity that acts as a randomness oracle. Block variables (in general, there are some exceptions) should not be used to source entropy, as they can be manipulated by miners.
Real-World Example: PRNG Contracts
In February 2018 Arseny Reutov blogged about his analysis of 3,649 live smart contracts that were using some sort of pseudorandom number generator (PRNG); he found 43 contracts that could be exploited.
External Contract Referencing
One of the benefits of the Ethereum “world computer” is the ability to reuse code and interact with contracts already deployed on the network. As a result, a large number of contracts reference external contracts, usually via external message calls. These external message calls can mask malicious actors' intentions in some nonobvious ways, which we'll now examine.
The Vulnerability
In Solidity, any address can be cast to a contract, regardless of whether the code at the address represents the contract type being cast. This can cause problems, especially when the author of the contract is trying to hide malicious code. Let's illustrate this with an example.
Consider a piece of code like Rot13Encryption.sol, which rudimentarily implements the ROT13 cipher.
Rot13Encryption.sol
// encryption contract contract Rot13Encryption { event Result(string convertedString); // rot13-encrypt a string function rot13Encrypt (string text) public { uint256 length = bytes(text).length; for (var i = 0; i < length; i++) { byte char = bytes(text)[i]; // inline assembly to modify the string assembly { // get the first byte char := byte(0,char) // if the character is in [n,z], i.e. wrapping if and(gt(char,0x6D), lt(char,0x7B)) // subtract from the ASCII number 'a', // the difference between character <char> and 'z' { char:= sub(0x60, sub(0x7A,char)) } if iszero(eq(char, 0x20)) // ignore spaces // add 13 to char {mstore8(add(add(text,0x20), mul(i,1)), add(char,13))} } } emit Result(text); } // rot13-decrypt a string function rot13Decrypt (string text) public { uint256 length = bytes(text).length; for (var i = 0; i < length; i++) { byte char = bytes(text)[i]; assembly { char := byte(0,char) if and(gt(char,0x60), lt(char,0x6E)) { char:= add(0x7B, sub(char,0x61)) } if iszero(eq(char, 0x20)) {mstore8(add(add(text,0x20), mul(i,1)), sub(char,13))} } } emit Result(text); } }
This code simply takes a string (letters a–z, without validation) and encrypts it by shifting each character 13 places to the right (wrapping around z); i.e., a shifts to n and x shifts to k. The assembly in the preceding contract does not need to be understood to appreciate the issue being discussed, so readers unfamiliar with assembly can safely ignore it.
Now consider the following contract, which uses this code for its encryption:
import "Rot13Encryption.sol"; // encrypt your top-secret info contract EncryptionContract { // library for encryption Rot13Encryption encryptionLibrary; // constructor - initialize the library constructor(Rot13Encryption _encryptionLibrary) { encryptionLibrary = _encryptionLibrary; } function encryptPrivateData(string privateInfo) { // potentially do some operations here encryptionLibrary.rot13Encrypt(privateInfo); } }
The issue with this contract is that the encryptionLibrary address is not public or constant. Thus, the deployer of the contract could give an address in the constructor that points to this contract:
// encryption contract contract Rot26Encryption { event Result(string convertedString); // rot13-encrypt a string function rot13Encrypt (string text) public { uint256 length = bytes(text).length; for (var i = 0; i < length; i++) { byte char = bytes(text)[i]; // inline assembly to modify the string assembly { // get the first byte char := byte(0,char) // if the character is in [n,z], i.e. wrapping if and(gt(char,0x6D), lt(char,0x7B)) // subtract from the ASCII number 'a', // the difference between character <char> and 'z' { char:= sub(0x60, sub(0x7A,char)) } // ignore spaces if iszero(eq(char, 0x20)) // add 26 to char! {mstore8(add(add(text,0x20), mul(i,1)), add(char,26))} } } emit Result(text); } // rot13-decrypt a string function rot13Decrypt (string text) public { uint256 length = bytes(text).length; for (var i = 0; i < length; i++) { byte char = bytes(text)[i]; assembly { char := byte(0,char) if and(gt(char,0x60), lt(char,0x6E)) { char:= add(0x7B, sub(char,0x61)) } if iszero(eq(char, 0x20)) {mstore8(add(add(text,0x20), mul(i,1)), sub(char,26))} } } emit Result(text); } }
This contract implements the ROT26 cipher, which shifts each character by 26 places (i.e., does nothing). Again, there is no need to understand the assembly in this contract. More simply, the attacker could have linked the following contract to the same effect:
contract Print{ event Print(string text); function rot13Encrypt(string text) public { emit Print(text); } }
If the address of either of these contracts were given in the constructor, the encryptPrivateData function would simply produce an event that prints the unencrypted private data.
Although in this example a library-like contract was set in the constructor, it is often the case that a privileged user (such as an owner) can change library contract addresses. If a linked contract doesn’t contain the function being called, the fallback function will execute. For example, with the line encryptionLibrary.rot13Encrypt(), if the contract specified by encryptionLibrary was:
contract Blank { event Print(string text); function () { emit Print("Here"); // put malicious code here and it will run } }
then an event with the text Here would be emitted. Thus, if users can alter contract libraries, they can in principle get other users to unknowingly run arbitrary code.
Warning: The contracts represented here are for demonstrative purposes only and do not represent proper encryption. They should not be used for encryption.
Preventative Techniques
As demonstrated previously, safe contracts can (in some cases) be deployed in such a way that they behave maliciously. An auditor could publicly verify a contract and have its owner deploy it in a malicious way, resulting in a publicly audited contract that has vulnerabilities or malicious intent.
There are a number of techniques that prevent these scenarios.
One technique is to use the new keyword to create contracts. In the preceding example, the constructor could be written as:
constructor() { encryptionLibrary = new Rot13Encryption(); }
This way an instance of the referenced contract is created at deployment time, and the deployer cannot replace the Rot13Encryption contract without changing it.
Another solution is to hardcode external contract addresses.
In general, code that calls external contracts should always be audited carefully. As a developer, when defining external contracts, it can be a good idea to make the contract addresses public (which is not the case in the honey-pot example in the following section) to allow users to easily examine code referenced by the contract. Conversely, if a contract has a private variable contract address it can be a sign of someone behaving maliciously (as shown in the real-world example). If a user can change a contract address that is used to call external functions, it can be important (in a decentralized system context) to implement a time-lock and/or voting mechanism to allow users to see what code is being changed, or to give participants a chance to opt in/out with the new contract address.
Real-World Example: Reentrancy Honey Pot
A number of recent honey pots have been released on the mainnet. These contracts try to outsmart Ethereum hackers who try to exploit the contracts, but who in turn end up losing ether to the contract they expect to exploit. One example employs this attack by replacing an expected contract with a malicious one in the constructor. The code can be found here:
pragma solidity ^0.4.19; contract Private_Bank { mapping (address => uint) public balances; uint public MinDeposit = 1 ether; Log TransferLog; function Private_Bank(address _log) { TransferLog = Log(_log); } function Deposit() public payable { if(msg.value >= MinDeposit) { balances[msg.sender]+=msg.value; TransferLog.AddMessage(msg.sender,msg.value,"Deposit"); } } function CashOut(uint _am) { if(_am<=balances[msg.sender]) { if(msg.sender.call.value(_am)()) { balances[msg.sender]-=_am; TransferLog.AddMessage(msg.sender,_am,"CashOut"); } } } function() external payable{} } contract Log { struct Message { address Sender; string Data; uint Val; uint Time; } Message[] public History; Message LastMsg; function AddMessage(address _adr,uint _val,string _data) public { LastMsg.Sender = _adr; LastMsg.Time = now; LastMsg.Val = _val; LastMsg.Data = _data; History.push(LastMsg); } }
This post by one reddit user explains how they lost 1 ether to this contract by trying to exploit the reentrancy bug they expected to be present in the contract.
Short Address/Parameter Attack
This attack is not performed on Solidity contracts themselves, but on third-party applications that may interact with them. This section is added for completeness and to give the reader an awareness of how parameters can be manipulated in contracts.
For further reading, see “The ERC20 Short Address Attack Explained”, “ICO Smart Contract Vulnerability: Short Address Attack”, or this Reddit post.
The Vulnerability
When passing parameters to a smart contract, the parameters are encoded according to the ABI specification. It is possible to send encoded parameters that are shorter than the expected parameter length (for example, sending an address that is only 38 hex chars (19 bytes) instead of the standard 40 hex chars (20 bytes)). In such a scenario, the EVM will add zeros to the end of the encoded parameters to make up the expected length.
This becomes an issue when third-party applications do not validate inputs. The clearest example is an exchange that doesn’t verify the address of an ERC20 token when a user requests a withdrawal. This example is covered in more detail in Peter Vessenes’s post, “The ERC20 Short Address Attack Explained”.
Consider the standard ERC20 transfer function interface, noting the order of the parameters:
function transfer(address to, uint tokens) public returns (bool success);
Now consider an exchange holding a large amount of a token (let’s say REP) and a user who wishes to withdraw their share of 100 tokens. The user would submit their address, 0xdeaddeaddeaddeaddeaddeaddeaddeaddeaddead, and the number of tokens, 100. The exchange would encode these parameters in the order specified by the transfer function; that is, address then tokens. The encoded result would be:
a9059cbb000000000000000000000000deaddeaddea \ ddeaddeaddeaddeaddeaddeaddead0000000000000 000000000000000000000000000000000056bc75e2d63100000
The first 4 bytes (a9059cbb) are the transfer function signature/selector, the next 32 bytes are the address, and the final 32 bytes represent the uint256 number of tokens. Notice that the hex 56bc75e2d63100000 at the end corresponds to 100 tokens (with 18 decimal places, as specified by the REP token contract).
Let us now look at what would happen if one were to send an address that was missing 1 byte (2 hex digits). Specifically, let’s say an attacker sends 0xdeaddeaddeaddeaddeaddeaddeaddeaddeadde as an address (missing the last two digits) and the same 100 tokens to withdraw. If the exchange does not validate this input, it will get encoded as:
a9059cbb000000000000000000000000deaddeaddea \ ddeaddeaddeaddeaddeaddeadde00000000000000 00000000000000000000000000000000056bc75e2d6310000000
The difference is subtle. Note that 00 has been added to the end of the encoding, to make up for the short address that was sent. When this gets sent to the smart contract, the address parameters will be read as 0xdeaddeaddeaddeaddeaddeaddeaddeaddeadde00 and the value will be read as 56bc75e2d6310000000 (notice the two extra 0s). This value is now 25600 tokens (the value has been multiplied by 256). In this example, if the exchange held this many tokens, the user would withdraw 25600 tokens (while the exchange thinks the user is only withdrawing 100) to the modified address. Obviously the attacker won't possess the modified address in this example, but if the attacker were to generate any address that ended in 0s (which can be easily brute-forced) and used this generated address, they could steal tokens from the unsuspecting exchange.
Preventative Techniques
All input parameters in external applications should be validated before sending them to the blockchain. It should also be noted that parameter ordering plays an important role here. As padding only occurs at the end, careful ordering of parameters in the smart contract can mitigate some forms of this attack.
Unchecked CALL Return Values
There are a number of ways of performing external calls in Solidity. Sending ether to external accounts is commonly performed via the transfer method. However, the send function can also be used, and for more versatile external calls the CALL opcode can be directly employed in Solidity. The call and send functions return a Boolean indicating whether the call succeeded or failed. Thus, these functions have a simple caveat, in that the transaction that executes these functions will not revert if the external call (intialized by call or send) fails; rather, the functions will simply return false. A common error is that the developer expects a revert to occur if the external call fails, and does not check the return value.
For further reading, see #4 on the DASP Top 10 of 2018 and “Scanning Live Ethereum Contracts for the ‘Unchecked-Send’ Bug”.
The Vulnerability
Consider the following example:
contract Lotto { bool public payedOut = false; address public winner; uint public winAmount; // ... extra functionality here function sendToWinner() public { require(!payedOut); winner.send(winAmount); payedOut = true; } function withdrawLeftOver() public { require(payedOut); msg.sender.send(this.balance); } }
This represents a Lotto-like contract, where a winner receives winAmount of ether, which typically leaves a little left over for anyone to withdraw.
The vulnerability exists on line 11, where a send is used without checking the response. In this trivial example, a winner whose transaction fails (either by running out of gas or by being a contract that intentionally throws in the fallback function) allows payedOut to be set to true regardless of whether ether was sent or not. In this case, anyone can withdraw the winner’s winnings via the withdrawLeftOver function.
Preventative Techniques
Whenever possible, use the transfer function rather than send, as transfer will revert if the external transaction reverts. If send is required, always check the return value.
A more robust recommendation is to adopt a withdrawal pattern. In this solution, each user must call an isolated withdraw function that handles the sending of ether out of the contract and deals with the consequences of failed send transactions. The idea is to logically isolate the external send functionality from the rest of the codebase, and place the burden of a potentially failed transaction on the end user calling the withdraw function.
Real-World Example: Etherpot and King of the Ether
Etherpot was a smart contract lottery, not too dissimilar to the example contract mentioned earlier. The downfall of this contract was primarily due to incorrect use of block hashes (only the last 256 block hashes are usable; see Aakil Fernandes’s post about how Etherpot failed to take account of this correctly). However, this contract also suffered from an unchecked call value. Consider the function cash in lotto.sol: Code snippet.
lotto.sol: Code snippet
... function cash(uint roundIndex, uint subpotIndex){ var subpotsCount = getSubpotsCount(roundIndex); if(subpotIndex>=subpotsCount) return; var decisionBlockNumber = getDecisionBlockNumber(roundIndex,subpotIndex); if(decisionBlockNumber>block.number) return; if(rounds[roundIndex].isCashed[subpotIndex]) return; //Subpots can only be cashed once. This is to prevent double payouts var winner = calculateWinner(roundIndex,subpotIndex); var subpot = getSubpot(roundIndex); winner.send(subpot); rounds[roundIndex].isCashed[subpotIndex] = true; //Mark the round as cashed } ...
Notice that on line 21 the send function’s return value is not checked, and the following line then sets a Boolean indicating that the winner has been sent their funds. This bug can allow a state where the winner does not receive their ether, but the state of the contract can indicate that the winner has already been paid.
A more serious version of this bug occurred in the King of the Ether. An excellent post-mortem of this contract has been written that details how an unchecked failed send could be used to attack the contract.
Race Conditions/Front Running
The combination of external calls to other contracts and the multiuser nature of the underlying blockchain gives rise to a variety of potential Solidity pitfalls whereby users race code execution to obtain unexpected states. Reentrancy (discussed earlier in this chapter) is one example of such a race condition. In this section we will discuss other kinds of race conditions that can occur on the Ethereum blockchain. There are a variety of good posts on this subject, including “Race Conditions” on the Ethereum Wiki, #7 on the DASP Top10 of 2018, and the Ethereum Smart Contract Best Practices.
The Vulnerability
As with most blockchains, Ethereum nodes pool transactions and form them into blocks. The transactions are only considered valid once a miner has solved a consensus mechanism (currently Ethash PoW for Ethereum). The miner who solves the block also chooses which transactions from the pool will be included in the block, typically ordered by the gasPrice of each transaction. Here is a potential attack vector. An attacker can watch the transaction pool for transactions that may contain solutions to problems, and modify or revoke the solver's permissions or change state in a contract detrimentally to the solver. The attacker can then get the data from this transaction and create a transaction of their own with a higher gasPrice so their transaction is included in a block before the original.
Let’s see how this could work with a simple example. Consider the contract shown in FindThisHash.sol.
FindThisHash.sol
contract FindThisHash { bytes32 constant public hash = 0xb5b5b97fafd9855eec9b41f74dfb6c38f5951141f9a3ecd7f44d5479b630ee0a; constructor() external payable {} // load with ether function solve(string solution) public { // If you can find the pre-image of the hash, receive 1000 ether require(hash == sha3(solution)); msg.sender.transfer(1000 ether); } }
Say this contract contains 1,000 ether. The user who can find the preimage of the following SHA-3 hash:
0xb5b5b97fafd9855eec9b41f74dfb6c38f5951141f9a3ecd7f44d5479b630ee0a
can submit the solution and retrieve the 1,000 ether. Let's say one user figures out the solution is Ethereum!. They call solve with Ethereum! as the parameter. Unfortunately, an attacker has been clever enough to watch the transaction pool for anyone submitting a solution. They see this solution, check its validity, and then submit an equivalent transaction with a much higher gasPrice than the original transaction. The miner who solves the block will likely give the attacker preference due to the higher gasPrice, and mine their transaction before the original solver's. The attacker will take the 1,000 ether, and the user who solved the problem will get nothing. Keep in mind that in this type of "front-running" vulnerability, miners are uniquely incentivized to run the attacks themselves (or can be bribed to run these attacks with extravagant fees). The possibility of the attacker being a miner themselves should not be underestimated.
Preventative Techniques
There are two classes of actor who can perform these kinds of front-running attacks: users (who modify the gasPrice of their transactions) and miners themselves (who can reorder the transactions in a block how they see fit). A contract that is vulnerable to the first class (users) is significantly worse off than one vulnerable to the second (miners), as miners can only perform the attack when they solve a block, which is unlikely for any individual miner targeting a specific block. Here we’ll list a few mitigation measures relative to both classes of attackers.
One method is to place an upper bound on the gasPrice. This prevents users from increasing the gasPrice and getting preferential transaction ordering beyond the upper bound. This measure only guards against the first class of attackers (arbitrary users). Miners in this scenario can still attack the contract, as they can order the transactions in their block however they like, regardless of gas price.
A more robust method is to use a commit–reveal scheme. Such a scheme dictates that users send transactions with hidden information (typically a hash). After the transaction has been included in a block, the user sends a transaction revealing the data that was sent (the reveal phase). This method prevents both miners and users from front-running transactions, as they cannot determine the contents of the transaction. This method, however, cannot conceal the transaction value (which in some cases is the valuable information that needs to be hidden). The ENS smart contract allowed users to send transactions whose committed data included the amount of ether they were willing to spend. Users could then send transactions of arbitrary value. During the reveal phase, users were refunded the difference between the amount sent in the transaction and the amount they were willing to spend.
A further suggestion by Lorenz Breidenbach, Phil Daian, Ari Juels, and Florian Tramèr is to use “submarine sends”. An efficient implementation of this idea requires the CREATE2 opcode, which currently hasn’t been adopted but seems likely to be in upcoming hard forks.
Real-World Examples: ERC20 and Bancor
The ERC20 standard is quite well-known for building tokens on Ethereum. This standard has a potential front-running vulnerability that comes about due to the approve function. Mikhail Vladimirov and Dmitry Khovratovich have written a good explanation of this vulnerability (and ways to mitigate the attack).
The standard specifies the approve function as:
function approve(address _spender, uint256 _value) returns (bool success)
This function allows a user to permit other users to transfer tokens on their behalf. The front-running vulnerability occurs in the scenario where a user Alice approves her friend Bob to spend 100 tokens. Alice later decides that she wants to revoke Bob’s approval to spend, say, 100 tokens, so she creates a transaction that sets Bob’s allocation to 50 tokens. Bob, who has been carefully watching the chain, sees this transaction and builds a transaction of his own spending the 100 tokens. He puts a higher gasPrice on his transaction than Alice's, so gets his transaction prioritized over hers. Some implementations of approve would allow Bob to transfer his 100 tokens and then, when Alice’s transaction is committed, reset Bob’s approval to 50 tokens, in effect giving Bob access to 150 tokens.
Another prominent real-world example is Bancor. Ivan Bogatyy and his team documented a profitable attack on the initial Bancor implementation. His blog post and DevCon3 talk discuss in detail how this was done. Essentially, prices of tokens are determined based on transaction value; users can watch the transaction pool for Bancor transactions and front-run them to profit from the price differences. This attack has been addressed by the Bancor team.
Denial of Service (DoS)
This category is very broad, but fundamentally consists of attacks where users can render a contract inoperable for a period of time, or in some cases permanently. This can trap ether in these contracts forever, as was the case in Real-World Example: Parity Multisig Wallet (Second Hack).
The Vulnerability
There are various ways a contract can become inoperable. Here we highlight just a few less-obvious Solidity coding patterns that can lead to DoS vulnerabilities:
- Looping through externally manipulated mappings or arrays: This pattern typically appears when an owner wishes to distribute tokens to investors with a distribute-like function, as in this example contract: + [source,solidity,linenums] ---- contract DistributeTokens { address public owner; // gets set somewhere address[] investors; // array of investors uint[] investorTokens; // the amount of tokens each investor gets
function invest() external payable { investors.push(msg.sender); investorTokens.push(msg.value * 5); // 5 times the wei sent }
function distribute() public { require(msg.sender == owner); // only owner for(uint i = 0; i < investors.length; i++) { transferToken(investors[i],investorTokens[i]); } } }
+ Notice that the loop in this contract runs over an array that can be artificially inflated. An attacker can create many user accounts, making the `investor` array large. In principle this can be done such that the gas required to execute the +for+ loop exceeds the block gas limit, essentially making the `distribute` function inoperable. Owner operations:: Another common pattern is where owners have specific privileges in contracts and must perform some task in order for the contract to proceed to the next state. One example would be an Initial Coin Offering (ICO) contract that requires the owner to `finalize` the contract, which then allows tokens to be transferable. For example: + [source,solidity,linenums]
bool public isFinalized = false; address public owner; // gets set somewhere
function finalize() public { require(msg.sender == owner); isFinalized == true; }
function transfer(address _to, uint _value) returns (bool) { require(isFinalized); super.transfer(_to,_value) }
...
+ In such cases, if the privileged user loses their private keys or becomes inactive, the entire token contract becomes inoperable. In this case, if the owner cannot call pass:[<span class="keep-together"><code>finalize</code></span>] no tokens can be transferred; the entire operation of the token ecosystem hinges on a single address. Progressing state based on external calls:: Contracts are sometimes written such that progressing to a new state requires sending ether to an address, or waiting for some input from an external source. These patterns can lead to DoS attacks when the external call fails or is prevented for external reasons. In the example of sending ether, a user can create a contract that does not accept ether. If a contract requires ether to be withdrawn in order to progress to a new state (consider a time-locking contract that requires all ether to be withdrawn before being usable again), the contract will never achieve the new state, as ether can never be sent to the user's contract that does not accept ether. [role="notoc"] ==== Preventative Techniques In the first example, contracts should not loop through data structures that can be artificially manipulated by external users. A withdrawal pattern is recommended, whereby each of the investors call a +withdraw+ function to claim tokens independently. In the second example, a privileged user was required to change the state of the contract. In such examples a failsafe can be used in the event that the owner becomes incapacitated. One solution is to make the owner a multisig contract. Another solution is to use a time-lock: in the example given the +require+ on line 5 could include a time-based mechanism, such as `require(msg.sender == owner || now > unlockTime)`, that allows any user to finalize after a period of time specified by `unlockTime`. This kind of mitigation technique can be used in the third example also. If external calls are required to progress to a new state, account for their possible failure and potentially add a time-based state progression in the event that the desired call never comes. [NOTE] ==== Of course, there are centralized alternatives to these suggestions: one can add a `maintenanceUser` who can come along and fix problems with DoS-based attack vectors if need be. Typically these kinds of contracts have trust issues, because of the power of such an entity. ==== ==== Real-World Examples: GovernMental http://governmental.github.io/GovernMental/[GovernMental] was an old Ponzi scheme that accumulated quite a large amount of ether (1,100 ether, at one point). Unfortunately, it was susceptible to the DoS vulnerabilities mentioned in this section. A http://bit.ly/2DcgvFc[Reddit post] by etherik describes how the contract required the deletion of a large mapping in order to withdraw the ether. The deletion of this mapping had a gas cost that exceeded the block gas limit at the time, and thus it was not possible to withdraw the 1,100 ether. The contract address is http://bit.ly/2Oh8j7R[+0xF45717552f12Ef7cb65e95476F217Ea008167Ae3+], and you can see from transaction http://bit.ly/2Ogzrnn[+0x0d80d67202bd9cb6773df8dd2020e719 0a1b0793e8ec4fc105257e8128f0506b+] that the 1,100 ether were finally obtained with a transaction that used 2.5M gas (when the block gas limit had risen enough to allow such a transaction). === Block Timestamp Manipulation Block timestamps have historically been used for a variety of applications, such as entropy for random numbers (see the <<entropyillusion_security>> for further details), locking funds for periods of time, and various state-changing conditional statements that are time-dependent. Miners have the ability to adjust timestamps slightly, which can prove to be dangerous if block timestamps are used incorrectly in smart contracts. Useful references for this include http://bit.ly/2OdUC9C[the Solidity docs] and http://bit.ly/2CQ8gh4[Joris Bontje's Ethereum Stack Exchange question] on the topic. [role="notoc"] ==== The Vulnerability `block.timestamp` and its alias `now` can be manipulated by miners if they have some incentive to do so. Let's construct a simple game, shown in <<roulette_security>>, that would be vulnerable to miner exploitation. [[roulette_security]] .roulette.sol ==== [source,solidity,linenums]
contract Roulette { uint public pastBlockTime; // forces one bet per block
constructor() external payable {} // initially fund contract
function () external payable { require(msg.value == 10 ether); // must send 10 ether to play require(now != pastBlockTime); // only 1 transaction per block pastBlockTime = now; if(now % 15 == 0) { // winner msg.sender.transfer(this.balance); } } }
==== This contract behaves like a simple lottery. One transaction per block can bet 10 ether for a chance to win the balance of the contract. The assumption here is that `block.timestamp`'s last two digits are uniformly distributed. If that were the case, there would be a 1 in 15 chance of winning this lottery. However, as we know, miners can adjust the timestamp should they need to. In this particular case, if enough ether pools in the contract, a miner who solves a block is incentivized to choose a timestamp such that `block.timestamp` or `now` modulo 15 is `0`. In doing so they may win the ether locked in this contract along with the block reward. As there is only one person allowed to bet per block, this is also vulnerable to front-running attacks (see <<frontrunning_security>> for further details). In practice, block timestamps are monotonically increasing and so miners cannot choose arbitrary block timestamps (they must be later than their predecessors). They are also limited to setting block times not too far in the future, as these blocks will likely be rejected by the network (nodes will not validate blocks whose timestamps are in the future). [role="notoc"] ==== Preventative Techniques Block timestamps should not be used for entropy or generating random numbers—i.e., they should not be the deciding factor (either directly or through some derivation) for winning a game or changing an important state. Time-sensitive logic is sometimes required; e.g., for unlocking contracts (time-locking), completing an ICO after a few weeks, or enforcing expiry dates. It is sometimes recommended to use http://bit.ly/2OdUC9C[`block.number`] and an average block time to estimate times; with a `10 second` block time, `1 week` equates to approximately, `60480 blocks`. Thus, specifying a block number at which to change a contract state can be more secure, as miners are unable to easily manipulate the block number. The http://bit.ly/2AAebFr[BAT ICO] contract employed this strategy. This can be unnecessary if contracts aren’t particularly concerned with miner manipulations of the block timestamp, but it is something to be aware of when developing contracts. ==== Real-World Example: GovernMental http://governmental.github.io/GovernMental/[GovernMental], the old Ponzi scheme mentioned above, was also vulnerable to a timestamp-based attack. The contract paid out to the player who was the last player to join (for at least one minute) in a round. Thus, a miner who was a player could adjust the timestamp (to a future time, to make it look like a minute had elapsed) to make it appear that they were the last player to join for over a minute (even though this was not true in reality). More detail on this can be found in the http://bit.ly/2Q1AMA6[“History of Ethereum Security Vulnerabilities, Hacks and Their Fixes” post] by Tanya pass:[<span class="keep-together">Bahrynovska</span>]. === Constructors with Care Constructors are special functions that often perform critical, privileged tasks when initializing contracts. Before Solidity v0.4.22, constructors were defined as functions that had the same name as the contract that contained them. In such cases, when the contract name is changed in development, if the constructor name isn’t changed too it becomes a normal, callable function. As you can imagine, this can lead (and has) to some interesting contract hacks. For further insight, the reader may be interested in attempting the https://github.com/OpenZeppelin/ethernaut[Ethernaut challenges] (in particular the Fallout level). [role="notoc"] ==== The Vulnerability If the contract name is modified, or there is a typo in the constructor's name such that it does not match the name of the contract, the constructor will behave like a normal function. This can lead to dire consequences, especially if the constructor performs privileged operations. Consider the following contract: [source,solidity,linenums]
contract OwnerWallet { address public owner;
function ownerWallet(address _owner) public { owner = _owner; }
function () payable {}
function withdraw() public { require(msg.sender == owner); msg.sender.transfer(this.balance); } }
This contract collects ether and allows only the owner to withdraw it, by calling the `withdraw` function. The issue arises because the constructor is not named exactly the same as the contract: the first letter is different! Thus, any user can call the `ownerWallet` function, set themselves as the owner, and then take all the ether in the contract by calling `withdraw`. [role="notoc"] ==== Preventative Techniques This issue has been addressed in version 0.4.22 of the Solidity compiler. This version introduced a `constructor` keyword that specifies the constructor, rather than requiring the name of the function to match the contract name. Using this keyword to specify constructors is recommended to prevent naming issues. ==== Real-World Example: Rubixi http://bit.ly/2ESWG7t[Rubixi] was another pyramid scheme that exhibited this kind of vulnerability. It was originally called `DynamicPyramid`, but the contract name was changed before deployment to `Rubixi`. The constructor’s name wasn’t changed, allowing any user to become the creator. Some interesting discussion related to this bug can be found on http://bit.ly/2P0TRWw[Bitcointalk]. Ultimately, it allowed users to fight for creator status to claim the fees from the pyramid scheme. More detail on this particular bug can be found in http://bit.ly/2Q1AMA6[“History of Ethereum Security Vulnerabilities, Hacks and Their Fixes”]. === Uninitialized Storage Pointers The EVM stores data either as storage or as memory. Understanding exactly how this is done and the default types for local variables of functions is highly recommended when developing contracts. This is because it is possible to produce vulnerable contracts by inappropriately intializing variables. To read more about storage and memory in the EVM, see the Solidity documentation on http://bit.ly/2OdUU0l[data location], http://bit.ly/2JslDWf[layout of state variables in storage], and http://bit.ly/2Dch2Hc[layout in memory]. [NOTE] ==== This section is based on an excellent http://bit.ly/2ERI0pb[post by Stefan Beyer]. Further reading on this topic, inspired by Stefan, can be found in this http://bit.ly/2OgxPtG[Reddit thread]. ==== [role="notoc"] ==== The Vulnerability Local variables within functions default to storage or memory depending on their type. Uninitialized local storage variables may contain the value of other storage variables in the contract; this fact can cause unintentional vulnerabilities, or be exploited deliberately. Let’s consider the relatively simple name registrar contract in <<nameregistrar_security>>. [[nameregistrar_security]] .NameRegistrar.sol ==== [source,solidity,linenums]
contract NameRegistrar {
bool public unlocked = false; // registrar locked, no name updates
struct NameRecord { // map hashes to addresses bytes32 name; address mappedAddress; }
mapping(address => NameRecord) public registeredNameRecord; mapping(bytes32 => address) public resolve;
function register(bytes32 _name, address _mappedAddress) public { NameRecord newRecord; newRecord.name = _name; newRecord.mappedAddress = _mappedAddress;
resolve[_name] = _mappedAddress; registeredNameRecord[msg.sender] = newRecord;
require(unlocked); // only allow registrations if contract is unlocked } }