Home

Awesome

Semgrep rules for smart contracts

In this repository you can find semgrep rules that look for patterns of vulnerabilities in smart contracts based on actual DeFi exploits as well as gas optimization rules that can be used as a part of the CI pipeline. The rules are part of the semgrep registry under p/smart-contracts.

Disclaimer

Currently semgrep supports Solidity in experimental mode. Some of the rules may not work until Solidity is in beta at least.

Scanning

Important: Some of the rules utilize the taint mode, which is restricted to the same function in the open-source version of semgrep. To take advantage of intra-procedural taint analysis, you must include the --pro flag with each command. Please note that this requires semgrep Pro.

  1. By cloning the repository:
$ semgrep --config solidity/security path/to/your/project
  1. By using semgrep registry:
$ semgrep --config p/smart-contracts path/to/your/project
  1. In your CI:

Create run-semgrep.yaml in .github/workflows with the following contents:

<details> <summary>run-semgrep.yaml</summary>
# Name of this GitHub Actions workflow.
name: Run Semgrep

on:
  # Scan changed files in PRs (diff-aware scanning):
  pull_request: {}
  # On-demand 
  workflow_dispatch: {}

jobs:
  semgrep:
    # User-definable name of this GitHub Actions job:
    name: Scan
    # If you are self-hosting, change the following `runs-on` value: 
    runs-on: ubuntu-latest

    container:
      # A Docker image with Semgrep installed. Do not change this.
      image: returntocorp/semgrep

    # Skip any PR created by dependabot to avoid permission issues:
    if: (github.actor != 'dependabot[bot]')

    steps:
      # Fetch project source with GitHub Actions Checkout.
      - uses: actions/checkout@v3
      # Fetch semgrep rules
      - name: Fetch semgrep rules
        uses: actions/checkout@v3
        with:
          repository: decurity/semgrep-smart-contracts
          path: rules
      # Run security and gas optimization rules
      - run: semgrep ci --sarif --output=semgrep.sarif || true
        env:
           SEMGREP_RULES: rules/solidity/security rules/solidity/performance
      # Upload findings to GitHub Advanced Security Dashboard
      - name: Upload findings to GitHub Advanced Security Dashboard
        uses: github/codeql-action/upload-sarif@v2
        with:
          sarif_file: semgrep.sarif
        if: always()
</details>

Testing

Each rule is accompanied by an actual vulnerable source code that was targeted by an exploit. Vulnerable lines are marked with // ruleid: ...

In case a rule is not yet supported by semgrep, you will find // todoruleid: ...

Run tests:

$ semgrep --test solidity

Validate rules:

$ semgrep --validate --config solidity

Feel free to submit any issues with the precision and quality of the rules!

Security Rules

Rule IDTargetsDescription
compound-borrowfresh-reentrancyCompound, Ola Finance, Hundred Finance, AgaveFunction borrowFresh() in Compound performs state update after doTransferOut()
compound-sweeptoken-not-restrictedTUSD, CompoundFunction sweepToken is allowed to be called by anyone
erc20-public-transferCreat FutureCustom ERC20 implementation exposes _transfer() as public
erc20-public-burnHospoWiseAnyone can burn tokens of other accounts
erc677-reentrancyOla FinanceERC677 callAfterTransfer() reentrancy
erc777-reentrancyBacon ProtocolERC777 tokensReceived() reentrancy
erc721-reentrancyHype BearsERC721 onERC721Received() reentrancy
erc721-arbitrary-transferfromDistortion GenesisCustom ERC721 implementation lacks access control checks in _transfer()
gearbox-tokens-path-confusionGearboxUniswapV3 adapter implemented incorrect extraction of path parameters
keeper-network-oracle-manipulationInverse FinanceKeep3rV2.current() call has high data freshness, but it has low security, an exploiter simply needs to manipulate 2 data points to be able to impact the feed.
basic-oracle-manipulationOnering Finance, Deus FinancegetSharePrice() can be manipulated via flashloan
redacted-cartel-custom-approval-bugRedacted CarteltransferFrom() can steal allowance of other accounts
rigoblock-missing-access-controlRigoBlocksetMultipleAllowances() is missing onlyOwner modifier
oracle-price-update-not-restrictedRikkei Finance, AaveOracle price data can be submitted by anyone
superfluid-ctx-injectionSuperfluidA specially crafted calldata may be used to impersonate other accounts
tecra-coin-burnfrom-bugTecra CoinParameter "from" is checked at incorrect position in "_allowances" mapping
arbitrary-low-level-callAuctus Options, Starstream Finance, BasketDAO, Li FinanceAn attacker may perform call() to an arbitrary address with controlled calldata
sense-missing-oracle-access-controlSense FinanceOracle update is not restricted in onSwap(), rule by Arbaz Kiraak
proxy-storage-collisionAudiusProxy declares a state var that may override a storage slot of the implementation
uniswap-callback-not-protectedGenericUniswap callback is not protected
encode-packed-collisionGenericHash collision with variable length arguments in abi.encodePacked
openzeppelin-ecdsa-recover-malleableOpenZeppelinPotential signature malleability
BETA: basic-arithmetic-underflowUmbrella Network, Remittance TokenPossible arithmetic underflow
unrestricted-transferownershipRagnarok Online InvasionContract ownership can be transfered by anyone
msg-value-multicallSushiswapFunction with constant msg.value can be called multiple times
no-bidi-charactersGenericThe code must not contain any of Unicode Direction Control Characters
delegatecall-to-arbitrary-addressGenericAn attacker may perform delegatecall() to an arbitrary address.
incorrect-use-of-blockhashGenericblockhash(block.number) and blockhash(block.number + N) always returns 0.
accessible-selfdestructGenericContract can be destructed by anyone in $FUNC
no-slippage-checkGenericNo slippage check in a Uniswap v2/v3 trade
balancer-readonly-reentrancy-getrateBalancergetRate() call on a Balancer pool is not protected from the read-only reentrancy.
balancer-readonly-reentrancy-getpooltokensBalancergetPoolTokens() call on a Balancer pool is not protected from the read-only reentrancy.
curve-readonly-reentrancyCurveget_virtual_price() call on a Curve pool is not protected from the read-only reentrancy.
public-transfer-fees-supporting-tax-tokensLeetSwappublic _transferFeesSupportingTaxTokens() without any modificators
olympus-dao-staking-incorrect-call-orderOlympusDAO, FloorDAO, Heavens Gate, Jump Farm, QuantumWNThe order of calling the transferFrom() and rebase() functions is incorrect in Olympus DAO forks
compound-precision-lossHundred Finance, Midas Finance, Onyx ProtocolIn Compound forks if there is a market with totalSupply = 0 and collateralFactor != 0 a precision loss attack is possible if redeemAmount is taken from the arguments of redeemFresh()
thirdweb-vulnerabilitySwopple Token, TIME Token, NAME Token, HXA TokenIn contracts that support Multicall and ERC2771Context an Arbitrary Address Spoofing attack is possible
exact-balance-checkGenericTesting the balance of an account as a basis for some action has risks associated with unexpected receipt of ether or another token, including tokens deliberately transfered to cause such tests to fail, as an MEV attack.
missing-assignmentGenericMeaningless statement that does not change any values could be a sign of missed security checks or other important changes.
oracle-uses-curve-spot-priceUwUOracle uses the get_p() Curve pool function which can be manipulated via flashloan to calculate the asset price
bad-transferfrom-access-controlGenericFunds approved by users can be stolen because of improper access control to a transferFrom function

Gas Optimization Rules

Rule IDDescription
array-length-outside-loopCaching the array length outside a loop saves reading it on each iteration, as long as the array's length is not changed during the loop.
init-variables-with-default-valueExplicitly initializing a variable with its default value costs unnecessary gas.
state-variable-read-in-a-loopReplace state variable reads and writes within loops with local variable reads and writes.
unnecessary-checked-arithmetic-in-loopA lot of times there is no risk that the loop counter can overflow. Using Solidity's unchecked block saves the overflow checks.
use-custom-error-not-requireConsider using custom errors as they are more gas efficient while allowing developers to describe the error in detail using NatSpec.
use-multiple-requireUsing multiple require statements is cheaper than using && multiple check combinations.
use-nested-ifUsing nested is cheaper than using && multiple check combinations.
use-prefix-decrement-not-postfixThe prefix decrement expression is cheaper in terms of gas.
use-prefix-increment-not-postfixThe prefix increment expression is cheaper in terms of gas.
use-short-revert-stringShortening revert strings to fit in 32 bytes will decrease gas costs for deployment and gas costs when the revert condition has been met.
non-payable-constructorConsider making costructor payable to save gas.
non-optimal-variables-swapConsider swapping variables using ($VAR1, $VAR2) = ($VAR2, $VAR1) to save gas.
inefficient-state-variable-increment<x> += <y> costs more gas than <x> = <x> + <y> for state variables.

Best Practices Rules

Rule IDDescription
use-abi-encodecall-instead-of-encodewithselectorTo guarantee arguments type safety it is recommended to use abi.encodeCall instead of abi.encodeWithSelector.
use-ownable2stepBy demanding that the receiver of the owner permissions actively accept via a contract call of its own, Ownable2Step and Ownable2StepUpgradeable prevent the contract ownership from accidentally being transferred to an address that cannot handle it.

Solana Rules

Rule IDDescription
solana-arbitrary-program-callAn attacker may be able to invoke arbitrary programs without address validations
solana-insecure-account-closingWriting the CLOSED_ACCOUNT_DISCRIMINATOR to a closed account is crucial to prevent the reuse of the account within the same transaction

Cairo Rules

Rule IDDescription
lack-of-error-messageError message is missing in the assert statement
tx-origin-authenticationUsing account_contract_address for authentication is insecure. Use get_caller_address or an appropriate method for verifying users.
view-fn-mutable-stateView function should not be able to modify state
view-fn-writesView function should not write to the state
zero-divisionPossible division by zero