cwindowswinapiportable-executable

Is it possible to write a valid PE file from memory to disk?


I'm working on a project where I want to create a new executable file by copying the sections of a running PE (Portable Executable) file from memory to disk using C on Windows. However, I'm running into issues when I try to run the output file, which results in an "invalid access to memory" error.

Here's my approach:

// current base address
IMAGE_DOS_HEADER* dosHeader = (IMAGE_DOS_HEADER*)hModule;
IMAGE_NT_HEADERS* ntHeaders = (IMAGE_NT_HEADERS*)((BYTE*)hModule + dosHeader->e_lfanew);
IMAGE_FILE_HEADER* fileHeader = &ntHeaders->FileHeader;
IMAGE_OPTIONAL_HEADER* optionalHeader = &ntHeaders->OptionalHeader;

unsigned char* buffer = (unsigned char*)malloc(optionalHeader->SizeOfImage);
memset(buffer, 0, optionalHeader->SizeOfImage);

// Copy the headers
memcpy(buffer, dosHeader, dosHeader->e_lfanew + sizeof(IMAGE_NT_HEADERS));

// Copy each section
IMAGE_SECTION_HEADER* sectionHeader = (IMAGE_SECTION_HEADER*)(ntHeaders + 1);
for (int i = 0; i < fileHeader->NumberOfSections; i++) {
    memcpy(buffer + sectionHeader[i].VirtualAddress,
           (BYTE*)hModule + sectionHeader[i].PointerToRawData,
           sectionHeader[i].SizeOfRawData);
}

Then I write it to disk using the WriteFile() API.


Solution

  • after PE, is loaded im memory, it was modified, import resolved and data pointed by FirstThunk was modified to real api addresses, when it on disk must point to IMAGE_IMPORT_BY_NAME or equal to ordinal. so how minimum you must fix import - copy context of OriginalFirstThunk to FirstThunk. however relocations not is problem. all what need, that pinth->OptionalHeader.ImageBase was corresponded to the real image base on which it was already loaded and for which the relocations was made. and windows by self adjust OptionalHeader.ImageBase to new correct base. after import, PE can have delay import, which also need fix, in case it already resolved. global variables can be modified, __security_cookie - it must be 0x2B992DDFA232 at begin or LdrInitSecurityCookie fail, etc. we can fix almost all, except global variables, which we dont know in general how fix to initial values


    demo code (no range/errors checks)

    #include <delayimp.h>
    
    ULONG GetImageSize(PIMAGE_NT_HEADERS pinth)
    {
        if (DWORD NumberOfSections = pinth->FileHeader.NumberOfSections)
        {
            PIMAGE_SECTION_HEADER pish = IMAGE_FIRST_SECTION(pinth);
    
            ULONG MaxOffset = 0;
            do 
            {
                if (DWORD SizeOfRawData = pish->SizeOfRawData)
                {
                    ULONG u = pish->PointerToRawData + SizeOfRawData;
                    if (MaxOffset < u)
                    {
                        MaxOffset = u;
                    }
                }
            } while (pish++, --NumberOfSections);
    
            return MaxOffset;
        }
    
        return 0;
    }
    
    void copyThunks(PVOID BaseAddress, ULONG OriginalFirstThunk, ULONG FirstThunk)
    {
        if (OriginalFirstThunk && FirstThunk)
        {
            union {
                PVOID pv;
                PULONG_PTR pu;
            };
            union {
                PVOID qv;
                PULONG_PTR qu;
            };
    
            pv = RtlOffsetToPointer(BaseAddress, OriginalFirstThunk); 
            qv = RtlOffsetToPointer(BaseAddress, FirstThunk);
    
            ULONGLONG u;
            do 
            {
                *qu++ = u = *pu++;
            } while (u);
        }
    }
    
    void FixImport(PVOID BaseAddress)
    {
        DWORD s;
        if (PIMAGE_IMPORT_DESCRIPTOR piid = (PIMAGE_IMPORT_DESCRIPTOR)
            RtlImageDirectoryEntryToData(BaseAddress, FALSE, IMAGE_DIRECTORY_ENTRY_IMPORT, &s))
        {
            while (piid->Name)
            {
                copyThunks(BaseAddress, piid->OriginalFirstThunk, piid->FirstThunk);
                piid++;
            }
        }
    }
    
    void FixDelayImport(PVOID BaseAddress)
    {
        DWORD s;
        if (ImgDelayDescr* piid = (ImgDelayDescr*)
            RtlImageDirectoryEntryToData(BaseAddress, FALSE, IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT, &s))
        {
            while (piid->rvaDLLName)
            {
                if (dlattrRva & piid->grAttrs)
                {
                    copyThunks(BaseAddress, piid->rvaUnloadIAT, piid->rvaIAT);
                }
                piid++;
            }
        }
    }
    
    void ImageToLine(PVOID ImageBase, PCWSTR pszFileName)
    {
        PIMAGE_NT_HEADERS pinth = RtlImageNtHeader(ImageBase);
    
        if (ULONG s = GetImageSize(pinth))
        {
            if (PVOID BaseAddress = VirtualAlloc(0, s, MEM_COMMIT, PAGE_READWRITE))
            {
                memcpy(BaseAddress, ImageBase, pinth->OptionalHeader.SizeOfHeaders);
    
                if (DWORD NumberOfSections = pinth->FileHeader.NumberOfSections)
                {
                    PIMAGE_SECTION_HEADER pish = IMAGE_FIRST_SECTION(pinth);
    
                    do 
                    {
                        if (DWORD SizeOfRawData = pish->SizeOfRawData)
                        {
                            memcpy((PBYTE)BaseAddress + pish->PointerToRawData, 
                                (PBYTE)ImageBase + pish->VirtualAddress, 
                                min(SizeOfRawData, pish->Misc.VirtualSize));
                        }
                    } while (pish++, --NumberOfSections);
                }
    
                FixImport(BaseAddress);
                FixDelayImport(BaseAddress);
    
                ULONG size;
                if (PIMAGE_LOAD_CONFIG_DIRECTORY picd = (PIMAGE_LOAD_CONFIG_DIRECTORY)
                    RtlImageDirectoryEntryToData(BaseAddress, FALSE, IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG, &size))
                {
                    if (RTL_SIZEOF_THROUGH_FIELD(IMAGE_LOAD_CONFIG_DIRECTORY, SecurityCookie) <= size &&
                        RTL_SIZEOF_THROUGH_FIELD(IMAGE_LOAD_CONFIG_DIRECTORY, SecurityCookie) <= picd->Size)
                    {
                        if (ULONG_PTR* psq = (ULONG_PTR*)RtlAddressInSectionTable(
                            pinth, BaseAddress, RtlPointerToOffset(ImageBase, picd->SecurityCookie)))
                        {
                            *psq = 0x2B992DDFA232;
                        }
                    }
                }
    
                HANDLE hFile = CreateFileW(pszFileName, FILE_APPEND_DATA, 0, 0, CREATE_ALWAYS, 0, 0);
                if (INVALID_HANDLE_VALUE != hFile)
                {
                    WriteFile(hFile, BaseAddress, s, &s, 0);
                    CloseHandle(hFile);
                }
    
                VirtualFree(BaseAddress, 0, MEM_RELEASE);
            }
        }
    }