bugx-cli 0.1.4 → 0.1.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +89 -210
- package/core/README.md +1 -1
- package/core/agent/agent_execution.py +7 -0
- package/core/agent/agent_targets.py +5 -1
- package/core/agent/agent_workspace.py +10 -2
- package/core/autonomous_cve/run_fault_matrix.py +692 -0
- package/core/autonomous_cve/run_oss_cve_exploit_verify.py +608 -0
- package/core/autonomous_cve/run_six_worker_penetration.py +382 -0
- package/core/autonomous_cve/verifier.py +5 -7
- package/core/bugx.md +1 -1
- package/core/bugx_paths.py +2 -2
- package/core/bundled_docs/OVERVIEW.md +70 -236
- package/core/bundled_docs/README.md +2 -2
- package/core/bundled_docs/README_EN.md +67 -211
- package/core/bundled_docs/ai/01_AI_REFERENCE.md +11 -6
- package/core/bundled_docs/ai/02_AI_USAGE.md +1 -1
- package/core/bundled_docs/ai/03_AI_COMMANDS.md +1 -1
- package/core/bundled_docs/guides/01_USER_GUIDE.md +5 -5
- package/core/bundled_docs/guides/02_COMMANDS.md +3 -3
- package/core/bundled_docs/guides/03_TROUBLESHOOTING.md +4 -4
- package/core/bundled_docs/guides/05_HOST_MATRIX_AND_DISPATCH.md +4 -2
- package/core/bundled_docs/hosts/bugx_SKILL.md +2 -2
- package/core/bundled_docs/hosts/platform_bugx_SKILL.md +2 -2
- package/core/bundled_docs/manifest.json +22 -22
- package/core/bundled_docs/reference/01_ENVIRONMENT_VARIABLES.md +1 -0
- package/core/bundled_docs/reference/04_REPOSITORY_TOPOLOGY.md +1 -1
- package/core/cloud_sync/flywheel_client.py +89 -0
- package/core/contracts/README.md +1 -1
- package/core/contracts/bugx-runtime-contract.md +1 -1
- package/core/contracts/bugx-worker.md +1 -1
- package/core/coverage/coverage_ai_review.py +15 -11
- package/core/coverage/coverage_bootstrap.py +18 -13
- package/core/coverage/coverage_discovery.py +1 -1
- package/core/coverage/coverage_gate.py +12 -2
- package/core/coverage/coverage_manifest.py +1 -1
- package/core/coverage/coverage_validate.py +5 -3
- package/core/dev_harness/interaction_preset.py +1 -1
- package/core/engine-integrity.json +183 -163
- package/core/host_acp/README.md +4 -0
- package/core/host_acp/agnescode.py +128 -0
- package/core/host_runtime/README.md +3 -0
- package/core/host_runtime/adapters.py +45 -6
- package/core/host_runtime/autonomous_runner.py +3 -2
- package/core/host_runtime/host_registry.py +7 -1
- package/core/hosts/README.md +4 -0
- package/core/hosts/__init__.py +1 -0
- package/core/hosts/agnescode.py +415 -0
- package/core/hosts/base.py +1 -0
- package/core/hosts/claude.py +6 -0
- package/core/hosts/cline.py +6 -0
- package/core/hosts/codex.py +10 -1
- package/core/hosts/kimi.py +6 -4
- package/core/hosts/opencode.py +12 -4
- package/core/hosts/zcode.py +6 -0
- package/core/infra/README.md +1 -1
- package/core/infra/build_info.py +2 -2
- package/core/infra/python_runtime.py +4 -1
- package/core/launch_phases/README.md +2 -2
- package/core/launch_phases/finding_confirm_phase.py +1 -1
- package/core/launch_phases/semantic_recon.py +3 -19
- package/core/launch_phases/startup_gates.py +10 -1
- package/core/launch_phases/startup_version_gate.py +2 -2
- package/core/launch_phases/verify_loop.py +3 -19
- package/core/ledger/README.md +1 -1
- package/core/ledger/finding_confirmation.py +1 -1
- package/core/ledger/finding_verification.py +2 -20
- package/core/ledger/fp_ledger.py +3 -19
- package/core/ledger/life_ledger.py +7 -33
- package/core/ledger/schema.py +1 -1
- package/core/locales/en-US.json +2 -0
- package/core/locales/zh-CN.json +2 -0
- package/core/mcp_handlers/supervisor_handlers.py +34 -2
- package/core/mcp_handlers/telemetry_handlers.py +32 -0
- package/core/mcp_handlers/tool_table.py +34 -0
- package/core/mcp_runtime_support/common.py +6 -0
- package/core/mcp_runtime_support/environment.py +82 -23
- package/core/metadata.txt +1 -1
- package/core/planning/README.md +1 -1
- package/core/planning/target_sandbox_manager.py +2 -0
- package/core/probes/mobile_probe.py +1 -0
- package/core/probes/sast_probe.py +1 -1
- package/core/probes/sca_scanner.py +1 -1
- package/core/project_profiler/constants.py +1 -1
- package/core/retrieval/README.md +1 -1
- package/core/retrieval/symbol_index.py +229 -53
- package/core/retrieval/universal_code_matcher.py +1 -0
- package/core/runtime/README.md +1 -1
- package/core/runtime/daemon_runner.py +3 -2
- package/core/runtime/mining_quality_framework.py +2 -1
- package/core/runtime/project_init.py +1 -1
- package/core/runtime/scenario_eval.py +5 -2
- package/core/skills/bugx_mcp_server.py +9 -0
- package/core/skills/mcp_session_proof.py +3 -31
- package/core/supervisor/README.md +1 -1
- package/core/supervisor/finding_commit.py +3 -24
- package/core/supervisor/task_scheduler.py +5 -2
- package/core/supervisor/worker_execution.py +5 -0
- package/core/supervisor/worker_handoff.py +2 -2
- package/docs/07_distribution/01_README_NPM.md +89 -210
- package/ecosystem/integrations/dsh/mcp/package.json +2 -2
- package/ecosystem/integrations/dsh/ui/package.json +1 -1
- package/ecosystem/integrations/opencode/bugx-mcp-manifest.json +3 -3
- package/ecosystem/integrations/opencode/mcp-lock.json +1 -1
- package/ecosystem/integrations/pi/extensions/bugx/manifest.json +1 -1
- package/ecosystem/integrations/qoder/connector-meta.json +1 -1
- package/ecosystem/integrations/workbuddy/connector-meta.json +1 -1
- package/ecosystem/integrations/workbuddy/skills/bugx/SKILL.md +1 -1
- package/ecosystem/plugins/bugx/.claude-plugin/plugin.json +1 -1
- package/ecosystem/plugins/bugx/.codex-plugin/plugin.json +1 -1
- package/ecosystem/plugins/bugx/.zcode-plugin/plugin.json +1 -1
- package/ecosystem/plugins/bugx/skills/bugx/SKILL.md +2 -2
- package/interfaces/cli/bugx_cli/__init__.py +1 -1
- package/interfaces/cli/bugx_cli/cli.py +15 -0
- package/interfaces/cli/bugx_cli/commands/agent.py +18 -0
- package/interfaces/cli/bugx_cli/commands/audit.py +5 -6
- package/interfaces/cli/bugx_cli/commands/doctor.py +1 -1
- package/interfaces/cli/bugx_cli/commands/lifecycle.py +1 -1
- package/interfaces/cli/bugx_cli/commands/patch.py +5 -1
- package/interfaces/cli/bugx_cli/commands/plugin.py +31 -2
- package/interfaces/cli/bugx_cli/commands/plugin_claude.py +2 -2
- package/interfaces/cli/bugx_cli/host_adapters.py +167 -1
- package/interfaces/cli/bugx_cli/hosts/registry.py +33 -1
- package/interfaces/cli/bugx_cli/infra/engine_installer.py +4 -4
- package/interfaces/cli/bugx_cli/infra/host_sync.py +1 -1
- package/package.json +1 -1
- package/scripts/sync-version.mjs +1 -1
- package/skills/platform/bugx/SKILL.md +2 -2
|
@@ -0,0 +1,608 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Run manifest-driven CVE PoCs against vulnerable and fixed target copies.
|
|
3
|
+
|
|
4
|
+
The manifest is deliberately small and explicit. Each target provides a
|
|
5
|
+
``before`` and ``after`` directory, one argv-only PoC executor, and at least
|
|
6
|
+
one positive case plus one ``negative_control`` case. The executor receives
|
|
7
|
+
``{target}``, ``{input}``, ``{phase}``, ``{cve}``, ``{case}``, and
|
|
8
|
+
``{manifest_root}`` substitutions and must print a JSON object on its final
|
|
9
|
+
non-empty stdout line, for example ``{"status_code": 500, "crashed": true}``.
|
|
10
|
+
|
|
11
|
+
Only the copied target is exposed to the PoC. Every execution gets a fresh
|
|
12
|
+
private temporary directory and is run through ``core.worker_execution`` so a
|
|
13
|
+
PoC cannot mutate the source target or outlive its process group.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import argparse
|
|
19
|
+
import base64
|
|
20
|
+
import hashlib
|
|
21
|
+
import json
|
|
22
|
+
import os
|
|
23
|
+
import shutil
|
|
24
|
+
import sys
|
|
25
|
+
import tempfile
|
|
26
|
+
from pathlib import Path
|
|
27
|
+
from typing import Any, Mapping, Sequence
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
REPO_ROOT = Path(__file__).resolve().parents[2]
|
|
31
|
+
CORE_ROOT = REPO_ROOT / "core"
|
|
32
|
+
if str(REPO_ROOT) not in sys.path:
|
|
33
|
+
sys.path.insert(0, str(REPO_ROOT))
|
|
34
|
+
if str(CORE_ROOT) not in sys.path:
|
|
35
|
+
sys.path.insert(0, str(CORE_ROOT))
|
|
36
|
+
|
|
37
|
+
from core.supervisor.worker_execution import WorkerExecutionError, run_bounded # noqa: E402
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
SCHEMA_VERSION = 1
|
|
41
|
+
DEFAULT_MANIFEST = (REPO_ROOT / "verification" / "sandboxes" / "cve_targets.json") if (REPO_ROOT / "verification" / "sandboxes").is_dir() else (REPO_ROOT / "sandboxes" / "cve_targets.json")
|
|
42
|
+
DEFAULT_OUT = REPO_ROOT / ".bugx" / "evidence" / "cve-exploit-verify.json"
|
|
43
|
+
MAX_COMMAND_ARGS = 128
|
|
44
|
+
MAX_CASES_PER_TARGET = 256
|
|
45
|
+
MAX_INPUT_BYTES = 16 * 1024 * 1024
|
|
46
|
+
MAX_OUTPUT_BYTES = 2 * 1024 * 1024
|
|
47
|
+
MAX_TIMEOUT_SECONDS = 300.0
|
|
48
|
+
RESPONSE_FIELDS = ("status_code", "crashed", "exit_code", "abnormal_exit")
|
|
49
|
+
SHELL_OPERATORS = frozenset({
|
|
50
|
+
";", "&", "&&", "|", "||", "<", ">", ">>", "<<", "<&", ">&",
|
|
51
|
+
"`", "$(", "(", ")",
|
|
52
|
+
})
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class DriverError(ValueError):
|
|
56
|
+
"""Invalid manifest, target boundary, or PoC protocol."""
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _canonical(value: object) -> bytes:
|
|
60
|
+
return json.dumps(
|
|
61
|
+
value,
|
|
62
|
+
ensure_ascii=False,
|
|
63
|
+
sort_keys=True,
|
|
64
|
+
separators=(",", ":"),
|
|
65
|
+
allow_nan=False,
|
|
66
|
+
).encode("utf-8")
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _sha256(value: bytes) -> str:
|
|
70
|
+
return hashlib.sha256(value).hexdigest()
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _text(value: object, field: str, *, allow_empty: bool = False, limit: int = 4096) -> str:
|
|
74
|
+
if not isinstance(value, str) or len(value) > limit or (not allow_empty and not value.strip()):
|
|
75
|
+
raise DriverError(f"{field} must be a {'string' if allow_empty else 'non-empty string'}")
|
|
76
|
+
return value
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _argv(value: object, field: str) -> list[str]:
|
|
80
|
+
if isinstance(value, (str, bytes)) or not isinstance(value, Sequence):
|
|
81
|
+
raise DriverError(f"{field} must be an argv array; shell strings are rejected")
|
|
82
|
+
result = list(value)
|
|
83
|
+
if not result or len(result) > MAX_COMMAND_ARGS or any(
|
|
84
|
+
not isinstance(item, str) or not item for item in result
|
|
85
|
+
):
|
|
86
|
+
raise DriverError(f"{field} must be a non-empty string argv array")
|
|
87
|
+
# Shell punctuation is safe inside one argv element (the PoC commonly uses
|
|
88
|
+
# ``python -c``); only standalone operator tokens would indicate an
|
|
89
|
+
# accidentally shell-shaped command contract.
|
|
90
|
+
if any(item in SHELL_OPERATORS for item in result):
|
|
91
|
+
raise DriverError(f"{field} contains a shell operator")
|
|
92
|
+
return result
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _path_without_symlink(root: Path, raw: object, field: str) -> Path:
|
|
96
|
+
relative = Path(_text(raw, field, limit=1024))
|
|
97
|
+
if relative.is_absolute():
|
|
98
|
+
raise DriverError(f"{field} must be relative to the manifest directory")
|
|
99
|
+
current = root
|
|
100
|
+
for part in relative.parts:
|
|
101
|
+
if part in {"", "."}:
|
|
102
|
+
continue
|
|
103
|
+
if part == "..":
|
|
104
|
+
current = current.parent
|
|
105
|
+
continue
|
|
106
|
+
current = current / part
|
|
107
|
+
if current.is_symlink():
|
|
108
|
+
raise DriverError(f"{field} cannot traverse a symlink: {relative}")
|
|
109
|
+
resolved_root = root.resolve()
|
|
110
|
+
resolved = (root / relative).resolve()
|
|
111
|
+
try:
|
|
112
|
+
resolved.relative_to(resolved_root)
|
|
113
|
+
except ValueError as exc:
|
|
114
|
+
raise DriverError(f"{field} escapes the manifest directory") from exc
|
|
115
|
+
if resolved.is_symlink() or not resolved.is_dir():
|
|
116
|
+
raise DriverError(f"{field} must name an ordinary directory: {resolved}")
|
|
117
|
+
return resolved
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _reject_tree_symlinks(source: Path) -> None:
|
|
121
|
+
for current, directories, files in os.walk(source, followlinks=False):
|
|
122
|
+
current_path = Path(current)
|
|
123
|
+
for name in [*directories, *files]:
|
|
124
|
+
candidate = current_path / name
|
|
125
|
+
if candidate.is_symlink():
|
|
126
|
+
raise DriverError(f"target tree contains a symlink: {candidate}")
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _decode_payload(case: Mapping[str, Any]) -> bytes:
|
|
130
|
+
if "payload" not in case:
|
|
131
|
+
raise DriverError(f"case {case.get('id', '?')} must provide payload")
|
|
132
|
+
payload = case["payload"]
|
|
133
|
+
if not isinstance(payload, str):
|
|
134
|
+
raise DriverError(f"case {case.get('id', '?')} payload must be a string")
|
|
135
|
+
encoding = case.get("encoding", "utf8")
|
|
136
|
+
try:
|
|
137
|
+
if encoding == "utf8":
|
|
138
|
+
data = payload.encode("utf-8", "surrogatepass")
|
|
139
|
+
elif encoding == "base64":
|
|
140
|
+
data = base64.b64decode(payload, validate=True)
|
|
141
|
+
elif encoding == "hex":
|
|
142
|
+
data = bytes.fromhex(payload)
|
|
143
|
+
else:
|
|
144
|
+
raise DriverError(f"case {case.get('id', '?')} has unsupported encoding: {encoding!r}")
|
|
145
|
+
except (ValueError, UnicodeEncodeError) as exc:
|
|
146
|
+
raise DriverError(f"case {case.get('id', '?')} payload is invalid") from exc
|
|
147
|
+
if len(data) > MAX_INPUT_BYTES:
|
|
148
|
+
raise DriverError(f"case {case.get('id', '?')} exceeds the input limit")
|
|
149
|
+
return data
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _oracle(value: object, field: str) -> dict[str, object]:
|
|
153
|
+
if not isinstance(value, Mapping) or not value:
|
|
154
|
+
raise DriverError(f"{field} must be a non-empty object")
|
|
155
|
+
unknown = set(value) - set(RESPONSE_FIELDS)
|
|
156
|
+
if unknown:
|
|
157
|
+
raise DriverError(f"{field} has unsupported fields: {sorted(unknown)}")
|
|
158
|
+
normalized: dict[str, object] = {}
|
|
159
|
+
for name in RESPONSE_FIELDS:
|
|
160
|
+
if name not in value:
|
|
161
|
+
continue
|
|
162
|
+
item = value[name]
|
|
163
|
+
if name in {"crashed", "abnormal_exit"}:
|
|
164
|
+
if not isinstance(item, bool):
|
|
165
|
+
raise DriverError(f"{field}.{name} must be boolean")
|
|
166
|
+
elif name in {"status_code", "exit_code"}:
|
|
167
|
+
if isinstance(item, bool) or not isinstance(item, int):
|
|
168
|
+
raise DriverError(f"{field}.{name} must be an integer")
|
|
169
|
+
if name == "exit_code" and not -255 <= item <= 255:
|
|
170
|
+
raise DriverError(f"{field}.exit_code is outside -255..255")
|
|
171
|
+
normalized[name] = item
|
|
172
|
+
if not normalized:
|
|
173
|
+
raise DriverError(f"{field} must constrain at least one response field")
|
|
174
|
+
return normalized
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _validate_manifest(manifest: Mapping[str, Any], manifest_root: Path) -> None:
|
|
178
|
+
if manifest.get("schema_version") != SCHEMA_VERSION:
|
|
179
|
+
raise DriverError(f"manifest schema_version must be {SCHEMA_VERSION}")
|
|
180
|
+
targets = manifest.get("targets")
|
|
181
|
+
if not isinstance(targets, list) or not targets:
|
|
182
|
+
raise DriverError("manifest targets must be a non-empty array")
|
|
183
|
+
seen_cves: set[str] = set()
|
|
184
|
+
for index, target in enumerate(targets):
|
|
185
|
+
label = f"targets[{index}]"
|
|
186
|
+
if not isinstance(target, Mapping):
|
|
187
|
+
raise DriverError(f"{label} must be an object")
|
|
188
|
+
cve = _text(target.get("cve_id"), f"{label}.cve_id", limit=64).upper()
|
|
189
|
+
if not cve.startswith("CVE-") or cve in seen_cves:
|
|
190
|
+
raise DriverError(f"{label}.cve_id must be unique and start with CVE-")
|
|
191
|
+
seen_cves.add(cve)
|
|
192
|
+
for phase in ("before", "after"):
|
|
193
|
+
phase_spec = target.get(phase)
|
|
194
|
+
if not isinstance(phase_spec, Mapping):
|
|
195
|
+
raise DriverError(f"{label}.{phase} must be an object")
|
|
196
|
+
_path_without_symlink(manifest_root, phase_spec.get("root"), f"{label}.{phase}.root")
|
|
197
|
+
poc = target.get("poc")
|
|
198
|
+
if not isinstance(poc, Mapping):
|
|
199
|
+
raise DriverError(f"{label}.poc must be an object")
|
|
200
|
+
_argv(poc.get("command"), f"{label}.poc.command")
|
|
201
|
+
timeout = poc.get("timeout_seconds", 30.0)
|
|
202
|
+
if isinstance(timeout, bool) or not isinstance(timeout, (int, float)):
|
|
203
|
+
raise DriverError(f"{label}.poc.timeout_seconds must be numeric")
|
|
204
|
+
if not 0.01 <= float(timeout) <= MAX_TIMEOUT_SECONDS:
|
|
205
|
+
raise DriverError(f"{label}.poc.timeout_seconds is outside 0.01..{MAX_TIMEOUT_SECONDS}")
|
|
206
|
+
cases = target.get("cases")
|
|
207
|
+
if not isinstance(cases, list) or not cases or len(cases) > MAX_CASES_PER_TARGET:
|
|
208
|
+
raise DriverError(f"{label}.cases must contain 1..{MAX_CASES_PER_TARGET} items")
|
|
209
|
+
seen_cases: set[str] = set()
|
|
210
|
+
negative_count = 0
|
|
211
|
+
positive_count = 0
|
|
212
|
+
for case_index, case in enumerate(cases):
|
|
213
|
+
case_label = f"{label}.cases[{case_index}]"
|
|
214
|
+
if not isinstance(case, Mapping):
|
|
215
|
+
raise DriverError(f"{case_label} must be an object")
|
|
216
|
+
case_id = _text(case.get("id"), f"{case_label}.id", limit=128)
|
|
217
|
+
if case_id in seen_cases:
|
|
218
|
+
raise DriverError(f"duplicate case id: {case_id}")
|
|
219
|
+
seen_cases.add(case_id)
|
|
220
|
+
_decode_payload(case)
|
|
221
|
+
negative = case.get("negative_control", False)
|
|
222
|
+
if not isinstance(negative, bool):
|
|
223
|
+
raise DriverError(f"{case_label}.negative_control must be boolean")
|
|
224
|
+
if negative:
|
|
225
|
+
negative_count += 1
|
|
226
|
+
else:
|
|
227
|
+
positive_count += 1
|
|
228
|
+
oracle = case.get("oracle")
|
|
229
|
+
if not isinstance(oracle, Mapping):
|
|
230
|
+
raise DriverError(f"{case_label}.oracle must be an object")
|
|
231
|
+
before = _oracle(oracle.get("before"), f"{case_label}.oracle.before")
|
|
232
|
+
after = _oracle(oracle.get("after"), f"{case_label}.oracle.after")
|
|
233
|
+
if not negative and before == after:
|
|
234
|
+
raise DriverError(f"{case_label} positive oracle must describe a before/after divergence")
|
|
235
|
+
if negative and before != after:
|
|
236
|
+
raise DriverError(f"{case_label} negative-control oracle must be identical before/after")
|
|
237
|
+
if negative_count == 0:
|
|
238
|
+
raise DriverError(f"{label} must contain an explicit negative control")
|
|
239
|
+
if positive_count == 0:
|
|
240
|
+
raise DriverError(f"{label} must contain a positive PoC case")
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def _load_manifest(path: Path) -> tuple[dict[str, Any], bytes, Path]:
|
|
244
|
+
try:
|
|
245
|
+
raw = path.read_bytes()
|
|
246
|
+
manifest = json.loads(raw.decode("utf-8"))
|
|
247
|
+
except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc:
|
|
248
|
+
raise DriverError(f"cannot load manifest {path}: {exc}") from exc
|
|
249
|
+
if not isinstance(manifest, dict):
|
|
250
|
+
raise DriverError("manifest root must be an object")
|
|
251
|
+
manifest_root = path.resolve().parent
|
|
252
|
+
_validate_manifest(manifest, manifest_root)
|
|
253
|
+
return manifest, raw, manifest_root
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def _render_command(
|
|
257
|
+
template: Sequence[str],
|
|
258
|
+
*,
|
|
259
|
+
target: Path,
|
|
260
|
+
input_path: Path,
|
|
261
|
+
phase: str,
|
|
262
|
+
cve_id: str,
|
|
263
|
+
case_id: str,
|
|
264
|
+
manifest_root: Path,
|
|
265
|
+
) -> list[str]:
|
|
266
|
+
substitutions = {
|
|
267
|
+
"{target}": str(target),
|
|
268
|
+
"{input}": str(input_path),
|
|
269
|
+
"{phase}": phase,
|
|
270
|
+
"{cve}": cve_id,
|
|
271
|
+
"{case}": case_id,
|
|
272
|
+
"{manifest_root}": str(manifest_root),
|
|
273
|
+
}
|
|
274
|
+
rendered: list[str] = []
|
|
275
|
+
for item in template:
|
|
276
|
+
value = item
|
|
277
|
+
for marker, replacement in substitutions.items():
|
|
278
|
+
value = value.replace(marker, replacement)
|
|
279
|
+
rendered.append(value)
|
|
280
|
+
return _argv(rendered, "rendered PoC command")
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _stream_summary(value: object) -> dict[str, object]:
|
|
284
|
+
raw = value if isinstance(value, bytes) else str(value or "").encode("utf-8", "replace")
|
|
285
|
+
text = raw.decode("utf-8", "replace")
|
|
286
|
+
return {
|
|
287
|
+
"bytes": len(raw),
|
|
288
|
+
"sha256": _sha256(raw),
|
|
289
|
+
"text": text[:4096],
|
|
290
|
+
"truncated": len(text) > 4096,
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def _response_json(stdout: object) -> tuple[dict[str, Any] | None, str | None]:
|
|
295
|
+
text = stdout if isinstance(stdout, str) else str(stdout or "")
|
|
296
|
+
lines = [line.strip() for line in text.splitlines() if line.strip()]
|
|
297
|
+
if not lines:
|
|
298
|
+
return None, "PoC executor emitted no JSON response"
|
|
299
|
+
try:
|
|
300
|
+
value = json.loads(lines[-1])
|
|
301
|
+
except json.JSONDecodeError as exc:
|
|
302
|
+
return None, f"PoC final stdout line is not JSON: {exc.msg}"
|
|
303
|
+
if not isinstance(value, dict):
|
|
304
|
+
return None, "PoC JSON response must be an object"
|
|
305
|
+
if "status_code" in value:
|
|
306
|
+
status_code = value["status_code"]
|
|
307
|
+
if isinstance(status_code, bool) or not isinstance(status_code, int):
|
|
308
|
+
return None, "PoC status_code must be an integer"
|
|
309
|
+
if "crashed" in value and not isinstance(value["crashed"], bool):
|
|
310
|
+
return None, "PoC crashed must be boolean"
|
|
311
|
+
return value, None
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def _run_phase(
|
|
315
|
+
*,
|
|
316
|
+
source_target: Path,
|
|
317
|
+
phase: str,
|
|
318
|
+
case: Mapping[str, Any],
|
|
319
|
+
poc: Mapping[str, Any],
|
|
320
|
+
cve_id: str,
|
|
321
|
+
manifest_root: Path,
|
|
322
|
+
sandbox_root: Path,
|
|
323
|
+
) -> dict[str, object]:
|
|
324
|
+
timeout = float(poc.get("timeout_seconds", 30.0))
|
|
325
|
+
run_root: Path | None = None
|
|
326
|
+
record: dict[str, object]
|
|
327
|
+
try:
|
|
328
|
+
with tempfile.TemporaryDirectory(
|
|
329
|
+
prefix=f"{cve_id.lower()}-{phase}-",
|
|
330
|
+
dir=str(sandbox_root),
|
|
331
|
+
) as temporary:
|
|
332
|
+
run_root = Path(temporary)
|
|
333
|
+
copied_target = run_root / "target"
|
|
334
|
+
_reject_tree_symlinks(source_target)
|
|
335
|
+
shutil.copytree(source_target, copied_target, symlinks=False)
|
|
336
|
+
input_path = run_root / "input.bin"
|
|
337
|
+
input_path.write_bytes(_decode_payload(case))
|
|
338
|
+
command = _render_command(
|
|
339
|
+
poc["command"],
|
|
340
|
+
target=copied_target,
|
|
341
|
+
input_path=input_path,
|
|
342
|
+
phase=phase,
|
|
343
|
+
cve_id=cve_id,
|
|
344
|
+
case_id=str(case["id"]),
|
|
345
|
+
manifest_root=manifest_root,
|
|
346
|
+
)
|
|
347
|
+
result = run_bounded(
|
|
348
|
+
command,
|
|
349
|
+
cwd=run_root,
|
|
350
|
+
timeout=timeout,
|
|
351
|
+
max_total_timeout=timeout,
|
|
352
|
+
max_output_bytes=MAX_OUTPUT_BYTES,
|
|
353
|
+
)
|
|
354
|
+
response, protocol_error = _response_json(result.stdout)
|
|
355
|
+
returncode = int(result.returncode)
|
|
356
|
+
timed_out = bool(getattr(result, "timed_out", False))
|
|
357
|
+
output_exceeded = bool(getattr(result, "output_exceeded", False))
|
|
358
|
+
crashed = returncode < 0 or bool(response and response.get("crashed", False))
|
|
359
|
+
abnormal_exit = timed_out or output_exceeded or returncode != 0
|
|
360
|
+
if timed_out:
|
|
361
|
+
execution_status = "TIMEOUT"
|
|
362
|
+
elif output_exceeded:
|
|
363
|
+
execution_status = "OUTPUT_LIMIT"
|
|
364
|
+
elif returncode != 0:
|
|
365
|
+
execution_status = "ABNORMAL_EXIT"
|
|
366
|
+
else:
|
|
367
|
+
execution_status = "OK"
|
|
368
|
+
stderr_summary = _stream_summary(result.stderr)
|
|
369
|
+
record = {
|
|
370
|
+
"phase": phase,
|
|
371
|
+
"status": execution_status,
|
|
372
|
+
"exit_code": returncode,
|
|
373
|
+
"abnormal_exit": abnormal_exit,
|
|
374
|
+
"crashed": crashed,
|
|
375
|
+
"crash_signature": (
|
|
376
|
+
_sha256(
|
|
377
|
+
(str(stderr_summary["sha256"]) + f"|{returncode}").encode("ascii")
|
|
378
|
+
)
|
|
379
|
+
if crashed
|
|
380
|
+
else None
|
|
381
|
+
),
|
|
382
|
+
"status_code": None if response is None else response.get("status_code"),
|
|
383
|
+
"stdout": _stream_summary(result.stdout),
|
|
384
|
+
"stderr": stderr_summary,
|
|
385
|
+
"command": command,
|
|
386
|
+
"protocol_error": protocol_error,
|
|
387
|
+
}
|
|
388
|
+
except (OSError, WorkerExecutionError, DriverError) as exc:
|
|
389
|
+
record = {
|
|
390
|
+
"phase": phase,
|
|
391
|
+
"status": "INFRA_ERROR",
|
|
392
|
+
"exit_code": None,
|
|
393
|
+
"abnormal_exit": False,
|
|
394
|
+
"crashed": False,
|
|
395
|
+
"crash_signature": None,
|
|
396
|
+
"status_code": None,
|
|
397
|
+
"stdout": _stream_summary(""),
|
|
398
|
+
"stderr": _stream_summary(str(exc)),
|
|
399
|
+
"command": None,
|
|
400
|
+
"protocol_error": str(exc),
|
|
401
|
+
}
|
|
402
|
+
record["sandbox_cleaned"] = run_root is None or not run_root.exists()
|
|
403
|
+
return record
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
def _matches(observation: Mapping[str, object], expected: Mapping[str, object]) -> bool:
|
|
407
|
+
return all(observation.get(field) == value for field, value in expected.items())
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def _divergence(before: Mapping[str, object], after: Mapping[str, object]) -> dict[str, object]:
|
|
411
|
+
changed: dict[str, dict[str, object]] = {}
|
|
412
|
+
for field in RESPONSE_FIELDS:
|
|
413
|
+
if before.get(field) != after.get(field):
|
|
414
|
+
changed[field] = {"before": before.get(field), "after": after.get(field)}
|
|
415
|
+
return {"is_divergent": bool(changed), "fields": changed}
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
def _evaluate_case(case: Mapping[str, Any], before: Mapping[str, object], after: Mapping[str, object]) -> dict[str, object]:
|
|
419
|
+
if before.get("status") == "INFRA_ERROR" or after.get("status") == "INFRA_ERROR":
|
|
420
|
+
outcome = "BLOCKED"
|
|
421
|
+
is_finding = False
|
|
422
|
+
else:
|
|
423
|
+
oracle = case["oracle"]
|
|
424
|
+
expected_before = _oracle(oracle["before"], "case.oracle.before")
|
|
425
|
+
expected_after = _oracle(oracle["after"], "case.oracle.after")
|
|
426
|
+
before_matches = _matches(before, expected_before)
|
|
427
|
+
after_matches = _matches(after, expected_after)
|
|
428
|
+
divergence = _divergence(before, after)
|
|
429
|
+
if case.get("negative_control", False):
|
|
430
|
+
passed = before_matches and after_matches and not bool(divergence["is_divergent"])
|
|
431
|
+
outcome = "SUPPRESSED" if passed else "FALSE_POSITIVE"
|
|
432
|
+
is_finding = not passed
|
|
433
|
+
else:
|
|
434
|
+
passed = before_matches and after_matches and bool(divergence["is_divergent"])
|
|
435
|
+
outcome = "CONFIRMED" if passed else "NOT_REPRODUCED"
|
|
436
|
+
is_finding = passed
|
|
437
|
+
result: dict[str, object] = {
|
|
438
|
+
"id": case["id"],
|
|
439
|
+
"negative_control": bool(case.get("negative_control", False)),
|
|
440
|
+
"outcome": outcome,
|
|
441
|
+
"is_finding": is_finding,
|
|
442
|
+
"before": dict(before),
|
|
443
|
+
"after": dict(after),
|
|
444
|
+
}
|
|
445
|
+
if outcome not in {"BLOCKED"}:
|
|
446
|
+
result["divergence"] = _divergence(before, after)
|
|
447
|
+
oracle = case["oracle"]
|
|
448
|
+
result["before_matches"] = _matches(before, _oracle(oracle["before"], "case.oracle.before"))
|
|
449
|
+
result["after_matches"] = _matches(after, _oracle(oracle["after"], "case.oracle.after"))
|
|
450
|
+
return result
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def _prepare_sandbox_root(value: Path | None) -> tuple[Path, bool]:
|
|
454
|
+
if value is None:
|
|
455
|
+
root = Path(tempfile.mkdtemp(prefix="bugx-cve-verify-"))
|
|
456
|
+
os.chmod(root, 0o700)
|
|
457
|
+
return root, True
|
|
458
|
+
root = value.expanduser()
|
|
459
|
+
if root.exists() and root.is_symlink():
|
|
460
|
+
raise DriverError("sandbox root cannot be a symlink")
|
|
461
|
+
root.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
462
|
+
if not root.is_dir():
|
|
463
|
+
raise DriverError("sandbox root must be a directory")
|
|
464
|
+
os.chmod(root, 0o700)
|
|
465
|
+
return root.resolve(), False
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
def _write_report(path: Path, report: Mapping[str, object]) -> None:
|
|
469
|
+
path = path.expanduser()
|
|
470
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
471
|
+
descriptor, temporary = tempfile.mkstemp(prefix=f".{path.name}.", dir=str(path.parent))
|
|
472
|
+
try:
|
|
473
|
+
os.fchmod(descriptor, 0o600)
|
|
474
|
+
with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
|
|
475
|
+
json.dump(report, handle, ensure_ascii=False, indent=2, sort_keys=True)
|
|
476
|
+
handle.write("\n")
|
|
477
|
+
handle.flush()
|
|
478
|
+
os.fsync(handle.fileno())
|
|
479
|
+
os.replace(temporary, path)
|
|
480
|
+
except BaseException:
|
|
481
|
+
try:
|
|
482
|
+
os.close(descriptor)
|
|
483
|
+
except OSError:
|
|
484
|
+
pass
|
|
485
|
+
try:
|
|
486
|
+
os.unlink(temporary)
|
|
487
|
+
except OSError:
|
|
488
|
+
pass
|
|
489
|
+
raise
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
def run_manifest(
|
|
493
|
+
manifest_path: Path,
|
|
494
|
+
out_path: Path,
|
|
495
|
+
*,
|
|
496
|
+
sandbox_root: Path | None = None,
|
|
497
|
+
) -> dict[str, object]:
|
|
498
|
+
"""Execute all manifest targets and persist one deterministic report."""
|
|
499
|
+
manifest_path = manifest_path.expanduser().resolve()
|
|
500
|
+
manifest, manifest_bytes, manifest_root = _load_manifest(manifest_path)
|
|
501
|
+
sandbox, owned_sandbox = _prepare_sandbox_root(sandbox_root)
|
|
502
|
+
report: dict[str, object] = {
|
|
503
|
+
"schema_version": SCHEMA_VERSION,
|
|
504
|
+
"status": "RUNNING",
|
|
505
|
+
"manifest": str(manifest_path),
|
|
506
|
+
"manifest_sha256": _sha256(manifest_bytes),
|
|
507
|
+
"sandbox_root": str(sandbox),
|
|
508
|
+
"sandbox_policy": "fresh private copy per CVE/case/phase; source symlinks rejected",
|
|
509
|
+
"targets": [],
|
|
510
|
+
"negative_controls": {"total": 0, "suppressed": 0, "false_positives": 0},
|
|
511
|
+
"evidence_boundary": "local manifest/process evidence only; no ACP, host, or external-runtime claim",
|
|
512
|
+
}
|
|
513
|
+
try:
|
|
514
|
+
for target in manifest["targets"]:
|
|
515
|
+
cve_id = str(target["cve_id"]).upper()
|
|
516
|
+
target_record: dict[str, object] = {"cve_id": cve_id, "cases": []}
|
|
517
|
+
before_root = _path_without_symlink(manifest_root, target["before"]["root"], f"{cve_id}.before.root")
|
|
518
|
+
after_root = _path_without_symlink(manifest_root, target["after"]["root"], f"{cve_id}.after.root")
|
|
519
|
+
for case in target["cases"]:
|
|
520
|
+
before = _run_phase(
|
|
521
|
+
source_target=before_root,
|
|
522
|
+
phase="before",
|
|
523
|
+
case=case,
|
|
524
|
+
poc=target["poc"],
|
|
525
|
+
cve_id=cve_id,
|
|
526
|
+
manifest_root=manifest_root,
|
|
527
|
+
sandbox_root=sandbox,
|
|
528
|
+
)
|
|
529
|
+
after = _run_phase(
|
|
530
|
+
source_target=after_root,
|
|
531
|
+
phase="after",
|
|
532
|
+
case=case,
|
|
533
|
+
poc=target["poc"],
|
|
534
|
+
cve_id=cve_id,
|
|
535
|
+
manifest_root=manifest_root,
|
|
536
|
+
sandbox_root=sandbox,
|
|
537
|
+
)
|
|
538
|
+
case_record = _evaluate_case(case, before, after)
|
|
539
|
+
target_record["cases"].append(case_record)
|
|
540
|
+
controls = report["negative_controls"]
|
|
541
|
+
if case.get("negative_control", False):
|
|
542
|
+
controls["total"] += 1
|
|
543
|
+
if case_record["outcome"] == "SUPPRESSED":
|
|
544
|
+
controls["suppressed"] += 1
|
|
545
|
+
elif case_record["outcome"] == "FALSE_POSITIVE":
|
|
546
|
+
controls["false_positives"] += 1
|
|
547
|
+
outcomes = [item["outcome"] for item in target_record["cases"]]
|
|
548
|
+
if "BLOCKED" in outcomes:
|
|
549
|
+
target_record["status"] = "BLOCKED"
|
|
550
|
+
elif "FALSE_POSITIVE" in outcomes:
|
|
551
|
+
target_record["status"] = "FALSE_POSITIVE"
|
|
552
|
+
elif any(outcome != "CONFIRMED" and outcome != "SUPPRESSED" for outcome in outcomes):
|
|
553
|
+
target_record["status"] = "NOT_REPRODUCED"
|
|
554
|
+
else:
|
|
555
|
+
target_record["status"] = "PASS"
|
|
556
|
+
report["targets"].append(target_record)
|
|
557
|
+
finally:
|
|
558
|
+
if owned_sandbox:
|
|
559
|
+
shutil.rmtree(sandbox, ignore_errors=True)
|
|
560
|
+
|
|
561
|
+
target_statuses = [target["status"] for target in report["targets"]]
|
|
562
|
+
if "BLOCKED" in target_statuses:
|
|
563
|
+
report["status"] = "BLOCKED"
|
|
564
|
+
elif "FALSE_POSITIVE" in target_statuses:
|
|
565
|
+
report["status"] = "FALSE_POSITIVE"
|
|
566
|
+
elif any(status != "PASS" for status in target_statuses):
|
|
567
|
+
report["status"] = "NOT_REPRODUCED"
|
|
568
|
+
else:
|
|
569
|
+
report["status"] = "PASS"
|
|
570
|
+
report["report_sha256"] = _sha256(_canonical(report))
|
|
571
|
+
_write_report(out_path, report)
|
|
572
|
+
return report
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
def _parser() -> argparse.ArgumentParser:
|
|
576
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
577
|
+
parser.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST)
|
|
578
|
+
parser.add_argument("--out", type=Path, default=DEFAULT_OUT)
|
|
579
|
+
parser.add_argument("--sandbox-root", type=Path, default=None)
|
|
580
|
+
parser.add_argument("--json", action="store_true", help="print the complete report as JSON")
|
|
581
|
+
return parser
|
|
582
|
+
|
|
583
|
+
|
|
584
|
+
def main(argv: list[str] | None = None) -> int:
|
|
585
|
+
args = _parser().parse_args(argv)
|
|
586
|
+
try:
|
|
587
|
+
report = run_manifest(args.manifest, args.out, sandbox_root=args.sandbox_root)
|
|
588
|
+
except (DriverError, OSError) as exc:
|
|
589
|
+
print(f"[oss-cve-exploit-verify] BLOCKED: {exc}", file=sys.stderr)
|
|
590
|
+
return 2
|
|
591
|
+
if args.json:
|
|
592
|
+
print(json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True))
|
|
593
|
+
else:
|
|
594
|
+
controls = report["negative_controls"]
|
|
595
|
+
print(
|
|
596
|
+
f"[oss-cve-exploit-verify] {report['status']}: "
|
|
597
|
+
f"targets={len(report['targets'])} "
|
|
598
|
+
f"negative_controls={controls['suppressed']}/{controls['total']}"
|
|
599
|
+
)
|
|
600
|
+
print(f"[oss-cve-exploit-verify] report: {args.out}")
|
|
601
|
+
return 0 if report["status"] == "PASS" else 2
|
|
602
|
+
|
|
603
|
+
|
|
604
|
+
__all__ = ["DriverError", "SCHEMA_VERSION", "main", "run_manifest"]
|
|
605
|
+
|
|
606
|
+
|
|
607
|
+
if __name__ == "__main__":
|
|
608
|
+
raise SystemExit(main())
|