def get_context_from_db_entry(db_entry):
    """Return the context for APPX from DB."""
    try:
        logger.info('Analysis is already Done. Fetching data from the DB...')
        context = {
            'title': 'Static Analysis',
            'version': settings.MOBSF_VER,
            'file_name': db_entry[0].FILE_NAME,
            'app_name': db_entry[0].APP_NAME,
            'publisher_name': db_entry[0].PUBLISHER_NAME,
            'size': db_entry[0].SIZE,
            'md5': db_entry[0].MD5,
            'sha1': db_entry[0].SHA1,
            'sha256': db_entry[0].SHA256,
            'app_version': db_entry[0].APP_VERSION,
            'architecture': db_entry[0].ARCHITECTURE,
            'compiler_version': db_entry[0].COMPILER_VERSION,
            'visual_studio_version': db_entry[0].VISUAL_STUDIO_VERSION,
            'visual_studio_edition': db_entry[0].VISUAL_STUDIO_EDITION,
            'target_os': db_entry[0].TARGET_OS,
            'appx_dll_version': db_entry[0].APPX_DLL_VERSION,
            'proj_guid': db_entry[0].PROJ_GUID,
            'opti_tool': db_entry[0].OPTI_TOOL,
            'target_run': db_entry[0].TARGET_RUN,
            'files': python_list(db_entry[0].FILES),
            'strings': python_list(db_entry[0].STRINGS),
            'binary_analysis': python_list(db_entry[0].BINARY_ANALYSIS),
            'binary_warnings': python_list(db_entry[0].BINARY_WARNINGS),
        }
        return context
    except Exception:
        logger.exception('Fetching from DB')
def get_screenshots(md5_hash, download_dir):
    """Get Screenshots."""
    # Only After Download Process is Done
    result = {}
    imgs = []
    act_imgs = []
    expact_imgs = []
    act = {}
    exp_act = {}
    try:
        screen_dir = os.path.join(download_dir, md5_hash + '-screenshots-apk/')
        sadb = StaticAnalyzerAndroid.objects.get(MD5=md5_hash)
        if os.path.exists(screen_dir):
            for img in os.listdir(screen_dir):
                if img.endswith('.png'):
                    if img.startswith('act'):
                        act_imgs.append(img)
                    elif img.startswith('expact'):
                        expact_imgs.append(img)
                    else:
                        imgs.append(img)
            exported_act = python_list(sadb.EXPORTED_ACTIVITIES)
            act_desc = python_list(sadb.ACTIVITIES)
            if act_imgs:
                if len(act_imgs) == len(act_desc):
                    act = dict(list(zip(act_imgs, act_desc)))
            if expact_imgs:
                if len(expact_imgs) == len(exported_act):
                    exp_act = dict(list(zip(expact_imgs, exported_act)))
    except Exception:
        logger.exception('Organising screenshots')
    result['screenshots'] = imgs
    result['activities'] = act
    result['exported_activities'] = exp_act
    return result
def activity_tester(request, api=False):
    """Exported & non exported activity Tester."""
    data = {}
    try:
        env = Environment()
        test = request.POST['test']
        md5_hash = request.POST['hash']
        if not is_md5(md5_hash):
            return invalid_params(api)
        app_dir = os.path.join(settings.UPLD_DIR, md5_hash + '/')
        screen_dir = os.path.join(app_dir, 'screenshots-apk/')
        if not os.path.exists(screen_dir):
            os.makedirs(screen_dir)
        static_android_db = StaticAnalyzerAndroid.objects.get(MD5=md5_hash)
        package = static_android_db.PACKAGE_NAME
        iden = ''
        if test == 'exported':
            iden = 'Exported '
            logger.info('Exported activity tester')
            activities = python_list(static_android_db.EXPORTED_ACTIVITIES)
        else:
            logger.info('Activity tester')
            activities = python_list(static_android_db.ACTIVITIES)
        logger.info('Fetching %sactivities for %s', iden, package)
        if not activities:
            msg = 'No {}Activites found'.format(iden)
            logger.info(msg)
            data = {'status': 'failed', 'message': msg}
            return send_response(data, api)
        act_no = 0
        logger.info('Starting %sActivity Tester...', iden)
        logger.info('%s %sActivities Identified', str(len(activities)), iden)
        for activity in activities:
            act_no += 1
            logger.info('Launching %sActivity - %s. %s', iden, str(act_no),
                        activity)
            if test == 'exported':
                file_iden = 'expact'
            else:
                file_iden = 'act'
            outfile = ('{}{}-{}.png'.format(screen_dir, file_iden, act_no))
            env.launch_n_capture(package, activity, outfile)
        data = {'status': 'ok'}
    except Exception as exp:
        logger.exception('%sActivity tester', iden)
        data = {'status': 'failed', 'message': str(exp)}
    return send_response(data, api)
def base64_decode(args):
    """Decode Base64 Automatically."""
    decoded = ''
    args_list = python_list(args)
    if not is_base64(args_list[0]):
        return decoded
    try:
        decoded = base64.b64decode(
            args_list[0]).decode('ISO-8859-1')
    except Exception:
        pass
    return decoded
Beispiel #5
0
 def android_component(self, bin_hash, comp):
     """Get APK Components."""
     anddb = StaticAnalyzerAndroid.objects.get(MD5=bin_hash)
     resp = []
     if comp == 'activities':
         resp = python_list(anddb.ACTIVITIES)
     elif comp == 'receivers':
         resp = python_list(anddb.RECEIVERS)
     elif comp == 'providers':
         resp = python_list(anddb.PROVIDERS)
     elif comp == 'services':
         resp = python_list(anddb.SERVICES)
     elif comp == 'libraries':
         resp = python_list(anddb.LIBRARIES)
     elif comp == 'exported_activities':
         resp = python_list(anddb.EXPORTED_ACTIVITIES)
     return '\n'.join(resp)
def get_context_from_db_entry(db_entry):
    """Return the context for IPA/ZIP from DB."""
    try:
        logger.info('Analysis is already Done. Fetching data from the DB...')
        context = {
            'version':
            settings.MOBSF_VER,
            'title':
            'Static Analysis',
            'file_name':
            db_entry[0].FILE_NAME,
            'app_name':
            db_entry[0].APP_NAME,
            'app_type':
            db_entry[0].APP_TYPE,
            'size':
            db_entry[0].SIZE,
            'md5':
            db_entry[0].MD5,
            'sha1':
            db_entry[0].SHA1,
            'sha256':
            db_entry[0].SHA256,
            'build':
            db_entry[0].BUILD,
            'app_version':
            db_entry[0].APP_VERSION,
            'sdk_name':
            db_entry[0].SDK_NAME,
            'platform':
            db_entry[0].PLATFORM,
            'min_os_version':
            db_entry[0].MIN_OS_VERSION,
            'bundle_id':
            db_entry[0].BUNDLE_ID,
            'bundle_url_types':
            python_list(db_entry[0].BUNDLE_URL_TYPES),
            'bundle_supported_platforms':
            python_list(db_entry[0].BUNDLE_SUPPORTED_PLATFORMS),
            'icon_found':
            db_entry[0].ICON_FOUND,
            'info_plist':
            db_entry[0].INFO_PLIST,
            'binary_info':
            python_dict(db_entry[0].BINARY_INFO),
            'permissions':
            python_dict(db_entry[0].PERMISSIONS),
            'ats_analysis':
            python_list(db_entry[0].ATS_ANALYSIS),
            'binary_analysis':
            python_list(db_entry[0].BINARY_ANALYSIS),
            'macho_analysis':
            python_dict(db_entry[0].MACHO_ANALYSIS),
            'ios_api':
            python_dict(db_entry[0].IOS_API),
            'code_analysis':
            python_dict(db_entry[0].CODE_ANALYSIS),
            'file_analysis':
            python_list(db_entry[0].FILE_ANALYSIS),
            'libraries':
            python_list(db_entry[0].LIBRARIES),
            'files':
            python_list(db_entry[0].FILES),
            'urls':
            python_list(db_entry[0].URLS),
            'domains':
            python_dict(db_entry[0].DOMAINS),
            'emails':
            python_list(db_entry[0].EMAILS),
            'strings':
            python_list(db_entry[0].STRINGS),
            'firebase_urls':
            python_list(db_entry[0].FIREBASE_URLS),
            'appstore_details':
            python_dict(db_entry[0].APPSTORE_DETAILS),
            'secrets':
            python_list(db_entry[0].SECRETS),
        }
        return context
    except Exception:
        logger.exception('Fetching from DB')
Beispiel #7
0
def get_context_from_db_entry(db_entry: QuerySet) -> dict:
    """Return the context for APK/ZIP from DB."""
    try:
        logger.info('Analysis is already Done. Fetching data from the DB...')
        context = {
            'version': settings.MOBSF_VER,
            'title': 'Static Analysis',
            'file_name': db_entry[0].FILE_NAME,
            'app_name': db_entry[0].APP_NAME,
            'app_type': db_entry[0].APP_TYPE,
            'size': db_entry[0].SIZE,
            'md5': db_entry[0].MD5,
            'sha1': db_entry[0].SHA1,
            'sha256': db_entry[0].SHA256,
            'package_name': db_entry[0].PACKAGE_NAME,
            'main_activity': db_entry[0].MAIN_ACTIVITY,
            'exported_activities': db_entry[0].EXPORTED_ACTIVITIES,
            'browsable_activities':
            python_dict(db_entry[0].BROWSABLE_ACTIVITIES),
            'activities': python_list(db_entry[0].ACTIVITIES),
            'receivers': python_list(db_entry[0].RECEIVERS),
            'providers': python_list(db_entry[0].PROVIDERS),
            'services': python_list(db_entry[0].SERVICES),
            'libraries': python_list(db_entry[0].LIBRARIES),
            'target_sdk': db_entry[0].TARGET_SDK,
            'max_sdk': db_entry[0].MAX_SDK,
            'min_sdk': db_entry[0].MIN_SDK,
            'version_name': db_entry[0].VERSION_NAME,
            'version_code': db_entry[0].VERSION_CODE,
            'icon_hidden': db_entry[0].ICON_HIDDEN,
            'icon_found': db_entry[0].ICON_FOUND,
            'permissions': python_dict(db_entry[0].PERMISSIONS),
            'certificate_analysis':
            python_dict(db_entry[0].CERTIFICATE_ANALYSIS),
            'manifest_analysis': python_list(db_entry[0].MANIFEST_ANALYSIS),
            'network_security': python_list(db_entry[0].NETWORK_SECURITY),
            'binary_analysis': python_list(db_entry[0].BINARY_ANALYSIS),
            'file_analysis': python_list(db_entry[0].FILE_ANALYSIS),
            'android_api': python_dict(db_entry[0].ANDROID_API),
            'code_analysis': python_dict(db_entry[0].CODE_ANALYSIS),
            'niap_analysis': python_dict(db_entry[0].NIAP_ANALYSIS),
            'urls': python_list(db_entry[0].URLS),
            'domains': python_dict(db_entry[0].DOMAINS),
            'emails': python_list(db_entry[0].EMAILS),
            'strings': python_list(db_entry[0].STRINGS),
            'firebase_urls': python_list(db_entry[0].FIREBASE_URLS),
            'files': python_list(db_entry[0].FILES),
            'exported_count': python_dict(db_entry[0].EXPORTED_COUNT),
            'apkid': python_dict(db_entry[0].APKID),
            'quark': python_list(db_entry[0].QUARK),
            'trackers': python_dict(db_entry[0].TRACKERS),
            'playstore_details': python_dict(db_entry[0].PLAYSTORE_DETAILS),
            'secrets': python_list(db_entry[0].SECRETS),
        }
        return context
    except Exception:
        logger.exception('Fetching from DB')
def dynamic_analyzer(request, checksum, api=False):
    """Android Dynamic Analyzer Environment."""
    try:
        identifier = None
        activities = None
        exported_activities = None
        if api:
            reinstall = request.POST.get('re_install', '1')
            install = request.POST.get('install', '1')
        else:
            reinstall = request.GET.get('re_install', '1')
            install = request.GET.get('install', '1')
        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, 'Cannot get package name from checksum', api)
        logger.info('Creating Dynamic Analysis Environment for %s', package)
        try:
            identifier = get_device()
        except Exception:
            pass
        if 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 '
                   f'{get_config_loc()}')
            return print_n_send_error_response(request, msg, api)

        # Get activities from the static analyzer results
        try:
            static_android_db = StaticAnalyzerAndroid.objects.get(MD5=checksum)
            exported_activities = python_list(
                static_android_db.EXPORTED_ACTIVITIES)
            activities = python_list(static_android_db.ACTIVITIES)
        except ObjectDoesNotExist:
            logger.warning('Failed to get Activities. '
                           'Static Analysis not completed for the app.')
        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, request)
        # 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()
        if install == '1':
            # Install APK
            apk_path = Path(settings.UPLD_DIR) / checksum / f'{checksum}.apk'
            status, output = env.install_apk(apk_path.as_posix(), package,
                                             reinstall)
            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_width': screen_width,
            'screen_height': screen_height,
            'package': package,
            'hash': checksum,
            'android_version': version,
            'version': settings.MOBSF_VER,
            'activities': activities,
            'exported_activities': exported_activities,
            '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)