Files
apk-reverse/skills/apk-reverse/scripts/trace_diff.py
T
root ab22b225ff Hardware pass: hardware watchpoints, ETE differential tracing, kernel-side event injection
Add the layer under the software tooling, in the repository's shape: what runs
on a host is measured, and every device-bound or kernel-bound piece is a gated,
labelled template.

- scripts/hw_watch.py: arm64 hardware watchpoints/execution breakpoints. WCR/
  BCR encoders with the 8-byte-window and alignment rules (unit-tested to the
  canonical 0x1FFD/0x3F05), a self-contained on-device ptrace helper that
  compiles clean as a static aarch64 ELF (observed: cross gcc 16.2), adb
  orchestration, and hit decoding to module+offset. The stealth ledger is
  stated three times on purpose: the ptrace route leaves TracerPid visible.
- scripts/ete_capture.py: CoreSight ETE capture with the five gates (kernel
  era, coresight sysfs, cs_etm PMU, perf-with-CORESIGHT, permission), the
  perf/OpenCSD build recipe, and the per-thread record wrapper whose
  --control one-instruction run must pass before any real capture.
- scripts/trace_diff.py: differential reduction of two execution traces into
  first-divergence / divergent regions / blocks-unique-to-each-side.
  Producer-agnostic: Stalker BLK logs (raw or run_probe-wrapped) and decoded
  cs_etm address streams alike, host-tested on synthetic flattened-dispatcher
  fixtures.
- scripts/kernel_instrument_scaffold.py: KPM/LKM watchpoint + register-rewrite
  templates plus an honest userspace carrier; every kernel file carries a
  NOT COMPILED AND NOT LOADED banner that verify enforces, and the
  register-rewrite action is fenced as experimental in the template itself.
- references/hardware-watchpoints.md, references/ete-diff-tracing.md,
  references/kernel-event-injection.md: the mechanism, the gates, the traps,
  and the composition recipes (watch the key buffer; diff two runs; flip the
  decision at the trap), with hand-offs instead of duplication.
- Registration: 3 symptom rows (SKILL.md + routing mirror), 3 reference rows,
  4 script rows, coverage/route-inventory/evidence rows, capability-matrix
  entries, known-limitations entry, eval case 4, README trees and coverage
  paragraphs in both languages, and three EXTENSION evidence records stating
  exactly what was measured on this host (encoders, compile, fixtures,
  generate/verify) and what was not (no watchpoint armed, no cs_etm stream,
  nothing kernel-side compiled or loaded anywhere).

Hardware pass 2: SPE/BRBE crash forensics, address symbolization, VM de-virtualization

Calibrated against the two public obfuscator implementations the user supplied
(dpkg123/ollvm-aosp-toolchain: Hikari-family and Pluto-family flattening, the
xvmp IR virtualizer at 63fec41f/9b7cf75e; fetched read-only into
tools/_work/refs, git-ignored). Source facts observed, runtime inferred.

- scripts/trace_addr2sym.py: runtime addresses -> symbol + static offset,
  zero-dependency ELF64 (PT_LOAD vaddr<->file-off conversion, .dynsym/.symtab,
  stripped section+off fallback). Host-verified against a real cross-compiled
  aarch64 .so with readelf as the independent cross-check, plus a hand-built
  minimal ELF covering vaddr!=offset; accepts hw_watch hits, trace mod+off
  keys, or raw address lists. Fixes on the way: --base int coercion, and
  nearest-below symbol semantics for PCs in inter-symbol gaps.
- scripts/vm_handler_slice.py: slice an interpreter trace into handler
  segments (dispatcher detection = histogram top + predecessor diversity; the
  first 4x-margin rule refused the calibrated fixture itself and was replaced),
  signature clustering, open-tail handling, and the guest-opcode trajectory via
  an optional handler->opcode map. Calibrated against xvmp's documented shape:
  vm_exec(code,size,vm_args,num) stubs, boxed arguments observable before
  interpretation, 11 opcodes + 19 arithmetic sub-ops, const-materialization
  dispatch as a distinct segment.
- references/hardware-sampling-and-crash.md: SPE (data flow without a known
  address; PC + data address per sample), BRBE (branch records when a crash
  stack cannot be trusted), the crash loop (tombstone -> branch records ->
  symbolize), and what each adds to the OLLVM/VMP routes. All
  documented-and-gated: no SPE sample or BRBE record was captured here.
- Flattening-recipe corrections from source: Hikari keeps a frame-resident
  switchVar written through an indirect pointer with scramble32-permuted cases;
  Pluto stores switchVar/switchXor rolling-XOR so memory only ever holds noise
  -- hardware-watchpoints.md's state-variable recipe now distinguishes the
  families, and ete-diff-tracing.md carries the family table plus the xvmp
  shape. AntiDebugging injects raw svc inline asm with randomized fields, so
  byte signatures cannot survive it; semantic site-location can.
- Registration: 3 symptom rows (untrustworthy crash stack; runtime addresses
  needing symbols; interpreter loop reading as noise), reference/script rows,
  coverage/evidence/capability-matrix entries, README trees in both languages,
  and EXTENSION-sampling-crash.md recording exactly what was measured (real .so
  symbolization, slicer fixtures, the slicer's self-found dispatcher-rule bug)
  and what was not (no SPE/BRBE capture, no hardened binary ever traced).

Fix all PR #1 review findings by severity; un-entrench the tests that pinned them

Major (device-breaking / wrong results):
- hw_watch: match the arm64 user_hwdebug_state slot ABI (address register
  first, control second -- the swap armed nothing correctly)
- hw_watch: every post-seize error path now clears slots and detaches;
  PTRACE_O_EXITKILL turned an analysis failure into a SIGKILL of the target
- hw_watch: forward genuine target SIGTRAPs (raise/tgkill/int3); only ptrace
  event stops are consumed -- the reference's signal-preservation promise
- hw_watch: run checks push/build/chmod and the helper's exit status; a dead
  capture is RESULT=blocked, never ok-no-hits
- hw_watch: decode offsets from the module base, not each mapping's start
- ete_capture: --control now requires the control record to DECODE
  (perf script event lines), the documented gate, not just a zero exit
- ete_capture: -o before the -- workload separator in --cmd mode; all
  values shell-quoted into su -c; stale remote perf.data removed first;
  perf exit status checked (timeout's 124 is the normal window end)
- kernel scaffold: --set-reg restricted to x0..x30; the rewrite is gated by
  its own breakpoint event so a watchpoint hit cannot run it; LKM pins the
  task (get/put_task_struct) across registration and calls the four-argument
  register_user_hw_breakpoint; --break rows initialize .addr/.len/.bp_type
  (there is no .pc member); --id validated against the module-id grammar
- trace_addr2sym: exact module matching (path or basename, never substring);
  load bias aligned against the PT_LOAD (bias = start - (foff - p_offset)
  - p_vaddr); PCs outside the ELF span are refused instead of landing on the
  last symbol; --json stdout is a pure document (RESULT= in text mode only)
- trace_diff: block keys need 0x or >=8 hex digits (PIDs/counts no longer
  parse); vm_handler_slice: dispatcher needs predecessor diversity, no
  frequency-margin fallback; both JSON outputs pure (check_commands' rule)

Minor/nitpick:
- capability-matrix + evidence-summary: trace reduction status ok->partial
  (no real-target producer ran it; the file's own definition of ok)
- hardware-sampling-and-crash.md and the script examples carry --elf
- kernel-event-injection.md no longer claims the callback's first statement
  is a filter (it prints unfiltered; the filter is a required change)
- Elf64 caches symbol addresses for per-row bisect
- docstring coverage of the touched surface: 16.67% -> 100%

Tests: every json.loads workaround stripping RESULT= is gone; new regression
tests cover the slot ABI, release-on-error, SIGTRAP forwarding, non-first
mapping offsets, -o placement and su -c quoting, the control decode gate,
x31/--id refusals, the guarded rewrite, outside-ELF PCs and bias math,
short-token refusal and the dispatcher margin rule. The minimal-ELF fixture
now packs a full 8-field Elf64_Phdr (its 7-field pack silently shifted
p_memsz onto p_align). 739 passed; flake8/mypy and all five gates clean.

Address the follow-up review on 0bd8dfe (6 findings)

- ete_capture: two-layer quoting for the control-record, decode and cleanup
  commands -- shlex.quote spliced between literal single quotes broke out of
  su -c for any spaced output name; --seconds must be positive (timeout 0
  disables the timer), refused before any adb check
- kernel scaffold: --set-reg now refuses sp/pc as well (the template has no
  rewrite path for them; a generate that silently drops the action is the
  misleading kind of success); both templates arm with a sampling period
  (LKM via hw_breakpoint_init, KPM spells out sample_period=1) -- a zero
  period is a non-sampling event whose callback never fires: armed, silent
- trace_addr2sym: contains_vaddr tests each PT_LOAD's loaded span instead
  of the whole-file extent; a PC in the unmapped gap between segments is
  refused rather than named after the nearest symbol below
- trace_diff: a bare all-digit token is indistinguishable from a date or
  count, so block keys need 0x or a non-decimal hex digit; a date-only log
  stays refused as a capture failure

Tests: two-layer quoting with a spaced control name, --seconds refusal,
sp/pc in the rejection list, sampling-period assertions for both templates,
a two-segment gap fixture, and a date-only parser case. 743 passed; flake8,
mypy and all five gates clean.
2026-10-15 15:33:28 +08:00

326 lines
13 KiB
Python

#!/usr/bin/env python3
"""trace_diff.py -- differential execution-trace reduction: two runs, one answer.
What question this answers
--------------------------
Not "what executed" but "**where did run A stop behaving like run B**". You run
the same operation twice with exactly one input changed -- the password's last
character, license valid versus invalid, key 0x00... versus key 0xff... -- and
diff the two execution traces. Every common block is machinery; every divergent
block is a decision that *your one-bit input difference* reached. Against OLLVM
control-flow flattening the divergences name the dispatcher states actually
taken; against a VM/VMP interpreter they name the handler sequence for the two
inputs; against whitebox-style crypto they name the key-dependent branch set.
This is the "differential" half of `references/ete-diff-tracing.md`, and it is
producer-agnostic by design.
What it accepts (auto-detected, or forced with --format)
-------------------------------------------------------
stalker `stalker_trace.js` logs: `BLK <seq> <mod>+0x<off>` block events
(BB/CALL/DONE lines ignored), including logs wrapped by
`run_probe.py` as `[host ts] [dev ts] TRACE BLK ...`.
plain any text where each line carries an address -- the last
whitespace token that parses as hex (`0x7f...`, `7f...`, and
`mod+0xoff` keys kept verbatim so modules stay comparable).
Decoded CoreSight/ETE `perf script` output fits this shape, as do
hand-scrapped disassembly walks.
What it produces
----------------
reduce the run-length form of one trace: ordered `(block, count)` runs plus
the execution histogram -- the same reductions `stalker_report.py`
prints, in a form the differ consumes.
diff an alignment of the two run-length sequences (difflib on the block
keys): identical prefix/suffix lengths, **first divergence**, each
divergent region with per-side counts, and the blocks unique to each
side ranked by count. The unique-to-B list is where "what does the
valid path do that the invalid path does not" is answered.
Discipline the tool does not enforce for you
--------------------------------------------
Same build and same address space (module+offset keys, never raw pointers,
unless ASLR is off); same input length; same capture window; and a *pair* whose
only difference is the input bit you chose. A diff across two builds or two
code versions is noise, and the tool cannot tell -- garbage in, confident
nonsense out.
Measured status: the parsers and the reducer/differ are host-tested on
synthetic flattened-dispatcher fixtures (tests/unit/test_trace_diff.py). No
ETE-produced trace has been fed to it by this repository's passes -- see
references/ete-diff-tracing.md for the producer side and its device gates.
Examples
python trace_diff.py reduce --log traceA.log
python trace_diff.py diff --a traceA.log --b traceB.log --top 15
python trace_diff.py diff --a wrong.log --b right.log --json
"""
import argparse
import difflib
import json
import re
import sys
from collections import Counter
# A block key is a hex address: `0x`-prefixed (unambiguous), or a bare run
# of at least 8 hex digits that is NOT pure decimal -- an all-digit run is
# indistinguishable from a date, a PID range or a count, and a log holding
# only those must stay refused (an empty trace is a capture failure, not a
# result). Shorter bare runs would swallow PIDs and timestamp fragments.
HEX_TOK = re.compile(r"^(?:0x[0-9a-fA-F]+|(?=[0-9a-fA-F]*[a-fA-F])[0-9a-fA-F]{8,})$")
MOD_OFF = re.compile(r"^[A-Za-z0-9_.+-]+\+0x[0-9a-fA-F]+$")
BLK_LINE = re.compile(r"(?:^|\s)BLK\s+\d+\s+(\S+)(?:\s|$)")
class TraceError(ValueError):
pass
# ---------------------------------------------------------------------------
# parsing
# ---------------------------------------------------------------------------
def parse_line_stalker(line):
"""One BLK line -> its block key, or None."""
m = BLK_LINE.search(line)
return m.group(1) if m else None
def parse_line_plain(line):
"""One plain trace line -> its block key, or None."""
toks = line.split()
for tok in reversed(toks):
if MOD_OFF.match(tok):
return tok
if HEX_TOK.match(tok):
return tok.lower()
return None
PARSERS = {"stalker": parse_line_stalker, "plain": parse_line_plain}
def read_blocks(path, fmt=None):
"""Ordered block keys from a trace log. Empty input raises: a diff against
nothing is a plumbing failure, not an analysis result (the zero-event
lesson from native-dbi-and-deobfuscation.md applies here too)."""
blocks = []
with open(path, "r", encoding="utf-8", errors="replace") as fh:
for line in fh:
if fmt:
key = PARSERS[fmt](line)
else:
key = parse_line_stalker(line) or parse_line_plain(line)
if key:
blocks.append(key)
if not blocks:
raise TraceError(
"no block keys parsed from %s -- an empty trace is a capture "
"failure, not a result; see the zero-event diagnostics in "
"references/native-dbi-and-deobfuscation.md" % path)
return blocks
def run_length(blocks):
"""[(key, run_len)] preserving order -- D D D R1 becomes (D,3),(R1,1)."""
runs = []
for b in blocks:
if runs and runs[-1][0] == b:
runs[-1][1] += 1
else:
runs.append([b, 1])
return [(k, n) for k, n in runs]
# ---------------------------------------------------------------------------
# reduction report
# ---------------------------------------------------------------------------
def reduce_trace(blocks):
"""Histogram and run-length summary of one block list."""
hist = Counter(blocks)
return {
"events": len(blocks),
"distinct_blocks": len(hist),
"runs": len(run_length(blocks)),
"top": hist.most_common(),
"sequence": run_length(blocks),
}
# ---------------------------------------------------------------------------
# differential
# ---------------------------------------------------------------------------
def diff_traces(a_blocks, b_blocks):
"""Structural diff: first divergence, regions, uniques."""
a_runs, b_runs = run_length(a_blocks), run_length(b_blocks)
a_keys = [k for k, _ in a_runs]
b_keys = [k for k, _ in b_runs]
sm = difflib.SequenceMatcher(a=a_keys, b=b_keys, autojunk=False)
identical = sum(n for i, j, n in sm.get_matching_blocks())
regions = []
first_divergence = None
a_hist, b_hist = Counter(a_blocks), Counter(b_blocks)
for tag, i1, i2, j1, j2 in sm.get_opcodes():
if tag == "equal":
continue
if first_divergence is None:
first_divergence = {
"run_index_a": i1, "run_index_b": j1,
"event_index_a": sum(n for _, n in a_runs[:i1]),
"event_index_b": sum(n for _, n in b_runs[:j1]),
"last_common_block": a_runs[i1 - 1][0] if i1 > 0 else None,
}
regions.append({
"tag": tag,
"a_runs": a_runs[i1:i2],
"b_runs": b_runs[j1:j2],
})
only_a = sorted(((k, v) for k, v in (a_hist - b_hist).items()),
key=lambda kv: -kv[1])
only_b = sorted(((k, v) for k, v in (b_hist - a_hist).items()),
key=lambda kv: -kv[1])
common = a_hist & b_hist
return {
"a_events": len(a_blocks), "b_events": len(b_blocks),
"a_distinct": len(a_hist), "b_distinct": len(b_hist),
"shared_blocks": sum(common.values()),
"identical_run_span": identical,
"divergent_regions": len(regions),
"first_divergence": first_divergence,
"regions": regions,
"unique_to_a": only_a,
"unique_to_b": only_b,
}
def render_diff(d, top=10, context=3):
"""Human-readable rendering of a diff_traces document."""
out = []
out.append("run A: %d events, %d distinct blocks" % (d["a_events"], d["a_distinct"]))
out.append("run B: %d events, %d distinct blocks" % (d["b_events"], d["b_distinct"]))
out.append("shared block executions: %d divergent regions: %d"
% (d["shared_blocks"], d["divergent_regions"]))
fd = d["first_divergence"]
if fd is None:
out.append("\nNO DIVERGENCE: the two runs executed the same block sequence.")
out.append("Either the input difference never reached control flow (pure data),")
out.append("or the two logs came from the same run. Check the producer.")
else:
out.append("")
out.append("first divergence: after run #%d (A) / #%d (B), "
"%d/%d events in, last common block %s"
% (fd["run_index_a"], fd["run_index_b"],
fd["event_index_a"], fd["event_index_b"],
fd["last_common_block"] or "<start>"))
for idx, r in enumerate(d["regions"][:top], 1):
out.append("")
out.append("region %d (%s)" % (idx, r["tag"]))
out.append(" A: " + _fmt_runs(r["a_runs"]))
out.append(" B: " + _fmt_runs(r["b_runs"]))
if d["unique_to_a"] or d["unique_to_b"]:
out.append("")
out.append("blocks unique to A (input-dependent, A-side), top %d:" % top)
for k, n in d["unique_to_a"][:top]:
out.append(" %6d %s" % (n, k))
out.append("blocks unique to B (input-dependent, B-side), top %d:" % top)
for k, n in d["unique_to_b"][:top]:
out.append(" %6d %s" % (n, k))
return "\n".join(out)
def _fmt_runs(runs):
"""Format a run list for the region renderer."""
if not runs:
return "<nothing>"
return " -> ".join("%s%s" % (k, ("*%d" % n) if n > 1 else "") for k, n in runs[:12]) + \
(" ... (%d runs)" % len(runs) if len(runs) > 12 else "")
# ---------------------------------------------------------------------------
# subcommands
# ---------------------------------------------------------------------------
def cmd_reduce(args):
"""reduce subcommand."""
try:
blocks = read_blocks(args.log, args.format)
except (OSError, TraceError) as exc:
print("RESULT=refused")
print(str(exc), file=sys.stderr)
return 2
rep = reduce_trace(blocks)
if args.json:
print(json.dumps({"status": "ok", "log": args.log,
"events": rep["events"],
"distinct_blocks": rep["distinct_blocks"],
"runs": rep["runs"],
"top": rep["top"][:args.top]}, indent=1))
return 0
print("%s: %d events, %d distinct blocks, %d runs"
% (args.log, rep["events"], rep["distinct_blocks"], rep["runs"]))
print("\ntop %d blocks (dispatcher candidate = the wide-margin top):" % args.top)
for k, n in rep["top"][:args.top]:
print(" %6d %s" % (n, k))
print("RESULT=ok")
return 0
def cmd_diff(args):
"""diff subcommand."""
try:
a = read_blocks(args.a, args.format)
b = read_blocks(args.b, args.format)
except (OSError, TraceError) as exc:
print("RESULT=refused")
print(str(exc), file=sys.stderr)
return 2
d = diff_traces(a, b)
if args.json:
doc = dict(d)
doc["status"] = "ok"
doc["regions"] = d["regions"][:args.top]
doc["unique_to_a"] = d["unique_to_a"][:args.top]
doc["unique_to_b"] = d["unique_to_b"][:args.top]
print(json.dumps(doc, indent=1))
return 0
print(render_diff(d, top=args.top))
print("RESULT=ok")
return 0
def main():
"""CLI entry: subcommand dispatch."""
ap = argparse.ArgumentParser(
description="Differential reduction of two execution traces (stalker or plain "
"address logs): first divergence, divergent regions, unique blocks.",
epilog="references/ete-diff-tracing.md owns the method: same build, same "
"window, one changed input bit -- and what the divergences mean "
"against OLLVM flattening and VMP handler loops.")
sub = ap.add_subparsers(dest="cmd", required=True)
p = sub.add_parser("reduce", help="run-length + histogram of one trace")
p.add_argument("--log", required=True, help="trace log (stalker or plain)")
p.add_argument("--format", choices=sorted(PARSERS), help="force a parser (default: auto)")
p.add_argument("--top", type=int, default=20)
p.add_argument("--json", action="store_true")
p.set_defaults(fn=cmd_reduce)
p = sub.add_parser("diff", help="align two traces and report the divergences")
p.add_argument("--a", required=True, help="trace log A (e.g. the failing/invalid run)")
p.add_argument("--b", required=True, help="trace log B (e.g. the passing/valid run)")
p.add_argument("--format", choices=sorted(PARSERS), help="force a parser (default: auto)")
p.add_argument("--top", type=int, default=10, help="regions / unique blocks to show")
p.add_argument("--json", action="store_true")
p.set_defaults(fn=cmd_diff)
args = ap.parse_args()
try:
return args.fn(args)
except BrokenPipeError:
return 0
if __name__ == "__main__":
sys.exit(main())