ink! Developers Security Guideline

This guide aims at supporting ink! developers who want to deploy their project on the Aleph Zero blockchain. It has been developed as part of the partnership between Aleph Zero and Kudelski Security.

Development Environment

  • Use Substrate multichain framework to build and deploy programs.

  • Use Ink! version 4. Check ink_lang version in Cargo.toml file.

  • Use a stable compilation toolchain.

  • Set the compiler flags debug-assertion and overflow-checks to true. These can be set in Cargo.toml for profile.release.

  • Use rustfmt formatter. Customize your guidelines by creating a rustfmt.toml in the root of you project and perform the following commands:

    cargo +nightly fmt \-- \--check
    cargo +nightly fmt
Use a linter, such as clippy, regularly during the development of a secure application.
  • Use rust clippy which is a collection of lints to catch common mistakes and improve your Rust code.

    1. Install Rustup. If you already have Rustup installed, update to ensure you have the latest Rustup and compiler:

    rustup update
    1. Install Clippy

    rustup component add clippy
    1. Run Clippy

    cargo clippy
    1. If necessary, fix Clippy suggestions automatically

    cargo clippy --fix
  • Use rustfix which reads and applies the suggestions made by rustc.

    1. Install rustfix

    cargo add rustfix
    cargo install cargo-fix
    cargo fix
    1. Open the rust files to manually verify the fixes.

Verify all dependencies are up to date.
  • Use cargo audit which audits your dependencies for crates with security vulnerabilities reported to the RustSec Advisory Database.

    1. Install cargo-audit

    cargo install cargo-audit
    1. Run cargo audit

    cargo audit
  • Use cargo outdated which displays when Rust dependencies are out of date.

    1. Install cargo-outdated

    cargo install --locked cargo-outdated
    1. Run cargo outdated

    cargo outdated
  • Use cargo update which updates dependencies as recorded in the local lock file.

    cargo update

Design

Ensure that the design documents of your smart contract contain the following components:

Threats/Risk assessment

While designing the smart contract, a threat assessment needs to be performed with the following five steps. A threat is an element which can hurt, harm, tamper with, or attack the smart contract.

  1. Context establishment

    • How will the project be used?

    • Who is the target audience?

  2. Threat assessment

    • This includes a list of all assets used in the project and their associated risks or threats

  3. Threat analysis & evaluation

    • Assets are classified by their risks/threats and their likelyhood.

  4. Mitigation treatment

    • What can be done to mitigate these risks/threats?

  5. Risk and control monitoring

    • Which operation can be done to conrol these risks/threats?

Conventions

  • Rust API Guidelines Checklist is a set of recommendations on how to design and present APIs for the Rust programming language.

  • Format strings using format!

  • Are the following elements using UpperCamelCase?

  • Are the following elements using snake_case?

  • Are the following elements using SCREAMING_SNAKE_CASE?

  • Is the following element using lowercase?

[ ] If one of the above boxes has not been checked, we strongly encourage to change your code to follow the recommended convention.

    For further conventions, see Rust API Guidelines Checklist.

Input Validation

[ ] Reentrancy: Calling external contracts gives them control over execution
[ ] Forced AZERO Reception: Contracts can be forced to receive AZERO
    • [ ] Avoid assuming how the balance of the contract increases, and implement a validation check to handle this type of edge cases.

    • https://github.com/crytic/not-so-smart-contracts/tree/master/forced_ether_reception (Solidity)

[ ] Insecure Oracle/Stale Price Feed - SVE1023

Output Encoding

[ ] Race Condition: Frontrunning attack
[ ] Unchecked External Call
    • [ ] Validate the result when making external calls, since operations/function calls/cross-contract calls silently fail.

    • https://github.com/crytic/not-so-smart-contracts/tree/master/unchecked_external_call (Solidity)

Authentication

[ ] Zero/Test Address Check
[ ] Missing Signer Check - SVE1001
    • [ ] If a function or asset should be available only to a restricted set of entities, you need to verify that the call has been signed by the appropriate entity.

    • https://github.com/project-serum/sealevel-attacks/tree/master/programs/0-signer-authorization

    • https://blog.neodyme.io/posts/solana_common_pitfalls/#missing-signer-check

[ ] Missing Owner Check - SVE1002
    • [ ] Your contract should trust accounts owned by itself. Check the owner and return an object of a trusted type.

    • https://github.com/project-serum/sealevel-attacks/tree/master/programs/2-owner-checks

    • https://blog.neodyme.io/posts/solana_common_pitfalls/#missing-ownership-check

[ ] Unprotected Function
    • [ ] Failure to use `#[ink(message)]` decorator may allow attacker to manipulate contract

    • https://github.com/crytic/not-so-smart-contracts/tree/master/unprotected_function

    • https://swcregistry.io/docs/SWC-100

[ ] Unencrypted Private Data On-Chain
    • [ ] Ensure that unencrypted private data is not stored in the contract code or state. In particular, items in the `#[ink(storage)]` section should not contain passwords, private keys, etc.

    • https://swcregistry.io/docs/SWC-136

[ ] UnverifiedParsedAccount - SVE1007
    • [ ] The account should be validated before parsing its data.

    • https://github.com/project-serum/sealevel-attacks/tree/master/programs/1-account-data-matching

Authorization

[ ] Denial of Service
[ ] Unprotected Token Withdrawal
    • [ ] Ensure that access controls are implemented so withdrawals can only be triggered by authorized parties or according to the specs of the smart contract system.

    • https://swcregistry.io/docs/SWC-105

[ ] Unprotected self destruction or burning instruction(s)
    • [ ] If the contract allows for removal of items from storage, these instructions should be properly authorized

    • https://swcregistry.io/docs/SWC-106 (Solidity)

    • https://github.com/Supercolony-net/openbrush-contracts/blob/main/examples/psp22_extensions/burnable/lib.rs (Burnable PSP22 contract).

[ ] Cross-Contract Call to Untrusted Callee
    • [ ] Use delegator call with caution and make sure to never call into untrusted contracts. If the target address is derived from user inputs, ensure to check it against a whitelist of trusted contracts.

    • https://swcregistry.io/docs/SWC-112

    • https://use.ink/basics/cross-contract-calling

[ ] Authorization through use of Self.env()
[ ] Signature Malleability: Valid signatures might be created by an attacker replaying previously signed messages.
    • [ ] Ensure that a signature is never included into a signed message hash to check if previously messages have been processed by the contract.

    • https://swcregistry.io/docs/SWC-117

    • https://eklitzke.org/bitcoin-transaction-malleability

[ ] Write to Arbitrary Storage Location
    • [ ] Ensure that writes to one data structure cannot inadvertently overwrite entries of another data structure.

    • https://use.ink/basics/storing-values

    • https://swcregistry.io/docs/SWC-124

[ ] Incorrect Trait Object Order
[ ] Insufficient Gas Griefing
[ ] Hardcoded Sensitive Values
[ ] Bump Seed Not Validated - SVE1014
    • [ ] The account's bump seed is not validated and may be vulnerable to seed canonicalization attacks.

    • https://github.com/project-serum/sealevel-attacks/tree/master/programs/7-bump-seed-canonicalization

Cryptography

[ ] Weak Sources of Randomness
[ ] Missing Protection against Signature Replay Attacks
[ ] Lack of Proper Signature Verification and Data Authenticity

Numerics

[ ] Integer overflow / underflow
    • [ ] If `doverflow-checks = false` in `Cargo.tolm` file please wrap arithmetic operations with safe math functions or validate all arithmetic to prevent overflows. * https://github.com/crytic/not-so-smart-contracts/tree/master/integer_overflow * https://swcregistry.io/docs/SWC-101 * https://medium.com/coinmonks/understanding-arithmetic-overflow-underflows-in-rust-and-solana-smart-contracts-9f3c9802dc45

[ ] Division by zero: Contracts go to panic mode when dividing by zero
    • [ ] Use a safe math function for division or validate the divisor not zero.

    • https://github.com/rust-lang/rust/issues/944

Memory management

When it comes to memory management, the following checks need to be done:

Error Handling

When it comes to memory management, the following checks need to be done:

[ ] Be careful when you use the following patterns that may cause panics.
  • using unwrap or expect,

  • using assert,

  • an unchecked access to an array,

  • integer overflow (in debug mode),

  • division by zero,

  • large allocations,

  • string formatting using format!.

Bad Programming practices

[ ] Incorrect Interface
    • [ ] A different type of interfaces are implemented, causing a different method ID to be created. For example, `Alice.set(uint)` takes an `uint` in Bob.rs but `Alice.set(int)` a `int` in Alice.rs. The two interfaces will produce two differents method IDs. As a result, Bob can call the fallback function of Alice rather than of `set`.

    • https://github.com/crytic/not-so-smart-contracts/tree/master/incorrect_interface

[ ] Wrong Constructor Name
[ ] Variable Shadowing
    • [ ] Don't name local variables identical to one in outer scope

    • https://github.com/crytic/not-so-smart-contracts/tree/master/variable%20shadowing (Solidity)

    • https://swcregistry.io/docs/SWC-119 (Solidity)

[ ] State Variable Default Visibility
[ ] Use of Uninitialized Storage
[ ] Assert Violation
[ ] Use of Deprecated Functions
    • [ ] Do not use the deprecated functions.

    • https://swcregistry.io/docs/SWC-111 (Solidity)

[ ] Unhandled Revert: Use `revert` properly
    • [ ] `if ... { return Err(Error::SomeError) }` should be used for `require` or `revert`. When a `Result::Err` is returned in ink!, then all state is reverted.

    • https://consensys.github.io/smart-contract-best-practices/development-recommendations/solidity-specific/assert-require-revert/ (Solidity)

    • https://use.ink/ink-vs-solidity#require-and-revert

[ ] DoS With Block Gas Limit: The cost of executing a function exceeds the block gas limit.
[ ] Presence of Unused Variables
[ ] Code with No Effects (Dead Code)
[ ] Account Reinitialization - SVE1013
[ ] Incorrect Calculation of Boundary Cases
    • [ ] Check the edge cases e.g. `>` instead of `>=`.

[ ] The contract is upgradeable.
    • [ ] Upgradeable contracts may change their rules over time.

[ ] The contract is pausable.
    • [ ] Having a way to pause your contract can help to limit the damage in case of attack or security breach.

Token Specific issues

[ ] Token Race Conditions: A transaction-ordering attack or a front running attack.
    • [ ] An attacker who is running a node can tell which transactions are going to occur before they are finalized. A race condition vulnerability occurs when code depends on the order of the transactions submitted to it.

    • https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/edit# (ERC20)

    • https://swcregistry.io/docs/SWC-114

    • https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 (Ethereum)

    • https://medium.com/coinmonks/solidity-transaction-ordering-attacks-1193a014884e (Solidity)

[ ] Lost Token Transfer - Revert on Fail
    • [ ] If a transfer fails, the function must throw an error and revert the transation, otherwise tokens will be lost by the sender.

[ ] `transfer`, `transfer_from`, and `transfer_from_to`
    • [ ] `transfer`, `transfer_from`, `transfer_from_to` return proper Result and Error message.

    • https://github.com/crytic/building-secure-contracts/blob/master/development-guidelines/token_integration.md#erc-conformity

[ ] `token_name`, `token_decimals`, and `token_symbol` functions
    • [ ] Must be present, if used. Optional functions in the standard.

    • https://github.com/crytic/building-secure-contracts/blob/master/development-guidelines/token_integration.md#erc-conformity

[ ] `token_decimals` returns proper u8.
    • [ ] Implemented tokens may incorrectly return a uint256, causing compatability issues

    • https://github.com/crytic/building-secure-contracts/blob/master/development-guidelines/token_integration.md#erc-conformity

[ ] The token has no external function call in transfer or transferFrom.
    • [ ] External calls in the transfer functions can lead to reentrancies.

[ ] The token only has one address.
    • [ ] Multiple addresses can result in mismatch in token supply, fees, rules, etc.

[ ] The token is not upgradeable.
    • [ ] Upgradeable contracts may change their rules over time, therefore provide justification into your documentation about the upgradeable function.

[ ] The owner has limited minting capabilities.
    • [ ] Malicious or compromised owners can abuse minting capabilities.

[ ] The token is not pausable.
    • [ ] Malicious or compromised owners can trap contracts relying on pausable tokens. Identify pausable code by hand.

[ ] The owner cannot blacklist the contract.
    • [ ] Malicious or compromised owners can trap contracts relying on tokens with a blacklist. Identify blacklisting features by hand.

Testing

[ ] Unit Tests
[ ] [cargo-fuzz](https://rust-fuzz.github.io/book/introduction.html)

Pre-Audit

This part aims to help preparing for a security audit which is necessary in order to achieve the best security possible. It is important to see an audit as a partnership between you and the company performing the audit. Therefore, it is important that you prepare some documents to the good functionning of audit.

Are the following elements ready?

[ ] Complete Documentations
[ ] Setup a communication channel with the audit team
    • [ ] Use a secure communication channel using end-to-end encryption.

[ ] Code ready to be frozen
[ ] Verify that the audit team can answer the following questions
[ ] Commit Hash

Audit

Maintenance

Last updated