Files

395 lines
15 KiB
Python

#!/usr/bin/env python3
"""Run the NimbusCart/BurpAT 65-scenario benchmark against a local lab.
The lab is deliberately vulnerable (RCE/SSRF/etc.) and must only be run on
localhost/isolated infrastructure. This script starts its own instance on a
dedicated port, resets it to a clean state, runs the harness once (or N times),
and scores the run with bench/score.py.
Examples:
python3 bench/run.py --preset quick
python3 bench/run.py --preset standard --model orcarouter:deepseek/deepseek-v4.1-flash
python3 bench/run.py --no-start --target http://127.0.0.1:3000 --preset quick
python3 bench/run.py --score-only runs/ns-...
"""
from __future__ import annotations
import argparse
import json
import os
import re
import shutil
import signal
import socket
import subprocess
import sys
import time
import urllib.request
from datetime import datetime
from pathlib import Path
HERE = Path(__file__).resolve().parent
ROOT = HERE.parent
DEFAULT_LAB = Path(os.environ.get("NIMBUSCART_LAB", "/opt/BenchMarkBurpAT"))
DEFAULT_MODEL = "deepseek:deepseek-flash"
DEFAULT_BINARY = ROOT / "neurosploit-rs" / "target" / "release" / "neurosploit"
RUN_ROOTS = [ROOT / "runs", ROOT / "neurosploit-rs" / "runs"]
PRESETS = {
"quick": ["--quick"],
"standard": ["--max-agents", "12", "--vote-n", "1", "--budget", "balanced",
"--recon", "3", "--chain-depth", "1"],
"deep": ["--max-agents", "0", "--vote-n", "1", "--budget", "unlimited",
"--recon", "4", "--chain-depth", "2"],
}
COPY_ARTIFACTS = [
"findings.json", "report.md", "report.json", "report.html", "meta.json",
"status.json", "recon.json", "assurance.json", "exploitation.md",
"coverage.md", "run_snapshot.json", "attack-paths.json",
]
sys.path.insert(0, str(HERE))
from score import score_run, summary_md # noqa: E402
ANSI = re.compile(r"\x1b\[[0-9;]*m")
def now_id() -> str:
return datetime.now().strftime("%Y%m%d-%H%M%S")
def port_open(port: int) -> bool:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.settimeout(0.4)
return s.connect_ex(("127.0.0.1", port)) == 0
def http_ok(url: str, timeout: float = 1.5) -> bool:
try:
with urllib.request.urlopen(url, timeout=timeout) as r:
return 200 <= r.status < 500
except Exception:
return False
def wait_http(url: str, seconds: float = 30.0) -> bool:
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
if http_ok(url):
return True
time.sleep(0.4)
return False
def stop_proc(p: subprocess.Popen, label: str) -> None:
if p.poll() is not None:
return
try:
os.killpg(os.getpgid(p.pid), signal.SIGTERM)
except Exception:
try:
p.terminate()
except Exception:
return
try:
p.wait(timeout=8)
except Exception:
try:
os.killpg(os.getpgid(p.pid), signal.SIGKILL)
except Exception:
try:
p.kill()
except Exception:
pass
try:
p.wait(timeout=3)
except Exception:
pass
def start_lab(lab: Path, port: int, target: str, out: Path,
reset: bool = True) -> subprocess.Popen | None:
if port_open(port):
raise SystemExit(
f"port {port} is already in use; use --port/--target or --no-start "
f"(not killing an existing process)"
)
if not (lab / "server.js").is_file():
raise SystemExit(f"lab not found at {lab}; set NIMBUSCART_LAB or --lab")
if not (lab / "node_modules").is_dir():
raise SystemExit(f"lab dependencies missing at {lab}; run `npm install` there first")
if reset:
(out / "lab-reset.log").parent.mkdir(parents=True, exist_ok=True)
with open(out / "lab-reset.log", "w") as f:
r = subprocess.run(["npm", "run", "reset"], cwd=lab, stdout=f,
stderr=subprocess.STDOUT)
if r.returncode != 0:
raise SystemExit(f"`npm run reset` failed; see {out / 'lab-reset.log'}")
env = os.environ.copy()
env["PORT"] = str(port)
env.setdefault("NODE_ENV", "development")
log = open(out / "lab.log", "w")
p = subprocess.Popen(["npm", "start"], cwd=lab, env=env, stdout=log,
stderr=subprocess.STDOUT, start_new_session=True)
(out / "lab.pid").write_text(str(p.pid))
if not wait_http(target, 40):
stop_proc(p, "lab")
tail = ""
try:
tail = (out / "lab.log").read_text(errors="ignore")[-2000:]
except Exception:
pass
raise SystemExit(f"lab did not become ready at {target}\n{tail}")
print(f" lab : {lab} → {target} (pid {p.pid})")
return p
def new_run_dirs(before: set[str]) -> list[Path]:
found: list[Path] = []
for root in RUN_ROOTS:
if not root.is_dir():
continue
for p in root.iterdir():
if p.is_dir() and p.name not in before and (p / "findings.json").is_file():
found.append(p)
return sorted(found, key=lambda p: p.stat().st_mtime, reverse=True)
def parse_output(log_text: str) -> Path | None:
text = ANSI.sub("", log_text)
m = re.search(r"output\s*:\s*(.+?)\s*$", text, re.M)
if not m:
return None
p = Path(m.group(1).strip())
return p if p.is_dir() else None
def run_once(args, models: list[str], out: Path, lab_proc,
before: set[str], run_no: int) -> dict:
target = args.target
preset = PRESETS[args.preset]
cmd = [
str(args.binary), "run", target,
"--environment", "lab",
"--objective", args.objective,
"--focus", "Web, API and LLM application security; prove each finding live.",
"--typesafe", args.typesafe,
]
for m in models:
cmd += ["--model", m]
if args.token_limit:
cmd += ["--token-limit", str(args.token_limit)]
if args.recheck:
cmd += ["--revalidate-poc"]
cmd += preset
if args.engine == "phased":
cmd += ["--no-reactive"]
elif args.engine == "reactive":
cmd += ["--reactive"]
if args.worker_tools:
cmd += ["--worker-tools"]
cmd += ["-v"]
run_dir = out / f"run-{run_no}"
run_dir.mkdir(parents=True, exist_ok=True)
command = {"argv": cmd, "cwd": str(ROOT), "target": target,
"preset": args.preset, "models": models, "started": time.time()}
(run_dir / "command.json").write_text(json.dumps(command, indent=2))
print(" cmd : " + " ".join(cmd))
if args.dry_run:
return {}
log_path = run_dir / "run.log"
started = time.monotonic()
with open(log_path, "w") as log:
env = os.environ.copy()
# The benchmark isolates agent reasoning by default; opt into the
# reactive worker tool loop explicitly with --worker-tools.
if not args.worker_tools:
env["NEUROSPLOIT_WORKER_TOOLS"] = "0"
p = subprocess.Popen(cmd, cwd=ROOT, stdout=log, stderr=subprocess.STDOUT,
start_new_session=True, env=env)
timed_out = False
try:
code = p.wait(timeout=args.timeout)
except subprocess.TimeoutExpired:
timed_out = True
code = -1
stop_proc(p, "harness")
duration = round(time.monotonic() - started, 1)
command.update({"finished": time.time(), "duration_s": duration,
"exit_code": code, "timed_out": timed_out})
(run_dir / "command.json").write_text(json.dumps(command, indent=2))
log_text = log_path.read_text(errors="ignore") if log_path.is_file() else ""
model_error = None
if "MODEL PREFLIGHT FAILED" in log_text:
model_error = "model preflight failed"
elif "NONE of the configured models are usable" in log_text:
model_error = "no usable model"
if model_error:
print(f" ! {model_error}", file=sys.stderr)
workdir = parse_output(log_text)
if workdir is None or not workdir.is_dir():
candidates = [d for d in new_run_dirs(before) if d.name not in {
q.name for q in []}]
workdir = candidates[0] if candidates else None
if workdir is None:
print(" ! no run directory found", file=sys.stderr)
return {"error": "no run directory", "command": command, "duration_s": duration}
print(f" run : {workdir}")
dest = run_dir / "artifacts"
dest.mkdir(parents=True, exist_ok=True)
for name in COPY_ARTIFACTS:
src = workdir / name
if src.is_file():
try:
shutil.copy2(src, dest / name)
except Exception:
pass
try:
shutil.copy2(log_path, dest / "run.log")
except Exception:
pass
s = score_run(workdir, log_path, duration, cmd)
s.update({"target": target, "preset": args.preset, "models": models,
"exit_code": code, "timed_out": timed_out, "error": model_error,
"artifacts": str(dest), "workdir": str(workdir)})
(run_dir / "score.json").write_text(json.dumps(s, indent=2))
(run_dir / "summary.md").write_text(summary_md(s))
print(f" score : {s['coverage']['union']}/{s['coverage']['total']} "
f"(flags {s['coverage']['strict']}, reported {s['coverage']['reported']}) "
f"in {duration}s")
return s
def aggregate(results: list[dict], out: Path, args) -> None:
all_rows = [r for r in results if r and "coverage" in r]
rows = [r for r in all_rows if not r.get("error")]
if not rows:
(out / "summary.md").write_text("# NimbusCart benchmark — no valid runs\n")
(out / "score.json").write_text(json.dumps({"runs": all_rows}, indent=2))
return
def mean(key):
return sum(r["coverage"][key] for r in rows) / len(rows)
def mean_f(key):
vals = [r[key] for r in rows if r.get(key) is not None]
return sum(vals) / len(vals) if vals else 0
summary = [
"# NimbusCart benchmark — aggregate",
"",
f"- Preset: `{args.preset}` · models: {', '.join(rows[0].get('models', []))}",
f"- Runs: {len(rows)} · target: `{args.target}`",
f"- Mean union coverage: **{mean('union'):.1f}/{rows[0]['coverage']['total']}**",
f"- Mean strict flags: {mean('strict'):.1f} · mean reported: {mean('reported'):.1f}",
f"- Mean duration: {mean_f('duration_s'):.1f}s · mean findings: {mean_f('findings'):.1f}",
f"- Mean cost: ${sum(r['tokens']['cost_usd'] for r in rows)/len(rows):.4f}",
"",
"| run | union | strict | reported | findings | extra | duration | cost |",
"|---|---|---|---|---|---|---|---|",
]
for r in rows:
c = r["coverage"]
summary.append(
f"| {r['run']} | {c['union']}/{c['total']} | {c['strict']} | {c['reported']} | "
f"{r['findings']} | {r['extra_count']} | {r.get('duration_s')}s | "
f"${r['tokens']['cost_usd']:.4f} |"
)
summary += ["", "Per-run details are in `run-N/summary.md`."]
(out / "summary.md").write_text("\n".join(summary) + "\n")
(out / "score.json").write_text(json.dumps({"runs": rows}, indent=2))
def score_only(run_path: str, out: str | None, log: str | None, duration: float | None) -> int:
s = score_run(run_path, log, duration)
if out:
o = Path(out)
o.mkdir(parents=True, exist_ok=True)
(o / "score.json").write_text(json.dumps(s, indent=2))
(o / "summary.md").write_text(summary_md(s))
print(summary_md(s))
return 0
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--lab", default=str(DEFAULT_LAB))
ap.add_argument("--port", type=int, default=3001)
ap.add_argument("--target", default=None)
ap.add_argument("--binary", default=str(DEFAULT_BINARY))
ap.add_argument("--model", action="append", default=None,
help=f"repeatable; default {DEFAULT_MODEL}")
ap.add_argument("--preset", choices=sorted(PRESETS), default="quick")
ap.add_argument("--engine", choices=["auto", "phased", "reactive"], default="phased",
help="phased is the stable baseline; auto is the product default")
ap.add_argument("--out", default=None)
ap.add_argument("--repeat", type=int, default=1)
ap.add_argument("--timeout", type=int, default=2400)
ap.add_argument("--token-limit", type=int, default=0)
ap.add_argument("--typesafe", choices=["off", "on", "auto"], default="off")
ap.add_argument("--recheck", action="store_true", help="--revalidate-poc")
ap.add_argument("--worker-tools", action="store_true",
help="enable the reactive worker tool loop (off for an isolated baseline)")
ap.add_argument("--no-start", action="store_true", help="use an existing target")
ap.add_argument("--keep-lab", action="store_true")
ap.add_argument("--dry-run", action="store_true")
ap.add_argument("--score-only", metavar="RUN_DIR")
ap.add_argument("--log")
ap.add_argument("--duration", type=float)
ap.add_argument("--objective", default=(
"Authorized local benchmark. Find and prove as many seeded web, API and "
"LLM vulnerabilities as possible; capture each unique BURPAT flag where "
"the target exposes one. Stay on the target."
))
args = ap.parse_args()
if args.score_only:
return score_only(args.score_only, args.out, args.log, args.duration)
args.lab = Path(args.lab)
args.binary = Path(args.binary)
args.target = args.target or f"http://127.0.0.1:{args.port}"
models = args.model or [DEFAULT_MODEL]
args.repeat = max(1, args.repeat)
out = Path(args.out) if args.out else ROOT / "benchmarks" / "runs" / f"nimbuscart-{now_id()}"
out.mkdir(parents=True, exist_ok=True)
if not args.binary.is_file():
raise SystemExit(f"binary not found: {args.binary}\n cargo build --release")
print(f" out : {out}")
lab_proc = None
if args.dry_run:
pass
elif not args.no_start:
lab_proc = start_lab(args.lab, args.port, args.target, out, reset=True)
elif not http_ok(args.target):
raise SystemExit(f"target is not reachable: {args.target}")
before = {p.name for root in RUN_ROOTS if root.is_dir() for p in root.iterdir() if p.is_dir()}
results: list[dict] = []
try:
for i in range(1, args.repeat + 1):
if i > 1 and not args.no_start:
stop_proc(lab_proc, "lab")
lab_proc = start_lab(args.lab, args.port, args.target, out, reset=True)
print(f"\n=== run {i}/{args.repeat} ===")
results.append(run_once(args, models, out, lab_proc, before, i))
finally:
if args.keep_lab:
print(f" lab : kept on {args.target}")
elif lab_proc is not None:
stop_proc(lab_proc, "lab")
print(" lab : stopped")
if not args.dry_run:
aggregate(results, out, args)
print(f"\n summary: {out / 'summary.md'}")
return 0 if (args.dry_run or any(r and not r.get("error") for r in results)) else 1
if __name__ == "__main__":
sys.exit(main())