Files
Claude-BugHunter/engine/test_scope_md_rules.py
a7e73914e6 fix(scope): harden the scope gate against three fail-open paths (#182, #198, #181) (#205)
* fix(scope): normalize every rule source to host; add Scope.warnings

Out-of-scope rules written with a scheme/port/path/trailing punctuation or a
wildcard matched nothing and silently failed open. One normalization point in
Scope.__init__ now reduces every rule source (scope.md, scope.json, CLI flags,
osint/recon helpers) to its host. Port/path widening is recorded in a new
Scope.warnings channel. Reported by @fairoz-539 (#182).

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

* fix(scope): recognize IPv6 CIDR rules via ipaddress

The CIDR detector used p.replace('.','').replace('/','').isdigit(), which colons
make non-digit, so an IPv6 CIDR deny/allow rule (2001:db8::/32) never matched.
Detect any CIDR via ipaddress.ip_network; a family mismatch returns False, never
raises. Reported by @fairoz-539 (#182).

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

* fix(scope): soft-fail an invalid out-of-scope regex (warn, treat as host)

A bad re: deny regex was caught and silently matched nothing — a fail-open on the
one gate that must fail closed. Now it warns loudly and re-admits the remainder as
a literal host deny rule, so the run continues with scope still enforcing. Valid
regexes are unaffected. Reported by @fairoz-539 (#182).

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

* fix(scope): open a section only on a start/end scope heading; hint recon hosts

A recon-seeded note heading ('... VERIFY in-scope before testing') matched the
substring 'in-scope' and opened the in-scope section, silently promoting passive
crt.sh/subfinder hosts to scope rules (#198). _section_of now opens a section only
when the heading's label starts or ends with a scope phrase (trailing parenthetical
and colon stripped first). Hosts found under a scope-mentioning note heading are
surfaced as a Scope.warnings hint instead. Scaffolder heading reworded (no inner
quotes; hunt.ps1 stays ASCII). Reported by @udarshmarthala (#198).

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

* fix(scope): surface scope warnings on stderr and in the engine log

Scope.warnings (bad deny regex, widened rule, recon-seeded hosts) now print to
stderr from scope.py and go to the engine log at start — nothing is silent, and
stdout stays clean for --json-style consumers.

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

* fix(engine): follow recon redirects one hop at a time, inside scope

Recon fetches followed redirects to any host: spa_recon adopted the landed
(possibly off-scope) origin and crawled its robots/sitemap; _probe ran curl -L, so
platform/openapi recon chased Location anywhere. A new _walk() follows at most
MAX_REDIRECTS hops and only while the scope predicate accepts the next URL; all
backends (requests, a no-redirect stdlib _OPENER, curl without -L) route through it.
spa_recon re-checks the landed host, and platform/openapi recon skip out-of-scope
seeds. In-scope redirects (http->https, / -> /home) are unaffected. Reported by
@fairoz-539 (#181).

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

* fix(engine): auth sweep grades a 3xx as enforcement, never chases Location

A declared-secured op answering 302 -> /login was graded by the followed login
page's 200 as 'declared-secured, NOT enforced' — a false positive. The sweep now
uses the no-redirect opener, so a 3xx is graded as itself (enforcement) and no
request chases Location. Repoints test_openapi_readonly to the module opener.
Adds the scope-hardening CHANGELOG entry. Reported by @fairoz-539 (#181).

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

* fix(scope): review follow-ups — bare IPv6 deny, prune redirect, test sockets

Fresh-review fixes:
- CRITICAL: a bare/zoned unbracketed IPv6 single-host rule normalized to its first
  hextet (urlparse split on ':'), so an IPv6 out-of-scope rule failed open. Detect a
  literal IP in _normalize_rule and return its canonical form.
- IMPORTANT: prune_inert_params followed no redirects (allow=None), so a live
  parameterized endpoint behind an in-scope redirect (http->https, canonical slash)
  was mis-judged inert and dropped. Thread scope through and follow in-scope hops.
- MINOR: loopback test servers now server_close() in tearDown (no leaked sockets
  under -W error).

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

* docs(superpowers): scope-hardening design + implementation plan

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

* test(osint): enumeration_roots covers host after scope normalizes port/path

Rebase interaction with #221: the scope gate (#205) now widens
example.com/path and example.com:8080 to the host example.com, so
enumeration_roots correctly yields ['example.com'] instead of dropping
them. Update the #221 regression case to the combined correct behavior.

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-23 20:52:33 +05:30

147 lines
5.3 KiB
Python

import os
import tempfile
import unittest
from scope import Scope, _scope_from_md, _section_of
SCOPE_MD = """# Engagement — acme
## In scope
- https://app.example.com/login — main app
- api.example.com
- `*.dev.example.com`
- (paste in-scope asset list here)
## Out of scope
- admin.example.com
## Focus areas
- idor
"""
class ScopeFromMarkdownTests(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp(suffix=".md")
with os.fdopen(fd, "w", encoding="utf-8") as fh:
fh.write(SCOPE_MD)
def tearDown(self):
os.remove(self.path)
def test_url_bullets_match_the_host_they_point_at(self):
scope = _scope_from_md(self.path)
self.assertIn("app.example.com", scope.in_scope)
self.assertIsNone(scope.reject_reason("https://app.example.com/login"))
def test_placeholder_bullets_are_not_rules(self):
scope = _scope_from_md(self.path)
self.assertFalse([p for p in scope.in_scope if p.startswith("(")])
def test_explicit_rule_forms_survive_normalization(self):
scope = _scope_from_md(self.path)
self.assertIn("api.example.com", scope.in_scope)
self.assertIn("*.dev.example.com", scope.in_scope)
self.assertTrue(scope.in_scope_host("https://api.example.com/v1/x"))
self.assertTrue(scope.in_scope_host("https://a.dev.example.com"))
self.assertIsNotNone(scope.reject_reason("https://admin.example.com"))
def test_unlisted_host_is_still_denied(self):
scope = _scope_from_md(self.path)
self.assertIsNotNone(scope.reject_reason("https://evil.test"))
def test_regex_and_cidr_rules_are_untouched(self):
self.assertEqual(Scope(["re:^lab[0-9]+\\.acme\\.io$"]).reject_reason("https://lab4.acme.io"), None)
self.assertEqual(Scope(["10.0.0.0/8"]).reject_reason("https://10.1.2.3"), None)
# ---- #198: a heading must open a section only when it IS a scope label ----
RECON_MD = """# Engagement — acme
## In scope
- app.example.com
## Recon-seeded live hosts (from cbh manifest — VERIFY in-scope before testing)
- jira.example.com
- legacy.example.com
"""
def _write_tmp(text):
fd, path = tempfile.mkstemp(suffix=".md")
with os.fdopen(fd, "w", encoding="utf-8") as fh:
fh.write(text)
return path
class ReconSeededHeadingTests(unittest.TestCase):
def setUp(self):
self.path = _write_tmp(RECON_MD)
def tearDown(self):
os.remove(self.path)
def test_recon_hosts_are_not_in_scope(self):
scope = _scope_from_md(self.path)
self.assertTrue(scope.in_scope_host("https://app.example.com/"))
self.assertFalse(scope.in_scope_host("https://jira.example.com/"))
self.assertFalse(scope.in_scope_host("https://legacy.example.com/"))
def test_recon_hint_warning_names_count(self):
scope = _scope_from_md(self.path)
self.assertTrue(any("2 recon-seeded host" in w and "add them to" in w
for w in scope.warnings))
def test_common_in_scope_heading_forms_open_a_section(self):
for heading in ("## In scope", "## In-Scope Assets", "## Assets in scope",
"### In scope (web)"):
md = "# t\n\n%s\n\n- app.example.com\n" % heading
path = _write_tmp(md)
try:
scope = _scope_from_md(path)
self.assertTrue(scope.in_scope_host("https://app.example.com/"),
"heading did not open in-scope: %r" % heading)
finally:
os.remove(path)
def test_out_of_scope_bold_heading_opens_a_section(self):
md = "# t\n\n## In scope\n\n- example.com\n\n## **Out of scope:**\n\n- admin.example.com\n"
path = _write_tmp(md)
try:
scope = _scope_from_md(path)
self.assertFalse(scope.in_scope_host("https://admin.example.com/"))
finally:
os.remove(path)
def test_scaffolder_heading_does_not_open_a_section(self):
# The heading each scaffolder writes must not be read as a scope label,
# even though its parenthetical note references the In scope section.
root = os.path.join(os.path.dirname(__file__), "..")
for script in ("hunt.sh", "hunt.ps1"):
with open(os.path.join(root, "scripts", script), encoding="utf-8") as fh:
text = fh.read()
line = next(ln for ln in text.splitlines() if "Recon-seeded live hosts" in ln)
heading = "## Recon-seeded live hosts" + line.split("Recon-seeded live hosts", 1)[1]
heading = heading.split("')")[0].split('")')[0].rstrip("'\"\\n ")
self.assertIsNone(_section_of(heading),
"%s heading opened a section: %r" % (script, heading))
def test_mid_sentence_scope_heading_closes_section(self):
md = "# t\n\n## In scope\n\n- example.com\n\n## Notes about scope rules\n\n- other.test\n"
path = _write_tmp(md)
try:
scope = _scope_from_md(path)
# the bullet under the mid-sentence heading is NOT added as an in-scope rule
self.assertFalse(scope.in_scope_host("https://other.test/"))
self.assertTrue(scope.in_scope_host("https://example.com/"))
finally:
os.remove(path)
if __name__ == "__main__":
unittest.main()