Fixed a bug where the script would try to patch addresses outside of the

allowed memory range
This commit is contained in:
Aéna Aria 2026-04-02 13:06:58 +02:00
parent 72281c4401
commit 9e8a6bdb9f

View file

@ -1,6 +1,8 @@
from utils import hex_address_to_memory_representation
import lief
import utils
def patch_direct_adress_call(pe: lief.PE.Binary, rva: int, instruction_offset: int):
# We can manually patch the instruction here: FF 15 08 10 00 01 represents `call [0x01001080]`
new_value = hex_address_to_memory_representation(
@ -9,6 +11,7 @@ def patch_direct_adress_call(pe: lief.PE.Binary, rva: int, instruction_offset: i
pe.abstract.header.endianness == lief.Header.ENDIANNESS.LITTLE,
)
pe.patch_address(instruction_offset, [0xFF, 0x15] + new_value, lief.Binary.VA_TYPES.RVA)
utils.print_debug(f" Patched a call at addr {hex(pe.imagebase+instruction_offset)}")
def patch_direct_adress_jump(pe: lief.PE.Binary, rva: int, instruction_offset: int):
@ -19,6 +22,7 @@ def patch_direct_adress_jump(pe: lief.PE.Binary, rva: int, instruction_offset: i
pe.abstract.header.endianness == lief.Header.ENDIANNESS.LITTLE,
)
pe.patch_address(instruction_offset, [0xFF, 0x25] + new_value, lief.Binary.VA_TYPES.RVA)
utils.print_debug(f" Patched a jump at addr {hex(pe.imagebase+instruction_offset)}")
def patch_instr_to_new_IAT_entry(pe: lief.PE.Binary, call: dict[str, str], rva: int):
@ -45,7 +49,8 @@ def patch_addr_found_in_mem(pe: lief.PE.Binary, rva: int, old_addr: str):
is_32,
little_endian,
)
adresses_to_patch = []
found_ref_addr = []
found_xref_addr = []
for section in pe.sections:
for i in range(len(section.content)):
found = True
@ -54,21 +59,25 @@ def patch_addr_found_in_mem(pe: lief.PE.Binary, rva: int, old_addr: str):
found = False
break
if found:
old_addr_ref = hex_address_to_memory_representation(
ref_addr = hex_address_to_memory_representation(
hex(
section.virtual_address + i + pe.imagebase,
),
is_32,
little_endian,
)
for section in pe.sections:
for k in range(len(section.content)):
foundxref = True
for L in range(len(old_addr_ref)):
if k + L < len(section.content) and section.content[k + L] != old_addr_ref[L]:
foundxref = False
break
if foundxref:
adresses_to_patch.append(section.virtual_address + k)
for addr in adresses_to_patch:
found_ref_addr.append(ref_addr)
for section in pe.sections:
for ref_addr in found_ref_addr:
for k in range(len(section.content)-len(ref_addr)):
foundxref = True
for L in range(len(ref_addr)):
if section.content[k + L] != ref_addr[L]:
foundxref = False
break
if foundxref:
found_xref_addr.append(section.virtual_address + k)
for addr in found_xref_addr:
pe.patch_address(addr, new_addr, lief.Binary.VA_TYPES.RVA)
utils.print_debug(f" Patched an xref to old IAT at {hex(pe.imagebase+addr)}")