Python idc.GetOperandValue() Examples

The following are 14 code examples of idc.GetOperandValue(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module idc , or try the search function .
Example #1
Source File: configuration_file.py    From idasec with GNU Lesser General Public License v2.1 6 votes vote down vote up
def create_call_map(self, ftype):
        assert_ida_available()
        import idc
        import idautils
        seg_mapping = {idc.SegName(x): (idc.SegStart(x), idc.SegEnd(x)) for x in idautils.Segments()}
        imports = seg_mapping[".idata"] if ftype == PE else seg_mapping['.plt']
        start, stop = seg_mapping[".text"]
        current = start
        while current <= stop:
            inst = current
            if idc.GetMnem(inst) in ["call", "jmp"]:
                value = idc.GetOperandValue(inst, 0)
                name = idc.GetOpnd(inst, 0)
                if imports[0] <= value <= imports[1]:
                    entry = self.config.call_map.add()
                    entry.address = inst
                    entry.name = name
            current = idc.NextHead(current, stop) 
Example #2
Source File: AnalysisWidget.py    From idasec with GNU Lesser General Public License v2.1 6 votes vote down vote up
def detect_start_and_stop(self):  # FIXME:Duplicate code with core (or something similar)
        start, stop = 0, 0
        if self.core.ftype == "PE":
            start, stop = self.core.fun_mapping["start"]
        else:
            if "main" in self.core.fun_mapping:
                start, stop = self.core.fun_mapping["main"]
            elif "start" in self.core.fun_mapping:
                if "__libc_start_main" in self.core.fun_mapping:
                    instrs = list(idautils.FuncItems(self.core.fun_mapping["start"][0]))
                    instrs.reverse()
                    for inst in instrs:
                        arg1 = idc.GetOperandValue(inst, 0)
                        if idc.GetMnem(inst) == "push":
                            start, stop = arg1, self.core.fun_mapping["start"][1]
                            break
                else:
                    start, stop = self.core.fun_mapping["start"]
            else:
                start, stop = idc.BeginEA(), 0
        self.start, self.stop = start, stop 
Example #3
Source File: interesting_xor.py    From idataco with GNU General Public License v3.0 6 votes vote down vote up
def find_interesting_xors(self):
        next_xor = idc.FindText(idc.MinEA(), idc.SEARCH_DOWN|idc.SEARCH_NEXT, 0, 0, "xor")
        while next_xor != idc.BADADDR:
            if idc.GetOpnd(next_xor, 0) != idc.GetOpnd(next_xor, 1):
                entry = {"func":"", "addr": next_xor, "loop":False, "disasm": idc.GetDisasm(next_xor)}
                func = idaapi.get_func(next_xor)
                if func:
                    entry["func"] = idaapi.get_name(idc.BADADDR, func.startEA)
                    heads = idautils.Heads(next_xor, func.endEA)
                    lxors = []
                    for head in heads:
                        if idc.GetMnem(head).startswith('j'):
                            jmp_addr = idc.GetOperandValue(head,0)
                            if jmp_addr < next_xor and jmp_addr > func.startEA:
                                entry["loop"] = True
                                break
                self._interesting_xors.append(entry)
            next_xor = idc.FindText(idc.NextHead(next_xor), idc.SEARCH_DOWN|idc.SEARCH_NEXT, 0, 0, "xor") 
Example #4
Source File: shellcode_hash_search.py    From flare-ida with Apache License 2.0 6 votes vote down vote up
def lookForOpArgs(self, start, end):
        for head in idautils.Heads(start, end):
            try:
                for i in range(2):
                    if using_ida7api:
                        t = idc.get_operand_type(head, i)
                    else:
                        t = idc.GetOpType(head, i)
                    if t == idc.o_imm:
                        if using_ida7api:
                            opval = idc.get_operand_value(head, i)
                        else:
                            opval = idc.GetOperandValue(head, i)
                        if self.params.useXORSeed:
                            opval = opval ^ self.params.XORSeed
                        for h in self.params.hashTypes:
                            hits = self.dbstore.getSymbolByTypeHash(h.hashType, opval)
                            for sym in hits:
                                logger.info("0x%08x: %s", head, str(sym))
                                self.addHit(head, sym)
                                self.markupLine(head, sym, self.params.useDecompiler)
            except Exception as err:
               logger.exception("Exception: %s", str(err)) 
Example #5
Source File: configuration_file.py    From idasec with GNU Lesser General Public License v2.1 5 votes vote down vote up
def set_start_stop(self, ftype):
        assert_ida_available()
        import idc
        import idaapi
        import idautils
        fun_mapping = {idc.GetFunctionName(x): (idaapi.get_func(x).startEA, idaapi.get_func(x).endEA-1)
                       for x in idautils.Functions()}
        start = idc.BeginEA()
        stop = 0
        if ftype == PE:
            start, stop = fun_mapping["start"]
        else:
            if not idc.isCode(idc.GetFlags(start)):
                if idc.MakeCode(start) == 0:
                    print "Fail to decode instr !"
                idaapi.autoWait()
            if idc.GetFunctionName(start) == "":
                if idc.MakeFunction(start) == 0:
                    print "Fail to create function !"
                idaapi.autoWait()
                fun_mapping = {idc.GetFunctionName(x): (idaapi.get_func(x).startEA, idaapi.get_func(x).endEA-1)
                               for x in idautils.Functions()}

            if "main" in fun_mapping:
                start, stop = fun_mapping["main"]
            elif "start" in fun_mapping:
                if "__libc_start_main" in fun_mapping:
                    instrs = list(idautils.FuncItems(fun_mapping["start"][0]))
                    instrs.reverse()
                    for inst in instrs:
                        arg1 = idc.GetOperandValue(inst, 0)
                        if idc.GetMnem(inst) == "push":
                            start, stop = arg1, fun_mapping["start"][1]
                            break
                else:
                    start, stop = fun_mapping["start"]
        self.config.start, self.config.stop = start, stop 
Example #6
Source File: create_tab_table.py    From win_driver_plugin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_operand_value(addr):
    """Returns the value of the second operand to the instruction at `addr` masked to be a 32 bit value"""

    return idc.GetOperandValue(addr, 1) & 0xffffffff 
Example #7
Source File: win_driver_plugin.py    From win_driver_plugin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_operand_value(addr):
    """Returns the value of the second operand to the instruction at `addr` masked to be a 32 bit value"""

    return idc.GetOperandValue(addr, 1) & 0xffffffff 
Example #8
Source File: collect_variable.py    From mcsema with Apache License 2.0 5 votes vote down vote up
def value(self):
    return idc.GetOperandValue(self._ea, self.index) 
Example #9
Source File: collect_variable.py    From mcsema with Apache License 2.0 5 votes vote down vote up
def value(self):
    return idc.GetOperandValue(self._ea, self.index) 
Example #10
Source File: BpHandler.py    From DIE with MIT License 5 votes vote down vote up
def get_called_func_data(self, ea):
        """
        Try to get the called function name and address.
        @param ea: Address to the CALL instruction
        @return: On success a tuple of called function data (Function_ea, Demangled_Function_Name).
        otherwise (None,None) tuple will be returned
        """
        try:
            func_name = None
            call_dest = None

            if idc.isCode(idc.GetFlags(ea)):
                if is_call(ea):
                    operand_type = idc.GetOpType(ea, 0)
                    if operand_type in (5, 6, 7, 2):
                        call_dest = idc.GetOperandValue(ea, 0)  # Call destination
                        func_name = get_function_name(call_dest).lower()

            return call_dest, func_name

        except Exception as ex:
            self.logger.exception("Failed to get called function data: %s", ex)
            return None, None

    ###############################################################################################
    #   Dynamic (RunTime) Breakpoints 
Example #11
Source File: dump_pool_tags.py    From win_driver_plugin with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def find_pool_tags():
	""" Dirty hack around IDA's type information, find references to tag using functions then the comment marking the tag 
	then add the function caller/tag to output dictionary.
	"""
	
	funcs = [
		'ExAllocatePoolWithTag',
		'ExFreePoolWithTag',
		'ExAllocatePoolWithTagPriority'
	]

	tags = {}

	def imp_cb(ea, name, ord):
		if name in funcs:
			for xref in idautils.XrefsTo(ea):
				call_addr = xref.frm
				caller_name = idc.GetFunctionName(call_addr)
				prev = idc.PrevHead(call_addr)
				for _ in range(10):
					if idc.Comment(prev) == 'Tag' and idc.GetOpType(prev, 1) == 5:
						tag_raw = idc.GetOperandValue(prev, 1)
						tag = ''
						for i in range(3, -1, -1):
							tag += chr((tag_raw >> 8 * i) & 0xFF)
						if tag in tags.keys():
							tags[tag].add(caller_name)
						else:
							tags[tag] = set([caller_name])
						break
					prev = idc.PrevHead(prev)
		return True
	
	nimps = idaapi.get_import_module_qty()

	for i in xrange(0, nimps):
		name = idaapi.get_import_module_name(i)
		if not name:
			continue

		idaapi.enum_import_names(i, imp_cb)
	return tags 
Example #12
Source File: 13_注释和重命名.py    From IDAPython_Note with MIT License 4 votes vote down vote up
def check_for_wrapper(func):
    flags = idc.GetFunctionFlags(func)
    #跳过库函数和简单的跳转函数
    if flags & FUNC_LIB or flags & FUNC_THUNK:
        return
    dism_addr = list(idautils.FuncItems(func))
    #获取函数的长度
    func_length = len(dism_addr)
    #如果函数的超过32条指令则返回
    if func_length > 0x20:
        return
    
    func_call = 0
    instr_cmp = 0
    op = None
    op_addr = None
    op_type = None
    
    #遍历函数中的每条指令
    for ea in dism_addr:
        m = idc.GetMnem(ea)
        if m == 'call' or m == 'jmp':
            if m == 'jmp':
                temp = idc.GetOperandValue(ea, 0)
                # 忽略函数边界内的跳转
                if temp in dism_addr:
                    continue
            func_call += 1
            #封装函数内不会包含多个函数调用
            if func_call == 2:
                return
            op_addr = idc.GetOperandValue(ea, 0)
            op_type = idc.GetOpType(ea, 0)
        elif m == 'cmp' or m == 'test':
            # 封装函数内不应该包含太多的逻辑运算
            instr_cmp += 1
            if instr_cmp == 3:
                return
        else:
            continue
    
    # 所有函数内的指令都被分析过了
    if op_addr == None:
        return
    
    name = idc.Name(op_addr)
    #跳过名称粉碎的函数名称
    if "[" in name or "$" in name or "?" in name or "@" in name or name == "":
        return
    name = "w_" + name
    if op_type == o_near:
        if idc.GetFunctionFlags(op_addr) & FUNC_THUNK:
            rename_wrapper(name, func)
            return
    if op_type == o_mem or op_type == o_far:
        rename_wrapper(name, func)
        return 
Example #13
Source File: IDAMetrics_static.py    From IDAmetrics with BSD 2-Clause "Simplified" License 4 votes vote down vote up
def get_function_args_count(self, function_ea, local_vars):
        """
        The function returns count of function arguments
        @function_ea - function entry point
        @local_vars - local variables dictionary
        @return - function arguments count
        """
        # i#9 Now, we can't identify fastcall functions.

        function_args_count = 0
        args_dict = dict()
        for local_var in local_vars:
            usage_list = local_vars.get(local_var, None)
            if usage_list == None:
                print "WARNING: empty usage list for ", local_var
                continue
            for head in usage_list:
                ops = self.get_instr_operands(int(head, 16))
                for idx, (op,type) in enumerate(ops):
                    if op.count("+") == 1:
                        value = idc.GetOperandValue(int (head, 16), idx)
                        if value < (15 * ARGUMENT_SIZE) and "ebp" in op:
                            args_dict.setdefault(local_var, []).append(head)
                    elif op.count("+") == 2:
                        if "arg" in local_var:
                            args_dict.setdefault(local_var, []).append(head)
                    else:
                        continue

        function_args_count = len(args_dict)
        if function_args_count:
            return function_args_count, args_dict

        #TODO Check previous algorithm here
        f_end = idc.FindFuncEnd(function_ea)
        f_end = idc.PrevHead(f_end, 0)
        instr_mnem = idc.GetMnem(f_end)
        #stdcall ?
        if "ret" in instr_mnem:
            ops = self.get_instr_operands(f_end)
            if len(ops) == 1:
                for op,type in ops:
                    op = op.replace("h", "")
                    function_args_count = int(op,16)/ARGUMENT_SIZE
                    return function_args_count, args_dict
        #cdecl ?
        refs = idautils.CodeRefsTo(function_ea, 0)
        for ref in refs:
            #trying to find add esp,x signature after call
            head = idc.NextHead(ref, 0xFFFFFFFF)
            if head:
                disasm = idc.GetDisasm(head)
                if "add" in disasm and "esp," in disasm:
                    ops = self.get_instr_operands(head)
                    op,type = ops[1]
                    if op:
                        op = op.replace("h", "")
                        function_args_count = int(op,16)/ARGUMENT_SIZE
                        return function_args_count, args_dict
        return function_args_count, args_dict 
Example #14
Source File: __init__.py    From flare-ida with Apache License 2.0 4 votes vote down vote up
def rename_constant(arg_ea, fct_name, arg_name, arg_enums):
    """ Rename constants to values from standard enumerations. """
    instruction = idc.GetMnem(arg_ea)
    if instruction == 'push':
        op_num = 0
    elif instruction == 'mov':
        op_num = 1
    else:
        raise RenamingException('Constant: unhandled instruction ' +
                                instruction)

    op_val = idc.GetOperandValue(arg_ea, op_num)
    # NULL
    if op_val == 0:
        targetid = idc.GetConstByName('NULL_{}_{}'.format(arg_name, fct_name))
        serial = 0
        enumid = idc.GetEnum(NULL_ENUM_NAME)
        constid = idc.GetConstEx(enumid, 0, serial, -1)
        while constid != idaapi.BADADDR:
            if constid == targetid:
                idc.OpEnumEx(arg_ea, op_num, enumid, serial)
                return
            serial = serial + 1
            constid = idc.GetConstEx(enumid, 0, serial, -1)

    # All other constants
    op_type = idc.GetOpType(arg_ea, op_num)
    if op_type == idaapi.o_imm:
        # only one choice
        if len(arg_enums) == 1:
            enumid = idc.GetEnum(arg_enums[0])
            idc.OpEnumEx(arg_ea, op_num, enumid, 0)
            return

        for enum in arg_enums:
            enumid = idc.GetEnum(enum)
            constid = get_constant_id(enumid, op_val)
            if constid == idaapi.BADADDR:
                # Not in this enum
                continue
            else:
                # Found the right enum
                idc.OpEnumEx(arg_ea, op_num, enumid, 0)
                return