Python:从PE文件中删除一个部分

时间:2014-04-19 11:14:21

标签: python reverse-engineering portable-executable

我使用Python和pefile库处理PE二进制文件。为了从二进制文件中读取信息并重写某些字节,该库可以很好地完成它。但现在我想完全从文件中删除一个部分。

我该怎么做?我找到的关于此任务的唯一代码位于http://goo.gl/YYl5Vbpop_back()函数中。但是这段代码只删除了最后一部分,而我需要删除任何部分。

我想,我可以用

之类的东西删除原始部分数据
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 个答案:

答案 0 :(得分:0)

您拥有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()更好的名字,但是:)