dyncvoke-spoof 0.1.1

Call stack spoofing primitives for Dyncvoke (synthetic and desync)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
//! Call-stack spoofing for Dyncvoke.
//!
//! Public API is [`spoof!`] (direct call) and [`spoof_syscall!`] (indirect
//! syscall). Mode is a compile-time choice:
//!
//! - **Synthetic** (default, `dyncvoke` feature `spoof`). Builds
//!   `RtlUserThreadStart -> BaseThreadInitThunk -> gadget frames -> target`.
//!   Works from any thread, including pool threads.
//! - **Desync** (`dyncvoke` feature `spoof-desync`, crate feature `desync`).
//!   Splices spoofed frames onto a live `BaseThreadInitThunk` return on the
//!   current thread. Looks closer to a normal user thread. Fails on pool
//!   threads that never went through that path.
//!
//! ```ignore
//! use spoof::{spoof_syscall, AsPointer};
//! use core::ffi::c_void;
//! use core::ptr::null_mut;
//!
//! let mut addr: *mut c_void = null_mut();
//! let mut size: usize = 0x1000;
//! let status = spoof_syscall!(
//!     "NtAllocateVirtualMemory",
//!     -1isize,
//!     addr.as_ptr_mut(),
//!     0usize,
//!     size.as_ptr_mut(),
//!     0x3000u32,
//!     0x04u32,
//! ).unwrap() as i32;
//! ```
//!
//! The trampoline lives in `src/asm/{msvc,gnu}/*.asm` and reads
//! [`types::Config`] by field order. Do not reorder those fields.
//! Syscall SSNs come from [`dyncvoke_core::resolve_syscall`].

#![no_std]
#![cfg_attr(docsrs, feature(doc_cfg))]
extern crate alloc;

#[cfg(not(windows))]
compile_error!("dyncvoke-spoof is Windows-only");

use alloc::string::String;
use alloc::vec::Vec;
use core::ffi::c_void;

use data::lc;

pub mod pe;
pub mod types;
pub mod unwind;
pub mod util;

use crate::pe::{function_by_rva, runtime_function_table};
use crate::types::{Config, ImageRuntimeFunction};
use crate::unwind::{rbp_offset, stack_frame};
#[cfg(not(feature = "desync"))]
use crate::unwind::ignoring_set_fpreg;
use crate::util::{find_gadget, find_valid_instruction_offset, shuffle};

#[cfg(feature = "desync")]
use crate::util::find_base_thread_return_address;

// Compile-time-selected asm trampoline. Synthetic mode calls SpoofSynthetic,
// desync calls Spoof. The asm files compile both — the linker drops the
// unused symbol.
#[cfg(feature = "desync")]
unsafe extern "C" {
    fn Spoof(config: &mut Config) -> *mut c_void;
}

#[cfg(not(feature = "desync"))]
unsafe extern "C" {
    fn SpoofSynthetic(config: &mut Config) -> *mut c_void;
}

/// Spoof a direct function call. Resolves the spoofing scaffolding once
/// and then jumps to `addr` with the supplied args under a fake stack.
///
/// # Examples
///
/// ```ignore
/// let kernel32 = dyncvoke_core::get_module_base_address("kernel32.dll");
/// let virtual_alloc = dyncvoke_core::get_function_address(kernel32, "VirtualAlloc");
/// let addr = spoof::spoof!(
///     virtual_alloc,
///     core::ptr::null_mut::<core::ffi::c_void>(),
///     1 << 12,
///     0x3000u32,
///     0x04u32
/// )?;
/// ```
#[macro_export]
macro_rules! spoof {
    ($addr:expr, $($arg:expr),+ $(,)?) => {
        unsafe {
            $crate::__private::spoof(
                $addr as *mut ::core::ffi::c_void,
                &[$(::core::mem::transmute($arg as usize)),*],
                $crate::SpoofKind::Function,
            )
        }
    };
}

/// Spoof an indirect syscall. SSN is resolved via dyncvoke_core's Tartarus
/// Gate, then the syscall instruction inside ntdll is dispatched under a
/// fake stack.
///
/// # Examples
///
/// ```ignore
/// use spoof::{spoof_syscall, AsPointer};
/// let mut addr = core::ptr::null_mut::<core::ffi::c_void>();
/// let mut size = (1 << 12) as usize;
/// let status = spoof_syscall!(
///     "NtAllocateVirtualMemory",
///     -1isize,
///     addr.as_ptr_mut(),
///     0usize,
///     size.as_ptr_mut(),
///     0x3000u32,
///     0x04u32
/// )? as i32;
/// ```
#[macro_export]
macro_rules! spoof_syscall {
    ($name:expr, $($arg:expr),* $(,)?) => {
        unsafe {
            $crate::__private::spoof(
                ::core::ptr::null_mut(),
                &[$(::core::mem::transmute($arg as usize)),*],
                $crate::SpoofKind::Syscall($name),
            )
        }
    };
}

/// Selects which mode the public entry uses.
pub enum SpoofKind<'a> {
    /// Spoof a direct function call.
    Function,
    /// Spoof an indirect syscall by ntdll export name.
    Syscall(&'a str),
}

/// Where a failure happened. Carried by SpoofError variants as a non-string
/// tag so the error path doesn't leak plaintext module/function names into
/// `.rdata`. Display impl decrypts via obfstr at format time only.
#[derive(Debug, Clone, Copy)]
pub enum SpoofTag {
    Kernelbase,
    Kernel32,
    Ntdll,
    RtlUserThreadStart,
    BaseThreadInitThunk,
    AddRspGadget,
    JmpRbxGadget,
}

/// Spoofing errors. Variants carry [`SpoofTag`] rather than literal strings.
#[derive(Debug)]
pub enum SpoofError {
    TooManyArguments,
    NullFunctionAddress,
    ModuleNotLoaded(SpoofTag),
    FunctionNotFound(SpoofTag),
    PdataMissing(SpoofTag),
    UnwindInfoMissing(SpoofTag),
    PrologueNotFound,
    PushRbpPrologueNotFound,
    GadgetNotFound(SpoofTag),
    BaseThreadReturnNotFound,
    SsnResolutionFailed,
}

impl core::fmt::Display for SpoofError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let tag_str = |t: SpoofTag| match t {
            SpoofTag::Kernelbase => lc!("kernelbase.dll"),
            SpoofTag::Kernel32 => lc!("kernel32.dll"),
            SpoofTag::Ntdll => lc!("ntdll.dll"),
            SpoofTag::RtlUserThreadStart => lc!("RtlUserThreadStart"),
            SpoofTag::BaseThreadInitThunk => lc!("BaseThreadInitThunk"),
            SpoofTag::AddRspGadget => lc!("add rsp,0x58; ret"),
            SpoofTag::JmpRbxGadget => lc!("jmp [rbx]"),
        };
        match self {
            SpoofError::TooManyArguments => write!(f, "{}", lc!("too many arguments")),
            SpoofError::NullFunctionAddress => write!(f, "{}", lc!("null function address")),
            SpoofError::ModuleNotLoaded(t) => write!(f, "{}: {}", lc!("module"), tag_str(*t)),
            SpoofError::FunctionNotFound(t) => write!(f, "{}: {}", lc!("export"), tag_str(*t)),
            SpoofError::PdataMissing(t) => write!(f, "{}: {}", lc!("pdata"), tag_str(*t)),
            SpoofError::UnwindInfoMissing(t) => write!(f, "{}: {}", lc!("unwind"), tag_str(*t)),
            SpoofError::PrologueNotFound => write!(f, "{}", lc!("no prologue")),
            SpoofError::PushRbpPrologueNotFound => write!(f, "{}", lc!("no rbp prologue")),
            SpoofError::GadgetNotFound(t) => write!(f, "{}: {}", lc!("gadget"), tag_str(*t)),
            SpoofError::BaseThreadReturnNotFound => write!(f, "{}", lc!("no thread return")),
            SpoofError::SsnResolutionFailed => write!(f, "{}", lc!("ssn fail")),
        }
    }
}

impl core::error::Error for SpoofError {}

/// Ergonomic trait that lets call sites write `addr.as_ptr_mut()` in macro
/// args instead of `&mut addr as *mut _ as *mut c_void`.
pub trait AsPointer {
    fn as_ptr_const(&self) -> *const c_void;
    fn as_ptr_mut(&mut self) -> *mut c_void;
}

impl<T> AsPointer for T {
    #[inline(always)]
    fn as_ptr_const(&self) -> *const c_void {
        self as *const _ as *const c_void
    }
    #[inline(always)]
    fn as_ptr_mut(&mut self) -> *mut c_void {
        self as *mut _ as *mut c_void
    }
}

#[doc(hidden)]
pub mod __private {
    use super::*;
    #[allow(unused_imports)]
    use alloc::string::String;

    /// Synthetic-mode entry. Builds the full scaffolding from scratch and
    /// hands it to the asm trampoline. Works on any thread.
    #[cfg(not(feature = "desync"))]
    pub unsafe fn spoof(
        addr: *mut c_void,
        args: &[*const c_void],
        kind: SpoofKind,
    ) -> Result<*mut c_void, SpoofError> {
        if args.len() > 11 {
            return Err(SpoofError::TooManyArguments);
        }
        if matches!(kind, SpoofKind::Function) && addr.is_null() {
            return Err(SpoofError::NullFunctionAddress);
        }

        let mut config = Config::default();

        let kernelbase = dyncvoke_core::get_module_base_address(&lc!("kernelbase.dll"));
        if kernelbase == 0 {
            return Err(SpoofError::ModuleNotLoaded(SpoofTag::Kernelbase));
        }
        let ntdll = dyncvoke_core::get_module_base_address(&lc!("ntdll.dll"));
        if ntdll == 0 {
            return Err(SpoofError::ModuleNotLoaded(SpoofTag::Ntdll));
        }
        let kernel32 = dyncvoke_core::get_module_base_address(&lc!("kernel32.dll"));
        if kernel32 == 0 {
            return Err(SpoofError::ModuleNotLoaded(SpoofTag::Kernel32));
        }

        let rtl_user_addr =
            dyncvoke_core::get_function_address(ntdll, &lc!("RtlUserThreadStart"));
        if rtl_user_addr == 0 {
            return Err(SpoofError::FunctionNotFound(SpoofTag::RtlUserThreadStart));
        }
        let base_thread_addr =
            dyncvoke_core::get_function_address(kernel32, &lc!("BaseThreadInitThunk"));
        if base_thread_addr == 0 {
            return Err(SpoofError::FunctionNotFound(SpoofTag::BaseThreadInitThunk));
        }

        config.rtl_user_addr = rtl_user_addr as *const c_void;
        config.base_thread_addr = base_thread_addr as *const c_void;

        let kb_table = runtime_function_table(kernelbase as *mut c_void)
            .ok_or(SpoofError::PdataMissing(SpoofTag::Kernelbase))?;
        let ntdll_table = runtime_function_table(ntdll as *mut c_void)
            .ok_or(SpoofError::PdataMissing(SpoofTag::Ntdll))?;
        let k32_table = runtime_function_table(kernel32 as *mut c_void)
            .ok_or(SpoofError::PdataMissing(SpoofTag::Kernel32))?;

        let rtl_user_runtime =
            function_by_rva(ntdll_table, (rtl_user_addr - ntdll) as u32)
                .ok_or(SpoofError::UnwindInfoMissing(SpoofTag::RtlUserThreadStart))?;
        let base_thread_runtime =
            function_by_rva(k32_table, (base_thread_addr - kernel32) as u32)
                .ok_or(SpoofError::UnwindInfoMissing(SpoofTag::BaseThreadInitThunk))?;

        config.rtl_user_thread_size =
            ignoring_set_fpreg(ntdll as *mut c_void, rtl_user_runtime)
                .ok_or(SpoofError::UnwindInfoMissing(SpoofTag::RtlUserThreadStart))? as u64;
        config.base_thread_size =
            ignoring_set_fpreg(kernel32 as *mut c_void, base_thread_runtime)
                .ok_or(SpoofError::UnwindInfoMissing(SpoofTag::BaseThreadInitThunk))? as u64;

        let first_prolog = find_prolog(kernelbase as *mut c_void, kb_table)
            .ok_or(SpoofError::PrologueNotFound)?;
        config.first_frame_fp =
            (first_prolog.frame + first_prolog.offset as u64) as *const c_void;
        config.first_frame_size = first_prolog.stack_size as u64;

        let second_prolog = find_push_rbp(kernelbase as *mut c_void, kb_table)
            .ok_or(SpoofError::PushRbpPrologueNotFound)?;
        config.second_frame_fp =
            (second_prolog.frame + second_prolog.offset as u64) as *const c_void;
        config.second_frame_size = second_prolog.stack_size as u64;
        config.rbp_stack_offset = second_prolog.rbp_offset as u64;

        let (add_rsp_addr, size) = find_gadget(
            kernelbase as *mut c_void,
            &[0x48, 0x83, 0xC4, 0x58, 0xC3],
            kb_table,
            Some(0x58),
        )
        .ok_or(SpoofError::GadgetNotFound(SpoofTag::AddRspGadget))?;
        config.add_rsp_gadget = add_rsp_addr as *const c_void;
        config.add_rsp_frame_size = size as u64;

        let (jmp_rbx_addr, size) =
            find_gadget(kernelbase as *mut c_void, &[0xFF, 0x23], kb_table, None)
                .ok_or(SpoofError::GadgetNotFound(SpoofTag::JmpRbxGadget))?;
        config.jmp_rbx_gadget = jmp_rbx_addr as *const c_void;
        config.jmp_rbx_frame_size = size as u64;

        config.number_args = args.len() as u64;
        write_args(&mut config, args);

        match kind {
            SpoofKind::Function => config.spoof_function = addr as *const c_void,
            SpoofKind::Syscall(name) => {
                let (ssn, syscall_addr) = dyncvoke_core::resolve_syscall(name)
                    .map_err(|_| SpoofError::SsnResolutionFailed)?;
                config.is_syscall = 1;
                config.ssn = ssn as u32;
                config.spoof_function = syscall_addr as *const c_void;
            }
        }

        Ok(SpoofSynthetic(&mut config))
    }

    /// Desync-mode entry. Reuses the current thread's real
    /// BaseThreadInitThunk return record. Won't work on pool threads.
    #[cfg(feature = "desync")]
    pub unsafe fn spoof(
        addr: *mut c_void,
        args: &[*const c_void],
        kind: SpoofKind,
    ) -> Result<*mut c_void, SpoofError> {
        if args.len() > 11 {
            return Err(SpoofError::TooManyArguments);
        }
        if matches!(kind, SpoofKind::Function) && addr.is_null() {
            return Err(SpoofError::NullFunctionAddress);
        }

        let mut config = Config::default();

        let kernelbase = dyncvoke_core::get_module_base_address(&lc!("kernelbase.dll"));
        if kernelbase == 0 {
            return Err(SpoofError::ModuleNotLoaded(SpoofTag::Kernelbase));
        }
        let kernel32 = dyncvoke_core::get_module_base_address(&lc!("kernel32.dll"));
        if kernel32 == 0 {
            return Err(SpoofError::ModuleNotLoaded(SpoofTag::Kernel32));
        }

        let base_thread_addr =
            dyncvoke_core::get_function_address(kernel32, &lc!("BaseThreadInitThunk"));
        if base_thread_addr == 0 {
            return Err(SpoofError::FunctionNotFound(SpoofTag::BaseThreadInitThunk));
        }

        let k32_table = runtime_function_table(kernel32 as *mut c_void)
            .ok_or(SpoofError::PdataMissing(SpoofTag::Kernel32))?;
        let base_thread_runtime =
            function_by_rva(k32_table, (base_thread_addr - kernel32) as u32)
                .ok_or(SpoofError::UnwindInfoMissing(SpoofTag::BaseThreadInitThunk))?;

        let base_thread_size =
            (base_thread_runtime.EndAddress - base_thread_runtime.BeginAddress) as usize;
        let stack_slot = find_base_thread_return_address(
            kernel32 as *mut c_void,
            base_thread_addr as *mut c_void,
            base_thread_size,
        )
        .ok_or(SpoofError::BaseThreadReturnNotFound)?;
        config.return_address = stack_slot as *const c_void;

        let kb_table = runtime_function_table(kernelbase as *mut c_void)
            .ok_or(SpoofError::PdataMissing(SpoofTag::Kernelbase))?;

        let first_prolog = find_prolog(kernelbase as *mut c_void, kb_table)
            .ok_or(SpoofError::PrologueNotFound)?;
        config.first_frame_fp =
            (first_prolog.frame + first_prolog.offset as u64) as *const c_void;
        config.first_frame_size = first_prolog.stack_size as u64;

        let second_prolog = find_push_rbp(kernelbase as *mut c_void, kb_table)
            .ok_or(SpoofError::PushRbpPrologueNotFound)?;
        config.second_frame_fp =
            (second_prolog.frame + second_prolog.offset as u64) as *const c_void;
        config.second_frame_size = second_prolog.stack_size as u64;
        config.rbp_stack_offset = second_prolog.rbp_offset as u64;

        let (add_rsp_addr, size) = find_gadget(
            kernelbase as *mut c_void,
            &[0x48, 0x83, 0xC4, 0x58, 0xC3],
            kb_table,
            Some(0x58),
        )
        .ok_or(SpoofError::GadgetNotFound(SpoofTag::AddRspGadget))?;
        config.add_rsp_gadget = add_rsp_addr as *const c_void;
        config.add_rsp_frame_size = size as u64;

        let (jmp_rbx_addr, size) =
            find_gadget(kernelbase as *mut c_void, &[0xFF, 0x23], kb_table, None)
                .ok_or(SpoofError::GadgetNotFound(SpoofTag::JmpRbxGadget))?;
        config.jmp_rbx_gadget = jmp_rbx_addr as *const c_void;
        config.jmp_rbx_frame_size = size as u64;

        config.number_args = args.len() as u64;
        write_args(&mut config, args);

        match kind {
            SpoofKind::Function => config.spoof_function = addr as *const c_void,
            SpoofKind::Syscall(name) => {
                let (ssn, syscall_addr) = dyncvoke_core::resolve_syscall(name)
                    .map_err(|_| SpoofError::SsnResolutionFailed)?;
                config.is_syscall = 1;
                config.ssn = ssn as u32;
                config.spoof_function = syscall_addr as *const c_void;
            }
        }

        Ok(Spoof(&mut config))
    }

    #[inline]
    fn write_args(cfg: &mut Config, args: &[*const c_void]) {
        for (i, &a) in args.iter().enumerate() {
            match i {
                0 => cfg.arg01 = a,
                1 => cfg.arg02 = a,
                2 => cfg.arg03 = a,
                3 => cfg.arg04 = a,
                4 => cfg.arg05 = a,
                5 => cfg.arg06 = a,
                6 => cfg.arg07 = a,
                7 => cfg.arg08 = a,
                8 => cfg.arg09 = a,
                9 => cfg.arg10 = a,
                10 => cfg.arg11 = a,
                _ => break,
            }
        }
    }
}

/// Selected decoy frame metadata.
#[derive(Copy, Clone, Default)]
struct Prolog {
    frame: u64,
    stack_size: u32,
    offset: u32,
    rbp_offset: u32,
}

/// Scan kernelbase's runtime function table for a function whose unwind
/// info describes a spoof-compatible RSP-based frame. Shuffles the survivors
/// and returns the first one — picks a different decoy each run.
fn find_prolog(module_base: *mut c_void, runtime_table: &[ImageRuntimeFunction]) -> Option<Prolog> {
    let mut prologs: Vec<Prolog> = runtime_table
        .iter()
        .filter_map(|runtime| {
            let (is_valid, stack_size) = unsafe { stack_frame(module_base, runtime) }?;
            if !is_valid {
                return None;
            }
            let offset = find_valid_instruction_offset(module_base, runtime)?;
            let frame = module_base as u64 + runtime.BeginAddress as u64;
            Some(Prolog {
                frame,
                stack_size,
                offset,
                ..Default::default()
            })
        })
        .collect();

    if prologs.is_empty() {
        return None;
    }
    shuffle(&mut prologs);
    prologs.first().copied()
}

/// Same idea but for an RBP-pushing prologue — these are needed for the
/// inner spoofed frame where the unwinder will reconstruct rbp from the
/// stored slot.
fn find_push_rbp(
    module_base: *mut c_void,
    runtime_table: &[ImageRuntimeFunction],
) -> Option<Prolog> {
    let mut prologs: Vec<Prolog> = runtime_table
        .iter()
        .filter_map(|runtime| {
            let (rbp_off, stack_size) = unsafe { rbp_offset(module_base, runtime) }?;
            if rbp_off == 0 || stack_size == 0 || stack_size <= rbp_off {
                return None;
            }
            let offset = find_valid_instruction_offset(module_base, runtime)?;
            let frame = module_base as u64 + runtime.BeginAddress as u64;
            Some(Prolog {
                frame,
                stack_size,
                offset,
                rbp_offset: rbp_off,
            })
        })
        .collect();

    if prologs.is_empty() {
        return None;
    }
    // First match is consistently unsuitable on most Windows builds; drop it.
    prologs.remove(0);
    if prologs.is_empty() {
        return None;
    }
    shuffle(&mut prologs);
    prologs.first().copied()
}