Python idautils.Functions() Examples

The following are 30 code examples of idautils.Functions(). 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: yara_fn.py    From ida_haru with Apache License 2.0 15 votes vote down vote up
def main():
    print 'Start'
    ans = ida_kernwin.ask_yn(0, 'define only selected function?')
    if ans:
        va = ScreenEA()
        fva = get_function(va)
        print('-' * 80)
        rule = create_yara_rule_for_function(fva)
        if rule:
            print(rule)
            if test_yara_rule(rule):
                logging.info('success: validated the generated rule')
            else:
                logging.error('error: failed to validate generated rule')
    else:
        for fva in idautils.Functions():
            print('-' * 80)
            rule = create_yara_rule_for_function(fva)
            if rule:
                print(rule)
    print 'Done' 
Example #2
Source File: win_driver_plugin.py    From win_driver_plugin with BSD 3-Clause "New" or "Revised" License 13 votes vote down vote up
def find_dispatch_by_struct_index():
    """Attempts to locate the dispatch function based off it being loaded in a structure
    at offset 70h, based off of https://github.com/kbandla/ImmunityDebugger/blob/master/1.73/Libs/driverlib.py """
    
    out = set()
    for function_ea in idautils.Functions():
        flags = idc.get_func_flags(function_ea)
        # skip library functions
        if flags & idc.FUNC_LIB:
            continue
        func = idaapi.get_func(function_ea)
        addr = func.startEA
        while addr < func.endEA:
            if idc.GetMnem(addr) == 'mov':
                if '+70h' in idc.GetOpnd(addr, 0) and idc.GetOpType(addr, 1) == 5:
                    out.add(idc.GetOpnd(addr, 1))
            addr = idc.NextHead(addr)
    return out 
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: stackstrings.py    From flare-ida with Apache License 2.0 6 votes vote down vote up
def getFuncRanges(ea, doAllFuncs):
    if using_ida7api:
        return getFuncRanges_ida7(ea, doAllFuncs)
    if doAllFuncs:
        funcs = []
        funcGen = idautils.Functions(idc.SegStart(ea), idc.SegEnd(ea))
        for i in funcGen:
            funcs.append(i)
        funcRanges = []
        for i in range(len(funcs) - 1):
            funcRanges.append( (funcs[i], funcs[i+1]) )
        funcRanges.append( (funcs[-1], idc.SegEnd(ea)) )
        return funcRanges
    else:
        #just get the range of the current function
        fakeRanges = [( idc.GetFunctionAttr(idc.here(), idc.FUNCATTR_START), idc.GetFunctionAttr(idc.here(), idc.FUNCATTR_END)), ]
        return fakeRanges 
Example #5
Source File: main.py    From ida_pdb_loader with MIT License 6 votes vote down vote up
def _rename_functions(self):
        '''Rename functions.'''

        print "IPL: Started to rename functions..."

        failed = 0
        total = 0
        for function in idautils.Functions():
            total += 1
            pdb_mangled_name = self.PDBLookup.lookup(function, True)
            if not pdb_mangled_name:
                failed += 1
                print "IPL: Failed to find symbol for function: 0x{:08x}".format(function)
                continue
            _, mangled_function_name = pdb_mangled_name.split('!')
            # https://www.hex-rays.com/products/ida/support/idadoc/203.shtml
            idc.MakeNameEx(function, mangled_function_name,
                           idc.SN_AUTO | idc.SN_NOCHECK)
        print "IPL: Total {} functions, {} failed to rename.".format(total, failed) 
Example #6
Source File: upload.py    From rematch with GNU General Public License v3.0 6 votes vote down vote up
def calc_file_version_hash():
    version_obj = []
    version_obj.append(('functions', [(offset, list(idautils.Chunks(offset)))
                                        for offset in idautils.Functions()]))
    # TODO: This is a little hackish way of getting the version of all vectors
    # of an instance. cannot make version a classmethod because vector sets are
    # only built by __init__ methods
    func_vector_versions = FunctionInstance(None, None).version()
    version_obj.append(('function_vector_versions', func_vector_versions))
    # TODO: Add function annotations as part of the version, because they're
    # also changing.
    # TODO: Add universal instance related versions

    version_str = repr(version_obj)
    version_hash = hashlib.md5(version_str).hexdigest()

    log('upload_action').info("file version string: %s", version_str)
    log('upload_action').info("file version hash: %s", version_hash)
    return version_hash 
Example #7
Source File: call_graph.py    From ida-scripts with The Unlicense 6 votes vote down vote up
def generate_graph():
	callees = dict()

	# Loop through all the functions in the binary
	for function_ea in idautils.Functions():

		f_name = GetFunctionName(function_ea)
		# For each of the incoming references
		for ref_ea in CodeRefsTo(function_ea, 0):
		
			# Get the name of the referring function
			caller_name = GetFunctionName(ref_ea)
			
			# Add the current function to the list of functions
			# called by the referring function
			callees[caller_name] = callees.get(caller_name, Set())

			callees[caller_name].add(f_name)
	return callees

#Visit functions called by our starting point recursively 
Example #8
Source File: ida_api.py    From lighthouse with MIT License 5 votes vote down vote up
def get_function_addresses(self):
        return list(idautils.Functions()) 
Example #9
Source File: ida.py    From bap-ida-python with MIT License 5 votes vote down vote up
def prototypes():
    types = set()
    for ea in idautils.Functions():
        proto = idaapi.print_type(ea, True)
        if proto:
            types.append(proto + ';')
    return list(types) 
Example #10
Source File: ida.py    From bap-ida-python with MIT License 5 votes vote down vote up
def output_symbols(out):
    """Dump symbols."""
    try:
        from idaapi import get_func_name2 as get_func_name
        # Since get_func_name is deprecated (at least from IDA 6.9)
    except ImportError:
        from idaapi import get_func_name
        # Older versions of IDA don't have get_func_name2
        # so we just use the older name get_func_name

    def func_name_propagate_thunk(ea):
        current_name = get_func_name(ea)
        if current_name[0].isalpha():
            return current_name
        func = idaapi.get_func(ea)
        temp_ptr = idaapi.ea_pointer()
        ea_new = idaapi.BADADDR
        if func.flags & idaapi.FUNC_THUNK == idaapi.FUNC_THUNK:
            ea_new = idaapi.calc_thunk_func_target(func, temp_ptr.cast())
        if ea_new != idaapi.BADADDR:
            ea = ea_new
        propagated_name = get_func_name(ea) or ''  # Ensure it is not `None`
        if len(current_name) > len(propagated_name) > 0:
            return propagated_name
        else:
            return current_name
            # Fallback to non-propagated name for weird times that IDA gives
            #     a 0 length name, or finds a longer import name

    for ea in idautils.Segments():
        fs = idautils.Functions(idc.SegStart(ea), idc.SegEnd(ea))
        for f in fs:
            out.write('("%s" 0x%x 0x%x)\n' % (
                func_name_propagate_thunk(f),
                idc.GetFunctionAttr(f, idc.FUNCATTR_START),
                idc.GetFunctionAttr(f, idc.FUNCATTR_END))) 
Example #11
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_functions():
        return (IdaLocation(f) for f in idautils.Functions()) 
Example #12
Source File: Main.py    From Virtuailor with GNU General Public License v3.0 5 votes vote down vote up
def get_all_functions():
    for func in idautils.Functions():
        print(hex(func), idc.get_func_name(func)) 
Example #13
Source File: ida_prefix.py    From prefix with MIT License 5 votes vote down vote up
def bulk_prefix():
    """
    Prefix the Functions window selection with a user defined string.
    """

    # prompt the user for a prefix to apply to the selected functions
    tag = idaapi.ask_str(PREFIX_DEFAULT, 0, "Function Tag")

    # the user closed the window... ignore
    if tag == None:
        return

    # the user put a blank string and hit 'okay'... notify & ignore
    elif tag == '':
        idaapi.warning("[ERROR] Tag cannot be empty [ERROR]")
        return

    #
    # loop through all the functions selected in the 'Functions window' and
    # apply the user defined prefix tag to each one.
    #

    for func_name in get_selected_funcs():

        # ignore functions that already have the specified prefix applied
        if func_name.startswith(tag):
            continue

        # apply the user defined prefix to the function (rename it)
        new_name  = '%s%s%s' % (str(tag), PREFIX_SEPARATOR, func_name)
        func_addr = idaapi.get_name_ea(idaapi.BADADDR, func_name)
        idaapi.set_name(func_addr, new_name, idaapi.SN_NOWARN)

    # refresh the IDA views
    refresh_views() 
Example #14
Source File: ida_prefix.py    From prefix with MIT License 5 votes vote down vote up
def match_funcs(qt_funcs):
    """
    Convert function names scraped from Qt to their *actual* representation.

    The function names we scrape from the Functions window Qt table actually
    use the underscore character ('_') as a substitute for a variety of
    different characters.

    For example, a function named foo%bar in the IDB will appears as foo_bar
    in the Functions window table.

    This function takes a list of names as they appear in the Functions window
    table such as the following:

        ['foo_bar']

    And applies a best effort lookup to return a list of the 'true' function
    names as they are stored in the IDB.

       ['foo%bar']

    TODO: rewrite this to be more efficient for larger idbs
    TODO: takes first matching function, may want to change it to make the requirements more strict
    """
    res = set()
    ida_funcs = get_all_funcs()
    for f in qt_funcs:
        for f2 in ida_funcs:
            if len(f) == len(f2):
                i = 0
                while i < len(f) and (f[i] == f2[i] or f[i] == '_'):
                    i += 1

                if i == len(f):
                    res.add(f2)
                    break

    return list(res) 
Example #15
Source File: ida_prefix.py    From prefix with MIT License 5 votes vote down vote up
def get_selected_funcs():
    """
    Return the list of function names selected in the Functions window.
    """
    import sip
    twidget = idaapi.find_widget("Functions window")
    widget  = sip.wrapinstance(int(twidget), QtWidgets.QWidget)

    # TODO: test this
    if not widget:
        idaapi.warning("Unable to find 'Functions window'")
        return

    #
    # locate the table widget within the Functions window that actually holds
    # all the visible function metadata
    #

    table = widget.findChild(QtWidgets.QTableView)

    #
    # scrape the selected function names from the Functions window table
    #

    selected_funcs = [str(s.data()) for s in table.selectionModel().selectedRows()]

    #
    # re-map the scraped names as they appear in the function table, to their true
    # names as they are saved in the IDB. See the match_funcs(...) function
    # comment for more details
    #

    return match_funcs(selected_funcs) 
Example #16
Source File: ida_prefix.py    From prefix with MIT License 5 votes vote down vote up
def get_all_funcs():
    """
    Enumerate all function names defined in the IDB.
    """
    return set(idaapi.get_func_name(ea) for ea in idautils.Functions()) 
Example #17
Source File: ida_prefix.py    From prefix with MIT License 5 votes vote down vote up
def clear_prefix():
    """
    Clear user defined prefixes from the selected functions in the Functions window.
    """

    #
    # loop through all the functions selected in the 'Functions window' and
    # clear any user defined prefixes applied to them.
    #

    for func_name in get_selected_funcs():

        #
        # locate the last (rfind) prefix separator in the function name as
        # we will want to keep everything that comes after it
        #

        i = func_name.rfind(PREFIX_SEPARATOR)

        # if there is no prefix (separator), there is nothing to trim
        if i == -1:
            continue

        # trim the prefix off the original function name and discard it
        new_name  = func_name[i+1:]
        func_addr = idaapi.get_name_ea(idaapi.BADADDR, func_name)
        idaapi.set_name(func_addr, new_name, idaapi.SN_NOWARN)

    # refresh the IDA views
    refresh_views()

#------------------------------------------------------------------------------
# IDA Util
#------------------------------------------------------------------------------ 
Example #18
Source File: FuncScopeChooser.py    From DIE with MIT License 5 votes vote down vote up
def __getFunctions():
    """
    Get all current functions
    @return: a tuple of (function_name, function_ea)
    """
    functions = {}
    for func_ea in idautils.Functions():
        functions[get_function_name(func_ea)] = func_ea

    return functions 
Example #19
Source File: upload.py    From rematch with GNU General Public License v3.0 5 votes vote down vote up
def start_upload(self):
    log('upload_action').info("Data upload started")

    # TODO: Is this too slow? should we move this to perform_upload? or into a
    # generator?
    self.instances = set((FunctionInstance, f) for f in idautils.Functions())
    self.instances.add((UniversalInstance, (s[0] for s in idautils.Structs())))

    self.dialog_obj.increase_maximum(len(self.instances))

    self.timer.timeout.connect(self.perform_upload)
    self.timer.start(0) 
Example #20
Source File: functions_plus.py    From functions-plus with MIT License 5 votes vote down vote up
def get_list_of_functions(self):
        '''
        Gets all functions list.
        '''

        functions_list = {}
        seg_ea = idc.get_segm_by_sel(idc.SEG_NORM)

        for func_ea in idautils.Functions(idc.get_segm_start(seg_ea),
                                          idc.get_segm_end(seg_ea)):
            function_name = idc.get_func_name(func_ea)
            functions_list[function_name] = func_ea

        return functions_list 
Example #21
Source File: functions_plus.py    From functions-plus with MIT License 5 votes vote down vote up
def __init__(self):
        super(FunctionsPlus, self).__init__()
        if idc.get_inf_attr(idc.INF_PROCNAME).lower() != 'metapc':
            print('Functions+ warning: not tested in this configuration')
        self.tree = None
        self.icon = 135
        # Enable this if you want to see extra information about function
        self.show_extra_fields = False
        self.cols = Cols(self.show_extra_fields) 
Example #22
Source File: functions_plus.py    From functions-plus with MIT License 5 votes vote down vote up
def Show(self):
        '''
        Creates the form is not created or focuses it if it was.
        '''
        return PluginForm.Show(self, 'Functions+') 
Example #23
Source File: ida_export.py    From bnida with MIT License 5 votes vote down vote up
def get_function_comments():
    """
    Get function comments from IDA database

    :return: Dict containing function comments
    """

    comments = {}
    for ea in idautils.Functions():
        comment = get_single_function_comment(ea)
        if comment:
            comments[ea] = comment

    return comments 
Example #24
Source File: ida_export.py    From bnida with MIT License 5 votes vote down vote up
def get_functions():
    """
    Get function start addresses

    :return: Array containing function addresses
    """

    func_addrs = []
    for ea in idautils.Functions():
        func_addrs.append(ea)

    return func_addrs 
Example #25
Source File: IdaInterface.py    From smda with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def getFunctions(self):
        return sorted([offset for offset in idautils.Functions()]) 
Example #26
Source File: IdaInterface.py    From smda with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def getFunctions(self):
        return sorted([offset for offset in idautils.Functions()]) 
Example #27
Source File: stackstrings.py    From flare-ida with Apache License 2.0 5 votes vote down vote up
def getFuncRanges_ida7(ea, doAllFuncs):
    if doAllFuncs:
        funcs = []
        funcGen = idautils.Functions(idc.get_segm_start(ea), idc.get_segm_end(ea))
        for i in funcGen:
            funcs.append(i)
        funcRanges = []
        for i in range(len(funcs) - 1):
            funcRanges.append( (funcs[i], funcs[i+1]) )
        funcRanges.append( (funcs[-1], idc.get_segm_end(ea)) )
        return funcRanges
    else:
        #just get the range of the current function
        fakeRanges = [( idc.get_func_attr(idc.here(), idc.FUNCATTR_START), idc.get_func_attr(idc.here(), idc.FUNCATTR_END)), ]
        return fakeRanges 
Example #28
Source File: code_grafter.py    From flare-ida with Apache License 2.0 5 votes vote down vote up
def _unpatchCalls(self, grafted_segs):
        def do_unpatch_call(va_callsite):
            size = idc.get_item_size(va_callsite)
            ida_xref.del_cref(va_callsite, fva_stub, 0)
            cmt = idc.get_cmt(va_callsite, 0)

            newcmt = cmt

            # Remove automated comments
            if newcmt.startswith(g_patched_call_cmt):
                newcmt = newcmt[newcmt.find('\n') + 1:]
                if newcmt.find('\n') == -1:
                    newcmt = ''
                else:
                    newcmt = newcmt[newcmt.find('\n') + 1:]
                if newcmt.startswith(g_cmt_pointed):
                    if newcmt.find('\n') == -1:
                        newcmt = ''
                    else:
                        newcmt = newcmt[newcmt.find('\n') + 1:]

            if newcmt != cmt:
                idc.set_cmt(va_callsite, newcmt, 0)

            if idc.get_operand_type(va_callsite, 0) == ida_ua.o_mem:
                patch_import(va_callsite, idc.BADADDR)
            elif idc.get_operand_type(va_callsite, 0) == ida_ua.o_reg:
                va_imp = self._get_imp_for_register_call(va_callsite)
                if va_imp:
                    patch_pointer_width(va_imp, idc.BADADDR)
            else:
                revert_patch(va_callsite, size)

        for fva_stub in idautils.Functions():
            for seg in grafted_segs:
                if fva_stub in seg:
                    mykutils.for_each_call_to(do_unpatch_call, fva_stub) 
Example #29
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 #30
Source File: static_opaque_analysis.py    From idasec with GNU Lesser General Public License v2.1 5 votes vote down vote up
def process_program(self):
        funs = list(idautils.Functions())
        nb = len(funs)
        for i, fun in zip(xrange(nb), funs):
            self.process_routine(fun, rtn_i=i+1, total_rtn=nb)
            if self.STOP:
                return