PE結構-合併節(附例項程式碼)

v寰宇發表於2020-10-24

在這裡插入圖片描述

合併節:
1、拉伸到記憶體
2、將第一個節的記憶體大小、檔案大小改成一樣
Max = SizeOfRawData>VirtualSize?SizeOfRawData:VirtualSize
SizeOfRawData = VirtualSize = 最後一個節的VirtualAddress + Max - SizeOfHeaders記憶體對齊後的大小
3、將第一個節的屬性改為包含所有節的屬性 (重點)
4、修改節的數量為1


BOOL MergingSection(IN OUT LPVOID* pImageBuffer)
{
	//DOC頭
	PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)*pImageBuffer;
	//NT頭
	PIMAGE_NT_HEADERS pNTHeader = (PIMAGE_NT_HEADERS)((DWORD)pDosHeader + pDosHeader->e_lfanew);
	//標準PE頭
	PIMAGE_FILE_HEADER pPEHeader = (PIMAGE_FILE_HEADER)(((DWORD)pNTHeader) + 4);
	//可選PE頭
	PIMAGE_OPTIONAL_HEADER32 pOptionHeader = (PIMAGE_OPTIONAL_HEADER32)((DWORD)pPEHeader + IMAGE_SIZEOF_FILE_HEADER);
	if (*((PWORD)*pImageBuffer) != IMAGE_DOS_SIGNATURE)
	{
		printf("MZ檔案標誌頭不存在!");
		free(pImageBuffer);
		return false;
	}
	PIMAGE_SECTION_HEADER pSectionHeader = NULL;
	pSectionHeader = (PIMAGE_SECTION_HEADER)((DWORD)pOptionHeader + pPEHeader->SizeOfOptionalHeader);
	DWORD Max = pSectionHeader->SizeOfRawData > pSectionHeader->Misc.VirtualSize ? pSectionHeader->SizeOfRawData : pSectionHeader->Misc.VirtualSize;
	PIMAGE_SECTION_HEADER pSectionHeader_tmp = pSectionHeader;
	pSectionHeader_tmp += (pPEHeader->NumberOfSections - 1);
	pSectionHeader->SizeOfRawData = pSectionHeader->Misc.VirtualSize = Align(pSectionHeader_tmp->VirtualAddress + Max - pOptionHeader->SizeOfHeaders, pOptionHeader->SectionAlignment);
	pPEHeader->NumberOfSections = 1;

	return true;
}

Github地址:https://github.com/vShellCode/Analysis-of-PE-structure

相關文章