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
//! Manual PE mapping - LoadLibrary bypass
//!
//! This module provides a complete PE loader that maps DLLs without using
//! the Windows loader, creating "ghost DLLs" invisible to GetModuleHandle.
//!
//! # Example
//!
//! ```no_run
//! use wraith::manipulation::manual_map::{ManualMapper, map_file};
//!
//! // convenience function for quick mapping
//! let mapper = map_file(r"C:\path\to\module.dll")?;
//! println!("Mapped at {:#x}", mapper.base());
//!
//! // or step-by-step for more control
//! let mapper = ManualMapper::from_file(r"C:\path\to\module.dll")?
//!     .allocate()?
//!     .map_sections()?
//!     .relocate()?
//!     .resolve_imports()?
//!     .process_tls()?
//!     .finalize()?;
//!
//! mapper.call_entry_point()?;
//! # Ok::<(), wraith::WraithError>(())
//! ```

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

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

mod allocator;
mod entry;
mod mapper;
mod parser;
mod relocator;
mod resolver;
mod tls;

pub use allocator::MappedMemory;
pub use entry::reason;
pub use parser::ParsedPe;

use crate::error::{Result, WraithError};
use core::marker::PhantomData;

/// type-state markers for manual mapping stages
pub mod state {
    /// PE has been parsed but no memory allocated
    pub struct Parsed;
    /// Memory has been allocated for the image
    pub struct Allocated;
    /// PE sections have been mapped to memory
    pub struct SectionsMapped;
    /// Base relocations have been applied
    pub struct Relocated;
    /// Import Address Table has been resolved
    pub struct ImportsResolved;
    /// TLS callbacks have been processed
    pub struct TlsProcessed;
    /// Image is ready for execution
    pub struct Ready;
}

/// manual mapper with type-state progression
///
/// the type parameter ensures mapping steps happen in correct order:
/// Parsed -> Allocated -> SectionsMapped -> Relocated -> ImportsResolved -> TlsProcessed -> Ready
pub struct ManualMapper<S> {
    pe: ParsedPe,
    memory: Option<MappedMemory>,
    _state: PhantomData<S>,
}

impl ManualMapper<state::Parsed> {
    /// parse PE from bytes
    pub fn parse(data: &[u8]) -> Result<Self> {
        let pe = ParsedPe::parse(data)?;
        Ok(Self {
            pe,
            memory: None,
            _state: PhantomData,
        })
    }

    /// parse PE from file
    #[cfg(feature = "std")]
    pub fn from_file(path: &str) -> Result<Self> {
        let data = std::fs::read(path).map_err(|e| WraithError::InvalidPeFormat {
            reason: format!("failed to read file: {e}"),
        })?;
        Self::parse(&data)
    }

    /// parse PE from file (no_std stub)
    #[cfg(not(feature = "std"))]
    pub fn from_file(_path: &str) -> Result<Self> {
        Err(WraithError::InvalidPeFormat {
            reason: "file operations not available in no_std".into(),
        })
    }

    /// get reference to parsed PE
    pub fn pe(&self) -> &ParsedPe {
        &self.pe
    }

    /// allocate memory for the PE image
    ///
    /// tries preferred base first, falls back to any available address
    pub fn allocate(self) -> Result<ManualMapper<state::Allocated>> {
        let size = self.pe.size_of_image();
        let preferred_base = self.pe.preferred_base();

        let memory = allocator::allocate_image(size, preferred_base)?;

        Ok(ManualMapper {
            pe: self.pe,
            memory: Some(memory),
            _state: PhantomData,
        })
    }

    /// allocate at specific address
    ///
    /// fails if address is not available
    pub fn allocate_at(self, base: usize) -> Result<ManualMapper<state::Allocated>> {
        let size = self.pe.size_of_image();
        let memory = allocator::allocate_at(base, size)?;

        Ok(ManualMapper {
            pe: self.pe,
            memory: Some(memory),
            _state: PhantomData,
        })
    }

    /// allocate anywhere (no preference)
    pub fn allocate_anywhere(self) -> Result<ManualMapper<state::Allocated>> {
        let size = self.pe.size_of_image();
        let memory = allocator::allocate_anywhere(size)?;

        Ok(ManualMapper {
            pe: self.pe,
            memory: Some(memory),
            _state: PhantomData,
        })
    }
}

impl ManualMapper<state::Allocated> {
    /// get allocated base address
    pub fn base(&self) -> usize {
        self.memory.as_ref().unwrap().base()
    }

    /// get reference to parsed PE
    pub fn pe(&self) -> &ParsedPe {
        &self.pe
    }

    /// map PE sections to allocated memory
    pub fn map_sections(mut self) -> Result<ManualMapper<state::SectionsMapped>> {
        let memory = self.memory.as_mut().unwrap();
        mapper::map_sections(&self.pe, memory)?;

        Ok(ManualMapper {
            pe: self.pe,
            memory: self.memory,
            _state: PhantomData,
        })
    }
}

impl ManualMapper<state::SectionsMapped> {
    /// get base address
    pub fn base(&self) -> usize {
        self.memory.as_ref().unwrap().base()
    }

    /// get reference to parsed PE
    pub fn pe(&self) -> &ParsedPe {
        &self.pe
    }

    /// apply base relocations
    pub fn relocate(mut self) -> Result<ManualMapper<state::Relocated>> {
        let memory = self.memory.as_mut().unwrap();
        let delta = memory.base() as i64 - self.pe.preferred_base() as i64;

        if delta != 0 {
            relocator::apply_relocations(&self.pe, memory, delta)?;
        }

        Ok(ManualMapper {
            pe: self.pe,
            memory: self.memory,
            _state: PhantomData,
        })
    }

    /// skip relocations (use if loaded at preferred base)
    pub fn skip_relocations(self) -> ManualMapper<state::Relocated> {
        ManualMapper {
            pe: self.pe,
            memory: self.memory,
            _state: PhantomData,
        }
    }
}

impl ManualMapper<state::Relocated> {
    /// get base address
    pub fn base(&self) -> usize {
        self.memory.as_ref().unwrap().base()
    }

    /// get reference to parsed PE
    pub fn pe(&self) -> &ParsedPe {
        &self.pe
    }

    /// resolve import address table
    pub fn resolve_imports(mut self) -> Result<ManualMapper<state::ImportsResolved>> {
        let memory = self.memory.as_mut().unwrap();
        resolver::resolve_imports(&self.pe, memory)?;

        Ok(ManualMapper {
            pe: self.pe,
            memory: self.memory,
            _state: PhantomData,
        })
    }

    /// resolve imports with custom resolver function
    pub fn resolve_imports_with<F>(
        mut self,
        resolver_fn: F,
    ) -> Result<ManualMapper<state::ImportsResolved>>
    where
        F: Fn(&str, &str) -> Option<usize>,
    {
        let memory = self.memory.as_mut().unwrap();
        resolver::resolve_imports_custom(&self.pe, memory, resolver_fn)?;

        Ok(ManualMapper {
            pe: self.pe,
            memory: self.memory,
            _state: PhantomData,
        })
    }

    /// skip import resolution (use if PE has no imports or manually resolved)
    pub fn skip_imports(self) -> ManualMapper<state::ImportsResolved> {
        ManualMapper {
            pe: self.pe,
            memory: self.memory,
            _state: PhantomData,
        }
    }
}

impl ManualMapper<state::ImportsResolved> {
    /// get base address
    pub fn base(&self) -> usize {
        self.memory.as_ref().unwrap().base()
    }

    /// get reference to parsed PE
    pub fn pe(&self) -> &ParsedPe {
        &self.pe
    }

    /// process TLS callbacks
    pub fn process_tls(mut self) -> Result<ManualMapper<state::TlsProcessed>> {
        let memory = self.memory.as_mut().unwrap();
        tls::process_tls(&self.pe, memory)?;

        Ok(ManualMapper {
            pe: self.pe,
            memory: self.memory,
            _state: PhantomData,
        })
    }

    /// skip TLS processing
    pub fn skip_tls(self) -> ManualMapper<state::TlsProcessed> {
        ManualMapper {
            pe: self.pe,
            memory: self.memory,
            _state: PhantomData,
        }
    }
}

impl ManualMapper<state::TlsProcessed> {
    /// get base address
    pub fn base(&self) -> usize {
        self.memory.as_ref().unwrap().base()
    }

    /// get reference to parsed PE
    pub fn pe(&self) -> &ParsedPe {
        &self.pe
    }

    /// finalize mapping with proper memory protections
    pub fn finalize(mut self) -> Result<ManualMapper<state::Ready>> {
        let memory = self.memory.as_mut().unwrap();
        mapper::set_section_protections(&self.pe, memory)?;

        Ok(ManualMapper {
            pe: self.pe,
            memory: self.memory,
            _state: PhantomData,
        })
    }

    /// finalize without setting protections (keeps RW everywhere)
    pub fn finalize_without_protections(self) -> ManualMapper<state::Ready> {
        ManualMapper {
            pe: self.pe,
            memory: self.memory,
            _state: PhantomData,
        }
    }
}

impl ManualMapper<state::Ready> {
    /// call DllMain with DLL_PROCESS_ATTACH
    pub fn call_entry_point(&self) -> Result<bool> {
        let memory = self.memory.as_ref().unwrap();
        entry::call_dll_attach(&self.pe, memory)
    }

    /// call DllMain with custom reason
    pub fn call_entry_point_with_reason(&self, call_reason: u32) -> Result<bool> {
        let memory = self.memory.as_ref().unwrap();
        entry::call_entry_point(&self.pe, memory, call_reason)
    }

    /// get export address by name
    pub fn get_export(&self, name: &str) -> Result<usize> {
        let memory = self.memory.as_ref().unwrap();
        resolver::get_mapped_export(&self.pe, memory, name)
    }

    /// get export address by ordinal
    pub fn get_export_by_ordinal(&self, ordinal: u16) -> Result<usize> {
        let memory = self.memory.as_ref().unwrap();
        resolver::get_mapped_export_by_ordinal(&self.pe, memory, ordinal)
    }

    /// get base address of mapped image
    pub fn base(&self) -> usize {
        self.memory.as_ref().unwrap().base()
    }

    /// get size of mapped image
    pub fn size(&self) -> usize {
        self.memory.as_ref().unwrap().size()
    }

    /// get reference to parsed PE
    pub fn pe(&self) -> &ParsedPe {
        &self.pe
    }

    /// consume and return raw memory handle
    pub fn into_memory(mut self) -> MappedMemory {
        self.memory.take().unwrap()
    }

    /// get pointer to specific offset in mapped image
    pub fn ptr_at(&self, offset: usize) -> *mut u8 {
        self.memory.as_ref().unwrap().ptr_at(offset)
    }

    /// unmap and free memory
    pub fn unmap(mut self) -> Result<()> {
        if let Some(memory) = self.memory.take() {
            // call DllMain with DLL_PROCESS_DETACH first (ignore errors)
            let _ = entry::call_dll_detach(&self.pe, &memory);
            memory.free()?;
        }
        Ok(())
    }
}

/// convenience function: map PE from bytes with all default steps
pub fn map_pe(data: &[u8]) -> Result<ManualMapper<state::Ready>> {
    ManualMapper::parse(data)?
        .allocate()?
        .map_sections()?
        .relocate()?
        .resolve_imports()?
        .process_tls()?
        .finalize()
}

/// convenience function: map PE from file with all default steps
pub fn map_file(path: &str) -> Result<ManualMapper<state::Ready>> {
    ManualMapper::from_file(path)?
        .allocate()?
        .map_sections()?
        .relocate()?
        .resolve_imports()?
        .process_tls()?
        .finalize()
}

/// convenience function: map PE from bytes and call entry point
pub fn map_and_call(data: &[u8]) -> Result<ManualMapper<state::Ready>> {
    let mapper = map_pe(data)?;
    mapper.call_entry_point()?;
    Ok(mapper)
}

/// convenience function: map PE from file and call entry point
pub fn map_file_and_call(path: &str) -> Result<ManualMapper<state::Ready>> {
    let mapper = map_file(path)?;
    mapper.call_entry_point()?;
    Ok(mapper)
}

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

    #[test]
    fn test_parse_and_allocate() {
        let exe_path = std::env::current_exe().unwrap();
        let data = std::fs::read(&exe_path).unwrap();

        let mapper = ManualMapper::parse(&data).unwrap();
        assert!(mapper.pe().size_of_image() > 0);

        let mapper = mapper.allocate().unwrap();
        assert!(mapper.base() != 0);
    }

    #[test]
    fn test_map_sections() {
        let exe_path = std::env::current_exe().unwrap();
        let data = std::fs::read(&exe_path).unwrap();

        let mapper = ManualMapper::parse(&data)
            .unwrap()
            .allocate()
            .unwrap()
            .map_sections()
            .unwrap();

        // verify MZ header was copied
        assert!(mapper.base() != 0);
    }

    // note: full integration tests that call entry points should be done
    // with actual test DLLs, not the running executable
}