print("usage: python3 <PePath>")
if pe_file.FILE_HEADER.Machine == 0x014c:
elif pe_file.FILE_HEADER.Machine ==0x0200 or pe_file.FILE_HEADER.Machine == 0x8664:
print("[-]unknow the format of this pe file")
def get_patch_stub(pe_file,func_offset):
b"\xE8\x00\x00\x00\x00" +#call <next_line>
b"\x48\x83\xEB\x09" +# sub ebx,9
b"\x53" +# push ebx (Image Base)
b"\x48\x81\xC3" +# add ebx,
pack("<I",func_offset) +# value
pe_file =pefile.PE(pe_path)
reflective_stub = open('stub64.bin','rb').read()
reflective_stub = open('stub32.bin','rb').read()
cave_size=len(reflective_stub);
for section in pe_file.sections:
section_cave_size = section.SizeOfRawData - section.Misc_VirtualSize
section_cave_location =section.Misc_VirtualSize + section.PointerToRawData
print("[+] looking for a codecave in %s sizeof %d offset of %x" % (section.Name,section_cave_size,section_cave_location))
if section_cave_size > cave_size:
patch_size=section_cave_size
patch_location = section_cave_location
print("[-] not enough size code cvae found ")
patch_stub = get_patch_stub(pe_file,patch_location)
pe_file_array = open(pe_path,'rb').read()
print("[+] loaded nameof %s"% (pe_path))
patch_pe_file = patch_stub + pe_file_array[len(patch_stub):patch_location] + reflective_stub +pe_file_array[patch_location+len(reflective_stub):]
print("[+] patched offset %x" % (section_cave_location))
patch_pe_name = "patch-" +pe_path
open(patch_pe_name,'wb').write(patch_pe_file)
print("[+] wrote nameof %s"% (patch_pe_name))
if __name__ == '__main__':