Repository Public
1#!/usr/bin/env python32# =============================================================================3# SP BOUCHER | SOFTWARE & RESEARCH4# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# Project : QYVORA8# File : security/audit/runners/timing.py9# Module : Security10# Repository : https://git.spboucher.ai/qyvora11# Project Website : Not specified12# Created : 2026-12-0413# Last Modified : 2026-12-0414#15# Author : Simon-Pierre Boucher16# Position : Professor of Finance17# Institution : Université du Québec en Outaouais (UQO)18# Organization : SP Boucher19# Website : https://spboucher.ai20# Git : https://git.spboucher.ai21#22# Preferred Contact: contact@spboucher.ai23# Development : dev@spboucher.ai24# Support : support@spboucher.ai25# Security/Admin : admin@spboucher.ai26#27# Copyright (c) 202628# Simon-Pierre Boucher29# All rights reserved where applicable. This file is governed by the30# applicable project license, copyright notices and relevant law.31# Existing third-party rights and notices remain unaffected.32#33# License : None specified (no license file in this repository)34#35# Do not embed credentials, private keys, access tokens,36# certificates or confidential personal information.37#38# =============================================================================39# END OF SP BOUCHER SOURCE HEADER40# =============================================================================4142"""Timing and side-channel checks: (1) conditional branches in the compiled code of the functions43that process secrets, (2) dudect-style statistical timing test (`qytiming`).4445Both are evidence, not proof: see the coverage statements returned with the results.46"""4748from __future__ import annotations4950import json51import sys52import time53from pathlib import Path5455sys.path.insert(0, str(Path(__file__).resolve().parents[1]))5657from lib import build # noqa: E40258from lib.common import (FAILED, NOT_RUN, POLICIES, RUN, Context, finding, load_json, not_run, tool_result, # noqa: E40259 write_json)60from lib.machinecode import functions, object_files # noqa: E4026162THRESHOLD = 4.5636465def machine_code(ctx: Context) -> dict:66 """Branch counts in the release objects of the Swift package (macOS build, this toolchain)."""67 start = time.time()68 policy = load_json(POLICIES / "constant-time-functions.json", {})69 exe, error = build.build_product("qytiming")70 if exe is None:71 return tool_result(tool="ct-machine-code", category="timing", status=FAILED, reason="build of the audit package failed: " + error)72 table: dict[str, dict] = {}73 missing_modules = []74 for module in policy.get("modules", []):75 objs = object_files(build.PRODUCT_SCRATCH, module)76 if not objs:77 missing_modules.append(module)78 for obj in objs:79 for name, v in functions(obj).items():80 entry = table.setdefault(name, {"instructions": 0, "conditional_branches": 0})81 entry["instructions"] += v["instructions"]82 entry["conditional_branches"] += v["conditional_branches"]83 if not table:84 return not_run("ct-machine-code", "timing", "no release object file of the engine modules found under " + str(build.PRODUCT_SCRATCH))85 return _evaluate(ctx, policy, table, tool="ct-machine-code", start=start, raw_name="ct-machine-code.json",86 command="otool -tV on the release objects of " + ", ".join(policy.get("modules", [])),87 what="arm64 release code of the Swift package built on macOS with this toolchain (the iOS application binary is checked "88 "by ct-machine-code-ios when the archive is built)",89 extra={"modules_without_objects": missing_modules})909192def machine_code_ios(ctx: Context) -> dict:93 """The same check on the iOS application binary of the archive built by the ipa-build step (symbols from its dSYM)."""94 start = time.time()95 policy = load_json(POLICIES / "constant-time-functions.json", {})96 try:97 from runners import ipa_build98 except Exception as error: # noqa: BLE00199 return not_run("ct-machine-code-ios", "timing", f"ipa_build runner unavailable: {error}")100 binary = ipa_build.APP / "Qyvora"101 dwarf = ipa_build.DSYM / "Contents" / "Resources" / "DWARF" / "Qyvora"102 if not binary.exists() or not dwarf.exists():103 return not_run("ct-machine-code-ios", "timing", "no application archive with its dSYM (the ipa-build step did not produce one in this run)")104 marker = load_json(ipa_build.MARKER, {}) or {}105 table = functions(binary, symbols=dwarf)106 if not table:107 return tool_result(tool="ct-machine-code-ios", category="timing", status=FAILED, reason="no symbol read from the dSYM of the archive")108 return _evaluate(ctx, policy, table, tool="ct-machine-code-ios", start=start, raw_name="ct-machine-code-ios.json",109 command=f"otool -tV {binary} with the symbols of its dSYM",110 what="arm64 code of the iOS application binary (unsigned Release archive built by xcodebuild in this run, symbols from its dSYM)",111 extra={"archive_built_from": marker})112113114def _evaluate(ctx: Context, policy: dict, table: dict, *, tool: str, start: float, raw_name: str, command: str, what: str, extra: dict) -> dict:115 tests, findings, rows = [], [], []116 for rule in policy.get("functions", []):117 matches = {n: v for n, v in table.items() if rule["match"] in n}118 if not matches:119 rows.append({"function": rule["match"], "status": "not visible (inlined or absent)", "max": rule["max"], "why": rule["why"]})120 tests.append({"area": "timing", "name": "machine code: " + rule["match"], "algorithm": "compiled code", "parameter_set": "",121 "cases": 0, "passed": 0, "failed": 0, "skipped": 1, "note": "NOT RUN: symbol not visible (inlined into its callers)"})122 continue123 worst = max(v["conditional_branches"] for v in matches.values())124 ok = worst <= rule["max"]125 rows.append({"function": rule["match"], "conditional_branches": worst, "max": rule["max"], "symbols": len(matches),126 "status": "ok" if ok else "ABOVE THE REVIEWED MAXIMUM", "why": rule["why"]})127 tests.append({"area": "timing", "name": "machine code: " + rule["match"], "algorithm": "compiled code", "parameter_set": "",128 "cases": 1, "passed": 1 if ok else 0, "failed": 0 if ok else 1, "skipped": 0,129 "note": f"{worst} conditional branch(es), reviewed maximum {rule['max']}: {rule['why']}"})130 if not ok:131 findings.append(finding(132 id=("QY-CTMC-IOS-" if tool.endswith("ios") else "QY-CTMC-") + rule["match"].split("(")[0].split(".")[-1].upper(),133 title=f"Compiled code of {rule['match'].rstrip('(')} has {worst} conditional branches (reviewed maximum {rule['max']})",134 severity="high", tool=tool, area="crypto", cwe="CWE-208", masvs="MASVS-CRYPTO-1",135 cvss_vector="CVSS:3.1/AV:L/AC:H/PR:L/UI:N/S:U/C:H/I:N/A:N", cvss_score=4.7,136 location="security/policies/constant-time-functions.json", rule=rule["match"],137 description="The release build of a function that processes secret values contains more conditional branch instructions "138 "than the count accepted after review. The compiler may have turned a branch-free expression into a branch "139 "that depends on secret data (as happened with the secp256k1 carry chain, QYV-AUD-002).",140 recommendation="Disassemble the function, identify what each new branch tests; rewrite the expression with bit arithmetic "141 "if it depends on a secret, otherwise raise the reviewed maximum in the policy file with the justification.",142 evidence=json.dumps(matches)))143 raw = ctx.raw_path(raw_name)144 engine_only = {n: v for n, v in table.items() if "Qyvora" in n}145 write_json(raw, {"swift": build.swift_version(), "rows": rows, "all_functions": engine_only})146 checked = sum(1 for r in rows if "conditional_branches" in r)147 metrics = {"functions_in_policy": len(rows), "functions_checked": checked, "not_visible": len(rows) - checked,148 "above_maximum": len(findings), "rows": rows}149 metrics.update(extra)150 return tool_result(151 tool=tool, category="timing", status=RUN, version=build.swift_version(), command=command, duration_s=time.time() - start,152 coverage="Counts conditional branch instructions in the functions listed in security/policies/constant-time-functions.json: "153 + what + ". A count at or below the reviewed maximum means no new branch appeared; it does not prove the absence of "154 "other leaks (variable-time instructions, memory access patterns, functions inlined into callers that are not listed).",155 metrics=metrics, tests=tests, findings=findings, artifacts=["security/reports/raw/" + raw_name])156157158def _run_qytiming(exe_cmd: list[str], scale: float, only: list[str] | None, out: Path, node: str | None,159 extra: list[str] | None = None) -> tuple[dict | None, str]:160 args = ["--scale", str(scale)] + (extra or [])161 if only:162 args += ["--only", ",".join(only)]163 if node:164 remote_json = "security/reports/raw/" + out.name.replace(".json", "-node.json")165 code, o, e, _ = build.remote(node, "mkdir -p security/reports/raw && " + " ".join(exe_cmd + args + ["--json", remote_json]), timeout=7200)166 if code != 0:167 return None, (o + e)[-1500:]168 if not build.fetch_from_node(node, remote_json, out):169 return None, "could not fetch the result file from " + node170 else:171 from lib.common import run_cmd172 code, o, e, _ = run_cmd(exe_cmd + args + ["--json", str(out)], timeout=7200)173 if code != 0:174 return None, (o + e)[-1500:]175 return load_json(out), ""176177178def _internals_command(node: str | None) -> tuple[list[str] | None, str]:179 """Builds qytiming with QY_TIMING_INTERNALS=1 and testability (its own scratch directory); returns the command."""180 if node:181 scratch = "security/tests/.build-internals"182 flags = " ".join(build.INTERNALS_ARGS)183 code, o, e, _ = build.remote(node, f"swift build -c release {flags} --package-path security/tests --scratch-path {scratch} "184 "--product qytiming 2>&1 | tail -5", timeout=3600,185 env={"QY_AUDIT_ONLY": "qytiming", **build.INTERNALS_ENV})186 if code != 0:187 return None, (o + e)[-800:]188 return ["env", "QY_AUDIT_ONLY=qytiming", "QY_TIMING_INTERNALS=1",189 f"$(QY_TIMING_INTERNALS=1 QY_AUDIT_ONLY=qytiming swift build -c release {flags} --package-path security/tests "190 f"--scratch-path {scratch} --show-bin-path)/qytiming"], ""191 exe, error = build.build_product("qytiming", scratch=build.INTERNALS_SCRATCH, extra_args=build.INTERNALS_ARGS, env=build.INTERNALS_ENV)192 if exe is None:193 return None, error194 return [str(exe)], ""195196197def dudect(ctx: Context) -> dict:198 start = time.time()199 nodes = ctx.options.get("nodes") or []200 node = ctx.options.get("timing_node") or (nodes[0] if nodes and ctx.full else None)201 scale = float(ctx.options.get("timing_scale") or (1.0 if ctx.full else 0.15))202 where = "this machine"203 if node:204 load = build.node_load(node)205 if load is None:206 return not_run("dudect-timing", "timing", f"node {node} unreachable")207 ok, msg = build.sync_to_node(node)208 if not ok:209 return tool_result(tool="dudect-timing", category="timing", status=FAILED, reason=f"rsync to {node} failed: {msg}")210 code, o, e, _ = build.remote(node, "swift build -c release --package-path security/tests --product qytiming 2>&1 | tail -5", timeout=3600,211 env={"QY_AUDIT_ONLY": "qytiming"})212 if code != 0:213 return tool_result(tool="dudect-timing", category="timing", status=FAILED, reason=f"build on {node} failed: {(o + e)[-800:]}")214 exe_cmd = ["env", "QY_AUDIT_ONLY=qytiming", "$(QY_AUDIT_ONLY=qytiming swift build -c release --package-path security/tests --show-bin-path)/qytiming"]215 where = f"{node} (1-minute load {load:.2f} before the run)"216 else:217 exe, error = build.build_product("qytiming")218 if exe is None:219 return tool_result(tool="dudect-timing", category="timing", status=FAILED, reason="build failed: " + error)220 exe_cmd = [str(exe)]221 first, error = _run_qytiming(exe_cmd, scale, None, ctx.raw_path("qytiming.json"), node)222 if first is None:223 return tool_result(tool="dudect-timing", category="timing", status=FAILED, reason="qytiming failed: " + error)224 results = {r["name"]: r for r in first["results"]}225 flagged = [n for n, r in results.items() if r["exceeds_threshold"] and not n.startswith(("control-", "info-"))]226 confirm = {}227 if flagged:228 # a noisy machine produces isolated exceedances: a target is reported only when a second run with another seed agrees229 second, error = _run_qytiming(exe_cmd, scale, flagged, ctx.raw_path("qytiming-confirm.json"), node)230 confirm = {r["name"]: r for r in (second or {}).get("results", [])}231232 # Ed25519 internals (chosen scalars and field elements): a second build with testability. The verdict is taken233 # with the data-independent-timing flag set, as the production entry points set it before reaching these234 # functions; the same targets without the flag are informational (`info-nodit-…`).235 internals_note = ""236 internals_cmd, error = _internals_command(node)237 if internals_cmd is None:238 internals_note = "NOT RUN: build of the internals variant of qytiming failed: " + error239 else:240 with_dit, error = _run_qytiming(internals_cmd, scale, None, ctx.raw_path("qytiming-internals-dit.json"), node, ["--internals", "--dit"])241 if with_dit is None:242 internals_note = "NOT RUN: internals run failed: " + error243 else:244 internal = {r["name"]: r for r in with_dit["results"]}245 internal_controls = {"internals-" + n: r for n, r in internal.items() if n.startswith("control-")}246 internal = {n: r for n, r in internal.items() if not n.startswith("control-")}247 flagged_internal = [n for n, r in internal.items() if r["exceeds_threshold"] and not n.startswith("info-")]248 if flagged_internal:249 again, error = _run_qytiming(internals_cmd, scale, flagged_internal, ctx.raw_path("qytiming-internals-confirm.json"), node, ["--dit"])250 confirm.update({r["name"]: r for r in (again or {}).get("results", [])})251 flagged += flagged_internal252 results.update(internal)253 for n, r in internal_controls.items():254 r = dict(r)255 r["name"] = n256 results["control-" + n if not n.startswith("control-") else n] = r257 if not with_dit.get("dit_enabled"):258 internals_note = "the processor has no data-independent-timing flag: the internals targets are informational on this machine"259 without, error = _run_qytiming(internals_cmd, scale, None, ctx.raw_path("qytiming-internals-nodit.json"), node, ["--internals"])260 for r in (without or {}).get("results", []):261 if r["name"].startswith("info-nodit-") or (r["name"].startswith("info-public-") and r["name"] not in results):262 results[r["name"]] = r263 tests, findings = [], []264 controls_ok = True265 for name, r in results.items():266 t = r["t_max"]267 again = confirm.get(name)268 if name.endswith("control-leaky-compare") or name.startswith("control-positive-"):269 ok = abs(t) > THRESHOLD270 controls_ok &= ok271 note = f"positive control: |t| = {abs(t):.1f} (must exceed {THRESHOLD}: the harness detects a real leak)"272 elif name.endswith("control-same-class") or name.startswith("control-negative-"):273 ok = abs(t) <= THRESHOLD274 controls_ok &= ok275 note = f"negative control: |t| = {abs(t):.2f} (must stay below {THRESHOLD})"276 elif name.startswith("info-"):277 ok = True278 note = f"informational (not a pass/fail check: public data, or the preparation of the inputs, differs between the classes): max |t| = {abs(t):.1f}, " \279 f"means {r['mean_a_ns']} / {r['mean_b_ns']} ns — {r['expectation']}"280 else:281 confirmed = r["exceeds_threshold"] and again is not None and again["exceeds_threshold"]282 ok = not confirmed283 note = f"max |t| = {abs(t):.2f} (raw {r['t_raw']:+.2f}, crop p{r['crop_of_max']}); {r['samples_a']}+{r['samples_b']} measurements; " \284 f"means {r['mean_a_ns']} / {r['mean_b_ns']} ns"285 if r["exceeds_threshold"]:286 note += f"; second run: max |t| = {abs(again['t_max']):.2f}" if again else "; second run failed"287 note += " — CONFIRMED" if confirmed else " — not confirmed by the second run (noise)"288 if confirmed:289 known = (load_json(POLICIES / "timing-known.json", {}) or {}).get("targets", {}).get(name, {})290 findings.append(finding(291 id=known.get("finding") or "QY-TIMING-" + name.upper(), title=f"Timing distributions differ for {r['description']}",292 # unknown confirmed difference on an operation that handles a private key: high until analysed (it blocks the gate)293 severity=known.get("severity") or ("high" if name.startswith(("secp256k1", "ecdsa", "schnorr", "mlkem", "ed25519", "slip10")) else "medium"),294 tool="dudect-timing", area="crypto", cwe="CWE-208", masvs="MASVS-CRYPTO-1",295 cvss_vector="CVSS:3.1/AV:L/AC:H/PR:L/UI:N/S:U/C:H/I:N/A:N", cvss_score=4.7, location="security/tests/Sources/qytiming/main.swift",296 rule=name,297 description=f"Welch t-test between '{r['class_a']}' and '{r['class_b']}' exceeds {THRESHOLD} in two independent runs "298 f"(|t| = {abs(t):.1f} then {abs(again['t_max']):.1f}; means {r['mean_a_ns']} ns / {r['mean_b_ns']} ns). "299 "The duration of the operation depends on the class of its input.",300 recommendation="Inspect the machine code of the operation for data-dependent branches or memory accesses "301 "(security/audit/lib/machinecode.py), fix, and re-run on a quiet machine.",302 evidence=json.dumps({"first": r, "second": again})))303 tests.append({"area": "timing", "name": name, "algorithm": r["description"], "parameter_set": f"{r['class_a']} / {r['class_b']}",304 "cases": r["samples_a"] + r["samples_b"], "passed": (r["samples_a"] + r["samples_b"]) if ok else 0,305 "failed": 0 if ok else 1, "skipped": 0, "seed": first.get("seed"), "note": note,306 "t_max": t, "t_raw": r["t_raw"], "mean_a_ns": r["mean_a_ns"], "mean_b_ns": r["mean_b_ns"]})307 if internals_note.startswith("NOT RUN"):308 tests.append({"area": "timing", "name": "ed25519 internals (chosen scalars and field elements)", "algorithm": "Ed25519", "parameter_set": "",309 "cases": 0, "passed": 0, "failed": 0, "skipped": 1, "note": internals_note})310 status = RUN if controls_ok else FAILED311 return tool_result(312 tool="dudect-timing", category="timing", status=status, version="qytiming (security/tests/Sources/qytiming)",313 reason="" if controls_ok else "a control did not behave as expected: the measurements of this run are not trustworthy",314 command=" ".join(exe_cmd) + f" --scale {scale}", duration_s=time.time() - start,315 coverage="dudect-style test: two input classes timed in random interleaved order, Welch t-test on raw and percentile-cropped "316 f"measurements, threshold |t| > {THRESHOLD}, confirmed by a second run. Both classes read their inputs through the same working "317 "buffers, from one block of memory whose slots are dealt to the classes at random, and the timed region is separated from "318 "the preparation of the inputs by a serialising barrier (dsb sy, isb), so that only the contents differ (QYV-AUD-005). "319 "Controls: an early-exit comparison and a decapsulation followed by a loop whose length is a byte of the shared secret "320 "must be detected; identical contents, two sets of random AES keys and two sets of valid ML-KEM ciphertexts must not "321 "(the asymmetric preparation that produced QYV-AUD-005 is kept as an informational measurement). Operations: ConstantTime.equal (position and number of differing bits), AES-GCM and "322 "ChaCha20-Poly1305 tag verification, AES key dependence, secp256k1 scalar multiplication, ECDSA and BIP-340 signing, "323 "ML-KEM decapsulation (valid against invalid ciphertexts; one ciphertext against many under one key), Ed25519 public-key "324 "derivation and signing (fixed against random seeds, fixed against random nonces) and SLIP-0010 derivation through the "325 "public interface; and, in a second build of the tool with testability, the Ed25519 internals with chosen operands "326 "(base-point and variable-base multiplication with scalars 0, 1, 2^252, 2^256-1 and a repeated scalar; field "327 "multiplication, squaring, inversion and canonical encoding; scalar reduction and multiply-add), measured with the "328 "data-independent-timing flag set as the production entry points set it (verdict) and without it (informational, "329 "`info-nodit-`). Two informational "330 "measurements compare one ML-KEM key against many: they include the public matrix expansion (rejection sampling on the "331 "public seed, variable-time by specification) and are reported without verdict. Not tested this way: ML-DSA and "332 "SLH-DSA signing (ML-DSA uses rejection sampling whose iteration count is public by design; SLH-DSA is hash-based), "333 "Argon2id and HKDF (their running time depends on public parameters and lengths; Argon2id's memory addressing is "334 "data-dependent by specification), X25519 (CryptoKit). Statistical evidence on one machine and one build: not a proof; "335 "Swift offers no constant-time guarantee; no power or electromagnetic analysis.",336 metrics={"machine": first.get("host"), "where": where, "scale": scale, "seed": first.get("seed"), "threshold": THRESHOLD,337 "dit_supported": first.get("dit_supported"), "dit_enabled": first.get("dit_enabled"),338 "serialised_timed_region": first.get("serialised_timed_region"),339 "targets": len(results), "exceeded_once": flagged, "confirmed": [f["rule"] for f in findings],340 "ed25519_internals": internals_note or "run (second build with QY_TIMING_INTERNALS=1 and -enable-testing)",341 "quick_mode_note": "" if ctx.full else "quick mode: reduced sample counts on a machine that is not quiet; the full run uses a cluster node"},342 tests=tests, findings=findings, artifacts=["security/reports/raw/qytiming.json"])343344345def run(ctx: Context) -> list[dict]:346 return [machine_code(ctx), dudect(ctx)]347348349if __name__ == "__main__":350 context = Context("full" if "--full" in sys.argv else "quick")351 print(json.dumps(run(context), indent=2))352