windowsassemblyreverse-engineeringida

Patching binary with IDA


I'd like to patch some binary (Windows PE) by adding to the program code just standard windows MessageBox. The problem is that the original PE do not import user32 where the MessageBox function is defined.

How can i add/import that needed library to call the MessageBox function in my patching code in IDA PRO (v7.5 SP3)?


Solution

  • IDA is meant for static analysis.

    While it has support for patching, this is very limited. Even considering the linked plug-ins (Keypatch and IDA Patcher), it's still too cumbersome to write a new chunk of assembly code. You can easily guess that seeing and writing one instruction at a time, in a single-line textbox, is too tedious for real assembly programming.

    In your particular case, you want to add a new imported symbol. This is cumbersome because you need to add an entry in the Import Lookup Table and in the Import Address Table. The latter cannot be moved because the linked code is referencing it through immediate offsets. So you'd need to have free space after the IAT, to eventually move the ILT and to find space for all the strings needed. If the user32.dll is already imported you usually cannot add another name entry for it because these tables are packed and there is no space left.
    If you managed to add a new import correctly, IDA should be able to let you assemble (one instruction at a time) code that calls the import.

    I would take another approach, though. I would simply write a position independent self-contained code that would access the PEB to look for the kernel32.dll module and make the minimal amount of code necessary to parse its export directory and get the address of LoadLibraryA/W and GetProcAddress.
    Then I'll have two function pointers that would allow me to import any API at runtime.
    I could test this code easily by assembling it into an executable binary.
    Finally I would use a hex editor to paste the code in the original binary at the position I need. Being the code position independent and self-contained, it would still run fine.
    In case I needed to add a much richer set of funcionality I would consider writing the code to bootstrap a DLL that I would embed in the original binary. I would then develop said DLL by any ordinary means.