Python pefile.PE Examples

The following are 30 code examples of pefile.PE(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pefile , or try the search function .
Example #1
Source File: loki.py    From malware_decoders with MIT License 6 votes vote down vote up
def find_key(pe):
	ret = None
	if type(pe) == pefile.PE:
		t = pe.get_memory_mapped_image()
	else:
		t = pe
	temp = re.findall(r'''\x68...\x00\x68...\x00\x68...\x00\x03\xc1''',t)
	if temp != []:
		ret = '\x08\x02\x00\x00\x03\x66\x00\x00\x18\x00\x00\x00'
		temp = temp[0][:-2].split('\x68')[::-1]
		for a in temp:
			if a != '':
				(addr,) = struct.unpack_from('<I',a)
				#print(hex(addr))
				addr -= 0x400000
				ret += t[addr:addr+8]
	return ret 
Example #2
Source File: pe.py    From qiew with GNU General Public License v2.0 6 votes vote down vote up
def disasmSymbol(self, va):
        if not hasattr(self.PE, 'DIRECTORY_ENTRY_IMPORT'):
            return None

        # TODO: should implement with a lookup table
        for i, entry in enumerate(self.PE.DIRECTORY_ENTRY_IMPORT):

            for imp in entry.imports:
                if imp.address == va:
                    name = ''
                    if imp.name:
                        name = imp.name

                    if imp.ordinal:
                        name = bytes(imp.ordinal)

                    return '{0}:{1}'.format(entry.dll.decode('cp437'), name.decode('cp437'))

        return None 
Example #3
Source File: pescanner.py    From CapTipper with GNU General Public License v3.0 6 votes vote down vote up
def check_verinfo(self, pe):
        """ Determine the version info in a PE file """
        ret = []
        
        if hasattr(pe, 'VS_VERSIONINFO'):
            if hasattr(pe, 'FileInfo'):
                for entry in pe.FileInfo:
                    if hasattr(entry, 'StringTable'):
                        for st_entry in entry.StringTable:
                            for str_entry in st_entry.entries.items():
                                ret.append(convert_to_printable(str_entry[0]) + ': ' + convert_to_printable(str_entry[1]) )
                    elif hasattr(entry, 'Var'):
                        for var_entry in entry.Var:
                            if hasattr(var_entry, 'entry'):
                                ret.append(convert_to_printable(var_entry.entry.keys()[0]) + ': ' + var_entry.entry.values()[0])
        return '\n'.join(ret) 
Example #4
Source File: malwoverview.py    From malwoverview with GNU General Public License v3.0 6 votes vote down vote up
def listsections(fname):

    pe=pefile.PE(fname)

    if(windows == 1):
        print("Sections: ", end='')
        print("\t\tEntropy\n")
        for sect in pe.sections:
            print("%17s" % (sect.Name).decode('utf-8'), end='')
            print(("\t%5.2f" % sect.get_entropy()))
    else:
        print("Sections: ", end='')
        print("\t\tEntropy\n")
        for sect in pe.sections:
            print("%17s" % (sect.Name).decode('utf-8'), end='')
            print(("\t\t%5.2f" % sect.get_entropy())) 
Example #5
Source File: pe.py    From qiew with GNU General Public License v2.0 6 votes vote down vote up
def kEND(self, k):
        gtype = str(self.ui.comboBox.currentText())

        if gtype == 'FileAddress':
            return self.plugin.dataModel.getDataSize()

        elif gtype == 'VirtualAddress':
            offset = self.plugin.dataModel.getDataSize()
            return self.plugin.PE.get_rva_from_offset(offset) + self.plugin.PE.OPTIONAL_HEADER.ImageBase
        elif gtype == 'RVA':
            offset = self.plugin.dataModel.getDataSize()
            return self.plugin.PE.get_rva_from_offset(offset)
        else:
            return None

    # goto address type fa/va/rva 
Example #6
Source File: pe.py    From qiew with GNU General Public License v2.0 6 votes vote down vote up
def eventFilter(self, watched, event):
        if event.type() == QtCore.QEvent.KeyPress:
            if event.key() == QtCore.Qt.Key_Return:

                # get RVA column from treeView
                item = self.widget.currentItem()
                rva = self.widget.indexFromItem(item, 1).data()
                if rva:
                    rva = str(rva)
                    # strip 0x
                    rva = int(rva, 0)

                    offset = self.plugin.PE.get_offset_from_rva(rva)

                    self.plugin._viewMode.goTo(offset)

        return False 
Example #7
Source File: static.py    From mac-a-mal-cuckoo with MIT License 6 votes vote down vote up
def run(self):
        """Run analysis.
        @return: analysis results dict or None.
        """
        if not os.path.exists(self.file_path):
            return {}

        try:
            self.pe = pefile.PE(self.file_path)
        except pefile.PEFormatError:
            return {}

        results = {}
        results["peid_signatures"] = self._get_peid_signatures()
        results["pe_imports"] = self._get_imported_symbols()
        results["pe_exports"] = self._get_exported_symbols()
        results["pe_sections"] = self._get_sections()
        results["pe_resources"] = self._get_resources()
        results["pe_versioninfo"] = self._get_versioninfo()
        results["pe_imphash"] = self._get_imphash()
        results["pe_timestamp"] = self._get_timestamp()
        results["pdb_path"] = self._get_pdb_path()
        results["signature"] = self._get_signature()
        results["imported_dll_count"] = len([x for x in results["pe_imports"] if x.get("dll")])
        return results 
Example #8
Source File: pe.py    From plaso with Apache License 2.0 6 votes vote down vote up
def _GetSectionNames(self, pefile_object):
    """Retrieves all PE section names.

    Args:
      pefile_object (pefile.PE): pefile object.

    Returns:
      list[str]: names of the sections.
    """
    section_names = []
    for section in pefile_object.sections:
      section_name = getattr(section, 'Name', b'')
      # Ensure the name is decoded correctly.
      try:
        section_name = '{0:s}'.format(section_name.decode('unicode_escape'))
      except UnicodeDecodeError:
        section_name = '{0:s}'.format(repr(section_name))
      section_names.append(section_name)

    return section_names 
Example #9
Source File: pe.py    From plaso with Apache License 2.0 6 votes vote down vote up
def _GetImportTimestamps(self, pefile_object):
    """Retrieves timestamps from the import directory, if available.

    Args:
      pefile_object (pefile.PE): pefile object.

    Returns:
      list[int]: import timestamps.
    """
    import_timestamps = []
    if not hasattr(pefile_object, 'DIRECTORY_ENTRY_IMPORT'):
      return import_timestamps
    for importdata in pefile_object.DIRECTORY_ENTRY_IMPORT:
      dll_name = getattr(importdata, 'dll', '')
      try:
        dll_name = dll_name.decode('ascii')
      except UnicodeDecodeError:
        dll_name = dll_name.decode('ascii', errors='replace')
      if not dll_name:
        dll_name = '<NO DLL NAME>'

      timestamp = getattr(importdata.struct, 'TimeDateStamp', 0)
      if timestamp:
        import_timestamps.append([dll_name, timestamp])
    return import_timestamps 
Example #10
Source File: pe.py    From plaso with Apache License 2.0 6 votes vote down vote up
def _GetResourceTimestamps(self, pefile_object):
    """Retrieves timestamps from resource directory entries, if available.

    Args:
      pefile_object (pefile.PE): pefile object.

    Returns:
      list[int]: resource timestamps.
    """
    timestamps = []
    if not hasattr(pefile_object, 'DIRECTORY_ENTRY_RESOURCE'):
      return timestamps
    for entrydata in pefile_object.DIRECTORY_ENTRY_RESOURCE.entries:
      directory = entrydata.directory
      timestamp = getattr(directory, 'TimeDateStamp', 0)
      if timestamp:
        timestamps.append(timestamp)
    return timestamps 
Example #11
Source File: pe.py    From plaso with Apache License 2.0 6 votes vote down vote up
def _GetDelayImportTimestamps(self, pefile_object):
    """Retrieves timestamps from delay import entries, if available.

    Args:
      pefile_object (pefile.PE): pefile object.

    Returns:
      tuple[str, int]: name of the DLL being imported and the second is
          the timestamp of the entry.
    """
    delay_import_timestamps = []
    if not hasattr(pefile_object, 'DIRECTORY_ENTRY_DELAY_IMPORT'):
      return delay_import_timestamps
    for importdata in pefile_object.DIRECTORY_ENTRY_DELAY_IMPORT:
      dll_name = importdata.dll
      try:
        dll_name = dll_name.decode('ascii')
      except UnicodeDecodeError:
        dll_name = dll_name.decode('ascii', errors='replace')

      timestamp = getattr(importdata.struct, 'dwTimeStamp', 0)
      delay_import_timestamps.append([dll_name, timestamp])
    return delay_import_timestamps 
Example #12
Source File: analyze_backspace.py    From grap with MIT License 6 votes vote down vote up
def decrypt_strings(algo, str_tuple, bin_path):
    try:
        data = open(bin_path, "rb").read()
        pe = pefile.PE(data=data)
        base_addr = pe.OPTIONAL_HEADER.ImageBase
    except:
        print("error: pefile")
        sys.exit(1)

    decrypted = []
    for size, addr in str_tuple:
        d = pe.get_data(addr - base_addr, size)
        decrypted_str = decrypt_str(d, algo)
        if decrypted_str is not None:
            decrypted.append(decrypted_str)

    return decrypted 
Example #13
Source File: python_exe_unpack.py    From python-exe-unpacker with GNU General Public License v3.0 6 votes vote down vote up
def open_executable(self):
        try:
            if not os.path.exists(self.file_path):
                raise FileNotFoundException 

            pe_file = pefile.PE(self.file_path)
            if not (pe_file.is_dll() or pe_file.is_exe()):
                raise FileFormatException    

            self.fPtr = open(self.file_path, 'rb')
            self.fileSize = os.stat(self.file_path).st_size
        except FileFormatException:
            print("[-] Not an executable")
            sys.exit(1)
        except FileNotFoundException:
            print("[-] No such file")
            sys.exit(1)
        except:
            print("[-] Error: Could not open {0}".format(self.file_path))
            sys.exit(1) 
Example #14
Source File: python_exe_unpack.py    From python-exe-unpacker with GNU General Public License v3.0 6 votes vote down vote up
def is_magic_recognised(self):
        self.open_executable()
        is_py2exe = False
        script_resource = None
        pe_file = pefile.PE(self.file_path)

        if hasattr(pe_file,'DIRECTORY_ENTRY_RESOURCE'):
            for entry in pe_file.DIRECTORY_ENTRY_RESOURCE.entries:
                if str(entry.name) == str("PYTHONSCRIPT"):
                    script_resource = entry.directory.entries[0].directory.entries[0]                
                    break
        
        if script_resource != None:
            rva = script_resource.data.struct.OffsetToData
            size = script_resource.data.struct.Size
            dump = pe_file.get_data(rva, size)
            current = struct.calcsize(b'iiii')
            metadata = struct.unpack(b'iiii', dump[:current])
            if hex(metadata[0]) == "0x78563412":
                is_py2exe = True

        self.close()
        return is_py2exe 
Example #15
Source File: syscall_extractor.py    From mayhem with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def main():
	output_formats = copy.copy(tabulate.tabulate_formats)
	output_formats.append('json')
	parser = argparse.ArgumentParser(description='syscall_extractor: Extract syscalls from a Windows PE file', conflict_handler='resolve')
	parser.add_argument('-f', '--format', dest='output_format', default='simple', choices=output_formats, help='output format')
	parser.add_argument('pe_files', nargs='+', help='pe files to extract syscall numbers from')
	args = parser.parse_args()

	parsed_files = []
	for pe_file in args.pe_files:
		parsed_files.append(extract_syscalls(os.path.abspath(pe_file)))
	parsed_files = list(pe_file for pe_file in parsed_files if pe_file)
	print("[+] Found {0:,} syscalls".format(sum(len(pe_file['syscalls']) for pe_file in parsed_files)))

	if args.output_format == 'json':
		print(json.dumps(parsed_files, sort_keys=True, indent=2, separators=(',', ': ')))
	else:
		syscalls = []
		for pe_file in parsed_files:
			syscalls.extend(pe_file['syscalls'])
		syscalls = ((syscall[0], hex(syscall[1]), syscall[2], syscall[3]) for syscall in syscalls)
		print(tabulate.tabulate(syscalls, headers=('Number', 'RVA', 'Name', 'Ordinal'), tablefmt=args.output_format))
	return 0 
Example #16
Source File: bozok.py    From CIRTKit with MIT License 6 votes vote down vote up
def extract_config(raw_data):
    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:
        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) == '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]
            return data 
Example #17
Source File: darkcomet.py    From CIRTKit with MIT License 6 votes vote down vote up
def extract_config(raw_data, key):            
    config = BASE_CONFIG

    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) == 'DCDATA':
            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 = v51_data(data, key)
        elif str(entry.name) in config.keys():
            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]
            dec = rc4crypt(unhexlify(data), key)
            config[str(entry.name)] = filter(lambda x: x in string.printable, dec)

    return config 
Example #18
Source File: xrat.py    From CIRTKit with MIT License 6 votes vote down vote up
def get_long_line(data):
    try:
        raw_config = None
        pe = pefile.PE(data=data)
        for entry in pe.DIRECTORY_ENTRY_RESOURCE.entries:
            if str(entry.name) == "RT_RCDATA":
                new_dirs = entry.directory
                for entry in new_dirs.entries:
                    if str(entry.name) == '0':
                        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]
                        raw_config = data
    except:
        raw_config = None
    if raw_config != None:
        return raw_config, 'V1'
    try:
        m = re.search('\x69\x00\x6F\x00\x6E\x00\x00\x59(.*)\x6F\x43\x00\x61\x00\x6E', data)
        raw_config = m.group(0)[4:-12]
        return raw_config, 'V2'
    except:
        return None, None 
Example #19
Source File: pe.py    From CIRTKit with MIT License 6 votes vote down vote up
def sections(self):
        if not self.__check_session():
            return

        rows = []
        for section in self.pe.sections:
            rows.append([
                section.Name,
                hex(section.VirtualAddress),
                hex(section.Misc_VirtualSize),
                section.SizeOfRawData,
                section.get_entropy()
            ])

        self.log('info', "PE Sections:")
        self.log('table', dict(header=['Name', 'RVA', 'VirtualSize', 'RawDataSize', 'Entropy'], rows=rows)) 
Example #20
Source File: unpy2exe.py    From rePy2exe with GNU General Public License v3.0 6 votes vote down vote up
def unpy2exe(filename, python_version=None, output_dir=None):
    """Process input params and produce output pyc files."""
    if python_version is None:
        version = __current_magic()
    else:
        version = versions.get(python_version, __current_magic())

    if output_dir is None:
        output_dir = '.'
    elif not os.path.exists(output_dir):
        os.makedirs(output_dir)

    pe = pefile.PE(filename)
    script_res = get_scripts_resource(pe)
    dump = resource_dump(pe, script_res)
    code_objects = get_co_from_dump(dump)
    for co in code_objects:
        save_co_to_pyc(co, version, output_dir) 
Example #21
Source File: disassembler.py    From grap with MIT License 6 votes vote down vote up
def dis(self, data, offset, iat_api, bin_instance, verbose=False):
        '''
            data: raw binary of full PE
            va: va of the instruction located at <data[index]>
            iat_api: dict of imported API like {VA_IN_IAT: API_NAME}
        '''

        insts = dict()
        insts = self.linear_sweep_cache(data=data, offset=offset, insts=insts, bin_instance=bin_instance, verbose=verbose)
        insts = self._dis(data=data, offset=offset, iat_api=iat_api, bin_instance=bin_instance, insts=insts, verbose=verbose)

        # Exploration of the exported functions
        self._dis_exported_funcs(bin_instance=bin_instance, insts=insts, data=data, verbose=verbose, iat_api=iat_api)

        # Search for unrecognized functions from their prolog function
        insts = self.dis_prologues(data=data, bin_instance=bin_instance, iat_api=iat_api, insts=insts, verbose=verbose)

        return insts 
Example #22
Source File: r2_hash_func_decoder.py    From radare2-scripts with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def parse_file(connection, path):
    c = connection.cursor()

    if path.endswith(".dll") or path.endswith(".exe"):
        print("Processing %s..." % (path))
        abs_path = os.path.abspath(path)
        f = pefile.PE(abs_path)
        for sym in f.DIRECTORY_ENTRY_EXPORT.symbols:
            if sym.name is not None:
                for technique in TECHNIQUES:
                    sql_command = "SELECT id FROM techniques WHERE technique=?"
                    c.execute(sql_command, (technique,))
                    technique_id = c.fetchone()[0]
                    dll_name = bytes(os.path.basename(path), 'ascii')
                    h = eval(technique)(sym.name, dll_name)
                    sql_command = "INSERT OR REPLACE INTO hashes VALUES (?, ?, ?, ?)"
                    c.execute(sql_command, (technique_id, int(h), str(sym.name, 'ascii'), str(dll_name, 'ascii')))

    connection.commit() 
Example #23
Source File: loki.py    From malware_decoders with MIT License 6 votes vote down vote up
def find_conf(pe):
	ret = []

	dlen = 8*4
	if type(pe) == pefile.PE:
		t = pe.get_memory_mapped_image()
	else:
		t = pe
	off = t.find('\x6a\x08\x59\xbe')
	(addr,) = struct.unpack_from('<I',t[off+4:])
	#print(hex(addr))
	addr -= 0x400000
	data = t[addr:addr+dlen]
	ret.append(data)

	dlen = 10*4
	off = t.find('\x6a\x0a\x59\xbe')
	(addr,) = struct.unpack_from('<I',t[off+4:])
	#print(hex(addr))
	addr -= 0x400000
	data = t[addr:addr+dlen]
	ret.append(data)

	return ret 
Example #24
Source File: malwoverview.py    From malwoverview with GNU General Public License v3.0 6 votes vote down vote up
def listimports(fname):

    I = []
    mype2=pefile.PE(fname,fast_load=True)
    if mype2.OPTIONAL_HEADER.DATA_DIRECTORY[pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_IMPORT']].VirtualAddress != 0:
        mype2.parse_data_directories(directories=[pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_IMPORT']])
        if mype2.DIRECTORY_ENTRY_IMPORT is not None:
            for entry in mype2.DIRECTORY_ENTRY_IMPORT:
                for imptab in entry.imports:
                    if imptab.name is None:
                        imptab.name = "None"
                    if imptab.address is None :
                        imptab.address = int(0) 
                    x = hex(int(imptab.address)), imptab.name
                    I.append(x)
    return I 
Example #25
Source File: pe.py    From CIRTKit with MIT License 5 votes vote down vote up
def run(self):
        super(PE, self).run()
        if self.args is None:
            return

        if not HAVE_PEFILE:
            self.log('error', "Missing dependency, install pefile (`pip install pefile`)")
            return

        if self.args.subname == 'imports':
            self.imports()
        elif self.args.subname == 'exports':
            self.exports()
        elif self.args.subname == 'resources':
            self.resources()
        elif self.args.subname == 'imphash':
            self.imphash()
        elif self.args.subname == 'compiletime':
            self.compiletime()
        elif self.args.subname == 'peid':
            self.peid()
        elif self.args.subname == 'security':
            self.security()
        elif self.args.subname == 'sections':
            self.sections()
        elif self.args.subname == 'language':
            self.language()
        elif self.args.subname == 'pehash':
            self.pehash()
        elif self.args.subname == 'entrypoint':
            self.entrypoint() 
Example #26
Source File: fileparser.py    From RATDecoders with MIT License 5 votes vote down vote up
def pe_resource_names(self):
        """
        Read PE Resources and return a list of resource names
        :return: list
        """
        resource_names = []
        pe = pefile.PE(data=self.file_data)
        for rsrc in pe.DIRECTORY_ENTRY_RESOURCE.entries:
            for entry in rsrc.directory.entries:
                if entry.name is not None:
                    resource_names.append(entry.name.decode('utf-8'))
        return resource_names 
Example #27
Source File: xtreme.py    From CIRTKit with MIT License 5 votes vote down vote up
def extract_config(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 
Example #28
Source File: fileparser.py    From RATDecoders with MIT License 5 votes vote down vote up
def pe_resource_by_name(self, resource_name):
        """
        Extract a PE Resource from a binary by name
        :param resource_name: str
        :return: byte array
        """
        offset = 0x00
        size = 0x00

        pe = pefile.PE(data=self.file_data)
        for rsrc in pe.DIRECTORY_ENTRY_RESOURCE.entries:
            for entry in rsrc.directory.entries:
                if entry.name is not None:
                    if entry.name.__str__() == resource_name:
                        offset = entry.directory.entries[0].data.struct.OffsetToData
                        size = entry.directory.entries[0].data.struct.Size

        return pe.get_memory_mapped_image()[offset:offset + size] 
Example #29
Source File: pandora.py    From CIRTKit with MIT License 5 votes vote down vote up
def get_config(data):
    try:
        pe = pefile.PE(data=data)
        try:
          rt_string_idx = [
          entry.id for entry in 
          pe.DIRECTORY_ENTRY_RESOURCE.entries].index(pefile.RESOURCE_TYPE['RT_RCDATA'])
        except ValueError, e:
            sys.exit()
        except AttributeError, e:
            sys.exit() 
Example #30
Source File: pe.py    From CIRTKit with MIT License 5 votes vote down vote up
def __check_session(self):
        if not __sessions__.is_set():
            self.log('error', "No session opened")
            return False

        if not self.pe:
            try:
                self.pe = pefile.PE(__sessions__.current.file.path)
            except pefile.PEFormatError as e:
                self.log('error', "Unable to parse PE file: {0}".format(e))
                return False

        return True