SuperAPI AI 工具集

rust-sanitizers-miri

安全与审计

查看项目

更新于 10-15 17:54

技能介绍

用途

本技能用于指导代理完成 Rust 的运行时安全验证:通过 RUSTFLAGS 运行 ASan、TSan、MSan、UBSan,并使用 Miri 对 unsafe 代码进行未定义行为(UB)检测,同时解释 sanitizer 报告。典型触发场景包括:如何在 Rust 代码上运行 AddressSanitizer、如何使用 Miri 检查 unsafe Rust、如何运行 ThreadSanitizer、如何检测 unsafe Rust 中的 UB、如何解读 Rust ASan 报告,以及在 stable 上能否运行 Rust sanitizer。

主要能力

Rust 的 sanitizer 需要 nightly 与兼容平台。安装方式为 rustup toolchain install nightly 与 rustup component add rust-src --toolchain nightly。运行 ASan(Linux、macOS)使用 RUSTFLAGS="-Z sanitizer=address" cargo +nightly test -Zbuild-std --target x86_64-unknown-linux-gnu;TSan(Linux)为 -Z sanitizer=thread;MSan(Linux,需要全插桩构建)为 -Z sanitizer=memory -Zsanitizer-memory-track-origins;UBSan 为 -Z sanitizer=undefined。-Zbuild-std 会用 sanitizer 重建标准库,这是准确结果的必要条件。

对于 stable 的替代方案,可使用 cross 工具配合预配置 sanitizer 的 Docker 镜像,或在带有 nightly 镜像的 Docker 容器中运行 cargo test;也可使用 cargo-sanitize 包装器:cargo install cargo-sanitize 后执行 cargo sanitize address。

Miri 解释 Rust MIR,可检测 sanitizer 可能遗漏的 UB。安装(需 nightly)为 rustup +nightly component add miri;运行测试为 cargo +nightly miri test,可指定测试名、运行二进制 cargo +nightly miri run。使用严格别名(Stacked Borrows)模型时设置 MIRIFLAGS="-Zmiri-strict-provenance";允许文件 I/O 与随机性时设置 MIRIFLAGS="-Zmiri-disable-isolation"。

Miri 可检测的示例包括:悬垂指针使用、无效枚举判别值(invalid tag)、未初始化内存读取、Stacked Borrows 违规,以及在线程下检测数据竞争(Miri 模拟顺序执行并通过 Stacked Borrows 检测竞争)。

ThreadSanitizer 的 Rust 用法为 RUSTFLAGS="-Z sanitizer=thread" RUST_TEST_THREADS=8 cargo +nightly test -Zbuild-std --target x86_64-unknown-linux-gnu,其输出会标注数据竞争的读写位置与线程。

使用方式

ASan 报告解读:错误行形如 ERROR: AddressSanitizer: heap-buffer-overflow on address ...,附带堆栈与分配位置。Rust 常见对应关系:heap-buffer-overflow 对应 unsafe 切片越界访问;use-after-free 对应 Vec 重新分配后使用 unsafe 指针;stack-use-after-return 对应返回局部变量引用;heap-use-after-free 对应 drop() 或 Box::from_raw 之后的使用。

MIRIFLAGS 配置项包括:-Zmiri-disable-isolation(允许 I/O、时钟、随机性)、-Zmiri-strict-provenance(严格指针来源,严于 LLVM)、-Zmiri-symbolic-alignment-check(更严格对齐检查)、-Zmiri-check-number-validity(检查浮点/整数有效性)、-Zmiri-num-cpus=N(模拟 N 个 CPU)、-Zmiri-seed=N(随机调度种子)、-Zmiri-ignore-leaks(抑制内存泄漏错误)、-Zmiri-tag-raw-pointers(跟踪裸指针来源)。

CI 集成(GitHub Actions)示例:Miri 步骤安装 nightly 与 miri 组件后运行 cargo +nightly miri test,可设置 MIRIFLAGS: "-Zmiri-disable-isolation";ASan 步骤添加 rust-src 组件后以 RUSTFLAGS="-Z sanitizer=address" cargo +nightly test -Zbuild-std --target x86_64-unknown-linux-gnu 运行。

适用场景

适用于需要在 Rust 项目中验证内存安全与并发安全、排查 unsafe 代码 UB、或在 CI 中自动化安全检测的开发者与工具链集成场景。相关技能方面,可用 rust-debugging 进行 GDB/LLDB 调试 Rust panic,用 runtimes/sanitizers 了解 C/C++ sanitizer 用法与比较,用 rust-unsafe 查看 unsafe 模式与审查清单,用 runtimes/fuzzing 生成触发 sanitizer 错误的输入。

限制

Rust sanitizer 需要 nightly 和兼容平台;MSan 需要全插桩构建;TSan 主要面向 Linux;stable 需借助 Docker 等替代方式。Miri 同样需要 nightly,且作为解释器运行,性能与真实运行存在差异,部分能力需通过 MIRIFLAGS 调整。价格、收费、平台支持范围等本资料未提供。