Here I showed how you can get information about the file using filebytes module. In this post I will show you how you can edit files.

All filetype classes have an attribute called _bytes. This is an array which holds the raw bytes of the file. You can edit those bytes and write it to a file. But also it is possible to edit easier specific bytes in the file. It is possible to edit all header fields which are available via the attribute header in every data container. If the header points to another region in the file those bytes are available via the attributes bytes and raw. The attribute raw can be used to edit the bytes of the file. To save the changes the bytes of the file have to be written to a file.

Here is a little example with an ELF file, but all that is also possible for PE, MachO and OAT.

from filebytes.elf import *

ls = ELF('/bin/ls')

# change entry point
ls.elfHeader.header.e_entry = 0x8048AAA

# change code
text_section = [s for s in ls.sections if s.name == '.text'][0]

main_func_addr = 0x8049f30                                          # found with disassembler 
main_func_offset = main_func_addr - text_section.header.sh_addr

text_section.raw[main_func_offset] = 0xc3                           # write ret at beginning of main

# another possibility
text_segment = [s for s in ls.segments if s.header.p_type == PT.LOAD and s.header.p_flags & PF.EXEC][0]

main_func_offset = main_func_addr - text_segment.header.p_vaddr
text_segment.raw[main_func_offset] = 0xc3

with open('new_ls','wb') as f:
    f.write(ls._bytes)