Repository Public
1#!/usr/bin/env python32# =============================================================================3# SP BOUCHER | SOFTWARE & RESEARCH4# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# Project : QYVORA8# File : security/audit/orchestrator.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"""QYVORA security-audit orchestrator.4344Runs every tool runner, merges their results with the findings register, evaluates the release gate45and writes security/reports/SECURITY_AUDIT_RESULTS.json, from which the reports are generated.46Entry point for users: `Scripts/security-audit.sh` (see security/README.md).4748A tool that cannot run is recorded as NOT RUN with its reason — never as passed. The exit status is49non-zero when the release gate fails.50"""5152from __future__ import annotations5354import argparse55import concurrent.futures56import datetime57import importlib58import json59import os60import platform61import re62import socket63import sys64import time65import traceback66from pathlib import Path6768sys.path.insert(0, str(Path(__file__).resolve().parent))6970from lib import build # noqa: E40271from lib.common import (FAILED, NOT_RUN, POLICIES, RAW, REPO, REPORTS, RUN, SECURITY, SEVERITIES, Context, # noqa: E40272 apply_triage, load_json, not_run, run_cmd, tool_result, write_json)7374SCHEMA = "qyvora-audit/results/1"75FULL_ONLY = {"ipa-build", "mobsf", "binary-checks", "ct-ios"}7677# (step name, module, function, tools it reports — used when the step cannot even be imported)78STEPS = [79 ("vectors", "runners.swift_tests", "vectors", ["vectors"]),80 ("engine-tests", "runners.swift_tests", "engine_tests", ["engine-tests"]),81 ("swift-audit", "runners.swift_tests", "swift_audit", ["swift-audit"]),82 ("timing", "runners.timing", "run", ["ct-machine-code", "dudect-timing"]),83 ("fuzz", "runners.fuzz", "run", ["qyfuzz"]),84 ("sanitizers", "runners.sanitizers", "run", ["sanitizers"]),85 ("semgrep", "runners.semgrep", "run", ["semgrep"]),86 ("gitleaks", "runners.gitleaks", "run", ["gitleaks"]),87 ("mobsfscan", "runners.mobsfscan", "run", ["mobsfscan"]),88 ("static-checks", "runners.static_checks", "run", ["static-checks"]),89 ("frameworks", "runners.frameworks", "run", ["coinspect-wsf", "owasp-masvs", "owasp-mastg", "wallet-audit", "dontrust"]),90 ("ipa-build", "runners.ipa_build", "run", ["ipa-build"]),91 ("mobsf", "runners.mobsf", "run", ["mobsf"]),92 ("binary-checks", "runners.binary_checks", "run", ["binary-checks"]),93 ("ct-ios", "runners.timing", "machine_code_ios", ["ct-machine-code-ios"]),94]9596# Steps of one lane run in order; lanes run concurrently (Swift builds, static tools, application build).97LANES = [98 ["vectors", "engine-tests"],99 ["swift-audit", "timing", "fuzz", "sanitizers"],100 ["semgrep", "gitleaks", "mobsfscan", "static-checks", "frameworks", "ipa-build", "mobsf", "binary-checks", "ct-ios"],101]102103104def log(message: str) -> None:105 print(f"[audit {datetime.datetime.now().strftime('%H:%M:%S')}] {message}", flush=True)106107108def git(*args: str) -> str:109 code, out, _, _ = run_cmd(["git", *args], cwd=REPO, timeout=120)110 return out.strip() if code == 0 else ""111112113def audit_metadata(mode: str, argv: list[str]) -> dict:114 project = (REPO / "App" / "project.yml").read_text() if (REPO / "App" / "project.yml").exists() else ""115 version = re.search(r"MARKETING_VERSION:\s*\"?([\w.\-]+)", project)116 build_number = re.search(r"CURRENT_PROJECT_VERSION:\s*\"?([\w.\-]+)", project)117 code0, porcelain, _, _ = run_cmd(["git", "status", "--porcelain"], cwd=REPO, timeout=120)118 status = [l for l in porcelain.splitlines() if l.strip() and "security/reports/" not in l]119 code, xcode, _, _ = run_cmd(["xcodebuild", "-version"], timeout=60)120 code2, macos, _, _ = run_cmd(["sw_vers", "-productVersion"], timeout=30)121 return {122 "product": "QYVORA",123 "wallet_version": version.group(1) if version else "unknown",124 "wallet_build": build_number.group(1) if build_number else "unknown",125 "version_source": "App/project.yml",126 "git_commit": git("rev-parse", "HEAD"),127 "git_branch": git("rev-parse", "--abbrev-ref", "HEAD"),128 "git_commit_date": git("log", "-1", "--format=%cI"),129 "git_dirty": bool(status),130 "git_dirty_files": [l[3:] for l in status][:60],131 "date_utc": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),132 "host": socket.gethostname(),133 "machine": platform.machine(),134 "macos": macos.strip(),135 "xcode": " ".join(xcode.split()) if code == 0 else "unavailable",136 "swift": build.swift_version(),137 "python": platform.python_version(),138 "mode": mode,139 "command": "Scripts/security-audit.sh " + " ".join(argv),140 }141142143def run_step(name: str, ctx: Context) -> list[dict]:144 module_name, function_name, tools = next((m, f, t) for n, m, f, t in STEPS if n == name)145 if name in FULL_ONLY and not ctx.full and not ctx.options.get("with_app"):146 return [not_run(t, "mobile", "quick mode: the application build, MobSF and the binary checks run with --full (or --with-app)") for t in tools]147 if name == "mobsf" and ctx.options.get("no_mobsf"):148 return [not_run("mobsf", "mobile", "disabled on the command line (--no-mobsf)")]149 start = time.time()150 log(f"start {name}")151 try:152 module = importlib.import_module(module_name)153 result = getattr(module, function_name)(ctx)154 results = result if isinstance(result, list) else [result]155 except Exception: # a runner must never take the whole audit down: its failure is recorded156 results = [tool_result(tool=t, category="runner", status=FAILED, duration_s=time.time() - start,157 reason="runner error: " + traceback.format_exc()[-1800:]) for t in tools]158 for r in results:159 log(f"done {r['tool']:<16} {r['status']:<8} {r.get('duration_s', 0):>7.1f}s "160 f"findings {len(r.get('findings', []))} {(r.get('reason') or '')[:110]}")161 return results162163164REGISTER_REQUIRED = ("id", "title", "severity", "status", "fingerprint", "location", "tool")165166167def load_register(tool_results: list[dict]) -> list[dict]:168 """The hand-written findings register (one JSON file per finding), reconciled with what the tools report now."""169 by_tool = {r["tool"]: r for r in tool_results}170 out = []171 for path in sorted((SECURITY / "audit" / "findings").glob("*.json")):172 f = load_json(path)173 if not isinstance(f, dict) or "id" not in f:174 continue175 missing = [k for k in REGISTER_REQUIRED if k not in f]176 if missing:177 raise SystemExit(f"findings register: {path.name} lacks {', '.join(missing)} (compare with another entry)")178 f.setdefault("source", "register")179 f["register_file"] = str(path.relative_to(REPO))180 resolver = f.get("auto_resolved_by")181 if resolver and resolver in by_tool:182 tool = by_tool[resolver]183 emitted = {x["id"] for x in tool.get("findings", [])}184 if tool["status"] == RUN and f["id"] not in emitted and f.get("status") == "open":185 f["status"] = "fixed"186 f["resolution_note"] = f"no longer reported by {resolver} at this commit"187 elif tool["status"] != RUN:188 f["resolution_note"] = f"{resolver} did not run: status carried over from the register"189 out.append(f)190 return out191192193def merge_findings(tool_results: list[dict], register: list[dict]) -> list[dict]:194 merged: dict[str, dict] = {}195 for f in register:196 merged[f["id"]] = f197 for r in tool_results:198 for f in r.get("findings", []):199 f.setdefault("source", "tool:" + r["tool"])200 known = merged.get(f["id"])201 if known:202 # same finding described in the register: keep the richer text, take the live status from the tool203 combined = dict(known)204 for key in ("status", "location", "evidence"):205 if f.get(key):206 combined[key] = f[key]207 combined["source"] = "register+tool:" + r["tool"]208 merged[f["id"]] = combined209 else:210 merged[f["id"]] = f211 findings = apply_triage(list(merged.values()))212 order = {s: i for i, s in enumerate(SEVERITIES)}213 findings.sort(key=lambda f: (order.get(f.get("severity", "info"), 9), f.get("status", ""), f["id"]))214 for f in findings:215 f.setdefault("fingerprint", "")216 return findings217218219def summarise(tool_results: list[dict], findings: list[dict]) -> dict:220 by_area: dict[str, dict] = {}221 for r in tool_results:222 for t in r.get("tests", []):223 a = by_area.setdefault(t.get("area") or r["category"], {"records": 0, "cases": 0, "passed": 0, "failed": 0, "not_run": 0})224 a["records"] += 1225 a["cases"] += t.get("cases", 0)226 a["passed"] += t.get("passed", 0)227 a["failed"] += t.get("failed", 0)228 if t.get("skipped") and not t.get("cases"):229 a["not_run"] += 1230 matrix = {s: {} for s in SEVERITIES}231 for f in findings:232 matrix.setdefault(f.get("severity", "info"), {}).setdefault(f.get("status", "open"), 0)233 matrix[f.get("severity", "info")][f.get("status", "open")] += 1234 return {235 "tools_total": len(tool_results),236 "tools_run": [r["tool"] for r in tool_results if r["status"] == RUN],237 "tools_not_run": [{"tool": r["tool"], "reason": r.get("reason", "")} for r in tool_results if r["status"] == NOT_RUN],238 "tools_failed": [{"tool": r["tool"], "reason": r.get("reason", "")} for r in tool_results if r["status"] == FAILED],239 "tests": {"records": sum(a["records"] for a in by_area.values()), "cases": sum(a["cases"] for a in by_area.values()),240 "failed": sum(a["failed"] for a in by_area.values()), "by_area": by_area},241 "findings": {"total": len(findings), "by_severity_and_status": matrix,242 "open": sum(1 for f in findings if f.get("status") == "open"),243 "fixed": sum(1 for f in findings if f.get("status") == "fixed"),244 "accepted_risk": sum(1 for f in findings if f.get("status") == "accepted-risk"),245 "false_positive": sum(1 for f in findings if f.get("status") == "false-positive")},246 }247248249def evaluate_gate(mode: str, tool_results: list[dict], findings: list[dict]) -> dict:250 policy = load_json(POLICIES / "release-gate.json", {}) or {}251 blockers, warnings = [], []252 severities = set(policy.get("block_severities", ["critical", "high"]))253 unresolved = set(policy.get("unresolved_statuses", ["open"]))254 for f in findings:255 if f.get("severity") in severities and f.get("status") in unresolved:256 blockers.append({"rule": "unresolved critical/high finding", "detail": f"{f['id']} ({f['severity']}): {f['title']}"})257 by_tool = {r["tool"]: r for r in tool_results}258 # "Failed test" applies to the tools whose records are executed tests. For pattern scanners and framework mappings a259 # "failed" record is a rule or control that reported something: it is triaged as a finding and gated by severity.260 test_tools = set(policy.get("failed_test_tools", ["vectors", "engine-tests", "swift-audit", "ct-machine-code", "qyfuzz", "sanitizers"]))261 if policy.get("block_on_failed_tests", True):262 for r in tool_results:263 if r["tool"] not in test_tools:264 continue265 failed = [t for t in r.get("tests", []) if t.get("failed")]266 if failed:267 names = ", ".join(sorted({(t.get("algorithm") or t.get("name") or "?") for t in failed})[:8])268 blockers.append({"rule": "failed test", "detail": f"{r['tool']}: {sum(t['failed'] for t in failed)} failed case(s) in {len(failed)} record(s) — {names}"})269 if policy.get("block_on_fuzz_crash", True):270 fuzz = by_tool.get("qyfuzz")271 crashes = (fuzz or {}).get("metrics", {}).get("crashes", 0) if fuzz else 0272 open_crashes = [f for f in findings if f.get("tool") == "qyfuzz" and f.get("status") == "open" and f.get("severity") in ("critical", "high", "medium")]273 if crashes or open_crashes:274 blockers.append({"rule": "fuzzing crash", "detail": f"{crashes} crash(es) or hang(s) in this run; {len(open_crashes)} open crash finding(s)"})275 if policy.get("block_on_secret", True):276 secrets = [f for f in findings if f.get("tool") == "gitleaks" and f.get("status") == "open"]277 if secrets:278 blockers.append({"rule": "secret found", "detail": f"{len(secrets)} untriaged secret(s) reported by Gitleaks"})279 for name in policy.get("block_on_tool_failed", []):280 r = by_tool.get(name)281 if r and r["status"] == FAILED:282 blockers.append({"rule": "tool failed", "detail": f"{name}: {(r.get('reason') or '')[:200]}"})283 required = list(policy.get("required_tools", []))284 if mode == "full":285 required += policy.get("required_tools_full", [])286 for name in required:287 r = by_tool.get(name)288 if r is None or r["status"] == NOT_RUN:289 blockers.append({"rule": "required tool not run", "detail": f"{name}: {(r or {}).get('reason', 'no result')[:200]}"})290 for r in tool_results:291 if r["status"] == NOT_RUN and r["tool"] not in required:292 warnings.append({"rule": "tool not run", "detail": f"{r['tool']}: {(r.get('reason') or '')[:200]}"})293 if r["status"] == FAILED and r["tool"] not in policy.get("block_on_tool_failed", []):294 warnings.append({"rule": "tool failed", "detail": f"{r['tool']}: {(r.get('reason') or '')[:200]}"})295 not_run_checks = [t for t in r.get("tests", []) if t.get("skipped") and not t.get("cases")]296 if not_run_checks:297 warnings.append({"rule": "checks not run", "detail": f"{r['tool']}: {len(not_run_checks)} check(s) recorded as NOT RUN"})298 open_medium = [f for f in findings if f.get("severity") == "medium" and f.get("status") == "open"]299 if open_medium:300 warnings.append({"rule": "open medium findings", "detail": f"{len(open_medium)} open medium finding(s): " + ", ".join(f["id"] for f in open_medium[:20])})301 if mode != "full":302 warnings.append({"rule": "quick run", "detail": "a publication requires a --full run (application binary, MobSF, long fuzzing campaigns, timing on a quiet node)"})303 return {304 "passed": not blockers, "mode": mode, "policy": "security/policies/release-gate.json", "blockers": blockers, "warnings": warnings,305 "meaning": "Passing this gate means the automated internal audit found no blocking condition at this commit. It is not a "306 "certification, not a proof of security, and does not replace the independent cryptographic review required before "307 "any recommendation to use the wallet with real funds.",308 }309310311def load_reviews() -> dict:312 out = {}313 for path in sorted((SECURITY / "audit" / "review").glob("*.json")):314 data = load_json(path)315 if data is not None:316 out[path.stem] = data317 return out318319320def main(argv: list[str]) -> int:321 parser = argparse.ArgumentParser(description="QYVORA security audit")322 parser.add_argument("--quick", action="store_true", help="short run (default)")323 parser.add_argument("--full", action="store_true", help="complete run: application binary, MobSF, long campaigns, full vector files")324 parser.add_argument("--no-mobsf", action="store_true", help="skip MobSF (recorded as NOT RUN)")325 parser.add_argument("--with-app", action="store_true", help="build the application and run the binary checks even in quick mode")326 parser.add_argument("--nodes", default="", help='cluster nodes for long campaigns, e.g. "M3U96a M3U96b"')327 parser.add_argument("--timing-node", default="", help="node used for the timing measurements (default: first of --nodes in full mode)")328 parser.add_argument("--only", default="", help="comma-separated step names to run (others are recorded as NOT RUN)")329 parser.add_argument("--skip", default="", help="comma-separated step names to skip (recorded as NOT RUN)")330 parser.add_argument("--jobs", type=int, default=3, help="number of lanes run concurrently (1 = sequential)")331 parser.add_argument("--no-report", action="store_true", help="write the JSON only")332 parser.add_argument("--update-docs", action="store_true",333 help="rewrite the generated 'last audit run' block of SECURITY.md and docs/THREAT_MODEL.md (default with --full)")334 parser.add_argument("--list", action="store_true", help="list the steps and exit")335 args = parser.parse_args(argv)336 if args.list:337 for name, module, function, tools in STEPS:338 print(f"{name:<14} {module}.{function} -> {', '.join(tools)}")339 return 0340 mode = "full" if args.full else "quick"341 options = {"nodes": args.nodes.split(), "no_mobsf": args.no_mobsf, "with_app": args.with_app,342 "timing_node": args.timing_node or None}343 ctx = Context(mode, options)344 only = {s for s in args.only.split(",") if s}345 skip = {s for s in args.skip.split(",") if s}346 unknown = (only | skip) - {n for n, *_ in STEPS}347 if unknown:348 print("unknown step(s): " + ", ".join(sorted(unknown)), file=sys.stderr)349 return 2350 start = time.time()351 meta = audit_metadata(mode, argv)352 log(f"QYVORA {meta['wallet_version']} ({meta['wallet_build']}) commit {meta['git_commit'][:12]}{' +dirty' if meta['git_dirty'] else ''} — {mode} audit")353354 def lane(steps: list[str]) -> list[dict]:355 out = []356 for name in steps:357 tools = next(t for n, _, _, t in STEPS if n == name)358 if (only and name not in only) or name in skip:359 out += [not_run(t, "skipped", "not selected on the command line (--only / --skip)") for t in tools]360 else:361 out += run_step(name, ctx)362 return out363364 load_register([]) # validates every register entry now, not after the run365366 results: list[dict] = []367 if args.jobs <= 1:368 for steps in LANES:369 results += lane(steps)370 else:371 with concurrent.futures.ThreadPoolExecutor(max_workers=min(args.jobs, len(LANES))) as pool:372 for lane_results in pool.map(lane, LANES):373 results += lane_results374 order = [t for _, _, _, tools in STEPS for t in tools]375 results.sort(key=lambda r: order.index(r["tool"]) if r["tool"] in order else len(order))376377 register = load_register(results)378 findings = merge_findings(results, register)379 gate = evaluate_gate(mode, results, findings)380 meta["duration_s"] = round(time.time() - start, 1)381 document = {382 "schema": SCHEMA,383 "statement": "Internal automated technical audit run on the project's own infrastructure. Not an independent certification; "384 "no independent cryptographic review has taken place. Post-quantum cryptography protects the local vault, backups, "385 "transfers and the separate identity; it does not make Bitcoin or Ethereum transactions quantum-resistant.",386 "audit": meta,387 "summary": summarise(results, findings),388 "gate": gate,389 "findings": findings,390 "tools": results,391 "reviews": load_reviews(),392 }393 REPORTS.mkdir(parents=True, exist_ok=True)394 write_json(REPORTS / "SECURITY_AUDIT_RESULTS.json", document)395 log(f"results: security/reports/SECURITY_AUDIT_RESULTS.json ({meta['duration_s']} s)")396 if not args.no_report:397 try:398 from report import generate399 written = generate.generate(document)400 # The status block of SECURITY.md / THREAT_MODEL.md follows the committed reports: full runs, or on request;401 # never when the output is redirected (hooks, server-side checks).402 if (args.full or args.update_docs) and not os.environ.get("QY_AUDIT_REPORTS"):403 written += generate.update_docs(document)404 document["reports"] = written405 write_json(REPORTS / "SECURITY_AUDIT_RESULTS.json", document)406 for item in written:407 log(f"report {item['file']}: {item['status']} {item.get('reason', '')}")408 except Exception:409 log("report generation failed:\n" + traceback.format_exc())410 return 3411 s = document["summary"]412 log(f"tools: {len(s['tools_run'])} run, {len(s['tools_not_run'])} not run, {len(s['tools_failed'])} failed — "413 f"test cases {s['tests']['cases']} ({s['tests']['failed']} failed) — findings {s['findings']['total']} ({s['findings']['open']} open)")414 for b in gate["blockers"]:415 log(f"BLOCKER {b['rule']}: {b['detail']}")416 log("RELEASE GATE: " + ("PASSED" if gate["passed"] else "FAILED") + f" ({len(gate['blockers'])} blocker(s), {len(gate['warnings'])} warning(s))")417 return 0 if gate["passed"] else 1418419420if __name__ == "__main__":421 sys.exit(main(sys.argv[1:]))422