windows_recipe_writefile/
windows-recipe-writefile.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
//! # [`recipe!`] example
//!
//! This example demonstrates how to write a recipe with multiple steps.
//!
//! The recipe is injected into the `explorer.exe` process and writes
//! a file to the guest.
//!
//! # Possible log output
//!
//! ```text
//! DEBUG found MZ base_address=0xfffff80002861000
//!  INFO profile already exists profile_path="cache/windows/ntkrnlmp.pdb/3844dbb920174967be7aa4a2c20430fa2/profile.json"
//!  INFO Creating VMI session
//!  INFO found explorer.exe pid=1248 object=0xfffffa80030e9060
//! DEBUG injector{vcpu=0 rip=0x0000000077c62c1a}:memory_access: thread hijacked current_tid=1932
//! DEBUG injector{vcpu=0 rip=0x0000000077c62c1a}:memory_access: recipe step index=0
//!  INFO injector{vcpu=0 rip=0x0000000077c62c1a}:memory_access: step 1: kernel32!CreateFileA() target_path="C:\\Users\\John\\Desktop\\test.txt"
//! DEBUG injector{vcpu=0 rip=0x0000000077c62c1a}:memory_access: recipe step index=1
//!  INFO injector{vcpu=0 rip=0x0000000077c62c1a}:memory_access: step 2: kernel32!WriteFile() handle=0x0000000000000000
//! DEBUG injector{vcpu=0 rip=0x0000000077c62c1a}:memory_access: recipe step index=2
//!  INFO injector{vcpu=0 rip=0x0000000077c62c1a}:memory_access: step 3: kernel32!WriteFile() number_of_bytes_written=13
//!  INFO injector{vcpu=0 rip=0x0000000077c62c1a}:memory_access: step 3: kernel32!CloseHandle() handle=0x0000000000000e08
//! DEBUG injector{vcpu=0 rip=0x0000000077c62c1a}:memory_access: recipe finished result=0x0000000000000001
//! ```

mod _common;

use vmi::{
    arch::amd64::Amd64,
    os::windows::WindowsOs,
    utils::injector::{recipe, InjectorHandler, Recipe, RecipeControlFlow},
    Hex, Va, VcpuId, VmiDriver,
};

#[derive(Debug, Default)]
struct GuestFile {
    /// Target path in the guest to write the file.
    target_path: String,

    /// Content to write to the file.
    content: Vec<u8>,

    /// Handle to the file.
    /// Assigned in 2nd step.
    handle: u64,

    /// The number of bytes written to the file.
    /// Assigned in 2nd step and used in 3rd step.
    bytes_written_ptr: Va,
}

impl GuestFile {
    pub fn new(target_path: impl AsRef<str>, content: impl AsRef<[u8]>) -> Self {
        Self {
            target_path: target_path.as_ref().to_string(),
            content: content.as_ref().to_vec(),

            // Mutable fields.
            handle: 0,
            bytes_written_ptr: Va::default(),
        }
    }
}

/// Create a recipe to write a file to the guest.
///
/// # Equivalent C pseudo-code
///
/// ```c
/// const char* target_path = "...\\test.txt";
/// const char content[] = "...";
///
/// HANDLE handle = CreateFileA(target_path,            // lpFileName
///                             GENERIC_WRITE,          // dwDesiredAccess
///                             0,                      // dwShareMode
///                             NULL,                   // lpSecurityAttributes
///                             CREATE_ALWAYS,          // dwCreationDisposition
///                             FILE_ATTRIBUTE_NORMAL,  // dwFlagsAndAttributes
///                             NULL);                  // hTemplateFile
///
/// if (handle == INVALID_HANDLE_VALUE) {
///     printf("kernel32!CreateFileA() failed\n");
///     return;
/// }
///
/// DWORD bytes_written;
/// if (!WriteFile(handle, content, sizeof(content), &bytes_written, 0)) {
///     printf("kernel32!WriteFile() failed\n");
/// }
///
/// CloseHandle(handle);
/// ```
fn recipe_factory<Driver>(data: GuestFile) -> Recipe<Driver, WindowsOs<Driver>, GuestFile>
where
    Driver: VmiDriver<Architecture = Amd64>,
{
    recipe![
        Recipe::<_, WindowsOs<Driver>, _>::new(data),
        //
        // Step 1:
        // - Create a file
        //
        {
            tracing::info!(
                target_path = data![target_path],
                "step 1: kernel32!CreateFileA()"
            );

            const GENERIC_WRITE: u64 = 0x40000000;
            const CREATE_ALWAYS: u64 = 2;
            const FILE_ATTRIBUTE_NORMAL: u64 = 0x80;

            inj! {
                kernel32!CreateFileA(
                    &data![target_path],        // lpFileName
                    GENERIC_WRITE,              // dwDesiredAccess
                    0,                          // dwShareMode
                    0,                          // lpSecurityAttributes
                    CREATE_ALWAYS,              // dwCreationDisposition
                    FILE_ATTRIBUTE_NORMAL,      // dwFlagsAndAttributes
                    0                           // hTemplateFile
                )
            }
        },
        //
        // Step 2:
        // - Verify the file handle
        // - Write the content to the file
        //
        {
            let return_value = registers!().rax;

            const INVALID_HANDLE_VALUE: u64 = 0xffff_ffff_ffff_ffff;

            if return_value == INVALID_HANDLE_VALUE {
                tracing::error!(
                    return_value = %Hex(return_value),
                    "step 2: kernel32!CreateFileA() failed"
                );

                return Ok(RecipeControlFlow::Break);
            }

            tracing::info!(
                handle = %Hex(data![handle]),
                "step 2: kernel32!WriteFile()"
            );

            // Save the handle.
            data![handle] = return_value;

            // Allocate a value on the stack to store the output parameter.
            data![bytes_written_ptr] = copy_to_stack!(0u64)?;

            inj! {
                kernel32!WriteFile(
                    data![handle],              // hFile
                    data![content],             // lpBuffer
                    data![content].len(),       // nNumberOfBytesToWrite
                    data![bytes_written_ptr],   // lpNumberOfBytesWritten
                    0                           // lpOverlapped
                )
            }
        },
        //
        // Step 3:
        // - Verify that the `WriteFile()` call succeeded
        // - Close the file handle
        //
        {
            let return_value = registers!().rax;

            // Check if the `WriteFile()` call failed.
            if return_value == 0 {
                tracing::error!(
                    return_value = %Hex(return_value),
                    "step 3: kernel32!WriteFile() failed"
                );

                // Don't exit, we want to close the handle.
                // return Ok(RecipeControlFlow::Break);
            }

            // Read the number of bytes written.
            let number_of_bytes_written = vmi!().read_u32(data![bytes_written_ptr])?;
            tracing::info!(number_of_bytes_written, "step 3: kernel32!WriteFile()");

            tracing::info!(
                handle = %Hex(data![handle]),
                "step 3: kernel32!CloseHandle()"
            );

            inj! {
                kernel32!CloseHandle(
                    data![handle]               // hObject
                )
            }
        },
    ]
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let (vmi, profile) = _common::create_vmi_session()?;

    let processes = {
        let _pause_guard = vmi.pause_guard()?;

        let registers = vmi.registers(VcpuId(0))?;
        vmi.os().processes(&registers)?
    };

    let explorer = processes
        .iter()
        .find(|process| process.name.to_lowercase() == "explorer.exe")
        .expect("explorer.exe");

    tracing::info!(
        pid = %explorer.id,
        object = %explorer.object,
        "found explorer.exe"
    );

    vmi.handle(|vmi| {
        InjectorHandler::new(
            vmi,
            &profile,
            explorer.id,
            recipe_factory(GuestFile::new(
                "C:\\Users\\John\\Desktop\\test.txt",
                "Hello, World!".as_bytes(),
            )),
        )
    })?;

    Ok(())
}