uniject 0.3.0

Inject and invoke .NET assemblies in Mono-embedded Windows processes
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
use std::collections::HashMap;
use std::num::NonZeroUsize;
use std::os::windows::io::{AsHandle, AsRawHandle, FromRawHandle, OwnedHandle};

use windows_sys::Win32::Foundation::{HANDLE, INVALID_HANDLE_VALUE, WAIT_FAILED};
use windows_sys::Win32::System::Diagnostics::Debug::FlushInstructionCache;
use windows_sys::Win32::System::Threading::{
    CreateRemoteThread, IsWow64Process, OpenProcess, PROCESS_ALL_ACCESS, WaitForSingleObject,
};
use windows_sys::core::BOOL;

use crate::assembler::Assembler;
use crate::error::{Error, Result};
use crate::memory::{Memory, checked_add, checked_mul};
use crate::process::get_mono_module;

macro_rules! mono_exports {
    ($($constant:ident = $symbol:literal),+ $(,)?) => {
        $(const $constant: &'static str = $symbol;)+

        const REQUIRED_MONO_EXPORTS: &'static [&'static str] = &[
            $(Self::$constant),+
        ];
    };
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum MonoImageOpenStatus {
    Ok,
    ErrorErrno,
    MissingAssemblyRef,
    Invalid,
}

impl From<i32> for MonoImageOpenStatus {
    fn from(value: i32) -> Self {
        match value {
            0 => MonoImageOpenStatus::Ok,
            1 => MonoImageOpenStatus::ErrorErrno,
            2 => MonoImageOpenStatus::MissingAssemblyRef,
            _ => MonoImageOpenStatus::Invalid,
        }
    }
}

/// An injector connected to one Mono-embedded target process.
///
/// The process handle and all remote allocations created by this value remain owned until the
/// injector is dropped.
pub struct Injector {
    memory: Memory<OwnedHandle>,
    exports: HashMap<&'static str, NonZeroUsize>,
    root_domain: Option<NonZeroUsize>,
    attach: bool,
    mono_module: NonZeroUsize,
    is_64_bit: bool,
    return_value_ptr: NonZeroUsize,
    code_buffer: Option<(NonZeroUsize, NonZeroUsize)>,
}

impl Injector {
    const MIN_CODE_BUFFER_CAPACITY: usize = 256;
    mono_exports! {
        MONO_GET_ROOT_DOMAIN = "mono_get_root_domain",
        MONO_THREAD_ATTACH = "mono_thread_attach",
        MONO_IMAGE_OPEN_FROM_DATA = "mono_image_open_from_data",
        MONO_ASSEMBLY_LOAD_FROM_FULL = "mono_assembly_load_from_full",
        MONO_ASSEMBLY_GET_IMAGE = "mono_assembly_get_image",
        MONO_CLASS_FROM_NAME = "mono_class_from_name",
        MONO_CLASS_GET_METHOD_FROM_NAME = "mono_class_get_method_from_name",
        MONO_RUNTIME_INVOKE = "mono_runtime_invoke",
        MONO_ASSEMBLY_CLOSE = "mono_assembly_close",
        MONO_IMAGE_STRERROR = "mono_image_strerror",
        MONO_OBJECT_GET_CLASS = "mono_object_get_class",
        MONO_CLASS_GET_NAME = "mono_class_get_name",
    }

    /// Opens `process_id`, locates its Mono module, and resolves the APIs required for injection.
    pub fn new(process_id: u32) -> Result<Self> {
        let raw_handle = unsafe { OpenProcess(PROCESS_ALL_ACCESS, 0, process_id) };

        if raw_handle.is_null() || raw_handle == INVALID_HANDLE_VALUE {
            return Err(Error::Windows {
                operation: "failed to open process",
                source: std::io::Error::last_os_error(),
            });
        }
        // SAFETY: OpenProcess returned a valid, owned handle.
        let handle = unsafe { OwnedHandle::from_raw_handle(raw_handle) };

        let is_64_bit = if cfg!(target_pointer_width = "64") {
            let mut is_wow64 = BOOL::default();
            if unsafe {
                IsWow64Process(handle.as_handle().as_raw_handle() as HANDLE, &mut is_wow64)
            } == 0
            {
                return Err(Error::Windows {
                    operation: "failed to check Wow64 status",
                    source: std::io::Error::last_os_error(),
                });
            }
            is_wow64 == 0
        } else {
            false
        };

        let mono_module =
            get_mono_module(handle.as_handle(), is_64_bit, Self::REQUIRED_MONO_EXPORTS)?
                .ok_or(Error::MonoModuleNotFound)?;

        for &name in Self::REQUIRED_MONO_EXPORTS {
            if !mono_module.exports.contains_key(name) {
                return Err(Error::MissingExport { name, module: mono_module.address });
            }
        }

        let mut memory = Memory::new(handle);
        let return_value_ptr = if is_64_bit {
            memory.allocate_and_write(&0u64.to_le_bytes())?
        } else {
            memory.allocate_and_write(&0u32.to_le_bytes())?
        };

        Ok(Injector {
            memory,
            exports: mono_module.exports,
            root_domain: None,
            attach: false,
            mono_module: mono_module.address,
            is_64_bit,
            return_value_ptr,
            code_buffer: None,
        })
    }

    /// Returns whether the target process uses a 64-bit address space.
    pub fn is_64_bit(&self) -> bool {
        self.is_64_bit
    }

    #[inline]
    fn export(&self, name: &'static str) -> Result<NonZeroUsize> {
        self.exports
            .get(name)
            .copied()
            .ok_or(Error::MissingExport { name, module: self.mono_module })
    }

    /// Loads `raw_assembly` and invokes the named static, parameterless method.
    ///
    /// The returned address identifies the loaded Mono assembly and can later be passed to
    /// [`Self::eject`].
    pub fn inject(
        &mut self,
        raw_assembly: &[u8],
        namespace: &str,
        class_name: &str,
        method_name: &str,
    ) -> Result<NonZeroUsize> {
        if raw_assembly.is_empty() {
            return Err(Error::EmptyRawAssembly);
        }

        if class_name.is_empty() {
            return Err(Error::EmptyClassName);
        }

        if method_name.is_empty() {
            return Err(Error::EmptyMethodName);
        }

        self.ensure_root_domain()?;
        let raw_image = self.open_image_from_data(raw_assembly)?;

        self.attach = true;
        let assembly = self.open_assembly_from_image(raw_image)?;
        self.invoke_assembly_method(assembly, namespace, class_name, method_name)?;

        Ok(assembly)
    }

    /// Invokes the named static, parameterless unload method and closes `assembly`.
    ///
    /// `assembly` must be an address previously returned by [`Self::inject`] for this target
    /// process.
    pub fn eject(
        &mut self,
        assembly: NonZeroUsize,
        namespace: &str,
        class_name: &str,
        method_name: &str,
    ) -> Result<()> {
        if class_name.is_empty() {
            return Err(Error::EmptyClassName);
        }

        if method_name.is_empty() {
            return Err(Error::EmptyMethodName);
        }

        self.ensure_root_domain()?;
        self.attach = true;

        self.invoke_assembly_method(assembly, namespace, class_name, method_name)?;
        let address = self.export(Self::MONO_ASSEMBLY_CLOSE)?;
        self.execute(address, &[assembly.get()])?;

        Ok(())
    }

    fn invoke_assembly_method(
        &mut self,
        assembly: NonZeroUsize,
        namespace: &str,
        class_name: &str,
        method_name: &str,
    ) -> Result<()> {
        let image = self.get_image_from_assembly(assembly)?;
        let class = self.get_class_from_name(image, namespace, class_name)?;
        let method = self.get_method_from_name(class, method_name)?;
        self.runtime_invoke(method)
    }

    fn ensure_root_domain(&mut self) -> Result<()> {
        if self.root_domain.is_some() {
            return Ok(());
        }

        let address = self.export(Self::MONO_GET_ROOT_DOMAIN)?;
        let root_domain = self.execute(address, &[])?;
        self.root_domain = Some(
            NonZeroUsize::new(root_domain).ok_or(Error::NullReturn(Self::MONO_GET_ROOT_DOMAIN))?,
        );
        Ok(())
    }

    fn open_image_from_data(&mut self, assembly: &[u8]) -> Result<NonZeroUsize> {
        //allocate space for pointer
        let status_ptr = self.memory.allocate_and_write(&0i32.to_le_bytes())?;

        let assembly_data_ptr = self.memory.allocate_and_write(assembly)?;

        //fetch
        let mono_image_open_from_data_address = self.export(Self::MONO_IMAGE_OPEN_FROM_DATA)?;

        //execute with pre alloc
        let raw_image = self.execute(
            mono_image_open_from_data_address,
            &[assembly_data_ptr.get(), assembly.len(), 1, status_ptr.get()],
        )?;

        self.check_image_status(status_ptr, Self::MONO_IMAGE_OPEN_FROM_DATA)?;

        NonZeroUsize::new(raw_image).ok_or(Error::NullReturn(Self::MONO_IMAGE_OPEN_FROM_DATA))
    }

    fn open_assembly_from_image(&mut self, image: NonZeroUsize) -> Result<NonZeroUsize> {
        let status_ptr = self.memory.allocate_and_write(&0i32.to_le_bytes())?;
        let empty_array_ptr = self.memory.allocate_and_write(&[0u8])?;

        let address = self.export(Self::MONO_ASSEMBLY_LOAD_FROM_FULL)?;
        let assembly =
            self.execute(address, &[image.get(), empty_array_ptr.get(), status_ptr.get(), 0])?;

        self.check_image_status(status_ptr, Self::MONO_ASSEMBLY_LOAD_FROM_FULL)?;

        NonZeroUsize::new(assembly).ok_or(Error::NullReturn(Self::MONO_ASSEMBLY_LOAD_FROM_FULL))
    }

    fn check_image_status(
        &mut self,
        status_ptr: NonZeroUsize,
        operation: &'static str,
    ) -> Result<()> {
        let status = MonoImageOpenStatus::from(self.memory.read_int(status_ptr)?);
        if status == MonoImageOpenStatus::Ok {
            return Ok(());
        }

        let address = self.export(Self::MONO_IMAGE_STRERROR)?;
        let message_ptr = self.execute(address, &[status as usize])?;
        let message_ptr =
            NonZeroUsize::new(message_ptr).ok_or(Error::NullReturn(Self::MONO_IMAGE_STRERROR))?;
        let message = self.memory.read_string(message_ptr, 256)?;

        Err(Error::MonoOperation { operation, message })
    }

    fn get_image_from_assembly(&mut self, assembly: NonZeroUsize) -> Result<NonZeroUsize> {
        let address = self.export(Self::MONO_ASSEMBLY_GET_IMAGE)?;
        let image = self.execute(address, &[assembly.get()])?;
        NonZeroUsize::new(image).ok_or(Error::NullReturn(Self::MONO_ASSEMBLY_GET_IMAGE))
    }

    fn get_class_from_name(
        &mut self,
        image: NonZeroUsize,
        namespace: &str,
        class_name: &str,
    ) -> Result<NonZeroUsize> {
        let namespace_ptr = self.memory.allocate_and_write(namespace.as_bytes())?;
        let class_name_ptr = self.memory.allocate_and_write(class_name.as_bytes())?;

        let address = self.export(Self::MONO_CLASS_FROM_NAME)?;
        let class =
            self.execute(address, &[image.get(), namespace_ptr.get(), class_name_ptr.get()])?;
        NonZeroUsize::new(class).ok_or(Error::NullReturn(Self::MONO_CLASS_FROM_NAME))
    }

    fn get_method_from_name(
        &mut self,
        class: NonZeroUsize,
        method_name: &str,
    ) -> Result<NonZeroUsize> {
        let method_name_ptr = self.memory.allocate_and_write(method_name.as_bytes())?;

        let address = self.export(Self::MONO_CLASS_GET_METHOD_FROM_NAME)?;
        let method = self.execute(address, &[class.get(), method_name_ptr.get(), 0])?;
        NonZeroUsize::new(method).ok_or(Error::NullReturn(Self::MONO_CLASS_GET_METHOD_FROM_NAME))
    }

    fn get_class_name(&mut self, mono_object: NonZeroUsize) -> Result<String> {
        let address = self.export(Self::MONO_OBJECT_GET_CLASS)?;
        let class_address = self.execute(address, &[mono_object.get()])?;
        let class_address = NonZeroUsize::new(class_address)
            .ok_or(Error::NullReturn(Self::MONO_OBJECT_GET_CLASS))?;

        let address = self.export(Self::MONO_CLASS_GET_NAME)?;
        let class_name_address = self.execute(address, &[class_address.get()])?;
        let class_name_address = NonZeroUsize::new(class_name_address)
            .ok_or(Error::NullReturn(Self::MONO_CLASS_GET_NAME))?;

        self.memory.read_string(class_name_address, 256)
    }

    fn read_mono_string(&self, mono_string: NonZeroUsize) -> Result<String> {
        let offset = if self.is_64_bit { 0x10 } else { 0x8 };
        let len_address = checked_add(mono_string, offset)?;
        let Some(len) = NonZeroUsize::new(usize::try_from(self.memory.read_int(len_address)?)?)
        else {
            return Ok(String::new());
        };

        let offset_str = if self.is_64_bit { 0x14 } else { 0xC };
        let string_address = checked_add(mono_string, offset_str)?;
        let byte_len =
            NonZeroUsize::new(checked_mul(len.get(), 2)?).ok_or(Error::ArithmeticOverflow)?;
        let bytes = self.memory.read_bytes(string_address, byte_len)?;
        let utf16_units: Vec<u16> =
            bytes.chunks_exact(2).map(|chunk| u16::from_le_bytes([chunk[0], chunk[1]])).collect();
        Ok(String::from_utf16(&utf16_units)?)
    }

    fn runtime_invoke(&mut self, method: NonZeroUsize) -> Result<()> {
        let exc_ptr = if self.is_64_bit {
            self.memory.allocate_and_write(&0u64.to_le_bytes())?
        } else {
            self.memory.allocate_and_write(&0u32.to_le_bytes())?
        };

        //res
        let address = self.export(Self::MONO_RUNTIME_INVOKE)?;
        self.execute(address, &[method.get(), 0, 0, exc_ptr.get()])?;

        let exc = self.memory.read_pointer(exc_ptr, self.is_64_bit)?;
        if let Some(exc) = NonZeroUsize::new(exc) {
            let class_name = self.get_class_name(exc)?;
            let message_address = checked_add(exc, if self.is_64_bit { 0x20 } else { 0x10 })?;
            let message = self.read_mono_string(message_address)?;
            return Err(Error::ManagedException { class_name, message });
        }

        Ok(())
    }

    fn execute(&mut self, address: NonZeroUsize, args: &[usize]) -> Result<usize> {
        if self.is_64_bit {
            self.memory.write(self.return_value_ptr, &0u64.to_le_bytes())?;
        } else {
            self.memory.write(self.return_value_ptr, &0u32.to_le_bytes())?;
        }

        let code = if self.is_64_bit {
            self.assemble_64(address, self.return_value_ptr, args)?
        } else {
            self.assemble_86(address, self.return_value_ptr, args)?
        };
        let code_buffer = match self.code_buffer {
            Some((address, capacity)) if code.len() <= capacity.get() => address,
            _ => {
                let capacity = code.len().max(Self::MIN_CODE_BUFFER_CAPACITY);
                let size = NonZeroUsize::new(capacity)
                    .expect("minimum code buffer capacity must be non-zero");
                let address = self.memory.allocate(size)?;
                self.code_buffer = Some((address, size));
                address
            }
        };
        self.memory.write(code_buffer, &code)?;
        if unsafe {
            FlushInstructionCache(
                self.memory.as_handle().as_raw_handle() as HANDLE,
                code_buffer.get() as *const std::ffi::c_void,
                code.len(),
            )
        } == 0
        {
            return Err(Error::Windows {
                operation: "failed to flush process instruction cache",
                source: std::io::Error::last_os_error(),
            });
        }

        let mut thread_id: u32 = 0;
        let thread = unsafe {
            CreateRemoteThread(
                self.memory.as_handle().as_raw_handle() as HANDLE,
                std::ptr::null(),
                0,
                Some(std::mem::transmute::<
                    usize,
                    unsafe extern "system" fn(*mut std::ffi::c_void) -> u32,
                >(code_buffer.get())),
                std::ptr::null(),
                0,
                &mut thread_id,
            )
        };

        if thread.is_null() || thread == INVALID_HANDLE_VALUE {
            return Err(Error::Windows {
                operation: "failed to create a remote thread",
                source: std::io::Error::last_os_error(),
            });
        }

        // SAFETY: CreateRemoteThread returned a valid, owned handle.
        let thread = unsafe { OwnedHandle::from_raw_handle(thread) };

        let wait_result =
            unsafe { WaitForSingleObject(thread.as_raw_handle() as HANDLE, u32::MAX) };
        if wait_result == WAIT_FAILED {
            return Err(Error::Windows {
                operation: "failed to wait for a remote thread",
                source: std::io::Error::last_os_error(),
            });
        }

        let ret = self.memory.read_pointer(self.return_value_ptr, self.is_64_bit)?;

        if ret == 0xC0000005 {
            let function_name = self
                .exports
                .iter()
                .find(|(_, export)| **export == address)
                .map(|(name, _)| *name)
                .unwrap_or("unknown function");

            return Err(Error::AccessViolation(function_name));
        }

        Ok(ret)
    }

    fn assemble_86(
        &self,
        function_ptr: NonZeroUsize,
        ret_val_ptr: NonZeroUsize,
        args: &[usize],
    ) -> Result<Vec<u8>> {
        let mut asm = Assembler::new()?;

        if let (true, Some(mono_thread_attach), Some(root_domain)) =
            (self.attach, self.exports.get(Self::MONO_THREAD_ATTACH).copied(), self.root_domain)
        {
            asm.push(root_domain.get() as isize)?;
            asm.mov_eax(mono_thread_attach.get() as isize)?;
            asm.call_eax()?;
            asm.add_esp(4)?;
        }

        for &arg in args.iter().rev() {
            asm.push(arg as isize)?;
        }

        asm.mov_eax(function_ptr.get() as isize)?;
        asm.call_eax()?;
        asm.add_esp(u8::try_from(checked_mul(args.len(), 4)?)?)?;
        asm.mov_eax_to(ret_val_ptr)?;
        asm.return_()?;

        asm.to_byte_array()
    }

    fn assemble_64(
        &self,
        function_ptr: NonZeroUsize,
        ret_val_ptr: NonZeroUsize,
        args: &[usize],
    ) -> Result<Vec<u8>> {
        let mut asm = Assembler::new()?;

        asm.sub_rsp(40)?;

        if let (true, Some(mono_thread_attach), Some(root_domain)) =
            (self.attach, self.exports.get(Self::MONO_THREAD_ATTACH).copied(), self.root_domain)
        {
            asm.mov_rax(mono_thread_attach.get())?;
            asm.mov_rcx(root_domain.get())?;
            asm.call_rax()?;
        }

        asm.mov_rax(function_ptr.get())?;

        for (i, &arg) in args.iter().enumerate() {
            match i {
                0 => asm.mov_rcx(arg)?,
                1 => asm.mov_rdx(arg)?,
                2 => asm.mov_r8(arg)?,
                3 => asm.mov_r9(arg)?,
                _ => break,
            }
        }

        asm.call_rax()?;
        asm.add_rsp(40)?;
        asm.mov_rax_to(ret_val_ptr)?;
        asm.return_()?;

        asm.to_byte_array()
    }
}