Giter VIP home page Giter VIP logo

coinspect / learn-evm-attacks Goto Github PK

View Code? Open in Web Editor NEW
1.6K 41.0 205.0 5.15 MB

Learn and contribute by exploring blockchain attacks in detail. Maintained by Coinspect smart contract audit team, renowned for their top-tier smart contract audit services.

Home Page: https://www.coinspect.com/services/smart-contract-audit/

License: MIT License

Solidity 98.11% Shell 0.06% D2 1.83%
audit ethereum ethereum-security evm security smart-contracts solidity-security

learn-evm-attacks's Introduction

Learn EVM Attacks

A collection of Foundry tests reproducing exploits, bug bounty reports, and theoretical vulnerabilities on EVM chains. Diagrams and context links accompany each attack reproduction to make it more helpful as a reference or study material for anyone trying to learn more about vulnerabilities in smart contract systems.

Want to take a quick look? Just go to a vulnerability folder (say, MBCToken). Read the README or jump ahead to running the reproduction in your computer! You only need Foundry installed.

$ git clone https://github.com/coinspect/learn-evm-attacks
$ forge install
$ forge test --match-contract Exploit_MBCToken -vvv

Index

We now have 40 reproduced exploits. Of those 40, we have chosen a few in case you want to start studying up with some of the most interesting ones.

  • Tornado Cash Governance Takeover is an excellent way to show the dangers of DELEGATECALL and the perils of governance systems.
  • Furucombo another excellent way to show the dangers of DELEGATECALL.
  • MBC Token is a primer on how sandwich attacks can be made with an interesting backstory on suspicious tokenomics.
  • Uranium is a great excuse to study up on the actual code that guards the famouse AMM constant product x*y=k.

To run an specific exploit, you can just use:

forge test --match-contract Exploit_MBCToken -vvv

Vary the amount of verbosity (-v, -vv...) according to the data you want. -vvvv includes traces!

The full list is below:

Access Control

Bad Data Validation

Business Logic

Reentrancy

Bridges

Contributing

To contribute, create a new file inside the most appropriate category. Use the template.txt file in the test folder including the information related to the attack.

Utils that perform flashloans and swaps are provided in test/utils to ease the job of reproducing future attacks. Also, modules that provide enhanced features to Foundry are included in the test/modules folder.

The tests should pass if the attacker succeeded, for examples: your requires should show that the attacker has more balance after the attack than before.

Past work and further study

  • DefiHackLabs has a similar repository with more exploits and more focus on the test reproductions alone, with no context or further explanations. It is nevertheless great if you only care about the attack reproductions! Go check it out.

Troubleshooting

The main reason why tests fail is due to failures on the RPC providers we have set up as defaults. Please either:

  • Try again
  • Change the corresponding provider in the foundry.toml

If a reproduction is still failing (ie: it reverts), try to:

  • Clean Forge's cache: forge cache clean
  • Update Foundry: foundryup

learn-evm-attacks's People

Contributors

benbktech avatar darienmh avatar donequis avatar joaquinlpereyra avatar juli avatar manylov avatar matthiasegli avatar nine-december avatar rodrigoherrerai avatar tiassumpcao avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

learn-evm-attacks's Issues

Unable to execute `Exploit_MBCToken` test

After executing:

$ git clone https://github.com/coinspect/learn-evm-attacks
$ forge install
$ forge test --match-contract Exploit_MBCToken -vvv

I recieved a lot of errors and was unable to complie the contract:

...
Discovered incompatible solidity versions in following
: test\Reentrancy\RevestFinance\RevestFinance.attack.sol (^0.8.17) imports:
    lib/forge-std/src\Test.sol (>=0.6.2 <0.9.0)
    test\TestHarness.sol (^0.8.17)
    test\interfaces\IERC20.sol (^0.8.0)
...

I've added solc="0.8.17" to foundry.toml, contracts compiled, and I received new error (the same as other 2 people):

forge test --match-contract Exploit_MBCToken
[⠢] Compiling...
No files changed, compilation skipped
The application panicked (crashed).
Message:  Failed to get account for 0x55d3…7955
(code: -32002, message: the resource eth_getCode is not available., data: None)
Location: evm/src/executor/fork/backend.rs:271

This is a bug. Consider reporting it at https://github.com/foundry-rs/foundry

Backtrace omitted. Run with RUST_BACKTRACE=1 environment variable to display it.
Run with RUST_BACKTRACE=full to include source snippets.
Aborted

This looks loke the problem with the rpc, could you please check that?

Feat: add DEX Pools and Pairs creation utils

Feature: Pool and Pair creation under utils folder

Overview: This utility has to allow users to quickly instantiate and create DEX pairs to enable broader test scenarios that depend on custom token pairs.

Read-only reentrency in the wild

There is mentioning that the read-only reentrancy is theoretical and there aren't cases out there where this was exploited. This is not true, as we published this class of vulnerability based on an actual bug with 100m+ at risk back when it was active. The technical details are here: https://chainsecurity.com/curve-lp-oracle-manipulation-post-mortem/ and a description of the vulnerable projects here: https://chainsecurity.com/heartbreaks-curve-lp-oracles/ (including how it was fixed by e.g. MakerDAO)

Till today, incorrect use of the stETH/ETH pool on Curve will allow attackers to exploit projects with this read-only reentrancy.

Feat: add Superfluid attack

On Feb 8, 2022 an attacker stole ~6.2MM in various tokens from Superfluid.

Attack Overview
Total Lost: ~6.2MM

Key Info Sources
Writeup: https://rekt.news/superfluid-rekt/

Principle: Access Control / Input Validation - Calldata crafting to impersonate an access controlled account

Error when running `forge test`

When I am running this command
forge test --match-contract Exploit_MBCToken -vvv

I am getting this error:
2023-03-24T08:42:22.475520Z ERROR sharedbackend: Failed to send/recv basicerr=GetAccount(0x55d398326f99059ff775485246999027b3197955, (code: -32002, message: the resource eth_getBalance is not available., data: None)) address=0x55d398326f99059ff775485246999027b3197955 2023-03-24T08:42:22.601997Z ERROR sharedbackend: Failed to send/recvbasicerr=GetAccount(0x9f8ccdafcc39f3c7d6ebf637c9151673cbc36b88, (code: -32002, message: the resource eth_getTransactionCount is not available., data: None)) address=0x9f8ccdafcc39f3c7d6ebf637c9151673cbc36b88 The application panicked (crashed). Message: calledOption::unwrap()on aNone value

Does anybody faced this issue before?

Reverse engineer attacker or vulnerable logic

Aim

There should be no need to use prank(attacker) in most scenarios, and there should be no need to hardcode payloads. We should be able to reproduce everything in the actual test.

Status

Bridges

  • Nomad Bridge: getPayload reproduces payload for any address
  • Roning Bridge: uses prank but OK, no interesting on-chain interactions, meat is offchain
  • Polynetwork: uses hardcoded bytecode from traces, no prank but attacker address needs to be hardcoded due to bytecode
  • Arbitrum Inbox: report, so no actual attacker address, attack is fully reproduced from scratch

Data Validation

  • Superfluid: implemented encode functions, nothing hardcoded
  • Bad Guys NFT: hardcoded attacker and merkle proof, needs logic to build merkle proof for any addr and set merkle root
  • Bond Olympus: OK, no hardcoding
  • Multichain Permit: OK, no hardcoding

Access Control

  • ⚠️ Sandbox: attacker/victim hardcoded, should work with any pair as long as victim has an NFT, could give it to them so test always works
  • ✅ ️ DAO Maker: OK, no hardcoding
  • 😞 Rikkeii: OK, but code could use some love so attack is more clear.
  • MBC Token: OK, address(this) is the attacker contract, could change it to anything
  • Temple DAO: OK, address(this) is the attacker contract, could change it to anything
  • Punk Protocol: OK, address(this) is the attacker contract, could change it to anything

Reentrancy

  • ✅ ️ Paraluni: OK, no hardcoding
  • ⚠️DFXFinance: Strong dependance on balance on an attacker address that is not in the test.
  • 😞 ️️ Fei Protocol: Needs love and work so assertGe asserts more things
  • ✅ ️️ Cream Finance: OK
  • ✅ ️️ Revest Finance: OK, uses attacker address but no prank, only to transfer loot
  • 😞 ️️ Hundred Finance: No hardcoding, but code is hard to understand. Missing asserts as token interactions are not clear.
  • 😞 Read only reeentrancy: totally theoretical so no hardcoding needed, but is missing asserts

Add the vulnerable code to the repository

When possible (ie: when the vulnerable code is verified, or we know its github, or we somehow have access to its sourcecode...) we should strive to add it to the repository, possibly to the test itself.

By itself, this would be a win, as it is easier to read: instead of going to etherscan and finding my way through their serviceable but not great code viewer, I can just inspect it here right next to the attack.

And with a bit of tinkering I think this would allow us to go even further and use Foundry's step-by-step debugger on attacks, which would be amazing to understand all the details of each exploit.

Hardhat is not working

What I did

npx hardhat test

What I expected: tests to run
What happened:

Error HH8: There's one or more errors in your config file:

  * Invalid account: #0 for network: mainnet - private key too short, expected 32 bytes
  * Invalid account: #0 for network: bsc - private key too short, expected 32 bytes
  * Invalid account: #0 for network: fantom - private key too short, expected 32 bytes
  * Invalid account: #0 for network: gnosis - private key too short, expected 32 bytes
  * Invalid account: #0 for network: polygon - private key too short, expected 32 bytes
  * 

To learn more about Hardhat's configuration, please go to https://hardhat.org/config/

For more info go to https://hardhat.org/HH8 or run Hardhat with --show-stack-traces```

I tried to fix it by removing the accounts in the configuration, but then test simply don't run.

$ npx hardhat test                                             
No need to generate any newer typings.


  0 passing (0ms)

I think we should deprecate hardhat support for now and focus on making it work nicely with Foundry, then we can add Hardhat support. It would also easy documentation.

Reimplement exploits without using cheat.startPrank(attacker)

If adding attacker to an allowlist is necessary then is better to spoof the owner's address and add our random attacker address to the allow list. This way the exploit code will be more real and more valuable for future research projects based on this repository.

Failing tests

Following tests are failing. If they are not needed, delete them

Encountered 1 failing test in test/Bad_Data_Validation/Superfluid/Superfluid.attack.sol:Exploit_Superfluid
[FAIL. Reason: Setup failed: Failed to get account for 0x1804c8ab1f12e6bbf3894d4083f33e07309d1f38: 0x1804c8ab1f12e6bbf3894d4083f33e07309d1f38] setUp() (gas: 0)
Encountered 1 failing test in test/Bad_Data_Validation/TransitSwap/TransitSwap.attack.sol:Exploit_TransitSwap
[FAIL. Reason: XswapApprove:Access restricted] test_attack_reproduced() (gas: 21784)
Encountered 1 failing test in test/Bridges/Wintermute/Wintermute.attack.sol:Exploit_Wintermute
[FAIL. Reason: EvmError: Revert] test_attack() (gas: 48996)
Encountered 1 failing test in test/Business_Logic/Beanstalk/Beanstalk.attack.sol:Exploit_Beanstalk
[FAIL. Reason: EvmError: Revert] test_attack() (gas: 5180199)

This passes, but throws errors

Running 1 test for test/Reentrancy/ReadOnlyReentrancy/ReadOnlyReentrancy.attack.sol:Exploit_ReadOnly
[PASS] test_attack() (gas: 423818)
Test result: ok. 1 passed; 0 failed; finished in 15.17s
2022-12-07T15:55:35.198195Z ERROR sharedbackend: Failed to send/recv `basic` err=GetAccount(0x1804c8ab1f12e6bbf3894d4083f33e07309d1f38,
(code: -32000, message: missing trie node eed22da7bf5ca4462adb3a5f34fb65fe538fd808b89f05187c540913ca9d130f (path ), data: None)) address=0x1804c8ab1f12e6bbf3894d4083f33e07309d1f38
2022-12-07T15:55:35.198363Z ERROR forge::runner: setUp failed reason="Failed to get account for 0x1804c8ab1f12e6bbf3894d4083f33e07309d1f38: 0x1804c8ab1f12e6bbf3894d4083f33e07309d1f38" contract=0x7fa9385be102ac3eac297483dd6233d62b3e1496

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.