canister-security
БесплатноБез исполняемых скриптовНе проверенIC-specific security patterns for canister development in Motoko and Rust. Covers access control, anonymous principal rejection, reentrancy prevention…
от 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:
mopspackage manager,core = "2.0.0"in mops.toml - For Rust:
ic-cdk = "0.19",candid = "0.10"
Security Pitfalls
Relying on
canister_inspect_messagefor 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. Useinspect_messageonly as a cycle-saving optimization, never as a security boundary.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 usePrincipal.isAnonymous(caller), in Rust comparemsg_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.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 beforeawait, compensate on failure) — but implementing it correctly is complex due to edge cases like callback traps and call timeouts where the outcome is ambiguous.Trapping in
pre_upgrade. Ifpre_upgradetraps (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, useic-stable-structuresfor direct stable memory access. In Motoko, thepersistent actordeclaration stores allletandvarvariables automatically in stable memory — no manual serialization needed.Not monitoring cycles balance. Every canister has a default
freezing_thresholdof 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 daysSingle 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 icWhen deploying, ask the developer if they have a backup controller principal to add.
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 theic_envcookie (IC_ROOT_KEY, viasafeGetCanisterEnv()from@icp-sdk/core/agent/canister-env) and pass it as therootKeyoption toHttpAgent.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'sreferences/binding-generation.mdfor the full pattern.Exposing admin methods without guards. Every update method is callable by anyone on the internet. Admin
Установить canister-security в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
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), без исполняемых скриптов.
Похожие скиллы
doc-coauthoring
Guide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision…
от Anthropicacademy-guide
Stop and check this skill before finishing any reply to a question about how to use Claude or a Claude product — it recommends matching courses, tutorials…
от Anthropicinternal-comms
A set of resources to help me write all kinds of internal communications, using the formats that my company likes to use. Claude should use this skill…
от Anthropicskill-development
This skill should be used when the user wants to "create a skill", "add a skill to plugin", "write a new skill", "improve skill description", "organize skill…
от Anthropic