Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Path: blob/master/external/source/evasion/windows/process_herpaderping/ProcessHerpaderping/pch.hpp
Views: 11788
#pragma once12//3// Windows4//5#define WIN32_LEAN_AND_MEAN6#define WIN32_NO_STATUS7#include <Windows.h>8#undef WIN32_NO_STATUS9#include <ntstatus.h>10#include <strsafe.h>11#include <winioctl.h>12#include <bcrypt.h>1314//15// STL16//17#include <iomanip>18#include <sstream>19#include <vector>20#include <optional>21#include <span>2223//24// Common Macros/Defines/Usings25//26#define SCAST(_X_) static_cast<_X_>27#define RCAST(_X_) reinterpret_cast<_X_>28#define Add2Ptr(_P_, _X_) RCAST(void*)(RCAST(uintptr_t)(_P_) + _X_)2930using handle_t = HANDLE;3132#define _REPORT(msg, err) dprintf(msg " (%S)", Utils::FormatError(err).c_str())33#define REPORT_AND_RETURN_WIN32(message, win32err) _REPORT(message, win32err); return HRESULT_FROM_WIN32(win32err);34#define REPORT_AND_RETURN_NT(message, status) _REPORT(message, status); return HRESULT_FROM_NT(status);35#define REPORT_AND_RETURN_HR(message, hr) _REPORT(message, hr); return hr;36//37// prefast suppression38//39#pragma warning(disable : 6319) // prefast: use of the comma-operator in a tested expression4041#ifdef DEBUGTRACE42#define dprintf(...) real_dprintf(__VA_ARGS__)43static void real_dprintf(const char* format, ...)44{45va_list args;46char buffer[1024];47va_start(args, format);48vsnprintf_s(buffer, sizeof(buffer), sizeof(buffer) - 3, format, args);49strcat_s(buffer, sizeof(buffer), "\r\n");50OutputDebugStringA(buffer);51va_end(args); // Needed as according to http://www.cplusplus.com/reference/cstdarg/va_start/52// one should always call va_end in the same function one calls va_start.53}54#else55#define dprintf(...)56#endif5758#define FILE_MAX_PATH 2605960#pragma warning(push)61#pragma warning(disable : 4201) // nameless struct/union62#pragma warning(disable : 4324) // structure was padded due to __declspec(align())63#pragma warning(disable : 4471) // a forward declaration of an unscoped enumeration64#pragma warning(disable : 28253) // prefast: inconsistent annotation656667#ifdef __cplusplus68extern "C" {69#endif707172#define NT_SUCCESS(Status) (((NTSTATUS)(Status)) >= 0)7374typedef struct _UNICODE_STRING75{76USHORT Length;77USHORT MaximumLength;78_Field_size_bytes_part_(MaximumLength, Length) PWCH Buffer;79} UNICODE_STRING, * PUNICODE_STRING;8081typedef struct _OBJECT_ATTRIBUTES82{83ULONG Length;84HANDLE RootDirectory;85PUNICODE_STRING ObjectName;86ULONG Attributes;87PVOID SecurityDescriptor; // PSECURITY_DESCRIPTOR;88PVOID SecurityQualityOfService; // PSECURITY_QUALITY_OF_SERVICE89} OBJECT_ATTRIBUTES, * POBJECT_ATTRIBUTES;9091typedef LONG KPRIORITY;9293typedef struct _PEB_LDR_DATA94{95ULONG Length;96BOOLEAN Initialized;97HANDLE SsHandle;98LIST_ENTRY InLoadOrderModuleList;99LIST_ENTRY InMemoryOrderModuleList;100LIST_ENTRY InInitializationOrderModuleList;101PVOID EntryInProgress;102BOOLEAN ShutdownInProgress;103HANDLE ShutdownThreadId;104} PEB_LDR_DATA, * PPEB_LDR_DATA;105106typedef struct _STRING107{108USHORT Length;109USHORT MaximumLength;110_Field_size_bytes_part_opt_(MaximumLength, Length) PCHAR Buffer;111} STRING, * PSTRING, ANSI_STRING, * PANSI_STRING, OEM_STRING, * POEM_STRING;112113typedef struct _RTL_DRIVE_LETTER_CURDIR114{115USHORT Flags;116USHORT Length;117ULONG TimeStamp;118STRING DosPath;119} RTL_DRIVE_LETTER_CURDIR, * PRTL_DRIVE_LETTER_CURDIR;120121typedef struct _CURDIR122{123UNICODE_STRING DosPath;124HANDLE Handle;125} CURDIR, * PCURDIR;126127#define RTL_MAX_DRIVE_LETTERS 32128129typedef struct _RTL_USER_PROCESS_PARAMETERS130{131ULONG MaximumLength;132ULONG Length;133134ULONG Flags;135ULONG DebugFlags;136137HANDLE ConsoleHandle;138ULONG ConsoleFlags;139HANDLE StandardInput;140HANDLE StandardOutput;141HANDLE StandardError;142143CURDIR CurrentDirectory;144UNICODE_STRING DllPath;145UNICODE_STRING ImagePathName;146UNICODE_STRING CommandLine;147PVOID Environment;148149ULONG StartingX;150ULONG StartingY;151ULONG CountX;152ULONG CountY;153ULONG CountCharsX;154ULONG CountCharsY;155ULONG FillAttribute;156157ULONG WindowFlags;158ULONG ShowWindowFlags;159UNICODE_STRING WindowTitle;160UNICODE_STRING DesktopInfo;161UNICODE_STRING ShellInfo;162UNICODE_STRING RuntimeData;163RTL_DRIVE_LETTER_CURDIR CurrentDirectories[RTL_MAX_DRIVE_LETTERS];164165ULONG_PTR EnvironmentSize;166ULONG_PTR EnvironmentVersion;167PVOID PackageDependencyData;168ULONG ProcessGroupId;169ULONG LoaderThreads;170171UNICODE_STRING RedirectionDllName; // REDSTONE4172UNICODE_STRING HeapPartitionName; // 19H1173ULONG_PTR DefaultThreadpoolCpuSetMasks;174ULONG DefaultThreadpoolCpuSetMaskCount;175} RTL_USER_PROCESS_PARAMETERS, * PRTL_USER_PROCESS_PARAMETERS;176177typedef struct _API_SET_NAMESPACE178{179ULONG Version;180ULONG Size;181ULONG Flags;182ULONG Count;183ULONG EntryOffset;184ULONG HashOffset;185ULONG HashFactor;186} API_SET_NAMESPACE, * PAPI_SET_NAMESPACE;187188#define GDI_HANDLE_BUFFER_SIZE32 34189#define GDI_HANDLE_BUFFER_SIZE64 60190191#ifndef _WIN64192#define GDI_HANDLE_BUFFER_SIZE GDI_HANDLE_BUFFER_SIZE32193#else194#define GDI_HANDLE_BUFFER_SIZE GDI_HANDLE_BUFFER_SIZE64195#endif196197typedef ULONG GDI_HANDLE_BUFFER[GDI_HANDLE_BUFFER_SIZE];198199typedef struct _PEB200{201BOOLEAN InheritedAddressSpace;202BOOLEAN ReadImageFileExecOptions;203BOOLEAN BeingDebugged;204union205{206BOOLEAN BitField;207struct208{209BOOLEAN ImageUsesLargePages : 1;210BOOLEAN IsProtectedProcess : 1;211BOOLEAN IsImageDynamicallyRelocated : 1;212BOOLEAN SkipPatchingUser32Forwarders : 1;213BOOLEAN IsPackagedProcess : 1;214BOOLEAN IsAppContainer : 1;215BOOLEAN IsProtectedProcessLight : 1;216BOOLEAN IsLongPathAwareProcess : 1;217};218};219220HANDLE Mutant;221222PVOID ImageBaseAddress;223PPEB_LDR_DATA Ldr;224PRTL_USER_PROCESS_PARAMETERS ProcessParameters;225PVOID SubSystemData;226PVOID ProcessHeap;227PRTL_CRITICAL_SECTION FastPebLock;228PVOID IFEOKey;229PSLIST_HEADER AtlThunkSListPtr;230union231{232ULONG CrossProcessFlags;233struct234{235ULONG ProcessInJob : 1;236ULONG ProcessInitializing : 1;237ULONG ProcessUsingVEH : 1;238ULONG ProcessUsingVCH : 1;239ULONG ProcessUsingFTH : 1;240ULONG ProcessPreviouslyThrottled : 1;241ULONG ProcessCurrentlyThrottled : 1;242ULONG ProcessImagesHotPatched : 1; // REDSTONE5243ULONG ReservedBits0 : 24;244};245};246union247{248PVOID KernelCallbackTable;249PVOID UserSharedInfoPtr;250};251ULONG SystemReserved;252ULONG AtlThunkSListPtr32;253PAPI_SET_NAMESPACE ApiSetMap;254ULONG TlsExpansionCounter;255PVOID TlsBitmap;256ULONG TlsBitmapBits[2];257258PVOID ReadOnlySharedMemoryBase;259PVOID SharedData; // HotpatchInformation260PVOID* ReadOnlyStaticServerData;261262PVOID AnsiCodePageData; // PCPTABLEINFO263PVOID OemCodePageData; // PCPTABLEINFO264PVOID UnicodeCaseTableData; // PNLSTABLEINFO265266ULONG NumberOfProcessors;267ULONG NtGlobalFlag;268269ULARGE_INTEGER CriticalSectionTimeout;270SIZE_T HeapSegmentReserve;271SIZE_T HeapSegmentCommit;272SIZE_T HeapDeCommitTotalFreeThreshold;273SIZE_T HeapDeCommitFreeBlockThreshold;274275ULONG NumberOfHeaps;276ULONG MaximumNumberOfHeaps;277PVOID* ProcessHeaps; // PHEAP278279PVOID GdiSharedHandleTable;280PVOID ProcessStarterHelper;281ULONG GdiDCAttributeList;282283PRTL_CRITICAL_SECTION LoaderLock;284285ULONG OSMajorVersion;286ULONG OSMinorVersion;287USHORT OSBuildNumber;288USHORT OSCSDVersion;289ULONG OSPlatformId;290ULONG ImageSubsystem;291ULONG ImageSubsystemMajorVersion;292ULONG ImageSubsystemMinorVersion;293ULONG_PTR ActiveProcessAffinityMask;294GDI_HANDLE_BUFFER GdiHandleBuffer;295PVOID PostProcessInitRoutine;296297PVOID TlsExpansionBitmap;298ULONG TlsExpansionBitmapBits[32];299300ULONG SessionId;301302ULARGE_INTEGER AppCompatFlags;303ULARGE_INTEGER AppCompatFlagsUser;304PVOID pShimData;305PVOID AppCompatInfo; // APPCOMPAT_EXE_DATA306307UNICODE_STRING CSDVersion;308309PVOID ActivationContextData; // ACTIVATION_CONTEXT_DATA310PVOID ProcessAssemblyStorageMap; // ASSEMBLY_STORAGE_MAP311PVOID SystemDefaultActivationContextData; // ACTIVATION_CONTEXT_DATA312PVOID SystemAssemblyStorageMap; // ASSEMBLY_STORAGE_MAP313314SIZE_T MinimumStackCommit;315316PVOID SparePointers[4]; // 19H1 (previously FlsCallback to FlsHighIndex)317ULONG SpareUlongs[5]; // 19H1318//PVOID* FlsCallback;319//LIST_ENTRY FlsListHead;320//PVOID FlsBitmap;321//ULONG FlsBitmapBits[FLS_MAXIMUM_AVAILABLE / (sizeof(ULONG) * 8)];322//ULONG FlsHighIndex;323324PVOID WerRegistrationData;325PVOID WerShipAssertPtr;326PVOID pUnused; // pContextData327PVOID pImageHeaderHash;328union329{330ULONG TracingFlags;331struct332{333ULONG HeapTracingEnabled : 1;334ULONG CritSecTracingEnabled : 1;335ULONG LibLoaderTracingEnabled : 1;336ULONG SpareTracingBits : 29;337};338};339ULONGLONG CsrServerReadOnlySharedMemoryBase;340PRTL_CRITICAL_SECTION TppWorkerpListLock;341LIST_ENTRY TppWorkerpList;342PVOID WaitOnAddressHashTable[128];343PVOID TelemetryCoverageHeader; // REDSTONE3344ULONG CloudFileFlags;345ULONG CloudFileDiagFlags; // REDSTONE4346CHAR PlaceholderCompatibilityMode;347CHAR PlaceholderCompatibilityModeReserved[7];348struct _LEAP_SECOND_DATA* LeapSecondData; // REDSTONE5349union350{351ULONG LeapSecondFlags;352struct353{354ULONG SixtySecondEnabled : 1;355ULONG Reserved : 31;356};357};358ULONG NtGlobalFlag2;359} PEB, * PPEB;360361typedef struct _PROCESS_BASIC_INFORMATION362{363NTSTATUS ExitStatus;364PPEB PebBaseAddress;365ULONG_PTR AffinityMask;366KPRIORITY BasePriority;367HANDLE UniqueProcessId;368HANDLE InheritedFromUniqueProcessId;369} PROCESS_BASIC_INFORMATION, * PPROCESS_BASIC_INFORMATION;370371typedef struct _PS_ATTRIBUTE372{373ULONG_PTR Attribute;374SIZE_T Size;375union376{377ULONG_PTR Value;378PVOID ValuePtr;379};380PSIZE_T ReturnLength;381} PS_ATTRIBUTE, * PPS_ATTRIBUTE;382383typedef struct _PS_ATTRIBUTE_LIST384{385SIZE_T TotalLength;386PS_ATTRIBUTE Attributes[1];387} PS_ATTRIBUTE_LIST, * PPS_ATTRIBUTE_LIST;388389typedef struct _CLIENT_ID390{391HANDLE UniqueProcess;392HANDLE UniqueThread;393} CLIENT_ID, * PCLIENT_ID;394395typedef struct _ACTIVATION_CONTEXT_STACK396{397struct _RTL_ACTIVATION_CONTEXT_STACK_FRAME* ActiveFrame;398LIST_ENTRY FrameListCache;399ULONG Flags;400ULONG NextCookieSequenceNumber;401ULONG StackId;402} ACTIVATION_CONTEXT_STACK, * PACTIVATION_CONTEXT_STACK;403404#define GDI_BATCH_BUFFER_SIZE 310405406typedef struct _GDI_TEB_BATCH407{408ULONG Offset;409ULONG_PTR HDC;410ULONG Buffer[GDI_BATCH_BUFFER_SIZE];411} GDI_TEB_BATCH, * PGDI_TEB_BATCH;412413typedef struct _TEB_ACTIVE_FRAME_CONTEXT414{415ULONG Flags;416PSTR FrameName;417} TEB_ACTIVE_FRAME_CONTEXT, * PTEB_ACTIVE_FRAME_CONTEXT;418419typedef struct _TEB_ACTIVE_FRAME420{421ULONG Flags;422struct _TEB_ACTIVE_FRAME* Previous;423PTEB_ACTIVE_FRAME_CONTEXT Context;424} TEB_ACTIVE_FRAME, * PTEB_ACTIVE_FRAME;425426typedef struct _TEB427{428NT_TIB NtTib;429430PVOID EnvironmentPointer;431CLIENT_ID ClientId;432PVOID ActiveRpcHandle;433PVOID ThreadLocalStoragePointer;434PPEB ProcessEnvironmentBlock;435436ULONG LastErrorValue;437ULONG CountOfOwnedCriticalSections;438PVOID CsrClientThread;439PVOID Win32ThreadInfo;440ULONG User32Reserved[26];441ULONG UserReserved[5];442PVOID WOW32Reserved;443LCID CurrentLocale;444ULONG FpSoftwareStatusRegister;445PVOID ReservedForDebuggerInstrumentation[16];446#ifdef _WIN64447PVOID SystemReserved1[30];448#else449PVOID SystemReserved1[26];450#endif451452CHAR PlaceholderCompatibilityMode;453CHAR PlaceholderReserved[11];454ULONG ProxiedProcessId;455ACTIVATION_CONTEXT_STACK ActivationStack;456457UCHAR WorkingOnBehalfTicket[8];458NTSTATUS ExceptionCode;459460PACTIVATION_CONTEXT_STACK ActivationContextStackPointer;461ULONG_PTR InstrumentationCallbackSp;462ULONG_PTR InstrumentationCallbackPreviousPc;463ULONG_PTR InstrumentationCallbackPreviousSp;464#ifdef _WIN64465ULONG TxFsContext;466#endif467468BOOLEAN InstrumentationCallbackDisabled;469#ifndef _WIN64470UCHAR SpareBytes[23];471ULONG TxFsContext;472#endif473GDI_TEB_BATCH GdiTebBatch;474CLIENT_ID RealClientId;475HANDLE GdiCachedProcessHandle;476ULONG GdiClientPID;477ULONG GdiClientTID;478PVOID GdiThreadLocalInfo;479ULONG_PTR Win32ClientInfo[62];480PVOID glDispatchTable[233];481ULONG_PTR glReserved1[29];482PVOID glReserved2;483PVOID glSectionInfo;484PVOID glSection;485PVOID glTable;486PVOID glCurrentRC;487PVOID glContext;488489NTSTATUS LastStatusValue;490UNICODE_STRING StaticUnicodeString;491WCHAR StaticUnicodeBuffer[261];492493PVOID DeallocationStack;494PVOID TlsSlots[64];495LIST_ENTRY TlsLinks;496497PVOID Vdm;498PVOID ReservedForNtRpc;499PVOID DbgSsReserved[2];500501ULONG HardErrorMode;502#ifdef _WIN64503PVOID Instrumentation[11];504#else505PVOID Instrumentation[9];506#endif507GUID ActivityId;508509PVOID SubProcessTag;510PVOID PerflibData;511PVOID EtwTraceData;512PVOID WinSockData;513ULONG GdiBatchCount;514515union516{517PROCESSOR_NUMBER CurrentIdealProcessor;518ULONG IdealProcessorValue;519struct520{521UCHAR ReservedPad0;522UCHAR ReservedPad1;523UCHAR ReservedPad2;524UCHAR IdealProcessor;525};526};527528ULONG GuaranteedStackBytes;529PVOID ReservedForPerf;530PVOID ReservedForOle;531ULONG WaitingOnLoaderLock;532PVOID SavedPriorityState;533ULONG_PTR ReservedForCodeCoverage;534PVOID ThreadPoolData;535PVOID* TlsExpansionSlots;536#ifdef _WIN64537PVOID DeallocationBStore;538PVOID BStoreLimit;539#endif540ULONG MuiGeneration;541ULONG IsImpersonating;542PVOID NlsCache;543PVOID pShimData;544USHORT HeapVirtualAffinity;545USHORT LowFragHeapDataSlot;546HANDLE CurrentTransactionHandle;547PTEB_ACTIVE_FRAME ActiveFrame;548PVOID FlsData;549550PVOID PreferredLanguages;551PVOID UserPrefLanguages;552PVOID MergedPrefLanguages;553ULONG MuiImpersonation;554555union556{557USHORT CrossTebFlags;558USHORT SpareCrossTebBits : 16;559};560union561{562USHORT SameTebFlags;563struct564{565USHORT SafeThunkCall : 1;566USHORT InDebugPrint : 1;567USHORT HasFiberData : 1;568USHORT SkipThreadAttach : 1;569USHORT WerInShipAssertCode : 1;570USHORT RanProcessInit : 1;571USHORT ClonedThread : 1;572USHORT SuppressDebugMsg : 1;573USHORT DisableUserStackWalk : 1;574USHORT RtlExceptionAttached : 1;575USHORT InitialThread : 1;576USHORT SessionAware : 1;577USHORT LoadOwner : 1;578USHORT LoaderWorker : 1;579USHORT SkipLoaderInit : 1;580USHORT SpareSameTebBits : 1;581};582};583584PVOID TxnScopeEnterCallback;585PVOID TxnScopeExitCallback;586PVOID TxnScopeContext;587ULONG LockCount;588LONG WowTebOffset;589PVOID ResourceRetValue;590PVOID ReservedForWdf;591ULONGLONG ReservedForCrt;592GUID EffectiveContainerId;593} TEB, * PTEB;594595#define NtCurrentProcess() ((HANDLE)(LONG_PTR)-1)596#define NtCurrentPeb() (NtCurrentTeb()->ProcessEnvironmentBlock)597598#define PROCESS_CREATE_FLAGS_INHERIT_HANDLES 0x00000004599600typedef enum _PROCESSINFOCLASS601{602ProcessBasicInformation, // q: PROCESS_BASIC_INFORMATION, PROCESS_EXTENDED_BASIC_INFORMATION603ProcessQuotaLimits, // qs: QUOTA_LIMITS, QUOTA_LIMITS_EX604ProcessIoCounters, // q: IO_COUNTERS605ProcessVmCounters, // q: VM_COUNTERS, VM_COUNTERS_EX, VM_COUNTERS_EX2606ProcessTimes, // q: KERNEL_USER_TIMES607ProcessBasePriority, // s: KPRIORITY608ProcessRaisePriority, // s: ULONG609ProcessDebugPort, // q: HANDLE610ProcessExceptionPort, // s: PROCESS_EXCEPTION_PORT611ProcessAccessToken, // s: PROCESS_ACCESS_TOKEN612ProcessLdtInformation, // qs: PROCESS_LDT_INFORMATION // 10613ProcessLdtSize, // s: PROCESS_LDT_SIZE614ProcessDefaultHardErrorMode, // qs: ULONG615ProcessIoPortHandlers, // (kernel-mode only)616ProcessPooledUsageAndLimits, // q: POOLED_USAGE_AND_LIMITS617ProcessWorkingSetWatch, // q: PROCESS_WS_WATCH_INFORMATION[]; s: void618ProcessUserModeIOPL,619ProcessEnableAlignmentFaultFixup, // s: BOOLEAN620ProcessPriorityClass, // qs: PROCESS_PRIORITY_CLASS621ProcessWx86Information,622ProcessHandleCount, // q: ULONG, PROCESS_HANDLE_INFORMATION // 20623ProcessAffinityMask, // s: KAFFINITY624ProcessPriorityBoost, // qs: ULONG625ProcessDeviceMap, // qs: PROCESS_DEVICEMAP_INFORMATION, PROCESS_DEVICEMAP_INFORMATION_EX626ProcessSessionInformation, // q: PROCESS_SESSION_INFORMATION627ProcessForegroundInformation, // s: PROCESS_FOREGROUND_BACKGROUND628ProcessWow64Information, // q: ULONG_PTR629ProcessImageFileName, // q: UNICODE_STRING630ProcessLUIDDeviceMapsEnabled, // q: ULONG631ProcessBreakOnTermination, // qs: ULONG632ProcessDebugObjectHandle, // q: HANDLE // 30633ProcessDebugFlags, // qs: ULONG634ProcessHandleTracing, // q: PROCESS_HANDLE_TRACING_QUERY; s: size 0 disables, otherwise enables635ProcessIoPriority, // qs: IO_PRIORITY_HINT636ProcessExecuteFlags, // qs: ULONG637ProcessResourceManagement, // ProcessTlsInformation // PROCESS_TLS_INFORMATION638ProcessCookie, // q: ULONG639ProcessImageInformation, // q: SECTION_IMAGE_INFORMATION640ProcessCycleTime, // q: PROCESS_CYCLE_TIME_INFORMATION // since VISTA641ProcessPagePriority, // q: PAGE_PRIORITY_INFORMATION642ProcessInstrumentationCallback, // qs: PROCESS_INSTRUMENTATION_CALLBACK_INFORMATION // 40643ProcessThreadStackAllocation, // s: PROCESS_STACK_ALLOCATION_INFORMATION, PROCESS_STACK_ALLOCATION_INFORMATION_EX644ProcessWorkingSetWatchEx, // q: PROCESS_WS_WATCH_INFORMATION_EX[]645ProcessImageFileNameWin32, // q: UNICODE_STRING646ProcessImageFileMapping, // q: HANDLE (input)647ProcessAffinityUpdateMode, // qs: PROCESS_AFFINITY_UPDATE_MODE648ProcessMemoryAllocationMode, // qs: PROCESS_MEMORY_ALLOCATION_MODE649ProcessGroupInformation, // q: USHORT[]650ProcessTokenVirtualizationEnabled, // s: ULONG651ProcessConsoleHostProcess, // q: ULONG_PTR // ProcessOwnerInformation652ProcessWindowInformation, // q: PROCESS_WINDOW_INFORMATION // 50653ProcessHandleInformation, // q: PROCESS_HANDLE_SNAPSHOT_INFORMATION // since WIN8654ProcessMitigationPolicy, // s: PROCESS_MITIGATION_POLICY_INFORMATION655ProcessDynamicFunctionTableInformation,656ProcessHandleCheckingMode, // qs: ULONG; s: 0 disables, otherwise enables657ProcessKeepAliveCount, // q: PROCESS_KEEPALIVE_COUNT_INFORMATION658ProcessRevokeFileHandles, // s: PROCESS_REVOKE_FILE_HANDLES_INFORMATION659ProcessWorkingSetControl, // s: PROCESS_WORKING_SET_CONTROL660ProcessHandleTable, // q: ULONG[] // since WINBLUE661ProcessCheckStackExtentsMode,662ProcessCommandLineInformation, // q: UNICODE_STRING // 60663ProcessProtectionInformation, // q: PS_PROTECTION664ProcessMemoryExhaustion, // PROCESS_MEMORY_EXHAUSTION_INFO // since THRESHOLD665ProcessFaultInformation, // PROCESS_FAULT_INFORMATION666ProcessTelemetryIdInformation, // PROCESS_TELEMETRY_ID_INFORMATION667ProcessCommitReleaseInformation, // PROCESS_COMMIT_RELEASE_INFORMATION668ProcessDefaultCpuSetsInformation,669ProcessAllowedCpuSetsInformation,670ProcessSubsystemProcess,671ProcessJobMemoryInformation, // PROCESS_JOB_MEMORY_INFO672ProcessInPrivate, // since THRESHOLD2 // 70673ProcessRaiseUMExceptionOnInvalidHandleClose, // qs: ULONG; s: 0 disables, otherwise enables674ProcessIumChallengeResponse,675ProcessChildProcessInformation, // PROCESS_CHILD_PROCESS_INFORMATION676ProcessHighGraphicsPriorityInformation,677ProcessSubsystemInformation, // q: SUBSYSTEM_INFORMATION_TYPE // since REDSTONE2678ProcessEnergyValues, // PROCESS_ENERGY_VALUES, PROCESS_EXTENDED_ENERGY_VALUES679ProcessActivityThrottleState, // PROCESS_ACTIVITY_THROTTLE_STATE680ProcessActivityThrottlePolicy, // PROCESS_ACTIVITY_THROTTLE_POLICY681ProcessWin32kSyscallFilterInformation,682ProcessDisableSystemAllowedCpuSets, // 80683ProcessWakeInformation, // PROCESS_WAKE_INFORMATION684ProcessEnergyTrackingState, // PROCESS_ENERGY_TRACKING_STATE685ProcessManageWritesToExecutableMemory, // MANAGE_WRITES_TO_EXECUTABLE_MEMORY // since REDSTONE3686ProcessCaptureTrustletLiveDump,687ProcessTelemetryCoverage,688ProcessEnclaveInformation,689ProcessEnableReadWriteVmLogging, // PROCESS_READWRITEVM_LOGGING_INFORMATION690ProcessUptimeInformation, // PROCESS_UPTIME_INFORMATION691ProcessImageSection, // q: HANDLE692ProcessDebugAuthInformation, // since REDSTONE4 // 90693ProcessSystemResourceManagement, // PROCESS_SYSTEM_RESOURCE_MANAGEMENT694ProcessSequenceNumber, // q: ULONGLONG695ProcessLoaderDetour, // since REDSTONE5696ProcessSecurityDomainInformation, // PROCESS_SECURITY_DOMAIN_INFORMATION697ProcessCombineSecurityDomainsInformation, // PROCESS_COMBINE_SECURITY_DOMAINS_INFORMATION698ProcessEnableLogging, // PROCESS_LOGGING_INFORMATION699ProcessLeapSecondInformation, // PROCESS_LEAP_SECOND_INFORMATION700ProcessFiberShadowStackAllocation, // PROCESS_FIBER_SHADOW_STACK_ALLOCATION_INFORMATION // since 19H1701ProcessFreeFiberShadowStackAllocation, // PROCESS_FREE_FIBER_SHADOW_STACK_ALLOCATION_INFORMATION702MaxProcessInfoClass703} PROCESSINFOCLASS;704705706NTSYSCALLAPI707NTSTATUS708NTAPI709NtCreateSection(710_Out_ PHANDLE SectionHandle,711_In_ ACCESS_MASK DesiredAccess,712_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,713_In_opt_ PLARGE_INTEGER MaximumSize,714_In_ ULONG SectionPageProtection,715_In_ ULONG AllocationAttributes,716_In_opt_ HANDLE FileHandle717);718719NTSYSCALLAPI720NTSTATUS721NTAPI722NtCreateProcessEx(723_Out_ PHANDLE ProcessHandle,724_In_ ACCESS_MASK DesiredAccess,725_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,726_In_ HANDLE ParentProcess,727_In_ ULONG Flags,728_In_opt_ HANDLE SectionHandle,729_In_opt_ HANDLE DebugPort,730_In_opt_ HANDLE ExceptionPort,731_In_ ULONG JobMemberLevel732);733734NTSYSCALLAPI735NTSTATUS736NTAPI737NtQueryInformationProcess(738_In_ HANDLE ProcessHandle,739_In_ PROCESSINFOCLASS ProcessInformationClass,740_Out_writes_bytes_(ProcessInformationLength) PVOID ProcessInformation,741_In_ ULONG ProcessInformationLength,742_Out_opt_ PULONG ReturnLength743);744745NTSYSCALLAPI746NTSTATUS747NTAPI748NtClose(749_In_ HANDLE Handle750);751752NTSYSCALLAPI753NTSTATUS754NTAPI755NtCreateThreadEx(756_Out_ PHANDLE ThreadHandle,757_In_ ACCESS_MASK DesiredAccess,758_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,759_In_ HANDLE ProcessHandle,760_In_ PVOID StartRoutine, // PUSER_THREAD_START_ROUTINE761_In_opt_ PVOID Argument,762_In_ ULONG CreateFlags, // THREAD_CREATE_FLAGS_*763_In_ SIZE_T ZeroBits,764_In_ SIZE_T StackSize,765_In_ SIZE_T MaximumStackSize,766_In_opt_ PPS_ATTRIBUTE_LIST AttributeList767);768769FORCEINLINE VOID RtlInitUnicodeString(770_Out_ PUNICODE_STRING DestinationString,771_In_opt_ PCWSTR SourceString772)773{774if (SourceString)775DestinationString->MaximumLength = (DestinationString->Length = (USHORT)(wcslen(SourceString) * sizeof(WCHAR))) + sizeof(UNICODE_NULL);776else777DestinationString->MaximumLength = DestinationString->Length = 0;778779DestinationString->Buffer = (PWCH)SourceString;780}781782NTSYSAPI783NTSTATUS784NTAPI785RtlCreateProcessParametersEx(786_Out_ PRTL_USER_PROCESS_PARAMETERS* pProcessParameters,787_In_ PUNICODE_STRING ImagePathName,788_In_opt_ PUNICODE_STRING DllPath,789_In_opt_ PUNICODE_STRING CurrentDirectory,790_In_opt_ PUNICODE_STRING CommandLine,791_In_opt_ PVOID Environment,792_In_opt_ PUNICODE_STRING WindowTitle,793_In_opt_ PUNICODE_STRING DesktopInfo,794_In_opt_ PUNICODE_STRING ShellInfo,795_In_opt_ PUNICODE_STRING RuntimeData,796_In_ ULONG Flags // pass RTL_USER_PROC_PARAMS_NORMALIZED to keep parameters normalized797);798799NTSYSAPI800NTSTATUS801NTAPI802RtlDestroyProcessParameters(803_In_ _Post_invalid_ PRTL_USER_PROCESS_PARAMETERS ProcessParameters804);805806#ifdef __cplusplus807}808#endif809810#pragma warning(pop)811812class AutoCloseHandle813{814public:815AutoCloseHandle(BOOL isNTHandle = FALSE) :816m_handle(INVALID_HANDLE_VALUE),817m_isNTHandle(isNTHandle)818{}819820~AutoCloseHandle()821{822if (!valid())823{824return;825}826if (m_isNTHandle)827{828NTSTATUS status = NtClose(m_handle);829if (!NT_SUCCESS(status))830{831dprintf("[AutoCloseHandle] Error when closing the NT handle (NTSTATUS: %d)", status);832}833}834else835{836if (CloseHandle(m_handle) == 0)837{838dprintf("[AutoCloseHandle] Error when closing handle (%d)", GetLastError());839}840}841m_handle = INVALID_HANDLE_VALUE;842}843844HANDLE& get()845{846return m_handle;847}848849void close()850{851this->~AutoCloseHandle();852}853854BOOL valid()855{856return (m_handle != NULL) && (m_handle != INVALID_HANDLE_VALUE);857}858private:859HANDLE m_handle;860BOOL m_isNTHandle;861};862863864class ProcessHandle865{866public:867ProcessHandle() :868m_processHandle(),869m_terminate(TRUE)870{}871872~ProcessHandle()873{874if (m_processHandle.valid())875{876if (m_terminate)877{878if (TerminateProcess(m_processHandle.get(), 0) == 0)879{880dprintf("Error when terminating process (%d)", GetLastError());881}882m_terminate = FALSE;883}884m_processHandle.close();885}886}887888BOOL& terminate()889{890return m_terminate;891}892893HANDLE& get()894{895return m_processHandle.get();896}897898BOOL valid()899{900return m_processHandle.valid();901}902903private:904AutoCloseHandle m_processHandle;905BOOL m_terminate;906};907908class FileHandle909{910public:911FileHandle(std::wstring fileName = L"", BOOL p_remove = FALSE) :912m_fileHandle(),913m_fileName(fileName),914m_remove(p_remove)915{}916917~FileHandle()918{919if (m_fileHandle.valid())920{921m_fileHandle.close();922}923if (m_remove)924{925dprintf("[FileHandle] Remove file %S", m_fileName.c_str());926if (DeleteFileW(m_fileName.c_str()) == 0)927{928dprintf("[FileHandle] Failed to delete the file %S (0x%d)", m_fileName.c_str(), GetLastError());929}930m_remove = FALSE;931}932}933934BOOL& remove()935{936return m_remove;937}938939HANDLE& get()940{941return m_fileHandle.get();942}943944BOOL valid()945{946return m_fileHandle.valid();947}948949void close()950{951m_fileHandle.close();952}953private:954AutoCloseHandle m_fileHandle;955BOOL m_remove;956std::wstring m_fileName;957};958959960class MappingHandle961{962public:963MappingHandle() :964m_mappingHandle(),965m_view(nullptr)966{}967968~MappingHandle()969{970if (m_view != nullptr)971{972dprintf("[MappingHandle] Unmapping view");973if (UnmapViewOfFile(m_view) == 0)974{975dprintf("[MappingHandle] Unmap view error (0x%x)", GetLastError());976}977m_view = nullptr;978}979if (m_mappingHandle.valid())980{981m_mappingHandle.close();982}983}984985HANDLE& get()986{987return m_mappingHandle.get();988}989990BOOL valid()991{992return m_mappingHandle.valid();993}994995void close()996{997this->~MappingHandle();998}9991000LPVOID& view()1001{1002return m_view;1003}10041005private:1006AutoCloseHandle m_mappingHandle;1007LPVOID m_view;1008};100910101011