Small program to set ALSR-bit
/* PESetASLR.c */
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
//#include <winnt.h>
#include <stdio.h>
int ProcessFile(HANDLE hFile, PBYTE pMem);
int main(int argc, char **argv)
{
HANDLE hFile, hMapping;
VOID *pMem;
if (argc < 2) {
printf("Usage: PESetASLR.exe <file>\n");
return 1;
}
hFile = CreateFile(argv[1], GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if (hFile != INVALID_HANDLE_VALUE) {
hMapping = CreateFileMapping(hFile, NULL, PAGE_READWRITE, 0, 0, NULL);
if (hMapping) {
pMem = MapViewOfFile(hMapping, FILE_MAP_WRITE, 0, 0, 0);
if (pMem) {
ProcessFile(hFile, pMem);
UnmapViewOfFile(pMem);
} else
printf("File open error");
CloseHandle(hMapping);
} else
printf("FileMapping error");
CloseHandle(hFile);
} else
printf("File open error");
return 0;
}
int ProcessFile(HANDLE hFile, PBYTE pMem)
{
PIMAGE_DOS_HEADER pDosHdr;
PIMAGE_NT_HEADERS pNTHeader;
PIMAGE_NT_HEADERS64 pNTHeader64;
DWORD nRelocs;
pDosHdr = (PIMAGE_DOS_HEADER)pMem;
if (pDosHdr->e_magic != IMAGE_DOS_SIGNATURE)
return 1;
pNTHeader = (PIMAGE_NT_HEADERS)(pMem+pDosHdr->e_lfanew);
pNTHeader64 = (PIMAGE_NT_HEADERS64)pNTHeader;
if (pNTHeader->OptionalHeader.DllCharacteristics & 0x0040) {
printf("ASLR bit already set\n");
return 1;
}
BOOL bIs64Bit = ( pNTHeader->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC );
if (bIs64Bit) nRelocs = pNTHeader64->OptionalHeader.DataDirectory[5].Size;
else nRelocs = pNTHeader->OptionalHeader.DataDirectory[5].Size;
if (!nRelocs) {
printf("missing reloc section\n");
return 2;
}
pNTHeader->OptionalHeader.DllCharacteristics += 0x0040;
printf("ASLR bit set\n");
return 0;
}