def __init__(self, serial=None):
        super(Frida, self).__init__()
        self._logger = logger.get_logger(self.__class__.__name__)
        self._frida_server_factory = FridaServerFactory(serial=serial)
        self._serial = serial
        self._frida_server = None
        self._device = None
        self._session = None

        found = False
        while not found:
            try:
                if serial is not None:
                    self._logger.info('Frida using device with serial "%s"',
                                      serial)
                    device = frida.get_device_manager().get_device(serial)
                else:
                    self._logger.info(
                        'No device serial given; using default USB device')
                    device = frida.get_device_manager().get_usb_device()

                found = True

            except frida.InvalidArgumentError as exception:
                self._logger.info('Frida exception "%s"; retrying in 2 secs.',
                                  str(exception))
                time.sleep(2)

        self._logger.info('Found device "%s" (%s) over %s', device.name,
                          device.id, device.type.upper())
        self._device = device
Beispiel #2
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 #3
0
def find_app(app_name_or_id, device_id, device_ip):
    if device_id is None:
        if device_ip is None:
            dev = frida.get_usb_device()
        else:
            frida.get_device_manager().add_remote_device(device_ip)
            dev = frida.get_device("tcp@" + device_ip)
    else:
        try:
            dev = next(dev for dev in frida.enumerate_devices()
                       if dev.id.startswith(device_id))
        except StopIteration:
            fatal('device id %s not found' % device_id)

    if dev.type not in ('tether', 'remote', 'usb'):
        fatal('unable to find device')

    try:
        app = next(
            app for app in dev.enumerate_applications()
            if app_name_or_id == app.identifier or app_name_or_id == app.name)
    except:
        print('app "%s" not found' % app_name_or_id)
        print('installed app:')
        for app in dev.enumerate_applications():
            print('%s (%s)' % (app.name, app.identifier))
        fatal('')

    return dev, app
Beispiel #4
0
def main():
    device = frida.get_device_manager().enumerate_devices()[-1]
    package_name = "com.skymoons.hqg.uc"

    # find and kill process.
    pid = get_process_pid(device, package_name)
    if pid != -1:
        print("killing {0}".format(pid))
        device.kill(pid)
        time.sleep(0.3)

    os.system("adb shell am start -n {0}/{1}".format(package_name, "com.onektower.sdk.tgame.SplashActivity"))
    time.sleep(0.2)

    pid = get_process_pid(device, package_name)
    if pid == -1:
        print("{0} is not found...".format(package_name))
        return

    session = None
    try:
        session = frida.get_device_manager().enumerate_devices()[-1].attach(pid)
        script_content = open("payload.js").read()
        script = session.create_script(script_content)
        script.on("message", on_message)
        script.load()
        sys.stdin.read()
    except KeyboardInterrupt as e:
        if session is not None:
            session.detach()
        sys.exit(0)
Beispiel #5
0
def main():
    device = frida.get_device_manager().enumerate_devices()[-1]
    package_name = "com.skymoons.hqg.uc"

    # find and kill process.
    pid = get_process_pid(device, package_name)
    if pid != -1:
        print("killing {0}".format(pid))
        device.kill(pid)
        time.sleep(0.3)

    os.system("adb shell am start -n {0}/{1}".format(
        package_name, "com.onektower.sdk.tgame.SplashActivity"))
    time.sleep(0.2)

    pid = get_process_pid(device, package_name)
    if pid == -1:
        print("{0} is not found...".format(package_name))
        return

    session = None
    try:
        session = frida.get_device_manager().enumerate_devices()[-1].attach(
            pid)
        script_content = open("payload.js").read()
        script = session.create_script(script_content)
        script.on("message", on_message)
        script.load()
        sys.stdin.read()
    except KeyboardInterrupt as e:
        if session is not None:
            session.detach()
        sys.exit(0)
Beispiel #6
0
    def __init__(self, parent=None, device_type='usb'):
        super().__init__(parent=parent)

        # dont show for local
        if device_type != 'usb':
            return

        self.parent = parent
        self.wait_for_devtype = device_type
        self.is_waiting = True
        self._adb = Adb()

        if not self._adb.min_required:
            raise Exception('Adb missing or no Device')

        self._git = Git()
        self.setAutoFillBackground(True)
        self.setStyleSheet(
            'background-color: crimson; color: white; font-weight: bold; margin: 0; padding: 10px;'
        )
        self.setup()
        self._timer = QTimer()
        self._timer.setInterval(500)
        self._timer.timeout.connect(self._on_timer)
        self._timer.start()
        self._timer_step = 0
        frida.get_device_manager().on('added', self._on_device)
        frida.get_device_manager().on('removed', self._on_device)
        self.devices_thread = DevicesUpdateThread(self)
        self.devices_thread.onAddDevice.connect(self.on_add_deviceitem)
        self.devices_thread.onDevicesUpdated.connect(self._on_devices_finished)
        self._update_thread = FridaUpdateThread(self)
        self._update_thread._adb = self._adb
        self._update_thread.onStatusUpdate.connect(self._update_statuslbl)
        self._update_thread.onFinished.connect(self._frida_updated)
        self._update_thread.onError.connect(self._on_download_error)
        self.updated_frida_version = ''
        self.updated_frida_assets_url = {}
        self._device_id = None
        self._devices = []
        remote_frida = self._git.get_frida_version()
        if remote_frida is None:
            self.updated_frida_version = ''
            self.updated_frida_assets_url.clear()
        else:
            remote_frida = remote_frida[0]
            self.updated_frida_version = remote_frida['tag_name']
            for asset in remote_frida['assets']:
                if 'android-' not in asset:
                    continue

                try:
                    name = asset['name']
                    tag_start = name.index('android-')
                    if name.index('server') >= 0:
                        tag = name[tag_start + 8:-3]
                        self.updated_frida_assets_url[tag] = asset[
                            'browser_download_url']
                except ValueError:
                    pass
Beispiel #7
0
    def run_instrumentation(self):

        """
        Select and run instrumentation function using the
        Frida instrumentation toolkit
        """

        while True:
            print(t.green("[{0}] ".format(datetime.now()) +
                          t.cyan("Enter 'quit' to exit Frida module!")))

            print(t.green("[{0}] ".format(datetime.now()) +
                          t.yellow("Available Frida functions: ") +
                          "activities, webview"))

            function = raw_input(t.green("[{0}] ".format(datetime.now())
                                         + t.yellow("Enter Frida function: ")))

            if function == "quit":
                break

            try:
                if function == "activities":
                    # adb forward just
                    # in case
                    #
                    Popen("adb forward tcp:27042 tcp:27042", shell=True).wait()
                    process = frida.get_device_manager().enumerate_devices()[-1].attach(self.apk.get_package())
                    script = process.create_script(self.do_activities())
                    script.on('message', self.on_message)
                    script.load()
                    sys.stdin.read()

                elif function == "webview":
                    # adb forward just
                    # in case
                    #
                    Popen("adb forward tcp:27042 tcp:27042", shell=True).wait()
                    process = frida.get_device_manager().enumerate_devices()[-1].attach(self.apk.get_package())
                    script = process.create_script(self.do_webview())
                    script.on('message', self.on_message)
                    script.load()
                    sys.stdin.read()

            except frida.ProcessNotFoundError as e:
                print(t.red("[{0}] ".format(datetime.now()) +
                            "Could not connect to target process!"))
                Logger.run_logger(e.message)
            except frida.ServerNotRunningError as e:
                print(t.red("[{0}] ".format(datetime.now()) +
                            "The frida-server is not running!"))
                Logger.run_logger(e.message)
            except frida.TransportError as e:
                print(t.red("[{0}] ".format(datetime.now()) +
                            "Connection was closed!"))
                Logger.run_logger(e.message)
            except KeyboardInterrupt:
                pass
def main():
    args = parse_args()
    if args.command == "run":
        script_file = args.script
        package_name = args.package

        if os.path.isabs(script_file) is False:
            script_file = os.path.abspath(script_file)

        device = frida.get_device_manager().enumerate_devices()[-1]

        pid = get_process_pid(device, package_name)
        if pid != -1:
            print("[+] killing {0}".format(pid))
            device.kill(pid)
            time.sleep(0.3)

        # Pause for 3s.
        os.system(
            r"adb shell su -c \"echo 4 > /data/data/{0}/files/.pause\"".format(
                package_name))
        os.system(
            r"adb shell monkey -p {0} -c android.intent.category.LAUNCHER 1".
            format(package_name))

        pid = -1
        for i in range(10):
            pid = get_process_pid(device, package_name)
            if pid != -1:
                break
            time.sleep(0.1)

        if pid == -1:
            print("[-] Run package {0} failed.".format(package_name))
            return

        print("[+] Injecting {0} to {1}({2})".format(script_file, package_name,
                                                     pid))

        session = None
        try:
            session = frida.get_device_manager().enumerate_devices(
            )[-1].attach(pid)
            script_content = open(script_file).read()
            # Update some consts.
            script_content = script_content.replace("__PACKAGE_NAME__",
                                                    package_name)
            script = session.create_script(script_content)
            script.on("message", on_message)
            script.load()
            sys.stdin.read()
        except KeyboardInterrupt as e:
            if session is not None:
                session.detach()
            sys.exit(0)

    else:
        pass
Beispiel #9
0
def attach(target):
    packageName = target
    if is_number(target):  #pid
        packageName = getPidMap()[target]
    online_session = None
    online_script = None
    rdev = None
    remoteDriver = run_env.getRemoteDriver()  #ip:port
    try:
        if remoteDriver:
            rdev = frida.get_device_manager().add_remote_device(remoteDriver)
        elif platform.system().find("Windows") != -1:
            warn("推荐使用linux或mac操作系统获得更好的兼容性.")
            rdev = frida.get_remote_device()
        else:
            rdev = frida.get_usb_device(1000)
        #print(f"attach {target}")
        if is_number(target):
            pid = int(target)
            online_session = frida.core.Session(rdev._impl.attach(pid))
        else:
            online_session = rdev.attach(target)
        if online_session == None:
            warn("attaching fail to " + target)
        online_script = online_session.create_script(run_env.rpc_jscode)
        online_script.on('message', on_message)
        online_script.load()
        checkRadarDex(packageName, online_script)
        createHookingEnverment(packageName,
                               online_script.exports.mainactivity())
    except Exception:
        warn(traceback.format_exc())
    return online_session, online_script, packageName
Beispiel #10
0
    def __init__(self, name, target_dict):

        self.name             = name
        self.frida_session    = None
        self.frida_script     = None
        self.process_name     = None
        self.process_pid      = None
        self.remote_frida     = False
        self.frida_port       = 27042
        self.modules          = None        # Modules which are loaded in the process
        self.modules_to_watch = None        # Modules which where given in the config file
                                            # for which the coverage should be tracked
        self.watched_modules = None         # intersection of self.modules and self.modules_to_watch

        if "function" in target_dict:
            self.function = target_dict["function"]
        else:
            log.warn("No 'function' in target-section '%s'!" % name)
            return False

        if "process_name" in target_dict:
            self.process_name = target_dict["process_name"]
        if "process_pid" in target_dict:
            self.process_pid = target_dict["process_pid"]
        if "remote_frida" in target_dict:
            self.remote_frida = target_dict["remote_frida"]
        if "frida_port" in target_dict:
            self.frida_port = target_dict["frida_port"]
        if "modules" in target_dict:
            self.modules_to_watch = target_dict["modules"]

        if self.remote_frida:
            self.frida_instance = frida.get_device_manager().add_remote_device('%s:%d' % ('localhost', self.frida_port))
        else:
            self.frida_instance = frida
Beispiel #11
0
    def _get_device() -> frida.core.Device:
        """
            Attempt to get a handle on a device.

            :return:
        """

        if state_connection.get_comms_type() == state_connection.TYPE_USB:

            if state_connection.device_serial:
                device = frida.get_device(state_connection.device_serial)
                click.secho('Using USB device `{n}`'.format(n=device.name),
                            bold=True)

                return device

            else:
                device = frida.get_usb_device(5)
                click.secho('Using USB device `{n}`'.format(n=device.name),
                            bold=True)

                return device

        if state_connection.get_comms_type() == state_connection.TYPE_REMOTE:
            device = frida.get_device_manager().add_remote_device(
                '{host}:{port}'.format(host=state_connection.host,
                                       port=state_connection.port))
            click.secho('Using networked device @`{n}`'.format(n=device.name),
                        bold=True)

            return device

        raise Exception('Failed to find a device to attach to!')
Beispiel #12
0
    def module_pre(self):
        # Run FridaModule setup function
        FridaModule.module_pre(self)

        # Get an handle to the device
        import frida
        if self.device.is_usb():
            self.printer.debug("Connected over USB")
            device = frida.get_usb_device()
        else:
            self.printer.debug("Connected over Wi-Fi")
            device = frida.get_device_manager().enumerate_devices()[1]

        # Launching the app
        self.printer.info("Launching the app...")
        self.device.app.open(self.APP_METADATA['bundle_id'])
        pid = int(self.device.app.search_pid(self.APP_METADATA['name']))

        # Attaching to the process
        self.printer.info("Attaching to process: %s" % pid)
        self.session = device.attach(pid)

        # Preparing results
        self.results = []
        return 1
Beispiel #13
0
def frida_runner(app_name, script_name, verbose, host):
    """
    Attach Frida script to an app running on a device
    """
    try:
        content = open(script_name, 'r').read()

        device_id = DEVICE_ID_PLACEHOLDER
        script_text = SCRIPT_WRAPPER % locals()
        script_text = script_text % 1

        if verbose:
            _print_with_line_no(script_text)

        print('Starting session...')
        if host:
            remote_device = frida.get_device_manager().add_remote_device(host)
            session = remote_device.attach(app_name)
        else:
            session = frida.get_usb_device().attach(app_name)
        script = session.create_script(script_text)

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

        print('Connected')
        sys.stdin.read()

    except Exception as e:
        print(e)
 def inject(self, traffic_sniffer):
     Popen(["adb forward tcp:27042 tcp:27042"], shell=True).wait()
     device = frida.get_device_manager().enumerate_devices()[-1]
     process = device.attach(self.proc)
     script = process.create_script(traffic_sniffer.get_sniffer_js())
     script.on('message', traffic_sniffer.on_message)
     script.load()
Beispiel #15
0
    def start_hook(self, script_path, udid=""):
        """
        直接hook进程
        :param udid:
        :param script_path:
        :return:
        """
        try:
            # signal.signal(signal.SIGINT, quit)
            # signal.signal(signal.SIGTERM, quit)
            # 加载Frida
            with open(script_path, encoding='utf-8') as f:
                jscode = f.read()

            if udid == "":
                device = frida.get_usb_device()
            else:
                device = frida.get_device_manager().get_device(udid)
            self.process = device.attach(self.package_name)
            self.process.enable_debugger()
            self.script = self.process.create_script(jscode, runtime="v8")
            self.script.on('message', self.on_message)
            print('[*] Running App')
            self.script.load()

            # sys.stdin.read()
        except Exception as e:
            print(e.args)
        pass
Beispiel #16
0
    def test_get_existing_device(self):
        device = frida.get_device_matching(lambda d: d.id == 'local')
        self.assertEqual(device.name, "Local System")

        device = frida.get_device_manager().get_device_matching(
            lambda d: d.id == 'local')
        self.assertEqual(device.name, "Local System")
Beispiel #17
0
def show_packages():
    global device
    global remote
    try:
        remote = request.args.get('remote')
        if device == None:
            if len(remote) != 0:
                # check remote ip address
                try:
                    socket.inet_aton(remote)
                    print("adding remote device to device manager : ", remote)
                    device=frida.get_device_manager().add_remote_device(remote)
                    print("remote device : ", device)
                except socket.error:
                    return render_template('intro.html')
            else:
                device = frida.get_remote_device()

        # get list of apps
        packages=device.enumerate_processes()
        print(packages)
    except frida.ServerNotRunningError :
        return render_template('error.html',error="cannot connect to remote :(")
    return render_template('packages_list.html',
                           packages=packages)
Beispiel #18
0
def frida_runner(app_name, script_name, verbose, host):
    """
    Attach Frida script to an app running on a device
    """
    try:
        content = open(script_name, 'r').read()

        device_id = DEVICE_ID_PLACEHOLDER
        script_text = SCRIPT_WRAPPER % locals()
        script_text = script_text % 1

        if verbose:
            _print_with_line_no(script_text)

        print('Starting session...')
        if host:
            remote_device = frida.get_device_manager().add_remote_device(host)
            session = remote_device.attach(app_name)
        else:
            session = frida.get_usb_device().attach(app_name)
        script = session.create_script(script_text)

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

        print('Connected')
        sys.stdin.read()

    except Exception as e:
        print(e)
Beispiel #19
0
def attach_lastdevice(processname):
    print("[*] Enumerate devices and attach the app on the last device")

    manager = frida.get_device_manager()
    device = manager.enumerate_devices()[-1]
    session = device.attach(processname)
    waitinterrupt(session)
 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 #21
0
def inject_process(package_name,
                   js_path,
                   is_reboot=False,
                   ip=default_ip,
                   port=default_port,
                   frida_server=default_frida_server_name,
                   is_clear_data=False):
    start_server(frida_server, ip, port)
    # 清除数据
    if is_clear_data: clear_application_data(package_name)
    # 获取设备
    device = frida.get_device_manager().add_remote_device(
        '{host}:{port}'.format(host=ip, port=port))
    # 注入进程
    if is_reboot:
        pid = device.spawn(package_name)
        process = device.attach(pid)
    else:
        process = device.attach(package_name)
    # 创建脚本
    js = open(js_path, 'r', encoding='UTF-8').read()
    script = process.create_script(js)
    # 绑定函数
    script.on('message', on_message)
    # 加载脚本
    script.load()
    if is_reboot:
        device.resume(pid)
    print("common_enabled_debug running....")
    # 执行脚本
    sys.stdin.read()
Beispiel #22
0
def get_usb_iphone(device_id=None):
    Type = 'usb'
    if int(frida.__version__.split('.')[0]) < 12:
        Type = 'tether'
    device_manager = frida.get_device_manager()
    changed = threading.Event()

    def on_changed():
        changed.set()

    device_manager.on('changed', on_changed)

    device = None
    while device is None:
        for dev in device_manager.enumerate_devices():
            if dev.type != Type: continue
            if device_id is not None and dev.id != device_id: continue
            device = dev
            break
        if device is None:
            print('Waiting for USB device...')
            changed.wait()

    device_manager.off('changed', on_changed)

    return device
def cli(package_name, library, output):
    global script
    global device
    global pid

    devices = frida.get_device_manager().enumerate_devices()
    device = get_device(devices)

    pid = device.spawn([package_name])
    process = device.attach(pid)

    js = resource_string("trace_registernatives.build", "_agent.js").decode()
    script = process.create_script(js, runtime="v8")

    script.on("message", process_message)
    script.load()
    device.resume(pid)
    script.post({"type": "library", "name": library})

    input()
    print("Stopped tracing...")

    if output:
        print("Saving output to file...")
        json.dump(registernatives, output)
Beispiel #24
0
def main():
    process = frida.get_device_manager().enumerate_devices()[-1].attach(
        package_name)
    script = process.create_script(hook_log_on_resume())
    script.on('message', get_messages_from_js)
    script.load()
    sys.stdin.read()
Beispiel #25
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 #26
0
    def run(self):
        mgr = frida.get_device_manager()

        on_devices_changed = lambda: self._reactor.schedule(self._try_start)
        mgr.on('changed', on_devices_changed)

        self._reactor.schedule(self._try_start)
        self._reactor.schedule(self._show_message_if_no_device, delay=1)

        old_sigterm_handler = signal.signal(signal.SIGTERM, lambda n, f: self._exit(0))

        self._reactor.run()

        signal.signal(signal.SIGTERM, old_sigterm_handler)

        if self._started:
            self._stop()

        if self._session is not None:
            self._session.off('detached', self._schedule_on_session_detached)
            self._session.detach()
            self._session = None

        if self._device is not None:
            self._device.off('output', self._schedule_on_output)
            self._device.off('lost', self._schedule_on_device_lost)

        mgr.off('changed', on_devices_changed)

        frida.shutdown()
        sys.exit(self._exit_status)
Beispiel #27
0
def get_usb_iphone():
    Type = 'usb'
    if int(frida.__version__.split('.')[0]) < 12:
        Type = 'tether'
    device_manager = frida.get_device_manager()
    changed = threading.Event()

    def on_changed():
        changed.set()

    device_manager.on('changed', on_changed)

    device = None
    while device is None:
        devices = [
            dev for dev in device_manager.enumerate_devices()
            if dev.type == Type
        ]
        if len(devices) == 0:
            print('Waiting for USB device...')
            changed.wait()
        else:
            device = devices[0]

    device_manager.off('changed', on_changed)

    return device
Beispiel #28
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 #29
0
def get_iphone():
    device_manager = frida.get_device_manager()
    device_manager.add_remote_device(Host)
    changed = threading.Event()

    def on_changed():
        changed.set()

    device_manager.on('changed', on_changed)

    device = None
    while device is None:
        devices = device_manager.enumerate_devices()
        if len(devices) < 1:
            print('Waiting for device...')
            changed.wait()
        else:
            print('Choose your device:')
            for i, d in enumerate(devices):
                print('{}) name={} type={}'.format(i, d.name, d.type))
            print('x) Rescan devices')
            choice = input()
            if choice.isdigit():
                device = devices[int(choice)]

    device_manager.off('changed', on_changed)

    return device
Beispiel #30
0
def attach(packageName):
    online_session = None
    online_script = None
    rdev = None
    remoteDriver = run_env.getRemoteDriver()  #ip:port
    try:
        if remoteDriver:
            rdev = frida.get_device_manager().add_remote_device(remoteDriver)
        elif platform.system().find("Windows") != -1:
            warn("推荐使用linux或mac操作系统获得更好的兼容性.")
            rdev = frida.get_remote_device()
        else:
            rdev = frida.get_usb_device(1000)
        online_session = rdev.attach(packageName)
        if online_session == None:
            warn("attaching fail to " + packageName)
        online_script = online_session.create_script(run_env.rpc_jscode)
        online_script.on('message', on_message)
        online_script.load()
        checkRadarDex(packageName, online_script)
        createHookingEnverment(packageName,
                               online_script.exports.mainactivity())
    except Exception:
        warn(traceback.format_exc())
    return online_session, online_script
Beispiel #31
0
def get_usb_iphone():
    device_type = 'usb'
    if int(frida.__version__.split('.')[0]) < 12:
        device_type = 'tether'
    device_manager = frida.get_device_manager()
    changed = threading.Event()

    def on_changed():
        changed.set()

    device_manager.on('changed', on_changed)

    device = None
    while device is None:
        devices = [
            dev for dev in device_manager.enumerate_devices()
            if dev.type == device_type
            and dev.id == '6d824076de766cf571c81a4600dbc2cdd9ad4869'
        ]
        if len(devices) == 0:
            print('Waiting for USB device...')
            changed.wait()
        else:
            device = devices[0]

    device_manager.off('changed', on_changed)

    return device
Beispiel #32
0
    def run(self):
        mgr = frida.get_device_manager()

        on_devices_changed = lambda: self._reactor.schedule(self._try_start)
        mgr.on('changed', on_devices_changed)

        self._reactor.schedule(self._try_start)
        self._reactor.schedule(self._show_message_if_no_device, delay=1)

        signal.signal(signal.SIGTERM, self._on_sigterm)

        self._reactor.run()

        if self._started:
            try:
                self._perform_on_background_thread(self._stop)
            except frida.OperationCancelledError:
                pass

        if self._session is not None:
            self._session.off('detached', self._schedule_on_session_detached)
            try:
                self._perform_on_background_thread(self._session.detach)
            except frida.OperationCancelledError:
                pass
            self._session = None

        if self._device is not None:
            self._device.off('output', self._schedule_on_output)
            self._device.off('lost', self._schedule_on_device_lost)

        mgr.off('changed', on_devices_changed)

        frida.shutdown()
        sys.exit(self._exit_status)
Beispiel #33
0
def attach(packageName, hookerDriverFridaServer, runningTime):
    hasException = False
    online_session = None
    online_script = None
    try:
        rdev = frida.get_device_manager().add_remote_device(
            hookerDriverFridaServer)
        online_session = rdev.attach(packageName)
        if online_session == None:
            warn("attaching fail to " + packageName)
        online_script = online_session.create_script(jscode)
        online_script.on('message', on_message)
        online_script.load()
        for i in range(1, runningTime):
            if i % 2 == 0:
                online_script.exports.log(mobileIP +
                                          " spider has running been " +
                                          str(i) + " seconds.")
            time.sleep(1)
    except Exception:
        hasException = True
        warn(traceback.format_exc())
    finally:
        if online_session != None and hasException == False:
            online_session.detach()
    return online_session, online_script
Beispiel #34
0
def main():
	if args.show_devices:
		for i,device in enumerate(frida.get_device_manager().enumerate_devices()):
			print "Index: {} | {}".format(i,device)
		return

	#Get device
	if args.device is None: #no args supplied, use USB
		device = frida.get_usb_device()
	else: #use device_id if supplied
		device = get_device(args.device)


	printlog("Device Connected: {}".format(device.name), 'ok')

	try:
		pid = device.spawn([package_name]) #spawned process with pid at suspended state
	except (frida.TransportError, frida.NotSupportedError, frida.ExecutableNotFoundError) as e:
		printlog(e.message, 'error')
		return
	except Exception:
		raise
	printlog("Spawned target with PID: {}".format(pid), 'debug')

	process = device.attach(pid) #get a debug session from pid
	printlog("Process attached!", 'ok')
	device.resume(pid) #resume process from suspended state

	#Create dumps directory, if it does not exist
	if not os.path.exists(dump_directory_location):
	    os.makedirs(dump_directory_location)
	    printlog( "Created Dumps Directory: {}".format(dump_directory_location), 'debug')
	else:
		printlog( "Dumps Directory: {}".format(dump_directory_location), 'debug')

	script = process.create_script(instrument_debugger_checks())
	script.on('message',get_messages_from_js)
	printlog("Hook script start!", 'debug')

	script.load()
	try:
		sys.stdin.read()
	except KeyboardInterrupt:
		printlog("\r", 'raw')
		printlog("Abort script acknowledged, cleaning up...".format(pid))
		device.kill(pid)
		printlog("Killed target with PID: {}".format(pid), 'debug')
		printlog("Script Exit.")
		return
	except Exception:
		raise
Beispiel #35
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
    def windowDidLoad(self):
        NSWindowController.windowDidLoad(self)

        device = [device for device in frida.get_device_manager().enumerate_devices() if device.type == 'local'][0]
        self.processList = ProcessList(device)
        self.capture = Capture(device)
        self.processCombo.setUsesDataSource_(True)
        self.processCombo.setDataSource_(self.processList)
        self.capture.setDelegate_(self)

        self.callTableView.setDataSource_(self.capture.calls)
        self.capture.calls.setDelegate_(self)

        self.loadDefaults()

        self.updateAttachForm_(self)
 def run(self):
     mgr = frida.get_device_manager()
     on_devices_changed = lambda: self._reactor.schedule(self._try_start)
     mgr.on('changed', on_devices_changed)
     self._reactor.schedule(self._try_start)
     self._reactor.schedule(self._show_message_if_no_device, delay=0.1)
     self._reactor.run()
     if self._started:
         self._stop()
     if self._process is not None:
         self._process.off('detached', self._schedule_on_process_detached)
         self._process.detach()
         self._process = None
     if self._device is not None:
         self._device.off('lost', self._schedule_on_device_lost)
     mgr.off('changed', on_devices_changed)
     frida.shutdown()
     sys.exit(self._exit_status)
Beispiel #38
0
    def module_pre(self):
        def launch_spawn():
            # Launching the app
            self.printer.info("Spawning the app...")
            pid = device.spawn([self.APP_METADATA['bundle_id']])
            # Attaching to the process
            self.printer.info("Attaching to process: %s" % pid)
            self.session = device.attach(pid)
            if self.options['resume']:
                self.printer.verbose("Resuming the app's process...")
                device.resume(pid)
        def launch_attach():
            # Launching the app
            self.printer.info("Launching the app...")
            self.device.app.open(self.APP_METADATA['bundle_id'])
            pid = int(self.device.app.search_pid(self.APP_METADATA['binary_name']))
            # Attaching to the process
            self.printer.info("Attaching to process: %s" % pid)
            self.session = device.attach(pid)

        # Run FridaModule setup function
        FridaModule.module_pre(self)
        # Get an handle to the device
        import frida
        if self.device.is_usb():
            self.printer.debug("Connected over USB")
            device = frida.get_usb_device()
        else:
            self.printer.debug("Connected over Wi-Fi")
            device = frida.get_device_manager().enumerate_devices()[1]
        # Spawn/attach to the process
        if self.options['spawn']:
            launch_spawn()
        else:
           launch_attach()
        # Prepare results
        self.results = []
        return 1
Beispiel #39
0
 def run(self):
     mgr = frida.get_device_manager()
     on_devices_changed = lambda: self._reactor.schedule(self._try_start)
     mgr.on('changed', on_devices_changed)
     self._reactor.schedule(self._try_start)
     self._reactor.schedule(self._show_message_if_no_device, delay=0.1)
     self._reactor.run()
     if self._started:
         self._stop()
     if self._session is not None:
         self._session.off('detached', self._schedule_on_session_detached)
         self._session.detach()
         self._session = None
     if self._spawned_pid is not None:
         try:
             self._device.kill(self._spawned_pid)
         except:
             pass
     if self._device is not None:
         self._device.off('lost', self._schedule_on_device_lost)
     mgr.off('changed', on_devices_changed)
     frida.shutdown()
     sys.exit(self._exit_status)
Beispiel #40
0
def show_packages():
    global device
    try:
        remote = request.args.get('remote')
        if device == None:
            if len(remote) != 0:
                # check remote ip address
                try:
                    socket.inet_aton(remote)
                    print "adding remote device to device manager : ",remote
                    device=frida.get_device_manager().add_remote_device(remote)
                    print "remote device : ", device
                except socket.error:
                    return render_template('intro.html')
            else:
                device = frida.get_usb_device()

        # get list of apps
        packages=device.enumerate_processes()
        print packages
    except frida.ServerNotRunningError :
        return render_template('error.html',error="cannot connect to remote :(")
    return render_template('packages_list.html',
                           packages=packages)
Beispiel #41
0
 def test_enumerate_devices(self):
     devices = frida.get_device_manager().enumerate_devices()
     self.assertTrue(len(devices) > 0)
Beispiel #42
0
					  offset: 0,
					  length: this.bufLen,
					  header: true,
					  ansi: true
					}));

					console.log("RESULT (1000 BYTES):");
					var buf = Memory.readByteArray(retval, 1000);
					send({name:'result'},buf);
					console.log(hexdump(buf, {
					  offset: 0,
					  length: 1000,
					  header: true,
					  ansi: true
					}));
		}
	});
        """

        return hook_code

deviceManager = frida.get_device_manager()
devices = deviceManager.enumerate_devices()
deviceMobile = devices[args.device]

process = deviceMobile.attach(package_name)
script = process.create_script(instrument_debugger_checks())
script.on('message',get_messages_from_js)
script.load()
sys.stdin.read()
 

def instrument_load_url():

        hook_code = """
        setTimeout(function(){
        Dalvik.perform(function () {

            var TM = Dalvik.use("android.telephony.TelephonyManager");

            TM.getDeviceId.implementation = function () {

                send("Called - deviceID()");

                return "pwn3d";

            };

        });

    },0);
        """

        return hook_code

process = frida.get_device_manager().enumerate_devices()[-1].attach(package_name)
script = process.create_script(instrument_load_url())
script.on('message',get_messages_from_js)
script.load()
sys.stdin.read()
              
Beispiel #44
0
def get_device(device_idx):
	device_manager = frida.get_device_manager()
	devices = device_manager.enumerate_devices()
	return devices[device_idx]
Beispiel #45
0
        Dalvik.perform(function () {

                var SSLPinning = Dalvik.use("com.onlycoin.android.secure.SSLPinning");

                    SSLPinning.a.overload("android.content.Context", "[Ljava.lang.String;", "java.lang.String").implementation = function (c, s, ss) {

                        send("SSLPinning");
                        send(c.toString());
                        send(s.toString());
                        send(ss.toString());
                        this.a.overload("android.content.Context", "[Ljava.lang.String;", "java.lang.String").call(this, c, s, ss);


                    };

                });

    """
    return ssl

if __name__ == "__main__":
    try:
         Popen(["adb forward tcp:27042 tcp:27042"], shell=True).wait()
         process = frida.get_device_manager().enumerate_devices()[-1].attach("com.onlycoin.android")
         script = process.create_script(do_ssl())
         script.on('message', on_message)
         script.load()
         sys.stdin.read()
    except KeyboardInterrupt as e:
        sys.exit(0)
Beispiel #46
0
def find_device(type):
    for device in frida.get_device_manager().enumerate_devices():
        if device.type == type:
            return device
    return None