ex1led
ex1led

Reputation: 469

How to MODIFY an ELF file with Python

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.

Upvotes: 1

Views: 6846

Answers (2)

pansila
pansila

Reputation: 177

You can use LIEF

import lief

b = lief.parse('main')
print(b.type)
s = b.get_symbol('main')
print(s.name)
s.name = 'test'
b.write('main.new')

Upvotes: 0

ex1led
ex1led

Reputation: 469

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

Upvotes: 1

Related Questions