Python idautils.Heads() Examples

The following are 16 code examples of idautils.Heads(). 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 Project: idapyscripts   Author: onethawt   File: dataxrefcounter.py    License: MIT License 6 votes vote down vote up
def dxc_scan_refs(seg, min_refs):
    start = SegStart(seg)
    end = SegEnd(seg)

    data_refs = {}

    for ea in idautils.Heads(start, end):
        gen_xrefs = XrefsTo(ea, 0)
        for xx in gen_xrefs:
            if ea in data_refs.keys():
                data_refs[ea] = data_refs[ea] + 1
            else:
                data_refs[ea] = 1

    data_refs = sorted(data_refs.items(), key=operator.itemgetter(1))
    data_refs = filter(lambda x: x[1] >= min_refs, data_refs)

    return data_refs 
Example #2
Source Project: idataco   Author: jjo-sec   File: interesting_xor.py    License: 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 #3
Source Project: CASC   Author: Cisco-Talos   File: casc_plugin.py    License: GNU General Public License v2.0 6 votes vote down vote up
def subsignature_selected(self, item):
        try:
            match = self.matches[item.subsignature_name]
            self.match_label.setText("Match:   EA: 0x%08x  Length: % 4d     Bytes: %s" % \
                    (match["ea"], len(match["data"]), " ".join("%02x" % ord(x) for x in match["data"])))
            idc.Jump(match["ea"])
            for ea, color in self.previous_colors:
                idc.SetColor(ea, idc.CIC_ITEM, color)
            self.previous_colors = []
            for ea in idautils.Heads(match["ea"], match["ea"] + len(match["data"])):
                self.previous_colors.append((ea, idc.GetColor(ea, idc.CIC_ITEM)))
                idc.SetColor(ea, idc.CIC_ITEM, SIGALYZER_COLOR_HIGHLIGHTED)
        except KeyError:
            self.match_label.setText("No match")
            for ea, color in self.previous_colors:
                idc.SetColor(ea, idc.CIC_ITEM, color)
            self.previous_colors = []
        except IndexError:
            log.exception("While selecting subsignature") 
Example #4
Source Project: IDAmetrics   Author: mxmssh   File: lib_parser.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def get_list_of_function_instr(addr, mode):
    #TODO follow subcalls MODE_INSTRUMENT_SUBCALLS
    f_start = addr
    f_end = idc.FindFuncEnd(addr)
    chunks = enumerate_function_chunks(f_start)
    list_of_addr = list()
    image_base = idaapi.get_imagebase(addr)
    for chunk in chunks:
        for head in idautils.Heads(chunk[0], chunk[1]):
            # If the element is an instruction
            if head == hex(0xffffffffL):
                raise Exception("Invalid head for parsing")
            if isCode(idc.GetFlags(head)):
                head = head - image_base
                head = str(hex(head))
                head = head.replace("L", "")
                head = head.replace("0x", "")
                list_of_addr.append(head)
    return list_of_addr 
Example #5
Source Project: flare-ida   Author: fireeye   File: shellcode_hash_search.py    License: 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 Project: idawilli   Author: williballenthin   File: color.py    License: Apache License 2.0 5 votes vote down vote up
def enum_heads():
    for segment in enum_segments():
        for head in idautils.Heads(segment.start, segment.end):
            yield head 
Example #7
Source Project: GhIDA   Author: Cisco-Talos   File: idaxml.py    License: Apache License 2.0 5 votes vote down vote up
def check_if_seg_contents(self, seg):
        """
        Determines if any address in a segment contains a value.

        Args:
            seg: IDA segment object

        Returns:
            True if any address in a segment contains a value.
            False if no address in a segment contains a value.
        """
        for addr in idautils.Heads(seg.start_ea, seg.end_ea):
            if idc.has_value(idc.get_full_flags(addr)) == True:
                return True
        return False 
Example #8
Source Project: DIE   Author: ynvb   File: BpHandler.py    License: MIT License 5 votes vote down vote up
def setBPs(self):
        """
        Set breakpoints on all CALL and RET instructions in all of the executable sections.
        """
        for seg_ea in idautils.Segments():
            for head in idautils.Heads(seg_ea, idc.SegEnd(seg_ea)):
                if idc.isCode(idc.GetFlags(head)):
                    # Add BP if instruction is a CALL
                    if is_call(head):
                        self.addBP(head) 
Example #9
Source Project: DIE   Author: ynvb   File: BpHandler.py    License: MIT License 5 votes vote down vote up
def walk_function(self, ea):
        """
        Walk function and place breakpoints on every call function found within it.
        @param ea: An effective address within the function.
        @return: True if function walked succeeded or False otherwise
        """
        try:
            function_name = get_function_name(ea)
            self.logger.debug("Walking function %s at address %s for breakpoints", function_name, hex(ea))

            if function_name in self.walked_functions:
                self.logger.debug("No breakpoints will be set in function %s, "
                                  "since it was already walked before.", function_name)
                return True

            # Add function to walked function list
            self.walked_functions[function_name] = ea

            # function = sark.Function(ea)
            # for line in function.lines:
            #     if line.is_code and line.insn.is_call:
            #         self.addBP(line.ea)
            start_adrs = get_function_start_address(ea)
            end_adrs = get_function_end_address(ea)

            # Walk function and place breakpoints on every call instruction found.
            for head in idautils.Heads(start_adrs, end_adrs):
                if idc.isCode(idc.GetFlags(head)):
                    # Add BP if instruction is a CALL
                    if is_call(head):
                        self.addBP(head)

            self.logger.debug("Function %s was successfully walked for breakpoints", function_name)
            return True

        except Exception as ex:
            self.logger.exception("Failed walking function at address %s for breakpoints.", hex(ea))
            return False 
Example #10
Source Project: CASC   Author: Cisco-Talos   File: casc_plugin.py    License: GNU General Public License v2.0 5 votes vote down vote up
def yara_match(self, strings):
        if isinstance(self.signatures_list.currentItem().parsed_signature, LdbSignature):
            self.matches = dict((x["identifier"], x) for x in strings)
        else:
            self.matches = {}
            self.match_label.setText("Match:   EA: 0x%08x  Length: % 4d     Bytes: %s" % \
                    (strings[0]["ea"], len(strings[0]["data"]), " ".join("%02x" % ord(x) for x in strings[0]["data"])))
            idc.Jump(strings[0]["ea"])
            for ea in idautils.Heads(strings[0]["ea"], strings[0]["ea"] + len(strings[0]["data"])):
                self.previous_colors.append((ea, idc.GetColor(ea, idc.CIC_ITEM)))
                idc.SetColor(ea, idc.CIC_ITEM, SIGALYZER_COLOR_HIGHLIGHTED) 
Example #11
Source Project: rematch   Author: nirizr   File: assembly.py    License: GNU General Public License v3.0 5 votes vote down vote up
def data(self):
    func = ida_funcs.get_func(self.offset)

    def clean(asm):
      """This removes markers of function offsets, including hidden variable
      length offsets that are of different length on 32 and 64 bit address IDA.
      Otherwise, IDA of different offset lengths will truncate incorrect number
      of bytes"""
      hex_chars = int(log(ida_idaapi.BADADDR + 1, 2) / 4)
      pattern = "\x01\\([0-9a-zA-Z]{%s}(.*?)\x02\\)" % hex_chars
      replace = r"\g<1>"
      return re.sub(pattern, replace, asm)

    # make sure only nodes inside the function are accounted for
    # this solves cascaded functions (when multiple functions share same ends)
    def node_contained(node):
      return (ida_funcs.func_contains(func, node.startEA) and
              ida_funcs.func_contains(func, node.endEA - 1))
    nodes = filter(node_contained, ida_gdl.FlowChart(func))
    node_ids = map(lambda n: n.id, nodes)

    nodes_data = []
    for node in nodes:
      assembly = [clean(ida_lines.generate_disasm_line(ea))
                    for ea in idautils.Heads(node.startEA, node.endEA)]
      successive_nodes = [succ.id
                            for succ in node.succs()
                            if succ.id in node_ids]
      serialized_node = {'id': node.id, 'type': node.type,
                         'start': node.startEA, 'end': node.endEA,
                         'successive': successive_nodes, 'assembly': assembly}
      nodes_data.append(serialized_node)

    return nodes_data 
Example #12
Source Project: Stingray   Author: darx0r   File: Stingray.py    License: GNU General Public License v3.0 5 votes vote down vote up
def find_function_strings( func_ea ):

    end_ea = idc.FindFuncEnd(func_ea)
    if end_ea == idaapi.BADADDR: return

    strings = []
    for line in idautils.Heads(func_ea, end_ea):
        refs = idautils.DataRefsFrom(line)
        for ref in refs:
            try:
                strings.append( String(line, ref) )
            except StringParsingException:
                continue

    return strings 
Example #13
Source Project: Stingray   Author: darx0r   File: Stingray.py    License: GNU General Public License v3.0 5 votes vote down vote up
def find_function_callees( func_ea, maxlvl ):

    callees = []
    visited = set()
    pending = set( (func_ea,) )
    lvl = 0

    while len(pending) > 0:
        func_ea = pending.pop()
        visited.add(func_ea)

        func_name = idc.GetFunctionName(func_ea)
        if not func_name: continue
        callees.append(func_ea)

        func_end = idc.FindFuncEnd(func_ea)
        if func_end == idaapi.BADADDR: continue

        lvl +=1
        if lvl >= maxlvl: continue

        all_refs = set()
        for line in idautils.Heads(func_ea, func_end):

            if not ida_bytes.isCode(get_flags(line)): continue

            ALL_XREFS = 0
            refs = idautils.CodeRefsFrom(line, ALL_XREFS)
            refs = set( filter( lambda x: not (x >= func_ea and x <= func_end), 
                                refs) )
            all_refs |= refs

        all_refs -= visited
        pending |= all_refs

    return callees 
Example #14
Source Project: IDAmetrics   Author: mxmssh   File: IDAMetrics_static.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_bbls(self, chunks, boundaries, edges):
        """
        Set bbls using edges and boundaries
        @chunks - a list of function chunks
        @boundaries - a list of function boundaries (see get_static_metrics)
        @edges - a list of function edges (see get_static_metrics)
        @return - a set of bbls boundaries
        """
        bbls = []
        bbl = []
        # NOTE: We can handle if jump xrefs to chunk address space.
        for chunk in chunks:
            for head in idautils.Heads(chunk[0], chunk[1]):
                if head in boundaries or head in edges:
                    if len(bbl) > 0:
                        bbls.append(bbl)
                        bbl = []
                    bbl.append(hex(head))
                elif GetInstructionType(head) == BRANCH_INSTRUCTION:
                    bbl.append(hex(head))
                    bbls.append(bbl)
                    bbl = []
                else:
                    bbl.append(hex(head))
        # add last basic block
        if len(bbl) > 0:
            bbls.append(bbl)
        return bbls 
Example #15
Source Project: smda   Author: danielplohmann   File: IdaInterface.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def getBlocks(self, function_offset):
        blocks = []
        function_chart = ida_gdl.FlowChart(ida_funcs.get_func(function_offset))
        for block in function_chart:
            extracted_block = []
            for instruction in idautils.Heads(block.start_ea, block.end_ea):
                if ida_bytes.is_code(ida_bytes.get_flags(instruction)):
                    extracted_block.append(instruction)
            if extracted_block:
                blocks.append(extracted_block)
        return sorted(blocks) 
Example #16
Source Project: smda   Author: danielplohmann   File: IdaInterface.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def getBlocks(self, function_offset):
        blocks = []
        function_chart = idaapi.FlowChart(idaapi.get_func(function_offset))
        for block in function_chart:
            extracted_block = []
            for instruction in idautils.Heads(block.startEA, block.endEA):
                if idc.isCode(idc.GetFlags(instruction)):
                    extracted_block.append(instruction)
            if extracted_block:
                blocks.append(extracted_block)
        return sorted(blocks)