Cargo Fuzz

作者 trailofbits82fe82262526无许可证7.4K 个星标收录于 2026年10月8日更新于 2026年10月8日仓库昨天更新

Sets up and runs cargo-fuzz, the standard fuzzing tool for Cargo-based Rust projects. Covers cargo fuzz init, the nightly toolchain requirement, fuzz_target! harnesses, Arbitrary-derived structured inputs, sanitizer options, cargo fuzz coverage, and reproducing a crash artifact. Use when fuzzing a Rust crate, writing a fuzz_target!, exercising unsafe blocks or FFI in Rust, or triaging a cargo fuzz crash.

AI 生成的概览

指导安装并运行 cargo-fuzz,用 libFuzzer 对基于 Cargo 的 Rust 项目进行模糊测试。

功能
说明如何配合 nightly Rust 工具链安装 cargo-fuzz、初始化 fuzz 目录并编写 fuzz_target! 测试骨架。内容涵盖使用 arbitrary crate 的结构化输入、AddressSanitizer 等 sanitizer 选项、覆盖率报告、字典以及崩溃样本复现。还包含故障排查和针对 ogg crate 的完整示例。
适用场景
适用于对使用 Cargo 的 Rust crate 进行模糊测试、编写 fuzz_target! 测试骨架,或测试 unsafe 代码块与 FFI。也适合排查 cargo fuzz 崩溃或分析模糊测试覆盖率。
运行要求
需要经 rustup 安装的 Rust 与 Cargo 以及 nightly 工具链,并通过 cargo install 安装 cargo-fuzz。覆盖率分析还需 llvm-tools-preview 组件、cargo-binutils 和 rustfilt。该技能不附带脚本,命令需手动执行。

cargo-fuzz

cargo-fuzz is the de facto choice for fuzzing Rust projects when using Cargo. It uses libFuzzer as the backend and provides a convenient Cargo subcommand that automatically enables relevant compilation flags for your Rust project, including support for sanitizers like AddressSanitizer.

When to Use

cargo-fuzz is currently the primary and most mature fuzzing solution for Rust projects using Cargo.

FuzzerBest ForComplexity
cargo-fuzzCargo-based Rust projects, quick setupLow
AFL++Multi-core fuzzing, non-Cargo projectsMedium
LibAFLCustom fuzzers, research, advanced use casesHigh

Choose cargo-fuzz when:

  • Your project uses Cargo (required)
  • You want simple, quick setup with minimal configuration
  • You need integrated sanitizer support
  • You're fuzzing Rust code with or without unsafe blocks

Quick Start

rust
#![no_main]
use libfuzzer_sys::fuzz_target;
fn harness(data: &[u8]) {    your_project::check_buf(data);}
fuzz_target!(|data: &[u8]| {    harness(data);});

Initialize and run:

bash
cargo fuzz init# Edit fuzz/fuzz_targets/fuzz_target_1.rs with your harnesscargo +nightly fuzz run fuzz_target_1

Installation

cargo-fuzz requires the nightly Rust toolchain because it uses features only available in nightly.

Prerequisites

  • Rust and Cargo installed via rustup
  • Nightly toolchain

Linux/macOS

bash
# Install nightly toolchainrustup install nightly
# Install cargo-fuzzcargo install cargo-fuzz

Verification

bash
cargo +nightly --versioncargo fuzz --version

Writing a Harness

Project Structure

cargo-fuzz works best when your code is structured as a library crate. If you have a binary project, split your main.rs into:

text
src/main.rs  # Entry point (main function)src/lib.rs   # Code to fuzz (public functions)Cargo.toml

Initialize fuzzing:

bash
cargo fuzz init

This creates:

text
fuzz/├── Cargo.toml└── fuzz_targets/    └── fuzz_target_1.rs

Harness Structure

rust
#![no_main]
use libfuzzer_sys::fuzz_target;
fn harness(data: &[u8]) {    // 1. Validate input size if needed    if data.is_empty() {        return;    }
    // 2. Call target function with fuzz data    your_project::target_function(data);}
fuzz_target!(|data: &[u8]| {    harness(data);});

Harness Rules

DoDon't
Structure code as library crateKeep everything in main.rs
Use fuzz_target! macroWrite custom main function
Handle Result::Err gracefullyPanic on expected errors
Keep harness deterministicUse random number generators

See Also: For detailed harness writing techniques and structure-aware fuzzing with the arbitrary crate, see the fuzz-harness-writing technique skill.

Structure-Aware Fuzzing

cargo-fuzz integrates with the arbitrary crate for structure-aware fuzzing:

rust
// In your library crateuse arbitrary::Arbitrary;
#[derive(Debug, Arbitrary)]pub struct Name {    data: String}
rust
// In your fuzz target#![no_main]use libfuzzer_sys::fuzz_target;
fuzz_target!(|data: your_project::Name| {    data.check_buf();});

Add to your library's Cargo.toml:

toml
[dependencies]arbitrary = { version = "1", features = ["derive"] }

Running Campaigns

Basic Run

bash
cargo +nightly fuzz run fuzz_target_1

Without Sanitizers (Safe Rust)

If your project doesn't use unsafe Rust, disable sanitizers for 2x performance boost:

bash
cargo +nightly fuzz run --sanitizer none fuzz_target_1

Check if your project uses unsafe code:

bash
cargo install cargo-geigercargo geiger

Re-executing Test Cases

bash
# Run a specific test case (e.g., a crash)cargo +nightly fuzz run fuzz_target_1 fuzz/artifacts/fuzz_target_1/crash-<hash>
# Run all corpus entries without fuzzingcargo +nightly fuzz run fuzz_target_1 fuzz/corpus/fuzz_target_1 -- -runs=0

Using Dictionaries

bash
cargo +nightly fuzz run fuzz_target_1 -- -dict=./dict.dict

Interpreting Output

OutputMeaning
NEWNew coverage-increasing input discovered
pulsePeriodic status update
INITEDFuzzer initialized successfully
Crash with stack traceBug found, saved to fuzz/artifacts/

Corpus location: fuzz/corpus/fuzz_target_1/ Crashes location: fuzz/artifacts/fuzz_target_1/

Sanitizer Integration

AddressSanitizer (ASan)

ASan is enabled by default and detects memory errors:

bash
cargo +nightly fuzz run fuzz_target_1

Disabling Sanitizers

For pure safe Rust (no unsafe blocks in your code or dependencies):

bash
cargo +nightly fuzz run --sanitizer none fuzz_target_1

Performance impact: ASan adds ~2x overhead. Disable for safe Rust to improve fuzzing speed.

Checking for Unsafe Code

bash
cargo install cargo-geigercargo geiger

See Also: For detailed sanitizer configuration, flags, and troubleshooting, see the address-sanitizer technique skill.

Coverage Analysis

cargo-fuzz integrates with Rust's coverage tools to analyze fuzzing effectiveness.

Prerequisites

bash
rustup toolchain install nightly --component llvm-tools-previewcargo install cargo-binutilscargo install rustfilt

Generating Coverage Reports

bash
# Generate coverage data from corpuscargo +nightly fuzz coverage fuzz_target_1

Create coverage generation script:

bash
cat <<'EOF' > ./generate_html#!/bin/shif [ $# -lt 1 ]; then    echo "Error: Name of fuzz target is required."    echo "Usage: $0 fuzz_target [sources...]"    exit 1fiFUZZ_TARGET="$1"shiftSRC_FILTER="$@"TARGET=$(rustc -vV | sed -n 's|host: ||p')cargo +nightly cov -- show -Xdemangler=rustfilt \  "target/$TARGET/coverage/$TARGET/release/$FUZZ_TARGET" \  -instr-profile="fuzz/coverage/$FUZZ_TARGET/coverage.profdata"  \  -show-line-counts-or-regions -show-instantiations  \  -format=html -o fuzz_html/ $SRC_FILTEREOFchmod +x ./generate_html

Generate HTML report:

bash
./generate_html fuzz_target_1 src/lib.rs

HTML report saved to: fuzz_html/

See Also: For detailed coverage analysis techniques and systematic coverage improvement, see the coverage-analysis technique skill.

Advanced Usage

Tips and Tricks

TipWhy It Helps
Start with a seed corpusDramatically speeds up initial coverage discovery
Use --sanitizer none for safe Rust2x performance improvement
Check coverage regularlyIdentifies gaps in harness or seed corpus
Use dictionaries for parsersHelps overcome magic value checks
Structure code as libraryRequired for cargo-fuzz integration

libFuzzer Options

Pass options to libFuzzer after --:

bash
# See all optionscargo +nightly fuzz run fuzz_target_1 -- -help=1
# Set timeout per runcargo +nightly fuzz run fuzz_target_1 -- -timeout=10
# Use dictionarycargo +nightly fuzz run fuzz_target_1 -- -dict=dict.dict
# Limit maximum input sizecargo +nightly fuzz run fuzz_target_1 -- -max_len=1024

Multi-Core Fuzzing

bash
# Experimental forking support (not recommended)cargo +nightly fuzz run --jobs 1 fuzz_target_1

Note: The multi-core fuzzing feature is experimental and not recommended. For parallel fuzzing, consider running multiple instances manually or using AFL++.

Real-World Examples

Example: ogg Crate

The ogg crate parses Ogg media container files. Parsers are excellent fuzzing targets because they handle untrusted data.

bash
# Clone and initializegit clone https://github.com/RustAudio/ogg.gitcd ogg/cargo fuzz init

Harness at fuzz/fuzz_targets/fuzz_target_1.rs:

rust
#![no_main]
use ogg::{PacketReader, PacketWriter};use ogg::writing::PacketWriteEndInfo;use std::io::Cursor;use libfuzzer_sys::fuzz_target;
fn harness(data: &[u8]) {    let mut pck_rdr = PacketReader::new(Cursor::new(data.to_vec()));    pck_rdr.delete_unread_packets();
    let output = Vec::new();    let mut pck_wtr = PacketWriter::new(Cursor::new(output));
    if let Ok(_) = pck_rdr.read_packet() {        if let Ok(r) = pck_rdr.read_packet() {            match r {                Some(pck) => {                    let inf = if pck.last_in_stream() {                        PacketWriteEndInfo::EndStream                    } else if pck.last_in_page() {                        PacketWriteEndInfo::EndPage                    } else {                        PacketWriteEndInfo::NormalPacket                    };                    let stream_serial = pck.stream_serial();                    let absgp_page = pck.absgp_page();                    let _ = pck_wtr.write_packet(                        pck.data, stream_serial, inf, absgp_page                    );                }                None => return,            }        }    }}
fuzz_target!(|data: &[u8]| {    harness(data);});

Seed the corpus:

bash
mkdir fuzz/corpus/fuzz_target_1/curl -o fuzz/corpus/fuzz_target_1/320x240.ogg \  https://commons.wikimedia.org/wiki/File:320x240.ogg

Run:

bash
cargo +nightly fuzz run fuzz_target_1

Analyze coverage:

bash
cargo +nightly fuzz coverage fuzz_target_1./generate_html fuzz_target_1 src/lib.rs

Troubleshooting

ProblemCauseSolution
"requires nightly" errorUsing stable toolchainUse cargo +nightly fuzz
Slow fuzzing performanceASan enabled for safe RustAdd --sanitizer none flag
"cannot find binary"No library crateMove code from main.rs to lib.rs
Sanitizer compilation issuesWrong nightly versionTry different nightly: rustup install nightly-2024-01-01
Low coverageMissing seed corpusAdd sample inputs to fuzz/corpus/fuzz_target_1/
Magic value not foundNo dictionaryCreate dictionary file with magic values

Related Skills

Technique Skills

SkillUse Case
fuzz-harness-writingStructure-aware fuzzing with arbitrary crate
address-sanitizerUnderstanding ASan output and configuration
coverage-analysisMeasuring and improving fuzzing effectiveness
fuzzing-corpusBuilding and managing seed corpora
fuzzing-dictionariesCreating dictionaries for format-aware fuzzing

Related Fuzzers

SkillWhen to Consider
libfuzzerFuzzing C/C++ code with similar workflow
aflppMulti-core fuzzing or non-Cargo Rust projects
libaflAdvanced fuzzing research or custom fuzzer development

Resources

Rust Fuzz Book - cargo-fuzz Official documentation for cargo-fuzz covering installation, usage, and advanced features.

arbitrary crate documentation Guide to structure-aware fuzzing with automatic derivation for Rust types.

cargo-fuzz GitHub Repository Source code, issue tracker, and examples for cargo-fuzz.

来源与署名

来源:trailofbits/skills位于plugins/testing-handbook-skills/skills/cargo-fuzz提交82fe822

许可证: 无许可证

内容归原作者所有。SourceWeft 从公开仓库中收录这些内容。

举报或申请下架