Git Product home page Git Product logo

slither's Introduction

Slither Static Analysis Framework Logo

Build Status PyPI Slither - Read the Docs Slither - Wiki

Join the Empire Hacking Slack

Slack Status

- Discussions and Support

Slither is a Solidity & Vyper static analysis framework written in Python3. It runs a suite of vulnerability detectors, prints visual information about contract details, and provides an API to easily write custom analyses. Slither enables developers to find vulnerabilities, enhance their code comprehension, and quickly prototype custom analyses.

Features

  • Detects vulnerable Solidity code with low false positives (see the list of trophies)
  • Identifies where the error condition occurs in the source code
  • Easily integrates into continuous integration and Hardhat/Foundry builds
  • Built-in 'printers' quickly report crucial contract information
  • Detector API to write custom analyses in Python
  • Ability to analyze contracts written with Solidity >= 0.4
  • Intermediate representation (SlithIR) enables simple, high-precision analyses
  • Correctly parses 99.9% of all public Solidity code
  • Average execution time of less than 1 second per contract
  • Integrates with Github's code scanning in CI
  • Support for Vyper smart contracts

Usage

Run Slither on a Hardhat/Foundry/Dapp/Brownie application:

slither .

This is the preferred option if your project has dependencies as Slither relies on the underlying compilation framework to compile source code.

However, you can run Slither on a single file that does not import dependencies:

slither tests/uninitialized.sol

How to install

Note
Slither requires Python 3.8+. If you're not going to use one of the supported compilation frameworks, you need solc, the Solidity compiler; we recommend using solc-select to conveniently switch between solc versions.

Using Pip

python3 -m pip install slither-analyzer

Using Git

git clone https://github.com/crytic/slither.git && cd slither
python3 -m pip install .

We recommend using a Python virtual environment, as detailed in the Developer Installation Instructions, if you prefer to install Slither via git.

Using Docker

Use the eth-security-toolbox docker image. It includes all of our security tools and every major version of Solidity in a single image. /home/share will be mounted to /share in the container.

docker pull trailofbits/eth-security-toolbox

To share a directory in the container:

docker run -it -v /home/share:/share trailofbits/eth-security-toolbox

Integration

  • For GitHub action integration, use slither-action.
  • To generate a Markdown report, use slither [target] --checklist.
  • To generate a Markdown with GitHub source code highlighting, use slither [target] --checklist --markdown-root https://github.com/ORG/REPO/blob/COMMIT/ (replace ORG, REPO, COMMIT)

Detectors

Num Detector What it Detects Impact Confidence
1 abiencoderv2-array Storage abiencoderv2 array High High
2 arbitrary-send-erc20 transferFrom uses arbitrary from High High
3 array-by-reference Modifying storage array by value High High
4 encode-packed-collision ABI encodePacked Collision High High
5 incorrect-shift The order of parameters in a shift instruction is incorrect. High High
6 multiple-constructors Multiple constructor schemes High High
7 name-reused Contract's name reused High High
8 protected-vars Detected unprotected variables High High
9 public-mappings-nested Public mappings with nested variables High High
10 rtlo Right-To-Left-Override control character is used High High
11 shadowing-state State variables shadowing High High
12 suicidal Functions allowing anyone to destruct the contract High High
13 uninitialized-state Uninitialized state variables High High
14 uninitialized-storage Uninitialized storage variables High High
15 unprotected-upgrade Unprotected upgradeable contract High High
16 codex Use Codex to find vulnerabilities. High Low
17 arbitrary-send-erc20-permit transferFrom uses arbitrary from with permit High Medium
18 arbitrary-send-eth Functions that send Ether to arbitrary destinations High Medium
19 controlled-array-length Tainted array length assignment High Medium
20 controlled-delegatecall Controlled delegatecall destination High Medium
21 delegatecall-loop Payable functions using delegatecall inside a loop High Medium
22 incorrect-exp Incorrect exponentiation High Medium
23 incorrect-return If a return is incorrectly used in assembly mode. High Medium
24 msg-value-loop msg.value inside a loop High Medium
25 reentrancy-eth Reentrancy vulnerabilities (theft of ethers) High Medium
26 return-leave If a return is used instead of a leave. High Medium
27 storage-array Signed storage integer array compiler bug High Medium
28 unchecked-transfer Unchecked tokens transfer High Medium
29 weak-prng Weak PRNG High Medium
30 domain-separator-collision Detects ERC20 tokens that have a function whose signature collides with EIP-2612's DOMAIN_SEPARATOR() Medium High
31 enum-conversion Detect dangerous enum conversion Medium High
32 erc20-interface Incorrect ERC20 interfaces Medium High
33 erc721-interface Incorrect ERC721 interfaces Medium High
34 incorrect-equality Dangerous strict equalities Medium High
35 locked-ether Contracts that lock ether Medium High
36 mapping-deletion Deletion on mapping containing a structure Medium High
37 shadowing-abstract State variables shadowing from abstract contracts Medium High
38 tautological-compare Comparing a variable to itself always returns true or false, depending on comparison Medium High
39 tautology Tautology or contradiction Medium High
40 write-after-write Unused write Medium High
41 boolean-cst Misuse of Boolean constant Medium Medium
42 constant-function-asm Constant functions using assembly code Medium Medium
43 constant-function-state Constant functions changing the state Medium Medium
44 divide-before-multiply Imprecise arithmetic operations order Medium Medium
45 out-of-order-retryable Out-of-order retryable transactions Medium Medium
46 reentrancy-no-eth Reentrancy vulnerabilities (no theft of ethers) Medium Medium
47 reused-constructor Reused base constructor Medium Medium
48 tx-origin Dangerous usage of tx.origin Medium Medium
49 unchecked-lowlevel Unchecked low-level calls Medium Medium
50 unchecked-send Unchecked send Medium Medium
51 uninitialized-local Uninitialized local variables Medium Medium
52 unused-return Unused return values Medium Medium
53 incorrect-modifier Modifiers that can return the default value Low High
54 shadowing-builtin Built-in symbol shadowing Low High
55 shadowing-local Local variables shadowing Low High
56 uninitialized-fptr-cst Uninitialized function pointer calls in constructors Low High
57 variable-scope Local variables used prior their declaration Low High
58 void-cst Constructor called not implemented Low High
59 calls-loop Multiple calls in a loop Low Medium
60 events-access Missing Events Access Control Low Medium
61 events-maths Missing Events Arithmetic Low Medium
62 incorrect-unary Dangerous unary expressions Low Medium
63 missing-zero-check Missing Zero Address Validation Low Medium
64 reentrancy-benign Benign reentrancy vulnerabilities Low Medium
65 reentrancy-events Reentrancy vulnerabilities leading to out-of-order Events Low Medium
66 return-bomb A low level callee may consume all callers gas unexpectedly. Low Medium
67 timestamp Dangerous usage of block.timestamp Low Medium
68 assembly Assembly usage Informational High
69 assert-state-change Assert state change Informational High
70 boolean-equal Comparison to boolean constant Informational High
71 cyclomatic-complexity Detects functions with high (> 11) cyclomatic complexity Informational High
72 deprecated-standards Deprecated Solidity Standards Informational High
73 erc20-indexed Un-indexed ERC20 event parameters Informational High
74 function-init-state Function initializing state variables Informational High
75 incorrect-using-for Detects using-for statement usage when no function from a given library matches a given type Informational High
76 low-level-calls Low level calls Informational High
77 missing-inheritance Missing inheritance Informational High
78 naming-convention Conformity to Solidity naming conventions Informational High
79 pragma If different pragma directives are used Informational High
80 redundant-statements Redundant statements Informational High
81 solc-version Incorrect Solidity version Informational High
82 unimplemented-functions Unimplemented functions Informational High
83 unused-import Detects unused imports Informational High
84 unused-state Unused state variables Informational High
85 costly-loop Costly operations in a loop Informational Medium
86 dead-code Functions that are not used Informational Medium
87 reentrancy-unlimited-gas Reentrancy vulnerabilities through send and transfer Informational Medium
88 similar-names Variable names are too similar Informational Medium
89 too-many-digits Conformance to numeric notation best practices Informational Medium
90 cache-array-length Detects for loops that use length member of some storage array in their loop condition and don't modify it. Optimization High
91 constable-states State variables that could be declared constant Optimization High
92 external-function Public function that could be declared external Optimization High
93 immutable-states State variables that could be declared immutable Optimization High
94 var-read-using-this Contract reads its own variable using this Optimization High

For more information, see

Printers

Quick Review Printers

In-Depth Review Printers

To run a printer, use --print and a comma-separated list of printers.

See the Printer documentation for the complete lists.

Tools

See the Tool documentation for additional tools.

Contact us to get help on building custom tools.

API Documentation

Documentation on Slither's internals is available here.

Getting Help

Feel free to stop by our Slack channel (#ethereum) for help using or extending Slither.

FAQ

How do I exclude mocks or tests?

How do I fix "unknown file" or compilation issues?

  • Because slither requires the solc AST, it must have all dependencies available. If a contract has dependencies, slither contract.sol will fail. Instead, use slither . in the parent directory of contracts/ (you should see contracts/ when you run ls). If you have a node_modules/ folder, it must be in the same directory as contracts/. To verify that this issue is related to slither, run the compilation command for the framework you are using e.g npx hardhat compile. That must work successfully; otherwise, slither's compilation engine, crytic-compile, cannot generate the AST.

License

Slither is licensed and distributed under the AGPLv3 license. Contact us if you're looking for an exception to the terms.

Publications

Trail of Bits publication

External publications

Title Usage Authors Venue Code
ReJection: A AST-Based Reentrancy Vulnerability Detection Method AST-based analysis built on top of Slither Rui Ma, Zefeng Jian, Guangyuan Chen, Ke Ma, Yujia Chen CTCIS 19 -
MPro: Combining Static and Symbolic Analysis forScalable Testing of Smart Contract Leverage data dependency through Slither William Zhang, Sebastian Banescu, Leodardo Pasos, Steven Stewart, Vijay Ganesh ISSRE 2019 MPro
ETHPLOIT: From Fuzzing to Efficient Exploit Generation against Smart Contracts Leverage data dependency through Slither Qingzhao Zhang, Yizhuo Wang, Juanru Li, Siqi Ma SANER 20 -
Verification of Ethereum Smart Contracts: A Model Checking Approach Symbolic execution built on top of Slither’s CFG Tam Bang, Hoang H Nguyen, Dung Nguyen, Toan Trieu, Tho Quan IJMLC 20 -
Smart Contract Repair Rely on Slither’s vulnerabilities detectors Xiao Liang Yu, Omar Al-Bataineh, David Lo, Abhik Roychoudhury TOSEM 20 SCRepair
Demystifying Loops in Smart Contracts Leverage data dependency through Slither Ben Mariano, Yanju Chen, Yu Feng, Shuvendu Lahiri, Isil Dillig ASE 20 -
Trace-Based Dynamic Gas Estimation of Loops in Smart Contracts Use Slither’s CFG to detect loops Chunmiao Li, Shijie Nie, Yang Cao, Yijun Yu, Zhenjiang Hu IEEE Open J. Comput. Soc. 1 (2020) -
SAILFISH: Vetting Smart Contract State-Inconsistency Bugs in Seconds Rely on SlithIR to build a storage dependency graph Priyanka Bose, Dipanjan Das, Yanju Chen, Yu Feng, Christopher Kruegel, and Giovanni Vigna S&P 22 Sailfish
SolType: Refinement Types for Arithmetic Overflow in Solidity Use Slither as frontend to build refinement type system Bryan Tan, Benjamin Mariano, Shuvendu K. Lahiri, Isil Dillig, Yu Feng POPL 22 -
Do Not Rug on Me: Leveraging Machine Learning Techniques for Automated Scam Detection Use Slither to extract tokens' features (mintable, pausable, ..) Mazorra, Bruno, Victor Adan, and Vanesa Daza Mathematics 10.6 (2022) -
MANDO: Multi-Level Heterogeneous Graph Embeddings for Fine-Grained Detection of Smart Contract Vulnerabilities Use Slither to extract the CFG and call graph Hoang Nguyen, Nhat-Minh Nguyen, Chunyao Xie, Zahra Ahmadi, Daniel Kudendo, Thanh-Nam Doan and Lingxiao Jiang IEEE 9th International Conference on Data Science and Advanced Analytics (DSAA, 2022) ge-sc
Automated Auditing of Price Gouging TOD Vulnerabilities in Smart Contracts Use Slither to extract the CFG and data dependencies Sidi Mohamed Beillahi, Eric Keilty, Keerthi Nelaturu, Andreas Veneris, and Fan Long 2022 IEEE International Conference on Blockchain and Cryptocurrency (ICBC) Smart-Contract-Repair

If you are using Slither on an academic work, consider applying to the Crytic $10k Research Prize.

slither's People

Contributors

0xalpharush avatar 0xgusmccrae avatar bart1e avatar bohendo avatar boyan-milanov avatar darkamaul avatar darrenchangjr avatar dependabot[bot] avatar devtooligan avatar dguido avatar disconnect3d avatar dokzai avatar elopez avatar ggrieco-tob avatar htadashi avatar jaime-iglesias avatar mgcolburn avatar montyly avatar pcaversaccio avatar rajeevgopalakrishna avatar samczsun avatar samparsky avatar sidarth16 avatar smonicas avatar snd avatar tiko7454 avatar troublor avatar vishnuram1999 avatar webthethird avatar xenomega 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  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

slither's Issues

Printer: Inheritance printing on stdout

Hey,

It would be cool to be able to print inheritance to stdout (to quickly analyze things), examples:

  • see what inherits from BaseContract: BaseContract childrens: A, B, C, D, E, ... (it should also list the contracts that derives from A, B, C, D, E)
  • see all base classes for given contract: Children inherits from: BaseContract1, BaseContract2, BaseBaseContract, SuperBaseBaseBaseContract

Use json output for travis test

Right now the travis tests only check for the number of results returned:

https://github.com/trailofbits/slither/blob/39f560bf973acbc31c908991f94d4cb57a7e4828/scripts/travis_test.sh#L5-L16

It would make more sense to test the json output.

  • Generate pre-defined json for each testcase (used as ground truth)
  • Update scripts/travis_test.sh to export the result in a json file (--json)
  • For each testcase, compare the generated json with the corresponding pre-defined json
  • If if an issue is found, print the difference
  • Clean the generated json file(s) (but not the ground true)

Add support for Vyper

SlithIR is flexible enough that we should be able to support Vyper with few modifications. This will require investigating how Vyper produces their AST and providing for some translation into SlithIR. SlithIR may need modification in the process to support the unique features of Vyper's AST.

Visual Studio Plugin

We should have a visual studio plugin

Features:

  • Run slither
  • Save the results
  • List the bugs found (with a checkbox 'Won't fix/False alarm")
  • Once you click on a bug, it highlights the code (using the JSON information)

Detector: Unused return value of a call

If the return value of a function is never used, it's likely to be bug.

  • severity low/medium

SlithIR can be used to track if the value returned by a call is used:

  • If the function does not return a value, the lvalue of the operation is None, otherwise its a variable.
  • We can check if the lvalue is in the read list of another operation

Example:

contract Target{
    function f() returns(uint);
}

contract Function{

    function test(Target t){
        t.f();
    }

}

Add support for LLL

SlithIR is flexible enough that we should be able to support LLL with few modifications. This will require investigating how LLL produces their AST and providing for some translation into SlithIR. SlithIR may need modification in the process to support the unique features of LLL's AST.

Handle multiple files

Would be nice to run batch analyses

$ slither contracts/*.sol
usage: slither.py contract.sol [flag]
slither: error: unrecognized arguments: contracts/B.sol contracts/C.sol ...

Slither should identify storage variables accessed under a different name

Hey, we came across this during the Trail of Bits workshop with @japesinator. When we are looking for a storage variable to be written to, slither does not find it if we access it under a different name in the solidity code.

We didn't figure out how to catch it with the currently available API. We were thinking about recursively tracking also variables where the storage variable would be read.

It should be possible for slither to identify these cases and report them as "writing to the storage variable with that name".

Minimal Example:

Python

from slither.slither import Slither
from slither.core.declarations.function import Function

slither = Slither('test.sol')

def get_msg_sender_checks(function):
    all_functions = function.all_internal_calls() + \
        [function] + function.modifiers

    all_nodes = [f.nodes for f in all_functions if isinstance(f, Function)]
    all_nodes = [item for sublist in all_nodes for item in sublist]

    all_conditional_nodes = [n for n in all_nodes if
                             n.contains_if() or n.contains_require_or_assert()]
    all_conditional_nodes_on_msg_sender = [str(n.expression) for n in all_conditional_nodes if
                                           'msg.sender' in [v.name for v in n.solidity_variables_read]]
    return all_conditional_nodes_on_msg_sender


for contract in slither.contracts:
    print('Contract: ' + contract.name)

    for function in contract.functions:

        msg_sender_condition = get_msg_sender_checks(function)

        if len(msg_sender_condition) == 0:
            for v in function.state_variables_written:
                if v.name == 'balances':
                    print('Function: {}'.format(function.name))
                    print('\tWriting to balances: {}'.format(v.name))

Solidiy

// test.sol

contract Test
{
    struct Balance {
        uint balance;
    }

    Balance public balances;

    function setBalances(uint _balances)
        public
    {
        require(msg.sender == address(0));
        balances.balance = _balances;
    }

    function setBalancesUnchecked(uint _balances) public {
        // `other` writes to storage `balances` as it is
        // uninitialized.
        Balance storage other;
        // Thus, this writes to storage variable balances,
        // but is not detected:
        other.balance = _balances;
    }
}

We later found out that this is also not found:
Balance storage other = balances;

/cc @pgev @benjaminbollen

Improve or create better remix plugin

Remix integrates now by default a plugin to run slither: https://medium.com/remix-ide/remix-ide-v0-7-5-released-a386ed6faf38

The current plugin is https://github.com/mul1sh/remix-analysis-plugin (it was built from this issue: https://github.com/ethereum/remix-ide/issues/1500)

The plugin does not give a good user experience:
image

We should either improve the current plugin through PR (see mul1sh/remix-analysis-plugin#1), or create a new plugin

Among others the plugin should:

  • Be up to date with the latest slither release
  • Don't show compiler warnings
  • Use colors
  • Prevent the text to be hidden outside the visible windows
  • Allow the user to select / disable some of the detectors

No module named detectors.abstract_detector

it will be error when I use the command, I have try to solve the problem, but it is failure, Can you help me solve the problem? thanks in advance!
my os is ubuntu 16.04
root@biaoy3:~/MetaCoin/contracts# lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 16.04.5 LTS
Release: 16.04
Codename: xenial

this is the error message.
root@biaoy3:~/MetaCoin/contracts# slither MetaCoin.sol
Traceback (most recent call last):
File "/usr/local/bin/slither", line 9, in
load_entry_point('slither-analyzer==0.2.0', 'console_scripts', 'slither')()
File "/usr/lib/python2.7/dist-packages/pkg_resources/init.py", line 542, in load_entry_point
return get_distribution(dist).load_entry_point(group, name)
File "/usr/lib/python2.7/dist-packages/pkg_resources/init.py", line 2569, in load_entry_point
return ep.load()
File "/usr/lib/python2.7/dist-packages/pkg_resources/init.py", line 2229, in load
return self.resolve()
File "/usr/lib/python2.7/dist-packages/pkg_resources/init.py", line 2235, in resolve
module = import(self.module_name, fromlist=['name'], level=0)
File "build/bdist.linux-x86_64/egg/slither/init.py", line 1, in
File "build/bdist.linux-x86_64/egg/slither/slither.py", line 6, in
ImportError: No module named detectors.abstract_detector

Incorrect do-while CFG

The following loop outputs the wrong CFG

function dowhile() public {
    uint8 i = 0;
    uint8 a;
    do {
        i++;
        a = 1;
        a = 2;
        a = 3;
    } while (i < 10);
}

out

Correct output would look like this:
out2

detector (old solc) only checks 0.4.23, 0.4.24

slither version: 0.3.1

in /slither/attributes/old_solc.py

old_pragma = [p for p in pragma if self._convert_pragma(p.version) not in ['0.4.23', '0.4.24']]
if old_pragma:
  # detected old pragma

It detects only "0.4.23", "0.4.24" as safe version. (even test solidity uses 0.4.25, it detected as old version)

should it be changed like under 0.4.25 is unsafe version? and also it will be great to support 0.5.X versions :)

Document and standardize the json output

We have private documentation for the json output. We need to standardize its format and bring it to the open source repo.

Some of the fields use a different naming convention, such as mixedCase / non_mixed. We need to settle on one naming convention.

Add functionality to exclude specific tests

I don't think the --high, --medium, --low flags make a ton of sense right now. As a user, it's more common that one or more noisy checks are false positives and I want to disable them specifically. We should add some notion of IDs to each check, then have a single flag like --exclude reentrancy or similar to turn it off for that run.

Integrate with Truffle

Truffle is the most popular development framework for smart contracts, and building this feature would enable the largest possible audience to have instant access to Slither.

At Trail of Bits, we are not experts in the internals of Truffle, and we try to avoid writing anything in JavaScript whenever possible. Our expertise here is limited and we're looking for help to implement this feature the "right" way. A successful implementation should use the lowest number of installation and configuration steps. It should just work.

Value and taint tracking

We're writing an Intermediate Representation (IR) for Solidity that enables capturing a greater level of detail about the code. Slither will translate the AST to the IR, and then perform analysis on the IR.

Add Contributor Guidelines

Overview

To support an influx of external contributions (incentivized from Gitcoin and more organic OSS approaches), I propose adding contributor guidelines to this repo to communicate how people should contribute. This will save time for repo owners as well as contributors and help verify that PRs are well-formed and opened issues are useful.

I see two straightforward approaches that could support contributor guidelines:

  1. Create a separate CONTRIBUTING file in the root directory
    • advantage: Obvious in the file tree. I've had success doing this for Aragon here
    • disadvantage: New file. Fragments documentation across wiki and elsewhere
  2. Create a new wiki Contributor Guidelines wiki entry and link to it from the README
    • advantage: Supports existing use of wiki for this repo. Could move to a more robust developer portal easily.
    • disadvantage: Less popular approach. Can't integrate cool things like PR templates directly.

Open to all feedback and thoughts.

Example Guidelines:

Pull Request process

Code of Conduct

Contact Info (Slack, Email, etc)

Docker image issues

  1. Clone Slither git repo
  2. docker build -t slither
  3. docker run slither
tests/uninitialized.sol:1:1: Error: Source file requires different compiler version (current compiler is 0.5.1+commit.c8a2cb62.Linux.g++ - note that nightly builds are considered to be strictly less than the released version
pragma solidity ^0.4.24;
^----------------------^
tests/uninitialized.sol:19:5: Error: No visibility specified. Did you intend to add "public"?
    function init() {
    ^ (Relevant source part starts here and spans across multiple lines).
tests/uninitialized.sol:23:5: Error: No visibility specified. Did you intend to add "public"?
    function use() {
    ^ (Relevant source part starts here and spans across multiple lines).
tests/uninitialized.sol:35:5: Error: No visibility specified. Did you intend to add "public"?
    function set(MyStruct storage st, uint v){
    ^ (Relevant source part starts here and spans across multiple lines).
tests/uninitialized.sol:49:5: Error: No visibility specified. Did you intend to add "public"?
    function init(){
    ^ (Relevant source part starts here and spans across multiple lines).
tests/uninitialized.sol:53:5: Error: No visibility specified. Did you intend to add "public"?
    function use(){
    ^ (Relevant source part starts here and spans across multiple lines).
tests/uninitialized.sol:8:9: Error: Member "transfer" not found or not visible after argument-dependent lookup in address.
        destination.transfer(msg.value);
        ^------------------^

INFO:Slither:tests/uninitialized.sol analyzed (0 contracts), 0 result(s) found

MacOS Mojave
Docker version 18.09.0, build 4d60db4

can't use xdot for slither

Yes, I have been use xdot for slither to analyze contract with the for example in the wiki,but the result is

38:Desktop bobby$ xdot wallet.sol.dot 

(xdot:70219): Gtk-WARNING **: 11:24:00.117: Error loading theme icon 'document-open' for stock: 图标“document-open”未在主题 Adwaita 中出现

(xdot:70219): Gtk-WARNING **: 11:24:00.169: Error loading theme icon 'view-refresh' for stock: 图标“view-refresh”未在主题 Adwaita 中出现

(xdot:70219): Gtk-WARNING **: 11:24:00.170: Error loading theme icon 'document-print' for stock: 图标“document-print”未在主题 Adwaita 中出现

(xdot:70219): Gtk-WARNING **: 11:24:00.170: Error loading theme icon 'zoom-in' for stock: 图标“zoom-in”未在主题 Adwaita 中出现

(xdot:70219): Gtk-WARNING **: 11:24:00.170: Error loading theme icon 'zoom-out' for stock: 图标“zoom-out”未在主题 Adwaita 中出现

dot: Not a directory

,and the for example is

dot examples/printers/inheritances.sol.dot -Tsvg -o examples/printers/inheritances.sol.png

the result is -bash: dot: command not found
why? can U help me?

Slither Bug: AttributeError: 'MappingType' object has no attribute 'type'

Description

First of all, thanks to Trail of Bits for creating and maintaining this great solidity static analyser!
Slither produces the following error messages when executed against specific solidity contracts:

ERROR:root:Error in Nomin.sol
ERROR:root:Traceback (most recent call last):
  File "/home/mz/.virtualenvs/test_slither/lib/python3.7/site-packages/slither/__main__.py", line 226, in main_impl
    (results, number_contracts) = process(filename, args, detector_classes, printer_classes)
  File "/home/mz/.virtualenvs/test_slither/lib/python3.7/site-packages/slither/__main__.py", line 35, in process
    slither = Slither(filename, args.solc, args.disable_solc_warnings, args.solc_args, ast)
  File "/home/mz/.virtualenvs/test_slither/lib/python3.7/site-packages/slither/slither.py", line 41, in __init__
    self._analyze_contracts()
  File "/home/mz/.virtualenvs/test_slither/lib/python3.7/site-packages/slither/solc_parsing/slitherSolc.py", line 191, in _analyze_contracts
    self._convert_to_slithir()
  File "/home/mz/.virtualenvs/test_slither/lib/python3.7/site-packages/slither/solc_parsing/slitherSolc.py", line 317, in _convert_to_slithir
    func.convert_expression_to_slithir()
  File "/home/mz/.virtualenvs/test_slither/lib/python3.7/site-packages/slither/solc_parsing/declarations/function.py", line 838, in convert_expression_to_slithir
    node.slithir_generation()
  File "/home/mz/.virtualenvs/test_slither/lib/python3.7/site-packages/slither/core/cfg/node.py", line 364, in slithir_generation
    self._find_read_write_call()
  File "/home/mz/.virtualenvs/test_slither/lib/python3.7/site-packages/slither/core/cfg/node.py", line 397, in _find_read_write_call
    self._high_level_calls.append((ir.destination.type.type, ir.function))
AttributeError: 'MappingType' object has no attribute 'type'

Steps to reproduce

Support compact solc AST

--ast-compact-json gives a different AST, which is supposed to be more precise.

Additionaly it seems that the solc support for the --ast-json format will be remove in the future.

Finally, it should also help supporting truffle (#18)

unrecognized arguments: --low

The readme says that there is a --low flag, but when I try it I get an error:

$ ./slither.py ../onchain/ProvethVerifier.sol --low
usage: slither.py contract.sol
slither.py: error: unrecognized arguments: --low

Also, it might be nice to change the usage line of the help to

usage: slither.py contract.sol [flags]

I initially assumed that flags go before the file to be analyzed.

vars-and-auth printer output bug

When using the vars-and-auth printer there is a bug in the output.

Problem Description

The entire table is written out on each iteration of going through the functions of a contract, instead of printing out once after the for each function loop is done.

Example output currently

INFO:Printers:
Contract MyContract
+----------+-------------------------+---------------------------------------------+
| Function | State variables written |           Conditions on msg.sender          |
+----------+-------------------------+---------------------------------------------+
|  setCEO  |       ['ceoAddress']    | ['require(bool)(msg.sender == ceoAddress)'] |
+----------+-------------------------+---------------------------------------------+
INFO:Printers:
Contract MyContract
+----------+-------------------------+---------------------------------------------+
| Function | State variables written |           Conditions on msg.sender          |
+----------+-------------------------+---------------------------------------------+
|  setCEO  |       ['ceoAddress']    | ['require(bool)(msg.sender == ceoAddress)'] |
|  setCMO  |       ['cmoAddress']    | ['require(bool)(msg.sender == ceoAddress)'] |
+----------+-------------------------+---------------------------------------------+
INFO:Printers:
Contract MyContract
+----------+-------------------------+---------------------------------------------+
| Function | State variables written |           Conditions on msg.sender          |
+----------+-------------------------+---------------------------------------------+
|  setCEO  |       ['ceoAddress']    | ['require(bool)(msg.sender == ceoAddress)'] |
|  setCMO  |       ['cmoAddress']    | ['require(bool)(msg.sender == ceoAddress)'] |
|  setCSO  |       ['csoAddress']    | ['require(bool)(msg.sender == ceoAddress)'] |
+----------+-------------------------+---------------------------------------------+
INFO:Printers:
Contract MyContract
+----------+-------------------------+---------------------------------------------+
| Function | State variables written |           Conditions on msg.sender          |
+----------+-------------------------+---------------------------------------------+
|  setCEO  |       ['ceoAddress']    | ['require(bool)(msg.sender == ceoAddress)'] |
|  setCMO  |       ['cmoAddress']    | ['require(bool)(msg.sender == ceoAddress)'] |
|  setCSO  |       ['csoAddress']    | ['require(bool)(msg.sender == ceoAddress)'] |
|  setCFO  |       ['cfoAddress']    | ['require(bool)(msg.sender == ceoAddress)'] |
+----------+-------------------------+---------------------------------------------+

Expected Output

just the last one..


INFO:Printers:
Contract MyContract
+----------+-------------------------+---------------------------------------------+
| Function | State variables written |           Conditions on msg.sender          |
+----------+-------------------------+---------------------------------------------+
|  setCEO  |       ['ceoAddress']    | ['require(bool)(msg.sender == ceoAddress)'] |
|  setCMO  |       ['cmoAddress']    | ['require(bool)(msg.sender == ceoAddress)'] |
|  setCSO  |       ['csoAddress']    | ['require(bool)(msg.sender == ceoAddress)'] |
|  setCFO  |       ['cfoAddress']    | ['require(bool)(msg.sender == ceoAddress)'] |
+----------+-------------------------+---------------------------------------------+

SlithIR: Incorrect conversion of return tuple

Slither does not convert correctly return with tuple expression:

contract Test{

    function test(uint a, uint b) returns(uint, uint){
        return(a,b);
    }   

    function test2(uint a) returns(uint){
        return(a);
    }   

    function test3(uint a) returns(uint){
        return a;
    }
}

Only test3 is correctly translated to slithir:

	Function test(uint256,uint256)
		Expression: (a,b)
		IRs:
	Function test2(uint256)
		Expression: (a)
		IRs:
	Function test3(uint256)
		Expression: a
		IRs:
			RETURN a

Detector: Detect public functions that could be declared as external

If a public function is never called, it should be marked as external, so that it can be optimized by solc

  • Severity: Informational

Hints:Use slithIR and check:

  • the function is never the destination of an InternalCall
  • there is no InternalDynamicCall (or ensure that the function is never the destination of an InternalDynamicCall)
  • Iterate only over the derived contracts (slither.contracts_derived) to be sure that no inherited contract calls the function

Detector: Detect complex functions

In the printer_human_readable branch we compute the cyclomatic complexity of a function: https://github.com/trailofbits/slither/blob/printer-human-readable/slither/utils/code_complexity.py

We can extend this idea and create a detector that detects complex functions. A complex function could be defined as:

  • high cyclomatic complexity (this needs some tests to define what is a high value for a smart contract)
  • numerous write to state variables
  • numerous external calls

Other metrics are also possible.

  • severity: informational

Rename --printers to --print

I think it makes more sense to ask, "Hey Slither, can you print vars and auth?" rather than "Hey Slither, can you printer vars and auth?"

Show the user how many contracts slither found and analyzed

It could be useful to show the user how many contracts analyzed in a directory, just to make sure it found the expected files. Right now, slither outputs:

INFO:Slither:somepath/contracts/ analyzed, 0 result(s) found

We could show how many contracts we analyzed:

INFO:Slither:somepath/contracts/ analyzed, 0 result(s) found in XX contracts

Add more details to JSON output

1. If I have two contract definitions in a file e.g.

contract C {
function i_am_backdoor(){}
}

contract D {
function i_am_backdoor(){
}
}

The json output doesn't tell me which of the contracts the function in the output belong to
The JSON output looks something like this

{  
      "check":"backdoor",
      "function":{  
         "name":"i_am_a_backdoor",
         "source_mapping":{  
            "start":43,
            "length":74,
            "filename":"/tmp/browser/suicide.sol",
            "lines":[  
               5,
               6,
               7
            ]
         }
      }
   }

it doesn't indicate which contract it belongs to.

2. Add Error Message

It would be great to have the error log messages displayed in the terminal as part of the JSON output.
The current implementation requires having to parse the details and reconstructing the messages.

These two changes are needed for the Slither Remix plugin

Improve track of storage reference

In the following example, both contracts have the same outcome, but slither detects an initialized variable in Reference:

contract Reference{
    mapping (uint128 => mapping (uint256 => uint256)) map;

    function init() external{
        mapping(uint256 => uint256) tmp = map[0];
        tmp[0] = 0;
    }
}

contract Direct{
    mapping (uint128 => mapping (uint256 => uint256)) map;
    
    function init() external{
        map[0][0] = 0;
    }
}

The issue is that slither does not track the storage reference created through mapping(uint256 => uint256) tmp = map[0];, while it should.

It is close to the issue #70

FileNotFoundError: [Errno 2] No such file or directory: 'solc'

I launch program like this:

slither Contract.sol 

and receive an error:
"FileNotFoundError: [Errno 2] No such file or directory: 'solc'"

I have solc installed.

$ solcjs --version
0.4.25+commit.59dbf8f1.Emscripten.clang

But executable is called solcjs, not solc. Or it is something different?

Modify command line arguments

The command line arguments are setup differently than I would expect for Slither. I wonder what people think about changing them? I would have expected some of these changes:

  • --detect which takes a comma-separated list indicating the checks to run (default: all)
  • --print which takes a comma-separated list of printers to output (default: ???)
  • --output which accepts a single parameter of either stdout or json (default: stdout)
  • remove exclusion rules entirely
  • calling slither with no arguments should print the help
  • reorganize the help screen into groups of related parameters for easier reading

Exception: Ternary operation not handled

  • slither version: 0.2.0
  • solc version: 0.4.25

In some case slither raises an exception of ternary operation, here is a test file:

pragma solidity ^0.4.24;
contract C{
    function f(uint a)public{
                uint [4][] memory res = new uint[4][]( a>0?1:0);
    }
}

and the trace

  File "/home/zqqz/playground/slither/slither/__main__.py", line 209, in main_impl
    (results, number_contracts) = process(filename, args, detector_classes, printer_classes)
  File "/home/zqqz/playground/slither/slither/__main__.py", line 34, in process
    slither = Slither(filename, args.solc, args.disable_solc_warnings, args.solc_args, ast)
  File "/home/zqqz/playground/slither/slither/slither.py", line 41, in __init__
    self._analyze_contracts()
  File "/home/zqqz/playground/slither/slither/solc_parsing/slitherSolc.py", line 187, in _analyze_contracts
    self._analyze_third_part(contracts_to_be_analyzed, libraries)
  File "/home/zqqz/playground/slither/slither/solc_parsing/slitherSolc.py", line 269, in _analyze_third_part
    self._analyze_variables_modifiers_functions(contract)
  File "/home/zqqz/playground/slither/slither/solc_parsing/slitherSolc.py", line 309, in _analyze_variables_modifiers_functions
    contract.analyze_content_functions()
  File "/home/zqqz/playground/slither/slither/solc_parsing/declarations/contract.py", line 331, in analyze_content_functions
    function.analyze_content()
  File "/home/zqqz/playground/slither/slither/solc_parsing/declarations/function.py", line 850, in analyze_content
    st = SplitTernaryExpression(node.expression)
  File "/home/zqqz/playground/slither/slither/utils/expression_manipulations.py", line 48, in __init__
    self.copy_expression(expression, self.true_expression, self.false_expression)
  File "/home/zqqz/playground/slither/slither/utils/expression_manipulations.py", line 90, in copy_expression
    false_expression.expressions[-1])
  File "/home/zqqz/playground/slither/slither/utils/expression_manipulations.py", line 100, in copy_expression
    false_expression.called)
  File "/home/zqqz/playground/slither/slither/utils/expression_manipulations.py", line 120, in copy_expression
    raise Exception('Ternary operation not handled {}'.format(type(expression)))
Exception: Ternary operation not handled <class 'slither.core.expressions.new_array.NewArray'>

Printer: Callgraph printer

A callgraph printer would show for each function, what are the contracts/functions called.

For example, on

contract ContractA{
    function my_func_a(){}
}

contract ContractB{
    
    ContractA a;
    
    constructor(){
        a = new ContractA();
    }
    
    function my_func_b(){
        a.my_func_a();
        my_second_func_b();
    }
    
    function my_second_func_b(){
    }
}

It should show that ContractB.my_func_b() calls ContractA.my_func_a and ContractB.my_second_func_b()

The printer will output a dot, similar to the inheritance printer.

It's probably more readable to group the functions of a contract into a dot subgraph

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.