Giter VIP home page Giter VIP logo

verified-smart-contracts's Introduction

Formally Verified Smart Contracts

This repository contains smart contracts that have been formally verified by Runtime Verification and/or collaborators.

To verify a smart contract, we need to first produce a formal specification stating what the smart contract is supposed to do. This is often the most difficult part of the verification effort, requiring sometimes several rounds of discussions and meetings with the owners of the smart contract, to ensure that everybody is on the same page regarding the intended functionality of the smart contract. Not surprisingly, many bugs or opportunities for improvement in the smart contract code are found at this early stage. Then we need to show that the binary or low-level code (e.g., EVM binary or IELE code) generated by the compiler from the smart contract high level code (e.g., Solidity or Vyper) indeed satisfies the specification. In our approach the proofs use reachability logic, a generalization of Hoare logic, separation logic and modal logic, and are performed using the K-framework. The K framework takes a formal semantics of a language as trusted input (e.g., that of EVM or IELE), and then uses it to symbolically execute the smart contract exhaustively on all paths, making use of SMT solvers like Z3 to solve the mathematical domain constraints.

List of Verified Smart Contracts

Resources

We use the K-framework and its verification infrastructure throughout the formal verification effort. All of the formal specifications are mechanized within the K-framework as well. Therefore, some background knowledge about the K-framework would be necessary for reading and fully understanding the formal specifications and reproducing the mechanized proofs. We refer the reader to the following resources for background knowledge about the K-framework and its verification infrastructure.

License

Copyrightable work in this repository is licensed by Runtime Verification, Inc. under the terms of The Reproducibility License 1.1.0, a restrictive license. That license is very readable, and you should read it. Most will want to pay special attention to its Reproducibility section.

Other parts of the proof toolchain, including the K-framework, are licensed under different, open source terms, like those of The University of Illinois/NCSA Open Source License.

Disclaimer

This repository does not constitute legal or investment advice. The preparers of this repository present it as an informational exercise documenting the due diligence involved in the secure development of the target contract only, and make no material claims or guarantees concerning the contract's operation post-deployment. The preparers of this repository assume no liability for any and all potential consequences of the deployment or use of this contract.

The formal verification results presented here only show that the target contract behaviors meet the formal (functional) specifications. Moreover, the correctness of the generated formal proofs assumes the correctness of the specifications and their refinement, the correctness of KEVM, the correctness of the K-framework's reachability logic theorem prover, and the correctness of the Z3 SMT solver. The presented result makes no guarantee about properties not specified in the formal specification. Importantly, the presented formal specification considers only the behaviors within the EVM, without considering the block/transaction level properties or off-chain behaviors, meaning that the verification result does not completely rule out the possibility of the contract being vulnerable to existing and/or unknown attacks.

Smart contracts are still a nascent software arena, and their deployment and public offering carries substantial risk. This repository makes no claims that its analysis is fully comprehensive, and recommends always seeking multiple opinions and audits.

This repository is also not comprehensive in scope, excluding a number of components critical to the correct operation of this system.

The possibility of human error in the manual review process is very real, and we recommend seeking multiple independent opinions on any claims which impact a large quantity of funds.

verified-smart-contracts's People

Contributors

anapantilie avatar anvacaru avatar bmmoore avatar daejunpark avatar denis-bogdanas avatar denisadiaconescu avatar dwightguth avatar ehildenb avatar eviefp avatar grosu avatar hacker-dom avatar iustines avatar kemitchell avatar ryanberryhill avatar tomtomjhj avatar yzhang90 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

verified-smart-contracts's Issues

todo for release

Must:

  • spec-tmpl.k => module-tmpl.k
  • rule-tmpl.k => spec-tmpl.k
  • rename *.ini spec files
  • fix spec generation command
  • fix spec running command
  • fix erc20 running script
  • fix bihu running script
  • fix abstract-semantics.k
  • fix lemmas.md tangler issue
  • fix Makefile
  • remove bak directory
  • add sum-to-n.md
  • add .PHONY target which allows to run the command even if accidently a file with the same name exists.
  • fix /erc20/README.md
  • drop edsl-notations.md and replace the links to it by kevm's one
  • fix the links in the end of /resources/edsl-spec.md
  • fix bihu report (two weeks time contracts)
  • rename all viper => vyper
  • fix "Viper" in erc20/vyper/vyper-erc20-spec.ini together with resources/lemmas.md

Optional:

  • fix hobby/spec-diff.patch
  • hobby erc20: explain approve function differences
  • vyper erc20: add LLL file
  • more explanation (why) for /resources/edsl-spec.md#program-specific-parameters
  • avoid duplication of proof running and kprove installation paragraphs
  • add collectToken loop spec (not trusted)
  • spec-gen: support 'import' instead of postfix convention
  • put prefix to collectToken spec.ini section names
  • cleanup bihu lemmas
  • cleanup lemmas, organize more
  • add ds-token spec
  • add consensys erc20 spec
  • fix pdf icon
  • prove both solc and remix compiled binaries
  • make verification.md for bihu
  • delete /resources/edsl-notations.md
  • consolidate verification methodology
  • delete scripts directory, moving gen-sepc.py to resources
  • move examples/sum-to-n
  • fix runtimeverification/evm-semantics#145 (comment)

Supported Solidity Versions?

I was hoping to verify some erc20 contracts written in solidity 0.5.0 using your tool, but was unable to find information about what versions of Solidity are supported. I performed a few tests myself, that yielded some odd results. Namely, I upgraded the zeppelin StandardToken to so it could be compiled with the Solidity 0.5.0 compiler. I then replaced the code section in the ini file with the bin-runtime received from the compiler. When I run make test (after cleaning and making again), a counterexample is found for the balanceOf spec rather than it being verified. A gist of my changes can be found here.

I therefore have 2 questions:

  1. What versions of the solidity language are supported by this project?
  2. If Solidity 0.5.0 is supported, do additional changes need to be made to the ini file (for example maybe the variable positions must change)?

Thanks in advance!

recompiling hkg standard token and runing proof produce different result

I would like to proof a simple erc20 token, and get error:

[Error] Critical: Z3 crashed on input query:
(declare-sort InternalOp)
(declare-sort K)
(declare-sort WordStack)
(declare-fun sizeWordStackAux (WordStack Int) Int)
(declare-fun sizeWordStack (WordStack) Int)
(declare-fun smt_keccak (WordStack) Int)
(declare-fun asByteStack (Int WordStack) WordStack)
(declare-fun chop (Int) Int)
(declare-fun smt_nthbyteof (Int Int Int) Int)
(declare-fun asWord (WordStack) Int)
(assert (forall ((|_784| Int)) (= (chop |_784|) (mod |_784|
115792089237316195423570985008687907853269984665640564039457584007913129639936))))
(assert (forall ((|_490| WordStack)(|_491| Int)) (= (>= (sizeWordStackAux
|_490| |_491|) 0) true)))
(declare-fun |_1215| () Int)
(declare-fun |R__432| () K)
(declare-fun |_1170| () Int)
(declare-fun |_1172| () Int)
(declare-fun |_1171| () Int)
(declare-fun |_3920| () K)
(declare-fun |_3922| () K)
(declare-fun |_3921| () InternalOp)
(assert (and (= (<= 0 |_1171|) true) (= (<= 0 |_1170|) true) (= (<= 0 |_1172|)
true) (= _3920 _3921) (= (< |_1172|
1461501637330902918203684832716283019655932542976) true) (= (<= 0 |_1215|)
true) (= (< |_1170| 1461501637330902918203684832716283019655932542976) true) (=
_3922 (smt_seq_elem |R__432|)) (= (< |_1215|
1461501637330902918203684832716283019655932542976) true) (= (< |_1171| 1024)
true)))
result:
(error "line 21 column 99: Sorts K and InternalOp are incompatible")
[Warning] Critical: missing SMTLib translation for Map:lookup (missing SMTLib
translation for Map:lookup)
[Warning] Critical: missing SMTLib translation for in_keys()_MAP (missing
SMTLib translation for in_keys()_MAP)

So I try to compile the sample.
I recompile the hkg standard token ( standardtoken.inlined.sol ) using remix (v0.4.19), the copy the bytes to hkg-erc20-spec.ini, and run
python3 resources/gen-spec.py erc20/module-tmpl.k erc20/spec-tmpl.k erc20/hkg/hkg-erc20-spec.ini totalSupply totalSupply > specs/hkg-erc20/totalSupply-spec.k

and run proof:
./kevm prove tests/proofs/specs/hkg-erc20/totalSupply-spec.k.

it output true originly, but this time it output somthing different( attached in the last). I am not sure if something goes wrong.

tmp.txt

Specifications for ERC721

I'm currently writing the specifications for ERC721 tokens. I've been able to specify: balanceOf, ownerOf, approve and getApproved. However, when trying to specify safeTransferFrom, I ran into issues and I'm now kinda stuck on them.

Specifically, I'm now focused on making safeTransferFrom works in the success cases (i'll do the failure afterwards). In the case where FROM_ID =/= TO_ID, everything works, but in the case where FROM_ID == TO_ID it does not work and I'm clueless about that.

Here is my gist of the specifications and the Solidity source code I used.

If someone can have a look and tell why it fails, it'll be greatly appreciated!

Compilation problems

org.kframework.utils.errorsystem.KEMException: [Error] Critical: Definition file doesn't exist: /home/qy/gituse/verified-smart-contracts/uniswap/.build/evm-semantics/./.build/defn/java/driver.k
at org.kframework.utils.errorsystem.KEMException.create(KEMException.java:110)
at org.kframework.utils.errorsystem.KEMException.criticalError(KEMException.java:35)
at org.kframework.kompile.KompileFrontEnd.run(KompileFrontEnd.java:64)
at org.kframework.main.FrontEnd.main(FrontEnd.java:59)
at org.kframework.main.Main.runApplication(Main.java:119)
at org.kframework.main.Main.runApplication(Main.java:108)
at org.kframework.main.Main.main(Main.java:54)

Cannot run program "stack"

I'm getting the error below when doing the following steps:

$ git clone https://github.com/runtimeverification/verified-smart-contracts
$ cd verified-smart-contracts/erc20/zeppelin
$ make

.....
[INFO] --- maven-antrun-plugin:1.7:run (build-haskell) @ haskell-backend ---
[INFO] Executing tasks

main:
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary:
[INFO] 
[INFO] K Framework Tool Parent ............................ SUCCESS [  0.170 s]
[INFO] K Framework KORE ................................... SUCCESS [ 17.425 s]
[INFO] K Framework Tool Kernel ............................ SUCCESS [  3.915 s]
[INFO] K Framework KTree .................................. SUCCESS [  0.065 s]
[INFO] K Framework Ocaml Backend .......................... SUCCESS [  0.366 s]
[INFO] K Framework Java Backend ........................... SUCCESS [  1.975 s]
[INFO] K Framework Haskell Backend ........................ FAILURE [  0.339 s]
[INFO] K Framework LLVM Backend ........................... SKIPPED
[INFO] K Framework Tool Distribution ...................... SKIPPED
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 24.829 s
[INFO] Finished at: 2019-02-06T09:30:35-08:00
[INFO] Final Memory: 66M/1446M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-antrun-plugin:1.7:run (build-haskell) on project haskell-backend: An Ant BuildException has occured: Execute failed: java.io.IOException: Cannot run program "stack" (in directory "/home/sbugrara/verified-smart-contracts/.build/k/haskell-backend/src/main/native/haskell-backend"): error=2, No such file or directory
[ERROR] around Ant part ...<exec failonerror="true" dir="/home/sbugrara/verified-smart-contracts/.build/k/haskell-backend/src/main/native/haskell-backend" executable="stack">... @ 4:150 in /home/sbugrara/verified-smart-contracts/.build/k/haskell-backend/target/antrun/build-main.xml
[ERROR] -> [Help 1]
[ERROR] 
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR] 
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
[ERROR] 
[ERROR] After correcting the problems, you can resume the build with the command
[ERROR]   mvn <goals> -rf :haskell-backend
../../resources/kprove.mak:78: recipe for target '/home/sbugrara/verified-smart-contracts/.build/k' failed
make: *** [/home/sbugrara/verified-smart-contracts/.build/k] Error 1
``

Cannot reproduce StandardToken.inlined.bytes

I followed the directions in the Solidity Source Code and Compiled EVM Bytecode section to try to reproduce the EVM bytecode for erc20/zeppelin/StandardToken.inlined.sol.

However, the bytecode in erc20/zeppelin/StandardToken.inlined.bytes is different than the bytecode that Remix is generating now. The verification seems to be failing on this latest Remix-generated bytecode. Specifically, there seems to be a code section at the beginning that is absent from erc20/zeppelin/StandardToken.inlined.bytes.

The screenshot below highlights this section that does not show up in StandardToken.inlined.bytes. How can I get Remix to generate the bytecode that would make the verification pass?

image

Use Local Memory Type Variable Instead of Global Storage Type Variable in Event to Save Gas

Hi, we recently have conducted a systematic study about Solidity event usage, evolution, and impact, and we are attempting to build a tool to improve the practice of Solidity event use based on our findings. We have tried our prototype tool on some of the most popular GitHub Solidity repositories, and for your repository, we find a potential optimization of gas consumption arisen from event use.

The point is that when we use emit operation to store the value of a certain variable, local memory type variable would be preferable to global storage type (state) variable if they hold the same value. The reason is that an extra SLOAD operation would be needed to access the variable if it is storage type, and the SLOAD operation costs 800 gas.

For your repository, we find that the following event use can be improved:

  • 13_hedg.sol
    function name:setOwner
    event name:  LogSetOwner
    variable:    owner->owner_
    function setOwner(address owner_)
        public
        auth
    {
        owner = owner_;
        emit LogSetOwner(owner);
    }

Do you find our results useful? Your reply and invaluable suggestions would be greatly appreciated, and are vital for improving our tool. Thanks a lot for your time!

Updated list of known security vulnerabilities in Wiki

It was using a strange format of links prefixed with org. Seems it was auto-generated, possibly by me in some weird Emacs mode. I switched to using Markdown-native links instead.

The table of contents can now be autogenerated in Emacs with markdown-toc-refresh-toc. But more importantly, it is now human-editable with fairly little effort, so it should be straightforward to add a new section and edit the TOC directly in Github.

However, in case I broke something, here is the list as it existed. Saving it here for posterity.

## Table of Contents

1.  [Integer Arithmetic](#org1f185e0)
2.  [Floating Point Arithmetic](#org70ac584)
3.  [Reentrancy](#orgf9d54a1)
4.  [Access Control](#org6d55064)
    1.  [Default Visibility](#orgcffc42f)
    2.  [Authentication With tx.origin](#org4fa2402)
    3.  [Signature Verification](#org1da8f97)
    4.  [Unprotected Functions](#org79b903b)
5.  [Code Injection via delegatecall](#org31d572b)
6.  [Signature Replay Attacks](#org9476f25)
7.  [Unchecked External Calls](#org79dacdb)
    1.  [Insufficient Gas Attacks](#orgfd8a738)
8.  [DOS](#org98ab01c)
    1.  [Unexpected Revert](#org774da42)
    2.  [Block Gas Limit](#org6e0b7cd)
    3.  [External Calls without Gas Stipends](#orgcd1de0d)
    4.  [Offline Owner](#org913efb1)
9.  [Entropy Illusion](#org52e4590)
10. [Privacy Illusion](#org740a808)
11. [Miner Attacks](#org4bcb8a6)
    1.  [Transaction Ordering](#orgf4807b1)
    2.  [Timestamp Manipulation](#orgc7639d9)
12. [Unexpected Ether](#orgaf213d5)
13. [External Contract Referencing](#orgc876f43)
14. [Uninitialized Storage Pointers](#orgfaaa9d9)
15. [Writes to Arbitrary Storage Locations](#org206eb61)
16. [Incorrect Interface](#org9c18b09)
17. [Arbitrary Jumps with Function Variables](#org31de46d)
18. [Variable Shadowing](#orgbdef312)
19. [Assert Violation](#org47d65a2)
20. [Dirty Higher Order Bits](#org308b871)
21. [Complex Modifiers](#org65a1628)
22. [Outdated Compiler](#org150ac0a)
23. [Use of Deprecated Solidity Functions](#org0fe4469)
24. [Function Selector Abuse](#function-selector-abuse)
25. [Experimental Language Features](#org0e436d6)
26. [Frontend (Off Chain) Attacks](#org3d4d9c2)
    1.  [Short Address Attack](#orge2bc80a)
27. [Historic Attacks](#org94754ed)
    1.  [Constructor Names](#orgfae98d5)
    2.  [Call Depth Attack](#org7700972)
    3.  [Constantinople Reentrancy](#org1cdbac3)
    4.  [Solidity Abi Encoder v2 Bug](#orgc992c1b)
28. Payable Multcall
29. [References](#orgdf00b55)

This page contains a comprehensive list of common smart contract security vulnerabilities, compiled from various sources. We use it as our reference list for security audits. In this page we only include basic information. Follow the links given in each section for more information.


<a id="org1f185e0"></a>

## Integer Arithmetic

Neither the EVM nor Solidity (before v0.8) provide builtin error reporting for arithmetic overflow/underflow. Consequently, applications need to check for these cases themselves. Furthermore, one cannot make the (seemingly reasonable) assumption that `x != -x`, because of [this case](https://gist.github.com/endorphin/b9d78601930922aea12ed3ce6a286576).

Note that since Solidity version 0.8, arithmetic operations revert on overflow and underflow. The developer can choose to bypass these checks by using the `unchecked` keyword, for example with `unchecked { x = a + b; }`

-   [Consensys Best Practices: Integer Overflow and Underflow](https://consensys.github.io/smart-contract-best-practices/known_attacks/#integer-overflow-and-underflow)
-   [DASP: Arithmetic Issues](https://www.dasp.co/#item-3)
-   [Sigmaprime: Arithmetic Over/Under Flows](https://blog.sigmaprime.io/solidity-security.html#ouflow)
-   [Solidity Documentation: Two's Complement / Underflows / Overflows](https://solidity.readthedocs.io/en/latest/security-considerations.html#two-s-complement-underflows-overflows)
-   [Solidity Documentation: Checked or Unchecked Arithmetic](https://docs.soliditylang.org/en/v0.8.9/control-structures.html?highlight=unchecked#checked-or-unchecked-arithmetic)
-   [SWC Registry: Integer Overflow and Underflow](https://smartcontractsecurity.github.io/swc-registry/docs/swc-101)
-   [Trail of Bits: Integer Overflow](https://github.com/crytic/not-so-smart-contracts/tree/master/integer_overflow)


<a id="org70ac584"></a>

## Floating Point Arithmetic

Fixed point numbers are not yet fully supported by solidity. User implementations may contain errors.

-   [Sigmaprime: Floating Points and Precision](https://blog.sigmaprime.io/solidity-security.html#precision)


<a id="orgf9d54a1"></a>

## Reentrancy

When a contract calls an external function, that external function may itself call the calling function. This can have unexpected effects. To prevent this sort of attack, a contract can implement a lock in storage that prevents re-entrant calls.

-   [Consensys Best Practices: Reentrancy](https://consensys.github.io/smart-contract-best-practices/known_attacks/#reentrancy)
-   [DASP: Reentrancy](https://www.dasp.co/#item-1)
-   [Sigmaprime: Reentrancy](https://blog.sigmaprime.io/solidity-security.html#reentrancy)
-   [Solidity Documentation: Reentrancy](https://solidity.readthedocs.io/en/latest/security-considerations.html#re-entrancy)
-   [SWC Registry: Reentrancy](https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-107)
-   [Trail of Bits: Reentrancy](https://github.com/crytic/not-so-smart-contracts/tree/master/reentrancy)


<a id="org6d55064"></a>

## Access Control

There are a number of common mistakes relating to access control.

-   [DASP: Access Control](https://www.dasp.co/#item-2)


<a id="orgcffc42f"></a>

#### Default Visibility

The default visibility for Solidity functions is `public`. Developers may forget to specify the visibility for a function that is intended to be private, leading to possible vulnerabilities.

-   [SWC Registry: State Variable Default Visibility](https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-108)
-   [SWC Registry: Function Default Visibility](https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-100)
-   [Sigmaprime: Default Visibilities](https://blog.sigmaprime.io/solidity-security.html#visibility)


<a id="org4fa2402"></a>

#### Authentication With tx.origin

Solidity has a global variable, `tx.origin`, which returns the address of the account that originally sent the call. Using this variable for authentication leaves the contract vulnerable to a phishing-like attack.

-   [Sigmaprime: tx.origin Authentication](https://blog.sigmaprime.io/solidity-security.html#tx-origin)
-   [SWC Registry: Authentication Through tx.origin](https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-115)
-   [Solidity Documentation: tx.origin](https://solidity.readthedocs.io/en/latest/security-considerations.html#tx-origin)


<a id="org1da8f97"></a>

#### Signature Verification

If a smart contract system implements its own signature verification scheme, it may contain vulnerabilities.

-   [SWC Registry: Lack of Proper Signature Verification](https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-122)


<a id="org79b903b"></a>

#### Unprotected Functions

Contracts may implement other (more complex) forms of access control themselves. Errors in this code can lead to functions that should be private being accessible by an attacker. In particular, one should always check that any `selfdestruct` calls and ether withdrawals can only be made by those who are intented to be able to.

-   [SWC Registry: Unprotected SELFDESTRUCT](https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-106)
-   [SWC Registry: Unprotected Ether Withdrawal](https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-105)
-   [Trail of Bits: Unprotected Functions](https://github.com/crytic/not-so-smart-contracts/tree/master/unprotected_function)


<a id="org31d572b"></a>

## Code Injection via delegatecall

Solidity allows calling external contracts via the `DELEGATECALL` opcode, which executes the code of an external contract in the persistent context of the present contract. Certain contracts perform `DELEGATECALL` calls using user-provided call data, which can effectively give full control to an attacker.

-   [Sigmaprime: delegatecall](https://blog.sigmaprime.io/solidity-security.html#delegatecall)
-   [SWC Registry: delegatecall to Untrusted Callee](https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-112)


<a id="org9476f25"></a>

## Signature Replay Attacks

If a smart contract system performs any sort of signature verification, it may be vulnerable to signature replay attacks. (Keep in mind that any signature sent to a contract via calldata will be publicly available.) Keeping track of processed signatures in storage is a simple way to prevent such attacks. Furthermore, in some cases, signatures may be malleable, i.e. an attacker may be able to modify them (so that they may be replayed) without destroying their validity.

-   [SWC Registry: Missing Protection Against Signature Replay Attacks](https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-121)
-   [SWC Registry: Signature Malleability](https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-117)


<a id="org79dacdb"></a>

## Unchecked External Calls

In Solidity, there are multiple ways to call an external contract and send ether. The function `transfer` reverts if the transfer fails. However, the functions `call` and `send` return false. Programmers may mistakenly expect `call` and `send` to revert, and fail to check for their return value.

-   [DASP: Unchecked Low Level Calls](https://www.dasp.co/#item-4)
-   [Sigmaprime: Unchecked CALL Return Values](https://blog.sigmaprime.io/solidity-security.html#unchecked-calls)
-   [Trail of Bits: Unchecked External Calls](https://github.com/crytic/not-so-smart-contracts/tree/master/unchecked_external_call)
-   [SWC Registry: Unchecked Call Return Value](https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-104)


<a id="orgfd8a738"></a>

#### Insufficient Gas Attacks

If a function makes a call to an external subroutine with `call`, an attacker may be able to cause the function to only partially execute by sending a (precise) insufficient amount of gas.

-   [Consensys Best Practices: Insufficient Gas Griefing](https://consensys.github.io/smart-contract-best-practices/known_attacks/#insufficient-gas-griefing)


<a id="org98ab01c"></a>

## DOS

This is a broad category of attacks where an attacker may render a contract inoperable, temporarily or permanently.

-   [DASP: Denial of Service](https://www.dasp.co/#item-5)
-   [Sigmaprime: Denial of Service](https://blog.sigmaprime.io/solidity-security.html#dos)
-   [Trail of Bits: Denial of Service](https://github.com/crytic/not-so-smart-contracts/tree/master/denial_of_service)


<a id="org774da42"></a>

#### Unexpected Revert

An attacker may be able to exploit the fact that `transfer` (alternatively `require(addr.send(amount))`) reverts on failure to prevent a function from ever completing execution.

-   [Consensys Best Practices: DOS with Unexpected Revert](https://consensys.github.io/smart-contract-best-practices/known_attacks/#dos-with-unexpected-revert)
-   [SWC Registry: DOS with Failed Call](https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-113)


<a id="org6e0b7cd"></a>

#### Block Gas Limit

In cases where the users of a system can manipulate how much computation (gas) is necessary for the execution of some function, it may be possible to DOS the system by causing the required gas to exceed the block gas limit. This is often the case in systems that loop over an array or mapping that can be enlarged by users at little cost.

-   [Consensys Best Practices: DOS with Block Gas Limit](https://consensys.github.io/smart-contract-best-practices/known_attacks/#dos-with-block-gas-limit)
-   [SWC Registry: DOS with Block Gas Limit](https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-128)
-   [Solidity Documentation: Gas Limit and Loops](https://solidity.readthedocs.io/en/latest/security-considerations.html#gas-limit-and-loops)


<a id="orgcd1de0d"></a>

#### External Calls without Gas Stipends

In some cases, developers may want to make a transfer and continue execution regardless of the result. One way to achieve this is with `call.value(v)()`, however this may allow the recipient to consume all the gas of the calling function, preventing execution from continuing. See example 1 here:

-   [Sigmaprime: Denial of Service](https://blog.sigmaprime.io/solidity-security.html#dos)


<a id="org913efb1"></a>

#### Offline Owner

Some systems may become inoperable if the owner or some other authority goes offline / loses their private key. This should be avoided.


<a id="org52e4590"></a>

## Entropy Illusion

The EVM does not have support for uncertainty/random number generation. Contracts may try to simulate uncertainty in a way that is in fact predictable and exploitable.

-   [DASP: Bad Randomness](https://www.dasp.co/#item-6)
-   [Sigmaprime: Entropy Illusion](https://blog.sigmaprime.io/solidity-security.html#entropy)
-   [Trail of Bits: Bad Randomness](https://github.com/crytic/not-so-smart-contracts/tree/master/bad_randomness)
-   [SWC Registry: Weak Sources of Randomness from Chain Attributes](https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-120)
-   [Solidity Documentation: Private Information and Randomness](https://solidity.readthedocs.io/en/latest/security-considerations.html#private-information-and-randomness)


<a id="org740a808"></a>

## Privacy Illusion

Developers may forget that everything on chain is public, and store private data in the open.


<a id="org4bcb8a6"></a>

## Miner Attacks


<a id="orgf4807b1"></a>

#### Transaction Ordering

Miners can see transactions for a short time before they get included in a block, and exploit this information. They can also alter the order of transactions within a block. Users also have some influence over this process by setting gas prices. This can often pose a security risk, especially in systems where users are bidding or otherwise competing for something.

-   [DASP: Front-Running](https://www.dasp.co/#item-7)
-   [Sigmaprime: Race Conditions / Front-Running](https://blog.sigmaprime.io/solidity-security.html#race-conditions)
-   [Consensys Best Practices: Front-Running](https://consensys.github.io/smart-contract-best-practices/known_attacks/#front-running-aka-transaction-ordering-dependence)
-   [Trail of Bits: Race Conditions](https://github.com/crytic/not-so-smart-contracts/tree/master/race_condition)
-   [SWC Registry: Transaction Order Dependence](https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-114)


<a id="orgc7639d9"></a>

#### Timestamp Manipulation

Many contracts use block timestamps for various purposes. Keep in mind that miners can slightly adjust them to their advantage.

-   [DASP: Time Manipulation](https://www.dasp.co/#item-8)
-   [Sigmaprime: Block Timestamp Manipulation](https://blog.sigmaprime.io/solidity-security.html#block-timestamp)
-   [Consensys Best Practices: Timestamp Dependence](https://consensys.github.io/smart-contract-best-practices/known_attacks/#timestamp-dependence)
-   [SWC Registry: Timestamp Dependence](https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-116)


<a id="orgaf213d5"></a>

## Unexpected Ether

Certain contracts behave erroneously when their account contains ether. It is always possible to forcibly send ether to a contract (without triggering its fallback function), using `selfdestruct`, or by mining to the account.

-   [Sigmaprime: Unexpected Ether](https://blog.sigmaprime.io/solidity-security.html#ether)
-   [Consensys Best Practices: Forcibly Sending Ether](https://consensys.github.io/smart-contract-best-practices/known_attacks/#forcibly-sending-ether-to-a-contract)
-   [Trail of Bits: Forced Ether Reception](https://github.com/crytic/not-so-smart-contracts/tree/master/forced_ether_reception)
-   [Solidity Documentation: Sending and Receiving Ether](https://solidity.readthedocs.io/en/latest/security-considerations.html#sending-and-receiving-ether)


<a id="orgc876f43"></a>

## External Contract Referencing

When a contract delegates some of its functionality to an external contract whose address is either inaccessible or subject to change, a benign implementation may be swapped out for a malicious one.

-   [Sigmaprime: External Contract Referencing](https://blog.sigmaprime.io/solidity-security.html#contract-reference)


<a id="orgfaaa9d9"></a>

## Uninitialized Storage Pointers

Local variables in solidity functions default to `storage` or `memory` depending on their type. Uninitialized local storage variables can point to unexpected storage locations in the contract, leading to intentional or unintentional vulnerabilities.

-   [Sigmaprime: Uninitialized Storage Pointers](https://blog.sigmaprime.io/solidity-security.html#storage)
-   [SWC Registry: Uninitialized Storage Pointer](https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-109)


<a id="org206eb61"></a>

## Writes to Arbitrary Storage Locations

In general, writes to arbitrary storage locations should be avoided. This can occur, for example, if a storage array is written to at an index specified by a user.

-   [SWC Registry: Write to Arbitrary Storage Location](https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-124)


<a id="org9c18b09"></a>

## Incorrect Interface

Typos or mistakes in the type signature of a function can lead to the fallback function being called instead.

-   [Trail of Bits: Incorrect Interfaces](https://github.com/crytic/not-so-smart-contracts/tree/master/incorrect_interface)


<a id="org31de46d"></a>

## Arbitrary Jumps with Function Variables

If a contract uses function variables, an attacker may be able to manipulate a function variable to point to an unexpected location.

-   [SWC Registry: Arbitrary Jump with Function Type Variable](https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-127)


<a id="orgbdef312"></a>

## Variable Shadowing

If multiple variables with the same name are declared in different scopes, there may be unintended effects. This is easy to miss in the case where a contract inherits from a contract implemented in a separate file.

-   [Trail of Bits: Variable Shadowing](https://github.com/crytic/not-so-smart-contracts/tree/master/variable%20shadowing)
-   [SWC Registry: Incorrect Inheritance Order](https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-125)
-   [SWC Registry: Shadowing State Variables](https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-119)


<a id="org47d65a2"></a>

## Assert Violation

Properly functioning code should never violate an `assert` statement. This can occur if developers mistakenly use `assert` instead of `require`.

-   [SWC Registry: Assert Violation](https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-110)
-   [SWC Registry: Requirement Violation](https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-123)
-   [Solidity Documentation: Error Handling](https://solidity.readthedocs.io/en/latest/control-structures.html?highlight=assert#error-handling-assert-require-revert-and-exceptions)


<a id="org308b871"></a>

## Dirty Higher Order Bits

If `keccak256(msg.data)` or some similar hash functionality is used (for example to log past calls), be aware that functions of types that don't occupy 32 bytes may be called with identical arguments but different hashes.

-   [Solidity Documentation: Minor Details](https://solidity.readthedocs.io/en/latest/security-considerations.html#minor-details)


<a id="org65a1628"></a>

## Complex Modifiers

Use modifiers only for input validation with `require`. Modifiers should not contain any substantive logic, because that logic will be executed before any input validation done at the start of function bodies.

-   [Consensys Best Practices: Use Modifiers Only for Assertions](https://consensys.github.io/smart-contract-best-practices/recommendations/#use-modifiers-only-for-assertions)


<a id="org150ac0a"></a>

## Outdated Compiler

Never use a compiler version that is significantly out of date. Implementations should specify an exact compiler version with `pragma`.

-   [SWC Registry: Outdated Compiler](https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-102)
-   [SWC Registry: Floating Pragma](https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-103)


<a id="org0fe4469"></a>

## Use of Deprecated Solidity Functions

Avoid the use of deprecated solidity functions.

-   [SWC Registry: Use of Deprecated Solidity Functions](https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-111)

<a id="function-selector-abuse"></a>

## Function Selector Abuse

To call a function on another contract, the standard ABI way to do so is to pass as calldata a function "selector", followed by the encoded arguments. You can read more [here](https://docs.soliditylang.org/en/v0.8.7/abi-spec.html), but a short example follows.

In solidity, a call may look like `otherContract.foo("hello")`, but in reality, the call becomes `address(otherContract).call(abi.encodeWithSignature("foo(string)", "hello"))` which in practice becomes

0xf31a69690000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000568656c6c6f000000000000000000000000000000000000000000000000000000


The first 4 bytes `0xf31a6969`, are called the function selector, and consist of the first 4 bytes of the Keccak256 hash of the string "foo(string)". All ABI-compliant contracts on Ethereum begin by looking at these bytes of the calldata and jump to the corresponding function body.

If a contract performs a call to an external contract, and the user can influence *any* part of the method signature (such as the function name, or its type), they can call *any* function on the external contract, simply by manipulating the string until a selector matching the desired one is found.

This was behind the Poly Network hack in August 2021, where an attacker crafted messages on one chain which got processed on another chain. The contracts assumed well-behaved transactions, and the attacker managed to trick the contracts into calling privileged functions on yet other contracts. https://twitter.com/kelvinfichter/status/1425217056660721666

<a id="org0e436d6"></a>

## Experimental Language Features

Avoid experimental language features, as these are not properly tested and have contained [vulnerabilities](https://blog.ethereum.org/2019/03/26/solidity-optimizer-and-abiencoderv2-bug/) in the past.


<a id="org3d4d9c2"></a>

## Constructor call

## Frontend (Off Chain) Attacks

These are possible vulnerabilities in frontends to ethereum contracts, not vulnerabilities in the contracts themselves. (Possibly out of scope.)


<a id="orge2bc80a"></a>

#### Short Address Attack

Frontends should validate any input used to make transactions on chain.

-   [Sigmaprime: Short Address / Parameter Attack](https://blog.sigmaprime.io/solidity-security.html#short-address)
-   [DASP: Short Address Attack](https://www.dasp.co/#item-9)


<a id="org94754ed"></a>

## Historic Attacks


<a id="orgfae98d5"></a>

#### Constructor Names

Fixed in solidity `v0.4.22`

-   [Sigmaprime: Constructors with Care](https://blog.sigmaprime.io/solidity-security.html#constructors)
-   [Trail of Bits: Wrong Constructor Name](https://github.com/crytic/not-so-smart-contracts/tree/master/wrong_constructor_name)
-   [SWC Registry: Incorrect Constructor Name](https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-118)


<a id="org7700972"></a>

#### Call Depth Attack

Fixed in [EIP 150](https://github.com/ethereum/EIPs/issues/150)

-   [Consensys Best Practices: Call Depth Attack](https://consensys.github.io/smart-contract-best-practices/known_attacks/#call-depth-attack-deprecated)
-   [Solidity Documentation: Callstack Depth](https://solidity.readthedocs.io/en/latest/security-considerations.html#callstack-depth)


<a id="org1cdbac3"></a>

#### Constantinople Reentrancy

-   [Consensys Best Practices: Constantinople Reentrancy Attack](https://consensys.github.io/smart-contract-best-practices/known_attacks/#constantinople-reentrancy-attack)


<a id="orgc992c1b"></a>

#### Solidity Abi Encoder v2 Bug

Fixed in solidity `v0.5.7`

-   [Ethereum.org Blog](https://blog.ethereum.org/2019/03/26/solidity-optimizer-and-abiencoderv2-bug/)

## Payable Multicall

This is present when Multicall is used on any contract which reads the value of `msg.value`.
Multicall is a pattern to call several contract endpoints in one transaction, using `delegatecall`.
A contract endpoint may implicitly assume that it is called in a single transaction, by looking at `msg.value`.
Since the value is defined per transaction, calling the same endpoint twice in one multicall means that the same `msg.value` may be read several times, even though the value was only transferred once.

For example, if a token contract accepts ETH in exchange for tokens in a `swap` function, and the contract implements multicall, an attacker may call swap several times in one transaction.
Let's say the attacker sends along 1 ETH in the multicall transaction, which would normally give them 100 tokens.
Each call to the `swap` function will read `msg.value` and transfer 100 tokens to the attacker.
If the attacker calls `swap` 10 times in one multicall, they will get 1,000 tokens in exchange for 1 ETH.

-   [Uniswap v3 issue](https://github.com/Uniswap/v3-periphery/issues/52)

<a id="orgdf00b55"></a>

## References

-   [DASP Top 10](https://www.dasp.co/)
-   [Sigmaprime Solidity Security](https://blog.sigmaprime.io/solidity-security.html)
-   [Consensys Best Practices](https://consensys.github.io/smart-contract-best-practices/known_attacks/)
-   [Trail of Bits "Not So Smart Contracts"](https://github.com/trailofbits/not-so-smart-contracts)
-   [SWC Registry](https://smartcontractsecurity.github.io/SWC-registry/)
-   [Solidity Documentation: Security Considerations](https://solidity.readthedocs.io/en/latest/security-considerations.html)
-   [Ethereum Wiki: Safety](https://github.com/ethereum/wiki/wiki/Safety)
-   [Trail of Bits Reference List](https://github.com/crytic/awesome-ethereum-security)

makfile problem

I want to reproduce the result of "uniswap", but makfile is wrong in two place:
1、cd /home/qy/gituse/new_gituse/verified-smart-contracts/uniswap/.build/evm-semantics
&& git fetch
&& git clean -fdx
&& git reset --hard 81bcba1a73188942fdc34979c59ee7be7253ece9
&& make tangle-deps
&& make defn
&& /home/qy/gituse/new_gituse/verified-smart-contracts/uniswap/.build/k/k-distribution/target/release/k/bin/kompile -v --debug --backend java -I .build/defn/java -d .build/defn/java --main-module ETHEREUM-SIMULATION --syntax-module ETHEREUM-SIMULATION .build/defn/java/driver.k

however, There is no .build/defn

2、make: Entering directory '/home/qy/gituse/new_gituse/verified-smart-contracts/uniswap'
/home/qy/gituse/new_gituse/verified-smart-contracts/uniswap/.build/k/k-distribution/target/release/k/bin/kprove -v --debug -d /home/qy/gituse/new_gituse/verified-smart-contracts/uniswap/.build/evm-semantics/.build/defn/java -m VERIFICATION --z3-impl-timeout 500 --shutdown-wait-time 5s --deterministic-functions --no-exc-wrap --cache-func-optimized --no-alpha-renaming --format-failures --boundary-cells k,pc --log-cells k,output,statusCode,localMem,pc,gas,wordStack,callData,accounts,memoryUsed,#pc,#result /home/qy/gituse/new_gituse/verified-smart-contracts/specs/uniswap/uniswap/addLiquidity-1-spec.k
com.beust.jcommander.ParameterException: "--shutdown-wait-time": couldn't convert "5s" to an integer

You don't even know how your program calls ? it should be "5", not "5s"

Kompiled definition is out of date

I'm getting the following error on Ubuntu 16.04 and JDK 1.8.0_201. Am I missing a step?

$ git clone https://github.com/runtimeverification/verified-smart-contracts
$ cd verified-smart-contracts/erc20/zeppelin
$ make
$ cd ../..
$ .build/evm-semantics/kevm prove specs/zeppelin-erc20/transfer-success-1-spec.k 
[Error] Critical: Kompiled definition is out of date with the latest version of
the K tool. Please re-run kompile and try again.
(org.kframework.kompile.KompileOptions; local class incompatible: stream
classdesc serialVersionUID = -406465945127669488, local class serialVersionUID
= -5178178340715675055)

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.