def start_dump(bv,funct): ret,settings = SettingsGUI(bv) if ret: execute = bv.file.original_filename if settings['name'] != "": execute = settings['name'] bn.log.log_info('Start \''+execute+' '+settings['cmd']+'\' on '+settings['dev'].id+' device ') data = {} ## Set the device data['device'] = settings['dev'] ## Command to spawn data['execute'] = [execute] if settings['cmd'] != "": for i in settings['cmd'].split(' '): data['execute'].append(i) ## Spawning spawn = True if settings['spawn'] == 1: data['pid'] = settings['pid'] spawn = False ## Preparing block data['dump'] = [] data['maps'] = [] data['entry'] = funct.start stalker = FridaHandler(data,bv.file.original_filename,spawn,'dump') stalker.start() bn.show_message_box('Frida stalking','Press OK button to terminate stalking') stalker.cancel() stalker.join() CreateMarkdownReport(bv,funct,data)
def _assemble_link_extract(self, code): blob = None try: template = '.section .text\n' \ '.globl _start\n\n' \ '_start:\n' \ '{}\n'.format(code) dirpath = tempfile.mkdtemp() print(dirpath) with open(dirpath + '/patch.S', 'w+b') as f: f.write(template.encode('utf-8')) if not self._assemble_code(dirpath): raise OSError('Failed to assemble code') if not self._link_code(dirpath): raise OSError('Failed to link code') blob = open('{}/patch.bin'.format(dirpath), 'rb').read() except Exception as err: show_message_box('genesis', 'Error: {}'.format(err)) shutil.rmtree(dirpath) return blob
def goto_bookmark(view): try: bookmarks = view.query_metadata('bookmarks') except KeyError: bookmarks = OrderedDict() view.store_metadata('bookmarks', bookmarks) if not bookmarks: bn.show_message_box( 'Bookmark error', 'There are no bookmarks yet.', icon=bn.enums.MessageBoxIcon.ErrorIcon ) return # Metadata can only store string keys in dictionaries currently. # Therefore, we have to convert keys to integers. chosen_bookmark = bn.get_choice_input( 'Go to bookmark', 'Bookmarks:', ['0x{:x} {}'.format(int(addr), bookmark) for addr, bookmark in bookmarks.iteritems()] ) # Again, we hae to convert string keys to integers. if chosen_bookmark is not None: navigate_to = int(bookmarks.keys()[chosen_bookmark]) view.file.navigate(view.file.view, navigate_to)
def load_bookmarks(view): filename = bn.get_open_filename_input('Load bookmarks', '*.bnbm') if filename is None: return if view.file.session_data.get('bookmarks'): overwrite = bn.show_message_box( 'Bookmarks exist', 'Overwrite existing bookmarks?', buttons=bn.enums.MessageBoxButtonSet.YesNoButtonSet) if not overwrite: return else: view.file.session_data['bookmarks'] = OrderedDict() try: with open(filename, 'r') as bookmarks_file: view.file.session_data['bookmarks'].update( pickle.load(bookmarks_file)) except ValueError: bn.show_message_box('Invalid Bookmarks', 'The bookmarks file could not be read', icon=bn.enums.MessageBoxIcon.ErrorIcon)
def start_stalking(bv): colors = [bn.HighlightStandardColor.BlueHighlightColor, bn.HighlightStandardColor.CyanHighlightColor, bn.HighlightStandardColor.GreenHighlightColor,bn.HighlightStandardColor.MagentaHighlightColor, bn.HighlightStandardColor.OrangeHighlightColor, bn.HighlightStandardColor.RedHighlightColor, bn.HighlightStandardColor.WhiteHighlightColor,bn.HighlightStandardColor.YellowHighlightColor] f_colors = bn.ChoiceField('Highlight color\t',[ a.name for a in colors]) f_funct = bn.ChoiceField('Intercept function\t',[a.name for a in bv.functions]) extra_settings = [f_colors, f_funct] ret,settings = SettingsGUI(bv,'Stalker',extra_settings) if ret: execute = bv.file.original_filename if settings['name'] != "": execute = settings['name'] bn.log.log_info('Start \''+execute+' '+settings['cmd']+'\' on '+settings['dev'].id+' device ') data = {} ## Set the device data['device'] = settings['dev'] ## Command to spawn data['execute'] = [execute] if settings['cmd'] != "": for i in settings['cmd'].split(' '): data['execute'].append(i) ## Spawning spawn = True if settings['spawn'] == 1: data['pid'] = settings['pid'] spawn = False ## Preparing block data['maps'] = [] data['blocks'] = [] data['entry'] = bv.functions[f_funct.result].start stalker = FridaHandler(data,bv.file.original_filename,spawn,'stalk') stalker.start() bn.show_message_box('Frida stalking','Press OK button to terminate stalking') stalker.cancel() stalker.join() colorize(data,colors[f_colors.result],bv)
def apply_symbols(self, symbols: dict, sections: list) -> None: """Make functions in text section of kernel image """ binary_text_start = None if '.text' in sections: binary_text_start = sections['.text'].start else: archs = get_architectures() arch_choices = list(archs.keys()) arch_field = ChoiceField('Architecture', arch_choices) stext_field = IntegerField('stext Symbol Offset') get_form_input([arch_field, stext_field], 'Kernel Architecture and stext Offset') self.view.platform = archs[arch_choices[ arch_field.result]].standalone_platform if stext_field.result is None: show_message_box('kallsyms', 'Failed to identify stext offset') return binary_text_start = stext_field.result binary_text_end = None if '.text' in sections: binary_text_end = sections['.text'].end else: binary_text_end = self.view.end kallsyms_text_start = symbols['T']['_stext'] self.apply_function_symbols(symbols, kallsyms_text_start, binary_text_start, binary_text_end) self.apply_data_symbols(symbols, kallsyms_text_start, binary_text_start) self.view.update_analysis_and_wait()
def gef_stop(bv): "Stopping background service... " stop_service() show_message_box("GEF", "Service successfully stopped", MessageBoxButtonSet.OKButtonSet, MessageBoxIcon.InformationIcon) return
def run(self): results = [] if self.options['static']: self.log_progress('Running data constant scans...') results.extend(self.run_data_constant_scans()) if not self.cancelled: self.log_progress('Running IL constant scans...') results.extend(self.run_il_constant_scans()) if self.options['signature'] and not self.cancelled: self.log_progress('Running signature scans') results.extend(self.run_signature_scans()) # Proceed to results, if cancelled display notification if self.cancelled: self.log_progress( 'Cancelling scan, checking for partial results...') results = self.prune_results(results) if len(results) is not 0: self.log_progress('Scan found {count} match{plural}'.format( count=len(results), plural='' if len(results) == 1 else 'es')) self.apply_symbols(results) self.display_results(results) elif not self.cancelled: self.log_progress('No scan results found') bn.show_message_box('CryptoScan results', 'No crypto constructs identified.', bn.MessageBoxButtonSet.OKButtonSet, bn.MessageBoxIcon.InformationIcon)
def dialog(bv): match_path_field = bn.OpenFileNameField("Match File", "*.BinDiff") role_field = bn.ChoiceField( "Current view role", [ "None", "Primary", "Secondary" ] ) form_fields = [ match_path_field, role_field ] # Present form if not bn.get_form_input(form_fields, "BinDiff Viewer"): # User cancelled return match_path = match_path_field.result if role_field.result == 0: role = None else: role = role_field.result - 1 try: view_bindiff_matches(bv, match_path, role) except: bn.show_message_box( "BinDiff Viewer Error", "Failed to load matches:\n{}".format(traceback.format_exc()) )
def rpyc_stop(bv): "Stopping background service... " if stop_service(): binaryninja.show_message_box( "Binja-RPyC", "Service successfully stopped", binaryninja.MessageBoxButtonSet.OKButtonSet, binaryninja.MessageBoxIcon.InformationIcon) return
def run(self): self.bv.platform = Platform['M68000'] call_table_addrs = self.find_call_tables() if not call_table_addrs: return count = self.disas_call_tables(call_table_addrs) show_message_box( 'genesis', 'Disassembled {} call table instructions'.format(count))
def gef_start(bv): global __service_thread dbg("Starting background service...") __service_thread = threading.Thread(target=start_service, args=(HOST, PORT, bv)) __service_thread.daemon = True __service_thread.start() register_gef_breakpoint_menu() show_message_box( "GEF", "Service successfully started, you can now have gef connect to it", MessageBoxButtonSet.OKButtonSet, MessageBoxIcon.InformationIcon) return
def rpyc_start(bv): global __service_thread dbg("Starting background service...") __service_thread = threading.Thread(target=start_service, args=(HOST, PORT, bv)) __service_thread.daemon = True __service_thread.start() binaryninja.show_message_box( "Binja-RPyC", "Service successfully started, you can use any RPyC client to connect to this instance of Binary Ninja", binaryninja.MessageBoxButtonSet.OKButtonSet, binaryninja.MessageBoxIcon.InformationIcon) return
def save_bookmarks(view): if not view.file.session_data.get('bookmarks'): return default_name = os.path.splitext(view.file.filename)[0] + '.bnbm' filename = bn.get_save_filename_input('Save bookmarks', '*.bnbm', default_name) try: with open(filename, 'w') as bookmarks_file: pickle.dump(view.file.session_data['bookmarks'], bookmarks_file) except ValueError: bn.show_message_box('Error Saving Bookmarks', 'The bookmarks file could not be saved', icon=bn.enums.MessageBoxIcon.ErrorIcon)
def run(self): params = self._get_params() blob = self._assemble_link_extract(params['code']) if blob is None: return blob_len = len(blob) if blob_len > 0: self.bv.write(params['start_offset'], blob) show_message_box( 'genesis', 'Wrote {} bytes beginning at {:08x}'.format( blob_len, params['start_offset']) ) else: show_message_box('genesis', 'Patch is 0 bytes in size')
def server_start_stop(bv): if t is None: start_server(bv) bn.show_message_box("Serv","Service successfully started, you can now connect to it", bn.MessageBoxButtonSet.OKButtonSet, bn.MessageBoxIcon.InformationIcon) else: try: cli = xmlrpclib.ServerProxy("http://{:s}:{:d}".format(HOST, PORT)) cli.shutdown() except socket.error: pass stop_server(bv) bn.show_message_box("Serv", "Service successfully stopped", bn.MessageBoxButtonSet.OKButtonSet, bn.MessageBoxIcon.InformationIcon) return
def _ui_save_image(_bv: BinaryView, window: bool, scale: Optional[int] = None) -> None: """ UI helper to save an image. If no scale is provided, the user will be prompted with a popup. :param window: whether the whole window (or just view) should be captured :param scale: the DPI-scaling factor to render the image at """ # Try to ask the user for the scale, will be None if canceled if scale is None: scale = get_int_input("Resolution multiplier:", "Screenshot Ninja") if scale is None: return # Get the screenshot. You would think this would be called after the user # chooses a save location, but that messes up Qt's ability to determine the # active window, so... try: img = get_active_window_image(scale) if window else get_active_view_image(scale) except ValueError as e: show_message_box( "Error", str(e), MessageBoxButtonSet.OKButtonSet, MessageBoxIcon.ErrorIcon, ) # Try to ask the user for a save location, will be None if canceled path = _get_save_path() if path is None: return # Try to save the image, will return False if unsuccessful if not img.save(path): show_message_box( "Error", "Failed to save image.", MessageBoxButtonSet.OKButtonSet, MessageBoxIcon.ErrorIcon, )
def goto_bookmark(view): if not view.file.session_data.get('bookmarks'): view.file.session_data['bookmarks'] = OrderedDict() bookmarks = view.file.session_data['bookmarks'] if not bookmarks: bn.show_message_box('Bookmark error', 'There are no bookmarks yet.', icon=bn.enums.MessageBoxIcon.ErrorIcon) return chosen_bookmark = bn.get_choice_input('Go to bookmark', 'Bookmarks:', [ '0x{:x} {}'.format(addr, bookmark) for addr, bookmark in bookmarks.iteritems() ]) if chosen_bookmark is not None: navigate_to = bookmarks.keys()[chosen_bookmark] view.file.navigate(view.file.view, navigate_to)
def start_dump(bv, funct): extra_settings = [] index = 0 for i in funct.parameter_vars: f = bn.LabelField('\'' + i.name + '\'') extra_settings.append(f) extra_settings.append( bn.MultilineTextField( 'Dumping data. v_args[NAME] is printed in report')) ret, settings = SettingsGUI(bv, 'Dump function contents', extra_settings) if ret: execute = bv.file.original_filename if settings['name'] != "": execute = settings['name'] bn.log.log_info('Start \'' + execute + ' ' + settings['cmd'] + '\' on ' + settings['dev'].id + ' device ') data = {} ## Set the device data['device'] = settings['dev'] ## Command to spawn data['execute'] = [execute] if settings['cmd'] != "": for i in settings['cmd'].split(' '): data['execute'].append(i) ## Spawning spawn = True if settings['spawn'] == 1: data['pid'] = settings['pid'] spawn = False ## Preparing block data['dump'] = [] data['maps'] = [] data['functions'] = funct data['arguments'] = extra_settings[-1].result stalker = FridaHandler(data, bv.file.original_filename, spawn, 'dump') stalker.start() bn.show_message_box('Frida running', 'Press OK button to terminate.') stalker.cancel() stalker.join() CreateMarkdownReport(bv, funct, data)
def run(self) -> None: """Run the plugin """ # Open the file filepath = OpenFileNameField('kernel symbol file: ') get_form_input([filepath], 'Select file containing kallsyms output') filepath = filepath.result self.progress = 'kallsyms: importing kernel symbols...' status, message = self.open_sym_file(filepath) if status is False: show_message_box('kallsyms', message) self.progress = '' return sections = self.view.sections if sections is None: show_message_box('kallsyms', 'No sections defined') return symbols = self.parse_kallsyms_file() self.apply_symbols(symbols, sections)
def run(self): log_info("Scanning binary view for matching YARA signatures") # TODO: Scan the raw binary data from the Raw view instead of by segment. # This would require mapping the addresses from the Raw view to the PE/ELF views. # raw = self.bv.get_view_of_type("Raw") # reader = BinaryReader(raw) # data = reader.read(raw.end) try: for idx, rule in enumerate(self.rules): if len(self.bv.segments) == 0: # Scan binary without segments self.scan(self.bv.start, self.bv.end, rule) else: # Scan by segment for segment in self.bv.segments: if self.cancelled: return self.scan(segment.start, segment.data_length, rule) self.progress = f"{self.progress_banner} matching on rules ({round((idx / len(self.rules)) * 100)}%)" except yara.TimeoutError: log_warn( "YARA scan exceeded timeout limit. Consider changing the timeout in settings." ) except yara.Error as err: log_error("Error matching on YARA rules: {}".format(str(err))) show_message_box("Error", "Check logs for details", icon=MessageBoxIcon.ErrorIcon) if 0 < len(self.results): if Settings().get_bool("yara.displayReport"): self.display_report() else: log_info("YARA scan finished with no matches.")
def gef_start_stop(bv): if __service_thread is None: dbg("Trying to start service thread") gef_start(bv) show_message_box( "GEF", "Service successfully started, you can now have gef connect to it", MessageBoxButtonSet.OKButtonSet, MessageBoxIcon.InformationIcon) else: dbg("Trying to stop service thread") try: cli = xmlrpc.client.ServerProxy("http://{:s}:{:d}".format( HOST, PORT)) cli.shutdown() except socket.error: pass gef_stop(bv) show_message_box("GEF", "Service successfully stopped", MessageBoxButtonSet.OKButtonSet, MessageBoxIcon.InformationIcon) return
def start_instrumentation(bv, address): ## TODO: Check the instrumented instruction. Frida has problem with some instruction f = bv.get_functions_containing(address) f_function = bn.LabelField('Container function\t' + f[0].name) f_funct = bn.LabelField('Instrumented instruction\t' + bv.get_disassembly(address)) f_script = bn.MultilineTextField("Frida script\t") extra_settings = [f_function, f_funct, f_script] ret, settings = SettingsGUI(bv, 'Instrumentation', extra_settings) if ret: execute = bv.file.original_filename if settings['name'] != "": execute = settings['name'] bn.log.log_info('Start \'' + execute + ' ' + settings['cmd'] + '\' on ' + settings['dev'].id + ' device ') data = {} ## Set the device data['device'] = settings['dev'] ## Command to spawn data['execute'] = [execute] if settings['cmd'] != "": for i in settings['cmd'].split(' '): data['execute'].append(i) ## Spawning spawn = True if settings['spawn'] == 1: data['pid'] = settings['pid'] spawn = False ## Stalker data data['maps'] = [] data['functions'] = [f[0].start, address] data['script'] = f_script.result stalker = FridaHandler(data, bv.file.original_filename, spawn, 'instr') stalker.start() bn.show_message_box('Frida running', 'Press OK button to terminate.') stalker.cancel() stalker.join()
def show(self): rendered = html_template.format(window=window) show_message_box("Explain Instruction", rendered)
def run(self): checksum = self._calculate_checksum() self.bv.write(self.checksum_off, struct.pack('>H', checksum)) show_message_box('genesis', 'ROM checksum has been updated')