def My_freadEnd(self): numBytesRead = idc.GetRegValue("EAX") self.logger.info("_fread read %d bytes." % (numBytesRead)) pBuffer = self.tempStack.pop(0) pSize = self.tempStack.pop(0) stream = self.tempStack.pop(0) callerAddr = self.tempStack.pop(0) callerFuncName = self.tempStack.pop(0) threadID = self.tempStack.pop(0) _buffer = idaapi.dbg_read_memory(pBuffer, pSize) self.logger.debug(_buffer) inputLoggingList = [] inputLoggingList.append(pBuffer) inputLoggingList.append(pSize) inputLoggingList.append(_buffer) inputLoggingList.append(stream) inputLoggingList.append(callerAddr) inputLoggingList.append(callerFuncName) inputLoggingList.append(threadID) if numBytesRead > 0: self.logger.info("_fread succeeded.") self.debuggerInstance.callbackProcessing(inputLoggingList) else: Print("_fread failed.") self.logger.info("_fread failed.") return 0
def XXXXXXXXXXXXXXXsignalClient(self, norev=False): start_eip = idc.GetRegValue(self.PC) if not norev: simicsString = gdbProt.Evalx('SendGDBMonitor("@cgc.rev1()");') eip = gdbProt.getEIPWhenStopped() if eip is None or not (type(eip) is int or type(eip) is long): print('signalClient got wrong stuff? %s from getEIP' % str(eip)) return #print('signalClient eip was at 0x%x, then after rev 1 0x%x call setAndDisable string is %s' % (start_eip, eip, simicsString)) idaapi.step_into() idc.GetDebuggerEvent(idc.WFNE_SUSP, -1) new_eip = idc.GetRegValue(self.PC) #print('signalClient back from cont new_eip is 0x%x' % new_eip) if new_eip >= self.kernel_base: print('in kernel, run to user') self.updateStackTrace()
def doStepOver(self): #print('in doStepOver') idaapi.step_over() idc.GetDebuggerEvent(idc.WFNE_SUSP, -1) cur_addr = idc.GetRegValue(self.PC) if cur_addr > self.kernel_base: self.runToUserSpace()
def wroteToRegister(self): highlighted = idaapi.get_highlighted_identifier() ''' if highlighted is None or highlighted not in self.reg_list: print('%s not in reg list' % highlighted) c=idaapi.Choose([], "Run backward until selected register modified", 1) c.width=50 c.list = self.reg_list chose = c.choose() if chose == 0: print('user canceled') return else: highlighted = self.reg_list[chose-1] ''' print 'Looking for a write to %s...' % highlighted command = "@cgc.revToModReg('%s')" % highlighted simicsString = gdbProt.Evalx('SendGDBMonitor("%s");' % command) eip = None if self.checkNoRev(simicsString): eip = gdbProt.getEIPWhenStopped() self.signalClient() else: return curAddr = idc.GetRegValue(self.PC) print('Current instruction (0x%x) wrote to reg %s' % (curAddr, highlighted)) return eip
def trackRegister(self): highlighted = idaapi.get_highlighted_identifier() if highlighted is None or highlighted not in self.reg_list: print('%s not in reg list' % highlighted) c = Choose([], "back track to source of selected register", 1) c.width = 50 c.list = self.reg_list chose = c.choose() if chose == 0: print('user canceled') return else: highlighted = self.reg_list[chose - 1] print 'backtrack to source of to %s...' % highlighted command = "@cgc.revTaintReg('%s')" % highlighted simicsString = gdbProt.Evalx('SendGDBMonitor("%s");' % command) eip = gdbProt.getEIPWhenStopped(2) #gdbProt.stepWait() self.signalClient() curAddr = idc.GetRegValue(self.PC) print( 'Current instruction (0x%x) is as far back as we can trace reg %s' % (curAddr, highlighted)) self.showSimicsMessage() bookmark_list = self.bookmark_view.updateBookmarkView() return eip
def revBlock(self): cur_addr = idc.GetRegValue(self.PC) f = idaapi.get_func(cur_addr) if f is None: print( 'Ida analysis sees no function, cannot perform this function') return fc = idaapi.FlowChart(f) block_start = None prev_addr = None prev_block = None for block in fc: block_start = block.startEA #print('block_start 0x%x, cur_addr is 0x%x' % (block_start, cur_addr)) if block_start > cur_addr: break prev_addr = block_start prev_block = block if prev_addr == cur_addr: self.doRevStepInto() elif prev_addr is not None: next_addr = idc.NextHead(prev_addr) if next_addr == cur_addr: ''' reverse two to get there? ''' print('revBlock rev two?') self.doRevStepInto() self.doRevStepInto() else: print('revBlock rev to 0x%x' % prev_addr) self.doRevToAddr(prev_addr, extra_back=0) else: print('must have been top, uncall') self.doRevFinish()
def doReverse(self, extra_back=None): print 'in doReverse' curAddr = idc.GetRegValue(self.PC) #goNowhere() #print('doReverse, back from goNowhere curAddr is %x' % curAddr) isBpt = idc.CheckBpt(curAddr) # if currently at a breakpoint, we need to back an instruction to so we don't break # here if isBpt > 0: print 'curAddr is %x, it is a breakpoint, do a rev step over' % curAddr addr = self.doRevStepOver() if addr is None: return None print 'in doReverse, did RevStepOver got addr of %x' % addr isBpt = idc.CheckBpt(addr) if isBpt > 0: # back up onto a breakpoint, we are done print('doReverse backed to breakpoint, we are done') return addr #print 'do reverse' param = '' if extra_back is not None: param = extra_back command = '@cgc.doReverse(%s)' % param simicsString = gdbProt.Evalx('SendGDBMonitor("%s");' % command) addr = None if self.checkNoRev(simicsString): addr = gdbProt.getEIPWhenStopped() self.signalClient() return addr
def readValue(self): if self.value != None: return self.value operandType = self.parser.getOperandType() regName = self.parser.getRegName() regValue = idc.GetRegValue(regName) if regName != None else None if operandType == OperandType.Value64OfRegisterPlusOffset: self.value = idc.Qword(regValue + self.opValue) elif operandType == OperandType.Value32OfRegisterPlusOffset: self.value = idc.Dword(regValue + self.opValue) elif operandType == OperandType.Value16OfRegisterPlusOffset: self.value = idc.Word(regValue + self.opValue) elif operandType == OperandType.Value8OfRegisterPlusOffset: self.value = idc.Byte(regValue + self.opValue) elif (operandType == OperandType.Register64) or (operandType == OperandType.Register32): self.value = regValue elif (operandType == OperandType.Register16) or (operandType == OperandType.Register8): self.value = regValue elif operandType == OperandType.ImmediateUnkown: self.value = self.opValue else: raise Exception("Unknown operand type") return self.value
def MyCreateFileAEnd(self): """ Monitors the end of CreateFileA function """ handle = idc.GetRegValue("EAX") self.logger.info("MyCreateFileAEnd HANDLE is 0x%x" % handle) return 0
def colorize_register(self, reg): result = '' reduced = False reg_val = idc.GetRegValue(reg) label, changed = self.get_reg_label(reg, reg_val) chain = self.get_ptr_chain(reg_val) result += label + self.colorize_value(chain[0]) if reg == dbg.registers.flagsr: return result, changed elif reg != dbg.registers.pc: vals = chain[1:] if len(vals) > config.max_deref_levels: vals = vals[:config.max_deref_levels] reduced = True result += ''.join([self.as_ptr(value) for value in vals]) if reduced: result += self.as_arrow_string("[...]") result += self.get_value_info(chain[-1]) if chain.limit_exceeded: result += self.as_arrow_string("[...]") return result, changed
def IDA_State(): if get_root_filename() is None: return 'empty' try: a = idc.GetRegValue('esp') return 'running' except: return 'static'
def set_reg(self): for i in self.reg_list: if 'arg' not in i: self.reg[i] = idc.GetRegValue(i) self.reg['arg1'] = self.get_stack_arg(1) self.reg['arg2'] = self.get_stack_arg(2) self.reg['arg3'] = self.get_stack_arg(3) self.reg['arg4'] = self.get_stack_arg(4)
def get_local_var_value_64(loc_var_name): frame = ida_frame.get_frame(idc.here()) loc_var = ida_struct.get_member_by_name(frame, loc_var_name) loc_var_start = loc_var.soff loc_var_ea = loc_var_start + idc.GetRegValue("RSP") loc_var_value = idc.read_dbg_qword( loc_var_ea ) # in case the variable is 32bit, just use get_wide_dword() instead return loc_var_value
def getfpu_tags(name): assert (name == 'fptag') re = 0 tag = idc.GetRegValue('TAGS') for i in range(8): f = (0 if ((tag >> (2 * i)) & 0b11) else 1) << (8 * i) re = (re) | f return re
def init_segm_mem(self): segment = {} gdt = gdt32(GDT_MAP_ADDR) fs_idx = idc.GetRegValue('fs') gs_idx = idc.GetRegValue('gs') fs_addr = idaapi.dbg_get_thread_sreg_base(idc.GetCurrentThreadId(), int(cpu.fs)) gs_addr = idaapi.dbg_get_thread_sreg_base(idc.GetCurrentThreadId(), int(cpu.gs)) G = 1 D = 0 L = 1 AVL = 0 gdt.addSegDiscription(fs_idx, fs_addr, 0x1000, 1, 0, 0, (G << 3) | (D << 2) | (L << 1) | AVL) gdt.addSegDiscription(gs_idx, gs_addr, 0x1000, 1, 0, 0, (G << 3) | (D << 2) | (L << 1) | AVL) return gdt.get_gdt()
def Regs_method(self): X86_EFLAGS_CF = 1 << 0 X86_EFLAGS_FIXED = 1 << 1 X86_EFLAGS_PF = 1 << 2 X86_EFLAGS_AF = 1 << 4 X86_EFLAGS_ZF = 1 << 6 X86_EFLAGS_SF = 1 << 7 X86_EFLAGS_TF = 1 << 8 X86_EFLAGS_IF = 1 << 9 X86_EFLAGS_DF = 1 << 10 X86_EFLAGS_OF = 1 << 11 X86_EFLAGS_IOPL = 1 << 12 X86_EFLAGS_IOPL_MASK = 3 << 12 X86_EFLAGS_NT = 1 << 14 X86_EFLAGS_RF = 1 << 16 X86_EFLAGS_VM = 1 << 17 X86_EFLAGS_AC = 1 << 18 X86_EFLAGS_VIF = 1 << 19 X86_EFLAGS_VIP = 1 << 20 X86_EFLAGS_ID = 1 << 21 getF64 = lambda x: get_fpu_regs("ST%d" % (7 - int(x[2:])))[1] method = { 'mm0': getF64, 'mm1': getF64, 'mm2': getF64, 'mm3': getF64, 'mm4': getF64, 'mm5': getF64, 'mm6': getF64, 'mm7': getF64, 'xmm0': get_xmm, 'xmm1': get_xmm, 'xmm2': get_xmm, 'xmm3': get_xmm, 'xmm4': get_xmm, 'xmm5': get_xmm, 'xmm6': get_xmm, 'xmm7': get_xmm, 'xmm8': get_xmm, 'xmm9': get_xmm, 'xmm10': get_xmm, 'xmm11': get_xmm, 'xmm12': get_xmm, 'xmm13': get_xmm, 'xmm14': get_xmm, 'xmm15': get_xmm, 'd': lambda name: 0xffffffff if idc.GetRegValue("DF") else 0x1, 'gdt': lambda name: GDT_MAP_ADDR, 'fpround': getfpround, 'sseround': getSseRound, 'ftop': getftop, 'fptag': getfpu_tags } return method
def My_fopenEnd(self): """ Not need to call this function here since fopen already contains the handle """ stream = idc.GetRegValue("EAX") self.logger.info("HANDLE is 0x%x" % stream) self.handleSet.add(stream) return 0
def My_fclose(self): """ int fclose ( FILE * stream ); """ stream = Util.GetData(0x4) self.logger.info("stream is 0x%x" % (stream)) retVal = idc.GetRegValue("EAX") return 0
def doStepOver(self): #print('in doStepOver') idaapi.step_over() #print('back from step over') idc.GetDebuggerEvent(idc.WFNE_SUSP, -1) #print('back getDebuggerEvent') cur_addr = idc.GetRegValue(self.PC) #print('cur_addr is 0x%x' % cur_addr) if cur_addr > self.kernel_base: print('run to user space') self.runToUserSpace()
def doRevToCursor(self): cursor = idc.ScreenEA() curAddr = idc.GetRegValue(self.PC) if cursor == curAddr: print 'attempt to go back to where you are ignored' return #doRevToAddr(cursor) command = '@cgc.revToAddr(0x%x, extra_back=%d)' % (cursor, 0) simicsString = gdbProt.Evalx('SendGDBMonitor("%s");' % command) eip = gdbProt.getEIPWhenStopped() self.signalClient()
def ReadFile(self): """ Monitors the the beginning of ReadFile function ReadFile arguments are read from the stack This is the function that will trigger the trace inputLoggingList holds arguments for """ """ BOOL WINAPI ReadFile( _In_ HANDLE hFile, _Out_ LPVOID lpBuffer, _In_ DWORD nNumberOfBytesToRead, _Out_opt_ LPDWORD lpNumberOfBytesRead, _Inout_opt_ LPOVERLAPPED lpOverlapped ); """ hFile = Util.GetData(0x0) self.logger.info("hFile is 0x%x" % (hFile)) lpBuffer = Util.GetData(0x4) self.logger.info("lpBuffer is 0x%x" % (lpBuffer)) nNumberOfBytesToRead = Util.GetData(0x8) self.logger.info("nNumberOfBytesToRead value is 0x%x" % (nNumberOfBytesToRead)) lpNumberOfBytesRead = Util.GetData(0xC) self.logger.info("lpNumberOfBytesRead value is 0x%x" % (lpNumberOfBytesRead)) lpOverlapped = Util.GetData(0x10) self.logger.info("lpOverlapped is 0x%x" % (lpOverlapped)) ea = idc.GetRegValue("EIP") retAddr = ea + idc.ItemSize(ea) Print("The return address is 0x%x" % retAddr) self.tempStack = [] self.tempStack.append(lpBuffer) self.tempStack.append(lpNumberOfBytesRead) self.tempStack.append(hFile) self.tempStack.append(ea) self.tempStack.append("ReadFile") self.tempStack.append(idc.GetCurrentThreadId()) idc.AddBpt(retAddr) idc.SetBptCnd(retAddr, "interactivemodeCallback.ReadFileEnd()") return 0
def GetData(index): """ Gets the data of the stack @param path: index of where to pull from @return: the address of the stack """ import idc esp = idc.GetRegValue("ESP") return idc.DbgDword(esp + index)
def beginAnalysis(self): if (self.rangeStart == 0) or (self.rangeEnd == 0): activeFuncScopeAddr = idc.ScreenEA() self.rangeStart = activeFuncScopeAddr self.rangeEnd = GetFuncEndAddr(activeFuncScopeAddr) # begin automatic debugging while idc.GetRegValue(x64Regs.RIP.value) != self.rangeEnd: idaapi.step_into() idc.GetDebuggerEvent(idc.WFNE_SUSP, -1) self.analyseStep()
def parseVar(self, obj, hs): vr = self.func.lvars[obj.v.idx] hs['name'] = vr.name hs['var'] = vr if obj.ea != idc.BADADDR: hs['val'] = obj.ea try: if vr.is_reg_var(): regid = vr.get_regnum() / 8 regname = self.REGS[regid] hs['reg'] = [vr.get_regnum(), regname] hs['val'] = idc.GetRegValue(regname) if vr.is_stk_var(): ofs = vr.location.calc_offset() hs['ofs'] = ofs val = idc.Qword(idc.GetRegValue('rsp') + ofs) if val != idc.BADADDR: hs['val'] = val except Exception: pass return hs
def scanRegisters(manual = False): messagePrefix = "Manual scan" if manual else "Scan" scanInitiatedMessage = messagePrefix + " initiated." print(scanInitiatedMessage) print("----------------------------------------------------") for reg in x64RegCommonList: scan_register(reg) print("----------------------------------------------------") ripValue = idc.GetRegValue(x64Regs.RIP.value) scanCompleteMessage = (messagePrefix + " completed at RIP=0x{:X}").format(ripValue) print(scanCompleteMessage)
def activate(self, ctx): highlighted = idaapi.get_highlighted_identifier() current = idc.GetRegValue(highlighted) default = '%x' % current print('default %s' % default) #prompt = 'Value to write to %s (in hex, no prefix)' % highlighted #print('prompt is %s' % prompt) #enc = prompt.encode('utf-8') value = idc.AskStr(default, 'reg value ?') if value is None: return reg_param = "'%s'" % highlighted simicsString = gdbProt.Evalx('SendGDBMonitor("@cgc.writeRegValue(%s, 0x%s)");' % (reg_param, value))
def MyCreateFileWEnd(self): """ Monitors the end of CreateFileW function The return value (handle to the file) for CreateFileW is stored in a set """ Print("Returning from CreateFileW...") handle = idc.GetRegValue("EAX") self.handleSet.add(handle) self.logger.info("HANDLE is 0x%x" % handle) return 0
def doRevFinish(self): #print 'doRevFinish' #doRevCommand('uncall-function') cur_addr = idc.GetRegValue(self.PC) f = idc.GetFunctionAttr(cur_addr, idc.FUNCATTR_START) if f != idaapi.BADADDR: print('doRevFinish got function start at 0x%x, go there, and further back 1' % f) self.doRevToAddr(f, extra_back=1) else: print('use monitor uncall function') simicsString = gdbProt.Evalx('SendGDBMonitor("@cgc.uncall()");') eip = gdbProt.getEIPWhenStopped() self.signalClient()
def wroteToAddress(self, target_addr): disabledSet = bpUtils.disableAllBpts(None) command = '@cgc.stopAtKernelWrite(0x%x)' % target_addr simicsString = gdbProt.Evalx('SendGDBMonitor("%s");' % command) eip = gdbProt.getEIPWhenStopped() #gdbProt.stepWait() self.signalClient() bpUtils.enableBpts(disabledSet) if eip >= self.kernel_base: print('previous syscall wrote to address 0x%x' % target_addr) else: curAddr = idc.GetRegValue(self.PC) #print('Current instruction (0x%x) wrote to 0x%x' % (curAddr, target_addr)) print('Previous instruction wrote to 0x%x' % (target_addr))
def checkBindEnd(self): retVal = idc.GetRegValue("EAX") if retVal == 0: self.logger.info("checkBindEnd: Bind succeeded.") socket = self.tempStack.pop(0) port = self.tempStack.pop(0) self.logger.info("checkBindEnd: The port is %s." % port) self.socket_dict[socket] = port else: self.logger.info("checkBindEnd: Bind failed.") return 0