为pe文件增加一个新节

#include "windows.h"
#include "stdio.h"
#include "winnt.h"
//#include "winbase.h"

DWORD alig(int size,unsigned int align)
{
if(size%align!=0)
return (size/align+1)*align;
else
return size;
}


void addsection(char *file )
{


char filename[255];
strcpy(filename,file);
IMAGE_DOS_HEADER image_dos_header;
IMAGE_NT_HEADERS image_nt_headers;
IMAGE_SECTION_HEADER image_section_header;
IMAGE_SECTION_HEADER old_section;
int num_section=0 ;
// byte sec[8]=".txt";



FILE *h;
h=fopen(filename,"rb+");
fseek(h,0,SEEK_SET);
fread(&image_dos_header,sizeof(IMAGE_DOS_HEADER),1,h);
fseek(h,image_dos_header.e_lfanew ,SEEK_SET);
fread(&image_nt_headers,sizeof(IMAGE_NT_HEADERS),1,h);
printf("%d",sizeof(IMAGE_NT_HEADERS));
for(int a=0;a<=15;a++)
printf("%x,%x\n",image_nt_headers.OptionalHeader.DataDirectory[a].VirtualAddress,image_nt_headers.OptionalHeader.DataDirectory[a].Size);

num_section=image_nt_headers.FileHeader.NumberOfSections ;
fseek(h,image_dos_header.e_lfanew + sizeof(IMAGE_NT_HEADERS)+(num_section-1) * sizeof(IMAGE_SECTION_HEADER),SEEK_SET);
fread(&old_section,sizeof(IMAGE_SECTION_HEADER),1,h);

image_nt_headers.FileHeader .NumberOfSections +=1;
image_section_header.Characteristics=0xe0000020;
image_section_header.Misc.VirtualSize =image_nt_headers.OptionalHeader.SectionAlignment ;
//bool x=true;
for (int n=1;true;n++)
if(image_nt_headers.OptionalHeader.FileAlignment *n>519) break;
image_section_header.SizeOfRawData =image_nt_headers.OptionalHeader.FileAlignment *n;
strcpy((char*)image_section_header.Name,".gao");
image_section_header.PointerToRawData =alig(old_section.PointerToRawData + old_section.SizeOfRawData ,image_nt_headers.OptionalHeader .FileAlignment );
image_section_header.VirtualAddress = alig(old_section.VirtualAddress + old_section.SizeOfRawData ,image_nt_headers.OptionalHeader.SectionAlignment );
fseek(h,image_dos_header.e_lfanew + sizeof(IMAGE_NT_HEADERS) + num_section * sizeof(IMAGE_SECTION_HEADER),SEEK_SET);
fwrite(&image_section_header,sizeof(IMAGE_SECTION_HEADER),1,h);


image_nt_headers.OptionalHeader.SizeOfImage =alig(image_section_header.VirtualAddress + image_section_header.SizeOfRawData ,image_nt_headers.OptionalHeader .SectionAlignment );
image_nt_headers.OptionalHeader.DataDirectory[11].VirtualAddress =0;
image_nt_headers.OptionalHeader.DataDirectory[11].Size =0;
fseek(h,image_dos_header.e_lfanew ,SEEK_SET);
fwrite(&image_nt_headers,sizeof(IMAGE_NT_HEADERS),1,h);

fseek(h,image_section_header.PointerToRawData ,SEEK_SET);
byte *s=(byte *)malloc(image_section_header.SizeOfRawData);
ZeroMemory((void *)s,image_section_header.SizeOfRawData );
fwrite(s,image_section_header.SizeOfRawData ,1,h);


fclose(h);



}
void main(void)
{

addsection("D:\\cmd.exe");

}


文章来自: 本站原创
Tags:
评论: 0 | 查看次数: 8118