Skip to content
This repository was archived by the owner on Nov 26, 2024. It is now read-only.

Commit 53812e6

Browse files
committed
Add fuzzing for jsonrpc
Import the fuzzing from `jsonrpc` source: https://github.com/apoelstra/rust-jsonrpc commit hash: `59646e6e6ac95f07998133b1709e4a1fa2dbc7bd` commit: `59646e6 Merge apoelstra/rust-jsonrpc#119: Use rust-bitcoin-maintainer-tools and re-write CI` Then I update the `generate-files.sh` script to mimic a recent one from `rust-bitcoin`. Add a README explaining how we got to the current state.
1 parent 49b72c1 commit 53812e6

File tree

10 files changed

+447
-0
lines changed

10 files changed

+447
-0
lines changed

.github/workflows/cron-daily-fuzz.yml

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
# Automatically generated by fuzz/generate-files.sh
2+
name: Fuzz
3+
on:
4+
schedule:
5+
# 6am every day UTC, this correlates to:
6+
# - 11pm PDT
7+
# - 7am CET
8+
# - 5pm AEDT
9+
- cron: '00 06 * * *'
10+
11+
jobs:
12+
fuzz:
13+
if: ${{ !github.event.act }}
14+
runs-on: ubuntu-latest
15+
strategy:
16+
fail-fast: false
17+
matrix:
18+
# We only get 20 jobs at a time, we probably don't want to go
19+
# over that limit with fuzzing because of the hour run time.
20+
fuzz_target: [
21+
minreq_http,
22+
simple_http,
23+
]
24+
steps:
25+
- name: Install test dependencies
26+
run: sudo apt-get update -y && sudo apt-get install -y binutils-dev libunwind8-dev libcurl4-openssl-dev libelf-dev libdw-dev cmake gcc libiberty-dev
27+
- uses: actions/checkout@v4
28+
- uses: actions/cache@v4
29+
id: cache-fuzz
30+
with:
31+
path: |
32+
~/.cargo/bin
33+
fuzz/target
34+
target
35+
key: cache-${{ matrix.target }}-${{ hashFiles('**/Cargo.toml','**/Cargo.lock') }}
36+
- uses: dtolnay/rust-toolchain@stable
37+
with:
38+
toolchain: '1.65.0'
39+
- name: fuzz
40+
run: |
41+
if [[ "${{ matrix.fuzz_target }}" =~ ^bitcoin ]]; then
42+
export RUSTFLAGS='--cfg=hashes_fuzz --cfg=secp256k1_fuzz'
43+
fi
44+
echo "Using RUSTFLAGS $RUSTFLAGS"
45+
cd fuzz && ./fuzz.sh "${{ matrix.fuzz_target }}"
46+
- run: echo "${{ matrix.fuzz_target }}" >executed_${{ matrix.fuzz_target }}
47+
- uses: actions/upload-artifact@v3
48+
with:
49+
name: executed_${{ matrix.fuzz_target }}
50+
path: executed_${{ matrix.fuzz_target }}
51+
52+
verify-execution:
53+
if: ${{ !github.event.act }}
54+
needs: fuzz
55+
runs-on: ubuntu-latest
56+
steps:
57+
- uses: actions/checkout@v4
58+
- uses: actions/download-artifact@v3
59+
- name: Display structure of downloaded files
60+
run: ls -R
61+
- run: find executed_* -type f -exec cat {} + | sort > executed
62+
- run: source ./fuzz/fuzz-util.sh && listTargetNames | sort | diff - executed

fuzz/.gitignore

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
2+
target
3+
corpus
4+
artifacts

fuzz/Cargo.toml

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
[package]
2+
name = "jsonrpc-fuzz"
3+
edition = "2021"
4+
rust-version = "1.63.0"
5+
version = "0.0.1"
6+
authors = ["Generated by fuzz/generate-files.sh"]
7+
publish = false
8+
9+
[package.metadata]
10+
cargo-fuzz = true
11+
12+
[dependencies]
13+
honggfuzz = { version = "0.5.55", default-features = false }
14+
jsonrpc = { path = "..", features = ["minreq_http"] }
15+
16+
serde = { version = "1.0.103", features = [ "derive" ] }
17+
serde_json = "1.0"
18+
19+
[lints.rust]
20+
unexpected_cfgs = { level = "deny", check-cfg = ['cfg(fuzzing)'] }
21+
22+
[[bin]]
23+
name = "minreq_http"
24+
path = "fuzz_targets/minreq_http.rs"
25+
26+
[[bin]]
27+
name = "simple_http"
28+
path = "fuzz_targets/simple_http.rs"

fuzz/README.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# `bitcoind-json-rpc` fuzzing
2+
3+
Currently we only fuzz `jsonrpc`, the fuzz code was imported along
4+
with the `jsonrpc` import from `github.com/apoelstra/rust-jsonrpc`
5+
commit hash: `59646e6e6ac95f07998133b1709e4a1fa2dbc7bd` which is
6+
7+
commit: `59646e6 Merge apoelstra/rust-jsonrpc#119: Use rust-bitcoin-maintainer-tools and re-write CI`
8+
9+
Then I updated the `generate-files.sh` script to mimic a recent one from `rust-bitcoin`.
10+
11+
## Note to devs
12+
13+
If you are considering adding fuzzing for the other crates take a look at how we set up
14+
`fuzz_target` in `rust-bitcoin/fuzz`.

fuzz/cycle.sh

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
#!/usr/bin/env bash
2+
3+
# Continuosly cycle over fuzz targets running each for 1 hour.
4+
# It uses chrt SCHED_IDLE so that other process takes priority.
5+
#
6+
# For hfuzz options see https://github.com/google/honggfuzz/blob/master/docs/USAGE.md
7+
8+
set -e
9+
REPO_DIR=$(git rev-parse --show-toplevel)
10+
# shellcheck source=./fuzz-util.sh
11+
source "$REPO_DIR/fuzz/fuzz-util.sh"
12+
13+
while :
14+
do
15+
for targetFile in $(listTargetFiles); do
16+
targetName=$(targetFileToName "$targetFile")
17+
echo "Fuzzing target $targetName ($targetFile)"
18+
19+
# fuzz for one hour
20+
HFUZZ_RUN_ARGS='--run_time 3600' chrt -i 0 cargo hfuzz run "$targetName"
21+
# minimize the corpus
22+
HFUZZ_RUN_ARGS="-i hfuzz_workspace/$targetName/input/ -P -M" chrt -i 0 cargo hfuzz run "$targetName"
23+
done
24+
done

fuzz/fuzz-util.sh

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
#!/usr/bin/env bash
2+
3+
REPO_DIR=$(git rev-parse --show-toplevel)
4+
5+
# Sort order is effected by locale. See `man sort`.
6+
# > Set LC_ALL=C to get the traditional sort order that uses native byte values.
7+
export LC_ALL=C
8+
9+
listTargetFiles() {
10+
pushd "$REPO_DIR/fuzz" > /dev/null || exit 1
11+
find fuzz_targets/ -type f -name "*.rs" | sort
12+
popd > /dev/null || exit 1
13+
}
14+
15+
targetFileToName() {
16+
echo "$1" \
17+
| sed 's/^fuzz_targets\///' \
18+
| sed 's/\.rs$//' \
19+
| sed 's/\//_/g'
20+
}
21+
22+
targetFileToHFuzzInputArg() {
23+
baseName=$(basename "$1")
24+
dirName="${baseName%.*}"
25+
if [ -d "hfuzz_input/$dirName" ]; then
26+
echo "HFUZZ_INPUT_ARGS=\"-f hfuzz_input/$FILE/input\""
27+
fi
28+
}
29+
30+
listTargetNames() {
31+
for target in $(listTargetFiles); do
32+
targetFileToName "$target"
33+
done
34+
}
35+
36+
# Utility function to avoid CI failures on Windows
37+
checkWindowsFiles() {
38+
incorrectFilenames=$(find . -type f -name "*,*" -o -name "*:*" -o -name "*<*" -o -name "*>*" -o -name "*|*" -o -name "*\?*" -o -name "*\**" -o -name "*\"*" | wc -l)
39+
if [ "$incorrectFilenames" -gt 0 ]; then
40+
echo "Bailing early because there is a Windows-incompatible filename in the tree."
41+
exit 2
42+
fi
43+
}
44+
45+
# Checks whether a fuzz case output some report, and dumps it in hex
46+
checkReport() {
47+
reportFile="hfuzz_workspace/$1/HONGGFUZZ.REPORT.TXT"
48+
if [ -f "$reportFile" ]; then
49+
cat "$reportFile"
50+
for CASE in "hfuzz_workspace/$1/SIG"*; do
51+
xxd -p -c10000 < "$CASE"
52+
done
53+
exit 1
54+
fi
55+
}

fuzz/fuzz.sh

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
#!/usr/bin/env bash
2+
set -ex
3+
4+
REPO_DIR=$(git rev-parse --show-toplevel)
5+
6+
# shellcheck source=./fuzz-util.sh
7+
source "$REPO_DIR/fuzz/fuzz-util.sh"
8+
9+
# Check that input files are correct Windows file names
10+
checkWindowsFiles
11+
12+
if [ "$1" == "" ]; then
13+
targetFiles="$(listTargetFiles)"
14+
else
15+
targetFiles=fuzz_targets/"$1".rs
16+
fi
17+
18+
cargo --version
19+
rustc --version
20+
21+
# Testing
22+
cargo install --force honggfuzz --no-default-features
23+
for targetFile in $targetFiles; do
24+
targetName=$(targetFileToName "$targetFile")
25+
echo "Fuzzing target $targetName ($targetFile)"
26+
if [ -d "hfuzz_input/$targetName" ]; then
27+
HFUZZ_INPUT_ARGS="-f hfuzz_input/$targetName/input\""
28+
else
29+
HFUZZ_INPUT_ARGS=""
30+
fi
31+
RUSTFLAGS="--cfg=jsonrpc_fuzz" HFUZZ_RUN_ARGS="--run_time 30 --exit_upon_crash -v $HFUZZ_INPUT_ARGS" cargo hfuzz run "$targetName"
32+
33+
checkReport "$targetName"
34+
done

fuzz/fuzz_targets/minreq_http.rs

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
extern crate jsonrpc;
2+
3+
// Note, tests are empty if "jsonrpc_fuzz" is not set but still show up in output of `cargo test --workspace`.
4+
5+
#[allow(unused_variables)] // `data` is not used when "jsonrpc_fuzz" is not set.
6+
fn do_test(data: &[u8]) {
7+
#[cfg(jsonrpc_fuzz)]
8+
{
9+
use std::io;
10+
11+
use jsonrpc::minreq_http::{MinreqHttpTransport, FUZZ_TCP_SOCK};
12+
use jsonrpc::Client;
13+
14+
*FUZZ_TCP_SOCK.lock().unwrap() = Some(io::Cursor::new(data.to_vec()));
15+
16+
let t = MinreqHttpTransport::builder()
17+
.url("localhost:123")
18+
.expect("parse url")
19+
.basic_auth("".to_string(), None)
20+
.build();
21+
22+
let client = Client::with_transport(t);
23+
let request = client.build_request("uptime", None);
24+
let _ = client.send_request(request);
25+
}
26+
}
27+
28+
fn main() {
29+
loop {
30+
honggfuzz::fuzz!(|data| {
31+
do_test(data);
32+
});
33+
}
34+
}
35+
36+
#[cfg(test)]
37+
mod tests {
38+
fn extend_vec_from_hex(hex: &str) -> Vec<u8> {
39+
let mut out = vec![];
40+
let mut b = 0;
41+
for (idx, c) in hex.as_bytes().iter().enumerate() {
42+
b <<= 4;
43+
match *c {
44+
b'A'..=b'F' => b |= c - b'A' + 10,
45+
b'a'..=b'f' => b |= c - b'a' + 10,
46+
b'0'..=b'9' => b |= c - b'0',
47+
_ => panic!("Bad hex"),
48+
}
49+
if (idx & 1) == 1 {
50+
out.push(b);
51+
b = 0;
52+
}
53+
}
54+
out
55+
}
56+
57+
#[test]
58+
fn duplicate_crash() { super::do_test(&extend_vec_from_hex("00")); }
59+
}

fuzz/fuzz_targets/simple_http.rs

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
extern crate jsonrpc;
2+
3+
// Note, tests are if empty "jsonrpc_fuzz" is not set but still show up in output of `cargo test --workspace`.
4+
5+
#[allow(unused_variables)] // `data` is not used when "jsonrpc_fuzz" is not set.
6+
fn do_test(data: &[u8]) {
7+
#[cfg(jsonrpc_fuzz)]
8+
{
9+
use std::io;
10+
11+
use jsonrpc::simple_http::{SimpleHttpTransport, FUZZ_TCP_SOCK};
12+
use jsonrpc::Client;
13+
14+
*FUZZ_TCP_SOCK.lock().unwrap() = Some(io::Cursor::new(data.to_vec()));
15+
16+
let t = SimpleHttpTransport::builder()
17+
.url("localhost:123")
18+
.expect("parse url")
19+
.auth("", None)
20+
.build();
21+
22+
let client = Client::with_transport(t);
23+
let request = client.build_request("uptime", None);
24+
let _ = client.send_request(request);
25+
}
26+
}
27+
28+
fn main() {
29+
loop {
30+
honggfuzz::fuzz!(|data| {
31+
do_test(data);
32+
});
33+
}
34+
}
35+
36+
#[cfg(test)]
37+
mod tests {
38+
fn extend_vec_from_hex(hex: &str) -> Vec<u8> {
39+
let mut out = vec![];
40+
let mut b = 0;
41+
for (idx, c) in hex.as_bytes().iter().enumerate() {
42+
b <<= 4;
43+
match *c {
44+
b'A'..=b'F' => b |= c - b'A' + 10,
45+
b'a'..=b'f' => b |= c - b'a' + 10,
46+
b'0'..=b'9' => b |= c - b'0',
47+
_ => panic!("Bad hex"),
48+
}
49+
if (idx & 1) == 1 {
50+
out.push(b);
51+
b = 0;
52+
}
53+
}
54+
out
55+
}
56+
57+
#[test]
58+
fn duplicate_crash() { super::do_test(&extend_vec_from_hex("00")); }
59+
}

0 commit comments

Comments
 (0)