1

I am trying to modify an ELF file's .text segment using python. I successfully acquired the .text field so then I can simply change the bit that I want. The thing is that pyelftools does not provide any way to generate an ELF file from the ELF object.

So what I tried is the following:

I've created a simple helloworld program in c, compiled it and got the a.out file. Then I used the pyelftools to disassemble it.

ex1led
  • 427
  • 5
  • 21
  • what is the actual specific question you have? – sophros Oct 04 '19 at 08:59
  • 3
    Possible duplicate of [how to save modified ELF by pyelftools](https://stackoverflow.com/questions/18569232/how-to-save-modified-elf-by-pyelftools) – sophros Oct 04 '19 at 09:00
  • @sophros I wish to generate a new ELF file based on the old one that I've got from compiling the HelloWorld programm from C. So Ideally I want it to PRODUCE the same output as the a.out file from the gcc. – ex1led Oct 04 '19 at 09:02
  • I am not sure I understand. If you want to produce the same output then copying should do ;) – sophros Oct 04 '19 at 10:26
  • I wish to create a script to modify the .text field of an ELF file. So it takes as input the original ELF, modifies its .text field and then generates a new MODIFIED ELF. With pyelftools i was able to get the text field, find the proper base and offset, get the whole .text field and I am almost ready to manipulate it. BUT before I start flipping bits lets say at the .text field I want to know that the generated file of the application will indeed be an executable ELF. So I simply tried to open teh ELF (create an pyelftools object) and with this loop tried to generate a new one. But no working – ex1led Oct 04 '19 at 11:54

1 Answers1

1

To change/edit any section of the ELF file I simply used pyelftools's ELFFile class methods to acquire the field's (i) offset and (ii) size. So then I know exactly where to look inside the binary file.

So after getting the values-margins of the field (A,B) I simply treated the file like a normal binary. The only thing I did is to do a file.seek(A) to move the file pointer to the specific section that I wish to modify.

def edit_elf_section(elf_object,original_file,section):
    
    elf_section = elf_object.get_section_by_name(section) 
                                             # !! IMPORTANT !!
    section_start = elf_section['sh_offset'] # NOT sh_addr. sh_addr is the logical address of the section
    section_end   = section_start + elf_section['sh_size']
    
    original_file.seek(section_start)

    # Write whatever you want to the file #

    assert(original_file.tell() <= section_end) # You've written outside the section

To validate the results you can use the diff binary to see that the files are/aren't identical

Roman Pokrovskij
  • 9,449
  • 21
  • 87
  • 142
ex1led
  • 427
  • 5
  • 21