Skip to main content

rf_classify/
effect.rs

1//! The semantic layer a constraint search needs and no consumer can derive
2//! from gadget text (CLS-09).
3//!
4//! Four things live here:
5//!
6//! 1. **Stack delta** — [`Classification::stack_delta`](crate::Classification::stack_delta),
7//!    documented on that field. `Option<i64>`, and `None` is a first-class
8//!    answer, not a failure: see [`stack_delta`](crate::Classification::stack_delta).
9//! 2. **Register-transfer relations** — [`Transfer`], with the source kind
10//!    ([`ValueSrc`]) distinguished, so `--from-stack` can mean "the value came
11//!    off the chain payload" rather than "the register ended up written
12//!    somehow".
13//! 3. **The clobber set** — [`Classification::clobbers`](crate::Classification::clobbers)
14//!    versus [`Classification::sets`](crate::Classification::sets), documented
15//!    on those fields.
16//! 4. **A filterable terminator classification** — [`TerminatorClass`], the
17//!    nine-way `ret / ret-imm / jmp-reg / jmp-mem / call-reg / call-mem /
18//!    syscall / far / other` split the query layer filters on. It is derived
19//!    from the existing [`Terminator`](crate::Terminator) plus
20//!    [`TerminatorTarget`]; the v0.3 enum and its serialized spellings are
21//!    unchanged.
22//!
23//! Everything here is *additive*: no existing field, name or serialization
24//! changed, so the v0.3 MCP `outputSchema` and the CLI's `--json` record are
25//! byte-identical until a consumer opts in.
26
27use serde::Serialize;
28
29/// Where a value came from.
30///
31/// The `Stack` / `Register` / `Memory` / `Immediate` split is the point of
32/// this type: a chain builder needs to know that `pop rdi` takes rdi from the
33/// payload while `mov rdi, rax` takes it from whatever rax happened to hold,
34/// and both are "rdi was written" to every consumer that only sees
35/// [`Classification::regs_written`](crate::Classification::regs_written).
36#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
37#[serde(tag = "kind", rename_all = "kebab-case")]
38pub enum ValueSrc {
39    /// The chain payload: a pop, or a load whose base register is the stack
40    /// pointer.
41    ///
42    /// `offset` is the byte offset from the stack pointer's value at gadget
43    /// **entry** — so `pop rdi ; pop rsi ; ret` reports rdi from offset 0 and
44    /// rsi from offset 8 — and is `None` when the running stack-pointer delta
45    /// stopped being constant before this instruction.
46    Stack {
47        /// Byte offset from the stack pointer at gadget entry; `None` when
48        /// the running delta stopped being constant.
49        offset: Option<i64>,
50    },
51    /// Another register's incoming value (`mov rax, rbx`).
52    Register {
53        /// The source register.
54        reg: String,
55    },
56    /// Memory that is *not* on the stack. `base` is the register that must
57    /// already hold an attacker-controlled pointer for the operand to be
58    /// usable; it is `None` for an absolute or PC-relative address, which
59    /// needs no set-up at all.
60    Memory {
61        /// Base register of the memory operand, if any.
62        base: Option<String>,
63        /// Index register of the memory operand, if any.
64        index: Option<String>,
65        /// Signed displacement, in bytes.
66        disp: i64,
67    },
68    /// The *address* of a memory operand rather than its contents — x86
69    /// `lea`, and the address-forming half of a load/store.
70    Address {
71        /// Base register of the address being formed, if any.
72        base: Option<String>,
73        /// Index register of the address being formed, if any.
74        index: Option<String>,
75        /// Signed displacement, in bytes.
76        disp: i64,
77    },
78    /// An instruction immediate.
79    Immediate {
80        /// The immediate's value, sign-extended.
81        value: i64,
82    },
83    /// A combination this analysis does not decompose further (`mul`, a
84    /// three-input arithmetic form, a conditional move).
85    Computed,
86}
87
88impl ValueSrc {
89    /// True for a value that came off the chain payload — the predicate
90    /// behind `--from-stack`.
91    pub fn is_from_stack(&self) -> bool {
92        matches!(self, ValueSrc::Stack { .. })
93    }
94
95    /// The register that must already hold an attacker-controlled pointer
96    /// before this source can be read, if any.
97    pub fn pointer_dep(&self) -> Option<&str> {
98        match self {
99            ValueSrc::Memory { base, .. } => base.as_deref(),
100            _ => None,
101        }
102    }
103}
104
105/// Where a value went.
106#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
107#[serde(tag = "kind", rename_all = "kebab-case")]
108pub enum ValueDst {
109    /// A register.
110    Register {
111        /// The destination register.
112        reg: String,
113    },
114    /// A stack slot, at a byte offset from the stack pointer's value at
115    /// gadget entry (`push rax` on entry writes offset -8 on x86-64).
116    Stack {
117        /// Byte offset from the stack pointer at gadget entry; `None` when
118        /// the running delta stopped being constant.
119        offset: Option<i64>,
120    },
121    /// Non-stack memory. `base` is the register that must already hold an
122    /// attacker-controlled pointer — this is the field that separates
123    /// `mov qword ptr [rdi], rax` (a controlled arbitrary write) from
124    /// `add byte ptr [rax], al` (a byte increment through the pointer it is
125    /// incrementing with).
126    Memory {
127        /// Base register of the memory operand, if any.
128        base: Option<String>,
129        /// Index register of the memory operand, if any.
130        index: Option<String>,
131        /// Signed displacement, in bytes.
132        disp: i64,
133    },
134}
135
136impl ValueDst {
137    /// The destination register, for a register destination.
138    pub fn register(&self) -> Option<&str> {
139        match self {
140            ValueDst::Register { reg } => Some(reg.as_str()),
141            _ => None,
142        }
143    }
144
145    /// The register that must already hold an attacker-controlled pointer for
146    /// the write to land where intended.
147    pub fn pointer_dep(&self) -> Option<&str> {
148        match self {
149            ValueDst::Memory { base, .. } => base.as_deref(),
150            _ => None,
151        }
152    }
153
154    /// True for a non-stack memory destination.
155    pub fn is_memory(&self) -> bool {
156        matches!(self, ValueDst::Memory { .. })
157    }
158}
159
160/// One value movement inside a gadget: `dst <- src`.
161///
162/// Transfers are recorded in program order, one per modelled instruction. A
163/// register written twice produces two entries; the **last** entry for a
164/// destination is the one that survives the gadget.
165#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
166pub struct Transfer {
167    /// Where the value went.
168    pub dst: ValueDst,
169    /// Where the value came from.
170    pub src: ValueSrc,
171    /// Registers that must already hold attacker-controlled values for this
172    /// transfer to be usable — the base and index registers of whichever of
173    /// `dst`/`src` is a non-stack memory operand. Empty for a pure
174    /// register-to-register move.
175    pub needs: Vec<String>,
176    /// The destination is read as well as written: `add rax, rbx`,
177    /// `add byte ptr [rax], al`. A read-modify-write cannot *place* a chosen
178    /// value; it can only perturb whatever is already there.
179    pub rmw: bool,
180    /// Width of the moved value in bytes, when the decoder states it.
181    pub width: Option<u32>,
182}
183
184impl Transfer {
185    /// `dst <- src` where the destination is a register and the source is the
186    /// chain payload.
187    pub fn is_stack_load(&self) -> bool {
188        !self.rmw && self.dst.register().is_some() && self.src.is_from_stack()
189    }
190}
191
192/// How the terminating control transfer picks its target.
193///
194/// Split out from [`Terminator`](crate::Terminator) rather than folded into
195/// it so that no existing variant, name or serialized string changes: v0.3's
196/// `terminator` field still reads `"ret"`, `"jmp"`, `"call"`, and the
197/// register/memory distinction the query layer wants arrives beside it.
198#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
199#[serde(tag = "kind", rename_all = "kebab-case")]
200pub enum TerminatorTarget {
201    /// The target is an immediate encoded in the instruction
202    /// (`jmp 0x400340`, `call 0x401120`).
203    Direct,
204    /// Indirect through a register (`jmp rax`, `blr x16`, `bctr`).
205    Register {
206        /// The register holding the branch target.
207        reg: String,
208    },
209    /// Indirect through memory (`jmp qword ptr [rax + 8]`).
210    Memory {
211        /// Base register of the memory operand, if any.
212        base: Option<String>,
213        /// Index register of the memory operand, if any.
214        index: Option<String>,
215        /// Signed displacement, in bytes.
216        disp: i64,
217    },
218    /// The target is not an operand: it comes off the stack (`ret`) or out of
219    /// a link register (`bx lr`, `jr $ra`, `blr`), or there is no terminator.
220    Implicit,
221}
222
223impl TerminatorTarget {
224    /// The register the transfer goes through, for `--dispatcher`-style
225    /// queries.
226    pub fn register(&self) -> Option<&str> {
227        match self {
228            TerminatorTarget::Register { reg } => Some(reg.as_str()),
229            TerminatorTarget::Memory { base, .. } => base.as_deref(),
230            _ => None,
231        }
232    }
233}
234
235/// The nine-way terminator classification the query layer filters on.
236///
237/// This is the vocabulary CLS-09 asks for. It is *derived*, not stored:
238/// [`Classification::terminator_class`](crate::Classification::terminator_class)
239/// folds [`Terminator`](crate::Terminator) together with
240/// [`TerminatorTarget`], so there is exactly one source of truth for what a
241/// gadget's terminator is.
242#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
243#[serde(rename_all = "kebab-case")]
244pub enum TerminatorClass {
245    /// A bare near return.
246    Ret,
247    /// `ret imm16` — returns, and also advances the stack pointer.
248    RetImm,
249    /// `jmp reg`.
250    JmpReg,
251    /// `jmp [mem]`.
252    JmpMem,
253    /// `call reg`.
254    CallReg,
255    /// `call [mem]`.
256    CallMem,
257    /// A syscall/interrupt gate.
258    Syscall,
259    /// A far or privilege-changing transfer: `retf`, `iret`, `jmp far`,
260    /// `call far`.
261    Far,
262    /// Anything else — a direct `jmp`/`call` to a fixed address, or no
263    /// terminator at all.
264    Other,
265}
266
267impl TerminatorClass {
268    /// The serialized spelling: `"ret"`, `"ret-imm"`, `"jmp-reg"`,
269    /// `"jmp-mem"`, `"call-reg"`, `"call-mem"`, `"syscall"`, `"far"`,
270    /// `"other"`.
271    pub fn name(self) -> &'static str {
272        match self {
273            TerminatorClass::Ret => "ret",
274            TerminatorClass::RetImm => "ret-imm",
275            TerminatorClass::JmpReg => "jmp-reg",
276            TerminatorClass::JmpMem => "jmp-mem",
277            TerminatorClass::CallReg => "call-reg",
278            TerminatorClass::CallMem => "call-mem",
279            TerminatorClass::Syscall => "syscall",
280            TerminatorClass::Far => "far",
281            TerminatorClass::Other => "other",
282        }
283    }
284
285    /// Every accepted value, for a parameter-validation error message.
286    pub const ALL: &'static [&'static str] = &[
287        "ret", "ret-imm", "jmp-reg", "jmp-mem", "call-reg", "call-mem", "syscall", "far", "other",
288    ];
289
290    /// Parse the serialized spelling.
291    pub fn parse(s: &str) -> Option<TerminatorClass> {
292        Some(match s {
293            "ret" => TerminatorClass::Ret,
294            "ret-imm" => TerminatorClass::RetImm,
295            "jmp-reg" => TerminatorClass::JmpReg,
296            "jmp-mem" => TerminatorClass::JmpMem,
297            "call-reg" => TerminatorClass::CallReg,
298            "call-mem" => TerminatorClass::CallMem,
299            "syscall" => TerminatorClass::Syscall,
300            "far" => TerminatorClass::Far,
301            "other" => TerminatorClass::Other,
302            _ => return None,
303        })
304    }
305}