def listCmpCallback(): try: notifyaddr=pykd.getOffset('nt!CmpCallBackVector') count=pykd.getOffset('nt!CmpCallBackCount') count=pykd.ptrPtr(count) print '-'*10+'CmpCallback'+'-'*10 if is_2000(): for i in xrange(count): funcaddr=pykd.ptrPtr(notifyaddr+i*g_mwordsize)&0xffffffffffffff8 symbolname=pykd.findSymbol(source) print 'routine:%x %s' % (funcaddr, symbolname) else: if pykd.is64bitSystem(): for i in xrange(count): funcaddr=pykd.ptrPtr(notifyaddr+i*g_mwordsize)&0xffffffffffffff8 symbolname=pykd.findSymbol(funcaddr) print 'routine:%x %s' % (funcaddr, symbolname) else: for i in xrange(count): routine_block=pykd.ptrPtr(notifyaddr+i*g_mwordsize)&0xffffffffffffff8 funcaddr=pykd.ptrPtr(routine_block+g_mwordsize) symbolname=pykd.findSymbol(funcaddr) print 'routine:%x %s' % (funcaddr, symbolname) except Exception, err: print traceback.format_exc()
def listCreateProcess(): try: print '-' * 10 + 'CreateProcess' + '-' * 10 notifyaddr = pykd.getOffset('nt!PspCreateProcessNotifyRoutine') count = pykd.getOffset('nt!PspCreateProcessNotifyRoutineCount') count = pykd.ptrPtr(count) try: excount = pykd.getOffset('nt!PspCreateProcessNotifyRoutineExCount') except: excount = 0 count += excount if is_2000(): for i in xrange(count): funcaddr = pykd.ptrPtr(notifyaddr + i * g_mwordsize) & 0xffffffffffffff8 symbolname = pykd.findSymbol(source) print 'routine:%x %s' % (funcaddr, symbolname) else: if pykd.is64bitSystem(): for i in xrange(count): funcaddr = pykd.ptrPtr(notifyaddr + i * g_mwordsize) & 0xffffffffffffff8 symbolname = pykd.findSymbol(funcaddr) print 'routine:%x %s' % (funcaddr, symbolname) else: for i in xrange(count): routine_block = pykd.ptrPtr( notifyaddr + i * g_mwordsize) & 0xffffffffffffff8 funcaddr = pykd.ptrPtr(routine_block + g_mwordsize) symbolname = pykd.findSymbol(funcaddr) print 'routine:%x %s' % (funcaddr, symbolname) except Exception, err: print traceback.format_exc()
def listCreateProcess(): try: print '-'*10+'CreateProcess'+'-'*10 notifyaddr=pykd.getOffset('nt!PspCreateProcessNotifyRoutine') count=pykd.getOffset('nt!PspCreateProcessNotifyRoutineCount') count=pykd.ptrPtr(count) try: excount=pykd.getOffset('nt!PspCreateProcessNotifyRoutineExCount') except: excount=0 count+=excount if is_2000(): for i in xrange(count): funcaddr=pykd.ptrPtr(notifyaddr+i*g_mwordsize)&0xffffffffffffff8 symbolname=pykd.findSymbol(source) print 'routine:%x %s' % (funcaddr, symbolname) else: if pykd.is64bitSystem(): for i in xrange(count): funcaddr=pykd.ptrPtr(notifyaddr+i*g_mwordsize)&0xffffffffffffff8 symbolname=pykd.findSymbol(funcaddr) print 'routine:%x %s' % (funcaddr, symbolname) else: for i in xrange(count): routine_block=pykd.ptrPtr(notifyaddr+i*g_mwordsize)&0xffffffffffffff8 funcaddr=pykd.ptrPtr(routine_block+g_mwordsize) symbolname=pykd.findSymbol(funcaddr) print 'routine:%x %s' % (funcaddr, symbolname) except Exception, err: print traceback.format_exc()
def listCmpCallback(): try: notifyaddr = pykd.getOffset('nt!CmpCallBackVector') count = pykd.getOffset('nt!CmpCallBackCount') count = pykd.ptrPtr(count) print '-' * 10 + 'CmpCallback' + '-' * 10 if is_2000(): for i in xrange(count): funcaddr = pykd.ptrPtr(notifyaddr + i * g_mwordsize) & 0xffffffffffffff8 symbolname = pykd.findSymbol(source) print 'routine:%x %s' % (funcaddr, symbolname) else: if pykd.is64bitSystem(): for i in xrange(count): funcaddr = pykd.ptrPtr(notifyaddr + i * g_mwordsize) & 0xffffffffffffff8 symbolname = pykd.findSymbol(funcaddr) print 'routine:%x %s' % (funcaddr, symbolname) else: for i in xrange(count): routine_block = pykd.ptrPtr( notifyaddr + i * g_mwordsize) & 0xffffffffffffff8 funcaddr = pykd.ptrPtr(routine_block + g_mwordsize) symbolname = pykd.findSymbol(funcaddr) print 'routine:%x %s' % (funcaddr, symbolname) except Exception, err: print traceback.format_exc()
def testNamespace(self): ti1 = pykd.typeInfo(target.moduleName, "Namespace1::Class1") ti2 = pykd.typeInfo(target.moduleName, "Namespace1::Namespace2::Class2") var3 = pykd.typedVar( ti1, pykd.getOffset(target.moduleName, "Namespace1::var3")) var4 = pykd.typedVar( ti1, pykd.getOffset(target.moduleName, "Namespace1::Namespace2::var4")) self.assertEqual(var3.m_field1, 50)
def inspectShadowSSDT(): r = pykd.dbgCommand('dd win32k L1').split(' ') win32kbase = pykd.addr64(int(r[0], 16)) print 'wink32.sys baseaddr:0x%x' % win32kbase W32pServiceTable = pykd.getOffset('win32k!W32pServiceTable') print 'win32k!W32pServiceTable:0x%x' % W32pServiceTable W32pServiceLimit = pykd.getOffset('win32k!W32pServiceLimit') W32pServiceLimit = pykd.ptrMWord(W32pServiceLimit) print 'win32k!W32pServiceLimit:0x%x(%d)' % (W32pServiceLimit, W32pServiceLimit) shadowssdttable = pykd.loadPtrs(W32pServiceTable, W32pServiceLimit) table_rva = (W32pServiceTable - win32kbase) print 'W32pServiceTable rva:0x%x' % table_rva win32kname = 'win32k.sys' windowsdir = win32api.GetWindowsDirectory() filepath = os.path.join(windowsdir, 'system32', win32kname) if not os.path.exists(filepath): raise Exception('%s not exists!' % win32kname) print 'win32k.sys path:', filepath filedata = open(filepath, 'rb').read() pe = pefile.PE(data=filedata, fast_load=True) if pe.DOS_HEADER.e_magic != 0X5A4D or pe.NT_HEADERS.Signature != 0x4550: raise Exception("%s is not a pe file" % filepath) table_fileoffset = pe.get_offset_from_rva(table_rva) print 'W32pServiceTable file offset:0x%x' % table_fileoffset d = filedata[table_fileoffset:table_fileoffset + g_mwordsize * W32pServiceLimit] number = 0 for i in xrange(W32pServiceLimit): source = binascii.b2a_hex(d[i * g_mwordsize:(i + 1) * g_mwordsize][::-1]) source = int(source, 16) - pe.OPTIONAL_HEADER.ImageBase + win32kbase symbolname = pykd.findSymbol(source) current = shadowssdttable[i] if source == current: print 'source:0x%x current:0x%x %s' % (source, current, symbolname) else: hooksymbolname = pykd.findSymbol(current) print 'source:0x%x %s <-> current:0x%x %s hooked!!!!!!!' % ( source, symbolname, current, hooksymbolname) number += 1 print 'hooked function number:', number
def listModuleByLdrHash(eprocessaddr): modulelist = {} try: cmdline = '.process /P %x;.reload;' % eprocessaddr r = pykd.dbgCommand(cmdline) try: LdrpHashTable = pykd.getOffset('ntdll!LdrpHashTable') except: print 'get LdrpHashTable symbol fail, maybe ldr is null' return [] if int(LdrpHashTable) != 0: for i in xrange(26): listhead = LdrpHashTable + i * 2 * g_mwordsize hashlink = listhead while 1: hashlink = pykd.ptrPtr(hashlink) if hashlink == listhead: break ldr = pykd.containingRecord(hashlink, 'nt!_LDR_DATA_TABLE_ENTRY', 'HashLinks') if int(ldr) not in modulelist: info = ModuleInfo() if info.init1(ldr): modulelist[int(ldr)] = info except Exception, err: print traceback.format_exc()
def testArrayField(self): v7 = pykd.typedVar(target.moduleName, "Type7", pykd.getOffset(target.moduleName, "var7")) self.assertEqual(v7.field1[1].field1, 10) self.assertEqual(v7.field1[5].field2, 20) self.assertEqual(v7.field2[1][0].field1, 10) self.assertEqual(v7.field2[0][1].field2, 20)
def resolve_symbol(self, symbol): offset = 0 if symbol.find('+') >= 0: addr_toks = addr_str.split("+") if len(addr_toks) > 1: symbol = addr_toks[0] offset = windbgtool.util.convert_to_int(addr_toks[1], 16) if symbol in self.symbol_to_address: return self.symbol_to_address[symbol] + offset if symbol.find("!") >= 0: (module_name, function_name) = symbol.split('!', 1) if module_name.find(".") >= 0: module_name = module_name.split('.')[0] self.load_symbols([ module_name, ]) if symbol in self.symbol_to_address: return self.symbol_to_address[symbol] + offset try: return pykd.getOffset(symbol) + offset except: return 0
def listModuleByLdrHash(eprocessaddr): modulelist = {} try: cmdline = ".process /P %x;.reload;" % eprocessaddr r = pykd.dbgCommand(cmdline) try: LdrpHashTable = pykd.getOffset("ntdll!LdrpHashTable") except: print "get LdrpHashTable symbol fail, maybe ldr is null" return [] if int(LdrpHashTable) != 0: for i in xrange(26): listhead = LdrpHashTable + i * 2 * g_mwordsize hashlink = listhead while 1: hashlink = pykd.ptrPtr(hashlink) if hashlink == listhead: break ldr = pykd.containingRecord(hashlink, "nt!_LDR_DATA_TABLE_ENTRY", "HashLinks") if int(ldr) not in modulelist: info = ModuleInfo() if info.init1(ldr): modulelist[int(ldr)] = info except Exception, err: print traceback.format_exc()
def inspectSSDT(): kernelbase=g_kernelbase KeServiceDescriptorTable=pykd.getOffset('nt!KeServiceDescriptorTable') KiServiceTable=pykd.ptrPtr(KeServiceDescriptorTable) serviceCount=pykd.ptrMWord(KeServiceDescriptorTable+2*g_mwordsize) print 'nt!KeServiceDescriptorTable:0x%x' % KeServiceDescriptorTable print 'nt!KiServiceTable:0x%x' % KiServiceTable print 'serviceCount:0x%x(%d)' % (serviceCount, serviceCount) ssdttable=pykd.loadPtrs(KiServiceTable, serviceCount) table_rva=(KiServiceTable-kernelbase) print 'KiServiceTable rva:0x%x' % table_rva filedata=open(g_kernelpath, 'rb').read() pe = pefile.PE(data=filedata, fast_load=True) if pe.DOS_HEADER.e_magic!=0X5A4D or pe.NT_HEADERS.Signature!=0x4550: raise Exception("%s is not a pe file" % filepath) table_fileoffset=pe.get_offset_from_rva(table_rva) print 'KiServiceTable file offset:0x%x' % table_fileoffset d=filedata[table_fileoffset:table_fileoffset+g_mwordsize*serviceCount] number=0 for i in xrange(serviceCount): source=binascii.b2a_hex(d[i*g_mwordsize:(i+1)*g_mwordsize][::-1]) source=pykd.addr64(int(source, 16))-pykd.addr64(pe.OPTIONAL_HEADER.ImageBase)+kernelbase symbolname=pykd.findSymbol(source) current=ssdttable[i] if source==current: print 'source:0x%x current:0x%x %s' % (source, current, symbolname) else: hooksymbolname=pykd.findSymbol(current) print 'source:0x%x %s <-> current:0x%x %s hooked!!!!!!!' % (source, symbolname, current, hooksymbolname) number+=1 print 'hooked function number:', number
def listShutdown(): try: print '-' * 10 + 'Shutdown' + '-' * 10 IRP_MJ_SHUTDOWN = 0x10 #define IRP_MJ_SHUTDOWN 0x10 head = pykd.getOffset('nt!IopNotifyShutdownQueueHead') next = head while 1: next = pykd.ptrPtr(next) if next == head: break try: deviceobjectaddr = pykd.ptrPtr(next + g_mwordsize * 2) deviceobject = pykd.typedVar('nt!_DEVICE_OBJECT', deviceobjectaddr) driverobject = pykd.typedVar('nt!_DRIVER_OBJECT', int(deviceobject.DriverObject)) funcaddr = pykd.ptrPtr(driverobject.MajorFunction + g_mwordsize * IRP_MJ_SHUTDOWN) symbolname = pykd.findSymbol(funcaddr) print 'routine:%x %s' % (funcaddr, symbolname) except Exception, err: pass except Exception, err: print traceback.format_exc()
def testPtrField(self): v6 = pykd.typedVar(target.moduleName, "Type6", pykd.getOffset(target.moduleName, "var6")) self.assertEqual(v6.field1, 10) self.assertEqual(v6.field2.field1, 10) self.assertEqual(v6.field2.field2, 20) self.assertNotEqual(v6.field2, 0) self.assertEqual(v6.field3[0].field1, 10) self.assertEqual(v6.field3[1].field2, 20)
def inspectShadowSSDT(): r=pykd.dbgCommand('dd win32k L1').split(' ') win32kbase=pykd.addr64(int(r[0],16)) print 'wink32.sys baseaddr:0x%x' % win32kbase W32pServiceTable=pykd.getOffset('win32k!W32pServiceTable') print 'win32k!W32pServiceTable:0x%x' % W32pServiceTable W32pServiceLimit=pykd.getOffset('win32k!W32pServiceLimit') W32pServiceLimit=pykd.ptrMWord(W32pServiceLimit) print 'win32k!W32pServiceLimit:0x%x(%d)' % (W32pServiceLimit, W32pServiceLimit) shadowssdttable=pykd.loadPtrs(W32pServiceTable, W32pServiceLimit) table_rva=(W32pServiceTable-win32kbase) print 'W32pServiceTable rva:0x%x' % table_rva win32kname='win32k.sys' windowsdir=win32api.GetWindowsDirectory() filepath=os.path.join(windowsdir, 'system32', win32kname) if not os.path.exists(filepath): raise Exception('%s not exists!' % win32kname) print 'win32k.sys path:', filepath filedata=open(filepath, 'rb').read() pe = pefile.PE(data=filedata, fast_load=True) if pe.DOS_HEADER.e_magic!=0X5A4D or pe.NT_HEADERS.Signature!=0x4550: raise Exception("%s is not a pe file" % filepath) table_fileoffset=pe.get_offset_from_rva(table_rva) print 'W32pServiceTable file offset:0x%x' % table_fileoffset d=filedata[table_fileoffset:table_fileoffset+g_mwordsize*W32pServiceLimit] number=0 for i in xrange(W32pServiceLimit): source=binascii.b2a_hex(d[i*g_mwordsize:(i+1)*g_mwordsize][::-1]) source=int(source, 16)-pe.OPTIONAL_HEADER.ImageBase+win32kbase symbolname=pykd.findSymbol(source) current=shadowssdttable[i] if source==current: print 'source:0x%x current:0x%x %s' % (source, current, symbolname) else: hooksymbolname=pykd.findSymbol(current) print 'source:0x%x %s <-> current:0x%x %s hooked!!!!!!!' % (source, symbolname, current, hooksymbolname) number+=1 print 'hooked function number:', number
def testSymbol(self): self.assertEqual( target.module.rva("FastcallFunc"), target.module.offset("FastcallFunc") - target.module.begin()) self.assertEqual(target.module.rva("FastcallFunc"), target.module.FastcallFunc - target.module.begin()) self.assertEqual( target.module.rva("FastcallFunc"), pykd.getOffset(target.module.name() + "!FastcallFunc") - target.module.begin())
def testSymbol(self): self.assertEqual( target.module.rva("FuncWithName0"), target.module.offset("FuncWithName0") - target.module.begin()) self.assertEqual(target.module.rva("FuncWithName0"), target.module.FuncWithName0 - target.module.begin()) self.assertEqual( target.module.rva("FuncWithName0"), pykd.getOffset(target.module.name() + "!FuncWithName0") - target.module.begin())
def inspectMsgHook(): msglist = [] try: gSharedInfo = pykd.getOffset('win32k!gSharedInfo') serverinfo = pykd.ptrPtr(gSharedInfo) aheList = pykd.ptrPtr(gSharedInfo + g_mwordsize) if is_2000() or is_xp(): count = pykd.ptrPtr(serverinfo + g_mwordsize * 2) else: count = pykd.ptrPtr(serverinfo + g_mwordsize * 1) for i in xrange(count): entry = aheList + i * 3 * g_mwordsize phook = pykd.ptrPtr(entry) #head type = pykd.ptrByte(entry + 2 * g_mwordsize) if type != 5: continue try: handle = pykd.ptrPtr(phook) msgtype = pykd.ptrPtr(phook + 6 * g_mwordsize) funcoffset = pykd.ptrPtr(phook + 7 * g_mwordsize) flags = pykd.ptrPtr(phook + 8 * g_mwordsize) if flags & 1: bGlobal = 1 else: bGlobal = 0 pti = pykd.ptrPtr(phook + 2 * g_mwordsize) threadobjectaddr = pykd.ptrPtr(pti) threadobject = pykd.typedVar('nt!_ETHREAD', threadobjectaddr) pid = int(threadobject.Cid.UniqueProcess) tid = (threadobject.Cid.UniqueThread) try: processobject = pykd.typedVar('nt!_EPROCESS', threadobject.ThreadsProcess) except Exception, err: processobject = pykd.typedVar('nt!_EPROCESS', threadobject.Tcb.Process) processpath = pykd.loadUnicodeString( processobject.SeAuditProcessCreationInfo.ImageFileName.Name ) msginfo = MsgInfo(handle=handle, pid=pid, tid=tid, msgtype=msgtype, funcoffset=funcoffset, bGlobal=bGlobal, processpath=processpath) msglist.append(msginfo) except Exception, err: print err
def listProcessByPsActiveProcessHead(): processlist=[] try: PsActiveProcessHead=pykd.getOffset('nt!PsActiveProcessHead') l=pykd.typedVarList(PsActiveProcessHead, 'nt!_EPROCESS', 'ActiveProcessLinks') for i in l: info=ProcessInfo() if info.init(i): processlist.append(info) except Exception, err: print traceback.format_exc()
def listProcessByPsActiveProcessHead(): processlist = [] try: PsActiveProcessHead = pykd.getOffset('nt!PsActiveProcessHead') l = pykd.typedVarList(PsActiveProcessHead, 'nt!_EPROCESS', 'ActiveProcessLinks') for i in l: info = ProcessInfo() if info.init(i): processlist.append(info) except Exception, err: print traceback.format_exc()
def listSeFileSystem(): try: print '-' * 10 + 'SeFileSystem' + '-' * 10 head = pykd.getOffset('nt!SeFileSystemNotifyRoutinesHead') next = head while 1: next = pykd.ptrPtr(next) if not next: break funcaddr = pykd.ptrPtr(next + g_mwordsize) symbolname = pykd.findSymbol(funcaddr) print 'routine:%x %s' % (funcaddr, symbolname) except Exception, err: print traceback.format_exc()
def listIopTimer(): try: print '-' * 10 + 'IopTimer' + '-' * 10 head = pykd.getOffset('nt!IopTimerQueueHead') next = head while 1: next = pykd.ptrPtr(next) if next == head: break funcaddr = pykd.ptrPtr(next + g_mwordsize * 2) symbolname = pykd.findSymbol(funcaddr) print 'routine:%x %s' % (funcaddr, symbolname) except Exception, err: print traceback.format_exc()
def listBugCheckReasonCallback(): try: print '-' * 10 + 'BugCheckReasonCallback' + '-' * 10 head = pykd.getOffset('nt!KeBugCheckReasonCallbackListHead') next = head while 1: next = pykd.ptrPtr(next) if next == head: break funcaddr = pykd.ptrPtr(next + g_mwordsize * 2) symbolname = pykd.findSymbol(funcaddr) print 'routine:%x %s' % (funcaddr, symbolname) except Exception, err: print traceback.format_exc()
def listDriverByPsLoadedModuleList(): driverlist=[] try: PsLoadedModuleList=pykd.getOffset('nt!PsLoadedModuleList') l=pykd.typedVarList(PsLoadedModuleList, 'nt!_LDR_DATA_TABLE_ENTRY', 'InLoadOrderLinks') for i in l: if int(i.InLoadOrderLinks)==PsLoadedModuleList: continue info=DriverInfo() if info.init2(i): driverlist.append(info) except Exception, err: print traceback.format_exc()
def listBugCheckReasonCallback(): try: print '-'*10+'BugCheckReasonCallback'+'-'*10 head=pykd.getOffset('nt!KeBugCheckReasonCallbackListHead') next=head while 1: next=pykd.ptrPtr(next) if next==head: break funcaddr=pykd.ptrPtr(next+g_mwordsize*2) symbolname=pykd.findSymbol(funcaddr) print 'routine:%x %s' % (funcaddr, symbolname) except Exception, err: print traceback.format_exc()
def listSeFileSystem(): try: print '-'*10+'SeFileSystem'+'-'*10 head=pykd.getOffset('nt!SeFileSystemNotifyRoutinesHead') next=head while 1: next=pykd.ptrPtr(next) if not next: break funcaddr=pykd.ptrPtr(next+g_mwordsize) symbolname=pykd.findSymbol(funcaddr) print 'routine:%x %s' % (funcaddr, symbolname) except Exception, err: print traceback.format_exc()
def listIopTimer(): try: print '-'*10+'IopTimer'+'-'*10 head=pykd.getOffset('nt!IopTimerQueueHead') next=head while 1: next=pykd.ptrPtr(next) if next==head: break funcaddr=pykd.ptrPtr(next+g_mwordsize*2) symbolname=pykd.findSymbol(funcaddr) print 'routine:%x %s' % (funcaddr, symbolname) except Exception, err: print traceback.format_exc()
def listDriverByPsLoadedModuleList(): driverlist = [] try: PsLoadedModuleList = pykd.getOffset('nt!PsLoadedModuleList') l = pykd.typedVarList(PsLoadedModuleList, 'nt!_LDR_DATA_TABLE_ENTRY', 'InLoadOrderLinks') for i in l: if int(i.InLoadOrderLinks) == PsLoadedModuleList: continue info = DriverInfo() if info.init2(i): driverlist.append(info) except Exception, err: print traceback.format_exc()
def listPlugPlay(): try: print '-' * 10 + 'PlugPlay' + '-' * 10 table = pykd.getOffset('nt!IopDeviceClassNotifyList') for i in xrange(13): head = table + g_mwordsize * i * 2 next = head while 1: next = pykd.ptrPtr(next) if next == head: break funcaddr = pykd.ptrPtr(next + g_mwordsize * 5) symbolname = pykd.findSymbol(funcaddr) print 'routine:%x %s' % (funcaddr, symbolname) except Exception, err: print traceback.format_exc()
def listPlugPlay(): try: print '-'*10+'PlugPlay'+'-'*10 table=pykd.getOffset('nt!IopDeviceClassNotifyList') for i in xrange(13): head=table+g_mwordsize*i*2 next=head while 1: next=pykd.ptrPtr(next) if next==head: break funcaddr=pykd.ptrPtr(next+g_mwordsize*5) symbolname=pykd.findSymbol(funcaddr) print 'routine:%x %s' % (funcaddr, symbolname) except Exception, err: print traceback.format_exc()
def inspectMsgHook(): msglist=[] try: gSharedInfo=pykd.getOffset('win32k!gSharedInfo') serverinfo=pykd.ptrPtr(gSharedInfo) aheList=pykd.ptrPtr(gSharedInfo+g_mwordsize) if is_2000() or is_xp(): count=pykd.ptrPtr(serverinfo+g_mwordsize*2) else: count=pykd.ptrPtr(serverinfo+g_mwordsize*1) for i in xrange(count): entry=aheList+i*3*g_mwordsize phook=pykd.ptrPtr(entry) #head type=pykd.ptrByte(entry+2*g_mwordsize) if type!=5: continue try: handle=pykd.ptrPtr(phook) msgtype=pykd.ptrPtr(phook+6*g_mwordsize) funcoffset=pykd.ptrPtr(phook+7*g_mwordsize) flags=pykd.ptrPtr(phook+8*g_mwordsize) if flags&1: bGlobal=1 else: bGlobal=0 pti=pykd.ptrPtr(phook+2*g_mwordsize) threadobjectaddr=pykd.ptrPtr(pti) threadobject=pykd.typedVar('nt!_ETHREAD', threadobjectaddr) pid=int(threadobject.Cid.UniqueProcess) tid=(threadobject.Cid.UniqueThread) try: processobject=pykd.typedVar('nt!_EPROCESS', threadobject.ThreadsProcess) except Exception, err: processobject=pykd.typedVar('nt!_EPROCESS', threadobject.Tcb.Process) processpath=pykd.loadUnicodeString(processobject.SeAuditProcessCreationInfo.ImageFileName.Name) msginfo=MsgInfo(handle=handle, pid=pid, tid=tid, msgtype=msgtype, funcoffset=funcoffset, bGlobal=bGlobal, processpath=processpath) msglist.append(msginfo) except Exception, err: print err
def listFsNotifyChange(): try: print '-'*10+'FsNotifyChange'+'-'*10 head=pykd.getOffset('nt!IopFsNotifyChangeQueueHead') next=head while 1: next=pykd.ptrPtr(next) if next==head: break dirverobjectaddr=pykd.ptrPtr(next+g_mwordsize*2) funcaddr=pykd.ptrPtr(next+g_mwordsize*3) try: driverobject=pykd.typedVar('nt!_DRIVER_OBJECT', dirverobjectaddr) drivername=pykd.loadUnicodeString(driverobject.DriverName) except Exception, err: drivername='' symbolname=pykd.findSymbol(funcaddr) print 'routine:%x %s driver:%s' % (funcaddr, symbolname, drivername) except Exception, err: print traceback.format_exc()
def listFsNotifyChange(): try: print '-' * 10 + 'FsNotifyChange' + '-' * 10 head = pykd.getOffset('nt!IopFsNotifyChangeQueueHead') next = head while 1: next = pykd.ptrPtr(next) if next == head: break dirverobjectaddr = pykd.ptrPtr(next + g_mwordsize * 2) funcaddr = pykd.ptrPtr(next + g_mwordsize * 3) try: driverobject = pykd.typedVar('nt!_DRIVER_OBJECT', dirverobjectaddr) drivername = pykd.loadUnicodeString(driverobject.DriverName) except Exception, err: drivername = '' symbolname = pykd.findSymbol(funcaddr) print 'routine:%x %s driver:%s' % (funcaddr, symbolname, drivername) except Exception, err: print traceback.format_exc()
def inspectSSDT(): kernelbase = g_kernelbase KeServiceDescriptorTable = pykd.getOffset('nt!KeServiceDescriptorTable') KiServiceTable = pykd.ptrPtr(KeServiceDescriptorTable) serviceCount = pykd.ptrMWord(KeServiceDescriptorTable + 2 * g_mwordsize) print 'nt!KeServiceDescriptorTable:0x%x' % KeServiceDescriptorTable print 'nt!KiServiceTable:0x%x' % KiServiceTable print 'serviceCount:0x%x(%d)' % (serviceCount, serviceCount) ssdttable = pykd.loadPtrs(KiServiceTable, serviceCount) table_rva = (KiServiceTable - kernelbase) print 'KiServiceTable rva:0x%x' % table_rva filedata = open(g_kernelpath, 'rb').read() pe = pefile.PE(data=filedata, fast_load=True) if pe.DOS_HEADER.e_magic != 0X5A4D or pe.NT_HEADERS.Signature != 0x4550: raise Exception("%s is not a pe file" % filepath) table_fileoffset = pe.get_offset_from_rva(table_rva) print 'KiServiceTable file offset:0x%x' % table_fileoffset d = filedata[table_fileoffset:table_fileoffset + g_mwordsize * serviceCount] number = 0 for i in xrange(serviceCount): source = binascii.b2a_hex(d[i * g_mwordsize:(i + 1) * g_mwordsize][::-1]) source = pykd.addr64(int(source, 16)) - pykd.addr64( pe.OPTIONAL_HEADER.ImageBase) + kernelbase symbolname = pykd.findSymbol(source) current = ssdttable[i] if source == current: print 'source:0x%x current:0x%x %s' % (source, current, symbolname) else: hooksymbolname = pykd.findSymbol(current) print 'source:0x%x %s <-> current:0x%x %s hooked!!!!!!!' % ( source, symbolname, current, hooksymbolname) number += 1 print 'hooked function number:', number
def listShutdown(): try: print '-'*10+'Shutdown'+'-'*10 IRP_MJ_SHUTDOWN=0x10 #define IRP_MJ_SHUTDOWN 0x10 head=pykd.getOffset('nt!IopNotifyShutdownQueueHead') next=head while 1: next=pykd.ptrPtr(next) if next==head: break try: deviceobjectaddr=pykd.ptrPtr(next+g_mwordsize*2) deviceobject=pykd.typedVar('nt!_DEVICE_OBJECT', deviceobjectaddr) driverobject=pykd.typedVar('nt!_DRIVER_OBJECT', int(deviceobject.DriverObject)) funcaddr=pykd.ptrPtr(driverobject.MajorFunction+g_mwordsize*IRP_MJ_SHUTDOWN) symbolname=pykd.findSymbol(funcaddr) print 'routine:%x %s' % (funcaddr, symbolname) except Exception, err: pass except Exception, err: print traceback.format_exc()
def testTypedVarByAddress(self): var5 = pykd.typedVar( pykd.getOffset(target.moduleName, "Namespace3::var5")) self.assertEqual(var5.m_field1, 5)
def getOffset(arg1): return pykd.getOffset(arg1)
def sym_off_to_addr(sym_off): sym_off = sym_off.split("+") if len(sym_off) > 1: return pykd.getOffset(sym_off[0]) + int(sym_off[1], 16) else: return pykd.getOffset(sym_off[0])
def listSocket(): try: r=pykd.dbgCommand('.reload tcpip.sys') if is_2000(): print 'no support' elif is_xp() or is_2003(): AddrObjTable=pykd.getOffset('tcpip!AddrObjTable') AddrObjTable=pykd.ptrPtr(AddrObjTable) AddrObjTableSize=pykd.getOffset('tcpip!AddrObjTableSize') AddrObjTableSize=pykd.ptrPtr(AddrObjTableSize) print '='*20 print 'AddrObjTable:%x AddrObjTableSize:%d' % (AddrObjTable, AddrObjTableSize) if pykd.is64bitSystem(): Next_offset=0 localIP_offset=0x58 #4bytes LocalPort_offset=0x5c#2bytes Protocol_offset=0x5e #2bytes pid_offset=0x238 #4bytes else: if is_xp(): Next_offset=0 localIP_offset=0x2c #4bytes LocalPort_offset=0x30#2bytes Protocol_offset=0x32 #2bytes pid_offset=0x148 #4bytes elif is_2003(): Next_offset=0 localIP_offset=0x30 #4bytes LocalPort_offset=0x34#2bytes Protocol_offset=0x36 #2bytes pid_offset=0x14c #4bytes print 'local remote protocol pid' for i in xrange(AddrObjTableSize): obj=pykd.ptrPtr(AddrObjTable+i*g_mwordsize) while obj!=0: LocalIP=pykd.ptrMWord(obj+localIP_offset) LocalPort=pykd.ptrWord(obj+LocalPort_offset) LocalPort=socket.htons(LocalPort) Protocol=pykd.ptrWord(obj+Protocol_offset) pid=pykd.ptrMWord(obj+pid_offset) Protocol=g_protocols.get(Protocol) print '%16s:%5d *.* %10s %d' % (socket.inet_ntoa(struct.pack('I', LocalIP)), LocalPort, Protocol, pid) obj=pykd.ptrPtr(obj+Next_offset) print '='*20 TCBTable=pykd.getOffset('tcpip!TCBTable') TCBTable=pykd.ptrPtr(TCBTable) MaxHashTableSize=pykd.getOffset('tcpip!MaxHashTableSize') MaxHashTableSize=pykd.ptrPtr(MaxHashTableSize) print 'TCBTable:%x MaxHashTableSize:%d' % (TCBTable, MaxHashTableSize) Next_offset=0 RemoteIP_offset=0x0c#4bytes LocalIP_offset=0x10#4bytes RemotePort_offset=0x14#2bytes LocalPort_offset=0x16 #2bytes pid_offset=0x18 #4bytes print 'local remote protocol pid' for i in xrange(MaxHashTableSize): obj=pykd.ptrPtr(TCBTable+i*g_mwordsize) while obj!=0: RemoteIP=pykd.ptrMWord(obj+RemoteIP_offset) LocalIP=pykd.ptrMWord(obj+LocalIP_offset) RemotePort=pykd.ptrWord(obj+RemotePort_offset) RemotePort=socket.htons(RemotePort) LocalPort=pykd.ptrWord(obj+LocalPort_offset) LocalPort=socket.htons(LocalPort) pid=pykd.ptrMWord(obj+pid_offset) print '%16s:%5d %16s:%5d TCP %d' % (socket.inet_ntoa(struct.pack('I', LocalIP)), LocalPort, socket.inet_ntoa(struct.pack('I', RemoteIP)), RemotePort, pid) obj=pykd.ptrPtr(obj+Next_offset) else: print 'no support' except Exception, err: print err
def testTemplates(self): ti3 = pykd.typeInfo(target.moduleName, "Namespace3::Class3<int>") var5 = pykd.typedVar( ti3, pykd.getOffset(target.moduleName, "Namespace3::var5")) self.assertEqual(var5.m_field1, 5)
#!/usr/bin/env python # -*- coding: utf-8 -* # author: SAI import os,sys,time import traceback import pykd from common import * mmhighestuseraddress=pykd.ptrPtr(pykd.getOffset('nt!MmHighestUserAddress')) class ProcessInfo(object): def init(self, eprocessobj): try: if eprocessobj.ObjectTable<mmhighestuseraddress or eprocessobj.VadRoot<mmhighestuseraddress or eprocessobj.QuotaBlock<mmhighestuseraddress: return False self.eprocessaddr=int(eprocessobj) self.pid=int(eprocessobj.UniqueProcessId) self.parentpid=int(eprocessobj.InheritedFromUniqueProcessId) self.peb=int(eprocessobj.Peb) filepath=pykd.loadUnicodeString(eprocessobj.SeAuditProcessCreationInfo.ImageFileName.Name) filepath=revise_filepath(filepath) name=pykd.loadChars(eprocessobj.ImageFileName, 16) if name.startswith('\x00'): name='' name=name.strip('\x00') self.filepath, self.name=guess_filepath(filepath, name) return True except Exception, err: print traceback.format_exc() return False
def get_address(self, name): return pykd.getOffset(name)
def listSocket(): try: r = pykd.dbgCommand('.reload tcpip.sys') if is_2000(): print 'no support' elif is_xp() or is_2003(): AddrObjTable = pykd.getOffset('tcpip!AddrObjTable') AddrObjTable = pykd.ptrPtr(AddrObjTable) AddrObjTableSize = pykd.getOffset('tcpip!AddrObjTableSize') AddrObjTableSize = pykd.ptrPtr(AddrObjTableSize) print '=' * 20 print 'AddrObjTable:%x AddrObjTableSize:%d' % (AddrObjTable, AddrObjTableSize) if pykd.is64bitSystem(): Next_offset = 0 localIP_offset = 0x58 #4bytes LocalPort_offset = 0x5c #2bytes Protocol_offset = 0x5e #2bytes pid_offset = 0x238 #4bytes else: if is_xp(): Next_offset = 0 localIP_offset = 0x2c #4bytes LocalPort_offset = 0x30 #2bytes Protocol_offset = 0x32 #2bytes pid_offset = 0x148 #4bytes elif is_2003(): Next_offset = 0 localIP_offset = 0x30 #4bytes LocalPort_offset = 0x34 #2bytes Protocol_offset = 0x36 #2bytes pid_offset = 0x14c #4bytes print 'local remote protocol pid' for i in xrange(AddrObjTableSize): obj = pykd.ptrPtr(AddrObjTable + i * g_mwordsize) while obj != 0: LocalIP = pykd.ptrMWord(obj + localIP_offset) LocalPort = pykd.ptrWord(obj + LocalPort_offset) LocalPort = socket.htons(LocalPort) Protocol = pykd.ptrWord(obj + Protocol_offset) pid = pykd.ptrMWord(obj + pid_offset) Protocol = g_protocols.get(Protocol) print '%16s:%5d *.* %10s %d' % (socket.inet_ntoa( struct.pack('I', LocalIP)), LocalPort, Protocol, pid) obj = pykd.ptrPtr(obj + Next_offset) print '=' * 20 TCBTable = pykd.getOffset('tcpip!TCBTable') TCBTable = pykd.ptrPtr(TCBTable) MaxHashTableSize = pykd.getOffset('tcpip!MaxHashTableSize') MaxHashTableSize = pykd.ptrPtr(MaxHashTableSize) print 'TCBTable:%x MaxHashTableSize:%d' % (TCBTable, MaxHashTableSize) Next_offset = 0 RemoteIP_offset = 0x0c #4bytes LocalIP_offset = 0x10 #4bytes RemotePort_offset = 0x14 #2bytes LocalPort_offset = 0x16 #2bytes pid_offset = 0x18 #4bytes print 'local remote protocol pid' for i in xrange(MaxHashTableSize): obj = pykd.ptrPtr(TCBTable + i * g_mwordsize) while obj != 0: RemoteIP = pykd.ptrMWord(obj + RemoteIP_offset) LocalIP = pykd.ptrMWord(obj + LocalIP_offset) RemotePort = pykd.ptrWord(obj + RemotePort_offset) RemotePort = socket.htons(RemotePort) LocalPort = pykd.ptrWord(obj + LocalPort_offset) LocalPort = socket.htons(LocalPort) pid = pykd.ptrMWord(obj + pid_offset) print '%16s:%5d %16s:%5d TCP %d' % ( socket.inet_ntoa(struct.pack('I', LocalIP)), LocalPort, socket.inet_ntoa(struct.pack( 'I', RemoteIP)), RemotePort, pid) obj = pykd.ptrPtr(obj + Next_offset) else: print 'no support' except Exception, err: print err
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) g_currentprocess = pykd.typedVar("nt!_EPROCESS", pykd.getCurrentProcess()) print "current process:%x" % g_currentprocess.getAddress()
def getOffset(funName): return pykd.getOffset(funName)
def __init__(self): addr = pykd.getOffset("ntdll!RtlReAllocateHeap") if addr is None: return self.bp_init = pykd.setBp(addr, self.enter_call_back) self.bp_end = None
#!/usr/bin/env python # -*- coding: utf-8 -* # author: SAI import os, sys, time import traceback import pykd from common import * mmhighestuseraddress = pykd.ptrPtr(pykd.getOffset('nt!MmHighestUserAddress')) def inspectKernelTimer(): try: cmdline = '.reload;' r = pykd.dbgCommand(cmdline) cmdline = r'!timer' r = pykd.dbgCommand(cmdline) r = r.splitlines() start = 0 idx = 0 for i in r: i = i.strip() if i.startswith('List Timer'): start = 1 continue if start != 1: continue data = i.strip() pos = data.find('(DPC @ ') if pos != -1:
def resolve_name(self, name): # return None on fail try: return pykd.getOffset(name) except BaseException: return None