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 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 install_frida_server(self): server_path = os.path.join(ROOT_DIR, 'assets', self.server_name) server_path_xz = server_path + '.xz' # if not exist frida server then install it if not self.adb.unsafe_shell("ls /data/local/tmp/" + self.server_name)['out']: LOGGER.info('download {} from github ...'.format(self.server_name)) with __lock__: download('https://github.com/frida/frida/releases/download/{}/{}.xz' .format(frida.__version__, self.server_name), server_path_xz) # extract frida server with open(server_path, 'wb') as f: with lzma.open(server_path_xz) as xz: f.write(xz.read()) # upload frida server self.adb.push(server_path, '/data/local/tmp/')
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 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 hook(self, app: str): app = app.strip() if not app: raise RuntimeError('try to hook empty app name') LOGGER.info('hook app ' + app) process = self.device.attach(app) js = 'Java.perform(function() {' # load all scripts under folder 'scripts' for (dirpath, dirnames, filenames) in os.walk(os.path.join(ROOT_DIR, 'scripts')): for filename in filenames: _ = open(os.path.join(dirpath, filename), encoding="utf-8").read() if _.startswith(r'''/*Deprecated*/'''): continue js += _ js += '\n' js += '});' script = process.create_script(js) script.on('message', self.on_message) script.load()
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() try: 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) # set handling interrupt exceptions signal.signal(signal.SIGTERM, shutdown) signal.signal(signal.SIGINT, shutdown) Adb.start_server() watch_thread = WatchThread(args.install, args.port, args.regexps) except (KeyboardInterrupt, InterruptedError) as e: LOGGER.info(e) sys.exit(-1) try: watch_thread.start() while True: time.sleep(1) except MainExit: while True: try: LOGGER.info( 'shutdown command received, wait for clean up please...') watch_thread.cancel() break except MainExit: pass # waiting for sub threads while True: try: while True: should_we_exit() time.sleep(1) except MainExit: try: n = len(thread_manager.thread_map) if n > 0: LOGGER.info( 'running sub threads: {}, wait a second please'.format( n)) except MainExit: pass
def should_we_exit(): if thread_manager.is_empty(): LOGGER.info('sub threads exit completely, bye!') sys.exit(0)