A Solidity static analyzer to identify contract vulnerabilities and gas efficiencies.

Related tags

Cryptography solstat
Overview

solstat

A Solidity static analyzer to identify contract vulnerabilities and gas efficiencies.

.------. .------. .------. .------. .------. .------. .------.
|S.--. | |O.--. | |L.--. | |S.--. | |T.--. | |A.--. | |T.--. |
| :/\: | | :/\: | | :/\: | | :/\: | | :/\: | | (\/) | | :/\: |
| :\/: | | :\/: | | (__) | | :\/: | | (__) | | :\/: | | (__) |
| '--'S| | '--'O| | '--'L| | '--'S| | '--'T| | '--'A| | '--'T|
`------' `------' `------' `------' `------' `------' `------'

Table of Contents

 

Installation

First, make sure that you have Rust installed. Then you can choose either of the installation methods by entering the corresponding command in your terminal below.

 

Install from crates.io

cargo install solstat

 

Install from source

git clone https://github.com/0xKitsune/solstat &&
cd solstat &&
cargo install --path .

 

Usage

Now that you have solstat involved, you can use the solstat command from anywhere in your terminal. By default, solstat looks for a ./contracts directory and analyzes every file within the folder. If you would like to specify the directory solstat should use, you can pass the --path flag (ex. solstat --path <path_to_dir>).

In the default configuration, solstat runs analysis for every currently included Optimization, Vulnerability and QA, however if you would like to run analysis for select patterns, you can create a .toml file for your custom configuration. Check out the default solstat.toml configuration for reference. After creating a custom .toml file, make sure to pass the --toml flag when running solstat (ex. solstat --toml <path_to_toml_file>).

Once solstat runs its analysis, a report will be generated and output as solstat_report.md.

At any point you can use solstat --help to see a list of all commands and options.

Usage: solstat [OPTIONS]

Options:
  -p, --path <PATH>  Path to the directory containing the files solstat will analyze. The default directory is `./contracts`
  -t, --toml <TOML>  Path to the toml file containing the solstat configuration when not using the default settings.
  -h, --help         Print help information

 

Contributing

First off, thanks for taking the time to contribute! Contributions are welcomed and greatly appreciated.

If you are interested in contributing, please check out Contributing.md.

Comments
  • 📝Cleanup documentation

    📝Cleanup documentation

    First of all, my bad, I should have created an issue first. Nonetheless, feel free to close this PR.

    TODO:

    • fix readme links to work with 0xKitsune repo (only a few)
    opened by 0xClandestine 5
  • feat: --match-file-name command

    feat: --match-file-name command

    Introduces --match-file-name command which allows users to generate a report for a specific contract within path.

    Usage

    solstat --match-file-name "Contract.sol"
    
    opened by 0xClandestine 4
  • Error with folders containing folders

    Error with folders containing folders

    reproduce error:

    1. forge init a blank repo

    2. cd repo ; solstat -p src ... should work

    3. create random folder in src ; solstat -p src ... should not work

    opened by 0xClandestine 4
  • odd error, cannot run

    odd error, cannot run

    Command:

    solstat --path ./src
    

    Error:

    thread 'main' panicked at 'Unable to read overview.md: Os { code: 2, kind: NotFound, message: "No such file or directory" }', /home/dev/.cargo/registry/src/github.com-1ecc6299db9ec823/solstat-0.1.0/src/report/optimization_report.rs:16:14
    note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
    
    opened by 0xClandestine 3
  • feat: add unprotected selfdestruct vulnerability

    feat: add unprotected selfdestruct vulnerability

    Closes #62


    Hi! This is my first contribution to Open Source ever 😊

    Here's the basic gist of the vulnerability implementation:

    Iterate over all function definitions:

    • Skip constructors and internal or private functions (as they are not vulnerable)
    • Analyze the body of the remaining functions:
      • check if they contain any selfdestruct calls
      • if they do, check if the function is protected (with modifiers or conditions)

    For the last step, I am checking the following criteria to decide if a function is protected or not:

    • If it contains a modifier that contains "only" in its name, the function is considered protected
    • If its body contains any function calls that take msg.sender as argument, the function is considered protected
    • If its body contains any function calls that evaluate an equality or inequality expression on msg.sender, the function is considered protected.

    This check is not exhaustive. For instance, it doesn't check if the modifier applied is implemented correctly. I made sure to specify this in a comment at line 54 of the vulnerability file.

    I had to implement a few helper functions inside the vulnerability file, because indentation was getting too crazy and I believe it is more readable like this. Please do let me know if you wish to remove them and keep everything in the top-level vulnerability function instead.

    At lines 173-181 and 187-194 in the vulnerability file, there is some repeated code. I am aware of this fact, and were considering adding another helper function to alleviate it, but I decided not to in order to keep the helpers more specialized and clear in their functionality.

    Please let me know if I missed anything!

    opened by nicolas-racchi 2
  • Styling: Fix indentation of generated report section for unsafe ERC20 operation

    Styling: Fix indentation of generated report section for unsafe ERC20 operation

    Currently, the unsafe ERC20 operation report section is generated with an extra indent from the rest of the report so that it looks like this:

    # Gas Optimizations - (Total Vulnerabilities 2)
    
    The following sections detail the high, medium and low severity vulnerabilities found throughout the codebase.
    
    <br>
    
    ## Low Risk
    
            ERC20 operations can be unsafe due to different implementations and vulnerabilities in the standard. To account for this, either use OpenZeppelin's SafeERC20 library or wrap each operation in a require statement.
            Additionally, ERC20's approve functions have a known race-condition vulnerability. To account for this, use OpenZeppelin's SafeERC20 library's `safeIncrease` or `safeDecrease` Allowance functions.
            
            #### Unsafe Transfer
            ```js
            IERC20(token).transfer(msg.sender, amount);
            ```
            #### OpenZeppelin SafeTransfer
            ```js        
            import {SafeERC20} from "openzeppelin/token/utils/SafeERC20.sol";
            //--snip--
            
            IERC20(token).safeTransfer(msg.sender, address(this), amount);
            ```
    
            #### Safe Transfer with require statement.
            ```js
            bool success = IERC20(token).transfer(msg.sender, amount);
            require(success, "ERC20 transfer failed");
            ```
    
            #### Unsafe TransferFrom
            ```js
            IERC20(token).transferFrom(msg.sender, address(this), amount);
            ```
            #### OpenZeppelin SafeTransferFrom
            ```js        
            import {SafeERC20} from "openzeppelin/token/utils/SafeERC20.sol";
            //--snip--
            
            IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
            ```
    
            #### Safe TransferFrom with require statement.
            ```js
            bool success = IERC20(token).transferFrom(msg.sender, address(this), amount);
            require(success, "ERC20 transfer failed");
            ```
        
        
    ### Lines
    - Contract.sol:438
    - Contract.sol:207
    

    When it seems it should look more like this:

    # Gas Optimizations - (Total Vulnerabilities 2)
    
    The following sections detail the high, medium and low severity vulnerabilities found throughout the codebase.
    
    <br>
    
    ## Low Risk
    
    ERC20 operations can be unsafe due to different implementations and vulnerabilities in the standard. To account for this, either use OpenZeppelin's SafeERC20 library or wrap each operation in a require statement.
    Additionally, ERC20's approve functions have a known race-condition vulnerability. To account for this, use OpenZeppelin's SafeERC20 library's `safeIncrease` or `safeDecrease` Allowance functions.
    
    #### Unsafe Transfer
    ```js
    IERC20(token).transfer(msg.sender, amount);
    ```
    #### OpenZeppelin SafeTransfer
    ```js        
    import {SafeERC20} from "openzeppelin/token/utils/SafeERC20.sol";
    //--snip--
    
    IERC20(token).safeTransfer(msg.sender, address(this), amount);
    ```
    
    #### Safe Transfer with require statement.
    ```js
    bool success = IERC20(token).transfer(msg.sender, amount);
    require(success, "ERC20 transfer failed");
    ```
    
    #### Unsafe TransferFrom
    ```js
    IERC20(token).transferFrom(msg.sender, address(this), amount);
    ```
    #### OpenZeppelin SafeTransferFrom
    ```js        
    import {SafeERC20} from "openzeppelin/token/utils/SafeERC20.sol";
    //--snip--
    
    IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
    ```
    
    #### Safe TransferFrom with require statement.
    ```js
    bool success = IERC20(token).transferFrom(msg.sender, address(this), amount);
    require(success, "ERC20 transfer failed");
    ```
        
        
    ### Lines
    - Contract.sol:438
    - Contract.sol:207
    

    Was this intentional?

    opened by 0xble 2
  • Panic on immutable variables

    Panic on immutable variables

    this line panics https://github.com/0xKitsune/solstat/blob/main/src/analyzer/optimizations/immutable_variables.rs#L218

    git clone https://github.com/Rari-Capital/vaults
    cd vaults
    solstate --path ./src
    
    opened by gakonst 2
  • chore: update cargo lock

    chore: update cargo lock

    Solstat has been bumped to version 0.5.0 in the cargo.toml. Shouldn't the cargo.lock get updated as well?

    Not 100% sure on this one, so please correct me if I'm wrong.

    opened by ChmielewskiKamil 1
  • Improper sizes returned by `get_type_size`

    Improper sizes returned by `get_type_size`

    The get_type_size seems to return invalid sizes, the comment states that it returns the size in bytes, but it returns the size in bits.

    • it returns 256 bits for address and payable which both are 160 bits only
    • the bytesx returns x*4 but should be x*8 to have the proper size, currently it believes that two bytes24 could be packed in the same storage slot.
    • a bool is stored with a whole byte, so should return 8 bits instead. To go down to only a single bit needs some bitpacking.
    opened by LHerskind 1
  • Create example that parses a contract into it's AST representation and print the result.

    Create example that parses a contract into it's AST representation and print the result.

    It would be helpful to see what the AST representation of a contract would look like when creating a new optimization/vuln/qa file. A contributor could use this to print out the AST and know what nodes to target when designing their pattern.

    This is very straightforward to do this. Just create an examples directory and then create a parse_contract.rs file in the examples.

    Then you can use something like the code below to convert a contract string to an AST and print the result.

     let file_contents = r#"
        
        contract Contract0 {
    
        }
        "#;
    
        let source_unit = solang_parser::parse(file_contents, 0).unwrap().0;
    
    
    println!("{:?}", source_unit);
    
    good first issue 
    opened by 0xKitsune 1
  • Non-value type variable should not be marked as immutable candidate

    Non-value type variable should not be marked as immutable candidate

    opened by dijkstra-dev 0
  • Added: SolHint[private-vars-leading-underscore] rule | #42

    Added: SolHint[private-vars-leading-underscore] rule | #42

    Related issue: #42

    In the test case file, it mentions that public and externals names must not be prefixed with an underscore. Maybe this should be addressed in an separated analyzer?

    In this PR both cases are taken account.

    opened by dijkstra-dev 2
  • error

    error

    solstat thread 'main' panicked at 'called Result::unwrap() on an Err value: [Diagnostic { loc: File(0, 342, 343), level: Error, ty: ParserError, message: "unrecognised token ',', expected ")", ";", "="", notes: [] }]', src\analyzer\vulnerabilities\mod.rs:102:73 note: run with RUST_BACKTRACE=1 environment variable to display a backtrace

    opened by Akriosss47 1
  • Vulnerability Request: Use `msg.sender` over `tx.orgin` when authorizing

    Vulnerability Request: Use `msg.sender` over `tx.orgin` when authorizing

    Contracts that authorize users using the tx.origin variable are typically vulnerable to phishing attacks which can trick users into performing authenticated actions.

    opened by 0xClandestine 0
  • Patch Unsafe ERC20 operations to ignore `transfer` the method access is on an `address` type.

    Patch Unsafe ERC20 operations to ignore `transfer` the method access is on an `address` type.

    Right now, the unsafe ERC20 operations vulnerability pattern is matching on MemberAccess nodes in the AST where the function identifier is transfer, transferFrom and approve. This needs to be updated to ignore instances where the MemberAccess is on an address type.

    bug 
    opened by 0xKitsune 0
Owner
null
Vanitygen-bip39 - Generate vanity / gas efficient Ethereum addresses for your hdwallet (bip39 12 or 24 words)

vanitygen-bip39 Generate Ethereum gas efficient addresses with leading zeros https://medium.com/coinmonks/on-efficient-ethereum-addresses-3fef0596e263

iam4x 9 Jul 2, 2022
A tool to help with estimating NEAR gas spent by transactions on Aurora.

Aurora Gas Estimator A tool to help with estimating NEAR gas spent by transactions on Aurora. Building from source Prerequisites Rust GNU Make (3.81+)

Michael Birch 4 Aug 23, 2022
A tool to identify related SSL keys, CSRs, and certificates.

⛓ sslchains A tool to identify related SSL keys, CSRs, and certificates. Usage Default Display Mode Run with any number of path arguments to define th

Gary Locke 1 Apr 2, 2022
Audit Cargo.lock files for dependencies with security vulnerabilities

RustSec Crates ?? ??️ ?? The RustSec Advisory Database is a repository of security advisories filed against Rust crates published via crates.io. The a

RustSec 1.2k Dec 30, 2022
Rust bindings for Solidity's AST and visitors

solc-ast solc-ast provides rust bindings for the solidity AST and visitors. The visitors were built to be 1-1 compatible with the visitors from solc.

Hari 35 May 7, 2023
Generates Solidity code to verify EIP-712 style signatures

eip712 Generates Solidity code to verify EIP-712 style signatures. Usage First, create an abstract contract implementing the functionality you want: /

Sam Wilson 11 Dec 22, 2022
evm2near compiles Solidity contracts into NEAR WebAssembly contracts.

EVM → NEAR evm2near is a project for compiling EVM bytecode into wasm bytecode, with the particular goal of having that wasm artifact be executable on

Aurora 125 Dec 3, 2022
A tool to optimize your Solidity function signatures.

sigop A CLI tool to optimize your Solidity function signatures. I wanted to create this after seeing transmissions11's comment about this optimization

Quartz Technology 11 Nov 24, 2022
Simple template for building smart contract(Rust) and RPC Client(web3.js) on Solana (WIP) ⛏👷🚧⚠️

Solana BPF Boilerplate Simple template for building smart contract(Rust) and RPC Client(web3.js) on Solana This boilerplate provides the following. Si

ono 6 Jan 30, 2022
Heimdall is an advanced Ethereum smart contract toolkit for forensic and heuristic analysis.

Heimdall is an advanced EVM toolkit which aims to make dealing with smart contracts on EVM based chains easier. Installation & Usage Heimdall's update

Jonathan Becker 489 Jan 2, 2023
Demo: Connect Phala's Fat Contract to external storage services, both centralized (Amazon s3) and decentralized .

This demo shows how to connect Phala's Fat Contract to external storage services, both centralized (Amazon s3) and decentralized (Arweave/Filecoin thr

Christopher Fok 2 Aug 30, 2022
A smart-contract api and client for revm

revmup A smart contract and client API for revm. Features: Auto-generate contracts that interact directly with revm without needing ethers provider Co

Dave Bryson 17 Aug 6, 2023
Substrate NFT !ink smart contract base

Substrate !ink NFT simple implementation This is a simple working version of base NFT smart contract written using latest (as of this date) !ink 3.0.0

POLK4.NET 14 Dec 3, 2022
clockchain is a system for benchmarking smart contract execution times across blockchains.

Clockchain Clockchain is a research tool for benchmarking smart contract execution times across blockchains using Arcesco-- a block-chain agnostic ins

Zeke Medley 7 Oct 3, 2022
Testing a smart contract on the Solana blockchain

Environment Setup Install Rust from https://rustup.rs/ Install Solana from https://docs.solana.com/cli/install-solana-cli-tools#use-solanas-install-to

Maurice 1 Oct 25, 2021
clockchain is a system for benchmarking smart contract execution times across blockchains.

Clockchain Clockchain is a research tool for benchmarking smart contract execution times across blockchains using Arcesco-- a block-chain agnostic ins

zeke 7 Oct 3, 2022
The NFT smart contract powering xyz on Terra

xyz NFT Contract This repository contains the core NFT smart contract that implements xyz, a base layer for metaverses on the Terra blockchain. The xy

null 16 Sep 25, 2022
An example smart contract that builds on top of xyz

xyz Guestbook Tutorial Contract This repository contains an example smart contract that illustrates how to build on top of the xyz NFT contract. This

null 5 Apr 4, 2022
Smart Contract for Terra Name Service

TERRA NAME SERVICE CONTRACTS Terra Name Service is to create easy-to-remember names for your Terra address like ‘dokwon.ust’ instead of ‘terra1...whez

null 12 Nov 23, 2022