Beispiel #1
0
    def __init__(self, parent=None, device='local'):
        super(DeviceWindow, self).__init__(parent=parent)
        self.setSizeGripEnabled(False)
        self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.setWindowFlag(Qt.WindowContextHelpButtonHint, False)
        self.setWindowFlag(Qt.WindowCloseButtonHint, True)
        self.setModal(True)

        self.device_type = device

        try:
            if device == 'local':
                self.device = frida.get_local_device()
                self.setWindowTitle('Dwarf - Local Session')
            elif device == 'usb':
                self.setWindowTitle('Dwarf - USB Session')
                #self.device = frida.get_usb_device()
                self.device = None
            else:
                self.device = frida.get_local_device()
        except frida.TimedOutError:
            self.device = None
            print('Frida TimedOutError: No Device')

        self.updated_frida_version = ''
        self.updated_frida_assets_url = {}

        self.frida_update_thread = None
        self.devices_thread = None

        self.setup_ui()
Beispiel #2
0
def parse_args():
    parser = OptionParser(usage='usage: %prog [options] BundleID',
                          version='%prog 0.1')
    parser.add_option('-L',
                      '--local',
                      action='store_true',
                      default=False,
                      help='Connect to local device')
    parser.add_option('-U',
                      '--usb',
                      action='store_true',
                      default=False,
                      help='Connect to USB device')
    parser.add_option('-R',
                      '--remote',
                      action='store',
                      metavar='HOST',
                      help='Connect to remote device')
    (options, args) = parser.parse_args()
    if options.local:
        device = frida.get_local_device()
    elif options.usb:
        device = frida.get_usb_device()
    elif options.remote:
        device = frida.get_device_manager().add_remote_device(options.remote)
    else:
        parser.print_help()
        sys.exit(0)
    if len(args) != 1:
        parser.print_help()
        sys.exit(0)
    return device, args[0]
Beispiel #3
0
    def set_device(self):
        """
            Set's the target device to work with.

            :return:
        """

        if self.config.device_id is not None:
            self.device = frida.get_device(self.config.device_id)

        elif (self.config.host is not None) or (self.config.device_type
                                                == 'remote'):
            if self.config.host is None:
                self.device = frida.get_remote_device()
            else:
                host = self.config.host
                port = self.config.port
                self.device = frida.get_device_manager() \
                    .add_remote_device(f'{host}:{port}' if host is not None else f'127.0.0.1:{port}')

        elif self.config.device_type is not None:
            for dev in frida.enumerate_devices():
                if dev.type == self.config.device_type:
                    self.device = dev
        else:
            self.device = frida.get_local_device()

        # surely we have a device by now?
        if self.device is None:
            raise Exception('Unable to find a device')

        self.device.on('output', self.handlers.device_output)
        self.device.on('lost', self.handlers.device_lost)

        debug_print(f'device determined as: {self.device}')
Beispiel #4
0
 def __init__(self, script_text):
     self.sessions = []
     self.script_text = script_text
     self._device = frida.get_local_device()
     self._device.on("child-added", self._on_child_added)
     self._device.on("child-removed", self._on_child_removed)
     self._device.on("output", self._on_output)
 def _try_start(self):
     if self._device is not None:
         return
     if self._device_id is not None:
         try:
             self._device = frida.get_device(self._device_id)
         except:
             self._update_status("Device '%s' not found" % self._device_id)
             self._exit(1)
             return
     elif self._device_type is not None:
         self._device = find_device(self._device_type)
         if self._device is None:
             return
     elif self._host is not None:
         self._device = frida.get_device_manager().add_remote_device(
             self._host)
     else:
         self._device = frida.get_local_device()
     self._device.on('output', self._schedule_on_output)
     self._device.on('lost', self._schedule_on_device_lost)
     if self._target is not None:
         spawning = True
         try:
             target_type, target_value = self._target
             if target_type == 'file':
                 argv = target_value
                 if not self._quiet:
                     self._update_status("Spawning `%s`..." %
                                         " ".join(argv))
                 self._spawned_pid = self._device.spawn(argv)
                 self._spawned_argv = argv
                 attach_target = self._spawned_pid
             else:
                 attach_target = target_value
                 if not self._quiet:
                     self._update_status("Attaching...")
             spawning = False
             self._session = self._device.attach(attach_target)
             if self._enable_jit:
                 self._session.enable_jit()
             if self._enable_debugger:
                 self._session.enable_debugger()
                 if self._enable_jit:
                     self._print(
                         "Chrome Inspector server listening on port 9229\n")
                 else:
                     self._print(
                         "Duktape debugger listening on port 5858\n")
             self._session.on('detached',
                              self._schedule_on_session_detached)
         except Exception as e:
             if spawning:
                 self._update_status("Failed to spawn: %s" % e)
             else:
                 self._update_status("Failed to attach: %s" % e)
             self._exit(1)
             return
     self._start()
     self._started = True
Beispiel #6
0
    def __init__(self,
                 process_name='',
                 process_id=0,
                 script_folder='scripts',
                 wait=True):
        if process_name:
            proc = process.Process(process_name, suspended=True)
            if not proc.create():
                return
            process_id = proc.get_id()
        else:
            proc = None

        self._device = frida.get_local_device()
        self._device.on("child-added", self._on_child_added)
        self._device.on("child-removed", self._on_child_removed)
        self._device.on("output", self._on_output)

        self.script_folder = script_folder
        self._instrument(process_id)

        if proc:
            proc.resume()

        if wait:
            print(
                "[!] Ctrl+D on UNIX, Ctrl+Z on Windows/cmd.exe to detach from instrumented program.\n\n"
            )
            sys.stdin.read()
            self.session.detach()
Beispiel #7
0
    def __init__(self):
        appdata_path = os.environ["appdata"]
        data_path = os.path.join(appdata_path,"winstrument")

        if not os.path.exists(data_path):
            os.mkdir(data_path)

        settings_path = os.path.join(data_path, "settings.toml")

        #unique temporary storage for each instance of the program
        self._db = DBConnection(os.path.join(data_path,f"db_{datetime.now().timestamp()}.sqlite3"))
        self.settings_controller = SettingsController(settings_path)
        default_settings = {'target': 'C:\\Windows\\System32\\Calc.exe' , "verbosity": 0}
        #settings won't exist on first run
        if self.settings_controller.get_module_settings(self.CORE_MODNAME) == {}:
            self.settings_controller.set_module_settings(self.CORE_MODNAME, default_settings)

        self.metadata = self.get_metadata()
        self._stop_requested = threading.Event()
        self._reactor = Reactor(run_until_return=lambda reactor: self._stop_requested.wait())
        self._device = frida.get_local_device()
        self._sessions = set()

        self._device.on("child-added", lambda child: self._reactor.schedule(lambda: self._on_child_added(child)))
        self._device.on("child-removed", lambda child: self._reactor.schedule(lambda: self._on_child_removed(child)))
        self._base_module = importlib.import_module("winstrument.base_module",None)
        self._modules_to_load=[]
        self._available_modules = self._enumerate_modules()
        self._loaded_modules = []
        self._instrumentations = []
Beispiel #8
0
    def __init__(self, analyzer):
        """@param analyzer: Analyzer instance.
        """
        if not HAVE_FRIDA:
            raise CuckooFridaError(
                "Failed to import Frida's Python bindings.. Check your guest "
                "installation."
            )

        self.pipe_ctrl = PipeController()

        self.processes = {}
        self.sessions = {}
        self.scripts = {}
        self.device = frida.get_local_device()

        self.device.on(
            "child-added",
            lambda child: self._on_child_added(child.pid)
        )
        self.device.on(
            "child-removed",
            lambda child: self._on_child_removed(child.pid)
        )

        self.agent_handler = AgentHandler(analyzer, self)

        self._on_child_added_callback = None
        self._on_child_removed_callback = None
Beispiel #9
0
def get_device(device_id: str) -> frida.core.Device:
    if device_id == 'usb':
        return frida.get_usb_device(1)
    elif device_id == 'local':
        return frida.get_local_device()
    else:
        return frida.get_device(device_id, timeout=1)
Beispiel #10
0
 def start(self, args):
     self.dwarf.onScriptDestroyed.connect(self.stop)
     if args.package is None:
         self._device_window.setModal(True)
         self._device_window.onSelectedProcess.connect(
             self.on_proc_selected)
         self._device_window.onClosed.connect(self._on_devdlg_closed)
         self._device_window.show()
     else:
         self.dwarf.device = frida.get_local_device()
         if not args.spawn:
             print('* Trying to attach to {0}'.format(args.package))
             try:
                 self.dwarf.attach(args.package, args.script, False)
             except Exception as e:  # pylint: disable=broad-except
                 print('-failed-')
                 print('Reason: ' + str(e))
                 print('Help: you can use -sp to force spawn')
                 self.stop()
                 exit(0)
         else:
             print('* Trying to spawn {0}'.format(args.package))
             try:
                 self.dwarf.spawn(args.package, args.script)
             except Exception as e:  # pylint: disable=broad-except
                 print('-failed-')
                 print('Reason: ' + str(e))
                 self.stop()
                 exit(0)
Beispiel #11
0
    def __init__(self, app, *__args):
        super().__init__(*__args)

        self.app = app

        self.startup_script = ''

        self.setup_ui()

        self.updated_frida_version = ''
        self.updated_frida_assets_url = {}

        self.frida_update_thread = None
        self.devices_thread = None
        self.procs_update_thread = None
        self.spawns_update_thread = None
        self.update_commits_thread = None
        self.update_dwarf_thread = None

        self.setup_threads()

        frida.get_device_manager().on('added', self.update_device_ui)
        frida.get_device_manager().on('removed', self.update_device_ui)

        if not self.app.get_adb().available():
            # additional check for null local device
            if frida.get_local_device() is None:
                utils.show_message_box(
                    'adb/device/emu not found or not rooted! see details or output',
                    self.app.get_adb().get_states_string())

        self.update_ui_sync()
Beispiel #12
0
    def attach_application(self, pid, frida_script, device):

        self.frida_script = frida_script

        if pid.isnumeric():
            self.pid = int(pid)
        else:
            self.pid = pid

        if device == 'remote':
            self.device = frida.get_remote_device()
        elif device == 'usb':
            self.device = frida.get_usb_device()
        else:
            self.device = frida.get_local_device()

        self.session = self.device.attach(self.pid)

        with codecs.open(self.frida_script, 'r', 'utf-8') as f:
            source = f.read()

        self.script = self.session.create_script(source)
        self.script.load()

        return
Beispiel #13
0
    def eval_script(self,
                    enable_shell=False,
                    disable_dns=False,
                    disable_send=False,
                    disable_com=False):

        self.device = frida.get_local_device()
        self.device.on('output', self.on_output)
        self.device.on('lost', self.on_lost)

        # Spawn and attach to the process
        pid = frida.spawn(self.process_sample)
        session = frida.attach(pid)

        # attach to the session
        with open("process_hooker.js") as fp:
            script_js = fp.read()

        self.script = session.create_script(script_js,
                                            name="process_hooker.js")

        self.script.on('message', self.on_message)

        session.on('detached', self.on_detach)

        self.script.on('destroyed', self.on_destroyed)

        self.script.load()

        # Set Script variables
        print(' [*] Setting Script Vars...')
        self.script.post({
            "type": "set_script_vars",
            "debug": self._debug,
            "disable_dns": disable_dns,
            "enable_shell": enable_shell,
            "disable_send": disable_send,
            "disable_com": disable_com
        })

        # Sleep for a second to ensure the vars are set..
        time.sleep(1)

        print(' [*] Hooking Process %s' % pid)
        frida.resume(pid)

        print(' Press ctrl-c to kill the process...')
        # Keep the process running...
        while True:
            try:
                time.sleep(0.5)
                if self._process_terminated:
                    break
            except KeyboardInterrupt:
                break

        if not self._process_terminated:
            # Kill it with fire
            frida.kill(pid)
Beispiel #14
0
    def cleanup(self):
        try:
            self.unload_script(), self.detach_session()
        finally:
            self.session = self.script = self.msg_cb = None
            self.proc_id, self.proc_name, self.proc_params = 0, '', []

            self.dev = frida.get_local_device()
Beispiel #15
0
def get_device(device_id: str) -> frida.core.Device:
    frida.get_usb_device().spawn
    if device_id == 'usb':
        return frida.get_usb_device()
    elif device_id == 'local':
        return frida.get_local_device()
    else:
        return frida.get_device(device_id)
Beispiel #16
0
def init_session():
    try:
        session = None
        if platform == 'ios' or platform == 'android':
            try:
                device = frida.get_usb_device()
            except Exception as e:
                print colored(str(e), "red")
                traceback.print_exc()
                if platform == 'android':
                    print colored("Troubleshooting Help", "blue")
                    print colored("HINT: Is USB Debugging enabled?", "blue")
                    print colored("HINT: Is `frida-server` running on mobile device (with +x permissions)?", "blue")
                    print colored("HINT: Is `adb` daemon running?", "blue")
                    sys.exit(1)
                elif platform == "ios":
                    print colored("Troubleshooting Help", "blue")
                    print colored("HINT: Have you installed `frida` module from Cydia?", "blue")
                    print colored("HINT: Have used `ipa_installer` to inject the `FridaGadget` shared lbrary?", "blue")
                    sys.exit(1)
        elif platform == 'macos':
            device = frida.get_local_device()
        else:
            print colored('[ERROR] Unsupported Platform', 'red')
            sys.exit(1)
        pid = None
        if app_name:
            try:
                if platform == 'android' and spawn == 1:
                    print colored("Now Spawning %s" % app_name, "green")
                    pid = device.spawn([app_name])
                    time.sleep(5)
                    session = device.attach(pid)
                    time.sleep(5)
                elif (platform == 'ios' or platform == 'macos') and spawn == 1:
                    bundleID = getBundleID(device, app_name, platform)
                    if bundleID:
                        print colored("Now Spawning %s" % bundleID, "green")
                        pid = device.spawn([bundleID])
                        time.sleep(5)
                        session = device.attach(pid)
                    else:
                        print colored("[ERROR] Can't spawn %s" % app_name, "red")
                        traceback.print_exc()
                        sys.exit(1)
                else:
                    session = device.attach(app_name)
            except Exception as e:
                print colored('[ERROR] ' + str(e), 'red')
                traceback.print_exc()
        if session:
            print colored('[INFO] Attached to %s' % (app_name), 'yellow')
            session.on('detached', on_detached)
    except Exception as e:
        print colored('[ERROR] ' + str(e), 'red')
        traceback.print_exc()
        sys.exit(1)
    return device, session, pid
Beispiel #17
0
def init_session():
    try:
        session = None
        if platform == 'ios' or platform == 'android':
            try:
                device = frida.get_usb_device()
            except Exception as e:
                print colored(str(e), "red")
                traceback.print_exc()
                if platform == 'android':
                    print colored("Troubleshooting Help", "blue")
                    print colored("HINT: Is USB Debugging enabled?", "blue")
                    print colored("HINT: Is `frida-server` running on mobile device (with +x permissions)?", "blue")
                    print colored("HINT: Is `adb` daemon running?", "blue")
                    sys.exit(1)
                elif platform == "ios":
                    print colored("Troubleshooting Help", "blue")
                    print colored("HINT: Have you installed `frida` module from Cydia?", "blue")
                    print colored("HINT: Have used `ipa_installer` to inject the `FridaGadget` shared lbrary?", "blue")
                    sys.exit(1)
        elif platform == 'macos':
            device = frida.get_local_device()
        else:
            print colored('[ERROR] Unsupported Platform', 'red')
            sys.exit(1)
        pid = None
        if app_name:
            try:
                if platform == 'android' and spawn == 1:
                    print colored("Now Spawning %s" % app_name, "green")
                    pid = device.spawn([app_name])
                    time.sleep(5)
                    session = device.attach(pid)
                    time.sleep(5)
                elif (platform == 'ios' or platform == 'macos') and spawn == 1:
                    bundleID = getBundleID(device, app_name, platform)
                    if bundleID:
                        print colored("Now Spawning %s" % bundleID, "green")
                        pid = device.spawn([bundleID])
                        time.sleep(5)
                        session = device.attach(pid)
                    else:
                        print colored("[ERROR] Can't spawn %s" % app_name, "red")
                        traceback.print_exc()
                        sys.exit(1)
                else:
                    session = device.attach(app_name)
            except Exception as e:
                print colored('[ERROR] ' + str(e), 'red')
                traceback.print_exc()
        if session:
            print colored('[INFO] Attached to %s' % (app_name), 'yellow')
            session.on('detached', on_detached)
    except Exception as e:
        print colored('[ERROR] ' + str(e), 'red')
        traceback.print_exc()
        sys.exit(1)
    return device, session, pid
Beispiel #18
0
    def __init__(self):
        self._stop_requested = threading.Event()
        self._reactor = Reactor(run_until_return=lambda reactor: self._stop_requested.wait())

        self._device = frida.get_local_device()
        self._sessions = set()

        self._device.on("child-added", lambda child: self._reactor.schedule(lambda: self._on_child_added(child)))
        self._device.on("child-removed", lambda child: self._reactor.schedule(lambda: self._on_child_removed(child)))
        self._device.on("output", lambda pid, fd, data: self._reactor.schedule(lambda: self._on_output(pid, fd, data)))
Beispiel #19
0
    def __init__(self, parent=None, device='local'):
        super(DeviceWindow, self).__init__(parent=parent)

        self.spawn_list = None
        self.proc_list = None
        self.desktop_geom = None
        self._dev_bar = None

        self.setSizeGripEnabled(False)
        self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.setWindowFlag(Qt.WindowContextHelpButtonHint, False)
        self.setWindowFlag(Qt.WindowCloseButtonHint, True)
        self.setModal(True)

        self.device_type = device

        try:
            if device == 'local':
                self.device = frida.get_local_device()
                self.title = 'Local Session'
            elif device == 'usb':  # TODO: change
                self.title = 'Android Session'
                self.device = None
            elif device == 'ios':
                self.title = 'iOS Session'
                self.device = frida.get_usb_device()
            elif device == 'remote':
                self.title = 'Remote Session'
                self.device = frida.get_remote_device()
            else:
                self.device = frida.get_local_device()
        except frida.TimedOutError:
            self.device = None
            print('Frida TimedOutError: No Device')

        self.updated_frida_version = ''
        self.updated_frida_assets_url = {}

        self.frida_update_thread = None
        self.devices_thread = None

        self.setup_ui()
Beispiel #20
0
def attach_spawn_target(args, user_script=None):
    if not args.target and not args.device:
        print('missing session type. use -t local|android|ios|remote to define the session type'
              ' or specify a device id with --device')
        exit(0)

    if args.any is None or args.any == '':
        print('missing file or package name to attach')
        exit(0)

    device = None
    try:
        if args.device:
            device = frida.get_device(id=args.device)
        else:
            session_type = args.target.lower()
            if session_type == 'local':
                device = frida.get_local_device()
            elif session_type == 'android' or session_type == 'ios':
                device = frida.get_usb_device(5)
            elif session_type == 'remote':
                device = frida.get_remote_device()
    except Exception as e:
        print('failed to get frida device')
        print(e)

    if device is not None:
        try:
            # parse target as pid
            args.pid = int(args.any)
        except ValueError:
            args.pid = 0

        if args.pid > 0:
            print('* Trying to attach to {0}'.format(args.pid))
            try:
                attach(args, device)
                print('* Dwarf attached to {0}'.format(args.pid))
            except Exception as e:  # pylint: disable=broad-except
                print('-failed-')
                print('Reason: ' + str(e))
                print('Help: you can use -sp to force spawn')
                exit(0)
        else:
            print('* Trying to spawn {0}'.format(args.any))
            try:
                _pid = spawn(args, device, user_script)
                print('* Dwarf attached to {0}'.format(_pid))
            except Exception as e:  # pylint: disable=broad-except
                print('-failed-')
                print('Reason: ' + str(e))
                exit(0)

        sys.stdin.read()
Beispiel #21
0
    def frida_sess_init(self):
        if self.frida:
            info = self.r2p.cmdj("ij")
            self.pid = int(self.r2p.cmd("\\dp"))

            self.device = frida.get_local_device()
            for dev in frida.enumerate_devices():
                if info["core"]["file"].startswith("frida://%s" % dev.id):
                    self.device = dev

            self.frida_sess = self.device.attach(self.pid)
Beispiel #22
0
    def __init__(self, launch_args=[]):
        self._launch_args = launch_args
        self._stop_requested = threading.Event()
        self._reactor = Reactor(
            run_until_return=lambda _: self._stop_requested.wait())

        self._device = frida.get_local_device()
        self._sessions = set()

        self._device.on(
            'child-added', lambda child: self._reactor.schedule(
                lambda: self._on_delivered(child)))
Beispiel #23
0
 def _try_start(self):
     if self._device is not None:
         return
     if self._device_id is not None:
         try:
             self._device = frida.get_device(self._device_id)
         except:
             self._update_status("Device '%s' not found" % self._device_id)
             self._exit(1)
             return
     elif self._device_type is not None:
         self._device = find_device(self._device_type)
         if self._device is None:
             return
     elif self._host is not None:
         self._device = frida.get_device_manager().add_remote_device(self._host)
     else:
         self._device = frida.get_local_device()
     self._device.on('output', self._schedule_on_output)
     self._device.on('lost', self._schedule_on_device_lost)
     if self._target is not None:
         spawning = True
         try:
             target_type, target_value = self._target
             if target_type == 'file':
                 argv = target_value
                 self._update_status("Spawning `%s`..." % " ".join(argv))
                 self._spawned_pid = self._device.spawn(argv)
                 self._spawned_argv = argv
                 attach_target = self._spawned_pid
             else:
                 attach_target = target_value
                 self._update_status("Attaching...")
             spawning = False
             self._session = self._device.attach(attach_target)
             if self._disable_jit:
                 self._session.disable_jit()
             if self._enable_debugger:
                 self._session.enable_debugger()
                 self._print("Debugger listening on port 5858\n")
             self._session.on('detached', self._schedule_on_session_detached)
         except Exception as e:
             if spawning:
                 self._update_status("Failed to spawn: %s" % e)
             else:
                 self._update_status("Failed to attach: %s" % e)
             self._exit(1)
             return
     self._start()
     self._started = True
Beispiel #24
0
    def frida_sess_init(self):
        if self.frida:
            info = self.r2p.cmdj("ij")
            self.pid = int(self.r2p.cmd("\\dp"))

            if "/usb/" in info["core"]["file"]:
                self.device = frida.get_usb_device()
            else:
                self.device = frida.get_local_device()

            for dev in frida.enumerate_devices():
                if dev.id in info["core"]["file"]:
                    self.device = dev

            self.frida_sess = self.device.attach(self.pid)
Beispiel #25
0
    async def run(self, command):
        """
        Run process tracking.

        :param command: `argv` for entry executable.
        """

        self._device = frida.get_local_device()
        self._device.on('child-added', self._on_child_added)
        self._device.on('child-removed', self._on_child_removed)

        _L.info(f'Running {command}...')
        pid = await util.async_run(self._device.spawn, command)
        await self._instrument(pid, 'exec', command[0], True)

        await self._wait_until_no_processes()
Beispiel #26
0
    def _get_device(self):
        try:
            self.device = frida.get_usb_device()
        except frida.TimedOutError:
            self.device = None

        if self.device is None:
            # now check for a local device
            try:
                self.device = frida.get_local_device()
            except frida.TimedOutError:
                self.device = None

            if self.device is None:
                return 1
        return 0
Beispiel #27
0
def main(target_binary, entrypoint):
    shm_var = os.getenv("__AFL_SHM_ID")
    print("__AFL_SHM_ID is {}".format(shm_var))
    print("Spawning {} ".format(" ".join(target_binary)))
    device = frida.get_local_device()
    pid = device.spawn(target_binary, aslr="disable")
    session = device.attach(pid)
    session.on('detached', exiting)
    with open('afl.js', 'r') as file:
        data = file.read()
        script = session.create_script(data, runtime='v8')
    script.on("message", on_message)
    script.load()
    if entrypoint:
        script.exports.init(entrypoint)
    device.resume(pid)
    finished.wait()
    def __init__(self):
        self._stop_requested = threading.Event()
        self._reactor = Reactor(
            run_until_return=lambda reactor: self._stop_requested.wait())

        self._device = frida.get_local_device()
        self._sessions = set()

        self._device.on(
            "child-added", lambda child: self._reactor.schedule(
                lambda: self._on_child_added(child)))
        self._device.on(
            "child-removed", lambda child: self._reactor.schedule(
                lambda: self._on_child_removed(child)))
        self._device.on(
            "output", lambda pid, fd, data: self._reactor.schedule(
                lambda: self._on_output(pid, fd, data)))
Beispiel #29
0
    def __init__(self, app, *__args):
        super().__init__(*__args)

        self.app = app

        self.startup_script = ''

        self.menu_bar = None
        self.status_bar = None

        _app = QApplication.instance()
        for w in _app.topLevelWidgets():
            if isinstance(w, QMainWindow):
                #self.menu_bar = w.get_menu()
                self.status_bar = w.get_statusbar()

        self.update_action = QAction('Update Dwarf')
        self.update_action.triggered.connect(self.update_dwarf)

        self.setup_ui()

        self.updated_frida_version = ''
        self.updated_frida_assets_url = {}

        self.frida_update_thread = None
        self.devices_thread = None
        self.procs_update_thread = None
        self.spawns_update_thread = None
        self.update_commits_thread = None
        self.update_dwarf_thread = None

        self.setup_threads()

        frida.get_device_manager().on('added', self.update_device_ui)
        frida.get_device_manager().on('removed', self.update_device_ui)

        if not self.app.get_adb().available():
            # additional check for null local device
            if frida.get_local_device() is None:
                utils.show_message_box('adb/device/emu not found or not rooted! see details or output',
                                       self.app.get_adb().get_states_string())

        self.update_ui_sync()
Beispiel #30
0
    def __init__(self, worker_pid, hooks, detach_event, new_child=False):
        super().__init__()
        self.worker_pid = worker_pid
        self.name = "HookWorkerThread-{}".format(str(worker_pid))
        self.hooks = hooks
        self.message_queue = message_queue
        self.detach_event = detach_event
        self.new_child = new_child

        try:
            logger.info("Starting to hook PHP-FPM Worker-{}".format(str(self.worker_pid)))
            attach_lock.acquire()
            self._device = frida.get_local_device()
            self.session = self._device.attach(self.worker_pid)
            attach_lock.release()
            self.session.on('detached', self.on_detached)

            if self.session:
                logger.info("PHP-FPM Worker-{} is attached".format(str(self.worker_pid)))
        except Exception as e:
            logger.exception(e)
Beispiel #31
0
    def __init__(self, config, logger_obj, api_watch_list):

        self.config = config
        self.logger = logger_obj
        self.api_watch_list = api_watch_list
        self.execution_timeout = self.config.get_execution_timeout()
        self.capture_basic_behavior = self.config.get_capture_behavior_report_basic_flag()
        self.capture_complete_behavior = self.config.get_capture_behavior_report_complete_flag()
        self.process_list = []
        self.target_process_pid = None

        # Initialize Reporting Module
        self.report_generator = Reporting(config, logger_obj)

        # Initialize Queue for FriSpyGUI to receive the events
        self.event_queue_name = self.config.get_event_queue_name()
        self.msmqueue_event = MSMQCustom(self.event_queue_name)

        self.config_queue_name = self.config.get_config_queue_name()
        self.msmqueue_config = MSMQCustom(self.config_queue_name)

        # Initialize Controller
        self._stop_requested = threading.Event()
        self._reactor = Reactor(run_until_return=lambda reactor: self._stop_requested.wait())

        self._device = frida.get_local_device()
        self._sessions = set()
        try:

            self._device.on("child-added", lambda child: self._reactor.schedule(lambda: self._on_child_added(child)))
            self._device.on("child-removed", lambda child: self._reactor.schedule(lambda: self._on_child_removed(child)))
            self._device.on("output", lambda pid, fd, data: self._reactor.schedule(lambda: self._on_output(pid, fd, data)))
            self._device.on("process-crashed", lambda crash: self._reactor.schedule(lambda: self._on_process_crashed(crash)))
            self._device.on("lost", lambda crash: self._reactor.schedule(lambda: self._on_process_crashed(crash)))

        except Exception as e:
            self.logger.log("error", "Exception - FriSpyController : run : %s" %(str(e)))
            self.Controller_cleaup(None)
            sys.exit(1)
Beispiel #32
0
    def __init__(self, master_pid, hooks, detach_event):
        super().__init__()
        self.master_pid = master_pid
        self.name = "HookMasterThread-{}".format(str(self.master_pid))
        self.hooks = hooks
        self.message_queue = message_queue
        self.detach_event = detach_event

        try:
            logger.info("Starting to hook PHP-FPM Master-{}".format(str(self.master_pid)))
            attach_lock.acquire()
            self._device = frida.get_local_device()
            self.session = self._device.attach(self.master_pid)
            attach_lock.release()
            self.session.on('detached', self.on_detached)
            self._device.on("child-added", self.on_child_added)
            self._device.on("child-removed", self.on_child_removed)

            if self.session:
                logger.info("PHP-FPM Master-{} is attached".format(str(self.master_pid)))
        except Exception as e:
            logger.exception(e)
Beispiel #33
0
def main(target, use_usb, pid, filter, should_parse):
    """Intercept XPC messages and more"""
    if target:
        pass
    elif pid:
        target = int(pid)
    else:
        ctx = click.get_current_context()
        click.secho(ctx.get_help())
        ctx.exit()
        sys.exit()

    os = None
    device = None
    if use_usb:
        os = 'ios'
        try:
            device = get_usb_device()
        except InvalidArgumentError:
            logger.exit_with_error(f"USB device not found")
            sys.exit()
    else:
        pf = platform()
        if pf.startswith('macOS'):
            os = 'macos'
            device = get_local_device()
        else:
            logger.exit_with_error(f"Unsupported platform: {pf}")
            sys.exit()

    if filter:
        filter = Filter.from_str(filter)
        if filter == None:
            logger.exit_with_error(f"Invalid filter string")
    else:
        filter = Filter.default()

    Agent(target, device, os, filter, should_parse)
    sys.stdin.read()
Beispiel #34
0
def init_session():
	try:
		session = None
		if platform == 'ios' or platform == 'android':
			device = frida.get_usb_device()
		elif platform == 'mac':
			device = frida.get_local_device()
		else:
			print colored('[ERROR] Unsupported platform', 'red')
			sys.exit()
		if app_name:
			try:
				session = device.attach(app_name)
			except Exception as e:
				print colored('[ERROR] ' + str(e), 'red')
				traceback.print_exc()
		if session:
			print colored('[INFO] Attached to %s' % (app_name), 'yellow')
			session.on('detached', on_detached)
	except Exception as e:
		print colored('[ERROR] ' + str(e), 'red')
		traceback.print_exc()
		sys.exit(1)
	return device, session
Beispiel #35
0
#
# Compile example.dylib like this:
# $ clang -shared example.c -o example.dylib
#
# Then run:
# $ python inject_blob.py Twitter example.dylib
#

from __future__ import unicode_literals, print_function

import sys

import frida


def on_uninjected(id):
    print("on_uninjected id=%u" % id)

(target, library_path) = sys.argv[1:]

device = frida.get_local_device()
device.on("uninjected", on_uninjected)
with open(library_path, "rb") as library_file:
    library_blob = library_file.read()
id = device.inject_library_blob(target, library_blob, "example_main", "w00t")
print("*** Injected, id=%u -- hit Ctrl+D to exit!" % id)
sys.stdin.read()
Beispiel #36
0
def init_session():
    try:
        session = None
        if platform == 'ios' or platform == 'android':
            try:
                device = frida.get_usb_device(3) # added timeout to wait for 3 seconds
            except Exception as e:
                print colored(str(e), "red")
                traceback.print_exc()
                if platform == 'android':
                    print colored("Troubleshooting Help", "blue")
                    print colored("HINT: Is USB Debugging enabled?", "blue")
                    print colored("HINT: Is `frida-server` running on mobile device (with +x permissions)?", "blue")
                    print colored("HINT: Is `adb` daemon running?", "blue")
                    sys.exit(1)
                elif platform == "ios":
                    print colored("Troubleshooting Help", "blue")
                    print colored("HINT: Have you installed `frida` module from Cydia?", "blue")
                    print colored("HINT: Have used `ipa_installer` to inject the `FridaGadget` shared lbrary?", "blue")
                    sys.exit(1)
        elif platform == 'iossim':
            try:
                device = frida.get_remote_device()
            except Exception as e:
                # print traceback.print_exc()
                print colored("Troubleshooting Help", "blue")
                print colored("HINT: Have you successfully integrated the FridaGadget dylib with the XCode Project?", "blue")
                print colored("HINT: Do you see a message similar to \"[Frida INFO] Listening on 127.0.0.1 TCP port 27042\" on XCode console logs?", "blue")
                sys.exit(1)
        elif platform == 'macos':
            device = frida.get_local_device()
        else:
            print colored('[ERROR] Unsupported Platform', 'red')
            sys.exit(1)
        pid = None
        if app_name:
            try:
                if platform == 'android' and spawn == 1:
                    print colored("Now Spawning %s" % app_name, "green")
                    pid = device.spawn([app_name])
                    #time.sleep(5)
                    session = device.attach(pid)
                    #time.sleep(5)
                elif (platform == 'ios' or platform == 'macos') and spawn == 1:
                    bundleID = getBundleID(device, app_name, platform)
                    if bundleID:
                        print colored("Now Spawning %s" % bundleID, "green")
                        pid = device.spawn([bundleID])
                        #time.sleep(5)
                        session = device.attach(pid)
                    else:
                        print colored("[ERROR] Can't spawn %s" % app_name, "red")
                        traceback.print_exc()
                        sys.exit(1)
                else:
                    arg_to_attach = app_name
                    if app_name.isdigit():
                        arg_to_attach = int(app_name)

                    session = device.attach(arg_to_attach)
            except Exception as e:
                print colored('[ERROR] ' + str(e), 'red')
                traceback.print_exc()
        if session:
            print colored('[INFO] Attached to %s' % (app_name), 'yellow')
            session.on('detached', on_detached)
    except Exception as e:
        print colored('[ERROR] ' + str(e), 'red')
        traceback.print_exc()
        sys.exit(1)
    return device, session, pid