Rex
Rex

Reputation: 81

how to save modified ELF by pyelftools

Recently I've been interested in ELF File Structure. Searching on web, I found an awesome script named pyelftools. But in fact I didn't know the way to save the modified ELF; ELFFile class doesn't have any method to do.

First of all, I did like below:

            header = self.elf.header
            self._emitline("%s" % header['e_shnum'])
            header['e_shnum'] = 30
            self._emitline("%s" % header['e_shnum'])

Yeah, that's poor way. But sadly I have no idea getting an offset of e_shnum in the ELF file. Is there anybody able to teach me?

Regards,

Rex.

Upvotes: 7

Views: 6759

Answers (1)

7h3rAm
7h3rAm

Reputation: 1895

According to the author @eli-bendersky, pyelftools is a module for parsing and analyzing ELF/DWARF files and it has no direct way of modifying them. I had a look at the module source files and could not find any methods to edit/save either.

On the introductory post, within comments author acknowledges that pyelftools has no API-level support to do this but some tinkering around can help achieve what you need.

If pyelftools is not a hard dependency, here's an example on how to do the same using elffile:

import elffile

eo = elffile.open(name="/bin/ls")
eo.fileHeader.shnum = 30
with open('./ls.bin', 'wb') as f: f.write(eo.pack())

Using readelf, you can verify that changes were saved correctly:

readelf -h ls.bin 
ELF Header:
  Magic:   7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00 
  Class:                             ELF32
  Data:                              2's complement, little endian
  Version:                           1 (current)
  OS/ABI:                            UNIX - System V
  ABI Version:                       0
  Type:                              EXEC (Executable file)
  Machine:                           Intel 80386
  Version:                           0x1
  Entry point address:               0x804be34
  Start of program headers:          105068 (bytes into file)
  Start of section headers:          103948 (bytes into file)
  Flags:                             0x0
  Size of this header:               52 (bytes)
  Size of program headers:           32 (bytes)
  Number of program headers:         9
  Size of section headers:           40 (bytes)
  Number of section headers:         30
  Section header string table index: 27
readelf: Error: Unable to read in 0x708 bytes of section headers

There's not much documentation on elffile but you can have a look at the source and figure out ways to replicate pyelftools-specific functionality. If that doesn't work, you can try using both pyelftools for reading/analyzing tasks and elffile to edit sections and write changes.

Upvotes: 7

Related Questions