#!/usr/bin/env bash # ============================================================================ # ios27-triage.sh — stage-0 instrumentation for a 27.0.1 / A18 chain # # Does NOT find bugs. It resolves, downloads, extracts, runs the sandbox # reachability gate, produces a relocation-normalised kernelcache census and # ranked function diff, writes a report, and emits the option-3 harness tree. # # Everything it emits is evidence. Confirming a bug is manual, from the report. # # Usage: # ./ios27-triage.sh --build 24A446 # ./ios27-triage.sh --build 24A446 --skip-gate-a # ./ios27-triage.sh --scaffold-only --build 24A446 # ============================================================================ set -euo pipefail DEVICE="iPhone17,5" BASE_VER="27.0.1" PATCH_VERS=("27.2" "27.2.1") PIN_BUILD="" SKIP_GATE_A=0 SKIP_DIFF=0 SCAFFOLD_ONLY=0 ROOT="${HOME}/ios27-triage" STAMP="$(date -u +%Y%m%dT%H%M%SZ)" while [[ $# -gt 0 ]]; do case "$1" in --device) DEVICE="$2"; shift 2 ;; --build) PIN_BUILD="$2"; shift 2 ;; --base-version) BASE_VER="$2"; shift 2 ;; --patch-version) PATCH_VERS=("$2"); shift 2 ;; --out) ROOT="$2"; shift 2 ;; --skip-gate-a) SKIP_GATE_A=1; shift ;; --skip-diff) SKIP_DIFF=1; shift ;; --scaffold-only) SCAFFOLD_ONLY=1; shift ;; *) echo "unknown arg: $1"; exit 2 ;; esac done mkdir -p "$ROOT"/{ipsw,extract,kexts,report,logs,tools,project} LOG="$ROOT/logs/$STAMP.log" exec > >(tee -a "$LOG") 2>&1 say() { printf '\n[*] %s\n' "$*"; } die() { printf '\n[!] %s\n' "$*" >&2; exit 1; } need() { command -v "$1" >/dev/null 2>&1; } say "ios27-triage $STAMP device=$DEVICE base=$BASE_VER pin=${PIN_BUILD:-none}" # ---------------------------------------------------------------- preflight if [[ $SCAFFOLD_ONLY -eq 0 ]]; then say "preflight" sudo apt-get update -qq sudo apt-get install -y -qq git curl jq python3 cmake libfuse3-dev fuse3 \ zlib1g-dev libssl-dev libbz2-dev pkg-config llvm clang ca-certificates if ! need go; then say "installing go" GOVER="$(curl -fsS https://go.dev/VERSION?m=text | head -1)" curl -fsSL "https://go.dev/dl/${GOVER}.linux-amd64.tar.gz" -o /tmp/go.tgz sudo rm -rf /usr/local/go && sudo tar -C /usr/local -xzf /tmp/go.tgz fi export PATH="$PATH:/usr/local/go/bin:$HOME/go/bin:/usr/lib/llvm-19/bin" if ! need ipsw; then say "installing ipsw" go install github.com/blacktop/ipsw/cmd/ipsw@latest \ || die "ipsw install failed — check go version" fi need ipsw || die "ipsw not on PATH" OBJDUMP="" for c in llvm-objdump-19 llvm-objdump-18 llvm-objdump aarch64-linux-gnu-objdump; do need "$c" && { OBJDUMP="$c"; break; } done [[ -n "$OBJDUMP" ]] || die "no aarch64-capable objdump found" say "objdump: $OBJDUMP" fi # ------------------------------------------------------------------ resolve # api.ipsw.me v4: /v4/device/?type=ipsw -> .firmwares[] {version,buildid,url,signed} api() { curl -fsS "https://api.ipsw.me/v4/device/${DEVICE}?type=ipsw"; } resolve_version() { # $1 version -> "buildidurl" api | jq -r --arg v "$1" \ '.firmwares[] | select(.version==$v) | "\(.buildid)\t\(.url)"' | head -1 } resolve_build() { # $1 buildid -> url api | jq -r --arg b "$1" \ '.firmwares[] | select(.buildid==$b) | .url' | head -1 } BASE_BUILD="$PIN_BUILD" BASE_URL="" if [[ -n "$PIN_BUILD" ]]; then BASE_URL="$(resolve_build "$PIN_BUILD")" else IFS=$'\t' read -r BASE_BUILD BASE_URL <<<"$(resolve_version "$BASE_VER")" fi [[ -n "${BASE_URL:-}" && "$BASE_URL" != "null" ]] || die "base $BASE_VER/$PIN_BUILD not resolvable" PATCH_LIST=() for v in "${PATCH_VERS[@]}"; do IFS=$'\t' read -r b u <<<"$(resolve_version "$v")" || true [[ -n "${u:-}" && "$u" != "null" ]] && PATCH_LIST+=("${b}|${u}") done [[ ${#PATCH_LIST[@]} -gt 0 ]] || die "no patch build resolvable" say "base build $BASE_BUILD ; patches ${#PATCH_LIST[@]}" printf '%s\n' "$BASE_BUILD" "${PATCH_LIST[@]%%|*}" > "$ROOT/report/builds.txt" # ----------------------------------------------------------------- download fetch() { # $1 build $2 url local f="$ROOT/ipsw/$1.ipsw" [[ -f "$f" ]] || { say "downloading $1"; curl -fL --retry 3 -o "$f" "$2"; } say "$1 $(stat -c%s "$f") bytes" printf '%s\n' "$f" } BASE_IPSW="$(fetch "$BASE_BUILD" "$BASE_URL")" PATCH_IPSW=() for entry in "${PATCH_LIST[@]}"; do PATCH_IPSW+=("$(fetch "${entry%%|*}" "${entry##*|}")") done # ------------------------------------------------------------------ extract extract_build() { # $1 ipsw $2 build local d="$ROOT/extract/$2" mkdir -p "$d" say "extracting $2" ipsw extract --kernel "$1" -o "$d" >/dev/null ipsw extract --files "$1" -o "$d" >/dev/null || say "rootfs extract failed for $2" ipsw extract --dyld "$1" -o "$d" >/dev/null || say "dyld cache extract failed for $2" local kc kc="$(find "$d" -name 'kernelcache*' -type f | head -1)" [[ -n "$kc" ]] || die "no kernelcache in $2" mkdir -p "$ROOT/kexts/$2" ipsw kernel kexts "$kc" -o "$ROOT/kexts/$2" >/dev/null ipsw kernel symbolicate "$kc" > "$ROOT/kexts/$2/symbols.txt" 2>/dev/null || true printf '%s\n' "$kc" } BASE_KC="$(extract_build "$BASE_IPSW" "$BASE_BUILD")" PATCH_KC=() for entry in "${PATCH_LIST[@]}"; do PATCH_KC+=("$(extract_build "$ROOT/ipsw/${entry%%|*}.ipsw" "${entry%%|*}")") done # ------------------------------------------------------------------- gate A if [[ $SKIP_GATE_A -eq 0 && $SCAFFOLD_ONLY -eq 0 ]]; then say "GATE A: WebContent -> QuickLook / CGPDFService" OUT="$ROOT/report/gate-a-$STAMP.md" MNT="$ROOT/extract/$BASE_BUILD/rootfs" DMG="$(find "$ROOT/extract/$BASE_BUILD" -maxdepth 1 -name '*.dmg' | head -1)" mkdir -p "$MNT" if [[ -n "$DMG" ]]; then sudo apfs-fuse "$DMG" "$MNT" 2>/dev/null || say "apfs-fuse failed; gate A will be empty" fi { echo "# Gate A — $BASE_BUILD" echo for p in com.apple.WebKit.WebContent.sb com.apple.WebProcess.sb; do f="$MNT/System/Library/Sandbox/Profiles/$p" echo "## $p" if [[ -f "$f" ]]; then grep -nE 'mach-lookup|CGPDFService|quicklook|ThumbnailsAgent' "$f" \ | sed 's/^/ /' || echo " (no match)" else echo " (absent)" fi echo done echo "## quicklook-thumbnail.sb" f="$MNT/System/Library/Sandbox/Profiles/quicklook-thumbnail.sb" [[ -f "$f" ]] && grep -nE 'iokit-open|mach-lookup|CGPDF' "$f" | sed 's/^/ /' \ || echo " (absent)" } | tee "$OUT" sudo umount "$MNT" 2>/dev/null || true if grep -qiE 'CGPDFService|ThumbnailsAgent|quicklook' "$OUT"; then say "GATE A: PASS (option 2 stays alive as a later refinement)" else say "GATE A: FAIL/AMBIGUOUS (option 3 is the only route)" fi fi # ---------------------------------------------------------------- kc diff if [[ $SKIP_DIFF -eq 0 && $SCAFFOLD_ONLY -eq 0 ]]; then cat > "$ROOT/tools/kc_diff.py" <<'PY' #!/usr/bin/env python3 """kc_diff.py — relocation-normalised function diff for arm64e kernelcaches. Narrows a patch batch to the functions a human should read. Not a bug finder. Scoring, per changed function: +3 new compare against a bound +2 new conditional branch +2 references retain/release/free +1 grew +1 in a kext with a user client """ import re, sys, os, json, subprocess, collections OBJDUMP = os.environ.get("OBJDUMP", "llvm-objdump") LABEL = re.compile(r'^[0-9a-f]+ <(.+)>:$') INS = re.compile(r'^\s*[0-9a-f]+:\s+[0-9a-f ]+\t(\S+)(?:\s+(.*))?$') KEEP = re.compile(r'^(cmp|cmn|tst|subs|adds|ccmp|b\.|cbz|cbnz|tbz|tbnz|bl|blr|' r'ldr|ldrb|ldrh|str|strb|strh|mov|adrp|add|ret|pac|aut)', re.I) RETAIN = re.compile(r'(retain|release|free|dealloc|dispose)', re.I) USERCLIENT = re.compile(r'(UserClient|userclient)', re.I) def norm(ops: str) -> str: o = re.sub(r'//.*$', '', ops) o = re.sub(r'#-?0x[0-9a-f]+', '#I', o) o = re.sub(r'#-?\d+', '#I', o) o = re.sub(r'0x[0-9a-f]{3,}', 'A', o) o = re.sub(r'\s+', ' ', o).strip() return o def dis(path): try: out = subprocess.run([OBJDUMP, "-d", "--no-show-raw-insn", "--arch=arm64e", path], capture_output=True, text=True, timeout=1800).stdout except Exception: out = subprocess.run([OBJDUMP, "-d", "--no-show-raw-insn", path], capture_output=True, text=True, timeout=1800).stdout funcs, cur = {}, None for line in out.splitlines(): m = LABEL.match(line.strip()) if m: cur = m.group(1); funcs[cur] = [] continue m = INS.match(line) if not m or cur is None: continue mn, ops = m.group(1), norm(m.group(2) or "") if KEEP.match(mn): funcs[cur].append(f"{mn} {ops}".strip()) return funcs def score(old, new, kext): if not new: return 0 add = [i for i in new if i not in old] s = 0 if sum(1 for i in add if i.startswith(("cmp", "cmn", "tst", "subs"))) >= 1: s += 3 if sum(1 for i in add if i.startswith(("b.", "cbz", "cbnz", "tbz", "tbnz"))) >= 1: s += 2 if any(RETAIN.search(i) for i in new): s += 2 if len(new) > len(old): s += 1 if USERCLIENT.search(kext): s += 1 return s def main(): old_root, new_root, outdir = sys.argv[1:4] os.makedirs(outdir, exist_ok=True) census, ranked = [], [] old_b = {d: os.path.join(old_root, d) for d in os.listdir(old_root) if os.path.isdir(os.path.join(old_root, d))} for b, newdir in ((b, os.path.join(new_root, b)) for b in old_b): if not os.path.isdir(newdir): continue for f in os.listdir(os.path.join(old_b[b])): po, pn = os.path.join(old_b[b], f), os.path.join(newdir, f) if not (os.path.isfile(po) and os.path.isfile(pn)): continue census.append((b, os.path.getsize(po), os.path.getsize(pn), os.path.getsize(pn) - os.path.getsize(po))) fo, fn = dis(po), dis(pn) for name, body in fn.items(): s = score(fo.get(name, []), body, b) if s >= 4: ranked.append((s, b, name, fo.get(name, []), body)) ranked.sort(key=lambda r: -r[0]) with open(os.path.join(outdir, "census.tsv"), "w") as fh: fh.write("bundle\told_bytes\tnew_bytes\tdelta\n") for row in sorted(census, key=lambda r: -r[3]): fh.write("\t".join(map(str, row)) + "\n") with open(os.path.join(outdir, "ranked.md"), "w") as fh: fh.write("# Ranked function deltas\n\n") for s, b, name, o, n in ranked[:400]: fh.write(f"## {s} {b} :: {name}\n\n```\n") fh.write("\n".join("- " + x for x in o if x not in n)) fh.write("\n") fh.write("\n".join("+ " + x for x in n if x not in o)) fh.write("\n```\n\n") print(f"{len(census)} kexts, {len(ranked)} ranked functions") main() PY chmod +x "$ROOT/tools/kc_diff.py" for entry in "${PATCH_LIST[@]}"; do b="${entry%%|*}" say "diffing $BASE_BUILD -> $b" OBJDUMP="$OBJDUMP" python3 "$ROOT/tools/kc_diff.py" \ "$ROOT/kexts/$BASE_BUILD" "$ROOT/kexts/$b" "$ROOT/report/diff-$b" \ || say "diff failed for $b" done fi # ------------------------------------------------------------------ report say "report" { echo "# ios27-triage $STAMP" echo echo "- device: $DEVICE" echo "- base: $BASE_VER ($BASE_BUILD)" echo "- patches: ${PATCH_VERS[*]}" echo "- host: $(uname -a)" echo echo "## top text-size deltas" for entry in "${PATCH_LIST[@]}"; do b="${entry%%|*}" [[ -f "$ROOT/report/diff-$b/census.tsv" ]] && { echo "### vs $b" echo '```' head -40 "$ROOT/report/diff-$b/census.tsv" echo '```' } done echo echo "## gate A" echo "see report/gate-a-$STAMP.md" echo echo "## next" echo "Read diff-*/ranked.md top-down. Kexts with user clients first." } > "$ROOT/report/REPORT-$STAMP.md" say "report at $ROOT/report/REPORT-$STAMP.md" say "done"