Files
Claude-BugHunter/eval/run_eval_ps.py
0620b24004 fix(engine+eval): 11 verified correctness/safety fixes (failed-hunt, TLS, auth-sweep FP, +8) (#50)
* fix(engine): 3 verified council findings — F7 (silent failed-hunt), F32 (TLS), F43 (auth-sweep FP)

F7 — engine/agent.py + engine/engine.py: agent hard errors (timeout / rate-limit /
  parse-fail / missing 'claude' CLI) were recorded as 'tested, found nothing' and never
  retried; sequential mode also crashed on a missing CLI. Now: catch FileNotFoundError/
  OSError in run_agent; _hunt_agent flags errored/no-verdict results; hunt() leaves those
  items un-tested (stay on worklist for retry) instead of marking them tested-negative.

F32 — cbh/cli.py: an ambient corporate HTTPS_PROXY/HTTP_PROXY silently set ssl.CERT_NONE
  (TLS verification off). Now CERT_NONE is gated behind an explicit Burp/insecure opt-in
  (--burp/--proxy or CBH_BURP_PROXY); ambient proxy env keeps verification ON.

F43 — engine/recon.py: a global OpenAPI 'security: []' (= public API) was treated as
  secured, producing false-positive 'broken function-level auth' findings. Now mirrors the
  op-level check: glob = spec.get('security') not in (None, []).

Verified: all files compile; agent.py/state.py self-tests pass; --mock dry-run unchanged;
added behavioral checks for each fix (errored-not-tested, ambient-proxy-TLS-on, security:[]-not-swept).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(engine+eval): 8 more verified council findings (F8/F9/F41/F24/F23/F12/F14/F20)

Core engine:
- F8  cbh/cli.py: crt.sh outage/rate-limit/JSON-error now warns loudly instead of
      silently returning empty (a failed lookup was indistinguishable from '0 subdomains').
- F9  engine/recon.py: prune_inert_params distinguishes a FAILED probe (code 0, network/
      curl error -> keep the endpoint) from a genuine HTTP >=400 dead endpoint; logs the
      unprobeable count. Transient failures no longer silently drop live surface.
- F41 engine/recon.py: mined relative routes now carry their source-document base
      (found_rel stores (base, rel)); each is resolved against the doc it came from, not the
      first seed's origin — fixes wrong-host endpoints on multi-seed runs.

Eval / labs / scripts:
- F24 docs/verification/phase3-playwright/harness.py: OAuth @-userinfo bypass payload was
      malformed (@ landed in the PATH -> browser stayed on localhost, refuting a real bug).
      Corrected to http://localhost:58020@<evil>/... (userinfo=localhost:58020, host=evil),
      which passes the server's startswith prefix AND swaps host. Docstring corrected.
- F23 eval/run_fp.py: validate --conditions against {baseline,skills}; a typo'd condition
      previously ran as baseline under the wrong label and invalidated the ablation.
- F12 eval/run_eval_ps.py: a post-run oracle read-failure (expired instance) was scored as
      solved=False (a miss). Now captures the ok flag, records solved=None + oracle_ok, and
      excludes oracle-unreadable runs from the solve-rate denominator (summary + per-class).
- F14 secret_scan.py: missing/unreadable and >10MB files were silently skipped (false
      'clean'); now warns to stderr on every skip.
- F20 eval/fp_app.py: the 'safe' /go open-redirect trap accepted /\evil.com (browsers
      normalize \ -> / -> protocol-relative external redirect), so its ground-truth 'safe'
      label was wrong. Now rejects backslashes and control chars.

Verified: all files compile; recon.py/agent.py/state.py self-tests pass; --mock flow
unchanged; added behavioral checks for F9/F41/F20/F24/F14/F23/F12.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Sachin Sharma <sachin.lucideus@gmail.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-27 23:55:30 +05:30

119 lines
5.8 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""
run_eval_ps.py — PortSwigger Web Security Academy tier of the eval harness.
This is the REAL skill-delta tier (lab solutions are far less memorized than Juice
Shop's). The agent engine + metrics are shared with run_eval.py; only the target and
oracle differ.
Launch is NOT auto-automated (the Academy launch flow is JS + CSRF gated under
/Academy/, and every existing tool has a human launch in-browser and paste the URL).
So the workflow is:
1. Log in at portswigger.net, open each lab's description page (the `slug` in
ps_labs.json), click "Access the lab", copy the https://<id>.web-security-academy.net URL.
2. For an ablation you need a FRESH instance per condition (a solved lab can't reset in
place — relaunching gives a new URL). Launch each lab once per condition and paste both
URLs into ps_labs.json -> instances.{skills,baseline}.
3. Run this. It runs the agent against each instance and polls the lab's own solved-widget.
python3 eval/run_eval_ps.py # all labs with instance URLs filled, both conditions
python3 eval/run_eval_ps.py --conditions skills # skills-on only (one instance per lab)
python3 eval/run_eval_ps.py --model claude-opus-4-8
"""
import argparse
import json
import os
import sys
import time
from datetime import datetime, timezone
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import run_eval as RE # noqa: E402 (shared agent runner + build_task)
from oracle_portswigger import ps_solved # noqa: E402
EVAL = os.path.dirname(os.path.abspath(__file__))
TARGET_DESC = ("a PortSwigger Web Security Academy lab instance — an authorized, "
"deliberately-vulnerable training lab tied to the tester's own account.")
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--labs", default=os.path.join(EVAL, "ps_labs.json"))
ap.add_argument("--conditions", default="skills,baseline")
ap.add_argument("--model", default="claude-sonnet-4-6",
help="held constant across conditions; the ablation isolates the skills")
ap.add_argument("--max-turns", type=int, default=60)
ap.add_argument("--timeout", type=int, default=900, help="per-run seconds (labs are multi-step)")
ap.add_argument("--out", default=os.path.join(EVAL, "results", "ps_run.jsonl"))
a = ap.parse_args()
labs = json.load(open(a.labs))
conditions = [c.strip() for c in a.conditions.split(",") if c.strip()]
os.makedirs(os.path.dirname(a.out), exist_ok=True)
out = open(a.out, "a")
rows = []
print(f"== PortSwigger eval: {len(labs)} lab(s) × {conditions} | model={a.model} ==")
for lab in labs:
for cond in conditions:
url = (lab.get("instances") or {}).get(cond, "").strip()
tag = f"[{lab['key']} | {cond}]"
if not url:
print(f"{tag} no instance URL — launch the lab & paste it into ps_labs.json — skipping")
continue
pre, ok = ps_solved(url)
if not ok:
print(f"{tag} oracle can't read {url} (expired / wrong URL?) — skipping")
continue
if pre:
print(f"{tag} instance already SOLVED — relaunch for a clean instance — skipping")
continue
print(f"{tag} running agent vs {url} (max_turns={a.max_turns}, timeout={a.timeout}s)...",
flush=True)
task = RE.build_task(lab["objective"], url, TARGET_DESC)
r = RE.run_agent(task, cond == "skills", a.model, a.max_turns, a.timeout)
time.sleep(3)
post, post_ok = ps_solved(url)
# If the oracle can't be read post-run (instance expired DURING the run), that's
# an infra failure, NOT a genuine miss — record solved=None and exclude it from
# the solve-rate denominator in the summary.
solved = bool(post) if post_ok else None
rec = {"ts": datetime.now(timezone.utc).isoformat(), "lab": lab["key"],
"class": lab.get("class"), "condition": cond, "solved": solved,
"oracle_ok": post_ok, "instance": url, **r}
rows.append(rec)
out.write(json.dumps(rec) + "\n"); out.flush()
note = "" if post_ok else " [oracle unreadable — excluded from solve-rate]"
print(f" -> solved={solved} turns={r.get('num_turns')} cost=${r.get('cost_usd')} "
f"{r.get('duration_s')}s{' [' + r['agent_error'] + ']' if r.get('agent_error') else ''}{note}")
out.close()
# summary
print("\n" + "=" * 60 + "\nSUMMARY (PortSwigger)")
by_cond = {}
for r in rows:
by_cond.setdefault(r["condition"], []).append(r)
for cond, rs in by_cond.items():
scored = [r for r in rs if r.get("solved") is not None] # exclude oracle-unreadable runs
s = sum(1 for r in scored if r["solved"])
skipped = len(rs) - len(scored)
cost = sum((r.get("cost_usd") or 0) for r in rs)
extra = f" ({skipped} oracle-unreadable, excluded)" if skipped else ""
print(f" {cond:9s}: solved {s}/{len(scored)} total ${cost:.2f}{extra}")
# per-class skill-delta (only where both conditions ran)
classes = sorted({r["class"] for r in rows})
if "skills" in by_cond and "baseline" in by_cond:
print("\n per-class (solved / ran):")
for cl in classes:
for cond in ("skills", "baseline"):
rs = [r for r in rows if r["class"] == cl and r["condition"] == cond
and r.get("solved") is not None] # exclude oracle-unreadable
if rs:
print(f" {cl:16s} {cond:9s} {sum(1 for r in rs if r['solved'])}/{len(rs)}")
print(f"\n raw: {a.out}")
if __name__ == "__main__":
sys.exit(main())