-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathremap.cpp
More file actions
651 lines (559 loc) · 14.4 KB
/
remap.cpp
File metadata and controls
651 lines (559 loc) · 14.4 KB
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
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
#include "remap.hpp"
#include "ntdll.hpp"
//=============================================================================
// Private Types
//=============================================================================
typedef BOOL(NTAPI* REMAP_ROUTINE)(
_In_ PVOID pRemapRegion
);
//=============================================================================
// Module Globals
//=============================================================================
static ULONG g_CharacteristicsProtectionMap[2][2][2] =
{
{
{ PAGE_NOACCESS, PAGE_WRITECOPY },
{ PAGE_READONLY, PAGE_READWRITE }
},
{
{ PAGE_EXECUTE, PAGE_EXECUTE_WRITECOPY },
{ PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE }
},
};
//=============================================================================
// Private Prototypes
//=============================================================================
_Check_return_
static
BOOL
RmppVerifyPeSectionAlignment(
_In_ PIMAGE_NT_HEADERS pNtHeaders
);
static
VOID
RmppCopyPeSections(
_In_ PIMAGE_NT_HEADERS pNtHeaders,
_In_ ULONG_PTR DestinationBase
);
_Check_return_
static
BOOL
RmppRemapImageRoutine(
_In_ PVOID pRemapRegion
);
_Check_return_
static
ULONG
RmppConvertSectionCharacteristicsToPageProtection(
_In_ ULONG Characteristics
);
_Check_return_
static
BOOL
RmppMapProtectedView(
_In_ HANDLE hSection,
_In_ ULONG_PTR BaseAddress,
_In_ SIZE_T cbSize,
_In_ SIZE_T cbOffset,
_In_ ULONG Protection
);
_Check_return_
static
BOOL
RmppValidateRemappedImageProtection(
_In_ ULONG_PTR ImageBase
);
_Check_return_
static
BOOL
RmppValidateRemappedPeSectionProtection(
_In_ PVOID pSectionBase
);
//=============================================================================
// Public Interface
//=============================================================================
//
// RmpRemapImage
//
// This function remaps the pe image at 'ImageBase' so that the page protection
// of all pages contained in the image cannot be changed.
//
// The remapping process uses the following strategy:
//
// 1. The image is copied to an executable buffer referred to as the 'remap
// region'.
//
// 2. The remap routine inside the remap region is located and invoked.
//
// 3. The remap routine creates a page-file-backed section to store the
// remapped image.
//
// 4. The remap routine maps a view of the entire section and copies the
// contents of the image to the view. This view is then unmapped.
//
// 5. The remap routine maps a view for each pe section in the image using the
// relative virtual address of the pe section as the section offset for
// the view. Each view is mapped using the 'SEC_NO_CHANGE' allocation
// type to prevent page protection changes.
//
// 6. The remap routine completes and execution returns to the remapped image.
//
// NOTE This strategy requires each pe section in the image to be aligned to
// the system allocation granularity. See the documentation for
// 'ZwMapViewOfSection' for details.
//
// NOTE This function currently only supports x64 images.
//
_Use_decl_annotations_
BOOL
RmpRemapImage(
ULONG_PTR ImageBase
)
{
PIMAGE_NT_HEADERS pNtHeaders = NULL;
PVOID pRemapRegion = NULL;
REMAP_ROUTINE fpRemapRoutine = NULL;
BOOL status = TRUE;
pNtHeaders = RtlImageNtHeader((PVOID)ImageBase);
if (!pNtHeaders)
{
status = FALSE;
goto exit;
}
status = RmppVerifyPeSectionAlignment(pNtHeaders);
if (!status)
{
goto exit;
}
//
// Allocate an executable and writable buffer where the remap routine will
// execute.
//
pRemapRegion = VirtualAlloc(
NULL,
pNtHeaders->OptionalHeader.SizeOfImage,
MEM_COMMIT | MEM_RESERVE,
PAGE_EXECUTE_READWRITE);
if (!pRemapRegion)
{
status = FALSE;
goto exit;
}
//
// Copy the image to the remap region.
//
RmppCopyPeSections(pNtHeaders, (ULONG_PTR)pRemapRegion);
//
// Locate the address of the remap routine inside the remap region.
//
fpRemapRoutine = (REMAP_ROUTINE)(
(ULONG_PTR)pRemapRegion +
(ULONG_PTR)RmppRemapImageRoutine -
ImageBase);
//
// Invoke the remap routine inside the remap region.
//
status = fpRemapRoutine(pRemapRegion);
if (!status)
{
goto exit;
}
//
// Verify that each pe section in the remapped image is protected.
//
status = RmppValidateRemappedImageProtection(ImageBase);
if (!status)
{
goto exit;
}
exit:
if (pRemapRegion)
{
if (!VirtualFree(pRemapRegion, 0, MEM_RELEASE))
{
}
}
return status;
}
//=============================================================================
// Private Interface
//=============================================================================
//
// RmppVerifyPeSectionAlignment
//
// Verify that each pe section is aligned to the system allocation granularity.
//
_Use_decl_annotations_
static
BOOL
RmppVerifyPeSectionAlignment(
PIMAGE_NT_HEADERS pNtHeaders
)
{
SYSTEM_INFO SystemInfo = {};
PIMAGE_SECTION_HEADER pSectionHeader = NULL;
ULONG_PTR SectionBase = 0;
BOOL status = TRUE;
//
// Query the system allocation granularity.
//
GetSystemInfo(&SystemInfo);
pSectionHeader = IMAGE_FIRST_SECTION(pNtHeaders);
for (WORD i = 0; i < pNtHeaders->FileHeader.NumberOfSections; ++i)
{
SectionBase =
pNtHeaders->OptionalHeader.ImageBase +
pSectionHeader[i].VirtualAddress;
status = POINTER_IS_ALIGNED(
SectionBase,
SystemInfo.dwAllocationGranularity);
if (!status)
{
goto exit;
}
}
//
// Verify pe header alignment.
//
status = POINTER_IS_ALIGNED(
pNtHeaders->OptionalHeader.ImageBase,
SystemInfo.dwAllocationGranularity);
if (!status)
{
goto exit;
}
exit:
return status;
}
//
// RmppCopyPeSections
//
_Use_decl_annotations_
static
VOID
RmppCopyPeSections(
PIMAGE_NT_HEADERS pNtHeaders,
ULONG_PTR DestinationBase
)
{
ULONG_PTR SourceBase = 0;
PIMAGE_SECTION_HEADER pSectionHeader = NULL;
SourceBase = pNtHeaders->OptionalHeader.ImageBase;
pSectionHeader = IMAGE_FIRST_SECTION(pNtHeaders);
//
// We copy each pe section individually because images compiled with the
// '/ALIGN' linker option will have reserved memory padding.
//
for (WORD i = 0; i < pNtHeaders->FileHeader.NumberOfSections; ++i)
{
RtlCopyMemory(
(PVOID)(DestinationBase + pSectionHeader[i].VirtualAddress),
(PVOID)(SourceBase + pSectionHeader[i].VirtualAddress),
pSectionHeader[i].Misc.VirtualSize);
}
//
// Copy the pe header.
//
RtlCopyMemory((PVOID)DestinationBase, (PVOID)SourceBase, PAGE_SIZE);
}
//
// RmppRemapImageRoutine
//
// This routine unmaps the original image then reconstructs it as contiguous
// memory mapped views.
//
_Use_decl_annotations_
static
BOOL
RmppRemapImageRoutine(
PVOID pRemapRegion
)
{
PIMAGE_NT_HEADERS pNtHeaders = NULL;
HANDLE hSection = NULL;
LARGE_INTEGER cbSectionSize = {};
PVOID pViewBase = NULL;
ULONG_PTR ImageBase = 0;
LARGE_INTEGER cbSectionOffset = {};
SIZE_T cbViewSize = 0;
PIMAGE_SECTION_HEADER pSectionHeader = NULL;
ULONG Protection = 0;
NTSTATUS ntstatus = STATUS_SUCCESS;
BOOL status = TRUE;
pNtHeaders = RtlImageNtHeader(pRemapRegion);
if (!pNtHeaders)
{
status = FALSE;
goto exit;
}
cbSectionSize.QuadPart = pNtHeaders->OptionalHeader.SizeOfImage;
//
// Create a page-file-backed section to store the remapped image.
//
ntstatus = NtCreateSection(
&hSection,
SECTION_ALL_ACCESS,
NULL,
&cbSectionSize,
PAGE_EXECUTE_READWRITE,
SEC_COMMIT | SEC_NO_CHANGE,
NULL);
if (!NT_SUCCESS(ntstatus))
{
status = FALSE;
goto exit;
}
//
// Map a view of the entire section.
//
ntstatus = NtMapViewOfSection(
hSection,
NtCurrentProcess(),
&pViewBase,
0,
pNtHeaders->OptionalHeader.SizeOfImage,
&cbSectionOffset,
&cbViewSize,
ViewUnmap,
0,
PAGE_READWRITE);
if (!NT_SUCCESS(ntstatus))
{
status = FALSE;
goto exit;
}
//
// Copy the image to our view.
//
RmppCopyPeSections(pNtHeaders, (ULONG_PTR)pViewBase);
//
// Unmap the copy-view because we no longer need it.
//
ntstatus = NtUnmapViewOfSection(NtCurrentProcess(), pViewBase);
if (!NT_SUCCESS(ntstatus))
{
status = FALSE;
goto exit;
}
//
// Unmap the original image.
//
ImageBase = pNtHeaders->OptionalHeader.ImageBase;
ntstatus = NtUnmapViewOfSection(NtCurrentProcess(), (PVOID)ImageBase);
if (!NT_SUCCESS(ntstatus))
{
status = FALSE;
goto exit;
}
//
// Reconstruct the image by mapping a view of the section for each pe
// section in the image.
//
pSectionHeader = IMAGE_FIRST_SECTION(pNtHeaders);
for (WORD i = 0; i < pNtHeaders->FileHeader.NumberOfSections; ++i)
{
Protection = RmppConvertSectionCharacteristicsToPageProtection(
pSectionHeader[i].Characteristics);
status = RmppMapProtectedView(
hSection,
ImageBase + pSectionHeader[i].VirtualAddress,
pSectionHeader[i].Misc.VirtualSize,
pSectionHeader[i].VirtualAddress,
Protection);
if (!status)
{
goto exit;
}
}
//
// Map a view for the pe header.
//
status = RmppMapProtectedView(
hSection,
ImageBase,
PAGE_SIZE,
0,
PAGE_READONLY);
if (!status)
{
goto exit;
}
exit:
if (hSection)
{
ntstatus = NtClose(hSection);
if (!NT_SUCCESS(ntstatus))
{
}
}
return status;
}
//
// RmppConvertSectionCharacteristicsToPageProtection
//
_Use_decl_annotations_
static
ULONG
RmppConvertSectionCharacteristicsToPageProtection(
ULONG Characteristics
)
{
BOOL fExecutable = FALSE;
BOOL fReadable = FALSE;
BOOL fWritable = FALSE;
ULONG Protection = 0;
if (0 != (IMAGE_SCN_MEM_EXECUTE & Characteristics))
{
fExecutable = TRUE;
}
if (0 != (IMAGE_SCN_MEM_READ & Characteristics))
{
fReadable = TRUE;
}
if (0 != (IMAGE_SCN_MEM_WRITE & Characteristics))
{
fWritable = TRUE;
}
Protection =
g_CharacteristicsProtectionMap[fExecutable][fReadable][fWritable];
if (0 != (IMAGE_SCN_MEM_NOT_CACHED & Characteristics))
{
Protection |= PAGE_NOCACHE;
}
return Protection;
}
//
// RmppMapProtectedView
//
_Use_decl_annotations_
static
BOOL
RmppMapProtectedView(
HANDLE hSection,
ULONG_PTR BaseAddress,
SIZE_T cbSize,
SIZE_T cbOffset,
ULONG Protection
)
{
LARGE_INTEGER cbSectionOffset = {};
PVOID pViewBase = NULL;
SIZE_T cbViewSize = 0;
NTSTATUS ntstatus = STATUS_SUCCESS;
BOOL status = TRUE;
pViewBase = (PVOID)BaseAddress;
cbViewSize = cbSize;
cbSectionOffset.QuadPart = cbOffset;
ntstatus = NtMapViewOfSection(
hSection,
NtCurrentProcess(),
&pViewBase,
0,
0,
&cbSectionOffset,
&cbViewSize,
ViewUnmap,
SEC_NO_CHANGE,
Protection);
if (!NT_SUCCESS(ntstatus))
{
status = FALSE;
goto exit;
}
exit:
return status;
}
//
// RmppValidateRemappedImageProtection
//
_Use_decl_annotations_
static
BOOL
RmppValidateRemappedImageProtection(
ULONG_PTR ImageBase
)
{
PIMAGE_NT_HEADERS pNtHeaders = NULL;
PIMAGE_SECTION_HEADER pSectionHeader = NULL;
BOOL status = TRUE;
pNtHeaders = RtlImageNtHeader((PVOID)ImageBase);
if (!pNtHeaders)
{
status = FALSE;
goto exit;
}
pSectionHeader = IMAGE_FIRST_SECTION(pNtHeaders);
for (WORD i = 0; i < pNtHeaders->FileHeader.NumberOfSections; ++i)
{
status = RmppValidateRemappedPeSectionProtection(
(PVOID)(ImageBase + pSectionHeader[i].VirtualAddress));
if (!status)
{
goto exit;
}
}
//
// Validate the pe header.
//
status = RmppValidateRemappedPeSectionProtection((PVOID)ImageBase);
if (!status)
{
goto exit;
}
exit:
return status;
}
//
// RmppValidateRemappedPeSectionProtection
//
_Use_decl_annotations_
static
BOOL
RmppValidateRemappedPeSectionProtection(
PVOID pSectionBase
)
{
MEMORY_BASIC_INFORMATION MemoryBasicInfo = {};
ULONG TestProtect = 0;
ULONG PreviousProtect = 0;
BOOL status = TRUE;
//
// Query the current page protection.
//
if (!VirtualQuery(pSectionBase, &MemoryBasicInfo, sizeof(MemoryBasicInfo)))
{
status = FALSE;
goto exit;
}
//
// We use PAGE_EXECUTE_READWRITE as our test protection value because it is
// the most permissive page protection.
//
if (PAGE_EXECUTE_READWRITE != MemoryBasicInfo.Protect)
{
TestProtect = PAGE_EXECUTE_READWRITE;
}
else
{
TestProtect = PAGE_NOACCESS;
}
//
// Attempt to modify the page protection of every page contained in the
// memory region. This should fail because each view was mapped with the
// SEC_NO_CHANGE allocation type.
//
status = VirtualProtect(
pSectionBase,
MemoryBasicInfo.RegionSize,
TestProtect,
&PreviousProtect);
if (status)
{
status = FALSE;
goto exit;
}
// Reset the status code to indicate success.
status = TRUE;
exit:
return status;
}