测试代码,写的很垃圾, 可用, 不过,不推荐大家使用
void TestAddSecToFile(LPSTR lpszFile)
{
LPVOID pFileBuffer = NULL;
pFileBuffer= ReadPEFile(lpszFile);
if(!pFileBuffer)
{
printf("文件读取失败\n");
return;
}
PIMAGE_DOS_HEADER pDosHeader = NULL;
PIMAGE_NT_HEADERS pNTHeader = NULL;
PIMAGE_FILE_HEADER pPEHeader = NULL;
PIMAGE_OPTIONAL_HEADER32 pOptionHeader = NULL;
PIMAGE_SECTION_HEADER pSectionHeader = NULL;
PIMAGE_SECTION_HEADER pSectionHeader_ADD = NULL;
//Header信息
pDosHeader = (PIMAGE_DOS_HEADER)pFileBuffer;
pNTHeader = (PIMAGE_NT_HEADERS)((DWORD)pFileBuffer+pDosHeader->e_lfanew);
pPEHeader = (PIMAGE_FILE_HEADER)(((DWORD)pNTHeader)+4);
pOptionHeader = (PIMAGE_OPTIONAL_HEADER32)((DWORD)pPEHeader+IMAGE_SIZEOF_FILE_HEADER);
pSectionHeader = (PIMAGE_SECTION_HEADER)((DWORD)pOptionHeader+pPEHeader->SizeOfOptionalHeader);
pSectionHeader_ADD = pSectionHeader;
//1 判断能否添加节
DWORD Header_size = pDosHeader->e_lfanew + 4 + 20 + pPEHeader->SizeOfOptionalHeader + pPEHeader->NumberOfSections*40;
if(pOptionHeader->SizeOfHeaders-Header_size<80)
{
printf("没有可用空间填充节表\n");
free(pFileBuffer);
return;
}
printf("空间:%d\n",pOptionHeader->SizeOfHeaders-Header_size);
//添加一个节
//确定参数
PIMAGE_SECTION_HEADER pSectionHeader_LAST = (PIMAGE_SECTION_HEADER)((DWORD)pSectionHeader+(pPEHeader->NumberOfSections-1)*40);
pSectionHeader_ADD=(PIMAGE_SECTION_HEADER)((DWORD)pSectionHeader_ADD+(pPEHeader->NumberOfSections)*40);
//="NewSec";
strcpy((char*)pSectionHeader_ADD->Name,"NewSec");
pSectionHeader_ADD->Misc.VirtualSize = 0x1000;
pSectionHeader_ADD->VirtualAddress = pOptionHeader->SizeOfImage;
pSectionHeader_ADD->SizeOfRawData = 0x1000;
pSectionHeader_ADD->PointerToRawData = pSectionHeader_LAST->PointerToRawData+pSectionHeader_LAST->SizeOfRawData;
pSectionHeader_ADD->Characteristics = pSectionHeader->Characteristics;
//填充0
LPVOID pSectionEND = (LPVOID)((DWORD)pSectionHeader_ADD+40);
memset(pSectionEND,0,IMAGE_SIZEOF_SECTION_HEADER);
printf("pFileBuffer: %x\n",pFileBuffer);
printf("pSectionHeader: %x\n",pSectionHeader);
printf("pSectionHeader_LAST: %x\n",pSectionHeader_LAST);
printf("pSectionHeader_ADD: %x\n",pSectionHeader_ADD);
printf("pSectionEND: %x\n",pSectionEND);
//修改PE头信息
pPEHeader->NumberOfSections = pPEHeader->NumberOfSections +1;
pOptionHeader->SizeOfImage = pOptionHeader->SizeOfImage+0x1000;
//写入到文件
FILE *pOutFile = NULL;
//打开文件
pOutFile = fopen("C://addSec.exe","a+b");
if(!pOutFile)
{
printf("无法打开文件EXE文件");
return;
}
//写出第一部分
printf("length: %x \n ",pSectionHeader_ADD->PointerToRawData+pSectionHeader_ADD->SizeOfRawData);
size_t writeSize = fwrite(pFileBuffer,pSectionHeader_ADD->PointerToRawData,1,pOutFile);
printf("WirteSize:%d\n",writeSize);
//写出第二部分
LPVOID pNewBuffer=(LPVOID)malloc(0x1000);
if(pNewBuffer==NULL)
{
printf("pNewBuffer分配空间失败\n");
return;
}
memset(pNewBuffer,0,0x1000);
writeSize = fwrite(pNewBuffer,0x1000,1,pOutFile);
//关闭文件
fclose(pOutFile);
free(pFileBuffer);
free(pNewBuffer);
}