def main(): parser = argparse.ArgumentParser(description='A tool that hook all apps you need') parser.add_argument('regexps', type=str, nargs='*', help=r'Regexps for the apps you want to hook such as "^com\.baidu\.", ' r'empty for hooking all apps') parser.add_argument('-i', '--install', action='store_true', help='install frida server to /data/local/tmp automatically') parser.add_argument('-p', '--port', type=int, help='reverse tcp port, if specified, manipulate iptables automatically') parser.add_argument('-v', action='store_true', help='verbose output') args = parser.parse_args() if args.v: LOGGER.setLevel(logging.DEBUG) # set log os.makedirs(LOG_DIR, mode=0o700, exist_ok=True) log_filename = time.strftime('%Y-%m-%d_%H-%M-%S.log') log_file = open(os.path.join(LOG_DIR, log_filename), 'a', encoding='utf-8') logger_handler = ColorizingStreamHandler(log_file) logger_handler.setFormatter(FORMATTER) LOGGER.addHandler(logger_handler) Adb.start_server() try: t = WatchThread(args.install, args.port, args.regexps, True) t.start() t.join() except KeyboardInterrupt: LOGGER.info('shutdown, thank you for using frida skeleton') except Exception as e: LOGGER.error(e)
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)
def hook_apps(self): apps = set() # monitor apps while True: time.sleep(0.1) new_apps = set(p.name for p in self.device.enumerate_processes()) if not new_apps: continue incremental_apps = new_apps - apps decremental_apps = apps - new_apps for incremental_app in incremental_apps: for regexp in self.regexps: if re.search(regexp, incremental_app): # waiting for app startup completely time.sleep(0.1) try: self.hook(incremental_app) except Exception as e: LOGGER.error(e) finally: break for decremental_app in decremental_apps: for regexp in self.regexps: if re.search(regexp, decremental_app): LOGGER.info('app {} has died'.format(decremental_app)) break apps = new_apps
def run(self) -> None: LOGGER.info("{} start with hook device: id={}, name={}, type={}".format( self.__class__.__name__, self.device.id, self.device.name, self.device.type)) try: self.prepare() self.hook_apps() except Exception as e: LOGGER.error(e)
def download(self, url, file_path): # get total size of file r1 = requests.get(url, stream=True, verify=False) total_size = int(r1.headers['Content-Length']) # check downloaded size if os.path.exists(file_path): temp_size = os.path.getsize(file_path) else: temp_size = 0 if temp_size == total_size: LOGGER.info('{} has downloaded completely'.format(file_path)) return if temp_size > total_size: LOGGER.error( '{} has corrupted, download it again'.format(file_path)) os.remove(file_path) return self.download(url, file_path) LOGGER.debug('{} of {} needs to be download'.format( total_size - temp_size, total_size)) # download from temp size to end headers = {'Range': 'bytes={}-'.format(temp_size)} r = requests.get(url, stream=True, verify=False, headers=headers) with open(file_path, "ab") as f: for chunk in r.iter_content(chunk_size=1024): if self.stop_flag: break if chunk: temp_size += len(chunk) f.write(chunk) f.flush() # download progress done = int(50 * temp_size / total_size) sys.stdout.write("\r[{}{}] {}%".format( '█' * done, ' ' * (50 - done), 100 * temp_size / total_size)) sys.stdout.flush() sys.stdout.write(os.linesep)
def cmd_and_debug(cls, cmd) -> map: ret = {'out': '', 'err': ''} LOGGER.debug(cmd) p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE, close_fds=True) err = p.stderr.read().decode().strip() if err: LOGGER.error('shell error: ' + err) ret['err'] = err out = p.stdout.read().decode().strip() if out: LOGGER.debug('shell output: ' + out) ret['out'] = out return ret
def on_message(self, message, data): try: if message['type'] == 'error': text = message['description'].strip() if not text: return LOGGER.error(text) else: text = message['payload'].strip() if message['type'] == 'send' else message.strip() if not text: return LOGGER.info(text) except Exception as e: LOGGER.error(e)
def cmd_and_debug(cls, cmd: str, debug=True) -> map: ret = {'out': '', 'err': ''} if debug: LOGGER.debug(cmd) p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE, close_fds=True) err = p.stderr.read().decode().strip() if err: if err != 'Unable to start: Error binding to address: Address already in use': LOGGER.error('shell error: ' + err) ret['err'] = err out = p.stdout.read().decode().strip() if out: if debug: LOGGER.debug('shell output: ' + out) ret['out'] = out return ret
def run(self) -> None: LOGGER.info( "{} start with hook device: id={}, name={}, type={}".format( self.__class__.__name__, self.device.id, self.device.name, self.device.type)) try: self.prepare() self.hook_apps() except Exception as e: LOGGER.error('device {}: {}'.format(self.device.id, e)) try: self.shutdown() except Exception as e: LOGGER.error( 'unexpected error occurred when shutdown device {}: {}'.format( self.device.id, e)) LOGGER.debug('device {} exit'.format(self.device.id)) thread_manager.del_thread(self)
def run(self) -> None: LOGGER.debug('{} start'.format(self.__class__.__name__)) while True: if self.stop_flag: 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.cmd_and_debug( 'adb devices', debug=False)['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, self.install, self.port, self.regexps) except RuntimeError as e: LOGGER.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() LOGGER.debug('watch thread exit')