Manually Patching a PE File

Apologies if this post doesn’t come out very clear, I’m mostly writing this for myself nor proof reading. This exercise goal is to manually patch a conditional jump in a PE file (download here). While this can be done with two clicks in Immunity Debugger/OllyDbg it will instead be done manually. So, we’ll need to dig up some information in the file during run time (with your favorite debugger), do some math and finally patch it with a hexeditor.

First we need to know what we need to patch, which in itself is another topic. For this I’ll want to patch the following offset in the binary but you can choose something else if you’d rather do that.

patch1

Offset to Patch: 00D72176

Now we need to gather some information from the IMAGE_SECTION_HEADER section in the binary. Namely, we need to find the ImageBase (start of the PE file) and the PointerToRawData (offset from virtual to/and physical address) as well as the RVA of the .text section and the ImageBase. This due to, usually, the code reside in the .text section ;).

Show the Memory of the running binary.

patch2

Here we got the ImageBase and its size (which you can also find in the PE signature).

ImageBase: 00D70000
Size: 0x1000

Also, we need some information from the PE header. Right-click the PE header row and choose ‘Dump to CPU’. Now, by standard, the bottom left window should show the information we’re after. If not, right click it and choose ‘Special -> PE header’. Start to scroll down, when you’ve found the PE signature you know you’re close.

patch3

Continue to scroll down until you come to the .text section.

patch4

PointerToRawData: 0x400

 

Final calculation:

OffsetToPatch: 00D72176
ImageBase: 00D70000
Size(RVA): 0x1000
PointerToRawData: 0x400

(OffsetToPatch - (ImageBase + Size)) + PointerToRawData
(D72176 - (D70000 + 0x1000)) + 0x400
(D72176 - D71000) + 0x400
1176 + 0x400 = 1576

Remember, everything need to be counted in hex!

The value 1576 is the Offset we’re going to look for in the hex editor. In the first picture you can see the opcode for that offset in memory, which should be the same at the value we now have calculated in the binary file. Now, open the file in your favorite hexeditor and jump to offset 1576.

patch5

NOP or change the distance of the conditional jump, it is up to you.

Tags: ,