示例#1
0
def main():
    devices = None
    try:
        devices = frida.enumerate_devices()
    except:
        pass
    if devices == None:
        print "frida can't enumerate devices. please check the frida connect."
        return

    autel_device = None
    for device in devices:
        print device
        if device.name.find("Autel") != -1:
            autel_device = frida.get_device(device.id)
            print "\nuse: %s" % autel_device
            break
    if autel_device == None:
        print "frida not found autel device."
        return

    try:
        target = autel_device.spawn("com.Autel.maxi")
        session = autel_device.attach(target)
        script = session.create_script(jscode)
        script.on('message', on_message)
        print('[*] Running Python Script.')
        script.load()
        autel_device.resume(target)
    except BaseException as e:
        print e

    sys.stdin.read()
 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
示例#3
0
    def start(self, args):
        self.dwarf.onScriptDestroyed.connect(self.stop)

        if not args.device:
            self.dwarf.device = self.frida_device
        else:
            self.dwarf.device = frida.get_device(id=args.device)

        if args.any == '':
            self._device_window.onSelectedProcess.connect(self._on_proc_selected)
            self._device_window.onSpawnSelected.connect(self._on_spawn_selected)
            self._device_window.onClosed.connect(self._on_device_dialog_closed)
            self._device_window.show()
        else:
            if args.pid > 0:
                print('* Trying to attach to {0}'.format(args.pid))
                try:
                    self.dwarf.attach(args.pid, args.script, False)
                    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')
                    self.stop()
                    exit(0)
            else:
                print('* Trying to spawn {0}'.format(args.any))
                try:
                    _pid = self.dwarf.spawn(args.any, args=args.args, script=args.script)
                    print('* Dwarf attached to {0}'.format(_pid))
                except Exception as e:  # pylint: disable=broad-except
                    print('-failed-')
                    print('Reason: ' + str(e))
                    self.stop()
                    exit(0)
    def start(self):
        '''
        Attach or spawn to an application with Frida
        :return:
        '''
        logging.debug("Frida:start()")
        # subprocess.Popen(['adb', 'shell', 'ln -s /system/bin/sh /data/local/tmp/MAGICNAME'],stdout=subprocess.DEVNULL)
        # os.system("adb shell ln -s /system/bin/sh /data/local/tmp/MAGICNAME")
        # os.system("adb shell /data/local/tmp/MAGICNAME &")
        # os.system("python3 /home/defaria/android_emuroot/android_emuroot.py -t 180 -VVVVV -d %s adbd"%self.device.device_id)
        # subprocess.Popen(['python3', '/home/defaria/android_emuroot/android_emuroot.py', '-t 180', '-VVVVV', '-d %s'%self.device.device_id, 'single', '--magic-name MAGICNAME'],stdout=subprocess.DEVNULL)
        # os.system("adb shell /data/local/tmp/frida-server &")
        # subprocess.Popen(['adb', 'shell', '/data/local/tmp/frida-server &'],stdout=subprocess.DEVNULL)

        device = frida.get_device(self.device.device_id)
        spawn = self.configuration.getboolean('spawn_app')

        if (spawn):
            pid = device.spawn([self.module.application.package])
            session = device.attach(pid)
        else:
            pid = device.get_process(self.module.application.package).pid
            session = device.attach(pid)

        self.script = session.create_script(
            open(f"{dirname}frida_scripts/_agent.js").read())
        self.script.on('message', self.on_message)
        self.script.load()

        if (spawn):
            device.resume(pid)
示例#5
0
    def _select_device(self):
        """Figure out which device we want to use."""

        if self.id:
            self.device = frida.get_device(self.id)
            return

        if self.type == "usb":
            usbs = [x for x in frida.enumerate_devices() if x.type == 'usb']
            if usbs == []:
                error = "Cannot find USB device."
                logger.error(error)
                raise Exception(error)

            if len(usbs) > 1:
                logger.warn(
                    "Found more than 1 usb device. Selecting first one...")

            self.device = usbs[0]
            self.id = self.device.id
            return

        error = "Couldn't find the device you requested..."
        logger.error(error)
        raise Exception(error)
示例#6
0
async def main():
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument('device')
    parser.add_argument('port')
    parser.add_argument('local', nargs='?', default=0, type=int)
    opt = parser.parse_args()

    if opt.device == 'usb':
        dev = frida.get_usb_device()
    else:
        dev = frida.get_device(opt.device)

    if opt.port == 'ssh':
        for port in (22, 44):
            try:
                dev.open_channel('tcp:22').close()
                break
            except frida.ServerNotRunningError:
                continue
        else:
            raise RuntimeError('failed to connect remote SSH')
    else:
        port = int(opt.port)

    handler = make_handler(dev, port)
    server = await asyncio.start_server(handler, '127.0.0.1', port=opt.local)
    _, port = server.sockets[0].getsockname()
    print(port)

    async with server:
        await server.serve_forever()
示例#7
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!')
示例#8
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.onSpwanSelected.connect(self.on_spawn_selected)
         self._device_window.onClosed.connect(self._on_devdlg_closed)
         self._device_window.show()
     else:
         if not args.device:
             self.dwarf.device = frida.get_usb_device()
         else:
             self.adb.device = args.device
             self.dwarf.device = frida.get_device(id=args.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)
示例#9
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}')
 def start_capture(self, device, package, script_path, output_file,
                   adb_cmd):
     self._ensure_frida_server(adb_cmd, device)
     scr_list = []
     for root, _dirs, files in os.walk(script_path):
         for fn in files:
             if fn.endswith('.js'):
                 print('frida-helper: Found script file',
                       os.path.join(root, fn))
                 with open(os.path.join(root, fn), 'r') as f:
                     scr_list.append(f.read())
     scr = '\n'.join(scr_list)
     print('frida-helper: Starting capture...')
     sys.stdout.flush()
     self.dev = frida.get_device(device)
     self.app = self.dev.spawn([package])
     self.session = self.dev.attach(self.app)
     self.session.on('detached', self._on_session_detach)
     self.script = self.session.create_script(scr)
     self.output = open(output_file, 'a')
     self.output.write('#NEW SESSION#\n')
     self.script.on('message', self._on_message)
     self.script.load()
     self.dev.resume(self.app)
     print('frida-helper: Capture started')
     print('#STARTUP OK#')
     # Ensure on-time message delivery
     sys.stdout.flush()
示例#11
0
    def start(self):
        '''
        Attach or spawn to an application with Frida
        :return:
        '''
        logging.debug("Frida:start()")

        device = frida.get_device(self.device.device_id)

        spawn = self.configuration.getboolean('spawn_app')

        if (spawn):
            pid = device.spawn([self.module.application.package])
            session = device.attach(pid)
        else:
            pid = device.get_process(self.module.application.package).pid
            session = device.attach(pid)

        self.script = session.create_script(
            open(f"{dirname}frida_scripts/_agent.js").read())
        self.script.on('message', self.on_message)
        self.script.load()

        if (spawn):
            device.resume(pid)
示例#12
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
示例#13
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)
 def connect(self):
     """Connect to Frida Server."""
     session = None
     try:
         env = Environment()
         self.clean_up()
         env.run_frida_server()
         device = frida.get_device(get_device(), settings.FRIDA_TIMEOUT)
         pid = device.spawn([self.package])
         device.resume(pid)
         logger.info('Spawning %s', self.package)
         time.sleep(2)
         session = device.attach(pid)
     except frida.ServerNotRunningError:
         logger.warning('Frida server is not running')
         self.connect()
     except frida.TimedOutError:
         logger.error('Timed out while waiting for device to appear')
     except (frida.ProcessNotFoundError,
             frida.TransportError,
             frida.InvalidOperationError):
         pass
     except Exception:
         logger.exception('Error Connecting to Frida')
     try:
         if session:
             script = session.create_script(self.get_script())
             script.on('message', self.frida_response)
             script.load()
             sys.stdin.read()
             script.unload()
             session.detach()
     except Exception:
         logger.exception('Error Connecting to Frida')
示例#15
0
 def _update_device(self, device_id):
     try:
         self.device = frida.get_device(device_id)
         self.proc_list.device = self.device
         self.spawn_list.device = self.device
     except frida.TimedOutError:
         self.device = None
def load_script_with_device(device, pkg_name, js_file):
    js_code = get_js_hook(js_file)
    device = frida.get_device(device.get_serial_no())
    session = device.attach(pkg_name)
    script = session.create_script(js_code)
    script.on("message", message_callback)
    script.load()
    return script
示例#17
0
文件: soFrida.py 项目: syh4ck/soFrida
 def frida_connect(self):
     try:
         self.device = frida.get_device(self.serial)
         return self.device
     except Exception as e:
         self.device = ""
         self.err = str(e)
         return self.device
示例#18
0
def disable_secure_flag(device, pkg_name, activity_name):
    js_code = get_js_hook("disable_secure_flag.js")
    device = frida.get_device(device.get_serial_no())
    session = device.attach(pkg_name)
    script = session.create_script(js_code)
    script.on("message", message_callback)
    script.load()
    script.exports.disablesecureflag(activity_name)
def frida_connect(device_identifier):
    """Connect to VM/Device"""
    try:
        device = frida.get_device(device_identifier)
        return device
    except:
        PrintException("[ERROR] Cannot Connect to Device/VM")
    return None
示例#20
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)
示例#21
0
def list_processes(search):
    eprint("⚡️ Listing processes...")
    for device in get_devices():
        eprint("📲 Device: {} ({})".format(get_device_model(device), device.get_serial_no()))
        frida_device = frida.get_device(device.get_serial_no())
        for app in frida_device.enumerate_applications():
            if search.lower() in app.identifier.lower() or search.lower() in app.name.lower():
                print("🌕 {} ({}) [{}]".format(app.name, app.identifier, app.pid))
示例#22
0
文件: ui_welcome.py 项目: ashr/Dwarf
 def on_refresh_spawns(self):
     self.on_clear_spawnlist()
     item_id = self.devices_list.itemData(self.devices_list.currentIndex())
     try:
         device = frida.get_device(item_id)
         self.update_spawn_list(device)
     except Exception:
         return
示例#23
0
文件: ui_welcome.py 项目: ashr/Dwarf
 def device_picked(self, index):
     item_id = self.devices_list.itemData(index)
     try:
         device = frida.get_device(item_id)
     except Exception:
         return
     self.app.get_dwarf().device_picked(device)
     self.update_spawn_list(device)
     self.update_proc_list(device)
示例#24
0
def attach_remote(processname):
    print("[*] Attach to process on remote machine on IP {}".format(IP_ADDR))

    # If not defined
    manager = frida.get_device_manager()
    device  = manager.add_remote_device(IP_ADDR)
    # If has been defined
    device  = frida.get_device("tcp@{}".format(IP_ADDR))

    session = device.attach(processname)
    waitinterrupt()
示例#25
0
 def __init__(self, device_id: str = None):
     """
     :param device_id: 设备号
     """
     server = resource.get_config("frida_server")
     self.device = device(device_id=device_id)
     self.frida_device = frida.get_device(self.device.id)
     self.server_name = server["name"].format(version=frida.__version__, abi=self.device.abi)
     self.server_url = server["url"].format(version=frida.__version__, abi=self.device.abi)
     self.server_file = resource.download_path(self.server_name)
     self.server_target_file = "/data/local/tmp/%s/%s" % (__name__, self.server_name)
示例#26
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()
示例#27
0
    def _on_device_changed(self, index):
        device = None
        device_id = self._devices_combobox.itemData(index)
        if device_id:
            try:
                device = frida.get_device(device_id)
            except:
                return

            if device:
                self._device_id = device.id
                self._check_device(device)
示例#28
0
def spawn_remote(appname):
    print("[*] Spawn process on remote machine (with frida server) on IP {}".format(IP_ADDR))

    # If not defined
    manager = frida.get_device_manager()
    device  = manager.add_remote_device(IP_ADDR)
    # If has been defined
    device  = frida.get_device("tcp@{}".format(IP_ADDR))
    pid     = device.spawn([appname])
    session = device.attach(pid)
    device.resume(pid)
    waitinterrupt()
示例#29
0
文件: frida.py 项目: cisco-sas/katnip
 def setup(self):
     super(FridaLaunchServerController, self).setup()
     if not self._is_victim_alive():
         self._frida_device = frida.get_device(self._frida_device_path)
         self._frida_pid = self._frida_device.spawn(self._frida_argv)
         self._frida_session = self._frida_device.attach(self._frida_pid)
         self._frida_session.on("detached", self._frida_session_on_detached)
         if self._frida_js_script is not None:
             self._frida_script = self._frida_session.create_script(self._frida_js_script)
             self._frida_script.on("message", self._frida_script_on_message)
             self._frida_script.load()
         self._frida_device.resume(self._frida_pid)
示例#30
0
def hook_start(serial_id):
    device = frida.get_device(serial_id, timeout=10)
    time.sleep(1)
    pid = device.spawn(["com.dianping.v1"])
    time.sleep(1)
    device.resume(pid)
    time.sleep(1)  # wait for app up.
    session = device.attach(pid)
    script = session.create_script(HOOKSCRIPT)
    script.on("message", _my_message_handler)
    script.load()
    return script
示例#31
0
async def main(opt):
    if opt.device == 'usb':
        dev = frida.get_usb_device()
    else:
        dev = frida.get_device(opt.device)

    if opt.port == 'ssh':
        for port in (22, 44):
            try:
                dev.open_channel('tcp:22').close()
                break
            except frida.ServerNotRunningError:
                continue
        else:
            raise RuntimeError('failed to connect remote SSH')
    else:
        port = int(opt.port)

    import shutil
    import subprocess
    import os

    cli = shutil.which('iproxy')
    if cli:
        output = subprocess.check_output([cli, '--help'])
        local_port = opt.local or find_free_port()
        args = [cli]
        if b'LOCAL_PORT:DEVICE_PORT' in output:  # new
            args += [f'{local_port}:{port}']
            if opt.device != 'usb':
                args += ['-u', opt.device]
        else:
            args += [str(local_port), str(port)]
            if opt.device != 'usb':
                args += [opt.device]

        if sys.platform == 'win32':
            subprocess.call(args)
            return
        else:
            os.execv(cli, args)

    # fallback to python (bad performace)
    handler = make_handler(dev, port)
    server = await asyncio.start_server(handler,
                                        '127.0.0.1',
                                        port=opt.local,
                                        start_serving=False)
    print('waiting for connection', file=sys.stderr, flush=True)
    # _, local_port = server.sockets[0].getsockname()
    # print(local_port, flush=True)
    async with server:
        await server.serve_forever()
示例#32
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