Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

canister-security

БесплатноБез исполняемых скриптовНе проверен

IC-specific security patterns for canister development in Motoko and Rust. Covers access control, anonymous principal rejection, reentrancy prevention…

jiayaoqijiaот jiayaoqijia★ 81 звезда на GitHub

Об этом скилле

Canister Security

What This Is

Security patterns for IC canisters in Motoko and Rust. The async messaging model creates TOCTOU (time-of-check-time-of-use) vulnerabilities where state changes between await calls. canister_inspect_message is NOT a reliable security boundary. Anyone on the internet can burn your cycles by sending update calls. This skill provides copy-paste correct patterns for access control, reentrancy prevention, async safety, and callback trap handling.

Prerequisites

  • For Motoko: mops package manager, core = "2.0.0" in mops.toml
  • For Rust: ic-cdk = "0.19", candid = "0.10"

Security Pitfalls

  1. Relying on canister_inspect_message for access control. This hook runs on a single replica without full consensus. If that replica is malicious, it can simply skip the check and execute the update call without any message inspection. It is also never called for inter-canister calls, query calls, or management canister calls. Always duplicate access checks inside every update method. Use inspect_message only as a cycle-saving optimization, never as a security boundary.

  2. Forgetting to reject the anonymous principal. Every endpoint that requires authentication must check that the caller is not the anonymous principal (2vxsx-fae). In Motoko use Principal.isAnonymous(caller), in Rust compare msg_caller() != Principal::anonymous(). Without this, unauthenticated callers can invoke protected methods — and if the canister uses the caller principal as an identity key (e.g., for balances), the anonymous principal becomes a shared identity anyone can use.

  3. Reading state before an async call and assuming it's unchanged after (TOCTOU). When your canister awaits an inter-canister call, other messages can interleave and mutate state. This is one of the most critical sources of DeFi exploits on IC. Use per-caller locking (CallerGuard pattern) to prevent concurrent operations. For financial operations, also consider the saga pattern (deduct before await, compensate on failure) — but implementing it correctly is complex due to edge cases like callback traps and call timeouts where the outcome is ambiguous.

  4. Trapping in pre_upgrade. If pre_upgrade traps (e.g., serializing too much data exceeds the instruction limit), the canister becomes permanently non-upgradeable. Avoid storing large data structures in the heap that must be serialized during upgrade. In Rust, use ic-stable-structures for direct stable memory access. In Motoko, the persistent actor declaration stores all let and var variables automatically in stable memory — no manual serialization needed.

  5. Not monitoring cycles balance. Every canister has a default freezing_threshold of 2,592,000 seconds (~30 days). When cycles drop below the threshold reserve, the canister freezes (rejects all update calls). When cycles reach zero, the canister is uninstalled — its code and memory are removed, though the canister ID and controllers survive. The real pitfall is not actively monitoring and topping up cycles. For production canisters holding valuable state, increase the freezing threshold and set up automated monitoring.

    # Check current settings (mainnet)
    icp canister settings show backend -e ic
    # Increase freezing threshold for high-value canisters
    icp canister settings update backend --freezing-threshold 7776000 -e ic  # 90 days
    
  6. Single controller with no backup. If you lose the controller identity's private key, the canister becomes unupgradeable forever. There is no recovery mechanism. Always add a backup controller or governance canister:

    icp canister settings update backend --add-controller <backup-principal> -e ic
    

    When deploying, ask the developer if they have a backup controller principal to add.

  7. Calling fetchRootKey() to make local development work. fetchRootKey() fetches the root public key from the replica at runtime and trusts whatever it returns — if that code path ever runs on mainnet, a man-in-the-middle can substitute a different key, breaking all verification. Never call it, even behind an environment check; environment branching is exactly how the call leaks into production builds. Instead, read the root key from the ic_env cookie (IC_ROOT_KEY, via safeGetCanisterEnv() from @icp-sdk/core/agent/canister-env) and pass it as the rootKey option to HttpAgent.create(). The cookie is set automatically by static-site/asset-canister frontends and by the icp-cli Vite dev server, so the same code works locally and in production with no branching — the cookie always carries the network's root key, and on mainnet that key is identical to the one hardcoded in the agent, so passing it is a harmless no-op. See the icp-cli skill's references/binding-generation.md for the full pattern.

  8. Exposing admin methods without guards. Every update method is callable by anyone on the internet. Admin

Полный SKILL.md на GitHub

Установить canister-security в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

LICENSESOURCE.mdTRUST.auto.yaml

FAQ

Что делает скилл canister-security?

IC-specific security patterns for canister development in Motoko and Rust. Covers access control, anonymous principal rejection, reentrancy prevention (CallerGuard pattern), async safety (saga pattern), callback trap handling, cycle drain protection, and safe upgrade patterns. Use when writing or modifying any canister that modifies state, handles tokens, makes inter-canister calls, or implements access control.

Как установить скилл canister-security?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл canister-security запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить canister-security с