AiSOC Self-play 紫队实战:构建一个会攻击自己的 SOC 闭环
AiSOC Self-play 紫队实战:构建一个会攻击自己的 SOC 闭环
本文以 AiSOC 的自博弈(Self-play)紫队能力为核心,讲清一件在安全工程里很容易被说漂亮、却很难被做对的事:让 SOC 用 LLM 规划的多阶段攻击链去打自己的防御,并按 ATT&CK 技术逐条记分、把漏检自动转成 Detection-as-Code 提案。读完后你将掌握三件事:如何在本仓库几秒内跑通离线确定性战役、硬性实验室范围守卫为什么必须写在代码里而不是提示词里、以及 plan → run → score → improve 这条闭环在源码层面的真实接口与扩展点。
从"测试执行器"到"持续对手"
AiSOC 的 purple-team 服务原本的定位是攻击模拟执行器(Atomic Red Team 执行、Caldera 对手仿真、ATT&CK 覆盖热力图、桌面推演)。Self-play 把这个定位往前推了一步:它不是一个被动的测试运行器,而是一个持续对手——
- 由 LLM 可参与规划的计划引擎,从 Atomic Red Team + Caldera 的技战术清单里组合出多阶段攻击链;
- 在闭环中对"活着的防御"执行,逐技术判定 detected / missed;
- 对每一次漏检自动提交 Detection-as-Code(下文简称 DAC)提案;
- 全程被一个代码级硬守卫约束在 allowlist 的实验室范围内。
这条能力在仓库中的落点是 services/purple-team/app/adversary 目录,包说明写在 init.py,它明确强调了最后那半句:"all constrained to an allowlisted lab scope by a hard code guard (never a prompt instruction)"。
模块划分非常克制,每个文件只承担一个环节:
| 文件 | 职责 |
|---|---|
| scope_guard.py | 硬性实验室范围守卫,违规即抛 ScopeViolation |
| planner.py | 从清单组合有序 kill chain,只打环境里真实存在的平台 |
| campaign.py | 执行 + 记分,发射器与检测神谕均为可插拔 Protocol |
| dac.py | 为每个漏检生成 Sigma 脚手架并提交提案 |
| scoreboard.py | 把战役报告聚合成周度记分板行 |
| canned.py | 离线确定性演示战役,即 pnpm aisoc:selfplay |
先用几秒钟跑通一次战役
仓库根目录的 package.json 挂了两个脚本,直接把 canned campaign 暴露成一条命令:
"aisoc:selfplay": "cd services/purple-team && python3 -m app.adversary.canned",
"aisoc:selfplay:json": "cd services/purple-team && python3 -m app.adversary.canned --json",
因此最短路径是:
pnpm aisoc:selfplay
输出是一份带 ledger 风格的逐阶段轨迹(下面这段就是 canned 战役的确定性结果):
── AiSOC self-play campaign (canned, offline) ──
[1] initial-access T1566.001 ✗ MISSED Spearphishing Attachment
[2] execution T1059.001 ✓ DETECTED (12.0s) PowerShell
[3] persistence T1547.001 ✗ MISSED Registry Run Keys / Startup Folder
[4] privilege-escalation T1055 ✓ DETECTED (12.0s) Process Injection
[5] exfiltration T1048 ✓ DETECTED (12.0s) Exfiltration Over Alternative Protocol
3/5 techniques detected (60%) · MTTV 12.0s
Auto-filed 2 Detection-as-Code proposal(s) for the misses (eval-gated review)
需要机器可读结果时改用 JSON 模式:
pnpm aisoc:selfplay:json
--json 会输出 report、dac_proposals_filed、scoreboard_row 三个键(见 canned.py),便于在 CI 或文档渲染中直接消费。也完全可以绕过 pnpm,在服务目录内直接跑模块:
cd services/purple-team && python3 -m app.adversary.canned --json
关于"确定性"这一点值得强调:canned 战役使用 InMemoryEmitter(把事件记在内存列表里,不写 Kafka)和 CannedOracle(固定检测集合、固定 12.0s 延迟),所以它零外部依赖、可在演示 CI 与笔记本上秒级复现。它演示的是闭环形状是否跑通,而不是某条防线今天的真实检测率。
读懂 canned 战役的三个常量
canned 战役的所有输入都是显式常量,读一遍就等于读懂了记分逻辑:
CANNED_INVENTORY = [
InventoryTechnique("T1566.001", "Spearphishing Attachment", "initial-access", frozenset({"windows"}), 90),
InventoryTechnique("T1059.001", "PowerShell", "execution", frozenset({"windows"}), 95),
InventoryTechnique("T1547.001", "Registry Run Keys / Startup Folder", "persistence", frozenset({"windows"}), 80),
InventoryTechnique("T1055", "Process Injection", "privilege-escalation", frozenset({"windows"}), 85),
InventoryTechnique("T1048", "Exfiltration Over Alternative Protocol", "exfiltration", frozenset({"windows", "linux"}), 88),
]
CANNED_TARGETS = [
Asset.of("lab-win-01", "lab", "windows"),
Asset.of("sandbox-win-02", "sandbox", "windows"),
]
CANNED_DETECTED = {"T1059.001", "T1055", "T1048"}
对应 canned.py。注意目标上的 lab / sandbox 标签不是装饰:没有它们,守卫会直接拒绝整场战役。
最重要的安全属性:范围守卫是代码,不是提示词
一个会攻击自己的 SOC,最危险的不是漏检,而是打到了生产资产。Self-play 的答案是一个不可绕过的硬失败点,位于 scope_guard.py。
两个数据类
@dataclass(frozen=True)
class Asset:
asset_id: str
tags: frozenset[str] = field(default_factory=frozenset)
@classmethod
def of(cls, asset_id: str, *tags: str) -> Asset:
return cls(asset_id=asset_id, tags=frozenset(t.strip().lower() for t in tags))
Asset.of() 会统一 strip().lower(),因此 " Lab "、"LAB" 都会被归一为 lab,避免大小写/空白差异把守卫绕过去。Asset 与 LabScope 都是 frozen=True,构造后不可变。
白名单与黑名单
| 类别 | 默认标签集合 |
|---|---|
allowed_tags |
lab, sandbox, purple-team, range, test |
forbidden_tags |
production, prod, live, crown-jewel, crown_jewels, pci, phi, customer-data |
判定规则只有一条,写在 LabScope.is_in_scope() 里:先看是否命中禁售标签,命中即拒;再看是否命中至少一个实验室标签。
def is_in_scope(self, asset: Asset) -> bool:
tags = {t.lower() for t in asset.tags}
if tags & self.forbidden_tags:
return False
return bool(tags & self.allowed_tags)
这个顺序就是"禁止标签永远赢"的实现:给一台 crown-jewel 机器再贴上 lab 标签,并不能把它洗白。
三种彻底拒绝
assert_in_scope() 是执行前的最终兜底,它会在三种情况下抛 ScopeViolation:
- 空目标集 —— 没有可安全攻击的对象时拒绝开跑(
"refusing to run: no in-scope lab targets were provided"); - 任一目标带禁止标签 —— 报错信息会列出具体资产与命中的标签;
- 任一目标不带任何实验室标签 —— 即"必须显式把资产 opt-in 到靶场",未打标签默认不安全。
错误信息会把所有违规资产拼在一起返回,而不是遇到第一个就中断,便于一次修完。关键点是:没有 force 开关,也没有"我知道我在做什么"的旁路参数。filter_lab_targets() 只是一个规划期的便利过滤,assert_in_scope() 仍然是执行期必然重跑的backstop。
守卫的对抗性测试
这类安全属性如果只有"正常路径"测试,等于没有测试。仓库为守卫写了专门的对抗用例,见 tests/test_adversary.py:
| 测试 | 证明的性质 |
|---|---|
test_scope_guard_hard_fails_on_production_asset |
带 production 标签的资产必被拒 |
test_scope_guard_hard_fails_on_untagged_asset |
未打标签资产必被拒(默认不安全) |
test_scope_guard_hard_fails_on_empty_targets |
空目标集必被拒 |
test_scope_guard_hard_fails_when_forbidden_tag_coexists_with_lab_tag |
lab + crown-jewel 的洗白尝试必被拒 |
test_scope_guard_allows_lab_and_sandbox |
lab 与 sandbox 正常放行 |
test_filter_lab_targets_drops_non_lab |
规划期过滤只保留实验室目标 |
其中"洗白尝试"那条用例最能说明设计意图:守卫不是启发式,而是集合交集判定,禁止集合优先。
闭环第一步:规划(Plan)
planner.py 定义固定顺序的五阶段 kill chain:
STAGES: tuple[str, ...] = (
"initial-access",
"execution",
"persistence",
"privilege-escalation",
"exfiltration",
)
清单条目携带技术 ID、名称、阶段、支持平台与优先级:
@dataclass(frozen=True)
class InventoryTechnique:
technique_id: str
technique_name: str
stage: str
platforms: frozenset[str] # e.g. {"windows", "linux"}
priority: int = 50 # higher = preferred when multiple match
只打"环境里真实存在"的东西
平台推断来自资产标签:_platforms_present() 只识别一组已知平台名(windows、linux、macos、aws、azure、gcp、kubernetes、office365);如果实验室目标没有声明任何平台,则回退为 {"windows", "linux"} 通用靶场假设。
每个阶段的候选集合是"阶段匹配 且(平台有交集 或 该技术不声明平台)",然后取 priority 最高者:
candidates = [t for t in inventory if t.stage == stage and (t.platforms & platforms or not t.platforms)]
if not candidates:
continue # attack only what the environment can actually run
chosen = max(candidates, key=lambda t: t.priority)
continue 而非报错,意味着缺失阶段会被跳过(例如清单里没有 exfiltration 技术时,就产出 4 步战役);但如果一个阶段都匹配不上,会抛 ScopeViolation("no inventory technique matches the lab environment's platforms")(planner.py)。
规划期就已经过一遍守卫
plan_campaign() 的第一件事是过滤 + 硬校验,然后才构建计划:
targets = filter_lab_targets(candidate_targets, scope)
assert_in_scope(targets, scope)
platforms = _platforms_present(targets)
primary = targets[0].asset_id
注意 primary:当前实现里所有步骤指向同一个主目标,这是刻意保守的简化。测试 test_plan_composes_ordered_kill_chain 断言了步骤顺序与 order 从 1 开始,以及 all(s.target == "lab-win-01")。
另一条重要的测试是 test_plan_only_attacks_present_platforms:Linux-only 靶场里,只有 frozenset({"linux"}) 的 T1059.004 会被选中,Windows-only 的 T1059.001 即便优先级更高(95 > 90)也不会被规划。
"LLM-planned" 的准确含义
文档把这个引擎描述为 LLM 规划的战役引擎;源码 docstring 的措辞更精确:组合本身是确定性的(每阶段取优先级最高的匹配技术),而"LLM 可以重排或丰富计划,但永远不能扩大范围"——因为规划期只选实验室目标,执行期还会再硬校验一次。从这个实现看,可复现性优先于模型自由度,这是安全与可审计的合理取舍。
闭环第二步与第三步:执行(Run)与记分(Score)
campaign.py 用两个 Protocol 把"产生遥测"和"判定是否被抓到"解耦,从而同一份闭环代码既能跑真环境,也能跑离线确定性测试。
class TelemetryEmitter(Protocol):
def emit(self, step: CampaignStep) -> dict: ...
class DetectionOracle(Protocol):
def was_detected(self, technique_id: str, event: dict) -> tuple[bool, float | None, str | None]: ...
was_detected() 的返回值是三元组 (detected, latency_s, detector_id):第二项是检测时延(用于 MTTV),第三项是告警/检测器标识。
执行前的最后一次守卫
def run_campaign(campaign, emitter, oracle, scope=None) -> CampaignReport:
# Backstop safety check at execution time — never trust that planning was safe.
assert_in_scope(list(campaign.targets) or [Asset.of("__none__")], scope)
这一行是整套设计里最关键的一行:or [Asset.of("__none__")] 把"目标为空"显式转换成一个必然失败的非实验室资产,于是空目标不会变成"零步骤顺利跑完"的假成功,而是直接抛 ScopeViolation。
报告的两类指标
执行完每步后填充 StepResult,聚合在 CampaignReport 上:
| 属性 | 含义 |
|---|---|
techniques_attempted |
实际执行的技术 ID 列表 |
detected / missed |
命中/漏检的 StepResult 列表 |
detection_rate |
len(detected)/len(results),四舍五入到 4 位;空报告为 0.0 |
mean_time_to_verdict_s |
仅对"已检测且延迟非空"的步骤求均值,保留 2 位;无可用样本时为 None |
to_dict() 输出适合直接落盘/上板的扁平结构:techniques_attempted(数量)、techniques_detected、detection_rate、mean_time_to_verdict_s、missed_techniques、steps[]。
这里有个容易被忽略的细节:MTTV 只统计命中样本。漏检不会被当作"∞ 秒"参与平均,因此 MTTV 必须与 detection_rate 一起读——60% 检出率下的 12.0s,含义是"被抓到的那 3 条平均 12 秒出结论",而不是"整场战役 12 秒"。
离线实现的语义
InMemoryEmitter.emit() 生成的事件带四个字段:technique_id、stage、target、source: "self-play"。source 字段让下游能一眼区分"自博弈产生的遥测"和真实流量。CannedOracle 则用固定的 detected_ids 集合与固定 latency_s(默认 12.0)实现确定性判定,命中时返回 alert-<technique_id> 作为检测器标识。
对应测试集中在 tests/test_adversary.py:
test_run_campaign_scores_detected_and_missed:5 步里命中 2 → 检出率0.4、MTTV12.0;test_emitter_records_events_for_every_step:发射器事件数与步骤数一致,且source全为self-play。
闭环第四步:把漏检变成 DAC 提案(Improve)
dac.py 的定位写得很直白:self-play 只能 propose,永远不能静默 merge。
提案草稿的结构
@dataclass(frozen=True)
class DacProposalDraft:
name: str
description: str
rule_language: str
rule_body: str
category: str
severity: str
confidence: int
mitre_techniques: list[str]
tags: list[str]
build_gap_proposal(miss) 会针对漏检技术生成一份 Sigma 脚手架,几个固定取值很关键:
| 字段 | 取值 | 理由 |
|---|---|---|
rule_language |
sigma |
与仓库检测规则生态一致 |
category |
purple-team-gap |
便于按来源筛选覆盖缺口 |
severity |
medium |
缺口而非已确认事件 |
confidence |
40 |
低置信:脚手架,待 eval + 人工评审 |
tags |
self-play、coverage-gap、stage:<stage> |
保留来源与阶段溯源 |
mitre_techniques |
[tid] |
绑定 ATT&CK 技术 |
生成的规则体刻意留了 # TODO: encode the observable for this technique,并只用一个粗糙的 CommandLine|contains 作为占位选择条件:
title: Self-play gap — <technique_name> (<tid>)
status: experimental
description: Auto-proposed by the self-play purple team after <tid> (<stage>) executed without detection. Refine the selection before promoting.
tags:
- attack.<tid 小写>
logsource:
category: process_creation
product: windows
detection:
selection:
# TODO: encode the observable for this technique
CommandLine|contains: '<technique_name 首词小写>'
condition: selection
falsepositives:
- Legitimate administrative activity
level: medium
这是"诚实脚手架"的写法:它不假装自己是一条可用的检测规则,而是把"这里需要人补什么"直接写进规则体。
提交流水线是可插拔的
class DacFiler(Protocol):
def file(self, draft: DacProposalDraft) -> str: ...
仓库当前实现的是 InMemoryFiler(把草稿收进列表,返回 in-memory-<n> 引用),供测试与 canned 演示使用;模块 docstring 同时说明了 live 路径的 HttpDacFiler 会向 API 的 POST /api/v1/detection-proposals 提交。auto_file_gaps(report, filer) 则对 report.missed 逐条生成并提交,返回提案引用列表。
对应测试(tests/test_adversary.py):
test_auto_file_files_one_proposal_per_miss:5 步命中 1 → 4 条提案,且category == "purple-team-gap"、rule_language == "sigma";test_gap_proposal_carries_the_technique_and_is_low_confidence:规则体含attack.<tid>标签,confidence <= 50,tags含self-play。
为什么"只提案"是硬约束
提案进入的是已有的 DAC 评审流水线,见 services/api/app/api/v1/endpoints/detection_proposals.py。该模块头部注释说明了两道独立的门,且必须同时通过才能晋升:
- 候选规则门(非循环):
POST /detection-proposals/{id}/evaluate-rule用运行时引擎执行提案规则本身,对调用方提供的正/负样本必须"正样本全命中、负样本全静默"。这修补了早期"晋升路径从不评估提案规则"的现实审计发现。 - 基座基准门:
POST /detection-proposals/{id}/eval跑scripts/run_evals.py,拒绝让仓库整体 MITRE 准确率回退 ≥max_regression_pp个百分点的候选。
完整生命周期包括:POST /detection-proposals(创建)、POST .../comment(评审意见)、POST .../evaluate-rule(候选规则评估)、POST .../eval(基准结果+裁决)、POST .../decide(批准/拒绝)、POST .../promote(物化进 detection_rules)。字段层面 DacProposalDraft 与提案模型对齐(name/description/rule_language/rule_body/category/severity/confidence/mitre_techniques/tags),所以一次自博弈漏检会自然落到"待评审"状态,而不是直接上线。
记分板与"synthetic"诚实标志
scoreboard.py 把报告聚合成一行周度记录:
def build_scoreboard_row(
report: CampaignReport,
*,
new_detections_filed: int,
synthetic: bool,
version: str = "unreleased",
) -> dict:
产出字段:date(UTC YYYY-MM-DD)、version、campaign、techniques_attempted、techniques_detected、detection_rate、mean_time_to_verdict_s、new_detections_filed、synthetic。merge_scoreboard(existing, row, keep=52) 把新行插到最前并最多保留 52 周。
公开数据落在 apps/docs/static/data/selfplay-scoreboard.json,canned 战役对应的那行是:
{
"date": "2026-07-17",
"version": "unreleased",
"campaign": "nightly-self-play (canned)",
"techniques_attempted": 5,
"techniques_detected": 3,
"detection_rate": 0.6,
"mean_time_to_verdict_s": 12.0,
"new_detections_filed": 2,
"synthetic": true
}
文件顶部的 _comment 把规则写死了:synthetic 标志用于区分"离线确定性 canned 演示"与"针对种子靶场的夜间实跑",永远不能把 synthetic 行当作实测的线上性能。这与仓库其他评估工具(例如 docs/benchmark-methodology.md 中反复强调的 synthetic vs real 划线)是同一条诚信规则。canned.py 在调用时硬编码 synthetic=True,并把这句话也打印在终端最后一行:"Synthetic canned campaign — the nightly live run scores against the seeded range."
手写一场针对 Linux 靶场的战役
canned 战役是 Windows 靶场。想验证"只打存在的平台"这条规则,可以直接在服务目录里用同一套 API 组一场自定义战役(不修改仓库任何文件):
cd services/purple-team && python3 - <<'PY'
from app.adversary.campaign import CannedOracle, InMemoryEmitter, run_campaign
from app.adversary.dac import InMemoryFiler, auto_file_gaps
from app.adversary.planner import InventoryTechnique, plan_campaign
from app.adversary.scope_guard import Asset
inventory = [
InventoryTechnique("T1059.004", "Unix Shell", "execution", frozenset({"linux"}), 90),
InventoryTechnique("T1059.001", "PowerShell", "execution", frozenset({"windows"}), 95),
InventoryTechnique("T1543.002", "Systemd Service", "persistence", frozenset({"linux"}), 80),
InventoryTechnique("T1041", "Exfiltration Over C2 Channel", "exfiltration", frozenset({"linux"}), 70),
]
targets = [Asset.of("lab-linux-01", "lab", "linux")]
campaign = plan_campaign("linux-drill", inventory, targets)
print([(s.order, s.stage, s.technique_id) for s in campaign.steps])
report = run_campaign(campaign, InMemoryEmitter(), CannedOracle({"T1059.004"}))
print(report.to_dict()["detection_rate"], report.mean_time_to_verdict_s)
filer = InMemoryFiler()
print(auto_file_gaps(report, filer), [d.name for d in filer.filed])
PY
预期行为:PowerShell(Windows-only,优先级更高)不会出现在计划里;initial-access 与 privilege-escalation 阶段因清单缺失被跳过;检出率 0.3333,MTTV 12.0,两条漏检各生成一条 [self-play] Detect ... 提案。
如果把最后一行换成 Asset.of("db-prod-01", "production", "linux"),plan_campaign 会在构建计划之前抛 ScopeViolation;即便你手工构造一个 Campaign 直接调用 run_campaign,执行前的 backstop 也会拦住它。这正是"守卫不依赖规划器是否正确"的含义。
与 purple-team 服务的其它能力如何衔接
Self-play 不是孤岛,它复用同一套服务资产(见 services/purple-team/app/api/routes.py):
- 原子测试入库:
POST /api/v1/purple-team/atomics/sync调用 atomic_loader.py 遍历 Atomic Red Team 的atomics/目录,按技术目录读取<TID>/<TID>.yaml,抽取attack_technique、display_name、atomic_tests[]的test_guid、supported_platforms、executor、input_arguments等字段,按tenant_id + test_guid去重入库。注意其_infer_tactic()是按技术 ID 前缀的粗略映射(例如T1059→execution、T1003→credential-access),源码注释也说明完整映射需要 STIX bundle——这正是 self-play 计划器需要自带stage字段、而不是从 loader 推断的原因。 - 执行记录与检测回填:
POST /api/v1/purple-team/atomics/run只创建pending记录(真实执行 out-of-band);PATCH /api/v1/purple-team/executions/{id}/detection回填detected、alert_id、detection_latency_seconds。self-play 的StepResult三要素(detected / latency / alert_id)与此形状一致,这是 live 神谕能自然落库的前提。 - 覆盖热力图:
GET /api/v1/purple-team/coverage由compute_coverage_for_tenant()基于执行历史实时计算,按真实 ATT&CK tactic 分组。 - 检测漂移:
POST /api/v1/purple-team/drift/snapshot、GET .../drift/latest提供快照与 delta;快照节奏由 config.py 的drift_snapshot_interval_seconds控制,默认7 * 24 * 60 * 60(周度),设0关闭。 - 租户与鉴权:路由默认拒绝(
router = APIRouter(dependencies=[Depends(require_service_auth)])),且每个触达租户数据的路由都额外取require_console_or_service_auth的租户主体,把tenant_id从"裸查询参数"改成"从主体解析 + 越权即 403"。POST /caldera/run会启动真实的对手仿真操作,因此租户解析发生在调用 Caldera 之前。
另外,CalderaClient 的密钥刻意没有默认值(config.py):注释指出历史上默认值是 Caldera 首次启动的公开口令 ADMIN123,导致"从未配置 Caldera 的部署"也会拿着默认口令去认证。_caldera() 在密钥为空时直接返回 503 并点名 CALDERA_API_KEY,把配置缺失与对方服务故障区分开。
当前状态与尚未闭环的那一段
按文档与源码,已实现并有测试覆盖的部分是:计划器、硬范围守卫、闭环记分器、DAC 自动提交器、canned 战役。test_canned_campaign_runs_end_to_end(tests/test_adversary.py)把整条链路钉住:5 条技术、3 条命中、2 条提案、synthetic is True、new_detections_filed == 2。
剩余工作同样明确:把夜间 live 战役接进 full-profile 调度器,即把三类 live 适配器落地——Kafka 遥测发射器、告警存储检测神谕、以及向 POST /api/v1/detection-proposals 提交的 HttpDacFiler。在当前仓库中,InMemoryEmitter / CannedOracle / InMemoryFiler 是已有实现,HttpDacFiler 仅出现在 dac.py 的模块说明里。因此:
- 可以引用的结论是"闭环骨架与安全守卫已完成并测试";
- 不能引用的结论是"夜间实跑已经在生产靶场产生实测检测率"。记分板里
synthetic: false的行,才是那条尚未被填上的记录。
实践要点清单
- 跑通:
pnpm aisoc:selfplay(人读)/pnpm aisoc:selfplay:json(机读),或在services/purple-team下python3 -m app.adversary.canned。 - 靶场准入:目标必须带
lab/sandbox/purple-team/range/test之一,且不得带production/prod/live/crown-jewel/crown_jewels/pci/phi/customer-data;默认不安全,必须显式 opt-in。 - 平台声明:给靶场资产打
windows/linux/… 标签,否则计划器按{windows, linux}通用靶场假设行事;声明得越准,"只打存在的平台"越严格。 - 缺口处理:把
confidence=40、category=purple-team-gap的提案当作待办工单,而不是已生效检测;晋升必须过候选规则门与基座基准门。 - 数据诚信:
synthetic: true的行只能用来证明流水线可跑,绝不能当作实测检测率对外引用。