Claude-BugHunter 确定性 scope 门禁:用 /scope 与 engine/scope.py 在首次 HTTP 请求前锁定授权边界

原创2026-11-16 13:53:222,183 阅读
文章标签:网络安全渗透测试AI 技能红蓝对抗漏洞扫描MCP Clients

Claude-BugHunter 确定性 scope 门禁:用 /scope 与 engine/scope.py 在首次 HTTP 请求前锁定授权边界

/scope 是 Claude-BugHunter 中唯一一个"先验证、后动手"的强制前置门禁:它把授权边界从"LLM 觉得应该没问题"变成"代码算出来的布尔值"。本文以 commands/scope.md 为骨架,结合 engine/scope.py 的实现细节、scripts/hunt.sh 生成的 scope.md 模板,以及 engine/engine.py 中的引擎级强制点,完整讲清这套"deny-wins + default-deny"机制如何工作、如何调用、如何排错。

读完你将能够:正确书写五种 scope 模式并避开其语义陷阱;用 /scope 或命令行直接对单个/批量资产做判定;写出能被解析器正确读取的 scope.md;并把判定结果接进自动化流水线(非零退出码即硬停)。

为什么 scope 必须由代码强制,而不是由 LLM 判断

commands/scope.md 开篇就给出了这个设计的定位:

The mandatory pre-flight gate. Verify a host or URL is in scope before any active testing. Scope is enforced in code (engine/scope.py), not by LLM judgment — deny wins, default deny.

原文给出两条理由,正好对应 engine/scope.py 的模块级 docstring:

  • 引擎可能无人值守运行(autopilot 场景),因此不能"相信 LLM 会记得边界";
  • deny wins:同时命中 in-scope 与 out-of-scope 规则时,判为越界;
  • default deny:没有命中任何 in-scope 规则,一律视为越界。

这两条组合起来的实际含义是:授权是白名单式的显式枚举,而不是"没被禁止就能测"。空白的 in-scope 列表会导致所有资产被拒绝——这不是 bug,而是安全默认值,commands/scope.md 的 Rules 一节明确把这一点写成了操作要求。

/scope 到底做了什么:三步语义

commands/scope.md 把行为拆成三步,这三点与 _main() 的实现一一对应:

  1. 加载模式集:从 engagement 的 scope.md(由 hunt 脚手架创建)读取,或从内联 --in-scope / --out-of-scope 参数读取;
  2. 确定性判定每个资产:五种模式各自有一套匹配语义(下一节展开);
  3. 打印结果并非零退出:输出 IN-SCOPE 或 OUT-OF-SCOPE <reason>,只要有任一资产越界就以非零码退出,从而"gate automation"。

对应到 engine/scope.py 的主循环:

worst = 0
for t in args.targets:
    reason = scope.reject_reason(t)
    if reason is None:
        print(f"IN-SCOPE   {t}")
    else:
        print(f"OUT-OF-SCOPE  {t}  ({reason})")
        worst = 1
return worst

注意 worst 是"粘性"的:一批资产里只要有一个越界,整次调用就以 1 退出,不会因为后面的资产合规而翻回 0。这使它可以直接用作 shell 里的前置条件:

python3 engine/scope.py api.acme.com --md ~/Targets/acme/scope.md || { echo "scope gate failed"; exit 1; }

reject_reason() 返回的三种人类可读原因(engine/scope.py)也让日志可解释:

情况 返回的 reason
无法解析出 host could not parse host
命中 out-of-scope 规则 <host> matches an out-of-scope rule
未命中任何 in-scope 规则 <host> matches no in-scope rule (default deny)
合规 None

五种模式语法及其精确语义

这是整套机制最容易写错的部分。原文的表格(commands/scope.md)给出五种形态,源码 _match()(engine/scope.py)给出了精确实现:

模式写法 语义 命中示例 不命中示例
acme.com apex 以及任意子域 acme.com、api.acme.com acme.io
*.acme.com 任意子域,不含裸 apex api.acme.com、a.b.acme.com acme.com
api.acme.com 仅该精确主机 api.acme.com x.api.acme.com
10.0.0.0/8 CIDR 内任意 IP 10.1.2.3 11.0.0.1
re:^lab[0-9]+\.acme\.io$ 显式正则(前缀 re:) lab42.acme.io lab.acme.io

裸域名分支同时覆盖"apex 或子域"

# bare domain: apex or any subdomain; or exact host
return host == p or host.endswith("." + p)

这一行同时承担两种角色:当成 acme.com 用时是"apex + 子域";当成 api.acme.com 用时,因为子域拼接会变成 .api.acme.com,所以 x.api.acme.com 也会命中——也就是说"精确主机"实际上只在不额外挂子域时才表现为精确。若你确实只想放开某一个主机而排斥其下级,需要靠 out-of-scope 规则兜底(deny wins 会生效)。

endswith("." + p) 的写法同时构成后缀混淆防护:notexample.com 不以 .example.com 结尾,example.com.evil.com 也不以 .example.com 结尾,因此原文档自测里的两条断言(engine/scope.py)都成立。

通配符 *. 不含裸 apex

if p.startswith("*."):
    base = p[2:]
    return host.endswith("." + base)

acme.com 不以 .acme.com 结尾,所以 *.acme.com 精确地"只放子域"。原文对此特意加了 (NOT the bare apex) 的说明,_selftest() 里也用 s2 专门断言了这条通配符深度语义(engine/scope.py):

s2 = Scope(in_scope=["*.test.example.com"])
assert s2.in_scope_host("a.test.example.com")
assert not s2.in_scope_host("test.example.com")

实践含义:程序页面写 *.acme.com 时,裸 acme.com 不在授权范围内,需要额外加一行 acme.com。

CIDR 分支依赖一个"看起来像数字"的启发式

if "/" in p and p.replace(".", "").replace("/", "").isdigit():  # CIDR
    try:
        return ipaddress.ip_address(host) in ipaddress.ip_network(p, strict=False)
    except ValueError:
        return False

strict=False 允许 10.0.0.1/8 这类"带主机位的网段写法"被规范化为 10.0.0.0/8,不会因为非网络地址而抛错。但入口判定用的是"去掉 . 和 / 后是否全是数字"这一启发式,因此有两个可推断的边界(属于源码结构推断,不是文档承诺):

  • 含主机名的 CIDR 不会被识别,会落到普通域名分支从而几乎必然不命中;
  • IPv6 网段(如 2001:db8::/32)含冒号,无法通过该 .isdigit() 判定,从源码看不会走 CIDR 分支。若授权清单里有 IPv6 段,建议改用 re: 形式显式表达。

re: 分支使用 re.search,不是全匹配

if p.startswith("re:"):
    try:
        return re.search(p[3:], host) is not None
    except re.error:
        return False

两个结论:

  1. 正则是"包含"语义,所以要精确锚定时必须自己写 ^...$——这就是原文档示例 re:^lab[0-9]+\.acme\.io$ 必须带锚点的原因;
  2. 非法正则是 fail-closed:re.error 直接返回 False(即不命中 in-scope / 不命中 out-of-scope),对 in-scope 而言是安全失败;但要小心:写在 out-of-scope 里的坏正则同样会静默失效,不会报错提示你规则写错了。

host 归一化:大小写、尾部点、端口与 scheme

def _host_of(target):
    t = target.strip()
    if "://" not in t:
        t = "//" + t
    host = (urlparse(t).hostname or "").lower().rstrip(".")
    return host

这段归一化决定了输入的容错能力:

  • 可以传裸主机:无 :// 时补 // 再解析,因此 api.acme.com 与 https://api.acme.com/x 等价;
  • 自动小写:DNS 大小写不敏感,这里也做了 lower;
  • 剥掉尾部点:api.acme.com.(FQDN 绝对写法)会归一为 api.acme.com,不会被误判;
  • 端口被丢弃:urlparse(...).hostname 不含端口,所以 https://10.1.2.3:8080/ 按 10.1.2.3 判定(自测里正是这么断言的)。

反过来,这也意味着模式侧不要带 scheme、端口或路径。因为 _match() 只对 pattern 做 strip().lower(),不做 URL 解析:模式 api.acme.com:8443 会去和 api.acme.com 比较,永远不相等;模式 https://api.acme.com 含 // 但不是纯数字,会落到普通字符串比较,同样不命中。模式应当是"纯 host 或 CIDR 或 re: 正则"。

两种调用方式:Slash 命令与确定性 CLI

Slash 命令(会话内首选)

原文给的最小用法(commands/scope.md):

/scope api.acme.com
/scope api.acme.com staging.acme.io admin.acme.com

支持一次传多个资产,判定是逐个独立进行的,输出也是逐行的——非常适合在拿到一批 recon 结果后先整体过一遍。

直接运行 CLI(可脚本化)

原文的 "Under the hood" 段落强调优先针对 engagement 的 scope.md 判定:

# Against the engagement scope.md (preferred — fill scope.md from the program page first)
python3 engine/scope.py api.acme.com --md ~/Targets/acme/scope.md

# Or with inline patterns (repeat --in-scope / --out-of-scope per pattern)
python3 engine/scope.py api.acme.com evil.com \
  --in-scope acme.com --in-scope '*.acme.io' --out-of-scope admin.acme.com

_main() 的完整参数面(engine/scope.py):

参数 作用 备注
targets(位置参数,nargs="*") 待判定的 host/URL 列表 为空直接 ap.error("no targets given")
--md PATH 从脚手架生成的 scope.md 读取规则 优先级最高
--scope-file PATH 从 engagement 的 scope.json 读取 供引擎复用同一份 JSON
--in-scope PATTERN 内联 in-scope 规则 action="append",可重复
--out-of-scope PATTERN 内联 out-of-scope 规则 action="append",可重复
--selftest 运行内置自测后返回 0 用于验证环境/回归

三个规则来源是互斥优先级而非叠加:--md 优先于 --scope-file,--scope-file 优先于内联参数;三者都没给会 ap.error("provide --md, --scope-file, or --in-scope/--out-of-scope patterns")。所以不要把 --md 和 --in-scope 混用来"补充几条"——后者会被静默忽略。

--scope-file 读取的是 JSON,键名与 engine/engagement.example.json 完全一致:

{
  "name": "demo-local",
  "in_scope": ["localhost", "127.0.0.1"],
  "out_of_scope": ["admin.localhost"],
  "seeds": ["http://localhost:3002"]
}

Scope.load() 按 in_scope / out_of_scope / seeds / name 四个键取值(engine/scope.py),缺省分别是空列表与 "engagement"。这也意味着 scope.json 里没有 out_of_scope 就等于没有任何例外规则,不是"不检查"。

另外值得明确一点:scope 没有对应的 cbh 子命令。从 cbh/cli.py 看,CLI 只注册了 recon、surface、classify、triage、report,scope 判定走的是 /scope 与 engine/scope.py 两条路径。

scope.md 的解析规则:_scope_from_md() 逐条讲清

/scope 推荐从 scope.md 读规则,这使得"人填 Markdown、机器读 Markdown"成为可能。解析器只有约 30 行(engine/scope.py),但规则不少,直接决定你的模板能不能被读到。

只认两级标题,且靠关键词区分方向

if low.startswith("#"):
    hashes = len(low) - len(low.lstrip("#"))
    if "out of scope" in low or "out-of-scope" in low:
        section = "out"
    elif "in scope" in low or "in-scope" in low:
        section = "in"
    elif hashes <= 2:
        section = None     # a peer-level section (## Focus areas, etc.)
    # deeper sub-headings (### Web, #### APIs) keep the current section
    continue

要点:

  • 判定是子串匹配,大小写不敏感(low),所以 ## Out of scope、## OUT-OF-SCOPE、### Out of Scope (per program page) 都能被识别;
  • 先判 out 再判 in,避免 ## In scope / out of scope notes 这类标题被误判为 in;
  • ### 及更深的标题继承当前分区:想在 ## In scope 下按业务线分组(### Web、### APIs),列表项仍然算 in-scope;
  • #~## 级别的其他标题会清空分区:所以 ## Focus areas、## Bounty bands 之后的列表不会被当作 scope 规则。这也正是原文模板把这三个小节放在 scope 之后仍安全的原因。

每个 bullet 只取第一个空白分隔 token

if section and (s.startswith("- ") or s.startswith("* ")):
    tok = s[2:].strip().split()[0:1]

这带来两个实用特性:

  • 支持 - api.example.com — 主站 API,重点关注 这种"规则 + 备注"写法,解析结果为 api.example.com(docstring 里的例子正是 - api.example.com — note);
  • 备注里不能出现空格分隔的第二个"看起来像规则"的 token 之前的内容——因为只取第一个 token,剩余部分整体丢弃,不会被误当成第二条规则。

但反过来说:如果一行里想写多个 host(- a.com b.com),只有 a.com 会被读进去,b.com 静默丢失。多条规则必须各占一行。

占位符会被跳过,空模板等于全部拒绝

if pat.startswith("(") or pat.startswith("["):
    continue          # placeholder text, not a real pattern

模板里的 - (paste in-scope asset list here) 以 ( 开头,因此被跳过;同理 - [ ] 这类复选框也不会被误读。结果是:未填写的 scope.md 产生空的 in-scope 列表 → default deny → 全量拒绝。原文 Rules 把这条写成了显式操作要求:

If scope.md is still the empty template ((paste ... here) placeholders), fill it from the program page first; an empty in-scope list = default-deny = everything rejected, which is the safe default.

一个容易踩的坑:如果你把占位符改成 - TODO: api.example.com,它以 T 开头,不会被当占位符跳过,于是 TODO: 会变成一条永远不会命中的规则,同时真实主机仍然被拒绝——现象看起来像"我明明填了却不生效"。

从 hunt 脚手架到可用的 scope.md

原文说 scope.md 由 hunt scaffold 创建(commands/scope.md),具体实现是 scripts/hunt.sh。运行 hunt acme 会在 ${HUNT_BASE:-$HOME/Targets}/acme/ 下建目录,并写入以下小节:

小节 是否被 _scope_from_md() 解析为规则
## In scope 是(in-scope)
## Out of scope 是(out-of-scope)
## Focus areas 否(## 级标题,清空分区)
## Bounty bands(表格) 否(且表格行不以 - 开头)
## Engagement rules / safe harbor 否
## Account / testing setup 否
## OOS clauses worth pre-empting in submissions 否(标题不含 in scope / out of scope 关键词;OOS 缩写不被识别)

模板头部还有一行提示,说明这段时间点的正确动作:

> Parse this from the program page (Bugcrowd / HackerOne / etc.) before
> doing any active testing. `/scope <asset>` can verify individual assets.

Out of scope 占位符的措辞也值得注意——它不只要求资产列表,还要求"被程序排除的漏洞类型":

- (paste OOS list here, including any bug classes excluded by the program)

不过要清楚:_scope_from_md() 只做主机级匹配,漏洞类型级别的排除(例如"不接受 non-auth 端点的限速问题")不会被 /scope 执行。这类排除属于 skills/triage-validation/SKILL.md 的 Q3/Q7 判断范围,与主机 scope 门禁是两个层次。

recon manifest 注入的"待验证"主机段

hunt 的第二个来源是 recon manifest(scripts/hunt.sh)。若存在 ./recon/<target>/manifest.json(或通过第二个参数 / HUNT_MANIFEST 指定),脚本会把 manifest 里的资产追加到 scope.md:

## Recon-seeded live hosts (from cbh manifest — VERIFY in-scope before testing)

- host1
- host2

这段落在 ## 级标题下,且标题不含 in scope 关键词,所以它不会被 /scope 当成 in-scope 规则——这是刻意的:来自 recon 的存活主机不等于授权资产,必须人工核对后移入 ## In scope。凡是把这段直接信任并拿去跑工具的做法,都会绕过白名单语义。

引擎级的强制点:scope 不只在命令行里生效

engine/README.md 对 scope.py 的一句话总结是 "deterministic allowlist (apex/wildcard/CIDR/regex; deny-wins; default-deny). Enforced at recon and hunt."。落实到代码,至少有四层:

第一层:recon 阶段过滤。 engine/recon.py 在入口处就检查 seed,并在功能点、JS endpoint、参数收集等处逐个调用 scope.in_scope_host()(约在 engine/recon.py 与 L346-L369),越界 URL 直接不进入采集结果。

第二层:hunt 阶段拒派。 engine/engine.py 在派发 agent 之前再做一次判定:

if not self.scope.in_scope_host(it["url"]):     # belt-and-suspenders scope gate
    self.eng.log(f"hunt: REFUSING out-of-scope {it['url']} ({self.scope.reject_reason(it['url'])})")

注释里的 belt-and-suspenders(背带 + 腰带)说明了设计意图:即使 recon 已经过滤过,派发前仍要独立再判一次。

第三层:把 scope 写进 agent 的 rules of engagement。 _roe()(engine/engine.py)把 in-scope 主机列表直接注入提示词,并明确"即使为了证明漏洞也不得触碰第三方服务":

- SCOPE: ONLY these hosts are in scope: {hosts}. NEVER send a request to ANY other host
  (no third-party APIs / CDNs / SaaS such as emailjs, salesforce, google, etc.), even to 'prove' a
  finding. If proof would require touching an out-of-scope host/service, DO NOT do it — report the
  finding but set proof_note='would require out-of-scope action (NOT performed)'.

第四层:事后审计。 _scope_audit()(engine/engine.py)从 finding 的 request、evidence、hosts_contacted 中正则抽取所有 https?://host,用同一套 in_scope_host() 反查:

hosts = set(re.findall(r'https?://([A-Za-z0-9.\-]+)', blob)) | set(f.get("hosts_contacted") or [])
return sorted({h for h in hosts if h and not self.scope.in_scope_host(h)})

命中即写入 scope_warning,并在报告中以 ⚠ 标注(engine/engine.py)。这一层是"提示而非阻断":finding 不会被自动删除,而是被标记为"PoC 引用了越界主机,需人工复核在合规前提下结论是否仍成立"。

与其他命令的协作位置

原文的 Rules 只给了一条硬约束:"Run this before any HTTP touch." 在整条流水线里,/scope 被放在所有主动动作之前:

命令 与 scope 的关系 依据
/hunt 兄弟命令委派表中的第一条:before any HTTP touch → /scope (mandatory pre-flight) commands/hunt.md
/autopilot 流程第一步即 "SCOPE Load and confirm program scope",并承诺 "Every URL is checked against the scope allowlist before any request" commands/autopilot.md
/recon 产出中的 in-scope-subs.txt 表示"确认在范围内"的子域,需要经过 scope 判定才能生成 commands/recon.md
/triage、/validate 7-Question Gate 的 Q3 问"asset 是否在范围内",越界直接 KILL;Q7 的 scope 依据就是 engagement scaffold 的 scope.md skills/triage-validation/SKILL.md

一个容易被忽略的细节来自 commands/hunt.md:/hunt 明确要求不要让操作员粘贴 SOW / engagement letter 原文,因为那是敏感客户数据。原文同时强调这不是绕过授权:

This is a data-hygiene rule, NOT an authorization bypass: scope is still enforced by /scope (deterministic, deny-wins) and the triage-validation 7-Question Gate before any finding ships.

也就是说,本套机制验证的是"在不在范围内",不收集"你有没有授权"的书面证据。授权本身被假定已在场外确立。这个边界必须在文档里说清楚,否则容易把门禁误当成授权来源。

用 --selftest 验证语义是否符合预期

engine/scope.py 自带一个可直接运行的自测(engine/scope.py):

python3 engine/scope.py --selftest
# scope.py self-test: PASS

它断言了 14 条语义,可作为一份"行为契约"速查:

断言 覆盖的语义
https://example.com/login 命中 裸域名的 apex
http://api.example.com/x 命中 裸域名覆盖子域
https://a.test.example.com 命中 *.test.example.com 通配
https://10.1.2.3:8080/ 命中 CIDR + 端口被丢弃
https://lab42.acme.io 命中 re: 正则
admin.example.com / internal.example.com 拒绝 deny wins
test.example.com 命中 裸 example.com 规则兜住子域
evil.com 拒绝 default deny
notexample.com 拒绝 后缀混淆防护
example.com.evil.com 拒绝 后缀混淆防护
11.0.0.1 拒绝 CIDR 外
reject_reason 返回真值 / None 原因可读性
a.test.example.com 命中、test.example.com 拒绝 通配符深度

注意自测里 test.example.com 之所以命中,是因为规则集同时含 example.com——这正好演示了"通配符 + 裸域"组合使用的必要性。

常见失败模式与排查清单

结合源码可以列出一份排错顺序,几乎覆盖了实际使用中会遇到的全部"判定结果不符合直觉":

  1. 结果是全量 OUT-OF-SCOPE → 先看 ## In scope 下是否还是 - (paste in-scope asset list here)。占位符被跳过 → 空列表 → default deny。
  2. 填了规则但没生效 → 检查标题层级:规则必须在 ## In scope(或它的 ### 子标题)之下;写在 ## Focus areas 后面的列表不会被解析。
  3. 规则行没被读到 → 检查是否以 - 或 * 开头(含空格);一行写多个 host 时只有第一个会被采用。
  4. 规则里带了 scheme/端口/路径 → 模式侧不做 URL 解析,https://api.acme.com、api.acme.com:8443 这类写法永远不命中。
  5. 以为是通配符,其实排除了 apex → *.acme.com 不含 acme.com;两者需分别写。
  6. 以为是精确主机,结果子域也被放行 → 裸域分支的 endswith("." + p) 会覆盖子域;需要排除的用 out-of-scope 显式写。
  7. 越界资产仍被放行 → 检查 out-of-scope 规则是否写成了非法正则(re: 分支 re.error 时会静默返回 False)。
  8. IPv6 网段不生效 → CIDR 分支的 .isdigit() 启发式无法识别冒号,从源码看应改用带锚点的 re: 规则。
  9. --md 与 --in-scope 同时给了,后者无效 → 三个规则来源是优先级关系,不是叠加。

把门禁接进日常流程的最小实践

基于原文的 Rules 与源码行为,一套稳定可复用的做法是:

  1. 先填模板,再判资产:hunt <target> 建脚手架 → 从程序页面把 in-scope / out-of-scope 逐条落到 ## In scope / ## Out of scope(一行一条,纯 host/CIDR/re:);
  2. 用自测确认环境无损:python3 engine/scope.py --selftest;
  3. 批量预检:把 recon 存活主机逐行喂给 /scope 或 CLI,用非零退出码卡住后续步骤;
  4. 每次主动测试前单点复检:对即将发包的那一个 host 再跑一次,尤其是拼接出来的子域、重定向目标、以及 PoC 里要引用的第三方回调;
  5. 发现漏洞后回头审计:确认 PoC 用到的所有主机都在白名单内;越界即按 proof_note='would require out-of-scope action (NOT performed)' 处理,把结论降级为"需在范围内复核"而不是硬凑证明。

这套流程没有依赖任何 LLM 判断:/scope 的价值不在于"提醒模型注意边界",而在于把边界变成一次可以返回非零退出码的函数调用。当规范、模板、解析器、引擎注入与事后审计都指向同一份 scope.md 时,授权边界才真正成为工程约束,而不是一句叮嘱。

登录后查看全文
Claude-BugHunter