def testSymbolNameAddress(self): """Lookup symbol by name/address""" with PeFileAsDumpLoader( os.path.join(os.environ["WINDIR"], r"System32\ole32.dll")): mod = pykd.module("ole32") print "\n" + str(mod) targetSymAddr = mod.offset("CPackagerMoniker::Create") self.assertNotEqual(0, targetSymAddr) self.assertEqual("CPackagerMoniker::Create", mod.findSymbol(targetSymAddr)) targetSymAddr = mod.offset("CoInitialize") self.assertNotEqual(0, targetSymAddr) self.assertEqual("CoInitialize", mod.findSymbol(targetSymAddr)) with PeFileAsDumpLoader( os.path.join(os.environ["WINDIR"], r"System32\authz.dll")): mod = pykd.module("authz") print "\n" + str(mod) targetSymAddr = mod.offset("AuthzpDefaultAccessCheck") self.assertNotEqual(0, targetSymAddr) self.assertEqual("AuthzpDefaultAccessCheck", mod.findSymbol(targetSymAddr)) targetSymAddr = mod.offset("AuthzAccessCheck") self.assertNotEqual(0, targetSymAddr) self.assertEqual("AuthzAccessCheck", mod.findSymbol(targetSymAddr))
def testFindModule(self): self.assertRaises(pykd.BaseException, pykd.module, target.module.begin() - 0x10) self.assertNotEqual(None, pykd.module(target.module.begin())) self.assertNotEqual(None, pykd.module(target.module.begin() + 0x10)) self.assertRaises(pykd.BaseException, pykd.module, target.module.end()) self.assertRaises(pykd.BaseException, pykd.module, target.module.end() + 0x10)
def main(): kernel32 = pykd.module("kernel32") HANDLE = pykd.typeInfo("Void*") LPCWSTR = pykd.typeInfo("WChar*") DWORD = pykd.typeInfo("UInt4B") LPSECURITY_ATTRIBUTES = pykd.typeInfo("Void*") CreateFileW_Type = pykd.defineFunction(HANDLE, pykd.callingConvention.NearStd) CreateFileW_Type.append("lpFileName", LPCWSTR) CreateFileW_Type.append("dwDesiredAccess", DWORD) CreateFileW_Type.append("dwShareMode", DWORD) CreateFileW_Type.append("lpSecurityAttributes", LPSECURITY_ATTRIBUTES) CreateFileW_Type.append("dwCreationDisposition", DWORD) CreateFileW_Type.append("dwFlagsAndAttributes", DWORD) CreateFileW_Type.append("hTemplateFile", HANDLE) CreateFileW = pykd.typedVar(CreateFileW_Type, kernel32.CreateFileW) fileHandle = CreateFileW("C:\\temp\\testfile.txt", GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL) print "File Handle", hex(fileHandle)
def monitorHeapAlloc(): """Start monitoring allocations for the HeapAlloc""" global GBP ntdll = pykd.module( "ntdll" ) HeapAllocAddress = ntdll.offset("RtlAllocateHeap") GBP[HeapAllocAddress] = pykd.setBp(HeapAllocAddress, allocServedHeapAllocSystem)
def InitTracer(): global DriverObject global ImageBase global NtImageEnd NtModule = pykd.module("nt") NtImageBase = NtModule.begin() NtImageEnd = NtModule.end() pykd.dbgCommand("ba e1 IopLoadDriver+4bd") pykd.dbgCommand("ba e1 IopLoadDriver+4c2") pykd.go() while(1): regPath = pykd.dbgCommand("du /c40 @rdx+10") if "VmpDriver.vmp" in regPath: print "[*] Find VMP Driver" DriverObject = pykd.reg("rcx") print "\t[-] Driver Object : 0x{:X}".format(DriverObject) ImageBase =pykd.ptrPtr(DriverObject+0x18) # DriverObject.DriverStart print "\t[-] ImageBase Address : 0x{:X}".format(ImageBase) VMPTracingSub.GetSectionInfo(ImageBase) EntryPoint = ImageBase + VMPTracingSub.EntryPoint_Off strEntryPoint = hex(EntryPoint).rstrip("L") pykd.dbgCommand("ba e1 "+strEntryPoint) pykd.go() pykd.dbgCommand("bc 2") return pykd.go()
def get_value(symbol): global cache_values k = symbol if k not in cache_values: mozglue = pykd.module('mozglue') symbol_addr = mozglue.offset(symbol) cache_values[k] = pykd.ptrDWord(symbol_addr) return cache_values[k]
def getModuleSize(module): """Getting the size of the module to perform memory searches""" global NPS print "[+] Getting module size..." if module == 'NPS': mod = pykd.module(NPS['base_addr']) NPS['size'] = mod.size() NPS['end_addr'] = NPS['base_addr'] + NPS['size'] print "[+] NPSBASE FOUND 0x%x, NPS_SIZE 0x%x, NPS_END 0x%x" %\ (NPS['base_addr'], NPS['size'], NPS['end_addr'])
def __init__(self, lObfusMem, br=None, memh=None): self.lObfusMem = lObfusMem if br == None: self.br = WinDbgBridge() else: self.br = br if memh == None: self.memh = MemBpHandler() else: self.memh = memh self.hNtdll = pykd.module(self.symNtdll) self.pFreeVirtualMemory = self.hNtdll.offset(self.symFreeVirtualMemory) self.br.dbiprintf("[!] %s!%s = 0x%08x" % (self.symNtdll, self.symFreeVirtualMemory, self.pFreeVirtualMemory)) self.bp_init = pykd.setBp(self.pFreeVirtualMemory, self.handler_onCall) self.bp_end = None
def _meta_object_addr_of_frame(frame): ax32serv = module('Ax32Serv') element_type = _element_type_of_raw_frame(frame) element_id = _element_id_of_raw_frame(frame) base_offset = 0 first_lvl_offset = 72 second_lvl_offset = 0 if element_type == ElementType.xpp_table: base_offset = ax32serv.offset('tableObj') second_lvl_offset = (element_id % 2500) * 8 elif element_type == ElementType.xpp_class: base_offset = ax32serv.offset('classObj') second_lvl_offset = (element_id % 2500) * 8 else: return 0 return ptrPtr(ptrPtr(base_offset + first_lvl_offset) + second_lvl_offset)
def main(): pykd.initialize() pykd.handler = ExceptionHandler() pykd.startProcess("hello.exe") targetModule = pykd.module("hello") targetModule.reload() breakCount = callCounter() b1 = pykd.setBp(targetModule.offset('add'), breakCount) # The b1 cannot be commented print "There is %d breakpoint" % pykd.getNumberBreakpoints() pykd.go() print breakCount.count targetModule = None pykd.killAllProcesses()
def __init__(self, base, config, *args, **kwargs): self.as_assert(base == None) self.as_assert(config.LOCATION=='windbg') self.as_assert(pykd.isKernelDebugging()) self.dtb = pykd.reg('cr3') self.nt = pykd.module('nt') config.KDBG = self.nt.KdCopyDataBlock self.pageSize = pykd.pageSize() self.lowPage = pykd.ptrMWord(self.nt.MmLowestPhysicalPage) self.highPage = pykd.ptrMWord(self.nt.MmHighestPhysicalPage) self.spaces = [ ( self.lowPage*self.pageSize, (self.highPage -self.lowPage )*self.pageSize) ] super(PykdAddressSpace,self).__init__(base,config) self.name = "WinDBG Address Space"
def __init__(self, base, config, *args, **kwargs): self.as_assert(base == None) self.as_assert(config.LOCATION == 'windbg') self.as_assert(pykd.isKernelDebugging()) self.dtb = pykd.reg('cr3') self.nt = pykd.module('nt') config.KDBG = self.nt.KdCopyDataBlock self.pageSize = pykd.pageSize() self.lowPage = pykd.ptrMWord(self.nt.MmLowestPhysicalPage) self.highPage = pykd.ptrMWord(self.nt.MmHighestPhysicalPage) self.spaces = [(self.lowPage * self.pageSize, (self.highPage - self.lowPage) * self.pageSize)] super(PykdAddressSpace, self).__init__(base, config) self.name = "WinDBG Address Space"
def testChangeSymbolsState(self): """Start new process and track change symbols exception""" _locProcessId = pykd.startProcess(target.appPath + " -testLoadUnload") with testutils.ContextCallIt( testutils.KillProcess(_locProcessId)) as killStartedProcess: mod = pykd.module("targetapp") symbolsStateHandler = SymbolsStateHandler(mod.begin()) pykd.dbgCommand(".reload /u targetapp.exe") self.assertTrue(symbolsStateHandler.unloadModuleTrigged) pykd.dbgCommand(".reload /u") self.assertTrue(symbolsStateHandler.unloadAllModulesTrigged) self.assertRaises(pykd.WaitEventException, testutils.infGo) self.assertTrue("iphlpapi" in symbolsStateHandler.modNames)
def main(): nt_module = pykd.module("nt") ObpTypeDirectoryObject_addr = int(nt_module.ObpTypeDirectoryObject) ObpTypeDirectoryObject_value = pykd.loadQWords(ObpTypeDirectoryObject_addr, 1)[0] dict_entry_list = pykd.loadQWords(ObpTypeDirectoryObject_value, 37) print 'TypeName PoolTag PoolType' for dict_entry in dict_entry_list: if dict_entry == 0: continue type_obj_addr = pykd.loadQWords(dict_entry + 8, 1)[0] name_str = pykd.loadUnicodeString(type_obj_addr + 0x10) key_str = pykd.loadCStr(type_obj_addr + 0xc0) pool_type = pykd.loadDWords(type_obj_addr + 0x40 + 0x24, 1)[0] if pool_type == 1: pool_type = 'PagedPool' elif pool_type == 0x200: pool_type = 'NonPagedPoolNx' print '%s\n%s\n%s\n' % (name_str, key_str, pool_type)
def get_value(symbol): mozglue = pykd.module('mozglue') symbol_addr = mozglue.offset(symbol) return pykd.ptrDWord(symbol_addr)
if __name__ == "__main__": if not pykd.isWindbgExt(): print("Script cannot be launched outside Windbg") quit(0) if len(sys.argv) < 2: print("Expecting process name as argument") quit(0) targetProcessName = sys.argv[1] pykd.dprintln("Target: " + targetProcessName) processList = pykd.typedVarList( pykd.module("nt").PsActiveProcessHead, "nt!_EPROCESS", "ActiveProcessLinks") for i, process in enumerate(processList): if pykd.loadCStr(process.ImageFileName) == targetProcessName: targetProcessList = pykd.module("nt").typedVar( "_LIST_ENTRY", process.ActiveProcessLinks) print("ActiveProcessLinks: 0x%08x" % process.ActiveProcessLinks) print(targetProcessList) #prevFlink = module("nt").typedVar("_LIST_ENTRY",targetProcessList.Blink) #nextBlink = module("nt").typedVar("_LIST_ENTRY",targetProcessList.Flink) print("prevFlink: 0x%08x" % pykd.ptrQWord(targetProcessList.Blink)) print("nextBlink: 0x%08x" % pykd.ptrQWord(targetProcessList.Flink + 8)) targetProcessBlink = targetProcessList.Blink
for extdirname in windbgextdirs: extdirpath=os.path.join(windbgpath, extdirname) fl=glob.glob(extdirpath) if not fl: raise Exception('%s not exists, have you installed the latest windbg?' % extdirpath) dirpath=fl[0] l=os.listdir(dirpath) for i in l: filepath=os.path.join(dirpath, i) if i in default_exts: print 'load', filepath pykd.dbgCommand('.load %s' % filepath) print 'load extensions ok' nt = pykd.module( "nt" ) g_kernelsize=int(nt.size()) g_kernelbase=int(nt.begin()) module_entry=pykd.ptrMWord(pykd.getOffset('nt!PsLoadedModuleList')) module_entry=pykd.typedVar('nt!_LDR_DATA_TABLE_ENTRY', module_entry) kernelpath=pykd.loadUnicodeString(module_entry.FullDllName) name=os.path.basename(kernelpath) g_kernelpath=os.path.join(g_system32dir, name) if not os.path.exists(g_kernelpath): raise Exception("can't find %s" % g_kernelpath) imagename=nt.image() kernelbasepath=os.path.join(g_system32dir, imagename) import shutil if not os.path.exists(kernelbasepath): shutil.copy(g_kernelpath, kernelbasepath)
def get_xul_version(): version = pykd.loadCStr(pykd.module('xul').offset('gToolkitVersion')) return version
def addressof(symbol): mozglue = pykd.module('mozglue') return mozglue.offset(symbol)
def testStart(self): target.processId = pykd.startProcess( target.appPath ) target.module = pykd.module( target.moduleName ) target.module.reload(); # print "\n" + str( pykd.getSystemVersion() ) pykd.go()
def input_file(self): exeModuleName = pykd.dbgCommand("lm1m").split('\n')[0] exeModule = pykd.module(exeModuleName) return open(exeModule.image(), "rb")
def getMouleByName(name): return pykd.module(name)
def setUp(self): pykd.startProcess(target.appPath + " breakhandlertest") self.targetModule = pykd.module(target.moduleName) self.targetModule.reload() pykd.go()
def main(argv): if len(argv) == 0: print "Usage: !py filter.py from_level to_level filtered" print "Filtered syscalls for 5th level: !py filter.py 5 5 1" exit(-1) ntMod = pykd.module("nt") KeServiceDescriptorTableFilter = int(ntMod.KeServiceDescriptorTableFilter) win32Mod = pykd.module("win32k") W32pServiceTableFilter = int(win32Mod.W32pServiceTableFilter) W32pServiceLimitFilter = pykd.loadDWords(win32Mod.W32pServiceLimitFilter, 1)[0] + 0x1000 print '[*]W32pServiceTableFilter Address:' print '[*]'+str(hex(W32pServiceTableFilter)) win32BaseMod = pykd.module("win32kbase") gaWin32KFilterBitmap = int(win32BaseMod.gaWin32KFilterBitmap) print '[*]gaWin32KFilterBitmap Address:' print '[*]'+str(hex(gaWin32KFilterBitmap)) start_level = int(argv[0]) end_level = int(argv[1]) filter = int(argv[2]) sum = 0 syscallsLimit = W32pServiceLimitFilter - 0x1000 for i in range(start_level, end_level + 1): bitmap = pykd.loadQWords(gaWin32KFilterBitmap + i * 8, 1)[0] print '[*]=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=' print '[*]Bitmap filter level ' + str(hex(i)) if filter: print '[*]Show Filtered' else: print '[*]Show Unfiltered' if not bitmap: print '[*] None' continue # Check SSSDT ID for 0x1000 for j in range(0x1000, W32pServiceLimitFilter): # bit index in byte syscallNum = j & 0xfff # function offset in W32pServiceTableFilter offset = pykd.loadDWords(W32pServiceTableFilter + syscallNum * 4, 1)[0] offset = (0xfffffffff0000000 | (offset >> 4)) # function address syscall = W32pServiceTableFilter + offset syscall = syscall % 2**64 # check check_byte = pykd.loadBytes(bitmap + (syscallNum >> 3), 1)[0] filtered = check_byte & (1 << (syscallNum & 7)) filtered = filtered != 0 # 1 is filtered,0 is unfiltered if filtered == filter: sum = sum + 1 print '[*]'+pykd.findSymbol(syscall) + ' ' + hex(j) if filter: print "[*]number of filtered system calls" else: print "[*]number of allowed system calls" print '[*]'+str(syscallsLimit) + "/" + str(sum) exit(0)
def testCtor(self): self.assertEqual(target.module.name(), pykd.module(target.module.begin()).name()) self.assertEqual(target.module.name(), pykd.module(target.module.name()).name())
def onSymbolsLoaded(self, modBase): if modBase: self.modNames.add(pykd.module(modBase).name())
def image_base(self): exeModuleName = pykd.dbgCommand("lm1m").split('\n')[0] exeModule = pykd.module(exeModuleName) return exeModule.begin()
def get_module(self, address): return pykd.module(address)
import pykd # Parsing the ProcessList with pykd if __name__ == "__main__": if not pykd.isWindbgExt(): print("Script cannot be launched outside Windbg") quit(0) pActiveProcessList = pykd.module("nt").PsActiveProcessHead # pActiveProcessList = pykd.getOffset("nt!PsActiveProcessHead") -> slower than using module("nt")... processList = pykd.typedVarList(pActiveProcessList, "nt!_EPROCESS", "ActiveProcessLinks") for i, process in enumerate(processList): pykd.dprint("Process " + str(i) + ":") name = pykd.loadCStr(process.ImageFileName) print(name)
for extdirname in windbgextdirs: extdirpath = os.path.join(windbgpath, extdirname) fl = glob.glob(extdirpath) if not fl: raise Exception("%s not exists, have you installed the latest windbg?" % extdirpath) dirpath = fl[0] l = os.listdir(dirpath) for i in l: filepath = os.path.join(dirpath, i) if i in default_exts: print "load", filepath pykd.dbgCommand(".load %s" % filepath) print "load extensions ok" nt = pykd.module("nt") g_kernelsize = int(nt.size()) g_kernelbase = int(nt.begin()) module_entry = pykd.ptrMWord(pykd.getOffset("nt!PsLoadedModuleList")) module_entry = pykd.typedVar("nt!_LDR_DATA_TABLE_ENTRY", module_entry) kernelpath = pykd.loadUnicodeString(module_entry.FullDllName) name = os.path.basename(kernelpath) g_kernelpath = os.path.join(g_system32dir, name) if not os.path.exists(g_kernelpath): raise Exception("can't find %s" % g_kernelpath) imagename = nt.image() kernelbasepath = os.path.join(g_system32dir, imagename) import shutil if not os.path.exists(kernelbasepath): shutil.copy(g_kernelpath, kernelbasepath)