Files
apk-reverse/skills/apk-reverse/references/kernel-event-injection.md
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

8.7 KiB

Kernel-side event injection — the driver as your hands inside the target

Load this when the observation or the change you need is impossible to deliver from the target's own process — TracerPid must stay 0, the code must not change by one byte, the decision must flip at a PC you choose, and it must all happen without any thread or mapping the target could enumerate. A kernel-side driver can do this because the arm64 debug registers can be programmed on the target's behalf through the kernel's perf/breakpoint layer, and the overflow callback runs holding the interrupted context's pt_regs. This file owns the primitive map and the composition recipes; scripts/kernel_instrument_scaffold.py generates the templates.

Division of labour, so nothing gets said twice. references/kernel-and-environment-hardening.md owns hiding from detection — which root scheme, which module, when escalation is wrong; its §4a gate table applies to this file unchanged. references/hardware-watchpoints.md owns the ptrace delivery of the same hardware, including its honest TracerPid column. This file is the third leg: instrumentation and injection from the kernel, when the other two deliveries are unacceptable.

Claim strength. gates/generate/verify run on the host — observed for the generator. No kernel-side file this scaffold emits has been compiled or loaded anywhere, by anyone in this repository's passes — every generated file says so in its own header, and the register-rewrite action is explicitly labelled experimental. The API surface (register_user_hw_breakpoint / perf_event_create_kernel_counter, PERF_TYPE_BREAKPOINT with bp_type/bp_addr/bp_len) is the kernel's documented GPL-exported interface — inferred as a mechanism, unverified as a route until a device with the matching gate compiles and loads it.

1. The primitive map — what each route can actually do

primitive KPM (KernelPatch) out-of-tree LKM eBPF Zygisk module
hardware watchpoint on the target task, hit logged to dmesg yes (via perf bp layer, symbols resolved at load) yes (register_user_hw_breakpoint, GPL-exported) no — no perf breakpoint creation from BPF no
rewrite a register at the trap (flip a branch decision, no code change) template action, experimental template action, experimental no no
read/write the target's memory from outside it yes yes (access_process_vm) read via helpers, write rarely in-process only (it is the process)
force a syscall return value yes — see kernelsu_syscall_mask.py yes (syscall table / inline hooks) observe; rewrite only for ALLOW_ERROR_INJECTION targets no (wrong layer)
deliver a signal at a chosen moment yes yes yes in-process
visible to the target (TracerPid, foreign threads, code deltas) none none none in-process, pre-init_array

Read the table as instructions: the only route that observes and alters with zero in-process footprint is a kernel module; eBPF is an observer; Zygisk is early inside the process — the right answer for init_array-early checks (references/kernel-and-environment-hardening.md §4 Kernel-level interception — the map, and the version gate), not for invisible watchpoints.

2. The recipes — "wish-mode", assembled from the other two files

These are compositions, not new mechanisms. Each names its deliverable and its fallback, because a kernel route is never the first thing to try — it is what you escalate to when the cheaper route's ledger (references/hardware-watchpoints.md §1 The stealth ledger) says the target will see you.

Recipe 1 — "give me the plaintext key, whatever wraps the cipher." Watch the buffer the crypto fills, kernel-armed so the RASP never notices, and read the buffer at the hit. Steps: locate the buffer statically (svc_scan.py, decompiler) → kernel_instrument_scaffold.py generate --pid <PID> --watch w:<ADDR>:8:w → load on a device with the KPM/LKM gate closed → dmesg gives the filling PC → at the next hit read the buffer (/proc/<pid>/mem from root outside the process is enough; no injection needed). Fallback: ptrace watchpoint when TracerPid is not read by the target — cheaper, same hit.

Recipe 2 — "make the check pass without changing one byte." The differential (references/ete-diff-tracing.md §4) names the branch that first consumes the valid/invalid difference. Instead of patching that branch (which the page checksum watches), arm an execution breakpoint at its PC from the kernel and rewrite the condition register at the trap: the decision flips, the image stays byte-identical. generate --break b:<PC> --set-reg x0=0x1. This is the experimental action — the register rewrite in a perf overflow callback was never run by this repository; validate on a device you can reboot, and prefer patching the code when the checksum threat model does not actually include self-verification of that page.

Recipe 3 — "trace it, but leave TracerPid alone." ETE capture needs no ptrace at all (it is perf + aux buffers), and kernel watchpoints need none either — so the entire observation half of this toolkit composes into a zero-ptrace session: ete_capture.py capture for paths, kernel watchpoints for addresses, dmesg as the event bus. What remains visible is the perf events themselves (a determined kernel-state reader can enumerate them) — say so rather than claiming true invisibility.

3. The scaffold and its gates

python skills/apk-reverse/scripts/kernel_instrument_scaffold.py gates
python skills/apk-reverse/scripts/kernel_instrument_scaffold.py generate \
    --out work/kwatch --pid <PID> --watch w:0x7b2000123450:8:w --break b:0x7b20001234c0 --set-reg x0=0x1
python skills/apk-reverse/scripts/kernel_instrument_scaffold.py verify --dir work/kwatch

The gates are the §4a table's: KPM needs a KernelPatch-patched boot image plus aarch64-none-elf-gcc; LKM needs kernel source matching the exact vermagic; the userspace module is an honest carrier that can arm nothing. One gate is new and belongs to this file: the kernel's perf breakpoint layer must own the debug registers (CONFIG_HW_PERF_EVENTS); if it is compiled out, register_user_hw_breakpoint does not exist and both templates close — check ls /sys/bus/event_source/devices/breakpoint on the device. Design notes carried in the generated files, all load-bearing: the callback runs on every hit, system-wide — the generated template prints unfiltered on entry, so adding a cheap first-statement filter is a required change before you rely on any hit (the same lesson the syscall-mask template learned publicly); symbols in a KPM are declared without extern or the loader rejects the module; and a slot that fails to arm is logged, never silently skipped.

4. When to stop — the same stop rules, extended one row

Every rule of references/kernel-and-environment-hardening.md §7 When to stop escalating — do not counter-escalate a userspace check with kernel development applies verbatim, plus this file's own:

Situation Do this Not this
The check sees TracerPid but not perf/kernel state kernel watchpoint + ETE, zero ptrace patching the boot image to hide one field
The decision site is known and the page is not self-verified byte patch (references/native-and-so.md) kernel register rewrite
You want a kernel route on a 4.14/Magisk device record the closed gate, use ptrace watchpoint or Zygisk "just build a quick module"
The register rewrite did not take effect report it — experimental means the first run is a measurement a second, larger rewrite from the same unverified template

Checklist

  • Cheaper route's ledger consulted first (hardware-watchpoints §1); kernel chosen because the target's detection actually demands it, not because it is stronger
  • gates run; KPM/LKM/perf-bp gates answered for this device, closed ones recorded
  • Watch specs passed plan-style validation at generation (window, alignment)
  • Control: one deliberate touch on a watched global produces one dmesg line before the real window — an unverified template owes this before any hit is trusted
  • Callback filter first, no sleeping, printk only (plus the explicitly-labelled experimental register action, only on a device you can reboot)
  • Every kernel file still carries its NOT COMPILED AND NOT LOADED banner after your edits (verify --dir), or the banner is replaced by your own measurement
  • Deliverable sentence re-read: a kernel-route result is a rooted-device result, labelled a fallback unless the task asked for exactly that