Beispiel #1
0
 def run(self, _):
     """
     This method is called when IDA is running the plugin as a script.
     """
     ida_kernwin.warning(
         "ida_medigate C++ plugin cannot be run as a script")
     return False
Beispiel #2
0
def create_segments(li):
    # create RAM segment
    create_ram_segment()

    # create segment for I/O registers
    # NES uses memory mapped I/O
    create_ioreg_segment()

    # create SRAM segment if supported by cartridge
    # if( INES_MASK_SRAM( hdr.rom_control_byte_0 ) )
    create_sram_segment()

    # create segment for expansion ROM
    create_exprom_segment()

    # load trainer, if one is present
    if (INES_MASK_TRAINER(hdr.rom_control_byte_0)):
        warning(
            "This ROM image seems to have a trainer.\n"
            "By default, this loader assumes the trainer to be mapped to $7000.\n"
        )
        load_trainer(li)

    # create segment for PRG ROMs
    create_rom_segment()
Beispiel #3
0
 def run(self, _):
     """
     This method is called when IDA is running the plugin as a script.
     Because IDArling isn't runnable per se, we need to return False.
     """
     ida_kernwin.warning("IDArling cannot be run as a script")
     return False
Beispiel #4
0
    def handle_new(self):
        new_name = self.new_name_w.text().encode('ascii',
                                                 'replace').strip().decode()

        if not itanium_mangler.check_identifier(new_name):
            ida_kernwin.warning('The name "%s" is invalid' % new_name)
            return

        struct_id = idc.get_struc_id(new_name)
        if struct_id != idc.BADADDR:
            if util.ask_yes_no(
                    'The struct "%s" already exists. Do you want to select it anyways?'
                    % new_name):
                self.struct_id = struct_id
                self.accept()
                return
            return

        self.struct_id = idaapi.add_struc(idc.BADADDR, new_name, False)
        if self.struct_id == idc.BADADDR:
            ida_kernwin.warning('Creating struct with the name "%s" failed' %
                                new_name)
            return

        self.accept()
Beispiel #5
0
    def __init__(self, f_debug, db_path, min_bytes, f_ex_libthunk, f_update, f_ana_exp, ana_pre, f_ana_cmp = False, f_fol_cmp = False, ana_fol='', threshold = None, threshold_cfg = None, max_bytes_for_score = None, ratio = 0):
        self.f_debug = f_debug
        self.conn = sqlite3.connect(db_path)
        self.cur = self.conn.cursor()
        self.init_db()
        self.in_memory_db()        
        self.min_bytes = min_bytes
        self.f_ex_libthunk = f_ex_libthunk
        # for export
        self.f_update = f_update
        self.f_ana_exp = f_ana_exp        
        self.ana_pre = ana_pre
        if f_ana_exp:
            self.ana_pat = re.compile(self.ana_pre)
        # for compare
        self.f_ana_cmp = f_ana_cmp
        self.f_fol_cmp = f_fol_cmp
        self.ana_fol = ana_fol
        self.threshold = threshold
        self.threshold_cfg = threshold_cfg
        self.max_bytes_for_score = max_bytes_for_score
        self.ratio = float(ratio)

        self.idb_path = get_idb_path()
        self.sha256 = ida_nalt.retrieve_input_file_sha256()
        try:
            self.sha256 = self.sha256.lower()
        except AttributeError:
            message = 'ida_nalt.retrieve_input_file_sha256() returned None. Probably the IDB was generated by old IDA (<6.9). Check the version by ida_netnode.cvar.root_node.supstr(ida_nalt.RIDX_IDA_VERSION)'
            error(message)
            ida_kernwin.warning(message)            
        self.md5 = ida_nalt.retrieve_input_file_md5().lower()
Beispiel #6
0
    def OnCreate(self, form):
        self.form = form
        self.parent = self.FormToPyQtWidget(form)

        vl = QVBoxLayout()
        hl = QHBoxLayout()
        hl2 = QHBoxLayout()
        hl3 = QHBoxLayout()
        hl4 = QHBoxLayout()

        flt = QLabel()
        flt.setText('Filter:')
        hl.addWidget(flt)

        self.cb = QCheckBox('Sync')
        self.cb.setChecked(True)
        self.cb.stateChanged.connect(self._toggle_sync)
        hl2.addWidget(self.cb)

        self.status = QLabel()
        self.status.setText('Cyber, cyber!')
        hl4.addWidget(self.status)

        self.pw = PixelWidget(self.parent, IDACyberForm.idbh)
        self.pw.setFocusPolicy(Qt.StrongFocus | Qt.WheelFocus)

        self.pw.statechanged.connect(self._update_widget)
        self.pw.next_filter.connect(self._select_next_filter)
        self.pw.prev_filter.connect(self._select_prev_filter)

        self.filterlist = self._load_filters(self.pw)
        if not len(self.filterlist):
            ida_kernwin.warning(
                "IDACyber: no filters found within /plugins/cyber/")
            return

        self.pw.set_filter(self.filterlist[0][1], 0)
        self.pw.set_addr(ida_kernwin.get_screen_ea())

        self.filterChoser = QComboBox()
        self.filterChoser.addItems(
            [obj.name for filter, obj in self.filterlist])
        self.filterChoser.currentIndexChanged.connect(self._select_filter)
        hl.addWidget(self.filterChoser)
        hl.addStretch(1)

        vl.addWidget(self.pw)

        vl.addLayout(hl)
        vl.addLayout(hl2)
        vl.addLayout(hl3)
        vl.addLayout(hl4)

        self.parent.setLayout(vl)
        if IDACyberForm.hook is not None:
            IDACyberForm.hook.new_ea.connect(self._change_screen_ea)
        self.clean_init = True
        return
Beispiel #7
0
def ChangeVariableType(func_ea, lvar, tif):
    lsi = ida_hexrays.lvar_saved_info_t()
    lsi.ll = lvar
    lsi.type = ida_typeinf.tinfo_t(tif)
    if not ida_hexrays.modify_user_lvar_info(func_ea, ida_hexrays.MLI_TYPE,
                                             lsi):
        ida_kernwin.warning("Could not modify lvar type for %s" % lvar.name)
        return False
    return True
Beispiel #8
0
 def init(self):
     if ida_hexrays.init_hexrays_plugin():
         self.hooks = callinfo_provider_t()
         self.hooks.hook()
         ida_kernwin.warning(
             "Installed callinfo provider sample (vds21.py)\n" +\
             "Please note that it is just an example\n" +\
             "and will spoil your decompilations!")
         return ida_idaapi.PLUGIN_KEEP  # keep us in the memory
Beispiel #9
0
    def generate(self):
        idaapi.visit_patched_bytes(0, idaapi.BADADDR, self.get_patch_byte)
        if len(self.patched_bytes) == 0:
            msg = 'Cannot generate patch because there is no patch applied.'
            print('genpatch: %s' % msg)
            ida_kernwin.warning(msg)
            return False

        template_path = ''
        for path in sys.path:
            if 'plugins' in path:
                template_path = os.path.join(path, 'patch_template.txt')

        patch_path = idc.get_input_file_path() + '_patch.py'

        template_data = None
        with open(template_path, "r") as f:
            template_data = f.readlines()

        lines = 13
        with open(patch_path, "w") as f:
            for data in self.patched_bytes:
                template_data.insert(lines,
                                     "# address: 0x%x\n" % data['begin_addr'])
                lines += 1
                template_data.insert(lines,
                                     "# function name: %s\n" % data['name'])
                lines += 1
                template_data.insert(
                    lines,
                    "# comment: %s\n" % data['comment'].replace('\n', ' '))
                lines += 1
                template_data.insert(
                    lines, "matches = re.findall('%s', target_data)\n" %
                    data['original'])
                lines += 1
                template_data.insert(lines, "if len(matches) == 1:\n")
                lines += 1
                template_data.insert(
                    lines,
                    "    target_data = target_data.replace('%s', '%s')\n" %
                    (data['original'], data['patched']))
                lines += 1
                template_data.insert(lines, "else:\n")
                lines += 1
                template_data.insert(
                    lines, '    print("Patch pattern isn\'t unique")\n')
                lines += 1
                template_data.insert(lines, "    sys.exit()\n")
                lines += 1

            f.writelines(template_data)

        msg = 'Successfully generated patch to %s from Patched Bytes' % patch_path
        print('genpatch: %s' % msg)
        ida_kernwin.info(msg)
        return True
Beispiel #10
0
 def _register_action(self, hotkey, desc):
     actname = HRDevHelper.get_action_name(desc)
     print(actname)
     if ida_kernwin.register_action(
             ida_kernwin.action_desc_t(actname, desc, hotkey_handler_t(),
                                       hotkey, None, -1)):
         self._registered_actions[actname] = (desc, hotkey)
     else:
         ida_kernwin.warning("%s: failed registering action" % PLUGIN_NAME)
Beispiel #11
0
def load_cfg(reload=False):
    """loads xray configuration from file. Creates and loads default config
    if none is present."""
    global PATTERN_LIST
    global HIGH_CONTRAST
    global DO_FILTER

    cfg_file = get_cfg_filename()
    kw.msg("%s: %sloading %s...\n" % (PLUGIN_NAME,
        "re" if reload else "",
        cfg_file))
    if not os.path.isfile(cfg_file):
        kw.msg("%s: %s does not exist! creating default config... " % (PLUGIN_NAME, cfg_file))
        try:
            with open(cfg_file, "w") as f:
                f.write(DEFAULT_CFG)
                kw.msg("success!\n")
        except:
            kw.msg("failed!\n")
            return False
        return load_cfg(reload=True)

    PATTERN_LIST = []

    config = ConfigParser.RawConfigParser()
    config.readfp(open(cfg_file))

    # read all sections
    for section in config.sections():
        expr_list = []
        if section.startswith("group_"):
            for k,v in config.items(section):
                if k.startswith("expr_"):
                    expr_list.append(v)
            try:
                bgcolor = swapcol(int(config.get(section, "bgcolor"), 16))
            except:
                bgcolor = swapcol(0x000000)
            try:
                hint = config.get(section, "hint")
            except:
                hint = None
            PATTERN_LIST.append(ConfigGroupSection(expr_list, bgcolor, hint))
        elif section == "global":
            try:
                HIGH_CONTRAST = config.getboolean(section, "high_contrast")
            except:
                HIGH_CONTRAST = False
            if not reload:
                try:
                    DO_FILTER = config.getboolean(section, "auto_enable")
                except:
                    DO_FILTER = False

    if not len(PATTERN_LIST):
        kw.warning("Config file does not contain any regular expressions.")
    return True
    def init(self):
        """Set up menu hooks and implements search methods."""

        valid_config = False
        self.menu = None
        config_file = os.path.join(idaapi.get_user_idadir(), 'virustotal.conf')
        vtsetup = VTpluginSetup(config_file)

        if vtsetup.check_version():
            ida_kernwin.info(
                'VirusTotal\'s IDA Pro Plugin\nNew version available!')
            logging.info('[VT Plugin] There\'s a new version of this plugin!')
        else:
            logging.debug('[VT Plugin] No update available.')

        if os.path.exists(config_file):
            valid_config = vtsetup.read_config()
        else:
            answer = vtsetup.show_warning()
            if answer == 1:  # OK
                vtsetup.auto_upload = True
                valid_config = vtsetup.write_config()
            elif answer == 0:  # NO
                vtsetup.auto_upload = False
                valid_config = vtsetup.write_config()
            elif answer == -1:  # Cancel
                valid_config = False

        if valid_config:
            checksample = CheckSample(vtsetup.auto_upload, vtsetup.file_path)
            checksample.start()

            self.menu = Popups()
            self.menu.hook()
            arch_info = idaapi.get_inf_structure()

            try:
                if arch_info.procName in self.SUPPORTED_PROCESSORS:
                    VTGrepWildcards.register(self, 'Search for similar code')
                    VTGrepWildCardsStrict.register(
                        self, 'Search for similar code (strict)')
                    VTGrepWildCardsFunction.register(
                        self, 'Search for similar functions')
                else:
                    logging.info('\n - Processor detected: %s',
                                 arch_info.procName)
                    logging.info(
                        ' - Searching for similar code is not available.')
                VTGrepBytes.register(self, 'Search for bytes')
                VTGrepStrings.register(self, 'Search for string')
            except:
                logging.error('[VT Plugin] Unable to register popups actions.')
        else:
            logging.info(
                '[VT Plugin] Plugin disabled, restart IDA to proceed. ')
            ida_kernwin.warning('Plugin disabled, restart IDA to proceed.')
        return idaapi.PLUGIN_KEEP
Beispiel #13
0
 def verify_project(self):
     """
     Verify a valid project is currently active.
     Show IDA warning if not.
     :return: None
     """
     try:
         super(IdaLoader, self).verify_project()
     except IOError as e:
         ida_kernwin.warning(e.message)
         raise e
Beispiel #14
0
 def _set_user_func(self):
     while True:
         func_def = ask_text(
             0, self.func_def,
             "Please define function (must return tuple(RR,GG,BB) format")
         if func_def is None:
             break
         res, s = self._compile(func_def)
         if res:
             break
         warning("%s" % s)
Beispiel #15
0
    def add_node(self, i):
        for k_obj_id in self.reverse.keys():
            if i.obj_id == k_obj_id:
                ida_kernwin.warning("bad ctree - duplicate nodes! (i.ea=%x)" % i.ea)
                return -1

        n = self.cg.add_node()
        if n <= len(self.cg.items):
            self.cg.items.append(i)
        self.cg.items[n] = i
        self.reverse[i.obj_id] = n
        return n
Beispiel #16
0
    def add_node(self, i):
        for k in self.reverse.keys():
            if i.obj_id == k.obj_id:
                ida_kernwin.warning("bad ctree - duplicate nodes! (i.ea=%x)" % i.ea)
                self.cg.dump()
                return -1

        n = self.cg.add_node()
        if n <= len(self.cg.items):
            self.cg.items.append(i)
        self.cg.items[n] = i
        self.reverse[i] = n
        return n
Beispiel #17
0
    def search_function_with_wildcards():
        addr_current = idc.get_screen_ea()
        addr_func = idaapi.get_func(addr_current)

        if not addr_func:
            logging.error(
                '[VT Plugin] Current address doesn\'t belong to a function')
            ida_kernwin.warning(
                'Point the cursor in an area beneath a function.')
        else:
            search_vt = vtgrep.VTGrepSearch(addr_start=addr_func.start_ea,
                                            addr_end=addr_func.end_ea)
            search_vt.search(True, False)
Beispiel #18
0
 def activate(self, ctx):
     if self.name == HRDevHelper.get_action_name(
             HRDevHelper.act_show_ctree):
         show_ctree_graph()
     elif self.name == HRDevHelper.get_action_name(
             HRDevHelper.act_show_sub_tree):
         show_ctree_graph(create_subgraph=True)
     elif self.name == HRDevHelper.get_action_name(
             HRDevHelper.act_show_context):
         context_viewer_t.open()
     else:
         ida_kernwin.warning("Not implemented")
     return 1
Beispiel #19
0
    def log(cls, level, msg, debug):
        if level == 'console':
            msg_t = '%s\n' % msg
        else:
            msg_t = '[%s] %s\n' % (level, msg)

        if cls.log_fd:
            if cls.enable_dbg or debug:
                cls.log_fd.write(msg_t)
                cls.log_fd.flush()

        ida_kernwin.msg(msg_t)
        if level == 'warn' or level == 'erro':
            ida_kernwin.warning(msg_t)
Beispiel #20
0
 def init(self):
     result = idaapi.PLUGIN_SKIP
     if ida_hexrays.init_hexrays_plugin():
         try:
             self.config = load_cfg()
         except:
             ida_kernwin.warning((
                 "%s failed parsing %s.\n"
                 "If fixing this config file manually doesn't help, please delete the file and re-run the plugin.\n\n"
                 "The plugin will now terminate." %
                 (PLUGIN_NAME, get_cfg_filename())))
         else:
             result = idaapi.PLUGIN_KEEP
     return result
Beispiel #21
0
    def _set_user_expr(self):
        while True:
            xpr = askstr(0, self.xpr, "Please enter expression")
            if xpr is None:
                break

            try:
                c = 0
                r, g, b = eval(xpr)
                self.xpr = xpr
                break
            except:
                warning("Invalid expression!")
                continue
Beispiel #22
0
 def on_mb_click(self, event, addr, size, mouse_offs):
     if event.button() == Qt.RightButton:
         if self.torch:
             self.flicker_idx = self.flicker_values[self.numframes / 2]
             if self.timer:
                 unregister_timer(self.timer)
                 self.timer = None
             else:
                 warning("!!!Bug!!!")
         else:
             self._enable_timer()
         self.torch = not self.torch
         self.pw.on_filter_request_update()
     return
Beispiel #23
0
Datei: vds5.py Projekt: ylkcy/src
    def add_node(self, i):
        for k, _ in self.reverse:
            if i.obj_id == k.obj_id:
                ida_kernwin.warning("bad ctree - duplicate nodes! (i.ea=%x)" %
                                    i.ea)
                self.cg.dump()
                return -1

        n = self.cg.add_node()
        if n <= len(self.cg.items):
            self.cg.items.append(i)
        self.cg.items[n] = i
        self.reverse.append((i, n))
        return n
Beispiel #24
0
    def _set_pattern(self):
        while True:
            pat = ask_str(self.pattern, 0, "Regular expression:")
            if pat is None:
                break

            try:
                c = 0
                prog = re.compile(pat)
                self.pattern = pat
                self.regex = prog
                break
            except:
                warning("Invalid expression!")
                continue
Beispiel #25
0
    def _set_pattern(self):
        while True:
            pat = askstr(0, self.pattern, "Please specify pattern")
            if pat is None:
                break

            try:
                c = 0
                prog = re.compile(pat)
                self.pattern = pat
                self.regex = prog
                break
            except:
                warning("Invalid pattern!")
                continue
Beispiel #26
0
def create_struct(name, fields, size):

    struct_id = idaapi.get_struc_id(name)
    # print struct_id
    if struct_id != idaapi.BADADDR:
        i = ida_kernwin.ask_yn(
            0,
            "A class structure for %s already exists. Are you sure you want to remake it?"
            % name)
        if i == idaapi.BADADDR:
            return
        if i == 1:
            idaapi.del_struc_members(idaapi.get_struc(struct_id), 0,
                                     idaapi.get_struc_size(struct_id))
            # struct_id = idc.AddStrucEx(idaapi.BADADDR, name + "_vtbl", 0)
    else:
        struct_id = idaapi.add_struc(idaapi.BADADDR, name, 0)
    if struct_id == idaapi.BADADDR:
        Warning(
            "Could not create the class structure!.\nPlease check something.")
        return
    sptr = idaapi.get_struc(struct_id)
    for off in fields:
        off, type_name, type_kind, field_name = fields[off]
        print(
            "Process field. Off = 0x%04X, type_name = %s (%d: %s), field_name = %s"
            %
            (off, type_name, type_kind, type_sizes[type_kind][0], field_name))
        type_size = type_sizes[type_kind][1]
        ret = ida_struct.add_struc_member(sptr, field_name.decode(), off,
                                          flags_dict[type_size], None,
                                          type_size)
        if ret != 0:
            ida_kernwin.warning("Unknown error! Err = %d" % ret)
            return
        mptr = ida_struct.get_member(sptr, off)
        ida_struct.set_member_cmt(
            mptr, " --> %s (%d: %s)" %
            (type_name.decode(), type_kind, type_sizes[type_kind][0]), False)
    struct_size = ida_struct.get_struc_size(sptr)
    if size < struct_size:
        ida_kernwin.warning(
            "Struct create error! final size (%d) > instanse size (%d)" %
            (struct_size, size))
    elif size > struct_size:
        for i in range(size - struct_size):
            ida_struct.add_struc_member(sptr, "dummy%d" % i, idaapi.BADADDR,
                                        idaapi.FF_BYTE, None, 1)
Beispiel #27
0
    def run(self, _):
        fn = ida_funcs.get_func(ida_kernwin.get_screen_ea())
        if fn is None:
            ida_kernwin.warning("Please position the cursor within a function")
            return True

        mmat = MCExplorer.ask_desired_maturity()
        if mmat == 0:
            return True

        hf = ida_hexrays.hexrays_failure_t()
        mba = Native.gen_microcode(fn, hf, None, 0, mmat)
        if not mba:
            return True

        fn_name = ida_funcs.get_func_name(fn.start_ea)
        mmat_name = LEVELS[mmat - 1]
        MCTextView(mba, fn_name, mmat_name).Show()
        return True
Beispiel #28
0
    def activate(self, ctx):
        vu = ida_hexrays.get_widget_vdui(ctx.widget)
        if not IsPtrSizedLvar(vu):
            return 1

        lvar = vu.item.get_lvar()
        name = ida_kernwin.ask_str(
            "", ida_kernwin.HIST_IDENT,
            "Please enter the API name for which to set the type")
        if name is None:
            return 1

        ptrTif = GetTypeSignature(name)
        if ptrTif is None:
            ida_kernwin.warning("Could not get type for \"%s\"" % name)
            return 1

        ChangeVariableType(vu.cfunc.entry_ea, lvar, ptrTif)
        vu.cfunc.refresh_func_ctext()

        return 1
Beispiel #29
0
 def OnKeydown(self, vkey, shift):
     if vkey == ord("G"):
         g = microcode_graphviewer_t(self._mba, self.title, self.lines)
         if g:
             g.Show()
             self._fit_graph(g)
             self._dock_widgets(
                 g, dockpos=kw.DP_FLOATING if shift else kw.DP_RIGHT)
         return True
     elif vkey == ord("I"):
         """TODO: at some point, the textual representation of the mba
              should manually be created.
           -> we would no longer have to parse the textual output
              that is created by the gen_microcode() function
           .> we may insert COLOR_ADDR tags which would allow us to
              contextually link different viewers"""
         widget = self.GetWidget()
         line = kw.get_custom_viewer_curline(widget, False)
         line = ida_lines.tag_remove(line)
         p = line.find(" ")
         if p != -1 and '.' in line[:p]:
             block, serial = line.split('.')[:2]
             serial = serial.strip().split(' ')[0]
             g = microcode_insnviewer_t(self._mba,
                                        self.mmat_name, self.fn_name,
                                        int(block), int(serial))
             if g:
                 g.Show()
                 self._fit_graph(g)
                 self._dock_widgets(
                     g, dockpos=kw.DP_FLOATING if shift else kw.DP_TAB)
         else:
             message = (
                 "There is something wrong with the output generated by gen_microcode()!\n"
                 "Please rerun '%s.py'!" % PLUGIN_NAME)
             if line.startswith(";") or not (len(line)):
                 message = "Please position the cursor on a microcode instruction."
             kw.warning(message)
         return True
     return False
Beispiel #30
0
    def search(self, wildcards=False, strict=False):
        """Processes current selection and generates a valid query for VTGrep.

    Args:
      wildcards: search replacing offsets and memory locations with
        widlcards (True) or look for a sequence of bytes (False)
      strict: All the inmediate values (constants) are wildcarded (True)
        or wildcard only values that are identified as offsets or
        memory addresses (False)

    Checks current lines selected in the disassembly window, call the
    appropriate method to generate a valid query. Finally, open the
    (default) web browser to launch the query.
    """

        str_buf = None

        if self.string_searching:
            # str_buf = self.string_searching.encode("utf-8").hex()
            str_buf = binascii.hexlify(self.string_searching).decode('utf-8')
        else:
            str_buf = self.__create_query(wildcards, strict)
            if wildcards and str_buf is not None:
                str_buf = self.__sanitize(self.__reduce_query(str_buf))

        # After creating the search string, checks if new size is valid
        if str_buf is None:
            logging.error('[VTGREP] Invalid query length or area selected.')
            ida_kernwin.warning('Invalid query length or area selected.')
        else:
            len_query = len(str_buf)

            if len_query and self._MIN_QUERY_SIZE >= len_query:
                logging.error('[VTGREP] The query produced is too short.')
                ida_kernwin.warning('The query produced is too short.')
            elif len_query and len_query > self._MAX_QUERY_SIZE:
                logging.error('[VTGREP] The query produced is too long.')
                ida_kernwin.warning('The query produced is too long.')
            else:
                str_buf = '{' + str_buf + '}'
                vtgrep_url = 'www.virustotal.com/gui/search/content:{}/files'
                url = 'https://{}'.format(quote(vtgrep_url.format(str_buf)))

                try:
                    webbrowser.open_new(url)
                except:
                    logging.error(
                        '[VTGREP] Error while opening the web browser.')
                    ida_kernwin.warning('Error while opening the web browser.')
Beispiel #31
0
def load_cfg():
    """loads xray configuration from file or creates default config
    if none is present."""
    global PATTERN_LIST
    global BGCOLOR

    cfg_file = get_cfg_filename()
    kw.msg("%s: loading %s... " % (PLUGIN_NAME, cfg_file))
    if not os.path.isfile(cfg_file):
        kw.msg("failed!\n"
               "> file does not exist: %s\n"
               "> creating default config... " % cfg_file)
        try:
            with open(cfg_file, "w") as f:
                f.write(DEFAULT_CFG)
                kw.msg("success!\n")
        except:
            kw.msg("failed!\n")
            return False
        return load_cfg()

    PATTERN_LIST = []

    # TODO: error-handling
    config = ConfigParser.ConfigParser()
    config.read(cfg_file)

    # read all regex expressions
    for _, v in config.items("regex"):
        PATTERN_LIST.append(v)

    # read bg color
    BGCOLOR = swapcol(int(config.get("ui", "bgcolor"), 16))

    if not len(PATTERN_LIST):
        kw.warning("Config file does not contain any regular expressions.")
    kw.msg("success!\n")
    return True
Beispiel #32
0
def main():
    if not ida_dbg.is_debugger_on():
        ida_kernwin.warning("Please run the process first!")
        return
    if ida_dbg.get_process_state() != -1:
        ida_kernwin.warning("Please suspend the debugger first!")
        return

    # get all debug namesp
    dn = ida_name.get_debug_names(ida_ida.cvar.inf.min_ea, ida_ida.cvar.inf.max_ea)
    # initiate a nearest name search (using debug names)
    nn = ida_name.NearestName(dn)

    ret, callstack = CallStackWalk(nn)
    if ret:
        title = "Call stack walker (thread %X)" % (ida_dbg.get_current_thread())
        ida_kernwin.close_chooser(title)
        c = CallStackWalkChoose(title, callstack)
        c.Show(True)
    else:
        ida_kernwin.warning("Failed to walk the stack:" + callstack)
Beispiel #33
0
This script fetches the API reference (from MSDN) of a given highlighted identifier
and returns the results in a new web browser page.

This script depends on the feedparser package: http://code.google.com/p/feedparser/
"""
from __future__ import print_function

# -----------------------------------------------------------------------
import ida_kernwin
import ida_name
import ida_idaapi

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

def get_url(ident):
    """
    Note: This code is left in a separate, toplevel function so that
    tests can easily override it and provide a replacement file://
    URL and work on machines without an internet connection
    """
    try:
        # This is a 'hook' to enable testing on machines disconnected
        # from the internet (we're not testing feedparser's HTTPS URL
        # download capabilities anyway)
        import sys
        return sys.modules["__main__"].get_url(ident)
    except:
        return "https://social.msdn.microsoft.com/search/en-US/feed?query=%s&format=RSS&theme=feed%%2fen-us" % ident