vmi 0.12.0

A modular and extensible library for Virtual Machine Introspection
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
// Kernel-mode `file-transfer` shellcode.
//
// The shellcode maps a file handle, copies its contents into a shared nonpaged
// buffer, and asks the bridge host to read each chunk.

#include <scfw/runtime.h>
#include <scfw/platform/windows/kernelmode.h>

#include <vmi/shellcode.hpp>

#include <cstdint>
#include <optional>

extern "C" {

//////////////////////////////////////////////////////////////////////////
// Kernel definitions not provided by the Windows SDK.
//////////////////////////////////////////////////////////////////////////

typedef CCHAR KPROCESSOR_MODE;

typedef enum _MODE {
    KernelMode,
    UserMode,
    MaximumMode
} MODE;

typedef _Enum_is_bitflag_ enum _POOL_TYPE {
    NonPagedPool,
} POOL_TYPE;

typedef struct _MM_COPY_ADDRESS {
    union {
        PVOID VirtualAddress;
        PHYSICAL_ADDRESS PhysicalAddress;
    };
} MM_COPY_ADDRESS, *PMMCOPY_ADDRESS;

#define MM_COPY_MEMORY_PHYSICAL             0x1
#define MM_COPY_MEMORY_VIRTUAL              0x2

NTKERNELAPI
PVOID
NTAPI
ExAllocatePoolWithTag(
    _In_ __drv_strictTypeMatch(__drv_typeExpr) POOL_TYPE PoolType,
    _In_ SIZE_T NumberOfBytes,
    _In_ ULONG Tag
    );

_IRQL_requires_max_(DISPATCH_LEVEL)
NTKERNELAPI
VOID
ExFreePoolWithTag(
    _Pre_notnull_ __drv_freesMem(Mem) PVOID P,
    _In_ ULONG Tag
    );

NTKERNELAPI
NTSTATUS
ObCloseHandle(
    _In_ _Post_ptr_invalid_ HANDLE Handle,
    _In_ KPROCESSOR_MODE PreviousMode
    );

_IRQL_requires_max_(APC_LEVEL)
NTKERNELAPI
NTSTATUS
NTAPI
MmCopyMemory(
    _In_ PVOID TargetAddress,
    _In_ MM_COPY_ADDRESS SourceAddress,
    _In_ SIZE_T NumberOfBytes,
    _In_ ULONG Flags,
    _Out_ PSIZE_T NumberOfBytesTransferred
    );

} // extern "C"

IMPORT_BEGIN();
    IMPORT_MODULE("ntoskrnl.exe");
        IMPORT_SYMBOL(ExAllocatePoolWithTag);
        IMPORT_SYMBOL(ExFreePoolWithTag);
        IMPORT_SYMBOL(MmCopyMemory);
        IMPORT_SYMBOL(ObCloseHandle);
        IMPORT_SYMBOL(ZwCreateSection);
        IMPORT_SYMBOL(ZwMapViewOfSection);
        IMPORT_SYMBOL(ZwQueryInformationFile);
        IMPORT_SYMBOL(ZwUnmapViewOfSection);
IMPORT_END();

namespace sc {

#define SHELLCODE_MEMORY_TAG 'tfcs'

enum class stage : uint8_t {
    none = 0x00,
    file_name = 0x01,
    file_size = 0x02,
    mapping = 0x03,
    buffer = 0x04,
    transfer = 0x05,
};

enum class error : uint8_t {
    ex_allocate_pool_with_tag = 0x01,
    mm_copy_memory = 0x02,
    zw_query_information_file = 0x03,
    zw_create_section = 0x04,
    zw_map_view_of_section = 0x05,
    bridge_begin = 0x06,
    invalid_chunk_size = 0x07,
};

template <>
struct vmi::is_error_code<error> : std::true_type {};

using failure = vmi::failure<error>;
using status = vmi::status<stage>;

struct bridge_traits : vmi::default_bridge_traits {
    //
    // The request code used by the bridge to identify this shellcode.
    //
    // This value is arbitrary but must match the request code expected
    // by the receiving side.
    //
    // See `FileTransferBridge::REQUEST` in
    //     examples/windows-bridge/file_transfer/bridge.rs
    //

    static constexpr uint16_t request = 0x0012;
};

enum class transfer_status : uint8_t {
    success = 0x00,
    error = 0xff,
};

struct bridge : vmi::bridge<bridge_traits> {
    //
    // The method codes used by the bridge to identify the different operations.
    //
    // Similarly to the request code, these values are also arbitrary but
    // must match the method codes expected by the receiving side.
    //

    static constexpr uint16_t  method_begin         = 0x0001;
    static constexpr uint16_t  method_set_buffer    = 0x0002;
    static constexpr uint16_t  method_chunk         = 0x0003;
    static constexpr uint16_t  method_close         = 0x0004;
    static constexpr uint16_t  method_exit          = 0xffff;

    //
    // The response codes used by the bridge to indicate the desired action.
    //
    // Also arbitrary, but also must match the response codes expected by
    // the receiving side.
    //

    static constexpr uint32_t response_continue     = 0x00000000;
    static constexpr uint32_t response_abort        = 0xffffffff;

    _Success_(return != 0)
    static
    ULONG
    begin(
        _In_ HANDLE FileHandle,
        _In_ LONGLONG FileSize,
        _In_ const UNICODE_STRING* FileName,
        _Out_ PULONG ChunkSize
        )
    {
        const auto response =
            send(
                method_begin,
                reinterpret_cast<uintptr_t>(FileHandle),
                static_cast<uint64_t>(FileSize),
                reinterpret_cast<uintptr_t>(FileName->Buffer),
                static_cast<uint64_t>(FileName->Length)
                );

        if (!response)
        {
            return 0;
        }

        *ChunkSize = (ULONG)(response->value1 >> 12);
        return (ULONG)(response->value1 & 0xfff);
    }

    static
    uint64_t
    set_buffer(
        _In_ ULONG TransferHandle,
        _In_ PVOID Buffer
        )
    {
        const auto response = send(
            method_set_buffer,
            TransferHandle,
            reinterpret_cast<uintptr_t>(Buffer)
            );

        return response
            ? response->value1
            : response_abort;
    }

    static
    uint64_t
    chunk(
        _In_ ULONG TransferHandle,
        _In_ ULONG Length
        )
    {
        const auto response = send(
            method_chunk,
            TransferHandle,
            static_cast<uint64_t>(Length)
            );

        return response
            ? response->value1
            : response_abort;
    }

    static
    void
    close(
        _In_ ULONG TransferHandle,
        _In_ transfer_status Status
        )
    {
        (void)send(
            method_close,
            TransferHandle,
            static_cast<uint64_t>(Status)
            );
    }

    static
    void
    exit(
        _In_ status status
        )
    {
        (void)send(
            method_exit,
            status.encode()
            );
    }
};

auto
TransferFile(
    _In_ HANDLE FileHandle
    ) -> status
{
    NTSTATUS Status;

    //
    // Query the file name.
    //

    IO_STATUS_BLOCK IoStatusBlock;
    FILE_NAME_INFORMATION PartialFileNameInformation;
    Status = ZwQueryInformationFile(FileHandle,
                                    &IoStatusBlock,
                                    &PartialFileNameInformation,
                                    sizeof(PartialFileNameInformation),
                                    ::FileNameInformation);

    if (Status != STATUS_BUFFER_OVERFLOW && !NT_SUCCESS(Status))
    {
        return status::operation_failed(
            stage::file_name,
            failure{ error::zw_query_information_file, Status }
            );
    }

    //
    // Allocate the full file name buffer and repeat the query.
    //

    PFILE_NAME_INFORMATION FileNameInformation;
    ULONG FileNameInformationSize =
        FIELD_OFFSET(FILE_NAME_INFORMATION, FileName)
        + PartialFileNameInformation.FileNameLength;

    do
    {
        FileNameInformation = (PFILE_NAME_INFORMATION)
            ExAllocatePoolWithTag(NonPagedPool,
                                  FileNameInformationSize,
                                  SHELLCODE_MEMORY_TAG);

        if (!FileNameInformation)
        {
            return status::operation_failed(
                stage::file_name,
                failure{
                    error::ex_allocate_pool_with_tag,
                    STATUS_INSUFFICIENT_RESOURCES
                    }
                );
        }

        Status = ZwQueryInformationFile(FileHandle,
                                        &IoStatusBlock,
                                        FileNameInformation,
                                        FileNameInformationSize,
                                        ::FileNameInformation);

        if (Status == STATUS_BUFFER_OVERFLOW)
        {
            //
            // Retry if a concurrent rename increases the required buffer size.
            //

            FileNameInformationSize =
                FIELD_OFFSET(FILE_NAME_INFORMATION, FileName)
                + FileNameInformation->FileNameLength;

            ExFreePoolWithTag(FileNameInformation, SHELLCODE_MEMORY_TAG);
        }
    } while (Status == STATUS_BUFFER_OVERFLOW);

    if (!NT_SUCCESS(Status))
    {
        ExFreePoolWithTag(FileNameInformation, SHELLCODE_MEMORY_TAG);

        return status::operation_failed(
            stage::file_name,
            failure{ error::zw_query_information_file, Status }
            );
    }

    UNICODE_STRING FileName;
    FileName.Length = (USHORT)FileNameInformation->FileNameLength;
    FileName.MaximumLength = FileName.Length;
    FileName.Buffer = FileNameInformation->FileName;

    //
    // Query the file size.
    //

    FILE_STANDARD_INFORMATION FileStandardInformation;
    Status = ZwQueryInformationFile(FileHandle,
                                    &IoStatusBlock,
                                    &FileStandardInformation,
                                    sizeof(FileStandardInformation),
                                    ::FileStandardInformation);

    if (!NT_SUCCESS(Status))
    {
        ExFreePoolWithTag(FileNameInformation, SHELLCODE_MEMORY_TAG);

        return status::operation_failed(
            stage::file_size,
            failure{ error::zw_query_information_file, Status }
            );
    }

    LONGLONG FileSize = FileStandardInformation.EndOfFile.QuadPart;

    //
    // Map the file into the current process. OBJ_KERNEL_HANDLE keeps the
    // temporary section handle out of the current process's user handle table.
    // Empty files intentionally fail with STATUS_MAPPED_FILE_SIZE_ZERO.
    //

    OBJECT_ATTRIBUTES ObjectAttributes;
    InitializeObjectAttributes(&ObjectAttributes,
                               NULL,
                               OBJ_KERNEL_HANDLE,
                               NULL,
                               NULL);

    HANDLE SectionHandle;
    Status = ZwCreateSection(&SectionHandle,
                             SECTION_MAP_READ,
                             &ObjectAttributes,
                             NULL,
                             PAGE_READONLY,
                             SEC_COMMIT,
                             FileHandle);

    if (!NT_SUCCESS(Status))
    {
        ExFreePoolWithTag(FileNameInformation, SHELLCODE_MEMORY_TAG);

        return status::operation_failed(
            stage::mapping,
            failure{ error::zw_create_section, Status }
            );
    }

    PVOID BaseAddress = NULL;
    SIZE_T ViewSize = 0;
    Status = ZwMapViewOfSection(SectionHandle,
                                ZwCurrentProcess(),
                                &BaseAddress,
                                0,
                                0,
                                NULL,
                                &ViewSize,
                                ViewUnmap,
                                0,
                                PAGE_READONLY);

    //
    // The mapped view keeps the section alive after its handle is closed.
    //

    ObCloseHandle(SectionHandle, KernelMode);

    if (!NT_SUCCESS(Status))
    {
        ExFreePoolWithTag(FileNameInformation, SHELLCODE_MEMORY_TAG);

        return status::operation_failed(
            stage::mapping,
            failure{ error::zw_map_view_of_section, Status }
            );
    }

    //
    // Open the host transfer with the file metadata.
    //

    auto status = status::success(stage::none);

    PVOID TransferBuffer;
    ULONG ChunkSize;
    ULONG TransferHandle = bridge::begin(FileHandle, FileSize, &FileName, &ChunkSize);

    if (!TransferHandle)
    {
        status = status::operation_failed(
            stage::transfer,
            failure{ error::bridge_begin }
            );

        goto CleanupMappedView;
    }

    if (!ChunkSize)
    {
        status = status::operation_failed(
            stage::buffer,
            failure{
                error::invalid_chunk_size,
                STATUS_INVALID_BUFFER_SIZE
                }
            );

        bridge::close(TransferHandle, transfer_status::error);
        goto CleanupMappedView;
    }

    //
    // Allocate the shared nonpaged chunk buffer.
    //

    TransferBuffer = ExAllocatePoolWithTag(NonPagedPool,
                                           (SIZE_T)ChunkSize,
                                           SHELLCODE_MEMORY_TAG);

    if (!TransferBuffer)
    {
        status = status::operation_failed(
            stage::buffer,
            failure{
                error::ex_allocate_pool_with_tag,
                STATUS_INSUFFICIENT_RESOURCES
                }
            );

        bridge::close(TransferHandle, transfer_status::error);
        goto CleanupMappedView;
    }

    //
    // Publish the buffer and transfer the file one chunk at a time.
    //

    if (bridge::set_buffer(TransferHandle, TransferBuffer)
        != bridge::response_continue)
    {
        status = status::aborted(stage::buffer);
        bridge::close(TransferHandle, transfer_status::error);

        goto CleanupTransferBuffer;
    }

    for (LONGLONG Offset = 0; Offset < FileSize; Offset += ChunkSize)
    {
        LONGLONG Remaining = FileSize - Offset;
        ULONG Length = (ULONG)(Remaining < ChunkSize ? Remaining : ChunkSize);

        MM_COPY_ADDRESS SourceAddress;
        SourceAddress.VirtualAddress = (UCHAR*)BaseAddress + (SIZE_T)Offset;

        SIZE_T BytesCopied;
        Status = MmCopyMemory(TransferBuffer,
                              SourceAddress,
                              (SIZE_T)Length,
                              MM_COPY_MEMORY_VIRTUAL,
                              &BytesCopied);

        if (!NT_SUCCESS(Status))
        {
            status = status::operation_failed(
                stage::transfer,
                failure{ error::mm_copy_memory, Status }
                );

            bridge::close(TransferHandle, transfer_status::error);
            goto CleanupTransferBuffer;
        }

        if (bridge::chunk(TransferHandle, Length)
            != bridge::response_continue)
        {
            status = status::aborted(stage::transfer);
            bridge::close(TransferHandle, transfer_status::error);

            goto CleanupTransferBuffer;
        }
    }

    status = status::success(stage::transfer);
    bridge::close(TransferHandle, transfer_status::success);

    //
    // Release acquired resources in reverse order.
    //

CleanupTransferBuffer:
    ExFreePoolWithTag(TransferBuffer, SHELLCODE_MEMORY_TAG);

CleanupMappedView:
    ZwUnmapViewOfSection(ZwCurrentProcess(), BaseAddress);

CleanupFileName:
    ExFreePoolWithTag(FileNameInformation, SHELLCODE_MEMORY_TAG);

    //
    // Return the final status.
    //

Exit:
    return status;
}

extern "C"
void
__fastcall
entry(
    _In_ void* argument1,  // Kernel image base for scfw.
    _In_ void* argument2   // File handle.
    )
{
    (void)argument1;

    bridge::exit(TransferFile(reinterpret_cast<HANDLE>(argument2)));
}

} // namespace sc