Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project : QYVORA7# File : security/audit/runners/sanitizers.py8# Module : Security9# Repository : https://git.spboucher.ai/qyvora10# Project Website : Not specified11# Created : 2026-12-0412# Last Modified : 2026-12-0413#14# Author : Simon-Pierre Boucher15# Position : Professor of Finance16# Institution : Université du Québec en Outaouais (UQO)17# Organization : SP Boucher18# Website : https://spboucher.ai19# Git : https://git.spboucher.ai20#21# Preferred Contact: contact@spboucher.ai22# Development : dev@spboucher.ai23# Support : support@spboucher.ai24# Security/Admin : admin@spboucher.ai25#26# Copyright (c) 202627# Simon-Pierre Boucher28# All rights reserved where applicable. This file is governed by the29# applicable project license, copyright notices and relevant law.30# Existing third-party rights and notices remain unaffected.31#32# License : None specified (no license file in this repository)33#34# Do not embed credentials, private keys, access tokens,35# certificates or confidential personal information.36#37# =============================================================================38# END OF SP BOUCHER SOURCE HEADER39# =============================================================================4041"""Sanitizer runner: test suites rebuilt and run under AddressSanitizer, ThreadSanitizer and UBSan.4243Heavy (every suite is rebuilt with instrumentation and runs several times slower): full mode only. With44ctx.options["nodes"] the first reachable node does the work (the tree is copied to <node>:qyvora-build/audit-fuzz/),45otherwise the local machine.4647What each sanitizer really covers here:48 address memory errors in the unsafe-pointer code of the engine (UnsafeMutablePointer, withUnsafeBytes, mmap) and49 in the C libraries it calls; Swift's own bounds and overflow checks are traps, found by fuzzing instead.50 thread data races in the actor-based services (wallet, networking, vault) and in the concurrent SLH-DSA code.51 undefined accepted by the toolchain, but UBSan instruments C-family code only: for a pure-Swift package it checks52 almost nothing. Run and reported for completeness, not as evidence about the Swift code.5354Standalone: python3 security/audit/runners/sanitizers.py [--full] [--nodes "M3U96b"] [--only address,thread]55"""5657from __future__ import annotations5859import json60import os61import re62import sys63import threading64import time65from pathlib import Path6667sys.path.insert(0, str(Path(__file__).resolve().parents[1]))68from lib.common import (FAILED, NOT_RUN, RAW, REPO, RUN, Context, apply_triage, finding, not_run, rel, run_cmd, # noqa: E40269 tool_result, write_json)7071REMOTE_DIR = "qyvora-build/audit-fuzz"7273# (sanitizer, package: "audit" = security/tests, "root" = the engine, test filter)74PLAN = [75 ("address", "audit", "FuzzReplayTests"),76 ("address", "root", "QyvoraCoreTests"),77 ("address", "root", "QyvoraBitcoinTests"),78 ("address", "root", "QyvoraEthereumTests"),79 ("address", "root", "QyvoraSecp256k1Tests"),80 ("address", "root", "QyvoraSymmetricTests"),81 ("address", "root", "QyvoraKeccakTests"),82 ("address", "root", "QyvoraMLKEMTests"),83 ("address", "root", "QyvoraStorageTests"),84 ("address", "root", "QyvoraVaultTests"),85 ("address", "root", "QyvoraIdentityTests"),86 ("address", "root", "QyvoraRecoveryTests"),87 ("address", "root", "QyvoraEd25519Tests"),88 ("address", "root", "QyvoraSolanaTests"),89 ("address", "root", "QyvoraTronTests"),90 ("thread", "root", "QyvoraWalletTests"),91 ("thread", "root", "QyvoraNetworkingTests"),92 ("thread", "root", "QyvoraVaultTests"),93 ("thread", "root", "QyvoraSLHDSATests"),94 ("thread", "root", "QyvoraEd25519Tests"),95 ("thread", "root", "QyvoraSolanaTests"),96 ("thread", "root", "QyvoraTronTests"),97 ("undefined", "audit", "FuzzReplayTests"),98 ("undefined", "root", "QyvoraSecp256k1Tests"),99 ("undefined", "root", "QyvoraSymmetricTests"),100 ("undefined", "root", "QyvoraEd25519Tests"),101]102103REPORT_PATTERNS = [104 ("address", re.compile(r"ERROR: AddressSanitizer: ([^\n]+)")),105 ("thread", re.compile(r"WARNING: ThreadSanitizer: ([^\n]+)")),106 ("undefined", re.compile(r"([^\s:]+:\d+:\d+): runtime error: ([^\n]+)")),107]108SUMMARY = re.compile(r"SUMMARY: (\w+Sanitizer): ([^\n]+)")109TESTS_RUN = re.compile(r"Test run with (\d+) tests? in (\d+) suites? (passed|failed)")110XCTEST_RUN = re.compile(r"Executed (\d+) tests?, with (\d+) failures?")111112113def command(sanitizer: str, package: str, flt: str) -> str:114 path = "security/tests" if package == "audit" else "."115 scratch = f"{path}/.build-{sanitizer}"116 return (f"swift test -c release --sanitize={sanitizer} --filter {flt} --package-path {path} --scratch-path {scratch} 2>&1")117118119def parse(output: str) -> dict:120 tests = failed_run = 0121 for m in TESTS_RUN.finditer(output):122 tests += int(m.group(1))123 if m.group(3) == "failed":124 failed_run += 1125 issues = len(re.findall(r"✘ Test .* recorded an issue", output))126 reports = []127 for kind, pattern in REPORT_PATTERNS:128 for m in pattern.finditer(output):129 reports.append({"sanitizer": kind, "text": " ".join(m.groups())[:300]})130 summaries = [f"{a}: {b}"[:300] for a, b in SUMMARY.findall(output)]131 return {"tests": tests, "failed_runs": failed_run, "issues": issues, "reports": reports, "summaries": summaries}132133134def run_suite(runner, sanitizer: str, package: str, flt: str, timeout: int) -> dict:135 start = time.time()136 code, out, err, _ = runner(command(sanitizer, package, flt), timeout)137 text = out + err138 parsed = parse(text)139 if code == 124:140 state = "TIMEOUT"141 elif code != 0 and "Test run" not in text:142 state = "BUILD FAILED" # nothing ran: the instrumented build (or the toolchain option) failed143 elif code == 0 and not parsed["reports"]:144 state = "PASSED"145 else:146 state = "FAILED"147 log = RAW / "sanitizers" / f"{sanitizer}-{flt}.log"148 log.parent.mkdir(parents=True, exist_ok=True)149 log.write_text(text[-400_000:])150 return {"sanitizer": sanitizer, "package": package, "suite": flt, "state": state, "exit": code,151 "seconds": round(time.time() - start, 1), "log": rel(log), **parsed}152153154def run(ctx: Context) -> dict:155 start = time.time()156 coverage = ("AddressSanitizer on the fuzz-replay tests and the parser/crypto/storage suites; ThreadSanitizer on the "157 "actor services and the concurrent SLH-DSA suite; both on the Ed25519, Solana and TRON suites; UBSan "158 "accepted but nearly void for pure Swift. "159 "Sanitizers see only what the tests execute.")160 if not ctx.full:161 return not_run("sanitizers", "dynamic", "full mode only (every suite is rebuilt with instrumentation); "162 "run Scripts/security-audit.sh --full", coverage)163 opts = ctx.options or {}164 only = set(str(opts.get("sanitizers") or os.environ.get("QY_SANITIZERS") or "address,thread,undefined").split(","))165 timeout = int(os.environ.get("QY_SANITIZER_TIMEOUT", "5400"))166 where = "local"167 host = os.uname().nodename168 runner = lambda cmd, t: run_cmd(["bash", "-lc", cmd], cwd=REPO, timeout=t) # noqa: E731169 for node in list(opts.get("nodes") or []):170 code, out, _, _ = run_cmd(["ssh", "-o", "ConnectTimeout=10", "-o", "BatchMode=yes", node, "hostname -s; swift --version 2>&1 | head -1"], timeout=40)171 if code != 0:172 continue173 excludes = [".build*", ".git", "security/.tools", "security/fuzzing/work", "security/reports/raw", "App/build", "build"]174 cmd = ["rsync", "-a", "--delete"] + [x for e in excludes for x in ("--exclude", e)] + [f"{REPO}/", f"{node}:{REMOTE_DIR}/"]175 if run_cmd(cmd, timeout=900)[0] != 0:176 continue177 where, host = node, out.splitlines()[0].strip() if out.strip() else node178 runner = lambda cmd, t, node=node: run_cmd(["ssh", "-o", "ServerAliveInterval=30", node, f"cd {REMOTE_DIR} && {cmd}"], timeout=t) # noqa: E731179 break180 _, version, _, _ = runner("swift --version 2>&1 | head -1", 60)181182 results: list[dict] = []183 lock = threading.Lock()184185 def lane(sanitizer: str) -> None: # one sanitizer = one scratch directory = sequential suites186 for s, package, flt in PLAN:187 if s == sanitizer:188 r = run_suite(runner, s, package, flt, timeout)189 with lock:190 results.append(r)191192 threads = [threading.Thread(target=lane, args=(s,), daemon=True) for s in ("address", "thread", "undefined") if s in only]193 for t in threads:194 t.start()195 for t in threads:196 t.join()197 results.sort(key=lambda r: (r["sanitizer"], r["suite"]))198199 findings, tests = [], []200 for r in results:201 ran = r["state"] in ("PASSED", "FAILED")202 tests.append({"area": "sanitizer", "name": f"{r['sanitizer']}/{r['suite']}", "algorithm": r["suite"], "parameter_set": r["sanitizer"],203 "cases": r["tests"] if ran else 0, "passed": r["tests"] if r["state"] == "PASSED" else 0,204 "failed": (len(r["reports"]) + r["issues"] + r["failed_runs"]) if r["state"] == "FAILED" else 0,205 "skipped": 0 if ran else 1, "seed": "", "note": f"{r['state']} in {r['seconds']} s on {host}"})206 seen = set()207 for rep in r["reports"]:208 key = rep["text"]209 if key in seen:210 continue211 seen.add(key)212 findings.append(finding(213 title=f"{rep['sanitizer'].capitalize()} sanitizer report in {r['suite']}: {rep['text'][:100]}",214 severity="high" if rep["sanitizer"] in ("address", "thread") else "medium", tool="sanitizers",215 rule=f"{rep['sanitizer']}:{r['suite']}:{rep['text'][:80]}", area="memory-safety" if rep["sanitizer"] != "thread" else "concurrency",216 location=r["log"], cwe="CWE-362" if rep["sanitizer"] == "thread" else "CWE-119", masvs="MASVS-CODE-4",217 description=f"swift test --sanitize={rep['sanitizer']} --filter {r['suite']} on {host}: {rep['text']}. "218 + " | ".join(r["summaries"][:3]),219 recommendation="Read the full report in the log, fix the root cause, add a regression test and re-run this suite under the sanitizer.",220 evidence=rep["text"]))221 if r["state"] == "FAILED" and not r["reports"]:222 findings.append(finding(223 title=f"Test suite {r['suite']} fails under the {r['sanitizer']} sanitizer build", severity="medium", tool="sanitizers",224 rule=f"{r['sanitizer']}:{r['suite']}:failed", area="testing", location=r["log"],225 description=f"Exit {r['exit']}, {r['issues']} recorded issue(s), no sanitizer report. A test that fails only under "226 "instrumentation is usually timing-sensitive; check the log before concluding.",227 recommendation="Inspect the log; fix the test or the code.", evidence=f"state {r['state']}"))228 findings = apply_triage(findings)229 not_executed = [f"{r['sanitizer']}/{r['suite']}: {r['state']}" for r in results if r["state"] not in ("PASSED", "FAILED")]230 metrics = {231 "host": host, "where": where, "swift": version.strip(), "suites": results,232 "passed": sum(1 for r in results if r["state"] == "PASSED"), "failed": sum(1 for r in results if r["state"] == "FAILED"),233 "not_executed": not_executed, "sanitizer_reports": sum(len(r["reports"]) for r in results),234 "tests_executed": sum(r["tests"] for r in results if r["state"] in ("PASSED", "FAILED")),235 }236 write_json(RAW / "sanitizers.json", metrics)237 status = RUN if any(r["state"] in ("PASSED", "FAILED") for r in results) else FAILED238 return tool_result(239 tool="sanitizers", category="dynamic", status=status, version=version.strip(),240 reason="" if status == RUN else "no suite could be built or run under a sanitizer",241 command="swift test -c release --sanitize=<address|thread|undefined> --filter <suite>", duration_s=time.time() - start,242 coverage=coverage + (f" Not executed: {'; '.join(not_executed)}." if not_executed else ""),243 metrics=metrics, tests=tests, findings=findings, artifacts=[rel(RAW / "sanitizers.json")])244245246if __name__ == "__main__":247 args = sys.argv[1:]248 options: dict = {}249 if "--nodes" in args:250 options["nodes"] = args[args.index("--nodes") + 1].split()251 if "--only" in args:252 options["sanitizers"] = args[args.index("--only") + 1]253 result = run(Context(mode="full" if "--full" in args else "quick", options=options))254 print(json.dumps({k: v for k, v in result.items() if k not in ("tests",)}, indent=2)[:8000])255 sys.exit(0 if result["status"] != FAILED and not [f for f in result["findings"] if f["status"] == "open"] else 1)256