# 函数级差分模糊台:对每个含改写点的函数,Switch 原映像在 Unicorn 里整函数跑 = 真值,改写映像同输入整函数跑 = 被测,比终态。 # 用法:fnfuzz.py <改写产物目录> <模块> [--seed 1] [--trials 6] [--budget 200000] [--jobs N] [--mutate 200] [--funcs a,b,..] [--tsv 文件] # 装法:两份映像同址装载、同样应用 RELATIVE/ABS64/GLOB_DAT/JUMP_SLOT 重定位;导入符号指向陷阱页(每符号 16 字节)。 # 一次试验在以下事件停:返回哨兵(ret)、调导入(import:名)、宿主门(gate:原映像执行 svc / 读 cntpct 处,改写映像进 KGATE 哨兵)、访存异常、指令预算用完。 # 两边停在同一事件(ret / 同名 import / 同一 gate 原址)才算「有效」,此时比:x0–x30(x18 比槽值)、sp、nzcv、v0–v31、tpidr、 # 全部写过的地址的终值(不比当前 sp 以下的死栈与 TSD)。改写映像在门处多压的 x29/x30 按模板还原后再比。 # 不等价报 DIFF;有效试验为 0 的函数列 NOEFF(射程缺口,不算失败但要报)。任一边停下时 sp 出了栈区记「sp越界」不比较(输入不现实)。 # 变异自检:抽 mutate 个普通改写块把替换指令改成 nop,统计「被执行到的」里有几个被判出分歧。 # Function-level differential fuzzing bench: for each function containing a rewrite site, the original Switch image run as a whole function in Unicorn = ground truth, the rewritten image run as a whole function with the same input = under test; final states are compared. # Usage: fnfuzz.py [--seed 1] [--trials 6] [--budget 200000] [--jobs N] [--mutate 200] [--funcs a,b,..] [--tsv file] # Loading: both images are loaded at the same address with the same RELATIVE/ABS64/GLOB_DAT/JUMP_SLOT relocations applied; imported symbols point at a trap page (16 bytes per symbol). # A trial stops on one of these events: return sentinel (ret), call to an import (import:name), host gate (gate: where the original image executes svc / reads cntpct, the rewritten image enters the KGATE sentinel), memory access fault, instruction budget exhausted. # Only when both sides stop on the same event (ret / same-named import / same gate original address) is the trial "effective"; then compare: x0–x30 (x18 against the slot value), sp, nzcv, v0–v31, tpidr, # the final values of all written addresses (dead stack below the current sp and the TSD are not compared). The extra x29/x30 the rewritten image pushes at a gate are restored per the template before comparing. # Non-equivalence is reported as DIFF; functions with 0 effective trials are listed as NOEFF (a coverage gap, not a failure but must be reported). If sp is outside the stack area when either side stops, it is recorded as 「sp越界」(sp out of bounds) and not compared (unrealistic input). # Mutation self-check: draw mutate ordinary rewrite blocks and change the replaced instruction to nop, then count how many of those "actually executed" are judged divergent. import sys, os, struct, random, argparse, bisect, multiprocessing as mp from unicorn import * from unicorn.arm64_const import * from capstone import * sys.path.insert(0, os.path.dirname(__file__)) import nsoimg md = Cs(CS_ARCH_ARM64, CS_MODE_ARM) md.detail = True ap = argparse.ArgumentParser() ap.add_argument('dir'); ap.add_argument('mod'); ap.add_argument('nso') ap.add_argument('--seed', type=int, default=1); ap.add_argument('--trials', type=int, default=6) ap.add_argument('--budget', type=int, default=200000); ap.add_argument('--jobs', type=int, default=os.cpu_count()) ap.add_argument('--mutate', type=int, default=200); ap.add_argument('--funcs'); ap.add_argument('--tsv') A = ap.parse_args() IB = 0x100000000 ARENA, ARENA_SZ = 0x10000000, 0x1000000 # 随机堆:一半的 8 字节字是指回堆内的指针 | Random heap: half of the 8-byte words are pointers back into the heap STK, STK_SZ = 0x20000000, 0x100000; SP0 = STK + STK_SZ - 0x10000 # sp 以上留 64 KB 给栈传参 | 64 KB kept above sp for stack-passed arguments TSD = 0x30000000 TPA = TSD + 0x8000 # linux-bionic:模拟 Bionic 线程指针区,[TPA + TP_SLOT_OFF] = TSD | linux-bionic: emulated Bionic thread pointer area, [TPA + TP_SLOT_OFF] = TSD TRAP = 0x300000000; RET = 0x400000000; GATE = 0x500000000 hdr = nsoimg.header(A.dir, A.mod) PO, TE = hdr['PATCH_OFF'], hdr['TEXT_END'] KEY_IDX = {k[4:-4]: v for k, v in hdr.items() if k.startswith('KEY_') and k.endswith('_IDX')} KEY_SLOT = {k: 300 + i for i, k in enumerate(sorted(KEY_IDX, key=KEY_IDX.get))} K18, KTLS, KTLR, KGATE = (KEY_SLOT[k] for k in ('K18', 'KTLS', 'KTLR', 'KGATE')) KEY_PAGE_OFF = hdr['KEY_PAGE_OFF'] orig = bytearray(nsoimg.load(A.nso)) pat = bytearray(open(f'{A.dir}/{A.mod}.patched.bin', 'rb').read()) # ---- 重定位(两份映像一样)---- # ---- Relocations (identical for both images) ---- imports = {} for off, typ, name, val, add in nsoimg.relocs(bytes(orig)): if typ == 1027: v = IB + add elif val is not None: v = IB + val + (add if typ == 257 else 0) else: v = TRAP + 16 * imports.setdefault(name, len(imports)) + (add if typ == 257 else 0) for b in (orig, pat): struct.pack_into('