Files
9ba66b1b3a fix(cbh,osint): four terminal-tooling bugs — triage gate, report BOM/CRLF, Windows console, h1 --program (#210)
* fix(cbh): triage gate — real request-target for Q1, scope-negation for Q3, clickjacking for Q7

Three false-verdict paths in the 7-Question Gate, each independently reported:

- Q1 matched a bare method word anywhere in the text, so prose like
  "target application" (contains "get ") or "input validation" passed Q1
  with no request at all. Q1 now needs a method followed by a path or URL
  (or curl / HTTP/1.1). Reported by @dajiaohuang (#209).
- Q7's never-submit list had "click-jacking" but not "clickjacking", so the
  unhyphenated spelling was never killed. Reported by @Ethereal49 (#197).
- Q3 answered YES on any scope/asset wording even when the finding itself
  said "out of scope" / "unverified". A scope/asset line carrying a negation
  no longer counts as in-scope evidence; non-scope lines ("Impact: unclear")
  still don't. Reported by @Ethereal49 (#197).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(cbh): parse finding frontmatter through a leading UTF-8 BOM

A BOM (\ufeff) written by some Windows editors sits before the `---` fence,
so the `^---` frontmatter regex missed it and severity/asset fell back to
defaults. Strip a leading BOM in parse_finding_metadata, the shared chokepoint
for every command that reads a finding, not just `cbh report`.

Reported by @jazzpher (#200).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(cbh): force UTF-8 stdout so Windows cp1252 consoles don't crash

cbh and setup_harness_mcp.py print the gate glyphs (check / cross / arrow /
em-dash) throughout. On a Windows console (cp1252) a bare print() raised
UnicodeEncodeError and the command died mid-run. Reconfigure stdout/stderr to
UTF-8 at both entrypoints, the same fix engine/engine.py:main already uses, so
the whole CLI is covered at one point rather than guarding every print.

Reported by @Sahilkumar-r (#180).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(offensive-osint): filter h1_reference --program by team_handle, not team_id

CompleteHacktivityReportIndex no longer accepts terms: {team_id: ...}, so
--program silently returned nothing. Switch to query_string "team_handle:<h>",
which filters correctly and still accepts sort + pagination (so --program now
composes with --top-voted / --top-bounty). Also: route the lookup progress line
to stderr so --json stdout stays pipeable, and reject an empty --program handle.

Two independent reports converged on this fix: @roonnnnyyyyyy (#206) and
@flipcyde101 (#202).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* docs(changelog): record the four tooling bugfixes with reporter credits

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(cbh,osint): review follow-ups — Q3 negation, Q1 markdown, CRLF, canonical handle

Adversarial review of the branch surfaced five real defects:

- Q3 _q3_scope_negated matched ANY line containing 'scope' plus a negation,
  so 'Impact: unclear scope of data exposure' wrongly killed an in-scope
  finding. Negation is now evaluated per line: strong phrases ('out of scope')
  disavow anywhere; weak words ('unknown','unclear') only on a scope/asset/
  target line (the key before the colon).
- Q3 negation list was space-only, so the common hyphenated 'out-of-scope'
  slipped through. Hyphens are normalized to spaces before matching.
- Q1 required whitespace between method and path, missing the markdown a PoC
  is usually written in (`GET /x`, **GET** /x, GET `/x`). The separator class
  now allows backticks and bold/italic markers. The prose ceiling
  ('an attacker can get /admin') is marked, not closed — requiring HTTP/ would
  reject the bare 'GET /path' PoC the gate must accept.
- parse_finding_metadata now also normalizes CRLF, so Windows findings (the
  same platform as the BOM in #200) don't skip frontmatter.
- h1_reference --program queried the raw input handle; query_string is
  case-sensitive while TeamLookup is not, so '--program Shopify' could return
  nothing. lookup_program now returns the team record and main uses the
  canonical handle.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-22 17:45:57 +05:30

286 lines
12 KiB
Python
Executable File
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
"""
setup_harness_mcp.py — wire this bundle's MCP servers into other harnesses.
Two servers can be wired:
- burp your EXISTING Burp MCP, discovered from ~/.claude.json (the stdio
command Claude Code already uses — we never invent one).
- hackerone the in-repo HackerOne MCP (mcp/hackerone/server.py), run with python3.
Carries HACKERONE_API_USERNAME / HACKERONE_API_TOKEN into the config
only if they are set in the environment at install time.
Each is written into the selected harness's config, backing up the file first. Idempotent.
Usage:
# pick servers (default is burp, for backward compatibility) and harnesses:
python3 scripts/setup_harness_mcp.py [--burp] [--hackerone] \
[--opencode] [--codex] [--hermes] [--antigravity] [--dry-run]
# optional overrides if burp auto-discovery fails:
python3 scripts/setup_harness_mcp.py --burp --opencode --command java --arg -jar --arg /path/mcp-proxy-all.jar
Schema notes (verified against each tool's docs, mid-2026):
- OpenCode ~/.config/opencode/opencode.json → mcp.<name> = {type:"local", command:[...], enabled:true} (JSON — written here)
- Codex ~/.codex/config.toml → [mcp_servers.<name>] command/args/env (TOML — appended here)
- Hermes ~/.hermes/config.yaml → MCP block (schema not independently verified) — we PRINT the
command + the Hermes MCP guide instead of blind-writing YAML.
- AntiGravity ~/.gemini/config/mcp_config.json → mcpServers.<name> = {command: "...", args: [...]} (JSON — written here)
"""
import argparse, json, os, shutil, sys, time
CLAUDE_JSON = os.path.expanduser("~/.claude.json")
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
def discover_burp():
"""Return (command:str, args:list[str], env:dict) for the 'burp' MCP server from ~/.claude.json."""
if not os.path.isfile(CLAUDE_JSON):
return None
try:
data = json.load(open(CLAUDE_JSON, encoding="utf-8"))
except Exception:
return None
hits = []
def walk(o):
if isinstance(o, dict):
for k, v in o.items():
if k in ("mcpServers", "mcp_servers", "mcp") and isinstance(v, dict):
for name, defn in v.items():
if "burp" in name.lower() and isinstance(defn, dict) and defn.get("command"):
hits.append(defn)
walk(v)
elif isinstance(o, list):
for x in o:
walk(x)
walk(data)
if not hits:
return None
d = hits[0]
return d.get("command"), list(d.get("args", [])), dict(d.get("env", {}) or {})
def hackerone_source():
"""Return (command, args, env) for the in-repo HackerOne MCP server.
env carries the HackerOne API credentials only if they are already set in the
environment (same opt-in as `claude mcp add -e`); otherwise the public tools
work keyless.
"""
server = os.path.join(REPO, "mcp", "hackerone", "server.py")
env = {k: os.environ[k] for k in ("HACKERONE_API_USERNAME", "HACKERONE_API_TOKEN")
if os.environ.get(k)}
return "python3", [server], env
def backup(path):
if os.path.exists(path):
b = f"{path}.bak-{time.strftime('%Y%m%d-%H%M%S')}"
shutil.copy2(path, b)
print(f" ↺ backed up {path} → {b}")
def toml_str(s):
# JSON's escapes are valid in TOML basic strings. Leave Unicode characters
# literal and explicitly escape DEL, which JSON permits but TOML forbids.
return json.dumps(s, ensure_ascii=False).replace("\x7f", "\\u007f")
def read_json_config(path, harness, server_key):
if not os.path.isfile(path):
return {}
try:
with open(path, encoding="utf-8") as config:
cfg = json.load(config)
if not isinstance(cfg, dict) or not isinstance(cfg.get(server_key, {}), dict):
raise ValueError(f"expected a JSON object with an object-valued {server_key} section")
except (OSError, ValueError) as exc:
print(f" ✗ {harness}: cannot update {path}: {exc}")
return None
return cfg
def write_opencode(cmd, args, env, dry, name="burp"):
path = os.path.expanduser("~/.config/opencode/opencode.json")
cfg = read_json_config(path, "OpenCode", "mcp")
if cfg is None:
return False
cfg.setdefault("$schema", "https://opencode.ai/config.json")
mcp = cfg.setdefault("mcp", {})
entry = {"type": "local", "command": [cmd] + args, "enabled": True}
if env:
entry["environment"] = env
if mcp.get(name) == entry:
print(f" = OpenCode: {name} MCP already configured (no change).")
return
mcp[name] = entry
print(f" → OpenCode: set mcp.{name} in {path}")
if dry:
print(" [dry-run] " + json.dumps(entry))
return
os.makedirs(os.path.dirname(path), exist_ok=True)
backup(path)
json.dump(cfg, open(path, "w", encoding="utf-8"), indent=2)
open(path, "a").write("\n")
print(f" ✓ OpenCode {name} MCP written.")
def write_codex(cmd, args, env, dry, name="burp"):
path = os.path.expanduser("~/.codex/config.toml")
existing = open(path, encoding="utf-8").read() if os.path.isfile(path) else ""
if f"[mcp_servers.{name}]" in existing:
print(f" = Codex: [mcp_servers.{name}] already present (no change).")
return
lines = ["", f"[mcp_servers.{name}]", f"command = {toml_str(cmd)}",
"args = [" + ", ".join(toml_str(a) for a in args) + "]"]
if env:
lines.append("")
lines.append(f"[mcp_servers.{name}.env]")
for k, v in env.items():
lines.append(f"{toml_str(k)} = {toml_str(str(v))}")
block = "\n".join(lines) + "\n"
print(f" → Codex: append [mcp_servers.{name}] to {path}")
if dry:
print(" [dry-run]\n" + "\n".join(" " + l for l in block.splitlines()))
return
os.makedirs(os.path.dirname(path), exist_ok=True)
backup(path)
with open(path, "a", encoding="utf-8") as f:
if existing and not existing.endswith("\n"):
f.write("\n")
f.write(block)
print(f" ✓ Codex {name} MCP appended. (alt: `codex mcp add {name} -- " + " ".join([cmd] + args) + "`)")
def write_hermes(cmd, args, env, dry, name="burp"):
# Hermes schema (verified): top-level `mcp_servers: <name>: {command, args, env}`.
# No PyYAML dependency, so we only WRITE when we can do it safely (append a new
# top-level block when `mcp_servers:` is absent). If it already exists, we PRINT
# the block rather than risk an unparsed merge.
path = os.path.expanduser("~/.hermes/config.yaml")
body = ["mcp_servers:", f" {name}:", f" command: {json.dumps(cmd)}",
" args: [" + ", ".join(json.dumps(a) for a in args) + "]"]
if env:
body.append(" env:")
for k, v in env.items():
body.append(f" {k}: {json.dumps(str(v))}")
block = "\n" + "\n".join(body) + "\n"
existing = open(path, encoding="utf-8").read() if os.path.isfile(path) else ""
has_mcp = existing.startswith("mcp_servers:") or "\nmcp_servers:" in existing
if has_mcp and f"{name}:" in existing:
print(f" = Hermes: {name} already in mcp_servers (no change).")
return
if has_mcp:
print(f" ℹ Hermes: {path} already has mcp_servers — add this under it manually:")
print("\n".join(" " + l for l in body[1:]))
return
print(f" → Hermes: append mcp_servers.{name} to {path}")
if dry:
print(" [dry-run]" + block.replace("\n", "\n "))
return
os.makedirs(os.path.dirname(path), exist_ok=True)
backup(path)
with open(path, "a", encoding="utf-8") as f:
if existing and not existing.endswith("\n"):
f.write("\n")
f.write(block)
print(f" ✓ Hermes {name} MCP written.")
def write_antigravity(cmd, args, env, dry, name="burp"):
path = os.path.expanduser("~/.gemini/config/mcp_config.json")
cfg = read_json_config(path, "AntiGravity", "mcpServers")
if cfg is None:
return False
servers = cfg.setdefault("mcpServers", {})
entry = {"command": cmd, "args": args}
if env:
entry["env"] = env
if servers.get(name) == entry:
print(f" = AntiGravity: {name} MCP already configured in mcp_config.json (no change).")
return
servers[name] = entry
print(f" → AntiGravity: set mcpServers.{name} in {path}")
if dry:
print(" [dry-run] " + json.dumps(entry))
return
os.makedirs(os.path.dirname(path), exist_ok=True)
backup(path)
json.dump(cfg, open(path, "w", encoding="utf-8"), indent=2)
open(path, "a").write("\n")
print(f" ✓ AntiGravity {name} MCP written.")
def _wire(name, cmd, args, env, a):
"""Write one server into every selected harness. Returns True on a hard failure."""
print(f"{name} MCP source: {cmd} {' '.join(args)}{' (dry-run)' if a.dry_run else ''}")
failed = False
if a.opencode:
failed = (write_opencode(cmd, args, env, a.dry_run, name) is False) or failed
if a.codex:
write_codex(cmd, args, env, a.dry_run, name)
if a.hermes:
write_hermes(cmd, args, env, a.dry_run, name)
if a.antigravity:
failed = (write_antigravity(cmd, args, env, a.dry_run, name) is False) or failed
return failed
def main():
# Windows/non-UTF-8 consoles default stdout to cp1252, which crashes on the
# check/cross/arrow glyphs this script prints. Force UTF-8 (see #180).
for _stream in (sys.stdout, sys.stderr):
try:
_stream.reconfigure(encoding="utf-8")
except (AttributeError, ValueError):
pass
ap = argparse.ArgumentParser()
ap.add_argument("--burp", action="store_true", help="wire the Burp MCP (default if no server flag given)")
ap.add_argument("--hackerone", action="store_true", help="wire the in-repo HackerOne MCP")
ap.add_argument("--opencode", action="store_true")
ap.add_argument("--codex", action="store_true")
ap.add_argument("--hermes", action="store_true")
ap.add_argument("--antigravity", action="store_true")
ap.add_argument("--dry-run", action="store_true")
ap.add_argument("--command")
ap.add_argument("--arg", action="append", default=[])
a = ap.parse_args()
want_burp, want_hackerone = a.burp, a.hackerone
if not (want_burp or want_hackerone):
want_burp = True # backward-compatible default
if not (a.opencode or a.codex or a.hermes or a.antigravity):
print("Nothing to do — pass --opencode / --codex / --hermes / --antigravity.")
return 0
# Resolve sources first so a burp-discovery failure doesn't half-wire hackerone.
sources = []
if want_burp:
if a.command:
sources.append(("burp", (a.command, a.arg, {})))
else:
found = discover_burp()
if found:
sources.append(("burp", found))
else:
print("✗ Could not find a 'burp' MCP server in ~/.claude.json.")
print(" Pass it explicitly, e.g.:")
print(" --command java --arg -jar --arg ~/.BurpSuite/mcp-proxy/mcp-proxy-all.jar --arg --sse-url --arg http://127.0.0.1:9876")
if not want_hackerone:
return 1
print(" → continuing with hackerone only.")
if want_hackerone:
sources.append(("hackerone", hackerone_source()))
if not sources:
return 1
failed = False
for name, (cmd, args, env) in sources:
failed = _wire(name, cmd, args, env, a) or failed
return int(failed)
if __name__ == "__main__":
sys.exit(main())