#!/usr/bin/env python3 """Sign and install triage.ipa on a connected device using a free Apple account.""" import argparse import getpass import os import plistlib import shutil import subprocess import sys import tempfile import time from pathlib import Path ROOT = Path(__file__).resolve().parent IPA = ROOT / "triage.ipa" CERTS = ROOT / "certs" DIST = ROOT / "dist" KEY = CERTS / "triage.key" CSR = CERTS / "triage.certSigningRequest" CER = CERTS / "development.cer" P12 = CERTS / "triage.p12" PROFILE = CERTS / "triage.mobileprovision" BUNDLE = "" TTY = sys.stdout.isatty() def c(s, code): return f"\033[{code}m{s}\033[0m" if TTY else s def info(s): print(c("[*] ", "36") + s) def ok(s): print(c("[+] ", "32") + s) def warn(s): print(c("[!] ", "33") + s) def die(s): print(c("[-] ", "31") + s); sys.exit(1) def run(cmd, capture=False, check=True, cwd=None): kw = dict(cwd=cwd, text=True) kw.update(stdout=subprocess.PIPE, stderr=subprocess.PIPE) if capture else None p = subprocess.run([str(x) for x in cmd], **kw) if check and p.returncode != 0: err = (p.stderr or p.stdout or "").strip() die(f"{cmd[0]} failed ({p.returncode}): {err}") return p def have(binary): return shutil.which(binary) is not None def p12_pass(): pw = os.environ.get("TRIAGE_P12_PASS") if pw: return pw pw = getpass.getpass("p12 export password: ") if not pw: die("empty password") return pw def connected_udids(): if not have("idevice_id"): die("libimobiledevice-utils missing: sudo apt install libimobiledevice-utils usbmuxd") p = run(["idevice_id", "-l"], capture=True, check=False) return [u.strip() for u in p.stdout.split() if u.strip()] def one_udid(explicit=None): if explicit: return explicit udids = connected_udids() if not udids: die("no device found — unlock it, connect USB, run: idevicepair pair") if len(udids) > 1: die("multiple devices: " + ", ".join(udids) + " — pass --udid") return udids[0] def decode_profile(path): p = run(["openssl", "smime", "-verify", "-noverify", "-inform", "DER", "-in", path], capture=True) return plistlib.loads(p.stdout.encode() if isinstance(p.stdout, str) else p.stdout) def app_bundle_id(ipa): with tempfile.TemporaryDirectory() as td: run(["unzip", "-q", "-o", ipa, "-d", td]) apps = list(Path(td, "Payload").glob("*.app")) if not apps: die("no Payload/*.app in IPA") info_plist = apps[0] / "Info.plist" with open(info_plist, "rb") as fh: return plistlib.load(fh).get("CFBundleIdentifier") def cmd_doctor(_): info("checking toolchain") for b in ("openssl", "unzip", "zsign", "idevice_id", "idevicepair"): (ok if have(b) else warn)(f"{b}: {'found' if have(b) else 'MISSING'}") for b in ("pymobiledevice3", "ideviceinstaller"): if have(b): ok(f"installer: {b}"); break else: warn("no installer — pip install pymobiledevice3") udids = connected_udids() ok(f"devices: {len(udids)}") if udids else warn("no device connected") for f in (KEY, CER, P12, PROFILE): (ok if f.exists() else warn)(f"{f.name}: {'present' if f.exists() else 'absent'}") if not IPA.exists(): die("triage.ipa not found next to this script") def cmd_setup(args): CERTS.mkdir(exist_ok=True) if KEY.exists() and CER.exists(): ok("key and certificate already present"); return email = args.email or run(["git", "config", "user.email"], capture=True, check=False).stdout.strip() if not email: email = input("Apple ID email: ").strip() name = args.name or "Developer" info(f"generating 2048-bit key -> {KEY.name}") run(["openssl", "genrsa", "-out", KEY, "2048"]) run(["openssl", "req", "-new", "-key", KEY, "-out", CSR, "-sha256", "-subj", f"/emailAddress={email}/CN={name}/C=US"]) ok(f"CSR written: {CSR}") print(f""" Now, on the Mac: 1. Xcode > Settings > Accounts > add {email} > Manage Certificates > + > Apple Development (or reuse an existing one) 2. developer.apple.com is closed to free teams, so pull the .cer from Xcode: Keychain Access > My Certificates > "Apple Development: {email}" > right-click > Export "Apple Development: {email}"... > .cer 3. Save it to: {CER} 4. Xcode > Window > Devices > select the phone > it registers the UDID 5. Plug the phone in, Run the project once, then Product > Archive > Distribute App > Development > Export -> overwrite {IPA} 6. Copy the newest profile from ~/Library/MobileDevice/Provisioning Profiles/ -> {PROFILE} """) if args.wait: info("waiting for development.cer (Ctrl-C to abort)") while not CER.exists(): time.sleep(3) ok("certificate detected"); cmd_import_cert(args) def cmd_import_cert(args): CERTS.mkdir(exist_ok=True) if not CER.exists(): die(f"{CER} not found") pw = p12_pass() with tempfile.TemporaryDirectory() as td: pem = Path(td, "dev.pem") run(["openssl", "x509", "-inform", "DER", "-in", CER, "-out", pem]) run(["openssl", "pkcs12", "-export", "-inkey", KEY, "-in", pem, "-out", P12, "-passout", f"pass:{pw}"]) P12.chmod(0o600) ok(f"p12 built: {P12}") def cmd_profile(args): if not PROFILE.exists(): die(f"drop the .mobileprovision at {PROFILE}") udid = one_udid(args.udid) prof = decode_profile(PROFILE) b = app_bundle_id(IPA) ok(f"bundle in IPA: {b}") devs = prof.get("ProvisionedDevices", []) if udid not in devs: die(f"UDID {udid} not in profile (has {len(devs)} devices) — re-export the profile with this phone attached") ok("UDID is provisioned") if b not in prof.get("Entitlements", {}).get("application-identifier", ""): warn("bundle id does not match profile's application-identifier") exp = prof.get("ExpirationDate") if not exp or exp < __import__("datetime").datetime.now(): die(f"profile expired: {exp}") left = (exp - __import__("datetime").datetime.now()) ok(f"profile valid for {left.days}d {left.seconds // 3600}h") if not prof.get("Entitlements", {}).get("get-task-allow"): warn("get-task-allow false — not a development profile") def cmd_sign(args): args.bundle = args.bundle or app_bundle_id(IPA) if not IPA.exists(): die("triage.ipa not found") adhoc = args.adhoc if not adhoc: for f in (P12, PROFILE): if not f.exists(): die(f"{f.name} missing — run: setup / import-cert / profile") if not have("zsign"): die("zsign missing — build from https://github.com/zhlynn/zsign") DIST.mkdir(exist_ok=True) out = DIST / "triage-signed.ipa" with tempfile.TemporaryDirectory() as td: work = Path(td) run(["unzip", "-q", "-o", IPA, "-d", work]) apps = list(work.glob("Payload/*.app")) if not apps: die("no Payload/*.app in IPA") app = apps[0] for d in app.rglob("_CodeSignature"): shutil.rmtree(d, ignore_errors=True) for f in list(app.rglob("embedded.mobileprovision")) + list(app.rglob("*.p7s")): f.unlink(missing_ok=True) for p in [work / "Payload", *app.rglob("*")]: p.chmod(0o755 if p.is_dir() else 0o644) if adhoc: info("ad-hoc signing (no cert)") run(["zsign", "-a", "-o", out, app], cwd=work) else: info("signing") run(["zsign", "-k", P12, "-p", p12_pass(), "-m", PROFILE, "-b", args.bundle, "-o", out, app], cwd=work) ok(f"signed -> {out}") listing = run(["unzip", "-l", out], capture=True).stdout if not adhoc and "embedded.mobileprovision" not in listing: die("profile not embedded — signing failed") ok("embedded profile verified") def cmd_install(args): ipa = DIST / "triage-signed.ipa" if not ipa.exists(): die("nothing signed — run: sign") udid = one_udid(args.udid) run(["idevicepair", "pair"], check=False) if have("pymobiledevice3"): info("installing via pymobiledevice3") run(["pymobiledevice3", "apps", "install", ipa]) elif have("ideviceinstaller"): info("installing via ideviceinstaller") run(["ideviceinstaller", "-u", udid, "-i", ipa]) else: die("no installer — pip install pymobiledevice3") ok("installed") print(""" First launch will show 'Untrusted Developer': Settings > General > VPN & Device Management > Apple Development: you@... > Trust, then launch again. """) def cmd_deploy(args): cmd_doctor(args) if not (P12.exists() and PROFILE.exists()): cmd_setup(args) if not CER.exists(): die("certificate not returned yet — re-run deploy once it exists") cmd_import_cert(args) cmd_profile(args) else: cmd_profile(args) cmd_sign(args) if not args.skip_install: cmd_install(args) def cmd_ota(args): global BUNDLE BUNDLE = app_bundle_id(DIST / "triage-signed.ipa") """Write manifest.plist + index.html for the hosted install page.""" ipa = DIST / "triage-signed.ipa" if not ipa.exists(): die("sign first") base = args.base_url.rstrip("/") root = Path(args.webroot) root.mkdir(parents=True, exist_ok=True) shutil.copy2(ipa, root / "triage.ipa") (root / "manifest.plist").write_text(f""" items assets kindsoftware-packageurl{base}/triage.ipa metadata bundle-identifier{BUNDLE} bundle-version1.0 kindsoftware titleTriage """) (root / "index.html").write_text(f""" Install Triage

Triage

Open in Safari.

Install """) ok(f"OTA bundle written to {root}") def main(): ap = argparse.ArgumentParser(description=__doc__) ap.add_argument("--udid"); ap.add_argument("--email"); ap.add_argument("--name") sub = ap.add_subparsers(dest="cmd", required=True) for name, fn in (("doctor", cmd_doctor), ("setup", cmd_setup), ("import-cert", cmd_import_cert), ("profile", cmd_profile), ("sign", cmd_sign), ("install", cmd_install), ("deploy", cmd_deploy), ("ota", cmd_ota)): p = sub.add_parser(name); p.set_defaults(fn=fn) p.add_argument("--bundle") if name == "setup": p.add_argument("--wait", action="store_true") if name == "sign": p.add_argument("--adhoc", action="store_true") if name == "deploy": p.add_argument("--wait", action="store_true") p.add_argument("--adhoc", action="store_true") p.add_argument("--skip-install", action="store_true") if name == "ota": p.add_argument("--base-url", required=True); p.add_argument("--webroot", required=True) a = ap.parse_args() a.fn(a) if __name__ == "__main__": main()