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.
Install Rustup. If you already have Rustup installed, update to ensure you have the latest Rustup and compiler:
rustup updateInstall Clippy
rustup component add clippyRun Clippy
cargo clippyIf necessary, fix Clippy suggestions automatically
cargo clippy --fixUse rustfix which reads and applies the suggestions made by rustc.
Install rustfix
cargo add rustfix cargo install cargo-fix cargo fixOpen 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.
Install cargo-audit
cargo install cargo-auditRun cargo audit
cargo auditUse cargo outdated which displays when Rust dependencies are out of date.
Install cargo-outdated
cargo install --locked cargo-outdatedRun cargo outdated
cargo outdatedUse 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.
Context establishment
How will the project be used?
Who is the target audience?
Threat assessment
This includes a list of all assets used in the project and their associated risks or threats
Threat analysis & evaluation
Assets are classified by their risks/threats and their likelyhood.
Mitigation treatment
What can be done to mitigate these risks/threats?
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
[ ] 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)
Output Encoding
[ ] 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
[ ] 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
[ ] 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
[ ] 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
[ ] 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
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
[ ] 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)
[ ] 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
[ ] 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 contract has only a few non-token-related functions.
[ ] Non-token-related functions increase the likelihood of an issue in the contract.
[ ] 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
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?
[ ] Setup a communication channel with the audit team
[ ] Use a secure communication channel using end-to-end encryption.
[ ] 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.
Last updated
Was this helpful?
