LogoLogo
  • WELCOME TO ALEPH ZERO
  • EXPLORE
    • About Aleph Zero
    • AlephBFT Consensus
    • The Economy of Aleph Zero
    • Where to Buy AZERO
    • Decentralized Governance on Aleph Zero
    • Ecosystem
    • Aleph Zero Foundation Treasury Management
    • Community
    • Glossary
    • Audit & Research Papers
  • USE
    • Wallets
    • Explorer
    • Ledger
    • Telegram Notifications
    • Aleph Zero Signer
      • General introduction
      • What does Signer do?
      • What are Sub-accounts and Sub-account paths?
      • Why is it critical to store your Secret Phrase in a safe place?
      • How to forget and restore accounts?
      • What are Networks?
      • What are Trusted apps?
    • Dashboard
      • Dashboard basics
      • Overview
    • Stake
      • Staking Basics
      • Staking Menu Overview
      • How to Start Staking with the Aleph Zero Dashboard
      • How to Start Staking With the Developer Wallet
      • How to start staking using Ledger hardware wallet
      • How to Change Nominations
      • How to Stop Staking
      • Staking Rewards
      • Validators
      • Commission and Foundation Nodes
      • Proxy Accounts
    • Validate
      • Validating Overview
      • Hardware requirements
      • Running an Aleph Node on Testnet
        • Downloading and running the node
        • Verifying your setup
        • Customizing your setup
        • Building and running from source [advanced]
          • Building from source
          • Set environment variables
          • Download DB snapshot
          • Running the binary
        • Appendix: Ports, addresses, validators, and archivists
      • Running an Aleph Node on Mainnet
        • Running the node
        • Building and running from source [advanced]
      • Setting your identity
      • Making the node validate
      • Securing your validator
      • Troubleshooting
      • Elections and Rewards Math
      • Testnet Validator Airdrop
      • Foundation Nomination Program
    • Using the EVM-layer
    • Governance
      • Token
      • Multisig Accounts
  • BUILD
    • Aleph Zero smart contracts basics
      • Setting up a Testnet account
      • Installing required tools
      • Creating your first contract
      • Deploying your contract to Aleph Zero Testnet
      • Extending your contract
    • Cross contract calls
      • Using references
      • Using dynamic calls
    • Migrating from Solidity
    • Writing e2e tests with ink-wrapper
    • Aleph Zero Signer integration
    • Front-end app: smart contract interaction
    • Security Course by Kudelski Security
      • ink! Developers Security Guideline
      • Lesson 1 - Getting started with ink!
      • Lesson 2 - Threat Assessment
      • Lesson 3 - Integer Overflow
      • Lesson 4 - Signed-integer
      • Lesson 5 - Role-Based Access Control
      • Lesson 6 - Address Validation
      • Lesson 7 - Smart Contract Control
    • Development on EVM-layer
  • PROTOCOL DETAILS
    • Shielder
      • Overview
      • Design against Bad Actors
      • Preliminaries - ZK-relations
      • Notes and Accounts
      • ZK-ID and Registrars
      • Anonymity Revokers
      • PoW Anonymity Revoking
      • Relayers
      • Deterministic Secret Management
      • SNARK-friendly Symmetric Encryption
      • SNARK-friendly Asymmetric Encryption
      • Cryptography
      • Token shortlist
      • User Wallet
      • Versioning
      • PoC
      • Version 0.1.0
      • Version 0.2.0
    • Common DEX
      • Common Whitepaper - Differences
      • Dutch Auctions
  • FAQ
  • Tutorials
    • Withdrawing coins from exchanges
      • How to withdraw your AZERO coins from KuCoin
      • How to withdraw your AZERO coins from MEXC Global
      • How to withdraw your AZERO coins from HTX
  • Setting up or restoring a wallet
    • How to set up or recover your AZERO account using Aleph Zero Signer
    • How to set up or recover your AZERO account using the official mainnet web wallet
    • How to set up or recover your AZERO account using Nova Wallet
    • How to set up or recover your AZERO account using SubWallet
    • How to set up or recover your AZERO account using Talisman
  • Staking
    • How to stake via a direct nomination using the Aleph Zero Dashboard
    • How to stake via a nomination pool using the Aleph Zero Dashboard
    • How to destroy a nomination pool via the Aleph Zero Dashboard
Powered by GitBook
On this page
  • Development Environment
  • Design
  • Threats/Risk assessment
  • Conventions
  • Input Validation
  • Output Encoding
  • Authentication
  • Authorization
  • Cryptography
  • Numerics
  • Memory management
  • Error Handling
  • Bad Programming practices
  • Token Specific issues
  • Testing
  • Pre-Audit
  • Audit
  • Maintenance

Was this helpful?

  1. BUILD
  2. Security Course by Kudelski Security

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.

PreviousSecurity Course by Kudelski SecurityNextLesson 1 - Getting started with ink!

Last updated 1 year ago

Was this helpful?

Development Environment

  • Use multichain framework to build and deploy programs.

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

  • Use a stable .

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

  • Use 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 which is a collection of lints to catch common mistakes and improve your Rust code.

    1. Install . 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 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 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 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 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

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

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

[ ] 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

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

Format strings using

Getter names follow Rust convention ()

Methods on collections that produce iterators follow iter, iter_mut, into_iter ()

Iterator type names match the methods that produce them ()

Feature names are free of placeholder words ()

Names use a consistent word order ()

For further conventions, see .

The object are exception-safe ()

Substrate
Ink!
compilation toolchain
set in Cargo.toml
rustfmt
rust clippy
Rustup
rustfix
cargo audit
cargo outdated
cargo update
Rust API Guidelines Checklist
format!
C-GETTER
C-ITER
C-ITER-TY
C-FEATURE
C-WORD-ORDER
Rust API Guidelines Checklist
RFC 1236