Python idc.SegStart() Examples

The following are 24 code examples of idc.SegStart(). 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: 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 #2
Source File: dsc_fix.py    From dsc_fix with GNU General Public License v3.0 6 votes vote down vote up
def map_exports(exports, verbose=True):
    """ gets an array of [(vaddress, name),..] and writes it to db"""
    if verbose:
        print "[+] going for %d exports" % (len(exports))
    for addr, export_name in exports:
        print "[+] creating export", export_name
        # check that there are no existing segments in that address
        if idc.SegStart(addr) == idc.BADADDR:
            print "[+] creating seg: 0x%08X: %d" % (addr, 4)
            idc.AddSegEx(addr,
                         addr + 4, 0, 0,
                         idaapi.saRelPara, idaapi.scPub,
                         idc.ADDSEG_FILLGAP)
        elif verbose:
            print "[!] Skipping creation of existing segment.."
        # set it as execuable
        idc.SetSegmentAttr(addr, idc.SEGATTR_PERM, SEGPERM_EXEC)
        if verbose:
            print "[+] making name: %s" % (export_name)
        make_name(addr, export_name) 
Example #3
Source File: shellcode_hash_search.py    From flare-ida with Apache License 2.0 6 votes vote down vote up
def processCode(self):
        if (self.params.startAddr==idc.BADADDR) and (self.params.endAddr==idc.BADADDR):

            if using_ida7api:
                self.params.startAddr = idc.get_segm_start(idc.here())
                self.params.endAddr = idc.get_segm_end(idc.here())
            else:
                self.params.startAddr = idc.SegStart(idc.here())
                self.params.endAddr = idc.SegEnd(idc.here())
            logger.info('Processing current segment only: 0x%08x - 0x%08x', self.params.startAddr, self.params.endAddr)
        else:
            logger.info('Processing range 0x%08x - 0x%08x', self.params.startAddr, self.params.endAddr)
        if self.params.searchDwordArray:
            self.lookForDwordArray(self.params.startAddr, self.params.endAddr)
        if self.params.searchPushArgs:
            self.lookForOpArgs(self.params.startAddr, self.params.endAddr) 
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: tagged_pointers.py    From ida_kernelcache with MIT License 5 votes vote down vote up
def untag_pointers():
    _log(2, 'Starting tagged pointer conversion')
    for seg in idautils.Segments():
        untag_pointers_in_range(idc.SegStart(seg), idc.SegEnd(seg))
    _log(2, 'Tagged pointer conversion complete') 
Example #6
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 #7
Source File: dsc_fix.py    From dsc_fix with GNU General Public License v3.0 5 votes vote down vote up
def map_segments(segments, dsc_file, verbose=True):
    for segaddr, segsize, segdata in segments:
        print "[+] creating seg: 0x%08X: %d" % (segaddr, segsize)
        # check that there are no existing segments in that address
        if idc.SegStart(segaddr) == idc.BADADDR:
            idc.AddSegEx(segaddr,
                         segaddr + segsize, 0, 0,
                         idaapi.saRelPara, idaapi.scPub,
                         idc.ADDSEG_FILLGAP)
            # set it as read-only
            idc.SetSegmentAttr(segaddr, idc.SEGATTR_PERM, SEGPERM_READ)
        else:
            print "[!] Skipping creation of existing segment.."

        # after mapping the segment, write the data to the db.
        try:
            for addr, size, macho_offset in segdata:
                dsc_file.seek(macho_offset)
                memcpy(addr, dsc_file.read(size))
                if verbose:
                    print "0x%X, 0x%06X, 0x%06X: %s" % (addr,
                                                        size,
                                                        macho_offset,
                                                        dsc_file.read(size))
        except Exception:
            print segdata
            raise 
Example #8
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 #9
Source File: idasec_core.py    From idasec with GNU Lesser General Public License v2.1 5 votes vote down vote up
def update_mapping(self):
        pass
        self.fun_mapping = {idc.GetFunctionName(x): (idaapi.get_func(x).startEA, idaapi.get_func(x).endEA-1) for x in
                            idautils.Functions()}
        self.seg_mapping = {idc.SegName(x): (idc.SegStart(x), idc.SegEnd(x)) for x in idautils.Segments()} 
Example #10
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 #11
Source File: __init__.py    From flare-ida with Apache License 2.0 5 votes vote down vote up
def expand_segment(ea):
    """ Expand last segment so it can hold more MSDN argument information.

    Argument:
    ea -- effective address within last segment
    """
    start = idc.SegStart(ea)
    end = idc.SegEnd(ea)
    if end != get_end_of_last_segment():
        raise FailedToExpandSegmentException('Can only expand last segment.')
    if start == idaapi.BADADDR or end == idaapi.BADADDR:
        raise FailedToExpandSegmentException('Invalid start or end address.')
    new_end = end + NEW_SEGMENT_SIZE / 2
    if not idc.SetSegBounds(ea, start, new_end, idaapi.SEGMOD_KEEP):
        raise FailedToExpandSegmentException('Setting segment bounds failed.') 
Example #12
Source File: util.py    From mcsema with Apache License 2.0 5 votes vote down vote up
def is_code(ea):
  if is_invalid_ea(ea):
    return False

  seg_ea = idc.SegStart(ea)
  seg_type = idc.GetSegmentAttr(seg_ea, idc.SEGATTR_TYPE)
  return seg_type == idc.SEG_CODE

# A stricter form of `is_code`, where we also check whether IDA thinks something
# is code. IDA is able to identify some things like embedded exception tables
# in the code section as not truly being code. 
Example #13
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 #14
Source File: ida.py    From bap-ida-python with MIT License 5 votes vote down vote up
def addresses():
    """Generate all mapped addresses."""
    for s in idautils.Segments():
        ea = idc.SegStart(s)
        while ea < idc.SegEnd(s):
            yield ea
            ea = idaapi.nextaddr(ea) 
Example #15
Source File: util.py    From mcsema with Apache License 2.0 5 votes vote down vote up
def is_invalid_ea(ea):
  """Returns `True` if `ea` is not valid, i.e. it doesn't point into any
  valid segment."""
  if idc.BADADDR == ea:
    return True

  try:
    idc.GetSegmentAttr(idc.SegStart(ea), idc.SEGATTR_TYPE)
    return False  # If we get here, then it must be a valid ea!
  except:
    return True 
Example #16
Source File: idb_indexer.py    From idsearch with GNU General Public License v3.0 5 votes vote down vote up
def iter_lines():
    """
    Iterate through all line addresses in the IDB
    Yields addresses of all lines.
    """
    for ea in idautils.Segments():
        seg_start = idc.SegStart(ea)
        seg_end = idc.SegEnd(ea)

        cur_addr = seg_start
        while (cur_addr < seg_end) and (cur_addr != idaapi.BADADDR):
            yield cur_addr
            cur_addr = idc.NextHead(cur_addr) 
Example #17
Source File: exception.py    From mcsema with Apache License 2.0 5 votes vote down vote up
def recover_frame_entries(seg_ea):
  if seg_ea == idc.BADADDR:
    return

  DEBUG("Recover entries from section : {}".format(idc.SegName(seg_ea)))
  ea = idc.SegStart(seg_ea)
  end_ea = idc.SegEnd(seg_ea)
  while ea != idc.BADADDR and ea < end_ea:
    ea = format_entries(ea) 
Example #18
Source File: util.py    From mcsema with Apache License 2.0 5 votes vote down vote up
def make_xref(from_ea, to_ea, xref_constructor, xref_size):
  """Force the data at `from_ea` to reference the data at `to_ea`."""
  if not idc.GetFlags(to_ea) or is_invalid_ea(to_ea):
    DEBUG("  Not making reference (A) from {:x} to {:x}".format(from_ea, to_ea))
    return

  make_head(from_ea)

  if is_code(from_ea):
    _CREFS_FROM[from_ea].add(to_ea)
    _CREFS_TO[to_ea].add(from_ea)
  else:
    _DREFS_FROM[from_ea].add(to_ea)
    _DREFS_TO[to_ea].add(from_ea)

  # If we can't make a head, then it probably means that we're at the
  # end of the binary, e.g. the last thing in the `.extern` segment.
  if not make_head(from_ea + xref_size):
    assert idc.BADADDR == idc.SegStart(from_ea + xref_size)

  idaapi.do_unknown_range(from_ea, xref_size, idc.DOUNK_EXPAND)
  xref_constructor(from_ea)
  if not is_code_by_flags(from_ea):
    idc.add_dref(from_ea, to_ea, idc.XREF_USER|idc.dr_O)
  else: 
    DEBUG("  Not making reference (B) from {:x} to {:x}".format(from_ea, to_ea)) 
Example #19
Source File: util.py    From mcsema with Apache License 2.0 5 votes vote down vote up
def is_constructor_segment(ea):
  """Returns `True` if the segment containing `ea` belongs to global constructor section"""
  seg_ea = idc.SegStart(ea)
  seg_name = idc.SegName(seg_ea).lower()
  if seg_name in [".init_array", ".ctor"]:
    return True
  return False 
Example #20
Source File: util.py    From mcsema with Apache License 2.0 5 votes vote down vote up
def is_external_segment(ea):
  """Returns `True` if the segment containing `ea` looks to be solely containing
  external references."""
  global _NOT_EXTERNAL_SEGMENTS

  seg_ea = idc.SegStart(ea)
  if seg_ea in _NOT_EXTERNAL_SEGMENTS:
    return False

  if seg_ea in _EXTERNAL_SEGMENTS:
    return True

  if is_external_segment_by_flags(ea):
    _EXTERNAL_SEGMENTS.add(seg_ea)
    return True

  ext_types = []
  seg_name = idc.SegName(seg_ea).lower()
  
  if IS_ELF:
    if ".got" in seg_name or ".plt" in seg_name:
      _EXTERNAL_SEGMENTS.add(seg_ea)
      return True

  elif IS_PE:
    if ".idata" == seg_name:  # Import table.
      _EXTERNAL_SEGMENTS.add(seg_ea)
      return True

  _NOT_EXTERNAL_SEGMENTS.add(seg_ea)
  return False 
Example #21
Source File: util.py    From mcsema with Apache License 2.0 5 votes vote down vote up
def is_external_segment_by_flags(ea):
  """Returns `True` if IDA believes that `ea` belongs to an external segment."""
  try:
    seg_ea = idc.SegStart(ea)
    seg_type = idc.GetSegmentAttr(seg_ea, idc.SEGATTR_TYPE)
    if seg_type == idc.SEG_XTRN:
      _EXTERNAL_SEGMENTS.add(seg_ea)
      return True
    else:
      return False
  except:
    return False 
Example #22
Source File: segment.py    From ida_kernelcache with MIT License 4 votes vote down vote up
def _initialize_segments_in_kext(kext, mach_header, skip=[]):
    """Rename the segments in the specified kext."""
    def log_seg(segname, segstart, segend):
        _log(3, '+ segment {: <20} {:x} - {:x}  ({:x})', segname, segstart, segend,
            segend - segstart)
    def log_sect(sectname, sectstart, sectend):
        _log(3, '  section {: <20} {:x} - {:x}  ({:x})', sectname, sectstart, sectend,
                sectend - sectstart)
    def log_gap(gapno, start, end, mapped):
        mapped = 'mapped' if mapped else 'unmapped'
        _log(3, '  gap     {: <20} {:x} - {:x}  ({:x}, {})', gapno, start, end,
            end - start, mapped)
    def process_region(segname, name, start, end):
        assert end >= start
        if segname in skip:
            _log(2, 'Skipping segment {}', segname)
            return
        newname = '{}.{}'.format(segname, name)
        if kext:
            newname = '{}:{}'.format(kext, newname)
        if start == end:
            _log(2, 'Skipping empty region {} at {:x}', newname, start)
            return
        ida_segstart = idc.SegStart(start)
        if ida_segstart == idc.BADADDR:
            _log(0, "IDA doesn't think this is a real segment: {:x} - {:x}", start, end)
            return
        ida_segend = idc.SegEnd(ida_segstart)
        if start != ida_segstart or end != ida_segend:
            _log(0, 'IDA thinks segment {} {:x} - {:x} should be {:x} - {:x}', newname, start, end,
                    ida_segstart, ida_segend)
            return
        _log(2, 'Rename {:x} - {:x}: {} -> {}', start, end, idc.SegName(start), newname)
        idc.SegRename(start, newname)
    def process_gap(segname, gapno, start, end):
        mapped = idau.is_mapped(start)
        log_gap(gapno, start, end, mapped)
        if mapped:
            name = 'HEADER' if start == mach_header else '__gap_' + str(gapno)
            process_region(segname, name, start, end)
    for segname, segstart, segend, sects in _macho_segments_and_sections(mach_header):
        log_seg(segname, segstart, segend)
        lastend = segstart
        gapno   = 0
        for sectname, sectstart, sectend in sects:
            if lastend < sectstart:
                process_gap(segname, gapno, lastend, sectstart)
                gapno += 1
            log_sect(sectname, sectstart, sectend)
            process_region(segname, sectname, sectstart, sectend)
            lastend = sectend
        if lastend < segend:
            process_gap(segname, gapno, lastend, segend)
            gapno += 1 
Example #23
Source File: vtableAddress.py    From Virtuailor with GNU General Public License v3.0 4 votes vote down vote up
def write_vtable2file(start_addr):
    """
    :param start_addr: The start address of the virtual call
    :return: The break point condition and the break point address
    """
    raw_opnd = idc.print_operand(start_addr, 0)
    if raw_opnd in REGISTERS:
        reg = raw_opnd
    else:
        for reg in REGISTERS:
            if raw_opnd.find(reg) != -1:
                break
    opnd = get_con2_var_or_num(reg, start_addr)
    reg_vtable = opnd[0]
    offset = opnd[1]
    bp_address = opnd[2]
    set_bp = True
    cond = ""
    # TODO check the get_con2 return variables!!@
    try:
        # TODO If a structure was already assigned to the BP (not by Virtuailor), before running the code the code will\
        # assume it was examined by the user, the BP will not be set
        arch_dct = get_arch_dct()
        plus_indx = raw_opnd.find(arch_dct["separator"])
        if plus_indx != -1:
            call_offset = raw_opnd[plus_indx + 1:raw_opnd.find(']')]
            # if the offset is in hex
            if call_offset.find('h') != -1:
                call_offset = int(call_offset[:call_offset.find('h')], 16)
        if offset.find('h') != -1:
            offset = str(int(offset[:offset.find('h')], 16))
        elif offset.find('0x') != -1:
            offset = str(int(offset[offset.find('0x') + 2:], 16))
    except ValueError:
        # A offset structure was set, the old offset will be deleted
        set_bp = False
    finally:
        if set_bp:
            # start_addr = start_addr - idc.SegStart(start_addr)
            if reg_vtable in REGISTERS:
                cond = get_bp_condition(start_addr, reg_vtable, offset)
    return cond, bp_address 
Example #24
Source File: util.py    From mcsema with Apache License 2.0 4 votes vote down vote up
def get_function_bounds(ea):
  """Get the bounds of the function containing `ea`. We want to discover jump
  table targets that are missed by IDA, and it's possible that they aren't
  marked as being part of the current function, and perhaps are after the
  assumed range of the current function. Ideally they will fall before the
  beginning of the next function, though.

  We need to be pretty careful with the case that one function tail-calls
  another. IDA will sometimes treat the end of the tail-called function
  (e.g. a thunk) as if it is the end of the caller. For this reason, we start
  with loose bounds using the prev/next functions, then try to narrow with
  the bounds of the function containing `ea`.

  TODO(pag): Handle discontinuous regions (e.g. because of function chunks).
             It may be worth to return an object here that can we queried
             for membership using the `__in__` method.
  """
  seg_start, seg_end = idc.SegStart(ea), idc.SegEnd(ea)
  min_ea = seg_start
  max_ea = seg_end

  if is_invalid_ea(min_ea) or not is_code(ea):
    return ea, ea

  # Get an upper bound using the next function.
  next_func_ea = idc.NextFunction(ea)
  if not is_invalid_ea(next_func_ea):
    max_ea = min(next_func_ea, max_ea)

  # Get a lower bound using the previous function.
  prev_func_ea = idc.PrevFunction(ea)
  if not is_invalid_ea(prev_func_ea):
    min_ea = max(min_ea, prev_func_ea)
    prev_func = idaapi.get_func(prev_func_ea)
    if prev_func and prev_func.endEA < ea:
      min_ea = max(min_ea, prev_func.endEA)

  # Try to tighten the bounds using the function containing `ea`.
  func = idaapi.get_func(ea)
  if func:
    min_ea = max(min_ea, func.startEA)
    max_ea = min(max_ea, func.endEA)

  return min_ea, max_ea