Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add fuzzing target to fuzz return type and parameters #301

Merged
merged 2 commits into from
Mar 5, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/Fuzzing.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ permissions:
contents: read

jobs:

fuzzing:
uses: ./.github/workflows/dep_fuzzing.yml
with:
targets: '["host_print", "guest_call", "host_call"]' # Pass as a JSON array
max_total_time: 18000 # 5 hours in seconds
secrets: inherit
1 change: 1 addition & 0 deletions .github/workflows/ValidatePullRequest.yml
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ jobs:
- docs-pr
uses: ./.github/workflows/dep_fuzzing.yml
with:
targets: '["host_print", "guest_call", "host_call"]' # Pass as a JSON array
max_total_time: 300 # 5 minutes in seconds
docs_only: ${{needs.docs-pr.outputs.docs-only}}
secrets: inherit
Expand Down
11 changes: 9 additions & 2 deletions .github/workflows/dep_fuzzing.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ on:
description: Maximum total time for the fuzz run in seconds
required: true
type: number
targets:
description: Fuzz targets to run
required: true
type: string
docs_only:
description: Skip fuzzing if docs only
required: false
Expand All @@ -21,6 +25,9 @@ jobs:
fuzz:
if: ${{ inputs.docs_only == 'false' }}
runs-on: [ self-hosted, Linux, X64, "1ES.Pool=hld-kvm-amd" ]
strategy:
matrix:
target: ${{ fromJson(inputs.targets) }}
steps:
- name: Checkout code
uses: actions/checkout@v4
Expand All @@ -44,12 +51,12 @@ jobs:
run: cargo install cargo-fuzz

- name: Run Fuzzing
run: cargo +nightly fuzz run --release fuzz_target_1 -- -max_total_time=300
run: just fuzz-timed ${{ matrix.target }} ${{ inputs.max_total_time }}
working-directory: src/hyperlight_host

- name: Upload Crash Artifacts
if: failure() # This ensures artifacts are only uploaded on failure
uses: actions/upload-artifact@v4
with:
name: fuzz-crash-artifacts
path: src/hyperlight_host/fuzz/artifacts/
path: fuzz/artifacts/
33 changes: 24 additions & 9 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ members = [
"src/hyperlight_host",
"src/hyperlight_guest_capi",
"src/hyperlight_testing",
"src/hyperlight_host/fuzz",
"fuzz",
]
# Because hyperlight-guest has custom linker flags,
# we exclude it from the default-members list
Expand Down
11 changes: 7 additions & 4 deletions Justfile
Original file line number Diff line number Diff line change
Expand Up @@ -190,8 +190,11 @@ bench target=default-target features="":
cargo bench --profile={{ if target == "debug" { "dev" } else { target } }} {{ if features =="" {''} else { "--features " + features } }} -- --verbose

# FUZZING
fuzz:
cd src/hyperlight_host && cargo +nightly fuzz run fuzz_target_1

fuzz-timed:
cd src/hyperlight_host && cargo +nightly fuzz run fuzz_target_1 -- -max_total_time=300
# Fuzzes the given target
fuzz fuzz-target:
cargo +nightly fuzz run {{ fuzz-target }} --release

# Fuzzes the given target. Stops after `max_time` seconds
fuzz-timed fuzz-target max_time:
cargo +nightly fuzz run {{ fuzz-target }} --release -- -max_total_time={{ max_time }}
File renamed without changes.
34 changes: 34 additions & 0 deletions fuzz/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
[package]
name = "hyperlight-fuzz"
version = "0.0.0"
publish = false
edition = { workspace = true }

[package.metadata]
cargo-fuzz = true

[dependencies]
libfuzzer-sys = "0.4"
hyperlight-testing = { workspace = true }
hyperlight-host = { workspace = true, default-features = true, features = ["fuzzing"]}

[[bin]]
name = "host_print"
path = "fuzz_targets/host_print.rs"
test = false
doc = false
bench = false

[[bin]]
name = "guest_call"
path = "fuzz_targets/guest_call.rs"
test = false
doc = false
bench = false

[[bin]]
name = "host_call"
path = "fuzz_targets/host_call.rs"
test = false
doc = false
bench = false
14 changes: 5 additions & 9 deletions src/hyperlight_host/fuzz/README.md → fuzz/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,19 @@ This directory contains the fuzzing infrastructure for Hyperlight. We use `cargo

You can run the fuzzers with:
```sh
cargo +nightly-2023-11-28-x86_64-unknown-linux-gnu fuzz run --release <fuzzer_name>
just fuzz <fuzz_target>
```

> Note: Because nightly toolchains are not stable, we pin the nightly version to `2023-11-28`. To install this toolchain, run:
> ```sh
> rustup toolchain install nightly-2023-11-28-x86_64-unknown-linux-gnu
> ```
which evaluates to the following command `cargo +nightly fuzz run host_print --release`. We use the release profile to make sure the release-optimized guest is used. The default fuzz profile which is release+debugsymbols would cause our debug guests to be loaded, since we currently determine which test guest to load based on whether debug symbols are present.

As per Microsoft's Offensive Research & Security Engineering (MORSE) team, all host exposed functions that receive or interact with guest data must be continuously fuzzed for, at least, 500 million fuzz test cases without any crashes. Because `cargo-fuzz` doesn't support setting a maximum number of iterations; instead, we use the `--max_total_time` flag to set a maximum time to run the fuzzer. We have a GitHub action (acting like a CRON job) that runs the fuzzers for 24 hours every week.

Currently, we only fuzz the `PrintOutput` function. We plan to add more fuzzers in the future.
Currently, we fuzz the parameters and return type to a hardcoded `PrintOutput` guest function, and the `HostPrint` host function. We plan to add more fuzzers in the future.

## On Failure

If you encounter a failure, you can re-run an entire seed (i.e., group of inputs) with:
```sh
cargo +nightly-2023-11-28-x86_64-unknown-linux-gnu fuzz run --release <fuzzer_name> -- -seed=<seed-number>
cargo +nightly fuzz run <fuzzer_target> -- -seed=<seed-number>
```

The seed number can be seed in a specific run, like:
Expand All @@ -29,5 +25,5 @@ The seed number can be seed in a specific run, like:
Or, if repro-ing a failure from CI, you can download the artifact from the fuzzing run, and run it like:

```sh
cargo +nightly-2023-11-28-x86_64-unknown-linux-gnu fuzz run --release -O <fuzzer_name> <fuzzer-input (e.g., fuzz/artifacts/fuzz_target_1/crash-93c522e64ee822034972ccf7026d3a8f20d5267c>
cargo +nightly fuzz run -O <fuzzer_target> <fuzzer-input (e.g., fuzz/artifacts/fuzz_target_1/crash-93c522e64ee822034972ccf7026d3a8f20d5267c>
```
Original file line number Diff line number Diff line change
Expand Up @@ -16,35 +16,35 @@ limitations under the License.

#![no_main]

use hyperlight_host::func::{ParameterValue, ReturnType, ReturnValue};
use std::sync::{Mutex, OnceLock};

use hyperlight_host::func::{ParameterValue, ReturnType};
use hyperlight_host::sandbox::uninitialized::GuestBinary;
use hyperlight_host::sandbox_state::sandbox::EvolvableSandbox;
use hyperlight_host::sandbox_state::transition::Noop;
use hyperlight_host::{MultiUseSandbox, UninitializedSandbox};
use hyperlight_testing::simple_guest_as_string;
use libfuzzer_sys::fuzz_target;

fuzz_target!(|data: &[u8]| {
let u_sbox = UninitializedSandbox::new(
GuestBinary::FilePath(simple_guest_as_string().expect("Guest Binary Missing")),
None,
None,
None,
)
.unwrap();

let mu_sbox: MultiUseSandbox = u_sbox.evolve(Noop::default()).unwrap();

let msg = String::from_utf8_lossy(data).to_string();
let len = msg.len() as i32;
let mut ctx = mu_sbox.new_call_context();
let result = ctx
.call(
"PrintOutput",
ReturnType::Int,
Some(vec![ParameterValue::String(msg.clone())]),
static SANDBOX: OnceLock<Mutex<MultiUseSandbox>> = OnceLock::new();

// This fuzz target tests all combinations of ReturnType and Parameters for `call_guest_function_by_name`.
// For fuzzing efficiency, we create one Sandbox and reuse it for all fuzzing iterations.
fuzz_target!(
init: {
let u_sbox = UninitializedSandbox::new(
GuestBinary::FilePath(simple_guest_as_string().expect("Guest Binary Missing")),
None,
None,
None,
)
.unwrap();

assert_eq!(result, ReturnValue::Int(len));
});
let mu_sbox: MultiUseSandbox = u_sbox.evolve(Noop::default()).unwrap();
SANDBOX.set(Mutex::new(mu_sbox)).unwrap();
},

|data: (ReturnType, Option<Vec<ParameterValue>>)| {
let mut sandbox = SANDBOX.get().unwrap().lock().unwrap();
let _ = sandbox.call_guest_function_by_name("PrintOutput", data.0, data.1);
}
);
59 changes: 59 additions & 0 deletions fuzz/fuzz_targets/host_call.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/*
Copyright 2024 The Hyperlight Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

#![no_main]

use std::sync::{Mutex, OnceLock};

use hyperlight_host::func::{ParameterValue, ReturnType};
use hyperlight_host::sandbox::uninitialized::GuestBinary;
use hyperlight_host::sandbox::SandboxConfiguration;
use hyperlight_host::sandbox_state::sandbox::EvolvableSandbox;
use hyperlight_host::sandbox_state::transition::Noop;
use hyperlight_host::{HyperlightError, MultiUseSandbox, UninitializedSandbox};
use hyperlight_testing::simple_guest_as_string;
use libfuzzer_sys::fuzz_target;
static SANDBOX: OnceLock<Mutex<MultiUseSandbox>> = OnceLock::new();

// This fuzz target tests all combinations of ReturnType and Parameters for `call_guest_function_by_name`.
// For fuzzing efficiency, we create one Sandbox and reuse it for all fuzzing iterations.
fuzz_target!(
init: {
let u_sbox = UninitializedSandbox::new(
GuestBinary::FilePath(simple_guest_as_string().expect("Guest Binary Missing")),
None,
None,
None,
)
.unwrap();

let mu_sbox: MultiUseSandbox = u_sbox.evolve(Noop::default()).unwrap();
SANDBOX.set(Mutex::new(mu_sbox)).unwrap();
},

|data: (String, ReturnType, Vec<ParameterValue>)| {
let (host_func_name, host_func_return, mut host_func_params) = data;
let mut sandbox = SANDBOX.get().unwrap().lock().unwrap();
host_func_params.insert(0, ParameterValue::String(host_func_name));
match sandbox.call_guest_function_by_name("FuzzHostFunc", host_func_return, Some(host_func_params)) {
Err(HyperlightError::GuestAborted(_, message)) if !message.contains("Host Function Not Found") => {
// We don't allow GuestAborted errors, except for the "Host Function Not Found" case
panic!("Guest Aborted: {}", message);
}
_ => {}
}
}
);
51 changes: 51 additions & 0 deletions fuzz/fuzz_targets/host_print.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
#![no_main]

use std::sync::{Mutex, OnceLock};

use hyperlight_host::func::{ParameterValue, ReturnType, ReturnValue};
use hyperlight_host::sandbox::uninitialized::GuestBinary;
use hyperlight_host::sandbox_state::sandbox::EvolvableSandbox;
use hyperlight_host::sandbox_state::transition::Noop;
use hyperlight_host::{MultiUseSandbox, UninitializedSandbox};
use hyperlight_testing::simple_guest_as_string;
use libfuzzer_sys::{fuzz_target, Corpus};

static SANDBOX: OnceLock<Mutex<MultiUseSandbox>> = OnceLock::new();

// This fuzz target is used to test the HostPrint host function. We generate
// an arbitrary ParameterValue::String, which is passed to the guest, which passes
// it without modification to the host function.
// For fuzzing efficiency, we create one Sandbox and reuse it for all fuzzing iterations.
fuzz_target!(
init: {
let u_sbox = UninitializedSandbox::new(
GuestBinary::FilePath(simple_guest_as_string().expect("Guest Binary Missing")),
None,
None,
None,
)
.unwrap();

let mu_sbox: MultiUseSandbox = u_sbox.evolve(Noop::default()).unwrap();
SANDBOX.set(Mutex::new(mu_sbox)).unwrap();
},

|data: ParameterValue| -> Corpus {
// only interested in String types
if !matches!(data, ParameterValue::String(_)) {
return Corpus::Reject;
}

let mut sandbox = SANDBOX.get().unwrap().lock().unwrap();
let res = sandbox.call_guest_function_by_name(
"PrintOutput",
ReturnType::Int,
Some(vec![data.clone()]),
);
match res {
Ok(ReturnValue::Int(len)) => assert!(len >= 0),
_ => panic!("Unexpected return value: {:?}", res),
}

Corpus::Keep
});
4 changes: 1 addition & 3 deletions rust-toolchain.toml
Original file line number Diff line number Diff line change
@@ -1,4 +1,2 @@
[toolchain]
channel = "1.81.0"
# if you update this, don't forget to change the pinned version
# of nightly we use in the fuzzing workflow.
channel = "1.81.0"
Loading
Loading