Skip to content

Kode-n-Rolla/web3

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

178 Commits
 
 
 
 

Repository files navigation

Web3 Security Toolkit

There are:

  1. Help
  2. Foundry
  3. Solidity
  4. Solana
  5. Toolkit
  6. Resources
  7. Researching
  8. Assembly and bytecode

Help

  1. Install libraries
  2. Interact with blockchain via CLI
  3. Surya
  4. Wake

         Install libraries

    • Forge-std
    • forge install foundry-rs/forge-std
    • Open Zeppelin
    • forge install OpenZeppelin/openzeppelin-contracts
      forge install OpenZeppelin/openzeppelin-contracts-upgradeable
      forge install transmissions11/solmate

          Interact with blockchain

  • Interact with blockchain storage
  • curl -X POST [RPC_URL] -H "Content-Type: application/json" -d '{"jsonrpc":"2.0", "method":"eth_getStorageAt", "params": ["[CONTRACT_ADDRESS]","[NUM_SLOT-IN-HEX]","latest"],"id":1}'
    Need to change [RPC_UR], [CONTRACT_ADDRESS], [NUM_SLOT-IN-HEX]

      Surya

  • Graph creation
  • surya graph [PATH/CONTRACT_NAME].sol
  • Action to function trace
  • 1. All imports to 1 file (mkdir -p flatten)
    forge flatten src/[CONTRACT_NAME].sol > flat/[CONTRACT_NAME].flatten.sol
    2. ftrace with flatten
    surya ftrace "[CONTRACT_NAME]::[FUNCTION_NAME]" [all|external|internal] flatten/[CONTRACT_NAME].flat.sol

      Wake

  • Fix
  • forge remappings > remappings.txt
    wake up config
    Settings -> Add wake.toml to Wake > Configuration:Toml_path
  • Run
  • wake detect --export json all

Foundry

  1. Cast
  2. Forge
  3. Functions
  4. Tips

      Cast

  • hex to decimal
  • cast --to-dec [hex]
  • hex to string
  • cast --abi-decode "myFunc()(string)" 0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000014416e79206b696e64206f6620636f6f6b69657321000000000000000000000000
    myFunc() is random name. Guess cast just need (unexisted)function in command.
  • keccak256 with string
  • cast keccak "..."
  • Function signature
  • cast sig "func(uint256,address)"
  • ABI encode with args
  • cast calldata "func(...)" arg1 arg2
  • ABI encode without sig, only args
  • cast calldata "func(...)" arg1 arg2
  • Check storage
  • cast storage [CONTRACT_ADDRESS] [NUM_SLOT] --rpc-url [RPC_URL]
  • Bytes32 to string
  • cast parse-bytes32-string [TARGET_BYTES]
  • Bytes4 (signature) to string
  • cast 4byte [sig]

      Forge

  • Test
    1. Test certain function
    2. forge test --match-test testFunctionName -vvv
      -vvv for deep verbose, --mp (match-path) to certain path contract
    3. Gas Report
    4. forge test --gas-report
  • Inspect
    1. To view storage layout
    2. forge inspect <CONTRACT_NAME> storage-layout
    3. To view contract`s methods
    4. forge inspect <CONTRACT_NAME> methods
  • Coverage
    1. Run
    2. forge coverage
    3. Can help with Stack too deep
    4. forge coverage --ir-minimum

      Functions

  • bound()
  • The bound() function is designed to constrain the input values of fuzz tests within a specified range

    Usage:

    _value = bound(_value, 1, type(uint256).max);
    The bound() function takes three uint256 arguments:
    1. x: The input value from the fuzzer.
    2. min: The lower bound (inclusive) of the desired range.
    3. max: The upper bound (inclusive) of the desired range.
  • Another restriction for fuzzing
  • vm.assume(_value > 0);
  • vm.warp() - skip some time
  • vm.warp(block.timestamp + 10 seconds);
  • vm.warp() - skip some blocks
  • vm.roll(block.number + 100);

      Tips

  • Ok starting time, not start from 1 (vm.warp)
  •     modifier startAtPresentDay() {
            vm.warp(1680616584);
            _;
        }
  • Fuzzing and assumption
  • // notSeller will be chosen randomly
    function testInvalidSellerAddress(address notSeller) public {
    	vm.assume(notSeller != seller); // предпологается, что точно не `seller`
    	vm.expectRevert("not the seller");
    	depositContract.sellerWithdraw(notSeller);
    }

Solidity

  • Compare string type
  • keccak256(abi.encodePacked(string1)) == keccak256(abi.encodePacked(string2))
  • Func sig
  • bytes4 selector = bytes4(keccak256("transfer(address,uint256)"));
    bytes4 selector = this.transfer.selector;

Solana

  • Commands
    1. Change to devnet
    2. solana config set --url https://api.devnet.solana.com
    3. Start anchor
    4. anchor init project_name
      cd project_name
      anchor build
      anchor keys sync
    5. Solana test validator running in other terminal
    6. solana-test-validator
    7. Solana logs in another:
    8. solana logs
    9. Test
    10. anchor test --skip-local-validator
    11. Add Lite SVM
    12. cargo add --dev litesvm

Toolkit

  1. VS Codium
  2. Foundry
  3. CLoC
  4. Slither
  5. Aderyn
  6. eth-security-toolbox
  7. upgradehub.xyz for checking smart contracts changes

Resources

  1. Auditors Handbook from Guadrdian Audits Lab
  2. Zokyo Tutorials
  3. workshop-fuzzing (instructions & examples)

Researching

  • Minimal Smart Contract Security Review Onboarding
  • The Rekt Test
    1. Do you have all actors, roles, and privileges documented?
    2. Do you keep documentation of all the external services, contracts, and oracles you rely on?
    3. Do you have a written and tested incident response plan?
    4. Do you document the best ways to attack your system?
    5. Do you perform identity verification and background checks on all employees?
    6. Do you have a team member with security defined in their role?
    7. Do you require hardware security keys for production systems?
    8. Does your key management system require multiple humans and physical steps?
    9. Do you define key invariants for your system and test them on every commit?
    10. Do you use the best automated tools to discover security issues in your code?
    11. Do you undergo external audits and maintain a vulnerability disclosure or bug bounty program?
    12. Have you considered and mitigated avenues for abusing users of your system?
    Audit Scoping Details
    • Public link code repo, if exist
    • How many contracts are in scope?
    • Total SLoC for these contracts?
    • How many external imports are there?
    • How many separate interfaces and struct definitions are there for the contracts within scope?
    • Does most of your code generally use composition or inheritance?
    • How many external calls?
    • What is the overall line coverage percentage provided by your tests?:
    • Is there a need to understand a separate part of the codebase / get context in order to audit this part of the protocol?
    • If so, please describe required context
    • Does it use an oracle?
    • Does the token conform to the ERC20 standard?
    • Do you expect ERC721, ERC777, FEE-ON-TRANSFER, REBASING or any other non-standard ERC will interact with the smart contracts?
    • Are there any novel or unique curve logic or mathematical models?
    • Does it use a timelock function?
    • Is it an NFT?
    • Does it have an AMM?
    • Is it a fork of a popular project?
    • Does it use rollups?
    • Is it multi-chain?
    • Does it use a side-chain?
    • Describe any specific areas you would like addressed. E.g. Please try to break XYZ."
    OWASP Smart Contract Top 10
    1. Access Control Vulnerabilities
    2. Price Oracle Manipulation
    3. Logic Errors
    4. Lack of Input Validation
    5. Reentrancy Attacks
    6. Unchecked External Calls
    7. Flash Loan Attacks
    8. Integer Overflow and Underflow
    9. Insecure Randomness
    10. Denial of Service (DoS) Attacks
    Methodology
    1. Read docs and understand the project
      • Main functionality
      • Roles
      • Invariants
    2. Static Analysis
    3. Dynamic analysis
    4. Steps
      # STRUCTURE: FIRST HOURS OF PROTOCOL RESEARCH
      1. ARCHITECTURE
         - read README and Deployment / addresses
         - find entrypoints (Router / Core / Vault / Manager)
         - draw diagramm
      2. TRUST MODEL
         - who can change and what can be changable (owner, guardian, controller)
         - where is upgrade, pause, withdraw, mint/burn
      3. USER FLOW
         - how regular user interact: deposit → stake → claim
         - which data go to в state
         - where is external call / callback
      4. SECURITY INVARIANTS
         - what have to be true: balance >= shares, owner != zero, etc.
         - what breaks invariants
      5. ATTACK SURFACE
         - external/public funcs without access-control
         - all loops (gas DoS)
         - all places with call.value / transfer / delegatecall / external token
         - where is state depends on external contracts
      6. CHECKLIST (rest)
         - Reentrancy
         - Privilege escalation
         - Math errors (arithmetic, rounding)
         - Oracle manipulation
         - Initialization / upgrade gaps
         - Access Control List
         - Broken Logic
      
      • Pragma version, imports, inheritances
      • State variables (visability)
      • Focus on external and public functions
      • Check-Effects-Interactions pattern
      • S.E.A.R.C.H. (State, External, Access, Reentrancy, Checks, Handling) pattern
    5. Testing (invariant tests -> stateless & stateful fuzzing, check hypotheses)
    6. Reporting

    Assembly and bytecode

    EVM Codes

    Releases

    No releases published

    Packages

     
     
     

    Contributors