rf_classify/lib.rs
1//! rf-classify — semantic gadget classification and the ranking function
2//! (Phase 5, PLAN sec. 5.1; Phase 3 remediation for CLS-02..CLS-13, ECO-05).
3//!
4//! The decision rules live in [`TAXONOMY.md`](../../../TAXONOMY.md); rule
5//! numbers (R1-R13) are cited inline.
6//!
7//! Three decode paths, one rule set:
8//!
9//! | arch | decoder | metadata |
10//! |---|---|---|
11//! | x86 / x64 | iced-x86 `InstructionInfoFactory` | full |
12//! | ARM, ARM64, MIPS, PPC, SPARC, RISC-V | capstone **detail mode** ([`rf_scan::Detailer`]) | full |
13//! | anything whose bytes no capstone mode reproduces | disassembly text | best effort, `low_confidence` |
14//!
15//! Before this release the middle row did not exist: `cs::open` never called
16//! `set_detail(true)` (ECO-05), so eight of the ten supported architectures
17//! fell through to the text path, `regs_written` was populated by splitting
18//! the operand string on `,` — which is where `{r4` and `#0x12e44` came from
19//! (CLS-05) — and the memory test was `operands.contains('[')`, which is
20//! false for every `off(reg)` architecture, so MIPS, PowerPC and RISC-V
21//! reported zero `mem-read`, zero `mem-write` and zero `stack-pivot` across
22//! an entire binary (CLS-04).
23//!
24//! ## Ranking (CLS-07)
25//!
26//! [`quality_score`] alone cannot order gadgets: it is a function of two
27//! integers that are both tiny for almost every gadget, so 92 % of a real
28//! binary ties at 100. [`usability`] adds the dimension that actually
29//! separates `pop rdi ; ret` from `retf 0xce39` — what the gadget's
30//! *terminator* is and whether it loads a register off the stack — and
31//! [`rank_key`] is the full order the CLI and the MCP server sort by.
32//!
33//! # Getting started
34//!
35//! One gadget in, one [`Classification`] out. The interesting part is not
36//! the label — it is the semantic fields underneath it, which are what let
37//! you ask "a gadget that loads rdi from the stack and clobbers neither rsi
38//! nor rdx" without re-parsing disassembly text.
39//!
40//! ```
41//! use rf_classify::{classify, Class, Terminator};
42//! use rf_core::{Arch, Endianness, RawBinary};
43//! use rf_scan::{scan_binary, ScanOptions};
44//!
45//! // `pop rdi ; ret`
46//! let image = RawBinary::new(&[0x5f, 0xc3], Arch::X64, Endianness::Little);
47//! let gadgets = scan_binary(&image, &ScanOptions { depth: 4, ..ScanOptions::default() })?;
48//! let g = gadgets.iter().find(|g| g.text() == "pop rdi ; ret").expect("pop rdi ; ret");
49//!
50//! let c = classify(g, Arch::X64);
51//! assert_eq!(c.primary, Class::RegWrite);
52//! assert_eq!(c.terminator, Terminator::Ret);
53//! assert_eq!(c.regs_written, ["rdi"]);
54//! assert_eq!(c.regs_from_stack, ["rdi"]);
55//! // The stack pointer moves 16 bytes: 8 for the pop, 8 for the return.
56//! assert_eq!(c.stack_delta, Some(16));
57//! # Ok::<(), rf_core::Error>(())
58//! ```
59//!
60//! ## Asking a real question
61//!
62//! The predicates on [`Classification`] are the query vocabulary both front
63//! ends expose (`--set-reg`, `--from-stack`, `--no-clobber`, `--terminator`),
64//! so a filter written against them means the same thing as the flag:
65//!
66//! ```
67//! use rf_classify::{Classifier, TerminatorClass};
68//! use rf_core::{Arch, Endianness, RawBinary};
69//! use rf_scan::{scan_binary, ScanOptions};
70//!
71//! // `pop rdi ; ret`, `pop rsi ; ret`, `xor eax, eax ; ret`
72//! let bytes = [0x5f, 0xc3, 0x5e, 0xc3, 0x31, 0xc0, 0xc3];
73//! let image = RawBinary::new(&bytes, Arch::X64, Endianness::Little);
74//! let gadgets = scan_binary(&image, &ScanOptions { depth: 4, ..ScanOptions::default() })?;
75//!
76//! // One classifier for the whole listing: it holds the open decoders.
77//! let cls = Classifier::new(Arch::X64);
78//! let hits: Vec<String> = gadgets
79//! .iter()
80//! .filter(|g| {
81//! let c = cls.classify(g);
82//! c.sets_reg("rdi")
83//! && c.reg_from_stack("rdi")
84//! && !c.clobbers_any(["rsi", "rdx"])
85//! && c.terminator_class() == TerminatorClass::Ret
86//! })
87//! .map(|g| g.text())
88//! .collect();
89//! assert_eq!(hits, ["pop rdi ; ret"]);
90//! # Ok::<(), rf_core::Error>(())
91//! ```
92//!
93//! ## Ranking
94//!
95//! ```
96//! use rf_classify::{classify, rank_key};
97//! use rf_core::{Arch, Endianness, RawBinary};
98//! use rf_scan::{scan_binary, ScanOptions};
99//!
100//! // `pop rdi ; ret` and a bare `ret`.
101//! let image = RawBinary::new(&[0x5f, 0xc3], Arch::X64, Endianness::Little);
102//! let mut gadgets = scan_binary(&image, &ScanOptions { depth: 4, ..ScanOptions::default() })?;
103//! gadgets.sort_by_key(|g| rank_key(&classify(g, Arch::X64), g));
104//! // RankKey orders best-first, so the useful gadget comes first.
105//! assert_eq!(gadgets[0].text(), "pop rdi ; ret");
106//! # Ok::<(), rf_core::Error>(())
107//! ```
108//!
109//! # Semver policy
110//!
111//! Covered by semver from 1.0: the fields of [`Classification`] and its
112//! predicate methods, the [`Class`], [`Terminator`] and [`TerminatorClass`]
113//! variant sets and their [`Class::name`] spellings, and the signatures of
114//! [`classify`], [`quality_score`], [`usability`] and [`rank_key`].
115//!
116//! **Not** covered, and free to change in a minor release: **the numeric
117//! output of [`quality_score`] / [`quality_score_full`] and the tier
118//! boundaries of [`usability`]** — these are a heuristic that is expected to
119//! be re-tuned against measured precision, so compare ranks, never absolute
120//! scores; and which class a *particular* gadget earns, since a rule fix
121//! changes it (that is what TAXONOMY.md's rule numbers are for — cite the
122//! rule, not the outcome). Adding a [`Class`] or [`Terminator`] variant is a
123//! minor release. Pin `rf-classify = "1"`.
124//!
125//! See `docs/API-STABILITY.md` in the repository for the workspace-wide
126//! statement.
127
128#![forbid(unsafe_code)]
129// ENG-08: every public item carries documentation.
130#![warn(missing_docs)]
131
132use std::cell::RefCell;
133use std::cmp::Ordering;
134use std::collections::HashMap;
135use std::rc::Rc;
136
137use rf_core::Arch;
138use rf_scan::{Detailer, Gadget, InsnDetail};
139use serde::Serialize;
140
141mod effect;
142mod generic;
143mod generic_effect;
144mod text;
145mod x86;
146mod x86_effect;
147
148pub use effect::{TerminatorClass, TerminatorTarget, Transfer, ValueDst, ValueSrc};
149
150/// Semantic classes (TAXONOMY.md table). `Other` is the fallback for
151/// gadgets with no labeled instruction (pure control flow, nop).
152#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
153#[serde(rename_all = "snake_case")]
154pub enum Class {
155 /// Writes a general-purpose register (`"reg-write"`).
156 RegWrite,
157 /// Moves the stack pointer to a value the payload controls
158 /// (`"stack-pivot"`).
159 StackPivot,
160 /// Loads from memory (`"mem-read"`).
161 MemRead,
162 /// Stores to memory (`"mem-write"`).
163 MemWrite,
164 /// Computes on registers (`"arithmetic"`).
165 Arithmetic,
166 /// Contains a syscall/trap instruction (`"syscall"`).
167 Syscall,
168 /// Branches through a register — a JOP dispatcher (`"dispatcher"`).
169 Dispatcher,
170 /// No labeled instruction: pure control flow, or a nop (`"other"`).
171 Other,
172}
173
174impl Class {
175 /// The kebab-case name used on both the CLI and the MCP surface, and in
176 /// serialized output. This is the vocabulary `--class` accepts.
177 pub fn name(self) -> &'static str {
178 match self {
179 Class::RegWrite => "reg-write",
180 Class::StackPivot => "stack-pivot",
181 Class::MemRead => "mem-read",
182 Class::MemWrite => "mem-write",
183 Class::Arithmetic => "arithmetic",
184 Class::Syscall => "syscall",
185 Class::Dispatcher => "dispatcher",
186 Class::Other => "other",
187 }
188 }
189}
190
191/// How a gadget hands control on — the single most important thing about it
192/// for chain construction, and the field the MCP surface filters on.
193///
194/// `Ret` means a **bare** return: `ret`, ARM64 `ret`, ARM `bx lr` and
195/// `pop {…, pc}`, MIPS `jr $ra`, PowerPC `blr`, SPARC `retl`, RISC-V
196/// `c.jr ra`. Everything that returns but also moves the stack pointer by a
197/// fixed amount (`ret imm16`), changes privilege or segment (`retf`, `iret`,
198/// a far transfer), or needs separate dispatch machinery (`jmp`, `call`) is a
199/// distinct variant, because those are the differences that decide whether a
200/// gadget can be dropped into a `ret`-driven chain at all.
201#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
202#[serde(rename_all = "kebab-case")]
203pub enum Terminator {
204 /// A bare near return.
205 Ret,
206 /// `ret imm16` — returns and adds a fixed amount to the stack pointer.
207 RetImm,
208 /// A far return (`retf`).
209 Retf,
210 /// An interrupt return (`iret`).
211 Iret,
212 /// A far transfer (far `jmp`/`call`).
213 Far,
214 /// An indirect jump.
215 Jmp,
216 /// An indirect call.
217 Call,
218 /// A syscall or trap instruction.
219 Syscall,
220 /// The gadget does not transfer control at its end.
221 None,
222}
223
224impl Terminator {
225 /// Full name, as serialized (`"ret"`, `"ret-imm"`, `"retf"`, …).
226 pub fn name(self) -> &'static str {
227 match self {
228 Terminator::Ret => "ret",
229 Terminator::RetImm => "ret-imm",
230 Terminator::Retf => "retf",
231 Terminator::Iret => "iret",
232 Terminator::Far => "far",
233 Terminator::Jmp => "jmp",
234 Terminator::Call => "call",
235 Terminator::Syscall => "syscall",
236 Terminator::None => "none",
237 }
238 }
239
240 /// Coarse kind for the MCP `terminator: "ret"|"jmp"|"call"|"syscall"`
241 /// filter: every returning form collapses to `"ret"`.
242 pub fn kind(self) -> &'static str {
243 match self {
244 Terminator::Ret
245 | Terminator::RetImm
246 | Terminator::Retf
247 | Terminator::Iret
248 | Terminator::Far => "ret",
249 Terminator::Jmp => "jmp",
250 Terminator::Call => "call",
251 Terminator::Syscall => "syscall",
252 Terminator::None => "none",
253 }
254 }
255
256 /// A plain near return with no stack adjustment, no privilege change and
257 /// no dispatch requirement — the only terminator a `ret`-driven chain can
258 /// use without extra machinery.
259 pub fn is_bare_return(self) -> bool {
260 self == Terminator::Ret
261 }
262}
263
264/// Precedence when one instruction earns several labels (R10):
265/// mem-write > mem-read > stack-pivot > dispatcher > syscall >
266/// arithmetic > reg-write.
267pub(crate) const PRECEDENCE: &[Class] = &[
268 Class::MemWrite,
269 Class::MemRead,
270 Class::StackPivot,
271 Class::Dispatcher,
272 Class::Syscall,
273 Class::Arithmetic,
274 Class::RegWrite,
275];
276
277/// Per-gadget semantic classification (R1-R13).
278#[derive(Debug, Clone, Serialize)]
279pub struct Classification {
280 /// Primary class: class of the last side-effecting instruction (R10).
281 pub primary: Class,
282 /// Full multi-label set (R9), sorted by name for determinism.
283 pub labels: Vec<Class>,
284 /// Registers written by the gadget (R1-normalized: implicit stack-pointer
285 /// effects of push/pop/call/ret excluded; hardwired-zero registers,
286 /// float/vector/condition registers and the program counter excluded),
287 /// lowercase and sigil-free (`$sp` -> `sp`, `%o0` -> `o0`), deduped, in
288 /// first-appearance order.
289 pub regs_written: Vec<String>,
290 /// Registers the gadget reads, normalized the same way as
291 /// [`Classification::regs_written`].
292 pub regs_read: Vec<String>,
293 /// The subset of `regs_written` whose value comes off the stack — a
294 /// `pop`, or a load whose base register is the stack pointer. This is the
295 /// property that makes a gadget *controllable* from the chain payload,
296 /// and it is what separates usability tier 3 from tier 2.
297 pub regs_from_stack: Vec<String>,
298 /// Instructions earning at least one label (R11).
299 pub side_effects: usize,
300 /// Memory operands whose base or index register must already hold an
301 /// attacker-controlled pointer before the gadget is usable — an
302 /// `add byte ptr [rax], al` needs rax set up first, an absolute or
303 /// RIP-relative operand does not. Counted per instruction.
304 pub mem_pointer_deps: usize,
305 /// Conditional branches sitting in the MIDDLE of the gadget: the tail
306 /// executes only if the flags happen to be right, so the gadget's effect
307 /// is not guaranteed. Counted per instruction.
308 pub mid_branches: usize,
309 /// Deterministic quality score (R12); higher = cleaner gadget.
310 pub quality: i32,
311 /// JOP/COP dispatcher heuristic (R8) — also reflected as the
312 /// `dispatcher` label when it fires.
313 pub dispatcher: bool,
314 /// How the gadget hands control on.
315 pub terminator: Terminator,
316 /// How the terminating transfer picks its target — the register/memory
317 /// distinction [`Terminator`] deliberately does not carry, so that the
318 /// v0.3 spellings of `terminator` stayed byte-identical (CLS-09).
319 /// Combined with `terminator` by
320 /// [`Classification::terminator_class`].
321 ///
322 /// Default for the text path and for gadgets with no terminator:
323 /// [`TerminatorTarget::Implicit`].
324 pub terminator_target: TerminatorTarget,
325 /// **Net change of the stack pointer across the whole gadget**, in bytes,
326 /// or `None` when the effect is not provably constant (CLS-09).
327 ///
328 /// The terminating transfer is included, because the payload bytes it
329 /// consumes are payload bytes: `pop rdi ; ret` is `Some(16)` on x86-64,
330 /// `ret` alone is `Some(8)`, `add rsp, 0x28 ; ret` is `Some(0x30)`. This
331 /// is what a concrete execution of the gadget would leave in `rsp`, which
332 /// is how `tests/ground-truth/oracle_unicorn.py` measures it.
333 ///
334 /// **`None` is a real answer.** A confident wrong stack delta silently
335 /// corrupts a chain layout, so every gadget whose rsp effect depends on a
336 /// register, on memory, or on a path not taken reports `None` rather than
337 /// a number: `xchg rsp, rax`, `pop rsp`, `mov rsp, rbp`, `add rsp, rax`,
338 /// `and rsp, -16`, `leave` (rsp becomes rbp+8), `iret*` (the pop count
339 /// depends on a privilege change), `add esp, 8` in 64-bit code (a 32-bit
340 /// write truncates rsp), and any gadget with a branch before its last
341 /// instruction or a byte that does not decode.
342 ///
343 /// **Which architectures compute it.**
344 ///
345 /// | arch | computed |
346 /// |---|---|
347 /// | arch | computed for |
348 /// |---|---|
349 /// | x86, x86-64 | **fully**, via iced-x86: the pop/push family, `call`, `ret`, `ret imm16`, `retf`, `pusha`/`popa`, `pushf`/`popf`, `enter`, `inc`/`dec rsp`, `add`/`sub rsp, imm`, `lea rsp, [rsp+d]` |
350 /// | ARM, ARM-Thumb | `push {…}` / `pop {…}` register lists, and `add`/`sub sp, sp, #imm`. **`ldm`/`stm` are `None`**, because their base register is printed inside the same operand list as the transfer list |
351 /// | ARM64 | `add`/`sub sp, sp, #imm` only. **`ldp`/`stp`/`ldr`/`str` through `sp` are `None`**: `rf_scan::InsnDetail` does not carry capstone's write-back flag, so `ldr x0, [sp], #16` and `ldr x0, [sp, #16]` are indistinguishable here and they differ by 16 |
352 /// | MIPS 32/64, RISC-V 32/64 | `addi(u)`/`daddi(u)`/`addiw`/`c.addi`/`c.addi16sp` on the stack pointer. Loads and stores through the stack pointer contribute 0, which is sound because neither ISA has a write-back addressing mode |
353 /// | PowerPC 32/64 | `addi r1, r1, imm` and the `stwu`/`stdu`/`lwzu`/… *update* forms based on `r1`. The indexed update forms (`stwux`) are `None`; plain `r1`-based loads and stores contribute 0 |
354 /// | SPARC (all) | **never**, not even 0 — `save`/`restore` rotate a register window, so they move the stack pointer without naming it and "this instruction does not mention `%sp`" proves nothing |
355 /// | any gadget on the text fallback path | **never** — no decoder metadata |
356 ///
357 /// On every architecture, anything not in that list that names the stack
358 /// pointer as an operand, or reaches memory through it, yields `None`.
359 pub stack_delta: Option<i64>,
360 /// Value movements inside the gadget, in program order (CLS-09).
361 ///
362 /// This is the field `--from-stack` is built on: it distinguishes
363 /// `rdi <- [rsp+8]` from `rdi <- rax` from `rdi <- [rbx+0x10]` (naming
364 /// rbx as the register that must already be attacker-controlled) from
365 /// `rdi <- 0x1234`. A register written twice appears twice; the last
366 /// entry for a destination is the one that survives.
367 ///
368 /// Empty on the text fallback path, and for instruction shapes the
369 /// analysis does not model.
370 pub transfers: Vec<Transfer>,
371 /// Registers the gadget writes with a value the chain payload decides —
372 /// a pop, an rsp-relative load, a folded constant, or any known function
373 /// of those (CLS-09).
374 ///
375 /// Names are architectural full-width (`rax` in 64-bit code, `eax` in
376 /// 32-bit, `x0` rather than `w0` on ARM64), because `mov al, [rsp]`
377 /// controls al but not rax and the question a chain author asks is about
378 /// rax. `sets` and [`Classification::clobbers`] partition the full-width
379 /// registers the gadget writes; neither ever contains the stack pointer,
380 /// whose movement is [`Classification::stack_delta`].
381 pub sets: Vec<String>,
382 /// Registers the gadget writes with a value the chain payload does *not*
383 /// decide — it came from an incoming register, from non-stack memory, or
384 /// from the incoming flags (CLS-09).
385 ///
386 /// This is what `--no-clobber rsi,rdx` filters on, and it is a strictly
387 /// stronger statement than "the register appears in `regs_written`":
388 /// `pop rsi ; ret` writes rsi and clobbers nothing, `mov rsi, rax ; ret`
389 /// writes rsi and clobbers it. When a clobber has a known source, the
390 /// corresponding [`Transfer`] names it, so a chain builder can decide to
391 /// control the source instead of rejecting the gadget.
392 pub clobbers: Vec<String>,
393 /// The gadget contains a privileged or undefined instruction (`hlt`,
394 /// `ud2`, `int3`, `cli`, `in`/`out`, `lgdt`, …): it faults or traps in
395 /// user mode, so it cannot appear in a chain.
396 pub privileged: bool,
397 /// True when the classification came from disassembly TEXT rather than
398 /// decoder metadata (R13) — now only reachable when no capstone mode
399 /// reproduces the gadget's recorded text.
400 pub low_confidence: bool,
401}
402
403impl Classification {
404 /// How the gadget hands control on. (Accessor mirroring the field, so
405 /// consumers that hold a `&Classification` behind an abstraction do not
406 /// need field access.)
407 pub fn terminator(&self) -> Terminator {
408 self.terminator
409 }
410
411 /// The nine-way `ret / ret-imm / jmp-reg / jmp-mem / call-reg / call-mem
412 /// / syscall / far / other` classification the query layer filters on
413 /// (CLS-09).
414 ///
415 /// Derived from [`Classification::terminator`] and
416 /// [`Classification::terminator_target`] rather than stored, so there is
417 /// one source of truth. A *direct* `jmp 0x400340` or `call 0x401120` is
418 /// `Other`: neither is reachable from a chain without the address being
419 /// what you wanted anyway.
420 pub fn terminator_class(&self) -> TerminatorClass {
421 match self.terminator {
422 Terminator::Ret => TerminatorClass::Ret,
423 Terminator::RetImm => TerminatorClass::RetImm,
424 Terminator::Retf | Terminator::Iret | Terminator::Far => TerminatorClass::Far,
425 Terminator::Syscall => TerminatorClass::Syscall,
426 Terminator::Jmp => match self.terminator_target {
427 TerminatorTarget::Register { .. } => TerminatorClass::JmpReg,
428 TerminatorTarget::Memory { .. } => TerminatorClass::JmpMem,
429 _ => TerminatorClass::Other,
430 },
431 Terminator::Call => match self.terminator_target {
432 TerminatorTarget::Register { .. } => TerminatorClass::CallReg,
433 TerminatorTarget::Memory { .. } => TerminatorClass::CallMem,
434 _ => TerminatorClass::Other,
435 },
436 Terminator::None => TerminatorClass::Other,
437 }
438 }
439
440 /// Does the gadget write `reg` with a value the chain payload decides?
441 /// The predicate behind `--set-reg`.
442 ///
443 /// `reg` is matched case-insensitively against the full-width names in
444 /// [`Classification::sets`].
445 pub fn sets_reg(&self, reg: &str) -> bool {
446 self.sets.iter().any(|r| r.eq_ignore_ascii_case(reg))
447 }
448
449 /// Does the gadget write `reg` with a value the chain payload does *not*
450 /// decide? The predicate behind `--no-clobber`.
451 pub fn clobbers_reg(&self, reg: &str) -> bool {
452 self.clobbers.iter().any(|r| r.eq_ignore_ascii_case(reg))
453 }
454
455 /// Does the gadget clobber any of `regs`? `--no-clobber rsi,rdx` is
456 /// `!c.clobbers_any(["rsi", "rdx"])`.
457 pub fn clobbers_any<I, S>(&self, regs: I) -> bool
458 where
459 I: IntoIterator<Item = S>,
460 S: AsRef<str>,
461 {
462 regs.into_iter().any(|r| self.clobbers_reg(r.as_ref()))
463 }
464
465 /// Is `reg`'s final value loaded straight off the chain payload — a pop,
466 /// or a load whose base is the stack pointer? The predicate behind
467 /// `--from-stack`, and strictly stronger than [`Classification::sets_reg`]:
468 /// `xor rdi, rdi ; ret` sets rdi without taking it from the stack.
469 ///
470 /// Uses the *last* transfer that writes `reg`, so
471 /// `pop rdi ; mov rdi, rax ; ret` is not from-stack.
472 pub fn reg_from_stack(&self, reg: &str) -> bool {
473 self.last_transfer_to(reg)
474 .is_some_and(Transfer::is_stack_load)
475 }
476
477 /// The payload offset, in bytes from the stack pointer at gadget entry,
478 /// that supplies `reg` — `Some(0)` for rdi in `pop rdi ; pop rsi ; ret`
479 /// and `Some(8)` for rsi. `None` when `reg` is not loaded from the stack
480 /// or the offset is not constant.
481 pub fn stack_offset_of(&self, reg: &str) -> Option<i64> {
482 match &self.last_transfer_to(reg)?.src {
483 ValueSrc::Stack { offset } => *offset,
484 _ => None,
485 }
486 }
487
488 /// The last [`Transfer`] whose destination is register `reg`.
489 pub fn last_transfer_to(&self, reg: &str) -> Option<&Transfer> {
490 self.transfers.iter().rev().find(|t| {
491 t.dst
492 .register()
493 .is_some_and(|d| d.eq_ignore_ascii_case(reg))
494 })
495 }
496
497 /// Every memory write the gadget performs, as `(destination, source)`
498 /// pairs — the write-what-where primitive a chain builder looks for.
499 pub fn memory_writes(&self) -> impl Iterator<Item = &Transfer> {
500 self.transfers.iter().filter(|t| t.dst.is_memory())
501 }
502
503 /// Is `reg` an *input* of this gadget? The predicate behind
504 /// `--reads-reg` / `reads_reg`.
505 ///
506 /// No single field answers this, which is why it lives here rather than
507 /// being re-derived per front end — it was, and the two spellings
508 /// disagreed by 741 gadgets on `elf-Linux-x64` at depth 4 because one of
509 /// them left the terminator out. Three sources are unioned:
510 ///
511 /// 1. [`Classification::regs_read`], the v0.3 list. It keeps the
512 /// *operand's* spelling (`al`, `edi`), so on its own `reads_reg("rax")`
513 /// would miss `add al, cl`.
514 /// 2. The transfer relations, which carry full-width names: a register
515 /// read as a value source ([`ValueSrc::Register`]), as an address
516 /// component (base or index, on either side), as a declared dependency
517 /// ([`Transfer::needs`]), or as the destination of a read-modify-write.
518 /// 3. The terminator's own target register. `jmp rax` reads rax — it is
519 /// the branch target, and a chain builder asking which gadgets consume
520 /// rax must be given the JOP dispatchers.
521 ///
522 /// Matching is case-insensitive on every source.
523 pub fn reads_reg(&self, reg: &str) -> bool {
524 if self.regs_read.iter().any(|r| r.eq_ignore_ascii_case(reg)) {
525 return true;
526 }
527 if self
528 .terminator_target
529 .register()
530 .is_some_and(|r| r.eq_ignore_ascii_case(reg))
531 {
532 return true;
533 }
534 let hit = |o: &Option<String>| o.as_deref().is_some_and(|r| r.eq_ignore_ascii_case(reg));
535 self.transfers.iter().any(|t| {
536 t.needs.iter().any(|r| r.eq_ignore_ascii_case(reg))
537 || match &t.src {
538 ValueSrc::Register { reg: r } => r.eq_ignore_ascii_case(reg),
539 ValueSrc::Memory { base, index, .. }
540 | ValueSrc::Address { base, index, .. } => hit(base) || hit(index),
541 _ => false,
542 }
543 || match &t.dst {
544 ValueDst::Memory { base, index, .. } => hit(base) || hit(index),
545 // A read-modify-write reads its destination register.
546 ValueDst::Register { reg: r } => t.rmw && r.eq_ignore_ascii_case(reg),
547 _ => false,
548 }
549 })
550 }
551}
552
553/// R12 (revised for CLS-07): `max(0, 100 - 15*|side_effects - 1| - 3*(n_insns - 2))`.
554///
555/// The original spelling clamped `side_effects` up to 1, so a gadget with NO
556/// side effects — `ret`, `jmp 0x400340`, `retf 0xce39` — scored exactly the
557/// same 100 as `pop rdi ; ret`. The ideal gadget does *exactly one* thing, so
558/// the penalty is the distance from one side effect in either direction,
559/// which costs the same 15 per step the rule already charged for an extra
560/// side effect. Measured effect on `tests/fixtures/elf-x64-bash-v4.1.5.1` at
561/// depth 10: the largest quality bucket falls from 47.17 % to a value
562/// recorded in the workstream report.
563pub fn quality_score(side_effects: usize, n_insns: usize) -> i32 {
564 quality_score_full(side_effects, n_insns, 0, 0)
565}
566
567/// [`quality_score`] plus the two terms CLS-07 names as missing:
568///
569/// * `regs_written` — each register clobbered beyond the first costs **5**, a
570/// third of a side effect, because a clobber constrains the surrounding
571/// chain without adding a behaviour to reason about;
572/// * `preconditions` — each thing that has to already be true for the gadget
573/// to do what it says costs **10**, two thirds of a side effect: a memory
574/// operand needing an attacker-controlled pointer already in a register
575/// ([`Classification::mem_pointer_deps`]) turns a one-gadget step into a
576/// two-gadget one, and a conditional branch in the middle of the gadget
577/// ([`Classification::mid_branches`]) means the tail runs only if the flags
578/// happen to cooperate.
579///
580/// Both weights are stated as fractions of R12's own 15-per-side-effect
581/// constant rather than fitted; their measured effect on the score
582/// distribution is recorded in the workstream report.
583///
584/// The two dimensions CLS-07 names that are NOT here are the stack delta,
585/// which is assigned to ECO-07/CLS-09 in a later wave, and bad bytes in the
586/// address, which depends on scan parameters and so cannot live in a
587/// parameter-independent score.
588pub fn quality_score_full(
589 side_effects: usize,
590 n_insns: usize,
591 regs_written: usize,
592 preconditions: usize,
593) -> i32 {
594 let se = side_effects as i32;
595 let ni = n_insns.max(2) as i32;
596 let extra_regs = (regs_written as i32 - 1).max(0);
597 (100 - 15 * (se - 1).abs() - 3 * (ni - 2) - 5 * extra_regs - 10 * preconditions as i32).max(0)
598}
599
600/// Usability tier, 0..=3 — the dimension that makes ranking work (CLS-07).
601///
602/// * **3** — bare return terminator, at least one register loaded off the
603/// stack, and at most two side effects. `pop rdi ; ret`.
604/// * **2** — bare return terminator and a useful class. `mov [rdi], rax ; ret`.
605/// * **1** — the gadget does something, but getting to the next gadget costs
606/// extra: `ret imm16`, `retf`, `iret`, a far transfer, or a `jmp`/`call`
607/// terminator that needs JOP/COP dispatch machinery; or the class is
608/// `other`, meaning nothing was identified.
609/// * **0** — the gadget contains a privileged or undefined instruction, or it
610/// has no side effects at all (pure control flow: `ret`, `jmp 0x400340`,
611/// `retf 0xce39`).
612///
613/// Deviation from the design note, recorded deliberately: the note lists
614/// `jmp`/`call` terminators nowhere. They are placed in tier 1 alongside the
615/// other non-bare terminators, because a JOP gadget cannot be used from a
616/// `ret`-driven chain without a dispatcher, which is exactly the property
617/// tier 1 already encodes.
618pub fn usability(c: &Classification, _g: &Gadget) -> u8 {
619 if c.privileged || c.side_effects == 0 {
620 return 0;
621 }
622 if !c.terminator.is_bare_return() || c.primary == Class::Other {
623 return 1;
624 }
625 if !c.regs_from_stack.is_empty() && c.side_effects <= 2 {
626 3
627 } else {
628 2
629 }
630}
631
632/// The default gadget order: **ascending `RankKey` is best-first**.
633///
634/// Key, in priority order: usability tier (descending), quality
635/// (descending), instruction count (ascending), side-effect count
636/// (ascending), address (ascending). The address is a deterministic final
637/// tie-break so the order is total and reproducible across runs, processes
638/// and platforms — which is what a cursor needs.
639#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
640pub struct RankKey {
641 /// The usability tier, 0-3; see [`usability`].
642 pub usability: u8,
643 /// The quality score; see [`quality_score`].
644 pub quality: i32,
645 /// Instruction count, terminator included.
646 pub n_insns: usize,
647 /// Side-effect count (TAXONOMY.md R11).
648 pub side_effects: usize,
649 /// The gadget's address — the deterministic final tie-break.
650 pub vaddr: u64,
651}
652
653impl Ord for RankKey {
654 fn cmp(&self, other: &Self) -> Ordering {
655 other
656 .usability
657 .cmp(&self.usability)
658 .then_with(|| other.quality.cmp(&self.quality))
659 .then_with(|| self.n_insns.cmp(&other.n_insns))
660 .then_with(|| self.side_effects.cmp(&other.side_effects))
661 .then_with(|| self.vaddr.cmp(&other.vaddr))
662 }
663}
664
665impl PartialOrd for RankKey {
666 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
667 Some(self.cmp(other))
668 }
669}
670
671/// Build the [`RankKey`] for one classified gadget.
672pub fn rank_key(c: &Classification, g: &Gadget) -> RankKey {
673 RankKey {
674 usability: usability(c, g),
675 quality: c.quality,
676 n_insns: g.insns.len(),
677 side_effects: c.side_effects,
678 vaddr: g.vaddr,
679 }
680}
681
682/// A reusable classifier for one architecture.
683///
684/// Holds the capstone detail handles for every mode that could have produced
685/// gadgets for its architecture (at most four; none for x86/x64) and picks
686/// per gadget the one that reproduces the gadget's recorded text. Prefer this
687/// over [`classify`] when classifying many gadgets: [`classify`] reaches the
688/// same handles through a thread-local cache, which costs a hash lookup per
689/// call.
690///
691/// `Classifier` is **not** `Send`/`Sync`: capstone handles are not. Construct
692/// one per worker thread.
693pub struct Classifier {
694 arch: Arch,
695 detailers: RefCell<Vec<Detailer>>,
696}
697
698impl std::fmt::Debug for Classifier {
699 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
700 f.debug_struct("Classifier")
701 .field("arch", &self.arch)
702 .field("detail_modes", &self.detailers.borrow().len())
703 .finish()
704 }
705}
706
707impl Classifier {
708 /// Build a classifier for `arch`, opening every capstone detail mode
709 /// that could have produced a gadget for it.
710 ///
711 /// Reuse one classifier across a whole listing: opening the detail
712 /// handles is the expensive part, and [`Classifier::classify`] takes
713 /// `&self`.
714 pub fn new(arch: Arch) -> Self {
715 Classifier {
716 arch,
717 detailers: RefCell::new(Detailer::all_candidates(arch)),
718 }
719 }
720
721 /// The architecture this classifier was built for.
722 pub fn arch(&self) -> Arch {
723 self.arch
724 }
725
726 /// True when this architecture has decoder metadata available — i.e. when
727 /// results will not be `low_confidence`.
728 pub fn has_metadata(&self) -> bool {
729 self.arch.is_x86_family() || !self.detailers.borrow().is_empty()
730 }
731
732 /// Classify one gadget.
733 ///
734 /// Prefer this over the free [`classify`] function when classifying
735 /// more than one gadget: this reuses the open decoder handles.
736 pub fn classify(&self, g: &Gadget) -> Classification {
737 match self.arch {
738 Arch::X86 => x86::classify_x86(g, 32),
739 Arch::X64 => x86::classify_x86(g, 64),
740 _ => match self.detail(g) {
741 Some(det) => generic::classify_detail(g, self.arch, &det),
742 None => text::classify_text(g, self.arch),
743 },
744 }
745 }
746
747 /// Decode `g` with the first detail mode that reproduces its text,
748 /// promoting that mode to the front so a whole-binary pass pays the
749 /// search once.
750 fn detail(&self, g: &Gadget) -> Option<Vec<InsnDetail>> {
751 let mut ds = self.detailers.borrow_mut();
752 for i in 0..ds.len() {
753 if let Some(d) = ds[i].decode_checked(g) {
754 if i > 0 {
755 ds.swap(0, i);
756 }
757 return Some(d);
758 }
759 }
760 None
761 }
762}
763
764thread_local! {
765 /// Per-thread `Classifier` cache: capstone handles are `!Send`, and
766 /// re-opening up to four of them per gadget would dominate the cost of
767 /// classification.
768 static CLASSIFIERS: RefCell<HashMap<Arch, Rc<Classifier>>> =
769 RefCell::new(HashMap::new());
770}
771
772/// Classify one gadget.
773pub fn classify(g: &Gadget, arch: Arch) -> Classification {
774 let c = CLASSIFIERS.with(|m| {
775 m.borrow_mut()
776 .entry(arch)
777 .or_insert_with(|| Rc::new(Classifier::new(arch)))
778 .clone()
779 });
780 c.classify(g)
781}
782
783pub(crate) fn push_unique(v: &mut Vec<String>, s: String) {
784 if !v.contains(&s) {
785 v.push(s);
786 }
787}
788
789pub(crate) fn push_unique_class(v: &mut Vec<Class>, c: Class) {
790 if !v.contains(&c) {
791 v.push(c);
792 }
793}
794
795#[cfg(test)]
796mod tests;