mirror of
https://github.com/elementalsouls/Claude-BugHunter.git
synced 2026-11-24 20:30:23 +01:00
* fix(cbh): classify_url matches path/query, not hostname (#219) Pattern triggers ran against the full URL, so a keyword in the hostname (verify.example.com, cart.shop.example) matched a leading-slash path pattern via the //. Match against parsed.path+query instead; the previously-unused parsed is now the source of truth. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(engine): extract_json keeps the last top-level JSON value (#217) The unfenced fallback used one greedy {.*} DOTALL span (first brace to last), so any earlier brace in the reply — a curl payload in the prose — made the whole span unparseable and the verdict was lost, re-running the item as no-verdict. Scan top-level values with raw_decode and keep the last. Fenced replies are unaffected. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(osint): secret_scan prunes skip dirs by name, always scans the root (#216) The skip check tested each noisy-dir word as a substring of the whole walked path, root included. So scanning ./dist, .github/ (contains .git), or nightly-builds/ matched and skipped everything, printing nothing and exiting 0 — a false clean in a leak guard. Prune os.walk's dirs by exact name below the root instead; the requested root is always scanned. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(osint): derive enumeration roots from authorized scope (#213) osint() and _expand_scope() took the enumeration apex by keeping a seed host's last two labels. Under a multi-label public suffix that apex is the suffix itself (example.co.uk -> co.uk), so subfinder/assetfinder/crt.sh queried the whole suffix and the in-scope filter discarded the results; --expand never enumerated the target at all. IP seeds became '3.4'. New shared osint.enumeration_roots() takes roots from in-scope domain rules and maps each seed to its shortest covering root (full hostname if uncovered), with no public-suffix list. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(leak-guard): reject malformed denylist hashes (#212) A committed .sha256 line that is not a 64-hex digest was loaded verbatim as a 'hash' that no real sha256 can match — a silent false-negative in the leak guard. load_denylist now validates each entry and fails closed (exit 2) on a malformed one, naming the line to fix without printing its content. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * docs(changelog): credit five tooling/engine bugfix reporters (#219,#217,#216,#213,#212) Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(review): harden extract_json, classify_url, and the skill-linter denylist Adversarial review of the five bugfixes surfaced four to fold: - extract_json: a truncated top-level array let an inner element be returned as the verdict; stop at the first unparseable bracket instead of descending. Also widen the except to (ValueError, RecursionError) so deep nesting in the C scanner can't escape into the verdict path. - classify_url: schemeless input (api.php.net/x) put the host in parsed.path, so .php still fired. Prefix // when there's no scheme. - lint_skills.load_denylist: same malformed-hash fail-open as #212 in the skill linter — validate and fail closed there too. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
216 lines
8.4 KiB
Python
216 lines
8.4 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
osint.py — deterministic OSINT / scope-expansion phase.
|
|
|
|
Given a domain, the FIRST step is discovering the in-scope footprint — subdomains,
|
|
live hosts, services, tech — not jumping straight to the apex page. This shells out
|
|
to the installed passive tools (subfinder, assetfinder) + certificate transparency
|
|
(crt.sh), scope-filters the results, then probes each host for liveness + tech stack.
|
|
The live in-scope targets feed per-target recon. No LLM in enumeration (it's mechanical).
|
|
|
|
PD httpx isn't reliably present (the `httpx` on PATH is often the Python lib), so the
|
|
liveness/tech probe uses a robust curl-based fingerprint that always works.
|
|
"""
|
|
import ipaddress
|
|
import json
|
|
import re
|
|
import subprocess
|
|
from shutil import which
|
|
from tempfile import TemporaryDirectory
|
|
from pathlib import Path
|
|
from urllib.parse import urlparse
|
|
|
|
|
|
def _run(cmd, timeout=120):
|
|
try:
|
|
return subprocess.run(cmd, capture_output=True, text=True, timeout=timeout).stdout
|
|
except Exception:
|
|
return ""
|
|
|
|
|
|
def enumerate_subdomains(apex, log=print):
|
|
subs = {apex}
|
|
if which("subfinder"):
|
|
out = _run(["subfinder", "-d", apex, "-silent"], 150)
|
|
names = [x.strip().lower() for x in out.splitlines() if x.strip()]
|
|
subs.update(names)
|
|
log(f"osint: subfinder -> {len(names)} name(s)")
|
|
if which("assetfinder"):
|
|
out = _run(["assetfinder", "--subs-only", apex], 90)
|
|
names = [x.strip().lower() for x in out.splitlines() if x.strip()]
|
|
subs.update(names)
|
|
log(f"osint: assetfinder -> +{len(names)} name(s)")
|
|
crt = _run(["curl", "-s", "-m", "25", f"https://crt.sh/?q=%25.{apex}&output=json"], 30)
|
|
try:
|
|
c = 0
|
|
for x in json.loads(crt):
|
|
for nm in x.get("name_value", "").split("\n"):
|
|
nm = nm.strip().lower()
|
|
if nm and "*" not in nm:
|
|
subs.add(nm); c += 1
|
|
log(f"osint: crt.sh -> +{c} name(s)")
|
|
except Exception:
|
|
log("osint: crt.sh (no data / slow)")
|
|
return subs
|
|
|
|
|
|
def _fingerprint(headers, body):
|
|
tech = []
|
|
for h in ("server", "x-powered-by", "x-generator"):
|
|
if headers.get(h):
|
|
tech.append(headers[h])
|
|
b = body[:8000].lower()
|
|
for marker, name in [("/_next/", "Next.js"), ("__next_data__", "Next.js"), ("/_nuxt/", "Nuxt"),
|
|
("ng-version", "Angular"), ("data-reactroot", "React"), ("wp-content", "WordPress"),
|
|
("gatsby", "Gatsby"), ("cdn.shopify", "Shopify"), ("drupal-", "Drupal"),
|
|
("readme.io", "ReadMe"), ("gitbook", "GitBook"), ("docusaurus", "Docusaurus")]:
|
|
if marker in b and name not in tech:
|
|
tech.append(name)
|
|
return tech
|
|
|
|
|
|
def probe(host, timeout=12):
|
|
"""Probe https then http; return target dict or None if dead."""
|
|
with TemporaryDirectory(prefix="cbh-osint-") as scratch:
|
|
for scheme in ("https", "http"):
|
|
url = f"{scheme}://{host}/"
|
|
body_path = Path(scratch) / scheme
|
|
out = _run(["curl", "-s", "-m", str(timeout), "-L", "-D", "-", "-o", str(body_path), url], timeout + 6)
|
|
codes = re.findall(r'^HTTP/\S+\s+(\d{3})', out, re.M)
|
|
if not codes:
|
|
continue
|
|
headers = {}
|
|
for line in out.splitlines():
|
|
m = re.match(r'^([A-Za-z0-9\-]+):\s*(.*?)\s*$', line)
|
|
if m:
|
|
headers[m.group(1).lower()] = m.group(2)
|
|
try:
|
|
body = body_path.read_text(encoding="utf-8", errors="replace")
|
|
except OSError:
|
|
body = ""
|
|
title = (re.search(r'<title[^>]*>([^<]*)', body, re.I) or [None, ""])[1].strip()
|
|
return {"host": host, "url": f"{scheme}://{host}/", "status": int(codes[-1]),
|
|
"server": headers.get("server", ""), "title": title[:70], "tech": _fingerprint(headers, body)}
|
|
return None
|
|
|
|
|
|
def _run_stdin(cmd, stdin, timeout=240):
|
|
try:
|
|
return subprocess.run(cmd, input=stdin, capture_output=True, text=True, timeout=timeout).stdout
|
|
except Exception:
|
|
return ""
|
|
|
|
|
|
def _pd_httpx():
|
|
"""Return the ProjectDiscovery httpx binary (httpx-toolkit) — NEVER the Python `httpx`
|
|
lib that often shadows `httpx` on PATH. None if a real PD binary isn't found."""
|
|
for cand in ("httpx-toolkit",):
|
|
if which(cand):
|
|
try:
|
|
r = subprocess.run([cand, "-version"], capture_output=True, text=True, timeout=10)
|
|
blob = (r.stdout + r.stderr).lower()
|
|
if "projectdiscovery" in blob or "current version" in blob:
|
|
return cand
|
|
except Exception:
|
|
pass
|
|
return None
|
|
|
|
|
|
def probe_hosts(hosts, log=print):
|
|
"""Liveness + tech probe. Prefers PD httpx-toolkit (batch, rich tech-detect); curl fallback."""
|
|
pd = _pd_httpx()
|
|
if pd:
|
|
out = _run_stdin([pd, "-silent", "-json", "-sc", "-title", "-td", "-server",
|
|
"-timeout", "12", "-no-color"], "\n".join(hosts))
|
|
targets = []
|
|
for line in out.splitlines():
|
|
try:
|
|
d = json.loads(line)
|
|
targets.append({"host": d.get("input") or urlparse(d.get("url", "")).hostname,
|
|
"url": d.get("url", ""), "status": d.get("status_code"),
|
|
"server": d.get("webserver", ""), "title": (d.get("title") or "")[:70],
|
|
"tech": d.get("tech", []) or []})
|
|
except Exception:
|
|
pass
|
|
return targets, pd
|
|
targets = [probe(h) for h in hosts]
|
|
return [t for t in targets if t], "curl(fallback — install PD httpx-toolkit)"
|
|
|
|
|
|
def _is_ip(host):
|
|
try:
|
|
ipaddress.ip_address(host)
|
|
return True
|
|
except ValueError:
|
|
return False
|
|
|
|
|
|
def enumeration_roots(scope):
|
|
"""Subdomain-enumeration roots taken from the authorized scope.
|
|
|
|
Truncating a seed to its last two labels lands on the public suffix for
|
|
multi-label TLDs (example.co.uk -> co.uk), so enumeration queried the whole
|
|
suffix and the in-scope filter discarded everything. Instead: every domain
|
|
rule in scope is a root; a seed covered by one uses the shortest covering
|
|
root; an uncovered seed is enumerated as its full hostname. No suffix list.
|
|
"""
|
|
domains = set()
|
|
for p in scope.in_scope:
|
|
p = p.strip().lower().rstrip(".")
|
|
if p.startswith("*."):
|
|
p = p[2:]
|
|
if not p or "/" in p or ":" in p or p.startswith("re:") or "." not in p:
|
|
continue
|
|
if _is_ip(p):
|
|
continue
|
|
domains.add(p)
|
|
roots = set(domains)
|
|
for seed in scope.seeds:
|
|
try:
|
|
host = urlparse(seed if "://" in seed else "//" + seed).hostname
|
|
except ValueError:
|
|
continue
|
|
if not host:
|
|
continue
|
|
host = host.lower().rstrip(".")
|
|
if _is_ip(host):
|
|
continue
|
|
covering = [d for d in domains if host == d or host.endswith("." + d)]
|
|
roots.add(min(covering, key=len) if covering else host)
|
|
return sorted(roots)
|
|
|
|
|
|
def osint(scope, log=print, max_probe=80):
|
|
"""Return live in-scope targets [{host,url,status,server,title,tech}]."""
|
|
apexes = enumeration_roots(scope)
|
|
log(f"osint: apex domain(s): {', '.join(apexes) or '(none)'}")
|
|
|
|
subs = set()
|
|
for apex in apexes:
|
|
subs |= enumerate_subdomains(apex, log)
|
|
in_scope = [s for s in sorted(subs) if scope.in_scope_host(s)]
|
|
log(f"osint: {len(subs)} name(s) discovered -> {len(in_scope)} in scope; probing liveness + tech...")
|
|
|
|
probed = in_scope[:max_probe]
|
|
targets, tool = probe_hosts(probed, log)
|
|
for t in targets:
|
|
log(f"osint: LIVE {(t.get('host') or '?'):28s} [{t.get('status')}] "
|
|
f"{('· ' + ', '.join(t['tech'])) if t.get('tech') else ''}")
|
|
dead = len(probed) - len(targets)
|
|
log(f"osint: {len(targets)} live target(s) via {tool}, {dead} dead/no-DNS "
|
|
f"(decommissioned; verify before claiming takeover)")
|
|
return targets
|
|
|
|
|
|
if __name__ == "__main__":
|
|
import sys
|
|
sys.path.insert(0, __file__.rsplit("/", 1)[0])
|
|
from scope import Scope
|
|
if len(sys.argv) > 1:
|
|
dom = sys.argv[1].replace("https://", "").replace("http://", "").strip("/")
|
|
sc = Scope(in_scope=[dom, "*." + dom], seeds=["https://" + dom + "/"], name="adhoc")
|
|
for t in osint(sc):
|
|
print(f" {t['url']:38s} [{t['status']}] {t['server']:18s} {', '.join(t['tech'])}")
|
|
else:
|
|
print("usage: python3 osint.py <domain>")
|