SPB Git

Repository Public

fuzz.py 21.6 KB 411 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project          : QYVORA7# File             : security/audit/runners/fuzz.py8# Module           : Security9# Repository       : https://git.spboucher.ai/qyvora10# Project Website  : Not specified11# Created          : 2026-12-0412# Last Modified    : 2026-12-0413#14# Author           : Simon-Pierre Boucher15# Position         : Professor of Finance16# Institution      : Université du Québec en Outaouais (UQO)17# Organization     : SP Boucher18# Website          : https://spboucher.ai19# Git              : https://git.spboucher.ai20#21# Preferred Contact: contact@spboucher.ai22# Development      : dev@spboucher.ai23# Support          : support@spboucher.ai24# Security/Admin   : admin@spboucher.ai25#26# Copyright (c) 202627# Simon-Pierre Boucher28# All rights reserved where applicable. This file is governed by the29# applicable project license, copyright notices and relevant law.30# Existing third-party rights and notices remain unaffected.31#32# License          : None specified (no license file in this repository)33#34# Do not embed credentials, private keys, access tokens,35# certificates or confidential personal information.36#37# =============================================================================38# END OF SP BOUCHER SOURCE HEADER39# =============================================================================4041"""Fuzzing runner: builds `qyfuzz` (security/tests), runs it locally and, in full mode, on cluster nodes.4243What it is, honestly: the Xcode toolchain has no libFuzzer (`-sanitize=fuzzer` is refused), so `qyfuzz`44is our own mutation engine. Two builds exist:45  plain     release build; feedback = outcome classes only (NOT coverage-guided)46  coverage  release build with AddressSanitizer + SanitizerCoverage inline 8-bit counters; the engine keeps47            inputs that reach new control-flow edges (edge-coverage guidance by our own loop, not libFuzzer)48Quick mode runs the plain build locally for a short time. Full mode runs both builds, locally and on every49node of ctx.options["nodes"] through security/fuzzing/campaign.sh.5051Standalone:  python3 security/audit/runners/fuzz.py [--full] [--nodes "M3U96a M3U96b"] [--seconds N]52Environment: QY_FUZZ_SECONDS (wall clock per machine), QY_FUZZ_WORKERS (local workers), QY_AUDIT_SCRATCH.53"""5455from __future__ import annotations5657import json58import os59import shutil60import sys61import threading62import time63from pathlib import Path6465sys.path.insert(0, str(Path(__file__).resolve().parents[1]))66from lib.common import (FAILED, NOT_RUN, RAW, REPO, RUN, Context, apply_triage, finding, load_json, not_run, rel,  # noqa: E40267                        run_cmd, tool_result, write_json)6869TESTS = REPO / "security" / "tests"70FUZZING = REPO / "security" / "fuzzing"71CRASHES = FUZZING / "crashes"72CAMPAIGNS = FUZZING / "campaigns"73REMOTE_DIR = "qyvora-build/audit-fuzz"74COVERAGE_FLAGS = ["--sanitize=address", "-Xswiftc", "-sanitize-coverage=edge,inline-8bit-counters"]7576COVERAGE_STATEMENT = (77    "Mutation-based fuzzing of {targets} harnesses (parsers, decoders and verifiers that take untrusted input) with a "78    "seeded generator, a committed seed corpus and crash capture in worker processes. libFuzzer is not available in "79    "the Xcode Swift toolchain. The plain build has no coverage feedback (outcome classes only). The instrumented build "80    "({coverage_note}) keeps inputs that reach new control-flow edges, measured with LLVM SanitizerCoverage inline "81    "counters and read by our own engine, under AddressSanitizer. A run without a crash shows that no trap was found in "82    "the executions made; it is not a proof of absence."83)848586def scratch(name: str) -> Path:87    base = Path(os.environ.get("QY_AUDIT_SCRATCH", "/tmp/qy-audit-fuzz"))88    return base if name == "plain" else Path(str(base) + "-cov")899091def build(kind: str, timeout: int = 3600) -> tuple[Path | None, str, float]:92    """Builds qyfuzz; returns (binary, error text, seconds)."""93    cmd = ["swift", "build", "-c", "release", "-Xswiftc", "-enable-testing", "--product", "qyfuzz",94           "--package-path", str(TESTS), "--scratch-path", str(scratch(kind))]95    if kind == "coverage":96        cmd += COVERAGE_FLAGS97    code, out, err, secs = run_cmd(cmd, timeout=timeout)98    binary = scratch(kind) / "release" / "qyfuzz"99    if code != 0 or not binary.exists():100        return None, (out + err)[-3000:], secs101    return binary, "", secs102103104def git_state() -> dict:105    _, head, _, _ = run_cmd(["git", "rev-parse", "HEAD"])106    _, status, _, _ = run_cmd(["git", "status", "--porcelain", "--untracked-files=no"])107    return {"commit": head.strip(), "dirty": bool(status.strip())}108109110def merge(parts: list[dict]) -> dict:111    """Merges qyfuzz JSON summaries (several builds and machines) into totals and per-target rows."""112    targets: dict[str, dict] = {}113    crashes, sites = [], {}114    executions = hangs = crash_count = 0115    for part in parts:116        for t in part.get("targets", []):117            row = targets.setdefault(t["target"], {"target": t["target"], "executions": 0, "seconds": 0.0, "crashes": 0,118                                                    "hangs": 0, "corpus_size": 0, "edges_covered": 0})119            row["executions"] += t.get("executions", 0)120            row["seconds"] = round(row["seconds"] + t.get("seconds", 0.0), 2)121            row["crashes"] += t.get("crashes", 0)122            row["hangs"] += t.get("hangs", 0)123            row["corpus_size"] = max(row["corpus_size"], t.get("corpus_size", 0))124            row["edges_covered"] = max(row["edges_covered"], t.get("edges_covered", 0))125        for c in part.get("crashes", []):126            c = dict(c)127            c["host"] = part.get("host", "")128            c["build"] = "coverage" if part.get("coverage_guided") else "plain"129            crashes.append(c)130        for s in part.get("crash_sites", []):131            sites[s["site"]] = sites.get(s["site"], 0) + s["count"]132        totals = part.get("totals", {})133        executions += totals.get("executions", 0)134        crash_count += totals.get("crashes", 0)135        hangs += totals.get("hangs", 0)136    return {"targets": sorted(targets.values(), key=lambda r: r["target"]), "crashes": crashes,137            "crash_sites": [{"site": k, "count": v} for k, v in sorted(sites.items())],138            "executions": executions, "crash_count": crash_count, "hangs": hangs}139140141def machine_record(host: str, parts: list[dict], host_info: dict | None = None) -> dict:142    m = merge(parts)143    return {144        "host": host, "cores": (host_info or {}).get("cores") or (parts[0].get("cores") if parts else None),145        "model": (host_info or {}).get("model", ""), "os": (host_info or {}).get("os", ""), "swift": (host_info or {}).get("swift", ""),146        "load_before": (host_info or {}).get("load_before", ""),147        "seconds": max([p.get("wall_seconds", 0) for p in parts], default=0),148        "workers": sum(p.get("workers", 0) for p in parts),149        "builds": [{"build": "coverage" if p.get("coverage_guided") else "plain", "workers": p.get("workers", 0),150                    "executions": p.get("totals", {}).get("executions", 0), "seed": p.get("seed", ""),151                    "wall_seconds": p.get("wall_seconds", 0), "edges_instrumented": p.get("edges_instrumented", 0)} for p in parts],152        "executions": m["executions"], "crashes": m["crash_count"], "hangs": m["hangs"],153    }154155156def run_local(binary: Path, seconds: int, workers: int, kind: str, out: Path) -> dict | None:157    work = FUZZING / "work" / f"local-{kind}"158    crashes = RAW / "fuzz-crashes"159    js = out / f"local-{kind}.json"160    js.unlink(missing_ok=True)161    cmd = [str(binary), "run", "--target", os.environ.get("QY_FUZZ_TARGETS", "all"), "--seconds", str(seconds),162           "--workers", str(workers), "--work", str(work), "--crashes", str(crashes), "--json", str(js)]163    if os.environ.get("QY_AUDIT_SEED"):164        cmd += ["--seed", os.environ["QY_AUDIT_SEED"]]165    run_cmd(cmd, timeout=seconds + 900)  # exit code 1 = crashes found: read the JSON either way166    return load_json(js)167168169def self_test(binary: Path) -> dict:170    """Proves crash capture on this machine: a harness with a planted out-of-range index behind a two-byte prefix171    (target selftest-trap, only present with QY_FUZZ_SELFTEST=1) must be found, captured and reported."""172    base = RAW / "fuzz-selftest"173    shutil.rmtree(base, ignore_errors=True)174    js = base / "out.json"175    cmd = [str(binary), "run", "--target", "selftest-trap", "--iterations", "400000", "--workers", "1", "--seed", "7",176           "--corpus", str(base / "corpus"), "--work", str(base / "work"), "--crashes", str(base / "crashes"), "--json", str(js)]177    code, out, err, secs = run_cmd(cmd, timeout=300, env={"QY_FUZZ_SELFTEST": "1"})178    d = load_json(js, {}) or {}179    crashes = d.get("crashes", [])180    captured = [c for c in crashes if c.get("input_hex", "").startswith("5159")]181    return {"found": bool(captured), "executions_to_crash": d.get("totals", {}).get("executions", 0),182            "located": any(".swift:" in c.get("site", "") for c in captured), "seconds": round(secs, 1),183            "message": captured[0].get("message", "") if captured else (err or out)[-300:]}184185186def run_node(node: str, seconds: int, results: dict) -> None:187    """Copies the tree to the node, runs campaign.sh there and brings the summaries and crash inputs back."""188    info: dict = {"node": node, "status": NOT_RUN, "reason": "", "parts": [], "host": {}}189    results[node] = info190    code, out, err, _ = run_cmd(["ssh", "-o", "ConnectTimeout=10", "-o", "BatchMode=yes", node, "sysctl -n hw.ncpu; uptime"], timeout=40)191    if code != 0:192        info["reason"] = f"node unreachable: {(err or out).strip()[:200]}"193        return194    lines = out.strip().splitlines()195    cores = int(lines[0]) if lines and lines[0].isdigit() else 8196    workers = max(2, cores // 2)197    excludes = [".build*", ".git", "security/.tools", "security/fuzzing/work", "security/reports/raw", "App/build", "build"]198    cmd = ["rsync", "-a", "--delete"] + [x for e in excludes for x in ("--exclude", e)] + [f"{REPO}/", f"{node}:{REMOTE_DIR}/"]199    code, out, err, _ = run_cmd(cmd, timeout=900)200    if code != 0:201        info["reason"] = f"rsync failed: {err.strip()[:200]}"202        return203    remote = f"cd {REMOTE_DIR} && rm -rf security/fuzzing/work/campaign && bash security/fuzzing/campaign.sh {seconds} {workers}"204    code, out, err, _ = run_cmd(["ssh", "-o", "ServerAliveInterval=30", node, remote], timeout=seconds + 3600)205    local = RAW / f"fuzz-{node}"206    shutil.rmtree(local, ignore_errors=True)207    local.mkdir(parents=True, exist_ok=True)208    run_cmd(["rsync", "-a", f"{node}:{REMOTE_DIR}/security/fuzzing/work/campaign/", f"{local}/"], timeout=600)209    info["host"] = load_json(local / "host.json", {}) or {}210    for name in ("plain.json", "coverage.json"):211        part = load_json(local / name)212        if part:213            info["parts"].append(part)214    if info["parts"]:215        info["status"] = RUN216    else:217        info["status"] = FAILED218        info["reason"] = f"campaign produced no summary (exit {code}): {(err or out).strip()[-300:]}"219220221def crash_findings(crashes: list[dict]) -> list[dict]:222    """One finding per (target, site). Severity high until triaged: a trap reachable from untrusted input stops the223    application; an invariant failure can be worse (acceptance of a forged input)."""224    grouped: dict[tuple, dict] = {}225    for c in crashes:226        key = (c.get("target", ""), c.get("site", ""))227        g = grouped.setdefault(key, {"count": 0, "first": c, "hosts": set()})228        g["count"] += 1229        g["hosts"].add(c.get("host", ""))230    out = []231    for (target, site), g in sorted(grouped.items()):232        c = g["first"]233        invariant = "FUZZ-INVARIANT" in c.get("message", "") or c.get("kind") == "crash" and "accepted" in site234        out.append(finding(235            title=f"Fuzzing: {c.get('kind', 'crash')} in target {target}: {site[:120]}",236            severity="high", tool="qyfuzz", rule=f"{target}:{site}", area="fuzzing",237            location=site.split(" ")[0] if ".swift:" in site else f"security/fuzzing/crashes/{target}/",238            cwe="CWE-20" if invariant else ("CWE-835" if c.get("kind") == "hang" else "CWE-248"),239            masvs="MASVS-CODE-4",240            description=(f"{g['count']} occurrence(s) on {', '.join(sorted(h for h in g['hosts'] if h)) or 'this machine'}. "241                         f"Message: {c.get('message', '')}. Reproduce: qyfuzz repro {target} <file>. "242                         f"First input ({c.get('input_bytes', 0)} bytes, hex): {c.get('input_hex', '')[:1200]}"),243            recommendation="Fix the root cause in the engine (or the harness if the invariant is wrong), keep the input under "244                           "security/fuzzing/crashes/ so that FuzzReplayTests replays it, and record the fix in the register.",245            evidence=f"{target}: {site}",  # stable across runs: the triage file keys on the fingerprint derived from it246        ))247    return out248249250def keep_crash_inputs(sources: list[Path]) -> list[str]:251    """Copies new crash inputs (and their notes) into security/fuzzing/crashes/<target>/ so the replay tests run them."""252    kept = []253    for src in sources:254        if not src.is_dir():255            continue256        for f in sorted(src.glob("*/*")):257            if f.suffix not in (".bin", ".txt"):258                continue259            dest = CRASHES / f.parent.name / f.name260            if not dest.exists():261                dest.parent.mkdir(parents=True, exist_ok=True)262                shutil.copy2(f, dest)263                kept.append(rel(dest))264    return kept265266267def record_campaign(parts: list[dict], host_info: dict, note: str = "", state: dict | None = None) -> Path | None:268    """Writes security/fuzzing/campaigns/<date>-<host>.json for a campaign that really ran (to be committed)."""269    if not parts:270        return None271    rec = machine_record(host_info.get("host") or parts[0].get("host", "unknown"), parts, host_info)272    m = merge(parts)273    started = host_info.get("started") or parts[0].get("started", "")274    rec.update({275        "date": started, "note": note, **(state or git_state()),276        "feedback": {("coverage" if p.get("coverage_guided") else "plain"): p.get("feedback", "") for p in parts},277        "targets": m["targets"], "crash_sites": m["crash_sites"],278        "crash_messages": sorted({c.get("message", "")[:200] for c in m["crashes"]}),279    })280    CAMPAIGNS.mkdir(parents=True, exist_ok=True)281    name = f"{(started or time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()))[:16].replace(':', '')}-{rec['host']}.json"282    path = CAMPAIGNS / name283    write_json(path, rec)284    return path285286287def recorded_campaigns() -> list[dict]:288    """Campaign summaries committed under security/fuzzing/campaigns/ (earlier runs, each with its own commit)."""289    out = []290    for f in sorted(CAMPAIGNS.glob("*.json")):291        d = load_json(f)292        if d:293            out.append({k: d.get(k) for k in ("date", "host", "cores", "model", "commit", "dirty", "seconds", "workers", "executions",294                                              "crashes", "hangs", "builds", "note")} | {"file": rel(f)})295    return out296297298def run(ctx: Context) -> dict:299    start = time.time()300    full = ctx.full301    opts = ctx.options or {}302    nodes = list(opts.get("nodes") or [])303    seconds = int(opts.get("fuzz_seconds") or os.environ.get("QY_FUZZ_SECONDS") or (1800 if full else 24))304    local_seconds = seconds if not nodes else min(seconds, 600)305    cores = os.cpu_count() or 4306    workers = int(os.environ.get("QY_FUZZ_WORKERS") or (max(2, cores // 2) if full else min(4, max(2, cores // 4))))307    out = RAW / "fuzz"308    out.mkdir(parents=True, exist_ok=True)309310    plain, error, build_secs = build("plain")311    if plain is None:312        return tool_result(tool="qyfuzz", category="fuzz", status=FAILED, reason="qyfuzz does not build: " + error[-600:],313                           duration_s=time.time() - start, coverage="Not run: the fuzzer did not build.")314    code, listing, _, _ = run_cmd([str(plain), "list"], timeout=120)315    target_count = sum(1 for line in listing.splitlines() if line and not line[0].isdigit()) if code == 0 else 0316317    proof = self_test(plain)318    if not proof["found"]:319        return tool_result(tool="qyfuzz", category="fuzz", status=FAILED, duration_s=time.time() - start,320                           reason="self-test failed: the planted trap was not found or not captured: " + proof["message"],321                           coverage="Not run: the fuzzer failed its own crash-capture self-test.", metrics={"self_test": proof})322323    coverage_note = "not built in quick mode"324    cov = None325    if full:326        cov, cov_error, _ = build("coverage")327        coverage_note = "built and run" if cov else "NOT RUN: the instrumented build failed: " + cov_error[-200:]328329    # nodes in parallel with the local run330    node_results: dict = {}331    threads = [threading.Thread(target=run_node, args=(n, seconds, node_results), daemon=True) for n in nodes] if full else []332    for t in threads:333        t.start()334335    parts, machines = [], []336    local_parts = []337    if cov:338        half = max(1, workers // 2)339        holder: dict = {}340        tc = threading.Thread(target=lambda: holder.update(cov=run_local(cov, local_seconds, half, "coverage", out)), daemon=True)341        tc.start()342        p = run_local(plain, local_seconds, max(1, workers - half), "plain", out)343        tc.join()344        local_parts = [x for x in (p, holder.get("cov")) if x]345    else:346        p = run_local(plain, local_seconds, workers, "plain", out)347        local_parts = [p] if p else []348    if not local_parts:349        return tool_result(tool="qyfuzz", category="fuzz", status=FAILED, reason="qyfuzz produced no summary",350                           duration_s=time.time() - start, coverage="Not run.")351    parts += local_parts352    machines.append(machine_record(local_parts[0].get("host", "local"), local_parts, {"cores": cores}))353354    for t in threads:355        t.join()356    node_notes = []357    for node in nodes if full else []:358        info = node_results.get(node, {})359        if info.get("status") == RUN:360            parts += info["parts"]361            machines.append(machine_record(info["host"].get("host") or node, info["parts"], info["host"]))362            record_campaign(info["parts"], info["host"], note=f"audit run, full mode, node {node}")363        else:364            node_notes.append(f"{node}: {info.get('status', NOT_RUN)} — {info.get('reason', 'no result')}")365    if nodes and not full:366        node_notes.append("nodes are used in full mode only")367368    merged = merge(parts)369    kept = keep_crash_inputs([RAW / "fuzz-crashes"] + [RAW / f"fuzz-{n}" / "crashes" for n in nodes])370    findings = apply_triage(crash_findings(merged["crashes"]))371    tests = [{"area": "fuzz", "name": f"fuzz/{t['target']}", "algorithm": t["target"], "parameter_set": "", "cases": t["executions"],372              "passed": t["executions"] - t["crashes"] - t["hangs"], "failed": t["crashes"] + t["hangs"], "skipped": 0,373              "seed": ",".join(sorted({str(p.get("seed", "")) for p in parts})),374              "note": f"{t['seconds']} worker-seconds; committed seeds {t['corpus_size']}"} for t in merged["targets"]]375    summary = {376        "mode": ctx.mode, "git": git_state(), "targets": target_count, "executions": merged["executions"],377        "seconds": round(time.time() - start, 1), "crashes": merged["crash_count"], "hangs": merged["hangs"],378        "unique_crash_sites": len(merged["crash_sites"]), "machines": machines, "node_notes": node_notes,379        "libfuzzer": "unavailable: swiftc refuses -sanitize=fuzzer in the Xcode toolchain (checked on the laptop, Swift 6.4, and on the nodes, Swift 6.3)",380        "coverage_guided_build": coverage_note, "self_test": proof, "crash_inputs_kept": kept, "recorded_campaigns": recorded_campaigns(),381    }382    write_json(RAW / "fuzz.json", {"summary": summary, "targets": merged["targets"], "crashes": merged["crashes"],383                                   "crash_sites": merged["crash_sites"]})384    return tool_result(385        tool="qyfuzz", category="fuzz", status=RUN, version="qyfuzz (security/tests), own mutation engine",386        command=f"qyfuzz run --target all --seconds {local_seconds} --workers {workers}" + (f"; campaign.sh {seconds} on {' '.join(nodes)}" if full and nodes else ""),387        duration_s=time.time() - start,388        coverage=COVERAGE_STATEMENT.format(targets=target_count, coverage_note=coverage_note),389        metrics=summary, tests=tests, findings=findings,390        artifacts=[rel(RAW / "fuzz.json")] + kept,391    )392393394if __name__ == "__main__":395    args = sys.argv[1:]396    if "--record" in args:  # turn the output directory of campaign.sh into a committed campaign summary397        src = Path(args[args.index("--record") + 1])398        found = [d for d in (load_json(src / "plain.json"), load_json(src / "coverage.json")) if d]399        note = args[args.index("--note") + 1] if "--note" in args else ""400        state = {"commit": args[args.index("--commit") + 1], "dirty": "--dirty" in args} if "--commit" in args else None401        print(record_campaign(found, load_json(src / "host.json", {}) or {}, note, state))402        sys.exit(0)403    options: dict = {}404    if "--nodes" in args:405        options["nodes"] = args[args.index("--nodes") + 1].split()406    if "--seconds" in args:407        options["fuzz_seconds"] = int(args[args.index("--seconds") + 1])408    result = run(Context(mode="full" if "--full" in args else "quick", options=options))409    print(json.dumps({k: v for k, v in result.items() if k != "tests"}, indent=2)[:6000])410    sys.exit(0 if result["status"] == RUN and not [f for f in result["findings"] if f["status"] == "open"] else 1)411
Files main
Menu

Theme