Python idc.get_operand_value() Examples

The following are 16 code examples of idc.get_operand_value(). 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: color.py    From idawilli with Apache License 2.0 6 votes vote down vote up
def color_head(ea):
    flags = ida_bytes.get_flags(ea)
    if not ida_bytes.is_code(flags):
        return

    mnem = ida_ua.print_insn_mnem(ea)
    if mnem == 'call':
        logger.debug('call: 0x%x', ea)
        idc.set_color(ea, idc.CIC_ITEM, CALL_COLOR)
    elif mnem == 'xor':
        if idc.get_operand_value(ea, 0) != idc.get_operand_value(ea, 1):
            logger.debug('non-zero xor: 0x%x', ea)
            idc.set_color(ea, idc.CIC_ITEM, ENCRYPT_COLOR)
    elif mnem in ('sdit', 'sgdt', 'sldt', 'smsw', 'str', 'in', 'cpuid'):
        logger.debug('anti-vm: 0x%x', ea)
        idc.set_color(ea, idc.CIC_ITEM, ANTIANALYSIS_COLOR)
    elif mnem == 'in':
        if idc.get_operand_value(ea, 0) in ("3", "2D"):
            logger.debug('anti-debug: 0x%x', ea)
            idc.set_color(ea, idc.CIC_ITEM, ANTIANALYSIS_COLOR)
    elif mnem in ('rdtsc', 'icebp'):
        logger.debug('anti-debug: 0x%x', ea)
        idc.set_color(ea, idc.CIC_ITEM, ANTIANALYSIS_COLOR) 
Example #2
Source File: analyser.py    From UEFI_RETool with MIT License 6 votes vote down vote up
def _find_est(self, gvar, start, end):
        RAX = 0
        BS_OFFSET = 0x60
        EFI_SYSTEM_TABLE = 'EFI_SYSTEM_TABLE *'
        if self.arch == 'x86':
            BS_OFFSET = 0x3c
        ea = start
        while (ea < end):
            if ((idc.print_insn_mnem(ea) == 'mov')
                    and (idc.get_operand_value(ea, 0) == RAX)
                    and (idc.get_operand_value(ea, 1) == BS_OFFSET)):
                if idc.SetType(gvar, EFI_SYSTEM_TABLE):
                    idc.set_name(gvar, 'gSt_{addr:#x}'.format(addr=gvar))
                    return True
            ea = idc.next_head(ea)
        return False 
Example #3
Source File: analyser.py    From UEFI_RETool with MIT License 6 votes vote down vote up
def get_boot_services(self):
        """found boot services in idb"""
        code = list(idautils.Functions())[0]
        start = idc.get_segm_start(code)
        end = idc.get_segm_end(code)
        ea = start
        while (ea <= end):
            if idc.print_insn_mnem(ea) != 'call':
                ea = idc.next_head(ea)
                continue
            for service_name in self.BOOT_SERVICES_OFFSET:
                # yapf: disable
                if (idc.get_operand_value(ea, 0) == self.BOOT_SERVICES_OFFSET[service_name]):
                    if not self.gBServices[service_name].count(ea):
                        self.gBServices[service_name].append(ea)
            ea = idc.next_head(ea) 
Example #4
Source File: klfdb.py    From ActionScript3 with GNU General Public License v3.0 6 votes vote down vote up
def get_stack_vars(self, start, end):

		stackvars = {}
	
		ea = start
		while (ea < end):
	
			if ("ebp" in idc.print_operand(ea, 0) and idc.get_operand_type(ea, 1) == idc.o_imm):
	
				op0 = idc.get_operand_value(ea, 0)
				op1 = idc.get_operand_value(ea, 1)
	
				if (op0 in stackvars):
					stackvars[op0]["values"].append(op1)
				else:
					stackvars[op0] = {"values": [], "hits": 0}
	
			ea += idc.get_item_size(ea)

		return stackvars 
Example #5
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 #6
Source File: code_grafter.py    From flare-ida with Apache License 2.0 6 votes vote down vote up
def _get_imp_for_register_call(self, va_call, nm=None):
        if idc.print_insn_mnem(va_call) != 'call':
            msg = 'va_call must be the virtual address of a call instruction'
            raise ValueError(msg)

        reg = idc.print_operand(va_call, 0)
        va_mov = mykutils.find_instr(va_call, 'up', 'mov',
                                     [(0, 1, reg), (1, 2, None)])
        if not va_mov:
            return None

        if nm and (nm not in idc.print_operand(va_mov, 1)):
            return None

        va_imp = idc.get_operand_value(va_mov, 1)
        return va_imp 
Example #7
Source File: code_grafter.py    From flare-ida with Apache License 2.0 6 votes vote down vote up
def patch_import(va, target):
    """Patch the import corresponding to the call at @va to point to @target.

    Args:
        va (numbers.Integral): Address of call site for imported function
        target (str): Name or address of new call destination for import entry

    Returns:
        bool: True if successful
    """
    is_call = idc.print_insn_mnem(va) == 'call'

    if is_call:
        opno = 0
    else:
        logger.warn('Not a call instruction at %s' % (phex(va)))
        return False

    if isinstance(target, basestring):
        target = idc.get_name_ea_simple(target)

    patch_pointer_width(idc.get_operand_value(va, opno), target)

    return True 
Example #8
Source File: analyser.py    From UEFI_RETool with MIT License 5 votes vote down vote up
def get_protocols(self):
        """found UEFI protocols information in idb"""
        for service_name in self.gBServices:
            for address in self.gBServices[service_name]:
                ea, found = address, False
                if self.arch == 'x86':
                    for _ in range(1, 25):
                        ea = idc.prev_head(ea)
                        if (idc.get_operand_value(ea, 0) > self.base
                                and idc.print_insn_mnem(ea) == 'push'):
                            found = True
                            break
                if self.arch == 'x64':
                    for _ in range(1, 16):
                        ea = idc.prev_head(ea)
                        if (idc.get_operand_value(ea, 1) > self.base
                                and idc.print_insn_mnem(ea) == 'lea'):
                            found = True
                            break
                if not found:
                    continue
                for xref in idautils.DataRefsFrom(ea):
                    if idc.print_insn_mnem(xref):
                        continue
                    if not check_guid(xref):
                        continue
                    cur_guid = get_guid(xref)
                    record = {
                        'address': xref,
                        'service': service_name,
                        'guid': cur_guid,
                    }
                    if not self.Protocols['all'].count(record):
                        self.Protocols['all'].append(record) 
Example #9
Source File: quicktime.py    From ida-minsc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def getMinorDispatchTableAddress(ea):
    """find address of last lea in function"""
    start = idc.get_func_attr(ea, idc.FUNCATTR_START)
    end = idc.prev_head( idc.get_func_attr(ea, idc.FUNCATTR_END), start)
    res = prevMnemonic(end, 'lea', start)
    assert res != idc.BADADDR
    return idc.get_operand_value(res, 1) 
Example #10
Source File: quicktime.py    From ida-minsc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def getMajorDispatchTableAddress():
    """find quicktime major dispatch table"""
    res = idc.get_name_ea_simple('theQuickTimeDispatcher')
    res = nextMnemonic(res, 'lea', idc.get_func_attr(res, idc.FUNCATTR_END))
    assert res != idc.BADADDR
    return idc.get_operand_value(res, 1) 
Example #11
Source File: quicktime.py    From ida-minsc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def getDispatchCode(ea):
    # get dispatch code out of an instruction
    first, second = (idc.print_operand(ea, 0), idc.get_operand_value(ea, 1))
    if first == 'eax':
        return second
    raise ValueError("Search resulted in address %08x, but instruction '%s' does fulfill requested constraints"% (ea, idc.print_insn_mnem(ea))) 
Example #12
Source File: klfdb.py    From ActionScript3 with GNU General Public License v3.0 5 votes vote down vote up
def set_jit_info(self, method_id, start):

		end = self.get_func_end(start)

		if (end < start or end - start > self.jit_max_size):
			return

		method = next((x for x in self.as3dump if x["id"] == method_id), None)

		if (method is None):
			return

		stackvars = self.get_stack_vars(start, end)
		save_eip = self.get_save_eip(method, stackvars)

		ea = start
		while (ea < end):
	
			if ("ebp" in idc.print_operand(ea, 0) and idc.get_operand_type(ea, 1) == idc.o_imm):
	
				op0 = idc.get_operand_value(ea, 0)
				op1 = idc.get_operand_value(ea, 1)
	
				if (op0 == save_eip):
					idc.set_cmt(ea, method["instructions"][op1], 0)
		
			ea += idc.get_item_size(ea) 
Example #13
Source File: ida_prefix.py    From prefix with MIT License 4 votes vote down vote up
def get_cursor_func_ref():
    """
    Get the function reference under the user cursor.

    Returns BADADDR or a valid function address.
    """
    current_widget = idaapi.get_current_widget()
    form_type      = idaapi.get_widget_type(current_widget)
    vu = idaapi.get_widget_vdui(current_widget)

    #
    # hexrays view is active
    #

    if vu:
        cursor_addr = vu.item.get_ea()

    #
    # disassembly view is active
    #

    elif form_type == idaapi.BWN_DISASM:
        cursor_addr = idaapi.get_screen_ea()
        opnum = idaapi.get_opnum()

        if opnum != -1:

            #
            # if the cursor is over an operand value that has a function ref,
            # use that as a valid rename target
            #

            op_addr = idc.get_operand_value(cursor_addr, opnum)
            op_func = idaapi.get_func(op_addr)

            if op_func and op_func.start_ea == op_addr:
                return op_addr

    # unsupported/unknown view is active
    else:
        return idaapi.BADADDR

    #
    # if the cursor is over a function definition or other reference, use that
    # as a valid rename target
    #

    cursor_func = idaapi.get_func(cursor_addr)
    if cursor_func and cursor_func.start_ea == cursor_addr:
        return cursor_addr

    # fail
    return idaapi.BADADDR 
Example #14
Source File: analyser.py    From UEFI_RETool with MIT License 4 votes vote down vote up
def set_types(self):
        """
        handle (EFI_BOOT_SERVICES *) type
        and (EFI_SYSTEM_TABLE *) for x64 images
        """
        RAX = 0
        O_REG = 1
        O_MEM = 2
        EFI_BOOT_SERVICES = 'EFI_BOOT_SERVICES *'
        EFI_SYSTEM_TABLE = 'EFI_SYSTEM_TABLE *'
        empty = True
        for service in self.gBServices:
            for address in self.gBServices[service]:
                ea = address
                num_of_attempts = 10
                for _ in range(num_of_attempts):
                    ea = idc.prev_head(ea)
                    if (idc.print_insn_mnem(ea) == 'mov'
                            and idc.get_operand_type(ea, 1) == O_MEM):
                        if (idc.get_operand_type(ea, 0) == O_REG
                                and idc.get_operand_value(ea, 0) == RAX):
                            gvar = idc.get_operand_value(ea, 1)
                            gvar_type = idc.get_type(gvar)
                            # if (EFI_SYSTEM_TABLE *)
                            if ((gvar_type != 'EFI_SYSTEM_TABLE *')
                                    and (idc.print_operand(
                                        address, 0).find('rax') == 1)):
                                if self._find_est(gvar, ea, address):
                                    # yapf: disable
                                    print('[ {0} ] Type ({type}) successfully applied'.format(
                                            '{addr:#010x}'.format(addr=gvar),
                                            type=EFI_SYSTEM_TABLE))
                                    empty = False
                                    break
                            # otherwise it (EFI_BOOT_SERVICES *)
                            if (gvar_type != 'EFI_BOOT_SERVICES *'
                                    and gvar_type != 'EFI_SYSTEM_TABLE *'):
                                if idc.SetType(gvar, EFI_BOOT_SERVICES):
                                    empty = False
                                    idc.set_name(
                                        gvar,
                                        'gBs_{addr:#x}'.format(addr=gvar))
                                    # yapf: disable
                                    print('[ {0} ] Type ({type}) successfully applied'.format(
                                            '{addr:#010x}'.format(addr=gvar),
                                            type=EFI_BOOT_SERVICES))
                            break
        if empty:
            print(' * list is empty') 
Example #15
Source File: objc2_analyzer.py    From flare-ida with Apache License 2.0 4 votes vote down vote up
def getIvarTypeFromFunc(self, eh, va):
        if va in self.ivarSetters:
            return self.ivarSetters[va]
        elif va in self.notIvarSetters:
            return UNKNOWN
        addr = va
        endVa = idc.get_func_attr(va, idc.FUNCATTR_END)
        if endVa - va < 0x20:
            ivarVa = None
            while addr <= endVa:
                srcOpnd = idc.print_operand(addr, 1)
                # if ivar is the src op for an instruction, assume this function will return it
                if eh.arch == unicorn.UC_ARCH_ARM and "_OBJC_IVAR_$_" in srcOpnd:
                    oploc = idc.get_name_ea_simple(
                        srcOpnd[srcOpnd.find("_OBJC_IVAR_$_"):srcOpnd.find(" ")])
                    if oploc != idc.BADADDR:
                        ivarVa = oploc
                        break
                elif eh.arch == unicorn.UC_ARCH_ARM64:
                    for x in idautils.XrefsFrom(addr):
                        if (idc.get_segm_name(x.to) == "__objc_ivar" and
                                idc.get_name(x.to, idc.ida_name.GN_VISIBLE)[:13] == "_OBJC_IVAR_$_"):
                            ivarVa = x.to
                            break
                elif eh.arch == unicorn.UC_ARCH_X86:
                    if "_OBJC_IVAR_$_" in srcOpnd:
                        ivarVa = idc.get_operand_value(addr, 1)
                        break

                addr = idc.next_head(addr, idc.get_inf_attr(idc.INF_MAX_EA))

            if ivarVa:
                for x in idautils.XrefsTo(ivarVa):
                    if x.frm >= self.objcConst[0] and x.frm < self.objcConst[1]:
                        typeStr = eh.getIDBString(
                            eh.derefPtr(x.frm + eh.size_pointer * 2))
                        self.ivarSetters[va] = typeStr[2:-1]
                        logging.debug("%s is an ivar getter function, returning type %s" % (
                            eh.hexString(va), typeStr[2:-1]))
                        return typeStr[2:-1]
            else:
                logging.debug(
                    "%s determined not to be an ivar getter function", eh.hexString(va))
                self.notIvarSetters.append(va)
        else:
            logging.debug(
                "%s determined not to be an ivar getter function", eh.hexString(va))
            self.notIvarSetters.append(va)
        return UNKNOWN


    # returns class or sel name from IDA name 
Example #16
Source File: mykutils.py    From flare-ida with Apache License 2.0 4 votes vote down vote up
def is_conformant_operand(va, op_spec):
    """Check that operand conforms to specification.

    Args:
        va (numbers.Integral): Virtual address of instruction to assess.
        op_spec (OpSpec): Operand specification tuple (operand position, type,
            and name)

    Returns:
        True if conformant
        False if nonconformant
    """
    spec = OpSpec(*op_spec)  # Make it convenient to pass plain tuples

    if (spec.pos is None) or ((not spec.name) and (not spec.type)):
        msg = 'Must specify an operand position and either a name or type'
        raise ValueError(msg)

    if spec.type is not None and idc.get_operand_type(va, spec.pos) != spec.type:
        return False

    if spec.name is not None:
        # For two types:
        #   o_phrase = 3 Base + Index
        #   o_displ =  4 Base + Index + Displacement
        # Use substring matching to compensate for IDA Pro's representation
        if spec.type in (ida_ua.o_phrase, ida_ua.o_displ):
            if spec.name not in idc.print_operand(va, spec.pos):
                return False

        # For these types:
        #   o_imm =  5   Immediate
        #   o_far =  6   Immediate Far Address
        #   o_near = 7   Immediate Near Address
        # Check both address and name
        elif spec.type in (ida_ua.o_imm, ida_ua.o_far, ida_ua.o_near):
            if isinstance(spec.name, basestring):
                if idc.print_operand(va, spec.pos) != spec.name:
                    return False
            elif idc.get_operand_value(va, spec.pos) != spec.name:
                return False
        else:
            if idc.print_operand(va, spec.pos) != spec.name:
                return False

    return True


###############################################################################
# Code Carving i.e. function extraction
###############################################################################
# Why:
# * To extract whole funtions for emulation, shellcode crafting, or other
#   external processing.
# * To extend Code Grafting by adding function opcodes to the library already
#   present there.
#
# Code Grafting allows you to graft static implementations of imported
# functions into your IDB for purposes of emulation in Bochs IDB mode or by
# other emulators. For instructions on adding synthetic import implementations
# to the Code Grafting library for use with your binary, see `code_grafter.py`.