I am toying with writing a basic PE packer, whose job is simply to execute the attached target PE in memory. I have spent a couple of days getting intimate with the format, and I think that I have grasped it well enough for the purpose. These are the methods I use:
- Firstly, the target is bundled with the loader by being inserted into the
.datasection of a nasm generated object file, which is later compiled together with the loader.
- Upon execution, the Image Data Directory is examined, and the Import Address Table properly bound by loading the needed libraries and functions.
- The PE and all of its sections need to be properly laid out in memory, hence
SizeOfImageare read, and sufficient virtual memory is allocated for the next two operations.
- PE headers are written into the new location.
- Section data is gathered via section headers, and every section gets written into the new memory space, each into its designated virtual address. Proper permissions via
VirtualProtect()are also set.
The loader, of course, has an exotic image base, as to not conflict with the standard
0x00400000 base. My problems lies somewhere along there. Almost every
.exe has its relocations table stripped, so there's no way to do a base relocation if the desired base address is unavailable. The loader having a non-standard image base solves the problem to an extent. The target's desired base is only available in about 50% of runs. I've tried to find out what might occupy the memory in the other 50%, and have found out that it's almost always a section view. Of what, or whose, I don't know. I've tried to use both
NtFreeVirtualMemory, but they don't solve the problem. The first seems to introduce memory corruption and the second does nothing. Is there any way of claiming that memory? Here's a screenshot from ProcessHacker:
All ideas are welcome.