模糊模組

libfuzzer-sys crate 可支援 Rust 模糊測試,提供與 LLVM 的 libFuzzer 模糊測試引擎繫結的功能。詳情請參閱 libfuzzer-sys 以及 LLVM libFuzzer 專案頁面

rust_fuzz 模組會產生模糊處理器二進位檔,並在執行時開始模糊處理 (類似 cc_fuzz 模組)。模糊效果會使用 libFuzzer 模糊測試引擎則可以使用多個引數來控制模糊化。這些 列舉顯示於 libFuzzer 說明文件

rust_fuzz 模組是 rust_binary 模組的擴充功能,因此會共用相同的屬性和考量事項。此外,它們實作許多與 cc_fuzz 模組相同的屬性和功能。

建構 rust_fuzz 模組時,會發出 --cfg fuzzing 旗標,這可表示 用於支援程式庫程式碼的條件式編譯,以改善模糊化作業。

編寫基本的 Rust 模糊元素

您可以使用以下程式碼,在 Android.bp 建構檔案中定義模糊測試模組:

rust_fuzz {
    name: "example_rust_fuzzer",
    srcs: ["fuzzer.rs"],

    // Config for running the target on fuzzing infrastructure can be set under
    // fuzz_config. This shares the same properties as cc_fuzz's fuzz_config.
    fuzz_config: {
        fuzz_on_haiku_device: true,
        fuzz_on_haiku_host: false,
    },

    // Path to a corpus of sample inputs, optional. See https://llvm.org/docs/LibFuzzer.html#corpus
    corpus: ["testdata/*"],

    // Path to a dictionary of sample byte sequences, optional. See https://llvm.org/docs/LibFuzzer.html#dictionaries
    dictionary: "example_rust_fuzzer.dict",
}

fuzzer.rs 檔案包含簡單的模糊測試器:

fn heap_oob() {
    let xs = vec![0, 1, 2, 3];
    let val = unsafe { *xs.as_ptr().offset(4) };
    println!("Out-of-bounds heap value: {}", val);
}

fuzz_target!(|data: &[u8]| {
    let magic_number = 327;
    if data.len() == magic_number {
        heap_oob();
    }
});

這裡的 fuzz_target!(|data: &[u8]| { /* fuzz using data here */ }); 會定義 libFuzzer 引擎呼叫的模糊目標進入點。data 引數是 由 libFuzzer 引擎提供,做為輸入操作操控的位元組序列 來模糊指定函式。

在這個範例中,模糊效果只會檢查資料長度,以判斷 是否呼叫 heap_oob 函式,如果呼叫, 資料是否超出範圍libFuzzer 是涵蓋率導向的模糊測試器,因此當它判斷前 326 B 的資料不會產生新的執行路徑時,就會快速收斂問題長度。

tools/security/fuzzing/example_rust_fuzzer/ 的樹狀結構中,找到這個範例。 如要查看樹狀結構中另一個用於模糊處理 rustlib 依附元件的較複雜的模糊處理器範例,請參閱 legacy_blob_fuzzer

如需如何編寫結構感知的 Rust 模糊測試指引, 請參閱 Rust Fuzz 書籍,這是 Rust Fuzz 專案的官方說明文件。