-
Notifications
You must be signed in to change notification settings - Fork 120
/
Copy pathDetoursNT.cpp
808 lines (686 loc) · 13.9 KB
/
DetoursNT.cpp
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
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
//
// Workaround for VS2017 to force this library to
// be compilable on ARM.
//
#define _ARM_WINAPI_PARTITION_DESKTOP_SDK_AVAILABLE 1
#include <windows.h>
#include "DetoursNT.h"
//
// Enable/disable exception handling routines.
//
// #define DETOURSNT_NO_EH
//
// Enable/disable CRT routines.
//
// #define DETOURSNT_NO_CRT
#ifdef __cplusplus
extern "C" {
#endif
#pragma region NTDLL.DLL
#define NT_SUCCESS(Status) (((NTSTATUS)(Status)) >= 0)
#define NtCurrentPeb() (NtCurrentTeb()->ProcessEnvironmentBlock)
#define RtlProcessHeap() (NtCurrentPeb()->ProcessHeap)
#define RTL_CONSTANT_STRING(s) { sizeof(s)-sizeof((s)[0]), sizeof(s), s }
// #define _CLIENT_ID Mock__CLIENT_ID
// #define CLIENT_ID Mock_CLIENT_ID
// #define PCLIENT_ID Mock_PCLIENT_ID
//
// #define _TEB Mock__TEB
// #define TEB Mock_TEB
// #define PTEB Mock_PTEB
typedef struct _PEB_LDR_DATA PEB_LDR_DATA, *PPEB_LDR_DATA;
typedef struct _RTL_USER_PROCESS_PARAMETERS RTL_USER_PROCESS_PARAMETERS, *PRTL_USER_PROCESS_PARAMETERS;
typedef struct _ANSI_STRING {
USHORT Length;
USHORT MaximumLength;
PSTR Buffer;
} ANSI_STRING;
typedef ANSI_STRING *PANSI_STRING;
typedef struct _UNICODE_STRING {
USHORT Length;
USHORT MaximumLength;
PWSTR Buffer;
} UNICODE_STRING;
typedef UNICODE_STRING *PUNICODE_STRING;
typedef struct _CLIENT_ID
{
HANDLE UniqueProcess;
HANDLE UniqueThread;
} CLIENT_ID, *PCLIENT_ID;
typedef struct _PEB
{
BOOLEAN InheritedAddressSpace;
BOOLEAN ReadImageFileExecOptions;
BOOLEAN BeingDebugged;
union
{
BOOLEAN BitField;
struct
{
BOOLEAN ImageUsesLargePages : 1;
BOOLEAN IsProtectedProcess : 1;
BOOLEAN IsImageDynamicallyRelocated : 1;
BOOLEAN SkipPatchingUser32Forwarders : 1;
BOOLEAN IsPackagedProcess : 1;
BOOLEAN IsAppContainer : 1;
BOOLEAN IsProtectedProcessLight : 1;
BOOLEAN IsLongPathAwareProcess : 1;
};
};
HANDLE Mutant;
PVOID ImageBaseAddress;
PPEB_LDR_DATA Ldr;
PRTL_USER_PROCESS_PARAMETERS ProcessParameters;
PVOID SubSystemData;
PVOID ProcessHeap;
//
// ...
//
} PEB, *PPEB;
typedef struct _TEB
{
NT_TIB NtTib;
PVOID EnvironmentPointer;
CLIENT_ID ClientId;
PVOID ActiveRpcHandle;
PVOID ThreadLocalStoragePointer;
PPEB ProcessEnvironmentBlock;
//
// ...
//
} TEB, *PTEB;
NTSYSAPI
PVOID
NTAPI
RtlAllocateHeap(
_In_ PVOID HeapHandle,
_In_opt_ ULONG Flags,
_In_ SIZE_T Size
);
NTSYSAPI
BOOLEAN
NTAPI
RtlFreeHeap(
_In_ PVOID HeapHandle,
_In_opt_ ULONG Flags,
_Frees_ptr_opt_ PVOID BaseAddress
);
NTSYSAPI
PVOID
NTAPI
RtlReAllocateHeap(
_In_ PVOID HeapHandle,
_In_ ULONG Flags,
_Frees_ptr_opt_ PVOID BaseAddress,
_In_ SIZE_T Size
);
NTSYSAPI
ULONG
NTAPI
RtlNtStatusToDosError(
_In_ NTSTATUS Status
);
NTSYSAPI
NTSTATUS
NTAPI
LdrLoadDll(
_In_opt_ PWSTR DllPath,
_In_opt_ PULONG DllCharacteristics,
_In_ PUNICODE_STRING DllName,
_Out_ PVOID *DllHandle
);
NTSYSAPI
NTSTATUS
NTAPI
LdrGetProcedureAddress(
_In_ PVOID DllHandle,
_In_opt_ PANSI_STRING ProcedureName,
_In_opt_ ULONG ProcedureNumber,
_Out_ PVOID *ProcedureAddress
);
#pragma endregion
#pragma region CRT
#ifndef DETOURSNT_NO_CRT
#pragma function(memset)
void* __cdecl
memset(
void* dest,
int ch,
size_t count
)
{
if (count)
{
char* d = (char*)dest;
do
{
*d++ = ch;
} while (--count);
}
return dest;
}
#pragma function(memcpy)
void* __cdecl
memcpy(
void* dest,
const void* src,
size_t count
)
{
char* d = (char*)dest;
char* s = (char*)src;
while (count--)
{
*d++ = *s++;
}
return dest;
}
void* __cdecl
malloc(
size_t size
)
{
return RtlAllocateHeap(RtlProcessHeap(), 0, size);
}
void* __cdecl
calloc(
size_t count,
size_t size
)
{
//
// UNIMPLEMENTED
//
return NULL;
}
void* __cdecl
realloc(
void* ptr,
size_t new_size
)
{
//
// UNIMPLEMENTED
//
return NULL;
}
void __cdecl
free(
void* ptr
)
{
RtlFreeHeap(RtlProcessHeap(), 0, ptr);
}
#ifdef __cplusplus
} // extern "C"
void* __cdecl
operator new(
size_t size
)
{
return malloc(size);
}
void* __cdecl
operator new[](
size_t size
)
{
return malloc(size);
}
void __cdecl
operator delete(
void* pointer
) noexcept
{
free(pointer);
}
void __cdecl
operator delete(
void* pointer,
size_t
) noexcept
{
free(pointer);
}
void __cdecl
operator delete[](
void* pointer
) noexcept
{
free(pointer);
}
void __cdecl
operator delete[](
void* pointer,
size_t
) noexcept
{
free(pointer);
}
extern "C" {
#endif
#ifndef DETOURSNT_NO_EH
#if defined(_M_AMD64) || defined(_M_ARM64) || defined(_M_ARM)
EXCEPTION_DISPOSITION
__cdecl
__C_specific_handler(
_In_ struct _EXCEPTION_RECORD* ExceptionRecord,
_In_ void* EstablisherFrame,
_Inout_ struct _CONTEXT* ContextRecord,
_Inout_ struct _DISPATCHER_CONTEXT* DispatcherContext
)
{
#if 0
static decltype(__C_specific_handler)* Procedure = nullptr;
if (!Procedure)
{
PVOID NtdllImageBase;
RtlPcToFileHeader((PVOID)NtAllocateVirtualMemory, &NtdllImageBase);
ANSI_STRING ProcedureName = RTL_CONSTANT_STRING("__C_specific_handler");
LdrGetProcedureAddress(NtdllImageBase, &ProcedureName, 0, (PVOID*)&Procedure);
//
// Do not check for errors, if Procedure remains NULL, we're screwed anyway.
//
}
return Procedure(ExceptionRecord, EstablisherFrame, ContextRecord, DispatcherContext);
#else
#ifdef _DEBUG
__debugbreak();
#endif
*reinterpret_cast<void**>(nullptr) = nullptr;
return (EXCEPTION_DISPOSITION)0;
#endif
}
#endif // defined(_M_AMD64) || defined(_M_ARM64) || defined(_M_ARM)
#if defined(_M_IX86)
int
_callnewh(
size_t size
)
{
return 0;
}
EXCEPTION_DISPOSITION
__cdecl
_except_handler3(
_In_ struct _EXCEPTION_RECORD* ExceptionRecord,
_In_ void* EstablisherFrame,
_Inout_ struct _CONTEXT* ContextRecord,
_Inout_ struct _DISPATCHER_CONTEXT* DispatcherContext
)
{
#ifdef _DEBUG
__debugbreak();
#endif
*reinterpret_cast<void**>(nullptr) = nullptr;
return (EXCEPTION_DISPOSITION)0;
}
#endif // defined(_M_IX86)
#endif // DETOURSNT_NO_EH
#endif // DETOURSNT_NO_CRT
#pragma endregion
#pragma region Detours/module.cpp
ULONG WINAPI DetourGetModuleSize(_In_opt_ HMODULE hModule)
{
PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)hModule;
if (hModule == NULL) {
// pDosHeader = (PIMAGE_DOS_HEADER)GetModuleHandleW(NULL);
pDosHeader = &__ImageBase;
}
__try {
#pragma warning(suppress:6011) // GetModuleHandleW(NULL) never returns NULL.
if (pDosHeader->e_magic != IMAGE_DOS_SIGNATURE) {
SetLastError(ERROR_BAD_EXE_FORMAT);
return 0;
}
PIMAGE_NT_HEADERS pNtHeader = (PIMAGE_NT_HEADERS)((PBYTE)pDosHeader +
pDosHeader->e_lfanew);
if (pNtHeader->Signature != IMAGE_NT_SIGNATURE) {
SetLastError(ERROR_INVALID_EXE_SIGNATURE);
return 0;
}
if (pNtHeader->FileHeader.SizeOfOptionalHeader == 0) {
SetLastError(ERROR_EXE_MARKED_INVALID);
return 0;
}
SetLastError(NO_ERROR);
return (pNtHeader->OptionalHeader.SizeOfImage);
}
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ?
EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
SetLastError(ERROR_EXE_MARKED_INVALID);
return 0;
}
}
#pragma endregion
#pragma region KERNEL32.DLL
static DWORD g_LastError = 0;
DWORD
WINAPI
GetLastError(
VOID
)
{
return g_LastError;
}
VOID
WINAPI
SetLastError(
IN DWORD dwErrCode
)
{
g_LastError = dwErrCode;
}
DWORD
WINAPI
BaseSetLastNTError(IN NTSTATUS Status)
{
DWORD dwErrCode;
/* Convert from NT to Win32, then set */
dwErrCode = RtlNtStatusToDosError(Status);
SetLastError(dwErrCode);
return dwErrCode;
}
DWORD
WINAPI
GetCurrentThreadId(
VOID
)
{
return HandleToUlong(NtCurrentTeb()->ClientId.UniqueThread);
}
LPVOID
NTAPI
VirtualAlloc(
IN LPVOID lpAddress,
IN SIZE_T dwSize,
IN DWORD flAllocationType,
IN DWORD flProtect
)
{
/* Call the extended API */
return VirtualAllocEx(GetCurrentProcess(),
lpAddress,
dwSize,
flAllocationType,
flProtect);
}
LPVOID
NTAPI
VirtualAllocEx(
IN HANDLE hProcess,
IN LPVOID lpAddress,
IN SIZE_T dwSize,
IN DWORD flAllocationType,
IN DWORD flProtect
)
{
NTSTATUS Status;
/* Handle any possible exceptions */
__try
{
/* Allocate the memory */
Status = NtAllocateVirtualMemory(hProcess,
&lpAddress,
0,
&dwSize,
flAllocationType,
flProtect);
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
Status = GetExceptionCode();
}
/* Check for status */
if (!NT_SUCCESS(Status))
{
/* We failed */
BaseSetLastNTError(Status);
return NULL;
}
/* Return the allocated address */
return lpAddress;
}
BOOL
NTAPI
VirtualFree(
IN LPVOID lpAddress,
IN SIZE_T dwSize,
IN DWORD dwFreeType
)
{
/* Call the extended API */
return VirtualFreeEx(GetCurrentProcess(),
lpAddress,
dwSize,
dwFreeType);
}
BOOL
NTAPI
VirtualFreeEx(
IN HANDLE hProcess,
IN LPVOID lpAddress,
IN SIZE_T dwSize,
IN DWORD dwFreeType
)
{
NTSTATUS Status;
/* Validate size and flags */
if (!(dwSize) || !(dwFreeType & MEM_RELEASE))
{
/* Free the memory */
Status = NtFreeVirtualMemory(hProcess,
&lpAddress,
&dwSize,
dwFreeType);
if (!NT_SUCCESS(Status))
{
/* We failed */
BaseSetLastNTError(Status);
return FALSE;
}
/* Return success */
return TRUE;
}
/* Invalid combo */
BaseSetLastNTError(STATUS_INVALID_PARAMETER);
return FALSE;
}
BOOL
NTAPI
VirtualProtect(
IN LPVOID lpAddress,
IN SIZE_T dwSize,
IN DWORD flNewProtect,
OUT PDWORD lpflOldProtect
)
{
/* Call the extended API */
return VirtualProtectEx(GetCurrentProcess(),
lpAddress,
dwSize,
flNewProtect,
lpflOldProtect);
}
BOOL
NTAPI
VirtualProtectEx(
IN HANDLE hProcess,
IN LPVOID lpAddress,
IN SIZE_T dwSize,
IN DWORD flNewProtect,
OUT PDWORD lpflOldProtect
)
{
NTSTATUS Status;
/* Change the protection */
Status = NtProtectVirtualMemory(hProcess,
&lpAddress,
&dwSize,
flNewProtect,
(PULONG)lpflOldProtect);
if (!NT_SUCCESS(Status))
{
/* We failed */
BaseSetLastNTError(Status);
return FALSE;
}
/* Return success */
return TRUE;
}
SIZE_T
NTAPI
VirtualQuery(
IN LPCVOID lpAddress,
OUT PMEMORY_BASIC_INFORMATION lpBuffer,
IN SIZE_T dwLength
)
{
/* Call the extended API */
return VirtualQueryEx(NtCurrentProcess(),
lpAddress,
lpBuffer,
dwLength);
}
SIZE_T
NTAPI
VirtualQueryEx(
IN HANDLE hProcess,
IN LPCVOID lpAddress,
OUT PMEMORY_BASIC_INFORMATION lpBuffer,
IN SIZE_T dwLength
)
{
NTSTATUS Status;
SIZE_T ResultLength;
/* Query basic information */
Status = NtQueryVirtualMemory(hProcess,
(LPVOID)lpAddress,
MemoryBasicInformation,
lpBuffer,
dwLength,
&ResultLength);
if (!NT_SUCCESS(Status))
{
/* We failed */
BaseSetLastNTError(Status);
return 0;
}
/* Return the length returned */
return ResultLength;
}
BOOL
NTAPI
ReadProcessMemory(
IN HANDLE hProcess,
IN LPCVOID lpBaseAddress,
IN LPVOID lpBuffer,
IN SIZE_T nSize,
OUT SIZE_T* lpNumberOfBytesRead
)
{
NTSTATUS Status;
/* Do the read */
Status = NtReadVirtualMemory(hProcess,
(PVOID)lpBaseAddress,
lpBuffer,
nSize,
&nSize);
/* In user-mode, this parameter is optional */
if (lpNumberOfBytesRead) *lpNumberOfBytesRead = nSize;
if (!NT_SUCCESS(Status))
{
/* We failed */
BaseSetLastNTError(Status);
return FALSE;
}
/* Return success */
return TRUE;
}
BOOL
WINAPI
FlushInstructionCache(
IN HANDLE hProcess,
IN LPCVOID lpBaseAddress,
IN SIZE_T nSize
)
{
NTSTATUS Status;
/* Call the native function */
Status = NtFlushInstructionCache(hProcess, (PVOID)lpBaseAddress, nSize);
if (!NT_SUCCESS(Status))
{
/* Handle failure case */
BaseSetLastNTError(Status);
return FALSE;
}
/* All good */
return TRUE;
}
DWORD
WINAPI
SuspendThread(
IN HANDLE hThread
)
{
ULONG PreviousSuspendCount;
NTSTATUS Status;
Status = NtSuspendThread(hThread, &PreviousSuspendCount);
if (!NT_SUCCESS(Status))
{
BaseSetLastNTError(Status);
return -1;
}
return PreviousSuspendCount;
}
DWORD
WINAPI
ResumeThread(
IN HANDLE hThread
)
{
ULONG PreviousResumeCount;
NTSTATUS Status;
Status = NtResumeThread(hThread, &PreviousResumeCount);
if (!NT_SUCCESS(Status))
{
BaseSetLastNTError(Status);
return -1;
}
return PreviousResumeCount;
}
BOOL
WINAPI
GetThreadContext(
IN HANDLE hThread,
OUT LPCONTEXT lpContext
)
{
NTSTATUS Status;
Status = NtGetContextThread(hThread, lpContext);
if (!NT_SUCCESS(Status))
{
BaseSetLastNTError(Status);
return FALSE;
}
return TRUE;
}
BOOL
WINAPI
SetThreadContext(
IN HANDLE hThread,
IN CONST CONTEXT *lpContext
)
{
NTSTATUS Status;
Status = NtSetContextThread(hThread, (PCONTEXT)lpContext);
if (!NT_SUCCESS(Status))
{
BaseSetLastNTError(Status);
return FALSE;
}
return TRUE;
}
#ifdef __cplusplus
}
#endif