Skip to content

[AUTOMATED] fix(p7): stackguard - remove the entry-side canary init (and its TLS residue) with the stripped check - #306

Merged
mahaloz merged 1 commit into
mainfrom
fix/i183-stackguard-entry-store
Aug 16, 2026
Merged

mahaloz merged 1 commit into
mainfrom
fix/i183-stackguard-entry-store

Conversation

@mahaloz

@mahaloz mahaloz commented Aug 16, 2026

Copy link
Copy Markdown
Contributor

Fixes #183

option stackguard (default-on, the port of angr's StackCanarySimplifier) stripped only the back half of the -fstack-protector idiom: the compare, its CBRANCH and the __stack_chk_fail handler went, but the entry-side canary init (mov rax, fs:0x28; mov [rsp+N], rax) survived as a dead first statement in ~96% of protected functions, together with a dead canary-slot declaration and the dangling // fs_offset TLS-base declaration. The angr original pops exactly that init statement (first_block_copy.statements.pop(stmt_idx)).

Root cause

The init store writes an addrtied stack varnode. ActionDirectWrite marks any real (non-COPY-form) write direct-write, and ActionDeadCode preserves addrforce on direct-write varnodes, so the store is auto-live on every pass and the dead-code pass can never collect it — it also pins the fs:0x28 LOAD and the TLS-base input alive with it. kuna's port detects the canary from the compare, so it never located the init.

Fix (p7_regions/kuna_stackguard.rs)

kuna realizes angr's statement-pop as a liveness release, tied to the stripped check:

  1. collect_canary_slots — before the CBRANCH dies, re-walk the compare's own derivation chains (the exact derives_from_canary_load peel set and bounds, every MULTIEQUAL input) and record the storage of each addrtied varnode proven to derive from a LOAD of the canary slot: the saved-canary stack slot the pass resolved.
  2. release_canary_slots — after the successful remove_branch/remove_unreachable_blocks, clear addrforce on every varnode version at that exact storage, and excise the slot range from the local scope via ScopeLocal::markNotMapped (the ported checkUnaliasedReturn idiom) so restructureVarnode keeps a range boundary and no adjacent open local (a char buf[], a piece-written struct) absorbs the freed 8 bytes.

Nothing is deleted by the pass itself: the following ActionDeadCode collects the store, the fs:0x28 LOAD and the TLS-base input through its ordinary consume fixpoint. That makes the robustness guarantee structural — a slot version still feeding a live reader (a second, not-yet-stripped check in a multi-check function, or a partial match the pass declined) is provably never removed, because real readers still seed consumption. No new option, no DIV row: this completes the ported pass's own semantics.

Before / after (tests/bug-repro/sort --addr 0x6e80, coreutils zaptemp)

Before:

  char v7 [136];
  long v8; // fs_offset
  unsigned long v9; // stack - 0x40

  v9 = *(unsigned long *)(v8 + 0x28);   // dead: v9 never read, v8 never assigned
  v3 = (long *)0x1e368;

After:

  char v7 [136];

  v3 = (long *)0x1e368;

The dead store and both declarations are gone; v7's size is untouched (the markNotMapped boundary prevents absorption). faillog --addr 0x3320 likewise. (The issue's *(void *) spelling on this line no longer reproduces on main — #302 changed the type vocabulary — but the statement was still dead and ill-typed relative to stackguard off; with the fix the symptom line does not exist at all.)

Off-mode proof

--option stackguard off output is byte-identical to the main-tree binary on both witnesses (diff of full function output, base binary vs this branch): the release only ever runs after a successful strip.

Corpus scan (issue methodology: // fs_offset decl + dead = *(... + 0x28); store, dest read never)

Over decompile-all --json of tests/bug-repro/{sort,faillog,grep,libselinux.so.1} (1629 functions):

binary funcs fs_offset decl (base -> fixed) dead store (base -> fixed)
sort 490 58 -> 2 57 -> 2
faillog 69 7 -> 1 7 -> 1
grep 449 72 -> 2 64 -> 1
libselinux.so.1 621 131 -> 0 130 -> 0
total 1629 268 -> 5 (98% gone) 258 -> 4 (98% gone)

Every survivor is a function where the check strip itself never fired (e.g. grep sub_11480 still carries its full __stack_chk_fail check — the issue's own "still has check" row; sort sub_5970 ends in a no-return tail call with no detected compare). Those are exactly the cases the robustness guard exists for: no strip, no release.

Collateral audit

Base-vs-fixed diff of all 4 binaries' whole-program C: 263 functions changed; all 263 had a // fs_offset declaration in base; zero unexplained changes. Sampled diffs contain only: the removed dead store, the removed declarations, and the consequent local renumbering. Buffer sizes and neighboring locals are unchanged (verified against the pre-markNotMapped prototype, which had grown char v14 [264] -> [280]-style extents — the boundary excision eliminated all of those).

Gates

  • make test — PARITY OK (675/675), no opt-outs added, no baseline re-pin. (The datatest gate caught the absorption collateral in piecestruct/switchhide during development; the markNotMapped boundary restored both to byte-identical.)
  • make test-stages — PARITY OK (462/462). Extended the existing two-pass stackguard testcase ghangr-ite-region-converter-missing-5db28e.xml with 2 stackguard strips the canary check but leaves a dead fs:0x28 load cast to *(void *) #183 assertions (off pass = full idiom incl. entry store; on pass = zero canary residue), scoped across both passes' concatenated output. Re-pinned 4 renumbering-only assertions in ghdec-undefname.xml (Render unknown types as real C types (realtypes, DIV-6) #6-Perf/actionpool cursor #8) and ghdec-returncopysplit.xml (Recover PLT/GOT import names in ELF decompilation #4) whose functions are canary functions (each with an XML comment). No new XML file (corpus count unchanged); docs/baseline-stages.json re-recorded via --save-baseline.
  • make rust-test — green (internal-PR CI skips the workspace suite; run locally).
  • make check-spec — green; kuna catalog --check — green.

Docs

  • phases.toml stackguard summary now states the entry-init removal; docs/options.md regenerated.
  • docs/spec/07-regions.md §7.3 "What it REMOVES" describes the init-store release (collect + release + markNotMapped) and the never-remove-a-live-reader guarantee.

Speed

Interleaved min-of-11, kuna decompile-all tests/bug-repro/sort --json > /dev/null: base 7.658s vs fixed 7.526s (-1.0%, within noise — the release is a handful of flag writes per stripped check, and dead-code then carries fewer ops).

Rebase note

Rebased onto current main (post #304/#305): docs/baseline-stages.json re-recorded on the rebased tree via --save-baseline (470/470 = main's 468 + the 2 new GH-183 assertions); docs/options.md and the catalog_bytecompat fixture regenerated from the rebased build (both byte-identical to the auto-merge). All four gates re-run green after the rebase.

Follow-up note (out of scope here)

The issue also documents the broader *(void *) relabel: realtype_unknown_base (p9_emit/printc.rs) renders any pointer-to-TYPE_UNKNOWN deref as *(void *), which is never legal C — 1382 of 7518 functions in the issue's 40-binary scan contained at least one such deref, most unrelated to the canary. This PR deliberately does not touch the printer; with the canary init gone the symptom line disappears from stackguard functions, but the relabel deserves its own issue (char */unsigned char * or undefinedN would both be valid).

🤖 Generated with Claude Code

https://claude.ai/code/session_01VBn8vgwoHqPFnnV4ZMApfq

…pped check

The strip removed only the back half of the -fstack-protector idiom
(compare/CBRANCH/__stack_chk_fail); the entry-side canary init survived as a
dead first statement in ~96% of protected functions because its addrtied
stack varnode is directwrite-marked, so ActionDeadCode preserves addrforce
and can never collect it.

Realize angr StackCanarySimplifier's statements.pop(stmt_idx) as a liveness
release tied to the stripped check: collect_canary_slots re-walks the
compare's derivation chains (the detector's exact peel set) to resolve the
saved-canary slot storage; release_canary_slots then clears addrforce on
every version at that storage and excises the slot range from the local
scope (ScopeLocal::markNotMapped, the checkUnaliasedReturn idiom) so no
adjacent open local absorbs the freed bytes. The following dead-code pass
collects the store, the fs:0x28 LOAD and the TLS-base input through its
ordinary consume fixpoint, so a slot version still feeding a live reader (a
second, not-yet-stripped check) is provably never removed.

Corpus (sort/faillog/grep/libselinux.so.1, 1629 fns): fs_offset decls
268 -> 5, dead canary stores 258 -> 4; every survivor is a function whose
check strip never fired. 675/675 datatests byte-identical with no opt-outs;
stage pins re-recorded for renumbering only. No new option, no DIV row:
this completes the ported pass's own semantics (GH-183).

[AUTOMATED]

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VBn8vgwoHqPFnnV4ZMApfq
@mahaloz
mahaloz merged commit fa6b353 into main Aug 16, 2026
9 checks passed
@mahaloz
mahaloz deleted the fix/i183-stackguard-entry-store branch August 16, 2026 20:10
mahaloz added a commit that referenced this pull request Aug 16, 2026
…T effect (GH-181)

[AUTOMATED] Two stacked correctness fixes, no new option:

1. Port the upstream Merge::snipReads carve-out (merge.cc:461, "snip must
   come after OP CAUSING EFFECT") that kuna's do_snip_reads_insert_point
   dropped: a cover-trim COPY of an INDIRECT-defined Varnode is inserted
   after the op iop-encoded in the INDIRECT's input 1 (the call), not at
   the INDIRECT marker, which precedes the call in block order.  Without
   it, libselinux lsetfilecon_raw's out-parameter copy printed above the
   lgetfilecon_raw call that fills the slot, so freecon() consumed the
   pre-call NULL.  Audited the other upstream sites: trimOpOutput already
   had the arm; eliminateIntersect/snipOutputInterference already used
   indirect_effect_op; mergeIndirect/trimOpInput match upstream.

2. Close the matching reordering hazard in kuna's own foldcallret
   (default-on, DIV-14): an op strictly between a call and its lone use
   that reads a value the call indirectly writes (an input defined by a
   CPUI_INDIRECT whose iop input names the call) is now a fold barrier,
   so the call expression is not sunk past the very copy fix 1 places
   after it.  Marker ops are skipped (a later call's INDIRECTs chain the
   earlier call's versions without a textual evaluation point).

New two-pass stage test gh181-snipreads-indirect.xml (default proves both
fixes; option foldcallret off isolates fix 1) plus a README row; corpus
count recounted to 206 on the rebased tree; baseline-stages re-recorded
(473/473 on post-#306 main, including #304's eight GH-180 assertions;
this branch's stage patterns are number-agnostic, so #306's canary
renumbering required no re-pinning).  Three stage tests pinned
renderings the fixes legitimately changed and were updated with comments:
ghangr-x8664-cvs-863633 (slot 0x58 now merge-coalesced even with
dedupvardecls off), ghangr-morton-my-message-callback (renumbering; the
bogus self-assign artifact is gone), ghdec-symbol-keyed-local-decls (the
checksum call is now sequenced before the CONCAT13 reading the slot it
may write).  Spec prose added to docs/spec/06-variables-and-merge.md.

Gates: make test PARITY OK (675/675), make test-stages PARITY OK,
make rust-test green, make check-spec green.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VBn8vgwoHqPFnnV4ZMApfq
mahaloz added a commit that referenced this pull request Aug 16, 2026
…T effect (GH-181) (#307)

[AUTOMATED] Two stacked correctness fixes, no new option:

1. Port the upstream Merge::snipReads carve-out (merge.cc:461, "snip must
   come after OP CAUSING EFFECT") that kuna's do_snip_reads_insert_point
   dropped: a cover-trim COPY of an INDIRECT-defined Varnode is inserted
   after the op iop-encoded in the INDIRECT's input 1 (the call), not at
   the INDIRECT marker, which precedes the call in block order.  Without
   it, libselinux lsetfilecon_raw's out-parameter copy printed above the
   lgetfilecon_raw call that fills the slot, so freecon() consumed the
   pre-call NULL.  Audited the other upstream sites: trimOpOutput already
   had the arm; eliminateIntersect/snipOutputInterference already used
   indirect_effect_op; mergeIndirect/trimOpInput match upstream.

2. Close the matching reordering hazard in kuna's own foldcallret
   (default-on, DIV-14): an op strictly between a call and its lone use
   that reads a value the call indirectly writes (an input defined by a
   CPUI_INDIRECT whose iop input names the call) is now a fold barrier,
   so the call expression is not sunk past the very copy fix 1 places
   after it.  Marker ops are skipped (a later call's INDIRECTs chain the
   earlier call's versions without a textual evaluation point).

New two-pass stage test gh181-snipreads-indirect.xml (default proves both
fixes; option foldcallret off isolates fix 1) plus a README row; corpus
count recounted to 206 on the rebased tree; baseline-stages re-recorded
(473/473 on post-#306 main, including #304's eight GH-180 assertions;
this branch's stage patterns are number-agnostic, so #306's canary
renumbering required no re-pinning).  Three stage tests pinned
renderings the fixes legitimately changed and were updated with comments:
ghangr-x8664-cvs-863633 (slot 0x58 now merge-coalesced even with
dedupvardecls off), ghangr-morton-my-message-callback (renumbering; the
bogus self-assign artifact is gone), ghdec-symbol-keyed-local-decls (the
checksum call is now sequenced before the CONCAT13 reading the slot it
may write).  Spec prose added to docs/spec/06-variables-and-merge.md.

Gates: make test PARITY OK (675/675), make test-stages PARITY OK,
make rust-test green, make check-spec green.


Claude-Session: https://claude.ai/code/session_01VBn8vgwoHqPFnnV4ZMApfq

Co-authored-by: Claude Fable 5 <[email protected]>
mahaloz added a commit that referenced this pull request Aug 17, 2026
The branch was cut from #302 while main advanced to #316; the engine
PRs in between (spillargtrial #315, stackguard #306, snip-reads #307,
loadguardrange #308, ...) legitimately shift the ghidra-path output, so
CI's merge-ref run measured register leaks 108 vs the pinned 106. Rebase
onto origin/main and re-pin every value to the rebased tree:

  registers 106/64/60 -> 108/58/60, unique 32/2/8 -> 34/4/8,
  mangled 21/13/7 -> 21/6/7, c_lines 241/174/89 -> 243/128/89,
  diff ratios 0.643/0.898/0.811 -> 0.646/0.867/0.811 (band unchanged);
  placeholders/resolvable/traffic unchanged (49/25/17, 24/18/14,
  1477/1003).

The sub_3320 shrink (c_lines -26%, FS_OFFSET gone from its register
set, mangled 13 -> 6) is the stackguard/snip-reads work stripping the
canary sequence -- explainable, not suspicious. Determinism verified:
three consecutive runs of the pins test are measurement-identical.

Gates on the rebased tree: harness release + --include-ignored green,
make test 675/675 PARITY OK, make test-stages PARITY OK, check-spec OK,
kuna-ghidra dev-profile spot check green. The full workspace suite ran
green on this branch pre-rebase and every added commit is already-CI-
green main history, so it is covered by the branch + main CI runs.

[AUTOMATED]

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01AfGYKwUWvPYYj1Aw7tcLhC
mahaloz added a commit that referenced this pull request Aug 17, 2026
…the GUI-path quality gap (#317)

* feat(ghidra): ghidra-sim differential test harness — pin the GUI-path quality gap

Extract the decompile_at_e2e MockJava loopback into a shared module
(tests/ghidra_sim/mod.rs — AnswerSource-pluggable pump, wire builders,
session tracer, dual-<function> doc parser, a markup->C flattener that
replicates Java's getC() token cleaning (IllegalCharCppTransformer),
badness scanners, line-diff metric) and build ghidra-sim v1 on top
(tests/ghidra_sim/oracle.rs): a mock-Java answer source backed by kuna's
own analysis of real vendored ELFs — bootstrap_from_object for
bytes/labels, the real Sleigh re-encoded as wire <inst> docs for
getPcode, and a tspec GENERATED from the loaded Sleigh's
AddrSpaceManager so packed space indices agree by construction.
getMappedSymbols/getExternalRef answer EMPTY at a marked PHASE-3 SEAM.

tests/ghidra_sim_e2e.rs drives the full wire lifecycle (registerProgram
-> setAction -> decompileAt x3 -> flushNative -> repeat -> deregister)
over tests/bug-repro/faillog (sort/grep as an ignored breadth test),
asserts the response-document schema (name/entry echo, markup
opref/varref subset-of ast, 19-query legality + query-legal placement),
and PINS today's Phase-2 reality: per-function raw-register leaks
(106/64/60), Unique tokens (32/2/8), placeholders (49/25/17) of which
the loader already knows names for 24/18/14 (Phase 3 drives to 0),
getC()-mangled tokens (21/13/7, PR-C drives to 0), ghidra-vs-CLI line
diff ratios (0.64/0.90/0.81 floors), getPcode traffic 1477/1003, and
getMappedSymbols == 0 (Phase 3 flips to >=1). Pins move only with the
provider/emitter change that earns them.

[AUTOMATED]

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01AfGYKwUWvPYYj1Aw7tcLhC

* ci(ghidra): run the ghidra-sim harness in the gates job + make test-ghidra

Add a `gates`-job step running `cargo test -p kuna-ghidra --release --
--include-ignored` (with the standard specs-skip canary grep) after the
catalog checks: the workspace suite is skipped on internal PRs, and a
GUI-path regression is exactly what the ghidra-sim pins exist to catch
pre-merge. Cost: ~1-2 min of compile over the release deps `make
binaries` already built, ~2 s of test runtime. `make test-ghidra` is the
same run locally.

[AUTOMATED]

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01AfGYKwUWvPYYj1Aw7tcLhC

* docs(ghidra): live-smoke rig + testing-strategy section for the harness

integrations/ghidra/live-smoke/: a manual/dev pyghidra rig that swaps
DecompileProcessFactory.exepath to kuna_ghidra inside a real Ghidra,
decompiles the same functions with both cores, and writes a side-by-side
report with the same badness-scanner counts the in-tree harness pins
(README covers the offline-pyghidra setup and the getC()-vs-GUI-panel
rendering distinction). docs/ghidra-integration.md §11 rewritten around
the shipped harness: what it covers, how to run it, where the pins live.

[AUTOMATED]

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01AfGYKwUWvPYYj1Aw7tcLhC

* test(ghidra): harden the ghidra-sim pins per adversarial review

- Diff-ratio pins are now a BAND: ceilings [0.70,0.95,0.90] join the
  floors (a markup regression that makes the GUI text worse now fails
  instead of saturating), the vacuous `<= 1.0` assert is gone, and the
  flattened-C normalized line count is pinned per target (241/174/89) --
  the assert that actually catches a <break>-token collapse. The pin
  comment now decomposes the ratio (Phase-3 symbol gap + option-preset
  skew until setOptions is wired) so nobody chases 0 with symbol work.
- decompile_cli now routes through the SHARED per-function step
  (kuna_console::decompile_step::decompile_one, DIV-66) with the
  error-noreturn CALL_RETURN flow overrides built exactly as
  kuna_console::project does -- the previous direct drive call silently
  dropped them (latent: faillog has no error() sites, and every faillog
  pin re-measured IDENTICAL; sort/grep-class fixtures would have
  diverged from the real CLI).
- Assert strength: warnings frames pinned trim-empty on registerProgram
  and decompileAt (no substring blocklists); markup oprefs AND varrefs
  pinned non-empty per class; ast varnode refs collected from the
  <varnodes> child only (all Java's buildVarnodeRefs keys -- an op
  operand ref undeclared there must not launder the subset assert);
  the name echo compares against the sim's code_label (which consults
  label_overrides) rather than the raw program lookup.
- CI: the gates-job harness step tees its output to a log before the
  canary grep, so a FAILING pin still prints its diagnostics (the old
  command substitution aborted under bash -e before any echo).
- live-smoke docs/script: kuna_ghidra is not built by `make binaries`;
  point at `cargo build --release -p kuna-ghidra`.

Tests/CI/docs-only diff: the parity gates are untouched by construction.
`cargo test -p kuna-ghidra --release -- --include-ignored` fully green;
`make check-spec` green. No pinned value moved.

[AUTOMATED]

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01AfGYKwUWvPYYj1Aw7tcLhC

* test(ghidra): re-measure the faillog pins on main @ 813ee13 (rebase)

The branch was cut from #302 while main advanced to #316; the engine
PRs in between (spillargtrial #315, stackguard #306, snip-reads #307,
loadguardrange #308, ...) legitimately shift the ghidra-path output, so
CI's merge-ref run measured register leaks 108 vs the pinned 106. Rebase
onto origin/main and re-pin every value to the rebased tree:

  registers 106/64/60 -> 108/58/60, unique 32/2/8 -> 34/4/8,
  mangled 21/13/7 -> 21/6/7, c_lines 241/174/89 -> 243/128/89,
  diff ratios 0.643/0.898/0.811 -> 0.646/0.867/0.811 (band unchanged);
  placeholders/resolvable/traffic unchanged (49/25/17, 24/18/14,
  1477/1003).

The sub_3320 shrink (c_lines -26%, FS_OFFSET gone from its register
set, mangled 13 -> 6) is the stackguard/snip-reads work stripping the
canary sequence -- explainable, not suspicious. Determinism verified:
three consecutive runs of the pins test are measurement-identical.

Gates on the rebased tree: harness release + --include-ignored green,
make test 675/675 PARITY OK, make test-stages PARITY OK, check-spec OK,
kuna-ghidra dev-profile spot check green. The full workspace suite ran
green on this branch pre-rebase and every added commit is already-CI-
green main history, so it is covered by the branch + main CI runs.

[AUTOMATED]

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01AfGYKwUWvPYYj1Aw7tcLhC

---------

Co-authored-by: Claude Fable 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

stackguard strips the canary check but leaves a dead fs:0x28 load cast to *(void *)

1 participant