• United States




What are blockchain’s smart contracts? And how to secure them

Oct 15, 201811 mins

Smart contracts are moving into the enterprise, but they aren’t bulletproof. These are the vulnerabilities and best practices for securing them.

hand holding magnifying glass over contract
Credit: Thinkstock

Smart contracts are a key component of blockchains. These little slices of business logic are the self-executing code that enables developers to create the rules and processes that make up any blockchain-based application. However, while they have the potential to automate and simplify business processes, they are also the main target of any malicious actor looking to compromise such an application.

A study by the National University of Singapore and University College London earlier this year found over 34,000 vulnerable smart contracts on the Ethereum network. Attacks involving poorly coded contracts could be something as trivial as the ability to cheat in a blockchain-based game of rock paper scissors, to the loss of millions of dollars’ worth of cryptocurrency, to the need to fork the underlying platform entirely, as happened in the wake of the DAO hack.

What are the ways smart contracts can be exploited, and what best practices can be applicated to ensure secure smart contracts?

Common smart contract vulnerabilities

Smart contracts offer interesting new ways to do business and manage business processes. They also offer new avenues for potential malicious activity.

Some are traditional types of exploits that can be found within most applications: access control issues, under- and overflow errors, insecure libraries, or business logic vulnerabilities. Developers need to be aware of a host of smart contract-specific vulnerabilities.

  • Re-entrancy enables attackers to misuse certain functions to repeatedly enter and execute their desires before a certain point in the code–for example, repeatedly transferring cryptocurrency before the balance is confirmed until the account is drained and causing the process to fail. This method was used in the DAO hack, but is preventable through good coding practice.
  • Integer overflow and underflows are commonly seen problems within smart contracts. One such flaw was recently reported in multiple Ethereum smart contracts using a certain protocol. These can often be fixed with libraries such as OpenZeppelin’s SafeMath library.
  • Short address attacks can occur if a target address within a transaction is short. The Ethereum platform pads the address with zeros instead of invalidating the transaction. Using this knowledge, malicious actors can execute a perfectly legitimate transfer for an amount that is much larger than should be possible, and potentially drain a wallet of tokens.
  • Mistakes around functions: In Ethereum, functions – the executable units of code within a contract — are public by default, meaning they can be called by anyone. A function issue enabled the hack of Parity Wallets and the loss of around $30 million in cryptocurrency.
  • Denial of service. There are various ways to knock out a contract through DoS attacks. These include inflating transaction costs, requiring certain privileges to authorize a transaction [owner operations], and or simply trapping contracts in infinite loops.  

“Most of the vulnerabilities are language independent as the smart contracts are compiled to the bytecode or intermediate code and executed by virtual machines,” says Damian Rusinek, IT security researcher at SecuRing. “However, the languages introduce different code structures to achieve the same functionality (e.g., access control) which can be harder to implement in some cases.”

Another factor to consider is that contracts can’t be updated once deployed; once live they can only be killed or chained to an updated contract (which can add complexity and risk). This might not be such a problem in private or consortium scenarios – where killing a contract and getting all involved parties to adopt the new contract is easier – but should still be prepared for.

“Smart contracts should be treated differently from other kinds of applications,” says Jordan Andrews, smart contract lead at Stratis. “There are unique challenges that come with executing smart contracts that do not exist in traditional computing paradigms – such as the level of certainty that developers need to have about the precise functionality of their code — which can affect the security of a contract.”

Enterprise smart contract applications also at risk

Most of the well-publicized exploits of smart contracts have involved cryptocurrencies, due to the fact that large amounts of difficult-to-track digital currencies make enticing targets, but there is plenty of potential for abuse in enterprise-based scenarios. In a supply chain example – an increasingly common use case for blockchain – a compromised smart contract could allow an attack to change details such as delivery locations or shipment size. A DoS-type attack could simply knock an entire part of your supply chain offline.

Another example could be an exploit in contracts used for identity management. An exploit to take control of or edit someone’s identity could which could have major ramifications if it was tied to somebody’s healthcare treatment.

Smart contracts on private blockchains can still be vulnerable

The enterprise space is more interested private/consortium blockchains, which are more focused on decentralization than the idea of being permissionless, as every entity in such scenarios is more likely to be known and trusted. “From the technical perspective the private blockchains have the same problems, but the fact that the group of its users is permissioned drastically decreases the risk,” says SecuRing’s Rusinek. He does warn, however, that assuming the nodes in the network are completely trusted could leave a company exposed to an insider threat.

Dan Guido, CEO of security consultant Trail of Bits, warns that smart contracts are “an unforgiving development platform” and even in private scenarios any single individual vulnerability or flaw can result in a total loss of functionality or trust in the contract. “Most developers have a difficult time wrapping their heads around the shared computing environment on a blockchain and how malicious users can abuse this unique vantage point to benefit themselves.”

Instead of Ethereum, many enterprises are using Hyperledger Fabric, the open-source blockchain platform from the Linux Foundation, as their choice of platform for private and consortium blockchain environments. A number of companies including IBM, Microsoft and Amazon use it as the basis for their blockchain as a service (BaaS) offerings.

“Fabric has thought about how you manage the lifecycle of chaincodes (the Hyperledger’s term for smart contracts) within the network, and how you manage, install, substantiate, upgrade the chaincode across different organizations, says David Gorman, part of IBM’s global client engagement team for blockchain. “You can be very specific about which organizations and which nodes have a copy of the chaincode, and which can be called to execute or endorse transactions.”

While it is possible for one organization to have installed a different version of the chaincode contract, the design of Hyperledger would quickly flag the fact that not every company that executed the chaincode returned the same result. You can also mitigate this by creating an endorsement policy to ensure that when the contract is first released, the package has been pre-validated by various organizations on the network.

The fact that Hyperledger uses a system called the “world state” also helps flag and prevent malicious activity. The world state is the “single source of truth” database of current states [e.g.,  bank account balances] shared between organizations, while “the ledger” is a record of the transactions [e.g., the switching of money between two parties]. If an organization’s copy of the world state is different to the rest, the proposed transactions would fail during the validation phase.

At the time of writing, there have been no publicized attacks involving Hyperledger Fabric. Javed Samuel, head of cryptography services at NCC Group, predicts that as more and more enterprises start to adopt and integrate blockchain-based processes, attackers will focus more attention to the likes of Hyperledger and business process compromise attacks involving smart contracts, and so developers should be ready.

“The security model they follow should be the same in both cases [public or private blockchains]. We shouldn’t go in with the assumption of security by obscurity, or that it’s only trusted users that will see the smart contract,” he says. “From a security perspective, we recommend you assume more people are going to view your smart contract than who might currently have access to it.”

It is also possible to deploy Ethereum-based smart contract within Hyperledger Fabric environments, which means vulnerabilities within those contracts could potentially be added into your own environments.

7 best practices for smart contract security

While there will be differences between writing contracts for different blockchain platforms and between the various languages, there are best practices that all developers can take note of and improve the security of their smart contracts:

  1. Do your research. Developers need a full understanding of the blockchain platform the contract will run on and (and the security architecture of the environment if in a private scenario), as well as the way smart contracts work and ways they can be compromised.

    “Developers should start by deeply reviewing the language, compiler, and known security risks before writing any code,” says Trail of Bits’ Guido. “Build a specification for your project and know what you want to write and how it connects together.”

  2. Keep contracts simple and remember they are non-editable. The more complex a contract is, the greater the likelihood it will contain an error. In the same way microservices are better than monoliths, smaller contracts are better than giant ones. Organizations will still need to ensure the contracts they deploy have been well tested and have a clear contract upgrade strategy to avoid introducing risk down the line. “The more complex smart contracts become, the more likely it is that logic errors are introduced,” says Bernhard Mueller, product engineer at blockchain production studio ConsenSys Diligence. “We therefore advocate simplicity before anything else. Once they enter an undesirable state there’s no way back. Therefore, the logic contained in the smart contract should always be as minimalistic as possible, and there should be clear specifications as to how the contract must behave.”
  3. Testing and auditing are important. Given the difficulty around fixing insecure contracts, a comprehensive selection of unit tests are needed to ensure it is as secure as possible before deployment. A number of testing and debug tools – Truffle, Slither, Echidna, Oyente, SmartCheck, Mythril – and third-party auditing services are available. Use them to ensure your contract is as robust as possible.
  4. Don’t rush to push. Ensure developers are given ample time and resources to develop contracts in a way that is secure, and security teams have been given time to probe for issues. “A lot of the time the focus is on building the smart contracting and getting the functionality up and running and less focus on trying to ensure what we have is secure,” says NCC’s Samuel. “We need to ensure we have sufficient time and resources for auditing and ensuring the smart contract is secured appropriately.”
  5. Be wary of calling to other contracts. Avoid calls to untrusted contracts; external calls may execute malicious code in that contract or any other contract that it depends upon. Also, verify the libraries than you plan to use; Etherscan is a popular tool that offers a contract verifier so you can check any contracts you do plan on linking to do what they say they’re going to do.
  6. Do not keep secret data as plaintext. Ensure you understand how to store and execute secret data securely. Otherwise, potentially sensitive information – some of which may be key to how the contract executes – can be read by anyone inspecting the contract. In a private/consortium environment, this is probably best achieved with encryption keys.
  7. Ensure all your functions are tagged. Depending on the platform, contract functions are often set to public by default. Unless there outside interaction is necessary, keep your functions private or internal. This avoids external actors interfering with the execution of your contract. The Parity Wallet hack was a result of default public functions.

    “If you don’t specific the visibility type, it’s default so anyone can execute it,” says SecuRing’s Rusinek. “Private functions can be called only inside the smart contract from other functions in the same smart contract.”

As well as the Ethereum and Solidity sites themselves, NCC Group’s DASP and Blockchain production studio Consensys both offer further reading for security best practices around securing smart contracts.