mcpField
R
rust-security

rust-security

github.com/mohitmishra786安全269557 次安装18 周前更新
代码仓库

关于 rust-security

面向编码 Agent 的 Rust 安全实践指南,涵盖依赖审计、策略检查、FFI 安全、模糊测试与 Miri 检查。

主要功能

  1. 01使用 cargo-audit 扫描漏洞
  2. 02通过 cargo-deny 执行依赖策略
  3. 03查询 RUSTSEC 安全公告
  4. 04编写内存安全的 FFI
  5. 05结合模糊测试与 Miri 检查

适用场景

  1. 01检查 Rust 项目的依赖漏洞
  2. 02在 CI 中落实依赖许可与来源规则
  3. 03审查 Rust 与 C 边界的安全性
  4. 04对 Rust 库进行模糊测试和未定义行为检查

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/mohitmishra786/low-level-dev-skills --skill rust-security

安装后在 Claude Code 中输入/rust-security确认已加载。

详细介绍

Rust 安全

用途

指导 Agent 遵循 Rust 安全实践:使用 cargo-audit 审计依赖项,使用 cargo-deny 强制执行策略,了解 RUSTSEC 公告数据库,采用内存安全的 FFI 模式,以及结合模糊测试和 Miri 进行安全审查。

触发条件

  • “如何检查 Rust 依赖项是否存在 CVE?”
  • “如何使用 cargo-audit?”
  • “如何在 CI 中强制执行依赖项策略?”
  • “什么是 RUSTSEC 公告数据库?”
  • “如何在 Rust 中编写内存安全的 FFI?”
  • “如何对 Rust 库进行模糊测试,以查找安全漏洞?”

工作流

1. cargo-audit — 漏洞扫描
# Install
cargo install cargo-audit --locked

# Scan current project
cargo audit

# Full output including ignored
cargo audit --deny warnings

# Audit the lockfile (CI-friendly)
cargo audit --file Cargo.lock

# JSON output for CI integration
cargo audit --json | jq '.vulnerabilities.list[].advisory.id'

输出格式:

error[RUSTSEC-2023-0052]: Vulnerability in `vm-superio`
    Severity: low
       Title: MMIO Register Misuse
    Solution: upgrade to `>= 0.7.0`
2. cargo-deny — 策略强制执行

cargo-deny 的功能不止于审计:它还能强制执行许可证策略、禁止特定 crate、检查来源,并验证重复的依赖项版本。

cargo install cargo-deny --locked

# Initialize deny.toml
cargo deny init

# Run all checks
cargo deny check

# Run specific check
cargo deny check advisories
cargo deny check licenses
cargo deny check bans
cargo deny check sources

deny.toml 配置:

[advisories]
vulnerability = "deny"      # Deny known vulnerabilities
unmaintained = "warn"       # Warn on unmaintained crates
yanked = "deny"             # Deny yanked versions

# Ignore specific advisories
ignore = [
    "RUSTSEC-2021-0145",    # known false positive for our usage
]

[licenses]
unlicensed = "deny"
allow = [
    "MIT", "Apache-2.0", "Apache-2.0 WITH LLVM-exception",
    "BSD-2-Clause", "BSD-3-Clause", "ISC", "Unicode-DFS-2016",
]
# Deny GPL for proprietary projects
deny = ["GPL-2.0", "GPL-3.0"]

[bans]
multiple-versions = "warn"  # Warn if same crate appears twice
wildcards = "deny"          # Deny wildcard dependencies

[[bans.deny]]
name = "openssl"            # Force rustls instead
wrappers = ["reqwest"]      # Allow if only required by these

[sources]
unknown-registry = "deny"
unknown-git = "deny"
allow-git = [
    "https://github.com/my-org/private-crate",
]

GitHub Actions CI 集成:

- name: Security audit
  run: |
    cargo install cargo-deny --locked
    cargo deny check
3. RUSTSEC 公告数据库

RUSTSEC 数据库位于 https://rustsec.org/,用于跟踪漏洞、无人维护的 crate 和不健全代码。

# Browse advisories from CLI
cargo audit --db ~/.cargo/advisory-db fetch
ls ~/.cargo/advisory-db/crates/

# Check a specific advisory
curl https://rustsec.org/advisories/RUSTSEC-2023-0001.json | jq .

# Common categories
# type: vulnerability — exploitable security bug
# type: unmaintained — no longer maintained (supply chain risk)
# type: unsound — documented unsoundness in safe API
# type: yanked — crate version yanked from crates.io
4. 内存安全的 FFI 模式

Rust/C 边界处常见的不安全来源:

// UNSAFE pattern — raw pointer from C, no lifetime
extern "C" fn process_data(data: *const u8, len: usize) {
    // Don't do this — no bounds check, no lifetime guarantee
    let slice = unsafe { std::slice::from_raw_parts(data, len) };
}

// SAFE pattern — validate before using
extern "C" fn process_data(data: *const u8, len: usize) -> i32 {
    // Validate pointer and length
    if data.is_null() || len == 0 || len > 1024 * 1024 {
        return -1;
    }
    // Safety: non-null, len validated, called from C with valid buffer
    let slice = unsafe { std::slice::from_raw_parts(data, len) };
    do_work(slice);
    0
}

// Use safe wrapper crates for common patterns
use nix::unistd::read;   // safe POSIX wrappers
use windows::Win32::System::Memory::VirtualAlloc;  // safe Windows bindings
5. 针对安全漏洞的模糊测试
# cargo-fuzz — libFuzzer-based
cargo install cargo-fuzz

# Initialize
cargo fuzz init
cargo fuzz add my_target

# fuzz/fuzz_targets/my_target.rs
# #![no_main]
# use libfuzzer_sys::fuzz_target;
# fuzz_target!(|data: &[u8]| {
#     if let Ok(s) = std::str::from_utf8(data) {
#         let _ = my_lib::parse(s);
#     }
# });

# Run fuzzing (long-running)
cargo fuzz run my_target

# With sanitizers for security coverage
cargo fuzz run my_target -- -sanitizer=address

# Reproduce a crash
cargo fuzz run my_target artifacts/my_target/crash-xxxx
# Honggfuzz — good for security targets
cargo install honggfuzz
cargo hfuzz run my_target
6. 使用 Miri 检查健全性
# Install Miri
rustup +nightly component add miri

# Run tests under Miri
cargo +nightly miri test

# Check for UB in unsafe code
MIRIFLAGS="-Zmiri-disable-isolation -Zmiri-backtrace=full" \
  cargo +nightly miri test

# Miri detects:
# - Use-after-free
# - Dangling references
# - Invalid pointer arithmetic
# - Data races (with -Zmiri-tree-borrows)
# - Uninitialized memory reads
7. 供应链加固
# Pin Cargo.lock in applications (not libraries)
# Always commit Cargo.lock for binaries

# Verify checksums (cargo already does this)
cargo fetch --locked    # fails if Cargo.lock doesn't match

# Audit all dependencies including transitive
cargo tree              # view full dependency tree
cargo tree -d           # show duplicate versions

# Use cargo-vet for peer review of new deps
cargo install cargo-vet
cargo vet              # check all deps have been vetted

# Minimal dependency principle
cargo machete          # finds unused dependencies

相关技能

  • 使用 skills/rust/rust-sanitizers-miri 了解 Miri 和 Sanitizer 详情
  • 使用 skills/runtimes/fuzzing 了解模糊测试策略和语料库管理
  • 使用 skills/rust/rust-unsafe 了解不安全代码审计模式
  • 使用 skills/rust/cargo-workflows 管理 Cargo.lock 和工作区

评论

支持 Markdown