Python idautils.XrefsTo() Examples

The following are 17 code examples of idautils.XrefsTo(). 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 idautils , or try the search function .
Example #1
Source File: objc2_xrefs_helper.py    From flare-ida with Apache License 2.0 6 votes vote down vote up
def get_xref(self,objc_selrefs,objc_msgrefs,objc_const):
        #We're looking for references to the selector string (think char **)
        #Which is either a selref, a msgref, or a pointer to the selector from the class's const method list
        name_ptr = self.name_pointer
        is_msg_ref=False
        selector_ref=None
        #how many references from __objc_const are there? This indicates how many classes
        #reference this selector
        const_ref_count=0
        for xref in XrefsTo(name_ptr):
            #Is this cross reference in the range of selector references?
            if objc_selrefs and xref.frm >= objc_selrefs[0] and xref.frm < objc_selrefs[1]:
                is_msg_ref=False
                selector_ref=xref
            #else, is this cross reference in the range of msg references?
            elif objc_msgrefs and xref.frm >= objc_msgrefs[0] and xref.frm < objc_msgrefs[1]:
                is_msg_ref=True
                selector_ref=xref
            #else, is this cross reference a pointer from a (const) method list?
            elif objc_const and xref.frm >= objc_const[0] and xref.frm < objc_const[1]:
                const_ref_count += 1



        return (is_msg_ref,selector_ref,const_ref_count) 
Example #2
Source File: objc2_analyzer.py    From flare-ida with Apache License 2.0 6 votes vote down vote up
def getSelRefFromImpPtr(self, eh, imp):
        selref = None
        retClsName = ""
        if eh.arch == unicorn.UC_ARCH_ARM and eh.isThumbMode(imp):
            imp |= 1
        logging.debug("checking xrefs for IMP %s" % eh.hexString(imp))
        for x in idautils.XrefsTo(imp):
            if x.frm >= self.objcConst[0] and x.frm < self.objcConst[1]:
                # even though imp ptr is stored at offset 0x10 in struct, xref just goes to base of struct, we want the
                # first field
                for y in idautils.XrefsTo(eh.derefPtr(x.frm)):
                    if y.frm >= self.objcSelRefs[0] and y.frm < self.objcSelRefs[1]:
                        selref = y.frm
                        break
                # determine return value's type
                # check type string to see if id is returned
                typeStr = eh.getIDBString(eh.derefPtr(x.frm + eh.size_pointer))
                if len(typeStr) > 0 and typeStr[0] == "@":
                    # scan imp for ivar reference, grab its type
                    if eh.arch == unicorn.UC_ARCH_ARM and eh.isThumbMode(imp):
                        imp = imp & ~1
                    retClsName = self.getIvarTypeFromFunc(eh, imp)

        return selref, retClsName 
Example #3
Source File: decrypt_str.py    From malware-research with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def decrypt_strings(info):
    xor_key = info['xor_key']
    for i, crypt_func_addr in enumerate(info['addr']):
        for xref in idautils.XrefsTo(crypt_func_addr):
            str_addr, str_len = find_params(xref)
            if str_addr == 0 or str_len == 0:
                print "ERROR: Can't find parameters for func" \
                  "at 0x{:08X}".format(xref)

            cipher = ida_bytes.get_bytes(str_addr, str_len)
            s = decrypt_str(cipher, xor_key)
            # Strings from the first decryption routine are UTF-16 encoded
            if i == 0:
                s = s.decode('utf-16').encode('utf-8')
                print "Str at 0x{:08X}: u'{}'".format(xref.frm, s)
                ida_bytes.set_cmt(xref.frm, "u'{}'".format(s), False)
                f_addr = ida_funcs.get_func(xref.frm)
                for xref_ in idautils.XrefsTo(f_addr.startEA):
                    ida_bytes.set_cmt(xref_.frm, "u'{}'".format(s), False)
            else:
                print "Str at 0x{:08X} : {}".format(xref.frm, repr(s))
                ida_bytes.set_cmt(xref.frm, repr(s), False)
                f_addr = ida_funcs.get_func(xref.frm)
                for xref_ in idautils.XrefsTo(f_addr.startEA):
                    ida_bytes.set_cmt(xref_.frm, repr(s), False) 
Example #4
Source File: dsc_fix.py    From dsc_fix with GNU General Public License v3.0 5 votes vote down vote up
def make_islands_xrefs_force_bl_call(ea, verbose=True):
    """ makes all BL references to a branch islands as call """
    segname = idc.SegName(ea)
    if verbose:
        print "[+] forcing bl call on: %s [0x%X]" % (segname, ea)
    if "branch_islands" in segname:
        idc.SetFunctionFlags(ea, idc.GetFunctionFlags(ea) & (0xffffffff - 1))
        for x in idautils.XrefsTo(ea):
            make_islands_xrefs_force_bl_call(x.frm)
        return
    idc.ArmForceBLCall(ea) 
Example #5
Source File: mykutils.py    From flare-ida with Apache License 2.0 5 votes vote down vote up
def for_each_call_to(callback, va=None):
    """For each xref to va that is a call, pass xref va to callback.

    Falls back to highlighted identifier or current location if va is
    unspecified.
    """
    if not va:
        v = ida_kernwin.get_current_viewer()
        hi = ida_kernwin.get_highlight(v)
        if hi and hi[1]:
            nm = hi[0]
            va = idc.get_name_ea_simple(nm)
            if va >= idaapi.cvar.inf.maxEA:
                va = None

    va = va or idc.here()

    # Obtain and de-duplicate addresses of xrefs that are calls
    callsites = set([x.frm for x in idautils.XrefsTo(va)
                     if idc.print_insn_mnem(x.frm) == 'call'])
    for va in callsites:
        callback(va)


# Instruction operand specification.
#
# Operand types are from ida_ua.o_* e.g. o_reg, o_mem.
# >>> {x: getattr(ida_ua, x) for x in dir(ida_ua) if x.startswith('o_')}
#
# Quick ref:
#   ida_ua.o_reg ==      1: "General Register (al,ax,es,ds...)",
#   ida_ua.o_mem ==      2: "Memory Reference",
#   ida_ua.o_phrase ==   3: "Base + Index",
#   ida_ua.o_displ ==    4: "Base + Index + Displacement",
#   ida_ua.o_imm ==      5: "Immediate",
#   ida_ua.o_far ==      6: "Immediate Far Address",
#   ida_ua.o_near ==     7: "Immediate Near Address",
#   ida_ua.o_idpspec0 == 8: "FPP register",
#   ida_ua.o_idpspec1 == 9: "386 control register",
#   ida_ua.o_idpspec2 == 10: "386 debug register",
#   ida_ua.o_idpspec3 == 11: "386 trace register", 
Example #6
Source File: argtracker.py    From flare-ida with Apache License 2.0 5 votes vote down vote up
def main():
    #jayutils.configLogger(__name__, logging.DEBUG)
    jayutils.configLogger(__name__, logging.INFO)
    logger = jayutils.getLogger('')
    logger.debug('Starting up in main')
    #name = idc.AskStr('CreateThread', 'Enter function to find args for')
    #argNum = idc.AskLong(6)

    filePath = jayutils.getInputFilepath()
    if filePath is None:
        self.logger.info('No input file provided. Stopping')
        return
    vw = jayutils.loadWorkspace(filePath)
    logger.debug('Loaded workspace')
    tracker = ArgTracker(vw)

    import idautils
    funcEa = idc.LocByName('CreateThread')
    if funcEa == idc.BADADDR:
        logger.info('CreateThread not found. Returning now')
        return
    for xref in idautils.XrefsTo(funcEa):
        argsList = tracker.getPushArgs(xref.frm, 6)
        for argDict in argsList:
            print '-'*60
            pc, value = argDict[3]
            print '0x%08x: 0x%08x: 0x%08x' % (xref.frm, pc, value) 
Example #7
Source File: objc2_analyzer.py    From flare-ida with Apache License 2.0 5 votes vote down vote up
def getRefPtr(self, eh, methodVa):
        isMsgRef, isAmbiguous, refPtr = (None, None, None)
        namePtr = eh.derefPtr(methodVa)
        cnt = 0
        for x in idautils.XrefsTo(namePtr):
            if self.objcSelRefs and x.frm >= self.objcSelRefs[0] and x.frm < self.objcSelRefs[1]:
                refPtr = x.frm
                isMsgRef = False
            elif self.objcMsgRefs and x.frm >= self.objcMsgRefs[0] and x.frm < self.objcMsgRefs[1]:
                refPtr = x.frm
                isMsgRef = True
            elif self.objcConst and x.frm >= self.objcConst[0] and x.frm < self.objcConst[1]:
                cnt += 1

        # ambiguous sel names
        isAmbiguous = False
        if cnt > 1:
            isAmbiguous = True
        return isAmbiguous, isMsgRef, refPtr


    # adds objc comment and calls fixXref to fix xrefs for objc_msgSend
    # address: address of msgSend call
    # id: class/instance name to show in comment
    # sel: selector name to show in comment
    # clsName: name of class to lookup for sel->imp mapping
    # selref: sel reference to lookup in sel->imp mapping 
Example #8
Source File: IdaTools.py    From apiscout with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def applyApiNames(self, api_results):
        num_renamed = 0
        num_skipped = 0
        num_xrefs_adapted = 0

        prev_offset = 0
        for api in sorted(api_results):
            if api[0] > prev_offset + 16:
                print("Annotating API Block @0x{:x}.".format(api[0]))
            prev_offset = api[0]
            if str(api[3]) == "None":
                num_skipped += 1
                print("Skipping 0x{:x}: no name provided by API DB (is None).".format(api[0]))
                self.makeDQWord(api)
                continue
            named = self.makeNameAndStructure(api)
            if not named:
                for suffix in range(10):
                    print("naming 0x{:x} to {} failed, trying with suffix \"_{}\".".format(api[0], str(api[3]), suffix))
                    named = self.makeNameAndStructure(api, suffix)
                    if named:
                        break
                    else:
                        print("  naming 0x{:x} to {} failed as well, trying next index...".format(api[0], str(api[3] + "_{}".format(suffix))))
            if named:
                num_renamed += 1
                for xref in idautils.XrefsTo(api[0]):
                    if self.setFunctionInformation(api[3], xref.frm):
                        num_xrefs_adapted += 1
        return num_renamed, num_skipped, num_xrefs_adapted 
Example #9
Source File: ida_batch_decompile.py    From ida-batch_decompile with GNU General Public License v3.0 5 votes vote down vote up
def get_xrefs(self):
        return (IdaLocation(x.frm) for x in idautils.XrefsTo(self.at)) 
Example #10
Source File: vtable.py    From ida_kernelcache with MIT License 5 votes vote down vote up
def _ok_to_rename_method(override, name):
    """Some method names are ok to rename."""
    return (name.startswith('j_') and idau.iterlen(idautils.XrefsTo(override)) == 1) 
Example #11
Source File: Main.py    From Virtuailor with GNU General Public License v3.0 5 votes vote down vote up
def get_xref_code_to_func(func_addr):
    a = idautils.XrefsTo(func_addr, 1)
    addr = {}
    for xref in a:
        frm = xref.frm  # ea in func
        start = idc.get_func_attr(frm, idc.FUNCATTR_START)  # to_xref func addr
        func_name = idc.get_func_name(start)  # to_xref func name
        addr[func_name] = [xref.iscode, start]
    return addr 
Example #12
Source File: 10_交叉引用.py    From IDAPython_Note with MIT License 5 votes vote down vote up
def get_xrefs_to(ea):
    xref_set = set()
    for xref in idautils.XrefsTo(ea, 1):
        xref_set.add(xref.frm)
    return xref_set 
Example #13
Source File: line.py    From Sark with MIT License 5 votes vote down vote up
def xrefs_to(self):
        """Xrefs to this line.

        Returns:
            Xrefs as `sark.code.xref.Xref` objects.
        """
        return list(map(Xref, idautils.XrefsTo(self.ea))) 
Example #14
Source File: function.py    From Sark with MIT License 5 votes vote down vote up
def xrefs_to(self):
        """Xrefs to the function.

        This only includes references to that function's start address.
        """
        return map(Xref, idautils.XrefsTo(self.start_ea)) 
Example #15
Source File: idaxml.py    From GhIDA with Apache License 2.0 5 votes vote down vote up
def export_user_memory_reference(self, addr):
        """
        Exports a user-specified memory reference at the address.

        Args:
            addr: Integer representing the instruction address.
        """
        for xref in idautils.XrefsTo(addr, ida_xref.XREF_FAR):
            if xref.user == 1:
                self.start_element(MEMORY_REFERENCE)
                self.write_address_attribute(ADDRESS, xref.frm)
                self.write_address_attribute(TO_ADDRESS, xref.to)
                self.write_attribute(USER_DEFINED, "y")
                self.close_tag() 
Example #16
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 #17
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