Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project : QYVORA7# File : security/audit/runners/mobsf.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"""MobSF static analysis of the compiled iOS application, on our own infrastructure.4243Cycle (fully automatic, configuration in security/policies/mobsf.json):44 1. build the unsigned .ipa (runners/ipa_build.py);45 2. start the pinned MobSF image (tag + digest) in a container WITHOUT network (`--network none`),46 on this machine or on our server through SSH; no port is published;47 3. copy the .ipa into the container and call the MobSF REST API from inside the container48 (security/audit/mobsf/client.py through `docker exec`): upload, scan, report_json, delete_scan;49 4. save the raw report to security/reports/raw/mobsf-report.json and normalise it into findings;50 5. remove the container (with its volumes) and the copied .ipa, and verify that nothing is left.5152The hosted MobSF service is never used and no source code is submitted.53`--no-mobsf` (ctx.options["no_mobsf"]) records the tool as NOT RUN.5455Standalone: `python3 security/audit/runners/mobsf.py`56"""5758from __future__ import annotations5960import json61import secrets62import shlex63import sys64import time65from pathlib import Path6667sys.path.insert(0, str(Path(__file__).resolve().parents[1]))68from lib.common import (FAILED, NOT_RUN, POLICIES, RUN, SECURITY, Context, finding, load_json, not_run, rel, # noqa: E40269 run_cmd, tool_result, write_json)70from runners import ipa_build # noqa: E4027172TOOL = "mobsf"73CLIENT = SECURITY / "audit" / "mobsf" / "client.py"74COVERAGE_BASE = (75 "MobSF static analysis of the unsigned Release .ipa (Mach-O arm64 binary, Info.plist, bundle files). "76 "It inspects binary protections, imported symbols/APIs, Info.plist permissions and ATS, embedded strings, "77 "URLs, e-mails and secret patterns, and the files of the bundle. It does NOT analyse Swift source logic, "78 "it does not run the application (no dynamic analysis: that needs a jailbroken device or Corellium), and on a "79 "Linux host the checks that need macOS tools are skipped by MobSF. Because the container has no network, "80 "MobSF's online lookups (App Store metadata, domain reputation and geolocation, update check) do not happen. "81 "The archive is unsigned: code-signature, provisioning-profile and applied-entitlement checks do not apply.")828384class Docker:85 """Runs shell commands where the Docker daemon lives (locally or over SSH)."""8687 def __init__(self, policy: dict):88 self.mode = policy.get("mode", "ssh")89 self.host = policy.get("host", "")9091 def sh(self, command: str, timeout: int = 120, stdin: str | None = None):92 if self.mode == "ssh":93 cmd = ["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=15", self.host, command]94 else:95 cmd = ["sh", "-c", command]96 return run_cmd(cmd, timeout=timeout, stdin=stdin)9798 def copy_in(self, local: Path, remote: str, timeout: int = 600):99 if self.mode == "ssh":100 return run_cmd(["scp", "-q", "-o", "BatchMode=yes", str(local), f"{self.host}:{remote}"], timeout=timeout)101 return run_cmd(["cp", str(local), remote], timeout=timeout)102103 @property104 def where(self) -> str:105 return f"{self.host} (ssh)" if self.mode == "ssh" else "this machine"106107108def _first(d: dict, *keys, default=""):109 for k in keys:110 if d.get(k) not in (None, ""):111 return d[k]112 return default113114115def normalise(report: dict, severity_map: dict, triage: dict | None = None) -> tuple[list[dict], dict]:116 """MobSF iOS report -> findings + metrics. Only what MobSF reports is copied; nothing is added."""117 findings: list[dict] = []118 triage = triage or {}119 loc = "App (compiled binary): Qyvora.app/Qyvora"120121 def add(section: str, key: str, title: str, mobsf_sev: str, description: str, cwe="", masvs="", cvss=None, evidence=""):122 sev = severity_map.get(str(mobsf_sev).lower(), "info")123 if str(mobsf_sev).lower() in ("secure", "good", "info"):124 return # informational and positive items are counted in the metrics, not listed as findings125 f = finding(126 title=f"MobSF: {title}"[:160], severity=sev, tool=TOOL, rule=f"{section}/{key}", location=loc,127 description=description, cwe=cwe, masvs=masvs, cvss_score=cvss, area="app-binary",128 evidence=evidence or key,129 recommendation="Review in the context of the application; MobSF findings are pattern matches on the binary.")130 entry = triage.get(f"{section}/{key}")131 if entry: # reviewed MobSF item (security/policies/mobsf.json: triage), justification kept with the finding132 f["mobsf_severity"] = sev133 f["status"] = entry.get("status", f["status"])134 f["severity"] = entry.get("severity", f["severity"])135 f["triage"] = entry.get("justification", "")136 findings.append(f)137138 counts = {"high": 0, "warning": 0, "info": 0, "secure": 0, "good": 0, "hotspot": 0}139140 def count(sev):141 s = str(sev).lower()142 counts[s] = counts.get(s, 0) + 1143144 # Binary protections (PIE, ARC, canary, RPATH, encryption, symbols…)145 macho = report.get("macho_analysis") or {}146 protections = {}147 for key, item in macho.items():148 if isinstance(item, dict) and "severity" in item:149 protections[key] = {k: item.get(k) for k in ("severity", "description") if k in item}150 protections[key]["value"] = next((v for k, v in item.items() if k.startswith(("has_", "is_"))), None)151 count(item["severity"])152 add("macho", key, f"binary protection `{key}`", item["severity"], item.get("description", ""))153 # Binary code analysis (insecure APIs, weak crypto, logging…)154 binary = report.get("binary_analysis") or {}155 if isinstance(binary, dict) and isinstance(binary.get("findings"), dict):156 binary = binary["findings"] # MobSF 4.x layout: {"findings": {title: item}, "summary": {...}}157 items = binary.items() if isinstance(binary, dict) else enumerate(binary)158 binary_count = 0159 for key, item in items:160 if not isinstance(item, dict):161 continue162 binary_count += 1163 sev = _first(item, "severity", default="info")164 count(sev)165 add("binary", str(key), str(key)[:140], sev,166 str(_first(item, "detailed_desc", "description")), cwe=str(item.get("cwe", "")),167 masvs=str(item.get("masvs", "")), evidence=str(key))168 # App Transport Security169 ats = report.get("ats_analysis") or {}170 ats_items = ats.get("ats_findings", []) if isinstance(ats, dict) else ats171 for item in ats_items or []:172 if isinstance(item, dict):173 sev = _first(item, "severity", default="info")174 count(sev)175 add("ats", str(item.get("issue", "")), str(item.get("issue", "ATS")), sev, str(item.get("description", "")),176 evidence=str(item.get("issue", "")))177 # Permissions (usage descriptions)178 permissions = report.get("permissions") or {}179 # Dynamic libraries / frameworks bundled180 for lib in report.get("dylib_analysis") or []:181 if isinstance(lib, dict):182 for key, item in (lib.get("macho_analysis") or lib).items():183 if isinstance(item, dict) and "severity" in item:184 count(item["severity"])185 add("dylib", f"{lib.get('name', '')}/{key}", f"bundled library protection `{key}`", item["severity"],186 item.get("description", ""))187 # Code analysis over bundle (rare for .ipa) and secrets188 code = (report.get("code_analysis") or {})189 code_findings = code.get("findings", {}) if isinstance(code, dict) else {}190 for key, item in (code_findings or {}).items():191 meta = item.get("metadata", {}) if isinstance(item, dict) else {}192 sev = _first(meta, "severity", default="info")193 count(sev)194 add("code", key, str(_first(meta, "description", default=key))[:140], sev, str(meta.get("description", "")),195 cwe=str(meta.get("cwe", "")), masvs=str(meta.get("masvs", "")))196 secrets_found = report.get("secrets") or []197 for s in secrets_found:198 findings.append(finding(title="MobSF: possible hard-coded secret in the bundle", severity="high", tool=TOOL,199 rule="secrets", location=loc, description="MobSF secret pattern matched in the application bundle.",200 cwe="CWE-798", masvs="MASVS-STORAGE-1", area="app-binary", evidence=str(s)[:300],201 recommendation="Confirm manually; a public constant or documentation string is a false positive."))202 appsec = report.get("appsec") or {}203 metrics = {204 "mobsf_version": report.get("version", ""),205 "file_name": report.get("file_name", ""),206 "sha256": report.get("sha256", ""),207 "bundle_id": report.get("bundle_id", ""),208 "app_version": report.get("app_version", ""),209 "build": report.get("build", ""),210 "sdk_name": report.get("sdk_name", ""),211 "min_os_version": report.get("min_os_version", ""),212 "security_score": appsec.get("security_score"),213 "appsec_counts": {k: len(v) for k, v in appsec.items() if isinstance(v, list)},214 "macho_protections": protections,215 "binary_analysis_items": binary_count,216 "ats_items": len(ats_items or []),217 "permissions": sorted(permissions.keys()) if isinstance(permissions, dict) else permissions,218 "urls_found": len(report.get("urls") or []),219 "domains_found": sorted((report.get("domains") or {}).keys()) if isinstance(report.get("domains"), dict) else [],220 "emails_found": len(report.get("emails") or []),221 "secrets_found": len(secrets_found),222 "trackers": (report.get("trackers") or {}).get("detected_trackers") if isinstance(report.get("trackers"), dict) else None,223 "bundled_libraries": len(report.get("dylib_analysis") or []),224 "bundled_frameworks": len(report.get("framework_analysis") or []),225 "items_by_mobsf_severity": counts,226 "informational_items": sorted(str(k) for k, v in (binary.items() if isinstance(binary, dict) else [])227 if isinstance(v, dict) and str(v.get("severity", "")).lower() == "info"),228 "steps": [str(l.get("status")) for l in report.get("logs") or []],229 "steps_with_exception": [f"{l.get('status')}: {l.get('exception')}" for l in report.get("logs") or [] if l.get("exception")],230 }231 return findings, metrics232233234def run(ctx: Context) -> dict:235 policy = load_json(POLICIES / "mobsf.json", {}) or {}236 version = policy.get("version", "")237 if ctx.options.get("no_mobsf"):238 return not_run(TOOL, "mobile", "disabled on the command line (--no-mobsf)", COVERAGE_BASE)239 if not policy.get("digest"):240 return not_run(TOOL, "mobile", "security/policies/mobsf.json missing or without a pinned image digest", COVERAGE_BASE)241242 start = time.time()243 build = ipa_build.build(ctx)244 if not build["ok"]:245 return tool_result(tool=TOOL, category="mobile", status=NOT_RUN, version=version, coverage=COVERAGE_BASE,246 reason="no .ipa to analyse: " + build["reason"], duration_s=time.time() - start)247 ipa = Path(build["ipa"])248249 docker = Docker(policy)250 image = f"{policy['image']}@{policy['digest']}"251 name = policy.get("container", "qyvora-mobsf")252 q = shlex.quote253254 code, out, err, _ = docker.sh("docker version --format '{{.Server.Version}}'", timeout=40)255 if code != 0:256 return tool_result(tool=TOOL, category="mobile", status=NOT_RUN, version=version, coverage=COVERAGE_BASE,257 reason=f"Docker daemon not reachable on {docker.where}: {(err or out).strip()[:300]}",258 duration_s=time.time() - start)259 docker_version = out.strip()260261 code, _, _, _ = docker.sh(f"docker image inspect {q(image)} >/dev/null 2>&1")262 pulled = False263 if code != 0:264 code, out, err, _ = docker.sh(f"docker pull -q {q(image)}", timeout=1800)265 pulled = True266 if code != 0:267 return tool_result(tool=TOOL, category="mobile", status=NOT_RUN, version=version, coverage=COVERAGE_BASE,268 reason=f"cannot pull the pinned MobSF image: {(err or out).strip()[:300]}",269 duration_s=time.time() - start)270271 api_key = secrets.token_hex(32)272 workdir = ""273 cleanup = {"container_removed": False, "remote_ipa_removed": False, "image_kept": bool(policy.get("keep_image", True))}274 failure = ""275 payload = None276 client = CLIENT.read_text()277 try:278 docker.sh(f"docker rm -f -v {q(name)} >/dev/null 2>&1") # a leftover of an interrupted run, same name: ours279 code, out, err, _ = docker.sh("mktemp -d /tmp/qyvora-mobsf.XXXXXX")280 if code != 0:281 raise RuntimeError("mktemp failed: " + err.strip())282 workdir = out.strip()283 code, out, err, _ = docker.copy_in(ipa, f"{workdir}/Qyvora.ipa")284 if code != 0:285 raise RuntimeError("copy of the .ipa failed: " + (err or out).strip()[:300])286 code, out, err, _ = docker.sh(287 f"docker run -d --name {q(name)} --network {q(policy.get('network', 'none'))} "288 f"-e MOBSF_API_KEY={api_key} {q(image)}", timeout=300)289 if code != 0:290 raise RuntimeError("docker run failed: " + (err or out).strip()[:300])291 wait_s = int(policy.get("startup_timeout_s", 240))292 code, out, err, _ = docker.sh(293 f"docker exec -i -e QY_ACTION=wait -e QY_TIMEOUT={wait_s} {q(name)} python3 -", timeout=wait_s + 60, stdin=client)294 if code != 0:295 raise RuntimeError("MobSF did not start: " + (out or err).strip()[-300:])296 code, out, err, _ = docker.sh(f"docker cp {q(workdir + '/Qyvora.ipa')} {q(name)}:/tmp/Qyvora.ipa")297 if code != 0:298 raise RuntimeError("docker cp failed: " + (err or out).strip()[:300])299 scan_s = int(policy.get("scan_timeout_s", 1800))300 code, out, err, _ = docker.sh(301 f"docker exec -i -e QY_ACTION=scan -e QY_TIMEOUT={scan_s} -e QY_IPA=/tmp/Qyvora.ipa {q(name)} python3 -",302 timeout=scan_s + 120, stdin=client)303 try:304 payload = json.loads(out.strip().splitlines()[-1]) if out.strip() else None305 except ValueError:306 payload = None307 if code != 0 or not payload or "qy_error" in payload:308 raise RuntimeError("MobSF scan failed: " + ((payload or {}).get("qy_error") or (err or out).strip()[-400:]))309 except RuntimeError as e:310 failure = str(e)311 finally:312 docker.sh(f"docker rm -f -v {q(name)} >/dev/null 2>&1", timeout=120)313 code, out, _, _ = docker.sh(f"docker ps -a --filter name=^{q(name)}$ --format '{{{{.Names}}}}'")314 cleanup["container_removed"] = code == 0 and out.strip() == ""315 if workdir.startswith("/tmp/qyvora-mobsf."):316 docker.sh(f"rm -rf {q(workdir)}")317 code, _, _, _ = docker.sh(f"test -e {q(workdir)}")318 cleanup["remote_ipa_removed"] = code != 0319 if not cleanup["image_kept"]:320 docker.sh(f"docker rmi {q(image)} >/dev/null 2>&1", timeout=300)321322 command = (f"[{docker.where}] docker run -d --name {name} --network {policy.get('network', 'none')} "323 f"-e MOBSF_API_KEY=<random> {image}; docker cp Qyvora.ipa; docker exec -i {name} python3 - < "324 f"security/audit/mobsf/client.py (upload, scan, report_json, delete_scan); docker rm -f -v {name}")325 base_metrics = {"host": docker.where, "docker_version": docker_version, "image": image, "image_pulled_now": pulled,326 "container_network": policy.get("network", "none"), "ipa_sha256": build.get("ipa_sha256", ""),327 "ipa_commit": build["state"]["commit"], "ipa_dirty_tree": build["state"]["dirty"], "cleanup": cleanup}328 if failure:329 return tool_result(tool=TOOL, category="mobile", status=FAILED, version=version, reason=failure, command=command,330 duration_s=time.time() - start, coverage=COVERAGE_BASE, metrics=base_metrics)331332 report = payload["report"]333 raw = ctx.raw_path("mobsf-report.json")334 write_json(raw, report)335 if payload.get("scorecard"):336 write_json(ctx.raw_path("mobsf-scorecard.json"), payload["scorecard"])337 findings, metrics = normalise(report, policy.get("severity_map", {}), policy.get("triage", {}))338 base_metrics.update(metrics)339 base_metrics["scan_deleted_in_mobsf"] = bool(payload.get("scan_deleted"))340 base_metrics["findings_listed"] = len(findings)341 base_metrics["findings_open_after_triage"] = sum(1 for f in findings if f["status"] == "open")342 return tool_result(tool=TOOL, category="mobile", status=RUN, version=report.get("version") or version, command=command,343 duration_s=time.time() - start, coverage=COVERAGE_BASE, metrics=base_metrics, findings=findings,344 artifacts=[rel(raw)])345346347if __name__ == "__main__":348 result = run(Context(mode="quick"))349 print(json.dumps(result, indent=2))350