def load_androguard(file_path, force_reload=False, write_session=True, session_file=None, s=None): """ Should handle saving and loading sessions automatically. Writing and Loading sessions currently cause a Kernel Disconnect or an EOF Error (Pickle serialization issues) """ if (not force_reload) and path.exists(session_file): print("Loading Existing Session") s = Load(session_file) a = d = dx = None else: print("Loading Session from Apk at", file_path) if s is None: s = Session() a, d, dx = AnalyzeAPK(file_path, s) if write_session: print("Saving Loaded Session to", session_file) s.add(file_path, dx=dx) Save(s, session_file) return a, d, dx
def androlyze_main(session, filename): """ Start an interactive shell :param session: Session file to load :param filename: File to analyze, can be APK or DEX (or ODEX) """ from androguard.core.androconf import ANDROGUARD_VERSION, CONF from IPython.terminal.embed import InteractiveShellEmbed from traitlets.config import Config from androguard.session import Session, Load from colorama import Fore import colorama import atexit # Import commonly used classes, for further usage... from androguard.core.bytecodes.apk import APK from androguard.core.bytecodes.dvm import DalvikVMFormat from androguard.core.analysis.analysis import Analysis from androguard.misc import AnalyzeAPK colorama.init() if session: print("Restoring session '{}'...".format(session)) s = CONF['SESSION'] = Load(session) print("Successfully restored {}".format(s)) # TODO Restore a, d, dx etc... else: s = CONF["SESSION"] = Session(export_ipython=True) if filename: ("Loading apk {}...".format(os.path.basename(filename))) print("Please be patient, this might take a while.") filetype = androconf.is_android(filename) print("Found the provided file is of type '{}'".format(filetype)) if filetype not in ['DEX', 'DEY', 'APK']: print(Fore.RED + "This file type is not supported by androlyze for auto loading right now!" + Fore.RESET, file=sys.stderr) print("But your file is still available:") print(">>> filename") print(repr(filename)) print() else: with open(filename, "rb") as fp: raw = fp.read() h = s.add(apk, raw) print("Added file to session: SHA256::{}".format(h)) if filetype == 'APK': print("Loaded APK file...") a, d, dx = s.get_objects_apk(digest=h) print(">>> a") print(a) print(">>> d") print(d) print(">>> dx") print(dx) print() elif filetype in ['DEX', 'DEY']: print("Loaded DEX file...") for h_, d, dx in s.get_objects_dex(): if h == h_: break print(">>> d") print(d) print(">>> dx") print(dx) print() def shutdown_hook(): """Save the session on exit, if wanted""" if not s.isOpen(): return try: res = input("Do you want to save the session? (y/[n])?").lower() except (EOFError, KeyboardInterrupt): pass else: if res == "y": # TODO: if we already started from a session, probably we want to save it under the same name... # TODO: be able to take any filename you want fname = s.save() print("Saved Session to file: '{}'".format(fname)) cfg = Config() _version_string = "Androguard version {}".format(ANDROGUARD_VERSION) ipshell = InteractiveShellEmbed(config=cfg, banner1="{} started" .format(_version_string)) atexit.register(shutdown_hook) ipshell()
def get_class_source(class_name, md5): """get source code from of an apk's class 'class_name' whose md5 == 'md5' """ app.logger.info('resolving src for {}'.format(class_name)) md5_analysis_dir = os.path.join(analysis_dir, md5) apk = os.path.join(md5_analysis_dir, md5 + '.apk') # #a, d, dx = Load(session_save_file) #a, d, dx = AnalyzeAPK(apk, decompiler='dad',session=s) a = None d = None dx = None #Check if we have a cached a,d,dx Androguard session object for this analysis in memory for cached_analysis in cached_analyses: if md5 == cached_analysis['md5']: app.logger.info('found cached analysis..loading') a, d, dx = cached_analysis['analysis'] break # else: load the Androguard session from a file, store it in cache memory if not a and not d and not dx: app.logger.info('nothing cached, loading session') analyze_start_time = time.time() session_save_file = os.path.join(md5_analysis_dir, md5 + '_androguard.session') #a, d, dx = load_session(session_save_file, binary=True) s = Load(session_save_file) a = next(iter(s.analyzed_apk.values()))[0] #print(a) #d, dx = next (iter (s.analyzed_dex.values())) d = [tmp_d for tmp_d in s.analyzed_dex.values()] app.logger.info(len(s.analyzed_vms.values())) dx = list(s.analyzed_vms.values())[0] app.logger.info(a) app.logger.info(d) app.logger.info(dx) analyze_end_time = time.time() elapsed = analyze_end_time - analyze_start_time app.logger.info('Reloading Session took {} seconds'.format(elapsed)) app.logger.info('caching analysis') cached_analyses.append({'md5': md5, 'analysis': (a, d, dx)}) #gather all classes from dexs 'd' classes = dx.classes #get_all_classes_from_dexs(d) src_start_time = time.time() class_data_src = None #find the matching class' src based on name for c_name, c_analysis in classes.items(): if c_name == class_name: if c_analysis.external: class_data_src = 'EXTERNAL' else: class_data_src = c_analysis.orig_class.get_source() break src_end_time = time.time() elapsed = src_end_time - src_start_time app.logger.info('get_source took {} seconds'.format(elapsed)) return class_data_src