#!/usr/bin/env python3 # 从苹果包(IPA)里的 Guest.framework 反推改写前的模块映像,写成未压缩 NSO:给拿不到原 ExeFS、只有可运行 IPA 的场合重出别的 ABI(如 DM_ABI=android)。 # 做法:按 guest_dylib.py 的节布局拼回 patched.bin;text 里每条跳进补丁区的 b 按补丁块形态还原原指令(patch_nso.py 各 site_* 的逆); # 参数位按 patch_nso.py 的 PARAMS 表还原两条原字;最后按包内 <名>.cuts.tsv 把剪口(含代码 / 数据)还原成原字节。 # 判据:用同一规则域(IPA 为 touch:DM_RULESET=touch-run-v4)苹果 ABI 重新改写,patched.bin / fixups / gates / cuts 须与包内逐字节一致(--check 自动做)。 # 局限:NSO 文件本身(lz4 压缩、表头校验值)复原不出,extract_game.sh 里的原文件 SHA256 对不上;包里没有 subsdk0(视频库,宿主不加载); # sdk 的构建号包里没有,写全 0(改写器只按构建号查 main 的登记表)。 # 用法:ipa_unpatch.py <输出目录> [--check] 输出 <输出目录>/{main,sdk} # Reconstruct the pre-rewrite module images from Guest.framework inside an Apple package (IPA) and write them as uncompressed NSOs: for when the original ExeFS is unavailable and only a runnable IPA is, so another ABI (e.g. DM_ABI=android) can be built. # Method: reassemble patched.bin from the section layout of guest_dylib.py; for every b in text that jumps into the patch area, restore the original instruction from the patch block's shape (the inverse of each site_* in patch_nso.py); # parameter slots get both original words back from patch_nso.py's PARAMS table; finally the package's .cuts.tsv restores cuts (code / data) to their original bytes. # Criterion: rewriting again with the same rule domain (the IPA is touch: DM_RULESET=touch-run-v4) and the Apple ABI must reproduce patched.bin / fixups / gates / cuts byte for byte (--check does this). # Limits: the NSO file itself (lz4 compression, header hashes) cannot be recovered, so the original-file SHA256 in extract_game.sh will not match; the package has no subsdk0 (video library, not loaded by the host); # the package does not carry sdk's build ID, so it is written as all zeros (the rewriter only looks up main's registries by build ID). # Usage: ipa_unpatch.py [--check] writes /{main,sdk} import os, re, struct, subprocess, sys, tempfile, zipfile from itertools import combinations from capstone import Cs, CS_ARCH_ARM64, CS_MODE_ARM HERE = os.path.dirname(os.path.abspath(__file__)) MODS = ('main', 'sdk') BUILD_IDS = {'main': 'db0507f36b84200ac05f75d76ed5026f'} PG = 0x4000 md = Cs(CS_ARCH_ARM64, CS_MODE_ARM); md.detail = True W = lambda b, o: struct.unpack_from('> p) & 31 == S] got = [] for k in range(len(pos), 0, -1): for c in combinations(pos, k): w = nw for p in c: w = (w & ~(31 << p)) | (18 << p) try: ins = dis(w, pc) except AssertionError: continue if not re.search(r'\b[xw]18\b', ins.op_str): continue want = re.sub(r'\b([xw])18\b', lambda m: f'{m.group(1)}{S}', ins.op_str) if dis(nw, pc).mnemonic != ins.mnemonic or dis(nw, pc).op_str != want: continue used = regs_in(ins) if S in used or (T is not None and (T in used or [r for r in range(16) if r not in used and r != 18][:2] != [S, T])): continue got.append((k, w)) if not got: return None # 多个候选正向改写都得 nw 时(立即数字段恰为 S,如逻辑立即数的 immr)取替换字段最少的:编码器给的规范编码;--check 的重改写仍须逐字节一致 # When several candidates all rewrite forward to nw (an immediate field happens to equal S, e.g. immr of a logical immediate), take the one with the fewest # substituted fields: the canonical encoding an assembler emits; --check still requires the re-rewrite to match byte for byte kmin = min(k for k, _ in got); best = {w for k, w in got if k == kmin} assert len(best) == 1, f'{pc:#x} {nw:08x} S=x{S}:候选 {[hex(x) for x in best]}' if len(got) > 1: AMBIG.append(pc) return best.pop() AMBIG = [] class Block: """补丁块读取器:跳过槽块基址前缀(apple:mrs tpidrro)+ 键页三条,返回 (基址寄存器, 键下标, 后续偏移)。 | Patch block reader.""" def __init__(self, pat, key_idx): self.pat, self.kv = pat, {v: k for k, v in key_idx.items()} def w(self, o): return W(self.pat, o) def slot(self, o): w = self.w(o); assert w & 0xFFFFFFE0 == 0xD53BD060, f'{o:#x} 不是 mrs tpidrro:{w:08x}' T = w & 31; ldr = self.w(o + 8) assert self.w(o + 4) & 0x9F000000 == 0x90000000 and ldr & 0xFFC00000 == 0xF9400000 and self.w(o + 12) & 0xFFE0FFFF == 0x8B000000 | (T << 5) | T, f'{o:#x} 键页序列不符' return T, self.kv[(ldr >> 10) & 0xFFF], o + 16 def restore(name, app, gates): hdr = header(app[f'dm/{name}.fixups.tsv'].decode()) se = sections(app['Frameworks/Guest.framework/Guest']) te, po, ko = hdr['TEXT_END'], hdr['PATCH_OFF'], hdr['KEY_PAGE_OFF'] pat = bytearray(se[f'__dm{name}x0'] + se[f'__DM{name}W'] + se[f'__dm{name}x1']) assert len(se[f'__dm{name}x0']) == r16(te) and len(se[f'__dm{name}x0']) + len(se[f'__DM{name}W']) == po assert pat[ko:ko + PG] == bytes(PG), '键页不是全 0' key_idx = {k[4:-4]: v for k, v in hdr.items() if k.startswith('KEY_') and k.endswith('_IDX')} B = Block(pat, key_idx) img = bytearray(pat[:ko]) gate_at = {orig: (k, arg) for ret, k, arg, orig in gates} params = {a: (wa, b, wb) for a, wa, b, wb in params_table()} if name in BUILD_IDS else {} cuts = [] if f'dm/{name}.cuts.tsv' in app: for l in app[f'dm/{name}.cuts.tsv'].decode().splitlines(): if l.startswith('#') or not l.strip(): continue f = l.split('\t'); cuts.append((int(f[0], 16), bytes.fromhex(f[1]), bytes.fromhex(f[2]))) cut_b = {off: nb for off, ob, nb in cuts if len(nb) == 4 and bt(W(nb, 0), off) is not None and bt(W(nb, 0), off) >= po} st = {} def put(o, w, kind): struct.pack_into('> 10) & 31 w1 = B.w(n) if w1 & 0x9F00001F == 0x90000000 | S: # adrp xS → adr / adrp x18 tgt = (n & ~0xFFF) + (((((w1 >> 5) & 0x7FFFF) << 2 | (w1 >> 29) & 3) ^ 0x100000) - 0x100000 << 12) if B.w(n + 4) & 0xFFC003FF == 0x91000000 | (S << 5) | S: tgt += (B.w(n + 4) >> 10) & 0xFFF; d = tgt - o put(o, 0x10000000 | ((d & 3) << 29) | (((d >> 2) & 0x7FFFF) << 5) | 18, 'adr') else: d = (tgt >> 12) - (o >> 12) put(o, 0x90000000 | ((d & 3) << 29) | (((d >> 2) & 0x7FFFF) << 5) | 18, 'adrp') continue assert w1 == 0xF9400000 | (T << 5) | S, f'{s:#x} 读槽不符' n += 4; w2 = B.w(n); m = dis(w2, n).mnemonic if B.w(n + 4) == 0xF9000000 | (T << 5) | S and B.w(n + 8) & 0xFFC07FFF == 0xA9400000 | (T << 10) | (31 << 5) | S and bt(B.w(n + 12), n + 12) == o + 4: w0 = unsubst(w2, S, o, T); assert w0 is not None, f'{o:#x} 普通块还原不出 x18' put(o, w0, 'plain'); continue if m in ('cbz', 'cbnz', 'tbz', 'tbnz') and w2 & 31 == S and bt(B.w(n + 8), n + 8) == o + 4: tgt = bt(B.w(n + 16), n + 16); off = (tgt - o) >> 2 nw = ((w2 & 0xFF000000) | ((off & 0x7FFFF) << 5) | 18) if m in ('cbz', 'cbnz') else ((w2 & 0xFFF80000) | ((off & 0x3FFF) << 5) | 18) put(o, nw, 'cond'); continue # 独占窗口:块里依次是窗口指令的拷贝,首条即原处那条(窗口首条是独占读,不是分支) # Exclusive window: the block holds copies of the window instructions in order; the first is the one at the original site (an exclusive load, not a branch) assert dis(w2, o).mnemonic.startswith(('ldxr', 'ldaxr', 'ldxp', 'ldaxp')), f'{o:#x} 窗口首条 {dis(w2, o).mnemonic}' w0 = unsubst(w2, S, o); put(o, w2 if w0 is None else w0, 'window') for off, ob, nb in cuts: assert bytes(img[off:off + len(nb)]) == nb, f'剪口 {off:#x} 现值 {bytes(img[off:off + len(nb)]).hex()} ≠ 新字节 {nb.hex()}' img[off:off + len(ob)] = ob st['cut'] = len(cuts) return img, hdr, st, pat def write_nso(path, img, hdr, build_id): te, ro, da, ko = hdr['TEXT_END'], hdr['RO_OFF'], hdr['DATA_OFF'], hdr['KEY_PAGE_OFF'] segs = [(0, te), (ro, da - ro), (da, ko - da)] # data 拉到键页前、bss 0:映像长 = KEY_PAGE_OFF,改写器算出同一 KEY_PAGE_OFF / PATCH_OFF h = bytearray(0x100); h[0:4] = b'NSO0' off = 0x100 for i, (mo, sz) in enumerate(segs): struct.pack_into(' <输出目录> [--check]') app = read_app(a[0]); os.makedirs(a[1], exist_ok=True); ok = True for name in MODS: gates = [] for l in app[f'dm/{name}.gates.tsv'].decode().splitlines(): r, k, arg, orig = l.split(); gates.append((int(r, 16), k, int(arg), int(orig, 16))) img, hdr, st, pat = restore(name, app, gates) write_nso(os.path.join(a[1], name), img, hdr, BUILD_IDS.get(name, '00' * 16)) print(name, st, '多候选取规范编码', len(AMBIG)); AMBIG.clear() if '--check' in sys.argv: c = check(name, a[1], app, pat); ok &= c; print(f' {name} 苹果 ABI 重改写 {"与包内逐字节一致" if c else "不一致"}') sys.exit(0 if ok else 1) if __name__ == '__main__': main()