def dynamic_analysis(request, api=False):
    """Android Dynamic Analysis Entry point."""
    try:
        scan_apps = []
        device_packages = {}
        and_ver = None
        and_sdk = None
        apks = StaticAnalyzerAndroid.objects.filter(
            APP_TYPE='apk')
        for apk in reversed(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 '
                   f'{get_config_loc()}')
            return print_n_send_error_response(request, msg, api)
        try:
            if identifier:
                env = Environment(identifier)
                device_packages = env.get_device_packages()
                pkg_file = Path(settings.DWD_DIR) / 'packages.json'
                with pkg_file.open('w', encoding='utf-8') as target:
                    dump(device_packages, target)
                and_ver = env.get_android_version()
                and_sdk = env.get_android_sdk()
        except Exception:
            pass
        context = {'apps': scan_apps,
                   'identifier': identifier,
                   'android_version': and_ver,
                   'android_sdk': and_sdk,
                   'proxy_ip': get_proxy_ip(identifier),
                   'proxy_port': settings.PROXY_PORT,
                   'settings_loc': get_config_loc(),
                   'device_packages': device_packages,
                   '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)
コード例 #2
0
    def get_result(self, file_path, file_hash):
        """
        Get Results from VT.

        Uploading a file and getting the approval msg from VT
        or fetching existing report
        :param file_path: file's path
        :param file_hash: file's hash - md5/sha1/sha256
        :return: VirusTotal result json / None upon error
        """
        try:
            logger.info('VirusTotal: Check for existing report')
            report = self.get_report(file_hash)
            # Check for existing report
            if report:
                if report['response_code'] == 1:
                    logger.info('VirusTotal: %s', report['verbose_msg'])
                    return report
            if settings.VT_UPLOAD:
                logger.info('VirusTotal: file upload')
                upload_response = self.upload_file(file_path)
                if upload_response:
                    logger.info('VirusTotal: %s',
                                upload_response['verbose_msg'])
                return upload_response
            else:
                logger.info('VirusTotal Scan not performed as file'
                            ' upload is disabled in %s. '
                            'To enable file upload, '
                            'set VT_UPLOAD to True.', get_config_loc())
                report = {
                    'verbose_msg': ('Scan not performed, VirusTotal file'
                                    ' upload disabled '
                                    'in %s', get_config_loc()),
                    'positives': 0,
                    'total': 0}
                return report
        except Exception:
            logger.exception('VirusTotal get_result')
コード例 #3
0
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 '
                   f'{get_config_loc()}')
            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,
            'settings_loc': get_config_loc(),
            '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)
コード例 #4
0
def _binary_analysis(app_dic):
    """Start binary analsis."""
    logger.info('Starting Binary Analysis')
    bin_an_dic = {}

    # Init optional sections to prevent None-Pointer-Errors
    bin_an_dic['results'] = []
    bin_an_dic['warnings'] = []
    # Search for exe
    for file_name in app_dic['files']:
        if file_name.endswith('.exe'):
            bin_an_dic['bin'] = file_name
            bin_an_dic['bin_name'] = file_name.replace('.exe', '')
            break
    if not bin_an_dic.get('bin_name'):
        logger.exception('No executable in appx.')
    bin_path = os.path.join(app_dic['app_dir'], bin_an_dic['bin'])

    # Execute strings command
    bin_an_dic['strings'] = ''
    # Make unique # pylint: disable-msg=R0204
    str_list = list(set(strings_util(bin_path)))
    str_list = [escape(s) for s in str_list]
    bin_an_dic['strings'] = str_list

    # Search for unsave function
    pattern = re.compile('(alloca|gets|memcpy|printf|scanf|sprintf|sscanf|'
                         'strcat|StrCat|strcpy|StrCpy|strlen|StrLen|strncat|'
                         'StrNCat|strncpy|StrNCpy|strtok|swprintf|vsnprintf|'
                         'vsprintf|vswprintf|wcscat|wcscpy|wcslen|wcsncat|'
                         'wcsncpy|wcstok|wmemcpy)')
    for elem in str_list:
        if pattern.match(elem[5:-5]):
            result = {
                'rule_id': 'Possible Insecure Function',
                'status': 'Insecure',
                'desc': ('Possible Insecure '
                         'Function detected: {}').format(elem[5:-5])}
            bin_an_dic['results'].append(result)

    # Execute binskim analysis if vm is available
    if platform.system() != 'Windows' or 'CI' in os.environ:
        if settings.WINDOWS_VM_IP:
            logger.info('Windows VM configured.')
            global proxy
            proxy = xmlrpc.client.ServerProxy(  # pylint: disable-msg=C0103
                'http://{}:{}'.format(
                    settings.WINDOWS_VM_IP,
                    settings.WINDOWS_VM_PORT))
            name = _upload_sample(bin_path)
            bin_an_dic = binskim(name, bin_an_dic)
            bin_an_dic = binscope(name, bin_an_dic)
        else:
            logger.warning(
                'Windows VM not configured in %s.'
                ' Skipping Binskim and Binscope.', get_config_loc())
            warning = {
                'rule_id': 'VM',
                'status': 'Info',
                'info': '',
                'desc': 'VM is not configured. Please read the readme.md'
                ' in MobSF/install/windows.',
            }
            bin_an_dic['results'].append(warning)
    else:
        logger.info('Running local analysis.')

        global config
        config = configparser.ConfigParser()
        # Switch to settings defined path if available
        config.read(expanduser('~') + '\\MobSF\\Config\\config.txt')

        # Run analysis functions
        bin_an_dic = binskim(bin_path,
                             bin_an_dic,
                             run_local=True,
                             app_dir=app_dic['app_dir'])
        bin_an_dic = binscope(bin_path,
                              bin_an_dic,
                              run_local=True,
                              app_dir=app_dic['app_dir'])

    return bin_an_dic