diff --git a/.github/workflows/_build.yml b/.github/workflows/_build.yml index 60e980ce4c..30d36f82d2 100644 --- a/.github/workflows/_build.yml +++ b/.github/workflows/_build.yml @@ -301,8 +301,11 @@ jobs: # One blocking join owns the security-sensitive transition from candidates # to public artifacts. Each target tuple contributes exactly three behavior- # equivalent candidates (unstripped/debug-stripped/stripped); the selector may - # only choose within that tuple. A hard result on ANY sibling blocks - # the all-target release rather than selecting around a real detection. + # only choose within that tuple. A hard result on ANY sibling blocks the + # all-target release rather than selecting around a real detection - with + # ONE exception (policy cbm-vt-candidate-selection-v2, SECURITY.md): a single + # "isolated" candidate, flagged by one non-Microsoft engine that judged every + # sibling form clean on the same definitions, is never shipped and disclosed. select-package: needs: [build-unix, build-windows, build-windows-arm64, build-linux-portable] runs-on: ubuntu-latest @@ -345,8 +348,9 @@ jobs: request_rate: 4 # The established gate tolerates only one Microsoft malicious label - # ending !ml and rejects every other malicious/suspicious combination. - # Every candidate still must complete with the minimum engine coverage. + # ending !ml and rejects every other malicious/suspicious combination, + # except the one isolated-sibling candidate this stage alone opts into + # (VT_ISOLATED_SIBLING_CANDIDATES; the archive surface scan stays strict). - name: Wait for complete VirusTotal candidate results if: ${{ inputs.scan_candidates }} env: @@ -355,6 +359,7 @@ jobs: VT_EXPECTED_SCAN_SET: release-candidate-scan/scan-set.tsv VT_ASSOCIATIONS: release-candidate-scan/associations.tsv VT_RESULTS_PATH: release-candidate-scan/vt-results.tsv + VT_ISOLATED_SIBLING_CANDIDATES: release-candidate-scan/candidates.tsv VT_POLL_TIMEOUT_SECONDS: 14400 MIN_ENGINES: 50 run: scripts/ci/check-virustotal.sh diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 51b7feebe5..275fcd722b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -504,7 +504,7 @@ jobs: gh release download "$VERSION" --repo "$GITHUB_REPOSITORY" --pattern 'release-selection.tsv' --output "$RUNNER_TEMP/release-selection.tsv" python3 scripts/ci/verify-release-selection.py \ --selection "$RUNNER_TEMP/release-selection.tsv" \ - --require-policy virustotal-v2 \ + --require-policy virustotal-v3 \ --archive-dir "$ARCHIVE_DIR" # 14 = 8 archives + 6 MCPB bundles; runtime 42 = 8×3 archive # sidecars + 6×3 bundle members (manifest.json, LICENSE, notices). diff --git a/SECURITY.md b/SECURITY.md index 88d931bf5b..ab261aa9d9 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -126,7 +126,7 @@ Releases are created as **drafts** (invisible to users) and only published after 2. **Sigstore cosign signing** — keyless digital signatures verifiable by anyone 3. **SBOM** — Software Bill of Materials (SPDX) listing all vendored dependencies 4. **SHA-256 checksums** — published with every release -5. **VirusTotal scanning** — three behaviourally identical executable candidates — unstripped, debug-stripped and stripped — are derived from one linker output for every release product and scanned before smoke/soak. Zero malicious and zero suspicious is preferred; the only tolerated result is exactly one Microsoft malicious label ending in `!ml`, which is disclosed. The selected executable is packaged without changing its SHA-256. After packaging, every distinct object extracted from the 14 shipped containers is scanned under the same policy — `install.sh`, `install.ps1`, `LICENSE`, `THIRD_PARTY_NOTICES.md`, the MCPB `manifest.json` and the unpacked UI assets — so the covered surface is everything we publish, not only the executables. Release notes link the verdict for the exact bytes shipped; the per-candidate results and the selection table are published as release assets for independent audit. +5. **VirusTotal scanning** — three behaviourally identical executable candidates — unstripped, debug-stripped and stripped — are derived from one linker output for every release product and scanned before smoke/soak. Zero malicious and zero suspicious is preferred; the only tolerated results are exactly one Microsoft malicious label ending in `!ml`, which is disclosed, and one "isolated" candidate per release (one other engine that judged every sibling form clean on the same definitions), which is never shipped and is named in the release notes. The selected executable is packaged without changing its SHA-256. After packaging, every distinct object extracted from the 14 shipped containers is scanned under the same policy — `install.sh`, `install.ps1`, `LICENSE`, `THIRD_PARTY_NOTICES.md`, the MCPB `manifest.json` and the unpacked UI assets — so the covered surface is everything we publish, not only the executables. Release notes link the verdict for the exact bytes shipped; the per-candidate results and the selection table are published as release assets for independent audit. 6. **OpenSSF Scorecard** — repository security health score 7. **Registry publishing without stored tokens** — npm and PyPI accept uploads only through OIDC trusted publishing from `release.yml` running in one of two GitHub environments, both restricted to `main`: `release`, which requires the maintainer's approval and publishes stable versions, and `rc`, which publishes release candidates (`vX.Y.Z-rc.N`) unattended to npm's `next` tag and as PyPI pre-releases. The environment follows the version's shape, checked three times before upload; no long-lived npm or PyPI token exists. The packages are built in a separate job that holds no publishing identity, from a toolchain (build backend included) installed by hash; the publishing job only uploads them. Release candidates pass every gate above, identically. A gate (VirusTotal, security, license, CodeQL, lint) is never retried, and a release that went green only on an automatic retry of a flaky test says so in its release notes. @@ -138,10 +138,11 @@ not mean the source code is vulnerability-free or that maintainers cannot change source. Consumers should verify the signer workflow, not only repository ownership. -If a scanned executable candidate has any result outside the one narrowly reviewed -Microsoft `!ml` tolerance, the release stays as a draft and is not published. -There is no manual bypass around that release gate; its sole machine-enforced -tolerance and selection table are specified in [Our release policy](#our-release-policy). +If a scanned executable candidate has any result outside the two narrowly reviewed +rules (the Microsoft `!ml` tolerance and the isolated-sibling rule), the release +stays as a draft and is not published. There is no manual bypass around that +release gate; its machine-enforced rules and selection order are specified in +[Our release policy](#our-release-policy). ### Code-Level Defenses @@ -257,44 +258,63 @@ Every release ships the material needed to check our artifacts independently. Use the commands in [Verification](#verification) above: SLSA Build Level 3 provenance ties the archive to the workflow run that produced it, Sigstore cosign verifies the signature, and `checksums.txt` pins the bytes. The release notes -carry a durable VirusTotal link for every executable candidate, including any -tolerated detection — we publish those results whether or not they are clean. +link the VirusTotal report for every shipped executable, including any tolerated +detection, and name any isolated candidate that was not shipped; the verdicts of +every candidate are published as release assets, whether or not they are clean. You can also rebuild from source and compare: `scripts/build.sh --with-ui` produces the shipped composition. ### Our release policy -A release may ship with **at most one** detection, and only when the engine is -Microsoft and the label ends in `!ml`. Two or more engines, any signature-based -label, any other vendor, or any "suspicious" verdict blocks the release. That -rule is enforced in `scripts/ci/check-virustotal.sh` and pinned by -`tests/test_vt_gate_policy_contract.sh`. - Before smoke and soak testing, each of the eight supported platform/link-mode -products is built in two conventional forms from the same linked executable: -stripped and unstripped. Both candidates are scanned, and selection is confined -to that product tuple; for example, a portable static Linux build can never be -substituted for the ordinary dynamically linked Linux build. - -The selection policy is deterministic: - -| Stripped candidate | Unstripped candidate | Selected candidate | -|---|---|---| -| Clean | Clean | Stripped | -| Clean | One tolerated Microsoft `!ml` | Stripped | -| One tolerated Microsoft `!ml` | Clean | Unstripped | -| One tolerated Microsoft `!ml` | One tolerated Microsoft `!ml` | Stripped | - -Any other verdict, an incomplete scan, a missing sibling, or a provenance/hash -mismatch blocks the complete release. The selected bytes are then packaged +products is built in three conventional forms from the same linked executable: +stripped, debug-stripped and unstripped. All forms are hashed and submitted to +VirusTotal once, before any result is known; nothing is rebuilt, re-stripped or +re-submitted in response to a verdict. Selection is confined to that product: +for example, a portable static Linux build can never be substituted for the +ordinary dynamically linked Linux build. + +Each candidate is classified as: + +- **clean**: no detection; +- **microsoft-ml**: exactly one detection, by Microsoft, with a label ending in `!ml`; +- **isolated**: exactly one detection, by one engine other than Microsoft, as + malicious, while every sibling form of the same product is clean and the same + engine, on the same engine version and definitions, returned a non-detection + for each of them; +- **blocking**: anything else, including two or more engines, a signature-based + Microsoft label, any "suspicious" verdict, a single-engine detection whose + engine did not answer for every sibling or answered on other definitions, and + a detection beside a sibling that is not clean. + +One blocking candidate, or more than one isolated candidate, blocks the complete +release, and so do an incomplete scan, a missing sibling and a provenance/hash +mismatch. An isolated candidate is never shipped. Among the rest, the first +clean form in the order stripped, debug-stripped, unstripped is shipped; only if +every form is microsoft-ml is the stripped form shipped, with that verdict +disclosed. + +The forms contain identical code, and two of them identical symbols, so a +detection that the same engine does not repeat on any sibling form describes +that file image, not the program. We do not ship that image, and the release +notes name it with its SHA-256, engine, label and definitions date. The scan of +everything extracted from the shipped containers after packaging has no +isolated class: there, every detection other than the single Microsoft `!ml` +blocks. + +These rules are enforced in `scripts/ci/check-virustotal.sh` and +`scripts/ci/select-release-candidates.py`, re-derived independently by +`scripts/ci/verify-release-selection.py`, and pinned by +`tests/test_vt_gate_policy_contract.sh` and +`tests/test_vt_candidate_selection_contract.sh`. The selected bytes are then packaged without stripping, signing, relinking, or any other content mutation, and the resulting archives—not rejected candidates—are what smoke and soak testing execute. After packaging, every archive and MCPB executable is extracted and its SHA-256 must still equal the selected candidate. This identity check makes a second VirusTotal submission of the same bytes unnecessary. -This is not obfuscation: stripping is a standard release transformation, both +This is not obfuscation: stripping is a standard release transformation, all forms and their SHA-256 provenance are recorded, and no binary is modified in response to an engine result. If the unstripped form is selected, it is larger and can expose compiler symbol names and build-time path metadata (but not source @@ -306,8 +326,8 @@ outputs of one linker result, and the actually selected form—not its sibling subjected to the full smoke/soak gate. That trade-off is visible in the published selection evidence. -Policy identifier: `cbm-vt-candidate-selection-v1`. It is reviewed at least -every 90 days; last review: 2026-08-13, next review due: 2026-11-11. +Policy identifier: `cbm-vt-candidate-selection-v2`. It is reviewed at least +every 90 days; last review: 2026-12-06, next review due: 2027-03-06. ### If you find something real diff --git a/scripts/ci/README.md b/scripts/ci/README.md index f38cf36a8e..e5597ff834 100644 --- a/scripts/ci/README.md +++ b/scripts/ci/README.md @@ -19,6 +19,6 @@ CI and the local infrastructure — both of which the venue-parity contract | `verify-shard-union.sh` | Prove sharded test legs lost nothing: shard count agreement, indices 1..n, identical suite lists, union of slices == full list (was inline YAML). No manifests is green only when the lane selection holds no test leg. | `_test.yml` shard-completeness | | `prepare-release-candidates.sh` | Copy one linker output into stripped/unstripped candidates, finalize signatures, composition-check them without execution, and record their hashes. | `_build.yml`, local artifact smoke | | `stage-release-candidates.py` | Admit exactly eight candidate artifacts / sixteen byte-distinct binaries into the content-addressed VirusTotal scan set. | `_build.yml` | -| `select-release-candidates.py` | Apply the reviewed tuple-local VT truth table, or the explicit dry-run stripped default, and atomically copy one content-bound binary per target. | `_build.yml` | +| `select-release-candidates.py` | Apply the reviewed tuple-local selection order (policy `cbm-vt-candidate-selection-v2`: first clean form, never the release's one isolated candidate, whose sibling proof it re-checks), or the explicit dry-run stripped default, and atomically copy one content-bound binary per target. | `_build.yml` | | `verify-release-selection.py` | Recompute the selection policy and prove every executable member in all 14 public containers equals its selected SHA-256. | `_build.yml`, `release.yml` final draft verification | -| `check-virustotal.sh` | Poll and validate the exact candidate scan set, enforce engine coverage and the narrow documented Microsoft `!ml` policy, and emit content-bound results evidence. | `_build.yml` | +| `check-virustotal.sh` | Poll and validate the exact scan set, record engine coverage (never gated), apply policy `cbm-vt-candidate-selection-v2` (the narrow Microsoft `!ml` tolerance and, at the candidate stage only, the isolated-sibling rule), and emit content-bound results evidence naming every detecting engine. | `_build.yml`, `release.yml` surface scan | diff --git a/scripts/ci/append-vt-notes.sh b/scripts/ci/append-vt-notes.sh index db4b50c0d0..7c2cdc4a64 100755 --- a/scripts/ci/append-vt-notes.sh +++ b/scripts/ci/append-vt-notes.sh @@ -50,6 +50,7 @@ RESULT_FIELDS = ( "total_engines", "malicious", "suspicious", "analysis_id", "microsoft_category", "microsoft_result", "policy_classification", "microsoft_engine_version", "microsoft_engine_update", "virustotal_url", + "detections", "isolated_evidence", ) SELECTION_FIELDS = ( "target", "selected_variant", "selected_path", "selected_sha256", @@ -109,7 +110,7 @@ candidate_meta, candidates = read_tsv( candidates_path, "cbm-release-candidates-v1", CANDIDATE_FIELDS ) result_meta, results = read_tsv( - results_path, "cbm-virustotal-results-v2", RESULT_FIELDS + results_path, "cbm-virustotal-results-v3", RESULT_FIELDS ) selection_meta, selections = read_tsv( selection_path, "cbm-release-selection-v1", SELECTION_FIELDS @@ -122,7 +123,7 @@ if [(row["target"], row["variant"]) for row in candidates] != expected_pairs: expected_scans = str(len(TARGETS) * len(VARIANTS)) if result_meta.get("scan_objects") != expected_scans or result_meta.get("associations") != expected_scans: fail("VirusTotal results do not cover every candidate") -if selection_meta != {"policy": "virustotal-v2", "targets": str(len(TARGETS)), "candidates": str(len(TARGETS) * len(VARIANTS))}: +if selection_meta != {"policy": "virustotal-v3", "targets": str(len(TARGETS)), "candidates": str(len(TARGETS) * len(VARIANTS))}: fail("selection was not produced by the scanned release policy") if [row["target"] for row in selections] != list(TARGETS): fail("selection rows are not the canonical target matrix") @@ -152,8 +153,11 @@ for result in results: fail(f"VirusTotal result is not bound to candidate bytes: {result['scan_path']}") completed = int(result["completed_engines"]) total = int(result["total_engines"]) - if completed < 50 or total < completed: - fail(f"incomplete VirusTotal result: {result['scan_path']}") + # As in the gate and the selector: `total < completed` is an incoherent + # response, but how many engines answered is VirusTotal fleet availability, + # not a verdict, so a low count is reported and never fails the release. + if total < completed: + fail(f"VirusTotal result has incoherent engine coverage: {result['scan_path']}") classification = result["policy_classification"] clean = ( classification == "clean" @@ -169,13 +173,30 @@ for result in results: and result["microsoft_category"] == "malicious" and result["microsoft_result"].endswith("!ml") ) - if not clean and not microsoft_ml: + detection_entries = [entry.split("|") for entry in result["detections"].split(";") if entry] + isolated = ( + classification == "isolated" + and result["malicious"] == "1" + and result["suspicious"] == "0" + and result["microsoft_category"] in {"undetected", "harmless"} + and len(detection_entries) == 1 + and len(detection_entries[0]) == 5 + and detection_entries[0][0] != "Microsoft" + and detection_entries[0][1] == "malicious" + and bool(result["isolated_evidence"]) + ) + if not clean and not microsoft_ml and not isolated: fail(f"blocked VirusTotal result reached release notes: {result['scan_path']}") if not result["analysis_id"] or not result["microsoft_engine_version"] or not result["microsoft_engine_update"]: fail(f"incomplete VirusTotal evidence: {result['scan_path']}") results_by_path[result["scan_path"]] = result if set(results_by_path) != set(candidate_by_path): fail("VirusTotal results are missing candidates") +isolated_paths = [ + path for path, result in results_by_path.items() if result["policy_classification"] == "isolated" +] +if len(isolated_paths) > 1: + fail(f"more than one isolated candidate reached release notes: {sorted(isolated_paths)}") selection_by_target: dict[str, dict[str, str]] = {} for selection in selections: @@ -187,6 +208,8 @@ for selection in selections: clean = [v for v in order if classes[v] == "clean"] expected_variant = clean[0] if clean else "stripped" selected = pair[expected_variant] + if classes[expected_variant] == "isolated": + fail(f"an isolated candidate would be shipped: {target}") if ( selection["selected_variant"] != expected_variant or selection["selected_sha256"] != selected["sha256"] @@ -211,14 +234,16 @@ asset_base = ( ) -# Release notes report the SHIPPED binary and nothing else. +# Release notes report the SHIPPED binary, plus the one exception the policy +# requires: an "isolated" candidate (policy cbm-vt-candidate-selection-v2). # # Several candidates per product are scanned so the selector has an alternative # when an opaque classifier flags one of them, but a reader installing cbm cares # about the bytes they receive, not about the ones we discarded. The rejected # candidates' verdicts stay in the published evidence TSVs for anyone auditing # the selection, and they matter to US in development as a signal; they are -# noise in a changelog. +# noise in a changelog. An isolated candidate is different: it is a hard +# detection that did NOT block the release, so the notes name it. def shipped_result(target: str) -> dict: selection = selection_by_target[target] variant = selection["selected_variant"] @@ -258,6 +283,24 @@ for target in TARGETS: section.append( f"| `{target}` | `{selection['selected_sha256']}` | {verdict_cell(target)} |" ) +for path in isolated_paths: + result = results_by_path[path] + candidate = candidate_by_path[path] + engine, _category, label, engine_version, definitions = result["detections"].split("|") + section.extend( + [ + "", + ( + f"**Not shipped, disclosed:** the `{candidate['target']}` " + f"{candidate['variant']} candidate (`{result['sha256']}`) was flagged by a " + f"single engine, {engine} (`{label}`, engine {engine_version}, definitions " + f"{definitions}). The same engine, on the same definitions, judged every " + f"other form of that product clean, so under policy " + f"`cbm-vt-candidate-selection-v2` that file image was not shipped and did not " + f"block the release. [VirusTotal]({result['virustotal_url']})" + ), + ] + ) section.extend( [ "", diff --git a/scripts/ci/check-virustotal.sh b/scripts/ci/check-virustotal.sh index 9bee287bd9..691e675595 100755 --- a/scripts/ci/check-virustotal.sh +++ b/scripts/ci/check-virustotal.sh @@ -3,10 +3,14 @@ # content-bound scan set produced by extract-release-archives.sh. # # Required: VT_API_KEY, VT_ANALYSIS, VT_EXPECTED_SCAN_SET, VT_ASSOCIATIONS -# Workflow policy: MIN_ENGINES=50, clean or exactly one disclosed Microsoft -# machine-learning (`!ml`) verdict; every other detection blocks. +# Workflow policy (cbm-vt-candidate-selection-v2): MIN_ENGINES=50 is reported, +# never gated; clean or exactly one disclosed Microsoft machine-learning (`!ml`) +# verdict; at the candidate stage only, at most one "isolated" candidate (one +# non-Microsoft engine that judged every sibling form clean on the same +# definitions; never shipped); every other detection blocks. # Optional: VT_RESULTS_PATH, VT_REQUEST_INTERVAL_SECONDS, -# VT_POLL_TIMEOUT_SECONDS, VT_CURL_TIMEOUT_SECONDS. +# VT_POLL_TIMEOUT_SECONDS, VT_CURL_TIMEOUT_SECONDS, +# VT_ISOLATED_SIBLING_CANDIDATES (candidate manifest; candidate stage only). set -euo pipefail command -v python3 >/dev/null 2>&1 || { @@ -81,7 +85,30 @@ RESULT_FIELDS = ( "microsoft_engine_version", "microsoft_engine_update", "virustotal_url", + "detections", + "isolated_evidence", ) +# The candidate manifest stage-release-candidates.py writes. Read only when the +# candidate stage opts into the isolated-sibling class (VT_ISOLATED_SIBLING_CANDIDATES). +CANDIDATE_FIELDS = ( + "target", + "variant", + "relative_path", + "source_sha256", + "pre_sign_sha256", + "sha256", + "size", + "format", + "architecture", + "linkage", + "transform", + "signature", + "strip_tool", + "strip_version", + "pair_verification", + "scan_path", +) +NON_DETECTION_STATS = ("undetected", "harmless") SHA256_RE = re.compile(r"\A[0-9a-f]{64}\Z") ANALYSIS_ID_RE = re.compile(r"\A[A-Za-z0-9_+/-]+={0,2}\Z") ALLOWED_STATS = { @@ -132,6 +159,10 @@ class CompletedResult: microsoft_engine_version: str microsoft_engine_update: str detections: Tuple[Tuple[str, str, str, str, str], ...] + # Every engine's answer for these bytes: (engine, category, version, defs). + # The isolated-sibling class needs what the flagging engine said about the + # SIBLING forms, which is a non-detection and so never in `detections`. + engines: Tuple[Tuple[str, str, str, str], ...] = () def required_env(name: str) -> str: @@ -551,6 +582,7 @@ def parse_completed(document: object, submission: Submission) -> Tuple[str, Opti suspicious = normalized["suspicious"] detections: List[Tuple[str, str, str, str, str]] = [] + engines: List[Tuple[str, str, str, str]] = [] results = attributes.get("results") microsoft_category = "" microsoft_result = "" @@ -566,6 +598,14 @@ def parse_completed(document: object, submission: Submission) -> Tuple[str, Opti category = result.get("category") if category not in ALLOWED_STATS: raise GateError(f"VirusTotal engine {engine} has invalid category: {category!r}") + engines.append( + ( + one_line(engine), + str(category), + one_line(result.get("engine_version") or ""), + one_line(result.get("engine_update") or ""), + ) + ) if category in {"malicious", "suspicious"}: detail_detections[category] += 1 label = one_line(result.get("result") or category) @@ -616,6 +656,7 @@ def parse_completed(document: object, submission: Submission) -> Tuple[str, Opti microsoft_engine_version, microsoft_engine_update, tuple(detections), + tuple(engines), ), detections, ) @@ -648,12 +689,28 @@ def fetch_analysis(api_key: str, analysis_id: str, curl_timeout: int) -> Optiona raise GateError(f"VirusTotal returned malformed JSON for analysis {analysis_id}") from error +def evidence_cell(value: str) -> str: + """One TSV-safe token: `|` and `;` separate fields and entries in a cell.""" + return one_line(value).replace("|", "/").replace(";", ",") + + +def format_detections(result: CompletedResult) -> str: + # engine|category|label|engine version|definitions, one entry per detecting + # engine. Published so a reader sees WHO flagged a candidate, not only how + # many engines did (the v2 format kept only Microsoft's columns). + return ";".join( + "|".join(evidence_cell(part) for part in (engine, category, label, version, updated)) + for engine, label, category, version, updated in result.detections + ) + + def write_results( path: pathlib.Path, *, results: Sequence[CompletedResult], associations: int, min_engines: int, + classifications: Dict[str, Tuple[str, str]], ) -> None: if os.path.lexists(path) and path.is_symlink(): raise GateError(f"results path is a symlink: {path}") @@ -662,7 +719,7 @@ def write_results( temporary = pathlib.Path(temporary_name) try: with os.fdopen(fd, "w", encoding="utf-8", newline="") as handle: - handle.write("# cbm-virustotal-results-v2\n") + handle.write("# cbm-virustotal-results-v3\n") handle.write(f"# scan_objects={len(results)}\n") handle.write(f"# associations={associations}\n") handle.write(f"# min_engines_policy={min_engines}\n") @@ -677,6 +734,7 @@ def write_results( writer.writeheader() for item in sorted(results, key=lambda result: result.submission.expected.scan_path): expected = item.submission.expected + classification, isolated_evidence = classifications[expected.scan_path] writer.writerow( { "scan_path": expected.scan_path, @@ -690,10 +748,12 @@ def write_results( "analysis_id": item.submission.analysis_id, "microsoft_category": item.microsoft_category, "microsoft_result": item.microsoft_result, - "policy_classification": classify_result(item, min_engines), + "policy_classification": classification, "microsoft_engine_version": item.microsoft_engine_version, "microsoft_engine_update": item.microsoft_engine_update, "virustotal_url": f"https://www.virustotal.com/gui/file/{expected.sha256}/detection", + "detections": format_detections(item), + "isolated_evidence": isolated_evidence, } ) handle.flush() @@ -747,6 +807,120 @@ def classify_result(result: CompletedResult, min_engines: int) -> str: return "clean" +def load_sibling_targets( + path: pathlib.Path, objects: Sequence[ExpectedObject] +) -> Dict[str, str]: + """scan_path -> release target, from the exact candidate manifest. + + Every scanned candidate must appear exactly once with the bytes the gate + hashed, and every target must have at least two forms: without siblings + there is nothing to compare a verdict against.""" + _metadata, rows = parse_versioned_tsv( + path, marker="cbm-release-candidates-v1", fields=CANDIDATE_FIELDS + ) + by_path = {item.scan_path: item for item in objects if not item.withheld} + targets: Dict[str, str] = {} + forms: Dict[str, int] = {} + for row in rows: + expected = by_path.get(row["scan_path"]) + if expected is None or row["scan_path"] in targets: + raise GateError(f"candidate manifest names an unknown or duplicate object: {row['scan_path']}") + if row["sha256"] != expected.sha256 or row["size"] != str(expected.size): + raise GateError(f"candidate manifest is not bound to the scanned bytes: {row['scan_path']}") + if not row["target"]: + raise GateError(f"candidate manifest row has no target: {row['scan_path']}") + targets[row["scan_path"]] = row["target"] + forms[row["target"]] = forms.get(row["target"], 0) + 1 + if set(targets) != set(by_path): + raise GateError("candidate manifest does not cover every scanned candidate") + lonely = sorted(target for target, count in forms.items() if count < 2) + if lonely: + raise GateError(f"candidate targets without sibling forms: {lonely}") + return targets + + +# Policy cbm-vt-candidate-selection-v2 (SECURITY.md, "Our release policy"). +# +# Every target ships ONE of several forms of a single linker output (stripped, +# debug-stripped, unstripped, ...): the same code, and some of them the same +# symbols. A verdict the flagging engine does not repeat on ANY sibling form, +# on the same engine version and definitions, describes that file image, not +# the program. Such a candidate is "isolated": it is never shipped, it is named +# in the release notes, and it no longer blocks the other seven products. +# +# Everything short of that proof stays "hard": two engines, a suspicious +# verdict, a Microsoft label (the `!ml` tolerance has its own rule), an engine +# that did not answer for a sibling or answered on other definitions, a sibling +# that is not fully clean, and more than one isolated candidate in a release. +# Only the candidate stage opts in; the surface scan of the archives does not. +def isolated_evidence( + result: CompletedResult, + siblings: Sequence[CompletedResult], +) -> Optional[str]: + if result.suspicious or result.malicious != 1 or len(result.detections) != 1: + return None + engine, _label, category, version, updated = result.detections[0] + if engine == "Microsoft" or category != "malicious": + return None + if version in ("", "?") or updated in ("", "?") or not siblings: + return None + entries = [f"{evidence_cell(engine)}|{evidence_cell(version)}|{evidence_cell(updated)}"] + for sibling in sorted(siblings, key=lambda item: item.submission.expected.scan_path): + if classify_result(sibling, 0) != "clean": + return None + answers = [entry for entry in sibling.engines if entry[0] == engine] + if len(answers) != 1: + return None + _engine, sibling_category, sibling_version, sibling_updated = answers[0] + if ( + sibling_category not in NON_DETECTION_STATS + or sibling_version != version + or sibling_updated != updated + ): + return None + entries.append(f"{sibling.submission.expected.scan_path}={sibling_category}") + return ";".join(entries) + + +def classify_all( + results: Sequence[CompletedResult], + sibling_targets: Optional[Dict[str, str]], + min_engines: int, +) -> Tuple[Dict[str, Tuple[str, str]], List[str]]: + """(scan_path -> (policy classification, isolated evidence), the candidates + that each met the isolated proof but were held hard because there was more + than one).""" + classes = { + item.submission.expected.scan_path: (classify_result(item, min_engines), "") + for item in results + } + if sibling_targets is None: + return classes, [] + by_target: Dict[str, List[CompletedResult]] = {} + for item in results: + by_target.setdefault(sibling_targets[item.submission.expected.scan_path], []).append(item) + isolated: Dict[str, str] = {} + for item in results: + scan_path = item.submission.expected.scan_path + if classes[scan_path][0] != "hard": + continue + siblings = [ + other + for other in by_target[sibling_targets[scan_path]] + if other.submission.expected.scan_path != scan_path + ] + evidence = isolated_evidence(item, siblings) + if evidence is not None: + isolated[scan_path] = evidence + # One isolated candidate is a statement about one file image. Several in + # one release is a pattern, and a pattern is not ours to explain away. + if len(isolated) == 1: + for scan_path, evidence in isolated.items(): + classes[scan_path] = ("isolated", evidence) + return classes, [] + return classes, sorted(isolated) + + def main() -> None: api_key = required_env("VT_API_KEY") raw_analysis = required_env("VT_ANALYSIS") @@ -773,6 +947,15 @@ def main() -> None: objects=expected, expected_associations=associations, ) + # Opt-in, candidate stage only (_build.yml select-package): the candidate + # manifest is what says which scanned objects are sibling forms of one + # linker output. Unset, every non-tolerated detection blocks as before. + sibling_manifest = os.environ.get("VT_ISOLATED_SIBLING_CANDIDATES", "") + sibling_targets = ( + load_sibling_targets(pathlib.Path(sibling_manifest).absolute(), expected) + if sibling_manifest + else None + ) submissions = parse_action_output( raw_analysis, objects=expected, @@ -793,6 +976,7 @@ def main() -> None: pending: Deque[Submission] = deque(submissions) completed: List[CompletedResult] = [] failures: List[str] = [] + flagged: Dict[str, str] = {} attempts: Dict[str, int] = {item.expected.scan_path: 0 for item in submissions} started = time.monotonic() next_request_at = started @@ -837,6 +1021,10 @@ def main() -> None: ) if tolerated: print(f"TOLERATED: {message}") + elif sibling_targets is not None: + # Decided once every sibling form has an answer (classify_all). + flagged[submission.expected.scan_path] = message + print(f"FLAGGED: {message}; decided after every sibling form completes") else: failures.append(message) print(f"BLOCKED: {message}") @@ -859,11 +1047,31 @@ def main() -> None: expected_paths = {item.expected.scan_path for item in submissions} if completed_paths != expected_paths or len(completed) != len(submissions): raise GateError("completed VirusTotal set differs from the exact submitted set") + classifications, held = classify_all(completed, sibling_targets, min_engines) + if held: + print( + f"BLOCKED: {len(held)} candidates each met the isolated-sibling proof; " + f"the policy allows at most one per release: {held}" + ) + for scan_path in sorted(flagged): + classification, evidence = classifications[scan_path] + if classification == "isolated": + engine_part, *sibling_parts = evidence.split(";") + engine, version, updated = engine_part.split("|") + print( + f"ISOLATED: {flagged[scan_path]}; never shipped: {engine} judged every " + f"sibling form clean on the same engine and definitions " + f"(engine {version}, defs {updated}): {', '.join(sibling_parts)}" + ) + else: + failures.append(flagged[scan_path]) + print(f"BLOCKED: {flagged[scan_path]}") write_results( results_path, results=completed, associations=associations, min_engines=min_engines, + classifications=classifications, ) if failures: print(f"VirusTotal completed-set evidence: {results_path}") diff --git a/scripts/ci/publish-vt-evidence.sh b/scripts/ci/publish-vt-evidence.sh index 3706f5bfd7..1d995a936e 100644 --- a/scripts/ci/publish-vt-evidence.sh +++ b/scripts/ci/publish-vt-evidence.sh @@ -40,7 +40,7 @@ publish_copy() { publish_copy "$VT_ASSOCIATIONS" cbm-release-scan-associations-v3 virustotal-associations.tsv publish_copy "$VT_EXPECTED_SCAN_SET" cbm-release-scan-set-v2 virustotal-scan-set.tsv -publish_copy "$VT_RESULTS_PATH" cbm-virustotal-results-v2 virustotal-results.tsv +publish_copy "$VT_RESULTS_PATH" cbm-virustotal-results-v3 virustotal-results.tsv for name in virustotal-associations.tsv virustotal-results.tsv virustotal-scan-set.tsv; do if command -v sha256sum >/dev/null 2>&1; then diff --git a/scripts/ci/select-release-candidates.py b/scripts/ci/select-release-candidates.py index 89cdb41df7..b214b58387 100755 --- a/scripts/ci/select-release-candidates.py +++ b/scripts/ci/select-release-candidates.py @@ -65,7 +65,11 @@ class ContractError(Exception): "microsoft_engine_version", "microsoft_engine_update", "virustotal_url", + "detections", + "isolated_evidence", ) +NON_DETECTION = {"undetected", "harmless"} +SELECTION_POLICY = "virustotal-v3" SELECTION_FIELDS = ( "target", "selected_variant", @@ -345,12 +349,15 @@ def validate_result_row(row: dict[str, str], candidate: dict[str, str]) -> None: raise ContractError(f"VT result URL is not content-bound: {scan_path}") classification = row["policy_classification"] + detections = parse_detections(row["detections"], scan_path=scan_path) if classification == "clean": coherent = ( malicious == 0 and suspicious == 0 - and row["microsoft_category"] in {"undetected", "harmless"} + and row["microsoft_category"] in NON_DETECTION and row["microsoft_result"] == "" + and not detections + and row["isolated_evidence"] == "" ) elif classification == "microsoft-ml": coherent = ( @@ -359,6 +366,25 @@ def validate_result_row(row: dict[str, str], candidate: dict[str, str]) -> None: and row["microsoft_category"] == "malicious" and bool(row["microsoft_result"]) and row["microsoft_result"].endswith("!ml") + and len(detections) == 1 + and detections[0][0] == "Microsoft" + and detections[0][2] + == row["microsoft_result"].replace("|", "/").replace(";", ",") + and row["isolated_evidence"] == "" + ) + elif classification == "isolated": + # One non-Microsoft engine, malicious, nothing suspicious, Microsoft + # clean; the sibling half of the proof is checked across rows in + # check_isolated, which needs every candidate of the target. + coherent = ( + malicious == 1 + and suspicious == 0 + and row["microsoft_category"] in NON_DETECTION + and row["microsoft_result"] == "" + and len(detections) == 1 + and detections[0][0] != "Microsoft" + and detections[0][1] == "malicious" + and bool(row["isolated_evidence"]) ) else: raise ContractError(f"VT result is a hard or unknown policy block: {scan_path}") @@ -366,12 +392,61 @@ def validate_result_row(row: dict[str, str], candidate: dict[str, str]) -> None: raise ContractError(f"VT classification contradicts its result details: {scan_path}") +def parse_detections(cell: str, *, scan_path: str) -> list[tuple[str, str, str, str, str]]: + """engine|category|label|engine version|definitions entries, `;`-joined.""" + if cell == "": + return [] + entries = [] + for entry in cell.split(";"): + parts = entry.split("|") + if len(parts) != 5 or not all(parts) or any(ord(c) < 32 for c in entry): + raise ContractError(f"VT result has malformed detection evidence: {scan_path}") + entries.append((parts[0], parts[1], parts[2], parts[3], parts[4])) + return entries + + +def check_isolated( + by_path: dict[str, dict[str, str]], candidates: Sequence[dict[str, str]] +) -> None: + """Re-derive the isolated-sibling proof from the recorded evidence instead + of trusting the gate's label: at most one per release, its engine answered + a non-detection for EVERY sibling form on the same version and definitions, + and every sibling is fully clean.""" + isolated = [path for path, row in by_path.items() if row["policy_classification"] == "isolated"] + if len(isolated) > 1: + raise ContractError(f"more than one isolated candidate in one release: {sorted(isolated)}") + for scan_path in isolated: + row = by_path[scan_path] + target = next(c["target"] for c in candidates if c["scan_path"] == scan_path) + siblings = sorted( + c["scan_path"] for c in candidates if c["target"] == target and c["scan_path"] != scan_path + ) + engine, _category, _label, version, updated = parse_detections( + row["detections"], scan_path=scan_path + )[0] + head, *answers = row["isolated_evidence"].split(";") + if head != f"{engine}|{version}|{updated}": + raise ContractError(f"isolated evidence names another engine or definitions: {scan_path}") + recorded = {} + for answer in answers: + sibling, separator, category = answer.partition("=") + if not separator or sibling in recorded: + raise ContractError(f"isolated evidence is malformed: {scan_path}") + recorded[sibling] = category + if sorted(recorded) != siblings: + raise ContractError(f"isolated evidence does not cover exactly the sibling forms: {scan_path}") + if any(category not in NON_DETECTION for category in recorded.values()): + raise ContractError(f"isolated evidence records a sibling detection: {scan_path}") + if any(by_path[sibling]["policy_classification"] != "clean" for sibling in siblings): + raise ContractError(f"an isolated candidate's sibling is not clean: {scan_path}") + + def load_results( path: pathlib.Path, candidates: Sequence[dict[str, str]] ) -> dict[str, dict[str, str]]: metadata, rows = parse_tsv( path, - marker="cbm-virustotal-results-v2", + marker="cbm-virustotal-results-v3", fields=RESULT_FIELDS, ) expected_count = len(candidates) @@ -408,6 +483,7 @@ def load_results( by_path[row["scan_path"]] = row if set(by_path) != set(candidate_by_path): raise ContractError("VT results are missing candidate objects") + check_isolated(by_path, candidates) completed = [int(row["completed_engines"]) for row in rows] if ( @@ -498,7 +574,7 @@ def main(argv: Sequence[str]) -> None: candidates, object_paths = load_candidates(args.candidates, args.objects_dir) results = load_results(args.results, candidates) if args.results else None - policy = "virustotal-v2" if results is not None else "unscanned-dry-run" + policy = SELECTION_POLICY if results is not None else "unscanned-dry-run" candidate_by_tuple = { (row["target"], row["variant"]): row for row in candidates } @@ -530,7 +606,9 @@ def main(argv: Sequence[str]) -> None: # smallest artifact first, then progressively more metadata. # A `hard` classification never reaches here - the gate fails # the release before selection - so every candidate below is - # either clean or a tolerated single Microsoft `!ml`. + # clean, a tolerated single Microsoft `!ml`, or the release's + # one `isolated` candidate, which is NEVER shipped (its + # siblings are all clean by construction, check_isolated). # # The variants are behaviourally identical, so this picks on # verdict alone: the first clean one in preference order, and @@ -538,6 +616,8 @@ def main(argv: Sequence[str]) -> None: # a flagged one (still the smallest). order = ("stripped", "debug-stripped", "unstripped") clean = [v for v in order if classifications[v] == "clean"] + if "isolated" in classifications.values() and not clean: + raise ContractError(f"isolated candidate without a clean sibling: {target}") if clean: selected_variant = clean[0] if selected_variant == "stripped": diff --git a/scripts/ci/verify-release-selection.py b/scripts/ci/verify-release-selection.py index be7733deb6..99a3e33377 100755 --- a/scripts/ci/verify-release-selection.py +++ b/scripts/ci/verify-release-selection.py @@ -93,7 +93,7 @@ def parse_arguments(argv: Sequence[str]) -> argparse.Namespace: parser.add_argument("--archive-dir", required=True, type=pathlib.Path) parser.add_argument( "--require-policy", - choices=("virustotal-v2", "unscanned-dry-run"), + choices=("virustotal-v3", "unscanned-dry-run"), help="reject a selection produced under any other policy", ) return parser.parse_args(argv[1:]) @@ -135,7 +135,7 @@ def load_selection( cursor += 1 if set(metadata) != {"policy", "targets", "candidates"}: raise ContractError("release selection metadata fields are incomplete or unexpected") - if metadata["policy"] not in {"virustotal-v2", "unscanned-dry-run"}: + if metadata["policy"] not in {"virustotal-v3", "unscanned-dry-run"}: raise ContractError("release selection has an invalid policy") if require_policy is not None and metadata["policy"] != require_policy: raise ContractError( @@ -165,18 +165,34 @@ def load_selection( selections: dict[str, dict[str, str]] = {} analysis_ids: set[str] = set() + isolated_seen: list[str] = [] for row in rows: target = row["target"] binary = "codebase-memory-mcp.exe" if target.startswith("windows-") else "codebase-memory-mcp" classifications = { variant: row[f"{FIELD_KEY[variant]}_classification"] for variant in VARIANTS } - if metadata["policy"] == "virustotal-v2": + if metadata["policy"] == "virustotal-v3": if any( - classification not in {"clean", "microsoft-ml"} + classification not in {"clean", "microsoft-ml", "isolated"} for classification in classifications.values() ): raise ContractError(f"release selection contains a hard classification: {target}") + # Policy cbm-vt-candidate-selection-v2: at most one isolated + # candidate per release, and only beside fully clean siblings. + isolated = [v for v in VARIANTS if classifications[v] == "isolated"] + if isolated: + isolated_seen.extend(f"{target}/{v}" for v in isolated) + if len(isolated_seen) > 1: + raise ContractError( + f"release selection has more than one isolated candidate: {isolated_seen}" + ) + if any( + classifications[v] != "clean" for v in VARIANTS if v not in isolated + ): + raise ContractError( + f"release selection has an isolated candidate beside a flagged sibling: {target}" + ) for variant in VARIANTS: sha256 = row[f"{FIELD_KEY[variant]}_sha256"] analysis_id = row[f"{FIELD_KEY[variant]}_analysis_id"] @@ -190,7 +206,8 @@ def load_selection( raise ContractError(f"release selection has unbound VT URL: {target}") # Re-derived here independently of the selector: smallest artifact # first, first CLEAN one wins, and only if every candidate drew the - # tolerated verdict do we ship the smallest flagged one. + # tolerated verdict do we ship the smallest flagged one. An + # isolated candidate is never clean, so it is never the one shipped. order = ("stripped", "debug-stripped", "unstripped") clean = [v for v in order if classifications[v] == "clean"] if clean: diff --git a/tests/test_release_gate_chain_contract.sh b/tests/test_release_gate_chain_contract.sh index 627bf4c7c3..155a815461 100755 --- a/tests/test_release_gate_chain_contract.sh +++ b/tests/test_release_gate_chain_contract.sh @@ -196,6 +196,26 @@ else: "select-package: must need every native candidate producer; missing " + ", ".join(missing)) + # Policy cbm-vt-candidate-selection-v2: only the candidate stage, where + # sibling forms exist and an isolated one is never shipped, may opt into + # the isolated-sibling class. The surface scan of the shipped archives + # must stay strict, so the opt-in appears exactly once, here, bound to the + # staged candidate manifest. + sibling_flag = "VT_ISOLATED_SIBLING_CANDIDATES: release-candidate-scan/candidates.tsv" + wait_step = re.search( + r"- name: Wait for complete VirusTotal candidate results\n(?: [^\n]*\n|\s*\n)*", + select) + sibling_keys = re.findall(r"(?m)^\s+VT_ISOLATED_SIBLING_CANDIDATES:", build_text) + if len(sibling_keys) != 1 or not wait_step \ + or sibling_flag not in wait_step.group(0): + failures.append( + "select-package: the isolated-sibling opt-in must appear exactly once, on the\n" + " candidate VirusTotal wait step, bound to the staged candidate manifest.") + if re.search(r"(?m)^\s+VT_ISOLATED_SIBLING_CANDIDATES:", text + "\n" + dry_text): + failures.append( + "release.yml/dry-run.yml: the archive surface scan must stay strict; the\n" + " isolated-sibling opt-in belongs to the candidate stage only.") + timeout = re.search(r"^ timeout-minutes:\s*(\d+)\s*$", select, re.M) if not timeout or int(timeout.group(1)) < 300: failures.append( @@ -318,7 +338,7 @@ if "needs.security.result == 'success'" not in verify_body: for token in ("--pattern 'release-selection.tsv'", "scripts/ci/verify-release-selection.py", '--selection "$RUNNER_TEMP/release-selection.tsv"', - "--require-policy virustotal-v2", + "--require-policy virustotal-v3", '--archive-dir "$ARCHIVE_DIR"'): if token not in verify_body: failures.append( diff --git a/tests/test_vt_candidate_selection_contract.sh b/tests/test_vt_candidate_selection_contract.sh index 0a2cf96c96..192f8df224 100755 --- a/tests/test_vt_candidate_selection_contract.sh +++ b/tests/test_vt_candidate_selection_contract.sh @@ -53,6 +53,7 @@ RESULT_FIELDS = ( "total_engines", "malicious", "suspicious", "analysis_id", "microsoft_category", "microsoft_result", "policy_classification", "microsoft_engine_version", "microsoft_engine_update", "virustotal_url", + "detections", "isolated_evidence", ) ARCHIVES = tuple( f"codebase-memory-mcp-{target}.tar.gz" @@ -236,21 +237,39 @@ def tamper_candidate(path: pathlib.Path) -> None: expect_stage_failure("tamper", tamper_candidate) +ISOLATING_ENGINE = ("APEX", "6.849", "20261204") + + def result_rows(classifications: dict[tuple[str, str], str], *, shuffle: bool = False) -> list[dict[str, object]]: rows = [] for row in candidates: classification = classifications[row["target"], row["variant"]] clean = classification == "clean" + microsoft_flag = classification == "microsoft-ml" + detections = isolated_evidence = "" + if microsoft_flag: + detections = "Microsoft|malicious|Trojan:Win32/Wacatac.B!ml|1.1.1|20260813" + elif classification == "isolated": + engine, version, defs = ISOLATING_ENGINE + detections = f"{engine}|malicious|Malicious|{version}|{defs}" + siblings = sorted( + c["scan_path"] for c in candidates + if c["target"] == row["target"] and c["scan_path"] != row["scan_path"] + ) + isolated_evidence = ";".join( + [f"{engine}|{version}|{defs}"] + [f"{s}=undetected" for s in siblings] + ) rows.append({ "scan_path": row["scan_path"], "sha256": row["sha256"], "size": row["size"], "association_count": 1, "completed_engines": 71, "total_engines": 71, "malicious": 0 if clean else 1, "suspicious": 0, "analysis_id": "analysis-" + row["sha256"][:24], - "microsoft_category": "undetected" if clean else "malicious", - "microsoft_result": "" if clean else "Trojan:Win32/Wacatac.B!ml", + "microsoft_category": "malicious" if microsoft_flag else "undetected", + "microsoft_result": "Trojan:Win32/Wacatac.B!ml" if microsoft_flag else "", "policy_classification": classification, "microsoft_engine_version": "1.1.1", "microsoft_engine_update": "20260813", "virustotal_url": "https://www.virustotal.com/gui/file/" + row["sha256"] + "/detection", + "detections": detections, "isolated_evidence": isolated_evidence, }) if shuffle: random.Random(8675309).shuffle(rows) @@ -258,7 +277,7 @@ def result_rows(classifications: dict[tuple[str, str], str], *, shuffle: bool = def write_results(path: pathlib.Path, rows: list[dict[str, object]]) -> None: - write_tsv(path, "cbm-virustotal-results-v2", { + write_tsv(path, "cbm-virustotal-results-v3", { "scan_objects": 24, "associations": 24, "min_engines_policy": 50, "min_completed_engines": 71, "max_completed_engines": 71, }, RESULT_FIELDS, rows) @@ -312,7 +331,7 @@ result = run(select_tool, "--candidates", staged / "candidates.tsv", require(result.returncode == 0, f"valid truth-table results rejected: {result.stdout}{result.stderr}") smeta, selections = selection_rows(selected) require(smeta["marker"] == "# cbm-release-selection-v1", "selection marker changed") -require(smeta.get("policy") == "virustotal-v2", "scanned selection policy not recorded") +require(smeta.get("policy") == "virustotal-v3", "scanned selection policy not recorded") require([row["target"] for row in selections] == list(TARGETS), "selection order is not canonical") for row in selections: target = row["target"] @@ -374,6 +393,76 @@ expect_select_failure("cross-target", lambda rows: ( rows[2].update(scan_path=candidates[0]["scan_path"], sha256=candidates[0]["sha256"], size=candidates[0]["size"]), )) +# Policy cbm-vt-candidate-selection-v2: the release's one "isolated" candidate, +# in ANY position of its product's order, is never shipped; the first clean +# form in the fixed order ships instead, and the evidence keeps the verdict. +for position in ORDER: + iso_classes = {key: "clean" for key in candidate_data} + iso_classes["windows-amd64", position] = "isolated" + iso_results = fix / f"isolated-{position}.tsv" + write_results(iso_results, result_rows(iso_classes)) + iso_out = fix / f"isolated-selected-{position}" + result = run(select_tool, "--candidates", staged / "candidates.tsv", + "--objects-dir", staged / "objects", "--out-dir", iso_out, + "--results", iso_results) + require(result.returncode == 0, + f"an isolated {position} candidate must not block selection: {result.stdout}{result.stderr}") + _, iso_rows = selection_rows(iso_out) + win = next(row for row in iso_rows if row["target"] == "windows-amd64") + want = next(variant for variant in ORDER if variant != position) + require(win["selected_variant"] == want, + f"isolated {position}: expected {want}, selected {win['selected_variant']}") + require(win[f"{position.replace('-', '_')}_classification"] == "isolated", + f"isolated {position}: the selection evidence must keep the isolated verdict") + if position == "stripped": + require(win["decision"] == "debug-stripped-clean-after-stripped:isolated-unstripped:clean", + f"isolated stripped: decision reason wrong: {win['decision']!r}") + else: + require(win["decision"] == "stripped-preferred", + f"isolated {position}: decision reason wrong: {win['decision']!r}") + + +def expect_isolated_failure(label: str, updates: dict[tuple[str, str], str], mutate=lambda rows: None) -> None: + iso_classes = {key: "clean" for key in candidate_data} + iso_classes.update(updates) + rows = result_rows(iso_classes) + mutate(rows) + evidence = fix / f"bad-isolated-{label}.tsv" + write_results(evidence, rows) + out = fix / f"bad-isolated-selected-{label}" + result = run(select_tool, "--candidates", staged / "candidates.tsv", + "--objects-dir", staged / "objects", "--out-dir", out, + "--results", evidence) + require(result.returncode != 0, f"selector accepted {label}") + require(not out.exists(), f"failed selection {label} published partial output") + + +def isolated_row(rows: list[dict[str, object]]) -> dict[str, object]: + return next(row for row in rows if row["policy_classification"] == "isolated") + + +WIN_UNSTRIPPED = {("windows-amd64", "unstripped"): "isolated"} +expect_isolated_failure("sibling-microsoft-ml", + {**WIN_UNSTRIPPED, ("windows-amd64", "stripped"): "microsoft-ml"}) +expect_isolated_failure("two-isolated", + {**WIN_UNSTRIPPED, ("linux-amd64", "unstripped"): "isolated"}) +expect_isolated_failure("other-engine", WIN_UNSTRIPPED, lambda rows: isolated_row(rows).update( + isolated_evidence=str(isolated_row(rows)["isolated_evidence"]).replace("APEX|", "OtherAV|", 1))) +expect_isolated_failure("other-definitions", WIN_UNSTRIPPED, lambda rows: isolated_row(rows).update( + isolated_evidence=str(isolated_row(rows)["isolated_evidence"]).replace("|20261204;", "|20261203;", 1))) +expect_isolated_failure("missing-sibling", WIN_UNSTRIPPED, lambda rows: isolated_row(rows).update( + isolated_evidence=str(isolated_row(rows)["isolated_evidence"]).rsplit(";", 1)[0])) +expect_isolated_failure("sibling-detected", WIN_UNSTRIPPED, lambda rows: isolated_row(rows).update( + isolated_evidence=str(isolated_row(rows)["isolated_evidence"]).replace("=undetected", "=malicious", 1))) +# Consistent in every other respect (the evidence names the same engine and +# definitions), so only the "not Microsoft" rule can reject it. +expect_isolated_failure("microsoft-engine", WIN_UNSTRIPPED, lambda rows: isolated_row(rows).update( + detections="Microsoft|malicious|Trojan:Win32/Emotet|1.1.1|20260813", + isolated_evidence=str(isolated_row(rows)["isolated_evidence"]).replace( + "APEX|6.849|20261204", "Microsoft|1.1.1|20260813", 1))) +expect_isolated_failure("no-evidence", WIN_UNSTRIPPED, lambda rows: isolated_row(rows).update( + isolated_evidence="")) + # Reconcile all 14 canonical containers, recursively, against the selected # eight hashes. Eligible MCPBs repeat exactly the matching selected bytes. archives = fix / "containers" @@ -416,6 +505,39 @@ def expect_verify_failure(label: str, mutate) -> None: expect_verify_failure("missing", lambda path: next(path.rglob("*.mcpb")).unlink()) + + +# The verifier re-derives the policy from the selection alone. These rewrite +# the truth-table selection (whose containers are the ones built above) on its +# all-clean target, so the ONLY thing that differs is the isolated verdicts: +# one isolated non-shipped form is accepted (positive control), shipping an +# isolated form or carrying two is rejected. +ALL_CLEAN_TARGET = TARGETS[TRUTH_KEYS.index(("clean", "clean", "clean"))] + + +def verify_rewritten(label: str, rewrite) -> subprocess.CompletedProcess: + source = selected / "release-selection.tsv" + lines = source.read_text().splitlines(keepends=True) + header_index = next(i for i, line in enumerate(lines) if line.startswith("target\t")) + header = lines[header_index].rstrip("\n").split("\t") + rows = [dict(zip(header, line.rstrip("\n").split("\t"))) for line in lines[header_index + 1:]] + rewrite(next(row for row in rows if row["target"] == ALL_CLEAN_TARGET)) + rewritten = fix / f"selection-{label}.tsv" + rewritten.write_text("".join(lines[:header_index + 1]) + + "".join("\t".join(row[field] for field in header) + "\n" for row in rows)) + return run(verify_tool, "--selection", rewritten, "--archive-dir", archives) + + +result = verify_rewritten("one-isolated", lambda row: row.update(unstripped_classification="isolated")) +require(result.returncode == 0, + f"one isolated non-shipped form must verify: {result.stdout}{result.stderr}") +result = verify_rewritten("ships-isolated", lambda row: row.update(stripped_classification="isolated")) +require(result.returncode != 0 and "contradicts the policy truth table" in result.stderr, + f"a selection shipping an isolated form must be rejected: {result.stdout}{result.stderr}") +result = verify_rewritten("two-isolated", lambda row: row.update( + unstripped_classification="isolated", debug_stripped_classification="isolated")) +require(result.returncode != 0 and "more than one isolated candidate" in result.stderr, + f"two isolated forms must be rejected: {result.stdout}{result.stderr}") expect_verify_failure("surplus", lambda path: (path / "surplus.zip").write_bytes(b"not allowed")) diff --git a/tests/test_vt_gate_policy_contract.sh b/tests/test_vt_gate_policy_contract.sh index 2f7e505e68..58720c9cbd 100644 --- a/tests/test_vt_gate_policy_contract.sh +++ b/tests/test_vt_gate_policy_contract.sh @@ -29,8 +29,12 @@ for surface in "$ROOT/README.md" "$ROOT/SECURITY.md" "$ROOT/docs/index.html"; do done grep -Fq 'Microsoft `!ml` tolerance' "$ROOT/README.md" || \ fail "README must link the exact documented Microsoft !ml tolerance" -grep -Fq 'Policy identifier: `cbm-vt-candidate-selection-v1`' "$ROOT/SECURITY.md" || \ +grep -Fq 'Policy identifier: `cbm-vt-candidate-selection-v2`' "$ROOT/SECURITY.md" || \ fail "SECURITY.md must name the versioned candidate-selection policy" +grep -Fq 'built in two conventional forms' "$ROOT/SECURITY.md" && \ + fail "SECURITY.md still describes the two-candidate policy" +grep -Fq '**isolated**' "$ROOT/SECURITY.md" || \ + fail "SECURITY.md must define the isolated class the gate enforces" # Every marker publish-vt-evidence.sh validates must be one the gate actually # writes. These drifted silently: the results format went to v2 while the @@ -308,7 +312,7 @@ alias_output="binaries/objects/probe=$(url_for upload-alias)" fail "a content-bound action-output path alias must pass: $(cat "$FIX/last.log")" RESULTS="$FIX/work/binaries/vt-results.tsv" [ -f "$RESULTS" ] || fail "clean gate did not atomically publish its results manifest" -grep -q '^# cbm-virustotal-results-v2$' "$RESULTS" || fail "results marker missing" +grep -q '^# cbm-virustotal-results-v3$' "$RESULTS" || fail "results marker missing" grep -q "objects/probe.*$PROBE_SHA.*$PROBE_SIZE.*60" "$RESULTS" || \ fail "results do not bind path/hash/size/actual engine count" grep -Fq 'upload-alias' "$RESULTS" || \ @@ -424,4 +428,168 @@ printf 'tampered\n' > "$FIX/work/binaries/objects/probe" [ "$(run_gate "$clean_output")" != "0" ] || fail "tampered staged object must block before polling" grep -q 'changed after extraction' "$FIX/last.log" || fail "tamper failure is not diagnosable" -echo 'PASS: VT gate is exact-set and content-bound; tolerates exactly one Microsoft !ml verdict and nothing else; engine count is evidence, not a gate' +# ── Isolated sibling (policy cbm-vt-candidate-selection-v2) ───────────────── +# Two targets, three forms each, as the candidate stage scans them. One form +# flagged by ONE non-Microsoft engine, while that engine judged both sibling +# forms clean on the same engine version and definitions, is "isolated": it +# passes the candidate stage, is recorded with the engine's sibling answers, +# and is never shipped. Every weaker situation still blocks. +SIB="$FIX/sib" +mkdir -p "$SIB/binaries/objects" "$SIB/responses" +python3 - "$SIB" <<'SIBFIX' +import hashlib, pathlib, sys +root = pathlib.Path(sys.argv[1]) +rows, assoc, cand = [], [], [] +for target in ("windows-amd64", "linux-amd64"): + for variant in ("unstripped", "debug-stripped", "stripped"): + name = f"{target}-{variant}" + body = f"{name}\n".encode() + (root / "binaries/objects" / name).write_bytes(body) + sha, size = hashlib.sha256(body).hexdigest(), len(body) + rows.append(f"objects/{name}\t{sha}\t{size}\t1\tbinary") + assoc.append(f"member\t{target}.zip\t{'c' * 64 if target.startswith('w') else 'd' * 64}\t{variant}\tbinary\t{variant}/codebase-memory-mcp\t\t\tobjects/{name}\t{sha}\t{size}") + cand.append("\t".join([target, variant, f"{variant}/codebase-memory-mcp", "e" * 64, sha, sha, + str(size), "pe", "amd64", "native", "copy", "not-applicable", + "strip", "contract", "same-linker-output-v1", f"objects/{name}"])) + (root / "sha" / name).parent.mkdir(exist_ok=True) + (root / "sha" / name).write_text(f"{sha} {size}") +(root / "binaries/scan-set.tsv").write_text( + "# cbm-release-scan-set-v2\n# scan_objects=6\n# associations=6\n" + "scan_path\tsha256\tsize\tassociation_count\tassociation_kinds\n" + "\n".join(rows) + "\n") +(root / "binaries/associations.tsv").write_text( + "# cbm-release-scan-associations-v3\n# archives=2\n# associations=6\n# scan_objects=6\n" + "association_type\tarchive\tarchive_sha256\tvariant\tkind\tmember\tasset_path\tmime\tscan_path\tobject_sha256\tsize\n" + + "\n".join(assoc) + "\n") +(root / "binaries/candidates.tsv").write_text( + "# cbm-release-candidates-v1\n# targets=2\n# candidates=6\n" + "target\tvariant\trelative_path\tsource_sha256\tpre_sign_sha256\tsha256\tsize\tformat\tarchitecture\t" + "linkage\ttransform\tsignature\tstrip_tool\tstrip_version\tpair_verification\tscan_path\n" + + "\n".join(cand) + "\n") +SIBFIX + +# sib_response [apex-defs] [extra JSON engines] [microsoft-category microsoft-result] +sib_response() { + python3 - "$SIB" "$@" <<'SIBRESP' +import json, pathlib, sys +root, name, ident, apex = pathlib.Path(sys.argv[1]), sys.argv[2], sys.argv[3], sys.argv[4] +defs = sys.argv[5] if len(sys.argv) > 5 and sys.argv[5] else "20261204" +extra = json.loads(sys.argv[6]) if len(sys.argv) > 6 and sys.argv[6] else {} +ms_category = sys.argv[7] if len(sys.argv) > 7 and sys.argv[7] else "undetected" +ms_result = sys.argv[8] if len(sys.argv) > 8 and sys.argv[8] else None +sha, size = (root / "sha" / name).read_text().split() +results = {"Microsoft": {"category": ms_category, "result": ms_result, + "engine_version": "1.26100", "engine_update": "20261205"}} +if apex != "absent": + results["APEX"] = {"category": apex, "result": "Malicious" if apex in ("malicious", "suspicious") else None, + "engine_version": "6.849", "engine_update": defs} +results.update(extra) +stats = {k: 0 for k in ("malicious", "suspicious", "undetected", "harmless", "timeout", + "confirmed-timeout", "failure", "type-unsupported")} +for answer in results.values(): + stats[answer["category"]] += 1 +stats["undetected"] += 60 +doc = {"meta": {"file_info": {"sha256": sha, "size": int(size)}}, + "data": {"id": ident, "type": "analysis", + "attributes": {"status": "completed", "stats": stats, "results": results}}} +(root / "responses" / f"{ident}.json").write_text(json.dumps(doc)) +SIBRESP +} + +# scenario : spec entries are object:apex-category[:defs[:extra-json[:ms-cat[:ms-result]]]] +# for the objects that differ from "APEX undetected"; every other object is clean. +scenario() { + local name="$1" output="" object + shift + rm -f "$SIB"/responses/*.json + for object in windows-amd64-unstripped windows-amd64-debug-stripped windows-amd64-stripped \ + linux-amd64-unstripped linux-amd64-debug-stripped linux-amd64-stripped; do + local spec="" entry + for entry in "$@"; do + [ "${entry%%=*}" = "$object" ] && spec="${entry#*=}" + done + local apex="undetected" defs="" extra="" ms_cat="" ms_res="" + if [ -n "$spec" ]; then + IFS='~' read -r apex defs extra ms_cat ms_res <<< "$spec" + fi + sib_response "$object" "$name-$object" "$apex" "$defs" "$extra" "$ms_cat" "$ms_res" + output="${output:+$output,}binaries/objects/$object=$(url_for "$name-$object")" + done + printf '%s' "$output" +} + +run_sib() { # action-output with-candidates(1|0) -> prints rc + rm -f "$SIB/binaries/vt-results.tsv" "$FIX/last.log" + local rc=0 sibling="" + [ "$2" = 1 ] && sibling=binaries/candidates.tsv + (cd "$SIB" && + PATH="$FIX/bin:$PATH" STUB_RESPONSES="$SIB/responses" VT_API_KEY=stub \ + VT_ANALYSIS="$1" VT_EXPECTED_SCAN_SET=binaries/scan-set.tsv \ + VT_ASSOCIATIONS=binaries/associations.tsv VT_RESULTS_PATH=binaries/vt-results.tsv \ + VT_ISOLATED_SIBLING_CANDIDATES="$sibling" \ + VT_REQUEST_INTERVAL_SECONDS=0 VT_POLL_TIMEOUT_SECONDS=2 VT_CURL_TIMEOUT_SECONDS=1 \ + MIN_ENGINES=50 bash "$GATE" > "$FIX/last.log" 2>&1) || rc=$? + echo "$rc" +} +SIB_RESULTS="$SIB/binaries/vt-results.tsv" + +# The v0.12.2-rc.1 case: APEX flags the unstripped Windows form only. +out="$(scenario isolated 'windows-amd64-unstripped=malicious')" +[ "$(run_sib "$out" 1)" = "0" ] || \ + fail "one engine flagging one form, with the same engine clean on both siblings, must pass the candidate stage: $(cat "$FIX/last.log")" +grep -q 'ISOLATED: objects/windows-amd64-unstripped flagged' "$FIX/last.log" || \ + fail "an isolated candidate must be reported as ISOLATED" +grep -q 'never shipped: APEX judged every sibling form clean on the same engine and definitions (engine 6.849, defs 20261204): objects/windows-amd64-debug-stripped=undetected, objects/windows-amd64-stripped=undetected' "$FIX/last.log" || \ + fail "the isolated report must name the engine, its definitions and every sibling's answer" +grep -Fq $'\tisolated\t' "$SIB_RESULTS" || fail "the isolated classification must be recorded" +grep -Fq 'APEX|malicious|Malicious|6.849|20261204' "$SIB_RESULTS" || \ + fail "the evidence must name the detecting engine, label, version and definitions" +grep -Fq 'APEX|6.849|20261204;objects/windows-amd64-debug-stripped=undetected;objects/windows-amd64-stripped=undetected' "$SIB_RESULTS" || \ + fail "the evidence must record the engine's answer for every sibling form" + +# The same verdict without the candidate manifest (the surface scan) blocks. +[ "$(run_sib "$out" 0)" != "0" ] || fail "without the candidate manifest a non-Microsoft detection must block" +grep -q 'BLOCKED: objects/windows-amd64-unstripped flagged' "$FIX/last.log" || \ + fail "the strict gate must report BLOCKED" +grep -Fq $'\thard\t' "$SIB_RESULTS" && ! grep -Fq $'\tisolated\t' "$SIB_RESULTS" || \ + fail "without the candidate manifest the evidence must record the verdict as hard, never isolated" + +sib_must_block() { # label diagnostic spec... + local label="$1" diagnostic="$2" + shift 2 + out="$(scenario "$label" "$@")" + [ "$(run_sib "$out" 1)" != "0" ] || fail "$label must block: $(cat "$FIX/last.log")" + grep -Fq "$diagnostic" "$FIX/last.log" || fail "$label must be diagnosable as: $diagnostic" + ! grep -q '^ISOLATED:' "$FIX/last.log" || fail "$label must not be reported as isolated" +} +sib_must_block sibling-other-defs 'BLOCKED: objects/windows-amd64-unstripped flagged' \ + 'windows-amd64-unstripped=malicious' 'windows-amd64-stripped=undetected~20261203' +sib_must_block sibling-other-version 'BLOCKED: objects/windows-amd64-unstripped flagged' \ + 'windows-amd64-unstripped=malicious' \ + 'windows-amd64-debug-stripped=undetected~~{"APEX":{"category":"undetected","result":null,"engine_version":"6.850","engine_update":"20261204"}}' +sib_must_block sibling-engine-absent 'BLOCKED: objects/windows-amd64-unstripped flagged' \ + 'windows-amd64-unstripped=malicious' 'windows-amd64-debug-stripped=absent' +sib_must_block sibling-engine-timeout 'BLOCKED: objects/windows-amd64-unstripped flagged' \ + 'windows-amd64-unstripped=malicious' 'windows-amd64-stripped=timeout' +sib_must_block two-forms-flagged 'BLOCKED: objects/windows-amd64-debug-stripped flagged' \ + 'windows-amd64-unstripped=malicious' 'windows-amd64-debug-stripped=malicious' +sib_must_block suspicious 'BLOCKED: objects/windows-amd64-unstripped flagged' \ + 'windows-amd64-unstripped=suspicious' +sib_must_block second-engine 'BLOCKED: objects/windows-amd64-unstripped flagged' \ + 'windows-amd64-unstripped=malicious~~{"Kaspersky":{"category":"malicious","result":"Trojan.Generic","engine_version":"22","engine_update":"20261204"}}' +sib_must_block sibling-microsoft-ml 'BLOCKED: objects/windows-amd64-unstripped flagged' \ + 'windows-amd64-unstripped=malicious' 'windows-amd64-stripped=undetected~~~malicious~Trojan:Script/Wacatac.C!ml' +sib_must_block microsoft-signature 'BLOCKED: objects/windows-amd64-unstripped flagged' \ + 'windows-amd64-unstripped=undetected~~~malicious~Trojan:Win32/Emotet' +sib_must_block two-isolated 'the policy allows at most one per release' \ + 'windows-amd64-unstripped=malicious' 'linux-amd64-unstripped=malicious' + +# The manifest must describe exactly the scanned bytes. +cp "$SIB/binaries/candidates.tsv" "$SIB/binaries/candidates.clean.tsv" +sed -i.bak '$d' "$SIB/binaries/candidates.tsv" && rm -f "$SIB/binaries/candidates.tsv.bak" +out="$(scenario isolated 'windows-amd64-unstripped=malicious')" +[ "$(run_sib "$out" 1)" != "0" ] || fail "a candidate manifest missing a scanned object must block" +grep -Fq 'candidate manifest does not cover every scanned candidate' "$FIX/last.log" || \ + fail "an incomplete candidate manifest must be diagnosable" +mv "$SIB/binaries/candidates.clean.tsv" "$SIB/binaries/candidates.tsv" + +echo 'PASS: VT gate is exact-set and content-bound; tolerates exactly one Microsoft !ml verdict; at the candidate stage at most one isolated-sibling candidate; engine count is evidence, not a gate' diff --git a/tests/test_vt_release_notes_contract.sh b/tests/test_vt_release_notes_contract.sh index 6360a2c28e..853d4667c2 100644 --- a/tests/test_vt_release_notes_contract.sh +++ b/tests/test_vt_release_notes_contract.sh @@ -33,6 +33,7 @@ result_fields = ( "total_engines", "malicious", "suspicious", "analysis_id", "microsoft_category", "microsoft_result", "policy_classification", "microsoft_engine_version", "microsoft_engine_update", "virustotal_url", + "detections", "isolated_evidence", ) selection_fields = ( "target", "selected_variant", "selected_path", "selected_sha256", @@ -104,6 +105,8 @@ for target in targets: "policy_classification": classification, "microsoft_engine_version": "1.1.1", "microsoft_engine_update": "20260813", "virustotal_url": f"https://www.virustotal.com/gui/file/{sha}/detection", + "detections": "" if clean else "Microsoft|malicious|Trojan:Win32/Wacatac.B!ml|1.1.1|20260813", + "isolated_evidence": "", }) result_by_pair = {(row["target"], row["variant"]): result for row, result in zip(candidates, results)} @@ -140,11 +143,11 @@ for target in targets: write(root / "release-candidates.tsv", "cbm-release-candidates-v1", {"targets": 8, "candidates": 24}, candidate_fields, candidates) -write(root / "virustotal-candidate-results.tsv", "cbm-virustotal-results-v2", +write(root / "virustotal-candidate-results.tsv", "cbm-virustotal-results-v3", {"scan_objects": 24, "associations": 24, "min_engines_policy": 50, "min_completed_engines": 61, "max_completed_engines": 61}, result_fields, results) write(root / "release-selection.tsv", "cbm-release-selection-v1", - {"policy": "virustotal-v2", "targets": 8, "candidates": 24}, + {"policy": "virustotal-v3", "targets": 8, "candidates": 24}, selection_fields, selections) PY @@ -231,6 +234,86 @@ if run_notes "$FIX/current.md" "$FIX/tampered.md"; then fi mv "$FIX/evidence/release-selection.clean.tsv" "$FIX/evidence/release-selection.tsv" +# How many engines answered is VirusTotal fleet availability, not a verdict: +# the gate and the selector record the count and never gate on it. A shipped, +# clean binary judged by 49 engines (as on the v0.12.2-rc.1 run) must publish +# its notes, and the count must appear in the reported range. +cp "$FIX/evidence/virustotal-candidate-results.tsv" "$FIX/evidence/vt-results.clean.tsv" +python3 - "$FIX/evidence/virustotal-candidate-results.tsv" <<'PY' +import hashlib, pathlib, sys +p = pathlib.Path(sys.argv[1]) +sha = hashlib.sha256(b"linux-arm64:stripped").hexdigest() +lines = p.read_text().splitlines(keepends=True) +hits = [i for i, line in enumerate(lines) if line.startswith(f"objects/{sha}\t")] +assert len(hits) == 1, "fixture row for the shipped linux-arm64 binary not found" +cells = lines[hits[0]].split("\t") +assert cells[4] == "61" and cells[11] == "clean", cells +cells[4] = "49" +lines[hits[0]] = "\t".join(cells) +p.write_text("".join(lines)) +PY +run_notes "$FIX/current.md" "$FIX/low-engines.md" || \ + fail "a clean shipped binary judged by 49 engines must not fail the release notes" +grep -q 'decisive engines: 49' "$FIX/low-engines.md" || \ + fail "the 49-engine count must be reported, not hidden" +mv "$FIX/evidence/vt-results.clean.tsv" "$FIX/evidence/virustotal-candidate-results.tsv" + +# Policy cbm-vt-candidate-selection-v2: the release's one isolated candidate +# (never shipped) is the exception to "notes report the shipped binary only": +# it was a hard detection that did not block, so the notes name it with its +# engine, label, definitions and link. Shipping it fails closed. +cp "$FIX/evidence/virustotal-candidate-results.tsv" "$FIX/evidence/vt-results.clean.tsv" +cp "$FIX/evidence/release-selection.tsv" "$FIX/evidence/release-selection.clean.tsv" +isolate() { # variant: mark that linux-arm64 form isolated in results and selection + python3 - "$FIX/evidence" "$1" <<'PY' +import hashlib, pathlib, sys +root, variant = pathlib.Path(sys.argv[1]), sys.argv[2] +sha = hashlib.sha256(f"linux-arm64:{variant}".encode()).hexdigest() +siblings = sorted( + "objects/" + hashlib.sha256(f"linux-arm64:{v}".encode()).hexdigest() + for v in ("unstripped", "debug-stripped", "stripped") if v != variant +) +results = root / "virustotal-candidate-results.tsv" +lines = results.read_text().splitlines(keepends=True) +row = next(i for i, line in enumerate(lines) if line.startswith(f"objects/{sha}\t")) +cells = lines[row].rstrip("\n").split("\t") +cells[6] = "1" # malicious +cells[11] = "isolated" # policy_classification +cells[15] = "APEX|malicious|Malicious|6.849|20261204" +cells[16] = ";".join(["APEX|6.849|20261204"] + [f"{s}=undetected" for s in siblings]) +lines[row] = "\t".join(cells) + "\n" +results.write_text("".join(lines)) +selection = root / "release-selection.tsv" +text = selection.read_text() +key = variant.replace("-", "_") +lines = text.splitlines(keepends=True) +header = next(i for i, line in enumerate(lines) if line.startswith("target\t")) +fields = lines[header].rstrip("\n").split("\t") +for i in range(header + 1, len(lines)): + cells = lines[i].rstrip("\n").split("\t") + if cells[0] == "linux-arm64": + cells[fields.index(f"{key}_classification")] = "isolated" + lines[i] = "\t".join(cells) + "\n" +selection.write_text("".join(lines)) +PY +} +isolate unstripped +run_notes "$FIX/current.md" "$FIX/isolated.md" || fail "an isolated, non-shipped candidate must not fail the release notes" +sha_iso="$(python3 -c 'import hashlib;print(hashlib.sha256(b"linux-arm64:unstripped").hexdigest())')" +grep -Fq "**Not shipped, disclosed:** the \`linux-arm64\` unstripped candidate (\`$sha_iso\`) was flagged by a single engine, APEX (\`Malicious\`, engine 6.849, definitions 20261204)" "$FIX/isolated.md" || \ + fail "the isolated candidate must be disclosed with product, form, sha256, engine, label and definitions" +grep -Fq "policy \`cbm-vt-candidate-selection-v2\`" "$FIX/isolated.md" || fail "the disclosure must name the policy" +grep -Fq "(https://www.virustotal.com/gui/file/$sha_iso/detection)" "$FIX/isolated.md" || \ + fail "the disclosure must link the isolated candidate's VirusTotal report" +cp "$FIX/evidence/vt-results.clean.tsv" "$FIX/evidence/virustotal-candidate-results.tsv" +cp "$FIX/evidence/release-selection.clean.tsv" "$FIX/evidence/release-selection.tsv" +isolate stripped +if run_notes "$FIX/current.md" "$FIX/isolated-shipped.md"; then + fail "a selection whose shipped form is isolated must fail closed" +fi +mv "$FIX/evidence/vt-results.clean.tsv" "$FIX/evidence/virustotal-candidate-results.tsv" +mv "$FIX/evidence/release-selection.clean.tsv" "$FIX/evidence/release-selection.tsv" + cat > "$FIX/reversed.md" <<'EOF' stale reversed data