Python:从PE文件中删除一个节
我正在使用Python和pefile库处理PE格式的二进制文件。这个库在读取二进制文件的信息和重写某些字节方面表现得很好。但是现在我想要完全删除文件中的一个部分。
我该怎么做呢?我找到的唯一与此任务相关的代码是在一个叫pop_back()
的函数里,链接是http://goo.gl/YYl5Vb。不过这段代码只删除最后一个部分,而我需要能够删除任何部分。
我想,我可以用类似下面的代码来删除原始部分数据:
dead_sect_start = dead_sect.PointerToRawData
dead_sect_ed = dead_sect.PointerToRawData + dead_sect.SizeOfRawData
pe.__data__ = pe.__data__[:dead_sect_start] + pe.__data__[dead_sect_end:])
其中pe是我解析后的二进制文件,dead_sect是我想要删除的部分。
但是,接下来我该如何修复部分头信息呢?我觉得如果我自己去修改单个头字节,可能会搞得一团糟。pefile库里有没有什么支持这个功能的东西?或者有没有人写过更好的代码可以参考?
提前谢谢你们!
1 个回答
1
你有 pop_back()
函数的源代码,只需要根据你的需求进行修改:
def remove(self, index):
"""Removes a section of the section table.
Deletes the section header in the section table, the data of the section
in the file, removes the section in the sections list of pefile and adjusts
the sizes in the optional header.
"""
# Checking if the section list is long enough to actually remove index.
if (self.pe.FILE_HEADER.NumberOfSections > index
and self.pe.FILE_HEADER.NumberOfSections == len(self.pe.sections)):
# Stripping the data of the section from the file.
if self.pe.sections[index].SizeOfRawData != 0:
self.pe.__data__ =
(self.pe.__data__[:self.pe.sections[index].PointerToRawData] +
self.pe.__data__[self.pe.sections[index].PointerToRawData +
self.pe.sections[index].SizeOfRawData:])
# Overwriting the section header in the binary with nulls.
# Getting the address of the section table and manually overwriting
# the header with nulls unfortunally didn't work out.
self.pe.sections[index].Name = '\x00'*8
self.pe.sections[index].Misc_VirtualSize = 0x00000000
self.pe.sections[index].VirtualAddress = 0x00000000
self.pe.sections[index].SizeOfRawData = 0x00000000
self.pe.sections[index].PointerToRawData = 0x00000000
self.pe.sections[index].PointerToRelocations = 0x00000000
self.pe.sections[index].PointerToLinenumbers = 0x00000000
self.pe.sections[index].NumberOfRelocations = 0x0000
self.pe.sections[index].NumberOfLinenumbers = 0x0000
self.pe.sections[index].Characteristics = 0x00000000
del self.pe.sections[index]
self.pe.FILE_HEADER.NumberOfSections -= 1
self.__adjust_optional_header()
else:
raise SectionDoublePError("There's no section to remove.")
你可以直接把这个函数添加到 SectionDoubleP
类里面,或者在一个 SectionDoubleP
对象上用明确的 self 来调用它:
remove(your_section_double_p, index_of_section_to_remove)
不过在后者的情况下,我建议给它起个比 remove()
更好的名字,哈哈 :)