vmi_utils/injector/os/
windows.rs

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
use isr_core::Profile;
use isr_macros::{offsets, Field};
use vmi_arch_amd64::{Amd64, ControlRegister, EventMonitor, EventReason, Interrupt, Registers};
use vmi_core::{
    os::ProcessId, Architecture as _, Hex, MemoryAccess, Registers as _, Va, View, VmiContext,
    VmiCore, VmiDriver, VmiError, VmiEventResponse, VmiHandler,
};
use vmi_os_windows::{WindowsOs, WindowsOsExt as _};

use super::{
    super::{arch::ArchAdapter as _, CallBuilder, InjectorHandler, Recipe, RecipeExecutor},
    OsAdapter,
};

// const INVALID_VA: Va = Va(0xffff_ffff_ffff_ffff);
const INVALID_VIEW: View = View(0xffff);
// const INVALID_TID: ThreadId = ThreadId(0xffff_ffff);
// const INVALID_PID: ProcessId = ProcessId(0xffff_ffff);

offsets! {
    #[derive(Debug)]
    pub struct Offsets {
        struct _KTRAP_FRAME {
            Rip: Field,
            Rsp: Field,
        }

        struct _KTHREAD {
            TrapFrame: Field,
        }
    }
}

impl<Driver> OsAdapter<Driver> for WindowsOs<Driver>
where
    Driver: VmiDriver<Architecture = Amd64>,
{
    type Offsets = Offsets;

    fn prepare_function_call(
        &self,
        vmi: &VmiCore<Driver>,
        registers: &mut Registers,
        builder: CallBuilder,
    ) -> Result<(), VmiError> {
        tracing::trace!(
            rsp = %Hex(registers.rsp),
            rip = %Hex(registers.rip),
            "preparing function call"
        );

        let arguments = Amd64::push_arguments(vmi, registers, &builder.arguments)?;

        tracing::trace!(
            rsp = %Hex(registers.rsp),
            "pushed arguments"
        );

        let mut addr = registers.rsp;

        let nb_args = arguments.len();

        // According to Microsoft Doc "Building C/C++ Programs":
        // > The stack will always be maintained 16-byte aligned, except within the
        // > prolog
        // > (for example, after the return address is pushed), and except where
        // > indicated
        // > in Function Types for a certain class of frame functions.
        //
        // Add padding to be aligned to "16+8" boundary.
        //
        // https://www.gamasutra.com/view/news/178446/Indepth_Windows_x64_ABI_Stack_frames.php
        //
        // This padding on the stack only exists if the maximum number of parameters
        // passed to functions is greater than 4 and is an odd number.
        let effective_nb_args = nb_args.max(4) as u64;
        if (addr - effective_nb_args * 0x8 - 0x8) & 0xf != 8 {
            addr -= 0x8;

            tracing::trace!(
                addr = %Hex(addr),
                "aligning stack"
            );
        }

        // http://www.codemachine.com/presentations/GES2010.TRoy.Slides.pdf
        //
        // First 4 parameters to functions are always passed in registers
        // P1=rcx, P2=rdx, P3=r8, P4=r9
        // 5th parameter onwards (if any) passed via the stack

        // write parameters (5th onwards) into guest's stack
        for index in (4..nb_args).rev() {
            addr -= 0x8;
            vmi.write_u64((addr.into(), registers.cr3.into()), arguments[index])?;

            tracing::trace!(
                index,
                value = %Hex(arguments[index]),
                addr = %Hex(addr),
                "argument (stack)"
            );
        }

        // write the first 4 parameters into registers
        if nb_args > 3 {
            registers.r9 = arguments[3];

            tracing::trace!(
                index = 3,
                value = %Hex(arguments[3]),
                "argument"
            );
        }

        if nb_args > 2 {
            registers.r8 = arguments[2];

            tracing::trace!(
                index = 2,
                value = %Hex(arguments[2]),
                "argument"
            );
        }

        if nb_args > 1 {
            registers.rdx = arguments[1];

            tracing::trace!(
                index = 1,
                value = %Hex(arguments[1]),
                "argument"
            );
        }

        if nb_args > 0 {
            registers.rcx = arguments[0];

            tracing::trace!(
                index = 0,
                value = %Hex(arguments[0]),
                "argument"
            );
        }

        // allocate 0x20 "homing space"
        addr -= 0x20;

        // save the return address
        addr -= 0x8;
        vmi.write_u64((addr.into(), registers.cr3.into()), registers.rip)?;

        // grow the stack
        registers.rsp = addr;

        // set the new instruction pointer
        registers.rip = builder.function_address.into();

        tracing::trace!(
            rsp = %Hex(registers.rsp),
            rip = %Hex(registers.rip),
            "finished preparing function call"
        );

        Ok(())
    }
}

#[allow(non_snake_case)]
impl<Driver, T> InjectorHandler<Driver, WindowsOs<Driver>, T>
where
    Driver: VmiDriver<Architecture = Amd64>,
{
    /// Creates a new injector handler.
    pub fn new(
        vmi: &VmiCore<Driver>,
        profile: &Profile,
        pid: ProcessId,
        recipe: Recipe<Driver, WindowsOs<Driver>, T>,
    ) -> Result<Self, VmiError> {
        let offsets = Offsets::new(profile)?;

        let view = vmi.create_view(MemoryAccess::RWX)?;
        vmi.switch_to_view(view)?;
        vmi.monitor_enable(EventMonitor::Register(ControlRegister::Cr3))?;
        vmi.monitor_enable(EventMonitor::Singlestep)?;

        let bridge = recipe.bridge;
        if bridge {
            vmi.monitor_enable(EventMonitor::CpuId)?;
        }

        Ok(Self {
            pid,
            tid: None,
            hijacked: false,
            sp_va: None,
            ip_va: None,
            ip_pa: None,
            offsets,
            recipe: RecipeExecutor::new(recipe),
            view,
            bridge,
            finished: false,
        })
    }

    #[tracing::instrument(
        name = "injector",
        skip_all,
        fields(
            vcpu = %vmi.event().vcpu_id(),
            rip = %Va(vmi.registers().rip),
        )
    )]
    fn dispatch(
        &mut self,
        vmi: &VmiContext<Driver, WindowsOs<Driver>>,
    ) -> Result<VmiEventResponse<Amd64>, VmiError> {
        match vmi.event().reason() {
            EventReason::MemoryAccess(_) => self.on_memory_access(vmi),
            EventReason::WriteControlRegister(_) => {
                let _ = self.on_write_cr(vmi);
                Ok(VmiEventResponse::default())
            }
            EventReason::CpuId(_) => self.on_cpuid(vmi),
            _ => panic!("Unhandled event: {:?}", vmi.event().reason()),
        }
    }

    #[tracing::instrument(name = "cpuid", skip_all)]
    fn on_cpuid(
        &mut self,
        vmi: &VmiContext<Driver, WindowsOs<Driver>>,
    ) -> Result<VmiEventResponse<Amd64>, VmiError> {
        const SYNC_MAGIC_LEAF: u32 = 0x406e7964; // '@nyd'
        const SYNC_MAGIC_RESPONSE: u64 = 0x616e7964; // 'anyd'

        const SYNC_REQUEST_HELLO: u16 = 0x0000;
        const SYNC_REQUEST_STATUS: u16 = 0x8000;
        const SYNC_REQUEST_ERROR: u16 = 0xFFFF;

        const SYNC_LAST_PHASE: u16 = 0xFFFF;

        const SYNC_RESPONSE_WAIT: u64 = 0x00000000;
        const SYNC_RESPONSE_CONTINUE: u64 = 0x00000001;
        const SYNC_RESPONSE_ABORT: u64 = 0xFFFFFFFF;

        let cpuid = vmi.event().reason().as_cpuid();

        let mut registers = vmi.registers().gp_registers();
        registers.rip += cpuid.instruction_length as u64;

        tracing::trace!(
            rip = %Va(registers.rip),
            leaf = %Hex(cpuid.leaf),
            subleaf = %Hex(cpuid.subleaf),
        );

        if cpuid.leaf != SYNC_MAGIC_LEAF {
            // tracing::trace!("not the right leaf");
            return Ok(VmiEventResponse::set_registers(registers));
        }

        let request = (cpuid.subleaf >> 16) as u16;
        let method = (cpuid.subleaf & 0xFFFF) as u16;

        match (request, method) {
            (SYNC_REQUEST_HELLO, _) => {
                tracing::debug!("hello request");
                registers.rax = SYNC_MAGIC_RESPONSE;
            }

            (SYNC_REQUEST_STATUS, SYNC_LAST_PHASE) => {
                tracing::debug!("last phase request");
                registers.rax = SYNC_RESPONSE_WAIT;
                self.finished = true;
            }

            (SYNC_REQUEST_STATUS, phase) => {
                tracing::debug!(phase, "status request");
                registers.rax = SYNC_RESPONSE_CONTINUE;
            }

            (SYNC_REQUEST_ERROR, code) => {
                tracing::error!(code, "error request");
                registers.rax = SYNC_RESPONSE_ABORT;
                self.finished = true;
            }

            _ => {
                tracing::error!(request, method, "unknown request");
                registers.rax = SYNC_RESPONSE_ABORT;
                self.finished = true;
            }
        };

        if self.finished {
            vmi.monitor_disable(EventMonitor::CpuId)?;
        };

        registers.rbx = SYNC_MAGIC_RESPONSE;
        registers.rcx = SYNC_MAGIC_RESPONSE;
        registers.rdx = SYNC_MAGIC_RESPONSE;
        Ok(VmiEventResponse::set_registers(registers))
    }

    #[tracing::instrument(name = "write_cr", skip_all)]
    fn on_write_cr(
        &mut self,
        vmi: &VmiContext<Driver, WindowsOs<Driver>>,
    ) -> Result<VmiEventResponse<Amd64>, VmiError> {
        //
        // Early exit if the thread has already been hijacked.
        // (Besides, in such case, this CR3 monitoring is being disabled anyway.)
        //

        if self.hijacked {
            return Ok(VmiEventResponse::default());
        }

        //
        // Early exit if the current process is not the target process.
        //

        let current_pid = vmi.os().current_process_id()?;
        if current_pid != self.pid {
            return Ok(VmiEventResponse::default());
        }

        //
        // Figure out if the current thread is viable for hijacking.
        // First, fetch the current TID and the next instruction from
        // trap frame of the current thread.
        //

        let current_tid = vmi.os().current_thread_id()?;

        let KTHREAD_TrapFrame = self.offsets._KTHREAD.TrapFrame.offset;
        let KTRAP_FRAME_Rsp = self.offsets._KTRAP_FRAME.Rsp.offset;
        let KTRAP_FRAME_Rip = self.offsets._KTRAP_FRAME.Rip.offset;

        let current_thread = vmi.os().current_thread()?;
        let current_thread = Va::from(current_thread);

        let trap_frame = vmi.read_va(current_thread + KTHREAD_TrapFrame)?;
        let sp_va = vmi.read_va(trap_frame + KTRAP_FRAME_Rsp)?;
        let ip_va = vmi.read_va(trap_frame + KTRAP_FRAME_Rip)?;

        //
        // Verify that the next instruction of this thread is in a user-mode
        // address space.
        //

        if !vmi.os().is_valid_user_address(ip_va)? {
            tracing::trace!(%ip_va, "skipping invalid pc");

            return Ok(VmiEventResponse::default());
        }

        //
        // Translate the instruction pointer to a physical address.
        //

        let ip_pa = match vmi.translate_address(ip_va) {
            Ok(ip_pa) => {
                tracing::trace!(
                    %current_tid,
                    %sp_va,
                    %ip_va,
                    %ip_pa,
                    "trying to hijack thread"
                );

                ip_pa
            }

            Err(err) => {
                tracing::trace!(
                    %current_tid,
                    %sp_va,
                    %ip_va,
                    ip_pa = "error",
                    "trying to hijack thread"
                );

                return Err(err);
            }
        };

        //
        // If we've tried to hijack a thread before, we need to restore the
        // previous memory access permissions.
        //

        if let Some(previous_ip_pa) = self.ip_pa {
            let previous_ip_gfn = Driver::Architecture::gfn_from_pa(previous_ip_pa);
            vmi.set_memory_access(previous_ip_gfn, self.view, MemoryAccess::RWX)?;
        }

        //
        // Set the memory access permissions for the next user-mode instruction.
        // This will unset the eXecute permission for the page containing the
        // next user-mode instruction. This is necessary to trigger a `MemoryAccess`
        // event when the thread resumes execution.
        //

        let ip_gfn = Driver::Architecture::gfn_from_pa(ip_pa);
        vmi.set_memory_access(ip_gfn, self.view, MemoryAccess::RW)?;

        //
        // Mark down the current TID and the VA/PA of the next user-mode instruction.
        // The next `MemoryAccess` handler will try to hijack the thread.
        //

        self.tid = Some(current_tid);
        self.sp_va = Some(sp_va);
        self.ip_va = Some(ip_va);
        self.ip_pa = Some(ip_pa);

        Ok(VmiEventResponse::default())
    }

    #[tracing::instrument(name = "memory_access", skip_all)]
    fn on_memory_access(
        &mut self,
        vmi: &VmiContext<Driver, WindowsOs<Driver>>,
    ) -> Result<VmiEventResponse<Amd64>, VmiError> {
        //
        // Early exit if the memory view is not the target view.
        //

        if vmi.event().view() != Some(self.view) {
            tracing::trace!(
                view = %self.view,
                current_view = %vmi.event().view().unwrap_or(INVALID_VIEW),
                "not the right view"
            );

            return Ok(VmiEventResponse::toggle_fast_singlestep().and_set_view(vmi.default_view()));
        }

        //
        // Early exit if the current process is not the target process.
        // Note that some physical memory pages (especially those containing
        // mapped files, such as DLLs) are shared among multiple processes.
        // Therefore this event might have been triggered by a different process.
        //

        let current_pid = vmi.os().current_process_id()?;
        if current_pid != self.pid {
            // Too noisy...
            // tracing::trace!(
            //     pid = %self.pid,
            //     %current_pid,
            //     "not the right process"
            // );
            return Ok(VmiEventResponse::toggle_fast_singlestep().and_set_view(vmi.default_view()));
        }

        //
        // Early exit if the current thread is not the target thread.
        //

        let current_tid = vmi.os().current_thread_id()?;
        if Some(current_tid) != self.tid {
            // Too noisy...
            // tracing::trace!(
            //     tid = %self.tid.unwrap_or(INVALID_TID),
            //     %current_tid,
            //     "not the right thread"
            // );
            return Ok(VmiEventResponse::toggle_fast_singlestep().and_set_view(vmi.default_view()));
        }

        //
        // Early exit if this instruction pointer is not the one we're looking for.
        //

        let registers = vmi.registers();
        let ip = Va(registers.rip);
        if Some(ip) != self.ip_va {
            //tracing::trace!(
            //    ip = %self.ip_va.unwrap_or(INVALID_VA),
            //    current_ip = %ip,
            //    "not the right instruction pointer"
            //);

            return Ok(VmiEventResponse::toggle_fast_singlestep().and_set_view(vmi.default_view()));
        }

        //
        // Hijack the thread, save the current registers, and disable CR3 monitoring.
        //

        if !self.hijacked {
            tracing::debug!(%current_tid, "thread hijacked");
            self.hijacked = true;

            vmi.monitor_disable(EventMonitor::Register(ControlRegister::Cr3))?;
        }

        let sp = Va(registers.rsp);
        if let Some(sp_va) = self.sp_va {
            if sp_va > sp {
                tracing::trace!(
                    sp = %sp_va,
                    current_sp = %sp,
                    "not the right stack pointer"
                );

                return Ok(
                    VmiEventResponse::toggle_fast_singlestep().and_set_view(vmi.default_view())
                );
            }
        }

        //
        // Execute the next step in the recipe.
        //

        //println!("BEFORE");
        //println!("RIP: 0x{:016X}", registers.rip);
        //println!("RSP: 0x{:016X}", registers.rsp);
        //let _ = hexdump(vmi, (Va(registers.rsp - 0x200), registers.cr3.into()), 0x400, Representation::U64);

        let new_registers = self.recipe.execute(vmi)?;
        self.sp_va = Some(Va(new_registers.rsp));

        //println!("AFTER");
        //println!("RIP: 0x{:016X}", new_registers.rip);
        //println!("RSP: 0x{:016X}", new_registers.rsp);
        //let _ = hexdump(vmi, (Va(registers.rsp - 0x200), registers.cr3.into()), 0x400, Representation::U64);

        if self.recipe.done() {
            //
            // If the recipe is finished, restore the previous memory access permissions,
            // switch back to the default view, disable single-stepping, and restore back
            // the original registers.
            //

            let memory_access = vmi.event().reason().as_memory_access();
            let gfn = Driver::Architecture::gfn_from_pa(memory_access.pa);
            vmi.set_memory_access(gfn, self.view, MemoryAccess::RWX)?;
            vmi.monitor_disable(EventMonitor::Singlestep)?;

            vmi.switch_to_view(vmi.default_view())?;
            vmi.destroy_view(self.view)?;

            // If the bridge was not enabled, we're done.
            if !self.bridge {
                self.finished = true;
            }
        }

        Ok(VmiEventResponse::set_registers(
            new_registers.gp_registers(),
        ))
    }
}

impl<Driver, T> VmiHandler<Driver, WindowsOs<Driver>>
    for InjectorHandler<Driver, WindowsOs<Driver>, T>
where
    Driver: VmiDriver<Architecture = Amd64>,
{
    fn handle_event(
        &mut self,
        vmi: VmiContext<Driver, WindowsOs<Driver>>,
    ) -> VmiEventResponse<Amd64> {
        vmi.flush_v2p_cache();

        match self.dispatch(&vmi) {
            Ok(response) => response,
            Err(VmiError::PageFault(pfs)) => {
                let pf = pfs[0];

                tracing::warn!(?pf, "injecting page fault");
                let _ = vmi
                    .inject_interrupt(vmi.event().vcpu_id(), Interrupt::page_fault(pf.address, 0));

                VmiEventResponse::default()
            }
            Err(err) => panic!("Unhandled error: {err:?}"),
        }
    }

    fn finished(&self) -> bool {
        self.finished
    }
}