def prob37(): num = 0 summ = 0 i = 10 while num < 11: # print(i) i += 1 k = i works = True while k: if not PE.isPrime(k): works = False break k /= 10 if works: k = i while k: if not PE.isPrime(k): works = False break if k < 10: k = 0 else : k = int(str(k)[1:]) if works: print(i) num += 1 summ += i print(summ)
def prob21(): summ = 0 for i in range(1, 10000): x = PE.sumDivisors(i) if x != i and PE.sumDivisors(x) == i: summ += i print(i) print(summ)
def prob21(): summ=0 for i in range(1,10000): x = PE.sumDivisors(i) if x!= i and PE.sumDivisors(x) == i: summ += i print(i) print(summ)
def saveDistinctElements(C6, arraymap, indexpe) : """retains within arraymay only those elements provably distinct from indexpe """ akeys = arraymap.keys() for key in akeys : elempe = PE.tupleToPe(key) # get pe-value of element-index # is the following good enough? Or will we need theorem proving? distinct = PE.prove(C6["rels"], ["!=", elempe, indexpe]) if not distinct : del arraymap[key]
def safeseh(vdb, line): """ Show the SafeSEH status of all the loaded DLLs or list the handlers for a particular dll by normalized name. Usage: safeseh [libname] """ t = vdb.getTrace() libs = t.getMeta("LibraryBases") if len(line): base = libs.get(line) if base is None: vdb.vprint("Unknown library: %s" % line) return vdb.vprint("%s:" % line) try: p = PE.peFromMemoryObject(t, base) except Exception: vdb.vprint('Error: %s (0x%.8x) %s' % (line, base, e)) return if p.IMAGE_LOAD_CONFIG is not None: va = int(p.IMAGE_LOAD_CONFIG.SEHandlerTable) if va != 0: count = int(p.IMAGE_LOAD_CONFIG.SEHandlerCount) for h in t.readMemoryFormat(va, "<%dL" % count): vdb.vprint("\t0x%.8x %s" % (base + h, vdb.reprPointer(base + h))) return vdb.vprint("None...") else: lnames = list(libs.keys()) lnames.sort() for name in lnames: base = libs.get(name) try: p = PE.peFromMemoryObject(t, base) except Exception as e: vdb.vprint('Error: %s (0x%.8x) %s' % (name, base, e)) continue enabled = False if p.IMAGE_LOAD_CONFIG is not None: va = int(p.IMAGE_LOAD_CONFIG.SEHandlerTable) if va != 0: enabled = True vdb.vprint("%16s\t%s" % (name, enabled))
def insertAppend(C6, v, e) : """appends e to the end of array/list v in the heap. Does the same actions as an insertAssign to an indexed array, but preserves more heap info since the append does not produce any aliases within v params : C6; v - a vartee; e - an etree """ sigma = C6["store"] heap = C6["heap"] vname = v[1] vold = Parse.makeOldVar(v) if lookupType(C6, vname) != "array" : error("cannot append to a non-list/array") else : loc = PE.peToTuple(sigma[vname]) length = heap[loc][0] newlength = PE.add(length, PE.make(1)) vector = heap[loc][1] # assign original to v_old: sigma[vold[1]] = sigma[vname] # make copy for the new value of v: copy = {} for k in vector : copy[k] = vector[k] newloc = PE.make(PE.makeSym()) rhs = PE.evall(C6, e) copy[ PE.peToTuple(length) ] = rhs sigma[vname] = newloc heap[ PE.peToTuple(newloc) ] = (newlength, copy)
def safeseh(vdb, line): """ Show the SafeSEH status of all the loaded DLLs or list the handlers for a particular dll by normalized name. Usage: safeseh [libname] """ t = vdb.getTrace() libs = t.getMeta("LibraryBases") if len(line): base = libs.get(line) if base == None: vdb.vprint("Unknown library: %s" % line) return vdb.vprint("%s:" % line) try: p = PE.peFromMemoryObject(t, base) except Exception as e: vdb.vprint('Error: %s (0x%.8x) %s' % (line, base, e)) return if p.IMAGE_LOAD_CONFIG != None: va = int(p.IMAGE_LOAD_CONFIG.SEHandlerTable) if va != 0: count = int(p.IMAGE_LOAD_CONFIG.SEHandlerCount) for h in t.readMemoryFormat(va, "<%dL" % count): vdb.vprint("\t0x%.8x %s" % (base+h, vdb.reprPointer(base+h))) return vdb.vprint("None...") else: lnames = list(libs.keys()) lnames.sort() for name in lnames: base = libs.get(name) try: p = PE.peFromMemoryObject(t, base) except Exception as e: vdb.vprint('Error: %s (0x%.8x) %s' % (name, base, e)) continue enabled = False if p.IMAGE_LOAD_CONFIG != None: va = int(p.IMAGE_LOAD_CONFIG.SEHandlerTable) if va != 0: enabled = True vdb.vprint("%16s\t%s" % (name, enabled))
def platformParseBinaryPe(self, filename, baseaddr, normname): # If we're on windows, fake out the PE header and use dbghelp if False: # FIXME this code is stolen and should be a function! import vtrace.platforms.win32 as vt_win32 fakepe = self.readMemory(baseaddr, 1024) tfile = tempfile.NamedTemporaryFile(delete=False) tfilename = tfile.name import ctypes pebuf = ctypes.create_string_buffer(fakepe) try: try: tfile.write(fakepe) tfile.close() #parser = vt_win32.Win32SymbolParser(-1, tfilename, baseaddr) parser = vt_win32.Win32SymbolParser(-1, None, ctypes.addressof(pebuf)) parser.parse() parser.loadSymsIntoTrace(self, normname) finally: os.unlink(tfilename) except Exception as e: print(e) else: pe = PE.peFromMemoryObject(self, baseaddr) for rva, ord, name in pe.getExports(): self.addSymbol(e_resolv.Symbol(name, baseaddr+rva, 0, normname))
def printIAT(trace, fileName, verbose=False): #print "FileName: %s" % fileName libs = trace.getMeta("LibraryPaths") libBase = trace.getMeta("LibraryBases") #print "Lib Base: %s" % libBase #print "File Name: %s" % fileName base = libBase[fileName.lower()] p = PE.peFromMemoryObject(trace, base) IMAGE_DIRECTORY_ENTRY_IMPORT = 1 # Import Directory IMAGE_DIRECTORY_ENTRY_IAT = 12 # Import Address Table idir = p.IMAGE_NT_HEADERS.OptionalHeader.DataDirectory[ IMAGE_DIRECTORY_ENTRY_IMPORT] poff = p.rvaToOffset(idir.VirtualAddress) psize = idir.Size # Once you have VirtualAddress BP on that and you can stop # the program before any external call. p.parseImports() if verbose == True: for i in p.imports: print("Address: %s \tLibrary: %s \tFirstThunk: %s" % (hex(base + i[0]), i[1], i[2])) return base, p.imports
def deAslr(trace, va): ''' Given an address in an ASLR'd library, rebase it back to the address as it would be if the given PE were at it's suggested address... ''' if vtrace.remote: raise Exception('deAslr only works for local debuggers!') map = trace.getMemoryMap(va) if map is None: return va mapva, mapsize, mapperm, mapfname = map if not mapfname: return va normname = trace.normFileName(mapfname) sym = trace.getSymByName(normname) if sym is None: return va membase = int(sym) pe = PE.peFromFileName(mapfname) filebase = pe.IMAGE_NT_HEADERS.OptionalHeader.ImageBase rva = va - membase return filebase + rva
def main(): parser = optparse.OptionParser() parser.add_option('--version', dest='version', default=False, action='store_true') parser.add_option('--resources', dest='resources', default=False, action='store_true') opts, argv = parser.parse_args() for fname in argv: print('Parsing: %s' % fname) vsver = None expname = None pe = PE.peFromFileName(fname) if opts.resources: print('Type Nameid - rva size sample') for rtype, nameid, (rva, size, codepage) in pe.getResources(): hexstr = pe.readAtRva(rva, max(size, 8)).encode('hex') print(('0x%.4x 0x%.4x - 0x%.8x 0x%.8x %s' % (rtype, nameid, rva, size, hexstr))) if opts.version: vs = pe.getVS_VERSIONINFO() if vs is None: print('No VS_VERSIONINFO found!') else: keys = vs.getVersionKeys() keys.sort() for k in keys: val = vs.getVersionValue(k) print('%s: %r' % (k, val)) code.interact(local=locals())
def test_pe_pe32p(self): ''' test that we use the right check for constructing the optional header and that the data directories are right ''' file_path = helpers.getTestPath( 'windows', 'amd64', 'a7712b7c45ae081a1576a387308077f808c666449d1ea9ba680ec410569d476f.file' ) pe = PE.peFromFileName(file_path) self.assertTrue(pe.pe32p) self.eq(pe.psize, 8) self.eq(pe.IMAGE_NT_HEADERS.OptionalHeader.SizeOfStackReserve, 0x100000) self.eq(pe.IMAGE_NT_HEADERS.OptionalHeader.SizeOfStackCommit, 0x1000) self.eq(pe.IMAGE_NT_HEADERS.OptionalHeader.SizeOfHeapReserve, 0x100000) self.eq(pe.IMAGE_NT_HEADERS.OptionalHeader.SizeOfHeapCommit, 0x1000) self.eq(pe.IMAGE_NT_HEADERS.OptionalHeader.LoaderFlags, 0) self.eq(pe.IMAGE_NT_HEADERS.OptionalHeader.NumberOfRvaAndSizes, 0x10) ddir = pe.getDataDirectory(PE.IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR) self.eq(ddir.VirtualAddress, 0x2008) self.eq(ddir.Size, 0x48) ddir = pe.getDataDirectory(PE.IMAGE_DIRECTORY_ENTRY_RESOURCE) self.eq(ddir.VirtualAddress, 0x9a2000) self.eq(ddir.Size, 0x3c78)
def platformParseBinaryPe(self, filename, baseaddr, normname): # If we're on windows, fake out the PE header and use dbghelp if False: # FIXME this code is stolen and should be a function! import ctypes import vtrace.platforms.win32 as vt_win32 fakepe = self.readMemory(baseaddr, 1024) tfile = tempfile.NamedTemporaryFile(delete=False) tfilename = tfile.name pebuf = ctypes.create_string_buffer(fakepe) try: try: tfile.write(fakepe) tfile.close() #parser = vt_win32.Win32SymbolParser(-1, tfilename, baseaddr) parser = vt_win32.Win32SymbolParser( -1, None, ctypes.addressof(pebuf)) parser.parse() parser.loadSymsIntoTrace(self, normname) finally: os.unlink(tfilename) except Exception as e: logger.warning(str(e)) else: pe = PE.peFromMemoryObject(self, baseaddr) for rva, ord, name in pe.getExports(): self.addSymbol( e_resolv.Symbol(name, baseaddr + rva, 0, normname))
def test_export_by_ordinal_base_45(self): file_path = helpers.getTestPath('windows', 'i386', 'export_by_ordinal_base_45.dll') pe = PE.peFromFileName(file_path) export_list = pe.getExports() self.assertEquals(len(export_list), 2, "expecting 2 exported functions") self.assertEquals(export_list[0][1], 45, "exported function with ordinal 45 not found") self.assertEquals(export_list[1][1], 55, "exported function with ordinal 55 not found")
def prob46(): n = 3 while True: print(n) if PE.isPrime(n): n += 2 continue found = False for p in range(int(math.sqrt(n)) + 1): if PE.isPrime(n - 2 * p * p): found = True break if not found: print("soln is: " + str(n)) return n += 2
def printIAT(trace, fileName, verbose=False): #print "FileName: %s" % fileName libs = trace.getMeta("LibraryPaths") libBase = trace.getMeta("LibraryBases") #print "Lib Base: %s" % libBase #print "File Name: %s" % fileName base = libBase[fileName.lower()] p = PE.peFromMemoryObject(trace, base) IMAGE_DIRECTORY_ENTRY_IMPORT =1 # Import Directory IMAGE_DIRECTORY_ENTRY_IAT =12 # Import Address Table idir = p.IMAGE_NT_HEADERS.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT] poff = p.rvaToOffset(idir.VirtualAddress) psize = idir.Size # Once you have VirtualAddress BP on that and you can stop # the program before any external call. p.parseImports() if verbose == True: for i in p.imports: print("Address: %s \tLibrary: %s \tFirstThunk: %s" % (hex(base+i[0]), i[1], i[2])) return base, p.imports
def showaslr(vdb, base, libname): t = vdb.getTrace() try: p = PE.peFromMemoryObject(t, base) except Exception, e: vdb.vprint('Error: %s (0x%.8x) %s' % (libname, base, e)) return
def platformParseBinary(self, filename, baseaddr, normname): try: pe = PE.peFromMemoryObject(self, baseaddr) for rva, ord, name in pe.getExports(): self.addSymbol(e_resolv.Symbol(name, baseaddr + rva, 0, normname)) except Exception, e: print ("Error Parsing Binary (%s): %s" % (normname, e))
def hooks(vdb, line): ''' Check the executable regions of the target process for any hooks by comparing against the PE on disk. This will account for relocations and import entries. ''' t = vdb.getTrace() bases = t.getMeta("LibraryBases") paths = t.getMeta("LibraryPaths") found = False for bname in bases.keys(): base = bases.get(bname) fpath = paths.get(base) pobj = PE.PE(file(fpath, 'rb')) filebase = pobj.IMAGE_NT_HEADERS.OptionalHeader.ImageBase skips = {} # Get relocations for skipping r = range(t.getPointerSize()) for relrva, reltype in pobj.getRelocations(): for i in r: skips[base + relrva + i] = True # Add the import entries to skip for iva, libname, name in pobj.getImports(): for i in r: skips[base + iva + i] = True for sec in pobj.getSections(): if sec.Characteristics & PE.IMAGE_SCN_MEM_EXECUTE: size = sec.VirtualSize va = base + sec.VirtualAddress fileva = filebase + sec.VirtualAddress filebytes = pobj.readAtRva(sec.VirtualAddress, sec.VirtualSize) procbytes = t.readMemory(va, size) for off, size in bindiff(filebytes, procbytes): difva = va + off fdifva = fileva + off # Check for a relocation covering this... if skips.get(difva): continue found = True dmem = procbytes[off:off + size].encode('hex')[:10] dfil = filebytes[off:off + size].encode('hex')[:10] vdb.canvas.addVaText('0x%.8x' % difva, difva) vdb.canvas.addText(' (0x%.8x) (%d)' % (fdifva, size)) vdb.canvas.addText(' mem: %s file: %s ' % (dmem, dfil)) sym = vdb.symobj.getSymByAddr(difva, exact=False) if sym != None: vdb.canvas.addText(' ') vdb.canvas.addVaText( '%s + %d' % (repr(sym), difva - long(sym)), difva) vdb.canvas.addText('\n') if not found: vdb.canvas.addText('No Hooks Found!\n')
def deAslr(trace, va): ''' Given an address in an ASLR'd library, rebase it back to the address as it would be if the given PE were at it's suggested address... ''' if vtrace.remote: raise Exception('deAslr only works for local debuggers!') map = trace.getMemoryMap(va) if map == None: return va mapva, mapsize, mapperm, mapfname = map if not mapfname: return va normname = trace.normFileName(mapfname) sym = trace.getSymByName(normname) if sym == None: return va membase = long(sym) pe = PE.peFromFileName(mapfname) filebase = pe.IMAGE_NT_HEADERS.OptionalHeader.ImageBase rva = va - membase return filebase + rva
def prob10(): summ = 0 for i in range(2, 2000000): print(i) if PE.isPrime(i): summ += i print(summ)
def prob46(): n = 3 while True: print(n) if PE.isPrime(n): n+=2 continue found = False for p in range(int(math.sqrt(n)) + 1): if PE.isPrime(n - 2*p*p): found = True break if not found: print("soln is: " + str(n)) return n+=2
def main(argv): opts = setup().parse_args(argv) with open(opts.file, 'rb') as f: p = PE.PE(f) baseaddr = p.IMAGE_NT_HEADERS.OptionalHeader.ImageBase osmajor = p.IMAGE_NT_HEADERS.OptionalHeader.MajorOperatingSystemVersion osminor = p.IMAGE_NT_HEADERS.OptionalHeader.MinorOperatingSystemVersion machine = p.IMAGE_NT_HEADERS.FileHeader.Machine vsver = p.getVS_VERSIONINFO() archname = PE.machine_names.get(machine) parser = vt_win32.Win32SymbolParser(0xffffffff, opts.file, baseaddr) parser.parse() t = parser._sym_types.values() e = parser._sym_enums.values() builder = vs_builder.VStructBuilder(defs=t, enums=e) print('# Version: %d.%d' % (osmajor, osminor)) print('# Architecture: %s' % archname) if vsver is not None: keys = vsver.getVersionKeys() keys.sort() for k in keys: val = vsver.getVersionValue(k) print('# %s: %s' % (k, val)) print(builder.genVStructPyCode())
def insertAssign(C6, v, etree): """updates the store of C6 with an assignment. If v already exists in C6's store, saves former value as v_old for later use in proof reasoning. params: v - has form, ["var", s] or ["index", ["var", s], etree] etree - another etree, to be assigned to the var. """ sigma = C6["store"] heap = C6["heap"] badvars = C6["novars"] if v[0] == "var" : vtree = v elif v[0] == "index" : vtree = v[1] vold = Parse.makeOldVar(vtree) # ["var", vname_old] # first, check if we are allowed to update v: if (vtree in badvars) : error("you may not update a protected global var outside of its maintenance function") return # if possible, rename current value of var v as v_old: if v[0] == "var" and v[1] in sigma : # and lookupType(C6, v[1]) != "array": sigma[vold[1]] = sigma[v[1]] # assign v's current value to v_old elif v[0] == "index" and lookupType(C6, v[1][1]) == "array": vname = v[1][1] loc = PE.peToTuple(sigma[vname]) length = heap[loc][0] vector = heap[loc][1] # make copy: copy = {} for k in vector : copy[k] = vector[k] # assign original to v_old and copy to v : sigma[vold[1]] = sigma[vname] newloc = PE.make(PE.makeSym()) sigma[vname] = newloc heap[ PE.peToTuple(newloc) ] = (length, copy) # (later, vold will be erased from sigma....) # now, eval assignment's rhs and store it into v: rhs = PE.evall(C6, etree) if v[0] == "var": # simple var sigma[v[1]] = rhs elif v[0] == "index": # an array/list reference # eval index expression (NOTE: no nested indexing allowed): indexpe = PE.evall(C6, v[2]) # save values in sigma[vname][1] provably distinct from vname[index]: vname = v[1][1] if vname not in sigma or lookupType(C6, vname) != "array" : error(vname + " is not an array in the store") #sigma[vname] = PE.makeArray() else : vmap = heap[PE.peToTuple(sigma[vname])][1] saveDistinctElements(C6, vmap, indexpe) vmap[PE.peToTuple(indexpe)] = rhs
def getOEP(trace, filepath): base = None libs = trace.getMeta("LibraryPaths") for k, v in libs.iteritems(): if filepath in v: base = k if base is None: p = PE.peFromFileName(filepath) base = p.IMAGE_NT_HEADERS.OptionalHeader.ImageBase else: p = PE.peFromMemoryObject(trace, base) ep = p.IMAGE_NT_HEADERS.OptionalHeader.AddressOfEntryPoint oep = base + ep return oep
def showaslr(vdb, base, libname): t = vdb.getTrace() p = PE.peFromMemoryObject(t, base) enabled = False c = p.IMAGE_NT_HEADERS.OptionalHeader.DllCharacteristics if c & IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE: enabled = True vdb.vprint("%16s\t%s" % (libname, enabled))
def prob4(): maxn = 0 for i in range(999, 900, -1): for j in range(999, 900, -1): print(i, j) if i * j > maxn and PE.isPalindrome(i * j): maxn = i * j print(maxn)
def prob4(): maxn = 0 for i in range(999, 900 , -1): for j in range(999, 900 , -1): print(i, j) if i*j > maxn and PE.isPalindrome(i*j): maxn = i*j print(maxn)
def platformParseBinary(self, filename, baseaddr, normname): try: pe = PE.peFromMemoryObject(self, baseaddr) for rva, ord, name in pe.getExports(): self.addSymbol( e_resolv.Symbol(name, baseaddr + rva, 0, normname)) except Exception, e: print('Error Parsing Binary (%s): %s' % (normname, e))
def test_export_by_name(self): file_path = helpers.getTestPath('windows', 'i386', 'export_by_name.dll') pe = PE.peFromFileName(file_path) export_list = pe.getExports() self.assertEquals(len(export_list), 2, "expecting 2 exported functions") self.assertEquals(export_list[0][1], 0, "exported function with ordinal 0 not found") self.assertEquals(export_list[0][2], "Func1", "exported function with name 'Func1' not found") self.assertEquals(export_list[1][1], 1, "exported function with ordinal 1 not found") self.assertEquals(export_list[1][2], "Func2", "exported function with name 'Func2' not found")
def test_pe_vsersion(self): fpath = os.path.join('test_pe','bins','wwaninst.dll') pe = PE.peFromFileName(fpath) vs = pe.getVS_VERSIONINFO() self.assertIsNotNone(vs) keys = vs.getVersionKeys() self.assertEqual(len(keys), len(vs_version)) for key in vs.getVersionKeys(): self.assertEqual(vs_version.get(key), vs.getVersionValue(key))
def test_pe_vsersion(self): fpath = os.path.join('test_pe', 'bins', 'wwaninst.dll') pe = PE.peFromFileName(fpath) vs = pe.getVS_VERSIONINFO() self.assertIsNotNone(vs) keys = vs.getVersionKeys() self.assertEqual(len(keys), len(vs_version)) for key in vs.getVersionKeys(): self.assertEqual(vs_version.get(key), vs.getVersionValue(key))
def verifyRelation(C6, bfactlist, bgoal) : """attempts to verify bgoal, which is a primitive (relop or forall) params: C6 table bfactlist: a list of facts of form [relop, e1, e2] or [forall/exists, lo, i, hi, e] bgoal: a single fact of form [relop, e1, e2] or [forall/exists, lo, i, hi, e] returns : True, if bfactlist |- bgoal is proved False, if not """ #print "verifyRelation: C6"#, C6 #print "bfactlist:", bfactlist #print "bgoal:", bgoal #raw_input("press Enter") if (bgoal[0] in RELOPS) : # [relop, e1, e2] # eval goal: pe1 = PE.evall(C6, bgoal[1]) pe2 = PE.evall(C6, bgoal[2]) goal = [bgoal[0], pe1, pe2] # eval all facts in the bfactlist: factlist = [] for f in list(bfactlist) : if f[0] in RELOPS : pe1 = PE.evall(C6, f[1]) pe2 = PE.evall(C6, f[2]) factlist.append([f[0], pe1, pe2]) elif f[0] in ("forall", "exists") : pass # can't handle quantified phrases (yet) in PE! # If I am brave, I might try to evaluate lower and upper # bounds of quantification and enumerate the facts therein. # But this is high overhead.... # send off the PE-valued facts and goal to the prover: #print "In verifyrelation; ready to call PE.prove:" #print "all facts=", factlist + C6["rels"] #print "goal=", goal return PE.prove(factlist + C6["rels"], goal) elif bgoal[0] == "forall" : return proveUniversal(C6, bfactlist, bgoal) else : # ["exists", lo, i, hi, e] ??? return False
def platformGetImageBaseAddress(self, name=None): trace = self.trace if name is None: name = trace.getMeta("ExeName") #print "Exe name is %s"%(str(name)) if name and os.path.split(trace.metadata['ExeName']) > 0: fname = os.path.split(trace.metadata['ExeName'])[-1] name = os.path.splitext(fname)[0] #print "Exe base name is %s"%(str(name)) if name is None or\ not trace.hasMeta('LibraryBases') or\ not name in trace.getMeta('LibraryBases'): return "0xFFFFFFFF" baseAddr = trace.getMeta('LibraryBases')[name] mem = PE.MemObjFile(trace, baseAddr) pobj = PE.PE(mem, inmem=True) optionalHeader = pobj.IMAGE_NT_HEADERS.OptionalHeader #+x.BaseOfCode return "0x%x" % (baseAddr + optionalHeader.BaseOfCode)
def test_NORMAL_DLL(self): self.pe = PE(NORMAL_DLL) self.assertEqual(self.pe.Arch, TESTCASES[NORMAL_DLL]["ARCH"]) self.assertEqual(self.pe.Type, TESTCASES[NORMAL_DLL]["TYPE"]) self.assertEqual(self.pe.Format, TESTCASES[NORMAL_DLL]["FORMAT"]) self.assertEqual(self.pe.Bits, TESTCASES[NORMAL_DLL]["BITS"]) self.assertEqual(self.pe.EntryPoint, TESTCASES[NORMAL_DLL]["ENTRYPOINT"]) self.assertEqual(self.pe.Rebase, TESTCASES[NORMAL_DLL]["REBASE"]) self.log("NNORMAL_DLL: " + NORMAL_DLL)
def loadSymbols(trace, library, pdb=None): import PE as PE SYMBOLS_PATH = os.getenv('_NT_SYMBOL_PATH') if SYMBOLS_PATH == None: SYMBOLS_PATH = "C:\\Symbols" baseaddr = trace.getMeta('LibraryBases').get(library) if baseaddr == None: #raise Exception("%s library not loaded" % library) return 2 else: pe = PE.peFromMemoryObject(trace, baseaddr) oh = pe.IMAGE_NT_HEADERS.OptionalHeader deb = pe.IMAGE_NT_HEADERS.OptionalHeader.DataDirectory[ PE.IMAGE_DIRECTORY_ENTRY_DEBUG] virtaddr = deb.vsGetField('VirtualAddress') virtsize = deb.vsGetField('Size') poff = pe.rvaToOffset(virtaddr) if poff == 0: return 1 imageDebugDirectory = pe.readStructAtOffset( poff, 'pe.IMAGE_DEBUG_DIRECTORY') addrRawData = imageDebugDirectory.vsGetField('AddressOfRawData') cvInfoPdb = pe.readStructAtOffset(addrRawData, 'pe.CV_INFO_PDB70') cvGuid = cvInfoPdb.vsGetField('GuidSignature') cvSig = cvInfoPdb.vsGetField('CvSignature') tmpGuid = cvGuid.vsGetFields() tmpGuid.sort() guid = bytearray(16) for elem in range(len(tmpGuid)): guid[elem] = tmpGuid[elem][1].vsGetValue() guid_str = str(guid).encode('hex') if pdb == None: sympath = os.getenv('_NT_SYMBOL_PATH') if sympath == None: # Guess that the symbols are in the typical spot for windows. sympath = SYMBOLS_PATH filename = sympath + "\\" + library + ".pdb\\" + guid_str + "1\\" + library + ".pdb" else: filename = pdb if os.path.isfile(filename): try: trace.parseWithDbgHelp(filename, baseaddr, library) return 0 except: return 1 else: return 1
def insertRelation(C6, btree): """extracts all [RELOP, e1, e2]-relations asserted within btree and places them into the rels table in C6 params: C6 table and btree """ #sigma = C6["store"] # eval all facts in the bfactlist: cnffact = NF.cnf(btree) # returns a list of disjunctive clauses # save any disjunctive clause that is exactly [[RELOP, b1, b2]]: for clause in cnffact : if len(clause) == 1 and clause[0][0] in RELOPS : relop = clause[0][0] pe1 = PE.evall(C6, clause[0][1]) pe2 = PE.evall(C6, clause[0][2]) if pe1 != {} and pe2 != {} : newrel = [relop, pe1, pe2] if newrel not in C6["rels"] : C6["rels"] = [newrel] + C6["rels"] # new fact at front
def test_hiaddr_imports(self): # Test if imports located at a high relative address are discovered. file_path = helpers.getTestPath('windows', 'i386', 'section_has_hi_virtualaddr.exe') pe = PE.peFromFileName(file_path) import_list = pe.getImports() self.assertEqual(len(import_list), 36, "expecting 36 imported functions") self.assertEqual( import_list[0][1], "advapi32.dll", "imported function with name 'advapi32.dll' not found")
def showaslr(vdb, base, libname): t = vdb.getTrace() try: p = PE.peFromMemoryObject(t, base) except Exception as e: vdb.vprint('Error: %s (0x%.8x) %s' % (libname, base, e)) return enabled = False c = p.IMAGE_NT_HEADERS.OptionalHeader.DllCharacteristics if c & IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE: enabled = True vdb.vprint("%16s\t%s" % (libname, enabled))
def prob7(): numprimes = 1 i = 2 while numprimes != 10001: print(i) print(numprimes) i += 1 if PE.isPrime(i): numprimes += 1 print("and it is") print(i)
def prob34(): summ = 0 for i in range(3,1000000): print(i) k=i currsum = 0 while k: currsum += PE.factorial(k%10) k/=10 if currsum == i: summ += i print(summ)
def loadSymbols(trace, library, pdb=None): import PE as PE SYMBOLS_PATH = os.getenv('_NT_SYMBOL_PATH') if SYMBOLS_PATH == None: SYMBOLS_PATH = "C:\\Symbols" baseaddr = trace.getMeta('LibraryBases').get(library) if baseaddr == None: #raise Exception("%s library not loaded" % library) return 2 else: pe = PE.peFromMemoryObject(trace, baseaddr) oh = pe.IMAGE_NT_HEADERS.OptionalHeader deb = pe.IMAGE_NT_HEADERS.OptionalHeader.DataDirectory[PE.IMAGE_DIRECTORY_ENTRY_DEBUG] virtaddr = deb.vsGetField('VirtualAddress') virtsize = deb.vsGetField('Size') poff = pe.rvaToOffset(virtaddr) if poff == 0: return 1 imageDebugDirectory = pe.readStructAtOffset(poff, 'pe.IMAGE_DEBUG_DIRECTORY') addrRawData = imageDebugDirectory.vsGetField('AddressOfRawData') cvInfoPdb = pe.readStructAtOffset(addrRawData, 'pe.CV_INFO_PDB70') cvGuid = cvInfoPdb.vsGetField('GuidSignature') cvSig = cvInfoPdb.vsGetField('CvSignature') tmpGuid = cvGuid.vsGetFields() tmpGuid.sort() guid = bytearray(16) for elem in range(len(tmpGuid)): guid[elem] = tmpGuid[elem][1].vsGetValue() guid_str = str(guid).encode('hex') if pdb == None: sympath = os.getenv('_NT_SYMBOL_PATH') if sympath == None: # Guess that the symbols are in the typical spot for windows. sympath = SYMBOLS_PATH filename = sympath + "\\" + library + ".pdb\\" + guid_str + "1\\" + library + ".pdb" else: filename = pdb if os.path.isfile(filename): try: trace.parseWithDbgHelp(filename, baseaddr, library) return 0 except: return 1 else: return 1
def is_legit_pe(bytes): """ Load the memory region into a vivisect memory object and try loading the memory region as a PE "from memory". If it succeeds and contains valid sections, it's considered a valid PE. Parameters: bytes : byte string to test Returns: bool - True if legit pe, False if not """ try: new_pe = PE.peFromBytes(bytes) # ImageBase will not be zero and will be page aligned if ( new_pe.IMAGE_NT_HEADERS.OptionalHeader.ImageBase == 0 or new_pe.IMAGE_NT_HEADERS.OptionalHeader.ImageBase & 0xFFF != 0 ): return False if new_pe.IMAGE_NT_HEADERS.OptionalHeader.AddressOfEntryPoint > len(bytes): return False if new_pe.IMAGE_NT_HEADERS.OptionalHeader.SizeOfHeaders < 0x80: return False if new_pe.IMAGE_NT_HEADERS.OptionalHeader.SizeOfHeaders > len(bytes): return False # Section check # Start at 0x80, never seen a PE that has a VirtualAddress for the # first section below 0x80, usually > 0x400 prva = 0x80 for sect in new_pe.getSections(): if prva > sect.VirtualAddress: return False elif sect.VirtualAddress & 0xFF != 0: return False prva = sect.VirtualAddress # Assuming that more than 20 sections in a PE is likely bogus if 0 >= new_pe.IMAGE_NT_HEADERS.FileHeader.NumberOfSections > 20: return False # Could do more checks, but leaving at these, hopefully it'll be enough to rule # out garbage, but still catch missing MZ or DOS text stubs except: return False return True
def prob5(): prod = 1 for i in range(1, 21): if PE.isPrime(i): prod *= i if prod % i != 0: k = i m = prod for c in range(1, i / 2 + 1): if m % c == 0 and k % c == 0: k /= c m /= c prod *= k print(prod)
def prob5(): prod = 1 for i in range(1,21): if PE.isPrime(i): prod *= i if prod % i != 0: k = i m = prod for c in range(1,i/2 + 1): if m % c == 0 and k % c == 0: k /= c m /= c prod *= k print(prod)
def prob3(): num = 600851475143 curr = 1 maxnum = 0 while(curr < num): if num % curr == 0: num /= curr if PE.isPrime(num): maxnum = num print(curr) curr += 1 print("and the result is") print(maxnum) return maxnum
def main(argv): opts = setup().parse_args(argv) with open(opts.file, 'rb') as f: p = PE.PE(f) base = p.IMAGE_EXPORT_DIRECTORY.Base ords = {} for fva, ord, name in p.getExports(): ords[ord + base] = name keys = list(ords.keys()) for k in keys.sort(): print(' %d:"%s",' % (k, ords.get(k)))
def prob3(): num = 600851475143 curr = 1 maxnum = 0 while (curr < num): if num % curr == 0: num /= curr if PE.isPrime(num): maxnum = num print(curr) curr += 1 print("and the result is") print(maxnum) return maxnum
def prob12(): i = 1 triangle = 0 maxdiv = 0 while True: triangle += i print(i) numdiv = PE.numDivisors(triangle) print(str(triangle) + " : " + str(numdiv)) if numdiv >= 500: print(str(i) ) return i i+=1
def prob47(): i = 640 while True: curr = set() print(i) for j in range(4): val = PE.factorize(i+j) if len(val) != 4: break # curr = curr.union(val) # if len(curr) != 3 * (j+1): # break if j==3: print("soln is: " + str(i)) return i+=1