Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project : QYVORA7# File : security/audit/runners/binary_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"""Own checks on the compiled iOS application (Qyvora.app of the unsigned Release archive).4243Independent of MobSF: Mach-O header and load commands (PIE, stack execution, canaries, ARC,44runpaths, encryption info, linked libraries), symbols (stripped, dSYM separate), debug code,45Info.plist (ATS, usage descriptions, file sharing, URL schemes, QYInternalMainnet), entitlements,46privacy manifest, bundle content, and a scan of the embedded strings for secrets, recovery47phrases and network endpoints. Each check is one test record (area "binary"); each failed check48is a finding QYV-BIN-NNN for the integrator (this runner never edits the application).4950Expected values live in security/policies/mobsf.json, key "binary_checks".5152Standalone: `python3 security/audit/runners/binary_checks.py [path/to/Qyvora.app]`53"""5455from __future__ import annotations5657import fnmatch58import hashlib59import json60import plistlib61import re62import sys63import time64from pathlib import Path65from urllib.parse import urlsplit6667sys.path.insert(0, str(Path(__file__).resolve().parents[1]))68from lib.common import NOT_RUN, POLICIES, REPO, RUN, Context, finding, load_json, run_cmd, tool_result # noqa: E40269from runners import ipa_build # noqa: E4027071TOOL = "binary-checks"72COVERAGE = (73 "Static inspection of the unsigned Release build with the Xcode command-line tools (otool, nm, strings, "74 "codesign, dwarfdump, plutil): compiler/linker hardening flags, linked libraries, symbols, Info.plist, "75 "entitlements file, bundle content, embedded strings (secret patterns, recovery phrases, URLs). "76 "It proves properties of the binary that was built here, not of the binary Apple distributes (signing, "77 "FairPlay encryption and App Store processing happen later). String scanning finds literal secrets only; "78 "it says nothing about run-time behaviour. No dynamic analysis, no jailbroken-device test.")7980URL_RE = re.compile(r"https?://[A-Za-z0-9._~:/?#\[\]@!$&()*+,;=%-]+")81SECRET_PATTERNS = {82 "PEM private key": re.compile(r"-----BEGIN (?:RSA |EC |DSA |OPENSSH |ENCRYPTED |PGP )?PRIVATE KEY"),83 "AWS access key id": re.compile(r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b"),84 "Slack token": re.compile(r"\bxox[baprs]-[0-9A-Za-z-]{10,}"),85 "GitHub token": re.compile(r"\bgh[pousr]_[0-9A-Za-z]{36,}\b"),86 "Google API key": re.compile(r"\bAIza[0-9A-Za-z_-]{35}\b"),87 "JSON Web Token": re.compile(r"\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}"),88 "BIP-32 extended private key": re.compile(r"\b[xtyzuv]prv[1-9A-HJ-NP-Za-km-z]{100,108}\b"),89 "Bitcoin WIF private key": re.compile(r"(?<![1-9A-HJ-NP-Za-km-z])(?:5[HJK][1-9A-HJ-NP-Za-km-z]{49}|[KLc][1-9A-HJ-NP-Za-km-z]{51})(?![1-9A-HJ-NP-Za-km-z])"),90 "credentials in URL": re.compile(r"https?://[^/\s:@]+:[^/\s:@]+@[A-Za-z0-9.-]+"),91 "API key assignment": re.compile(r"(?i)\b(?:api[_-]?key|secret[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret)\s*[=:]\s*['\"]?[A-Za-z0-9/+_-]{20,}"),92 "API key in URL": re.compile(r"(?i)[?&](?:api[_-]?key|apikey|key|token|access_token)=[A-Za-z0-9_-]{12,}"),93 "provider project id in URL": re.compile(r"(?i)(?:infura\.io/v3|alchemy\.com/v2|g\.alchemy\.com/v2|quiknode\.pro)/[A-Za-z0-9_-]{16,}"),94}95REQUIRED_REASON_APIS = {96 "NSPrivacyAccessedAPICategoryUserDefaults": re.compile(r"\bUserDefaults\b|@AppStorage"),97 "NSPrivacyAccessedAPICategoryFileTimestamp": re.compile(r"\.creationDate\b|\.modificationDate\b|contentModificationDateKey|creationDateKey|\bfstat\(|\bstat\("),98 "NSPrivacyAccessedAPICategorySystemBootTime": re.compile(r"\bsystemUptime\b|mach_absolute_time\("),99 "NSPrivacyAccessedAPICategoryDiskSpace": re.compile(r"volumeAvailableCapacity|systemFreeSize|systemSize\b|statfs\("),100}101102103class Checks:104 def __init__(self):105 self.tests: list[dict] = []106 self.findings: list[dict] = []107108 def record(self, name: str, ok: bool | None, note: str = "") -> None:109 """ok=None: the check does not apply to this build (counted as skipped, never as passed)."""110 self.tests.append({"area": "binary", "name": name, "algorithm": "", "parameter_set": "",111 "cases": 0 if ok is None else 1, "passed": 1 if ok else 0, "failed": 1 if ok is False else 0,112 "skipped": 1 if ok is None else 0, "note": note[:600]})113114 def find(self, id: str, title: str, severity: str, location: str, description: str, recommendation: str,115 cwe: str = "", masvs: str = "", evidence: str = "", status: str = "open") -> None:116 f = finding(id=id, title=title, severity=severity, tool=TOOL, location=location, description=description,117 recommendation=recommendation, cwe=cwe, masvs=masvs, area="app-binary", evidence=evidence,118 status=status, rule=id)119 self.findings.append(f)120121122def tool(*cmd: str, timeout: int = 180) -> str:123 code, out, err, _ = run_cmd(list(cmd), timeout=timeout)124 return out if code == 0 else out + err125126127def line_of(path: Path, needle: str) -> str:128 try:129 for i, line in enumerate(path.read_text(errors="replace").splitlines(), 1):130 if needle in line:131 return f"{path.relative_to(REPO)}:{i}"132 except OSError:133 pass134 return str(path.relative_to(REPO))135136137def swift_sources() -> list[Path]:138 return sorted(p for base in (REPO / "Sources", REPO / "App" / "Sources") for p in base.rglob("*.swift"))139140141def bip39_words() -> set[str]:142 text = (REPO / "Sources/QyvoraCore/HD/BIP39English.swift").read_text(errors="replace")143 body = text.split("END OF SP BOUCHER SOURCE HEADER")[-1]144 words = set()145 for line in body.splitlines(): # the list is stored as lines made only of lower-case words146 tokens = line.strip().strip('"').split()147 if tokens and all(re.fullmatch(r"[a-z]{3,8}", t) for t in tokens):148 words.update(tokens)149 return words if len(words) == 2048 else set()150151152def find_mnemonics(strings: list[str], words: set[str]) -> list[str]:153 """Runs of >= 12 BIP-39 words that are not a slice of the (alphabetical) word list itself."""154 hits = []155 for s in strings:156 tokens = s.strip().split(" ")157 if len(tokens) < 12 or len(tokens) > 24 * 4:158 continue159 if all(t in words for t in tokens) and tokens != sorted(tokens):160 hits.append(s.strip())161 return hits162163164def run_checks(app: Path, dsym: Path | None, policy: dict) -> tuple[Checks, dict]:165 c = Checks()166 metrics: dict = {}167 exe = app / "Qyvora"168 info = plistlib.loads((app / "Info.plist").read_bytes())169 info_src = REPO / "App/Resources/Info.plist"170 ent_src = REPO / "App/Resources/Qyvora.entitlements"171 bloc = "App (compiled binary): Qyvora.app/Qyvora"172 metrics["bundle"] = {k: info.get(k) for k in ("CFBundleIdentifier", "CFBundleShortVersionString", "CFBundleVersion",173 "MinimumOSVersion", "DTSDKName", "DTXcode", "UIDeviceFamily")}174 metrics["executable_sha256"] = hashlib.sha256(exe.read_bytes()).hexdigest()175176 # --- Mach-O header and load commands ---------------------------------------------------------177 header = tool("otool", "-hv", str(exe))178 flags = header.strip().splitlines()[-1].split() if header.strip() else []179 metrics["macho_flags"] = [f for f in flags if f.isupper() and not f.startswith("MH_MAGIC")]180 pie = "PIE" in flags181 c.record("Mach-O: position-independent executable (PIE)", pie, "otool -hv flags: " + " ".join(metrics["macho_flags"]))182 if not pie:183 c.find("QYV-BIN-010", "Release binary is not position independent", "high", bloc,184 "The MH_PIE flag is missing: ASLR does not apply to the main executable.",185 "Remove any -no_pie linker flag; PIE is the Xcode default.", cwe="CWE-119", masvs="MASVS-CODE-4")186 nostack = "ALLOW_STACK_EXECUTION" not in flags187 c.record("Mach-O: stack not executable", nostack, "MH_ALLOW_STACK_EXECUTION absent" if nostack else "flag present")188 if not nostack:189 c.find("QYV-BIN-011", "Release binary allows stack execution", "high", bloc,190 "MH_ALLOW_STACK_EXECUTION is set.", "Remove -allow_stack_execute.", cwe="CWE-119", masvs="MASVS-CODE-4")191192 undefined = set(tool("nm", "-u", str(exe)).split())193 metrics["imported_symbols"] = len(undefined)194 canary = "___stack_chk_guard" in undefined and "___stack_chk_fail" in undefined195 c.record("Stack canaries (___stack_chk_guard / ___stack_chk_fail imported)", canary)196 if not canary:197 c.find("QYV-BIN-012", "Release binary has no stack canary", "medium", bloc,198 "Neither ___stack_chk_guard nor ___stack_chk_fail is imported.",199 "Build with -fstack-protector-strong (Xcode default); check custom OTHER_CFLAGS / OTHER_SWIFT_FLAGS.",200 cwe="CWE-121", masvs="MASVS-CODE-4")201 arc = any(s.startswith("_objc_release") for s in undefined) and any(s.startswith("_swift_release") for s in undefined)202 c.record("Automatic reference counting (objc_release / swift_release imported)", arc,203 "Swift has no manual memory-management mode; the check confirms the runtime entry points are used")204205 load = tool("otool", "-l", str(exe))206 rpaths = re.findall(r"cmd LC_RPATH\n\s+cmdsize \d+\n\s+path (\S+)", load)207 metrics["rpaths"] = rpaths208 frameworks_dir = app / "Frameworks"209 embedded = sorted(str(p.relative_to(app)) for p in app.rglob("*") if p.suffix in (".dylib", ".framework", ".appex", ".bundle"))210 metrics["embedded_code"] = embedded211 bad_rpaths = [r for r in rpaths if r not in ("@executable_path/Frameworks", "/usr/lib/swift")]212 c.record("Runpaths limited to the application bundle", not bad_rpaths,213 f"LC_RPATH: {rpaths or 'none'}; Frameworks directory in bundle: {frameworks_dir.exists()}")214 if bad_rpaths:215 c.find("QYV-BIN-013", "Unexpected runpath in the Release binary", "medium", bloc,216 f"LC_RPATH entries outside the bundle: {bad_rpaths}.", "Remove custom LD_RUNPATH_SEARCH_PATHS entries.",217 cwe="CWE-426", masvs="MASVS-CODE-4", evidence=", ".join(bad_rpaths))218 c.record("No embedded dynamic library, framework or extension in the bundle", not embedded, f"found: {embedded or 'none'}")219 if embedded:220 c.find("QYV-BIN-014", "Bundle embeds dynamic code", "low", "App (bundle): Qyvora.app",221 f"The engine is specified as dependency-free, yet the bundle embeds: {embedded}.",222 "Confirm each embedded item is first-party and expected.", masvs="MASVS-CODE-3", evidence=", ".join(embedded))223224 libs = re.findall(r"^\s+(\S+) \(compatibility", tool("otool", "-L", str(exe)), flags=re.M)225 prefixes = tuple(policy.get("allowed_library_prefixes", []))226 outside = [l for l in libs if not l.startswith(prefixes)]227 fw = sorted({m.group(1) for l in libs if (m := re.search(r"/([A-Za-z0-9_]+)\.framework/", l))})228 unexpected_fw = [f for f in fw if f not in set(policy.get("expected_frameworks", []))]229 metrics["linked_libraries"] = len(libs)230 metrics["linked_frameworks"] = fw231 c.record("Linked libraries are system libraries only (no third-party dylib)", not outside,232 f"{len(libs)} libraries, all under /System/Library/Frameworks, /usr/lib/swift, libobjc, libSystem"233 if not outside else f"outside the system paths: {outside}")234 if outside:235 c.find("QYV-BIN-015", "Release binary links a non-system library", "medium", bloc,236 f"Libraries outside the system paths: {outside}.", "Remove the dependency or justify it.",237 masvs="MASVS-CODE-3", evidence=", ".join(outside))238 c.record("Linked system frameworks match the expected list", not unexpected_fw,239 "frameworks: " + ", ".join(fw) + (f"; not in the expected list: {unexpected_fw}" if unexpected_fw else ""))240 if unexpected_fw:241 c.find("QYV-BIN-016", "Release binary links a system framework that is not on the expected list", "info", bloc,242 f"New framework(s): {unexpected_fw}. A new framework can add a capability (network, location, contacts…).",243 "Review why it is needed, then add it to security/policies/mobsf.json (binary_checks.expected_frameworks).",244 masvs="MASVS-PLATFORM-1", evidence=", ".join(unexpected_fw))245246 m = re.search(r"cmd LC_ENCRYPTION_INFO(?:_64)?\n(?:.*\n){1,4}?\s+cryptid (\d+)", load)247 metrics["cryptid"] = int(m.group(1)) if m else None248 c.record("Encryption info load command present (FairPlay applied by the App Store)", m is not None,249 f"cryptid {metrics['cryptid']}: 0 is expected before App Store processing; not a protection we control")250251 # --- Banned / weak imports ---------------------------------------------------------------------252 banned = sorted(undefined & set(policy.get("banned_imports", [])))253 metrics["banned_imports_found"] = banned254 c.record("No banned C function, non-system random generator or weak hash imported", not banned,255 "checked: " + ", ".join(policy.get("banned_imports", [])) if not banned else f"imported: {banned}")256 if banned:257 c.find("QYV-BIN-017", "Release binary imports a banned function", "medium", bloc,258 f"Imported symbols on the banned list: {banned} (unsafe C string functions, non-SecRandom generators, MD5/SHA-1, "259 "dynamic loading).", "Locate the caller in the Swift sources and replace it; the engine draws randomness from "260 "SecRandomCopyBytes only.", cwe="CWE-676", masvs="MASVS-CRYPTO-1", evidence=", ".join(banned))261 secrandom = "_SecRandomCopyBytes" in undefined262 c.record("SecRandomCopyBytes imported (system CSPRNG is the entropy source)", secrandom)263 logging = sorted(s for s in undefined if s in ("_NSLog", "_NSLogv", "__os_log_impl", "_os_log_create", "_printf", "_puts", "_fputs", "_syslog"))264 metrics["logging_symbols_imported"] = logging265 src_log = []266 log_re = re.compile(r"(?<![A-Za-z0-9_.])(?:NSLog|os_log|print|debugPrint|dump)\(|\bLogger\(")267 for p in swift_sources():268 if "qyvora-bench" in p.parts:269 continue270 for i, line in enumerate(p.read_text(errors="replace").splitlines(), 1):271 if log_re.search(line) and not line.lstrip().startswith("//"):272 src_log.append(f"{p.relative_to(REPO)}:{i}")273 metrics["logging_calls_in_app_sources"] = src_log[:50]274 c.record("Logging entry points: imports vs calls in the shipped sources", None if logging and not src_log else not src_log,275 f"imported: {logging or 'none'}; logging calls found in Sources/ and App/Sources (excluding the benchmark CLI): {len(src_log)}. "276 "Imports without a source call come from SwiftUI/Foundation code inlined into the binary; this check cannot tell what they log"277 if not src_log else f"logging calls: {src_log[:10]}")278279 # --- Symbols and debug code ----------------------------------------------------------------------280 all_syms = tool("nm", "-a", str(exe)).splitlines()281 defined_local = [l for l in all_syms if re.match(r"^[0-9a-f]{16} [a-z] ", l)]282 # "radr://5614542" is the marker the `strip` tool itself leaves in a stripped binary: not a debug symbol.283 debug_stabs = [l for l in all_syms if re.match(r"^[0-9a-f]{16} - ", l) and "radr://5614542" not in l]284 strip_marker = any("radr://5614542" in l for l in all_syms)285 exported = [l for l in tool("nm", "-gU", str(exe)).splitlines() if l.strip()]286 has_dwarf = "segname __DWARF" in load287 metrics["symbols"] = {"local_defined": len(defined_local), "debug_stab_entries": len(debug_stabs),288 "exported": len(exported), "dwarf_segment_in_binary": has_dwarf}289 stripped = not debug_stabs and not has_dwarf and len(defined_local) <= 50290 c.record("Release binary stripped (no debug symbols, no local symbol table)", stripped,291 f"local defined symbols {len(defined_local)}, debug entries {len(debug_stabs)}, exported {len(exported)}, __DWARF segment {has_dwarf}, strip marker {strip_marker}")292 if not stripped:293 c.find("QYV-BIN-018", "Release binary is not stripped", "low", bloc,294 f"{len(defined_local)} local symbols and {len(debug_stabs)} debug entries remain; they ease reverse engineering.",295 "Keep STRIP_INSTALLED_PRODUCT=YES, COPY_PHASE_STRIP=YES and DEBUG_INFORMATION_FORMAT=dwarf-with-dsym for Release.",296 cwe="CWE-215", masvs="MASVS-RESILIENCE-3")297 if dsym and dsym.exists():298 uuids = set(re.findall(r"UUID: ([0-9A-F-]{36})", tool("dwarfdump", "--uuid", str(exe))))299 dsym_uuids = set(re.findall(r"UUID: ([0-9A-F-]{36})", tool("dwarfdump", "--uuid", str(dsym))))300 c.record("Debug information kept in a separate dSYM matching the binary UUID", bool(uuids) and uuids == dsym_uuids,301 f"binary {sorted(uuids)}, dSYM {sorted(dsym_uuids)}")302 else:303 c.record("Debug information kept in a separate dSYM matching the binary UUID", None, "no dSYM next to this build")304305 raw_strings = tool("strings", "-a", "-n", "6", str(exe)).splitlines()306 metrics["strings_scanned"] = len(raw_strings)307 blob = "\n".join(raw_strings)308 debug_markers = set()309 for name in ("DebugGallery.swift", "DebugLaunch.swift"):310 p = REPO / "App/Sources" / name311 if p.exists():312 debug_markers.add(p.stem)313 debug_markers.update(re.findall(r"-(QY[A-Za-z]+)\b", p.read_text(errors="replace")))314 present = sorted(mk for mk in debug_markers if mk in blob or any(mk in l for l in all_syms))315 metrics["debug_markers_checked"] = sorted(debug_markers)316 c.record("DEBUG-only code absent from the Release binary (DebugGallery, DebugLaunch, -QY… launch arguments)", not present,317 f"{len(debug_markers)} markers searched in strings and symbols" + (f"; present: {present}" if present else "; none present"))318 if present:319 c.find("QYV-BIN-019", "DEBUG-only code is present in the Release binary", "medium",320 "App/Sources/DebugLaunch.swift:41",321 f"Markers of the debug launch arguments / debug gallery found in the Release executable: {present}. "322 "These paths open screens directly and bypass the normal flow.",323 "Keep both files entirely inside `#if DEBUG` and check SWIFT_ACTIVE_COMPILATION_CONDITIONS of the Release configuration.",324 cwe="CWE-489", masvs="MASVS-RESILIENCE-3", evidence=", ".join(present))325 paths = sorted({s.strip() for s in raw_strings if re.fullmatch(r"[\w/+.-]+\.swift", s.strip())})326 metrics["source_file_paths_in_binary"] = len(paths)327 absolute = [p for p in paths if p.startswith("/")]328 c.record("No absolute build path (developer home directory) embedded in the binary", not absolute,329 f"{len(paths)} module-relative Swift file identifiers (used by runtime traps), absolute paths: {len(absolute)}")330 if absolute:331 c.find("QYV-BIN-020", "Absolute source paths embedded in the Release binary", "info", bloc,332 f"{len(absolute)} absolute paths reveal the build machine layout, e.g. {absolute[:3]}.",333 "Use #fileID instead of #file/#filePath in shipped code.", cwe="CWE-200", masvs="MASVS-RESILIENCE-3")334335 # --- Embedded strings: secrets, recovery phrases, endpoints --------------------------------------336 bundle_text = []337 for p in sorted(app.rglob("*")):338 if p.is_file() and p != exe and p.suffix not in (".png", ".car"):339 try:340 data = p.read_bytes()341 bundle_text.append(json.dumps(plistlib.loads(data), default=str) if p.suffix == ".plist" or data[:6] == b"bplist"342 else data.decode("utf-8", "replace"))343 except Exception: # noqa: BLE001 - unreadable resource: scanned as raw text below344 bundle_text.append(p.read_bytes().decode("latin-1"))345 car = app / "Assets.car"346 car_strings = tool("strings", "-a", "-n", "8", str(car)).splitlines() if car.exists() else []347 haystack = raw_strings + car_strings + [l for t in bundle_text for l in t.splitlines()]348 secret_hits = []349 for label, rx in SECRET_PATTERNS.items():350 for s in haystack:351 if rx.search(s):352 secret_hits.append(f"{label}: {s.strip()[:80]}")353 metrics["secret_patterns_checked"] = sorted(SECRET_PATTERNS)354 c.record("Embedded strings: no secret pattern (private keys, tokens, API keys, credentials in URLs)", not secret_hits,355 f"{len(haystack)} strings of the executable and bundle resources against {len(SECRET_PATTERNS)} patterns"356 + (f"; hits: {secret_hits[:5]}" if secret_hits else ""))357 if secret_hits:358 c.find("QYV-BIN-021", "Secret-like literal embedded in the application", "high", bloc,359 f"{len(secret_hits)} string(s) of the shipped bundle match a secret pattern.",360 "Remove the literal from the sources; rotate the credential if it is real.", cwe="CWE-798",361 masvs="MASVS-STORAGE-1", evidence="; ".join(secret_hits[:10]))362 words = bip39_words()363 if words:364 mnemonics = find_mnemonics(haystack, words)365 allow = policy.get("public_test_mnemonics_sha256", {})366 unknown = [m for m in mnemonics if hashlib.sha256(m.encode()).hexdigest() not in allow]367 metrics["mnemonic_like_strings"] = len(mnemonics)368 metrics["public_test_mnemonics_allowlisted"] = len(mnemonics) - len(unknown)369 c.record("Embedded strings: no recovery phrase other than allow-listed public test vectors", not unknown,370 f"{len(mnemonics)} BIP-39 phrase(s) found, {len(mnemonics) - len(unknown)} are public reference vectors listed with "371 "their justification in security/policies/mobsf.json")372 if unknown:373 c.find("QYV-BIN-022", "Recovery phrase literal embedded in the Release binary", "high", bloc,374 f"{len(unknown)} BIP-39 phrase(s) that are not on the list of public test vectors are compiled into the application "375 "(SHA-256 given as evidence, the phrase itself is not copied here).",376 "Remove the literal; if it is a public vector used by a self-test or benchmark, add its SHA-256 and source to the policy.",377 cwe="CWE-798", masvs="MASVS-STORAGE-1",378 evidence=", ".join(hashlib.sha256(m.encode()).hexdigest() for m in unknown))379 else:380 c.record("Embedded strings: no recovery phrase other than allow-listed public test vectors", None,381 "BIP-39 word list could not be read from Sources/QyvoraCore/HD/BIP39English.swift")382383 urls = sorted({u.rstrip("'\".,;)") for s in haystack for u in URL_RE.findall(s)})384 urls = [u for u in urls if urlsplit(u).hostname]385 hosts = sorted({urlsplit(u).hostname for u in urls})386 source_hosts = set()387 for p in swift_sources() + [info_src]:388 body = p.read_text(errors="replace").split("END OF SP BOUCHER SOURCE HEADER")[-1]389 source_hosts.update(h for u in URL_RE.findall(body) if (h := urlsplit(u).hostname))390 expected = policy.get("expected_hosts", {})391 not_expected = [h for h in hosts if h not in expected]392 not_in_source = [h for h in hosts if h not in source_hosts]393 cleartext = [u for u in urls if u.startswith("http://") and u not in policy.get("cleartext_allowed", [])]394 metrics["urls_in_binary"] = urls395 metrics["hosts_in_binary"] = hosts396 c.record("Embedded endpoints: every host is on the reviewed list", not not_expected,397 f"{len(hosts)} hosts: {', '.join(hosts)}" + (f"; not reviewed: {not_expected}" if not_expected else ""))398 if not_expected:399 c.find("QYV-BIN-023", "Network endpoint in the binary that is not on the reviewed list", "low", bloc,400 f"Host(s) {not_expected} are compiled into the application but absent from the reviewed endpoint list.",401 "Confirm the endpoint is intended (default endpoints are user-configurable and never receive keys), then add it "402 "with its purpose to security/policies/mobsf.json (binary_checks.expected_hosts).",403 masvs="MASVS-NETWORK-1", evidence=", ".join(not_expected))404 c.record("Embedded endpoints: every host of the binary appears in the first-party sources", not not_in_source,405 "no host comes from anything other than Sources/, App/Sources or Info.plist" if not not_in_source406 else f"hosts with no first-party source literal: {not_in_source}")407 if not_in_source:408 c.find("QYV-BIN-024", "Network endpoint in the binary with no first-party source literal", "medium", bloc,409 f"Host(s) {not_in_source} are in the compiled application but in no Swift source of the repository.",410 "Find which linked code brings the URL.", masvs="MASVS-NETWORK-1", evidence=", ".join(not_in_source))411 c.record("Embedded endpoints: no cleartext http:// URL", not cleartext,412 "only the Info.plist DTD reference (never fetched)" if not cleartext else f"cleartext: {cleartext}")413 if cleartext:414 c.find("QYV-BIN-025", "Cleartext http:// endpoint embedded in the application", "medium", bloc,415 f"URL(s): {cleartext}.", "Use https:// only; ATS blocks cleartext by default.", cwe="CWE-319",416 masvs="MASVS-NETWORK-1", evidence=", ".join(cleartext))417418 # --- Info.plist --------------------------------------------------------------------------------------419 ats = info.get("NSAppTransportSecurity")420 ats_weak = []421 if isinstance(ats, dict):422 for key in ("NSAllowsArbitraryLoads", "NSAllowsArbitraryLoadsInWebContent", "NSAllowsArbitraryLoadsForMedia", "NSAllowsLocalNetworking"):423 if ats.get(key):424 ats_weak.append(key)425 for domain, conf in (ats.get("NSExceptionDomains") or {}).items():426 if isinstance(conf, dict) and (conf.get("NSExceptionAllowsInsecureHTTPLoads") or conf.get("NSExceptionMinimumTLSVersion") in ("TLSv1.0", "TLSv1.1")427 or conf.get("NSExceptionRequiresForwardSecrecy") is False):428 ats_weak.append(f"NSExceptionDomains[{domain}]")429 metrics["ats"] = ats if ats is not None else "key absent (system default: ATS fully enabled)"430 c.record("App Transport Security: no exception (default policy: TLS 1.2+, forward secrecy, no cleartext)", not ats_weak,431 "NSAppTransportSecurity absent from Info.plist" if ats is None else f"weakening keys: {ats_weak or 'none'}")432 if ats_weak:433 c.find("QYV-BIN-026", "App Transport Security is weakened in Info.plist", "high", line_of(info_src, "NSAppTransportSecurity"),434 f"ATS exceptions: {ats_weak}.", "Remove the exceptions; endpoints are https only.", cwe="CWE-319",435 masvs="MASVS-NETWORK-1", evidence=", ".join(ats_weak))436437 usage = sorted(k for k in info if k.endswith("UsageDescription"))438 extra = [k for k in usage if k not in policy.get("expected_usage_descriptions", [])]439 empty = [k for k in usage if not str(info.get(k, "")).strip()]440 metrics["usage_descriptions"] = {k: info[k] for k in usage}441 c.record("Permissions: usage descriptions limited to camera and Face ID, each with a purpose text", not extra and not empty,442 ", ".join(usage) + (f"; unexpected: {extra}" if extra else "") + (f"; empty: {empty}" if empty else ""))443 if extra or empty:444 c.find("QYV-BIN-027", "Unexpected or empty permission usage description", "low", line_of(info_src, (extra + empty)[0]),445 f"Unexpected: {extra}; empty: {empty}. A wallet that only scans QR codes and uses Face ID needs no other permission.",446 "Remove the permission or document why it is needed.", masvs="MASVS-PLATFORM-1", evidence=", ".join(extra + empty))447448 sharing = [k for k in ("UIFileSharingEnabled", "LSSupportsOpeningDocumentsInPlace", "UISupportsDocumentBrowser") if info.get(k)]449 c.record("Documents directory not exposed (no iTunes file sharing, no open-in-place)", not sharing,450 "UIFileSharingEnabled false/absent, LSSupportsOpeningDocumentsInPlace absent" if not sharing else f"enabled: {sharing}")451 if sharing:452 c.find("QYV-BIN-028", "Application documents are exposed to Files / Finder", "high", line_of(info_src, sharing[0]),453 f"{sharing} is enabled: the vault file and backups in Documents become readable by the user's computer and by Files.",454 "Disable the key; exports go through an explicit share sheet.", cwe="CWE-552", masvs="MASVS-STORAGE-2",455 evidence=", ".join(sharing))456 schemes = [s for t in info.get("CFBundleURLTypes", []) for s in t.get("CFBundleURLSchemes", [])]457 metrics["url_schemes"] = schemes458 c.record("No custom URL scheme registered (no deep-link entry point)", not schemes,459 "CFBundleURLTypes absent" if not schemes else f"schemes: {schemes} (each handler must validate its input)")460 if schemes:461 c.find("QYV-BIN-029", "Custom URL scheme registered", "info", line_of(info_src, "CFBundleURLTypes"),462 f"Schemes {schemes} are an entry point any application or web page can trigger.",463 "Treat every parameter as untrusted; never start a signature from a URL without the review screen.",464 cwe="CWE-939", masvs="MASVS-PLATFORM-1", evidence=", ".join(schemes))465 background = info.get("UIBackgroundModes", [])466 metrics["background_modes"] = background467 c.record("No background mode declared", not background, f"UIBackgroundModes: {background or 'absent'}")468469 mainnet = bool(info.get("QYInternalMainnet"))470 metrics["QYInternalMainnet"] = mainnet471 c.record("Info.plist key QYInternalMainnet (internal mainnet gate) — state recorded", None,472 f"present and true: {mainnet}. Informational: it is the owner's decision for the internal TestFlight build; "473 "a public build must not carry it")474 if mainnet:475 c.find("QYV-BIN-001", "This build declares QYInternalMainnet (mainnet enabled for internal testing)", "info",476 line_of(info_src, "QYInternalMainnet"),477 "Info.plist carries QYInternalMainnet = true. Together with the user switch it unlocks mainnet with the "478 "per-transaction limits of MainnetPolicy (Sources/QyvoraCore/Networks.swift). This is the owner's standing decision "479 "of 2026-12-04 for the internal TestFlight build only; the cryptography has had no independent review.",480 "Before any public distribution: remove the key (or set it to false) and re-run the audit; the release gate should "481 "refuse a public build whose Info.plist contains it.", masvs="MASVS-CODE-2", evidence="QYInternalMainnet=true")482 families = info.get("UIDeviceFamily", [])483 c.record("Device family matches the project setting (iPhone only)", families == [1],484 f"UIDeviceFamily in the built Info.plist: {families}; App/project.yml sets TARGETED_DEVICE_FAMILY \"1\"")485 if families != [1]:486 c.find("QYV-BIN-003", "Built application declares iPad support although the project targets iPhone only", "info",487 line_of(REPO / "App/project.yml", "TARGETED_DEVICE_FAMILY"),488 f"UIDeviceFamily is {families} in the compiled Info.plist while App/project.yml sets TARGETED_DEVICE_FAMILY to \"1\" "489 "at project level. The interface (privacy cover, review screens) has only been designed for iPhone; an iPad layout "490 "(split view, slide over, external display) is outside what was reviewed.",491 "Set TARGETED_DEVICE_FAMILY: \"1\" in the target settings of App/project.yml (the target-level default overrides the "492 "project-level value) and check the built Info.plist.", masvs="MASVS-PLATFORM-3", evidence=str(families))493494 # --- Entitlements -----------------------------------------------------------------------------------495 signed = "code object is not signed" not in tool("codesign", "-dv", str(app))496 metrics["signed"] = signed497 ent = {}498 if signed:499 out = tool("codesign", "-d", "--entitlements", "-", "--xml", str(app))500 try:501 ent = plistlib.loads(out[out.index("<?xml"):].encode()) if "<?xml" in out else {}502 except Exception: # noqa: BLE001503 ent = {}504 ent_origin = "codesign -d --entitlements (applied entitlements of the signed build)"505 else:506 try:507 ent = plistlib.loads(ent_src.read_bytes())508 except Exception: # noqa: BLE001509 ent = {}510 ent_origin = "App/Resources/Qyvora.entitlements (the build is unsigned: entitlements are not applied, the source file is read instead)"511 metrics["entitlements"] = ent512 metrics["entitlements_origin"] = ent_origin513 c.record("Code signature", None if not signed else True,514 "unsigned audit archive (CODE_SIGNING_ALLOWED=NO): signature, provisioning profile and applied entitlements must be "515 "checked on the signed build of the release pipeline" if not signed else "signed build")516 protection = ent.get("com.apple.developer.default-data-protection")517 c.record("Entitlement: default data protection is NSFileProtectionComplete", protection == "NSFileProtectionComplete",518 f"{protection!r} from {ent_origin}")519 if protection != "NSFileProtectionComplete":520 c.find("QYV-BIN-030", "Default data-protection class is weaker than NSFileProtectionComplete", "medium",521 "App/Resources/Qyvora.entitlements",522 f"com.apple.developer.default-data-protection is {protection!r}: files created without an explicit class are readable "523 "while the device is locked.", "Set the entitlement to NSFileProtectionComplete.", cwe="CWE-311", masvs="MASVS-STORAGE-1")524 risky = sorted(k for k in ent if k in ("get-task-allow", "com.apple.security.application-groups", "keychain-access-groups",525 "com.apple.developer.icloud-container-identifiers", "com.apple.developer.ubiquity-kvstore-identifier",526 "com.apple.developer.associated-domains", "aps-environment") and ent.get(k))527 if signed:528 risky = [k for k in risky if k != "keychain-access-groups"] # always present once signed (the app's own group)529 c.record("Entitlements: no debugger attachment, shared container, iCloud, push or associated domain", not risky,530 f"keys: {sorted(ent) or 'none'}" + (f"; to review: {risky}" if risky else ""))531 if risky:532 c.find("QYV-BIN-031", "Entitlement widening the attack surface", "medium" if "get-task-allow" in risky else "low",533 "App/Resources/Qyvora.entitlements",534 f"Entitlements {risky}: get-task-allow lets a debugger attach (development builds only); shared groups, iCloud and "535 "associated domains move data or entry points outside the application sandbox.",536 "Remove what the wallet does not need; a distribution build must not carry get-task-allow.",537 masvs="MASVS-RESILIENCE-4", evidence=", ".join(risky))538539 # --- Privacy manifest and bundle content -----------------------------------------------------------540 manifest = app / "PrivacyInfo.xcprivacy"541 used = {}542 for p in swift_sources():543 text = p.read_text(errors="replace")544 if "#if DEBUG" in text[:3000] and p.name.startswith("Debug"):545 continue546 for category, rx in REQUIRED_REASON_APIS.items():547 for i, line in enumerate(text.splitlines(), 1):548 if rx.search(line) and not line.lstrip().startswith("//"):549 used.setdefault(category, []).append(f"{p.relative_to(REPO)}:{i}")550 metrics["required_reason_api_usage"] = {k: v[:8] for k, v in used.items()}551 declared = set()552 if manifest.exists():553 try:554 declared = {e.get("NSPrivacyAccessedAPIType") for e in plistlib.loads(manifest.read_bytes()).get("NSPrivacyAccessedAPITypes", [])}555 except Exception: # noqa: BLE001556 declared = set()557 missing = sorted(set(used) - declared)558 c.record("Privacy manifest (PrivacyInfo.xcprivacy) present and covering the required-reason APIs used", not missing and (manifest.exists() or not used),559 f"manifest in bundle: {manifest.exists()}; required-reason API categories used in the sources: {sorted(used) or 'none'}; "560 f"not declared: {missing or 'none'}")561 if missing or (used and not manifest.exists()):562 first = next(iter(used.values()))[0] if used else "App/Resources"563 c.find("QYV-BIN-002", "No privacy manifest although required-reason APIs are used", "low", first,564 f"The bundle has {'no PrivacyInfo.xcprivacy' if not manifest.exists() else 'an incomplete PrivacyInfo.xcprivacy'}; the sources use "565 f"required-reason API categories {sorted(used)} (first uses: {[v[0] for v in used.values()]}). App Store Connect rejects or "566 "warns about such uploads (ITMS-91053), and the manifest is where the application states that it collects nothing and "567 "tracks nobody.",568 "Add App/Resources/PrivacyInfo.xcprivacy: NSPrivacyTracking false, NSPrivacyCollectedDataTypes empty, "569 "NSPrivacyAccessedAPITypes with NSPrivacyAccessedAPICategoryUserDefaults reason CA92.1 (and any other category listed "570 "here), and include it in the target resources.", masvs="MASVS-PRIVACY-1", evidence=", ".join(missing or sorted(used)))571572 allowed = policy.get("allowed_bundle_files", [])573 files = sorted(str(p.relative_to(app)) for p in app.rglob("*") if p.is_file())574 unexpected = [f for f in files if not any(fnmatch.fnmatch(f, pat) for pat in allowed)]575 metrics["bundle_files"] = files576 c.record("Bundle content limited to the expected files", not unexpected,577 f"{len(files)} files: {', '.join(files)}" + (f"; unexpected: {unexpected}" if unexpected else ""))578 if unexpected:579 c.find("QYV-BIN-032", "Unexpected file in the application bundle", "low", "App (bundle): Qyvora.app",580 f"Files not on the expected list: {unexpected}. Configuration files, databases, scripts or sources shipped by mistake "581 "are a common source of leaks.", "Remove the file from the target resources or add it to the policy with its purpose.",582 cwe="CWE-538", masvs="MASVS-STORAGE-2", evidence=", ".join(unexpected))583 native = [str(p.relative_to(REPO)) for base in (REPO / "Sources", REPO / "App") for p in base.rglob("*")584 if p.suffix in (".c", ".m", ".mm", ".cpp", ".cc", ".h", ".hpp", ".s", ".S") and "DerivedData" not in p.parts and "build" not in p.parts]585 # Reviewed exceptions are listed, with their purpose, in the policy: anything else fails the check.586 reviewed = policy.get("reviewed_native_sources", {})587 unreviewed = [f for f in native if f not in reviewed]588 metrics["native_c_family_sources"] = native589 metrics["native_c_family_sources_unreviewed"] = unreviewed590 c.record("No C, Objective-C, C++ or assembly source in the shipped modules beyond the reviewed list", not unreviewed,591 ("memory-unsafe languages absent from Sources/ and App/" if not native592 else f"reviewed exceptions only: {', '.join(native)}" if not unreviewed else f"not on the reviewed list: {unreviewed[:10]}"))593 return c, metrics594595596def run(ctx: Context) -> dict:597 start = time.time()598 policy = (load_json(POLICIES / "mobsf.json", {}) or {}).get("binary_checks", {})599 override = ctx.options.get("app_path")600 if override:601 app, dsym, state, signed_note = Path(override), None, {"commit": "(external build)", "dirty": None}, "external build"602 else:603 build = ipa_build.build(ctx)604 if not build["ok"]:605 return tool_result(tool=TOOL, category="mobile", status=NOT_RUN, coverage=COVERAGE, duration_s=time.time() - start,606 reason="no compiled application to inspect: " + build["reason"])607 app, dsym, state, signed_note = Path(build["app"]), Path(build["dsym"]), build["state"], "unsigned audit archive"608 if not (app / "Qyvora").exists() or not (app / "Info.plist").exists():609 return tool_result(tool=TOOL, category="mobile", status=NOT_RUN, coverage=COVERAGE, duration_s=time.time() - start,610 reason=f"{app} is not a Qyvora.app bundle")611 _, xv, _, _ = run_cmd(["xcodebuild", "-version"])612 checks, metrics = run_checks(app, dsym, policy)613 metrics.update(build_commit=state["commit"], build_dirty_tree=state["dirty"], build_kind=signed_note,614 checks=len(checks.tests), checks_passed=sum(t["passed"] for t in checks.tests),615 checks_failed=sum(t["failed"] for t in checks.tests),616 checks_not_applicable=sum(t["skipped"] for t in checks.tests))617 return tool_result(tool=TOOL, category="mobile", status=RUN, version="Xcode command-line tools: " + " ".join(xv.split()),618 command="otool -hv/-l/-L, nm -u/-a/-gU, strings -a, codesign -dv, dwarfdump --uuid on Qyvora.app/Qyvora",619 duration_s=time.time() - start, coverage=COVERAGE, metrics=metrics, tests=checks.tests,620 findings=checks.findings)621622623if __name__ == "__main__":624 options = {"app_path": sys.argv[1]} if len(sys.argv) > 1 else {}625 print(json.dumps(run(Context(mode="quick", options=options)), indent=2, default=str))626