def dynamic_analysis(request): """Android Dynamic Analysis Entry point.""" try: apks = StaticAnalyzerAndroid.objects.filter( ZIPPED='&type=apk').order_by('-id') try: identifier = get_device() except Exception: msg = ('Is Genymotion Andoird VM running? MobSF cannot' ' find android instance identifier.' ' Please run an android instance and refresh' ' this page. If this error persists,' ' set ANALYZER_IDENTIFIER in MobSF/settings.py') return print_n_send_error_response(request, msg) proxy_ip = get_proxy_ip(identifier) context = { 'apks': apks, 'identifier': identifier, 'proxy_ip': proxy_ip, 'proxy_port': settings.PROXY_PORT, 'title': 'MobSF Dynamic Analysis' } template = 'dynamic_analysis/dynamic_analysis.html' return render(request, template, context) except Exception as exp: logger.exception('Dynamic Analysis') return print_n_send_error_response(request, exp)
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')
def __init__(self, identifier=None): if identifier: self.identifier = identifier else: self.identifier = get_device() self.tools_dir = settings.TOOLS_DIR self.frida_str = f'MobSF-Frida-{FRIDA_VERSION}'.encode('utf-8') self.xposed_str = b'MobSF-Xposed'
def execute_adb(request): """Execute ADB Commands.""" data = {'status': 'ok', 'message': ''} cmd = request.POST['cmd'] if cmd: args = [get_adb(), '-s', get_device()] try: proc = subprocess.Popen(args + cmd.split(' '), stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = proc.communicate() except Exception: logger.exception('Executing ADB Commands') if stdout or stderr: out = stdout or stderr out = out.decode('utf8', 'ignore') else: out = '' data = {'status': 'ok', 'message': out} return json_response(data)
def dynamic_analysis(request, api=False): """Android Dynamic Analysis Entry point.""" try: scan_apps = [] apks = StaticAnalyzerAndroid.objects.filter( APP_TYPE='apk').order_by('-id') for apk in apks: temp_dict = { 'ICON_FOUND': apk.ICON_FOUND, 'MD5': apk.MD5, 'APP_NAME': apk.APP_NAME, 'VERSION_NAME': apk.VERSION_NAME, 'FILE_NAME': apk.FILE_NAME, 'PACKAGE_NAME': apk.PACKAGE_NAME, } scan_apps.append(temp_dict) try: identifier = get_device() except Exception: msg = ('Is Android VM running? MobSF cannot' ' find android instance identifier.' ' Please run an android instance and refresh' ' this page. If this error persists,' ' set ANALYZER_IDENTIFIER in MobSF/settings.py') return print_n_send_error_response(request, msg, api) proxy_ip = get_proxy_ip(identifier) context = {'apps': scan_apps, 'identifier': identifier, 'proxy_ip': proxy_ip, 'proxy_port': settings.PROXY_PORT, 'title': 'MobSF Dynamic Analysis', 'version': settings.MOBSF_VER} if api: return context template = 'dynamic_analysis/dynamic_analysis.html' return render(request, template, context) except Exception as exp: logger.exception('Dynamic Analysis') return print_n_send_error_response(request, exp, api)
def __init__(self, identifier=None): if identifier: self.identifier = identifier else: self.identifier = get_device() self.tools_dir = settings.TOOLS_DIR
def dynamic_analyzer(request): """Android Dynamic Analyzer Environment.""" logger.info('Creating Dynamic Analysis Environment') try: bin_hash = request.GET['hash'] package = request.GET['package'] no_device = False if (is_attack_pattern(package) or not is_md5(bin_hash)): return print_n_send_error_response(request, 'Invalid Parameters') try: identifier = get_device() except Exception: no_device = True if no_device or not identifier: msg = ('Is the android instance running? MobSF cannot' ' find android instance identifier. ' 'Please run an android instance and refresh' ' this page. If this error persists,' ' set ANALYZER_IDENTIFIER in MobSF/settings.py') return print_n_send_error_response(request, msg) env = Environment(identifier) if not env.connect_n_mount(): msg = 'Cannot Connect to ' + identifier return print_n_send_error_response(request, msg) version = env.get_android_version() logger.info('Android Version identified as %s', version) xposed_first_run = False if not env.is_mobsfyied(version): msg = ('This Android instance is not MobSfyed.\n' 'MobSFying the android runtime environment') logger.warning(msg) if not env.mobsfy_init(): return print_n_send_error_response( request, 'Failed to MobSFy the instance') if version < 5: xposed_first_run = True if xposed_first_run: msg = ('Have you MobSFyed the instance before' ' attempting Dynamic Analysis?' ' Install Framework for Xposed.' ' Restart the device and enable' ' all Xposed modules. And finally' ' restart the device once again.') return print_n_send_error_response(request, msg) # Clean up previous analysis env.dz_cleanup(bin_hash) # Configure Web Proxy env.configure_proxy(package) # Supported in Android 5+ env.enable_adb_reverse_tcp(version) # Apply Global Proxy to device env.set_global_proxy(version) # Start Clipboard monitor env.start_clipmon() # Get Screen Resolution screen_width, screen_height = env.get_screen_res() logger.info('Installing APK') app_dir = os.path.join(settings.UPLD_DIR, bin_hash + '/') # APP DIRECTORY apk_path = app_dir + bin_hash + '.apk' # APP PATH env.adb_command(['install', '-r', apk_path], False, True) logger.info('Testing Environment is Ready!') context = { 'screen_witdth': screen_width, 'screen_height': screen_height, 'package': package, 'md5': bin_hash, 'version': version, 'title': 'Dynamic Analyzer' } template = 'dynamic_analysis/android/dynamic_analyzer.html' return render(request, template, context) except Exception: logger.exception('Dynamic Analyzer') return print_n_send_error_response(request, 'Dynamic Analysis Failed.')
def dynamic_analyzer(request, checksum, api=False): """Android Dynamic Analyzer Environment.""" logger.info('Creating Dynamic Analysis Environment') try: no_device = False if not is_md5(checksum): # We need this check since checksum is not validated # in REST API return print_n_send_error_response( request, 'Invalid Parameters', api) package = get_package_name(checksum) if not package: return print_n_send_error_response( request, 'Invalid Parameters', api) try: identifier = get_device() except Exception: no_device = True if no_device or not identifier: msg = ('Is the android instance running? MobSF cannot' ' find android instance identifier. ' 'Please run an android instance and refresh' ' this page. If this error persists,' ' set ANALYZER_IDENTIFIER in MobSF/settings.py') return print_n_send_error_response(request, msg, api) env = Environment(identifier) if not env.connect_n_mount(): msg = 'Cannot Connect to ' + identifier return print_n_send_error_response(request, msg, api) version = env.get_android_version() logger.info('Android Version identified as %s', version) xposed_first_run = False if not env.is_mobsfyied(version): msg = ('This Android instance is not MobSfyed/Outdated.\n' 'MobSFying the android runtime environment') logger.warning(msg) if not env.mobsfy_init(): return print_n_send_error_response( request, 'Failed to MobSFy the instance', api) if version < 5: xposed_first_run = True if xposed_first_run: msg = ('Have you MobSFyed the instance before' ' attempting Dynamic Analysis?' ' Install Framework for Xposed.' ' Restart the device and enable' ' all Xposed modules. And finally' ' restart the device once again.') return print_n_send_error_response(request, msg, api) # Clean up previous analysis env.dz_cleanup(checksum) # Configure Web Proxy env.configure_proxy(package) # Supported in Android 5+ env.enable_adb_reverse_tcp(version) # Apply Global Proxy to device env.set_global_proxy(version) # Start Clipboard monitor env.start_clipmon() # Get Screen Resolution screen_width, screen_height = env.get_screen_res() apk_path = Path(settings.UPLD_DIR) / checksum / f'{checksum}.apk' # Install APK status, output = env.install_apk(apk_path.as_posix(), package) if not status: # Unset Proxy env.unset_global_proxy() msg = (f'This APK cannot be installed. Is this APK ' f'compatible the Android VM/Emulator?\n{output}') return print_n_send_error_response( request, msg, api) logger.info('Testing Environment is Ready!') context = {'screen_witdth': screen_width, 'screen_height': screen_height, 'package': package, 'hash': checksum, 'android_version': version, 'version': settings.MOBSF_VER, 'title': 'Dynamic Analyzer'} template = 'dynamic_analysis/android/dynamic_analyzer.html' if api: return context return render(request, template, context) except Exception: logger.exception('Dynamic Analyzer') return print_n_send_error_response( request, 'Dynamic Analysis Failed.', api)