Exemple #1
0
def apply_labels(fun_names):
    new_sub = 0
    new_som = 0
    new_oth = 0

    named_overwrittens = []

    for f_ea, name in fun_names.iteritems():
        name = re.sub('[^a-zA-Z0-9_]+', '', name)
        curr_name = idaapi.get_func_name(f_ea)
        if curr_name.startswith("sub_"):
            new_sub += 1
        elif "_something" in curr_name:
            new_som += 1
        else:
            new_oth += 1
            named_overwrittens.append(curr_name)
            #so we don't overwrite these
            continue

        # stats counting aside, make sure we don't overwrite non-sub
        # functions from e.g. our IDC assignments
        if not curr_name.startswith("sub_") and not "_something" in curr_name:
            continue

        ret = idc.LocByName(name)
        count = 1
        while (ret != 0xffffffff):
            count += 1
            ret = idc.LocByName(name + "__" + "%d" % count)
        idc.MakeName(f_ea, name + ("__%d" % count) * (count > 1))
def memToLvl(address, levelId = None):
    refTableAddr = idc.LocByName("levelReferenceTable")
    if refTableAddr == BADADDR:
        print("Can't get level reference table address. Make sure its name is levelReferenceTable.")
        return
    
    if levelId == None:
        endTableAddr = idc.LocByName("levelEndTable")
        if endTableAddr == BADADDR:
            print("Can't get level end table address. Make sure its name is levelEndTable.")
            return

        lvl0StartAddr = idc.Dword(refTableAddr)
        lvl1StartAddr = idc.Dword(refTableAddr + 4)

        lvl0EndAddr = idc.Dword(endTableAddr) 
        lvl1EndAddr = idc.Dword(endTableAddr + 4)

        if address >= lvl0StartAddr and address <= lvl0EndAddr:
            fileRelativeAddr = address - lvl0StartAddr 
            idc.Message("Fix.lvl relative address: 0x" + format(fileRelativeAddr, '02X') + "\n")
            return

        if address >= lvl1StartAddr and address <= lvl1EndAddr:
            fileRelativeAddr = address - lvl1StartAddr 
            idc.Message("Actual level relative address: 0x" + format(fileRelativeAddr, '02X') + "\n")
            return

        idc.Message("ERROR: This address does not belong to any level file.")
    else:
        lvlStartAddr = idc.Dword(refTableAddr + levelId * 4)
        fileRelativeAddr = address - lvlStartAddr

        idc.Message("Address relative to file: 0x" + format(fileRelativeAddr, '02X') + "\n") 
Exemple #3
0
    def get_ea_by_name(self, name):
        '''
        Get the address of a location by name.

        @name - Location name

        Returns the address of the named location, or idc.BADADDR on failure.
        '''
        # This allows support of the function offset style names (e.g., main+0C)
        # TODO: Is there something in the IDA API that does this already??
        if '+' in name:
            (func_name, offset) = name.split('+')
            base_ea = idc.LocByName(func_name)
            if base_ea != idc.BADADDR:
                try:
                    ea = base_ea + int(offset, 16)
                except:
                    ea = idc.BADADDR
        else:
            ea = idc.LocByName(name)
            if ea == idc.BADADDR:
                try:
                    ea = int(name, 0)
                except:
                    ea = idc.BADADDR

        return ea
def search_reg():
  global mod_addr_min
  global mod_addr_max

  code_reg = idc.LocByName('g_code_reg')
  meta_reg = idc.LocByName('g_meta_reg')

  print('searching metareg')

  if meta_reg == idc.BADADDR:
    meta_reg = search_meta_reg(mod_addr_min + 56, mod_addr_max - 256)

    if meta_reg == idc.BADADDR:
      print('Failed to search metareg')
      raise

    print('%08X: g_meta_reg' % meta_reg)
    idc.MakeName(meta_reg, 'g_meta_reg')

  if code_reg == idc.BADADDR:
    print('searching codereg')

    code_reg = search_code_reg(meta_reg - 256, meta_reg - 16)

    if code_reg == idc.BADADDR:
      print('Failed to search codereg')
      raise

    print('%08X: g_code_reg' % code_reg)
    idc.MakeName(code_reg, 'g_code_reg')

  #if code_reg == idc.BADADDR or meta_reg == idc.BADADDR:
  #  return analyze_reg()

  return code_reg, meta_reg
Exemple #5
0
def find_main_arena():
    main_arena = idc.LocByName("main_arena")  # from libc6-dbg
    if main_arena != idc.BADADDR:
        return main_arena

    ea = idc.SegStart(idc.LocByName("_IO_2_1_stdin_"))
    end_ea = idc.SegEnd(ea)

    # &main_arena->next
    offsets = {
        4: [1088, 1096],  # 32 bits
        8: [2152, 2160]  # 64 bits
    }

    if ea == idc.BADADDR or end_ea == idc.BADADDR:
        return None

    get_ptr = config.get_ptr
    while ea < end_ea:
        ptr = get_ptr(ea)  # ptr to main_arena
        if idaapi.is_loaded(ptr) and ptr < ea and get_ptr(
                ptr) == 0:  # flags=0x0
            if (ea - ptr) in offsets[config.ptr_size]:
                return ptr
        ea += config.ptr_size
    return None
Exemple #6
0
    def GetBranchList(self, start=None, end=None):
        self.branch_list = list()

        current = start
        if self.arc == ARCHITECTURE['MIPS']:
            o_iasm = mips_iasm.MIPS_IAsm()
            branch_obj = o_iasm.mips_asm_class['branch']
            jump_obj = o_iasm.mips_asm_class['jump']

            while current <= end:
                method = 'do_' + idc.GetMnem(current)
                if hasattr(branch_obj, method) or hasattr(jump_obj, method):
                    if self.isNearAddr(idc.GetOpType(current, 0)):
                        opr = idc.LocByName(idc.GetOpnd(current, 0))
                        if opr in self.func_ref_list:
                            self.branch_list.append(hex(opr))
                    elif self.isNearAddr(idc.GetOpType(current, 1)):
                        opr = idc.LocByName(idc.GetOpnd(current, 1))
                        if opr in self.func_ref_list:
                            self.branch_list.append(hex(opr))
                    elif self.isNearAddr(idc.GetOpType(current, 2)):
                        opr = idc.LocByName(idc.GetOpnd(current, 2))
                        if opr in self.func_ref_list:
                            self.branch_list.append(hex(opr))

                current = idc.NextHead(current, end)

        self.branch_list = list(set(self.branch_list))
        self.branch_list.sort()

        return self.branch_list
Exemple #7
0
	def GetBranchList(self, start=None, end=None):
		branch_list = list()

		current = start
		if self.arc == ARCHITECTURE['MIPS']:
			branch_obj = self.asm.mips_asm_class['branch']
			jump_obj = self.asm.mips_asm_class['jump']

			while current <= end:
				method = 'do_' + idc.GetMnem(current)
				if hasattr(branch_obj, method) or hasattr(jump_obj, method):
					if idc.GetOpType(current, 0) == ASM_TYPE['Imm_Near_Addr']:
						opr = idc.LocByName(idc.GetOpnd(current, 0))
						if opr in self.func_ref_list:
							branch_list.append(hex(opr))
					elif idc.GetOpType(current, 1) == ASM_TYPE['Imm_Near_Addr']:
						opr = idc.LocByName(idc.GetOpnd(current, 1))
						if opr in self.func_ref_list:
							branch_list.append(hex(opr))
					elif idc.GetOpType(current, 2) == ASM_TYPE['Imm_Near_Addr']:
						opr = idc.LocByName(idc.GetOpnd(current, 2))
						if opr in self.func_ref_list:
							branch_list.append(hex(opr))

				current = idc.NextHead(current, end)

		branch_list = list(set(branch_list))
		branch_list.sort()

		return branch_list
Exemple #8
0
    def jumps_to(f, t):
        f_ea = idc.LocByName(f)
        t_ea = idc.LocByName(t)

        for start, end in idautils.Chunks(f_ea):
            ea = start
            while (ea < end):
                i = idautils.DecodeInstruction(ea)

                #Functions have data chunks in them, these are offsets and dwords. skipping 4 ahead seems like a safe choice.
                if type(i) == type(None):
                    ea += 4
                    continue

                #detect if instruction is a jump to t_ea
                m = idc.GetMnem(ea)
                if idc.GetMnem(ea) == "LDR" and idc.GetOpnd(
                        ea, 0) == "PC" and t in idc.GetOpnd(ea, 1):
                    return True
                elif idc.GetMnem(ea) == "BX" and idc.GetOpnd(ea, 0) == t:
                    return True

                try:
                    ea += i.size
                except:
                    print "0x%08x" % ea
                    print "DecodeInstruction failed!"
                    print i.size

        return False
Exemple #9
0
def findroot(TargetFunc):
    global rootpath
    global rootfunc
    global m_rootpath
    global depth
    global dstfunc
    depth += 1
    if (depth >= 10):
        rootfunc.append(TargetFunc)
        rootpath.append(
            "It's difficult to reverse because depth is too deep!!Try: " +
            TargetFunc)
        return
    for xref in idautils.XrefsTo(idc.LocByName(TargetFunc)):
        if (idc.GetFunctionName(xref.frm) == ""):  #if root function
            for storcheck in idautils.XrefsTo(idc.LocByName(TargetFunc)):
                if (storcheck.type == 17):  #not root function
                    return
            if m_rootpath not in rootpath:
                if (depth > 7):
                    m_rootpath = dstfunc + "<--" + TargetFunc
                rootfunc.append(idc.GetFunctionName(xref.to))
                rootpath.append(m_rootpath)
            return
        else:
            g_rootpath = m_rootpath
            m_rootpath += "<--" + idc.GetFunctionName(xref.frm)
            findroot(idc.GetFunctionName(xref.frm))
            depth -= 1
            m_rootpath = g_rootpath
Exemple #10
0
    def get_ea_by_name(name):
        """
        Get the address of a location by name.

        @name - Location name

        Returns the address of the named location, or idc.BADADDR on failure.
        """
        # This allows support of the function offset style names (e.g., main+0C)
        # TODO: Is there something in the IDA API that does this already??
        # TODO: AppCall maybe? http://www.hexblog.com/?p=112 -fireundubh
        ea = idc.BADADDR
        if '+' in name:
            (func_name, offset) = name.split('+')
            base_ea = idc.LocByName(func_name)
            if base_ea != idc.BADADDR:
                try:
                    ea = base_ea + int(offset, 16)
                except:
                    ea = idc.BADADDR
        else:
            ea = idc.LocByName(name)
            if ea == idc.BADADDR:
                try:
                    ea = int(name, 0)
                except:
                    ea = idc.BADADDR
        return ea
Exemple #11
0
 def get_jlocs(self, sw):
     jlocs = []
     ncases = sw.ncases if sw.jcases == 0 else sw.jcases
     for i in range(ncases):
         addr = idc.Dword(sw.jumps+i*4)
         name = idaapi.get_name(idc.BADADDR, addr)
         comm = idc.GetCommentEx(idc.LocByName(name), 1)
         comm = comm[comm.find('case'):] if comm is not None and comm.startswith('jumptable') else comm
         jlocs.append((name, idc.LocByName(name), comm))
     return jlocs
Exemple #12
0
 def addNodes(self):
     for node in self.result:
         name = idc.GetFunctionName(node)
         if not name:
             continue
         
         if name not in self.added:
             try:
                 self.nodes[idc.LocByName(name)] = self.AddNode((idc.LocByName(name), name))
                 self.added.append(name)
             except:
                 print "Error adding node", sys.exc_info()[1]
Exemple #13
0
 def addEdges(self):
     for ea in self.result:
         refs = GetCodeRefsFrom(ea)
         for ref in refs:
             name = idc.GetFunctionName(ref)
             name2 = idc.GetFunctionName(ea)
             try:
                 if name in self.added:
                     self.AddEdge(self.nodes[idc.LocByName(name2)], self.nodes[idc.LocByName(name)])
                     self.added.append((ea, ref))
             except:
                 print "Error", sys.exc_info()[1]
Exemple #14
0
    def handler(self):
      if 1:
        b1 = 'sn00gle-fl00gle-p00dlekins'
        dst = idautils.cpu.esp + 0x100
        dstsize = 0x102
        idc.DbgWrite(dst, '\x00'*dstsize)

        buf = dst - len(b1)-10
        idc.DbgWrite(buf, b1+'\x00')

        gen_perm_ea = idc.LocByName('generate_perm')
        mix_ea = idc.LocByName('mix_things')
        pass1_ea = idc.LocByName('PASSWORD1')
        pass1_len = read_u32(idc.LocByName('PASSWORD1_LEN'))

        finalsize = pass1_len
        finaldest = idautils.cpu.esp - 2*finalsize
        idc.DbgWrite(finaldest, '\x00'*(finalsize+1))

        self.call(gen_perm_ea, dst, buf, len(b1))
        yield


        print(hex(dst), hex(pass1_ea), hex(finaldest), hex(pass1_len))
        #self.done = 1
        #return
        self.call(mix_ea, dst, pass1_ea, finaldest, pass1_len)
        yield
        with open('./final.data', 'wb') as f:
          f.write(idc.DbgRead(finaldest, pass1_len))

      else:
        stride = 0x24

        nseg = read_u32(self.rx_seg_count)
        base_addr = self.rx_seg_desc
        print('HANDLER', nseg)
        for i in range(nseg):
          seg_addr = base_addr + stride * i
          for data in self.decode_seg(seg_addr, False):
            yield

        nseg = read_u32(self.rw_seg_count)
        base_addr = self.rw_seg_desc
        for i in range(nseg):
          seg_addr = base_addr + stride * i
          for data in self.decode_seg(seg_addr, True):
            yield

        print('dumping handler')
        json.dump(self.segs, open('./dump.json', 'w'))
      self.done = 1
Exemple #15
0
    def Call(self, function, arguments=[], retaddr=0, block_until_return=True):
        '''
		Call a given function. Arguments must already be configured.
		This should not be used to call functions hooked with IDASimulator or it likely won't work.

		@function           - The name or address of the function to call.
		@arguments          - A list of function arguments.
		@retaddr            - The address to return to.
		@block_until_return - If set to True, this method will not return until the function does.
				      If set to False, this method will return immediately after calling the function.

		Returns the return value of the function on success.
		Returns None on failure, or if block_until_return is False.
		'''
        retval = None

        # Process should already be paused, but just in case...
        idc.PauseProcess()

        # If a function name was specified, get its address
        if isinstance(function, type('')):
            function = idc.LocByName('.' + function)

            if function == idc.BADADDR:
                function = idc.LocByName(function)

        if function != idc.BADADDR:
            if not retaddr:
                retaddr = self.cpu.ProgramCounter()

            # Set the specified function arguments
            self.cpu.SetArguments(arguments)

            # Do any arch-specific initialization before the function call
            self.cpu.PreFunctionCall(function)

            # Set up the return address and point the program counter to the start of the target function
            self.cpu.ReturnAddress(value=retaddr)
            self.cpu.ProgramCounter(value=function)
            idc.Jump(function)

            if block_until_return:
                # Resume process and wait for the target function to return
                idc.StepUntilRet()
                idc.GetDebuggerEvent(idc.WFNE_CONT | idc.WFNE_SUSP, -1)
                idc.Jump(retaddr)
                retval = self.cpu.ReturnValue()
            else:
                idc.ResumeProcess()

        return retval
Exemple #16
0
def AuditApiCall(funcname, auditfunc):
    
    print funcname
    
    func = idc.LocByName(funcname)

    print funcname + " func addr "
    print hex(func)

    count = 0

    if(func != BADADDR):
        for xref in idautils.XrefsTo(func,0):
            print xref.type,idautils.XrefTypeName(xref.type)
    
            print 'from',hex(xref.frm)
            print 'to',hex(xref.to)

            ####audit func#####
            ####not from an const####

            func_start = idc.GetFunctionAttr(xref.frm, idc.FUNCATTR_START)
            func_end = idc.GetFunctionAttr(xref.frm, idc.FUNCATTR_END)
            local_size = idc.GetFunctionAttr(xref.frm, idc.FUNCATTR_FRSIZE)
            ###Data offset  eg: lis r10, VOS_sprintf@h
            ###            addi r10, r10, VOS_sprintf@l
            if(xref.type == 1):
                print "disass is "+idc.GetDisasm(xref.frm)
                if("add" in idc.GetDisasm(xref.frm)):
                    caller = TraceApiCall(xref.frm)
                    auditfunc(caller)
                    break            
            else:
                caller= xref.frm
Exemple #17
0
def get_virtual_func_address(name, tinfo=None, offset=None):
    """
    :param name: method name
    :param tinfo: class tinfo
    :param offset: virtual table offset
    :return: address of the method
    """

    address = idc.LocByName(name)
    if address != idaapi.BADADDR:
        return address

    address = demangled_names.get(name, idaapi.BADADDR)
    if address != idaapi.BADADDR:
        return address + idaapi.get_imagebase()

    if tinfo is None or offset is None:
        return

    offset *= 8
    udt_member = idaapi.udt_member_t()
    while tinfo.is_struct():
        address = demangled_names.get(tinfo.dstr() + '::' + name,
                                      idaapi.BADADDR)
        if address != idaapi.BADADDR:
            return address + idaapi.get_imagebase()
        udt_member.offset = offset
        tinfo.find_udt_member(idaapi.STRMEM_OFFSET, udt_member)
        tinfo = udt_member.type
        offset = offset - udt_member.offset
Exemple #18
0
def bulk_function():
    functionPtrs = ""
    for func_name in get_selected_funcs():
        functionPtrDef = copy_function(idc.LocByName(func_name))
        functionPtrs = functionPtrs + functionPtrDef + "\n"
    copy_to_clip(functionPtrs)
    idaapi.msg(functionPtrs)
Exemple #19
0
    def __init__(self, ea=UseCurrentAddress, name=None):
        if name is not None and ea != self.UseCurrentAddress:
            raise ValueError(
                ("Either supply a name or an address (ea). "
                 "Not both. (ea={!r}, name={!r})").format(ea, name))

        elif name is not None:
            ea = idc.LocByName(name)
            if ea == idc.BADADDR:
                raise exceptions.SarkNoFunction(
                    "The supplied name does not belong to an existing function. "
                    "(name = {!r})".format(name))

        elif ea == self.UseCurrentAddress:
            ea = idc.here()

        elif ea is None:
            raise ValueError(
                "`None` is not a valid address. To use the current screen ea, "
                "use `Function(ea=Function.UseCurrentAddress)` or supply no `ea`."
            )

        elif isinstance(ea, Line):
            ea = ea.ea
        self._func = get_func(ea)
        self._comments = Comments(self)
def LocatePointerLists():
    seg = idc.FirstSeg()
    initArrayAddr = 0
    while seg != idc.BADADDR:
        seg = idc.NextSeg(seg)
        segName = idc.SegName(seg)
        if segName == ".init_array":
            initArrayAddr = idc.SegStart(seg)
            break

    # find Il2CppCodeRegistrationOffset from init_array
    Il2CppCodeRegistrationOffset = initArrayAddr + 30 * (BITS / 8)
    print "find Il2CppCodeRegistrationOffset %x" % Il2CppCodeRegistrationOffset

    Il2CppCodeRegistrationCpp = GetVarFromAddr(Il2CppCodeRegistrationOffset)

    print "Il2CppCodeRegistrationCpp: %x" % Il2CppCodeRegistrationCpp
    idc.MakeName(Il2CppCodeRegistrationCpp, "Il2CppCodeRegistrationCpp")

    #Il2CppCodegenRegistration = 0
    #for r in idautils.XrefsFrom(Il2CppCodeRegistrationAddr + 0x14, 0):
    #    Il2CppCodegenRegistration = hex(r.to)

    #g_CodeRegistration = 0
    #for r in idautils.XrefsFrom(Il2CppCodegenRegistration + 0x18, 0):
    #    g_CodeRegistration = hex(r.to)

    opndValue = idc.GetOperandValue(Il2CppCodeRegistrationCpp + 0x8, 1)
    offset = GetVarFromAddr(opndValue)

    _GLOBAL_OFFSET_TABLE_ = idc.LocByName("_GLOBAL_OFFSET_TABLE_")

    print "_GLOBAL_OFFSET_TABLE_ %x" % _GLOBAL_OFFSET_TABLE_

    Il2CppCodegenRegistration = (_GLOBAL_OFFSET_TABLE_ + offset) & 0xFFFFFFFF
    idc.MakeName(Il2CppCodegenRegistration, "Il2CppCodegenRegistration")
    print "Il2CppCodegenRegistration %x" % Il2CppCodegenRegistration

    opndValue = idc.GetOperandValue(Il2CppCodegenRegistration + 0xC, 1)
    offset = GetVarFromAddr(opndValue)
    g_CodeRegistration = (_GLOBAL_OFFSET_TABLE_ + offset) & 0xFFFFFFFF
    idc.MakeName(g_CodeRegistration, "g_CodeRegistration")
    print "g_CodeRegistration %x" % g_CodeRegistration

    g_MethodPointers = GetVarFromAddr(g_CodeRegistration + 0x4)
    idc.MakeName(g_MethodPointers, "g_MethodPointers")
    print "g_MethodPointers %x" % g_MethodPointers

    opndValue = idc.GetOperandValue(Il2CppCodegenRegistration + 0x04, 1)
    offset = GetVarFromAddr(opndValue)
    g_MetadataRegistration = GetVarFromAddr((_GLOBAL_OFFSET_TABLE_ + offset)
                                            & 0xFFFFFFFF)
    idc.MakeName(g_MetadataRegistration, "g_MetadataRegistration")
    print "g_MetadataRegistration %x" % g_MetadataRegistration

    g_MetadataUsages = GetVarFromAddr(g_MetadataRegistration + 0x3C)
    idc.MakeName(g_MetadataUsages, "g_MetadataUsages")
    print "g_MetadataUsages %x" % g_MetadataUsages

    return (g_MethodPointers, g_MetadataUsages)
Exemple #21
0
def get_function_para(func_name):
    func_args = []
    code_buf = []

    ea = idc.LocByName(func_name)
    if ea != idc.BADADDR:
        f = idaapi.get_func(ea)
        if f is not None:
            try:
                cfunc = idaapi.decompile(f)
                if cfunc != None:
                    #
                    sv = cfunc.get_pseudocode()
                    for sline in sv:
                        code_line = idaapi.tag_remove(sline.line)
                        code_buf.append(code_line)

                    #print('find: %s(' %func_name, end='')
                    for arg in cfunc.arguments:
                        func_args.append(arg.name)
                        #print(arg.name+', ', end='')
                    #print(')')
            except Exception as e:
                print(e)

    #code_str = '\n'.join(code_buf)
    return func_args, code_buf
Exemple #22
0
def run(segments, args, addresses, interpreter=None, **kwargs):
    if args.name:
        ea = idc.LocByName(args.name)
        occurrences = [ea] if ea != idc.BADADDR else []
    else:
        occurrences = list(utils.ida_find_all(args.bytes))

    frm = set()
    for ea in occurrences:
        froms = [ref.frm for ref in idautils.XrefsTo(ea)]

        if args.function_start:
            froms = [function_start.get_function_start(segments, ea)
                     for ea in froms]

        frm.update(frm for frm in froms if frm != idc.BADADDR)

    retval = set()
    retval.update(addresses)

    if getattr(args, 'or'):
        retval.update(frm)

    elif getattr(args, 'and'):
        retval.intersection_update(frm)

    return list(retval)
Exemple #23
0
def parse_mpu():
	"""
	NOTE: to find this symbol, run find_mcr.py and look for the MPU config instructions.
	Backtrace that function to a wrapper; backtrace that one to the MPU initialization function,
	which calls the wrapper in a loop using values from an array. That array is MPU_region_configs.
	"""
	mpu_struct_addr = idc.LocByName("MPU_region_configs")

	if mpu_struct_addr == 0xFFFFFFFF:
		print "NOTE: to find this symbol, run find_mcr.py and look for the MPU config instructions.\nBacktrace that function to a wrapper; backtrace that one to the MPU initialization function,\nwhich calls the wrapper in a loop using values from an array. That array is MPU_region_configs."
		return

	while(1):
		r = Region(mpu_struct_addr)
		if r.num == 0xFF:
			print "Delimiter found!"
			break
		else:
			r.pprint()			

		mpu_struct_addr += 40

	new_region = Region()
	new_region.set_DRNR(14)
	new_region.set_DRBAR(0x404E6000) 	# mo_call_establishment_trace_setup_msg
	new_region.set_size(0b01011) 		# 256*(2**4) aka 0x1000 aka 4096 bytes
	new_region.set_en(1)				# enabled
	new_region.set_TEX_C_B(0b001,0,0)	# non-cacheble
	new_region.set_XN(0)				# no XN bit
	new_region.set_AP(0b011) 			# RW
	new_region.set_S(1)					# shareable

	new_region.pprint()
Exemple #24
0
def GetDataXrefString(ea):
    name = idc.GetFunctionName(ea)
    ea = idc.LocByName(name)

    f_start = ea
    f_end = idc.GetFunctionAttr(ea, idc.FUNCATTR_END)

    ret = []
    for chunk in idautils.Chunks(ea):
        astart = chunk[0]
        aend = chunk[1]
        for head in idautils.Heads(astart, aend):
            # If the element is an instruction
            if idc.isCode(idc.GetFlags(head)):
                refs = list(idautils.DataRefsFrom(head))
                for ref in refs:
                    s = idc.GetString(ref, -1, idc.ASCSTR_C)
                    if not s or len(s) <= 4:
                        s = idc.GetString(ref, -1, idc.ASCSTR_UNICODE)

                    if s:
                        if len(s) > 4:
                            ret.append(repr(s))

    if len(ret) > 0:
        return "\n\n" + "\n".join(ret)
    else:
        return ""
Exemple #25
0
    def _find_system_calls(self, start_ea, end_ea):
        system_calls = []
        system_load = MIPSInstruction("la", "$t9", "system")
        stack_arg_zero = MIPSInstruction("addiu", "$a0", "$sp")

        for xref in idautils.XrefsTo(idc.LocByName('system')):
            ea = xref.frm
            if ea >= start_ea and ea <= end_ea and idc.GetMnem(ea)[0] in [
                    'j', 'b'
            ]:
                a0_ea = self._find_next_instruction_ea(ea + self.INSIZE,
                                                       stack_arg_zero,
                                                       ea + self.INSIZE)
                if a0_ea == idc.BADADDR:
                    a0_ea = self._find_prev_instruction_ea(
                        ea, stack_arg_zero,
                        ea - (self.SEARCH_DEPTH * self.INSIZE))

                if a0_ea != idc.BADADDR:
                    control_ea = self._find_prev_instruction_ea(
                        ea - self.INSIZE, system_load,
                        ea - (self.SEARCH_DEPTH * self.INSIZE))
                    if control_ea != idc.BADADDR:
                        system_calls.append(
                            ROPGadget(self._get_instruction(control_ea),
                                      self._get_instruction(ea),
                                      self._get_instruction(a0_ea),
                                      description="System call",
                                      base=self.base))

                ea += self.INSIZE
            else:
                break

        return system_calls
Exemple #26
0
    def DeepSearch(self, function_name, line, max_deep, current_deep=0):

        data = {}
        opcode_offset = 0
        function_start = idc.LocByName(function_name)
        function_end = idc.GetFunctionAttr(function_start, idc.FUNCATTR_END)
        while function_start + opcode_offset < function_end:

            opcode_index = function_start + opcode_offset
            dline = idc.GetDisasm(opcode_index)
            if idc.GetMnem(opcode_index) == "call":
                if current_deep >= max_deep:
                    return
                elif idc.GetOpnd(opcode_index, 0)[:4] == "sub_":
                    deep = self.DeepSearchWithRgx(idc.GetOpnd(opcode_index,
                                                              0), line,
                                                  max_deep, current_deep + 1)
                    if deep:
                        data.update(deep)

            if dline == line:
                data["%x" % opcode_index] = dline

            opcode_offset += idc.ItemSize(opcode_index)

        return data
Exemple #27
0
def MakeEnum(enumName, offsetArray):
    print("enum class %s\r\n{" % enumName)
    for offset in offsetArray:
        if len(offset[0]) == 0:
            print("")
            continue
        if type(offset[1]) is str:
            print("   %s = %s," % (offset[0], offset[1]))
            continue
        '''
		fncValue = offset[1] if offset[1] != -1 else 0x0
		'''
        # print "   %s = 0x%08x,%s" % (offset[0], fncValue, ' // Unknown' if fncValue == 0x0 else '')

        fncValue = offset[1] if offset[1] != -1 else 0x0

        locByName = idc.LocByName(offset[0])
        isMismatch = locByName != fncValue

        if locByName == BADADDR:
            locByName = fncValue

        print("   %s = 0x%08x,%s" %
              (offset[0], locByName,
               '// Possible mismatch' if isMismatch else ''))

    print("};\r\n")
Exemple #28
0
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)
Exemple #29
0
def do_diff(original_string, modified_string):
    original_list = original_string.split()
    modified_list = modified_string.split()

    if len(original_list) != len(modified_list):
        print '[!] Differing number of words when splitting original and modified text.'
        print '[!] Unable to handle this, exiting'
        return None

    modification_dict = {}
    for i in range(0, len(original_list)):
        if original_list[i].strip() != modified_list[i].strip():
            (original_name,
             modified_name) = get_modified_name(original_list[i],
                                                modified_list[i])
            if original_name and modified_name:
                if original_name not in modification_dict:
                    modification_dict[original_name] = modified_name
                else:
                    existing_name = modification_dict[original_name]
                    if existing_name != modified_name:
                        print '[!] Multiple modifications to the same name %s and %s' % (
                            original_name, modified_name)
            else:
                print '[!] Unable to match name %s and %s' % (original_name,
                                                              modified_name)
                #print original_list[i], modified_list[i]

    new_modification_dict = {}
    for original, modified in modification_dict.iteritems():
        if idc.LocByName(original) != idaapi.BADADDR:
            #print '%s --> %s' % (original, modified)
            new_modification_dict[original] = modified
    return new_modification_dict
Exemple #30
0
    def OnCommand(self, n, cmd):
        if cmd == self.show_all_toggle_cmd:

            if self.min_xrefs == self.MIN_XREFS:
                self.min_xrefs = 0
            if self.min_xrefs != self.MIN_XREFS:
                self.min_xrefs = self.MIN_XREFS

            if self.must_have_loop == self.MUST_HAVE_LOOP:
                self.must_have_loop = False
            else:
                self.must_have_loop = self.MUST_HAVE_LOOP

        elif cmd == self.rename_cmd:

            if idc.AskYN(
                    0,
                    "Are you sure you want to rename all 'sub_XXXXXX' functions to 'leaf_XXXXXX'?"
            ) == 1:
                for item in self.items:
                    # Is this a leaf function?
                    if item[-1] == True:
                        current_name = item[0]
                        if current_name.startswith('sub_'):
                            new_name = current_name.replace('sub_', 'leaf_')
                            idc.MakeName(idc.LocByName(current_name), new_name)

        self.populate_items()
        return 0