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

chevron-rightUse a linter, such as clippy, regularly during the development of a secure application.hashtag
  • Use rust clippyarrow-up-right which is a collection of lints to catch common mistakes and improve your Rust code.

    1. Install Rustuparrow-up-right. 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 rustfixarrow-up-right 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.

chevron-rightVerify all dependencies are up to date.hashtag
  • Use cargo auditarrow-up-right 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 outdatedarrow-up-right 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 updatearrow-up-right 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 Checklistarrow-up-right is a set of recommendations on how to design and present APIs for the Rust programming language.

  • Format strings using format!arrow-up-right

  • 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?

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

Input Validation

chevron-right[ ] Reentrancy: Calling external contracts gives them control over executionhashtag
chevron-right[ ] Forced AZERO Reception: Contracts can be forced to receive AZEROhashtag
    • [ ] 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)

chevron-right[ ] Insecure Oracle/Stale Price Feed - SVE1023hashtag

Output Encoding

chevron-right[ ] Race Condition: Frontrunning attackhashtag
chevron-right[ ] Unchecked External Callhashtag
    • [ ] 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

chevron-right[ ] Zero/Test Address Checkhashtag
chevron-right[ ] Missing Signer Check - SVE1001hashtag
    • [ ] 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

chevron-right[ ] Missing Owner Check - SVE1002hashtag
    • [ ] 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

chevron-right[ ] Unprotected Functionhashtag
    • [ ] 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

chevron-right[ ] Unencrypted Private Data On-Chainhashtag
    • [ ] 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

chevron-right[ ] UnverifiedParsedAccount - SVE1007hashtag
    • [ ] The account should be validated before parsing its data.

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

Authorization

chevron-right[ ] Denial of Servicehashtag
chevron-right[ ] Unprotected Token Withdrawalhashtag
    • [ ] 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

chevron-right[ ] Unprotected self destruction or burning instruction(s)hashtag
    • [ ] 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).

chevron-right[ ] Cross-Contract Call to Untrusted Calleehashtag
    • [ ] 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

chevron-right[ ] Authorization through use of Self.env()hashtag
chevron-right[ ] Signature Malleability: Valid signatures might be created by an attacker replaying previously signed messages.hashtag
    • [ ] 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

chevron-right[ ] Write to Arbitrary Storage Locationhashtag
    • [ ] 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

chevron-right[ ] Incorrect Trait Object Orderhashtag
chevron-right[ ] Insufficient Gas Griefinghashtag
chevron-right[ ] Hardcoded Sensitive Valueshashtag
chevron-right[ ] Bump Seed Not Validated - SVE1014hashtag
    • [ ] 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

chevron-right[ ] Weak Sources of Randomnesshashtag
chevron-right[ ] Missing Protection against Signature Replay Attackshashtag
chevron-right[ ] Lack of Proper Signature Verification and Data Authenticityhashtag

Numerics

chevron-right[ ] Integer overflow / underflowhashtag
    • [ ] 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

chevron-right[ ] Division by zero: Contracts go to panic mode when dividing by zerohashtag
    • [ ] 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:

chevron-right[ ] Be careful when you use the following patterns that may cause panics.hashtag
  • 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

chevron-right[ ] Incorrect Interfacehashtag
    • [ ] 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

chevron-right[ ] Wrong Constructor Namehashtag
chevron-right[ ] Variable Shadowinghashtag
    • [ ] 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)

chevron-right[ ] State Variable Default Visibilityhashtag
chevron-right[ ] Use of Uninitialized Storagehashtag
chevron-right[ ] Assert Violationhashtag
chevron-right[ ] Use of Deprecated Functionshashtag
    • [ ] Do not use the deprecated functions.

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

chevron-right[ ] Unhandled Revert: Use `revert` properlyhashtag
    • [ ] `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

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

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

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

Token Specific issues

chevron-right[ ] Token Race Conditions: A transaction-ordering attack or a front running attack.hashtag
    • [ ] 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)

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

chevron-right[ ] `transfer`, `transfer_from`, and `transfer_from_to`hashtag
    • [ ] `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

chevron-right[ ] `token_name`, `token_decimals`, and `token_symbol` functionshashtag
    • [ ] 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

chevron-right[ ] `token_decimals` returns proper u8.hashtag
    • [ ] 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

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

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

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

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

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

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

Testing

chevron-right[ ] Unit Testshashtag
chevron-right[ ] [cargo-fuzz](https://rust-fuzz.github.io/book/introduction.html)hashtag

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?

chevron-right[ ] Complete Documentationshashtag
chevron-right[ ] Setup a communication channel with the audit teamhashtag
    • [ ] Use a secure communication channel using end-to-end encryption.

chevron-right[ ] Code ready to be frozenhashtag
chevron-right[ ] Verify that the audit team can answer the following questionshashtag
chevron-right[ ] Commit Hashhashtag

Audit

Maintenance

Last updated

Was this helpful?