Exemple #1
0
    if not psp_typelib:
        print("[PSP] Could not load type library")
        return

    if psp_typelib not in bv.type_libraries:
        bv.add_type_library(psp_typelib)

    # Now resolve symbols
    for sym in bv.get_symbols_of_type(SymbolType.ImportedFunctionSymbol):
        func = bv.get_function_at(sym.address)

        if not func:
            continue

        func_type = psp_typelib.get_named_object(func.name)

        if func_type is None:
            continue

        func.set_user_type(func_type)
        print("[PSP] Resolved type for {}".format(func.name))


PluginCommand.register("MHFU\\Map ovl file", "Map ovl file", map_ovl)
PluginCommand.register("MHFU\\Unmap ovl file", "Unmap an ovl file", unmap_ovl)
PluginCommand.register("MHFU\\Trace based function detection",
        "Detect functions based on ppsspp trace", trace_detect_function)
PluginCommand.register("MHFU\\Resolve nid calls", "Resolve PSP api calls" , nid_resolve)
PluginCommand.register("MHFU\\Apply pspsdk types", "Apply pspsdk type library", load_type_library)
Exemple #2
0
    def __init__(self, bv, options):
        global task
        BackgroundTaskThread.__init__(self, "Importing data from Polypyus",
                                      False)
        self.csv_file = options.csv_file
        self.options = options
        self.bv = bv
        task = self

    def run(self):
        (success, error_message) = import_pp(self.options.csv_file, self.bv,
                                             self.options)
        if not success:
            log_error(error_message)


def import_pp_in_background(bv):
    options = GetOptions(True)
    background_task = ImportPPInBackground(bv, options)
    background_task.start()


if __name__ == "__main__":
    main()
else:
    PluginCommand.register(
        "Import data from Polypyus",
        "Import data from Polypyus",
        import_pp_in_background,
    )
            ident = get_identifier(bv, sym)
            if ident is None:
                continue
            module = normalize_module(get_symbol_module(sym))
            mod_syms = candidates.setdefault(module, {})
            these_syms = mod_syms.setdefault(ident, [])
            these_syms.append(sym)

    # Find any associated dependency files and process them
    for module, filename in find_possible_dependencies(bv, candidates.keys()):
        log_info('Processing: {}...'.format(filename))
        analyze_dependency(bv, module, filename,
                           candidates[normalize_module(module)])


PluginCommand.register("Analyze self", "Resolve metadata for self",
                       analyze_self)
PluginCommand.register("Analyze dependencies",
                       "Resolve metadata for analyzed dependencies",
                       analyze_dependencies)

settings = Settings()
settings.register_group("depanalyzer", "Dependency Analyzer Plugin")
settings.register_setting(
    "depanalyzer.path",
    json.dumps({
        'title': 'Dependency Paths',
        'description': 'Paths to search for dependencies',
        'type': 'array',
        'elementType': 'string',
        'default': ['.'],
    }))
Exemple #4
0
            self.binary.write(bv.file.raw.read(0, len(bv.file.raw)))
            self.binary.flush()

        def run(self):
            binary = pefile.PE(self.binary.name)

            names = dict()
            for entry in binary.DIRECTORY_ENTRY_IMPORT:
                for imp in entry.imports:
                    names[imp.address] = "{}!{}".format(
                        entry.dll[:-4], imp.name)
            for symbol in self.bv.get_symbols_of_type(
                    SymbolType.ImportAddressSymbol):
                if "Ordinal_" in symbol.name and symbol.address in names:
                    bv.define_user_symbol(
                        Symbol(symbol.type, symbol.address,
                               names[symbol.address]))

    r = Resolver(bv)
    r.start()


def is_pe_file(bv):
    return bv.view_type == 'PE'


PluginCommand.register(
    "Try resolve Ordinals",
    "Try to resolve names of ordinals that binary ninja could not resolve",
    resolve_ordinals, is_pe_file)
        patch_opaque(self.bv, self)


def patch_opaque_in_background(bv):
    background_task = PatchOpaqueInBackground(bv, "Patching opaque predicates")
    background_task.start()


def main():
    bv = BinaryViewType.get_view_of_file(sys.argv[1])
    if bv is None:
        print("Couldn't open %s" % sys.argv[1])
        return

    patch_opaque(bv)

    dbname = sys.argv[1]
    if not dbname.endswith(".bndb"):
        dbname += ".bndb"

    bv.create_database(dbname)


if __name__ == "__main__":
    main()
else:
    PluginCommand.register(
        "Patch Opaque Predicates",
        "Find branches which are unnecessary and remove them",
        patch_opaque_in_background)
from binaryninja.plugin import PluginCommand

from pdata_finder import PdataFinder
from split_function_fixer import SplitFunctionFixer
from xref_finder import XrefFinder

PluginCommand.register("Function Finder - Fix Split Functions",
                       "Combines unnecessarily split functions",
                       lambda bv: SplitFunctionFixer(bv).start())

PluginCommand.register(
    "Function Finder - code xref",
    "Search for references to possible functions in executable segments",
    lambda bv: XrefFinder(bv).start())

PluginCommand.register("Function Finder - .pdata",
                       "Search for functions using .pdata section",
                       lambda bv: PdataFinder(bv).start())
Exemple #7
0
from binaryninja.plugin import PluginCommand
from .ief import ief_find_export_bg, ief_find_import_bg, ief_find_library_bg

PluginCommand.register(
    'Import Export Find\\Find binaries that import library named',
    'find binaries that import a library named', ief_find_library_bg)

PluginCommand.register_for_function(
    'Import Export Find\\Find binaries that export current function',
    'find binaries that export the current function', ief_find_export_bg)

PluginCommand.register_for_function(
    'Import Export Find\\Find binaries that import current function',
    'find binaries that import the current function', ief_find_import_bg)
Exemple #8
0
def add_breakpoint():
    """
    Add a software break point on ntdll!EtwEventWrite
    """
    raise NotImplementedError()


def delete_breakpoint():
    """
    Delete the breakpoint set on ntdll_EtwEventWrite
    """
    raise NotImplementedError()


def etw_breaker(bv):
    ETWBreaker().run(bv)


def check_platform(bv, *platforms):
    platform = bv.platform
    if platform is None:
        return False
    return platform.name in platforms


PluginCommand.register(
    "ETWBreaker",
    "Statically find ETW events in a PE file and show their properties",
    lambda bv: etw_breaker(bv),
    lambda bv: check_platform(bv, "windows-x86", "windows-x86_64"))
Exemple #9
0
        # bvs = set([bv] + bvs)
        func(bvs)

    return wrapper


def register_file(bv):
    # name = os.path.basename(bv.file.filename).split(".")[0]
    name = pe_parsing.get_eat_name(bv)

    files[name.lower()] = bv
    log_info("Registered PE binary view %r" % name.lower())


PluginCommand.register("PE\\Load binary",
                       "Load the current binary into the PE binary registry",
                       register_file,
                       is_valid=bv_is_pe)
PluginCommand.register("PE\\Resolve imports",
                       "Resolve import names and load types",
                       sync.resolve_imports,
                       is_valid=bv_is_pe)

PluginCommand.register("PE\\Debug\\PE tables",
                       "Show the IAT and EAT as seen by PE Utils",
                       reports.generate_table_graph,
                       is_valid=bv_is_pe)
PluginCommand.register(
    "PE\\Debug\\Binary relationship graph",
    "Show a relationship graph for the currently loaded BVs",
    all_bvs(reports.generate_relation_graph),
    is_valid=bv_is_pe)
Exemple #10
0
    harness = interaction.get_save_filename_input("Filename to write to?",
                                                  "cpp")
    harness = csv_file.decode("utf-8") + ".cpp"

    log.log_info("Writing new template to workspace")
    with open(harness, "w+") as fd:
        fd.write(template)

    interaction.show_message_box("Success",
                                 f"Done, wrote fuzzer harness to {harness}")


PluginCommand.register(
    "Fuzzable\\Analyze fuzzable targets",
    "Identify and generate targets for fuzzing",
    run_fuzzable,
)

PluginCommand.register(
    "Fuzzable\\Export fuzzability report as CSV",
    "Identify and generate targets for fuzzing",
    run_export_report,
)

PluginCommand.register_for_function(
    "Fuzzable\\Generate fuzzing harness (EXPERIMENTAL, C/C++ ONLY)",
    "For a target function, generate a AFL/libFuzzer C++ harness",
    run_harness_generation,
)
	contents = "## %s ##\n" % bv.file.filename
	contents += "- START: 0x%x\n\n" % bv.start
	contents += "- ENTRY: 0x%x\n\n" % bv.entry_point
	contents += "- ARCH: %s\n\n" % bv.arch.name
	contents += "### First 10 Functions ###\n"

	contents += "| Start | Name   |\n"
	contents += "|------:|:-------|\n"
	for i in xrange(min(10, len(bv.functions))):
		contents += "| 0x%x | %s |\n" % (bv.functions[i].start, bv.functions[i].symbol.full_name)

	contents += "### First 10 Strings ###\n"
	contents += "| Start | Length | String |\n"
	contents += "|------:|-------:|:-------|\n"
	for i in xrange(min(10, len(bv.strings))):
		start = bv.strings[i].start
		length = bv.strings[i].length
		string = bv.read(start, length)
		contents += "| 0x%x |%d | %s |\n" % (start, length, string)
	return contents


def display_bininfo(bv):
	interaction.show_markdown_report("Binary Info Report", get_bininfo(bv))


if __name__ == "__main__":
	print get_bininfo(None)
else:
	PluginCommand.register("Binary Info", "Display basic info about the binary", display_bininfo)
def avoid_instr(bv, addr):
	# Highlight the instruction in red
	blocks = bv.get_basic_blocks_at(addr)
	for block in blocks:
		block.set_auto_highlight(HighlightColor(HighlightStandardColor.RedHighlightColor, alpha = 128))
		block.function.set_auto_instr_highlight(addr, HighlightStandardColor.RedHighlightColor)

	# Add the instruction to the list associated with the current view
	bv.session_data.angr_avoid.add(addr)


def solve(bv):
	if len(bv.session_data.angr_find) == 0:
		show_message_box("Angr Solve", "You have not specified a goal instruction.\n\n" +
			"Please right click on the goal instruction and select \"Find Path to This Instruction\" to " +
			"continue.", MessageBoxButtonSet.OKButtonSet, MessageBoxIcon.ErrorIcon)
		return

	# Start a solver thread for the path associated with the view
	s = Solver(bv.session_data.angr_find, bv.session_data.angr_avoid, bv)
	s.start()


# Register commands for the user to interact with the plugin
PluginCommand.register_for_address("Find Path to This Instruction",
	"When solving, find a path that gets to this instruction", find_instr)
PluginCommand.register_for_address("Avoid This Instruction",
	"When solving, avoid paths that reach this instruction", avoid_instr)
PluginCommand.register("Solve With Angr", "Attempt to solve for a path that satisfies the constraints given", solve)
        br = BinaryReader(bv)
        br.seek(addr)
        tgt = [br.read(size)]
        print "[linsweep] User Defined Search Start"
        fs = len(bv.functions)
        self.find_functions(bv, tgt, bv.start, bv.end, "-U")
        print "[linsweep] User: Found %d New Functions" % (len(bv.functions) -
                                                           fs)
        interaction.show_message_box('Linear Sweep',
                                     "Created %d new functions" %
                                     (len(bv.functions) - fs),
                                     buttons=MessageBoxButtonSet.OKButtonSet)


PluginCommand.register("Simple Linear Sweep - Cautious",
                       "Search for existing prologues in text section",
                       lambda bv: Searcher(CAUTIOUS, bv, None, None).start())
PluginCommand.register("Simple Linear Sweep - Aggressive",
                       "Search for function prologues from bv.start",
                       lambda bv: Searcher(AGGRESSIVE, bv, None, None).start())
PluginCommand.register("Simple Linear Sweep - Exhaustive",
                       "Search for function prologues from bv.start",
                       lambda bv: Searcher(EXHAUSTIVE, bv, None, None).start())
PluginCommand.register_for_range(
    "Simple Linear Sweep - User", "Search for selected data as a prologue",
    lambda bv, addr, size: Searcher(USER, bv, addr, size).start())

if "bv" in locals():
    # noinspection PyUnresolvedReferences
    print "Detected execfile from console " + str(bv)
    print "Starting aggressive search"
Exemple #14
0
        lookup[f.symbol.full_name] = {
            'address': f.start,
            'blocks': len(blocks),
            'edges': n_edges,
            'complexity': complexity
        }

    # load into table rows
    table_data = []
    for fname in sorted(lookup,
                        key=lambda x: lookup[x]['complexity'],
                        reverse=True):
        row = [
            fname, lookup[fname]['edges'], lookup[fname]['blocks'],
            lookup[fname]['complexity']
        ]
        table_data.append(row)

    # launch gui
    import threading
    threading.Thread(target=gui_thread).start()


#
from binaryninja.plugin import PluginCommand

PluginCommand.register(
    "Cyclomatic Complexity",
    "Popup a GUI table with sorted cyclomatic complexities.",
    show_cyclomatic_complexity_table)
Exemple #15
0
def initialize_ui():
    widget.register_dockwidget(BreakpointsWidget.DebugBreakpointsWidget,
                               "Breakpoints", Qt.BottomDockWidgetArea,
                               Qt.Horizontal, False)
    widget.register_dockwidget(RegistersWidget.DebugRegistersWidget,
                               "Registers", Qt.RightDockWidgetArea,
                               Qt.Vertical, False)
    widget.register_dockwidget(ThreadsWidget.DebugThreadsWidget, "Threads",
                               Qt.BottomDockWidgetArea, Qt.Horizontal, False)
    widget.register_dockwidget(StackWidget.DebugStackWidget, "Stack",
                               Qt.LeftDockWidgetArea, Qt.Vertical, False)
    widget.register_dockwidget(ModulesWidget.DebugModulesWidget, "Modules",
                               Qt.BottomDockWidgetArea, Qt.Horizontal, False)
    widget.register_dockwidget(ConsoleWidget.DebugConsoleWidget,
                               "Debugger Console", Qt.BottomDockWidgetArea,
                               Qt.Horizontal, False)

    PluginCommand.register_for_address(
        "Debugger\\Toggle Breakpoint",
        "sets/clears breakpoint at right-clicked address",
        cb_bp_toggle,
        is_valid=valid_bp_toggle)

    PluginCommand.register("Debugger\\Process\\Run",
                           "Start new debugging session",
                           cb_process_run,
                           is_valid=valid_process_run)
    PluginCommand.register("Debugger\\Process\\Restart",
                           "Restart debugging session",
                           cb_process_restart,
                           is_valid=valid_process_restart)
    PluginCommand.register("Debugger\\Process\\Quit",
                           "Terminate debugged process and end session",
                           cb_process_quit,
                           is_valid=valid_process_quit)
    # PluginCommand.register("Debugger\\Process\\Attach", "Attach to running process", cb_process_attach, is_valid=valid_process_attach)
    PluginCommand.register("Debugger\\Process\\Detach",
                           "Detach from current debugged process",
                           cb_process_detach,
                           is_valid=valid_process_detach)
    PluginCommand.register("Debugger\\Process\\Settings",
                           "Open adapter settings menu",
                           cb_process_settings,
                           is_valid=valid_process_settings)
    PluginCommand.register("Debugger\\Control\\Pause",
                           "Pause execution",
                           cb_control_pause,
                           is_valid=valid_control_pause)
    PluginCommand.register("Debugger\\Control\\Resume",
                           "Resume execution",
                           cb_control_resume,
                           is_valid=valid_control_resume)
    PluginCommand.register("Debugger\\Control\\Step Into (Assembly)",
                           "Step into assembly",
                           cb_control_step_into_asm,
                           is_valid=valid_control_step_into_asm)
    PluginCommand.register("Debugger\\Control\\Step Into (IL)",
                           "Step into IL",
                           cb_control_step_into_il,
                           is_valid=valid_control_step_into_il)
    PluginCommand.register("Debugger\\Control\\Step Over (Assembly)",
                           "Step over function call",
                           cb_control_step_over_asm,
                           is_valid=valid_control_step_over_asm)
    PluginCommand.register("Debugger\\Control\\Step Over (IL)",
                           "Step over function call",
                           cb_control_step_over_il,
                           is_valid=valid_control_step_over_il)
    PluginCommand.register("Debugger\\Control\\Step Return",
                           "Step until current function returns",
                           cb_control_step_return,
                           is_valid=valid_control_step_return)

    ViewType.registerViewType(DebugView.DebugViewType())
Exemple #16
0
            if opt_visitors.result > 0:
                SHOW_VISITORS = not SHOW_VISITORS
        COVERAGE_FIRST_LOAD = False
    t1 = threading.Thread(target=watch_cur_func, args=(bv, ))
    t1.daemon = True
    t1.start()


def toggle_visits(bv):
    global SHOW_VISITS
    SHOW_VISITS = not SHOW_VISITS


def toggle_length(bv):
    global SHOW_LENGTH
    SHOW_LENGTH = not SHOW_LENGTH


def toggle_visitors(bv):
    global SHOW_VISITORS
    SHOW_VISITORS = not SHOW_VISITORS


PluginCommand.register('Coverage: Start Tracking', 'Track Coverage',
                       coverage_load)
PluginCommand.register('Coverage: Toggle Visits (RED)', 'Toggle Red',
                       toggle_visits)
PluginCommand.register('Coverage: Toggle Length (BLUE)', 'Toggle Blue',
                       toggle_length)
PluginCommand.register('Coverage: Toggle Visitors (GREEN)', 'Toggle Green',
                       toggle_visitors)
Exemple #17
0
    state = State.get(bv)
    state.show_time = not state.show_time
    if state.show_time:
        log_info("Time Visualization Enabled (Blue)")
    else:
        log_info("Time Visualization Disabled (Blue)")
    state.color_now = True

def toggle_visitors(bv):
    state = State.get(bv)
    state.show_visitors = not state.show_visitors
    if state.show_visitors:
        log_info("Visitor Visualization Enabled (Green)")
    else:
        log_info("Visitor Visualization Disabled (Green)")
    state.color_now = True

def toggle_track(bv):
    state = State.get(bv)
    state.track_coverage = not state.track_coverage
    if state.track_coverage:
        log_info("Tracking Enabled")
    else:
        log_info("Tracking Disabled")

PluginCommand.register('revsync\\Coverage: Toggle Tracking', 'Toggle Tracking', toggle_track)
PluginCommand.register('revsync\\Coverage: Toggle Visits (RED)', 'Toggle Red', toggle_visits)
PluginCommand.register('revsync\\Coverage: Toggle Time (BLUE)', 'Toggle Blue', toggle_time)
PluginCommand.register('revsync\\Coverage: Toggle Visitors (GREEN)', 'Toggle Green', toggle_visitors)
PluginCommand.register('revsync\\Load', 'load revsync!!!', revsync_load)
Exemple #18
0
def worker(bv):
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.bind(('127.0.0.1', 31337))

    while True:
        print('udp_nav: calling sock.recvfrom()')
        data, addr = sock.recvfrom(1024)
        print("udp_nav: received ", data)

        try:
            data = data.decode('utf-8')
            address = int(data, 16)
        except Exception:
            continue

        dh = DockHandler.getActiveDockHandler()
        vf = dh.getViewFrame()
        cv = vf.getCurrentView()
        print('udp_nav: bv.navigate(\'%s\', 0x%X)' % (cv, address))
        bv.navigate(cv, address)


def go(bv):
    threading.Thread(target=worker, args=(bv, )).start()


if not headless:
    from binaryninja.plugin import PluginCommand
    PluginCommand.register("udp nav", "udp nav", go)
Exemple #19
0
    log("Writing out {}".format(options.output_name), options.verbose)
    bv.create_database(options.output_name)
    return


class ImportIDAInBackground(BackgroundTaskThread):
    def __init__(self, bv, options):
        global task
        BackgroundTaskThread.__init__(self, "Importing data from IDA", False)
        self.json_file = options.json_file
        self.options = options
        self.bv = bv
        task = self

    def run(self):
        (success, error_message) = import_ida(self.options.json_file, self.bv, self.options)
        if not success:
            log_error(error_message)


def import_ida_in_background(bv):
    options = GetOptions(True)
    background_task = ImportIDAInBackground(bv, options)
    background_task.start()


if __name__ == "__main__":
    main()
else:
    PluginCommand.register("Import data from IDA", "Import data from IDA", import_ida_in_background)
Exemple #20
0
                print('WARNING: unfamiliar call operand in {}'.format(instruction))
                continue
            symbol = bv.get_symbol_at(instruction.prefix_operands[2])
            if symbol and symbol.type == SymbolType.ImportedFunctionSymbol:
                #print(symbol.name)
                #demangler.demangleImport(bv, instruction.prefix_operands[2])
                #demangler.demangleImport(bv, symbol.name)
                name = symbol.name
                if name[:2] == '__':
                    name = name[1:]
                try:
                    result = demangler.demangleSymbolAsNode(bv, name)
                    if not result:
                        skipped.append(symbol.name)
                        print('SKIPPING: {}'.format(symbol.name))
                        continue
                    successful.append(symbol.name)
                    print(result)
                    #print(demangler.getNodeTreeAsString(result))
                except Exception as e:
                    logging.exception(e)

    print(len(skipped))
    print(skipped)
    print(len(successful))
    print(successful)

PluginCommand.register("Define Objective-C classes", "Parses the objc_classlist section to define Objective C and Swift classes", define_classes)
PluginCommand.register_for_address("Demangle Swift symbol", "Demangles the Swift symbol name at the given address", demangler.demangleAddress)
PluginCommand.register_for_function("Demangle imported Swift symbols", "Demangles the imported Swift symbol names in the given function", demangleImportsInFunction)
Exemple #21
0
@db_required
def display_bb_viewer(bv):
    dock_handler = None

    for wg in QApplication.allWidgets():
        wg_win = wg.window()
        dock_handler = wg_win.findChild(DockHandler, "__DockHandler")

        if dock_handler:
            break

    if dock_handler is None:
        print("Could not find DockHandler")
        return

    dock_widget = BBViewerWidget("Basic Block viewer", dock_handler.parent(),
                                 bv, LOADED_DB)
    dock_handler.addDockWidget(dock_widget, Qt.RightDockWidgetArea,
                               Qt.Vertical, True)


PluginCommand.register("Wakare\\Load trace database", "Loads a trace database",
                       db_load)
PluginCommand.register_for_address("Wakare\\Branch xrefs from",
                                   "Displays xrefs from a branch",
                                   display_branch_xrefs)

PluginCommand.register("Wakare\\Show basic block viewer",
                       "Displays information about basic blocks",
                       display_bb_viewer)
    def __init__(self, view):
        BackgroundTaskThread.__init__(
            self,
            initial_progress_text=self._PROGRESS_TEXT + "...",
            can_cancel=True)
        self._view = view
        self._total = 0
        self._current = 0

    def set_total(self, total):
        self._total = total

    def advance(self):
        self._current += 1
        self.progress = "{} ({}/{})...".format(self._PROGRESS_TEXT,
                                               self._current, self._total)
        return not self.cancelled

    def run(self):
        try:
            analyze_cxx_abi(self._view, task=self)
        finally:
            self.finish()


PluginCommand.register(
    'Analyze Itanium C++ ABI...',
    'Infer data types from C++ symbol names conforming to Itanium ABI.',
    lambda view: CxxAbiAnalysis(view).start())
            addr, HighlightStandardColor.RedHighlightColor)

    # Add the instruction to the list associated with the current view
    bv.session_data.angr_avoid.add(addr)


def solve(bv):
    if len(bv.session_data.angr_find) == 0:
        show_message_box(
            "Angr Solve", "You have not specified a goal instruction.\n\n" +
            "Please right click on the goal instruction and select \"Find Path to This Instruction\" to "
            + "continue.", MessageBoxButtonSet.OKButtonSet,
            MessageBoxIcon.ErrorIcon)
        return

    # Start a solver thread for the path associated with the view
    s = Solver(bv.session_data.angr_find, bv.session_data.angr_avoid, bv)
    s.start()


# Register commands for the user to interact with the plugin
PluginCommand.register_for_address(
    "Find Path to This Instruction",
    "When solving, find a path that gets to this instruction", find_instr)
PluginCommand.register_for_address(
    "Avoid This Instruction",
    "When solving, avoid paths that reach this instruction", avoid_instr)
PluginCommand.register(
    "Solve With Angr",
    "Attempt to solve for a path that satisfies the constraints given", solve)
Exemple #24
0
    PM = PaperMachete()

    #print "Invoking Binary Ninja and analyzing file: {}".format(target)

    bv.add_analysis_option("linearsweep")
    print "Performing linear sweep..."
    #bv.update_analysis_and_wait()  # Doesn't work on personal license
    print "Linear sweep complete. Collecting BNIL data..."
    analyze(bv, func_list)  # Needed for converting specific functions to JSON
    # pretty printed json (pretty printed files are much larger than compact files!)
    target_json = json.dumps(PM,
                             default=lambda o: o.__dict__,
                             indent=4,
                             sort_keys=True)

    # compact / minified json
    #target_json = json.dumps(PM, default=lambda o: o.__dict__)

    try:
        jf = None
        fullpath = os.path.join(tempfile.gettempdir(), 'data.json')
        jf = open(fullpath, "w")
        jf.write(target_json)
        jf.close()
    except IOError:
        print "ERROR: Unable to open/write to ~/tmp/data.json"
        return  #target_json


PluginCommand.register("Paper Machete", "JSON File", pmanalyze_binja)
Exemple #25
0
    typelib.add_platform(platform)
    typelib.finalize()

    return typelib


def select_typelib(bv):
    libs = bv.platform.type_libraries
    choice = get_choice_input("Select Type Library", "Platform Libraries",
                              [i.name for i in libs])
    bv.add_type_library(libs[choice])


PluginCommand.register(
    "Type Manager\Generate Type Library [Single Platform]",
    "Generate a type library for a single platform.",
    generate_single_platform,
)

PluginCommand.register(
    "Type Manager\Generate Type Library [All Platforms]",
    "Generate a type library for all Binary Ninja platforms.",
    generate_all_platforms,
)

PluginCommand.register(
    "Type Manager\Load Type Library",
    "Load a type library for use in the binary view.",
    select_typelib,
)
Exemple #26
0
# x86_64 syscall table
syscall_table = ["read","write","open","close","stat","fstat","lstat","poll","lseek","mmap","mprotect","munmap","brk","rt_sigaction","rt_sigprocmask","rt_sigreturn","ioctl","pread","pwrite","readv","writev","access","pipe","select","sched_yield","mremap","msync","mincore","madvise","shmget","shmat","shmctl","dup","dup","pause","nanosleep","getitimer","alarm","setitimer","getpid","sendfile","socket","connect","accept","sendto","recvfrom","sendmsg","recvmsg","shutdown","bind","listen","getsockname","getpeername","socketpair","setsockopt","getsockopt","clone","fork","vfork","execve","exit","wait","kill","uname","semget","semop","semctl","shmdt","msgget","msgsnd","msgrcv","msgctl","fcntl","flock","fsync","fdatasync","truncate","ftruncate","getdents","getcwd","chdir","fchdir","rename","mkdir","rmdir","creat","link","unlink","symlink","readlink","chmod","fchmod","chown","fchown","lchown","umask","gettimeofday","getrlimit","getrusage","sysinfo","times","ptrace","getuid","syslog","getgid","setuid","setgid","geteuid","getegid","setpgid","getppid","getpgrp","setsid","setreuid","setregid","getgroups","setgroups","setresuid","getresuid","setresgid","getresgid","getpgid","setfsuid","setfsgid","getsid","capget","capset","rt_sigpending","rt_sigtimedwait","rt_sigqueueinfo","rt_sigsuspend","sigaltstack","utime","mknod","uselib","personality","ustat","statfs","fstatfs","sysfs","getpriority","setpriority","sched_setparam","sched_getparam","sched_setscheduler","sched_getscheduler","sched_get_priority_max","sched_get_priority_min","sched_rr_get_interval","mlock","munlock","mlockall","munlockall","vhangup","modify_ldt","pivot_root","_sysctl","prctl","arch_prctl","adjtimex","setrlimit","chroot","sync","acct","settimeofday","mount","umount","swapon","swapoff","reboot","sethostname","setdomainname","iopl","ioperm","create_module","init_module","delete_module","get_kernel_syms","query_module","quotactl","nfsservctl","getpmsg","putpmsg","afs_syscall","tuxcall","security","gettid","readahead","setxattr","lsetxattr","fsetxattr","getxattr","lgetxattr","fgetxattr","listxattr","llistxattr","flistxattr","removexattr","lremovexattr","fremovexattr","tkill","time","futex","sched_setaffinity","sched_getaffinity","set_thread_area","io_setup","io_destroy","io_getevents","io_submit","io_cancel","get_thread_area","lookup_dcookie","epoll_create","epoll_ctl_old","epoll_wait_old","remap_file_pages","getdents","set_tid_address","restart_syscall","semtimedop","fadvise","timer_create","timer_settime","timer_gettime","timer_getoverrun","timer_delete","clock_settime","clock_gettime","clock_getres","clock_nanosleep","exit_group","epoll_wait","epoll_ctl","tgkill","utimes","vserver","mbind","set_mempolicy","get_mempolicy","mq_open","mq_unlink","mq_timedsend","mq_timedreceive","mq_notify","mq_getsetattr","kexec_load","waitid","add_key","request_key","keyctl","ioprio_set","ioprio_get","inotify_init","inotify_add_watch","inotify_rm_watch","migrate_pages","openat","mkdirat","mknodat","fchownat","futimesat","newfstatat","unlinkat","renameat","linkat","symlinkat","readlinkat","fchmodat","faccessat","pselect","ppoll","unshare","set_robust_list","get_robust_list","splice","tee","sync_file_range","vmsplice","move_pages","utimensat","epoll_pwait","signalfd","timerfd_create","eventfd","fallocate","timerfd_settime","timerfd_gettime","accept","signalfd","eventfd","epoll_create","dup","pipe","inotify_init","preadv","pwritev","rt_tgsigqueueinfo","perf_event_open","recvmmsg","fanotify_init","fanotify_mark","prlimit","name_to_handle_at","open_by_handle_at","clock_adjtime","syncfs","sendmmsg","setns","getcpu","process_vm_readv","process_vm_writev","kcmp","finit_module","sched_setattr","sched_getattr","renameat","seccomp","getrandom","memfd_create","kexec_file_load","bpf","execveat","userfaultfd","membarrier","mlock","copy_file_range","preadv","pwritev","pkey_mprotect","pkey_alloc","pkey_free","statx","io_pgetevents","rseq"]

def print_syscalls(bv):
	# Print Syscall numbers for a provided file
	calling_convention = bv.platform.system_call_convention
	if calling_convention is None:
		log_error('Error: No syscall convention available for {:s}'.format(bv.platform))
		return

	register = calling_convention.int_arg_regs[0]

	report = "### Syscalls for {}\n".format(bv.file.filename)

	for func in bv.functions:
		syscalls = (il for il in chain.from_iterable(func.low_level_il)
					if il.operation == LowLevelILOperation.LLIL_SYSCALL)
		for il in syscalls:
			value = func.get_reg_value_at(il.address, register).value
			report += "##### System call address: [{:#x}](binaryninja://?expr={:#x}) - {}\n".format(il.address, il.address, syscall_table[value])

	if len(report) == 0:
		return "# No Syscalls Discovered in binary"
	return report

def display_syscalls(bv):
	bv.show_markdown_report("Syscall Info Report", print_syscalls(bv))


PluginCommand.register("Syscall Finder", "Shows information about all the syscalls in the binary", display_syscalls)
Exemple #27
0
	contents += "| Start | Name   |\n"
	contents += "|------:|:-------|\n"
	functions = list(bv.functions)
	for i in range(min(10, len(functions))):
		contents += "| 0x%x | %s |\n" % (functions[i].start, functions[i].symbol.full_name)

	contents += "### First 10 Strings ###\n"
	contents += "| Start | Length | String |\n"
	contents += "|------:|-------:|:-------|\n"
	for i in range(min(10, len(bv.strings))):
		start = bv.strings[i].start
		length = bv.strings[i].length
		string = bv.read(start, length)
		try:
			string = string.decode('utf8')
		except UnicodeDecodeError:
			pass
		contents += "| 0x%x |%d | %s |\n" % (start, length, string)
	return contents


def display_bininfo(bv):
	interaction.show_markdown_report("Binary Info Report", get_bininfo(bv))


if __name__ == "__main__":
	print(get_bininfo(None))
else:
	PluginCommand.register("Binary Info", "Display basic info about the binary", display_bininfo)
Exemple #28
0
        bv.add_user_segment(
            p['base'], p['size'], 0, 0, SegmentFlag.SegmentContainsData
            | SegmentFlag.SegmentReadable | SegmentFlag.SegmentWritable)
        bv.define_data_var(p['base'], struct_type)
        bv.define_user_symbol(
            Symbol(SymbolType.ImportedDataSymbol, p['base'], p['name']))

    for p in base_peripherals:
        s = Structure()
        for r in p['registers'].values():
            if r['size'] is None:
                s.insert(r['offset'], Type.int(4, False), r['name'])
            else:
                s.insert(r['offset'], Type.int(int(r['size'] / 8), False),
                         r['name'])
        struct_type = Type.structure_type(s)
        bv.define_user_type(p['name'], struct_type)
        register_peripheral(p, struct_type)

    for p in derived_peripherals:
        struct_type = bv.get_type_by_name(
            device['peripherals'][p['derives']]['name'])
        register_peripheral(p, struct_type)


PluginCommand.register(
    "SVD\\SVD Browser",
    "Manage SVD files and browse/search for new files to load.",
    launch_browser)

PluginCommand.register("SVD\\Load SVD", "Apply an SVD's memory map", load_svd)