Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project : QYVORA7# File : security/audit/runners/static_checks.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"""Repository-specific static checks that generic tools do not cover.4243Each check reads the current tree (the application sources change: nothing is tied to a line number) and44produces one test record (area "hygiene" or "wallet") and, when violated, a finding with a stable45identifier QYV-STA-NNN. These are text-level checks: they establish that a protective construct is46present (or a forbidden one absent) in the source; they do not prove run-time behaviour, which the47integrator's device tests and the MASVS assessment cover.4849Standalone: python3 security/audit/runners/static_checks.py50"""5152from __future__ import annotations5354import json55import plistlib56import re57import sys58import time59from pathlib import Path6061sys.path.insert(0, str(Path(__file__).resolve().parents[1]))62from lib.common import REPO, RUN, Context, apply_triage, finding, tool_result # noqa: E4026364ENGINE = REPO / "Sources"65APP = REPO / "App" / "Sources"66INFO_PLIST = REPO / "App" / "Resources" / "Info.plist"67ENTITLEMENTS = REPO / "App" / "Resources" / "Qyvora.entitlements"68PROJECT_YML = REPO / "App" / "project.yml"6970# macOS command-line benchmark tool: not linked into the iOS application.71NOT_IN_APP = ("Sources/qyvora-bench/",)72SECRET_NAMES = r"(?i:secret|seed|mnemonic|passw|passphrase|privateKey|private_key|phrase|entropy|masterKey|xprv|sharedSecret|\bpin\b|\bwif\b)"73COVERAGE = (74 "Text-level checks of this code base: single entropy source, no secret-named value in logging calls, "75 "pasteboard only through QClipboard (local-only, expiring), no secret-named UserDefaults key, privacy cover "76 "wired to the scene phase, privacy-sensitive seed views, ATS left at its default, URLSession hardening and "77 "redirect refusal, endpoint acceptance enforced in the engine, Keychain accessibility classes, file "78 "protection and backup exclusion, mainnet build flag, debug-only code fenced by #if DEBUG, Info.plist "79 "exposure keys; since 2026-12-05 also: the application signs only through the calls that take the acknowledged "80 "critical warnings, no consent is set by the code, a watch-only package is imported only with its compared code, "81 "payment requests go through the bounded parser and never past the form, dollar ceilings are converted only by "82 "the cross-checked price function. They show the presence or absence of constructs in the source, not run-time behaviour."83)848586def rel(p: Path) -> str:87 return str(p.relative_to(REPO))888990def swift_files(*roots: Path, skip: tuple = NOT_IN_APP) -> list[Path]:91 out = []92 for root in roots:93 if root.exists():94 out += [p for p in sorted(root.rglob("*.swift")) if not any(rel(p).startswith(s) for s in skip)]95 return out969798def grep(pattern: str, files: list[Path], code_only: bool = True) -> list[tuple[str, int, str]]:99 """(path, line number, stripped line) of every match; comment lines skipped when `code_only`."""100 rx = re.compile(pattern)101 hits = []102 for f in files:103 try:104 lines = f.read_text(errors="replace").splitlines()105 except OSError:106 continue107 for i, line in enumerate(lines, 1):108 s = line.strip()109 if code_only and (s.startswith("//") or s.startswith("*") or s.startswith("/*")):110 continue111 if rx.search(line):112 hits.append((rel(f), i, s[:220]))113 return hits114115116def loc(h: tuple[str, int, str]) -> str:117 return f"{h[0]}:{h[1]}"118119120def listing(hits: list, limit: int = 12) -> str:121 text = "; ".join(f"{loc(h)} `{h[2][:90]}`" for h in hits[:limit])122 return text + (f"; … {len(hits) - limit} more" if len(hits) > limit else "")123124125def debug_regions(path: Path) -> list[bool]:126 """For each line, True when it is inside an `#if DEBUG` region (nesting and #else handled)."""127 flags, stack = [], []128 for line in path.read_text(errors="replace").splitlines():129 s = line.strip()130 if s.startswith("#if"):131 stack.append("DEBUG" if re.match(r"#if\s+DEBUG\b", s) else "NOT_DEBUG" if re.match(r"#if\s+!\s*DEBUG\b", s) else "OTHER")132 elif s.startswith("#else") and stack:133 stack[-1] = {"DEBUG": "NOT_DEBUG", "NOT_DEBUG": "DEBUG"}.get(stack[-1], "OTHER")134 elif s.startswith("#elseif") and stack:135 stack[-1] = "OTHER"136 elif s.startswith("#endif") and stack:137 stack.pop()138 flags.append(False)139 continue140 flags.append("DEBUG" in stack)141 return flags142143144class Checks:145 def __init__(self):146 self.records, self.findings = [], []147148 def record(self, area: str, name: str, ok: bool, note: str, cases: int = 1):149 self.records.append({"area": area, "name": name, "algorithm": "", "parameter_set": "", "cases": cases,150 "passed": cases if ok else 0, "failed": 0 if ok else cases, "skipped": 0, "note": note[:900]})151152 def skip(self, area: str, name: str, reason: str):153 self.records.append({"area": area, "name": name, "algorithm": "", "parameter_set": "", "cases": 0, "passed": 0,154 "failed": 0, "skipped": 1, "note": "NOT RUN: " + reason})155156 def find(self, id: str, title: str, severity: str, location: str, description: str, recommendation: str,157 cwe: str = "", masvs: str = "", area: str = "app", cvss: tuple = ("", None)):158 self.findings.append(finding(159 id=id, title=title, severity=severity, location=location, tool="static-checks", rule=id,160 description=description, recommendation=recommendation, cwe=cwe, masvs=masvs, area=area,161 cvss_vector=cvss[0], cvss_score=cvss[1], evidence=id))162163164def run(ctx: Context) -> dict:165 started = time.time()166 c = Checks()167 engine = swift_files(ENGINE)168 app = swift_files(APP)169 everything = engine + app170171 # ---- hygiene: entropy ----------------------------------------------------------------------------------172 sanctioned = "Sources/QyvoraMath/SystemRandom.swift"173 forbidden = grep(174 r"\b(arc4random(_uniform|_buf)?|drand48|erand48|lrand48|srand48|srandom|srand|rand|random)\s*\(|"175 r"\bSystemRandomNumberGenerator\b|\.random\s*\(\s*(in\s*:|using\s*:|\))|\.randomElement\s*\(|\.shuffled\s*\(\s*\)|"176 r"\.shuffle\s*\(\s*\)|\bGKRandom\w*|\bSecRandomCopyBytes\b|\bCCRandomGenerateBytes\b|/dev/u?random|\bSecKeyGenerateSymmetric\b",177 everything)178 forbidden = [h for h in forbidden if h[0] != sanctioned and not re.search(r"\bfunc\s+random\s*\(", h[2])]179 sys_calls = grep(r"\bSystemRandom\.bytes\s*\(", everything)180 sec_calls = grep(r"\bSecRandomCopyBytes\b", swift_files(ENGINE, skip=()))181 ok = not forbidden and len(sec_calls) == 1 and sec_calls[0][0] == sanctioned182 c.record("hygiene", "entropy: single source (SecRandomCopyBytes only in SystemRandom.swift, no other generator API)", ok,183 f"{len(sys_calls)} SystemRandom.bytes call sites in {len({h[0] for h in sys_calls})} files; "184 f"SecRandomCopyBytes call sites: {', '.join(loc(h) for h in sec_calls) or 'none'}; "185 f"forbidden generator API occurrences: {len(forbidden)}")186 if not ok:187 c.find("QYV-STA-001", "Randomness drawn outside SystemRandom", "high",188 loc(forbidden[0]) if forbidden else sanctioned,189 "Root cause: a generator other than SystemRandom (SecRandomCopyBytes) is used, or SecRandomCopyBytes is "190 "called from more than one place. Impact: key, nonce or seed material may come from a predictable or "191 "unreviewed source. Occurrences: " + (listing(forbidden) or listing(sec_calls)),192 "Draw every random byte through SystemRandom.bytes.", cwe="CWE-338", masvs="MASVS-CRYPTO-1", area="engine",193 cvss=("CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:N", 7.4))194195 # Deterministic generators defined in the code (ordering heuristics); listed, and checked for their seed source.196 prng_types = grep(r"\b(struct|final class|class)\s+\w*(Generator|PRNG|Xoshiro|SplitMix)\w*\b", everything)197 prng_types = [h for h in prng_types if "Benchmarks" not in h[0] and not re.search(r"(QRCode|Report|Sheet|Identifier|ID)Generator", h[2])]198 prng_uses = grep(r"\bSeededGenerator\s*\(", engine)199 c.record("hygiene", "entropy: deterministic generators in the engine (inventory)", True,200 "defined: " + (listing(prng_types) or "none") + " | instantiated: " + (listing(prng_uses) or "none")201 + ". These are not key sources; see finding QYV-STA-002 when present.", cases=max(1, len(prng_types)))202 if prng_types:203 seeds = grep(r"seed\s*:\s*[^,)]*", [REPO / h[0] for h in prng_uses]) if prng_uses else []204 c.find("QYV-STA-002", "Deterministic (non-cryptographic) generator used for transaction ordering", "low",205 loc(prng_uses[0]) if prng_uses else loc(prng_types[0]),206 "A seeded SplitMix-style generator shuffles Bitcoin inputs and outputs and jitters the lock time. It is "207 "seeded with 64 bits from SystemRandom unless the caller supplies `seed` (meant for tests). It produces no "208 "key, nonce or signature material: the impact is limited to the privacy heuristics (ordering, lock time), "209 "whose 64-bit seed is ample. Risk: a production caller passing a fixed seed would make ordering "210 "predictable. Definition: " + listing(prng_types) + ". Use: " + listing(prng_uses),211 "Keep `seed` nil outside tests (assert it in the wallet service), and state in the type's documentation "212 "that it must never produce secret material.", cwe="CWE-338", masvs="MASVS-CRYPTO-1", area="engine")213214 # ---- hygiene: logs ------------------------------------------------------------------------------------215 log_calls = grep(r"\b(print|debugPrint|dump|NSLog|os_log|os_signpost)\s*\(|\bLogger\s*\(|\.(debug|notice|fault)\s*\(\s*\"", everything)216 secret_logs = [h for h in log_calls if re.search(SECRET_NAMES, h[2])]217 c.record("hygiene", "logs: no logging call mentions a secret-named value", not secret_logs,218 f"{len(log_calls)} logging call(s) in Sources/ and App/Sources: " + (listing(log_calls, 8) or "none")219 + f"; secret-named: {len(secret_logs)}")220 if secret_logs:221 c.find("QYV-STA-003", "Secret-named value passed to a logging call", "high", loc(secret_logs[0]),222 "A logging call mentions a value named like a secret; the unified log and crash reports are readable "223 "outside the application. Occurrences: " + listing(secret_logs),224 "Remove the call or log a non-secret summary.", cwe="CWE-532", masvs="MASVS-STORAGE-2",225 area="app" if secret_logs[0][0].startswith("App/") else "engine",226 cvss=("CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", 5.5))227228 # ---- hygiene: pasteboard ------------------------------------------------------------------------------229 helper = "Sources/QyvoraUI/Feedback.swift"230 paste = grep(r"\b(UIPasteboard|NSPasteboard)\b", everything)231 outside = [h for h in paste if h[0] != helper]232 c.record("hygiene", "pasteboard: used only inside the sanctioned helper QClipboard", not outside,233 f"{len(paste)} pasteboard reference(s), {len(outside)} outside {helper}")234 if outside:235 c.find("QYV-STA-004", "Pasteboard used outside QClipboard", "medium", loc(outside[0]),236 "Direct pasteboard access bypasses the helper that keeps sensitive values on this device and makes them "237 "expire (Universal Clipboard would otherwise carry them to other devices). Occurrences: " + listing(outside),238 "Call QClipboard.copy(_:sensitive:) instead.", cwe="CWE-200", masvs="MASVS-PLATFORM-3")239 helper_text = (REPO / helper).read_text(errors="replace") if (REPO / helper).exists() else ""240 has_expiry = ".expirationDate" in helper_text and ".localOnly" in helper_text241 m = re.search(r"sensitiveLifetime\s*:\s*TimeInterval\s*=\s*([\d.]+)", helper_text)242 c.record("hygiene", "pasteboard: sensitive copies are local-only and expire", has_expiry,243 f"localOnly + expirationDate present: {has_expiry}; lifetime: {m.group(1) + ' s' if m else 'not found'}")244 if not has_expiry:245 c.find("QYV-STA-005", "Clipboard helper does not expire or localise sensitive values", "medium", helper,246 "QClipboard no longer sets `.localOnly` and `.expirationDate` for sensitive values.",247 "Restore both options in QClipboard.copy.", cwe="CWE-200", masvs="MASVS-PLATFORM-3", area="engine")248 copies = grep(r"\b(QClipboard\.copy|QCopyButton|CopyButton)\s*\(", everything)249 risky = [h for h in copies if re.search(SECRET_NAMES, h[2]) and "sensitive: true" not in h[2] and "sensitive: sensitive" not in h[2]250 and "func copy" not in h[2]]251 c.record("hygiene", "pasteboard: secret-named values are copied with sensitive: true", not risky,252 f"{len(copies)} copy call site(s); secret-named without `sensitive: true`: {len(risky)}")253 if risky:254 c.find("QYV-STA-006", "Secret-named value copied without the sensitive flag", "medium", loc(risky[0]),255 "A value named like a secret is copied without `sensitive: true`, so it does not expire and may travel "256 "through Universal Clipboard. Occurrences: " + listing(risky),257 "Pass `sensitive: true`, or do not offer a copy of this value.", cwe="CWE-200", masvs="MASVS-PLATFORM-3")258259 # ---- hygiene: UserDefaults ----------------------------------------------------------------------------260 writes = grep(r"(?i:defaults)\w*\s*\.\s*(set|setValue)\s*\(|@AppStorage\s*\(|@SceneStorage\s*\(", everything)261 keys = grep(r"(?i)static let \w*key\w*\s*=\s*\"|@AppStorage\s*\(\s*\"|forKey:\s*\"", app + swift_files(ENGINE / "QyvoraUI"))262 bad = [h for h in writes + keys if re.search(SECRET_NAMES, h[2])]263 c.record("hygiene", "UserDefaults: no secret-named key or value", not bad,264 f"{len(writes)} write site(s): " + (listing(writes, 8) or "none") + f"; secret-named: {len(bad)}")265 if bad:266 c.find("QYV-STA-007", "Secret-named value stored in UserDefaults", "high", loc(bad[0]),267 "UserDefaults is an unencrypted property list included in device backups. Occurrences: " + listing(bad),268 "Store the value in the vault or the Keychain.", cwe="CWE-312", masvs="MASVS-STORAGE-1",269 cvss=("CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", 5.5))270271 # ---- wallet: privacy cover, screenshots, privacy-sensitive views ---------------------------------------272 cover_def = grep(r"struct\s+PrivacyCover\b", engine)273 cover_use = grep(r"\.qPrivacyCover\s*\(", app)274 scene = grep(r"scenePhase\s*!=\s*\.active|scenePhase\s*==\s*\.(inactive|background)", app)275 ok = bool(cover_def and cover_use and scene)276 c.record("wallet", "privacy cover: defined, applied at the root and driven by the scene phase", ok,277 f"definition: {listing(cover_def) or 'missing'}; applied: {listing(cover_use) or 'missing'}; "278 f"scene phase condition: {listing(scene) or 'missing'}")279 if not ok:280 c.find("QYV-STA-008", "Privacy cover not applied when the application leaves the foreground", "medium",281 loc(cover_use[0]) if cover_use else "App/Sources/RootView.swift",282 "The app-switcher snapshot may show balances, addresses or a recovery phrase.",283 "Apply `.qPrivacyCover(isActive: scenePhase != .active)` at the root view.", cwe="CWE-200", masvs="MASVS-PLATFORM-3")284 capture = grep(r"isCaptured|capturedDidChangeNotification|userDidTakeScreenshotNotification|sceneCaptureState", everything)285 c.record("wallet", "screen capture: recording / screenshot awareness present", bool(capture),286 "references: " + (listing(capture) or "none found"))287 if not capture:288 c.find("QYV-STA-009", "No screen-recording or screenshot awareness on secret screens", "low", "App/Sources",289 "Nothing in Sources/ or App/Sources observes screen capture (`sceneCaptureState` / `UIScreen.isCaptured`) or "290 "the screenshot notification. A recovery phrase shown during a screen recording, AirPlay mirroring or a "291 "screenshot is captured in clear; iOS cannot block a screenshot, but the phrase can be hidden while the "292 "screen is captured and the user warned after a screenshot.",293 "On the recovery-phrase and private-key screens, hide the content while `sceneCaptureState == .active` and "294 "show a warning after `userDidTakeScreenshotNotification`.", cwe="CWE-200", masvs="MASVS-PLATFORM-3",295 cvss=("CVSS:3.1/AV:L/AC:H/PR:N/UI:R/S:U/C:H/I:N/A:N", 4.7))296 seed_views = [f for f in engine + app if re.search(r"(?i)seed|phrase|mnemonic", f.name)]297 seed_views = [f for f in seed_views if "QyvoraUI" in rel(f) or rel(f).startswith("App/")]298 missing = [rel(f) for f in seed_views if ".privacySensitive(" not in f.read_text(errors="replace")]299 c.record("wallet", "recovery phrase views are marked .privacySensitive", bool(seed_views) and not missing,300 f"views: {', '.join(rel(f) for f in seed_views) or 'none found'}; without .privacySensitive: {', '.join(missing) or 'none'}",301 cases=max(1, len(seed_views)))302 if missing:303 c.find("QYV-STA-017", "Recovery phrase view not marked privacy-sensitive", "medium", missing[0],304 "The view shows or accepts a recovery phrase without `.privacySensitive()`; it stays readable in "305 "redacted contexts. Files: " + ", ".join(missing),306 "Add `.privacySensitive()` to the phrase grid and to the entry fields.", cwe="CWE-200", masvs="MASVS-PLATFORM-3")307 kb = grep(r"shouldAllowExtensionPointIdentifier", everything)308 seed_entry = grep(r"\.autocorrectionDisabled\s*\(", swift_files(ENGINE / "QyvoraUI"))309 c.record("wallet", "keyboards: third-party keyboard extensions refused", bool(kb),310 "application(_:shouldAllowExtensionPointIdentifier:) " + ("present: " + listing(kb) if kb else "absent")311 + f"; autocorrection disabled on {len(seed_entry)} entry field(s)")312 if not kb:313 c.find("QYV-STA-016", "Third-party keyboards are not refused", "low", "App/Sources/QyvoraApp.swift",314 "No application delegate refuses the keyboard extension point. A third-party keyboard with full access can "315 "observe a recovery phrase typed during restore (SecureField password entry always uses the system "316 "keyboard; the phrase entry is a plain text field).",317 "Add a UIApplicationDelegate adaptor returning false for `.keyboard` in "318 "application(_:shouldAllowExtensionPointIdentifier:).", cwe="CWE-200", masvs="MASVS-PLATFORM-1",319 cvss=("CVSS:3.1/AV:L/AC:H/PR:N/UI:R/S:U/C:H/I:N/A:N", 4.7))320321 # ---- wallet: Info.plist, entitlements, build configuration ---------------------------------------------322 info = None323 if INFO_PLIST.exists():324 try:325 info = plistlib.loads(INFO_PLIST.read_bytes())326 except Exception as e: # noqa: BLE001327 c.skip("wallet", "Info.plist checks", f"cannot parse {rel(INFO_PLIST)}: {e}")328 else:329 c.skip("wallet", "Info.plist checks", f"{rel(INFO_PLIST)} missing")330 if info is not None:331 ats = info.get("NSAppTransportSecurity")332 c.record("wallet", "ATS: no App Transport Security exception in Info.plist", not ats,333 "NSAppTransportSecurity " + ("absent (system default: TLS 1.2+, forward secrecy, valid certificate)" if not ats else f"present: {ats}"))334 if ats:335 c.find("QYV-STA-010", "App Transport Security exception declared", "medium", rel(INFO_PLIST),336 f"Info.plist declares NSAppTransportSecurity = {ats}. Any exception weakens transport security for the "337 "hosts it covers.", "Remove the exception; plain http is only needed for local hosts, which ATS already "338 "exempts for IP literals and .local names.", cwe="CWE-319", masvs="MASVS-NETWORK-1")339 exposure = {k: info.get(k) for k in ("UIFileSharingEnabled", "LSSupportsOpeningDocumentsInPlace", "CFBundleURLTypes",340 "CFBundleDocumentTypes", "UIBackgroundModes") if info.get(k)}341 c.record("wallet", "Info.plist: no file sharing, URL scheme, document type or background mode exposed", not exposure,342 "exposure keys set: " + (json.dumps(exposure, default=str)[:300] if exposure else "none"))343 if exposure:344 c.find("QYV-STA-019", "Info.plist exposes the application container or an entry point", "medium", rel(INFO_PLIST),345 "Keys set: " + json.dumps(exposure, default=str)[:400] + ". File sharing exposes the Documents directory "346 "to a connected computer; URL schemes and document types are entry points for untrusted input.",347 "Remove the keys that are not needed, and validate every input received through the others.",348 cwe="CWE-200", masvs="MASVS-PLATFORM-1")349 usage = {k: v for k, v in info.items() if k.endswith("UsageDescription")}350 c.record("wallet", "Info.plist: permissions limited to Face ID and camera", set(usage) <= {"NSFaceIDUsageDescription", "NSCameraUsageDescription"},351 "usage descriptions: " + ", ".join(sorted(usage)))352 flag = info.get("QYInternalMainnet")353 c.record("wallet", "mainnet build flag QYInternalMainnet (state recorded)", True,354 f"QYInternalMainnet = {flag!r} in {rel(INFO_PLIST)} (true = internal TestFlight build allowed to reach mainnet "355 "with the user switch; a public build must not carry it)")356 if flag:357 c.find("QYV-STA-014", "QYInternalMainnet is set: this build may reach mainnet before the audit is complete", "low",358 rel(INFO_PLIST),359 "Info.plist declares QYInternalMainnet = true (owner decision of 2026-12-04 for the internal TestFlight "360 "build: mainnet with small amounts, behind a user switch and per-transaction limits, "361 "MainnetPolicy.auditCompleted = false). Impact: real funds are handled by cryptography that has had no "362 "independent review. This is an accepted, bounded exposure for internal testing; it becomes a release "363 "blocker for any public build.",364 "Keep the key out of every public build configuration (set it only in the internal TestFlight "365 "configuration) and keep the limits of MainnetPolicy.limits.", cwe="CWE-1188", masvs="MASVS-CODE-4")366 if ENTITLEMENTS.exists():367 try:368 ent = plistlib.loads(ENTITLEMENTS.read_bytes())369 except Exception: # noqa: BLE001370 ent = {}371 dp = ent.get("com.apple.developer.default-data-protection")372 extra = sorted(k for k in ent if k != "com.apple.developer.default-data-protection")373 c.record("wallet", "entitlements: default data protection is NSFileProtectionComplete", dp == "NSFileProtectionComplete",374 f"default-data-protection = {dp!r}; other entitlements: {', '.join(extra) or 'none'}")375 else:376 dp = None377 c.skip("wallet", "entitlements check", f"{rel(ENTITLEMENTS)} missing")378379 policy = (ENGINE / "QyvoraCore" / "Networks.swift")380 if policy.exists():381 t = policy.read_text(errors="replace")382 both = bool(re.search(r"auditCompleted\s*\|\|\s*\(\s*internalBuild\s*&&\s*userOptIn\s*\)", t))383 audit_false = bool(re.search(r"static let auditCompleted\s*=\s*false", t))384 c.record("wallet", "mainnet gate: needs the build flag AND the user switch; audit flag is false", both and audit_false,385 f"mainnetEnabled = auditCompleted || (internalBuild && userOptIn): {both}; auditCompleted = false: {audit_false}")386 if not (both and audit_false):387 c.find("QYV-STA-018", "Mainnet gate no longer requires both conditions", "high", rel(policy),388 "MainnetPolicy.mainnetEnabled is expected to be `auditCompleted || (internalBuild && userOptIn)` with "389 "`auditCompleted = false` until an independent review. The source no longer matches.",390 "Restore the two-condition gate; do not set auditCompleted without an independent cryptographic review.",391 cwe="CWE-284", masvs="MASVS-CODE-4", area="engine")392 else:393 c.skip("wallet", "mainnet gate", "Sources/QyvoraCore/Networks.swift missing")394395 # ---- wallet: debug-only code ---------------------------------------------------------------------------396 leaks = []397 debug_files = [f for f in app if f.name.startswith("Debug")]398 for f in debug_files:399 lines = f.read_text(errors="replace").splitlines()400 flags = debug_regions(f)401 for i, (line, inside) in enumerate(zip(lines, flags), 1):402 s = line.strip()403 if s and not s.startswith("//") and not s.startswith("#") and not inside:404 leaks.append((rel(f), i, s[:120]))405 break406 for f in app:407 if f in debug_files:408 continue409 lines = f.read_text(errors="replace").splitlines()410 flags = debug_regions(f)411 for i, (line, inside) in enumerate(zip(lines, flags), 1):412 if re.search(r"\bDebug(Launch|Gallery)\b", line) and not inside and not line.strip().startswith("//"):413 leaks.append((rel(f), i, line.strip()[:120]))414 yml = PROJECT_YML.read_text(errors="replace") if PROJECT_YML.exists() else ""415 release_block = yml.split("Release:", 1)[1].split("\ntargets:", 1)[0] if "Release:" in yml else ""416 release_defines_debug = "DEBUG" in release_block417 runtime = grep(r"ProcessInfo\.processInfo\.(arguments|environment)|CommandLine\.arguments", everything)418 runtime_out = []419 for h in runtime:420 f = REPO / h[0]421 if not debug_regions(f)[h[1] - 1]:422 runtime_out.append(h)423 ok = not leaks and not release_defines_debug and not runtime_out424 c.record("wallet", "debug code: Debug* files and their references are fenced by #if DEBUG; Release does not define DEBUG", ok,425 f"debug files: {', '.join(rel(f) for f in debug_files) or 'none'}; unfenced lines: {len(leaks)}; "426 f"Release defines DEBUG: {release_defines_debug}; launch-argument/environment reads outside #if DEBUG: {len(runtime_out)}",427 cases=max(1, len(debug_files)))428 if not ok:429 hits = leaks + runtime_out430 c.find("QYV-STA-015", "Debug-only code reachable in a Release build", "medium",431 loc(hits[0]) if hits else rel(PROJECT_YML),432 "Debug screens, launch arguments or environment switches are compiled into Release, or the Release "433 "configuration defines DEBUG. Occurrences: " + (listing(hits) or "Release configuration defines DEBUG"),434 "Fence the code with `#if DEBUG` and keep SWIFT_ACTIVE_COMPILATION_CONDITIONS free of DEBUG in Release.",435 cwe="CWE-489", masvs="MASVS-RESILIENCE-3")436437 # ---- wallet: network -----------------------------------------------------------------------------------438 http = ENGINE / "QyvoraNetworking" / "HTTP.swift"439 if http.exists():440 t = http.read_text(errors="replace")441 need = {442 "ephemeral configuration": r"URLSessionConfiguration\.ephemeral",443 "no cookie storage": r"httpCookieStorage\s*=\s*nil",444 "cookies not set": r"httpShouldSetCookies\s*=\s*false",445 "no URL cache": r"urlCache\s*=\s*nil",446 "no credential storage": r"urlCredentialStorage\s*=\s*nil",447 "redirects refused (delegate returns nil)": r"willPerformHTTPRedirection[\s\S]{0,200}?\n\s*nil\s*\n",448 }449 missing_cfg = [k for k, rx in need.items() if not re.search(rx, t)]450 sessions = grep(r"\bURLSession\s*\(|\bURLSession\.shared\b|\bNSURLConnection\b|\bWKWebView\b|\bNWConnection\b|\bCFStream\w*\b|\bURLSessionWebSocketTask\b", everything)451 other = [h for h in sessions if h[0] != rel(http)]452 trust = grep(r"URLAuthenticationChallenge|\.serverTrust\b|URLCredential\s*\(\s*trust|SecTrustSetExceptions|SecTrustSetAnchorCertificates", everything)453 ok = not missing_cfg and not other and not trust454 c.record("wallet", "network: one hardened URLSession (ephemeral, no cookies/cache/credentials, redirects refused), system trust evaluation untouched", ok,455 f"missing settings: {', '.join(missing_cfg) or 'none'}; network API outside HTTP.swift: {listing(other) or 'none'}; "456 f"server-trust overrides: {listing(trust) or 'none'}", cases=len(need) + 2)457 if not ok:458 c.find("QYV-STA-011", "Network stack deviates from the hardened single-session design", "medium",459 loc(other[0]) if other else loc(trust[0]) if trust else rel(http),460 "Expected: one ephemeral URLSession without cookies, cache or credential storage, refusing redirects, "461 "and no server-trust override. Missing settings: " + (", ".join(missing_cfg) or "none")462 + ". Other network API: " + (listing(other) or "none") + ". Trust overrides: " + (listing(trust) or "none"),463 "Route every request through URLSessionTransport and leave trust evaluation to the system.",464 cwe="CWE-295", masvs="MASVS-NETWORK-1", area="engine")465 enforced = grep(r"isAcceptable\s*\(", swift_files(ENGINE / "QyvoraNetworking") + swift_files(ENGINE / "QyvoraWallet"))466 enforced = [h for h in enforced if "func isAcceptable" not in h[2]]467 pin = grep(r"(?i)pinn(ed|ing)|SecTrustEvaluate|publicKeyHash|SPKI", swift_files(ENGINE / "QyvoraNetworking"))468 c.record("wallet", "network: endpoint acceptance (https, or http to local/private hosts only) enforced in the engine", bool(enforced),469 "EndpointConfiguration.isAcceptable enforced at: " + (listing(enforced) or "nowhere outside the editor")470 + f"; certificate pinning code: {'present' if pin else 'none (by design: endpoints are user-configurable; rated in the MASVS assessment)'}")471 if not enforced:472 c.find("QYV-STA-020", "Endpoint acceptance is only checked by the settings screen", "medium", rel(http),473 "EndpointConfiguration.isAcceptable is no longer applied when the engine builds its URL lists: a stored "474 "configuration could carry a cleartext or credential-bearing URL.",475 "Filter every endpoint list through isAcceptable where the clients are built.", cwe="CWE-319",476 masvs="MASVS-NETWORK-1", area="engine")477 else:478 c.skip("wallet", "network checks", "Sources/QyvoraNetworking/HTTP.swift missing")479480 # ---- wallet: Keychain and files ------------------------------------------------------------------------481 classes = grep(r"kSecAttrAccessible\w+", everything)482 allowed = {"kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly", "kSecAttrAccessibleWhenUnlockedThisDeviceOnly", "kSecAttrAccessible"}483 weak = [h for h in classes if set(re.findall(r"kSecAttrAccessible\w*", h[2])) - allowed]484 sync = grep(r"kSecAttrSynchronizable[^\n]*=\s*(true|kCFBooleanTrue)", everything)485 bio = grep(r"\.biometryCurrentSet|\.biometryAny|\.userPresence|\.devicePasscode", engine)486 ok = bool(classes) and not weak and not sync487 c.record("wallet", "Keychain: only WhenPasscodeSetThisDeviceOnly / WhenUnlockedThisDeviceOnly, nothing synchronizable", ok,488 f"accessibility references: {listing(classes)}; weaker classes: {len(weak)}; synchronizable: {len(sync)}; "489 f"access-control flags: {listing(bio) or 'none'}", cases=max(1, len(classes)))490 if not ok:491 c.find("QYV-STA-012", "Keychain item with a weak accessibility class", "high",492 loc(weak[0]) if weak else loc(sync[0]) if sync else "Sources/QyvoraStorage/KeychainStore.swift",493 "A Keychain item is readable while the device is locked, migrates to other devices, or synchronises "494 "through iCloud. Occurrences: " + (listing(weak + sync) or "no accessibility attribute found at all"),495 "Use kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly (or WhenUnlockedThisDeviceOnly for Secure Enclave keys).",496 cwe="CWE-522", masvs="MASVS-STORAGE-1", area="engine",497 cvss=("CVSS:3.1/AV:P/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", 4.6))498 store = ENGINE / "QyvoraStorage" / "FileStore.swift"499 if store.exists():500 t = store.read_text(errors="replace")501 prot = bool(re.search(r"completeFileProtection", t)) and bool(re.search(r"\.protectionKey", t))502 excl = bool(re.search(r"isExcludedFromBackup\s*=\s*true", t))503 direct = grep(r"\.write\s*\(\s*to\s*:|FileManager\.default\.createFile\s*\(|FileHandle\s*\(\s*forWritingTo|NSKeyedArchiver|OutputStream\s*\(", everything)504 direct = [h for h in direct if h[0] != rel(store)]505 ok = prot and excl and dp == "NSFileProtectionComplete"506 c.record("wallet", "files: FileStore applies data protection and backup exclusion; default protection class is Complete", ok,507 f"file protection applied: {prot}; isExcludedFromBackup = true: {excl}; entitlement: {dp!r}; "508 f"writes outside FileStore: {listing(direct) or 'none'}", cases=3)509 if not ok:510 c.find("QYV-STA-013", "Wallet files not protected or not excluded from backups", "medium", rel(store),511 f"FileStore protection applied: {prot}; backup exclusion: {excl}; default-data-protection entitlement: {dp!r}. "512 "The vault file is encrypted by the application, but the platform protections are the second layer.",513 "Restore the protection key, isExcludedFromBackup and the NSFileProtectionComplete entitlement.",514 cwe="CWE-311", masvs="MASVS-STORAGE-1", area="engine")515 c.record("wallet", "files: writes outside FileStore (inventory)", True,516 "direct writes (exports chosen by the user and benchmark reports are expected here): " + (listing(direct) or "none"),517 cases=max(1, len(direct)))518 else:519 c.skip("wallet", "file storage checks", "Sources/QyvoraStorage/FileStore.swift missing")520521 # ---- wallet: the screens reach the signature and the import through one door each ----------------------522 # (QYV-APP-020/041/060/082, QYV-APP-080, QYV-APP-101, QYV-SVC-087: properties of the 2026-12-05 review of App/Sources)523 wallet_sources = swift_files(ENGINE / "QyvoraWallet")524525 def fenced(hits):526 """Hits that are outside every `#if DEBUG` region."""527 out, cache = [], {}528 for h in hits:529 flags = cache.setdefault(h[0], debug_regions(REPO / h[0]))530 if not (h[1] - 1 < len(flags) and flags[h[1] - 1]):531 out.append(h)532 return out533534 side_doors = grep(r"\.\s*(signAndBroadcastEthereum|signAndBroadcastBitcoin|signAndBroadcastCoin|signPSBT|signColdEthereumPayload|signEthereum|signSolana|signTron)\s*\(", app)535 sign_calls = grep(r"\.\s*(signAndBroadcast|signColdTransaction)\s*\(", app)536 unacknowledged = [h for h in sign_calls if "acknowledged:" not in h[2]]537 public_bare = grep(r"public\s+func\s+signAndBroadcast\s*\(\s*_\s+review\s*:\s*SendReview\s*\)|"538 r"public\s+func\s+signColdTransaction\s*\([^)]*acceptUnverifiedAmounts\s*:\s*Bool\s*=\s*false\s*\)|"539 r"public\s+func\s+importWatchOnly\s*\(\s*package\s+input\s*:\s*\[String\]\s*\)", wallet_sources)540 rule = grep(r"static func requireAcknowledged\(", wallet_sources)541 ok = not side_doors and not unacknowledged and not public_bare and bool(rule) and len(sign_calls) >= 2542 c.record("wallet", "signing: the application signs only through the calls that take the acknowledged critical warnings", ok,543 f"{len(sign_calls)} signature call(s) in App/Sources, without `acknowledged:`: {len(unacknowledged)}; calls of a family-specific signing function: "544 f"{len(side_doors)}; public form without the rule in the service: {len(public_bare)}; rule present: {bool(rule)}"545 + ("; " + listing(side_doors + unacknowledged + public_bare) if side_doors or unacknowledged or public_bare else ""))546 if not ok:547 c.find("QYV-STA-021", "A screen can sign without stating which critical warnings were acknowledged", "high",548 loc((side_doors + unacknowledged + public_bare + [("Sources/QyvoraWallet/WalletService+Send.swift", 1, "")])[0]),549 "The service refuses a signature unless every critical warning of the review was acknowledged by its identifier. That holds only while "550 "the application calls `signAndBroadcast(_:acknowledged:)` and `signColdTransaction(…acknowledged:)` and nothing else, and while the forms "551 "without the rule are not public. Occurrences: " + (listing(side_doors + unacknowledged + public_bare) or "the rule itself is missing"),552 "Call the two public signing functions only, with the set the acknowledgement controls filled.", cwe="CWE-356", masvs="MASVS-PLATFORM-3", area="app")553554 presets = fenced(grep(r"\b(allowBlind|acceptUnverified|compared)\s*=\s*true\b|\backnowledged\s*=\s*(Set\(|\[\s*\")|\backnowledged\.(insert|formUnion)\s*\(", app))555 # the one sanctioned write: the binding of the control itself556 presets = [h for h in presets if not (h[0].endswith("Wallet/WarningAcknowledgement.swift") and "acknowledged.insert(warning.id)" in h[2])]557 defaults_on = grep(r"@State\s+private\s+var\s+(allowBlind|acceptUnverified|compared|acknowledged)\b[^\n]*=\s*(true|Set\(\[|\[\s*\")", app)558 c.record("wallet", "acknowledgements: no consent is set by the code (controls start off, only their own binding turns them on)", not presets and not defaults_on,559 f"assignments outside the control and outside #if DEBUG: {len(presets)}; consent states that start on: {len(defaults_on)}"560 + ("; " + listing(presets + defaults_on) if presets or defaults_on else ""))561 if presets or defaults_on:562 c.find("QYV-STA-022", "A consent or an acknowledgement is set by the code instead of the user", "high", loc((presets + defaults_on)[0]),563 "Blind signing, unverified amounts, the comparison of a watch-only package and the acknowledgement of a critical warning must be turned on "564 "by the user. Occurrences: " + listing(presets + defaults_on),565 "Remove the assignment; a screenshot helper belongs inside #if DEBUG.", cwe="CWE-356", masvs="MASVS-PLATFORM-3", area="app")566567 package_imports = grep(r"\.\s*importWatchOnly\s*\(\s*package\s*:", app)568 without_code = [h for h in package_imports if "comparedFingerprint:" not in h[2]]569 shows_code = grep(r"watchOnlyPreview\s*\(", swift_files(APP / "Security")) and grep(r"watchOnlyPreview\s*\(", swift_files(APP / "Onboarding"))570 ok = bool(package_imports) and not without_code and bool(shows_code)571 c.record("wallet", "watch-only package: both screens compute its code, and the import states the code compared", ok,572 f"package imports in App/Sources: {len(package_imports)}, without `comparedFingerprint:`: {len(without_code)}; preview computed on the export and on the import side: {bool(shows_code)}")573 if not ok:574 c.find("QYV-STA-023", "A watch-only package can be imported without the comparison of its code", "high",575 loc((without_code + [("App/Sources/Onboarding/WatchOnlyFlow.swift", 1, "")])[0]),576 "A watch-only package is not authenticated (QYV-APP-080): the code shown on both devices and stated at the import is what detects a substitution.",577 "Show `WalletService.watchOnlyPreview` on both sides and import with `importWatchOnly(package:comparedFingerprint:)`.",578 cwe="CWE-345", masvs="MASVS-PLATFORM-3", area="app")579580 own_parsing = grep(r"\bqueryItems\b|URLComponents\s*\(\s*string\s*:", [f for f in app if "/Wallet/" in rel(f) or "/Onboarding/" in rel(f)])581 parser = REPO / "Sources" / "QyvoraWallet" / "PaymentRequests.swift"582 parser_text = parser.read_text(errors="replace") if parser.exists() else ""583 bounded = all(k in parser_text for k in ("maximumRequestLength", "maximumAddressLength", "maximumMemoLength", 'hasPrefix("req-")', "func matches(_ chain: ChainDescriptor)"))584 flow = (APP / "Wallet" / "SendFlow.swift").read_text(errors="replace") if (APP / "Wallet" / "SendFlow.swift").exists() else ""585 start = flow[flow.find(" func start() {"):flow.find(" func restart() {")] if " func start() {" in flow and " func restart() {" in flow else ""586 auto_advance = bool(re.search(r"\bprepare\s*\(|signAndBroadcast|\.step\s*=\s*\.(review|export|result)", start.split("if let handedReview {")[0] + (start.split("return\n }", 1)[1] if "return\n }" in start else "")))587 form_checks = grep(r"payment\.matches\(descriptor\)", [APP / "Wallet" / "SendFormView.swift"]) if (APP / "Wallet" / "SendFormView.swift").exists() else []588 ok = not own_parsing and bounded and bool(start) and not auto_advance and bool(form_checks)589 c.record("wallet", "payment requests: parsed by the bounded engine parser only, checked against the network of the form, never advanced to a review", ok,590 f"URL parsing in the wallet screens: {len(own_parsing)}; parser bounds and scheme rule present: {bounded}; a scanned request opens the form only: {bool(start) and not auto_advance}; "591 f"the form checks the scheme and the network of a scanned request: {bool(form_checks)}" + ("; " + listing(own_parsing) if own_parsing else ""))592 if not ok:593 c.find("QYV-STA-024", "A payment request can reach the send flow outside the bounded parser, or past the form", "medium",594 loc((own_parsing + [("App/Sources/Wallet/SendFlow.swift", 1, "")])[0]),595 "Payment requests are attacker-controlled (QYV-APP-101): they are parsed by `WalletScanParser` (lengths bounded, unknown required parameters and "596 "contract calls refused, scheme bound to the family), fill the visible form only and never open a review by themselves.",597 "Parse with `WalletScanParser.parse`, check `Payment.matches`, and leave the Review button to the user.", cwe="CWE-20", masvs="MASVS-PLATFORM-1", area="app")598599 one_price = grep(r"\bfreshUSDPrice\s*\(", engine)600 market = (ENGINE / "QyvoraWallet" / "WalletService+Market.swift").read_text(errors="replace") if (ENGINE / "QyvoraWallet" / "WalletService+Market.swift").exists() else ""601 ceilings = grep(r"\bnativeCeiling\s*\(\s*usd\s*:|\btokenUSDPerTransaction\b|\.allows\s*\(\s*wei\s*:", wallet_sources)602 # the converter's own lines: the agreement is computed from the two quotes (and once more after a re-read), its603 # result is what is returned, and nothing takes the lower of the two (the regression tests prove the behaviour)604 rules = (market.count("MainnetPolicy.agreedCeilingPrice(") >= 2 and "var agreement = MainnetPolicy.agreedCeilingPrice(first, second)" in market605 and "guard let agreed = agreement else" in market and "return agreed" in market606 and "MainnetPolicy.stablecoinCeilingPrice(quote: first)" in market and "MainnetPolicy.isPlausibleUSDPrice(agreed, priceID: id)" in market607 and not re.search(r"\bmin\s*\(\s*first\s*,\s*second\s*\)", market))608 converters = grep(r"\blimitUSDPrice\s*\(", wallet_sources)609 ok = not one_price and rules and len(converters) >= 8610 c.record("wallet", "dollar ceilings: converted only by limitUSDPrice (peg rule or two agreeing sources, floors)", ok,611 f"single-source conversions left: {len(one_price)}; rules present in the converter: {rules}; uses of the converter: {len(converters)}; "612 f"sites that apply a dollar ceiling (inventory): {len(ceilings)}")613 if not ok:614 c.find("QYV-STA-025", "A dollar ceiling is converted outside the cross-checked price function", "high",615 loc((one_price + [("Sources/QyvoraWallet/WalletService+Market.swift", 1, "")])[0]),616 "A ceiling in dollars allows `ceiling / price` units: a price that is too low lifts it (QYV-SVC-082, QYV-SVC-087). Every conversion goes through "617 "`limitUSDPrice`, which applies the peg rule or the agreement of two sources, and the floors.",618 "Use `limitUSDPrice` for every dollar ceiling.", cwe="CWE-345", masvs="MASVS-NETWORK-1", area="engine")619620 findings = apply_triage(c.findings)621 failed = sum(r["failed"] for r in c.records)622 metrics = {623 "checks": len(c.records), "checks_failed": sum(1 for r in c.records if r["failed"]),624 "checks_not_run": sum(1 for r in c.records if r["skipped"]),625 "engine_files": len(engine), "app_files": len(app), "findings": len(findings), "failed_cases": failed,626 }627 return tool_result(tool="static-checks", category="static", status=RUN, version="repository checks (security/audit/runners/static_checks.py)",628 coverage=COVERAGE, command="python3 security/audit/runners/static_checks.py", metrics=metrics,629 duration_s=time.time() - started,630 tests=c.records, findings=findings)631632633if __name__ == "__main__":634 print(json.dumps(run(Context("full" if "--full" in sys.argv else "quick")), indent=2))635