How to use pefile - 10 common examples

To help you get started, we’ve selected a few pefile examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github PUNCH-Cyber / stoq-plugins-public / v2 / peinfo / peinfo / peinfo.py View on Github external
return

            rich_hdr['checksum'] = hex(rich_hdr['checksum'])

            # Generate a signature of the block. Need to apply checksum
            # appropriately. The hash here is sha256 because others are using
            # that here.
            #
            # Most of this code was taken from pefile but modified to work
            # on the start and checksum blocks.
            try:
                rich_data = pe.get_data(0x80, 0x80)
                if len(rich_data) != 0x80:
                    return None
                data = list(struct.unpack("<32I", rich_data))
            except pefile.PEFormatError as e:
                return None

            checksum = data[1]
            headervalues = []

            for i in range(len(data) // 2):
                if data[2 * i] == 0x68636952:  # Rich
                    if data[2 * i + 1] != checksum:
                        self.log.error('Rich Header corrupted')
                    break
                headervalues += [data[2 * i] ^ checksum, data[2 * i + 1] ^ checksum]

            sha_256 = hashlib.sha256()
            for hv in headervalues:
                sha_256.update(struct.pack('
github hyuunnn / Hyara / old_version / YaraGenerator_old.py View on Github external
self.label1 = QLabel("Start Offset : ")
        self.label2 = QLabel("Length : ")
        self.label3 = QLabel("Variable name : ")
        self.LineEdit1 = QLineEdit()
        self.LineEdit2 = QLineEdit()
        self.LineEdit3 = QLineEdit()
        self.PushButton1 = QPushButton("Enter")
        self.PushButton1.clicked.connect(self.YaraMaker) 

        for section in self.pe.sections:
            self.section_list[section.Name.decode("utf-8").replace("\x00","")] = [hex(section.VirtualAddress), hex(section.SizeOfRawData), hex(section.PointerToRawData)]

        for entry in self.pe.DIRECTORY_ENTRY_RESOURCE.entries:
            resource_type = entry.name
            if resource_type is None:
                resource_type = pefile.RESOURCE_TYPE.get(entry.struct.Id)

            for directory in entry.directory.entries:
                for resource in directory.directory.entries:
                    name = str(resource_type)
                    if name in "RT_ICON":
                        name = str(resource_type)
                        offset = resource.data.struct.OffsetToData
                        size = resource.data.struct.Size
                        RVA_ = int(self.section_list['.rsrc'][0],16) - int(self.section_list['.rsrc'][2],16)
                        real_offset = offset - RVA_
                        img_size = hex(size)[2:]
                        if len(img_size) % 2 == 1:
                            img_size = "0"+img_size

                        img_ = "\x00\x00\x01\x00\x01\x00\x30\x30\x00\x00\x01\x00\x08\x00" + bytearray.fromhex(img_size)[::-1] + "\x00\x00\x16\x00\x00\x00"
                        f = open(GetInputFilePath(),"rb")
github doomedraven / VirusTotalApi / vt / vt.py View on Github external
def fileInfo(self, *args,  **kwargs):
        if PEFILE:
            files = kwargs.get('value')
            for file in files:
                try:
                    pe = pefile.PE(file)
                except pefile.PEFormatError:
                    print '[-] Not PE file'
                    return

                print "\nName: {0}".format(file.split("/")[-1])

                print "\n[+] Hashes"
                print "MD5: {0}".format(pe.sections[0].get_hash_md5())
                print "SHA1: {0}".format(pe.sections[0].get_hash_sha1())
                print "SHA256: {0}".format(pe.sections[0].get_hash_sha256())
                print "SHA512: {0}".format(pe.sections[0].get_hash_sha512())
                try:
                    print 'ImpHash: {0}'.format(pe.get_imphash())
                except:
                    pass

                if pe.FILE_HEADER.TimeDateStamp:
github fireeye / flare-ida / shellcode_hashes / make_sc_hash_db.py View on Github external
if sym.name is not None:
                            symCount += 1
                            for hashName in self.hashes.keys():
                                hashType, hashMeth = self.hashes[hashName]
                                #print "Trying to hash: %s:%s" % (hashName, sym.name)
                                symHash = hashMeth(sym.name,fName)
                                #print " Done hashing: %08x:%s" % (symHash, sym.name)
                                if symHash is not None:
                                    self.addSymbolHash(symHash, hashType, libKey, sym.name)
                    #commit outstanding transaction
                    self.conn.commit()
                    time2 = time.time()
                    timeDiff = time2 - time1
                    print "Processed %d export symbols in %.02f seconds: %s" % (symCount, timeDiff, filePath)

            except pefile.PEFormatError, err:
                if VERBOSE:
                    print "Skipping non-PE file %s: %s" % (filePath, str(err))
            except Exception, err:
                if VERBOSE:
                    print "Skipping %s: %s" % (filePath, str(err))
                raise
github fr0gger / unprotect / windows_unprotect / unprotect.py View on Github external
if len(sys.argv) == 2 and sys.argv[1] == "-h" or sys.argv[1] == "--help":
        help()
        exit(0)
		
    if len(sys.argv) == 2:

        print module.config.__asciiart__
        print "\t\t" + module.config.__copyright__ + " | " + module.config.__author__
        # print "\t\t\tUnprotect malware for the mass"

        try:
            exe = pefile.PE(exefile)
        except OSError as e:
            print(e)
            sys.exit()
        except pefile.PEFormatError as e:
            print  "[-] PEFormatError: %s" % e.value
            print  "[!] The file is not a valid PE"
            sys.exit()

        strings_list, decoded_strings = get_strings(exefile)

        concatenate_strings = strings_list + decoded_strings

        print "\nPE Summary"
        print "-" * 80

        fname, fsize, tsdate, dll, nsec = get_info(exe, exefile)

        #print  "File type:\t %s" % ftype
        print  "File name:\t %s" % fname
        print  "File size:\t %s Bytes" % fsize
github devwerks / Static-Malware-Analyses / malware-analyses.py View on Github external
for resource_type in pe.DIRECTORY_ENTRY_RESOURCE.entries:
                if resource_type.name is not None:
                    name = "%s" % resource_type.name
                    print name
                else:
                    name = "%s" % pefile.RESOURCE_TYPE.get(resource_type.struct.Id)
                if name == None:
                    name = "%d" % resource_type.struct.Id
                for resource_id in resource_type.directory.entries:
                    if hasattr(resource_type, 'directory'):
                        for resource_id in resource_type.directory.entries:
                            if hasattr(resource_id, 'directory'):
                                for resource_lang in resource_id.directory.entries:
                                    data = pe.get_data(resource_lang.data.struct.OffsetToData, resource_lang.data.struct.Size)
                                    lang = pefile.LANG.get(resource_lang.data.lang)
                                    sublang = pefile.get_sublang_name_for_lang(resource_lang.data.lang, resource_lang.data.sublang)
                                    html.write("%s %s %s %s %s\n" % (name, hex(resource_lang.data.struct.OffsetToData), hex(resource_lang.data.struct.Size), lang, sublang))

            html.write("\n")

            insertSeperator(html)

            # get printable strings in the binary file by calling the external program strings
            strings = subprocess.check_output(["strings", filePath])

            html.write("<br><b><a id="strings">Strings:</a></b><br>\n")
            html.write("<br>\n".join(strings.split()))
github kevthehermit / RATDecoders / StandAlone / CyberGate.py View on Github external
def configExtract(rawData):
	try:
		pe = pefile.PE(data=rawData)

		try:
		  rt_string_idx = [
		  entry.id for entry in 
		  pe.DIRECTORY_ENTRY_RESOURCE.entries].index(pefile.RESOURCE_TYPE['RT_RCDATA'])
		except ValueError, e:
			return None
		except AttributeError, e:
			return None

		rt_string_directory = pe.DIRECTORY_ENTRY_RESOURCE.entries[rt_string_idx]

		for entry in rt_string_directory.directory.entries:
			if str(entry.name) == "XX-XX-XX-XX" or str(entry.name) == "CG-CG-CG-CG":
				data_rva = entry.directory.entries[0].data.struct.OffsetToData
				size = entry.directory.entries[0].data.struct.Size
				data = pe.get_memory_mapped_image()[data_rva:data_rva+size]
				config = data.split('####@####')
				return config
	except:
		return None
github hyuunnn / Hyara / IDA Plugin / old_version / Hyara_Using_simplecustviewer_Choose.py View on Github external
icon4 = QLabel("Save Rule")
        icon4.setAlignment(Qt.AlignCenter)

        self.LineEdit1 = QLineEdit()
        self.LineEdit2 = QLineEdit()
        self.LineEdit3 = QLineEdit()
        self.PushButton1 = QPushButton("Enter")
        self.PushButton1.clicked.connect(self.YaraMaker) 

        for section in self.pe.sections:
            self.section_list[section.Name.decode("utf-8").replace("\x00","")] = [hex(section.VirtualAddress), hex(section.SizeOfRawData), hex(section.PointerToRawData)]

        for entry in self.pe.DIRECTORY_ENTRY_RESOURCE.entries:
            resource_type = entry.name
            if resource_type is None:
                resource_type = pefile.RESOURCE_TYPE.get(entry.struct.Id)

            for directory in entry.directory.entries:
                for resource in directory.directory.entries:
                    name = str(resource_type)
                    if name in "RT_ICON":
                        name = str(resource_type)
                        offset = resource.data.struct.OffsetToData
                        size = resource.data.struct.Size
                        RVA_ = int(self.section_list['.rsrc'][0],16) - int(self.section_list['.rsrc'][2],16)
                        real_offset = offset - RVA_
                        img_size = hex(size)[2:]
                        if len(img_size) % 2 == 1:
                            img_size = "0"+img_size

                        img_ = "\x00\x00\x01\x00\x01\x00\x30\x30\x00\x00\x01\x00\x08\x00" + bytearray.fromhex(img_size)[::-1] + "\x00\x00\x16\x00\x00\x00"
                        f = open(GetInputFilePath(),"rb")
github kevthehermit / RATDecoders / StandAlone / Xena.py View on Github external
def get_config(raw_data):
    try:
        pe = pefile.PE(data=raw_data)
        rt_string_idx = [entry.id for entry in pe.DIRECTORY_ENTRY_RESOURCE.entries].index(pefile.RESOURCE_TYPE['RT_RCDATA'])
        rt_string_directory = pe.DIRECTORY_ENTRY_RESOURCE.entries[rt_string_idx]
        for entry in rt_string_directory.directory.entries:
            if str(entry.name) == "CFG":
                data_rva = entry.directory.entries[0].data.struct.OffsetToData
                size = entry.directory.entries[0].data.struct.Size
                data = pe.get_memory_mapped_image()[data_rva:data_rva+size]
                config = data.split('##')
                return config
    except:
        return None
github kevthehermit / RATDecoders / decoders / CyberGate.py View on Github external
def extract_config(raw_data):
    try:
        pe = pefile.PE(data=raw_data)

        try:
            rt_string_idx = [
                entry.id for entry in pe.DIRECTORY_ENTRY_RESOURCE.entries
            ].index(pefile.RESOURCE_TYPE['RT_RCDATA'])
        except ValueError, e:
            return None
        except AttributeError, e:
            return None

        rt_string_directory = pe.DIRECTORY_ENTRY_RESOURCE.entries[rt_string_idx]

        for entry in rt_string_directory.directory.entries:
            if str(entry.name) == 'XX-XX-XX-XX' or str(entry.name) == 'CG-CG-CG-CG':
                data_rva = entry.directory.entries[0].data.struct.OffsetToData
                size = entry.directory.entries[0].data.struct.Size
                data = pe.get_memory_mapped_image()[data_rva:data_rva+size]
                config = data.split('####@####')
                return config
    except:
        return None