Research Summary: Attacks on Smart Contracts

TLDR:

  • We present an up-to-date survey of smart contract security issues and their mitigations. We achieve this by combining the top research on smart contract security with cutting edge open source knowledge and information.
  • We find that almost all of the most common attacks could be avoided or at least severely mitigated by following better coding practices. This includes general principles as well as specific design patterns against given attack types.
  • The most common smart contract attack types are explained on a technical level and suggested mitigations against each one are given.

Citation

Porkka, Otto. “Attacks on Smart Contracts.” (2022). https://helda.helsinki.fi/bitstream/handle/10138/345427/20220607_Porkka_Pro_Gradu_FINAL.pdf?sequence=2

Background

Smart contracts expand the utility of blockchains to distributed state machines, where anyone can store and run code and then mutually agree on the next state. This added utility also brings up many security challenges which are of the utmost importance given the money involved with smart contracts.

As a brand new and constantly changing field, the need for better coverage and understanding of smart contract security issues is increasing. A major portion of smart contract research and innovation also happens outside of the scientific field in online communities, so getting an up-to-date view on smart contract security, combining cutting edge open source knowledge and previous scientific work is needed.

As a master’s level thesis, smart contracts and blockchain technologies are explained on a technical level in the background section so very little prior knowledge is needed to understand the topic.

Important terminology:

  • Smart Contracts: Autonomous accounts living in the blockchain with the code that dictates their behaviour. When triggered by a transaction, the smart contract’s code is executed on the Ethereum Virtual Machine (or, if not Ethereum, the blockchain’s native environment).
  • Ethereum Virtual Machine (EVM): Ethereum’s execution environment. Also, a general term for the distributed state machine that the nodes of a blockchain network forms. It maintains the blockchain’s state and allows the execution of smart contracts. If a smart contract code is executed, the nodes execute and validate the code and mutually agree on the next state.
  • Transaction: A request to update the blockchain state. Includes value transactions and smart contract invocations. Always requested by externally-owned accounts, i.e. accounts controlled by a human/private key, although smart contracts can invoke other smart contracts via transactions once executed. Transactions are mined into a block once executed.
  • Gas: Fee to be paid to nodes for executing a transaction and including it in a block.
  • Mining/Miner: Mining is the action of forming the next block in the blockchain. Miners are the nodes that form the blockchain network and maintain and update the state of the blockchain and EVM via a consensus algorithm. (In this thesis we refer nodes of the network generally as miners even though they are not always technically “mining” if, for example, Proof of Stake is used)
  • Consensus Algorithm: A way for miners to mutually agree on the next state of the blockchain. Proof of Work is the most used one, Proof of Stake is making its way.
  • DeFi: Decentralized Finance. Financial systems built with smart contracts that operate on blockchains in a decentralized manner.
  • Attack Type: Used as an umbrella term for all the attacks and vulnerabilities that are covered. This is to make distinction between an
    • attack, which refers to a specific action,
    • vulnerability, which refers to a flaw in the code or technology,
    • attack vector, which refers to a general pathway or attack surface that exploits use.

Research Question or Use Case

What are the most common attacks on smart contracts and how can they be mitigated? In other words, what is the current state of smart contract security?

Summary

In this thesis we give an up-to-date survey of smart contract security issues. First we give a brief introduction to blockchains and smart contracts and explain the most common varieties of attacks and ways to mitigate them. Then we sum up and analyse our findings.

Covered attack types include:

  • Re-entrancy
  • Timestamp Dependence
  • Front-Running (First in general, then split into sub-types)
    • Transaction Ordering Dependence
    • Block Stuffing
    • Block Reorganization Attacks
  • Integer Overflow and Underflow
  • DoS With Revert
  • Insufficient Gas Griefing
  • Forcibly sending Ether To A Contract
  • Oracle Manipulation

After each attack type, we present suggested mitigations. These are split into three classes: better coding practices, automated tools and technology changes. Better coding practices include coding practices and principles that can prevent specific problems or help design secure smart contracts in general. Automated tools includes a range of tools from IDE expansions and code analyzers, to full-on fuzzing and testing software. Lastly, technology changes refers to changes to the underlying blockchain technology, i.e., making changes to a protocol.

To conduct the analysis, all covered attack types are categorized based on the location of the vulnerability (smart contract code / technology level) and the type of suggested mitigations (better coding practices / automated tools / technology changes). This categorization can be seen in the table 4.1 below.

After this, all the findings and results of the categorization are summed up and analysed a bit more to give a big picture of the current state of smart contract security.

Key findings:

  • Almost all common attacks could be avoided or at least severely mitigated by following better coding practices.
    • This indicates how crucial good coding practices and expertise of the coders are when designing and implementing secure smart contracts.
    • Immutability and the open nature of the blockchain make developing secure smart contracts difficult.
  • Many automated tools for security are being developed and put into practice.
    • This indicates movement towards more conventional coding where automated tools like scanners and analysers are used to cover a large set of security issues.
  • Making changes to the underlying blockchain technology is usually not the best way to counter issues, even if it can work in some cases. It is hard to do, can restrict the usability of contracts and requires community coordination.
  • Many attacks combine technological property with a vulnerability in the targeted smart contract’s code.
    • Many challenges and dangers have to be considered when writing secure code. Developers must have a good understanding of blockchain-related threats and technology itself.
    • They must also be aware of conventional threats, given that smart contracts are Turing-complete. (For example, integer overflow and underflow are really common outside the smart contract world).
  • For some issues and exploits that target smart contracts, there is nothing that can be done on smart contract level.
    • For example, block reorganization attacks are done purely on the blockchain-level even though the majority of profits are extracted from smart contracts. If someone alters blockchain history, the smart contract can’t do anything since its state is also reversed.
    • Another good example is web interfaces. Even though they interact with smart contracts, if there is a problem with the web interface itself, the contract can’t do anything. (Interfaces and programs outside the blockchain interacting with smart contracts are outside of scope of this thesis.)

The biggest challenge when making this survey was using open source information as reference material. Many sources needed double-checking and required finding scientific sources as backup.

When it comes to the future of smart contract security, the Proof of Stake -consensus algorithm and changes it brings are one of the most urgent topics. Another interesting topic involving security is MEV extraction, which is closely tied to front-running covered in this thesis.

References

There were many interesting articles that came along when writing this thesis. The Bitcoin whitepaper and Ethereum documentation are recommended for anyone who hasn’t read them already. To truly understand security issues, background knowledge about blockchain technology is an absolute necessity. For Ethereum, their development documentation is an especially great source, although their whitepaper is also interesting read:

Here are links for those:

From the developer’s point of view, ConsenSys hosts a great github page with relevant information on smart contract security for anyone writing Solidity. It doubles as a great summary of smart contract security:

For a more technical database of smart contract vulnerabilities, SWC Registry is a great source:

(Note: These latter two may not be actively maintained)

10 Likes

@ode Thank you for joining us and welcome to the forum!

I wonder if it is under the scope of your research to study the best practices for building secure administrated contracts proposed by another recent summary on the forum?

They’ve suggested three best practices…

  • deferred maintenance
  • board of trustees
  • safe pausing

…so in the case when the access of administrated smart contracts are compromised there is a fallback plan.
In what brackets (better coding practices, automated tools, and technology changes) would you consider these practices to fall into?

6 Likes

@Twan Thanks, happy to be here!

This would indeed fall under the scope of my research, although I didn’t talk much about mitigating damages after an attack or in case of malicious smart contract administrators.

I would rank all these under better coding practices since they are all enforced on the contract level in the code. They are all also essentially design patterns, which help to mitigate a specific problem. In this case, the problem being the owner of a smart contract having too much power.

I would also say these practices follow the principle of preparing for failure, which indicates that “contract code must be able to respond to bugs gracefully due to the lack of patching schemes” and that “the contract must be able to pause to avoid further financial losses”. These are from a great article, “Smart Contract Security: A Software Lifecycle Perspective”, from 2019. Smart Contract Security: A Software Lifecycle Perspective | IEEE Journals & Magazine | IEEE Xplore.

Other similar examples of design patterns I also mentioned in my thesis and that would fall under better coding practices are pull over push -pattern and commit-reveal -scheme. First one means it is better to let users withdraw instead of contracts sending ETH and the latter one is useful in mitigating front-running in contracts that take submissions against rewards.

4 Likes

@ode Thanks for a nice research summary. I have been hoping to see a collated attack/security issues summary on smart contracts just like the one on NFTs by @LTTOguns.

From this research, three methods were listed for solving issues of security on smart contracts. It is important that we also put into perspective the ease, cost, and impacts of these various methods before deciding on the one to deploy for solving particular issues.

Again, most, if not all, smart contracts are audited by auditing companies, like Certik, before being deployed on blockchains. In essence, these auditing companies are supposed to ensure that codes follow due process and that potential harmful bugs are detected.

Sincerely, while reading this summary, I was kind of bewildered. The summary stressed the fact that better coding practices could help smart contracts avoid the various attacks listed in the research summary.

So, I am finding it a bit difficult to reconcile these two ideas : auditing by security companies and better coding practices. Does it mean that auditing companies whose job is to find these bugs and code errors are not efficient? I am trying to wrap my head around why the problem is a persistent one since the infrastructure to handle this issue is in place. I ask this knowing at the back of my mind that these codes are audited before the smart contracts are deployed.

7 Likes

@ode Thanks for providing a very interesting summary of your thesis!

In particular, your analysis of front-running caught my attention. As noted, front-running is a revenue-extraction phenomena in DeFi that originates from traditional finance. And, as you state, it is closely related to MEV. Actually, I would conjecture that most, if not all, MEV trading methods actually originate in traditional finance, e.g. front-running, liquidations, arbitrage etc. which all extract revenue from the regular user.

Now, in traditional finance the broker takes advantage of an informational advantage to perform front-running trades at the market, thus exploiting the soon-to-be price change from the received trade. However, this type of frontrunning was made illegal through regulation. Hence, I am curious as to whether you could imagine “regulation” as a fourth pillar of mitigation strategies besides BCP, T, and TC?

Further, in traditional finance, new methods of frontrunning arose with the rise of electronic trading in the 90s and 2000s: High-Frequency Trading (HFT). These traders attempt to gain informational advantages regarding trades mere microseconds before the broader market and then trade on this knowledge. This advantage can, for instance, be achieved through placing servers close to stock exchanges or purchasing access to brokers’ dark pools. This small time-advantage allows these HFT traders to perform front-running trades and arbitrage. This type of frontrunning is very similar to the type of front-running observed in DeFi, where trading bots gain an informational advantage through observing the mempool and then trade on the speed (or order optimization) advantage they achieve through attached gas fees. In general, it seems that DeFi and several types of attack vectors are mirroring modern traditional finance. Do you think some future types of attacks can be predicted/prevented by means of lessons learned from traditional finance?

4 Likes

I just stumbled on a detailed post made by @lnrdpss on auditing and it provided an answer to my original question here. Sharing it here for anyone who, perhaps, desire some answer too.

4 Likes

@Ulysses Hey and thanks for the comment!

I see you found an answer already, but here are some of my thoughts anyway that I was just about to post :sweat_smile:

These mitigation types listed here are used only for categorization and analysing. “Tools” and “technology changes” are straightforward, but for everything else I had to come up with a common term so “better coding practices” is used for that. “Better coding practices” then includes everything that can be done codewise to mitigate problems, i.e., using design patterns that are proven to be good, following principles to make contracts secure or simply having enough expertise to spot possible bugs and vulnerabilities.

As I see it, security audits are there to enforce exactly that. If some bug or vulnerability went unnoticed when coding, the security audit should spot it. And if it doesn’t, it would indeed mean that the audit was not efficient.

However, I think much also depends on the attack itself. Attacks like re-entrancy or timestamp dependence are easy enough to spot and (probably) not that common anymore, but for attacks like front-running or oracle manipulation it is not that simple. This is because the vulnerability is not in a specific piece of code, but in the design of the system as a whole. Take oracle manipulation, for example. The vulnerability might be in the fact that anyone can update the oracle at any time, but from the audit point of view the contract can still be flawless and working as intended. A situation that could still be avoided by using proper data validation, for example.

In the end, I would say audits heavily overlap with “better coding practices”, but not necessarily all the way. This leads to a situation where good coding practices are needed especially in system design and audits are there to make sure more technical bugs and vulnerabilities do not go unspotted. (Although some audits might spot design flaws also.)

4 Likes

@windr Hey, thanks for kind words and great question! :smile:

I’d say that regulation would fit perfectly as a fourth type of mitigation. Laws are already used everywhere else to prevent malicious acts so why not in crypto. But then we will of course face the ideological debate about crypto regulation and if it should be done at all. Personally I’m currently more on the “code is the law” -side but law things are not really my area of expertise so I can’t pick sides. This thesis was also done from a purely technical point of view so legal things fall out of scope.

What I can say is that in front-running things often fall into the grey area. For example, arbitrage ensures better and more accurate prices for everyone using DeXes, even though it is technically a frontrunning attack. In theory frontrunning is also fair since anyone can do transaction bidding and transaction pool is readable by anyone. However, in practice it is just like in HFT and traditional finance that a small group with best AI bots and/or access to private pools dominate the scene and reap the profits, so I’m not sure how I feel about that. And some frontrunning like stealing submissions or sandwich trading are only bad for common users.

What comes to the future types of attacks, I feel that it is more than likely that we see the same kind of attacks and malicious acts as in traditional finance as we implement things from TradFi on Defi. Hopefully people designing these systems are aware of these issues too and can adjust accordingly. I’m not that familiar with the finance world so can’t really say more than that.

For podcast fans and those interested in frontrunning and MEV extraction, Uncommon Core had a great episode last year where they interviewed an anonymous MEV searcher/extractor. (Other episodes are of course recommended too, really good crypto stuff in general): Interview with a Searcher - with MEV Senpai and Hasu - YouTube

4 Likes

I completely agree on the ambiguity of frontrunning, since, as you mention, arbitrage is a necessity for a well-functioning financial system. Just as in TradFi where arbitrageurs ensure efficient markets at (almost) all times. I suppose my biggest worries are related to the pool of searchers/extracters/MEV-bots who reap the profits at the expense of “regular” network users through e.g. sandwich attacks. Actually, I recently read a funny blog post about these issues (though it is arguable painting a bleaker-than-necessary image of the future). Nevertheless, it will definitely be of importance to solve these issues, and I guess projects such as flashbots might pave a way forward.

4 Likes

Beautiful explanation @ode, I couldn’t have asked for more. The differences are explicit now. Thanks for your time.

1 Like

Thanks for the summary. It was really a great insight into smart security issues and it’s mitigations.
Blockchain technology’s cutting-edge smart contracts have applications in practically every sector.
It is therefore crucial that the implementation of smart contracts is safe against attacks aimed at stealing or interfering with the assets since they deal with and transfer high-value assets.
A smart contract is sophisticated but fragile as the name suggests.
It can be vulnerable to hostile attacks and reentrancy attacks, as well as to coding errors and protocol problems, among other manifestations of its susceptibility.
Similar to how there is no one trustworthy way to guarantee the security of any technological innovation, I believe that there is no one dependable way to
to guarantee the security of smart contracts and mitigate the attacks on smart contracts just as you mentioned in the summary.
It is believed that when a trustworthy blockchain development company creates a smart contract, it is believed to be safe and secured.

We risk getting into a lot of trouble if we deploy smart contracts too rapidly and without the proper security checks and audits carried out.

Hi @ode. Nice summary :+1:.I am happy to learn about attacks on smart contract and how it can be mitigated.
Just wanted to enquire if there could be a detention tool for smart contract vulnerabilities that can help detect reentrancy vulnerability?

Is it worth it to target and attack smart contracts ? Because I feel it’s a waste of time and tools :thinking:

Hi @ode, This is quite an excellent summary. I’d like to make some comments on the attack on Smart Contracts, and I hope it further adds to this body of knowledge.

Numerous attacks on smart contracts, like the ones mentioned in this study, have taken place and cost a lot of money. However, the Parity Wallet hack and the DAO attack received the most attention.
A small group of Ethereum society members launched the DAO in May 2016. Genesis DAO was the name given to the beginning. The DAO was a smart contract that anyone could use to convert DAO tokens into the ether. This method of exchange enabled the collection of roughly $150M, giving the DAO a sizable crowdfund. DAO token holders were allowed to vote on proposals and receive rewards so long as the vote produced a profit. However, the DAO contract had serious flaws that made it possible for attackers to make money.

Users can form decentralized digital agreements using smart contract technologies without the need for a third party. Health, business management, shareholder agreements, and insurance have all been drawn to smart contract technology.
However, as this technology advances, it attracts the attention of potential attackers, resulting in a number of severe exploitations.

Can smart contracts be hacked?

Yes. There are numerous known vulnerabilities that can be exploited by malicious actors to attack the protocol and steal data and funds. As a result, it is critical to ensure the high security of the protocol and smart contracts, adhere to industry best practices, and conduct regular audits.

What tools are available to help me secure smart contracts?

Mythril, Slither, Scribble, Echidna, and Vertigo are some of the most effective tools for ensuring high smart contract security.

What are the best smart contract security practices?

The following are best practices for smart contract security:

Complete a full unit test.
Audit the security of smart contracts.
Ensure the code’s uniqueness.
Use multisig logic to prevent unauthorized access to private keys.
Hire skilled DeFi developers.
Launch a bug bounty to solicit assistance with bugs and errors from your protocol community.
Maintain complete and up-to-date documentation.

How can smart contracts be made more secure?

Hiring reputable auditing firms and conducting at least two smart contract audits is the best way to ensure high security of your protocol. This way, you can check your contracts for bugs and other vulnerabilities and get detailed recommendations on how to fix them.

Furthermore, to improve smart contract security, you should always adhere to best industry practices and employ cutting-edge tools.

Conclusion

Users can form decentralized digital agreements using smart contract technologies without the need for a third party. Health, business management, shareholder agreements, and insurance have all been drawn to smart contract technology. However, as this technology advances, it attracts the attention of potential attackers, resulting in a number of severe exploitations.

3 Likes

Smart contracts are the foundation of DeFi, NFTs, play-to-earn, and other phenomena associated with the internet. Unfortunately, while smart contracts are awesome and store huge amounts of value, they are not as secure as we think. Smart contracts contain bugs and vulnerabilities that attackers exploit to steal funds.

In my humble opinion, smart contract attacks are made for fun or to prove a point - they can hack the protocol. While these attacks are not purely evil, they show the lengths humans would go to satisfy our whims.

In the past, the attacks were spread out and less devastating. However, the attacks have recently been bolder, with hackers making away tens and hundreds of millions of dollars. October alone has been hacker’s most profitable month, with over $700 million in hacks.

How is this possible? What attack vectors are hackers exploiting which give them an unfair advantage?

As a brand new and fast-paced field, answers to these questions are important. And the answer is better coverage and understanding of these vulnerabilities so users and developers can properly mitigate the attacks to prevent more loss of funds.

The causes of previous attacks are the popular vulnerabilities listed below:

  • Re-entrancy: The word “reentrancy” means “entering again (reentering).” The main vulnerability of reentrancy smart contracts is that they receive addresses as function parameters. This is dangerous as another harmful external contract can initiate transactions without us knowing.
  • Timestamp Dependence: This bug happens when the smart contract relies on the value of the blockchain’s timestamp for execution. The problem is that the timestamp is generated by the node(s) executing the code making the feature open for manipulation.
  • Transaction Ordering Dependence: This attack is also called the Front Running attack. It happens when someone else (the attacker) sends a transaction that modifies the price before your transaction is recorded. This action creates a vulnerability because each smart contract relies on the state of storage variables staying at a certain value during transactions.
  • Call to Unknown: Call to unknown vulnerabilities occur when a function that doesn’t exist in the target contract is called. This action is a special function that the hacker can create, giving them some access to transact with the address.

Apart from the vulnerabilities mentioned above - which are the main types - there are about 36 other known vulnerabilities that plague the smart contract ecosystem. Discovering these vulnerabilities and bugs would have been impossible without the available vulnerability detection tools.

For context, vulnerability detection tools are automated tools that crosscheck and analyze smart contracts to identify potential vulnerabilities. In my upcoming discussion post, I listed and explained the available tools under their input and analysis methods. There are two analysis methods - static and dynamic. As the name imply, the static analysis method involves examining the code without executing the program. The dynamic analysis method involves testing and evaluating the code by running it in real time. Furthermore, these analysis and input methods are responsible for how well and fast an analysis tool detects contract vulnerabilities.

In the key finding section, we notice that most if not all smart contract attacks can be mitigated with better coding practices. With this finding, we can infer that the programming language - Solidity - is also responsible for causing bugs.

The programming language is very nascent, notwithstanding the amount of dapps built with it. Everyday, developers are still figuring out different parameters for smart contract applications. While that happens, hackers also keep up with the updates and look for loopholes they can exploit.

In closing my comment, I am particularly interested in how Ethereum’s switch to PoS influences the exploits. Would be glad to learn more in that direction.

2 Likes

Is this because of the Solidity language itself or how people are using it? That seems to be an important distinction.

1 Like

It’s a combination of both.

The Solidity Language is prone to bugs/vulnerabilities because the language executes functions differently/uniquely from the classic programming languages. Because of this uniqueness, there is a disconnect between how programmers interpret/iterate the language and how the language executes instructions.

Additionally, the language is hosted on the blockchain which means you can’t reorder, delay, edit the code once it’s published.

This post was flagged by the community and is temporarily hidden.

This post was flagged by the community and is temporarily hidden.

I enjoyed reading this @ode and I’ll say this,
There are roughly 36 more confirmed vulnerabilities that affect the blockchain based system in addition to the basic vulnerabilities outlined earlier. With little existing vulnerability surveillance technologies, it would not have been feasible to find these problems and vulnerabilities.

To put things in perspective, vulnerability testing techniques are operating speed that merge and examine decentralized applications in order to find any possible failures.
Static and dynamic analysis techniques are both available. The static analysis method, includes looking at the source before running the application. The dynamic analysis process includes running the code instantaneously while analyzing and assessing it.

Additionally, the accuracy and speed with which an analysis software reveals agreement problems depends on these data and tested algorithms.

Smart contract techniques allow us to create blockchain and digital deals without the involvement of a separate entity. Smart contract has attracted users in the fields of healthcare, management of businesses, stakeholder contracts, and wellness.

As the technology develops, though, it catches the attention of possible threats, causing a number of major vulnerabilities.

1 Like