Пример #1
0
    def activate(self, ctx):
        if self.action == ACTION_HX_REMOVERETTYPE:
            if IDA7:
                vdui = idaapi.get_widget_vdui(ctx.widget)
            else:
                vdui = idaapi.get_tform_vdui(ctx.form)
            self.remove_rettype(vdui)
            vdui.refresh_ctext()
        elif self.action == ACTION_HX_COPYEA:
            ea = idaapi.get_screen_ea()
            if ea != idaapi.BADADDR:
                copy_to_clip("0x%X" % ea)
                print("Address 0x%X has been copied to clipboard" % ea)
        elif self.action == ACTION_HX_COPYNAME:
            if IDA7:
                name = idaapi.get_highlight(idaapi.get_current_viewer())[0]
            else:
                name = idaapi.get_highlighted_identifier()
            if name:
                copy_to_clip(name)
                print("%s has been copied to clipboard" % name)
        elif self.action == ACTION_HX_GOTOCLIP:
            loc = parse_location(clip_text())
            print("Goto location 0x%x" % loc)
            Jump(loc)
        else:
            return 0

        return 1
Пример #2
0
    def finish_populating_widget_popup(self, form, popup):
        form_type = idaapi.get_widget_type(form)
        if form_type == idaapi.BWN_DISASM or form_type == idaapi.BWN_DUMP:
            idaapi.attach_action_to_popup(form, popup, ACTION_PASTE, None)
            idaapi.attach_action_to_popup(form, popup, ACTION_DUMPER, None)
            idaapi.attach_action_to_popup(form, popup, ACTION_JMP, None)
            t0, t1, view = idaapi.twinpos_t(), idaapi.twinpos_t(
            ), idaapi.get_current_viewer()
            if idaapi.read_selection(
                    view, t0,
                    t1) or idc.get_item_size(idc.get_screen_ea()) > 1:
                idaapi.attach_action_to_popup(form, popup, ACTION_XORDATA,
                                              None)
                idaapi.attach_action_to_popup(form, popup, ACTION_FILLNOP,
                                              None)
                for action in ACTION_CONVERT:
                    idaapi.attach_action_to_popup(form, popup, action,
                                                  "Convert/")

        if form_type == idaapi.BWN_DISASM and (ARCH, BITS) in [
            (idaapi.PLFM_386, 32),
            (idaapi.PLFM_386, 64),
            (idaapi.PLFM_ARM, 32),
        ]:
            idaapi.attach_action_to_popup(form, popup, ACTION_SCANVUL, None)
Пример #3
0
    def activate(self, ctx):
        if self.action == ACTION_HX_REMOVERETTYPE:
            if IDA7:
                vdui = idaapi.get_widget_vdui(ctx.widget)
            else:
                vdui = idaapi.get_tform_vdui(ctx.form)
            self.remove_rettype(vdui)
            vdui.refresh_ctext()
        elif self.action == ACTION_HX_COPYEA:
            ea = idaapi.get_screen_ea()
            if ea != idaapi.BADADDR:
                copy_to_clip("0x%X" % ea)
                print "Address 0x%X has been copied to clipboard" % ea
        elif self.action == ACTION_HX_COPYNAME:
            if IDA7:
                name = idaapi.get_highlight(idaapi.get_current_viewer())[0]
            else:
                name = idaapi.get_highlighted_identifier()
            if name:
                copy_to_clip(name)
                print "%s has been copied to clipboard" % name
        else:
            return 0

        return 1
Пример #4
0
def get_ea_from_highlight():
    view = idaapi.get_current_viewer()
    thing = ida_kernwin.get_highlight(view)
    if thing and thing[1]:
        # we have a highligh, is it a valid name ?
        ea = idc.get_name_ea_simple(thing[0])
        if ea != idaapi.BADADDR:
            return ea

        # get name at screen ea
        ea = idc.get_screen_ea()
        name = idc.get_name(ea, idaapi.GN_DEMANGLED)
        if name and thing[0] in name:
            return ea

        # Try to get full highlight name
        place = idaapi.get_custom_viewer_place(view, False)
        if place and len(place) == 3:   # (plate_t, x, y)
            ea = place[0].toea()
            far_code_refs = [xref.to for xref in idautils.XrefsFrom(ea, ida_xref.XREF_FAR)]
            if far_code_refs:
                return far_code_refs[0] # First xref

    # Reach now, we do not have any valid name, return current screen ea
    return idc.get_screen_ea()
Пример #5
0
def get_highlighted_identifier():
    if not hasattr(idaapi, "get_highlighted_identifier"):
        thing = idaapi.get_highlight(idaapi.get_current_viewer())
        if thing and thing[1]:
            return thing[0]
    else:
        return idaapi.get_highlighted_identifier()
Пример #6
0
def get_selected_text():
    """ Get the highlight text. If none, force IDA copy text and we will get from clipboard """
    text = ""
    old_text = clip_text()

    view = idaapi.get_current_viewer()
    if view:
        thing = ida_kernwin.get_highlight(view)
        if thing and thing[1]:
            text = thing[0]

    # We not have a highlight text
    if not text:
        for action in idaapi.get_registered_actions():
            if "Copy" in action:
                shortcut = idaapi.get_action_shortcut(action)
                state = idaapi.get_action_state(action)
                if ("Ctrl-C" in shortcut) and (state and state[0] and (state[1] <= idaapi.AST_ENABLE)):
                    idaapi.process_ui_action(action)
                    text = clip_text()
                    if text != old_text:
                        break

    if not text:
        plg_print("Could not get any highlight/auto copied text\n" \
                  "Search with old clipboard text: '%s'" % old_text)
        text = old_text

    return text
Пример #7
0
def jump_to_line(ea, line, col):
    idc.Jump(ea)
    viewer = idaapi.get_current_viewer()
    (pl, x, y) = idaapi.get_custom_viewer_place(viewer, False)
    pl2 = idaapi.place_t_as_simpleline_place_t(pl.clone())
    pl2.n = line
    x = col
    y = 10
    idaapi.jumpto(viewer, pl2, x, y)
Пример #8
0
 def selection(cls):
     '''Return the current address range of whatever is selected'''
     view = idaapi.get_current_viewer()
     left, right = idaapi.twinpos_t(), idaapi.twinpos_t()
     ok = idaapi.read_selection(view, left, right)
     if not ok:
         raise internal.exceptions.DisassemblerError("{:s}.selection() : Unable to read the current selection.".format('.'.join((__name__, cls.__name__))))
     pl_l, pl_r = left.place(view), right.place(view)
     return _database.address.head(pl_l.ea), _database.address.tail(pl_r.ea)
Пример #9
0
 def selection(cls):
     '''Return the current address range of whatever is selected'''
     view = idaapi.get_current_viewer()
     left, right = idaapi.twinpos_t(), idaapi.twinpos_t()
     ok = idaapi.read_selection(view, left, right)
     if not ok:
         raise internal.exceptions.DisassemblerError(u"{:s}.selection() : Unable to read the current selection.".format('.'.join((__name__, cls.__name__))))
     pl_l, pl_r = left.place(view), right.place(view)
     ea_l, ea_r = internal.interface.address.inside(pl_l.ea, pl_r.ea)
     return internal.interface.bounds_t(ea_l, ea_r)
Пример #10
0
    def symbol(cls):
        '''Return the current highlighted symbol name.'''
        if idaapi.__version__ < 7.0:
            return idaapi.get_highlighted_identifier()

        # IDA 7.0 way of getting the currently selected text
        viewer = idaapi.get_current_viewer()
        res = idaapi.get_highlight(viewer)
        if res and res[1]:
            return res[0]
        return res
Пример #11
0
    def finish_populating_widget_popup(self, form, popup):
        form_type = idaapi.get_widget_type(form)

        if form_type == idaapi.BWN_DISASM or form_type == idaapi.BWN_DUMP:
            t0, t1, view = idaapi.twinpos_t(), idaapi.twinpos_t(
            ), idaapi.get_current_viewer()
            if idaapi.read_selection(view, t0, t1) \
                    or idc.get_item_size(idc.get_screen_ea()) > 1:
                idaapi.attach_action_to_popup(form, popup, GOLANG_FUNC, None)
                idaapi.attach_action_to_popup(form, popup, GOLANG_STRING, None)
                idaapi.attach_action_to_popup(form, popup, RENAME_POINTER,
                                              None)
Пример #12
0
    def activate(self, ctx):
        t0, t1, view = idaapi.twinpos_t(), idaapi.twinpos_t(
        ), idaapi.get_current_viewer()
        if idaapi.read_selection(view, t0, t1):
            start, end = t0.place(view).toea(), t1.place(view).toea()
            end += idaapi.get_item_size(end)
        else:
            start = idaapi.get_screen_ea()

            if start == idaapi.BADADDR:
                print('Easy Nop :: Screen EA == idaapi.BADADDR')
                return 0

            end = start + idaapi.get_item_size(start)

        if start == idaapi.BADADDR:
            print('Easy Nop :: Selection EA == idaapi.BADADDR')
            return 0

        if start == end:
            print('Easy Nop :: Nothing to nop')
            return 0

        for x in range(start, end):
            # Maybe theres a smarter way to get the nop value for different archs e.g. Assemble('nop') -> 0x90
            idaapi.patch_byte(x, 0x90)

        for x in range(start + 1, end):
            idaapi.hide_item(x)

        # Must do this else it bugs out on 2x 1 byte instructions being nopped
        idaapi.hide_item(start)
        idaapi.unhide_item(start)

        # Search for hidden nops and add to count
        while idaapi.get_byte(end) == 0x90 and idaapi.is_hidden_item(
                end) == True:
            end += 1

        count = end - start

        if count > 1:
            idaapi.set_cmt(start, "truncated nops (%d)" % (count), False)

        print(end)
        print(start)

        return 1
Пример #13
0
    def handle_set_vtable_range(self):
        if self.edit_class is None:
            return

        p0 = idaapi.twinpos_t()
        p1 = idaapi.twinpos_t()
        view = idaapi.get_current_viewer()

        success = idaapi.read_selection(view, p0, p1)

        if not success:
            idaapi.warning('Please, select region in ida dissasembler')

        ea0 = p0.place(view).ea
        ea1 = p1.place(view).ea

        # Check selection
        if ea0 == idc.BADADDR or ea1 == idc.BADADDR:
            return

        if ea0 > ea1:
            return

        if ea0 != idc.get_screen_ea() and ea1 != idc.get_screen_ea():
            return

        # Warning for large ranges
        if (ea1 - ea0) > 0x1000:
            if not util.ask_yes_no(
                    'Warning: The VTable range is longer than 0x1000 bytes. Continue?',
                    False):
                return

        try:
            self.edit_class.set_vtable_range(ea0, ea1)
            self.update_fields()
        except ValueError as e:
            idaapi.warning(str(e))
Пример #14
0
    def run(self, arg):
        # Get the highlighted identifier
        v = idaapi.get_current_viewer()
        id = ida_kernwin.get_highlight(v)[0]
        if not id:
            print "No identifier was highlighted"
            return

        import webbrowser

        try:
            import feedparser
        except:
            idaapi.warning('Feedparser package not installed')
            return

        id = self.sanitize_name(id)
        print "Looking up '%s' in MSDN online" % id
        d = feedparser.parse("http://social.msdn.microsoft.com/Search/Feed.aspx?locale=en-us&format=RSS&Query=%s" % id)
        if len(d['entries']) > 0:
            url = d['entries'][0].link
            webbrowser.open_new_tab(url)
        else:
            print "API documentation not found for: %s" % id
Пример #15
0
 def fun():
     idaapi.set_view_renderer_type(idaapi.get_current_viewer(),
                                   idaapi.TCCRT_FLAT)
Пример #16
0
def get_highlighted_identifier():
    thing = idaapi.get_highlight(idaapi.get_current_viewer())
    if thing and thing[1]:
        return thing[0]
Пример #17
0
def F**k():
    InitFn()
    name, _ = idaapi.get_highlight(idaapi.get_current_viewer())
    if name in funcDB.keys():
        os.startfile(funcDB[name], 'open')
Пример #18
0
    def activate(self, ctx):
        if self.action in ACTION_CONVERT:
            # convert
            t0, t1, view = idaapi.twinpos_t(), idaapi.twinpos_t(
            ), idaapi.get_current_viewer()
            if idaapi.read_selection(view, t0, t1):
                start, end = t0.place(view).toea(), t1.place(view).toea()
                size = end - start
            elif idc.get_item_size(idc.get_screen_ea()) > 1:
                start = idc.get_screen_ea()
                size = idc.get_item_size(start)
                end = start + size
            else:
                return False

            data = idc.get_bytes(start, size)
            if isinstance(data, str):  # python2 compatibility
                data = bytearray(data)
            name = idc.get_name(start, idc.GN_VISIBLE)
            if not name:
                name = "data"
            if data:
                print("\n[+] Dump 0x%X - 0x%X (%u bytes) :" %
                      (start, end, size))
                if self.action == ACTION_CONVERT[0]:
                    # escaped string
                    print('"%s"' % "".join("\\x%02X" % b for b in data))
                elif self.action == ACTION_CONVERT[1]:
                    # hex string
                    print("".join("%02X" % b for b in data))
                elif self.action == ACTION_CONVERT[2]:
                    # C array
                    output = "unsigned char %s[%d] = {" % (name, size)
                    for i in range(size):
                        if i % 16 == 0:
                            output += "\n    "
                        output += "0x%02X, " % data[i]
                    output = output[:-2] + "\n};"
                    print(output)
                elif self.action == ACTION_CONVERT[3]:
                    # C array word
                    data += b"\x00"
                    array_size = (size + 1) // 2
                    output = "unsigned short %s[%d] = {" % (name, array_size)
                    for i in range(0, size, 2):
                        if i % 16 == 0:
                            output += "\n    "
                        output += "0x%04X, " % u16(data[i:i + 2])
                    output = output[:-2] + "\n};"
                    print(output)
                elif self.action == ACTION_CONVERT[4]:
                    # C array dword
                    data += b"\x00" * 3
                    array_size = (size + 3) // 4
                    output = "unsigned int %s[%d] = {" % (name, array_size)
                    for i in range(0, size, 4):
                        if i % 32 == 0:
                            output += "\n    "
                        output += "0x%08X, " % u32(data[i:i + 4])
                    output = output[:-2] + "\n};"
                    print(output)
                elif self.action == ACTION_CONVERT[5]:
                    # C array qword
                    data += b"\x00" * 7
                    array_size = (size + 7) // 8
                    output = "unsigned long %s[%d] = {" % (name, array_size)
                    for i in range(0, size, 8):
                        if i % 32 == 0:
                            output += "\n    "
                        output += "%#018X, " % u64(data[i:i + 8])
                    output = output[:-2] + "\n};"
                    print(output.replace("0X", "0x"))
                elif self.action == ACTION_CONVERT[6]:
                    # python list
                    print("[%s]" % ", ".join("0x%02X" % b for b in data))
                elif self.action == ACTION_CONVERT[7]:
                    # python list word
                    data += b"\x00"
                    print("[%s]" % ", ".join("0x%04X" % u16(data[i:i + 2])
                                             for i in range(0, size, 2)))
                elif self.action == ACTION_CONVERT[8]:
                    # python list dword
                    data += b"\x00" * 3
                    print("[%s]" % ", ".join("0x%08X" % u32(data[i:i + 4])
                                             for i in range(0, size, 4)))
                elif self.action == ACTION_CONVERT[9]:
                    # python list qword
                    data += b"\x00" * 7
                    print("[%s]" % ", ".join(
                        "%#018X" % u64(data[i:i + 8])
                        for i in range(0, size, 8)).replace("0X", "0x"))
        elif self.action == ACTION_XORDATA:
            t0, t1, view = idaapi.twinpos_t(), idaapi.twinpos_t(
            ), idaapi.get_current_viewer()
            if idaapi.read_selection(view, t0, t1):
                start, end = t0.place(view).toea(), t1.place(view).toea()
            else:
                if idc.get_item_size(idc.get_screen_ea()) > 1:
                    start = idc.get_screen_ea()
                    end = start + idc.get_item_size(start)
                else:
                    return False

            data = idc.get_bytes(start, end - start)
            if isinstance(data, str):  # python2 compatibility
                data = bytearray(data)
            x = idaapi.ask_long(0, "Xor with...")
            if x:
                x &= 0xFF
                print("\n[+] Xor 0x%X - 0x%X (%u bytes) with 0x%02X:" %
                      (start, end, end - start, x))
                print(repr("".join(chr(b ^ x) for b in data)))
        elif self.action == ACTION_FILLNOP:
            t0, t1, view = idaapi.twinpos_t(), idaapi.twinpos_t(
            ), idaapi.get_current_viewer()
            if idaapi.read_selection(view, t0, t1):
                start, end = t0.place(view).toea(), t1.place(view).toea()
                idaapi.patch_bytes(start, b"\x90" * (end - start))
                print("\n[+] Fill 0x%X - 0x%X (%u bytes) with NOPs" %
                      (start, end, end - start))
        elif self.action == ACTION_SCANVUL:
            print("\n[+] Finding Format String Vulnerability...")
            found = []
            for addr in idautils.Functions():
                name = idc.get_func_name(addr)
                if "printf" in name and "v" not in name and idc.get_segm_name(
                        addr) in (".text", ".plt", ".idata"):
                    xrefs = idautils.CodeRefsTo(addr, False)
                    for xref in xrefs:
                        vul = self.check_fmt_function(name, xref)
                        if vul:
                            found.append(vul)
            if found:
                print("[!] Done! %d possible vulnerabilities found." %
                      len(found))
                ch = VulnChoose("Vulnerability", found, None, False)
                ch.Show()
            else:
                print("[-] No format string vulnerabilities found.")
        else:
            return 0

        return 1
Пример #19
0
 def viewer(cls):
     '''Return the current viewer.'''
     return idaapi.get_current_viewer()
Пример #20
0
        def cb(user_data, notification_code, va_list):
            '''
            example hook_cb_t function that handles custom viewer hints.

            Args:
              user_data (ctypes.c_void_p): context supplied to callback registration
              notification_code (int): one of the UI_NOTIFICATIONS enum values
              va_list (ctypes.c_void_p): varargs that must be manually parsed

            Returns:
              int: see notifiication code documentation for interpretation

            Notes:
              - This is a closure that expects to have 
            '''

            # this function is called *a lot*, so don't do any heavy lifting
            #  until you know its the event you want.

            # ctypes doesn't support varargs in callback functions.
            # so, we need to parse the remaining arguments ourselves.
            #
            # on windows, varargs are sequential stack locations.
            # so, lets access the members like an array of ints/pointers.
            #
            # WARNING: the following section that manually parses varargs is
            #  probably architecture and platfrom dependent!
            va_list = ctypes.cast(va_list, c_long_p)

            if notification_code == UI_NOTIFICATIONS.UI_GET_EA_HINT:
                # ea is just a number:
                #
                #     typedef uint32 	ea_t
                #
                # via: https://www.hex-rays.com/products/ida/support/sdkdoc/pro_8h.html#a7b0aeaed04e477c02cf8ea3452002d1a
                ea = va_list[0]
                buf = ctypes.cast(va_list[1], ctypes.c_char_p)
                bufsize = va_list[2]

                print('ui_get_ea_hint:')
                print('>.. notification code: %s' % (notification_code))
                print('>.. ea: %s' % (hex(ea)))
                print('>.. buf: %s' % (buf))
                print('>.. bufsize: %s' % (hex(bufsize)))

                the_hint = datetime.datetime.now().isoformat(' ')

                self.dll.qstrncpy(buf, ctypes.c_char_p(the_hint), bufsize)
                print('<.. buf: %s' % (buf))

                return 1

            elif notification_code == UI_NOTIFICATIONS.UI_GET_CUSTOM_VIEWER_HINT:
                viewer = ctypes.cast(va_list[0], c_long_p)
                place = ctypes.cast(va_list[1], c_long_p)
                important_lines = ctypes.cast(va_list[2], c_long_p)
                hint = ctypes.cast(va_list[3], c_char_pp)

                if not place:
                    print('ui_get_custom_viewer_hint: invalid place')
                    return 0

                print('ui_get_custom_viewer_hint:')
                print('>.. notification code: %s' % (notification_code))
                print('>.. important lines: %s %s' %
                      (important_lines, important_lines.contents))
                print('>.. hint: %s %s' % (hint, hint.contents))

                # so, we'd like to fetch the EA of the current view.
                # ideally, we'd do:
                #
                #     ea = place.toea()
                #
                # but `place` is a raw c++ object pointer, and ctypes isn't that smart.
                # next best would be to do something like:
                #
                #     place = self.dll.get_custom_viewer_place(viewer);
                #
                # however, this doesn't work because `get_custom_viewer_place` is not an exported routine.
                # it seems to be part of the IDA SDK static lib to which plugins link.
                #
                # next best would be to use `idaapi.get_custom_viewer_place`:
                #
                #     place = idaapi.get_custom_viewer_place(viewer);
                #
                # but, this doesn't work because we're mixing a ctypes pointer with a swig function.
                # so, we'll fall back to querying the current viewer, and fetching the place from there.

                # let's only display for disassembly listings
                #
                # i only know how to test the view/form type using the `get_tform_type` function.
                # therefore, we'll first query the current tform, and subsequently the current custom_viewer.
                tform = idaapi.get_current_tform()
                if idaapi.get_tform_type(tform) != idaapi.BWN_DISASM:
                    return 0

                viewer = idaapi.get_current_viewer()

                # `place` is a tuple (though techincally, a list), with elements:
                #  - place_t proxy
                #  - x position in characters
                #  - y position in characters from top of screen/form (-1 in graph view)
                place, x, y = idaapi.get_custom_viewer_place(viewer, True)

                the_hint = '0x%08X: %s' % (
                    place.toea(), datetime.datetime.now().isoformat(' '))

                important_lines[0] = ctypes.c_long(1)
                # we don't have access to the qstring c++ class methods,
                #  so we'll use a dummy routine to correctly set our qstring contents.
                # `replace_tabs` assigns from a char * to a qstring *.
                #
                # relevant idasdk documentation:
                #
                #    idaman THREAD_SAFE bool ida_export
                #    replace_tabs (
                #        qstring *out,
                #        const char *str,
                #        int tabsize)
                self.dll.replace_tabs(hint, ctypes.c_char_p(the_hint), 4)

                print('<.. important lines: %s %s' %
                      (important_lines, important_lines.contents))
                print('<.. hint: %s %s' % (hint, hint.contents))

                return 1

            return 0
Пример #21
0
 def viewer(cls):
     '''Return the current viewer.'''
     return idaapi.get_current_viewer()
Пример #22
0
def get_highlight():
    highlight_result = idaapi.get_highlight(idaapi.get_current_viewer())
    return highlight_result[
        0] if highlight_result and highlight_result[1] else ''