首页 文章

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

提问于
浏览
0

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

我该怎么办?我找到的关于此任务的唯一代码是http://goo.gl/YYl5Vb函数 pop_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是我要删除的部分 .

但是,我如何修复节 Headers ?如果我自己开始使用单个头字节进行修改,我认为我不会做对 . 在pefile库中是否有一些支持?还是一些代码,比我更有能力的人写的?

提前致谢!

1 回答

  • 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)
    

    在后一种情况下,我会选择一个比_1334009更好的名字,但:)

相关问题