Search
⌃K

ink! Developers Security Guideline

This guideline aims at supporting ink! developers who want to deploy their project on the Aleph Zero Blockchain. This guideline has been developed as part of the partnership between Aleph Zero and Kud

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. 1.
      Install Rustup. If you already have Rustup installed, update to ensure you have the latest Rustup and compiler:
    rustup update
    1. 2.
      Install Clippy
    rustup component add clippy
    1. 3.
      Run Clippy
    cargo clippy
    1. 4.
      If necessary, fix Clippy suggestions automatically
    cargo clippy --fix
  • Use rustfix which reads and applies the suggestions made by rustc.
    1. 1.
      Install rustfix
    cargo add rustfix
    cargo install cargo-fix
    cargo fix
    1. 2.
      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. 1.
      Install cargo-audit
    cargo install cargo-audit
    1. 2.
      Run cargo audit
    cargo audit
  • Use cargo outdated which displays when Rust dependencies are out of date.
    1. 1.
      Install cargo-outdated
    cargo install --locked cargo-outdated
    1. 2.
      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:
  • Architecture diagrams with all global state variables.
  • Code documentation:
  • We strongly ncourage developers to update the document as written in the code.
  • We also encourage to include a set up guideline and simple use case examples.

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. 1.
    Context establishment
    • How will the project be used?
    • Who is the target audience?
  2. 2.
    Threat assessment
    • This includes a list of all assets used in the project and their associated risks or threats
  3. 3.
    Threat analysis & evaluation
    • Assets are classified by their risks/threats and their likelyhood.
  4. 4.
    Mitigation treatment
    • What can be done to mitigate these risks/threats?
  5. 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?
    • Types
    • Traits
    • Enum variants
  • Are the following elements using snake_case?
    • Functions
    • Macros
    • Variables
    • Modules
  • Are the following elements using SCREAMING_SNAKE_CASE?
    • Statics
    • Constants
  • Is the following element using lowercase?
    • Lifetimes
[ ] If one of the above boxes has not been checked, we strongly encourage to change your code to follow the recommended convention.
    • [ ] Ad-hoc conversions follow as_, to_, into_ conventions ([C-CONV](https://rust-lang.github.io/api-guidelines/naming.html#c-conv))
    • Getter names follow Rust convention (C-GETTER)
    • Methods on collections that produce iterators follow iter, iter_mut, into_iter (C-ITER)
    • Iterator type names match the methods that produce them (C-ITER-TY)
    • Feature names are free of placeholder words (C-FEATURE)
    • Names use a consistent word order (C-WORD-ORDER)
    For further conventions, see Rust API Guidelines Checklist.

Input Validation

[ ] Reentrancy: Calling external contracts gives them control over execution
    • [ ] A malicious contract calls back into the calling contract before the first invocation of the function is finished.
    • Make sure all internal state changes are performed before the call is executed.
    • Use a reentrancy lock function if available.
    • https://github.com/crytic/not-so-smart-contracts/tree/master/reentrancy
    • https://swcregistry.io/docs/SWC-107
[ ] 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
    • [ ] Use the latest oracle API
    • Be aware the risk of oracle manipulation attack.
    • https://blog.solend.fi/response-to-solana-network-issues-5c8184607283 (Solana).

Output Encoding

[ ] Race Condition: Frontrunning attack
    • [ ] There is a gap between the creation of a transaction and the moment it is accepted in the blockchain. Therefore, an attacker can take advantage of this gap to put a contract in a state that advantages them.
    • Be aware that all transactions may be front-run.
    • https://github.com/crytic/not-so-smart-contracts/tree/master/race_condition
[ ] 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
    • [ ] Contract ensures that each provided address is not zero or one of the default test accounts (e.g. Bob, Alice) because zero address public key has a known private key in the sr25519 and ed25519.
    • Use the ink! v4.4.0-rc or higher version where the default implementation for AccountIds by zero has been removed.
    • Tests against testnet allow the use of Zero address, but must be specified.
    • https://substrate.stackexchange.com/questions/982/why-does-the-all-0-public-key-have-a-known-private-key-in-sr25519-and-ed25519
[ ] 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
    • [ ] Be aware that an attacker can stall contract execution by failing in a strategic way. In particular, contracts that bulk perform transactions or updates using a loop can be DoS'd if a call to another contract or transfer fails during the loop.
    • If iterating over a dynamically sized data structure, be able to handle the case where the function takes multiple blocks to execute. One strategy for this is storing iterator in a private variable and using while loop that exists when gas drops below certain threshold.
    • https://github.com/crytic/not-so-smart-contracts/tree/master/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()
    • [ ] Authorization checks by `Self.env().caller()` should validate the contract-only controllable values.
    • Ensure that the use of Self.env().caller() does not allow for manipulating sensitive values.
    • https://swcregistry.io/docs/SWC-115 (Solidity)
    • https://blog.neodyme.io/posts/solana_common_pitfalls/#solana-account-confusions (Solana)
[ ] 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
    • [ ] Through the *#[ink::trait_definition]* [ ] proc. macro, your own trait definitions are implementable by ink! smart contracts. This allows to define shared smart contract interfaces to different concrete implementations.
    • When defining shared smart contracts, you should carefully specify the trait definitions in the correct order.
    • https://use.ink/basics/trait-definitions
    • https://swcregistry.io/docs/SWC-125
[ ] Insufficient Gas Griefing
    • [ ] In the case of a relayer contract, the user who executes the transaction, the 'forwarder', can effectively censor transactions by using just enough gas to execute the transaction, but not enough for the sub-call to succeed.
    • This attack is a form of "griefing": It doesn't directly benefit the attacker, but causes grief for the victim.
    • To prevent this attack, only allow trusted users to relay transactions or require that the forwarder provides enough gas.
    • https://swcregistry.io/docs/SWC-126
    • https://consensys.github.io/smart-contract-best-practices/known_attacks/#insufficient-gas-griefing
    • https://ethereum.stackexchange.com/questions/73261/griefing-attacks-are-they-profitable-for-the-attacker
[ ] Hardcoded Sensitive Values
    • [ ] Values hardcoded in the contract lead to unexpected behavior.
    • Unexpected balance reflects some token balance or address hard-coded into a contract
    • https://swcregistry.io/docs/SWC-134 (Message call with hardcoded gas limit)
    • https://swcregistry.io/docs/SWC-132 (Solidity)
[ ] 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
    • [ ] Verify that there is no bad randomness: On-chain randomness may be a weak because it can be manipulated by users.
    • Use a random number generator whose randomness has been verified.
    • Use external sources of randomness via oracles if trusted oracles are available. Note that it may be reasonable to use multiple oracles, in particular for a seed of the random sequence.
    • Use the up-to-date API to get a random number.
    • https://github.com/crytic/not-so-smart-contracts/tree/master/bad_randomness
    • https://swcregistry.io/docs/SWC-120
[ ] Missing Protection against Signature Replay Attacks
    • [ ] Check a new message hash and verify it has never been processed before.
    • See also signature malleability in the authorization.
    • https://swcregistry.io/docs/SWC-121
[ ] Lack of Proper Signature Verification and Data Authenticity
    • [ ] Add data authentication and signature verification to your contract.
    • Use a proper API for verification funcitons.
    • https://swcregistry.io/docs/SWC-122

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:
  • Uninitialized memory must not be used.
  • Zero out memory of sensitive data after use.
  • The forget function of std::mem (core::mem) must not be used.
  • The code must not leak memory or resource in particular via Box::leak.
  • Iterators are used rather than explicit indexing.
    • If indexing is necessary, explicitly check for correctness.

Error Handling

When it comes to memory management, the following checks need to be done:
  • The object are exception-safe (RFC 1236)
  • The ? operator can be used to improve readability of code.
  • The try! macro should not be used.
  • The Result enum for explicit error handling is used instead of calling panic.
  • Try to avoid using crates containing functions or instructions that can fail and cause the code to panic.
[ ] 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
    • [ ] A constructor function is named correctly so that it does not cause to end up in the runtime bytecode instead of being a constructor.
    • A constructor is responsible for bootstrapping the initial contract state into the storage.
    • Use #[ink(constructor)] constructor instead of a named constructor.
    • https://github.com/crytic/not-so-smart-contracts/tree/master/wrong_constructor_name (Solidity)
    • https://swcregistry.io/docs/SWC-118 (Solidity)
    • https://use.ink/3.x/macros-attributes/constructor
[ ] 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
    • [ ] Labeling the visibility explicitly for variables.
    • Variables can be specified as being public or private. Explicitly define visibility for all state variables.
    • https://swcregistry.io/docs/SWC-108 (Solidity)
[ ] Use of Uninitialized Storage
    • [ ] Initialized local storage variables, otherwise they can point to unexpected storage locations in the contract, which can lead to intentional or unintentional vulnerabilities.
    • Use ink_storage::Mapping which maps key-value pairs directly into contract storage.
    • https://swcregistry.io/docs/SWC-109
    • https://use.ink/datastructures/mapping
[ ] Assert Violation
    • [ ] The assert function should only be used to test for internal errors, and to check invariants.
    • Consider whether the condition checked in the assert! is actually an invariant. If not, replace the assert! statement with a require! statement.
    • https://swcregistry.io/docs/SWC-110 (Solidity)
    • https://use.ink/ink-vs-solidity/#assert
[ ] 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.
    • [ ] Be cautious when you expect to have large arrays that grow over time. Actions that require looping across the entire data structure should be avoided.
    • If you absolutely must loop over an array of unknown size, then you should plan for it to potentially take multiple blocks, and therefore require multiple transactions.
    • https://swcregistry.io/docs/SWC-128
[ ] Presence of Unused Variables
    • [ ] Unused variables cause an increase in computations, indicate bugs or malformed data structures, and decrease readability of the code.
    • Remove all unused variables.
    • https://swcregistry.io/docs/SWC-131
    • cargo contract build will warn against unused variables
[ ] Code with No Effects (Dead Code)
    • [ ] Remove dead codes.
    • Ensure that your contract works as intended without dead codes.
    • https://swcregistry.io/docs/SWC-135
[ ] Account Reinitialization - SVE1013
    • [ ] Be aware that an account can be vulnerable to program re-initialization.
    • Check whether the contract is already initialized from other program before executing the initialization function.
    • https://github.com/project-serum/sealevel-attacks/tree/master/programs/4-initialization
[ ] 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
    • [ ] Ensure all edge cases are included.
    • If not implemented, red flag here. No need to go further. Please design unit Tests with edge case you can think of.
[ ] [cargo-fuzz](https://rust-fuzz.github.io/book/introduction.html)
    • [ ] Review all findings and update your code accordingly.
    • It can be a good starting point to produce more secure code.

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
    • [ ] Explaination of the purpose of the smart contract
    • Documentation and explanation of all smart contract's functions and variables
    • Examples and use cases:
    • Machine setup, installation, deployment and testing instructions:
    • Example of helpful documents
      • architecture diagrams,
      • threat models,
      • academic papers,
      • whitepapers,
      • blog posts,
      • or any other piece of documentation relevant to the project.
[ ] Setup a communication channel with the audit team
    • [ ] Use a secure communication channel using end-to-end encryption.
[ ] Code ready to be frozen
    • [ ] setup the credential for auditors.
    • share the repository.
[ ] Verify that the audit team can answer the following questions
    • [ ] What does it do?
    • Who does it do this for?
    • What kind of information will it hold/handle?
    • How does it handle entities or identities?
    • What aspects seem most concerning?
[ ] Commit Hash
    • [ ] Get the commit hash of the frozen code
    • Inform the commit hash value to the audit team

Audit

  • High-risk findings have been escalated immediately via a secure channel.
  • Communication with audit team are frequent enough.
  • Questions from the audit team have been answered.
  • All findings have been corrected and re-reviewed.

Maintenance

  • Keep monitoring new security attacks and evaluate your contracts accordingly.
  • Apply remedies to the smart contracts immediately if new vulnerabilities are discovered.
    • Contract needs to be upgratable.
  • Run automated code analysis tools whenever new commits are added to the repository.
  • Pause the smart contract when an unusual happen.
  • Contract needs to have a pause option.
  • Consider re-auditing your smart contracts if they have been significantly updated.
  • Feel free to contact security partners for evaluation and scoping.