Determining Physical Offsets from Virtual Addresses in PE Files
While writing some PE analysis code I needed to calculate the actual physical offset in a PE file for a given RVA (relative virtual address). Looking around on the Internet it was non-obvious. The Metasploit Framework's msfpescan was actually the most help. I've ported it to Ero Carrera's pefile module and attached the patch to this post. Pefile is a Python module that I highly recommend.
Read more for the simple technique.
- Find the section that the RVA is in. In this example we'll use the AddressOfEntryPoint in the OPTIONAL_HEADER field.
pe = pefile.PE('malware.exe')
section = pe.get_section_by_rva(pe.OPTIONAL_HEADER.AddressOfEntryPoint)
- Next calculate the displacement between the section and the virtual address
phystovirt = section.VirtualAddress - section.PointerToRawData
- Finally use that to calcuate the real file offset in the PE
realoffset = rva - phystovirt
I've attached a patch to pefile version 1.1 Enjoy.