#!/usr/bin/env bash
#
# make-fuzz-harness.sh -- generate a libFuzzer harness, a build script and a
#                         seed corpus for a C function, with the sanitizer
#                         flags set correctly.
#
# Chapter 70 -- Vulnerability Research, scripts/
#
# PURPOSE
#   The boilerplate of starting a fuzzing campaign is the same every time and
#   is easy to get subtly wrong: the wrong sanitizer combination, a missing
#   -fno-omit-frame-pointer that costs you readable stack traces, a
#   -fsanitize=fuzzer link on Android that fails on undefined `ceilf`, a
#   harness that aborts on rejected input. This script writes the parts that
#   are mechanical so that your attention goes to the part that is not: which
#   bytes of the fuzzer's input are DATA and which are BEHAVIOUR SELECTORS.
#
#   It generates, into --out:
#       harness.c        the LLVMFuzzerTestOneInput adapter, with TODOs where
#                        judgement is required
#       build.sh         builds every variant the local toolchain supports
#       run.sh           a sensible default campaign invocation
#       corpus/          an empty directory, and a note about why seeds matter
#       NOTES.md         what you must decide before this harness is any good
#
# USAGE
#   ./make-fuzz-harness.sh --name acfg --func acfg_parse \
#        --sig 'int(const uint8_t*, size_t)' \
#        --header acfg.h --source acfg-vulnerable.c \
#        --out /tmp/acfg-harness
#
#   ./make-fuzz-harness.sh --name vimg --func vimg_decode \
#        --sig 'int(const uint8_t*, size_t)' \
#        --dlopen libvendorimg.so \
#        --out /tmp/vimg-harness
#
#   Options:
#     --name N        short name for the target (used in filenames)
#     --func F        the function to fuzz
#     --sig 'S'       its signature, for the generated declaration
#     --header H      a header to include (repeatable)
#     --source S      a .c file to compile in (repeatable)
#     --dlopen LIB    load LIB at runtime and resolve --func from it, instead
#                     of linking a source file. For prebuilt libraries
#     --out DIR       output directory (required)
#     --abi ABI       android abi for the cross build: arm64|arm|x86_64|x86
#     --api N         android api level for the cross build (default 24)
#     --force         overwrite an existing --out
#
# REQUIREMENTS
#   bash. The generated build.sh needs a C compiler; it detects clang, gcc and
#   the NDK and reports which variants it can and cannot produce.
#
# WHAT THIS WILL NOT TELL YOU
#   * Whether the generated harness reaches your target. It cannot. Run the
#     planted-crash check in chapter 70 section 7.10 before you trust a
#     campaign that comes out of this.
#   * How to carve the fuzzer's bytes into your function's arguments. That is
#     the actual work and it is left as a marked TODO on purpose -- a generator
#     that guessed would produce harnesses that run and test nothing.
#   * Whether your target has state that must be reset between calls. If it
#     does and you do not reset it, your crashes will not reproduce and you
#     will conclude they were flukes. Section 3.4 rule 1.
#   * Whether the function even exists in the library at runtime. --dlopen
#     harnesses trap at startup when the symbol is missing, which is loud on
#     purpose.

set -eu

NAME=""
FUNC=""
SIG="int(const uint8_t*, size_t)"
OUT=""
DLOPEN=""
ABI="x86_64"
API="24"
FORCE=0
HEADERS=()
SOURCES=()

die() { printf 'error: %s\n' "$*" >&2; exit 1; }

usage() {
    sed -n '2,60p' "$0" | sed 's/^# \{0,1\}//'
    exit "${1:-0}"
}

while [ $# -gt 0 ]; do
    case "$1" in
        --name)    NAME="$2"; shift 2 ;;
        --func)    FUNC="$2"; shift 2 ;;
        --sig)     SIG="$2"; shift 2 ;;
        --header)  HEADERS+=("$2"); shift 2 ;;
        --source)  SOURCES+=("$2"); shift 2 ;;
        --dlopen)  DLOPEN="$2"; shift 2 ;;
        --out)     OUT="$2"; shift 2 ;;
        --abi)     ABI="$2"; shift 2 ;;
        --api)     API="$2"; shift 2 ;;
        --force)   FORCE=1; shift ;;
        -h|--help) usage 0 ;;
        *) die "unknown option: $1 (try --help)" ;;
    esac
done

[ -n "$NAME" ] || die "--name is required"
[ -n "$FUNC" ] || die "--func is required"
[ -n "$OUT" ]  || die "--out is required"

if [ -e "$OUT" ] && [ "$FORCE" != "1" ]; then
    die "$OUT already exists (use --force to overwrite)"
fi

mkdir -p "$OUT/corpus" "$OUT/findings"

# ---------------------------------------------------------------------------
# harness.c
# ---------------------------------------------------------------------------

{
cat <<HEADER
/*
 * harness.c -- fuzzing harness for ${FUNC}().
 *
 * Generated by 70-VulnerabilityResearch/scripts/make-fuzz-harness.sh
 *
 * THE FIVE RULES this file follows (chapter 70 section 3.4). Do not break them
 * when you edit it:
 *   1. No state carried across calls. This function runs millions of times in
 *      one process; state makes crashes depend on order and destroys
 *      reproducibility.
 *   2. Free everything on every path, including error paths.
 *   3. No output per iteration. A printf here costs more than most parses.
 *   4. Never abort() on input the target merely dislikes. A rejected input is
 *      correct behaviour, not a finding.
 *   5. READ what the target produced. A harness that parses and frees tests
 *      only the parser; missing NUL terminators and bad accessors stay
 *      invisible unless something reads the fields.
 */

#include <stdint.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
HEADER

if [ -n "$DLOPEN" ]; then
    printf '#include <dlfcn.h>\n'
fi

for h in "${HEADERS[@]:-}"; do
    [ -n "$h" ] && printf '#include "%s"\n' "$(basename "$h")"
done

cat <<'SINK'

/*
 * File-scope volatile sink for values read out of the parsed object.
 *
 * It must be volatile, or the optimiser deletes the reads and the coverage
 * they generate disappears -- a harness that tests LESS the harder you
 * optimise it.
 *
 * It must be at file scope and not a function-local static, because clang's
 * -Wunused-but-set-variable fires on a local that is only written, and a build
 * with -Werror then fails. Measured: gcc 11.4 accepts the local form, clang 14
 * (NDK r25c) rejects it.
 */
static volatile size_t g_sink;
SINK

if [ -n "$DLOPEN" ]; then
cat <<DLO

/* --- prebuilt-library mode -------------------------------------------------
 *
 * The target lives in ${DLOPEN}, which we load at startup and resolve by name.
 *
 * WARNING, and read this before you report anything found this way: a library
 * fuzzed in isolation is missing everything its real caller does -- the
 * initialisation, the allocator state, the threading, and above all the checks
 * the CALLER performs before handing over the buffer. A crash found here may
 * be unreachable in production. Every finding from this mode needs level 3 or
 * level 4 reachability evidence before it is a finding at all. Section 6.4.
 */
typedef int (*target_fn)(const uint8_t *, size_t);
static target_fn g_target;

int LLVMFuzzerInitialize(int *argc, char ***argv);

int LLVMFuzzerInitialize(int *argc, char ***argv)
{
    void *h;
    (void)argc; (void)argv;

    /* One-time setup belongs HERE, not in TestOneInput, or you pay for it a
     * million times. */
    h = dlopen("${DLOPEN}", RTLD_NOW);
    if (h == NULL) {
        /* Trap loudly at startup rather than crashing per-input, so the
         * failure is unmistakably an environment problem and not a finding. */
        __builtin_trap();
    }
    g_target = (target_fn)dlsym(h, "${FUNC}");
    if (g_target == NULL) {
        __builtin_trap();
    }
    return 0;
}
DLO
elif [ "${#HEADERS[@]}" -eq 0 ]; then
    # Only emit a fallback declaration when no header was supplied. Emitting
    # one anyway produces "conflicting types for ..." against the real
    # prototype, which is a generator bug that costs the user five minutes of
    # believing their toolchain is broken. Found by testing this script.
    #
    # The declaration is derived from --sig by inserting the function name at
    # the parameter list, so a three-argument signature declares three
    # arguments rather than being silently wrong.
    printf '\n/* No --header supplied, so the prototype is derived from --sig. */\n'
    printf 'extern %s;\n' "$(printf '%s' "$SIG" | sed "s/(/ ${FUNC}(/")"
else
    printf '\n/* Prototype comes from the supplied header(s). */\n'
fi

cat <<BODY

int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size);

int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
{
    /*
     * ============================ TODO 1 ============================
     * CARVE THE INPUT.
     *
     * If ${FUNC} takes more than a buffer, take the extra arguments out of the
     * front of the fuzzer's input -- and CONSTRAIN the ones that select
     * behaviour while leaving the ones that are data unconstrained:
     *
     *     if (size < 1) return 0;
     *     uint8_t mode = data[0] % NUMBER_OF_VALID_MODES;
     *     data += 1; size -= 1;
     *
     * Without the modulo, most of the input space hits an "invalid mode" error
     * path and the campaign spends its life proving that invalid modes are
     * rejected. This is the commonest reason a harness plateaus at low
     * coverage. Section 3.4.
     * ================================================================
     */

    /*
     * ============================ TODO 2 ============================
     * IF THE FORMAT HAS A CHECKSUM, fix it up here before calling the target.
     * A byte-oriented mutator invalidates a checksum with every mutation and
     * will never get past the check. Recomputing it in the harness is
     * legitimate and standard -- you are testing the parser, not the checksum
     * -- but note it in your findings, because the reachability argument must
     * account for the attacker being able to compute it too. They usually can:
     * the algorithm is in the binary.
     * ================================================================
     */

BODY

if [ -n "$DLOPEN" ]; then
cat <<'CALLD'
    if (g_target == NULL) {
        return 0;
    }
    g_target(data, size);
CALLD
else
    # How many parameters does the declared signature have? If it is not the
    # simple (buffer, length) shape, the generated call CANNOT be right, and
    # the honest thing is to fail the build loudly rather than emit something
    # that compiles and tests the wrong thing.
    ARGC=$(printf '%s' "$SIG" | sed 's/.*(//; s/).*//' | awk -F, '{print NF}')
    if [ "${ARGC:-2}" -le 2 ]; then
cat <<CALLS
    ${FUNC}(data, size);
CALLS
    else
cat <<CALLX
#error "TODO 1 is not done: ${FUNC} takes ${ARGC} arguments, not 2. Carve them \\
out of the fuzzer input above, replace this directive with the real call, and \\
remember to constrain any argument that selects behaviour. A generator that \\
guessed here would produce a harness that compiles and tests nothing."

    /* ${FUNC}(...);   <-- signature given was: ${SIG} */
CALLX
    fi
fi

cat <<'TAIL'

    /*
     * ============================ TODO 3 ============================
     * READ THE OUTPUT (rule 5). If ${FUNC} fills a structure, walk it and
     * accumulate the fields into g_sink:
     *
     *     size_t acc = 0;
     *     for (i = 0; i < out.count; i++) {
     *         acc += strlen(out.items[i].name);   // catches a missing NUL
     *         acc += out.items[i].type;
     *     }
     *     g_sink = acc;
     *
     * A missing terminator produces NO symptom at all without a read like
     * this, and it ships.
     * ================================================================
     */

    /*
     * ============================ TODO 4 ============================
     * FREE EVERYTHING (rule 2), on every path including the error paths.
     * Calling the free function unconditionally also tests the target's
     * promise that freeing a failed parse is safe -- which is its own bug
     * class. Section 5.5.
     * ================================================================
     */

    return 0;   /* libFuzzer requires 0. Other values are reserved. */
}
TAIL
} > "$OUT/harness.c"

# ---------------------------------------------------------------------------
# build.sh
# ---------------------------------------------------------------------------

SRC_LIST=""
for s in "${SOURCES[@]:-}"; do
    [ -n "$s" ] && SRC_LIST="$SRC_LIST $(basename "$s")"
done

for f in "${HEADERS[@]:-}" "${SOURCES[@]:-}"; do
    [ -n "${f:-}" ] && [ -f "$f" ] && cp -f "$f" "$OUT/"
done

cat > "$OUT/build.sh" <<BUILD
#!/usr/bin/env bash
#
# build.sh -- build the ${NAME} harness with every variant this machine can
#             produce. Generated by make-fuzz-harness.sh.
#
# The flag choices are the point of this file. Read them before you change one.

set -u
HERE="\$(cd "\$(dirname "\${BASH_SOURCE[0]}")" && pwd)"
SRCS="harness.c${SRC_LIST}"

# -g                       symbols, so stack traces name functions and lines.
#                          Without this every triage report is hex addresses.
# -O1                      fast enough to fuzz, low enough that the optimiser
#                          has not rearranged the code beyond recognition.
#                          -O0 is too slow; -O2 makes line numbers lie.
# -fno-omit-frame-pointer  readable stack traces. Costs one register.
# -Wall -Wextra            the compiler finds bugs for free.
COMMON="-std=c11 -Wall -Wextra -g -O1 -fno-omit-frame-pointer -I\$HERE"

ok=0; skip=0; fail=0

echo "=== host, clang + libFuzzer + ASan + UBSan ==="
if command -v clang >/dev/null 2>&1 && \\
   printf '#include <stdint.h>\\n#include <stddef.h>\\nint LLVMFuzzerTestOneInput(const uint8_t*d,size_t n){(void)d;(void)n;return 0;}\\n' \\
     > /tmp/.probe\$\$.c && clang -fsanitize=fuzzer /tmp/.probe\$\$.c -o /tmp/.probe\$\$ 2>/dev/null; then
    rm -f /tmp/.probe\$\$.c /tmp/.probe\$\$
    # -fsanitize=fuzzer,address,undefined is the standard combination.
    # address+memory and address+thread are MUTUALLY EXCLUSIVE and will not
    # link -- if you need MSan or TSan, build a separate binary.
    if (cd "\$HERE" && clang \$COMMON -fsanitize=fuzzer,address,undefined \\
            -fsanitize-address-use-after-scope \\
            \$SRCS -o fuzz_${NAME}); then
        echo "  [BUILT]   fuzz_${NAME}"; ok=\$((ok+1))
    else
        echo "  [FAILED]  fuzz_${NAME}"; fail=\$((fail+1))
    fi
else
    rm -f /tmp/.probe\$\$.c /tmp/.probe\$\$
    echo "  [SKIPPED] no clang with -fsanitize=fuzzer here"; skip=\$((skip+1))
fi

echo "=== host, gcc or clang + ASan + UBSan, no coverage feedback ==="
CC=""
command -v clang >/dev/null 2>&1 && CC=clang
[ -z "\$CC" ] && command -v gcc >/dev/null 2>&1 && CC=gcc
if [ -n "\$CC" ]; then
    echo "  note: this variant has NO libFuzzer main(). Supply your own driver,"
    echo "        or copy the standalone driver from"
    echo "        70-VulnerabilityResearch/examples/fuzz-acfg.c"
    if (cd "\$HERE" && \$CC \$COMMON -fsanitize=address,undefined -c harness.c -o harness.o); then
        echo "  [BUILT]   harness.o (\$CC)"; ok=\$((ok+1))
    else
        echo "  [FAILED]  harness.o"; fail=\$((fail+1))
    fi
else
    echo "  [SKIPPED] no host C compiler"; skip=\$((skip+1))
fi

echo "=== Android cross build (${ABI}, API ${API}) ==="
if [ -z "\${NDK:-}" ]; then
    echo "  [SKIPPED] NDK not set."
    echo "            export NDK=<ndk>/toolchains/llvm/prebuilt/<host>"
    skip=\$((skip+1))
else
    case "${ABI}" in
        arm64)  T="aarch64-linux-android${API}" ;;
        arm)    T="armv7a-linux-androideabi${API}" ;;
        x86_64) T="x86_64-linux-android${API}" ;;
        x86)    T="i686-linux-android${API}" ;;
        *)      T="" ;;
    esac
    CCA="\$NDK/bin/\$T-clang"
    [ -x "\$CCA" ] || CCA="\$NDK/bin/\$T-clang.cmd"
    if [ -z "\$T" ] || { [ ! -x "\$CCA" ] && [ ! -f "\$CCA" ]; }; then
        echo "  [SKIPPED] \$CCA not found"; skip=\$((skip+1))
    else
        # -lm is REQUIRED and its absence is not obvious. libclang_rt.fuzzer
        # for Android is C++ and references ceilf and sqrt from libm; the C
        # driver does not link libm by default, so the link fails with
        # "undefined symbol: ceilf" pointing at FuzzerDataFlowTrace.cpp.o
        # inside the sanitizer runtime rather than at your code.
        # Linking with \$T-clang++ instead works equally well.
        if (cd "\$HERE" && "\$CCA" \$COMMON -fsanitize=fuzzer,address \\
                \$SRCS -lm -o android_${ABI}_fuzz_${NAME}); then
            echo "  [BUILT]   android_${ABI}_fuzz_${NAME}"; ok=\$((ok+1))
            echo "  note: ASan on Android is a SHARED runtime. Push"
            echo "        libclang_rt.asan-<abi>-android.so next to the binary"
            echo "        and set LD_LIBRARY_PATH, or it will not start."
            echo "  note: check your target's page size first --"
            echo "        'adb shell getconf PAGE_SIZE'. NDK r25 and earlier"
            echo "        produce 4 KB-aligned binaries that SEGFAULT on a"
            echo "        16 KB-page image, including a three-line main()."
        else
            echo "  [FAILED]  android_${ABI}_fuzz_${NAME}"; fail=\$((fail+1))
        fi
    fi
fi

echo ""
echo "built=\$ok skipped=\$skip failed=\$fail"
[ "\$fail" -eq 0 ]
BUILD
chmod +x "$OUT/build.sh"

# ---------------------------------------------------------------------------
# run.sh
# ---------------------------------------------------------------------------

cat > "$OUT/run.sh" <<RUN
#!/usr/bin/env bash
#
# run.sh -- a sensible default campaign for the ${NAME} harness.
#
# Every flag here is deliberate; see chapter 70 section 7.1 for the full table.

set -eu
HERE="\$(cd "\$(dirname "\${BASH_SOURCE[0]}")" && pwd)"
cd "\$HERE"

# halt_on_error for UBSan is NOT the default, and without it a UBSan-only
# finding prints one line, the process continues, and your campaign exits 0
# with the bug sitting in the log. Chapter 70 section 3.7 measured exactly
# this happening.
export ASAN_OPTIONS="\${ASAN_OPTIONS:-abort_on_error=1:detect_leaks=1:allocator_may_return_null=0}"
export UBSAN_OPTIONS="\${UBSAN_OPTIONS:-halt_on_error=1:print_stacktrace=1}"

[ -x ./fuzz_${NAME} ] || { echo "build it first: ./build.sh"; exit 1; }

# -max_len       cap the input size. Unbounded inputs waste enormous time.
# -seed          fix the PRNG so two campaigns are comparable. Without this,
#                "it found it at execution N" is not a reproduction step.
# -print_final_stats  your evidence of what the campaign actually did.
exec ./fuzz_${NAME} corpus/ \\
    -artifact_prefix=findings/ \\
    -max_len="\${MAX_LEN:-4096}" \\
    -seed="\${SEED:-1}" \\
    -print_final_stats=1 \\
    "\$@"
RUN
chmod +x "$OUT/run.sh"

# ---------------------------------------------------------------------------
# NOTES.md
# ---------------------------------------------------------------------------

cat > "$OUT/NOTES.md" <<NOTES
# ${NAME} harness — what you must decide before this is any good

Generated by \`make-fuzz-harness.sh\`. The generator wrote the plumbing. These
are the decisions it could not make for you.

## 1. Carve the input (TODO 1 in harness.c)

Which bytes of the fuzzer's input are **data** and which are **behaviour
selectors**? Constrain the selectors with a modulo; leave the data alone. Get
this wrong and the campaign spends its life in an error path.

## 2. Seeds (corpus/ is empty and that is a problem)

A fuzzer starting from nothing must rediscover your format's magic bytes before
it executes a single line of the interesting code. **Seeds are worth more than
CPU.** Put at least these in \`corpus/\`:

- one minimal valid input
- one valid input exercising each major branch of the format
- one empty file
- one input at your format's maximum size

## 3. Prove the harness reaches the target

Before you trust a single campaign result, do the planted-crash check:

1. Add \`abort();\` as the first statement of \`${FUNC}\`.
2. Rebuild, run one input, confirm it dies.
3. Remove it.

A harness that does not reach the target produces a campaign log identical to
one that found nothing. This check is the only thing that tells them apart.

## 4. State

Does \`${FUNC}\` leave anything behind between calls — a cache, a global, a
static buffer, an open file descriptor? If so, reset it, or your crashes will
not reproduce and you will conclude they were flukes.

## 5. Before you report anything

- Does the artefact reproduce in a **fresh process**?
- Is the top meaningful frame in the **target** or in **this harness**?
- Is the defect **reachable** by a real attacker through a real entry point?
  Nothing in a crash report answers that. Chapter 70 section 3.9.

## Commands

\`\`\`bash
./build.sh                                  # build every variant available
./run.sh                                    # default campaign
./run.sh -runs=1000000                      # bounded, reproducible
./fuzz_${NAME} -minimize_crash=1 -runs=100000 findings/crash-<hash>
python3 -B triage-asan.py --dir findings/   # after the crashes arrive
\`\`\`
NOTES

cat > "$OUT/corpus/README.txt" <<'CORPUS'
Put seed inputs here, one per file.

A fuzzer starting from an empty corpus must rediscover your format's structure
before it reaches interesting code. Seeds are the single cheapest improvement
you can make to a campaign -- far cheaper than more CPU.

Delete this file once you have real seeds; libFuzzer will otherwise treat it
as one.
CORPUS

printf 'generated:\n'
printf '  %s/harness.c\n' "$OUT"
printf '  %s/build.sh\n' "$OUT"
printf '  %s/run.sh\n' "$OUT"
printf '  %s/NOTES.md\n' "$OUT"
printf '  %s/corpus/\n' "$OUT"
printf '\n'
printf 'next: read NOTES.md. There are four TODOs in harness.c and the\n'
printf 'campaign is worthless until you have answered at least the first.\n'
