canister-audit

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Canister Audit

Canister 审计

What This Is

这是什么

A workflow for auditing a Rust
ic-cdk
canister you did not write, and for turning a suspected flaw into a proven one.
canister-security
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.
The worked example throughout is a deliberately-broken ledger canister,
token_vault
, whose accounting invariant
sum(balances) <= total_deposited
is broken by exactly one unguarded method.
这是一套用于审计并非由你编写的 Rust
ic-cdk
canister 的工作流,并可将疑似漏洞转化为已证实的漏洞。
canister-security
讲解 canister 应遵循的模式;这个 skill 则站在另一面——针对现有代码,找出这些模式被违反的位置,并通过在 PocketIC 中复现漏洞利用来证明严重级别最高的发现。grep 命中或直觉判断只是一个候选项;而能够驱动已部署 wasm 并跨越安全边界的 PocketIC 测试才是证据。
贯穿全文的示例是一个刻意包含缺陷的账本 canister
token_vault
,其会计不变量
sum(balances) <= total_deposited
恰好被一个缺少防护的方法破坏。

Prerequisites

前置条件

  • Rust toolchain + the wasm target:
    rustup target add wasm32-unknown-unknown
    .
  • Optional static tools:
    cargo-audit
    (RustSec dependency CVEs) and Semgrep (a coarse first pass; Rust support is experimental, so treat it as high-recall).
  • For the proof step: the
    pocket-ic
    crate (e.g.
    16.1
    ). With
    POCKET_IC_BIN
    unset,
    PocketIc::new()
    downloads the matching server release from
    dfinity/pocketic
    on first use. To pin a binary you have verified (sha256) instead, point
    POCKET_IC_BIN
    at it; the server's major version must match the crate's.
  • Rust 工具链及 wasm target:
    rustup target add wasm32-unknown-unknown
    。
  • 可选静态工具:
    cargo-audit
    (RustSec 依赖 CVE)和 Semgrep(粗粒度初筛;其 Rust 支持仍属实验性,因此应将其视为高召回率工具)。
  • 对于证明步骤:需要
    pocket-ic
    crate(例如
    16.1
    )。未设置
    POCKET_IC_BIN
    时,
    PocketIc::new()
    会在首次使用时从
    dfinity/pocketic
    下载匹配的 server release。如果希望改为固定使用已验证(sha256)的二进制文件,可将
    POCKET_IC_BIN
    指向该文件;服务端主版本必须与 crate 的主版本匹配。

The audit workflow

审计工作流

  1. Detect the canister. Confirm it is a Rust ic-cdk canister: a
    Cargo.toml
    depending on
    ic-cdk
    /
    candid
    ,
    #[ic_cdk::update]
    /
    #[ic_cdk::query]
    entrypoints, a
    .did
    . A canister's logic is not recoverable from its deployed wasm, so you need the source - there is no audit-by-mainnet-address mode.
  2. 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
    await
    . The audit then hunts for a path that breaks each invariant. For
    token_vault
    the invariant is
    sum(balances) <= total_deposited
    .
  3. 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]
      ,
      #[ic_cdk::update]
      , with or without arguments (
      guard = ...
      ,
      name = ...
      ),
      async
      or not — with no caller check (
      is_controller
      , an owner check, or a
      == Principal::anonymous()
      rejection).
      CallerGuard
      is a reentrancy lock, not a caller check: it admits the anonymous principal;
    • fetch_root_key
      /
      fetchRootKey
      /
      shouldFetchRootKey
      anywhere in the repo, including calls behind an environment check (
      canister-security
      pitfall #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 the
      ic_env
      cookie (
      IC_ROOT_KEY
      , via
      safeGetCanisterEnv()
      ) as
      rootKey
      to
      HttpAgent.create()
      ;
    • let _ = CallerGuard::new(...)
      - a guard bound to
      _
      is dropped at the end of the statement, so the lock is released immediately;
    • ic_cdk::caller()
      - deprecated in favour of
      msg_caller()
      ; legacy call sites often predate the current guard conventions. A deliberately high-recall rule flags
      deposit
      ,
      withdraw
      , and
      claim_bonus
      here, even though
      deposit
      rejects the anonymous principal and
      withdraw
      takes a
      CallerGuard
      - the point is to surface candidates for review, not to decide. Example Semgrep rule (tested with Semgrep 1.185):
    yaml
    rules:
      - 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)
    The suppression is by name only, so methods it hides are still reviewed in step 4 - it just orders the queue.
  4. Systematic review against the pitfalls. Walk each entrypoint against the
    canister-security
    checklist (anonymous principal #2, TOCTOU across
    await
    #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: a
    guard = "..."
    function or helper proves nothing until you have read it,
    require_authenticated
    -style guards stop only the anonymous principal (not enough for admin methods), and a guard called as a statement whose
    Result
    is discarded (
    require_owner();
    ) is a bypass - the mutation runs whether or not it returned
    Err
    . In
    token_vault
    ,
    claim_bonus
    credits the caller with no guard and never touches
    total_deposited
    , so it breaks the invariant and is reachable by the anonymous principal (pitfalls #2 and #8);
    deposit
    's
    == Principal::anonymous()
    check refutes its own candidate.
  5. Prove a confirmed HIGH/CRITICAL with PocketIC (next section).
  6. Report. Per finding: the pitfall, the
    file:line
    , 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.
  1. 识别 canister。 确认它是一个 Rust ic-cdk canister:
    Cargo.toml
    依赖
    ic-cdk
    /
    candid
    ,包含
    #[ic_cdk::update]
    /
    #[ic_cdk::query]
    入口点,并提供
    .did
    。canister 的逻辑无法从已部署的 wasm 中还原,因此需要源代码——不存在仅凭 mainnet 地址进行审计的模式。
  2. 首先建模不变量。 在查找漏洞之前,先记录必须始终成立的约束:会计恒等式、谁可以调用哪些方法,以及每次
    await
    前后哪些状态会发生变化。接下来的审计将寻找破坏每项不变量的路径。对于
    token_vault
    ,其不变量为
    sum(balances) <= total_deposited
    。
  3. 静态初筛(高召回率、尽力而为)。 使用 grep 或 Semgrep 搜索明显的陷阱,并将每个命中都视为需要确认的候选项,而非自动判定为发现:
    • 会改变状态的 update fn——带参数或不带参数(
      guard = ...
      、
      name = ...
      )、同步或异步形式——且没有调用方检查(
      is_controller
      、owner 检查,或对
      == Principal::anonymous()
      的拒绝)。
      CallerGuard
      是一种重入锁,而不是调用方检查:它允许匿名 principal 通过;
    • fetch_root_key
      /
      fetchRootKey
      /
      shouldFetchRootKey
      出现在仓库中的任何位置,包括位于环境检查之后的调用(
      canister-security
      陷阱 #7 禁止这种做法,即使存在环境分支也不允许——环境分支可能泄漏到生产构建中);只有测试专用代码可以豁免。建议的修复方式是移除该调用,并从
      ic_env
      cookie(
      IC_ROOT_KEY
      ,通过
      safeGetCanisterEnv()
      获取)传入 root key,作为
      HttpAgent.create()
      的
      rootKey
      ;
    • let _ = CallerGuard::new(...)
      ——绑定到
      _
      的 guard 会在语句末尾立即被丢弃,因此锁会马上释放;
    • ic_cdk::caller()
      ——已被
      msg_caller()
      取代;遗留调用点通常早于当前的 guard 约定。 此处,一条有意采用高召回率的规则会标记
      deposit
      、
      withdraw
      和
      claim_bonus
      ,尽管
      deposit
      会拒绝匿名 principal,且
      withdraw
      获取了
      CallerGuard
      ——重点是暴露需要审查的候选项,而不是直接下结论。示例 Semgrep 规则(已使用 Semgrep 1.185 测试):
    yaml
    rules:
      - 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)
    抑制规则仅基于名称匹配,因此它隐藏的方法仍会在第 4 步中接受审查——它只是调整处理顺序。
  4. 依据陷阱清单进行系统审查。 按照
    canister-security
    检查清单逐一审查每个入口点(匿名 principal #2、跨
    await
    的 TOCTOU #3、无防护的管理员方法 #8、存储 / cycle-drain DoS #10/#5、变更后 callback-trap-after-mutation #11,以及其他问题)。对于每个候选项,阅读代码并判断其是真实漏洞还是已被排除。必须追踪每个 guard 的函数体:
    guard = "..."
    所指向的函数或辅助函数,在读过其实现之前不能证明任何安全性;
    require_authenticated
    风格的 guard 只能拦截匿名 principal(对于管理员方法远远不够);将 guard 作为语句调用并丢弃其
    Result
    (
    require_owner();
    )属于绕过——无论它是否返回
    Err
    ,变更都会执行。在
    token_vault
    中,
    claim_bonus
    在没有任何 guard 的情况下为调用方记入余额,并且从不修改
    total_deposited
    ,因此破坏了不变量且可由匿名 principal 访问(陷阱 #2 和 #8);
    deposit
    的
    == Principal::anonymous()
    检查则排除了其对应的候选项。
  5. 使用 PocketIC 证明已确认的 HIGH/CRITICAL 漏洞(见下一节)。
  6. 报告。 每项发现应包含:对应陷阱、
    file:line
    、被破坏的不变量;对于已证明的漏洞,还应包含复现过程。应诚实地将未经证明的候选项描述为"疑似,未复现",并且绝不要公开发布针对尚未修复 canister 的可用漏洞利用程序——它应仅出现在提供给 canister 控制方的私有报告中。

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
Principal::anonymous()
), and assert the prohibited outcome. If the test passes, the exploit is real.
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.toml
:
toml
[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.toml
:
toml
[package]
name = "token_vault_repro"
version = "0.1.0"
edition = "2021"
publish = false

Empty [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"
undefined

1. The flaw (
token_vault/src/lib.rs
)

1. 缺陷(
token_vault/src/lib.rs
)

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;
    });
}
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
)

2. 复现(独立的
token_vault_repro
crate,
tests/repro.rs
)

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"
    );
}
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-unknown
bash
rustup target add wasm32-unknown-unknown

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

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)

如果被审计的 crate 是 Cargo workspace 的一部分,其 wasm 会生成在 **workspace** 的 `target/` 目录中——请相应调整路径。

测试通过正是整个流程的关键:这证明匿名 principal 可以创建一个没有存款支撑的余额——已部署 wasm 上的会计不变量已经被破坏。这就是"`claim_bonus` 看起来没有防护"与"这里是匿名 principal 凭空铸造余额"之间的区别。测试所证明的内容应严格限定在其实际展示的范围内:它本身**不能**证明资金可以被盗取。若要证明盗取,可扩展测试——由正常用户 principal 为金库注资,让攻击者调用 `claim_bonus` 后再调用 `withdraw`,并断言提现成功且诚实用户的资金无法再被足额支付。

Notes

注意事项

  • The PocketIC server and the
    pocket-ic
    crate share a major version. Pin both and update the
    update_call
    /
    query_call
    signatures together if you bump (the 16.x API returns
    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 与
    pocket-ic
    crate 使用相同的主版本。如果升级,应同时固定两者版本,并同步更新
    update_call
    /
    query_call
    的签名(16.x API 返回
    Result<Vec<u8>, _>
    )。
  • 未复现或复现失败都不能否定静态分析或代码审查得出的发现。漏洞可能真实存在,但难以在单元测试中复现,例如涉及时序或多 canister 部署;此时应保留分析推理,并将证明标记为待完成。
  • 静态命中只是候选项,而不是结论。高召回率规则集用于避免遗漏明显问题;最终确认依赖于系统审查和 PocketIC 证明。