Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project : QYVORA7# File : security/audit/runners/mobsfscan.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"""mobsfscan runner: MobSF's source-code rule set over the Swift sources (Sources/ and App/Sources).4243mobsfscan drives Semgrep through libsast with `--metrics=off`; here it also runs with44SEMGREP_SEND_METRICS=off and, on macOS, under `sandbox-exec` with every network operation denied.4546Two kinds of result:47 * code matches (a file and a line): findings to triage;48 * "best practice" rules, which fire when a protective construct is ABSENT from the whole code base49 (certificate pinning, jailbreak detection, anti-debugging, custom-keyboard restriction, keyboard50 cache): reported as informational findings without a location; they are design questions rated in51 the MASVS assessment, not defects located by the tool.5253Standalone: python3 security/audit/runners/mobsfscan.py54"""5556from __future__ import annotations5758import json59import os60import shutil61import sys62from pathlib import Path6364sys.path.insert(0, str(Path(__file__).resolve().parents[1]))65from lib.common import (FAILED, REPO, RUN, Context, apply_triage, finding, load_json, not_run, # noqa: E40266 run_cmd, tool_pins, tool_result, which)6768TARGETS = ["Sources", "App/Sources"]69NO_NETWORK = "(version 1)(allow default)(deny network*)"70COVERAGE = (71 "mobsfscan's iOS rule set for Swift is small: {swift_rules} Semgrep rules (weak hashes and TLS versions, "72 "UIWebView, logging calls, keychain accessibility, biometric ACLs, hard-coded secret names, random "73 "generators, pasteboard) plus 2 Objective-C pattern rules that do not apply to this code base. It runs on "74 "source text only, with the same Swift parsing limits as Semgrep (files with Swift 6 constructs are "75 "parsed partially). It knows nothing about wallets or about cryptography written from scratch."76)777879def _swift_rule_count() -> int | None:80 exe = which("mobsfscan")81 if not exe:82 return None83 venv = Path(exe).resolve().parent.parent84 count = 085 for d in venv.glob("lib/python*/site-packages/mobsfscan/rules/semgrep"):86 for sub in ("swift", "best_practices/swift"):87 for f in (d / sub).glob("*.yaml"):88 count += sum(1 for line in f.read_text().splitlines() if line.strip().startswith("- id:"))89 return count or None909192def run(ctx: Context) -> dict:93 exe = which("mobsfscan")94 n_rules = _swift_rule_count()95 coverage = COVERAGE.format(swift_rules=n_rules if n_rules is not None else "an unknown number of")96 if not exe:97 return not_run("mobsfscan", "static", "mobsfscan is not installed (run security/audit/install-tools.sh)", coverage)98 semgrep = which("semgrep")99 if not semgrep:100 return not_run("mobsfscan", "static", "mobsfscan needs semgrep, which is not installed", coverage)101 _, out, err, _ = run_cmd([exe, "--version"])102 import re103 m = re.search(r"v(\d+\.\d+\.\d+)", out + err)104 version = m.group(1) if m else ""105 pin = (tool_pins().get("tools", {}).get("mobsfscan", {}) or {}).get("version", "")106107 sandbox = []108 sb = shutil.which("sandbox-exec")109 if sb and run_cmd([sb, "-p", NO_NETWORK, "/usr/bin/true"])[0] == 0:110 sandbox = [sb, "-p", NO_NETWORK]111 raw = ctx.raw_path("mobsfscan.json")112 if raw.exists():113 raw.unlink()114 targets = [t for t in TARGETS if (REPO / t).exists()]115 env = {"PATH": f"{Path(semgrep).parent}:{os.environ.get('PATH', '')}",116 "SEMGREP_SEND_METRICS": "off", "SEMGREP_ENABLE_VERSION_CHECK": "0"}117 cmd = sandbox + [exe, "--json", "--no-fail", "-o", str(raw)] + targets118 code, out, err, secs = run_cmd(cmd, env=env, timeout=1800)119 data = load_json(raw)120 if data is None:121 return tool_result(tool="mobsfscan", category="static", status=FAILED, version=version, coverage=coverage,122 reason=f"no JSON output (exit {code}): {(out + err).strip()[-400:]}", duration_s=secs)123 errors = data.get("errors") or []124 fatal = [e for e in errors if isinstance(e, str)]125 if fatal:126 return tool_result(tool="mobsfscan", category="static", status=FAILED, version=version, coverage=coverage,127 reason="; ".join(fatal)[:400], duration_s=secs)128 partial = sorted({e.get("path", "") for e in errors if isinstance(e, dict) and e.get("path")})129130 sev = {"ERROR": "high", "WARNING": "medium", "INFO": "info"}131 findings, located, absent = [], 0, 0132 for rule, r in sorted((data.get("results") or {}).items()):133 md = r.get("metadata", {})134 severity = sev.get(md.get("severity", ""), "low")135 cwe = str(md.get("cwe", "")).split(":")[0]136 masvs = str(md.get("masvs", ""))137 desc = " ".join(str(md.get("description", "")).split())138 files = r.get("files") or []139 if not files:140 absent += 1141 findings.append(finding(142 title=f"mobsfscan best practice not detected in the source: {rule}", severity="info", location="",143 tool="mobsfscan", rule=rule, description=desc, cwe=cwe, masvs=masvs, area="app", evidence=rule,144 recommendation="Design question: see the MASVS assessment for the rating and the rationale."))145 continue146 for f in files:147 located += 1148 line = (f.get("match_lines") or [0])[0]149 text = " ".join(str(f.get("match_string", "")).split())[:200]150 findings.append(finding(151 title=f"{rule}: {text[:90]}", severity=severity, location=f"{f.get('file_path')}:{line}",152 tool="mobsfscan", rule=rule, description=desc, cwe=cwe, masvs=masvs, evidence=text,153 area="app" if str(f.get("file_path", "")).startswith("App/") else "engine",154 recommendation="Review the match; fix it, or record a justified triage entry in security/policies/triage.json."))155 findings = apply_triage(findings)156 metrics = {157 "swift_rules": n_rules, "located_matches": located, "absent_best_practices": absent,158 "files_parsed_partially": partial,159 "network": "denied by sandbox-exec (deny network*)" if sandbox else "not sandboxed (sandbox-exec unavailable)",160 "pinned_version": pin, "version_matches_pin": version == pin,161 }162 records = [{"area": "static", "name": "mobsfscan Swift rules", "algorithm": "", "parameter_set": "",163 "cases": n_rules or 0, "passed": (n_rules or 0) - len(data.get("results") or {}),164 "failed": len(data.get("results") or {}), "skipped": 0,165 "note": "rules evaluated / rules that reported (located matches and absent best practices); triage decides"}]166 return tool_result(tool="mobsfscan", category="static", status=RUN, version=version, duration_s=secs,167 coverage=coverage, command="mobsfscan --json --no-fail -o <raw> " + " ".join(targets),168 metrics=metrics, tests=records, findings=findings,169 artifacts=["security/reports/raw/mobsfscan.json"])170171172if __name__ == "__main__":173 print(json.dumps(run(Context("full" if "--full" in sys.argv else "quick")), indent=2))174