wraith-rs 0.1.8

Safe abstractions for Windows PEB/TEB manipulation and anti-detection techniques
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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
//! Spoofed syscall invocation
//!
//! Combines gadget finding, stack spoofing, and trampolines to invoke
//! syscalls with spoofed return addresses that appear legitimate.

#[cfg(all(not(feature = "std"), feature = "alloc"))]
use alloc::{format, string::String, vec::Vec};

#[cfg(feature = "std")]
use std::{format, string::String, vec::Vec};

#[cfg(feature = "std")]
use std::sync::OnceLock;

use super::gadget::GadgetFinder;
use super::trampoline::{SpoofTrampoline, TrampolineAllocator};
use crate::error::{Result, WraithError};
use crate::manipulation::syscall::SyscallEntry;
use core::arch::asm;

/// global trampoline allocator
#[cfg(feature = "std")]
static TRAMPOLINE_ALLOC: OnceLock<Result<TrampolineAllocator>> = OnceLock::new();

#[cfg(feature = "std")]
fn get_trampoline_allocator() -> Result<&'static TrampolineAllocator> {
    let result = TRAMPOLINE_ALLOC.get_or_init(TrampolineAllocator::new);
    match result {
        Ok(alloc) => Ok(alloc),
        Err(_e) => Err(WraithError::TrampolineAllocationFailed {
            near: 0,
            size: 0,
        }),
    }
}

#[cfg(not(feature = "std"))]
fn get_trampoline_allocator() -> Result<&'static TrampolineAllocator> {
    Err(WraithError::TrampolineAllocationFailed {
        near: 0,
        size: 0,
    })
}

/// mode of return address spoofing
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SpoofMode {
    /// use a gadget (jmp rbx/rax) for clean indirect jump
    Gadget,
    /// synthesize a fake stack frame chain
    SyntheticStack,
    /// simple return address replacement
    SimpleSpoof,
    /// no spoofing (falls back to indirect syscall)
    None,
}

impl Default for SpoofMode {
    fn default() -> Self {
        Self::Gadget
    }
}

/// configuration for spoofed syscalls
#[derive(Debug, Clone)]
pub struct SpoofConfig {
    /// spoofing mode to use
    pub mode: SpoofMode,
    /// prefer ntdll gadgets (most legitimate looking)
    pub prefer_ntdll: bool,
    /// custom spoof address (for SimpleSpoof mode)
    pub custom_spoof_addr: Option<usize>,
    /// stack pattern to synthesize (for SyntheticStack mode)
    pub stack_pattern: Option<Vec<&'static str>>,
}

impl Default for SpoofConfig {
    fn default() -> Self {
        Self {
            mode: SpoofMode::Gadget,
            prefer_ntdll: true,
            custom_spoof_addr: None,
            stack_pattern: None,
        }
    }
}

impl SpoofConfig {
    /// create config for gadget-based spoofing
    pub fn gadget() -> Self {
        Self {
            mode: SpoofMode::Gadget,
            ..Default::default()
        }
    }

    /// create config for simple address spoofing
    pub fn simple(spoof_addr: usize) -> Self {
        Self {
            mode: SpoofMode::SimpleSpoof,
            custom_spoof_addr: Some(spoof_addr),
            ..Default::default()
        }
    }

    /// create config for synthetic stack
    pub fn synthetic(pattern: Vec<&'static str>) -> Self {
        Self {
            mode: SpoofMode::SyntheticStack,
            stack_pattern: Some(pattern),
            ..Default::default()
        }
    }
}

/// spoofed syscall invoker
///
/// wraps a syscall with return address spoofing to evade call stack analysis
pub struct SpoofedSyscall {
    /// syscall number
    ssn: u16,
    /// address of syscall instruction in ntdll
    syscall_addr: usize,
    /// gadget address for return
    gadget_addr: usize,
    /// spoof address for simple mode
    spoof_addr: usize,
    /// name of the syscall
    name: String,
    /// allocated trampoline (if using trampoline mode)
    trampoline: Option<SpoofTrampoline>,
    /// spoofing mode
    mode: SpoofMode,
}

impl SpoofedSyscall {
    /// create spoofed syscall from name with default config
    pub fn new(name: &str) -> Result<Self> {
        Self::with_config(name, SpoofConfig::default())
    }

    /// create spoofed syscall with custom configuration
    pub fn with_config(name: &str, config: SpoofConfig) -> Result<Self> {
        let table = crate::manipulation::syscall::get_syscall_table()?;
        let entry = table.get(name).ok_or_else(|| WraithError::SyscallNotFound {
            name: name.to_string(),
        })?;

        Self::from_entry_with_config(entry, config)
    }

    /// create from syscall entry with config
    pub fn from_entry_with_config(entry: &SyscallEntry, config: SpoofConfig) -> Result<Self> {
        let syscall_addr = entry.syscall_address.ok_or_else(|| {
            WraithError::SyscallEnumerationFailed {
                reason: format!("no syscall address for {}", entry.name),
            }
        })?;

        // find gadget based on mode
        let (gadget_addr, spoof_addr) = match config.mode {
            SpoofMode::Gadget => {
                let finder = GadgetFinder::new()?;
                let gadget = finder.find_best_jmp_gadget()?;
                (gadget.address(), 0)
            }
            SpoofMode::SimpleSpoof => {
                let spoof = config.custom_spoof_addr.unwrap_or_else(|| {
                    // default: use a kernel32 address
                    let finder = GadgetFinder::new().ok();
                    finder
                        .and_then(|f| f.find_ret("kernel32.dll").ok())
                        .and_then(|r| r.into_iter().next())
                        .map(|g| g.address())
                        .unwrap_or(0)
                });
                (0, spoof)
            }
            SpoofMode::SyntheticStack => {
                // for synthetic stack, we need both a gadget and the stack setup
                let finder = GadgetFinder::new()?;
                let gadget = finder.find_best_jmp_gadget()?;
                (gadget.address(), 0)
            }
            SpoofMode::None => (0, 0),
        };

        // allocate trampoline if needed
        let trampoline = if config.mode != SpoofMode::None {
            let alloc = get_trampoline_allocator()?;
            let tramp = alloc.allocate()?;

            // write appropriate trampoline code
            match config.mode {
                SpoofMode::Gadget => {
                    tramp.write_spoofed_syscall(entry.ssn, syscall_addr, gadget_addr)?;
                }
                SpoofMode::SimpleSpoof => {
                    tramp.write_simple_spoofed_syscall(entry.ssn, syscall_addr, spoof_addr)?;
                }
                SpoofMode::SyntheticStack => {
                    tramp.write_spoofed_syscall(entry.ssn, syscall_addr, gadget_addr)?;
                }
                SpoofMode::None => {}
            }

            Some(tramp)
        } else {
            None
        };

        Ok(Self {
            ssn: entry.ssn,
            syscall_addr,
            gadget_addr,
            spoof_addr,
            name: entry.name.clone(),
            trampoline,
            mode: config.mode,
        })
    }

    /// create from syscall entry with default config
    pub fn from_entry(entry: &SyscallEntry) -> Result<Self> {
        Self::from_entry_with_config(entry, SpoofConfig::default())
    }

    /// get syscall number
    pub fn ssn(&self) -> u16 {
        self.ssn
    }

    /// get syscall name
    pub fn name(&self) -> &str {
        &self.name
    }

    /// get the spoofing mode
    pub fn mode(&self) -> SpoofMode {
        self.mode
    }

    /// get gadget address (if using gadget mode)
    pub fn gadget_addr(&self) -> Option<usize> {
        if self.gadget_addr != 0 {
            Some(self.gadget_addr)
        } else {
            None
        }
    }
}

// x86_64 syscall implementations with spoofing
#[cfg(target_arch = "x86_64")]
impl SpoofedSyscall {
    /// invoke spoofed syscall with 0 arguments
    ///
    /// # Safety
    /// caller must ensure the syscall is appropriate to call with 0 args
    #[inline(never)]
    pub unsafe fn call0(&self) -> i32 {
        if let Some(ref tramp) = self.trampoline {
            type Fn0 = unsafe extern "system" fn() -> i32;
            let f: Fn0 = unsafe { tramp.as_fn_ptr() };
            unsafe { f() }
        } else {
            unsafe { self.call0_direct() }
        }
    }

    /// invoke spoofed syscall with 1 argument
    ///
    /// # Safety
    /// caller must ensure args are valid for this syscall
    #[inline(never)]
    pub unsafe fn call1(&self, arg1: usize) -> i32 {
        if let Some(ref tramp) = self.trampoline {
            type Fn1 = unsafe extern "system" fn(usize) -> i32;
            let f: Fn1 = unsafe { tramp.as_fn_ptr() };
            unsafe { f(arg1) }
        } else {
            unsafe { self.call1_direct(arg1) }
        }
    }

    /// invoke spoofed syscall with 2 arguments
    ///
    /// # Safety
    /// caller must ensure args are valid for this syscall
    #[inline(never)]
    pub unsafe fn call2(&self, arg1: usize, arg2: usize) -> i32 {
        if let Some(ref tramp) = self.trampoline {
            type Fn2 = unsafe extern "system" fn(usize, usize) -> i32;
            let f: Fn2 = unsafe { tramp.as_fn_ptr() };
            unsafe { f(arg1, arg2) }
        } else {
            unsafe { self.call2_direct(arg1, arg2) }
        }
    }

    /// invoke spoofed syscall with 3 arguments
    ///
    /// # Safety
    /// caller must ensure args are valid for this syscall
    #[inline(never)]
    pub unsafe fn call3(&self, arg1: usize, arg2: usize, arg3: usize) -> i32 {
        if let Some(ref tramp) = self.trampoline {
            type Fn3 = unsafe extern "system" fn(usize, usize, usize) -> i32;
            let f: Fn3 = unsafe { tramp.as_fn_ptr() };
            unsafe { f(arg1, arg2, arg3) }
        } else {
            unsafe { self.call3_direct(arg1, arg2, arg3) }
        }
    }

    /// invoke spoofed syscall with 4 arguments
    ///
    /// # Safety
    /// caller must ensure args are valid for this syscall
    #[inline(never)]
    pub unsafe fn call4(&self, arg1: usize, arg2: usize, arg3: usize, arg4: usize) -> i32 {
        if let Some(ref tramp) = self.trampoline {
            type Fn4 = unsafe extern "system" fn(usize, usize, usize, usize) -> i32;
            let f: Fn4 = unsafe { tramp.as_fn_ptr() };
            unsafe { f(arg1, arg2, arg3, arg4) }
        } else {
            unsafe { self.call4_direct(arg1, arg2, arg3, arg4) }
        }
    }

    /// invoke spoofed syscall with 5 arguments
    ///
    /// # Safety
    /// caller must ensure args are valid for this syscall
    #[inline(never)]
    pub unsafe fn call5(
        &self,
        arg1: usize,
        arg2: usize,
        arg3: usize,
        arg4: usize,
        arg5: usize,
    ) -> i32 {
        if let Some(ref tramp) = self.trampoline {
            type Fn5 = unsafe extern "system" fn(usize, usize, usize, usize, usize) -> i32;
            let f: Fn5 = unsafe { tramp.as_fn_ptr() };
            unsafe { f(arg1, arg2, arg3, arg4, arg5) }
        } else {
            unsafe { self.call5_direct(arg1, arg2, arg3, arg4, arg5) }
        }
    }

    /// invoke spoofed syscall with 6 arguments
    ///
    /// # Safety
    /// caller must ensure args are valid for this syscall
    #[inline(never)]
    pub unsafe fn call6(
        &self,
        arg1: usize,
        arg2: usize,
        arg3: usize,
        arg4: usize,
        arg5: usize,
        arg6: usize,
    ) -> i32 {
        if let Some(ref tramp) = self.trampoline {
            type Fn6 = unsafe extern "system" fn(usize, usize, usize, usize, usize, usize) -> i32;
            let f: Fn6 = unsafe { tramp.as_fn_ptr() };
            unsafe { f(arg1, arg2, arg3, arg4, arg5, arg6) }
        } else {
            unsafe { self.call6_direct(arg1, arg2, arg3, arg4, arg5, arg6) }
        }
    }

    /// invoke with variable arguments
    ///
    /// # Safety
    /// caller must ensure args are valid for this syscall
    #[inline(never)]
    pub unsafe fn call_many(&self, args: &[usize]) -> i32 {
        match args.len() {
            0 => unsafe { self.call0() },
            1 => unsafe { self.call1(args[0]) },
            2 => unsafe { self.call2(args[0], args[1]) },
            3 => unsafe { self.call3(args[0], args[1], args[2]) },
            4 => unsafe { self.call4(args[0], args[1], args[2], args[3]) },
            5 => unsafe { self.call5(args[0], args[1], args[2], args[3], args[4]) },
            6 => unsafe { self.call6(args[0], args[1], args[2], args[3], args[4], args[5]) },
            _ => unsafe { self.call6(args[0], args[1], args[2], args[3], args[4], args[5]) },
        }
    }

    // direct fallback implementations (non-spoofed)
    #[inline(never)]
    unsafe fn call0_direct(&self) -> i32 {
        let status: i32;
        unsafe {
            asm!(
                "sub rsp, 0x28",
                "mov r10, rcx",
                "mov eax, {ssn:e}",
                "call {addr}",
                "add rsp, 0x28",
                ssn = in(reg) self.ssn as u32,
                addr = in(reg) self.syscall_addr,
                out("eax") status,
                out("rcx") _,
                out("r10") _,
                out("r11") _,
            );
        }
        status
    }

    #[inline(never)]
    unsafe fn call1_direct(&self, arg1: usize) -> i32 {
        let status: i32;
        unsafe {
            asm!(
                "sub rsp, 0x28",
                "mov r10, rcx",
                "mov eax, {ssn:e}",
                "call {addr}",
                "add rsp, 0x28",
                ssn = in(reg) self.ssn as u32,
                addr = in(reg) self.syscall_addr,
                in("rcx") arg1,
                out("eax") status,
                out("r10") _,
                out("r11") _,
            );
        }
        status
    }

    #[inline(never)]
    unsafe fn call2_direct(&self, arg1: usize, arg2: usize) -> i32 {
        let status: i32;
        unsafe {
            asm!(
                "sub rsp, 0x28",
                "mov r10, rcx",
                "mov eax, {ssn:e}",
                "call {addr}",
                "add rsp, 0x28",
                ssn = in(reg) self.ssn as u32,
                addr = in(reg) self.syscall_addr,
                in("rcx") arg1,
                in("rdx") arg2,
                out("eax") status,
                out("r10") _,
                out("r11") _,
            );
        }
        status
    }

    #[inline(never)]
    unsafe fn call3_direct(&self, arg1: usize, arg2: usize, arg3: usize) -> i32 {
        let status: i32;
        unsafe {
            asm!(
                "sub rsp, 0x28",
                "mov r10, rcx",
                "mov eax, {ssn:e}",
                "call {addr}",
                "add rsp, 0x28",
                ssn = in(reg) self.ssn as u32,
                addr = in(reg) self.syscall_addr,
                in("rcx") arg1,
                in("rdx") arg2,
                in("r8") arg3,
                out("eax") status,
                out("r10") _,
                out("r11") _,
            );
        }
        status
    }

    #[inline(never)]
    unsafe fn call4_direct(&self, arg1: usize, arg2: usize, arg3: usize, arg4: usize) -> i32 {
        let status: i32;
        unsafe {
            asm!(
                "sub rsp, 0x28",
                "mov r10, rcx",
                "mov eax, {ssn:e}",
                "call {addr}",
                "add rsp, 0x28",
                ssn = in(reg) self.ssn as u32,
                addr = in(reg) self.syscall_addr,
                in("rcx") arg1,
                in("rdx") arg2,
                in("r8") arg3,
                in("r9") arg4,
                out("eax") status,
                out("r10") _,
                out("r11") _,
            );
        }
        status
    }

    #[inline(never)]
    unsafe fn call5_direct(
        &self,
        arg1: usize,
        arg2: usize,
        arg3: usize,
        arg4: usize,
        arg5: usize,
    ) -> i32 {
        let status: i32;
        unsafe {
            asm!(
                "sub rsp, 0x28",
                "mov [rsp+0x20], {arg5}",
                "mov r10, rcx",
                "mov eax, {ssn:e}",
                "call {addr}",
                "add rsp, 0x28",
                ssn = in(reg) self.ssn as u32,
                addr = in(reg) self.syscall_addr,
                arg5 = in(reg) arg5,
                in("rcx") arg1,
                in("rdx") arg2,
                in("r8") arg3,
                in("r9") arg4,
                out("eax") status,
                out("r10") _,
                out("r11") _,
            );
        }
        status
    }

    #[inline(never)]
    unsafe fn call6_direct(
        &self,
        arg1: usize,
        arg2: usize,
        arg3: usize,
        arg4: usize,
        arg5: usize,
        arg6: usize,
    ) -> i32 {
        let status: i32;
        unsafe {
            asm!(
                "sub rsp, 0x30",
                "mov [rsp+0x20], {arg5}",
                "mov [rsp+0x28], {arg6}",
                "mov r10, rcx",
                "mov eax, {ssn:e}",
                "call {addr}",
                "add rsp, 0x30",
                ssn = in(reg) self.ssn as u32,
                addr = in(reg) self.syscall_addr,
                arg5 = in(reg) arg5,
                arg6 = in(reg) arg6,
                in("rcx") arg1,
                in("rdx") arg2,
                in("r8") arg3,
                in("r9") arg4,
                out("eax") status,
                out("r10") _,
                out("r11") _,
            );
        }
        status
    }
}

// x86 implementation (32-bit)
#[cfg(target_arch = "x86")]
impl SpoofedSyscall {
    /// invoke spoofed syscall (x86)
    ///
    /// # Safety
    /// caller must ensure args are valid for this syscall
    #[inline(never)]
    pub unsafe fn call(&self, args: &[usize]) -> i32 {
        // x86 spoofing is simpler - just manipulate the stack
        let status: i32;
        let args_ptr = args.as_ptr();

        unsafe {
            asm!(
                "mov eax, {ssn:e}",
                "mov edx, {args}",
                "call {addr}",
                ssn = in(reg) self.ssn as u32,
                args = in(reg) args_ptr,
                addr = in(reg) self.syscall_addr,
                out("eax") status,
                options(nostack)
            );
        }
        status
    }

    pub unsafe fn call0(&self) -> i32 {
        unsafe { self.call(&[]) }
    }

    pub unsafe fn call1(&self, arg1: usize) -> i32 {
        unsafe { self.call(&[arg1]) }
    }

    pub unsafe fn call2(&self, arg1: usize, arg2: usize) -> i32 {
        unsafe { self.call(&[arg1, arg2]) }
    }

    pub unsafe fn call3(&self, arg1: usize, arg2: usize, arg3: usize) -> i32 {
        unsafe { self.call(&[arg1, arg2, arg3]) }
    }

    pub unsafe fn call4(&self, arg1: usize, arg2: usize, arg3: usize, arg4: usize) -> i32 {
        unsafe { self.call(&[arg1, arg2, arg3, arg4]) }
    }

    pub unsafe fn call5(
        &self,
        arg1: usize,
        arg2: usize,
        arg3: usize,
        arg4: usize,
        arg5: usize,
    ) -> i32 {
        unsafe { self.call(&[arg1, arg2, arg3, arg4, arg5]) }
    }

    pub unsafe fn call6(
        &self,
        arg1: usize,
        arg2: usize,
        arg3: usize,
        arg4: usize,
        arg5: usize,
        arg6: usize,
    ) -> i32 {
        unsafe { self.call(&[arg1, arg2, arg3, arg4, arg5, arg6]) }
    }

    pub unsafe fn call_many(&self, args: &[usize]) -> i32 {
        unsafe { self.call(args) }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_spoofed_syscall_creation() {
        match SpoofedSyscall::new("NtClose") {
            Ok(syscall) => {
                assert!(syscall.ssn() > 0);
                assert!(syscall.gadget_addr().is_some());
            }
            Err(_) => {
                // might fail in some test environments
            }
        }
    }

    #[test]
    fn test_spoofed_syscall_ntclose() {
        if let Ok(syscall) = SpoofedSyscall::new("NtClose") {
            // call with invalid handle - should fail but not crash
            let status = unsafe { syscall.call1(0xDEADBEEF) };
            assert_eq!(
                status, 0xC0000008_u32 as i32,
                "should return STATUS_INVALID_HANDLE"
            );
        }
    }

    #[test]
    fn test_simple_spoof_mode() {
        if let Ok(syscall) = SpoofedSyscall::with_config("NtClose", SpoofConfig {
            mode: SpoofMode::SimpleSpoof,
            custom_spoof_addr: Some(0x7FFE0000), // arbitrary address
            ..Default::default()
        }) {
            let status = unsafe { syscall.call1(0xDEADBEEF) };
            assert_eq!(status, 0xC0000008_u32 as i32);
        }
    }

    #[test]
    fn test_none_mode_fallback() {
        if let Ok(syscall) = SpoofedSyscall::with_config("NtClose", SpoofConfig {
            mode: SpoofMode::None,
            ..Default::default()
        }) {
            let status = unsafe { syscall.call1(0xDEADBEEF) };
            assert_eq!(status, 0xC0000008_u32 as i32);
        }
    }
}