Python idautils.Segments() Examples

The following are 30 code examples of idautils.Segments(). 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: dump_section_list.py    From python-idb with Apache License 2.0 8 votes vote down vote up
def print_section_list():
    for s in idautils.Segments():
        seg = idaapi.getseg(s)
        print("%s" % idc.SegName(s))
        print(" - start address: 0x%x" % seg.startEA)
        print(" - sclass: 0x%x" % seg.sclass)
        print(" - orgbase: 0x%x" % seg.orgbase)
        print(" - flags: 0x%x" % seg.flags)
        print(" - align: 0x%x" % seg.align)
        print(" - comb: 0x%x" % seg.comb)
        print(" - perm: 0x%x" % seg.perm)
        print(" - bitness: 0x%x" % seg.bitness)
        print(" - sel: 0x%x" % seg.sel)
        # print(' - defsr: 0x%x' % seg.defsr)
        print(" - type: 0x%x" % seg.type)
        print(" - color: 0x%x" % seg.color) 
Example #2
Source File: ida_export.py    From bnida with MIT License 7 votes vote down vote up
def get_sections():
    """
    Get section names and start/end addrs from IDA database

    :return: Dict containing section info
    """

    sections = {}
    for ea in idautils.Segments():
        segm = ida_segment.getseg(ea)
        name = ida_segment.get_segm_name(segm)
        if name == 'LOAD':
            continue

        curr = {}
        curr['start']  = segm.start_ea
        curr['end']    = segm.end_ea
        sections[name] = curr

    return sections 
Example #3
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 #4
Source File: jayutils.py    From flare-ida with Apache License 2.0 6 votes vote down vote up
def getx86CodeSize(ea=None):
    '''
    For a given EA, finds the code size. Returns 16 for-16bit, 32 for 32-bit, or 64 for 64-bit.
    If no EA is given, searches through all segments for a code segment to use.
    '''
    if using_ida7api:
        return getx86CodeSize_ida7(ea)
    if ea is None:
        for seg in idautils.Segments():
            if idc.GetSegmentAttr(seg, idc.SEGATTR_TYPE) == idc.SEG_CODE:
                ea = seg
                break
    if ea is None:
        raise RuntimeError('Could not find code segment to use for getx86CodeSize')
    bitness = idc.GetSegmentAttr(ea, idc.SEGATTR_BITNESS)
    if bitness == 0:
        return 16
    elif bitness == 1:
        return 32
    elif bitness == 2:
        return 64
    raise RuntimeError('Bad bitness') 
Example #5
Source File: ida_export.py    From bnida with MIT License 6 votes vote down vote up
def get_line_comments():
    """
    Iterate through every address in a segment and check for comments

    :return: Dict containing line comments
    """

    last_comment = ''
    comments = {}
    for ea in idautils.Segments():
        segm = ida_segment.getseg(ea)
        name = ida_segment.get_segm_name(segm)
        if name == 'LOAD':
            continue

        for i in range(segm.start_ea, segm.end_ea):
            comment = get_single_line_comment(i)
            if comment and comment != last_comment:
                comments[i] = comment
                last_comment = comment

    return comments 
Example #6
Source File: kernel.py    From ida_kernelcache with MIT License 6 votes vote down vote up
def _find_prelink_info_segments():
    """Find all candidate __PRELINK_INFO segments (or sections).

    We try to identify any IDA segments with __PRELINK_INFO in the name so that this function will
    work both before and after automatic rename. A more reliable method would be parsing the
    Mach-O.
    """
    segments = []
    # Gather a list of all the possible segments.
    for seg in idautils.Segments():
        name = idc.SegName(seg)
        if '__PRELINK_INFO' in name or name == '__info':
            segments.append(seg)
    if len(segments) < 1:
        _log(0, 'Could not find any __PRELINK_INFO segment candidates')
    elif len(segments) > 1:
        _log(1, 'Multiple segment names contain __PRELINK_INFO: {}',
                [idc.SegName(seg) for seg in segments])
    return segments 
Example #7
Source File: stub.py    From ida_kernelcache with MIT License 6 votes vote down vote up
def initialize_stub_symbols(make_thunk=True):
    """Populate IDA with information about the stubs in an iOS kernelcache.

    Search through the kernelcache for stubs (__stubs sections) and rename each stub function
    according to the target function it calls.

    Arm64 only.

    Options:
        make_thunk: Set the thunk attribute for each stub function. Default is True.
    """
    next_stub = internal.make_name_generator(kernelcache_stub_suffix)
    for ea in idautils.Segments():
        segname = idc.SegName(ea)
        if not segname.endswith('__stubs'):
            continue
        _log(3, 'Processing segment {}', segname)
        _process_stubs_section(ea, make_thunk, next_stub) 
Example #8
Source File: offset.py    From ida_kernelcache with MIT License 6 votes vote down vote up
def initialize_data_offsets():
    """Convert offsets in data segments into offsets in IDA.

    Segment names must be initialized with segments.initialize_segments() first.
    """
    # Normally, for user-space programs, this operation would be dangerous because there's a good
    # chance that a valid userspace address would happen to show up in regular program data that is
    # not actually an address. However, since kernel addresses are numerically much larger, the
    # chance of this happening is much less.
    for seg in idautils.Segments():
        name = idc.SegName(seg)
        if not (name.endswith('__DATA_CONST.__const') or name.endswith('__got')
                or name.endswith('__DATA.__data')):
            continue
        for word, ea in idau.ReadWords(seg, idc.SegEnd(seg), addresses=True):
            if idau.is_mapped(word, value=False):
                idc.OpOff(ea, 0, 0) 
Example #9
Source File: lib_parser.py    From IDAmetrics with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def find_function(function):
    for seg_ea in idautils.Segments():
        # For each of the functions
        function_ea = seg_ea
        while function_ea != 0xffffffffL:
            function_name = idc.GetFunctionName(function_ea)
            function = function.replace("\n", "")
            function = function.replace("\r", "")
            function = function.replace(" ", "")
            if function.lower() == function_name.lower():
                print "Found function ", function_name
                print hex(function_ea)
                return function_ea
            function_ea = idc.NextFunction(function_ea)  
    return -1 
Example #10
Source File: jayutils.py    From flare-ida with Apache License 2.0 5 votes vote down vote up
def getx86CodeSize_ida7(ea=None):
    '''
    For a given EA, finds the code size. Returns 16 for-16bit, 32 for 32-bit, or 64 for 64-bit.
    If no EA is given, searches through all segments for a code segment to use.
    '''
    if ea is None:
        for seg in idautils.Segments():
            if idc.get_segm_attr(seg, idc.SEGATTR_TYPE) == idc.SEG_CODE:
                ea = seg
                break
    if ea is None:
        raise RuntimeError('Could not find code segment to use for getx86CodeSize')
    bitness = idc.get_segm_attr(ea, idc.SEGATTR_BITNESS)
    if bitness == 0:
        return 16
    elif bitness == 1:
        return 32
    elif bitness == 2:
        return 64
    raise RuntimeError('Bad bitness')

########################################

 
###############################################################################
# Config loggers and add hex dumps to the logger
############################################################################### 
Example #11
Source File: IDAMetrics_static.py    From IDAmetrics with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def start_analysis(self, metrics_used):
        """
        The function starts static metrics analysis.
        @metrics_used - a dictionary of metrics used in the following format {metrics_list element:1 or 0}
        PTAL metrics_list global list and args_parser routine
        @return - None
        """
        self.metrics_mask = metrics_used
        # For each of the segments
        for seg_ea in idautils.Segments():
            # For each of the functions
            function_ea = seg_ea
            while function_ea != 0xffffffffL:
                function_name = idc.GetFunctionName(function_ea)
                # if already analyzed
                if self.functions.get(function_name, None) != None:
                    function_ea = idc.NextFunction(function_ea)
                    continue
                print "Analysing ", hex(function_ea)
                try:
                    self.functions[function_name] = self.get_static_metrics(function_ea)
                except:
                    print 'Can\'t collect metric for this function ', hex(function_ea)
                    print 'Skip'
                    function_ea = idc.NextFunction(function_ea)
                    continue
                self.collect_total_metrics(function_name)
                function_ea = idc.NextFunction(function_ea)
        self.collect_final_metrics() 
Example #12
Source File: ida_import.py    From bnida with MIT License 5 votes vote down vote up
def adjust_addr(sections, addr):
    """
    Adjust the address if there are differences in section base addresses

    :param sections: Dictionary containing section info
    :param addr: Address that might need adjusted
    :return: Adjusted address
    """

    bn_section_start = None
    section_name = None
    for name, section in sections.items():
        if addr >= int(section['start']) and addr <= int(section['end']):
            bn_section_start = int(section['start'])
            section_name = name
            break

    # Make sure the section was found (this check should always pass)
    if section_name is None:
        print('Section not found in bnida analysis data for addr: {:08x}'.format(addr))
        return None

    # Retrieve section start in IDA and adjust the addr
    ida_sections = idautils.Segments()
    for ea in ida_sections:
        segm = ida_segment.getseg(ea)
        if ida_segment.get_segm_name(segm) == section_name:
            return addr - bn_section_start + segm.start_ea

    print('Section not found - name:{} addr:{:08x}'.format(section_name, addr))
    return None 
Example #13
Source File: findcrypt3.py    From findcrypt-yara with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _get_memory(self):
        result = bytearray()
        segment_starts = [ea for ea in idautils.Segments()]
        offsets = []
        start_len = 0
        for start in segment_starts:
            end = idc.get_segm_attr(start, idc.SEGATTR_END)
            result += ida_bytes.get_bytes(start, end - start)
            offsets.append((start, start_len, len(result)))
            start_len = len(result)
        return bytes(result), offsets 
Example #14
Source File: ida_batch.py    From cosa-nostra with GNU General Public License v3.0 5 votes vote down vote up
def try_search_functions(self):
    MakeUnknown(MinEA(), MaxEA() - MinEA(), DOUNK_EXPAND)
    for ea in idautils.Segments():
      segend = idc.GetSegmentAttr(ea, SEGATTR_END)
      start = ea
      while start < segend:
        if Byte(start) == 0xCC:
          start += 1
          continue

        MakeFunction(start)
        MakeCode(start)
        start = FindUnexplored(start+1, SEARCH_DOWN) 
Example #15
Source File: IdaTools.py    From apiscout with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def getAllMemoryFromIda(self):
        self.ida_proxy = IdaProxy()
        result = {}
        seg_start = [ea for ea in idautils.Segments()][0]
        current_start = seg_start
        seg_end = self.ida_proxy.getSegEnd(current_start)
        current_buffer = ""
        for index, current_start in enumerate(idautils.Segments()):
            # get current buffer content
            current_buffer = ""
            for ea in lrange(current_start, self.ida_proxy.getSegEnd(current_start)):
                current_buffer += chr(self.ida_proxy.getByte(ea))
            # first buffer is only saved
            if index == 0:
                result[seg_start] = current_buffer
                continue
            # otherwise decide if the buffers are consecutive and either save or update contents
            if current_start != seg_end:
                seg_start = current_start
                result[seg_start] = current_buffer
            else:
                result[seg_start] += current_buffer
            seg_end = self.ida_proxy.getSegEnd(current_start)
        # convert to bytes
        if sys.version_info > (3,):
            for segment_offset, data in result.items():
                if isinstance(data, str):
                    result[segment_offset] = bytes([ord(c) for c in data])
        return result 
Example #16
Source File: IdaTools.py    From apiscout with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def getBaseAddress(self):
        return [ea for ea in idautils.Segments()][0] 
Example #17
Source File: IdaTools.py    From apiscout with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def getLastAddress(self):
        return self.ida_proxy.getSegEnd([ea for ea in idautils.Segments()][-1]) - 1 
Example #18
Source File: IdaForm.py    From apiscout with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, title, api_results, flags=0):
        Choose.__init__(self,
                         title,
                         [["#", 6], ["Offset", 14], ["API Address", 14], ["DLL", 20], ["API", 35]],
                         embedded=True, width=140, height=20, flags=flags)
        self.row_count = 0
        self.base_address = [ea for ea in idautils.Segments()][0]
        self.scout = ApiScout()
        self.scout.setBaseAddress(self.base_address)
        self.api_results = api_results
        self.all_items = self.populate(api_results)
        self.items = self.populate(api_results)
        self.icon = 4
        self.selcount = 0 
Example #19
Source File: IdaInterface.py    From smda with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def getBaseAddr(self):
        base_addr = 0
        segment_starts = [ea for ea in idautils.Segments()]
        if segment_starts:
            first_segment_start = segment_starts[0]
            # re-align by 0x10000 to reflect typically allocation behaviour for IDA-mapped binaries
            first_segment_start = (first_segment_start / 0x10000) * 0x10000
            base_addr = int(first_segment_start)
        return base_addr 
Example #20
Source File: IdaInterface.py    From smda with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def getBaseAddr(self):
        segment_starts = [ea for ea in idautils.Segments()]
        first_segment_start = segment_starts[0]
        # re-align by 0x10000 to reflect typically allocation behaviour for IDA-mapped binaries
        first_segment_start = (first_segment_start / 0x10000) * 0x10000
        return int(first_segment_start) 
Example #21
Source File: IdaInterface.py    From smda with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def getBinary(self):
        result = b""
        segment_starts = [ea for ea in idautils.Segments()]
        offsets = []
        start_len = 0
        for start in segment_starts:
            end = idc.SegEnd(start)
            result += idc.get_bytes(start, end - start)
            offsets.append((start, start_len, len(result)))
            start_len = len(result)
        return result 
Example #22
Source File: objc2_analyzer.py    From flare-ida with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        self.magicMask64 = 0xabbadabbad000000
        self.magicMask32 = 0xabba0000
        self.magicMaskMask64 = 0xffffffffffff0000
        self.magicMaskMask32 = 0xffff0000
        self.callMnems = ["call", "jmp", "BL", "BLX", "BLEQ", "BLXEQ", "BLR", "BLREQ", "B"]
        self.objcData = None
        self.objcSelRefs = None
        self.objcMsgRefs = None
        self.objcConst = None
        self.objcClassRefs = None
        self.objcCatList = None
        self.fixedSelXRefs = []
        self.ivarSetters = {}
        self.notIvarSetters = []
        for segVA in idautils.Segments():
            segName = idc.get_segm_name(segVA)
            endVA = idc.get_segm_end(segVA)
            if segName == "__objc_data":
                self.objcData = (segVA, endVA)
            elif segName == "__objc_selrefs":
                self.objcSelRefs = (segVA, endVA)
            elif segName == "__objc_msgrefs":
                self.objcMsgRefs = (segVA, endVA)
            elif segName == "__objc_const":
                self.objcConst = (segVA, endVA)
            elif segName == "__objc_classrefs":
                self.objcClassRefs = (segVA, endVA)
            elif segName == "__objc_catlist":
                self.objcCatList = (segVA, endVA)
        if self.objcSelRefs or self.objcMsgRefs:
            self.processObjc()
        else:
            logging.debug("this Mach-O does not implement any Objective-C classes")
    
    # it appears idc.get_name_ea_simple does not work for selector reference names that end in "_" 
Example #23
Source File: objc2_xrefs_helper.py    From flare-ida with Apache License 2.0 5 votes vote down vote up
def find_all_segments(self,segment_names):
        segments={name:None for name in segment_names}
        for seg_va in Segments():
            seg_name=SegName(seg_va)
            if seg_name in segment_names:
                segments[seg_name]=(seg_va,SegEnd(seg_va))
        return segments 
Example #24
Source File: __init__.py    From flare-ida with Apache License 2.0 5 votes vote down vote up
def get_end_of_last_segment():
    """ Return the last segment's end address. """
    last_ea = 0
    for segment in idautils.Segments():
        if idc.SegEnd(segment) > last_ea:
            last_ea = idc.SegEnd(segment)
    return last_ea 
Example #25
Source File: __init__.py    From flare-ida with Apache License 2.0 5 votes vote down vote up
def append_segment(segment_name):
    """ Add a new segment to the IDB file and return its starting address.
    Information about function arguments will be stored here. Only works if the
    segment name is not used yet. This does not affect the original binary.

    Arguments:
    segment_name -- the name of the segment to be added
    """
    for segment in idautils.Segments():
        if idc.SegName(segment) == segment_name:
            g_logger.warning('Segment ' + segment_name + ' already exists')
            return idc.SegStart(segment)

    new_segment_start = get_end_of_last_segment()
    g_logger.debug('Adding new segment at 0x%08x' % new_segment_start)
    if not idc.AddSeg(new_segment_start, (new_segment_start+NEW_SEGMENT_SIZE),
                      0, 1, 0, idaapi.scPub) == 1:
        raise FailedToAppendSegmentException('Could not add segment')
    # set new segment's attributes
    if not idc.RenameSeg(new_segment_start, segment_name):
        raise FailedToAppendSegmentException('Could not rename segment')
    if not idc.SetSegClass(new_segment_start, 'DATA'):
        raise FailedToAppendSegmentException('Could not set segment class')
    if not idc.SegAlign(new_segment_start, idc.saRelPara):
        raise FailedToAppendSegmentException('Could not align segment')
    if not idc.SetSegAddressing(new_segment_start, 1):  # 1 -- 32 bit
        raise FailedToAppendSegmentException(
            'Could not set segment addressing')
    return new_segment_start 
Example #26
Source File: shellcode_hash_search.py    From flare-ida with Apache License 2.0 5 votes vote down vote up
def processAllSegments(self):
        for seg in idautils.Segments():
            if using_ida7api:
                segStart = idc.get_segm_start(seg)
                segEnd = idc.get_segm_end(seg)
            else:
                segStart = idc.SegStart(seg)
                segEnd = idc.SegEnd(seg)

            if self.params.searchPushArgs:
                self.lookForOpArgs(segStart, segEnd)
            if self.params.searchDwordArray:
                self.lookForDwordArray(segStart, segEnd) 
Example #27
Source File: jayutils.py    From flare-ida with Apache License 2.0 5 votes vote down vote up
def isValidPointer(va):
    if using_ida7api:
        return isValidPointer_ida7(va)
    for segStart in idautils.Segments():
        if (va >= segStart) and (va < idc.SegEnd(segStart)):
            return True
    return False 
Example #28
Source File: jayutils.py    From flare-ida with Apache License 2.0 5 votes vote down vote up
def isValidPointer_ida7(va):
    for segStart in idautils.Segments():
        if (va >= segStart) and (va < idc.get_segm_end(segStart)):
            return True
    return False

######################################## 
Example #29
Source File: luac_proc.py    From lua_re with GNU Affero General Public License v3.0 5 votes vote down vote up
def init_seginfo(self):
        #print("seg len:%d\n" % len(list(idautils.Segments())))
        for seg in idautils.Segments():
            segname = idc.SegName(seg)
            if segname.startswith('func_'):
                self.segstarts[idc.SegStart(seg)] = segname
                self.segends[idc.SegEnd(seg)] = segname
                #print("segname:%s\n" % segname)
                #print("add_func() called ret:%d" % add_func(idc.SegStart(seg), idc.SegEnd(seg))) 
Example #30
Source File: util.py    From mcsema with Apache License 2.0 5 votes vote down vote up
def get_destructor_segment():
  """Returns the start address of the global destructor section"""
  for seg_ea in idautils.Segments():
    seg_name = idc.get_segm_name(seg_ea).lower()
    if seg_name in [".fini_array", ".dtor"]:
      return seg_ea;