Smart Contract Hacking – To Hack or To Protect? - Hacken (2024)

  • Hacken
  • Blog
  • Discover

9 minutes

By Malanii Oleh

While most hacks in Web3 come as rug pulls and access control compromises, smart contract vulnerability exploits account for a regularly significant share of losses. In Q3 2023, Web3 projects lost nearly $100M due to smart contract hacks.

With so much money at stake, it’s at least understandable why smart contract developers go over the dark side and try themselves in hacking. In this article, let’s try to uncover that perspective and discuss how smart contracts can be exploited. Our goal is to give you the information, and it’s you who makes the hacking vs protecting decision.

Keep an eye out throughout this text for the most helpful resources.

Understanding Smart Contracts

Smart contracts are the backbone of decentralized trading, lending, and staking applications. Developed as deterministic programs in a high-level language (Solidity, Rust, etc.), smart contracts are compiled into bytecode for a runtime environment (EVM, WebAssembly, etc.). Once deployed, they operate continuously on the blockchain like Ethereum, Radix, or NEAR.

Because smart contracts are stored on-chain, hackers can examine the public codebase for vulnerabilities, such as reentrancy or missing checks, and then conduct their attacks. For example, the most recent KyberSwap $47M hack had a reentrancy error in the mint function of their new token implementation. Hackers can even combine their exploits with flash loans for maximum damage, as in the case of the SushiSwap DEX hack.

Hence, knowing how smart contracts operate and the potential weak spots of the most common tech stacks is vital for both hacking and protecting the underlying assets.

Smart Contract Hacking Setup

A robust setup is essential for identifying and exploiting vulnerabilities in smart contract development and security testing. Critical components of this setup include development frameworks and runtime environments.

Development Frameworks

  • Hardhat offers a local Ethereum environment for testing, debugging, and deploying contracts. Many believe the Hardhat stack is the most complete framework today, but you can decide.
  • Truffle, renowned for its comprehensive development suite, provides contract testing and migrations functionalities.
  • On the other hand, Foundry is gaining popularity for its fast and flexible testing capabilities.
  • Remix IDE is a powerful, open-source tool that allows developers to write, deploy, and test smart contracts directly in a web browser. It’s handy for quick prototyping and provides an accessible platform for beginners and experts to experiment with smart contract code.

Runtime Environment

Understanding Ethereum Virtual Machine (EVM) or WebAssembley is critical because it will run your smart contracts on the blockchain. Knowledge of EVM’s inner workings aids in comprehending contract behaviors and potential vulnerabilities.

The Hacker’s Perspective: How Hackers Exploit Vulnerabilities

Let’s discuss the most common ways smart contracts are not secure.

Reentrancy

Issue: Functions call external contracts before updating their state.
Scenario: Based on Rari Capital 2022 hack, the attacker exploited a vulnerability in the borrow function, which executed asset transfer before updating the state.
Mitigation: Implement the “Checks-Effects-Interactions” pattern—execute all checks and state updates before external calls, use reentrancy guard, and limit available gas for functions to prevent loop exploits.

Bad Randomness

Issue: Lack of secure, random number generation in Ethereum smart contracts.
Scenario: Attackers manipulate block hashes or timestamps to influence outcomes, like in lotteries.
Mitigation: Avoid reliance on on-chain randomness. Emerging solutions include verifiable delay functions and Randao commit-reveal schemes.

Denial of Service (DoS)

Issue: Contracts performing bulk operations are vulnerable to stalling if a component fails.
Scenario: A failed refund transaction can indefinitely stall the process in an auction contract.
Mitigation: Prefer pull over push mechanisms and efficiently manage loops to handle large data structures.

Forced Ether Reception

Issue: Contracts can unintentionally receive Ether, disrupting their functions.
Scenario: Use of selfdestruct in a contract forcibly sends Ether to another contract.
Mitigation: Design contracts to handle unexpected Ether receipts, avoiding assumptions about contract balances.

Integer Overflow

Issue: Solidity’s integer operations can overflow or underflow, leading to errors.
Scenario: ERC20 tokens without underflow checks can result in attackers gaining excessive tokens.
Mitigation: Use libraries like OpenZeppelin’s SafeMath and validate all arithmetic operations.

Race Condition

Issue: The time gap between transaction creation and acceptance can be exploited.
Scenario: In ERC20 tokens, approve and transferFrom can be manipulated, allowing unintended token transfers.
Mitigation: Implement zero balance approval requirements and design contracts to anticipate and handle front-running scenarios.

See related: Top 6 Smart Contract Vulnerabilities And How to Stop Them

Hands-On Smart Contract Hacking Experience

You won’t be able to hack anything if you don’t know how to create a smart contract in the first place.

Start with setting up a development environment. For example, Remix IDE offers tools for writing, compiling, and deploying smart contracts. The process includes writing the contract code in Solidity, the most popular programming language for smart contracts, and compiling the code to ensure it’s ready for deployment. Next, you should deploy the contract to a test network like Goerli using tools like Metamask to confirm its behavior. Once tested and debugged, which may involve experimenting with various inputs and observing the outcomes to ensure proper functionality, you can go to the mainnent to interact with other contracts. Related resources:

  • How To Create A Smart Contract: A Hacken’s tutorial on creating your first Solidity contract.
  • Crypto Zombies: A foundational course in Solidity, offering insights into the language’s nuances and quirks. Ideal for beginners to grasp the basic concepts of smart contract programming.

Deploying your first smart contract is only the beginning, and you really have to master a smart contract programming language and learn a lot about the DeFi business even to spot unprotected liquidity. Here are the best resources to learn:

Standard and Testing:

Assuming you excel in these steps, it’s time to hone your offensive skills. Participate in wargames and playgrounds. Here are a few resources that are definitely worth your time:

  • Capture the Ether: A dozen of challenges to get into the basics of doing miscellaneous things.
  • Damn Vulnerable DeFi: A series of 15 hacking offensive security challenges for Ethereum smart contracts covering all major aspects of decentralized applications: flash loans, price oracles, governance mechanisms, NFTs, decentralized exchanges, lending pools, smart contract wallets, and timelocks. One of the best wargames out there.
  • Ethernaut: 29 fun and challenging tasks for you to hack the smart contract, allowing for hands-on practice in identifying and exploiting smart contract weaknesses.

Smart Contract Security – Turning The Tables

Even ignoring the ethical and legal considerations, smart contract hacking is an extremely challenging and risky endeavor. A successful hack requires a perfect alignment of factors – finding unaudited and/or vulnerable contracts, being the first to discover and act, having the right skills for an attack, and managing to evade detection while vanishing with the stolen assets. As a result, the path of a smart contract hacker will be largely unrewarding for most people.

Yet, software engineers passionate about discovering vulnerabilities can engage in a more rewarding path. Independent ethical hackers, auditors, and bug hunters have all discovered that Web3 offers a different way of challenging your snooper character.

See related: How To Become A Smart Contract Auditor

Learning from Smart Contract Hacks

Every smart contract hack always offers valuable learning opportunities. Let’s take Onyx Protocol exploit, for example. Onyx, a Compound Finance fork, lost $2.1 million due to a rounding error when creating new liquidity markets. But there’s a catch. The exact same vulnerability had already hit Hundred Finance and Midas earlier this year. It wasn’t the first time that projects didn’t implement simple workarounds to high-profile vulnerabilities.

So the implication is clear: read about hacks and learn from them. Resources like rekt and Hacken Insights may help.

Tools for Security Analysis

A multi-stage approach is essential for thorough vulnerability discovery. Here are some key tips and smart contract audit tools used in this process:

1. Preliminary Assessment:

  • Tool Integration: Begin with tools like Slither for Solidity contracts, which analyze source code for vulnerabilities, and Clippy for Rust contracts, designed to catch common mistakes.
  • Initial Analysis: Use tools like Mythril and Solgraph to identify potential vulnerabilities and visualize function control flows in Solidity contracts. For Rust, Cargo-udeps and Cargo-audit can help in detecting unused dependencies and auditing crates for security vulnerabilities.
  • Functional Testing: Incorporate Echidna for fuzzing and property-based testing of Solidity contracts, and Cargo-geiger to detect the usage of unsafe Rust code.

2. In-Depth Review:

  • Line-by-Line Analysis: Conduct a thorough review of the code. This includes using tools like Mythx for Solidity, which combines static and dynamic analysis, to detect a wide range of vulnerabilities.
  • Parameter Checking: Apply over 50 language-specific parameters for EVM (Solidity, Vyper, Yul) and Rust-based contracts (Solana, Near, CosmWasm) to ensure comprehensive coverage.
  • Testing Gaps: Assess test coverage rigorously. If gaps are found, develop and implement additional test cases to cover both positive and negative scenarios.

3. Verification:

Reference authoritative resources to verify found vulnerabilities in Solidity and other programming languages:

See related: Smart Contract Audit Process Followed By Top Auditors

Best Practices for Secure Smart Contract Development

Secure smart contract development rests on several key pillars, each contributing to a robust defense against potential vulnerabilities:

  1. Defensive Programming: This strategy proactively checks for and limits access in smart contracts to avert financial losses.
  1. Principle of Least Privilege: This principle limits system access to only what’s necessary for each task, preventing unauthorized actions through access control and role-based authorizations.
  1. Proactive Checks: These checks validate inputs and outputs, preventing erratic contract behavior and ranging from basic balance validations to intricate business logic constraints.
  1. Utilization of Well-Known Libraries: Using proven libraries like OpenZeppelin, PRBMath, and Gnosis Safe enhances smart contract security and functionality.
  1. Purposeful Delays: Deliberate action delays in contracts, especially in DeFi, offer a time-based buffer against threats and allow community response.
  1. Concrete Types Usage: Using the most secure default types in smart contracts ensures type safety, efficiency, and intended functionality.

Community Engagement & Knowledge Sharing

Stay updated with blockchain language and network advancements, actively engage in open-source communities, and share knowledge for professional growth in this dynamic field.

Summary

The challenges and risks associated with hacking, coupled with legal and ethical considerations, make it a largely unrewarding option for most engineers. Instead, aspiring ethical hackers can find a rewarding career in safeguarding blockchain technology. Engaging in security analysis, learning from past vulnerabilities, and joining communities like Hackenproof are ways to contribute positively to the Web3 ecosystem. Choosing security over hacking offers a fulfilling career and is crucial in building a safer digital blockchain world.

Follow @hackenclub on 𝕏 (Twitter)

Subscribe
to our newsletter

Be the first to receive our latest company updates, Web3 security insights, and exclusive content curated for the blockchain enthusiast.в

Smart Contract Hacking – To Hack or To Protect? - Hacken (1)

Table of contents

  • →Understanding Smart Contracts
  • →Smart Contract Hacking Setup
  • →The Hacker’s Perspective: How Hackers Exploit Vulnerabilities
  • →Smart Contract Security – Turning The Tables

Tell us about your project

Follow Us

Read next:

More related
  • What is DePIN? Exploring Decentralized Physical Infrastructure Networks

    7 min read

    Discover

  • 10 min read

    Discover

  • WebAssembly (WASM) Smart Contracts: Their Role In Future Blockchain Ecosystems

    8 min read

    Discover

More related →

Trusted Web3 Security Partner

Smart Contract Hacking – To Hack or To Protect? - Hacken (2024)

FAQs

Can a smart contract be hacked? ›

Because smart contracts are stored on-chain, hackers can examine the public codebase for vulnerabilities, such as reentrancy or missing checks, and then conduct their attacks.

What are the different types of attacks on smart contracts? ›

Index
CategoryDescription
Denial of ServiceDenial of service attacks through unexpected reverts and the block gas limit.
GriefingAttacks relating to bad faith players around a smart contract system.
Force FeedingForcing Ether to be sent to smart contracts to manipulate balance checks.
7 more rows

What are the vulnerabilities in smart contracts? ›

What are the most common smart contract security vulnerabilities? The most common smart contract weaknesses include unsafe type inference, timestamp dependency, reentrancy, implicit visibility level, gas limit and loops, and much more.

What is smart contract exploit? ›

This is when an attacker is able to repeatedly call a function within a smart contract, exploiting the fact that the state of the contract hasn't been updated as expected. This could lead to funds or other resources being drained from the contract.

Can smart contracts be trusted? ›

Unfortunately, there is no way to be 100% sure of a smart contract's legitimacy, short of spending many hours familiarising yourself with Solidity and related coding languages so that you can audit them yourself. So it bears repeating: always act with caution on web3.

How risky are smart contracts? ›

Security Flaws and Loopholes

Security flaws, such as reentrancy attacks or overflow/underflow bugs, pose serious threats to smart contracts. These vulnerabilities can be exploited by attackers, leading to unauthorized access or manipulation of contract functions.

What is an example of a malicious smart contract? ›

Malicious smart contracts come in many variations, so I'll give a couple of examples: Approval contracts that give a hacker access to a certain token you own. Liquidity pool smart contracts that never actually let you withdraw your money. Deposit contracts that sends your crypto over to a hacker's wallet.

What is smart contract security? ›

Smart contract security refers to the security principles and practices used by developers, users, and exchanges when creating or interacting with smart contracts.

What is the most common type of security attacks? ›

Common types of cyberattacks
  1. Malware. Cyberattackers use harmful software such as spyware, viruses, ransomware, and worms known as malware to access your system's data. ...
  2. Phishing. ...
  3. Spoofing. ...
  4. Backdoor Trojan. ...
  5. Ransomware. ...
  6. Password attacks. ...
  7. Internet of Things attack. ...
  8. Cryptojacking.
Jan 24, 2024

Can a smart contract be breached? ›

So, to achieve rectification, a court may order a party to enter into an amended contract onto the ledger. From a legal perspective, if a smart contract is solely in code, it could be particularly difficult to establish a breach of contract, due to the interpretive constraints outlined above.

What are the two drawbacks of smart contracts? ›

Disadvantages of Smart Contracts :-

The consumers are quite suspicious in nature because most of the people are not well acquainted with the Smart Contract Technology. It is resistant to the modification of the data. For example – If you want to buy a new car, then data already stored can't be changed so easily.

How can I make my smart contract more secure? ›

Aim for low-code complexity: Think of your smart contract as a well-maintained apparatus. Each additional line of code increases the attack surface, making audits more like disassembling a sophisticated clockwork mechanism. Give priority to well-written, succinct, and documented code.

Can a smart contract steal money? ›

Smart contract scams are a particularly complex type of cryptocurrency scam, and it can be very difficult to get your coins back once they have been stolen. In some cases, it may be possible to contact the developers of the smart contract in question and request that they return the funds.

Can you destroy a smart contract? ›

The destroy function can only be called by an owner and will only succeed if all owners have confirmed their agreement. If these conditions are met, the selfdestruct function is called, and all Ether stored in the contract is sent to the receiver address.

What is a real example of smart contract? ›

Examples of smart contract applications include financial purposes like trading, investing, lending, and borrowing. They can be used for applications in gaming, healthcare, and real estate; and they can even be used to configure entire corporate structures.

Can anyone access a smart contract? ›

Security – The functions defined in a smart contract should be called only by the authorised participants. Due to the transparency and equal rights of public blockchains, all the smart contracts are also publicly available to everyone connecting to the Internet.

Can smart devices be hacked? ›

Do you spot unfamiliar or unauthorized devices? If so, it's a clear sign that someone may have breached your network. Hackers often do this to exploit vulnerabilities in smart devices or launch attacks. Secure your network with strong passwords and consider implementing network segmentation for added protection.

How do I secure my smart contract? ›

Follow secure coding practices

Developers should use secure coding methods when developing smart contracts. These include avoiding outdated or untested functions and libraries, validating input, and implementing input validation checks to prevent unexpected behavior.

Top Articles
Why little details like the ‘10 and five’ rule are a big deal in hotels
How do I start a blog with no money? (REAL tips that work)
Cranes For Sale in United States| IronPlanet
Danatar Gym
Botanist Workbench Rs3
Naturalization Ceremonies Can I Pick Up Citizenship Certificate Before Ceremony
THE 10 BEST River Retreats for 2024/2025
Devourer Of Gods Resprite
My Vidant Chart
Tugboat Information
Derpixon Kemono
Pwc Transparency Report
Missing 2023 Showtimes Near Landmark Cinemas Peoria
Breakroom Bw
Curtains - Cheap Ready Made Curtains - Deconovo UK
No Hard Feelings Showtimes Near Cinemark At Harlingen
Arboristsite Forum Chainsaw
9044906381
Icommerce Agent
Bing Chilling Words Romanized
Jeff Now Phone Number
Reptile Expo Fayetteville Nc
Homeaccess.stopandshop
Craigslist Lewes Delaware
Canvasdiscount Black Friday Deals
Gas Buddy Prices Near Me Zip Code
Www Va Lottery Com Result
Craigslist Roseburg Oregon Free Stuff
Gma' Deals & Steals Today
100 Gorgeous Princess Names: With Inspiring Meanings
Rs3 Bring Leela To The Tomb
Nacogdoches, Texas: Step Back in Time in Texas' Oldest Town
Adecco Check Stubs
Newcardapply Com 21961
2012 Street Glide Blue Book Value
W B Crumel Funeral Home Obituaries
R&J Travel And Tours Calendar
Dr Adj Redist Cadv Prin Amex Charge
Busch Gardens Wait Times
Kerry Cassidy Portal
Craigslist Houses For Rent Little River Sc
Gonzalo Lira Net Worth
A Man Called Otto Showtimes Near Cinemark Greeley Mall
Wood River, IL Homes for Sale & Real Estate
Doelpuntenteller Robert Mühren eindigt op 38: "Afsluiten in stijl toch?"
Used Auto Parts in Houston 77013 | LKQ Pick Your Part
Poster & 1600 Autocollants créatifs | Activité facile et ludique | Poppik Stickers
How To Win The Race In Sneaky Sasquatch
Divisadero Florist
Overstock Comenity Login
Predator revo radial owners
Latest Posts
Article information

Author: Nathanial Hackett

Last Updated:

Views: 6484

Rating: 4.1 / 5 (72 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Nathanial Hackett

Birthday: 1997-10-09

Address: Apt. 935 264 Abshire Canyon, South Nerissachester, NM 01800

Phone: +9752624861224

Job: Forward Technology Assistant

Hobby: Listening to music, Shopping, Vacation, Baton twirling, Flower arranging, Blacksmithing, Do it yourself

Introduction: My name is Nathanial Hackett, I am a lovely, curious, smiling, lively, thoughtful, courageous, lively person who loves writing and wants to share my knowledge and understanding with you.