Skip to content

A Claude Code skill bundle for bug hunting and external red-team work - 82 skills, 15 slash commands, 681 disclosed-report patterns curated across 24 core vulnerability classes, plus enterprise identity + infrastructure attack matrices.

fix(engine+eval): 11 verified correctness/safety fixes (failed-hunt, TLS, auth-sweep FP, +8) (#50)

Sachin Sharma0620b240043c
diff --git a/cbh/cli.py b/cbh/cli.py
index b9e585a..7c66ccc 100755
--- a/cbh/cli.py
+++ b/cbh/cli.py
@@ -110,37 +110,43 @@ def run_cmd(cmd: list[str], timeout: int = 30) -> tuple[int, str, str]:
_HTTP_OPENER: urllib.request.OpenerDirector | None = None
-def configure_http_proxy(proxy_url: str | None = None) -> tuple[bool, str]:
+def configure_http_proxy(proxy_url: str | None = None, insecure: bool = False) -> tuple[bool, str]:
"""Configure urllib to route through a proxy (typically Burp Suite at
127.0.0.1:8080). Returns (configured, message) — message describes the mode.
- Resolution order:
- 1. explicit proxy_url argument
- 2. CBH_BURP_PROXY env var
- 3. HTTPS_PROXY / HTTP_PROXY env vars
- 4. fallback: auto-detect default Burp on http://127.0.0.1:8080 (only if --burp flag)
+ TLS certificate verification is disabled ONLY when `insecure=True` (an explicit
+ Burp/insecure opt-in). An ambient corporate HTTPS_PROXY/HTTP_PROXY is still used,
+ but keeps certificate verification ON — so a corporate proxy env var can never
+ silently turn off TLS validation while reconning a production target.
+
+ Resolution order when proxy_url is not given:
+ 1. CBH_BURP_PROXY env var (the tool's own Burp var → implies insecure)
+ 2. HTTPS_PROXY / HTTP_PROXY env vars (ambient/corporate → TLS stays verified)
"""
global _HTTP_OPENER
if not proxy_url:
- proxy_url = os.environ.get("CBH_BURP_PROXY") or os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY")
+ burp_env = os.environ.get("CBH_BURP_PROXY")
+ if burp_env:
+ proxy_url, insecure = burp_env, True # Burp's CA isn't trusted → insecure
+ else:
+ proxy_url = os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY")
if not proxy_url:
_HTTP_OPENER = None
return False, "direct (no proxy)"
- # Disable TLS verification when going through Burp (its CA isn't typically trusted)
import ssl
ctx = ssl.create_default_context()
- ctx.check_hostname = False
- # WARNING: TLS verification is disabled for Burp proxy traffic.
- # Use --proxy only in isolated lab environments — not on production targets.
- ctx.verify_mode = ssl.CERT_NONE
- print("[warning] TLS certificate verification is DISABLED — proxy mode active. "
- "Use only in isolated lab environments, not on production targets.", flush=True)
+ if insecure:
+ # Only for an explicit Burp/insecure opt-in: Burp's CA isn't typically trusted.
+ ctx.check_hostname = False
+ ctx.verify_mode = ssl.CERT_NONE
+ print("[warning] TLS certificate verification is DISABLED — insecure/Burp proxy mode. "
+ "Use only in isolated lab environments, not on production targets.", flush=True)
proxy_handler = urllib.request.ProxyHandler({"http": proxy_url, "https": proxy_url})
https_handler = urllib.request.HTTPSHandler(context=ctx)
_HTTP_OPENER = urllib.request.build_opener(proxy_handler, https_handler)
- return True, f"via proxy {proxy_url}"
+ return True, f"via proxy {proxy_url} ({'TLS verify OFF' if insecure else 'TLS verify on'})"
def detect_burp() -> str | None:
@@ -187,10 +193,17 @@ def recon_subdomains_via_crtsh(target: str) -> set[str]:
url = f"https://crt.sh/?q=%25.{target}&output=json"
status, _, body = http_get(url, timeout=20)
if status != 200 or not body:
+ # An outage / rate-limit (crt.sh often 503s) must NOT be mistaken for
+ # "no subdomains exist" — warn loudly so a failed lookup isn't read as empty.
+ why = f"HTTP {status}" if status else "unreachable / network error"
+ print(f"[warning] crt.sh lookup failed ({why}) — subdomain results may be INCOMPLETE, "
+ f"not necessarily empty.", file=sys.stderr, flush=True)
return set()
try:
rows = json.loads(body)
except Exception:
+ print("[warning] crt.sh returned unparseable JSON — subdomain results may be INCOMPLETE.",
+ file=sys.stderr, flush=True)
return set()
subs = set()
for r in rows:
@@ -246,11 +259,12 @@ def configure_proxy_from_args(args: argparse.Namespace) -> None:
"""If --burp or --proxy was passed, set up the urllib opener accordingly.
Print the mode banner so the operator knows where traffic is going."""
proxy_url = None
+ insecure = False
if getattr(args, "proxy", None):
- proxy_url = args.proxy
+ proxy_url, insecure = args.proxy, True # explicit --proxy: operator opted in
elif getattr(args, "burp", False):
- proxy_url = detect_burp() or "http://127.0.0.1:8080"
- configured, mode = configure_http_proxy(proxy_url)
+ proxy_url, insecure = (detect_burp() or "http://127.0.0.1:8080"), True
+ configured, mode = configure_http_proxy(proxy_url, insecure)
if configured:
say(color(f" HTTP routing: {mode}", "yellow"))
say(color(f" Tip: requests will appear in Burp Proxy → HTTP history.", "dim"))
diff --git a/docs/verification/phase3-playwright/harness.py b/docs/verification/phase3-playwright/harness.py
index 73272ca..2f0d6e4 100644
--- a/docs/verification/phase3-playwright/harness.py
+++ b/docs/verification/phase3-playwright/harness.py
@@ -91,16 +91,17 @@ def test_oauth_userinfo_bypass():
cross-origin.
Server validates redirect_uri by prefix-match (starts with
- `http://localhost:58020/legit/`). Attacker sends a redirect_uri of:
- http://localhost:58020/legit/@127.0.0.1:58021/attacker-callback
- Per RFC 3986, the browser parses:
+ `http://localhost:58020`, per target_app.py). Attacker sends a redirect_uri of:
+ http://localhost:[email protected]/attacker-callback
+ Per RFC 3986 the authority ends at the first `/`, so the browser parses:
scheme: http
- userinfo: localhost:58020/legit/
- host: 127.0.0.1
- port: 58021
+ userinfo: localhost:58020 (credentials — ignored for navigation)
+ host: evil.attacker.example
path: /attacker-callback
- So the browser navigates to 127.0.0.1:58021 even though the server
- prefix-check passed.
+ The string still starts with `http://localhost:58020`, so the server
+ prefix-check passes — yet the browser navigates to evil.attacker.example.
+ (The earlier `.../legit/@host/...` form is WRONG: the `@` lands in the path,
+ not userinfo, so the browser stays on localhost and the test refutes a real bug.)
This test verifies BROWSER BEHAVIOR — not server behavior. The
server-side Phase 2F verification already showed the prefix check
@@ -119,7 +120,10 @@ def test_oauth_userinfo_bypass():
# Build the malicious redirect_uri
evil_host = "evil.attacker.example" # browser will fail to resolve;
# we capture the navigation attempt first
- redirect_uri = f"http://localhost:58020/legit/@{evil_host}/attacker-callback"
+ # `@` must sit right after the registered prefix so localhost:58020 becomes
+ # USERINFO and evil_host becomes the real host (RFC 3986) — while the string
+ # still startswith the server's allowed prefix `http://localhost:58020`.
+ redirect_uri = f"http://localhost:58020@{evil_host}/attacker-callback"
from urllib.parse import quote
oauth_url = f"http://localhost:58020/oauth/authorize?client_id=acme-spa&redirect_uri={quote(redirect_uri, safe='')}"
diff --git a/engine/agent.py b/engine/agent.py
index acdc4cc..6ee5897 100644
--- a/engine/agent.py
+++ b/engine/agent.py
@@ -36,6 +36,10 @@ def run_agent(task, skills_on=False, model="claude-sonnet-4-6", max_turns=40, ti
p = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
except subprocess.TimeoutExpired:
return {"result": "", "error": "timeout", "duration_s": round(time.time() - t0, 1)}
+ except (FileNotFoundError, OSError) as e:
+ # e.g. the `claude` CLI isn't installed / not on PATH — return a structured
+ # error instead of raising, so a single missing binary can't crash the phase.
+ return {"result": "", "error": f"exec:{e}", "duration_s": round(time.time() - t0, 1)}
try:
d = json.loads(p.stdout)
res = d.get("result") or ""
diff --git a/engine/engine.py b/engine/engine.py
index 1a3d28c..5ceb170 100644
--- a/engine/engine.py
+++ b/engine/engine.py
@@ -232,10 +232,17 @@ class Engine:
todo.append(it)
self.eng.log(f"hunt: testing {len(todo)} item(s), {self.parallel} at a time")
for it, f in self._run_parallel(self._hunt_agent, todo):
- self.eng.mark_tested(it)
if f and f.get("rate_limited"):
self.eng.log("hunt: ⚠ claude usage limit hit — remaining results may be partial")
- if f and f.get("vulnerable"):
+ if (not f) or f.get("errored"):
+ # Not actually tested (agent hard error / worker exception): do NOT mark
+ # tested, so the item stays on the worklist and is retried on the next run.
+ reason = (f or {}).get("error", "worker-exception")
+ self.eng.log(f"hunt: ⚠ NOT tested ({reason}) — left on worklist: "
+ f"{it.get('vuln_class')}@{it.get('url')}")
+ continue
+ self.eng.mark_tested(it)
+ if f.get("vulnerable"):
oos = self._scope_audit(f)
cand = {"url": it["url"], "param": it.get("param", ""), "vuln_class": it.get("vuln_class"),
"severity": f.get("severity", "unknown"), "evidence": f.get("evidence", ""),
@@ -269,8 +276,16 @@ class Engine:
r = A.run_agent(task, model=self.model, max_turns=self.max_turns, timeout=self.timeout)
if r.get("error"):
self.eng.log(f"hunt agent error ({it['url']}): {r['error']}")
- return {"vulnerable": False, "rate_limited": r["error"] == "rate-limited"}
- return A.extract_json(r["result"]) or {"vulnerable": False}
+ # Hard error (timeout / rate-limit / parse / missing CLI): the item was NOT
+ # actually tested. Flag it so the caller leaves it on the worklist for retry.
+ return {"vulnerable": False, "errored": True, "error": r["error"],
+ "rate_limited": r["error"] == "rate-limited"}
+ verdict = A.extract_json(r["result"])
+ if verdict is None:
+ # Agent ran but produced no parseable verdict — inconclusive, not a real negative.
+ self.eng.log(f"hunt: no parseable verdict for {it['url']} — inconclusive, left for retry")
+ return {"vulnerable": False, "errored": True, "error": "no-verdict"}
+ return verdict
# ---------------- validate ----------------
def validate(self):
diff --git a/engine/recon.py b/engine/recon.py
index 264bd81..e9d5832 100644
--- a/engine/recon.py
+++ b/engine/recon.py
@@ -81,11 +81,13 @@ def _testable(item):
item.get("source") == "form" or bool(item.get("param"))
-def _mine(text, found_rel, found_abs):
+def _mine(text, found_rel, found_abs, base=""):
+ # found_rel stores (base, relpath) so each route is later resolved against the
+ # document it was mined from — not a single shared seed origin (fixes multi-seed).
for m in REL_API.findall(text):
- found_rel.add(m)
+ found_rel.add((base, m))
for m in NEXT_DATA.findall(text):
- found_rel.add(m)
+ found_rel.add((base, m))
for m in ABS_URL.findall(text):
if not NOISE.search(m):
found_abs.add(m.rstrip('.,);"\''))
@@ -148,8 +150,8 @@ def spa_recon(scope, seeds=None, max_js=20, interesting_only=True, log=print):
for a, b in re.findall(r'(?:Allow|Disallow):\s*(\S+)|<loc>([^<]+)</loc>', t):
pp = a or b
if pp:
- found_rel.add(pp if pp.startswith('/') else (urlparse(pp).path or '/'))
- _mine(html, found_rel, found_abs)
+ found_rel.add((base, pp if pp.startswith('/') else (urlparse(pp).path or '/')))
+ _mine(html, found_rel, found_abs, base)
secrets += scan_secrets(html, final)
for m in JS_SRC.findall(html):
ju = urljoin(base, m)
@@ -163,7 +165,8 @@ def spa_recon(scope, seeds=None, max_js=20, interesting_only=True, log=print):
for ju in list(js_urls)[:max_js]:
js, _, _ = _get(ju)
if js:
- _mine(js, found_rel, found_abs)
+ js_base = f"{urlparse(ju).scheme}://{urlparse(ju).netloc}"
+ _mine(js, found_rel, found_abs, js_base)
secrets += scan_secrets(js, ju)
# dedup secrets by (type, redacted)
_seen = set()
@@ -175,8 +178,9 @@ def spa_recon(scope, seeds=None, max_js=20, interesting_only=True, log=print):
log(f"recon: 🔑 SECRET {s['type']} = {s['redacted']} in {s['url']}")
items, oos = [], set()
- for rel in sorted(found_rel):
- url = rel if rel.startswith('http') else urljoin(seed_base + '/', rel.lstrip('/'))
+ for base_i, rel in sorted(found_rel):
+ b = base_i or seed_base # resolve against the route's own source doc
+ url = rel if rel.startswith('http') else urljoin((b or "") + '/', rel.lstrip('/'))
if scope.in_scope_host(url):
items.append({"url": url, "param": "", "source": "js/html"})
for au in sorted(found_abs):
@@ -370,7 +374,7 @@ def prune_inert_params(items, log=print):
response beyond echoing itself). Deterministic: marker-normalized body-diff vs the no-param
baseline — removing the marker first neutralizes the canonical/og:url reflection trap. Keeps
only live, processable params. (Active: ~1 request per unique endpoint + 1 per param.)"""
- kept, dead, inert, base_cache = [], 0, 0, {}
+ kept, dead, inert, failed, base_cache = [], 0, 0, 0, {}
marker = "zq9k7xp"
for it in items:
base_path = it.get("url", "").split("?", 1)[0]
@@ -378,10 +382,18 @@ def prune_inert_params(items, log=print):
if base_path not in base_cache:
base_cache[base_path] = _probe(base_path)
bcode, bbody = base_cache[base_path]
- if bcode == 0 or bcode >= 400:
+ if bcode == 0:
+ kept.append(it) # probe FAILED (network/curl) — can't judge; keep, don't prune
+ failed += 1
+ continue
+ if bcode >= 400:
dead += 1
- continue # dead endpoint
+ continue # genuinely dead endpoint (real HTTP >= 400)
tcode, tbody = _probe(f"{base_path}?{param}={marker}")
+ if tcode == 0:
+ kept.append(it) # param probe failed — keep rather than silently drop
+ failed += 1
+ continue
if tcode >= 400:
dead += 1
continue
@@ -390,9 +402,9 @@ def prune_inert_params(items, log=print):
inert += 1
continue # param ignored — no effect on response
kept.append(it)
- if dead or inert:
- log(f"params: inertness-prune dropped {dead} dead-endpoint + {inert} inert param(s) "
- f"-> {len(kept)} live/processable remain")
+ if dead or inert or failed:
+ log(f"params: inertness-prune dropped {dead} dead-endpoint + {inert} inert param(s); "
+ f"kept {failed} unprobeable (probe failed, not judged dead) -> {len(kept)} remain")
return kept
@@ -432,7 +444,9 @@ def auth_enforcement_sweep(spec, base, log=print, junk="zzz-pentest-nonexistent-
import urllib.request
import urllib.error
import time
- glob = "security" in spec
+ # A global `security: []` means "no auth for the whole API" — treat as NOT secured
+ # (mirror the op-level `!= []` check below), else public ops are wrongly swept as broken-auth.
+ glob = spec.get("security") not in (None, [])
broken, n = [], 0
for path, methods in spec.get("paths", {}).items():
for m, op in methods.items():
@@ -546,7 +560,7 @@ def openapi_recon(scope, log=print):
paths = spec.get("paths")
if not paths:
continue
- glob_sec = "security" in spec
+ glob_sec = spec.get("security") not in (None, []) # `security: []` == public, not secured
title = spec.get("info", {}).get("title", "API")
noauth = 0
for p, methods in paths.items():
@@ -613,7 +627,8 @@ if __name__ == "__main__":
rel, ab = set(), set()
_mine('a "/api/completion" b fetch("/api/v1/users") <a href="https://api.acme.com/x">'
' "/graphql" "https://www.googleapis.com/y"', rel, ab)
- assert "/api/completion" in rel and "/api/v1/users" in rel and "/graphql" in rel, rel
+ rels = {r for _, r in rel}
+ assert "/api/completion" in rels and "/api/v1/users" in rels and "/graphql" in rels, rel
assert "https://api.acme.com/x" in ab, ab
assert not any("googleapis" in a for a in ab), "noise not filtered"
assert classify({"url": "/api/completion"}) == "llm-ai"
diff --git a/eval/fp_app.py b/eval/fp_app.py
index ebd635e..7ff0c5a 100644
--- a/eval/fp_app.py
+++ b/eval/fp_app.py
@@ -43,7 +43,11 @@ class H(BaseHTTPRequestHandler):
return self._send(200, json.dumps({"query": g("q"), "results": []}), "application/json")
if p == "/go": # same-origin-validated redirect -> not open redirect
url = g("url")
- if url.startswith("/") and not url.startswith("//"):
+ # Reject backslashes (browsers normalize \ -> /) and control chars — otherwise
+ # `/\evil.com` becomes protocol-relative `//evil.com`, an EXTERNAL redirect, which
+ # would make this "safe" ground-truth trap actually vulnerable and mis-score agents.
+ if (url.startswith("/") and not url.startswith("//")
+ and "\\" not in url and all(ord(c) >= 0x20 for c in url)):
return self._send(302, "", extra={"Location": url})
return self._send(400, "External redirects are not allowed")
if p == "/api/product": # canned: no injection, no boolean/error diff
diff --git a/eval/run_eval_ps.py b/eval/run_eval_ps.py
index 5ba5527..49f813f 100644
--- a/eval/run_eval_ps.py
+++ b/eval/run_eval_ps.py
@@ -74,15 +74,19 @@ def main():
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, _ = ps_solved(url)
- solved = bool(post)
+ 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,
- "instance": url, **r}
+ "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 ''}")
+ f"{r.get('duration_s')}s{' [' + r['agent_error'] + ']' if r.get('agent_error') else ''}{note}")
out.close()
# summary
@@ -91,16 +95,20 @@ def main():
for r in rows:
by_cond.setdefault(r["condition"], []).append(r)
for cond, rs in by_cond.items():
- s = sum(1 for r in rs if r["solved"])
+ 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)
- print(f" {cond:9s}: solved {s}/{len(rs)} total ${cost:.2f}")
+ 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]
+ 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}")
diff --git a/eval/run_fp.py b/eval/run_fp.py
index f6fbb7a..487afd6 100644
--- a/eval/run_fp.py
+++ b/eval/run_fp.py
@@ -89,6 +89,12 @@ def main():
cases = json.load(open(a.cases))
conds = [c.strip() for c in a.conditions.split(",") if c.strip()]
+ # Validate up front: an unknown/typo'd condition (e.g. "skils") would silently run as
+ # baseline under the wrong label and quietly invalidate the ablation.
+ _VALID_CONDS = {"baseline", "skills"}
+ _bad = [c for c in conds if c not in _VALID_CONDS]
+ if _bad:
+ sys.exit(f"unknown --conditions: {', '.join(_bad)} (valid: {', '.join(sorted(_VALID_CONDS))})")
os.makedirs(os.path.dirname(a.out), exist_ok=True)
out = open(a.out, "a")
rows = []
diff --git a/skills/offensive-osint/scripts/secret_scan.py b/skills/offensive-osint/scripts/secret_scan.py
index a11a29a..a9371f2 100644
--- a/skills/offensive-osint/scripts/secret_scan.py
+++ b/skills/offensive-osint/scripts/secret_scan.py
@@ -142,12 +142,15 @@ def scan_path(path: str):
yield from scan_path(p)
return
try:
- # Skip large binary files (>10MB)
+ # Skip large files (>10MB) — but say so: a silently-skipped bundle is a false "clean".
if os.path.getsize(path) > 10 * 1024 * 1024:
+ print(f"[warning] skipped (>10MB, NOT scanned): {path}", file=sys.stderr)
return
with open(path, "r", errors="replace") as fh:
yield from scan_text(fh.read(), source=path)
- except (OSError, IOError):
+ except (OSError, IOError) as e:
+ # Missing/unreadable path must not be mistaken for "no secrets found".
+ print(f"[warning] could not read (skipped): {path} ({e})", file=sys.stderr)
return