• Stars
    star
    138
  • Rank 263,043 (Top 6 %)
  • Language
    JavaScript
  • Created almost 3 years ago
  • Updated 10 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

🧠 A scriptable semantic grep utility for solidity

get in touch with Consensys Diligence
[ 🌐 📩 🔥 ]

🧠 SolGrep - A scriptable semantic grep utility for solidity

So you have a set of smart contracts and want to find all contracts that have a public method named withdrawEth but lexical grep yields a lot of false-positives? Here's where solgrep can help! 🙌

💾 npm install -g solgrep

Solgrep recursively finds smart contracts in a target directory, parses the source units to understand the language semantics, and makes this information available to a powerful javascript-based filter function. This way, you can:

  • extract semantic information from solidity source code based on custom filter functions
  • find target contracts based on a custom filter script you define
  • create & run your own or built-in rules (e.g. for CI checks)
  • crunch numbers and generate statistics from a code base
  • find doppelgangers! i.e. duplicate contracts sharing the same code structure (AST_EXACT and AST_FUZZY matching)

Probably the most common way to use this tool is to run it with the --find=<js-filter-statement> option, where js-filter-statement is a javascript one-liner that tells the engine what you are interested in. You either provide a statement that returns boolean ("find mode") or return information you want to extract ("extract mode").

solgrep2

⚠️ Make sure to only allow trusted inputs to --find=<js-filter-statement> as this argument is being evaluated as javascript!

⚠️ Check out the proper order for arguments when using --find, --rule. See Usage.

Examples

Run the default rules and display some stats?

  solgrep <folder> 

Run a specific or multiple built-in rules (solgrep -l to list available rules)? 👉

  solgrep <folder> --rule=IsInitializable --rule=Stats

You want to find all source-units with a contract that has a function named withdrawEth? 👉

  solgrep <folder> --find="function.name=='withdrawEth'" 

Do the same thing but case-insensitive? 👉

  solgrep <folder> --find="function.name.toLowerCase()=='withdraweth'" 

Find all functions that call selfdestruct? 👉

  solgrep <folder> --find="function.callsTo('selfdestruct')"

Exctract all function names from all contracts? 👉

  solgrep <folder> --find="function.name" 

Get a list of all external functions? 👉

  solgrep <folder> --find="function.visibility.includes('external')"  

Find ERC777 contracts? 👉

  solgrep <folder> --find="contract.name=='ERC777'" 

Extract all Contract names? 👉

  solgrep <folder> --find="contract.name"

Extract all Interface names? 👉

  solgrep <folder> --find="contract.name && contract.kind=='interface'"

Match against something in the AST? 👉

  solgrep <folder> --find="Object.keys(function.modifiers).includes('nonReentrant')"

Lexial match a functions source code? 👉

  solgrep <folder> --find="function.getSource().includes('hi')"

Find duplicate contracts? (AST exact and fuzzy matching) 👉

  solgrep <folder> --rule DupeFinder

Use option --output=<output.json> to write all results to a file.

Built-In Keywords for --find

  • The sourceUnit object matches the source-file the engine is currently processing.
  • The contract object matches the contract the engine is currently processing.
  • The function object matches the function the engine is currently processing.

Available Methos

The following methods are available:

  • <sourceUnit|contract|function>.getSource() - provides access to the units source code
  • <sourceUnit|contract|function>.ast - provides direct access to the solidity-parser AST
  • function.callsTo('withdrawEth') - find all functions in all contracts that call a method named withdrawEth
  • There's even more information easily available (functions/events/pragmas/etc.). Go check out the Solidity SourceUnit/Contract/Function Wrapper Classes functionality (attribs/functions).

Special Functions

Special contract functions can be references as:

  • function.name == '__fallback__'
  • function.name == '__receiveEther__'
  • function.name == '__constructor__'

Built-In Rules

  • Stats - collects stats about how many files, contracts, unique names, etc. were processed
  • GenericGrep - is the engine behind the --find feature
  • ...

SHARING IS CARING - submit your rules!

Usage

  solgrep --help
Usage: solgrep <folder|...> [options]

Options:
  -r, --rule        Enable rules                           [array] [default: []]
  -l, --list-rules  List available rules              [boolean] [default: false]
  -f, --find        Find/Extract information using custom pattern
                                                           [array] [default: []]
  -o, --output      Write "results" as JSON to output file path.        [string]
  -h, --help        Show help                                          [boolean]
  -v, --version     Show version number                                [boolean]

⚠️ when using multi-options (--find, --rule) make sure to use this format:

⇒  solgrep <folder|...> [options]

or

⇒  solgrep [options] -- <folder|...> 

or else additional options might be interpreted as additional --find options!

Library

const solgrep = require('solgrep');

let sg = new SolGrep('::memory::', rules, callbacks);
sg.analyzeDir("/path/to/smart/contracts").then(() => {
    console.log("   ──────────────────────────── Results")
    console.log(sg.results)
    console.log("   ────────────────────────────")
    sgrep.close();
})

Demo

Here's an example that illustrates how to extract all function names from all sourceUnits and contracts.

  solgrep ../d0  --find='function.name' 
🧠 SolGrep v0.0.3 ready!

  Enabled Modules:
    ✔️ GenericGrep          _function.name

[████████████████████████████████████████] 100% | 🕙 ETA: 0s | 5/5 | 🌲 389 | 🔥 0 | 🗂️  ../d0

   ────────────────────────────
{
  '../d0/D0788Af7a613b81F437a51b96594A6387c7329b1_PendleLiquidityMiningBaseV2Multi.sol': [
    {
      rule: 'GenericGrep',
      tag: 'match-function: PendleLiquidityMiningBaseV2Multi.__constructor__',
      info: '__constructor__',
      loc: [Object]
    },
    {
      rule: 'GenericGrep',
      tag: 'match-function: PendleLiquidityMiningBaseV2Multi.setUpEmergencyMode',
      info: 'setUpEmergencyMode',
      loc: [Object]
    },
...

Run default Rulesets

If you provide no configuration options it will take the default built-in grep rules and crunch numbers using the stats module.

  solgrep ../d6 
🧠 SolGrep v0.0.1 starting ...


  📁 ../d6
 ████████████████████████████████████████ 100% | ETA: 0s | 5/5

   ──────────────────────────── Results
{
  '../d6/d60a598998ed27a7C54315F2675908B628E434B1_LiquidityPool.sol': [
    {
      rule: 'IsInitializable',
      tag: 'INITIALIZEABLE',
      info: 'initialize - public initialize function; likely proxy'
    },
    {
      rule: 'IsInitializable',
      tag: 'INITIALIZEABLE',
      info: 'initialize - public initialize function; likely proxy'
    }
  ],
  '../d6/d64E77C7C6A1dcC7e302F8fe31A22745e223c39c_MyStrategy.sol': [
    {
      rule: 'IsInitializable',
      tag: 'INITIALIZEABLE',
      info: 'initialize - public initialize function; likely proxy'
    }
  ],
  undefined: [ { rule: 'Stats', tag: 'STATS', info: [Object] } ]
}
   ────────────────────────────
{
  sourceUnits: 4,
  contracts: {
    total: 13,
    names: {
      ERC20: 1,
      StrategySushiEthMimLp: 1,
      LiquidityPool: 1,
      Getter: 1,
      Governance: 1,
      LibraryEvents: 1,
      Perpetual: 1,
      Storage: 1,
      ArbiBoneman: 1,
      ERC721: 1,
      MyStrategy: 1,
      PausableUpgradeable: 1,
      SettAccessControl: 1
    }
  },
  interfaces: {
    total: 39,
    names: {
      IERC20: 1,
      IJar: 1,
      IStakingRewards: 1,
      IStakingRewardsFactory: 1,
      IMasterchef: 1,
      UniswapRouterV2: 1,
      IUniswapV2Pair: 1,
      IUniswapV2Factory: 1,
      IRewarder: 1,
      IMiniChefV2: 1,
      ILiquidityPool: 1,
      IOracle: 1,
      IAccessControl: 1,
      IGovernor: 1,
      IPoolCreatorFull: 1,
      ISymbolService: 1,
      IPoolCreator: 1,
      ITracer: 1,
      IVersionControl: 1,
      IVariables: 1,
      IKeeperWhitelist: 1,
      IProxyAdmin: 1,
      IDecimals: 1,
      ILiquidityPoolGetter: 1,
      ILiquidityPoolGovernance: 1,
      IPerpetual: 1,
      IERC721Enumerable: 1,
      IERC721: 1,
      IERC721Receiver: 1,
      IERC721Metadata: 1,
      IERC165: 1,
      ICurveGauge: 1,
      ICurveStableSwapREN: 1,
      IUniswapRouterV2: 1,
      IStrategy: 1,
      IController: 2,
      IERC20Upgradeable: 2
    }
  },
  libraries: {
    total: 31,
    names: {
      SafeMath: 1,
      SafeERC20: 1,
      BoringERC20: 1,
      EnumerableSetUpgradeable: 1,
      SafeCastUpgradeable: 1,
      AMMModule: 1,
      LiquidityPoolModule: 1,
      PerpetualModule: 1,
      SignedSafeMathUpgradeable: 1,
      Constant: 1,
      Math: 1,
      SafeMathExt: 1,
      Utils: 1,
      MarginAccountModule: 1,
      EnumerableSet: 1,
      OrderData: 1,
      CollateralModule: 1,
      TradeModule: 1,
      OrderModule: 1,
      Signature: 1,
      ECDSAUpgradeable: 1,
      Strings: 1,
      MathUpgradeable: 1,
      Address: 2,
      SafeMathUpgradeable: 2,
      AddressUpgradeable: 2,
      SafeERC20Upgradeable: 2
    }
  },
  abstract: {
    total: 13,
    names: {
      StrategyBase: 1,
      StrategySushiFarmBase: 1,
      ReentrancyGuardUpgradeable: 1,
      ERC721Enumerable: 1,
      Ownable: 1,
      ERC165: 1,
      BaseStrategy: 1,
      Context: 2,
      ContextUpgradeable: 2,
      Initializable: 2
    }
  }
}
TOTAL FILES: 5
ERRORS: 1
   ────────────────────────────



cheers 🙌 
    @tintinweb 
    ConsenSys Diligence @ https://consensys.net/diligence/
    https://github.com/tintinweb/solgrep/ 

More Repositories

1

smart-contract-sanctuary

🐦🌴🌴🌴🦕 A home for ethereum smart contracts. 🏠
Python
1,423
star
2

solidity-shell

An interactive Solidity Shell
JavaScript
535
star
3

scapy-ssl_tls

SSL/TLS layers for scapy the interactive packet manipulation tool
Python
418
star
4

ecdsa-private-key-recovery

A simple library to recover the private key of ECDSA and DSA signatures sharing the same nonce k and therefore having identical signature parameter r
Python
384
star
5

electron-inject

Inject javascript into closed source electron applications e.g. to enable developer tools for debugging.
Python
296
star
6

ida-batch_decompile

*Decompile All the Things* - IDA Batch Decompile plugin and script for Hex-Ray's IDA Pro that adds the ability to batch decompile multiple files and their imports with additional annotations (xref, stack var size) to the pseudocode .c file
Python
265
star
7

pub

Vulnerability Notes, PoC Exploits and Write-Ups for security issues disclosed by tintinweb
Python
254
star
8

smart-contract-sanctuary-ethereum

🐦🌴🌴🌴🦕 A home for ethereum smart contracts. 🏠
251
star
9

ethereum-dasm

An ethereum evm bytecode disassembler and static/dynamic analysis tool
Python
212
star
10

smart-contract-inspector

the magic X-ray machine for solidity smart contracts
JavaScript
172
star
11

striptls

proxy poc implementation of STARTTLS stripping attacks
Python
167
star
12

vscode-interactive-graphviz

Interactive Graphviz Dot Preview for Visual Studio Code
TypeScript
145
star
13

vscode-decompiler

Decompile things directly from VSCode
Python
141
star
14

smart-contract-storage-viewer

🔆🔎👀 Smart Contract Storage Viewer, DataType Guesser, Toolbox & Transaction Decoder
JavaScript
99
star
15

smart-contract-sanctuary-bsc

🐦🌴🌴🌴🦕 A home for ethereum smart contracts. 🏠
75
star
16

smart-contract-vulndb

🍋 An open dataset containing smart contract audit issues from various sources.
JavaScript
63
star
17

ethereum-input-decoder

Decode transaction inputs based on the contract ABI
Python
59
star
18

bugbounty-companion

A BugBounty companion that checks out high-reward yielding bug bounty code-bases from Immunefi/code4rena 🙌 (use at own risk)
Python
55
star
19

vscode-vyper

Ethereum Vyper language support for Visual Studio Code
JavaScript
52
star
20

unbox

🎁 unbox - Unpack and Decompile the $h*! out of things
Python
48
star
21

vscode-inline-bookmarks

Customizable inline Bookmarks for Visual Studio Code
JavaScript
45
star
22

smart-contract-sanctuary-arbitrum

🐦🌴🌴🌴🦕 A home for ethereum smart contracts. 🏠
Solidity
43
star
23

pyetherchain

A python interface to the ethereum blockchain explorer at www.etherchain.org ❤⛓🐍
Python
42
star
24

hallucinate.sol

😵‍💫 A Recurrent Neural Network (RNN) hallucinating solidity source code.
Jupyter Notebook
38
star
25

smart-contract-sanctuary-polygon

🐦🌴🌴🌴🦕 A home for ethereum smart contracts. 🏠
37
star
26

DSAregenK

Recover the private key from signed DSA messages. (multiple signed messages, static coefficient 'k')
Python
35
star
27

smart-contract-sanctuary-optimism

🐦🌴🌴🌴🦕 A home for ethereum smart contracts. 🏠
Solidity
34
star
28

aggroArgs

Bruteforce commandline buffer overflows and automated exploit generation, linux, aggressive arguments
Python
33
star
29

evm-shell

An interactive EVM repl/shell.
JavaScript
30
star
30

smart-contract-sanctuary-avalanche

🐦🌴🌴🌴🦕 A home for ethereum smart contracts. 🏠
Solidity
26
star
31

sigbank

🏦 SigBank - A Database of Smart Contract Function Signatures
20
star
32

smart-contract-sanctuary-fantom

🐦🌴🌴🌴🦕 A home for ethereum smart contracts. 🏠
Solidity
19
star
33

vscode-ethereum-security-bundle

A meta-extension bundling marketplace plugins for secure Ethereum smart contract development.
19
star
34

smart-contract-sanctuary-tron

[Tron] 🐦🌴🌴🌴🦕 A home for ethereum smart contracts. 🏠
Solidity
16
star
35

vscode-circom-pro

👩‍💻 Circom compiler, snippets, hover and language support for Visual Studio Code
JavaScript
15
star
36

solidity-workspace

A simple workspace based interface to the solidity-parser and objectified Abstract Syntax Tree
JavaScript
14
star
37

solidity-doppelganger

JavaScript
13
star
38

solidity-ecdsa-malleability-demo

Solidity
12
star
39

scapy-ssh

ssh key exchange layer for scapy
Python
12
star
40

python-smtpd-tls

An extension to the standard python 2.x smtpd library implementing implicit/explicit SSL/TLS/STARTTLS
Python
11
star
41

heroku-eth-address-converter

Ethereum ENR ⇄ enode ⇄ MultiAddress converter heroku app
Python
11
star
42

smart-contract-sanctuary-celo

🐦🌴🌴🌴🦕 A home for ethereum smart contracts. 🏠
Solidity
10
star
43

solidity-metrics-action

📊 Generates Solidity Code Metrics Reports for Solidity Source Units in your Repository.
Dockerfile
10
star
44

aragraph

**Repo Moved** Easily generate permission graphs for Aragon DAO Templates
8
star
45

ssl_tls_socket_layers

ssl tls tcp udp layers for python sockets intended for messing with tls ssl protocol fields (fuzzing, exploitation, ...)
Python
7
star
46

IP_UDPFlood

General purpose IP src/dst network flooder
Python
6
star
47

vscode-solidity-language

Solidity Language Support, Syntax Highlighting, and Themes for VSCode - This is the standalone passive language support originally found in the Solidity Visual Developer extension
6
star
48

feedmon

monitor rss/atom feeds for some keywords
Python
4
star
49

tintinweb

4
star
50

EBNFSpill

Create Random Data based on EBNF Syntax description (EBNF parser: simpleparse)
Python
4
star
51

vscode-LLL

Ethereum LLL language support for Visual Studio Code
JavaScript
4
star
52

random-ssl-server

spawns a server listening for HTTPS (SSL) requests supplying random auto-generated certificates for each request. [HTTPS,SSL,Fuzzing,Testing,Resiliency]
Python
4
star
53

pymemscrape

A python-ctypes based process memory scraper that attempts to find key-material by matching template C structs in memory (OpenSSL ssl_session_st, dsa_st, rsa_st, bignum_st, ec_key_st, dh_st and generic ASN.1)
Python
4
star
54

openssl-version_scan

Scan Files and Processes for traces of static and shared OpenSSL libraries and display version information.
Python
4
star
55

vscode-solidity-flattener

Flatten Solidity Contracts using `truffle-flattener`
JavaScript
3
star
56

solcwrapper

Easily run any version of solc with solcwrapper. Automatically downloads/compiles/installs and transparently invokes officially released solc versions.
Python
3
star
57

DHCPv4v6

low-level scapy based dhcp client script (ipv4 ipv6)
Python
2
star
58

HashCollisioneer

checks a predefined list of names and hash-algorithms for collisions to find the best suiting hash-algorithm for some sample data
Python
1
star
59

heroku-vscode-downloader

A Simple Heroku WebApp to download vscode extensions for offline use
HTML
1
star