“When smart people hear the term “smart contracts”, their imaginations tend to run wild. They conjure up dreams of autonomous intelligent software, going off into the world, taking data along for the ride. Unfortunately, the reality of smart contracts is more mundane.”

Dr Gideon Greenspan - Founder and CEO of Coin Sciences, Smart Contracts in and their Vulnerabilities Alex Harris & Tancredi Castellano Pucci Survey Attacks on Ethereum Smart Contracts

Nicola Atzei, Massimo Bartoletti, and Tiziana Cimoli What is a ?

● Smart contracts are simply computer programs that can be correctly executed by a network of mutually distrusting nodes, without the need for an external trusted authority (centralization). ● Perhaps should more accurately be called automatic escrow accounts. ● Smart contracts can be used to manage and transfer valuable assets, so it is essential that they execute correctly and are secure against attacks. ● Applications: finance, insurance, e-commerce, auditing and taxation, elections Brief History of Smart Contracts

● Principle of smart contracts first described by in 1996. ● Digital protocols for information transfer that use algorithms to execute a transaction automatically once the established conditions are met and that fully control the process. ● Why did smart contracts become so closely linked with the distributed ? ● Isn’t it wasteful to have every node running the smart contract? ● first appeared in 2008, followed by Ethereum in 2013. ● So far, Ethereum is the best-known and most-used network for smart contracts, so the paper discusses these issues in this context. Smart Contracts on Ethereum

● The consensus protocol specifies how the nodes of the peer-to-peer network extend the , with the goal of ensuring correct execution. ● Ethereum is written in a Turing-complete language, unlike Bitcoin. The Bitcoin system is purposefully not Turing-complete: it is a left-right stack without loops, making it completely deterministic and avoiding the halting problem. ● Assumptions of the Paper: ○ Ethereum blockchain is immutable. ○ Ethereum is secure if a majority of the computational power is controlled by honest nodes. ○ Ethereum smart contracts execute correctly (still insufficient to make smart contracts secure). Example: A Simple Wallet Contract

● AWallet is run only once, when the contract is created. ● The function pay sends amount wei (10-18 ether) from the contract to recipient. ● The contract throws an exception if the caller is not the owner, or if some ether is attached and ● Note that the function send may transferred to the contract. fail if the recipient is a contract. ● The call terminates if the required amount is unavailable. Why are Ethereum smart contracts so vulnerable?

● Ethereum uses , a high-level language with counterintuitive semantics, which compiles into EVM bytecode. ○ Solidity looks like a typed Javascript-like language, but has strange feature implementations. ○ Computation steps recorded on a public blockchain, where they can he unpredictably reordered or delayed. ○ When an exception is thrown, it cannot be caught: the execution stops, the fee is lost, and all the side effects — including transfers of ether — are reverted. ● Ethereum uses Turing-complete EVM bytecode, potentially making it vulnerable to the halting problem. ○ Bugs that are appended to the blockchain cannot be changed. ○ Ether lost in transfer. ○ EVM bytecode has no support for functions. Instead, each function has to be uniquely identified by a signature, based on its name and type parameters.

Vulnerability Type: Solidity

● Example: Gasless send ● Related to the counterintuitive semantics of Solidity. ● When using send to transfer ether to a contract, it is possible to incur an out-of-gas exception. This is counterintuitive because programmers do not associate transferring ether with executing code. ● c.send(amount) is compiled in the same way as a call with empty signature, but the actual number of gas units available is always bounded. ● Since the call has no signature, it will invoke the callee’s fallback function. ● The upper bound (2300) allows only a limited set of instructions, so in any other case the call will end up in an out-of-gas exception. Vulnerability Type: Solidity

● Example: Keeping secrets ● Fields in contracts can be either public or private. ● Declaring a field to be private does not ensure its secrecy. ● To set the value of a field, users must send a suitable transaction to miners, who will then publish it on the blockchain. It is therefore possible to infer the new value of the field from the public contents of the transaction. ● If necessary, timed commitments and other cryptographic techniques can be used to ensure that the field remains secret. ○ E.g. Applications in multiplayer games. Vulnerability Type: EVM

● Example: Immutable bugs ● Once a contract is published on the blockchain, it cannot be altered. ● This creates a problem if a contract contains a bug, since there is then no direct way to patch it. ● It becomes necessary for programmers to anticipate ways to alter or terminate a contract when implementing it. ● We will see how this vulnerability was exploited in the DAO attack. Vulnerability Type: EVM

● Example: Ether lost in transfer ● When sending ether, it is necessary to specify the recipient’s address. Many of these addresses are orphan, not associated with any user or contract. ● Ether sent to an orphan address is lost forever, and there is no way to detect whether an address is orphan. ● Only option is to ensure the correctness of the recipient addresses manually. ○ How? Vulnerability Type: Blockchain

● Example: Unpredictable state ● The state of a contract is determined by the value of its fields and balance. ● A user cannot be sure that a transaction broadcast to the network will be run in the same state the contract was in at the time of broadcast. ● This is because other transactions may have changed the contract state. Miners are not required to preserve any particular order. ● The actual state also becomes ambiguous in the event of a hard . Vulnerability Type: Blockchain

● Example: Time constraints ● Typically implemented using block timestamps agreed upon by all miners. ● All contracts within a block share the same timestamp. ● This means that the miner who creates the new block can choose the timestamp to some degree arbitrarily.

The DAO Attack

● The DAO was a contract implementing a platform. ● Raised around $150M before the attack on June 18, 2016. ● Attacker managed to get $60M under control, before a hard fork nullified the effects of the attack transactions. The DAO Attack

● Attack #1: Similar to the actual DAO attack. Allows the adversary to steal all the ether from the SimpleDAO. ● First step: Publish the contract Mallory (see next slide). The adversary donates some ether for Mallory, and invokes withdraw, which transfers the ether to Mallory. The DAO Attack

● Crucial step: The function call used for this purpose has the side effect of invoking Mallory’s fallback function, which maliciously calls back withdraw. ● This causes withdraw to be interrupted before it can update the credit field, allowing the check if (credit[msg.sender] >= amount) to succeed again. ● The DAO therefore sends the credit to Mallory and invokes the fallback again, resulting in a malicious loop. The DAO Attack

● The malicious loop continues until: a. the gas is exhausted; b. the call stack is full; c. the balance of DAO falls to zero. ● Overall, this attack allows the adversary to steal all the ether from the DAO. The DAO Attack

● Attack #2: Similar to Attack #1, except that this time only two calls of the fallback function are required. ● First step: Publish the contract Mallory2, providing it with 1 wei. The adversary invokes attack to donate 1 wei to itself, and withdraws it. The DAO Attack

● The function withdraw checks that the credit is sufficient, and if so transfers the ether to contract Mallory2. ● Once again, call invokes Mallory2’s fallback, which in turn calls withdraw. ● The check succeeds again since withdraw is interrupted as before. ● The DAO sends 1 wei to Mallory2 for a second time, and invokes the fallback again, which does nothing this time. ● The underflow results in a second update to Mallory2’s credit: (2256-1) wei. ● Finally, Mallory2 invokes getJackpot, which steals all the ether from SimpleDAO and transfers it to Mallory2’s owner. The DAO Attack

● Key Vulnerability: Both attacks are possible because SimpleDAO sends the specified amount of ether before updating the credit. These attacks exploit the “call to the unknown” and “reentrancy” vulnerabilities mentioned earlier as general vulnerabilities in the Ethereum network. ● Which is better: Attack #1 or Attack #2? ○ How do the sizes of investment compare between the two attacks?

The DAO Attack

● Resolution: HARD FORK ● Parallels between the hard fork in response to the DAO attack and bank bailouts in the wake of the financial crisis? Which vulnerabilities enabled the DAO attack? Which vulnerabilities in Ethereum are you most concerned about? Why? Automatic Analysis of Safety/Soundness of Smart Contracts Why do we need said tools?

● Current state of empirical knowledge within the area is very limited. ○ Educational/Vocational resources are still rare.

● More thoroughly checked contracts are needed given hackers have walked away with 14% of Digital Currencies (approx 10B USD).

● Contracts need to get better but why do we need automatic tools? Why do we need said tools?

● Current state of empirical knowledge within the area is very limited. ○ Educational/Vocational resources are still rare.

● More thoroughly checked contracts are needed given hackers have walked away with 14% of Digital Currencies (approx 10B USD).

● Contracts need to get better but why do we need automatic tools? ○ Yes ■ Manual Auditing remains laborious and error prone. ○ No ■ Contracts tend to be less than 200 lines of code (due to gas cost). ■ 1% of contracts contain 99% of the value in the smart contract ecosystem. What should these tools be checking for?

Any characterization of bugs should be taken with a grain of salt, since one can always argue that the exposed behavior embodies intent.

● Correctness - adherence to safe programming practices. ○ E.g. Integer Overflow ● Fairness - code adheres to higher level logic. ○ Should the tools even be checking for fairness? What should these tools be checking for?

Any characterization of bugs should be taken with a grain of salt, since one can always argue that the exposed behavior embodies intent.

● Correctness - adherence to safe programming practices. ○ E.g. Integer Overflow ● Fairness - code adheres to higher level business logic. ○ Should the tools even be checking for fairness? ○ Examples: ■ Auctions with reserves vs Auctions without reserves. ■ =+ instead of += ■ payoutCursor_Id_ vs payoutCursor_id ○ Disincentivizes amateur hacker but also creates complacency? Feasibility of Automatically Verifying Smart Contracts

● Verifying Smart Contracts can be challenging for a number of reasons: ○ State Space Explosion ■ In theory this is an issue, in practice less so: ● Due to cost of operations (gas) which means that contracts seldom contain more than 200 lines of code. ● Lack of diverse contracts. ● Solidity is still a restricted language albeit Turing Complete. ○ Challenging to test due to interactive nature. ■ They can call other contracts. ■ The state of the contract may not be fixed. ○ It is impossible to fully check a program for bugs. ● Who is responsible if when something does go wrong? Current State of Affairs

● Most Current Tools are Static ○ E.g. Oyente, Mythril, Securify, SmartCheck. ● Oyente - June 2016 ○ Based on Symbolic Execution ■ Represents the values of program variables as symbolic expression of the input symbolic values. ■ Symbolic execution can statically reason about a program path-by-path. ○ 50% accuracy ● General Outcome ○ Most of the tools find common errors like arithmetic overflows. However, most fail in finding more complex attacks. Finding The Greedy, Prodigal, and Suicidal Contracts at Scale - MAIAN

● Main Feat: ○ Doesn’t only do static analysis of smart contracts but also dynamic analysis based on traces. ■ An execution trace is a (possibly infinite) sequence of runs on a contract recorded on the blockchain ● Methodology ○ Inputs: ■ Bytecode + Analysis Specifications e.g. vulnerability category, search depth, etc ○ Steps ■ 1) Symbolically Interpret bytecode. ■ 2) Search through the state space of the contract using a DFS checking that contracts do not violate certain properties (Safety and Liveness). ○ Validation ■ Contracts were tested on a private Ethereum Fork to discover ground truth. MAIAN - Nuances

● Violations that are checked ○ Safety - Nothing Bad Happens ○ Liveliness - Something Good eventually Happens

● Only checks for three ‘types’ of bugs: ○ Prodigal - Leaks Ether to an arbitrary user. ○ Suicidal - Susceptible to be killed by user. ○ Greedy - Locks funds indefinitely. ○ (Posthumous Contracts) - You can send funds to a dead contract. ■ Onus is on the sender to check if the contract is still alive. ■ This seems like a Solidity implementation bug? Comments? ZEUS: Analyzing Safety of Smart Contracts

● Main Feat: ○ Analyses fairness as well as correctness. ● Methodology: ○ Inputs: ■ Smart Contract + Policy ○ Steps ■ 1) Performs Static Analysis atop the smart contract code ■ 2) Inserts Policy Predicates as assert statements at correct program points leveraging user assistance. ■ 2) Uses its source code translator to translate code into LLVM Bytecode ■ 3) Uses Constrained Horn Clause Verifier to determine assertion violation. ○ ZEUS - Nuances

● Validation ○ Manually Validated?

● Checks for 7 bugs: ○ Incorrect Contracts ■ Reentrancy, Unchecked Send, Failed Send, Integer Under/Over Flow, Transaction State Dependance, ○ Unfair Contracts ■ Absence of Logic, Incorrect Logic Comparison

MAIAN ZEUS

Inputs Contract in Bytecode, Analysis Contract in high level language + Policy Specification, and a concrete starting block value

Evaluation 970,898 smart contracts 22.4k smart contracts.

Runtime Average (10 seconds) Less than a minute for 95% of contracts.

Bugs Checked For 3 7

Vulnerable Contracts 3.52% 94.6% True Positives 89% 97% Future of Smart Contracts?

● Are these papers dealing with symptoms? When in reality we should be dealing with the issue? Better smart contract language? more educational resources?

● Do smart contracts have a future? How useful can they actually be? Thank you!