如何通过pyelftools保存修改的ELF [英] how to save modified ELF by pyelftools
问题描述
最近,我对ELF文件结构感兴趣。在网上搜索时,我发现了一个名为 pyelftools 的出色脚本。但是实际上我不知道保存修改后的ELF的方法; ELFFile类没有任何方法。
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.
首先,我的操作如下:
header = self.elf.header
self._emitline("%s" % header['e_shnum'])
header['e_shnum'] = 30
self._emitline("%s" % header['e_shnum'])
是的,糟糕的方法。但是可悲的是,我不知道在ELF文件中得到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?
问候,
Rex。
推荐答案
根据作者@ eli-bendersky,pyelftools是用于解析和分析ELF / DWARF文件的模块,并且没有直接修改它们的方法。我看了看模块的源文件,也找不到任何编辑/保存的方法。
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.
在介绍性帖子的评论作者承认pyelftools具有没有API级别的支持来执行此操作,但进行一些修补可以帮助您实现所需的功能。
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.
如果pyelftools不是硬依赖项,则以下示例说明了如何使用 elffile :
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())
使用readelf,可以验证更改是否正确保存:
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
关于elffile的文档并不多,但是您可以看一下找出并复制复制pyelftools特定功能的方法。如果不行,您可以尝试同时使用pyelftools和elffile来读取/分析任务,并使用elffile编辑节和编写更改。
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.
这篇关于如何通过pyelftools保存修改的ELF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!