示例#1
0
    def autoenum(self):
        common_value = get_common_value()

        enum_name = idaapi.ask_str(self._last_enum, 0, "Enum Name")
        if enum_name is None:
            return

        if not enum_name:
            enum_name = None

        self._last_enum = enum_name

        # Can't ask with negative numbers.
        if common_value >> ((8 * sark.core.get_native_size()) - 1):
            common_value = 0

        const_value = idaapi.ask_long(common_value, "Const Value")
        if const_value is None:
            return

        modify = True

        try:
            enum = sark.add_enum(enum_name)

        except sark.exceptions.EnumAlreadyExists:
            enum = sark.Enum(enum_name)
            yes_no_cancel = idaapi.ask_yn(idaapi.ASKBTN_NO,
                                          "Enum already exists. Modify?\n")
            if yes_no_cancel == idaapi.ASKBTN_CANCEL:
                return

            elif yes_no_cancel == idaapi.ASKBTN_YES:
                modify = True

            else:  # yes_no_cancel == idaapi.ASKBTN_NO:
                modify = False

        member_name = const_name(enum, const_value)

        if modify:

            try:
                enum.members.add(member_name, const_value)
            except sark.exceptions.SarkErrorAddEnumMemeberFailed as ex:
                idaapi.msg("[AutoEnum] Adding enum member failed: {}.".format(
                    ex.message))

        else:
            for member in enum.members:
                if member.value == const_value:
                    member_name = member.name
                    break
                else:
                    return

        # Apply the enum
        apply_enum_by_name(enum, member_name)
示例#2
0
 def OnKeydown(self, vkey, shift):
     """
     User pressed a key
     @param vkey: Virtual key code
     @param shift: Shift flag
     @return: Boolean. True if you handled the event
     """
     print "OnKeydown, vk=%d shift=%d" % (vkey, shift)
     # ESCAPE?
     if vkey == 27:
         self.Close()
     # VK_DELETE
     elif vkey == 46:
         n = self.GetLineNo()
         if n is not None:
             self.DelLine(n)
             self.Refresh()
             print "Deleted line %d" % n
     # Goto?
     elif vkey == ord('G'):
         n = self.GetLineNo()
         if n is not None:
             v = idaapi.ask_long(self.GetLineNo(), "Where to go?")
             if v:
                 self.Jump(v, 0, 5)
     elif vkey == ord('R'):
         print "refreshing...."
         self.Refresh()
     elif vkey == ord('C'):
         print "refreshing current line..."
         self.RefreshCurrent()
     elif vkey == ord('A'):
         s = idaapi.ask_str("NewLine%d" % self.Count(), 0,
                            "Append new line")
         self.AddLine(s)
         self.Refresh()
     elif vkey == ord('X'):
         print "Clearing all lines"
         self.ClearLines()
         self.Refresh()
     elif vkey == ord('I'):
         n = self.GetLineNo()
         s = idaapi.ask_str("InsertedLine%d" % n, 0, "Insert new line")
         self.InsertLine(n, s)
         self.Refresh()
     elif vkey == ord('E'):
         l = self.GetCurrentLine(notags=1)
         if not l:
             return False
         n = self.GetLineNo()
         print "curline=<%s>" % l
         l = l + idaapi.COLSTR("*", idaapi.SCOLOR_VOIDOP)
         self.EditLine(n, l)
         self.RefreshCurrent()
         print "Edited line %d" % n
     else:
         return False
     return True
示例#3
0
 def OnKeydown(self, vkey, shift):
     """
     User pressed a key
     @param vkey: Virtual key code
     @param shift: Shift flag
     @return: Boolean. True if you handled the event
     """
     print("OnKeydown, vk=%d shift=%d" % (vkey, shift))
     # ESCAPE?
     if vkey == 27:
         self.Close()
     # VK_DELETE
     elif vkey == 46:
         n = self.GetLineNo()
         if n is not None:
             self.DelLine(n)
             self.Refresh()
             print("Deleted line %d" % n)
     # Goto?
     elif vkey == ord('G'):
         n = self.GetLineNo()
         if n is not None:
             v = idaapi.ask_long(self.GetLineNo(), "Where to go?")
             if v:
                 self.Jump(v, 0, 5)
     elif vkey == ord('R'):
         print("refreshing....")
         self.Refresh()
     elif vkey == ord('C'):
         print("refreshing current line...")
         self.RefreshCurrent()
     elif vkey == ord('A'):
         s = idaapi.ask_str("NewLine%d" % self.Count(), 0, "Append new line")
         self.AddLine(s)
         self.Refresh()
     elif vkey == ord('X'):
         print("Clearing all lines")
         self.ClearLines()
         self.Refresh()
     elif vkey == ord('I'):
         n = self.GetLineNo()
         s = idaapi.ask_str("InsertedLine%d" % n, 0, "Insert new line")
         self.InsertLine(n, s)
         self.Refresh()
     elif vkey == ord('E'):
         l = self.GetCurrentLine(notags=1)
         if not l:
             return False
         n = self.GetLineNo()
         print("curline=<%s>" % l)
         l = l + idaapi.COLSTR("*", idaapi.SCOLOR_VOIDOP)
         self.EditLine(n, l)
         self.RefreshCurrent()
         print("Edited line %d" % n)
     else:
         return False
     return True
示例#4
0
 def slot_add_n_bytes_feature(self, action):
     """ """
     count = idaapi.ask_long(
         16,
         f"Enter number of bytes (1-{capa.features.common.MAX_BYTES_FEATURE_SIZE}):"
     )
     if count and 1 <= count <= capa.features.common.MAX_BYTES_FEATURE_SIZE:
         item = self.selectedItems()[0].data(0, 0x100)
         item.value = item.value[:count]
         self.editor.update_features([item])
示例#5
0
 def set_stack_entries(self):
     value = idaapi.ask_long(config.n_stack_entries,
                             "Set the number of stack entries to show")
     if value is not None:
         if value <= 0:
             idaapi.warning("Negative values are not allowed")
             return False
         config.n_stack_entries = value
         self.reload_info()
         return True
     return False
示例#6
0
    def set_deref_levels(self):
        value = idaapi.ask_long(config.max_deref_levels, "Set current dereferencing levels to show")
        if value is not None:
            if value < 0:
                idaapi.warning("Negative values are not allowed")
                return False

            if value > config.deref_limit:
                idaapi.warning("Value should not exceed the dereferencing limit: %d" % config.deref_limit)
                return False

            config.max_deref_levels = value
            self.reload_info()
            return True
        return False
示例#7
0
def rename_immediate():
    highlighted = sark.get_highlighted_identifier()
    try:
        desired = int(highlighted, 0)
    except (ValueError, TypeError):
        desired = None
    value = idaapi.ask_long(get_common_value(desired), "Const Value")
    if value is None:
        return

    name = idaapi.ask_str("", 0, "Constant Name")
    if name is None:
        return

    try:
        enum = sark.Enum('GlobalConstants')
    except sark.exceptions.EnumNotFound:
        enum = sark.add_enum('GlobalConstants')

    enum.members.add(name, value)
    apply_enum_by_name(enum, name)
示例#8
0
 def set_string(self):
     start = idc.here()
     str_len = idaapi.ask_long(0, "string len...")
     if str_len:
         MakeStr(start, start + str_len)
     return 1
示例#9
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
示例#10
0
    def activate(self, ctx):
        if self.action in ACTION_CONVERT:
            sel, start, end = lazy_read_selection()
            if not sel:
                idc.msg("[LazyIDA] Nothing to convert.")
                return False

            size = end - start
            data = idc.get_bytes(start, size)
            if isinstance(data, str):  # python2 compatibility
                data = bytearray(data)
            assert size == len(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_COPYDATA:
            # added by merc, modfiy by HTC
            sel, start, end = lazy_read_selection()
            if not sel:
                return 0

            data = idaapi.get_bytes(start, end - start)
            data = data.encode('hex')
            copy_to_clip(data)
            print("[LazyIDA] copied hex string '%s'" % data)
        elif self.action == ACTION_XORDATA:
            sel, start, end = lazy_read_selection()
            if not sel:
                return 0

            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:
            sel, start, end = lazy_read_selection()
            if not sel:
                return 0
            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.")
        elif self.action == ACTION_COPYNAME:
            copy_highlight_name()
        elif self.action == ACTION_PASTENAME:
            paste_highlight_name()
        else:
            return 0

        return 1
示例#11
0
if __name__ == '__main__':
    #清空输出窗口
    form = idaapi.find_tform("Output window")
    idaapi.switchto_tform(form, True)
    idaapi.process_ui_action("msglist:Clear")

    #save to file
    path = os.path.abspath(__file__)
    path = os.path.realpath(__file__)
    path = os.path.dirname(path)

    #
    target_path = idc.GetInputFilePath()
    target_file = idc.GetInputFile()

    if idaapi.init_hexrays_plugin():
        #print("Hex-rays version %s has been detected" % idaapi.get_hexrays_version())
        pass
    else:
        load_plugin_decompiler(is_bit64)

    #
    #get_strings()
    sub_value = idaapi.ask_long(0x20, 'please input stack additional value')
    if sub_value is not None:
        #0x20 为在原来基础上再增加的空间大小
        patch_vul_func(sub_value)
    else:
        print('you select Cancel operate')
示例#12
0
 def _activate(self, ctx):
     distance = idaapi.ask_long(4, 'Distance From Source')
     show_xref_graph(ctx.cur_ea, to=False, distance=distance)