CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
rapid7

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: rapid7/metasploit-framework
Path: blob/master/external/source/evasion/windows/process_herpaderping/ProcessHerpaderping/pch.hpp
Views: 11788
1
#pragma once
2
3
//
4
// Windows
5
//
6
#define WIN32_LEAN_AND_MEAN
7
#define WIN32_NO_STATUS
8
#include <Windows.h>
9
#undef WIN32_NO_STATUS
10
#include <ntstatus.h>
11
#include <strsafe.h>
12
#include <winioctl.h>
13
#include <bcrypt.h>
14
15
//
16
// STL
17
//
18
#include <iomanip>
19
#include <sstream>
20
#include <vector>
21
#include <optional>
22
#include <span>
23
24
//
25
// Common Macros/Defines/Usings
26
//
27
#define SCAST(_X_) static_cast<_X_>
28
#define RCAST(_X_) reinterpret_cast<_X_>
29
#define Add2Ptr(_P_, _X_) RCAST(void*)(RCAST(uintptr_t)(_P_) + _X_)
30
31
using handle_t = HANDLE;
32
33
#define _REPORT(msg, err) dprintf(msg " (%S)", Utils::FormatError(err).c_str())
34
#define REPORT_AND_RETURN_WIN32(message, win32err) _REPORT(message, win32err); return HRESULT_FROM_WIN32(win32err);
35
#define REPORT_AND_RETURN_NT(message, status) _REPORT(message, status); return HRESULT_FROM_NT(status);
36
#define REPORT_AND_RETURN_HR(message, hr) _REPORT(message, hr); return hr;
37
//
38
// prefast suppression
39
//
40
#pragma warning(disable : 6319) // prefast: use of the comma-operator in a tested expression
41
42
#ifdef DEBUGTRACE
43
#define dprintf(...) real_dprintf(__VA_ARGS__)
44
static void real_dprintf(const char* format, ...)
45
{
46
va_list args;
47
char buffer[1024];
48
va_start(args, format);
49
vsnprintf_s(buffer, sizeof(buffer), sizeof(buffer) - 3, format, args);
50
strcat_s(buffer, sizeof(buffer), "\r\n");
51
OutputDebugStringA(buffer);
52
va_end(args); // Needed as according to http://www.cplusplus.com/reference/cstdarg/va_start/
53
// one should always call va_end in the same function one calls va_start.
54
}
55
#else
56
#define dprintf(...)
57
#endif
58
59
#define FILE_MAX_PATH 260
60
61
#pragma warning(push)
62
#pragma warning(disable : 4201) // nameless struct/union
63
#pragma warning(disable : 4324) // structure was padded due to __declspec(align())
64
#pragma warning(disable : 4471) // a forward declaration of an unscoped enumeration
65
#pragma warning(disable : 28253) // prefast: inconsistent annotation
66
67
68
#ifdef __cplusplus
69
extern "C" {
70
#endif
71
72
73
#define NT_SUCCESS(Status) (((NTSTATUS)(Status)) >= 0)
74
75
typedef struct _UNICODE_STRING
76
{
77
USHORT Length;
78
USHORT MaximumLength;
79
_Field_size_bytes_part_(MaximumLength, Length) PWCH Buffer;
80
} UNICODE_STRING, * PUNICODE_STRING;
81
82
typedef struct _OBJECT_ATTRIBUTES
83
{
84
ULONG Length;
85
HANDLE RootDirectory;
86
PUNICODE_STRING ObjectName;
87
ULONG Attributes;
88
PVOID SecurityDescriptor; // PSECURITY_DESCRIPTOR;
89
PVOID SecurityQualityOfService; // PSECURITY_QUALITY_OF_SERVICE
90
} OBJECT_ATTRIBUTES, * POBJECT_ATTRIBUTES;
91
92
typedef LONG KPRIORITY;
93
94
typedef struct _PEB_LDR_DATA
95
{
96
ULONG Length;
97
BOOLEAN Initialized;
98
HANDLE SsHandle;
99
LIST_ENTRY InLoadOrderModuleList;
100
LIST_ENTRY InMemoryOrderModuleList;
101
LIST_ENTRY InInitializationOrderModuleList;
102
PVOID EntryInProgress;
103
BOOLEAN ShutdownInProgress;
104
HANDLE ShutdownThreadId;
105
} PEB_LDR_DATA, * PPEB_LDR_DATA;
106
107
typedef struct _STRING
108
{
109
USHORT Length;
110
USHORT MaximumLength;
111
_Field_size_bytes_part_opt_(MaximumLength, Length) PCHAR Buffer;
112
} STRING, * PSTRING, ANSI_STRING, * PANSI_STRING, OEM_STRING, * POEM_STRING;
113
114
typedef struct _RTL_DRIVE_LETTER_CURDIR
115
{
116
USHORT Flags;
117
USHORT Length;
118
ULONG TimeStamp;
119
STRING DosPath;
120
} RTL_DRIVE_LETTER_CURDIR, * PRTL_DRIVE_LETTER_CURDIR;
121
122
typedef struct _CURDIR
123
{
124
UNICODE_STRING DosPath;
125
HANDLE Handle;
126
} CURDIR, * PCURDIR;
127
128
#define RTL_MAX_DRIVE_LETTERS 32
129
130
typedef struct _RTL_USER_PROCESS_PARAMETERS
131
{
132
ULONG MaximumLength;
133
ULONG Length;
134
135
ULONG Flags;
136
ULONG DebugFlags;
137
138
HANDLE ConsoleHandle;
139
ULONG ConsoleFlags;
140
HANDLE StandardInput;
141
HANDLE StandardOutput;
142
HANDLE StandardError;
143
144
CURDIR CurrentDirectory;
145
UNICODE_STRING DllPath;
146
UNICODE_STRING ImagePathName;
147
UNICODE_STRING CommandLine;
148
PVOID Environment;
149
150
ULONG StartingX;
151
ULONG StartingY;
152
ULONG CountX;
153
ULONG CountY;
154
ULONG CountCharsX;
155
ULONG CountCharsY;
156
ULONG FillAttribute;
157
158
ULONG WindowFlags;
159
ULONG ShowWindowFlags;
160
UNICODE_STRING WindowTitle;
161
UNICODE_STRING DesktopInfo;
162
UNICODE_STRING ShellInfo;
163
UNICODE_STRING RuntimeData;
164
RTL_DRIVE_LETTER_CURDIR CurrentDirectories[RTL_MAX_DRIVE_LETTERS];
165
166
ULONG_PTR EnvironmentSize;
167
ULONG_PTR EnvironmentVersion;
168
PVOID PackageDependencyData;
169
ULONG ProcessGroupId;
170
ULONG LoaderThreads;
171
172
UNICODE_STRING RedirectionDllName; // REDSTONE4
173
UNICODE_STRING HeapPartitionName; // 19H1
174
ULONG_PTR DefaultThreadpoolCpuSetMasks;
175
ULONG DefaultThreadpoolCpuSetMaskCount;
176
} RTL_USER_PROCESS_PARAMETERS, * PRTL_USER_PROCESS_PARAMETERS;
177
178
typedef struct _API_SET_NAMESPACE
179
{
180
ULONG Version;
181
ULONG Size;
182
ULONG Flags;
183
ULONG Count;
184
ULONG EntryOffset;
185
ULONG HashOffset;
186
ULONG HashFactor;
187
} API_SET_NAMESPACE, * PAPI_SET_NAMESPACE;
188
189
#define GDI_HANDLE_BUFFER_SIZE32 34
190
#define GDI_HANDLE_BUFFER_SIZE64 60
191
192
#ifndef _WIN64
193
#define GDI_HANDLE_BUFFER_SIZE GDI_HANDLE_BUFFER_SIZE32
194
#else
195
#define GDI_HANDLE_BUFFER_SIZE GDI_HANDLE_BUFFER_SIZE64
196
#endif
197
198
typedef ULONG GDI_HANDLE_BUFFER[GDI_HANDLE_BUFFER_SIZE];
199
200
typedef struct _PEB
201
{
202
BOOLEAN InheritedAddressSpace;
203
BOOLEAN ReadImageFileExecOptions;
204
BOOLEAN BeingDebugged;
205
union
206
{
207
BOOLEAN BitField;
208
struct
209
{
210
BOOLEAN ImageUsesLargePages : 1;
211
BOOLEAN IsProtectedProcess : 1;
212
BOOLEAN IsImageDynamicallyRelocated : 1;
213
BOOLEAN SkipPatchingUser32Forwarders : 1;
214
BOOLEAN IsPackagedProcess : 1;
215
BOOLEAN IsAppContainer : 1;
216
BOOLEAN IsProtectedProcessLight : 1;
217
BOOLEAN IsLongPathAwareProcess : 1;
218
};
219
};
220
221
HANDLE Mutant;
222
223
PVOID ImageBaseAddress;
224
PPEB_LDR_DATA Ldr;
225
PRTL_USER_PROCESS_PARAMETERS ProcessParameters;
226
PVOID SubSystemData;
227
PVOID ProcessHeap;
228
PRTL_CRITICAL_SECTION FastPebLock;
229
PVOID IFEOKey;
230
PSLIST_HEADER AtlThunkSListPtr;
231
union
232
{
233
ULONG CrossProcessFlags;
234
struct
235
{
236
ULONG ProcessInJob : 1;
237
ULONG ProcessInitializing : 1;
238
ULONG ProcessUsingVEH : 1;
239
ULONG ProcessUsingVCH : 1;
240
ULONG ProcessUsingFTH : 1;
241
ULONG ProcessPreviouslyThrottled : 1;
242
ULONG ProcessCurrentlyThrottled : 1;
243
ULONG ProcessImagesHotPatched : 1; // REDSTONE5
244
ULONG ReservedBits0 : 24;
245
};
246
};
247
union
248
{
249
PVOID KernelCallbackTable;
250
PVOID UserSharedInfoPtr;
251
};
252
ULONG SystemReserved;
253
ULONG AtlThunkSListPtr32;
254
PAPI_SET_NAMESPACE ApiSetMap;
255
ULONG TlsExpansionCounter;
256
PVOID TlsBitmap;
257
ULONG TlsBitmapBits[2];
258
259
PVOID ReadOnlySharedMemoryBase;
260
PVOID SharedData; // HotpatchInformation
261
PVOID* ReadOnlyStaticServerData;
262
263
PVOID AnsiCodePageData; // PCPTABLEINFO
264
PVOID OemCodePageData; // PCPTABLEINFO
265
PVOID UnicodeCaseTableData; // PNLSTABLEINFO
266
267
ULONG NumberOfProcessors;
268
ULONG NtGlobalFlag;
269
270
ULARGE_INTEGER CriticalSectionTimeout;
271
SIZE_T HeapSegmentReserve;
272
SIZE_T HeapSegmentCommit;
273
SIZE_T HeapDeCommitTotalFreeThreshold;
274
SIZE_T HeapDeCommitFreeBlockThreshold;
275
276
ULONG NumberOfHeaps;
277
ULONG MaximumNumberOfHeaps;
278
PVOID* ProcessHeaps; // PHEAP
279
280
PVOID GdiSharedHandleTable;
281
PVOID ProcessStarterHelper;
282
ULONG GdiDCAttributeList;
283
284
PRTL_CRITICAL_SECTION LoaderLock;
285
286
ULONG OSMajorVersion;
287
ULONG OSMinorVersion;
288
USHORT OSBuildNumber;
289
USHORT OSCSDVersion;
290
ULONG OSPlatformId;
291
ULONG ImageSubsystem;
292
ULONG ImageSubsystemMajorVersion;
293
ULONG ImageSubsystemMinorVersion;
294
ULONG_PTR ActiveProcessAffinityMask;
295
GDI_HANDLE_BUFFER GdiHandleBuffer;
296
PVOID PostProcessInitRoutine;
297
298
PVOID TlsExpansionBitmap;
299
ULONG TlsExpansionBitmapBits[32];
300
301
ULONG SessionId;
302
303
ULARGE_INTEGER AppCompatFlags;
304
ULARGE_INTEGER AppCompatFlagsUser;
305
PVOID pShimData;
306
PVOID AppCompatInfo; // APPCOMPAT_EXE_DATA
307
308
UNICODE_STRING CSDVersion;
309
310
PVOID ActivationContextData; // ACTIVATION_CONTEXT_DATA
311
PVOID ProcessAssemblyStorageMap; // ASSEMBLY_STORAGE_MAP
312
PVOID SystemDefaultActivationContextData; // ACTIVATION_CONTEXT_DATA
313
PVOID SystemAssemblyStorageMap; // ASSEMBLY_STORAGE_MAP
314
315
SIZE_T MinimumStackCommit;
316
317
PVOID SparePointers[4]; // 19H1 (previously FlsCallback to FlsHighIndex)
318
ULONG SpareUlongs[5]; // 19H1
319
//PVOID* FlsCallback;
320
//LIST_ENTRY FlsListHead;
321
//PVOID FlsBitmap;
322
//ULONG FlsBitmapBits[FLS_MAXIMUM_AVAILABLE / (sizeof(ULONG) * 8)];
323
//ULONG FlsHighIndex;
324
325
PVOID WerRegistrationData;
326
PVOID WerShipAssertPtr;
327
PVOID pUnused; // pContextData
328
PVOID pImageHeaderHash;
329
union
330
{
331
ULONG TracingFlags;
332
struct
333
{
334
ULONG HeapTracingEnabled : 1;
335
ULONG CritSecTracingEnabled : 1;
336
ULONG LibLoaderTracingEnabled : 1;
337
ULONG SpareTracingBits : 29;
338
};
339
};
340
ULONGLONG CsrServerReadOnlySharedMemoryBase;
341
PRTL_CRITICAL_SECTION TppWorkerpListLock;
342
LIST_ENTRY TppWorkerpList;
343
PVOID WaitOnAddressHashTable[128];
344
PVOID TelemetryCoverageHeader; // REDSTONE3
345
ULONG CloudFileFlags;
346
ULONG CloudFileDiagFlags; // REDSTONE4
347
CHAR PlaceholderCompatibilityMode;
348
CHAR PlaceholderCompatibilityModeReserved[7];
349
struct _LEAP_SECOND_DATA* LeapSecondData; // REDSTONE5
350
union
351
{
352
ULONG LeapSecondFlags;
353
struct
354
{
355
ULONG SixtySecondEnabled : 1;
356
ULONG Reserved : 31;
357
};
358
};
359
ULONG NtGlobalFlag2;
360
} PEB, * PPEB;
361
362
typedef struct _PROCESS_BASIC_INFORMATION
363
{
364
NTSTATUS ExitStatus;
365
PPEB PebBaseAddress;
366
ULONG_PTR AffinityMask;
367
KPRIORITY BasePriority;
368
HANDLE UniqueProcessId;
369
HANDLE InheritedFromUniqueProcessId;
370
} PROCESS_BASIC_INFORMATION, * PPROCESS_BASIC_INFORMATION;
371
372
typedef struct _PS_ATTRIBUTE
373
{
374
ULONG_PTR Attribute;
375
SIZE_T Size;
376
union
377
{
378
ULONG_PTR Value;
379
PVOID ValuePtr;
380
};
381
PSIZE_T ReturnLength;
382
} PS_ATTRIBUTE, * PPS_ATTRIBUTE;
383
384
typedef struct _PS_ATTRIBUTE_LIST
385
{
386
SIZE_T TotalLength;
387
PS_ATTRIBUTE Attributes[1];
388
} PS_ATTRIBUTE_LIST, * PPS_ATTRIBUTE_LIST;
389
390
typedef struct _CLIENT_ID
391
{
392
HANDLE UniqueProcess;
393
HANDLE UniqueThread;
394
} CLIENT_ID, * PCLIENT_ID;
395
396
typedef struct _ACTIVATION_CONTEXT_STACK
397
{
398
struct _RTL_ACTIVATION_CONTEXT_STACK_FRAME* ActiveFrame;
399
LIST_ENTRY FrameListCache;
400
ULONG Flags;
401
ULONG NextCookieSequenceNumber;
402
ULONG StackId;
403
} ACTIVATION_CONTEXT_STACK, * PACTIVATION_CONTEXT_STACK;
404
405
#define GDI_BATCH_BUFFER_SIZE 310
406
407
typedef struct _GDI_TEB_BATCH
408
{
409
ULONG Offset;
410
ULONG_PTR HDC;
411
ULONG Buffer[GDI_BATCH_BUFFER_SIZE];
412
} GDI_TEB_BATCH, * PGDI_TEB_BATCH;
413
414
typedef struct _TEB_ACTIVE_FRAME_CONTEXT
415
{
416
ULONG Flags;
417
PSTR FrameName;
418
} TEB_ACTIVE_FRAME_CONTEXT, * PTEB_ACTIVE_FRAME_CONTEXT;
419
420
typedef struct _TEB_ACTIVE_FRAME
421
{
422
ULONG Flags;
423
struct _TEB_ACTIVE_FRAME* Previous;
424
PTEB_ACTIVE_FRAME_CONTEXT Context;
425
} TEB_ACTIVE_FRAME, * PTEB_ACTIVE_FRAME;
426
427
typedef struct _TEB
428
{
429
NT_TIB NtTib;
430
431
PVOID EnvironmentPointer;
432
CLIENT_ID ClientId;
433
PVOID ActiveRpcHandle;
434
PVOID ThreadLocalStoragePointer;
435
PPEB ProcessEnvironmentBlock;
436
437
ULONG LastErrorValue;
438
ULONG CountOfOwnedCriticalSections;
439
PVOID CsrClientThread;
440
PVOID Win32ThreadInfo;
441
ULONG User32Reserved[26];
442
ULONG UserReserved[5];
443
PVOID WOW32Reserved;
444
LCID CurrentLocale;
445
ULONG FpSoftwareStatusRegister;
446
PVOID ReservedForDebuggerInstrumentation[16];
447
#ifdef _WIN64
448
PVOID SystemReserved1[30];
449
#else
450
PVOID SystemReserved1[26];
451
#endif
452
453
CHAR PlaceholderCompatibilityMode;
454
CHAR PlaceholderReserved[11];
455
ULONG ProxiedProcessId;
456
ACTIVATION_CONTEXT_STACK ActivationStack;
457
458
UCHAR WorkingOnBehalfTicket[8];
459
NTSTATUS ExceptionCode;
460
461
PACTIVATION_CONTEXT_STACK ActivationContextStackPointer;
462
ULONG_PTR InstrumentationCallbackSp;
463
ULONG_PTR InstrumentationCallbackPreviousPc;
464
ULONG_PTR InstrumentationCallbackPreviousSp;
465
#ifdef _WIN64
466
ULONG TxFsContext;
467
#endif
468
469
BOOLEAN InstrumentationCallbackDisabled;
470
#ifndef _WIN64
471
UCHAR SpareBytes[23];
472
ULONG TxFsContext;
473
#endif
474
GDI_TEB_BATCH GdiTebBatch;
475
CLIENT_ID RealClientId;
476
HANDLE GdiCachedProcessHandle;
477
ULONG GdiClientPID;
478
ULONG GdiClientTID;
479
PVOID GdiThreadLocalInfo;
480
ULONG_PTR Win32ClientInfo[62];
481
PVOID glDispatchTable[233];
482
ULONG_PTR glReserved1[29];
483
PVOID glReserved2;
484
PVOID glSectionInfo;
485
PVOID glSection;
486
PVOID glTable;
487
PVOID glCurrentRC;
488
PVOID glContext;
489
490
NTSTATUS LastStatusValue;
491
UNICODE_STRING StaticUnicodeString;
492
WCHAR StaticUnicodeBuffer[261];
493
494
PVOID DeallocationStack;
495
PVOID TlsSlots[64];
496
LIST_ENTRY TlsLinks;
497
498
PVOID Vdm;
499
PVOID ReservedForNtRpc;
500
PVOID DbgSsReserved[2];
501
502
ULONG HardErrorMode;
503
#ifdef _WIN64
504
PVOID Instrumentation[11];
505
#else
506
PVOID Instrumentation[9];
507
#endif
508
GUID ActivityId;
509
510
PVOID SubProcessTag;
511
PVOID PerflibData;
512
PVOID EtwTraceData;
513
PVOID WinSockData;
514
ULONG GdiBatchCount;
515
516
union
517
{
518
PROCESSOR_NUMBER CurrentIdealProcessor;
519
ULONG IdealProcessorValue;
520
struct
521
{
522
UCHAR ReservedPad0;
523
UCHAR ReservedPad1;
524
UCHAR ReservedPad2;
525
UCHAR IdealProcessor;
526
};
527
};
528
529
ULONG GuaranteedStackBytes;
530
PVOID ReservedForPerf;
531
PVOID ReservedForOle;
532
ULONG WaitingOnLoaderLock;
533
PVOID SavedPriorityState;
534
ULONG_PTR ReservedForCodeCoverage;
535
PVOID ThreadPoolData;
536
PVOID* TlsExpansionSlots;
537
#ifdef _WIN64
538
PVOID DeallocationBStore;
539
PVOID BStoreLimit;
540
#endif
541
ULONG MuiGeneration;
542
ULONG IsImpersonating;
543
PVOID NlsCache;
544
PVOID pShimData;
545
USHORT HeapVirtualAffinity;
546
USHORT LowFragHeapDataSlot;
547
HANDLE CurrentTransactionHandle;
548
PTEB_ACTIVE_FRAME ActiveFrame;
549
PVOID FlsData;
550
551
PVOID PreferredLanguages;
552
PVOID UserPrefLanguages;
553
PVOID MergedPrefLanguages;
554
ULONG MuiImpersonation;
555
556
union
557
{
558
USHORT CrossTebFlags;
559
USHORT SpareCrossTebBits : 16;
560
};
561
union
562
{
563
USHORT SameTebFlags;
564
struct
565
{
566
USHORT SafeThunkCall : 1;
567
USHORT InDebugPrint : 1;
568
USHORT HasFiberData : 1;
569
USHORT SkipThreadAttach : 1;
570
USHORT WerInShipAssertCode : 1;
571
USHORT RanProcessInit : 1;
572
USHORT ClonedThread : 1;
573
USHORT SuppressDebugMsg : 1;
574
USHORT DisableUserStackWalk : 1;
575
USHORT RtlExceptionAttached : 1;
576
USHORT InitialThread : 1;
577
USHORT SessionAware : 1;
578
USHORT LoadOwner : 1;
579
USHORT LoaderWorker : 1;
580
USHORT SkipLoaderInit : 1;
581
USHORT SpareSameTebBits : 1;
582
};
583
};
584
585
PVOID TxnScopeEnterCallback;
586
PVOID TxnScopeExitCallback;
587
PVOID TxnScopeContext;
588
ULONG LockCount;
589
LONG WowTebOffset;
590
PVOID ResourceRetValue;
591
PVOID ReservedForWdf;
592
ULONGLONG ReservedForCrt;
593
GUID EffectiveContainerId;
594
} TEB, * PTEB;
595
596
#define NtCurrentProcess() ((HANDLE)(LONG_PTR)-1)
597
#define NtCurrentPeb() (NtCurrentTeb()->ProcessEnvironmentBlock)
598
599
#define PROCESS_CREATE_FLAGS_INHERIT_HANDLES 0x00000004
600
601
typedef enum _PROCESSINFOCLASS
602
{
603
ProcessBasicInformation, // q: PROCESS_BASIC_INFORMATION, PROCESS_EXTENDED_BASIC_INFORMATION
604
ProcessQuotaLimits, // qs: QUOTA_LIMITS, QUOTA_LIMITS_EX
605
ProcessIoCounters, // q: IO_COUNTERS
606
ProcessVmCounters, // q: VM_COUNTERS, VM_COUNTERS_EX, VM_COUNTERS_EX2
607
ProcessTimes, // q: KERNEL_USER_TIMES
608
ProcessBasePriority, // s: KPRIORITY
609
ProcessRaisePriority, // s: ULONG
610
ProcessDebugPort, // q: HANDLE
611
ProcessExceptionPort, // s: PROCESS_EXCEPTION_PORT
612
ProcessAccessToken, // s: PROCESS_ACCESS_TOKEN
613
ProcessLdtInformation, // qs: PROCESS_LDT_INFORMATION // 10
614
ProcessLdtSize, // s: PROCESS_LDT_SIZE
615
ProcessDefaultHardErrorMode, // qs: ULONG
616
ProcessIoPortHandlers, // (kernel-mode only)
617
ProcessPooledUsageAndLimits, // q: POOLED_USAGE_AND_LIMITS
618
ProcessWorkingSetWatch, // q: PROCESS_WS_WATCH_INFORMATION[]; s: void
619
ProcessUserModeIOPL,
620
ProcessEnableAlignmentFaultFixup, // s: BOOLEAN
621
ProcessPriorityClass, // qs: PROCESS_PRIORITY_CLASS
622
ProcessWx86Information,
623
ProcessHandleCount, // q: ULONG, PROCESS_HANDLE_INFORMATION // 20
624
ProcessAffinityMask, // s: KAFFINITY
625
ProcessPriorityBoost, // qs: ULONG
626
ProcessDeviceMap, // qs: PROCESS_DEVICEMAP_INFORMATION, PROCESS_DEVICEMAP_INFORMATION_EX
627
ProcessSessionInformation, // q: PROCESS_SESSION_INFORMATION
628
ProcessForegroundInformation, // s: PROCESS_FOREGROUND_BACKGROUND
629
ProcessWow64Information, // q: ULONG_PTR
630
ProcessImageFileName, // q: UNICODE_STRING
631
ProcessLUIDDeviceMapsEnabled, // q: ULONG
632
ProcessBreakOnTermination, // qs: ULONG
633
ProcessDebugObjectHandle, // q: HANDLE // 30
634
ProcessDebugFlags, // qs: ULONG
635
ProcessHandleTracing, // q: PROCESS_HANDLE_TRACING_QUERY; s: size 0 disables, otherwise enables
636
ProcessIoPriority, // qs: IO_PRIORITY_HINT
637
ProcessExecuteFlags, // qs: ULONG
638
ProcessResourceManagement, // ProcessTlsInformation // PROCESS_TLS_INFORMATION
639
ProcessCookie, // q: ULONG
640
ProcessImageInformation, // q: SECTION_IMAGE_INFORMATION
641
ProcessCycleTime, // q: PROCESS_CYCLE_TIME_INFORMATION // since VISTA
642
ProcessPagePriority, // q: PAGE_PRIORITY_INFORMATION
643
ProcessInstrumentationCallback, // qs: PROCESS_INSTRUMENTATION_CALLBACK_INFORMATION // 40
644
ProcessThreadStackAllocation, // s: PROCESS_STACK_ALLOCATION_INFORMATION, PROCESS_STACK_ALLOCATION_INFORMATION_EX
645
ProcessWorkingSetWatchEx, // q: PROCESS_WS_WATCH_INFORMATION_EX[]
646
ProcessImageFileNameWin32, // q: UNICODE_STRING
647
ProcessImageFileMapping, // q: HANDLE (input)
648
ProcessAffinityUpdateMode, // qs: PROCESS_AFFINITY_UPDATE_MODE
649
ProcessMemoryAllocationMode, // qs: PROCESS_MEMORY_ALLOCATION_MODE
650
ProcessGroupInformation, // q: USHORT[]
651
ProcessTokenVirtualizationEnabled, // s: ULONG
652
ProcessConsoleHostProcess, // q: ULONG_PTR // ProcessOwnerInformation
653
ProcessWindowInformation, // q: PROCESS_WINDOW_INFORMATION // 50
654
ProcessHandleInformation, // q: PROCESS_HANDLE_SNAPSHOT_INFORMATION // since WIN8
655
ProcessMitigationPolicy, // s: PROCESS_MITIGATION_POLICY_INFORMATION
656
ProcessDynamicFunctionTableInformation,
657
ProcessHandleCheckingMode, // qs: ULONG; s: 0 disables, otherwise enables
658
ProcessKeepAliveCount, // q: PROCESS_KEEPALIVE_COUNT_INFORMATION
659
ProcessRevokeFileHandles, // s: PROCESS_REVOKE_FILE_HANDLES_INFORMATION
660
ProcessWorkingSetControl, // s: PROCESS_WORKING_SET_CONTROL
661
ProcessHandleTable, // q: ULONG[] // since WINBLUE
662
ProcessCheckStackExtentsMode,
663
ProcessCommandLineInformation, // q: UNICODE_STRING // 60
664
ProcessProtectionInformation, // q: PS_PROTECTION
665
ProcessMemoryExhaustion, // PROCESS_MEMORY_EXHAUSTION_INFO // since THRESHOLD
666
ProcessFaultInformation, // PROCESS_FAULT_INFORMATION
667
ProcessTelemetryIdInformation, // PROCESS_TELEMETRY_ID_INFORMATION
668
ProcessCommitReleaseInformation, // PROCESS_COMMIT_RELEASE_INFORMATION
669
ProcessDefaultCpuSetsInformation,
670
ProcessAllowedCpuSetsInformation,
671
ProcessSubsystemProcess,
672
ProcessJobMemoryInformation, // PROCESS_JOB_MEMORY_INFO
673
ProcessInPrivate, // since THRESHOLD2 // 70
674
ProcessRaiseUMExceptionOnInvalidHandleClose, // qs: ULONG; s: 0 disables, otherwise enables
675
ProcessIumChallengeResponse,
676
ProcessChildProcessInformation, // PROCESS_CHILD_PROCESS_INFORMATION
677
ProcessHighGraphicsPriorityInformation,
678
ProcessSubsystemInformation, // q: SUBSYSTEM_INFORMATION_TYPE // since REDSTONE2
679
ProcessEnergyValues, // PROCESS_ENERGY_VALUES, PROCESS_EXTENDED_ENERGY_VALUES
680
ProcessActivityThrottleState, // PROCESS_ACTIVITY_THROTTLE_STATE
681
ProcessActivityThrottlePolicy, // PROCESS_ACTIVITY_THROTTLE_POLICY
682
ProcessWin32kSyscallFilterInformation,
683
ProcessDisableSystemAllowedCpuSets, // 80
684
ProcessWakeInformation, // PROCESS_WAKE_INFORMATION
685
ProcessEnergyTrackingState, // PROCESS_ENERGY_TRACKING_STATE
686
ProcessManageWritesToExecutableMemory, // MANAGE_WRITES_TO_EXECUTABLE_MEMORY // since REDSTONE3
687
ProcessCaptureTrustletLiveDump,
688
ProcessTelemetryCoverage,
689
ProcessEnclaveInformation,
690
ProcessEnableReadWriteVmLogging, // PROCESS_READWRITEVM_LOGGING_INFORMATION
691
ProcessUptimeInformation, // PROCESS_UPTIME_INFORMATION
692
ProcessImageSection, // q: HANDLE
693
ProcessDebugAuthInformation, // since REDSTONE4 // 90
694
ProcessSystemResourceManagement, // PROCESS_SYSTEM_RESOURCE_MANAGEMENT
695
ProcessSequenceNumber, // q: ULONGLONG
696
ProcessLoaderDetour, // since REDSTONE5
697
ProcessSecurityDomainInformation, // PROCESS_SECURITY_DOMAIN_INFORMATION
698
ProcessCombineSecurityDomainsInformation, // PROCESS_COMBINE_SECURITY_DOMAINS_INFORMATION
699
ProcessEnableLogging, // PROCESS_LOGGING_INFORMATION
700
ProcessLeapSecondInformation, // PROCESS_LEAP_SECOND_INFORMATION
701
ProcessFiberShadowStackAllocation, // PROCESS_FIBER_SHADOW_STACK_ALLOCATION_INFORMATION // since 19H1
702
ProcessFreeFiberShadowStackAllocation, // PROCESS_FREE_FIBER_SHADOW_STACK_ALLOCATION_INFORMATION
703
MaxProcessInfoClass
704
} PROCESSINFOCLASS;
705
706
707
NTSYSCALLAPI
708
NTSTATUS
709
NTAPI
710
NtCreateSection(
711
_Out_ PHANDLE SectionHandle,
712
_In_ ACCESS_MASK DesiredAccess,
713
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
714
_In_opt_ PLARGE_INTEGER MaximumSize,
715
_In_ ULONG SectionPageProtection,
716
_In_ ULONG AllocationAttributes,
717
_In_opt_ HANDLE FileHandle
718
);
719
720
NTSYSCALLAPI
721
NTSTATUS
722
NTAPI
723
NtCreateProcessEx(
724
_Out_ PHANDLE ProcessHandle,
725
_In_ ACCESS_MASK DesiredAccess,
726
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
727
_In_ HANDLE ParentProcess,
728
_In_ ULONG Flags,
729
_In_opt_ HANDLE SectionHandle,
730
_In_opt_ HANDLE DebugPort,
731
_In_opt_ HANDLE ExceptionPort,
732
_In_ ULONG JobMemberLevel
733
);
734
735
NTSYSCALLAPI
736
NTSTATUS
737
NTAPI
738
NtQueryInformationProcess(
739
_In_ HANDLE ProcessHandle,
740
_In_ PROCESSINFOCLASS ProcessInformationClass,
741
_Out_writes_bytes_(ProcessInformationLength) PVOID ProcessInformation,
742
_In_ ULONG ProcessInformationLength,
743
_Out_opt_ PULONG ReturnLength
744
);
745
746
NTSYSCALLAPI
747
NTSTATUS
748
NTAPI
749
NtClose(
750
_In_ HANDLE Handle
751
);
752
753
NTSYSCALLAPI
754
NTSTATUS
755
NTAPI
756
NtCreateThreadEx(
757
_Out_ PHANDLE ThreadHandle,
758
_In_ ACCESS_MASK DesiredAccess,
759
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
760
_In_ HANDLE ProcessHandle,
761
_In_ PVOID StartRoutine, // PUSER_THREAD_START_ROUTINE
762
_In_opt_ PVOID Argument,
763
_In_ ULONG CreateFlags, // THREAD_CREATE_FLAGS_*
764
_In_ SIZE_T ZeroBits,
765
_In_ SIZE_T StackSize,
766
_In_ SIZE_T MaximumStackSize,
767
_In_opt_ PPS_ATTRIBUTE_LIST AttributeList
768
);
769
770
FORCEINLINE VOID RtlInitUnicodeString(
771
_Out_ PUNICODE_STRING DestinationString,
772
_In_opt_ PCWSTR SourceString
773
)
774
{
775
if (SourceString)
776
DestinationString->MaximumLength = (DestinationString->Length = (USHORT)(wcslen(SourceString) * sizeof(WCHAR))) + sizeof(UNICODE_NULL);
777
else
778
DestinationString->MaximumLength = DestinationString->Length = 0;
779
780
DestinationString->Buffer = (PWCH)SourceString;
781
}
782
783
NTSYSAPI
784
NTSTATUS
785
NTAPI
786
RtlCreateProcessParametersEx(
787
_Out_ PRTL_USER_PROCESS_PARAMETERS* pProcessParameters,
788
_In_ PUNICODE_STRING ImagePathName,
789
_In_opt_ PUNICODE_STRING DllPath,
790
_In_opt_ PUNICODE_STRING CurrentDirectory,
791
_In_opt_ PUNICODE_STRING CommandLine,
792
_In_opt_ PVOID Environment,
793
_In_opt_ PUNICODE_STRING WindowTitle,
794
_In_opt_ PUNICODE_STRING DesktopInfo,
795
_In_opt_ PUNICODE_STRING ShellInfo,
796
_In_opt_ PUNICODE_STRING RuntimeData,
797
_In_ ULONG Flags // pass RTL_USER_PROC_PARAMS_NORMALIZED to keep parameters normalized
798
);
799
800
NTSYSAPI
801
NTSTATUS
802
NTAPI
803
RtlDestroyProcessParameters(
804
_In_ _Post_invalid_ PRTL_USER_PROCESS_PARAMETERS ProcessParameters
805
);
806
807
#ifdef __cplusplus
808
}
809
#endif
810
811
#pragma warning(pop)
812
813
class AutoCloseHandle
814
{
815
public:
816
AutoCloseHandle(BOOL isNTHandle = FALSE) :
817
m_handle(INVALID_HANDLE_VALUE),
818
m_isNTHandle(isNTHandle)
819
{}
820
821
~AutoCloseHandle()
822
{
823
if (!valid())
824
{
825
return;
826
}
827
if (m_isNTHandle)
828
{
829
NTSTATUS status = NtClose(m_handle);
830
if (!NT_SUCCESS(status))
831
{
832
dprintf("[AutoCloseHandle] Error when closing the NT handle (NTSTATUS: %d)", status);
833
}
834
}
835
else
836
{
837
if (CloseHandle(m_handle) == 0)
838
{
839
dprintf("[AutoCloseHandle] Error when closing handle (%d)", GetLastError());
840
}
841
}
842
m_handle = INVALID_HANDLE_VALUE;
843
}
844
845
HANDLE& get()
846
{
847
return m_handle;
848
}
849
850
void close()
851
{
852
this->~AutoCloseHandle();
853
}
854
855
BOOL valid()
856
{
857
return (m_handle != NULL) && (m_handle != INVALID_HANDLE_VALUE);
858
}
859
private:
860
HANDLE m_handle;
861
BOOL m_isNTHandle;
862
};
863
864
865
class ProcessHandle
866
{
867
public:
868
ProcessHandle() :
869
m_processHandle(),
870
m_terminate(TRUE)
871
{}
872
873
~ProcessHandle()
874
{
875
if (m_processHandle.valid())
876
{
877
if (m_terminate)
878
{
879
if (TerminateProcess(m_processHandle.get(), 0) == 0)
880
{
881
dprintf("Error when terminating process (%d)", GetLastError());
882
}
883
m_terminate = FALSE;
884
}
885
m_processHandle.close();
886
}
887
}
888
889
BOOL& terminate()
890
{
891
return m_terminate;
892
}
893
894
HANDLE& get()
895
{
896
return m_processHandle.get();
897
}
898
899
BOOL valid()
900
{
901
return m_processHandle.valid();
902
}
903
904
private:
905
AutoCloseHandle m_processHandle;
906
BOOL m_terminate;
907
};
908
909
class FileHandle
910
{
911
public:
912
FileHandle(std::wstring fileName = L"", BOOL p_remove = FALSE) :
913
m_fileHandle(),
914
m_fileName(fileName),
915
m_remove(p_remove)
916
{}
917
918
~FileHandle()
919
{
920
if (m_fileHandle.valid())
921
{
922
m_fileHandle.close();
923
}
924
if (m_remove)
925
{
926
dprintf("[FileHandle] Remove file %S", m_fileName.c_str());
927
if (DeleteFileW(m_fileName.c_str()) == 0)
928
{
929
dprintf("[FileHandle] Failed to delete the file %S (0x%d)", m_fileName.c_str(), GetLastError());
930
}
931
m_remove = FALSE;
932
}
933
}
934
935
BOOL& remove()
936
{
937
return m_remove;
938
}
939
940
HANDLE& get()
941
{
942
return m_fileHandle.get();
943
}
944
945
BOOL valid()
946
{
947
return m_fileHandle.valid();
948
}
949
950
void close()
951
{
952
m_fileHandle.close();
953
}
954
private:
955
AutoCloseHandle m_fileHandle;
956
BOOL m_remove;
957
std::wstring m_fileName;
958
};
959
960
961
class MappingHandle
962
{
963
public:
964
MappingHandle() :
965
m_mappingHandle(),
966
m_view(nullptr)
967
{}
968
969
~MappingHandle()
970
{
971
if (m_view != nullptr)
972
{
973
dprintf("[MappingHandle] Unmapping view");
974
if (UnmapViewOfFile(m_view) == 0)
975
{
976
dprintf("[MappingHandle] Unmap view error (0x%x)", GetLastError());
977
}
978
m_view = nullptr;
979
}
980
if (m_mappingHandle.valid())
981
{
982
m_mappingHandle.close();
983
}
984
}
985
986
HANDLE& get()
987
{
988
return m_mappingHandle.get();
989
}
990
991
BOOL valid()
992
{
993
return m_mappingHandle.valid();
994
}
995
996
void close()
997
{
998
this->~MappingHandle();
999
}
1000
1001
LPVOID& view()
1002
{
1003
return m_view;
1004
}
1005
1006
private:
1007
AutoCloseHandle m_mappingHandle;
1008
LPVOID m_view;
1009
};
1010
1011