PE 新增一个节区细节

Posted dounine

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PE 新增一个节区细节相关的知识,希望对你有一定的参考价值。

pe 文件中新增一个节区的细节

主要是Misc.VirtualSize为添加的实际大小,非内存对齐后的大小。

LPVOID addSection(LPVOID fileBuffer, PTCHAR sectionName, size_t sectionCodeSize) 
    if (strlen(sectionName) >= 8) 
        cout << "sectionName size < 8" << endl;
        return nullptr;
    
    auto ntHeader = getNtHeader(fileBuffer);
    size_t fileAlign = ntHeader->OptionalHeader.FileAlignment;
    size_t fileSize = peSize(fileBuffer);
    size_t outFileSize = fileSize + align(sectionCodeSize, fileAlign);
    auto newFileBuffer = malloc(outFileSize);
    memset(newFileBuffer, 0, outFileSize);
    memcpy(newFileBuffer, fileBuffer, fileSize);
    free(fileBuffer);
    auto newFileNtHeader = getNtHeader(newFileBuffer);
    auto newOptionHeader = &newFileNtHeader->OptionalHeader;
    auto newFileSectionHeader =
            (PIMAGE_SECTION_HEADER) ((PTCHAR) newOptionHeader +
                                     sizeof(*newOptionHeader));

    if ((newFileSectionHeader->PointerToRawData -
         (DWORD) (newFileSectionHeader + newFileNtHeader->FileHeader.NumberOfSections)) < 0x50) 
        cout << "table space not enought" << endl;
        return nullptr;
    

    size_t sectionAlign = newFileNtHeader->OptionalHeader.SectionAlignment;
    auto newFileLatestSectionHeader =
            (PIMAGE_SECTION_HEADER) (newFileSectionHeader + (newFileNtHeader->FileHeader.NumberOfSections - 1));
    auto addSectionHeader = newFileLatestSectionHeader + 1;


	//最多为8个字节
    memcpy(addSectionHeader->Name, (LPVOID)".import", 8);

	//Misc.VirtualSize 为新增字节的真实长度,非内存对齐后的长度
    addSectionHeader->Misc.VirtualSize = sectionCodeSize;
    cout << sectionCodeSize << endl;
    addSectionHeader->VirtualAddress = align(
            newFileLatestSectionHeader->VirtualAddress + newFileLatestSectionHeader->Misc.VirtualSize,
            sectionAlign);
    addSectionHeader->SizeOfRawData = align(sectionCodeSize, fileAlign);
    addSectionHeader->PointerToRawData =
            newFileLatestSectionHeader->PointerToRawData + newFileLatestSectionHeader->SizeOfRawData;
    addSectionHeader->Characteristics = IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE;

    newFileNtHeader->FileHeader.NumberOfSections += 1;

    newFileNtHeader->OptionalHeader.SizeOfImage += align(sectionCodeSize, sectionAlign);
    newFileNtHeader->OptionalHeader.SizeOfHeaders += sizeof(*addSectionHeader);
    return newFileBuffer;

以上是关于PE 新增一个节区细节的主要内容,如果未能解决你的问题,请参考以下文章

PE 新增一个节区细节

PE文件格式全解读

PE格式:新建节并插入代码

内存Dump出PE

内存Dump出PE

PE格式:手工给程序插入ShellCode