DappGuard : Active Monitoring and Defense for Solidity ... · DappGuard : Active Monitoring and...

12
DappGuard : Active Monitoring and Defense for Solidity Smart Contracts Thomas Cook [email protected] Alex Latham [email protected] Jae Hyung Lee [email protected] Abstract Ethereum’s smart contracts present an attractive in- centive toward participating in the network. De- ploying a smart contract allows a user to run a distributed application (Dapp) that includes stor- age, payment features, and cryptographic services all within the context of just a contract script and its layout. However, recently exploited vulnerabili- ties in the Solidity smart contract language have un- dermined the integrity of Ethereum’s smart contract implementations. After some discussion of previ- ous work, we examine whether known vulnerabil- ities can be detected as attacks post factum from information available on the Ethereum blockchain. Then, we present findings on what information is available for a few selected contracts. Finally, we propose our design for a live monitoring and pro- tection system based on our research findings, the prototypes we developed to gather data, and docu- mented plans for extension. 1 Introduction Emerging blockchain technologies have shown great promise in offering decentralized services backed by a distributed ledger. This has espe- cially proven true with the deployment of various cryptocurrencies, the most prominent being Bitcoin, Ripple, and Ethereum, all with market capitaliza- tion (as of writing) of over $USD 5 billion. The Ethereum blockchain is current the most popular cryptocurrency that utilizes the smart contract ab- straction layer to log transactions. 1.1 Smart Contracts and Dapps Smart contracts allow accounts on the Ethereum network to host, on the blockchain, a ’near’ Turing- complete program that supports publicly verifiable transactions. It can facilitate the exchange of money, content, property, shares, or anything of value. When run on the blockchain a smart con- tract becomes like a self-operating program that au- tomatically executes when specific conditions are met. Because smart contracts run on the blockchain, they run exactly as programmed without any possi- bility of censorship, downtime, fraud or third party interference. [2] A majority of smart contracts rely on a traditional web app front end to provide the user interface for that contract’s functions. A function is invoked, when a user of the Dapp sends a transaction using his/her account address to the contracts address. For the most part, the functions current smart contracts provide can be categorized as one of financial, no- tary, library, gaming, or that of a wallet. [6] 1.2 Solidity, Ethereum Virtual Machine, and Ethereum Networks Solidity is a imperatively typed programming lan- guage, similar to Javascript, for writing smart contracts. Solidity smart contracts are compiled to EVM bytecode before being deployed on the blockchain. Ethereum smart contracts are run on the Ethereum Virtual Machine, which is isolated from any miner or contract owner’s local machine, and nodes on the EVM executed smart contracts– 1

Transcript of DappGuard : Active Monitoring and Defense for Solidity ... · DappGuard : Active Monitoring and...

Page 1: DappGuard : Active Monitoring and Defense for Solidity ... · DappGuard : Active Monitoring and Defense for Solidity Smart Contracts Thomas Cook tomcook@mit.edu ... Best practices

DappGuard : Active Monitoring and Defense for Solidity Smart Contracts

Thomas [email protected]

Alex [email protected]

Jae Hyung [email protected]

Abstract

Ethereum’s smart contracts present an attractive in-centive toward participating in the network. De-ploying a smart contract allows a user to run adistributed application (Dapp) that includes stor-age, payment features, and cryptographic servicesall within the context of just a contract script andits layout. However, recently exploited vulnerabili-ties in the Solidity smart contract language have un-dermined the integrity of Ethereum’s smart contractimplementations. After some discussion of previ-ous work, we examine whether known vulnerabil-ities can be detected as attacks post factum frominformation available on the Ethereum blockchain.Then, we present findings on what information isavailable for a few selected contracts. Finally, wepropose our design for a live monitoring and pro-tection system based on our research findings, theprototypes we developed to gather data, and docu-mented plans for extension.

1 Introduction

Emerging blockchain technologies have showngreat promise in offering decentralized servicesbacked by a distributed ledger. This has espe-cially proven true with the deployment of variouscryptocurrencies, the most prominent being Bitcoin,Ripple, and Ethereum, all with market capitaliza-tion (as of writing) of over $USD 5 billion. TheEthereum blockchain is current the most popularcryptocurrency that utilizes the smart contract ab-straction layer to log transactions.

1.1 Smart Contracts and Dapps

Smart contracts allow accounts on the Ethereumnetwork to host, on the blockchain, a ’near’ Turing-complete program that supports publicly verifiabletransactions. It can facilitate the exchange ofmoney, content, property, shares, or anything ofvalue. When run on the blockchain a smart con-tract becomes like a self-operating program that au-tomatically executes when specific conditions aremet. Because smart contracts run on the blockchain,they run exactly as programmed without any possi-bility of censorship, downtime, fraud or third partyinterference. [2]

A majority of smart contracts rely on a traditionalweb app front end to provide the user interface forthat contract’s functions. A function is invoked,when a user of the Dapp sends a transaction usinghis/her account address to the contracts address. Forthe most part, the functions current smart contractsprovide can be categorized as one of financial, no-tary, library, gaming, or that of a wallet. [6]

1.2 Solidity, Ethereum Virtual Machine,and Ethereum Networks

Solidity is a imperatively typed programming lan-guage, similar to Javascript, for writing smartcontracts. Solidity smart contracts are compiledto EVM bytecode before being deployed on theblockchain.

Ethereum smart contracts are run on theEthereum Virtual Machine, which is isolated fromany miner or contract owner’s local machine, andnodes on the EVM executed smart contracts–

1

Page 2: DappGuard : Active Monitoring and Defense for Solidity ... · DappGuard : Active Monitoring and Defense for Solidity Smart Contracts Thomas Cook tomcook@mit.edu ... Best practices

code that executes conditioned transactions betweenusers and other contracts. Contracts can store value,transfer and receive value, and execute code. Theexecution of transactions with these contracts is per-formed by nodes on the EVM in a publicly visibleway, and paid for in units of gas.

The amount of gas allocated for a given trans-action’s execution is finite and fixed by the creatorof the transaction. The gas cost for each EVM in-struction is provided in [12] and roughly correlatesto the computational cost of each instruction mak-ing exceptions where other system goals are consid-ered. For example, arithmetic operations are verycheap while storage is among the most expensiveoperations so that the blockchain does not grow tooquickly.

A smart contract’s transaction is executed whenit is mined into a block. Miners receive a static re-ward, as well as the value of any gas used timesthe gas price (set by the market and having unitsether/gas) when they successfully solve a proof-of-work puzzle and submit a block to the blockchain.

1.3 TheDAO Incident

A DAO is fully autonomous, decentralized organi-zation with no single leader. It is designed to re-place the rules and structure of a traditional orga-nization, eliminating the need for people and cen-tralized control. ”TheDAO” is one kind of DAOinitiated and developed by German startup Slock.it.“TheDAO” was launched in April 2016 became asone of the most popular smart contracts since theEthereum blockchain started running. However,several Ethereum developers raised questions andconcerns about its potential vulnerability within itsrecursive call of splitDAO function which is usedfor person who want to leave “theDAO” contract.In mid of June 2016, one of “theDAO” creator an-nounced that the “recursive call bug” had been ad-dressed and no “theDAO” contracts and funds wereat risk. [1]

However, 3 days later after the announcement,unkown attacker could drain more then 3.6 mil-lion ethers by utilizing bug in the recursive spilit-DAO function. The Ethereum development teamdid attempt to split “theDAO” contract to preventmore ether from being taken, but the attempt did

not work since they could not get the votes neces-sary in such a short time. In characteristic of smartcontract, developers and designers didn’t considersuch an attack or malicious usage condition within“theDAO”. [4]

1.4 Testing Methodology

The contribution of this paper is twofold. Motivatedby existing security analyses of smart contracts inEthereum, we first demonstrate that there is indeedopportunity to infer attacks from blockchain meta-data. Second, we describe and propose future di-rections for our prototype of DappGuard. Addtion-ally, we conclude with general discussion of smartcontract security as it relates to the Dapp and smartcontract environment.

2 Background and Related Work

The Solidity language does not introduce constructsto deal with domain-specific aspects since its com-putation steps are recorded on a public blockchain.Hence, Ethereum developers had focused on cor-rectness of its execution to avoid manipulation andtamper of adversary. However, in last couple ofyears it has been proven that correctness of the ex-ecution cannot guarantee security of the smart con-tract not only from reordered. several security vul-nerabilities in Ethereum smart contracts have beendiscovered both by hands-on development experi-ence. [5]

2.1 Security Issues

Most notably, a taxonomy of vulnerabilities and re-lated attacks against Solidity, the EVM, and theblockchain were recently described by Atzei, Bar-toletti, and Cimoli [5]. They defined 12 vulnera-bilities among these components that pose risks tothe contract owners. We utilize this vocabulary inour analyses and thus, we provide the list and briefdescriptions for clarity and convenience.

1. Call to the unknown: This refers to any use ofcall , delegatecall , send, or direct call toanother contract that results results in execu-tion of an unknown, possibly malicious, fall-

2

Page 3: DappGuard : Active Monitoring and Defense for Solidity ... · DappGuard : Active Monitoring and Defense for Solidity Smart Contracts Thomas Cook tomcook@mit.edu ... Best practices

back function (the anonymous function on ev-ery smart contract invoked as a catch all).

2. Gasless send: If the callee of a send (theEthereum function to transfer ether) is a con-tract with a relatively expensive fallback func-tion, then the amount of gas the caller is limitedto– 2300 units for sending ether to an address–will be insufficient, and an out-of-gas excep-tion will be thrown.

3. Exception disorder: refers to uncheckedsend errors or called contracts that throw ex-ceptions. The effect is that the calling contracttransaction is entirely reverted and all gas islost.

4. Type casts: if the arguments to a direct callfrom one contract to a function of another con-tract is incorrectly typed, or the address of thecalled contract is incorrect, either nothing willhappen, or the wrong code will execute. In nei-ther case is an exception thrown, and the calleris not made aware.

5. Reentrancy: In some cases, a contract’s fall-back function allows it to re-enter a caller func-tion before it has terminated. This can resultin the repeated execution of functions intendedonly to be executed once per transaction.

6. Keeping secrets: by the public nature of theblockchain, contract fields marked private

are not guaranteed to remain secret- to set aprivate field, a contract owner must broadcasta transaction. Cryptographic protocols are re-quired to guarantee that fields are not visible toanyone mining or inspecting the blockchain.

7. Immutability: when a contract is added to theblockchain, there is no way to edit it. If a con-tract is found to be defective, there is oftennothing to be done short of killing the contract(assuming measures were taken by the contractcreator to make this possible).

8. Ether lost in transfer: If ether is sent to an“orphan” address that doesn’t actually belongto any user or contract, that ether will be lostand cannot be retrieved.

9. Transaction Ordering Dependence (TOD) :This occurs when the assumed state of theblockchain is not the blockchain’s actual statewhen a transaction is executed. The order inwhich transactions are mined can have adverseeffects on the execution of any given transac-tion. This bug is said to be present in up to%15.8 of all contracts on the blockchain1.

10. Stack size limit: a transaction’s call stackgrows with each contract invocation, and oncethe stack is 1,024 frames tall, an exception isthrown. Changes to gas rules and certian in-struction costs have resolved this vulnerabilityin the current enviromnent.

11. Generating Randomness: many contractsthat require random numbers use the hash oftransactions yet-to-appear in the blockchain. Amalicious miner could arrange their block toinfluence the outcome of this random numbergeneration.

12. Timestamp dependence: some Dapps usetimestamps to generate random numbers.However, the clock in Ethereum is set by thelocal clocks of its miners. So, such Dapps canbe influenced with slight adjustments to min-ers’ reported times.

Additionally, there have been at least 20 reportedtypes of integer orverflow/underflow vulnerabilities.Finally, the solidity documentation maintatins a listof known bugs by version.

2.2 Static Analysis

It was demonstrated that many contracts are likelyvulnerable to exception disorder in the form ofunchecked ’send’ instructions [3]. Further, theevmdis [10] tool performs disassembly of contractbytecode and JUMP target analysis.

2.3 Symbolic Execution: Oyente [11]

Luu and colleagues developed the Oyente symbolicexecution system with the security goals of mit-

1https://medium.com/@hrishiolickel/why-smart-contracts-fail-undiscovered-bugs-and-what-we-can-do-about-them-119aa2843007

3

Page 4: DappGuard : Active Monitoring and Defense for Solidity ... · DappGuard : Active Monitoring and Defense for Solidity Smart Contracts Thomas Cook tomcook@mit.edu ... Best practices

igating TOD, exception disorder, and timestampdependence bugs for contract owners in the pre-deployment stage and users in the pre-transactionstage. Oyente is able to, given the Ethereum globalstate and a contract’s bytecode, whether the con-tract’s execution has feasible paths to the bug andwith what input and path constraints. Oyente’s de-sign also utilizes a black box validator to identifyand remove false positives.

2.4 Formal Verification

Smart contract security has seen some progress viaformally verified proofs about certain contract prop-erties. For example, Bhargavan and showed that bydecompiling certain Solidity contracts to F*, boundscan be proven on the gas consumed by a call invo-cation. [7]. The most prominent shortcoming cur-rently is that the system used to translate the Soliditycode does not support all Solidity features.

2.5 Best practices

Best practices for writing safe smart contracts arescattered across the Ethereum community. [9, 8].Many of these are guidelines for engineering securemechanisms into smart contracts such as fail-safemodes, circuit breakers, and assert guards. Thesemechanisms have been studied in other contexts,and we adopt some of them into our design whereapplicable. Other best practices actually eliminatemany vulnerabilities. Additionally, these best prac-tices have become Ethereum Improvement Propos-als, which introduce lasting changes to the environ-ment. EIP 150, one notable example, essentiallysolved the stack size limit bug. For example, usingname resolution for called contracts (which is pro-vided by some library smart contracts). Further, us-ing blocknumber over timestamp avoids any minerattacks on timestamp dependence. Finally, timedcommitments are one way to overcome the keepingsecrets bug. [5]

3 Our Contribution

Our work consisted of two phases. First, an inves-tigation of what information about smart contracttransactions exists on the Ethereum blockchain, if

this information is enough to identify potentiallymalicious transactions, and finally, if these mark-ers provide reason to think that common vulnera-bilities are actually being exploited in selected livecontracts. Our findings motivate the second compo-nent, DappGuard, a system for live smart contractmonitoring.

3.1 Searching for attack fingerprints

For each common vulnerability we identified, wefirst considered what the visible effects of an exploitof that vulnerability might be. The codification ofthese side-channel effects informed our subsequentanalysis of the live contracts.

Keeping Secrets, TOD This vulnerability is com-mon in ‘random’ gambling-based contracts, as usersmight be able to influence the outcome of a con-tract’s execution by broadcasting a large number oftransactions immediately preceding the execution.Here, we would expect to see a burst of activity froma given user in a short period of time, which, withina given period, could present as higher-than-averagegas costs, or as larger bets, given the influencedoutcome (which might mean a higher-than-averagetransaction value when they place their bet).

Reentrancy Reentrancy will result in multiplecalls to a contract’s fallback function, which maybe easily visible in the offending transaction’s log.Here especially, abnormally high gas usage could bea symptom of an attack. Comparing a normal trans-action to a malicious transaction exploiting reen-trancy on our SimpleDAO contract, the amount ofgas used in the malicious transaction was directlyproportional to the number of reentrancies that con-tract was able to make.

Gasless send, call to the unknown These aremost often caused by mistakes in writing eithertransactions or contracts, rather than exploitablevulnerabilities, but they can result in unexpectedconsequences (i.e. the seemingly unpredictable ex-ecution of the recipient contract’s fallback func-tion). It is not likely that gasless sends are inten-tionally provoked by a malicious user, because a

4

Page 5: DappGuard : Active Monitoring and Defense for Solidity ... · DappGuard : Active Monitoring and Defense for Solidity Smart Contracts Thomas Cook tomcook@mit.edu ... Best practices

contract would likely stand to gain more value inether than the gas wasted by a calling address whowould get an out of gas exception. Likewise, callsto the unknown are likely mistakes rather than theresult of malicious activity, and tools provided bymany Ethereum wallets as well as Dapps like theEthereum Name Service can help prevent erroneoussends.

Integer overflow/underflow Atzei, Bartoletti,and Cimoli identified a second possible of attackon the DAO contract that relies on an integer un-derflow to allow a malicious contract to withdrawmore ether than it deposited. This is a more sub-tle vulnerability than reentrancy, as it only involvestwo calls to the malicious contract’s fallback, mak-ing the attack less obvious and less likely to resultin an out-of-gas exception. However, we still expectsuch an exploit to consume more gas than a normalcall, and we might also be able to detect the two fall-back invocations in the affected transaction’s log.

Exception disorders Exceptions in Solidity arehandled inconsistently, with behavior depending onhow the inciting call was made. This means thatthe identification of non-exception side-channel ef-fects of exploits (and exceptions, in any case, aren’talways a result of certain exploits) is especially im-portant in identifying exploits that intentionally orunintentionally take advantage of Solidity’s confus-ing exception handling model.

3.2 Testing Methodology

What is likely common between the effects of ex-ploits on common smart contract vulnerabilities arehigh gas usage, strange message values (especiallyin transactions on ‘random’ gambling contracts),and suspicious fallback invocations that might bevisible in a transaction’s log. We are interested inthe prevalence and detectabbility of these effects inreal contracts.

3.2.1 SimpleDAO

To test the likelihood of a given contract being sub-ject to malicious behavior, we first deployed a smartcontract modeling the DAO contract and attempted

to replay the attack against the DAO (an instanceof reentrancy). After depositing (test) ether into thecontract, called SimpleDAO, on behalf of multipleother contracts, our malicious contract was able towithdraw more ether than was deposited on its be-half. Once we initiated the reentrancy with a callto the malicious contract’s fallback (which occursany time ether is transferred to a contract), the con-tract was able to perform two withdrals of one ethereach (after depositing only one) before running outof gas.

That our example exploit was successful, and re-quired extremely simple techniques on behalf of themalicious party, we expect that the same vulnerabil-ity that affected the DAO is still possible and imple-mentable (especially given that many contracts pub-lish their source code publicly). Without attention tothe transaction receipts, or if a contract has a partic-ularly large gas allocation, such an attack might gounnoticed, especially on high-value contracts withmany transactions. The feasibility of this exploit,and the ease with which it might go undiscoveredin less-dramatic instances than of the DAO, is evi-dence that the attacks we identified are very possibleto execute.

3.3 Live Contract Analysis

Seeing that a common smart contract exploit wasfeasible, and could potentially be detected via aber-rant gas usage or message values, we analyzedthe transaction receipts for several gambling-basedDapps.

3.3.1 Transaction Receipts

For each of the Dapps EthereumLottery, Etheroll,HonestDice, and Rouleth (versions 3.5 and 4.8), weretrieved transaction receipts for up to 10,000 trans-actions on the contract. Each transaction receipt isof the following form:

{"blockNumber":"3702663",

"timeStamp":"1494720276",

"hash":"0x662aca...",

"nonce":"40",

"blockHash":"0x64b...",

5

Page 6: DappGuard : Active Monitoring and Defense for Solidity ... · DappGuard : Active Monitoring and Defense for Solidity Smart Contracts Thomas Cook tomcook@mit.edu ... Best practices

"transactionIndex":"12",

"from":"0xa4fc86...",

"to":"0x9473bc8b...",

"value":"200000",

"gas":"303587",

"gasPrice":"10000000000",

"isError":"0",

"input":"0x727b1...",

"contractAddress":"",

"cumulativeGasUsed":"752879",

"gasUsed":"203587",

"confirmations":"3612"

}

Transaction receipts only refer to transactionsthat have been successfully added to the blockchain,so blockNumber refers to the block where thetransaction was mined (and timeStamp the time itwas mined). The hash is the transaction’s iden-tifier. Nonce is a hash of the proof of work re-quired of the miner who mined the block containingthis transaction, and the transaction’s index refersto its position relative to other transactions on theblock. The number of miners who agree on thistransaction’s outcome is given in confirmations.ContractAddress is empty for all transactions thatdo not create a contract (for transactions where thecontract of interest is called by another user or con-tract, the to field will be the address of the contractof interest).

For the purposes of our analysis, we are interestedin the following fields:

• from: This is the address of the calling con-tract or user. The large number of transactionsfor some contracts means we might identifypatterns in certain users’ behavior.

• isError: This flag is set to 1 when an ex-ception occurred during the execution of thetransaction. Exceptions are reasonably com-mon (and can be the result of a simple mis-take in writing contracts or transactions), but ifspecific users generate many exceptions wheninteracting with a given contract, we might besuspicious.

• gasUsed: This measures (in units of gas) theamount of gas consumed during the transac-tion’s execution. Many exploits come with the

side effect of using more gas than we mightexpect, and so we can check for suspiciouslyhigh gas usage among users. Again, gas usagecan be variable and doesn’t necessarily indi-cate wrongdoing, but consistently high gas us-age from a single user might be a sign of anattacker.

• value: We are examining gambling contracts,and so the value (in wei, which is equivalent to10−18 ether) often represents a bet. A spike inmessage value might represent a suspiciouslyhigh bet, perhaps indicating that the user hasmore confidence than others about the outcomeof the gamble.

Given this information, we gathered the follow-ing data for each contract tested:

• For each user, the number of transactions thatresulted in exceptions.

• For each user, the amount of ether transmittedand gas per transaction (and the respective av-erages per user).

• The total amount of gas spent on the contract’stransactions, the total value transferred, and thetotal number of transactions considered.

• The average and standard deviation of gas us-age over all of the contract’s transactions, andthe average and standard deviation of valueover all of the contract’s transactions.

• For each user and each transaction, the numberof standard deviations away from the contractaverage for gas and value the transaction’s gasusage and value lie.

• The number of users who had transactionswhere gas expenditure fell outside two stan-dard deviations of the contract’s average.

Of course, evaluating value and gas usage acrossusers is less illustrative if gas expenditure and mes-sage values seem random. However, as we wouldexpect, in the contracts we tested gas usage tends topeak around certain values (presumably, functionsin the called contract expend reasonably consistentamounts of gas per call), and values seem similarly

6

Page 7: DappGuard : Active Monitoring and Defense for Solidity ... · DappGuard : Active Monitoring and Defense for Solidity Smart Contracts Thomas Cook tomcook@mit.edu ... Best practices

clustered. The standard deviation calculations as-sumed a roughly normal distribution for gas andvalue, but this assumption was likely inappropri-ate for some of the contracts. More refined outlierdetection would be necessary to evaluate contractswith more complicated distributions.

3.3.2 Observations

From this analysis, we noticed the following2. First,we observed several users with high proportions oferroneous transactions– one user of Rouleth3.5 (thelargest contract we tested by number of transac-tions) had a total of eight transactions with the con-tract, seven of which resulted in exceptions. We alsosaw a number of users who had at least one transac-tion with gas usage more than two standard devia-tions above the contract’s average (for Rouleth3.5,92 such unique addresses were identified from themost recent 10,000 transactions).

Second, we found instances of contracts withwell-grouped distributions of average gas use andvalue transferred per user. Histograms of averagegas usage per user reveal that some contracts admitto normal-looking distributions of average user gasexpenditure per transaction. Pictured is such a his-togram for Rouleth3.5, where we can clearly see anumber of users that, on average, used significantlymore gas than most– but, according to the amountof gas allowed, did not, on average, run out of gas.This result is of considerable interest- instances ofgas usages that are much higher than average coulddefinitely be suspect– but, because the gas used wasstill within the amount allocated, it caused no visibleeffects. Of course, there are legitimate reasons whya transaction might use a lot of gas, but this is toshow that malicious executions that will definitelyuse excess gas can be identified.

An example of a histogram of average user valueper transaction is shown for Etheroll. Here, we seethat a large proportion of transactions transferreda small amount of Ether, but a handful transferred

2All transactions initiated by the contract creator were omit-ted from this analysis. Contract creators might call a host offunctions on their own contract that do not represent standarduse of the contract, and the contract owners often make a largenumber of transactions that would likely have skewed our anal-ysis.

much more– on the order of ten-times more, in somecases. Again, a high value transfer is not certainlysuspect, but this is to show that outliers, at least forsome contracts, can be identified.

4 Proposed Design

4.1 Threat Model

DappGuard assumes that an attacker holds at leastone Ethereum account and may or may not also bea miner. We also assume the contract creator fol-lows best practices and deploys formally verifiedcontract.

4.2 System and Goals

In order to collect data from the blockchain, oneneeds to run a blockchain node with one of the avail-able clients. The most popular clients for Ethereumare geth written in Go and parity written in Rust.These clients have managment APIs that allow ex-

7

Page 8: DappGuard : Active Monitoring and Defense for Solidity ... · DappGuard : Active Monitoring and Defense for Solidity Smart Contracts Thomas Cook tomcook@mit.edu ... Best practices

ecution tracing and In our experimentation, to de-ploy test contracts without needing to spend realmonetary value holding ether, we used a testnet andexperimented implemnting a fail-safe by sendingtransactions to our contract. As a result, we presenta design for DappGuard.

The goals of DappGuard are relatively simple:

1. Classify known attacks from transaction data

2. Protect smart contracts from known attacks

3. Determine malicious actors and learn new at-tacks

To accomplish these goals, DappGuard’s archi-tecture relies on the following components:

• EthWorldModel (EWM)

– ContractModel

– AddressModel

– MinerModel

– Rules

• Blockchain Monitor Nodes (BMN)

– Mainnet node

– Private testnet Clone node

• TransactionRiskAnalyzer (TRA)

– Oyente Validator

– Transaction Foretrace

– Anomaly Analysis + Rules Engine

– Responder

The EWM stores information about transactionhistories for the contract, for users who have in-teracted with the contract, and metadata associatedwith the blocks containing each transaction. TheContractModel stores statistics relevant to the clas-sification of any new transactions– such as distribu-tions of gas usage and value transferred from pasttransactions and the number of transactions on thecontract (in total, and from particular users). Thesemodels will resemble a refined version of our livecontract analysis (Sec. 3.3).

The AddressModel represents each address’s in-teraction with the contract– amount of value trans-ferred, average gas usage, and the number of excep-tions among its transactions with the contract.

The MinerModel serves to relate transactions onthe contract wiht the details of the blocks and min-ers responsible for adding them to the blockchain.Such information as who mined a block contain-ing a transaction on the contract, the order of trans-actions on that block, associated with informationfrom the AddressModel for the source of the trans-action.

The Rules Engine works to apply each model tonew transactions to inform judgments about the va-lidity of the transaction, and updates each model tostrengthen the identification of standard and mali-cious transactions and mining patterns.

The BMNs serve to keep an up-to-date versionof the blockchain available (the Mainnet node), andto test the execution of pending transactions on ourcontract (the Testnet node). These nodes are eachEthereum nodes on the main network and a test net-work (such as Ropsten or Kovan) respectively. TheMainnet node’s job is to remain synced with themain blockchain. The job of the Testnet node is totrace the possible states for all orderings of transac-tions on our contract that are pending on the mainnetwork.

To identify security risks associated with TOD,exception disorders, and timestamp dependencies,we validate pending transactions against the resultsof the Oyente symbolic execution system. This val-idator uses the results of running Oyente on our con-tract, in the form of constraints on function inputsthat produce bugs of these kinds, to determine thevalidity of the transaction’s execution. Security is-sues outside the scope of this validator will be ad-dressed by either the Testnet simulation or applica-tion of our Rules Engine.

Finally, the Responder module reacts to danger-ous transactions as determined by the contract. Thismight send a notification to the contract owner (as alogged event on the Testnet node), or initiate a take-down of the contract, or kick off a transaction gen-erated by the user that changes the contract’s stateto prevent an imminent transaction from exploitinga security hole.

8

Page 9: DappGuard : Active Monitoring and Defense for Solidity ... · DappGuard : Active Monitoring and Defense for Solidity Smart Contracts Thomas Cook tomcook@mit.edu ... Best practices

4.3 Modes of Operation

4.3.1 Knowledge Acquisition

This mode refers to DappGuard initially populating,maintaining, and optimizing its EthWorldModel forefficient transaction analysis. This would includegathering a complete blockchain transaction historyand analysis, and updates to any known vulnera-bilities or risk indicators used by the Rules En-gine. Any post-mordem analysis of missed attackswould be one example. Finally, any information ex-change with client smart contract owners that resultsin changes to the EWM would fall under knowledgeacquisition for DappGuard.

4.3.2 Active Monitoring & Detection

For any client smart contracts that DappGuard man-ages, it actively monitors the incoming transactions.For all incoming transactions to the contract of in-terest, we the use the saved result of Oyente excu-tion for the contract to determine quickly whetherthe contract will experience a TOD, exception dis-order, or timestamp dependence bug. Then, for re-maining potential vulnerabilities, the contract exe-cution is simulated on the private testnet and anyattacks on that execution are detected using theAnomaly Analysis and Rules Engine. Finally, if athreat is detected that will possibly transpire, Dapp-Guard will send a transaction, that with high proba-bility, gets mined before the risky transaction.

5 Suggestions for Future work

As to future work, we mention directions we con-sidered before finalizing our decision. Although So-lidity was the only smart contract language we con-sidered, others too have emerged such as the func-tionally typed Bamboo, which hopes to mitigate im-mutability bugs. Additionally, we considered thatbecause Dapps have traditional web front ends, thatthey could be vulnerable, too, to traditional web ex-ploits. The last attack vector we considered was thatof padding in the Ethereum Virtual Machine andmalleability of transactions. This is protected cur-rently, so long as the keccak256 hash of the data isverified and that keccak256 remains secure.

6 Discussion

Obviously, the current incarnation of DappGuard islittle more than proof-of-concept based on our de-veloped tools. However, we believe that our re-search shows that blockchain data and knowledgeof smart contract attack mechanics can be used todetect attacks as they occur. Further, we believe byproviding this design, we both motivate active andadaptive security in the Ethereum ecosystem andidentify strong candidates for tools a system of thisnature would rely on.

9

Page 10: DappGuard : Active Monitoring and Defense for Solidity ... · DappGuard : Active Monitoring and Defense for Solidity Smart Contracts Thomas Cook tomcook@mit.edu ... Best practices

References

[1] Ethereum Hack dao hack simplified.http://blog.erratasec.com/2016/06/

etheriumdao-hack-similfied.html. Accessed:2016-06-18.

[2] Ethereum what is ethereum for beginners. https://

blockgeeks.com/guides/what-is-ethereum. Ac-cessed: 2012-01-30.

[3] Hacking, Distributed: Scanning live Ethereum con-tracts for the ”unchecked-send” bug, author= Wen,Zikai Alex and Miller, Andrew, year = 2016, howpub-lished = ://hackingdistributed.com/2016/06/16/scanning-live-ethereum-contracts-for-bugs/.

[4] thedao hack faq. https://ethereum.

stackexchange.com/questions/6183/

thedao-hack-faq-how-did-the-attack-happen-on-17-june-2016.Accessed: 2016-06-17.

[5] ATZEI, N., BARTOLETTI, M., AND CIMOLI, T. A sur-vey of attacks on ethereum smart contracts. Tech. rep.

[6] BARTOLETTI, M., AND POMPIANU, L. An empiricalanalysis of smart contracts: platforms, applications, anddesign patterns. CoRR abs/1703.06322 (2017).

[7] BHARGAVAN, K., DELIGNAT-LAVAUD, A., FOURNET,C., GOLLAMUDI, A., GONTHIER, G., KOBEISSI, N.,KULATOVA, N., RASTOGI, A., SIBUT-PINOTE, T.,SWAMY, N., AND ZANELLA-BEGUELIN, S. Formal ver-ification of smart contracts: Short paper. In Proceedingsof the 2016 ACM Workshop on Programming Languagesand Analysis for Security (New York, NY, USA, 2016),PLAS ’16, ACM, pp. 91–96.

[8] CONSENSYS. Smart contract best prac-tices. https://github.com/ConsenSys/

smart-contract-best-practices#

eng-techniques, 2017.

[9] ETHEREUM. Security considerations. http:

//solidity.readthedocs.io/en/develop/

security-considerations.html, 2015–2017.

[10] JOHNSON, N. evmdis. https://github.com/

Arachnid/evmdis, 2016–2017.

[11] LUU, L., CHU, D.-H., OLICKEL, H., SAXENA, P.,AND HOBOR, A. Making smart contracts smarter. InProceedings of the 2016 ACM SIGSAC Conference onComputer and Communications Security (New York, NY,USA, 2016), CCS ’16, ACM, pp. 254–269.

[12] WOOD, G. Ethereum: A secure decentralised generalisedtransaction ledger. Ethereum Project Yellow Paper 151(2014).

Code

All code relevant to this project can be found inthe following repository: https://github.com/

cookt/857final

10

Page 11: DappGuard : Active Monitoring and Defense for Solidity ... · DappGuard : Active Monitoring and Defense for Solidity Smart Contracts Thomas Cook tomcook@mit.edu ... Best practices

Appendix of Live Contract Gas and ValueHistograms

11

Page 12: DappGuard : Active Monitoring and Defense for Solidity ... · DappGuard : Active Monitoring and Defense for Solidity Smart Contracts Thomas Cook tomcook@mit.edu ... Best practices

12