Ejemplo n.º 1
0
def accept_file(li, filename):
    """
    Check if the file is of supported format

    @param li: a file-like object which can be used to access the input data
    @param n : format number. The function will be called with incrementing
                number until it returns zero
    @return: 0 - no more supported formats
                string "name" - format name to display in the chooser dialog
                dictionary { 'format': "name", 'options': integer }
                options: should be 1, possibly ORed with ACCEPT_FIRST (0x8000)
                to indicate preferred format
    """
    if not idaxml.is_ida_version_supported():
        return 0
    # read 16K bytes to allow for the DTD
    data = li.read(0x4000)
    # look for start of <PROGRAM> element
    start = data.find("<PROGRAM")
    if start >= 0:
        s = data.find("<PROCESSOR ")
        p = data[s + 11:]
        e = p.find("/>")
        proc = p[:e]
        ida_kernwin.info("Processor specified in the XML file is:\n" + proc +
                         "\n\nYou must select and set the compatible " +
                         "IDA processor type.")
        return {'format': "XML PROGRAM file", 'options': 0x8001}
    return 0
def map_segments(li, table, file_offset, mclib_addr, no_save):
    for name, addr, size in table:
        seg = ida_segment.segment_t()
        seg.start_ea = BASE_ADDR + addr
        sclass = "CODE"

        if name in [b"image_h", b"img-hdr"]:
            sclass = "DATA"
        elif name == b"mclib":
            seg.start_ea = mclib_addr - 8
        elif name == b"rtm":
            seg.start_ea = S0CB_ADDR
        elif name in TRUSTLETS:
            if not no_save:
                extract_binary(li, name + b".tlbin", file_offset + addr, size)
            continue
        elif name != b"mtk":
            ida_kernwin.info("Unknown table entry '%s'" % decode(name))
            continue

        seg.end_ea = seg.start_ea + size
        seg.bitness = 1
        ida_segment.add_segm_ex(seg, decode(name), sclass, 0)
        li.file2base(file_offset + addr, seg.start_ea, seg.end_ea - 1, 0)

        if not no_save:
            filename = b"%s_%08x.bin" % (name, seg.start_ea)
            extract_binary(li, filename, file_offset + addr, size)
Ejemplo n.º 3
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
Ejemplo n.º 4
0
    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
 def OnButtonUpdate(self, *_):
     app = dict()
     app['app_url'] = self.GetControlValue(self.txtServer)
     app['un'] = self.GetControlValue(self.txtUser)
     app['pw'] = self.GetControlValue(self.txtPw)
     self.configuration['apps'][app['app_url']] = app
     self.listView.UpdateItems()
     self.RefreshField(self.fvChooser)
     # Select the newly added item
     self.SetControlValue(
         self.fvChooser,
         [self.configuration['apps'].keys().index(app['app_url'])])
     self.updateDpList()
     info("Updated / added connection %s." % app['app_url'])
 def OnButtonUpdate(self, *_):
     app = dict()
     app['app_url'] = self.GetControlValue(self.txtServer)
     app['un'] = self.GetControlValue(self.txtUser)
     app['pw'] = self.GetControlValue(self.txtPw)
     self.configuration['apps'][app['app_url']] = app
     self.listView.UpdateItems()
     self.RefreshField(self.fvChooser)
     # Select the newly added item
     self.SetControlValue(self.fvChooser, [
         self.configuration['apps'].keys().index(
             app['app_url']
         )])
     self.updateDpList()
     info("Updated / added connection %s." % app['app_url'])
Ejemplo n.º 7
0
Archivo: bb.py Proyecto: zined/winnie
def main():
    out_file_name = ida_kernwin.ask_file(True, 'basicblocks.bb',
                                         'Select output file')

    print('Will save to %s' % out_file_name)

    if os.path.isfile(out_file_name):
        # validate existing file before appending to it
        with open(out_file_name, 'r') as f:
            for line in f:
                if line.startswith('[') and module_name in line:
                    warning('Module %s already exists in %s' %
                            (module_name, os.path.basename(out_file_name)))
                    return

    with open(out_file_name, 'a') as f:
        f.write('[%s]\n' % (module_name, ))
        for fva in idautils.Functions():
            dump_bbs(fva, f)
        f.close()

    print('OK, done. Found %d basic blocks' % (len(dumped), ))
    ida_kernwin.info('Saved to %s' % (out_file_name, ))
Ejemplo n.º 8
0
def SCRIPT_ENTRY():
    """script entry point."""
    if not is_plugin():
        (kw.info("Success!") if install_plugin() else
            kw.warning("Error! Plugin could not be installed!"))
    return
Ejemplo n.º 9
0
def sr_main():
    global sr

    if sr:
        del sr
        sr = None
        print("Stopped recording")
    else:
        w = ida_kernwin.get_current_widget()
        title = "IDA View-A"
        if w:
            title = ida_kernwin.get_widget_title(w)
        title = ida_kernwin.ask_str(
            title, 0, "Please specify title of widget to capture")
        if title:
            path = ida_kernwin.ask_str("", ida_kernwin.HIST_DIR,
                                       "Please specify destination path")
            if path and os.path.exists(path):
                sr = screen_record_t(title, path)
                print("Started recording")


try:
    sr
    ida_kernwin.info("Already installed. Press %s to start/stop recording." %
                     HOTKEY)
except:
    sr = None
    sr_hotkey = ida_kernwin.add_hotkey(HOTKEY, sr_main)
    print("Press %s to start/stop recording" % HOTKEY)
Ejemplo n.º 10
0
 def show_info(msg):
     ida_kernwin.info(msg)
Ejemplo n.º 11
0
                    self.painting = False
                    self.transform = True
                    """workaround!
                    widget.render() causes widget to be repainted.
                    In order to deal with this situation, we'll issue
                    another repaint() and transform the widget"""
                    self.target.repaint()
        elif event.type() in [QtCore.QEvent.Close, QtCore.QEvent.Hide]:
            self.die()

        return QtCore.QObject.eventFilter(self, receiver, event)


def coffee_main():
    global coffee

    if coffee and not coffee.is_dead():
        coffee.die()
        coffee = None
        return
    coffee = painter_t()
    ida_kernwin.msg("Caffeinated\n")


try:
    coffee
    ida_kernwin.info("Already installed. Press %s" % HOTKEY)
except:
    coffee = None
    print("Press %s for coffee overload" % HOTKEY)
    ida_kernwin.add_hotkey(HOTKEY, coffee_main)
Ejemplo n.º 12
0
    def keyReleaseEvent(self, event):
        update = False
        key = event.key()
        modifiers = event.modifiers()

        shift_pressed = ((modifiers & Qt.ShiftModifier) == Qt.ShiftModifier)
        ctrl_pressed = ((modifiers & Qt.ControlModifier) == Qt.ControlModifier)

        if key == Qt.Key_F1 and ctrl_pressed:
            self.show_help()

        elif key == Qt.Key_G:
            addr = ask_addr(self.base + self.offs, 'Jump to address')
            if addr is not None:
                if self.sync:
                    ida_kernwin.jumpto(addr)
                else:
                    minea = ida_idaapi.get_inf_structure().get_minEA()
                    maxea = ida_idaapi.get_inf_structure().get_maxEA()
                    dst = min(max(addr, minea), maxea)
                    self.set_addr(dst)

        elif key == Qt.Key_S:
            if not self.fm.lock_sync:
                self.set_sync_state(not self.get_sync_state())
                update = True

        elif key == Qt.Key_T:
            self.render_data = not self.render_data
            self.repaint()

        elif key == Qt.Key_D:
            self.cur_formatter_idx = (self.cur_formatter_idx +
                                      1) % self.max_formatters
            self.repaint()

        elif key == Qt.Key_N:
            self.next_filter.emit()

        elif key == Qt.Key_B:
            self.prev_filter.emit()

        elif key == Qt.Key_F2:
            hlp = self.fm.help
            if hlp is None:
                hlp = 'Help unavailable'
            ida_kernwin.info('%s\n\n' % hlp)

        elif key == Qt.Key_F12:
            img = self.render_image(cursor=False)
            img = img.scaled(img.width() * self.pixelSize,
                             img.height() * self.pixelSize, Qt.KeepAspectRatio,
                             Qt.FastTransformation)
            done = False
            i = 0
            while not done:
                fname = 'IDACyber_%04d.bmp' % i
                if not os.path.isfile(fname):
                    if img.save(fname):
                        ida_kernwin.msg('File exported to %s\n' % fname)
                    else:
                        ida_kernwin.warning(
                            'Error exporting screenshot to %s.' % fname)
                    done = True
                i += 1
                if i > 40:
                    ida_kernwin.warning('Aborted. Error exporting screenshot.')
                    break

        elif key == Qt.Key_PageDown:
            self.set_offset_delta(-self.get_pixels_total())
            update = True

        elif key == Qt.Key_PageUp:
            self.set_offset_delta(self.get_pixels_total())
            update = True

        elif key == Qt.Key_Down:
            if shift_pressed:
                self.set_offset_delta(-1)
            else:
                self.set_offset_delta(-self.get_width())
            update = True

        elif key == Qt.Key_Up:
            if shift_pressed:
                self.set_offset_delta(1)
            else:
                self.set_offset_delta(self.get_width())
            update = True

        elif key == Qt.Key_Plus:
            if ctrl_pressed:
                self.set_zoom_delta(1)
            update = True

        elif key == Qt.Key_Minus:
            if ctrl_pressed:
                self.set_zoom_delta(-1)
            update = True

        self.key = None

        if update:
            if self.get_sync_state():
                ida_kernwin.jumpto(self.base + self.offs)
                self.activateWindow()
                self.setFocus()
            self.statechanged.emit()
            self.repaint()

        return
Ejemplo n.º 13
0
 def show_help(self):
     ida_kernwin.info("%s" % PLUGIN_HELP)
Ejemplo n.º 14
0
        pp.die()
        pp = None
        return
    w = ida_kernwin.get_current_widget()
    title = "IDA View-A"
    if w:
        title = ida_kernwin.get_widget_title(w)
    title = ida_kernwin.ask_str(title, 0, "Please specify title of widget")
    if title:
        path = ida_kernwin.ask_str(
            "", ida_kernwin.HIST_DIR,
            "Please specify path containing png files to play back")
        if path and os.path.exists(path):
            files = find_files(path, "*.png")
            print("found %d files" % len(files))
            if len(files):
                interval = ida_kernwin.ask_long(
                    100, "Please specify timer interval")
                if interval:
                    pp = png_player_t(title, files, interval=interval)
                    print("PNGs playing in widget %s" % title)


try:
    pp
    ida_kernwin.info("Already installed. Press %s to start/stop playback." %
                     HOTKEY)
except:
    pp = None
    print("Press %s to start/stop playing PNG files" % HOTKEY)
    ida_kernwin.add_hotkey(HOTKEY, pp_main)
Ejemplo n.º 15
0
 def show_help(self):
     global plugin_help
     ida_kernwin.info("%s" % plugin_help)