示例#1
0
    def run(self) -> None:
        self.log.debug('{} start'.format(self.__class__.__name__))

        while True:
            if self._terminate:
                break

            devices = frida.enumerate_devices()

            # usb devices from frida api
            usb_devices = [
                device for device in devices if device.type == 'usb'
            ]
            usb_devices_ids = [device.id for device in usb_devices]

            # devices strings from "adb devices"
            adb_devices_strings = Shell().exec('adb devices',
                                               quiet=True).out.split('\n')[1:]
            adb_devices_strings = [
                _.split('\t')[0] for _ in adb_devices_strings
            ]

            # we need to access these devices remotely
            remote_devices_strings = set(adb_devices_strings) - set(
                usb_devices_ids)
            remote_devices = []

            for _ in remote_devices_strings:
                new_device = FakeDevice()
                new_device.id = _
                remote_devices.append(new_device)

            for device in usb_devices + remote_devices:
                duplicated = False

                for t in self.frida_threads:
                    if t.device.id == device.id:
                        if not t.is_alive():
                            self.frida_threads.remove(t)
                            break

                        duplicated = True
                        break

                if duplicated:
                    continue

                try:
                    frida_thread = FridaThread(device)
                except RuntimeError as e:
                    self.log.error(
                        'error occurred when init frida thread: {}'.format(e))
                else:
                    frida_thread.start()
                    self.frida_threads.append(frida_thread)

            time.sleep(0.1)

        self.shutdown()
        self.log.debug('watch thread exit')
示例#2
0
def main():
    # Get device (see also attach.py)
    # device = frida.get_remote_device()
    device = frida.enumerate_devices()[0]    # get the first device

    # Get list of processes (all without filter)
    processes = enum_process(device)
示例#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}')
def enmuDevices():
    devices = frida.enumerate_devices()

    for device in sorted(devices, key=cmp_to_key(compare_devices)):
        if device.id != 'local' and device.id != 'tcp':

            return device.id
示例#5
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()
示例#6
0
 def _start(self):
     try:
         devices = frida.enumerate_devices()
     except Exception as e:
         self._update_status("Failed to enumerate devices: %s" % e)
         self._exit(1)
         return
     id_column_width = max(map(lambda device: len(device.id), devices))
     type_column_width = max(
         map(lambda device: len(device.type), devices))
     name_column_width = max(
         map(lambda device: len(device.name), devices))
     header_format = "%-" + str(id_column_width) + "s  " + \
         "%-" + str(type_column_width) + "s  " + \
         "%-" + str(name_column_width) + "s"
     self._print(header_format % ("Id", "Type", "Name"))
     self._print("%s  %s  %s" %
                 (id_column_width * "-", type_column_width * "-",
                  name_column_width * "-"))
     line_format = "%-" + str(id_column_width) + "s  " + \
         "%-" + str(type_column_width) + "s  " + \
         "%-" + str(name_column_width) + "s"
     for device in sorted(devices, key=cmp_to_key(compare_devices)):
         self._print(line_format %
                     (device.id, device.type, device.name))
     self._exit(0)
示例#7
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
示例#8
0
def dump(app_name_or_id, device_id, verbose):
    if device_id is None:
        dev = frida.get_usb_device()
    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 != 'tether':
        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('')

    task = IPADump(dev, app, verbose=verbose)
    task.run()
示例#9
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)
示例#10
0
    def run(self) -> None:
        LOGGER.debug('{} start'.format(self.__class__.__name__))

        threads = []

        while True:
            devices = frida.enumerate_devices()

            for device in devices:
                if device.type != 'usb':
                    continue

                duplicated = False

                for t in threads:
                    if t.device.id == device.id:
                        if not t.is_alive():
                            threads.remove(t)
                            break

                        duplicated = True
                        break

                if duplicated:
                    continue
                try:
                    new_thread = FridaThread(device, self.install, self.port,
                                             self.regexps, True)
                    new_thread.start()
                    threads.append(new_thread)
                except Exception as e:
                    LOGGER.error(e)

            time.sleep(0.1)
示例#11
0
def SettingsGUI(bv,action=None,extra_settings=None):
    ## Frida devices enumeration
    devices     = frida.enumerate_devices()
    f_dev       = bn.ChoiceField('Device\t', [a.id for a in devices])
    ## TODO:: TCP GUI
    f_appName   = bn.TextLineField('Application\t')
    cmdLine     = bn.TextLineField('Command line\t')
    spawn       = bn.ChoiceField('Execution mode\t',['Spawn a new process', 'Attacch to PID'])
    pid         = []
    for i in psutil.process_iter(attrs=['pid','name']):
        pid.append(i.info['name']+' ('+str(i.info['pid'])+')')
    f_pid       = bn.ChoiceField('PID\t',pid)
    form        = [bn.LabelField('Frida general settings'), bn.SeparatorField(),f_dev,f_appName,cmdLine,spawn,f_pid]
    if extra_settings != None:
        form += [bn.SeparatorField(),bn.LabelField(action)] + extra_settings
    ret         = bn.interaction.get_form_input(form, 'BinRida')
    ## Global settings
    settings = {}
    if ret:
        settings['dev']  = devices[f_dev.result]
        settings['name'] = f_appName.result
        settings['pid']  = int(pid[f_pid.result].split('(')[1][:-1])
        #  0 for spawn, 1 else
        settings['spawn']= spawn.result
        settings['cmd']  = cmdLine.result
    return ret,settings
示例#12
0
    def run(self):
        # get frida devices
        devices = frida.enumerate_devices()

        for device in devices:
            self.onAddDevice.emit(device.name, device.type)

        self.onDevicesUpdated.emit()
示例#13
0
    def run(self):
        # get frida devices
        devices = frida.enumerate_devices()

        for device in devices:
            self.onAddDevice.emit({'id': device.id, 'name': device.name, 'type': device.type})

        self.onDevicesUpdated.emit()
示例#14
0
def devices() -> list:
    props = ['id', 'name', 'type']

    def wrap(dev):
        obj = {prop: getattr(dev, prop) for prop in props}
        obj['icon'] = png.to_uri(dev.icon)
        return obj

    return [wrap(dev) for dev in frida.enumerate_devices()]
示例#15
0
 def update_device_ui(self):
     devices = frida.enumerate_devices()
     for device in devices:
         if device.type == 'usb':
             self.update_spawn_list(device)
             self.update_proc_list(device)
             return
     self.spawn_list.clear()
     self.proc_list.clear()
示例#16
0
 def __init__(self, event):
     self.devices = frida.enumerate_devices()
     self.event_queue = event
     self.app_name = ""
     self.respawn = True
     self.plugins = []
     self.scripts = []
     self.isRunning = False
     self.callback = self.recv_data
示例#17
0
def test_devices():
    devices = frida.enumerate_devices()
    assert devices
    connected = False
    for device in devices:
        if device.type == 'usb':
            connected = True
            TestLogger.info("Detected device: %s" % device.name)
    if not connected:
        TestLogger.warning("Unable to detect device")
示例#18
0
 def get_device_list(self):
     try:
         self.devices = frida.enumerate_devices()
         device_list = []
         for device in self.devices[2:]:
             device_list.append({"serial":device.id, "name":device.name, "type":device.type})
         return device_list
     except Exception as e:
         self.err = str(e)
         return None
def get_vm(dev_id, dev_type):
    """find android vm"""
    try:
        devices = frida.enumerate_devices()
        for device in devices:
            if (dev_id == device.id and dev_type == device.type):
                return device.id
        print "[WARNING] Frida Cannot Find Android Device/VM"
    except:
        PrintException("[ERROR] Frida Cannot Enumerate Device/VM")
    return None
示例#20
0
文件: dumper.py 项目: thor509/medusa
def dump_pkg(pkg):
    try:
        print('Availlable devices:')
        devices = frida.enumerate_devices()
        i = 0

        for dv in devices:
            print('{}) {}'.format(i, dv))
            i += 1
        j = input('Enter the index of device to use:')
        device = devices[int(j)]
    except:
        device = frida.get_remote_device()

    bring_to_front = input(
        'Bring the application you want to dump to the front and press enter.....\n'
    )

    target = device.get_frontmost_application()

    pkg_name = pkg  #target.identifier
    print('---------' + pkg)
    processes = get_all_process(device, pkg_name)
    if len(processes) == 1:
        target = processes[0]
    else:
        s_processes = ""
        for index in range(len(processes)):
            s_processes += "\t[{}] {}\n".format(index, str(processes[index]))
        input_id = int(
            input(
                "[{}] has multiprocess: \n{}\nplease choose target process: ".
                format(pkg_name, s_processes)))
        target = processes[input_id]
        try:
            for index in range(len(processes)):
                if index == input_id:
                    os.system("adb shell \"su -c 'kill -18 {}'\"".format(
                        processes[index].pid))
                else:
                    os.system("adb shell \"su -c 'kill -19 {}'\"".format(
                        processes[index].pid))
        except:
            pass

    logging.info("[DEXDump]: found target [{}] {}".format(
        target.pid, pkg_name))
    session = device.attach(target.pid)
    path = '.'  #os.path.dirname(save_path)
    #path = path if path else "."
    script = session.create_script(open(path + "/dexdump.js").read())
    script.load()

    dump(pkg_name, script.exports)
示例#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)
示例#22
0
 def update_device_ui(self):
     devices = frida.enumerate_devices()
     self.devices_list.clear()
     should_clear = True
     for device in devices:
         self.devices_list.addItem('%s (%s)' % (device.name, device.type))
         self.devices_list.setItemData(self.devices_list.count() - 1, device.id)
         if device.type == 'usb' and should_clear:
             # set the first usb device found
             should_clear = False
             self.devices_list.setCurrentIndex(self.devices_list.count() - 1)
     if should_clear:
         self.spawn_list.clear()
         self.proc_list.clear()
示例#23
0
文件: ui_welcome.py 项目: ashr/Dwarf
    def run(self):
        # clear lists
        self.clear_devices.emit()
        self.clear_procs.emit()
        self.clear_spawns.emit()

        # get frida devices
        devices = frida.enumerate_devices()

        for device in devices:
            device_string = ('Device: {0} - ({1})'.format(device.name, device.type))
            self.add_device.emit(device_string, device.id, device.type == 'usb')

        self.devices_updated.emit()
示例#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)
示例#25
0
def devices() -> list:
    props = ['id', 'name', 'type']

    def wrap(dev):
        obj = {prop: getattr(dev, prop) for prop in props}
        obj['icon'] = png.to_uri(dev.icon)
        return obj

    # workaround
    try:
        frida.get_usb_device(1)
    except:
        pass

    return [wrap(dev) for dev in frida.enumerate_devices()]
示例#26
0
文件: lsd.py 项目: 0xItx/frida-python
 def _start(self):
     try:
         devices = frida.enumerate_devices()
     except Exception as e:
         self._update_status("Failed to enumerate devices: %s" % e)
         self._exit(1)
         return
     id_column_width = max(map(lambda device: len(device.id), devices))
     type_column_width = max(map(lambda device: len(device.type), devices))
     name_column_width = max(map(lambda device: len(device.name), devices))
     header_format = "%-" + str(id_column_width) + "s  " + \
         "%-" + str(type_column_width) + "s  " + \
         "%-" + str(name_column_width) + "s"
     self._print(header_format % ("Id", "Type", "Name"))
     self._print("%s  %s  %s" % (id_column_width * "-", type_column_width * "-", name_column_width * "-"))
     line_format = "%-" + str(id_column_width) + "s  " + \
         "%-" + str(type_column_width) + "s  " + \
         "%-" + str(name_column_width) + "s"
     for device in sorted(devices, key=cmp_to_key(compare_devices)):
         self._print(line_format % (device.id, device.type, device.name))
     self._exit(0)
    def run(self, bv, function=None):
        frida_devices = frida.enumerate_devices()
        try:
            last_device = bv.query_metadata("frida_plugin_device_id")
        except KeyError:
            last_device = self.settings.get_string("frida.device_id")

        devices = []
        device_reorder = []
        for device in frida_devices:
            if device.id == last_device:
                devices.insert(0, device.name)
                device_reorder.insert(0, device)
            else:
                devices.append(device.name)
                device_reorder.append(device)
        choice_f = ChoiceField("Devices", devices)
        get_form_input([choice_f], "Get Frida Device")
        if choice_f.result != None:
            self.settings.set_string("frida.device_id",
                                     device_reorder[choice_f.result].id)
            bv.store_metadata("frida_plugin_device_id",
                              str(device_reorder[choice_f.result].id))
            self.frida_device = device_reorder[choice_f.result]
示例#28
0
def find_device(type):
    for device in frida.enumerate_devices():
        if device.type == type:
            return device
    return None
示例#29
0
    "-m",
    action="append",
    dest="mod_names",
    default=[],
    help=
    "Specify zero or more modules that need to be loaded in the target process."
)

# Parse command line arguments.
args = parser.parse_args()

# Show available devices.
if args.device == "list":
    print "Available devices:"
    print "  %-10s %s" % ("ID", "Name")
    for device in frida.enumerate_devices():
        print "  %-10s %s" % (device.id, device.name)

    sys.exit()

# Lookup the desired device.
if args.device:
    devs = [dev.id for dev in frida.enumerate_devices()]
    if args.device not in devs:
        logging.error("Invalid device id `%s`." % args.device)
        sys.exit(-1)

    # Get the device.
    device = frida.get_device(args.device)

    print "Using device %r." % device
示例#30
0
def find_device(type):
    for device in frida.enumerate_devices():
        if device.type == type:
            return device
    return None
示例#31
0
文件: script.py 项目: neskk/droidsf
        log.info("Analysed %s with DroidStat-X.", app_package)

    if args.no_dynamic_analysis:
        log.info("Skipped Frida dynamic analysis.")
        sys.exit(0)

    adb = droidsf.adb.ADB(args)

    adb.select_device()
    adb.launch_adb_server()
    adb.install_apk(app_package)
    adb.launch_frida_server()

    try:
        found = False
        for device in frida.enumerate_devices():
            if device.id == adb.device_id:
                found = True
                log.debug("Frida found device: %s", device)
                break

        if not found:
            log.error("Frida could not find device: %s", adb.device_id)

        device = frida.get_device(id=adb.device_id)
        # device = frida.get_usb_device(timeout=5)

        found = False
        for app in device.enumerate_applications():
            if app.identifier == app_package:
                found = True
        utils.getCalc.implementation = function(a, b){
            a = 12345;
            b = 54321;
            var retval = this.getCalc(a, b);
            console.log(a, b, retval);
            return retval;
        }
	});
});

"""


def message(message, data):
    if message["type"] == 'send':
        print("[*] {0}".format(message['payload']))
    else:
        print(message)


# rdev = frida.get_device_manager().enumerate_devices()
rdev = frida.enumerate_devices()  # 和上面的方式的原理是一样的 返回一个列表
print(rdev)
rdev = rdev[int(sys.argv[1])]  # 获取命令行参数
# rdev = rdev[3]
process = rdev.attach('com.xiaojianbang.app')  # 也可以传入唯一的进程pid
script = process.create_script(jscode)
script.on('message', message)
script.load()
sys.stdin.read()
示例#33
0
# py 2.x
# reload(module)

# py 3.3
#imp.reload(module)






# frida
import frida

devices = frida.enumerate_devices()






# github
import github3

user = '******'
repo = 'test'

gh_client = github3.login(token=os.environ['GITHUB_TOKEN'])
repo = gh_client.repository(owner='chillara nand', repository='test')