def staticanalyzer_windows(request):
    """Analyse a windows app."""
    try:
        # Input validation
        print "[INFO] Windows Static Analysis Started"
        app_dic = {}  # Dict to store the binary attributes
        typ = request.GET['type']
        rescan = str(request.GET.get('rescan', 0))
        md5_regex = re.match('^[0-9a-f]{32}$', request.GET['checksum'])
        if (md5_regex) and (typ in ['appx']):
            app_dic['app_name'] = request.GET['name']  # APP ORGINAL NAME
            app_dic['md5'] = request.GET['checksum']
            app_dic['app_dir'] = os.path.join(settings.UPLD_DIR,
                                              app_dic['md5'] + '/')
            app_dic['tools_dir'] = os.path.join(
                settings.BASE_DIR, 'StaticAnalyzer/tools/windows/')
            if typ == 'appx':
                # DB
                db_entry = StaticAnalyzerWindows.objects.filter(  # pylint: disable-msg=E1101
                    MD5=app_dic['md5'])
                if db_entry.exists() and rescan == '0':
                    print "\n[INFO] Analysis is already Done. Fetching data from the DB..."
                    context = {
                        'title': db_entry[0].TITLE,
                        'name': db_entry[0].APP_NAME,
                        'pub_name': db_entry[0].PUB_NAME,
                        'size': db_entry[0].SIZE,
                        'md5': db_entry[0].MD5,
                        'sha1': db_entry[0].SHA1,
                        'sha256': db_entry[0].SHA256,
                        'bin_name': db_entry[0].BINNAME,
                        'version': db_entry[0].VERSION,
                        'arch': db_entry[0].ARCH,
                        '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),
                        'bin_an_results':
                        python_list(db_entry[0].BIN_AN_RESULTS),
                        'bin_an_warnings':
                        python_list(db_entry[0].BIN_AN_WARNINGS)
                    }
                else:
                    print "[INFO] Windows Binary Analysis Started"
                    app_dic['app_path'] = os.path.join(
                        app_dic['app_dir'], app_dic['md5'] + '.appx')
                    # ANALYSIS BEGINS
                    app_dic['size'] = str(FileSize(app_dic['app_path'])) + 'MB'
                    # Generate hashes
                    app_dic['sha1'], app_dic['sha256'] = HashGen(
                        app_dic['app_path'])
                    # EXTRACT APPX
                    print "[INFO] Extracting APPX"
                    app_dic['files'] = Unzip(app_dic['app_path'],
                                             app_dic['app_dir'])
                    xml_dic = _parse_xml(app_dic['app_dir'])
                    bin_an_dic = _binary_analysis(app_dic)
                    # Saving to db
                    print "\n[INFO] Connecting to DB"
                    if rescan == '1':
                        print "\n[INFO] Updating Database..."
                        StaticAnalyzerWindows.objects.filter(  # pylint: disable-msg=E1101
                            MD5=app_dic['md5']).update(
                                TITLE='Static Analysis',
                                APP_NAME=app_dic['app_name'],
                                PUB_NAME=xml_dic['pub_name'],
                                SIZE=app_dic['size'],
                                MD5=app_dic['md5'],
                                SHA1=app_dic['sha1'],
                                SHA256=app_dic['sha256'],
                                BINNAME=bin_an_dic['bin_name'],
                                VERSION=xml_dic['version'],
                                ARCH=xml_dic['arch'],
                                COMPILER_VERSION=xml_dic['compiler_version'],
                                VISUAL_STUDIO_VERSION=xml_dic[
                                    'visual_studio_version'],
                                VISUAL_STUDIO_EDITION=xml_dic[
                                    'visual_studio_edition'],
                                TARGET_OS=xml_dic['target_os'],
                                APPX_DLL_VERSION=xml_dic['appx_dll_version'],
                                PROJ_GUID=xml_dic['proj_guid'],
                                OPTI_TOOL=xml_dic['opti_tool'],
                                TARGET_RUN=xml_dic['target_run'],
                                FILES=app_dic['files'],
                                STRINGS=bin_an_dic['strings'],
                                BIN_AN_RESULTS=bin_an_dic['results'],
                                BIN_AN_WARNINGS=bin_an_dic['warnings'],
                            )
                    elif rescan == '0':
                        print "\n[INFO] Saving to Database"
                        db_item = StaticAnalyzerWindows(
                            TITLE='Static Analysis',
                            APP_NAME=app_dic['app_name'],
                            PUB_NAME=xml_dic['pub_name'],
                            SIZE=app_dic['size'],
                            MD5=app_dic['md5'],
                            SHA1=app_dic['sha1'],
                            SHA256=app_dic['sha256'],
                            BINNAME=bin_an_dic['bin_name'],
                            VERSION=xml_dic['version'],
                            ARCH=xml_dic['arch'],
                            COMPILER_VERSION=xml_dic['compiler_version'],
                            VISUAL_STUDIO_VERSION=xml_dic[
                                'visual_studio_version'],
                            VISUAL_STUDIO_EDITION=xml_dic[
                                'visual_studio_edition'],
                            TARGET_OS=xml_dic['target_os'],
                            APPX_DLL_VERSION=xml_dic['appx_dll_version'],
                            PROJ_GUID=xml_dic['proj_guid'],
                            OPTI_TOOL=xml_dic['opti_tool'],
                            TARGET_RUN=xml_dic['target_run'],
                            FILES=app_dic['files'],
                            STRINGS=bin_an_dic['strings'],
                            BIN_AN_RESULTS=bin_an_dic['results'],
                            BIN_AN_WARNINGS=bin_an_dic['warnings'],
                        )
                        db_item.save()
                    context = {
                        'title': 'Static Analysis',
                        'name': app_dic['app_name'],
                        'pub_name': xml_dic['pub_name'],
                        'size': app_dic['size'],
                        'md5': app_dic['md5'],
                        'sha1': app_dic['sha1'],
                        'sha256': app_dic['sha256'],
                        'bin_name': bin_an_dic['bin_name'],
                        'version': xml_dic['version'],
                        'arch': xml_dic['arch'],
                        'compiler_version': xml_dic['compiler_version'],
                        'visual_studio_version':
                        xml_dic['visual_studio_version'],
                        'visual_studio_edition':
                        xml_dic['visual_studio_edition'],
                        'target_os': xml_dic['target_os'],
                        'appx_dll_version': xml_dic['appx_dll_version'],
                        'proj_guid': xml_dic['proj_guid'],
                        'opti_tool': xml_dic['opti_tool'],
                        'target_run': xml_dic['target_run'],
                        'files': app_dic['files'],
                        'strings': bin_an_dic['strings'],
                        'bin_an_results': bin_an_dic['results'],
                        'bin_an_warnings': bin_an_dic['warnings'],
                    }
                template = "static_analysis/windows_binary_analysis.html"
                return render(request, template, context)
            else:
                return HttpResponseRedirect('/error/')
        else:
            return HttpResponseRedirect('/error/')
    except Exception as exception:
        PrintException("[ERROR] Static Analyzer Windows")
        context = {
            'title': 'Error',
            'exp': exception.message,
            'doc': exception.__doc__
        }
        template = "general/error.html"
        return render(request, template, context)
def staticanalyzer_windows(request, api=False):
    """Analyse a windows app."""
    try:
        # Input validation
        logger.info("Windows Static Analysis Started")
        app_dic = {}  # Dict to store the binary attributes
        if api:
            typ = request.POST['scan_type']
            rescan = str(request.POST.get('re_scan', 0))
            checksum = request.POST['hash']
            filename = request.POST['file_name']
        else:
            typ = request.GET['type']
            rescan = str(request.GET.get('rescan', 0))
            checksum = request.GET['checksum']
            filename = request.GET['name']
        md5_regex = re.match('^[0-9a-f]{32}$', checksum)
        if (md5_regex) and (typ in ['appx']):
            app_dic['app_name'] = filename  # APP ORGINAL NAME
            app_dic['md5'] = checksum
            app_dic['app_dir'] = os.path.join(settings.UPLD_DIR,
                                              app_dic['md5'] + '/')
            app_dic['tools_dir'] = os.path.join(
                settings.BASE_DIR, 'StaticAnalyzer/tools/windows/')
            if typ == 'appx':
                # DB
                db_entry = StaticAnalyzerWindows.objects.filter(  # pylint: disable-msg=E1101
                    MD5=app_dic['md5'])
                if db_entry.exists() and rescan == '0':
                    logger.info(
                        "Analysis is already Done. Fetching data from the DB..."
                    )
                    context = {
                        'title': db_entry[0].TITLE,
                        'name': db_entry[0].APP_NAME,
                        'pub_name': db_entry[0].PUB_NAME,
                        'size': db_entry[0].SIZE,
                        'md5': db_entry[0].MD5,
                        'sha1': db_entry[0].SHA1,
                        'sha256': db_entry[0].SHA256,
                        'bin_name': db_entry[0].BINNAME,
                        'version': db_entry[0].VERSION,
                        'arch': db_entry[0].ARCH,
                        '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),
                        'bin_an_results':
                        python_list(db_entry[0].BIN_AN_RESULTS),
                        'bin_an_warnings':
                        python_list(db_entry[0].BIN_AN_WARNINGS)
                    }
                else:
                    logger.info("Windows Binary Analysis Started")
                    app_dic['app_path'] = os.path.join(
                        app_dic['app_dir'], app_dic['md5'] + '.appx')
                    # ANALYSIS BEGINS
                    app_dic['size'] = str(file_size(
                        app_dic['app_path'])) + 'MB'
                    # Generate hashes
                    app_dic['sha1'], app_dic['sha256'] = hash_gen(
                        app_dic['app_path'])
                    # EXTRACT APPX
                    logger.info("Extracting APPX")
                    app_dic['files'] = unzip(app_dic['app_path'],
                                             app_dic['app_dir'])
                    xml_dic = _parse_xml(app_dic['app_dir'])
                    bin_an_dic = _binary_analysis(app_dic)
                    # Saving to db
                    logger.info("Connecting to DB")
                    if rescan == '1':
                        logger.info("Updating Database...")
                        StaticAnalyzerWindows.objects.filter(  # pylint: disable-msg=E1101
                            MD5=app_dic['md5']).update(
                                TITLE='Static Analysis',
                                APP_NAME=app_dic['app_name'],
                                PUB_NAME=xml_dic['pub_name'],
                                SIZE=app_dic['size'],
                                MD5=app_dic['md5'],
                                SHA1=app_dic['sha1'],
                                SHA256=app_dic['sha256'],
                                BINNAME=bin_an_dic['bin_name'],
                                VERSION=xml_dic['version'],
                                ARCH=xml_dic['arch'],
                                COMPILER_VERSION=xml_dic['compiler_version'],
                                VISUAL_STUDIO_VERSION=xml_dic[
                                    'visual_studio_version'],
                                VISUAL_STUDIO_EDITION=xml_dic[
                                    'visual_studio_edition'],
                                TARGET_OS=xml_dic['target_os'],
                                APPX_DLL_VERSION=xml_dic['appx_dll_version'],
                                PROJ_GUID=xml_dic['proj_guid'],
                                OPTI_TOOL=xml_dic['opti_tool'],
                                TARGET_RUN=xml_dic['target_run'],
                                FILES=app_dic['files'],
                                STRINGS=bin_an_dic['strings'],
                                BIN_AN_RESULTS=bin_an_dic['results'],
                                BIN_AN_WARNINGS=bin_an_dic['warnings'],
                            )
                        update_scan_timestamp(app_dic['md5'])
                    elif rescan == '0':
                        logger.info("Saving to Database")
                        db_item = StaticAnalyzerWindows(
                            TITLE='Static Analysis',
                            APP_NAME=app_dic['app_name'],
                            PUB_NAME=xml_dic['pub_name'],
                            SIZE=app_dic['size'],
                            MD5=app_dic['md5'],
                            SHA1=app_dic['sha1'],
                            SHA256=app_dic['sha256'],
                            BINNAME=bin_an_dic['bin_name'],
                            VERSION=xml_dic['version'],
                            ARCH=xml_dic['arch'],
                            COMPILER_VERSION=xml_dic['compiler_version'],
                            VISUAL_STUDIO_VERSION=xml_dic[
                                'visual_studio_version'],
                            VISUAL_STUDIO_EDITION=xml_dic[
                                'visual_studio_edition'],
                            TARGET_OS=xml_dic['target_os'],
                            APPX_DLL_VERSION=xml_dic['appx_dll_version'],
                            PROJ_GUID=xml_dic['proj_guid'],
                            OPTI_TOOL=xml_dic['opti_tool'],
                            TARGET_RUN=xml_dic['target_run'],
                            FILES=app_dic['files'],
                            STRINGS=bin_an_dic['strings'],
                            BIN_AN_RESULTS=bin_an_dic['results'],
                            BIN_AN_WARNINGS=bin_an_dic['warnings'],
                        )
                        db_item.save()
                    context = {
                        'title': 'Static Analysis',
                        'name': app_dic['app_name'],
                        'pub_name': xml_dic['pub_name'],
                        'size': app_dic['size'],
                        'md5': app_dic['md5'],
                        'sha1': app_dic['sha1'],
                        'sha256': app_dic['sha256'],
                        'bin_name': bin_an_dic['bin_name'],
                        'version': xml_dic['version'],
                        'arch': xml_dic['arch'],
                        'compiler_version': xml_dic['compiler_version'],
                        'visual_studio_version':
                        xml_dic['visual_studio_version'],
                        'visual_studio_edition':
                        xml_dic['visual_studio_edition'],
                        'target_os': xml_dic['target_os'],
                        'appx_dll_version': xml_dic['appx_dll_version'],
                        'proj_guid': xml_dic['proj_guid'],
                        'opti_tool': xml_dic['opti_tool'],
                        'target_run': xml_dic['target_run'],
                        'files': app_dic['files'],
                        'strings': bin_an_dic['strings'],
                        'bin_an_results': bin_an_dic['results'],
                        'bin_an_warnings': bin_an_dic['warnings'],
                    }
                template = "static_analysis/windows_binary_analysis.html"
                if api:
                    return context
                else:
                    return render(request, template, context)
            else:
                msg = "File type not supported"
                if api:
                    return print_n_send_error_response(request, msg, True)
                else:
                    return print_n_send_error_response(request, msg, False)
        else:
            msg = "Hash match failed or Invalid file extension"
            if api:
                return print_n_send_error_response(request, msg, True)
            else:
                return print_n_send_error_response(request, msg, False)
    except Exception as exception:
        msg = str(exception)
        exp_doc = exception.__doc__
        if api:
            return print_n_send_error_response(request, msg, True, exp_doc)
        else:
            return print_n_send_error_response(request, msg, False, exp_doc)