Skip to main content

(This is a modified excerpt of Chapter 12 of Building Blockchain Apps by Michael Juntao Yuan, written and contributed by AnChain CEO Victor Fang. You may find the complete chapter and the rest of the book here.)

Smart contract, coined by American computer scientist Nick Szabo, is rightfully hailed as the revolutionary feature that defines blockchain 2.0, compared to the peer-to-peer decentralized transactions in the blockchain 1.0 era such as Bitcoin, Ripple, etc.

Ethereum is the most widely adopted smart contract-enabled blockchain. Ethereum smart contracts are, in essence decentralized software that can be executed and verified on the Ethereum public blockchain. Ethereum smart contracts are programmed in Solidity, a JavaScript-like programming language (ECMAScript syntax), and run in the EVM (Ethereum Virtual Machine).

Since Ethereum’s launch in 2015, developers have witnessed a plethora of successful applications, to name a few:

However, they have also experienced major smart contract security vulnerabilities that have caused billions of dollars of loss, and have been cause of growing concerns among the Blockchain communities.

Major Smart Contract Hacks and Vulnerabilities

Since the launch of Ethereum, the community has witnessed a multitude of major hacks, taking over the headlines for all the wrong reasons. A few select smart contract security issues and hacks behind those exploitations have been highlighted below.

DAO (Decentralized Autonomous Organization) Hack

The DAO smart contract hack is probably the most notorious hack in Ethereum history. A DAO is a Decentralized Autonomous Organization. Its goal is to codify the rules and decision- making apparatus of an organization, eliminating the need for documents and people in governing, creating a structure with decentralized control.

In June 2016, the attacker drained 3.5M ETH (~$50M) from The DAO smart contract, after the ICO token sale had ended. It led to a hard fork of Ethereum. The technique the attackers used is Re-entrancy.

Re-entrancy is also known as recursive call vulnerability. It occurs when external

contract calls are allowed to make new calls to the calling contract before the initial

execution is complete. For a function, this means that the contract state may change

in the middle of its execution as a result of a call to an untrusted contract or the use

of a low-level function with an external address.

In fact, re-entrancy is quite common. In Oct 2018, SpankChain, a cryptocurrency

project focused on the adult industry, suffered a breach that saw almost $40,000 in ETH stolen.

BEC Token Hack

The BEC token is particularly interesting because it shows how smart contract security issues can have a massive impact on a centralized crypto exchange (OK Exchange) in a subtle way, causing billions of USD in losses.

The Beauty Chain (BEC) was a high-profile cryptocurrency in China. Its stated goal is to be “a truly decentralized and beauty-themed ecosystem.”

It started trading on OKEX on Feb. 23, 2018. From its peak market cap of around $70 billion, it has gradually come down to around $2 billion as of April 22, when its trading value suddenly dropped to zero. OKEX subsequently suspended trading of BECs.

The BEC token hack was due to the “integer overflow” vulnerability in its ERC20 smart contract. The annotated code line in the listing below multiplies two uint256 numbers and assigns the result to another uint256 variable amount. Unfortunately, there is no overflow checking on that line. When the hacker passes legitimate but large uint256 variables, it can cause the product to overflow.

The way to prevent this is to use SafeMath for all arithmetic. In fact, this smart contract uses SafeMath in all except this particular function, and it caused catastrophic damage not only to BEC, but also to all exchanges that trade it.

There are ways to prevent integer overflows in smart contracts. The Lity language and virtual machine extensions to Ethereum checks for integer overflow at compile time, and then detects and aborts the smart contract when integer overflows at runtime.

The Parity Wallet Hack

This vulnerability showcases another way how the cryptographic smart contract design bug can damage the ecosystem: the wallet. The impacted Parity Wallet is one popular wallet for Ethereum and tokens.

In fact, Parity Multi-sig Bug is one of common bugs in cybersecurity OWASP (Open Web Application Security Project), called Access Control. These smart contract security issues are common in all programs, as well.

This bug impacted all users with assets in a multi-sig wallet created in Parity Wallet that was deployed after 20th July, 2017, worth $155 million. This bug was patched immediately after the hack.

The attacker sent two transactions to each of the affected contracts:

Step 1: Obtain exclusive ownership of the MultiSig.

In the wallet contract payable() function contains a bug that causes all public functions from the library to be callable by anyone, including initWallet, which can change the contract’s owners.

Unfortunately, initWallet has no checks to prevent an attacker from calling it after the contract was initialized. The attacker exploited this and simply changed the contract’s owner state variable to hackers’ addresses. This modified the access control and persisted in the immutable Ethereum Blockchain.

Step 2: Move all of its funds.

After the hacker took over the ownership, it was just a matter of invoking the execute function to send all funds to the hacker’s account. This execution was automatically authorized, since the attacker was then the only owner of the multisig, effectively draining the contract of all its funds.

FOMO3D and LastWinner DApp Hack

DApp, Decentralized App, is one dominant trend enabled by smart contracts. As of

March 2019, there are 2,667 DApps running on public blockchains, and the number

will likely grow tremendously.

FOMO3D (Fear Of Missing Out) is a gambling DApp that was so popular from July to August 2018 that it even congested the Ethereum blockchain. The FOMO3D Game’s simple rules are as follows.

  • User buys a “key” i.e. a lotto, to participate.
  • When anyone buys a key, the countdown clock adds a few seconds, 24 hours max.
  • The final buyer when the clock hits 0, wins the jackpot, $$$ millions.
  • Each key buyer receives a random airdrop bonus.

In fact, FOMO3D is a typical Ponzi scheme that theoretically should never stop,

because it is driven by human nature: greed.

Unfortunately, FOMO3D and its copycat LastWinner were both hacked in August 2018. Those hacks led to AnChain.AI’s discovery of the first Blockchain Advanced Persistent Threat (BAPT). APT, Advanced Persistent Threat, is defined as “Stealthy and continuous

computer hacking processes, often orchestrated by persons targeting a specific entity.”

MIT Technology Review featured this story:

“In August 2018, AnChain.ai identified five Ethereum addresses behind an extremely sophisticated attack that exploited a contract flaw in a popular gambling game to steal $4 million.”

Random number generation (RNG) is commonly used in DApps, just like all online Internet games. Think about online poker games. The house will generate the hand based on a random number generator every play.

A perfect random number should mathematically have high entropy, and cannot be predicted. However, on-blockchain RNG turns out to be quite challenging, due to the nature of the Blockchain: immutable, decentralized, transparent. Once the DApp has “bad randomness”, it will be exploited by hackers to predict the game play.

The Lity language and virtual machine extend the Ethereum protocol to provide

highly secure random number seeds for smart contracts, when the underlying

Blockchain consensus is Delegated Proof of Stake (DPoS).

Unknowns and Beyond

These reported vulnerabilities may be only the tip of the iceberg. In the Ethereum network, millions of smart contracts have been deployed with a balance of billions of US dollars, but only a small percentage of them contain publicly accessible source code.

Based on research powered by AnChain.ai smart contract auditing sandbox, more than 0.6% out of the 50,000 mainnet deployed smart contract source code are vulnerable to re-entrancy attack. 57,911 known vulnerabilities found among all of them. Even known vulnerability can repeat history.

On January 16th, 2019, the Constantinople protocol upgrade was delayed, at the last minute, due to a security vulnerability enabled by EIP 1283. This change led to possibility of a new reentrancy vector making previously known secure withdrawal patterns (.send() and .transfer()) unsafe in specific situations, where the attacker could hijack the control flow and use the remaining gas enabled by EIP 1283, leading to vulnerabilities due to re-entrancy. The upgrade was hence delayed. Otherwise another Ethereum catastrophe would have happened.

Smart Contract Security Best Practices

The above major smart contract hacks clearly illustrate that developing secure smart

contracts is quite challenging.

In fact, average bugs per LOC statistics in Steve McConnell’s Code Complete, shows that Industry Average: about 15 – 50 errors per 1000 lines of delivered code; Microsoft Applications: “about 10 – 20 defects per 1000 lines of code during inhouse testing, and 0.5 defect per KLOC (KLOC stands for “1000 lines of code”) in the released product.

Another challenge for the Ethereum blockchain is that it’s hard to change the smart contract code, once it’s deployed. Think about Microsoft Windows patches that arrive weekly to fix the known vulnerabilities. There is no such mechanism on the blockchain. It’s “code is law”.

The Lity project provides a mechanism to upgrade Ethereum-compatible smart contracts on Lity-based blockchains. The idea is to declare the contract interface at the contract address, and then provide proxy implementations of all the functions.

Hence, it is critical to write secure code in the upcoming smart contract era. Fortunately, there are various projects and startups that aim to help developers establish smart contract security by performing auditing that will identify vulnerabilities. Below are a few best practices.

Expert Manual Auditing

The widely adopted way of performing a smart contract security audit, especially the ICO tokens, is expert manual auditing. Solidity is a new programming language and lacks security tools, compared to in the well-established cybersecurity industry that has commercial tools such as Coverity for enterprise C++ / Java source code auditing. The experts are mostly computer language experts with experience in identifying vulnerabilities manually.

Formal Verification

FV is one of the promising fields for a smart contract security audit, which aims to mathematically prove the source code correctness.

Formal verification is the act of proving or disproving the correctness of intended algorithms underlying a system with respect to a certain formal specification or property, using formal methods of mathematics.

In fact, the Formal Method dates back to 40 years ago, and there are various applications such as Windows leveraging formal verification to prove some of the critical kernel modules’ source code correctness.

Sandbox

Sandbox, simply put, is a specially designed “Virtual Machine”, which can automatically execute the opcode instructions in a restricted environment. Sandbox is a proven technology in cybersecurity, companies like FireEye, Palo Alto Network develop malware sandbox products that can detect the most sophisticated malware like APT32 and such.

For example, modern advanced malware is “polymorphic” which will modify its bytes. Most antivirus software still relies on “signature based” which is a hash of the payload bytes. Hence, these polymorphic malwares can bypass the AV detection since they’ve got a different hash, though they function similarly. Alternatively, sandbox will analyze the code execution behaviors, and look for suspicious patterns, in a fully automated fashion.

Inspired by the proven success of malware sandbox, AnChain.ai developed the world’s first smart contract security audit sandbox, and launched in Feb 2019. A good sandbox product should have built in features such as:

  • Static analysis
  • Dynamic execution
  • Statistical analysis, and;
  • Code similarity, and more.

Optimize Your Smart Contract Security Now

Ethereum is still in its infancy. We consider it like the 1990s of the Internet, slow and vulnerable. We believe it will soon become as mature as the Internet in 2019. However, with data breaches, APT hacks occasionally taking our headlines, even Internet security still has a long way to go. Security is a collaborative effort that involves many specialized experts, teams, and tools.

Are you ready to establish your smart contract security? Contact us here.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments