I'm having some strange errors with the following function which adds a section to a pe executable. When I run the program I get the success message, when I proceed to try to open the executable in ollydbg I get an invalid file error, I then open it in LordPE and find that the section has been added and everything seems to be in order, when I again open the executable in ollydbg it opens the executable and I can see that the section has been added though all the fields aside from section name are set to 0. I have tried this many times and get the same result with different executables.
void addSection(char* fileName)
{
HANDLE hFile = CreateFile(fileName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if(hFile !=INVALID_HANDLE_VALUE){
DWORD fileSize = GetFileSize(hFile, NULL);
BYTE *byte = new BYTE[fileSize];
DWORD numberOfBytesReadTracker;
ReadFile(hFile, byte, fileSize, &numberOfBytesReadTracker, NULL);
IMAGE_DOS_HEADER *dosHeader = (IMAGE_DOS_HEADER*)byte;
IMAGE_NT_HEADERS *ntHeader = (IMAGE_NT_HEADERS*)((DWORD)byte+dosHeader->e_lfanew);
if(dosHeader->e_magic==IMAGE_DOS_SIGNATURE && ntHeader->Signature == IMAGE_NT_SIGNATURE){
IMAGE_FILE_HEADER *fileHeader = (IMAGE_FILE_HEADER*)((DWORD)byte+dosHeader->e_lfanew+sizeof(IMAGE_NT_SIGNATURE));
IMAGE_OPTIONAL_HEADER *optionalHeader = (IMAGE_OPTIONAL_HEADER*)((DWORD)byte+dosHeader->e_lfanew+sizeof(IMAGE_NT_SIGNATURE)+sizeof(IMAGE_FILE_HEADER));
IMAGE_SECTION_HEADER *sectionHeader = (IMAGE_SECTION_HEADER*)((DWORD)ntHeader+sizeof(IMAGE_NT_HEADERS));
const char *sectionName = "AddedSec";
ZeroMemory(§ionHeader[fileHeader->NumberOfSections], sizeof(IMAGE_SECTION_HEADER));
CopyMemory(§ionHeader[fileHeader->NumberOfSections].Name, sectionName, 8);
sectionHeader[fileHeader->NumberOfSections].Characteristics = 0x60500060;
sectionHeader[fileHeader->NumberOfSections].Misc.VirtualSize = 0x1000;
sectionHeader[fileHeader->NumberOfSections].VirtualAddress = sectionHeader[fileHeader->NumberOfSections-1].VirtualAddress+optionalHeader->SectionAlignment;
sectionHeader[fileHeader->NumberOfSections].SizeOfRawData = optionalHeader->FileAlignment;
sectionHeader[fileHeader->NumberOfSections].PointerToRawData = sectionHeader[fileHeader->NumberOfSections-1].PointerToRawData+sectionHeader[fileHeader->NumberOfSections-1].SizeOfRawData;
fileHeader->NumberOfSections = fileHeader->NumberOfSections+1;
optionalHeader->SizeOfImage = optionalHeader->SizeOfImage+alignToSectionAlignment(sectionHeader[fileHeader->NumberOfSections].Misc.VirtualSize, optionalHeader->SectionAlignment);
cout << "ADDED SECTION" << endl;
SetFilePointer(hFile, 0, NULL, FILE_BEGIN);
WriteFile(hFile, byte, fileSize, &numberOfBytesReadTracker, NULL);
}else{
cout << "Is not a PE executbale" << endl;
}
CloseHandle(hFile);
}
}