Python pefile.DIRECTORY_ENTRY Examples
The following are 17
code examples of pefile.DIRECTORY_ENTRY().
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: malwoverview.py From malwoverview with GNU General Public License v3.0 | 6 votes |
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 #2
Source File: META_PE_SIGNATURE.py From fsf with Apache License 2.0 | 6 votes |
def META_PE_SIGNATURE(s, buff): sig_buff = [] pe = pefile.PE(data=buff) address = pe.OPTIONAL_HEADER.DATA_DIRECTORY[pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_SECURITY']].VirtualAddress size = pe.OPTIONAL_HEADER.DATA_DIRECTORY[pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_SECURITY']].Size # Eight bytes in due to the struct spec # typedef struct _WIN_CERTIFICATE # { # DWORD dwLength; # WORD wRevision; # WORD wCertificateType; # BYTE bCertificate[ANYSIZE_ARRAY]; # } WIN_CERTIFICATE, *LPWIN_CERTIFICATE; sig_buff = buff[address + 8 : address + 8 + size] # Remove sequence and objid structures, 19 bytes signed_data, rest = decode(sig_buff[19:], asn1Spec=rfc2315.SignedData()) return get_cert_info(signed_data)
Example #3
Source File: PEFileModule.py From codex-backend with MIT License | 6 votes |
def initialize(self, sample): if(self.already_initialized): return self.library self.already_initialized = True try: self.library = pefile.PE(data=sample.getBinary(), fast_load=True) # see if this initializations can be done on plugins. self.library.parse_data_directories(directories=[ pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_IMPORT'], pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_EXPORT'], pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_TLS'], pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_SECURITY'], pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_RESOURCE']]) except pefile.PEFormatError: # print("parse fail") self.library = None # print(traceback.format_exc()) logging.error("Error parsing pefileModule with sample:%s", sample.getID(), exc_info=True)
Example #4
Source File: PEHeaderReader.py From codex-backend with MIT License | 6 votes |
def getImports(self): if (self.pe.OPTIONAL_HEADER.DATA_DIRECTORY[pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_IMPORT']].VirtualAddress == 0): return None d = {} # print(self.pe.DIRECTORY_ENTRY_IMPORT) for entry in self.pe.DIRECTORY_ENTRY_IMPORT: aux = [] for i in range(len(entry.dll)): if(ord(entry.dll[i]) >= 128): aux.append('.') else: aux.append(entry.dll[i]) dll_name = "".join(aux) # print entry.dll # print entry.imports l = [] for imp in entry.imports: l.append(str(imp.name)) # print '\t', hex(imp.address), imp.name d[unicode(str(dll_name), "utf-8")] = l return d
Example #5
Source File: PEHeaderReader.py From codex-backend with MIT License | 6 votes |
def get_import_size_stats(self): # self.pe.parse_data_directories() # si if has fast load. total = 0 if (self.pe.OPTIONAL_HEADER.DATA_DIRECTORY[pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_IMPORT']].VirtualAddress == 0): return 0, 0, 0 for entry in self.pe.DIRECTORY_ENTRY_IMPORT: total = total + len(entry.imports) # print entry.dll # for imp in entry.imports: # print '\t', hex(imp.address), imp.name cant_librerias = (len(self.pe.DIRECTORY_ENTRY_IMPORT)) total_imports = total promedio = total / cant_librerias return total_imports, cant_librerias, promedio
Example #6
Source File: pe.py From cle with BSD 2-Clause "Simplified" License | 6 votes |
def _parse_pe_non_reloc_data_directories(self): """ Parse data directories that is not DIRECTORY_ENTRY_BASERELOC since parsing relocations can take a long time in many PE binaries. """ directory_names = ( 'IMAGE_DIRECTORY_ENTRY_EXPORT', 'IMAGE_DIRECTORY_ENTRY_IMPORT', 'IMAGE_DIRECTORY_ENTRY_RESOURCE', 'IMAGE_DIRECTORY_ENTRY_EXCEPTION', 'IMAGE_DIRECTORY_ENTRY_SECURITY', 'IMAGE_DIRECTORY_ENTRY_DEBUG', 'IMAGE_DIRECTORY_ENTRY_COPYRIGHT', 'IMAGE_DIRECTORY_ENTRY_GLOBALPTR', 'IMAGE_DIRECTORY_ENTRY_TLS', 'IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG', 'IMAGE_DIRECTORY_ENTRY_IAT', 'IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT', 'IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR', 'IMAGE_DIRECTORY_ENTRY_RESERVED', ) directories = tuple(pefile.DIRECTORY_ENTRY[n] for n in directory_names) self._pe.parse_data_directories(directories=directories)
Example #7
Source File: check_file.py From SSMA with GNU General Public License v3.0 | 5 votes |
def checkTSL(self): _tls = self.pe.OPTIONAL_HEADER.DATA_DIRECTORY[ pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_TLS']].VirtualAddress if _tls: return _tls else: return None
Example #8
Source File: ImportsPlug.py From codex-backend with MIT License | 5 votes |
def process(self): pelib = self._getLibrary(PEFileModule().getName()) if(pelib is None): return "" try: if (pelib.OPTIONAL_HEADER.DATA_DIRECTORY[pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_IMPORT']].VirtualAddress == 0): return "" except Exception, e: print str(e) return ""
Example #9
Source File: pe.py From plasma with GNU General Public License v3.0 | 5 votes |
def load_dyn_sym(self): try: self.pe.parse_data_directories( pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_IMPORT']) except Exception as e: raise ExcPEFail(e) if hasattr(self.pe, 'DIRECTORY_ENTRY_IMPORT'): for entry in self.pe.DIRECTORY_ENTRY_IMPORT: for imp in entry.imports: if imp.name is None: continue name = imp.name # erocarrera/pefile returns a bytes but mlaferrera/prefile # returns a string. if isinstance(name, bytes): name = name.decode() n = name if name in self.symbols: name = self.rename_sym(name) self.reverse_symbols[imp.address] = name self.symbols[name] = imp.address # TODO: always a function ? # set the index, but the object is currently None self.func_add_flag(imp.address, n) self.db.functions[imp.address] = None
Example #10
Source File: peinfo.py From ida_pdb_loader with MIT License | 5 votes |
def get_debug_data(pe, type=DEBUG_TYPE[u'IMAGE_DEBUG_TYPE_CODEVIEW']): retval = None if not hasattr(pe, u'DIRECTORY_ENTRY_DEBUG'): # fast loaded - load directory pe.parse_data_directories(DIRECTORY_ENTRY[u'IMAGE_DIRECTORY_ENTRY_DEBUG']) if not hasattr(pe, u'DIRECTORY_ENTRY_DEBUG'): raise PENoDebugDirectoryEntriesError() else: for entry in pe.DIRECTORY_ENTRY_DEBUG: off = entry.struct.PointerToRawData size = entry.struct.SizeOfData if entry.struct.Type == type: retval = pe.__data__[off:off+size] break return retval
Example #11
Source File: pefile_test.py From pefile with MIT License | 5 votes |
def test_write_header_fields(self): """Verify correct field data modification.""" # Test version information writing control_file = os.path.join(REGRESSION_TESTS_DIR, 'MSVBVM60.DLL') pe = pefile.PE(control_file, fast_load=True) pe.parse_data_directories( directories=[ pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_RESOURCE']]) original_data = pe.write() str1 = b'string1' str2 = b'str2' str3 = b'string3' pe.FileInfo[0][0].StringTable[0].entries[b'FileDescription'] = str1 pe.FileInfo[0][0].StringTable[0].entries[b'FileVersion'] = str2 pe.FileInfo[0][0].StringTable[0].entries[b'InternalName'] = str3 new_data = pe.write() diff, differences = 0, list() for idx in range(len(original_data)): if original_data[idx] != new_data[idx]: diff += 1 # Skip the zeroes that pefile automatically adds to pad a new, # shorter string, into the space occupied by a longer one. if new_data[idx] != 0: differences.append(chr(new_data[idx])) # Verify all modifications in the file were the ones we just made # self.assertEqual(''.join(differences).encode('utf-8', 'backslashreplace'), str1+str2+str3) pe.close()
Example #12
Source File: malwoverview.py From malwoverview with GNU General Public License v3.0 | 5 votes |
def listexports(fname): E = [] mype2=pefile.PE(fname,fast_load=True) if mype2.OPTIONAL_HEADER.DATA_DIRECTORY[pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_EXPORT']].VirtualAddress != 0: mype2.parse_data_directories(directories=[pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_EXPORT']]) for exptab in mype2.DIRECTORY_ENTRY_EXPORT.symbols: x = hex(mype2.OPTIONAL_HEADER.ImageBase + exptab.address), exptab.name E.append(x) return E
Example #13
Source File: windows_memory_patches.py From MemoryPatchDetector with MIT License | 5 votes |
def get_relocations(pe, proc, module_base_address): try: relocations = [] relocation_table = pe.NT_HEADERS.OPTIONAL_HEADER.DATA_DIRECTORY[ pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_BASERELOC']] rva = relocation_table.VirtualAddress size = relocation_table.Size if size == 0: return [] rlc_size = pefile.Structure(pe.__IMAGE_BASE_RELOCATION_format__).sizeof() end = rva + size while rva < end: try: rlc = pe.__unpack_data__( pe.__IMAGE_BASE_RELOCATION_format__, proc.read(module_base_address + rva, rlc_size), file_offset=pe.get_offset_from_rva(rva)) except pefile.PEFormatError: rlc = None if not rlc: break relocation_entries = parse_relocations(proc, module_base_address, pe, rva + rlc_size, rlc.VirtualAddress, rlc.SizeOfBlock - rlc_size) relocations.append( pefile.BaseRelocationData( struct=rlc, entries=relocation_entries)) if not rlc.SizeOfBlock: break rva += rlc.SizeOfBlock return relocations except Exception as ex: print(str(ex))
Example #14
Source File: pe.py From cle with BSD 2-Clause "Simplified" License | 4 votes |
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.segments = self.sections # in a PE, sections and segments have the same meaning self.os = 'windows' if self.binary is None: self._pe = pefile.PE(data=self._binary_stream.read(), fast_load=True) self._parse_pe_non_reloc_data_directories() elif self.binary in self._pefile_cache: # these objects are not mutated, so they are reusable within a process self._pe = self._pefile_cache[self.binary] else: self._pe = pefile.PE(self.binary, fast_load=True) self._parse_pe_non_reloc_data_directories() if not self.is_main_bin: # only cache shared libraries, the main binary will not be reused self._pefile_cache[self.binary] = self._pe if self.arch is None: self.set_arch(archinfo.arch_from_id(pefile.MACHINE_TYPE[self._pe.FILE_HEADER.Machine])) self.mapped_base = self.linked_base = self._pe.OPTIONAL_HEADER.ImageBase self._entry = AT.from_rva(self._pe.OPTIONAL_HEADER.AddressOfEntryPoint, self).to_lva() if hasattr(self._pe, 'DIRECTORY_ENTRY_IMPORT'): self.deps = [entry.dll.decode().lower() for entry in self._pe.DIRECTORY_ENTRY_IMPORT] else: self.deps = [] if self.binary is not None and not self.is_main_bin: self.provides = os.path.basename(self.binary).lower() else: self.provides = None self.tls_index_address = None self.tls_callbacks = None self.supports_nx = self._pe.OPTIONAL_HEADER.DllCharacteristics & 0x100 != 0 self.pic = self.pic or self._pe.OPTIONAL_HEADER.DllCharacteristics & 0x40 != 0 if hasattr(self._pe, 'DIRECTORY_ENTRY_LOAD_CONFIG'): self.load_config = {name: value['Value'] for name, value in self._pe.DIRECTORY_ENTRY_LOAD_CONFIG.struct.dump_dict().items() if name != 'Structure'} else: self.load_config = {} self._exports = {} self._ordinal_exports = {} self._symbol_cache = self._exports # same thing self._handle_imports() self._handle_exports() if self.loader._perform_relocations: # parse base relocs self._pe.parse_data_directories(directories=(pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_BASERELOC'],)) self.__register_relocs() # parse TLS self._register_tls() # parse sections self._register_sections() self.linking = 'dynamic' if self.deps else 'static' self.jmprel = self._get_jmprel() self.memory.add_backer(0, self._pe.get_memory_mapped_image())
Example #15
Source File: static.py From mac-a-mal-cuckoo with MIT License | 4 votes |
def _get_signature(self): """If this executable is signed, get its signature(s).""" dir_index = pefile.DIRECTORY_ENTRY["IMAGE_DIRECTORY_ENTRY_SECURITY"] if len(self.pe.OPTIONAL_HEADER.DATA_DIRECTORY) < dir_index: return [] dir_entry = self.pe.OPTIONAL_HEADER.DATA_DIRECTORY[dir_index] if not dir_entry or not dir_entry.VirtualAddress or not dir_entry.Size: return [] if not HAVE_MCRYPTO: log.critical("You do not have the m2crypto library installed " "preventing certificate extraction: " "pip install m2crypto") return [] signatures = self.pe.write()[dir_entry.VirtualAddress+8:] bio = M2Crypto.BIO.MemoryBuffer(signatures) if not bio: return [] pkcs7_obj = M2Crypto.m2.pkcs7_read_bio_der(bio.bio_ptr()) if not pkcs7_obj: return [] ret = [] p7 = M2Crypto.SMIME.PKCS7(pkcs7_obj) for cert in p7.get0_signers(M2Crypto.X509.X509_Stack()) or []: subject = cert.get_subject() ret.append({ "serial_number": "%032x" % cert.get_serial_number(), "common_name": subject.CN, "country": subject.C, "locality": subject.L, "organization": subject.O, "email": subject.Email, "sha1": "%040x" % int(cert.get_fingerprint("sha1"), 16), "md5": "%032x" % int(cert.get_fingerprint("md5"), 16), }) if subject.GN and subject.SN: ret[-1]["full_name"] = "%s %s" % (subject.GN, subject.SN) elif subject.GN: ret[-1]["full_name"] = subject.GN elif subject.SN: ret[-1]["full_name"] = subject.SN return ret
Example #16
Source File: CertficatePlug.py From codex-backend with MIT License | 4 votes |
def process2(self): pe = self._getLibrary(PEFileModule().getName()) if(pe is None): return "" # get the security directory entry address = pe.OPTIONAL_HEADER.DATA_DIRECTORY[ pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_SECURITY']].VirtualAddress if address > 0: # Always in DER format AFAIK derData = pe.write()[address + 8:] else: logging.debug("address 0") return (contentInfo, rest) = decoder.decode( derData, asn1Spec=rfc2315.ContentInfo()) contentType = contentInfo.getComponentByName('contentType') if contentType == rfc2315.signedData: signedData = decode(contentInfo.getComponentByName( 'content'), asn1Spec=rfc2315.SignedData()) for sd in signedData: if sd == '': continue signerInfos = sd.getComponentByName('signerInfos') for si in signerInfos: issuerAndSerial = si.getComponentByName( 'issuerAndSerialNumber') issuer = issuerAndSerial.getComponentByName( 'issuer').getComponent() for i in issuer: for r in i: at = r.getComponentByName('type') if rfc2459.id_at_countryName == at: cn = decode(r.getComponentByName( 'value'), asn1Spec=rfc2459.X520countryName()) print(cn[0]) elif rfc2459.id_at_organizationName == at: on = decode(r.getComponentByName( 'value'), asn1Spec=rfc2459.X520OrganizationName()) print(on[0].getComponent()) elif rfc2459.id_at_organizationalUnitName == at: ou = decode(r.getComponentByName( 'value'), asn1Spec=rfc2459.X520OrganizationalUnitName()) print(ou[0].getComponent()) elif rfc2459.id_at_commonName == at: cn = decode(r.getComponentByName( 'value'), asn1Spec=rfc2459.X520CommonName()) print(cn[0].getComponent()) else: print at
Example #17
Source File: invisimole_decrypt.py From malware-research with BSD 2-Clause "Simplified" License | 4 votes |
def main(): if len(sys.argv) < 2: print('Usage: {0:s} input_dll'.format(sys.argv[0])) return filename = sys.argv[1] pe = pefile.PE(filename) pe.parse_data_directories(directories=[pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_RESOURCE']]) RC2CL_offset, RC2CL_size = 0, 0 RC2FM_offset, RC2FM_size = 0, 0 if hasattr(pe, 'DIRECTORY_ENTRY_RESOURCE'): for resource_type in pe.DIRECTORY_ENTRY_RESOURCE.entries: if pefile.RESOURCE_TYPE.get(resource_type.struct.Id, '-') == 'RT_RCDATA': 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: if hasattr(resource_lang, 'data'): if str(resource_id.name) == 'RC2CL': RC2CL_offset = resource_lang.data.struct.OffsetToData RC2CL_size = resource_lang.data.struct.Size elif str(resource_id.name) == 'RC2FM': RC2FM_offset = resource_lang.data.struct.OffsetToData RC2FM_size = resource_lang.data.struct.Size if RC2CL_offset != 0 and RC2CL_size != 0: print('RC2CL resource {0:08X} - {1:08X}'.format(RC2CL_offset, RC2CL_size)) save_payload(filename, 'RC2CL', pe.get_data(RC2CL_offset, RC2CL_size), RC2CL_size) else: print('RC2CL resource not found') if RC2FM_offset != 0 and RC2FM_size != 0: print('RC2FM resource {0:08X} - {1:08X}'.format(RC2FM_offset, RC2FM_size)) save_payload(filename, 'RC2FM', pe.get_data(RC2FM_offset, RC2FM_size), RC2FM_size) else: print('RC2FM resource not found')