private void OnContext(IAsyncResult ar)
 {
     try
     {
         var context = _listener.EndGetContext(ar);
         var request = new WebRequestContext(context);
         Task.Factory.StartNew(() => Run(request));
     }
     catch (ObjectDisposedException e)
     {
         // This exception is expected because we don't synchronize dispose with
         // EndGetContext...
         Log.DebugFormat("Caught expected/unavaoidable exception: {0}", e);
     }
     catch (Exception e)
     {
         Log.Error("Caught unexpected exception: {0}", e);
     }
     finally
     {
         if (!_isDisposed)
         {
             Listen();
         }
     }
 }
        public void TestSendRequestUsingBrowserWebRequestHandlingHttpException()
        {
            ObjectResolver.RegisterType <IProcessManager, ProcessManager>();
            var browserInstances = new Dictionary <BrowserType, int> {
                { BrowserType.Chrome, 1 }
            };

            using (var browserManager = new BrowserManager(browserInstances))
            {
                ObjectResolver.RegisterInstance <IBrowserManager>(browserManager);
                var context = new Context();
                WebRequestContext webRequestContext =
                    context.SendRequest(new ContextSendRequestParameter
                {
                    Url         = nonExistingTargetUrl,
                    BrowserType = BrowserType.Chrome
                });

                // check that we got the proper response back
                webRequestContext.ResponseHolder.ShouldNotBeNull();
                webRequestContext.ResponseHolder.ResponseContent.ShouldNotBeEmpty();
                webRequestContext.ResponseHolder.RequestUserAgent.ShouldEqual(BrowserType.Chrome.ToString());
                webRequestContext.ResponseHolder.StatusCode.ShouldEqual(HttpStatusCode.OK);
                webRequestContext.ResponseHolder.BrowserPageTitle.IndexOfOi("404").ShouldBeGreaterThan(-1);
            }
        }
Beispiel #3
0
        /// <summary>
        /// Overriding the Check Vulnerability implementation because we just want to look in the response headers.
        /// </summary>
        /// <param name="webRequestContext">
        /// The web Request Context.
        /// </param>
        /// <param name="testcase">
        /// The test case.
        /// </param>
        /// <param name="testedParam">
        /// The tested Parameter.
        /// </param>
        /// <param name="testValue">
        /// The tested Val.
        /// </param>
        /// <seealso cref="M:BackScatterScannerLib.Engine.TestBase.CheckForVuln(WebRequestContext,TestCase,string,string)"/>
        protected override void CheckForVulnerabilities(
            WebRequestContext webRequestContext,
            TestCase testcase,
            string testedParam,
            string testValue)
        {
            HttpWebResponseHolder response = webRequestContext.ResponseHolder;

            var fromHeaderValue = response.Headers["From"];

            if (response.Headers == null ||
                string.IsNullOrWhiteSpace(fromHeaderValue))
            {
                return;
            }

            // Have we injected a from header and does it contain the domain we are attempting to redirect to?
            if (fromHeaderValue.IndexOf("*****@*****.**", StringComparison.InvariantCultureIgnoreCase) > -1)
            {
                Vulnerabilities.Enqueue(new Vulnerability
                {
                    Title        = "HTTP Response Splitting - Newline Injection",
                    Level        = (int)VulnerabilityLevelEnum.High,
                    TestedParam  = testedParam,
                    TestedVal    = testValue,
                    HttpResponse = response,
                    Evidence     = $"From : {fromHeaderValue}",
                    MatchString  = testcase.MatchString,
                    TestPlugin   = GetType().Name
                });
            }
        }
        public void TestSendRequestUsingBrowserWebRequest()
        {
            ObjectResolver.RegisterType <IProcessManager, ProcessManager>();
            var browserInstances = new Dictionary <BrowserType, int> {
                { BrowserType.Chrome, 1 }
            };

            using (var browserManager = new BrowserManager(browserInstances))
            {
                ObjectResolver.RegisterInstance <IBrowserManager>(browserManager);

                var context = new Context();
                WebRequestContext webRequestContext =
                    context.SendRequest(new ContextSendRequestParameter
                {
                    Url         = targetUrl,
                    BrowserType = BrowserType.Chrome
                });

                // check that we got the proper response back
                webRequestContext.ResponseHolder.ShouldNotBeNull();
                webRequestContext.ResponseHolder.ResponseContent.ShouldNotBeNullOrEmpty();
                webRequestContext.ResponseHolder.RequestUserAgent.ShouldContain(BrowserType.Chrome.ToString());
            }
        }
Beispiel #5
0
        /// <summary>
        /// The end web request event.
        /// </summary>
        /// <param name="webRequestContext">
        /// The web request context.
        /// </param>
        /// <param name="testCase">
        /// The test case.
        /// </param>
        /// <param name="parameterKey">
        /// The parameter key.
        /// </param>
        /// <param name="parameterValue">
        /// The parameter value.
        /// </param>
        private void EndWebRequestEvent(
            WebRequestContext webRequestContext,
            TestCase testCase,
            string parameterKey,
            string parameterValue)
        {
            HttpWebResponseHolder response = webRequestContext.ResponseHolder;

            // valid response type?
            if (string.IsNullOrEmpty(response.ResponseContent) ||
                IsContentTypeValid(testCase, response.ResponseContentType))
            {
                BrowserHelper.ReleaseBrowser(webRequestContext);
                return;
            }

            // run detectors
            this.Context.RunDetectors(
                response,
                this.TestTarget,
                this.GetType().Name,
                testCase,
                parameterKey,
                parameterValue);

            // execute client callback
            this.ExecuteCheckForVulnerabilities(
                webRequestContext,
                testCase,
                parameterKey,
                parameterValue);
        }
Beispiel #6
0
        /// <summary>
        /// Inside a test check to see if the match string gets found on the response page,regex used for matching
        /// if that is the case then log a vulnerabilities.
        /// </summary>
        /// <param name="webRequestContext">web request context</param>
        /// <param name="testCase">test case</param>
        /// <param name="testParameter">tested parameter</param>
        /// <param name="testValue">tested value</param>
        protected virtual void CheckForVulnerabilities(
            WebRequestContext webRequestContext,
            TestCase testCase,
            string testParameter,
            string testValue)
        {
            HttpWebResponseHolder response = webRequestContext.ResponseHolder;

            if (string.IsNullOrEmpty(testCase.MatchString))
            {
                return;
            }

            MatchCollection matches = Regex.Matches(
                response.ResponseContent,
                testCase.MatchString,
                RegexOptions.IgnoreCase);

            if (matches.Count > 0)
            {
                this.Vulnerabilities.Enqueue(new Vulnerability
                {
                    Title        = testCase.TestName,
                    Level        = 1,
                    TestedParam  = testParameter,
                    TestedVal    = testValue,
                    HttpResponse = response,
                    MatchString  = testCase.MatchString,
                    TestPlugin   = GetType().Name
                });
            }
        }
Beispiel #7
0
        private int RunCGIMode(string scriptFile)
        {
            var engine = new HostedScriptEngine();
            engine.AttachAssembly(System.Reflection.Assembly.GetExecutingAssembly());

            var request = new WebRequestContext();
            engine.InjectGlobalProperty("ВебЗапрос", request, true);
            engine.InjectObject(this, false);
            engine.Initialize();

            var source = engine.Loader.FromFile(scriptFile);
            
            Process process;

            try
            {
                process = engine.CreateProcess(this, source);
            }
            catch (Exception e)
            {
                ShowExceptionInfo(e);
                return 1;
            }

            int exitCode = process.Start();
            
            if (!_isContentEchoed)
                Echo("");

            return exitCode;
        }
        /// <summary>
        /// Inside a test check to see if the match string gets found on the response page,regex used for
        /// matching if that is the case then log a vulnerability.
        /// </summary>
        /// <param name="webRequestContext">
        /// The web Request Context.
        /// </param>
        /// <param name="testCase">
        /// The test Case.
        /// </param>
        /// <param name="testParameter">
        /// The tested Parameter.
        /// </param>
        /// <param name="testValue">
        /// The tested Val.
        /// </param>
        /// <seealso cref="M:BackScatterScannerLib.Engine.TestBase.CheckForVuln(WebRequestContext,TestCase,string,string)"/>
        protected override void CheckForVulnerabilities(
            WebRequestContext webRequestContext,
            TestCase testCase,
            string testParameter,
            string testValue)
        {
            HttpWebResponseHolder response = webRequestContext.ResponseHolder;

            if (string.IsNullOrWhiteSpace(response.ResponseContent))
            {
                return;
            }

            if (response.ResponseContent.IndexOfOi("<system.web>") > -1 &&
                response.ResponseContent.IndexOfOi("</system.web>") > -1)
            {
                this.AddVulnerability(
                    this.Name,
                    testParameter,
                    testValue,
                    "Directory traversal attack succeeded.",
                    response,
                    testCase,
                    VulnerabilityLevelEnum.High);
            }
        }
Beispiel #9
0
        /// <inheritdoc/>
        protected override void CheckForVulnerabilities(
            WebRequestContext webRequestContext,
            TestCase testcase,
            string testedParam,
            string testValue)
        {
            HttpWebResponseHolder response = webRequestContext.ResponseHolder;

            if (response.StatusCode >= HttpStatusCode.OK &&
                response.StatusCode < HttpStatusCode.Ambiguous)
            {
                return;
            }

            try
            {
                var evidence = ExtractEvidence(response.ResponseContent, TestTarget.Content);

                if (!string.IsNullOrEmpty(evidence))
                {
                    this.AddVulnerability(
                        testcase.TestName,
                        testedParam,
                        testValue,
                        evidence,
                        response,
                        testcase,
                        VulnerabilityLevelEnum.Info);
                }
            }
            catch (OutOfMemoryException ex)
            {
                Logger.WriteError(ex);
            }
        }
Beispiel #10
0
        /// <summary>
        /// Get Packet RawData
        /// </summary>
        /// <param name="requestContext"></param>
        /// <param name="headers"></param>
        /// <returns></returns>
        public static async Task <byte[]> RequestRawAsync(WebRequestContext requestContext, string token = "")
        {
            var endPointAddr = new Url(requestContext.BaseUrl ?? "").AppendPathSegment(requestContext.ServiceUrl ?? "");
            var flurlRequest = new FlurlClient(endPointAddr).Request();

            //if (headers != null && headers.Length > 0)
            //{
            //    foreach (var (name, value) in headers)
            //    {
            //        flurlRequest.WithHeader(name, value);
            //    }
            //}

            flurlRequest.WithOAuthBearerToken(token);

            var convertedSegments = ConvertSegments(requestContext.SegmentGroup, requestContext.SegmentData);

            flurlRequest.AppendPathSegments(convertedSegments);

            List <(string, string)> convertedParams = ConvertQueryParams(requestContext.QueryParamGroup, requestContext.QueryParamData);

            foreach (var(name, value) in convertedParams)
            {
                flurlRequest.SetQueryParam(name, value);
            }

            requestContext.DataSerialize();
            return(await SendAsync(flurlRequest, requestContext));
        }
Beispiel #11
0
        /// <summary>
        /// Inside a test check to see if the match string gets found on the response page,regex used for
        /// matching if that is the case then log a vulnerability.
        /// </summary>
        /// <param name="webRequestContext">
        /// The web Request Context.
        /// </param>
        /// <param name="testcase">
        /// The test case.
        /// </param>
        /// <param name="testedParam">
        /// The tested parameter.
        /// </param>
        /// <param name="testValue">
        /// The tested Val.
        /// </param>
        /// <seealso cref="M:BackScatterScannerLib.Engine.TestBase.CheckForVuln(WebRequestContext,TestCase,string,string)"/>
        protected override void CheckForVulnerabilities(
            WebRequestContext webRequestContext,
            TestCase testcase,
            string testedParam,
            string testValue)
        {
            HttpWebResponseHolder response = webRequestContext.ResponseHolder;

            if (response.ResponseUri != null &&
                response.ResponseUri.Host.IndexOf(response.RequestHost, StringComparison.InvariantCultureIgnoreCase) ==
                -1 &&
                response.RequestHost.IndexOf(response.ResponseUri.Host, StringComparison.InvariantCultureIgnoreCase) ==
                -1 &&
                response.ResponseUri.Host.IndexOf("ikeahackers.net", StringComparison.InvariantCultureIgnoreCase) > -1)
            {
                this.AddVulnerability(
                    testcase.TestName,
                    testedParam,
                    testValue,
                    response.ResponseUri.Host,
                    response,
                    testcase,
                    VulnerabilityLevelEnum.High);
            }
        }
 /// <inheritdoc/>
 protected override void CheckForVulnerabilities(
     WebRequestContext webRequestContext,
     TestCase testcase,
     string testedParam,
     string testValue)
 {
     // don't do anything here, just override the default behavior
 }
Beispiel #13
0
        public async Task <TOut> RequestAsyncWithToken <TOut>(WebRequestContext reqContext)
        {
            TOut result = default;

            if (!await CheckInternetConnection() || !await RefrashToken())
            {
                return(result);
            }

            result = await WebClient.RequestAsync <TOut>(reqContext, ClientContext.Token);

            return(result);
        }
Beispiel #14
0
        public async Task <byte[]> RequestRawAsyncWithToken(WebRequestContext reqContext)
        {
            byte[] result = null;

            if (!await CheckInternetConnection() || !await RefrashToken())
            {
                return(result);
            }

            result = await WebClient.RequestRawAsync(reqContext, ClientContext.Token);

            return(result);
        }
Beispiel #15
0
 /// <summary>
 /// The execute check for vulnerabilities.
 /// </summary>
 /// <param name="webRequestContext">
 /// The web request context.
 /// </param>
 /// <param name="testCase">
 /// The test case.
 /// </param>
 /// <param name="parameterKey">
 /// The parameter key.
 /// </param>
 /// <param name="parameterValue">
 /// The parameter value.
 /// </param>
 private void ExecuteCheckForVulnerabilities(
     WebRequestContext webRequestContext,
     TestCase testCase,
     string parameterKey,
     string parameterValue)
 {
     try
     {
         // as long as we have a response, check to see if there was a vuln/match
         this.CheckForVulnerabilities(webRequestContext, testCase, parameterKey, parameterValue);
     }
     finally
     {
         // We are done with the browser, give it back.
         BrowserHelper.ReleaseBrowser(webRequestContext);
     }
 }
Beispiel #16
0
        private static async Task <byte[]> SendAsync(IFlurlRequest flurlRequest, WebRequestContext requestContext)
        {
            byte[] rawData = null;

            try
            {
                requestContext.AttemptCnt++;

                if (requestContext.MethodType == WebMethodType.GET)
                {
                    rawData = await flurlRequest.GetBytesAsync();
                }
                else if (requestContext.MethodType == WebMethodType.POST)
                {
                    rawData = await flurlRequest
                              .PostAsync(new ByteArrayContent(requestContext))
                              .ReceiveBytes();
                }
            }
            catch (FlurlHttpException flurlException)
            {
                if (requestContext.AttemptCnt < WebConfig.ReTryCount)
                {
                    rawData = await RequestRetryPolicy(flurlException, flurlRequest, requestContext);
                }
                else
                {
                    if (_exceptionHandler != null)
                    {
                        await _exceptionHandler.Invoke(flurlException);
                    }
                }
            }
            catch (Exception ex)
            {
                if (_exceptionHandler != null)
                {
                    await _exceptionHandler.Invoke(ex);
                }
            }

            return(rawData);
        }
Beispiel #17
0
        public User Login(string account, string password, string endpoint, Dictionary <string, string> properties, out string ticket)
        {
            ticket = null;
            if (string.IsNullOrEmpty(account) || string.IsNullOrEmpty(password))
            {
                return(null);
            }
            //账号不区分大小写
            account = account.ToUpper();
            //获取服务端加密后的密码
            string   encryptedPassword = SHA1Helper.SHA1(password);
            ISession session           = DBOperator.Instance.GetCurrentSession();
            User     user = session.Query <User>()
                            .Where(p => p.Account.ToUpper() == account && p.Password == encryptedPassword)
                            .SingleOrDefault();

            if (user == null)
            {
                //用户名或密码错误,登录失败
                return(null);
            }

            //客户端为每个用户创建一个票据,而移动端为每个设备创建一个票据
            //创建身份票据
            ticket = WebRequestContext.Current().CreateTicket();



            //url权限、菜单权限(node端使用)
            //操作权限(调用服务方法时使用)

            //设置当前登录系统的终端类型
            Session[LilacRequestContext.EndpointKey] = endpoint;

            //设置当前登录用户信息
            this.CurrentUser = new UserInfo()
            {
                UserID   = user.ID,
                UserName = user.Name,
            };
            return(user.UnWrapNHibernateClass());
        }
Beispiel #18
0
        public static async Task <TOut> RequestAsync <TOut>(WebRequestContext requestContext, string token = "")
        {
            var endPointAddr = new Url(requestContext.BaseUrl ?? "").AppendPathSegment(requestContext.ServiceUrl ?? "");
            var flurlRequest = new FlurlClient(endPointAddr).Request();

            //if (headers != null && headers.Length > 0)
            //{
            //    foreach (var (name, value) in headers)
            //    {
            //        flurlRequest.WithHeader(name, value);
            //    }
            //}

            flurlRequest.WithOAuthBearerToken(token);

            var convertedSegments = ConvertSegments(requestContext.SegmentGroup, requestContext.SegmentData);

            flurlRequest.AppendPathSegments(convertedSegments);

            List <(string, string)> convertedParams = ConvertQueryParams(requestContext.QueryParamGroup, requestContext.QueryParamData);

            foreach (var(name, value) in convertedParams)
            {
                flurlRequest.SetQueryParam(name, value);
            }

            requestContext.DataSerialize();
            if (requestContext.NeedEncrypt)
            {
                if (requestContext.PostData != null)
                {
                    requestContext.PostData = CryptoFacade.Instance.Encrypt_AES((byte[])requestContext);
                }

                return(await EncryptSendAsync <TOut>(flurlRequest, requestContext));
            }
            else
            {
                return(await SendAsync <TOut>(flurlRequest, requestContext));
            }
        }
Beispiel #19
0
 /// <inheritdoc/>
 protected override void CheckForVulnerabilities(
     WebRequestContext webRequestContext,
     TestCase testcase,
     string testedParam,
     string testValue)
 {
     if (webRequestContext.Browser.AlertMessageDisplayed.Contains(TestBaseHelper.AttackSignature))
     {
         Vulnerabilities.Enqueue(new Vulnerability
         {
             Title        = testcase.TestName,
             Level        = (int)VulnerabilityLevelEnum.High,
             TestedParam  = testedParam,
             TestedVal    = testValue,
             HttpResponse = webRequestContext.ResponseHolder,
             Evidence     = $"Found by {webRequestContext.Browser.BrowserType}",
             MatchString  = testcase.MatchString,
             TestPlugin   = GetType().Name
         });
     }
 }
Beispiel #20
0
        public static async Task <HttpResponseMessage> RequestSimpleAsync(WebRequestContext requestContext, string token = "")
        {
            var endPointAddr = new Url(requestContext.BaseUrl ?? "").AppendPathSegment(requestContext.ServiceUrl ?? "");
            var flurlRequest = new FlurlClient(endPointAddr).Request();

            flurlRequest.WithOAuthBearerToken(token);

            var convertedSegments = ConvertSegments(requestContext.SegmentGroup, requestContext.SegmentData);

            flurlRequest.AppendPathSegments(convertedSegments);

            List <(string, string)> convertedParams = ConvertQueryParams(requestContext.QueryParamGroup, requestContext.QueryParamData);

            foreach (var(name, value) in convertedParams)
            {
                flurlRequest.SetQueryParam(name, value);
            }

            requestContext.DataSerialize();
            return(await SendSimpleAsync(flurlRequest, requestContext));
        }
Beispiel #21
0
        /// <summary>
        /// Inside a test check to see if the match string gets found on the response page,regex used for
        /// matching if that is the case then log a vulnerability.
        /// </summary>
        /// <param name="webRequestContext">
        /// The web Request Context.
        /// </param>
        /// <param name="testCase">
        /// The test Case.
        /// </param>
        /// <param name="testedParam">
        /// The tested Parameter.
        /// </param>
        /// <param name="testValue">
        /// The tested Val.
        /// </param>
        /// <seealso cref="M:BackScatterScannerLib.Engine.TestBase.CheckForVuln(WebRequestContext,TestCase,string,string)"/>
        protected override void CheckForVulnerabilities(
            WebRequestContext webRequestContext,
            TestCase testCase,
            string testedParam,
            string testValue)
        {
            HttpWebResponseHolder response = webRequestContext.ResponseHolder;

            try
            {
                string[] sqlerrors =
                {
                    "sql syntax",
                    "sql error",
                    "syntax error"
                };

                var evidence =
                    sqlerrors.FirstOrDefault(
                        e => response.ResponseContent.IndexOf(e, StringComparison.InvariantCultureIgnoreCase) > -1);

                if (!string.IsNullOrEmpty(evidence) ||
                    (testCase.TestName.Equals(TimingTestCase, StringComparison.InvariantCultureIgnoreCase) &&
                     response.Latency.TotalSeconds >= BaselineLatencyInSeconds + TimeOutInSeconds + 1))
                {
                    this.AddVulnerability(
                        testCase.TestName,
                        testedParam,
                        testValue,
                        evidence ?? TimingTestCase,
                        response,
                        testCase,
                        VulnerabilityLevelEnum.High);
                }
            }
            catch (Exception ex)
            {
                Logger.WriteError(ex);
            }
        }
        private void Run(WebRequestContext context)
        {
            var response = new WebResponse(500);

            try
            {
                try
                {
                    var uri    = context.Request.Url;
                    var subUri = RemovePrefix(uri);
                    response = _handler.TryHandle(subUri, context.Request);
                }
                catch (Exception e)
                {
                    Log.ErrorFormat("Caught unexpected exception: {0}", e);
                    response = new WebResponse(500);
                }
            }
            finally
            {
                context.SetResponse(response);
            }
        }
Beispiel #23
0
 public SitecoreVisitRequestContext(WebRequestContext <SitecoreResponseInfo> visitorContext, Visit visit)
     : base(visitorContext, visit)
 {
 }
        /// <summary>
        /// Inside a test check to see if the match string gets found on the response page,regex used for
        /// matching if that is the case then log a vulnerability.
        /// </summary>
        /// <param name="webRequestContext">
        /// The web Request Context.
        /// </param>
        /// <param name="testCase">
        /// The test Case.
        /// </param>
        /// <param name="testParameter">
        /// The tested Parameter.
        /// </param>
        /// <param name="testValue">
        /// The tested Val.
        /// </param>
        /// <seealso cref="M:BackScatterScannerLib.Engine.TestBase.CheckForVuln(WebRequestContext,TestCase,string,string)"/>
        protected override void CheckForVulnerabilities(
            WebRequestContext webRequestContext,
            TestCase testCase,
            string testParameter,
            string testValue)
        {
            HttpWebResponseHolder response = webRequestContext.ResponseHolder;

            if (string.IsNullOrWhiteSpace(response.ResponseContent))
            {
                return;
            }

            string evidence = string.Empty;

            if (
                response.ResponseContent.IndexOf(
                    "[an error occurred while processing this directive]",
                    StringComparison.InvariantCultureIgnoreCase) > -1)
            {
                evidence += "[an error occurred while processing this directive]";
            }

            if (
                response.ResponseContent.IndexOf("Volume Serial Number is", StringComparison.InvariantCultureIgnoreCase) >
                -1)
            {
                evidence += "Volume Serial Number is";
            }

            if (
                response.ResponseContent.IndexOf(
                    "is not recognized as an internal or external command",
                    StringComparison.InvariantCultureIgnoreCase) > -1)
            {
                evidence += "is not recognized as an internal or external command";
            }

            if (!string.IsNullOrEmpty(evidence))
            {
                this.AddVulnerability(
                    this.Name,
                    testParameter,
                    testValue,
                    "A server-side directive was executed:" + evidence,
                    response,
                    testCase,
                    VulnerabilityLevelEnum.High);
            }

            if (
                this.includeVirtualIndicators.All(
                    t => response.ResponseContent.IndexOf(t, StringComparison.InvariantCultureIgnoreCase) > -1))
            {
                this.AddVulnerability(
                    this.Name,
                    testParameter,
                    testValue,
                    "<configuration></configuration> present",
                    response,
                    testCase,
                    VulnerabilityLevelEnum.High);
            }
        }
Beispiel #25
0
        private static async Task <HttpResponseMessage> SendSimpleAsync(IFlurlRequest flurlRequest, WebRequestContext requestContext)
        {
            HttpResponseMessage result = default;

            try
            {
                requestContext.AttemptCnt++;
                if (requestContext.MethodType == WebMethodType.GET)
                {
                    result = await flurlRequest.GetAsync();
                }
                else if (requestContext.MethodType == WebMethodType.POST)
                {
                    result = await flurlRequest.PostJsonAsync((string)requestContext);
                }
            }
            catch (FlurlHttpException flurlException)
            {
                if (flurlException.Call.Response != null &&
                    requestContext.AttemptCnt < WebConfig.ReTryCount)
                {
                    result = await SendSimpleAsync(flurlRequest, requestContext);
                }
            }
            catch (Exception)
            {
            }

            return(result);
        }
Beispiel #26
0
        private static async Task <TOut> SendAsync <TOut>(IFlurlRequest flurlRequest, WebRequestContext requestContext)
        {
            TOut result = default;

            try
            {
                requestContext.AttemptCnt++;

                if (requestContext.MethodType == WebMethodType.GET)
                {
                    if (requestContext.SerializeType == SerializeType.Json)
                    {
                        result = await flurlRequest.GetJsonAsync <TOut>();
                    }
                    else
                    {
                        var rawData = await flurlRequest.GetBytesAsync();

                        result = MessagePackSerializer.Deserialize <TOut>(rawData);
                    }
                }
                else if (requestContext.MethodType == WebMethodType.POST)
                {
                    if (requestContext.SerializeType == SerializeType.Json)
                    {
                        result = await flurlRequest
                                 .PostJsonAsync((string)requestContext)
                                 .ReceiveJson <TOut>();
                    }
                    else
                    {
                        var rawData = await flurlRequest
                                      .PostAsync(new ByteArrayContent(requestContext))
                                      .ReceiveBytes();

                        result = MessagePackSerializer.Deserialize <TOut>(rawData);
                    }
                }
            }
            catch (FlurlHttpException flurlException)
            {
                if (requestContext.AttemptCnt < WebConfig.ReTryCount)
                {
                    result = await RequestRetryPolicy <TOut>(flurlException, flurlRequest, requestContext);
                }
                else
                {
                    if (_exceptionHandler != null)
                    {
                        await _exceptionHandler.Invoke(flurlException);
                    }
                }
            }
            catch (Exception ex)
            {
                if (_exceptionHandler != null)
                {
                    await _exceptionHandler.Invoke(ex);
                }
            }

            return(result);
        }
 internal protected WebVisitRequestContext(WebRequestContext <TResponseInfo> visitorContext, Visit visit)
 {
     Visit          = visit;
     VisitorContext = visitorContext;
 }
Beispiel #28
0
        private static async Task <TOut> EncryptSendAsync <TOut>(IFlurlRequest flurlRequest, WebRequestContext requestContext)
        {
            TOut result = default;

            try
            {
                requestContext.AttemptCnt++;

                byte[] e_rawData = null;
                if (requestContext.MethodType == WebMethodType.GET)
                {
                    e_rawData = await flurlRequest.GetBytesAsync();
                }
                else if (requestContext.MethodType == WebMethodType.POST)
                {
                    e_rawData = await flurlRequest
                                .PostAsync(new ByteArrayContent(requestContext))
                                .ReceiveBytes();
                }

                var rawData = CryptoFacade.Instance.Decrypt_AES(e_rawData);
                result = MessagePackSerializer.Deserialize <TOut>(rawData);
            }
            catch (FlurlHttpException flurlException)
            {
                if (requestContext.AttemptCnt < WebConfig.ReTryCount)
                {
                    result = await RequestRetryPolicy <TOut>(flurlException, flurlRequest, requestContext);
                }
                else
                {
                    if (_exceptionHandler != null)
                    {
                        await _exceptionHandler.Invoke(flurlException);
                    }
                }
            }
            catch (CryptographicException cryptoEx)
            {
                if (requestContext.AttemptCnt < WebConfig.ReTryCount)
                {
                    result = await EncryptSendAsync <TOut>(flurlRequest, requestContext);
                }
                else
                {
                    if (_exceptionHandler != null)
                    {
                        await _exceptionHandler.Invoke(cryptoEx);
                    }
                }
            }
            catch (Exception ex)
            {
                if (_exceptionHandler != null)
                {
                    await _exceptionHandler.Invoke(ex);
                }
            }

            return(result);
        }
Beispiel #29
0
        private static async Task <byte[]> RequestRetryPolicy(FlurlHttpException flurlException, IFlurlRequest flurlRequest, WebRequestContext requestContext)
        {
            byte[] result = default;

            if (flurlException.Call.Response != null &&
                flurlException.Call.Response.StatusCode == System.Net.HttpStatusCode.ServiceUnavailable)
            {
                _exceptionHandler?.Invoke(flurlException);
            }
            else if (flurlException.Call.Response != null)// 재시도
            {
                result = await SendAsync(flurlRequest, requestContext);
            }

            return(result);
        }
Beispiel #30
0
        /// <summary>
        /// Executes the tests.
        /// </summary>
        /// <seealso cref="M:BackScatterScannerLib.Engine.TestBase.DoTests()"/>
        public override void DoTests()
        {
            var newUrlCrossDomain = TestTarget.Uri.GetLeftPart(UriPartial.Authority) + "/" + "crossdomain.xml";

            WebRequestContext webRequestContext =
                Context.SendRequest(new ContextSendRequestParameter {
                Url = newUrlCrossDomain, AllowRedirect = false
            });

            HttpWebResponseHolder responseDomain = webRequestContext.ResponseHolder;

            if (string.IsNullOrEmpty(responseDomain.ResponseContent) || responseDomain.StatusCode != HttpStatusCode.OK)
            {
                Context.ReleaseBrowser(webRequestContext.Browser);
                return;
            }

            try
            {
                var root = XElement.Parse(responseDomain.ResponseContent);

                // Check CrossDomain.xml should not contain a global wild-card character.
                var badDomains =
                    root.Descendants()
                    .Where(e => e.Attribute("domain") != null && e.Attribute("domain").Value == "*");
                foreach (var e in badDomains)
                {
                    this.AddVulnerability(
                        "Trust of all domains",
                        string.Empty,
                        string.Empty,
                        e.ToString(),
                        responseDomain,
                        null,
                        VulnerabilityLevelEnum.High);
                }

                // Check if CrossDomain.xml contains the secured=true attribute
                var insecure =
                    root.Descendants()
                    .Where(
                        e =>
                        e.Attribute("secure") != null &&
                        e.Attribute("secure")
                        .Value.Equals("false", StringComparison.InvariantCultureIgnoreCase));

                foreach (var e in insecure)
                {
                    this.AddVulnerability(
                        "Insecure trust with a domain",
                        string.Empty,
                        string.Empty,
                        e.ToString(),
                        responseDomain,
                        null,
                        VulnerabilityLevelEnum.High);
                }
            }
            catch (XmlException ex)
            {
                Logger.WriteWarning(ex);
            }
            finally
            {
                Context.ReleaseBrowser(webRequestContext.Browser);
            }
        }