def listProcessByWorkingSetExpansionLinks(sourceprocesslist=[]): processlist={} try: if not sourceprocesslist: sourceprocesslist=listProcessByPsActiveProcessHead() WorkingSetExpansionLinks_list=[] for eproc in sourceprocesslist: eprocessaddr=eproc.eprocessaddr if eprocessaddr not in processlist: #print hex(eprocessaddr) eprocessobj=pykd.typedVar('nt!_EPROCESS', eprocessaddr) WorkingSetExpansionLinks=eprocessobj.Vm.WorkingSetExpansionLinks WorkingSetExpansionLinks=int(WorkingSetExpansionLinks) if WorkingSetExpansionLinks and WorkingSetExpansionLinks not in WorkingSetExpansionLinks_list: WorkingSetExpansionLinks_list.append(WorkingSetExpansionLinks) l=pykd.typedVarList(WorkingSetExpansionLinks, 'nt!_EPROCESS', 'Vm.WorkingSetExpansionLinks') for i in l: if int(i) not in processlist: info=ProcessInfo() if info.init(i): processlist[int(i)]=info except Exception, err: print traceback.format_exc()
def listObjectCallback(): try: cmdline='!object \objecttypes' r=pykd.dbgCommand(cmdline) featurestr='----\n' pos=r.find(featurestr) if pos==-1: return r=r[pos+len(featurestr):].splitlines() for i in r: if i.find('Type'): typeobjectaddr, name=i.split(' Type ') pos=typeobjectaddr.rfind(' ') if pos==-1: return name=name.strip() typeobjectaddr=typeobjectaddr[pos+1:] typeobjectaddr=int(typeobjectaddr, 16) print '-'*20 print 'typeobject "%s":%x' % (name, typeobjectaddr) typeobject=pykd.typedVar('nt!_OBJECT_TYPE', typeobjectaddr) TypeInfo=pykd.typedVar('nt!_OBJECT_TYPE_INITIALIZER', typeobject.TypeInfo) for membername, membervalue in TypeInfo: if membername.endswith('Procedure'): funcaddr=int(membervalue) if funcaddr: symbolname=pykd.findSymbol(funcaddr) else: symbolname='' print '%s %x %s' % (membername, funcaddr, symbolname) except Exception, err: print traceback.format_exc()
def addTableChilds(table, links): table.append(links.getAddress() + sizeof("nt", "_RTL_BALANCED_LINKS")) if links.LeftChild != 0: addTableChilds(table, typedVar("nt", "_RTL_BALANCED_LINKS", links.LeftChild)) if links.RightChild != 0: addTableChilds(table, typedVar("nt", "_RTL_BALANCED_LINKS", links.RightChild))
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 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 testArrayOf(self): arrayType = pykd.typeInfo("UInt8B").arrayOf(5) arrayVar = pykd.typedVar(arrayType, target.module.offset("ulonglongArray")) self.assertEqual(0xFF, arrayVar[1]) self.assertEqual(0xFFFFFFFFFFFFFFFF, arrayVar[4]) arrayStructType = pykd.typeInfo("structTest").arrayOf(2) arrayStructVar = pykd.typedVar(arrayStructType, target.module.offset("g_testArray")) self.assertEqual(True, arrayStructVar[0].m_field2) self.assertEqual(1, arrayStructVar[1].m_field3)
def testCtor( self ): tv = target.module.typedVar( "structTest", target.module.g_structTest ) tv = target.module.typedVar( "g_structTest" ) tv = pykd.typedVar( "structTest", target.module.g_structTest ) tv = pykd.typedVar( target.moduleName + "!structTest", target.module.g_structTest ) structTest = target.module.type( "structTest" ) tv = pykd.typedVar( structTest, target.module.g_structTest ) tv = pykd.typedVar( "g_structTest" ) tv = pykd.typedVar( target.moduleName + "!g_structTest" )
def inspectProcessInlineHook(eprocessaddr=None): if eprocessaddr: eprocessobj=pykd.typedVar('nt!_EPROCESS', eprocessaddr) eprocessinfo=ProcessInfo() if not eprocessinfo.init(eprocessobj): print 'it is not a eprocess' return processlist=[eprocessinfo] else: processlist=listProcessByPsActiveProcessHead() if not processlist: print 'can not get process list' return for eprocessinfo in processlist: print '='*10, 'process:%x pid:%d %s' % (eprocessinfo.eprocessaddr, eprocessinfo.pid, eprocessinfo.filepath), '='*10 modulelist=listModuleByVadRoot(eprocessinfo.eprocessaddr) if not modulelist: print 'the process has no modules(vadroot is null)' continue cmdline='.process /P %x' % eprocessinfo.eprocessaddr r=pykd.dbgCommand(cmdline) for i in modulelist: modulepath=i.filepath modulebase=i.baseaddr if not os.path.exists(modulepath): print "can't find file:%s" % modulepath continue inspectInlineHook(modulepath, modulebase) print print print 'inspect completely'
def listModuleByLdrList(eprocessaddr): modulelist = {} try: cmdline = '.process /P %x;.reload;' % eprocessaddr r = pykd.dbgCommand(cmdline) eprocessobj = pykd.typedVar('nt!_EPROCESS', eprocessaddr) if int(eprocessobj.Peb) != 0: entry = int(eprocessobj.Peb.Ldr.InLoadOrderModuleList) entryList1 = pykd.typedVarList(entry, 'nt!_LDR_DATA_TABLE_ENTRY', 'InLoadOrderLinks') entry = int(eprocessobj.Peb.Ldr.InMemoryOrderModuleList) entryList2 = pykd.typedVarList(entry, 'nt!_LDR_DATA_TABLE_ENTRY', 'InMemoryOrderLinks') entry = int(eprocessobj.Peb.Ldr.InInitializationOrderModuleList) entryList3 = pykd.typedVarList(entry, 'nt!_LDR_DATA_TABLE_ENTRY', 'InInitializationOrderLinks') for entrylist in [entryList1, entryList2, entryList3]: for ldr in entrylist: if int(ldr) not in modulelist: info = ModuleInfo() if info.init1(ldr): modulelist[int(ldr)] = info else: print 'peb is 0' except Exception, err: print traceback.format_exc()
def listProcessBySessionProcessLinks(sourceprocesslist=[]): processlist = {} try: if not sourceprocesslist: sourceprocesslist = listProcessByPsActiveProcessHead() SessionProcessLinks_table = [] for eproc in sourceprocesslist: eprocessaddr = eproc.eprocessaddr if eprocessaddr not in processlist: #print hex(eprocessaddr) eprocessobj = pykd.typedVar('nt!_EPROCESS', eprocessaddr) SessionProcessLinks = eprocessobj.SessionProcessLinks SessionProcessLinks = int(SessionProcessLinks) if SessionProcessLinks and SessionProcessLinks not in SessionProcessLinks_table: SessionProcessLinks_table.append(SessionProcessLinks) l = pykd.typedVarList(SessionProcessLinks, 'nt!_EPROCESS', 'SessionProcessLinks') for i in l: if int(i) not in processlist: info = ProcessInfo() if info.init(i): processlist[int(i)] = info except Exception, err: print traceback.format_exc()
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: endpos=data.find(')', pos) data=data[pos+len('(DPC @ '):endpos] dpc=pykd.addr64(int(data, 16)) if dpc<=int(mmhighestuseraddress): print i, '!!!!!!!!' else: dpcobj=pykd.typedVar('nt!_KDPC', dpc) symbolname=pykd.findSymbol(dpcobj.DeferredRoutine) print '%d dpc:%x timerfunc:%x %s' % (idx, int(dpc), int(dpcobj.DeferredRoutine), symbolname) idx+=1 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 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: endpos = data.find(')', pos) data = data[pos + len('(DPC @ '):endpos] dpc = pykd.addr64(int(data, 16)) if dpc <= int(mmhighestuseraddress): print i, '!!!!!!!!' else: dpcobj = pykd.typedVar('nt!_KDPC', dpc) symbolname = pykd.findSymbol(dpcobj.DeferredRoutine) print '%d dpc:%x timerfunc:%x %s' % ( idx, int(dpc), int(dpcobj.DeferredRoutine), symbolname) idx += 1 except Exception, err: print traceback.format_exc()
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 listProcessByWorkingSetExpansionLinks(sourceprocesslist=[]): processlist = {} try: if not sourceprocesslist: sourceprocesslist = listProcessByPsActiveProcessHead() WorkingSetExpansionLinks_list = [] for eproc in sourceprocesslist: eprocessaddr = eproc.eprocessaddr if eprocessaddr not in processlist: #print hex(eprocessaddr) eprocessobj = pykd.typedVar('nt!_EPROCESS', eprocessaddr) WorkingSetExpansionLinks = eprocessobj.Vm.WorkingSetExpansionLinks WorkingSetExpansionLinks = int(WorkingSetExpansionLinks) if WorkingSetExpansionLinks and WorkingSetExpansionLinks not in WorkingSetExpansionLinks_list: WorkingSetExpansionLinks_list.append( WorkingSetExpansionLinks) l = pykd.typedVarList(WorkingSetExpansionLinks, 'nt!_EPROCESS', 'Vm.WorkingSetExpansionLinks') for i in l: if int(i) not in processlist: info = ProcessInfo() if info.init(i): processlist[int(i)] = info except Exception, err: print traceback.format_exc()
def listProcessBySessionProcessLinks(sourceprocesslist=[]): processlist={} try: if not sourceprocesslist: sourceprocesslist=listProcessByPsActiveProcessHead() SessionProcessLinks_table=[] for eproc in sourceprocesslist: eprocessaddr=eproc.eprocessaddr if eprocessaddr not in processlist: #print hex(eprocessaddr) eprocessobj=pykd.typedVar('nt!_EPROCESS', eprocessaddr) SessionProcessLinks=eprocessobj.SessionProcessLinks SessionProcessLinks=int(SessionProcessLinks) if SessionProcessLinks and SessionProcessLinks not in SessionProcessLinks_table: SessionProcessLinks_table.append(SessionProcessLinks) l=pykd.typedVarList(SessionProcessLinks, 'nt!_EPROCESS', 'SessionProcessLinks') for i in l: if int(i) not in processlist: info=ProcessInfo() if info.init(i): processlist[int(i)]=info except Exception, err: print traceback.format_exc()
def inspectDispatchRoutine(driverobjectaddr=None): try: if driverobjectaddr: driverinfo=DriverInfo() if not driverinfo.init1(driverobjectaddr): print 'fail to get driver info' return driverlist=[driverinfo] else: driverlist=listDriverByDirectoryObject() for driverinfo in driverlist: try: startaddr=driverinfo.baseaddr endaddr=driverinfo.baseaddr+driverinfo.modulesize driverobjectaddr=driverinfo.driverobjectaddr driverobject=pykd.typedVar('nt!_DRIVER_OBJECT', driverobjectaddr) print '='*10, 'drvobj:%x %s' % (driverobjectaddr,driverinfo.filepath),'='*10 for i in xrange(28): funcaddr=pykd.ptrPtr(driverobject.MajorFunction+i*g_mwordsize) symbolname=pykd.findSymbol(funcaddr) if funcaddr<startaddr or funcaddr>=endaddr: if symbolname.find('+')!=-1: print '%d %s %x %s maybe hooked!!!!!' % (i, MajorFunction[i], funcaddr, symbolname) else: print '%d %s %x %s' % (i, MajorFunction[i], funcaddr, symbolname) else: print '%d %s %x %s' % (i, MajorFunction[i], funcaddr, symbolname) except Exception, err: print traceback.format_exc() except Exception, err: print traceback.format_exc()
def testUdtSubscribe(self): tv = pykd.typedVar("g_virtChild") self.assertEqual(5, len(tv)) fieldName, fieldVal = tv[4] self.assertEqual(fieldName, "m_baseField") self.assertEqual(fieldVal, tv.m_baseField) for field in tv: str(field)
def testPtrTo(self): tvBaseType = pykd.typedVar( pykd.typeInfo("UInt8B").ptrTo(), target.module.offset("pbigValue")) self.assertEqual(target.module.typedVar("bigValue"), tvBaseType.deref()) tvDiaStruct = pykd.typedVar( target.module.type("structTest").ptrTo(), target.module.offset("g_structTestPtr")) self.assertEqual(500, tvDiaStruct.deref().m_field1) customStructTest = pykd.createStruct(name="customStructTest", align=4) customStructTest.append("m_field0", pykd.baseTypes.UInt4B) customStructTest.append("m_field1", pykd.baseTypes.UInt8B) tvCustomStruct = pykd.typedVar(customStructTest.ptrTo(), target.module.offset("g_structTestPtr")) self.assertEqual(500, tvCustomStruct.deref().m_field1)
def reloadModules(): global moduleList for m in moduleList: globals()[m.name().lower()] = None if pykd.isKernelDebugging(): global nt nt = pykd.loadModule("nt") modules = pykd.typedVarList(nt.PsLoadedModuleList, "nt", "_LDR_DATA_TABLE_ENTRY", "InLoadOrderLinks") moduleList.append(nt) else: ntdll = pykd.loadModule("ntdll") peb = pykd.typedVar("ntdll", "_PEB", pykd.getCurrentProcess()) ldr = pykd.typedVar("ntdll", "_PEB_LDR_DATA", peb.Ldr) modules = pykd.typedVarList(ldr.InLoadOrderModuleList.getAddress(), "ntdll", "_LDR_DATA_TABLE_ENTRY", "InLoadOrderLinks") moduleList = [] for m in modules: baseName = str(pykd.loadUnicodeString(m.BaseDllName.getAddress())) if baseName == "ntoskrnl.exe": continue module = pykd.findModule(m.DllBase) globals()[module.name().lower()] = module moduleList.append(module)
def testSimpleStruct(self): ti = pykd.typeInfo(target.moduleName, "Type1") self.assertTrue(hasattr(ti, "field1")) self.assertTrue(hasattr(ti, "field2")) self.assertTrue(hasattr(ti, "field3")) tv = pykd.typedVar(ti, target.module.var1) self.assertEqual(tv.field1, -121) self.assertEqual(tv.field2, 220)
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 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 testPtrTo(self): tvBaseType = pykd.typedVar( pykd.typeInfo("UInt8B").ptrTo(), target.module.offset("g_pUlonglongValue")) self.assertEqual(target.module.typedVar("g_ulonglongValue"), tvBaseType.deref()) tvDiaStruct = pykd.typedVar( target.module.type("structTest").ptrTo(), target.module.offset("g_structTestPtr")) self.assertEqual(500, tvDiaStruct.deref().m_field1) customStructTest = pykd.typeBuilder().createStruct( "customStructTest", 4) customStructTest.append("m_field0", pykd.typeInfo("UInt4B")) customStructTest.append("m_field1", pykd.typeInfo("UInt8B")) tvCustomStruct = pykd.typedVar(customStructTest.ptrTo(), target.module.offset("g_structTestPtr")) self.assertEqual(500, tvCustomStruct.deref().m_field1)
def listDriverDevice(driverobjectaddr): try: driverobject = pykd.typedVar('nt!_DRIVER_OBJECT', driverobjectaddr) deviceobject = driverobject.DeviceObject while 1: if not int(deviceobject): break print '%x' % int(deviceobject) deviceobject = deviceobject.NextDevice except Exception, err: print traceback.format_exc()
def listDriverDevice(driverobjectaddr): try: driverobject=pykd.typedVar('nt!_DRIVER_OBJECT', driverobjectaddr) deviceobject=driverobject.DeviceObject while 1: if not int(deviceobject): break print '%x' % int(deviceobject) deviceobject=deviceobject.NextDevice except Exception, err: print traceback.format_exc()
def listThreadByThreadListEntry(eprocessaddr): threadlist=[] try: cmdline='.process /P %x;.reload;' % eprocessaddr r=pykd.dbgCommand(cmdline) eprocessobj=pykd.typedVar('nt!_EPROCESS', eprocessaddr) l=pykd.typedVarList(eprocessobj.ThreadListHead, 'nt!_ETHREAD', 'ThreadListEntry') for i in l: info=ThreadInfo(i) threadlist.append(info) except Exception, err: print traceback.format_exc()
def listThreadByThreadListEntry(eprocessaddr): threadlist = [] try: cmdline = '.process /P %x;.reload;' % eprocessaddr r = pykd.dbgCommand(cmdline) eprocessobj = pykd.typedVar('nt!_EPROCESS', eprocessaddr) l = pykd.typedVarList(eprocessobj.ThreadListHead, 'nt!_ETHREAD', 'ThreadListEntry') for i in l: info = ThreadInfo(i) threadlist.append(info) except Exception, err: print traceback.format_exc()
def listModuleByVadRoot(eprocessaddr): modulelist = [] try: cmdline = '.process /P %x;.reload;' % eprocessaddr r = pykd.dbgCommand(cmdline) eprocess = pykd.typedVar('nt!_EPROCESS', eprocessaddr) VadRoot = int(eprocess.VadRoot) if not VadRoot: return [] cmdline = '!vad %x' % VadRoot r = pykd.dbgCommand(cmdline).splitlines() for i in r: i = i.strip() pos = i.find('Exe EXECUTE_') if pos == -1: continue a = i[pos + len('Exe '):] pos = a.find(' ') if pos == -1: continue type = a[:pos].strip() filepath = a[pos + len(' '):].strip() pos = i.find(')') if pos == -1: continue a = i[pos + 1:].lstrip() pos = a.find(' ') if pos == -1: continue baseaddr = a[:pos].strip() baseaddr = int(baseaddr, 16) * 0x1000 a = a[pos + 1:].lstrip() pos = a.find(' ') if pos == -1: continue endaddr = a[:pos].strip() endaddr = int(endaddr, 16) * 0x1000 info = ModuleInfo() if info.init2(baseaddr=baseaddr, endaddr=endaddr, filepath=filepath): modulelist.append(info) except Exception, err: print traceback.format_exc()
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 inspectProcessHiddenThread(eprocessaddr=None): try: if eprocessaddr: eprocessobj = pykd.typedVar('nt!_EPROCESS', eprocessaddr) eprocessinfo = ProcessInfo() if not eprocessinfo.init(eprocessobj): print 'it is not a eprocess' return processlist = [eprocessinfo] else: processlist = listProcessByPsActiveProcessHead() if not processlist: print 'can not get process list' return funclist = [ listThreadByTcbThreadListEntry, listThreadByThreadListEntry ] for eprocessinfo in processlist: try: eprocessaddr = eprocessinfo.eprocessaddr print '=' * 10, 'process:%x pid:%d %s' % ( eprocessaddr, eprocessinfo.pid, eprocessinfo.filepath), '=' * 10 threadlist = {} for func in funclist: try: l = func(eprocessaddr) except Exception, err: l = [] print err for info in l: if info.ethreadaddr not in threadlist: threadlist[info.ethreadaddr] = info hooknumber = 0 for info in threadlist.values(): symbolname = pykd.findSymbol(info.entrypoint) if symbolname.find('!') == -1: print 'ethread:%x tid:%d entry:%x' % ( info.ethreadaddr, info.tid, info.entrypoint) hooknumber += 1 if hooknumber == 0: print 'no hidden thread' except Exception, err: print traceback.format_exc()
def listModuleByVadRoot(eprocessaddr): modulelist = [] try: cmdline = ".process /P %x;.reload;" % eprocessaddr r = pykd.dbgCommand(cmdline) eprocess = pykd.typedVar("nt!_EPROCESS", eprocessaddr) VadRoot = int(eprocess.VadRoot) if not VadRoot: return [] cmdline = "!vad %x" % VadRoot r = pykd.dbgCommand(cmdline).splitlines() for i in r: i = i.strip() pos = i.find("Exe EXECUTE_") if pos == -1: continue a = i[pos + len("Exe ") :] pos = a.find(" ") if pos == -1: continue type = a[:pos].strip() filepath = a[pos + len(" ") :].strip() pos = i.find(")") if pos == -1: continue a = i[pos + 1 :].lstrip() pos = a.find(" ") if pos == -1: continue baseaddr = a[:pos].strip() baseaddr = int(baseaddr, 16) * 0x1000 a = a[pos + 1 :].lstrip() pos = a.find(" ") if pos == -1: continue endaddr = a[:pos].strip() endaddr = int(endaddr, 16) * 0x1000 info = ModuleInfo() if info.init2(baseaddr=baseaddr, endaddr=endaddr, filepath=filepath): modulelist.append(info) except Exception, err: print traceback.format_exc()
def init2(self, ldr): try: if not int(ldr): return False DriverSection=pykd.typedVar('nt!_LDR_DATA_TABLE_ENTRY', ldr) self.driverobjectaddr=0 filepath=revise_filepath(pykd.loadUnicodeString(DriverSection.FullDllName)) name=pykd.loadUnicodeString(DriverSection.BaseDllName) self.filepath, self.name=guess_filepath(filepath, name) self.baseaddr=int(DriverSection.DllBase) self.modulesize=int(DriverSection.SizeOfImage) self.entrypoint=int(DriverSection.EntryPoint) return True except Exception, err: print traceback.format_exc() return False
def listProcessByPspcidTable(): processlist = [] try: cmdline = '!process 0 0' r = pykd.dbgCommand(cmdline) r = r.splitlines() for i in r: if i.startswith('PROCESS '): startpos = len('PROCESS ') endpos = i.find(' ', startpos) eprocessaddr = int(i[startpos:endpos], 16) eprocessobj = pykd.typedVar('nt!_EPROCESS', eprocessaddr) info = ProcessInfo() if info.init(eprocessobj): processlist.append(info) except Exception, err: print traceback.format_exc()
def listProcessByPspcidTable(): processlist=[] try: cmdline='!process 0 0' r=pykd.dbgCommand(cmdline) r=r.splitlines() for i in r: if i.startswith('PROCESS '): startpos=len('PROCESS ') endpos=i.find(' ', startpos) eprocessaddr=int(i[startpos:endpos], 16) eprocessobj=pykd.typedVar('nt!_EPROCESS', eprocessaddr) info=ProcessInfo() if info.init(eprocessobj): processlist.append(info) except Exception, err: print traceback.format_exc()
def inspectProcessHiddenThread(eprocessaddr=None): try: if eprocessaddr: eprocessobj=pykd.typedVar('nt!_EPROCESS', eprocessaddr) eprocessinfo=ProcessInfo() if not eprocessinfo.init(eprocessobj): print 'it is not a eprocess' return processlist=[eprocessinfo] else: processlist=listProcessByPsActiveProcessHead() if not processlist: print 'can not get process list' return funclist=[listThreadByTcbThreadListEntry, listThreadByThreadListEntry] for eprocessinfo in processlist: try: eprocessaddr=eprocessinfo.eprocessaddr print '='*10, 'process:%x pid:%d %s' % (eprocessaddr, eprocessinfo.pid, eprocessinfo.filepath), '='*10 threadlist={} for func in funclist: try: l=func(eprocessaddr) except Exception, err: l=[] print err for info in l: if info.ethreadaddr not in threadlist: threadlist[info.ethreadaddr]=info hooknumber=0 for info in threadlist.values(): symbolname=pykd.findSymbol(info.entrypoint) if symbolname.find('!')==-1: print 'ethread:%x tid:%d entry:%x' % (info.ethreadaddr, info.tid, info.entrypoint) hooknumber+=1 if hooknumber==0: print 'no hidden thread' except Exception, err: print traceback.format_exc()
def init1(self, driverobjectaddr): try: driverobject=pykd.typedVar('nt!_DRIVER_OBJECT', driverobjectaddr) ldr=int(driverobject.DriverSection) if self.init2(ldr): self.driverobjectaddr=int(driverobject) return True self.driverobjectaddr=int(driverobject) filepath=revise_filepath(pykd.loadUnicodeString(driverobject.DriverName)) self.filepath, self.name=guess_filepath(filepath) self.baseaddr=int(driverobject.DriverStart) self.modulesize=int(driverobject.DriverSize) self.entrypoint=0 return True except Exception, err: print traceback.format_exc() return False
def list_callback(obj, type, driverlist): try: if type=='Driver': driverobjectaddr=int(obj, 16) elif type=='Device': deviceobjectaddr=int(obj, 16) deviceobject=pykd.typedVar('nt!_DEVICE_OBJECT', deviceobjectaddr) driverobjectaddr=int(deviceobject.DriverObject) else: return True if driverobjectaddr not in driverlist: info=DriverInfo() if info.init1(driverobjectaddr): driverlist[driverobjectaddr]=info else: pass except Exception, err: print traceback.format_exc()
def init2(self, ldr): try: if not int(ldr): return False DriverSection = pykd.typedVar('nt!_LDR_DATA_TABLE_ENTRY', ldr) self.driverobjectaddr = 0 filepath = revise_filepath( pykd.loadUnicodeString(DriverSection.FullDllName)) name = pykd.loadUnicodeString(DriverSection.BaseDllName) self.filepath, self.name = guess_filepath(filepath, name) self.baseaddr = int(DriverSection.DllBase) self.modulesize = int(DriverSection.SizeOfImage) self.entrypoint = int(DriverSection.EntryPoint) return True except Exception, err: print traceback.format_exc() return False
def init1(self, driverobjectaddr): try: driverobject = pykd.typedVar('nt!_DRIVER_OBJECT', driverobjectaddr) ldr = int(driverobject.DriverSection) if self.init2(ldr): self.driverobjectaddr = int(driverobject) return True self.driverobjectaddr = int(driverobject) filepath = revise_filepath( pykd.loadUnicodeString(driverobject.DriverName)) self.filepath, self.name = guess_filepath(filepath) self.baseaddr = int(driverobject.DriverStart) self.modulesize = int(driverobject.DriverSize) self.entrypoint = 0 return True except Exception, err: print traceback.format_exc() return False
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 list_callback(obj, type, driverlist): try: if type == 'Driver': driverobjectaddr = int(obj, 16) elif type == 'Device': deviceobjectaddr = int(obj, 16) deviceobject = pykd.typedVar('nt!_DEVICE_OBJECT', deviceobjectaddr) driverobjectaddr = int(deviceobject.DriverObject) else: return True if driverobjectaddr not in driverlist: info = DriverInfo() if info.init1(driverobjectaddr): driverlist[driverobjectaddr] = info else: pass except Exception, err: print traceback.format_exc()
def inspectDispatchRoutine(driverobjectaddr=None): try: if driverobjectaddr: driverinfo = DriverInfo() if not driverinfo.init1(driverobjectaddr): print 'fail to get driver info' return driverlist = [driverinfo] else: driverlist = listDriverByDirectoryObject() for driverinfo in driverlist: try: startaddr = driverinfo.baseaddr endaddr = driverinfo.baseaddr + driverinfo.modulesize driverobjectaddr = driverinfo.driverobjectaddr driverobject = pykd.typedVar('nt!_DRIVER_OBJECT', driverobjectaddr) print '=' * 10, 'drvobj:%x %s' % ( driverobjectaddr, driverinfo.filepath), '=' * 10 for i in xrange(28): funcaddr = pykd.ptrPtr(driverobject.MajorFunction + i * g_mwordsize) symbolname = pykd.findSymbol(funcaddr) if funcaddr < startaddr or funcaddr >= endaddr: if symbolname.find('+') != -1: print '%d %s %x %s maybe hooked!!!!!' % ( i, MajorFunction[i], funcaddr, symbolname) else: print '%d %s %x %s' % (i, MajorFunction[i], funcaddr, symbolname) else: print '%d %s %x %s' % (i, MajorFunction[i], funcaddr, symbolname) except Exception, err: print traceback.format_exc() 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 inspectProcessInlineHook(eprocessaddr=None): if eprocessaddr: eprocessobj = pykd.typedVar('nt!_EPROCESS', eprocessaddr) eprocessinfo = ProcessInfo() if not eprocessinfo.init(eprocessobj): print 'it is not a eprocess' return processlist = [eprocessinfo] else: processlist = listProcessByPsActiveProcessHead() if not processlist: print 'can not get process list' return for eprocessinfo in processlist: print '=' * 10, 'process:%x pid:%d %s' % ( eprocessinfo.eprocessaddr, eprocessinfo.pid, eprocessinfo.filepath), '=' * 10 modulelist = listModuleByVadRoot(eprocessinfo.eprocessaddr) if not modulelist: print 'the process has no modules(vadroot is null)' continue cmdline = '.process /P %x' % eprocessinfo.eprocessaddr r = pykd.dbgCommand(cmdline) for i in modulelist: modulepath = i.filepath modulebase = i.baseaddr if not os.path.exists(modulepath): print "can't find file:%s" % modulepath continue inspectInlineHook(modulepath, modulebase) print print print 'inspect completely'
def listModuleByLdrList(eprocessaddr): modulelist = {} try: cmdline = ".process /P %x;.reload;" % eprocessaddr r = pykd.dbgCommand(cmdline) eprocessobj = pykd.typedVar("nt!_EPROCESS", eprocessaddr) if int(eprocessobj.Peb) != 0: entry = int(eprocessobj.Peb.Ldr.InLoadOrderModuleList) entryList1 = pykd.typedVarList(entry, "nt!_LDR_DATA_TABLE_ENTRY", "InLoadOrderLinks") entry = int(eprocessobj.Peb.Ldr.InMemoryOrderModuleList) entryList2 = pykd.typedVarList(entry, "nt!_LDR_DATA_TABLE_ENTRY", "InMemoryOrderLinks") entry = int(eprocessobj.Peb.Ldr.InInitializationOrderModuleList) entryList3 = pykd.typedVarList(entry, "nt!_LDR_DATA_TABLE_ENTRY", "InInitializationOrderLinks") for entrylist in [entryList1, entryList2, entryList3]: for ldr in entrylist: if int(ldr) not in modulelist: info = ModuleInfo() if info.init1(ldr): modulelist[int(ldr)] = info else: print "peb is 0" except Exception, err: print traceback.format_exc()
def inspectProcessIatEatHook(eprocessaddr=None): if eprocessaddr: eprocessobj=pykd.typedVar('nt!_EPROCESS', eprocessaddr) eprocessinfo=ProcessInfo() if not eprocessinfo.init(eprocessobj): print 'it is not a eprocess' return processlist=[eprocessinfo] else: processlist=listProcessByPsActiveProcessHead() if not processlist: print 'can not get process list' return for eprocessinfo in processlist: print '='*10, 'process:%x pid:%d %s' % (eprocessinfo.eprocessaddr, eprocessinfo.pid, eprocessinfo.filepath), '='*10 modulelist=listModuleByVadRoot(eprocessinfo.eprocessaddr) if not modulelist: print 'the process has no modules(vadroot is null)' else: inspectIatEatHook(modulelist, eprocessinfo.eprocessaddr) print print 'inspect completely'
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 getAVLTable( addr ): table = [] avl = typedVar( "nt!_RTL_AVL_TABLE", addr ) addTableChilds( table, avl.BalancedRoot ) return table
def inspectProcessHiddenModule(eprocessaddr=None): try: if eprocessaddr: eprocessobj = pykd.typedVar("nt!_EPROCESS", eprocessaddr) eprocessinfo = ProcessInfo() if not eprocessinfo.init(eprocessobj): print "it is not a eprocess" return processlist = [eprocessinfo] else: processlist = listProcessByPsActiveProcessHead() if not processlist: print "can not get process list" return funclist = [listModuleByLdrList, listModuleByLdrHash] for eprocessinfo in processlist: try: eprocessaddr = eprocessinfo.eprocessaddr print "=" * 10, "process:%x pid:%d %s" % ( eprocessaddr, eprocessinfo.pid, eprocessinfo.filepath, ), "=" * 10 sourcemodulelist = listModuleByVadRoot(eprocessaddr) if not sourcemodulelist: print "fail to get vad!!!!!" continue hooknumber = 0 for func in funclist: modulelist = func(eprocessaddr) # print len(modulelist) modulelist2 = {} for i in modulelist: modulelist2[i.baseaddr] = i l = [] for i in sourcemodulelist: if i.baseaddr not in modulelist2: l.append(i) else: modulelist2.pop(i.baseaddr) if l: print "!" * 5, "following modules can not be found by %s" % func.func_name for i in l: print "base:%x size:%x entry:%x %s %s" % ( i.baseaddr, i.size, i.entrypoint, i.name, i.filepath, ) hooknumber += 1 if modulelist2: print "!" * 5, "following modules can be only found by %s" % func.func_name for i in modulelist2.values(): print "base:%x size:%x entry:%x %s %s" % ( i.baseaddr, i.size, i.entrypoint, i.name, i.filepath, ) hooknumber += 1 if hooknumber == 0: print "no hidden dll" except Exception, err: print traceback.format_exc() print print "inspect completely"