Ejemplo n.º 1
0
        //internal object _GetTransportContext()
        //{
        //    if (base._httpsStream != null)
        //    {
        //        return base._httpsStream.get_TransportContext();
        //    }
        //    return null;
        //}

        private X509Certificate AttachClientCertificate(Session oS, object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers)
        {
            if (localCertificates.Count > 0)
            {
                this.MarkAsAuthenticated(oS.LocalProcessID);
                oS.oFlags["x-client-cert"] = localCertificates[0].Subject + " Serial#" + localCertificates[0].GetSerialNumberString();
                return(localCertificates[0]);
            }
            if ((remoteCertificate != null) || (acceptableIssuers.Length >= 1))
            {
                X509Certificate certificate = this._GetDefaultCertificate();
                if (certificate != null)
                {
                    this.MarkAsAuthenticated(oS.LocalProcessID);
                    oS.oFlags["x-client-cert"] = certificate.Subject + " Serial#" + certificate.GetSerialNumberString();
                    return(certificate);
                }
                if (Browser.bShowDefaultClientCertificateNeededPrompt && SDVPApplication.Prefs.GetBoolPref("SDVP.network.https.clientcertificate.ephemeral.prompt-for-missing", true))
                {
                    SDVPApplication.DoNotifyUser("The server [" + targetHost + "] requests a client certificate.\nPlease save a client certificate using the filename:\n\n" + Browser.GetPath("DefaultClientCertificate"), "Client Certificate Requested");
                    SDVPApplication.Prefs.SetBoolPref("SDVP.network.https.clientcertificate.ephemeral.prompt-for-missing", false);
                }
            }
            return(null);
        }
Ejemplo n.º 2
0
        private bool HeadersAvailable()
        {
            if (this.iEntityBodyOffset <= 0)
            {
                HTTPHeaderParseWarnings warnings;
                if (this.m_responseData == null)
                {
                    return(false);
                }
                if (!Parser.FindEndOfHeaders(this.m_responseData.GetBuffer(), ref this._iBodySeekProgress, this.m_responseData.Length, out warnings))
                {
                    return(false);
                }
                this.iEntityBodyOffset = this._iBodySeekProgress + 1;
                switch (warnings)
                {
                case HTTPHeaderParseWarnings.EndedWithLFLF:
                    SDVPApplication.HandleHTTPError(this.m_session, SessionFlags.ProtocolViolationInResponse, false, true, "The Server did not return properly formatted HTTP Headers. HTTP headers\nshould be terminated with CRLFCRLF. These were terminated with LFLF.");
                    break;

                case HTTPHeaderParseWarnings.EndedWithLFCRLF:
                    SDVPApplication.HandleHTTPError(this.m_session, SessionFlags.ProtocolViolationInResponse, false, true, "The Server did not return properly formatted HTTP Headers. HTTP headers\nshould be terminated with CRLFCRLF. These were terminated with LFCRLF.");
                    break;
                }
            }
            return(true);
        }
Ejemplo n.º 3
0
 internal bool Attach(bool bCollectGWInfo)
 {
     if (!this._bIsAttached)
     {
         if (bCollectGWInfo)
         {
             this.CollectConnectoidAndGatewayInfo();
         }
         WinINETProxyInfo oNewInfo = new WinINETProxyInfo();
         oNewInfo.bUseManualProxies = true;
         oNewInfo.bAllowDirect      = true;
         oNewInfo.sHttpProxy        = Browser.sSDVPListenHostPort;
         if (Browser.bCaptureCONNECT)
         {
             oNewInfo.sHttpsProxy = Browser.sSDVPListenHostPort;
         }
         else if (this.piPrior != null)
         {
             oNewInfo.sHttpsProxy = this.piPrior.sHttpsProxy;
         }
         if ((this.piPrior != null) && this.piPrior.bUseManualProxies)
         {
             oNewInfo.sFtpProxy   = this.piPrior.sFtpProxy;
             oNewInfo.sSocksProxy = this.piPrior.sSocksProxy;
         }
         if (Browser.bCaptureFTP)
         {
             oNewInfo.sFtpProxy = Browser.sSDVPListenHostPort;
         }
         oNewInfo.sHostsThatBypass = Browser.sHostsThatBypassSDVP;
         if (Browser.bHookWithPAC)
         {
             if (SDVPApplication.Prefs.GetBoolPref("SDVP.proxy.pacfile.usefileprotocol", true))
             {
                 oNewInfo.sPACScriptLocation = "file://" + Browser.GetPath("Pac");
             }
             else
             {
                 oNewInfo.sPACScriptLocation = "http://" + Browser.sSDVPListenHostPort + "/proxy.pac";
             }
         }
         if (!Browser.bIsViewOnly)
         {
             if (this.oAllConnectoids.HookConnections(oNewInfo))
             {
                 this._bIsAttached = true;
                 SDVPApplication.OnSDVPAttach();
                 this.WriteAutoProxyPACFile(true);
             }
             else
             {
                 SDVPApplication.DoNotifyUser("Failed to register SDVP as the system proxy.", "Error");
                 _setDynamicRegistryKey(false);
                 return(false);
             }
             _setDynamicRegistryKey(true);
         }
     }
     return(true);
 }
Ejemplo n.º 4
0
 private bool isRequestComplete()
 {
     if (this.m_headers == null)
     {
         if (!this.HeadersAvailable())
         {
             return(false);
         }
         if (!this.ParseRequestForHeaders())
         {
             string str;
             if (this.m_requestData != null)
             {
                 str = Utilities.ByteArrayToHexView(this.m_requestData.GetBuffer(), 0x18, (int)Math.Min(this.m_requestData.Length, 0x800L));
             }
             else
             {
                 str = "{Web Browser:no data}";
             }
             if (this.m_headers == null)
             {
                 this.m_headers             = new HTTPRequestHeaders();
                 this.m_headers.HTTPMethod  = "BAD";
                 this.m_headers["Host"]     = "BAD-REQUEST";
                 this.m_headers.RequestPath = "/BAD_REQUEST";
             }
             this.FailSession(400, "Web Browser - Bad Request", "[Web Browser] Request Header parsing failed. Request was:\n" + str);
             return(true);
         }
         this.m_session.Timers.SDVPGotRequestHeaders = DateTime.Now;
         this.m_session._AssignID();
         SDVPApplication.DoRequestHeadersAvailable(this.m_session);
     }
     if (this.m_headers.ExistsAndEquals("Transfer-encoding", "chunked"))
     {
         long num;
         long num2;
         return(Utilities.IsChunkedBodyComplete(this.m_session, this.m_requestData, (long)this.iEntityBodyOffset, out num2, out num));
     }
     if (this.m_headers.Exists("Content-Length"))
     {
         long result = 0L;
         try
         {
             if (!long.TryParse(this.m_headers["Content-Length"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out result) || (result < 0L))
             {
                 SDVPApplication.HandleHTTPError(this.m_session, SessionFlags.ProtocolViolationInRequest, true, true, "Request content length was invalid.\nContent-Length: " + this.m_headers["Content-Length"]);
                 this.FailSession(400, "Web Browser - Bad Request", "[Web Browser] Request Content-Length header parsing failed.\nContent-Length: " + this.m_headers["Content-Length"]);
                 return(true);
             }
             return(this.m_requestData.Length >= (this.iEntityBodyOffset + result));
         }
         catch
         {
             this.FailSession(400, "Web Browser - Bad Request", "[Web Browser] Unknown error: Check content length header?");
             return(false);
         }
     }
     return(true);
 }
Ejemplo n.º 5
0
        internal bool SecureExistingConnection(Session oS, string sCertCN, string sClientCertificateFilename, string sPoolingKey, ref int iHandshakeTime)
        {
            RemoteCertificateValidationCallback userCertificateValidationCallback = null;
            LocalCertificateSelectionCallback   userCertificateSelectionCallback  = null;
            Stopwatch stopwatch = Stopwatch.StartNew();

            try
            {
                this.sPoolKey = sPoolingKey;
                X509CertificateCollection certificateCollectionFromFile = this.GetCertificateCollectionFromFile(sClientCertificateFilename);
                if (userCertificateValidationCallback == null)
                {
                    userCertificateValidationCallback = delegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) {
                        return(ConfirmServerCertificate(oS, sCertCN, certificate, chain, sslPolicyErrors));
                    };
                }
                if (userCertificateSelectionCallback == null)
                {
                    userCertificateSelectionCallback = delegate(object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers) {
                        return(this.AttachClientCertificate(oS, sender, targetHost, localCertificates, remoteCertificate, acceptableIssuers));
                    };
                }
                base._httpsStream = new SslStream(new NetworkStream(base._baseSocket, false), false, userCertificateValidationCallback, userCertificateSelectionCallback);
                base._httpsStream.AuthenticateAsClient(sCertCN, certificateCollectionFromFile, Browser.oAcceptedServerHTTPSProtocols, SDVPApplication.Prefs.GetBoolPref("SDVP.https.checkcertificaterevocation", false));
                iHandshakeTime = (int)stopwatch.ElapsedMilliseconds;
            }
            catch (Exception exception)
            {
                iHandshakeTime = (int)stopwatch.ElapsedMilliseconds;
                SDVPApplication.DebugSpew(exception.StackTrace + "\n" + exception.Message);
                return(false);
            }
            return(true);
        }
Ejemplo n.º 6
0
        internal bool ResendRequest()
        {
            bool b = this.pipeServer != null;

            if (!this.ConnectToHost())
            {
                SDVPApplication.DebugSpew("ConnectToHost returned null. Bailing...");
                this.m_session.SetBitFlag(SessionFlags.ServerPipeReused, b);
                return(false);
            }
            try
            {
                this.pipeServer.IncrementUse(this.m_session.id);
                this.m_session.Timers.ServerConnected = this.pipeServer.dtConnected;
                this._bWasForwarded = this.pipeServer.isConnectedToGateway;
                this.m_session.SetBitFlag(SessionFlags.ServerPipeReused, this.pipeServer.iUseCount > 1);
                this.m_session.SetBitFlag(SessionFlags.SentToGateway, this._bWasForwarded);
                if (!this._bWasForwarded && !this.m_session.isHTTPS)
                {
                    this.m_session.oRequest.headers.RenameHeaderItems("Proxy-Connection", "Connection");
                }
                if (!this.pipeServer.isAuthenticated)
                {
                    string str = this.m_session.oRequest.headers["Authorization"];
                    if ((str != null) && str.StartsWith("N"))
                    {
                        this.pipeServer.MarkAsAuthenticated(this.m_session.LocalProcessID);
                    }
                }
                this.m_session.Timers.SDVPBeginRequest = DateTime.Now;
                if (this.m_session.oFlags.ContainsKey("request-trickle-delay"))
                {
                    int num = int.Parse(this.m_session.oFlags["request-trickle-delay"]);
                    this.pipeServer.TransmitDelay = num;
                }
                this.pipeServer.Send(this.m_session.oRequest.headers.ToByteArray(true, true, this._bWasForwarded && !this.m_session.isHTTPS));
                this.pipeServer.Send(this.m_session.requestBodyBytes);
            }
            catch (Exception exception)
            {
                if (this.bServerSocketReused && (this.m_session.state != SessionStates.Aborted))
                {
                    this.pipeServer = null;
                    return(this.ResendRequest());
                }
                SDVPApplication.DebugSpew("ResendRequest() failed: " + Utilities.DescribeException(exception));
                this.m_session.oRequest.FailSession(0x1f8, "Web Browser - Send Failure", "ResendRequest() failed: " + Utilities.DescribeException(exception));
                return(false);
            }
            this.m_session.oFlags["x-EgressPort"] = this.pipeServer.LocalPort.ToString();
            if (this.m_session.oFlags.ContainsKey("log-drop-request-body"))
            {
                this.m_session.oFlags["x-RequestBodyLength"] = (this.m_session.requestBodyBytes != null) ? this.m_session.requestBodyBytes.Length.ToString() : "0";
                this.m_session.requestBodyBytes = new byte[0];
            }
            return(true);
        }
Ejemplo n.º 7
0
 private bool GetHeaders()
 {
     if (!this.HeadersAvailable())
     {
         return(false);
     }
     if (!this.ParseResponseForHeaders())
     {
         string str;
         this.m_session.SetBitFlag(SessionFlags.ProtocolViolationInResponse, true);
         this._PoisonPipe();
         if (this.m_responseData != null)
         {
             str = "<plaintext>\n" + Utilities.ByteArrayToHexView(this.m_responseData.GetBuffer(), 0x18, (int)Math.Min(this.m_responseData.Length, 0x800L));
         }
         else
         {
             str = "{Web Browser:no data}";
         }
         this.m_session.oRequest.FailSession(500, "Web Browser - Bad Response", string.Format("[Web Browser] Response Header parsing failed.\n{0}Response Data:\n{1}", this.m_session.isFlagSet(SessionFlags.ServerPipeReused) ? "This can be caused by an illegal HTTP response earlier on this reused server socket-- for instance, a HTTP/304 response which illegally contains a body.\n" : string.Empty, str));
         return(true);
     }
     if ((this.m_inHeaders.HTTPResponseCode <= 0x63) || (this.m_inHeaders.HTTPResponseCode >= 200))
     {
         return(true);
     }
     if (this.m_inHeaders.Exists("Content-Length") && ("0" != this.m_inHeaders["Content-Length"].Trim()))
     {
         SDVPApplication.HandleHTTPError(this.m_session, SessionFlags.ProtocolViolationInResponse, false, true, "HTTP/1xx responses MUST NOT contain a body, but a non-zero content-length was returned.");
     }
     if (SDVPApplication.Prefs.GetBoolPref("SDVP.network.streaming.leakhttp1xx", true) && (this.m_session.oRequest.pipeClient != null))
     {
         try
         {
             StringDictionary dictionary;
             this.m_session.oRequest.pipeClient.Send(this.m_inHeaders.ToByteArray(true, true));
             (dictionary = this.m_session.oFlags)["x-SDVP-Stream1xx"] = dictionary["x-SDVP-Stream1xx"] + "Returned a HTTP/" + this.m_inHeaders.HTTPResponseCode.ToString() + " message from the server.";
         }
         catch (Exception exception)
         {
             if (SDVPApplication.Prefs.GetBoolPref("SDVP.network.streaming.abortifclientaborts", false))
             {
                 throw new Exception("Leaking HTTP/1xx response to client failed", exception);
             }
         }
     }
     else
     {
         StringDictionary dictionary2;
         (dictionary2 = this.m_session.oFlags)["x-SDVP-streaming"] = dictionary2["x-SDVP-streaming"] + "Eating a HTTP/" + this.m_inHeaders.HTTPResponseCode.ToString() + " message from the stream.";
     }
     this._deleteInformationalMessage();
     return(this.GetHeaders());
 }
Ejemplo n.º 8
0
        internal bool SecureClientPipe(string sHostname, HTTPResponseHeaders oHeaders)
        {
            X509Certificate2 certificate;

            try
            {
                certificate = CertMaker.FindCert(sHostname, true);
            }
            catch (Exception exception)
            {
                //SDVPApplication.Log.LogFormat("SDVP.https> Failed to obtain certificate for {0} due to {1}", new object[] { sHostname, exception.Message });
                certificate = null;
            }
            try
            {
                if (certificate == null)
                {
                    SDVPApplication.DoNotifyUser("Unable to find Certificate for " + sHostname, "HTTPS Interception Failure");
                    oHeaders.HTTPResponseCode   = 0x1f6;
                    oHeaders.HTTPResponseStatus = "502 SDVP unable to generate certificate";
                }
                if (Browser.bDebugSpew)
                {
                    SDVPApplication.DebugSpew("SecureClientPipe for: " + this.ToString() + " sending data to client:\n" + Utilities.ByteArrayToHexView(oHeaders.ToByteArray(true, true), 0x20));
                }
                base.Send(oHeaders.ToByteArray(true, true));
                if (oHeaders.HTTPResponseCode != 200)
                {
                    SDVPApplication.DebugSpew("SecureClientPipe returning FALSE because HTTPResponseCode != 200");
                    return(false);
                }
                base._httpsStream = new SslStream(new NetworkStream(base._baseSocket, false), false);
                base._httpsStream.AuthenticateAsServer(certificate, _bWantClientCert, Browser.oAcceptedClientHTTPSProtocols, false);
                return(true);
            }
            catch (Exception exception2)
            {
                //SDVPApplication.Log.LogFormat("Secure client pipe failed: {0}{1}.", new object[] { exception2.Message, (exception2.InnerException == null) ? string.Empty : (" InnerException: " + exception2.InnerException.Message) });
                SDVPApplication.DebugSpew("Secure client pipe failed: " + exception2.Message);
                try
                {
                    base.End();
                }
                catch (Exception)
                {
                }
            }
            return(false);
        }
Ejemplo n.º 9
0
        internal byte[] TakeEntity()
        {
            byte[] bytes;
            if (this.iEntityBodyOffset < 0)
            {
                throw new InvalidDataException("Request Entity Body Offset must not be negative");
            }
            long num  = this.m_requestData.Length - this.iEntityBodyOffset;
            long num2 = this._calculateExpectedEntityTransferSize();

            if (num > num2)
            {
                //SDVPApplication.Log.LogFormat("HTTP Pipelining Client detected; excess data on client socket for session #{0}.", new object[] { this.m_session.id });
                try
                {
                    bytes = new byte[num - num2];
                    this.m_requestData.Position = this.iEntityBodyOffset + num2;
                    this.m_requestData.Read(bytes, 0, bytes.Length);
                }
                catch (OutOfMemoryException exception)
                {
                    SDVPApplication.ReportException(exception, "HTTP Request Pipeline Too Large");
                    bytes = Encoding.ASCII.GetBytes("Web Browser: Out of memory");
                    this.m_session.PoisonClientPipe();
                    return(new byte[0]);
                }
                this.pipeClient.putBackSomeBytes(bytes);
                num = num2;
            }
            if ((num != num2) && (num < num2))
            {
                SDVPApplication.HandleHTTPError(this.m_session, SessionFlags.ProtocolViolationInRequest, true, true, string.Format("Content-Length mismatch: Request Header indicated {0:N0} bytes, but client sent {1:N0} bytes.", num2, num));
            }
            try
            {
                bytes = new byte[num];
                this.m_requestData.Position = this.iEntityBodyOffset;
                this.m_requestData.Read(bytes, 0, bytes.Length);
            }
            catch (OutOfMemoryException exception2)
            {
                SDVPApplication.ReportException(exception2, "HTTP Request Too Large");
                bytes = Encoding.ASCII.GetBytes("Web Browser: Out of memory");
                this.m_session.PoisonClientPipe();
            }
            this._freeRequestData();
            return(bytes);
        }
Ejemplo n.º 10
0
 private void ScanPathForTranscoders(string sPath)
 {
     try
     {
         if (Directory.Exists(sPath))
         {
             Evidence securityEvidence = Assembly.GetExecutingAssembly().Evidence;
             bool     boolPref         = SDVPApplication.Prefs.GetBoolPref("SDVP.debug.extensions.verbose", false);
             if (boolPref)
             {
                 //SDVPApplication.Log.LogFormat("Searching for Transcoders under {0}", new object[] { sPath });
             }
             foreach (FileInfo info in new DirectoryInfo(sPath).GetFiles())
             {
                 if (info.FullName.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) && !info.FullName.StartsWith("_", StringComparison.OrdinalIgnoreCase))
                 {
                     Assembly assembly;
                     if (boolPref)
                     {
                         //SDVPApplication.Log.LogFormat("Looking for Transcoders inside {0}", new object[] { info.FullName.ToString() });
                     }
                     try
                     {
                         if (Browser.bRunningOnCLRv4)
                         {
                             assembly = Assembly.LoadFrom(info.FullName);
                         }
                         else
                         {
                             assembly = Assembly.LoadFrom(info.FullName, securityEvidence);
                         }
                     }
                     catch (Exception exception)
                     {
                         SDVPApplication.LogAddonException(exception, "Failed to load " + info.FullName);
                         continue;
                     }
                     this.ScanAssemblyForTranscoders(assembly);
                 }
             }
         }
     }
     catch (Exception exception2)
     {
         SDVPApplication.DoNotifyUser(string.Format("[Web Browser] Failure loading Transcoders: {0}", exception2.Message), "Transcoders Load Error");
     }
 }
Ejemplo n.º 11
0
        private void _NotifyThreadExecute(object objThreadState)
        {
            PrefChangeEventArgs e = (PrefChangeEventArgs)objThreadState;
            string prefName       = e.PrefName;
            List <EventHandler <PrefChangeEventArgs> > list = null;

            try
            {
                GetReaderLock(this._RWLockWatchers);
                try
                {
                    foreach (PrefWatcher watcher in this._listWatchers)
                    {
                        if (prefName.StartsWith(watcher.sPrefixToWatch, StringComparison.Ordinal))
                        {
                            if (list == null)
                            {
                                list = new List <EventHandler <PrefChangeEventArgs> >();
                            }
                            list.Add(watcher.fnToNotify);
                        }
                    }
                }
                finally
                {
                    FreeReaderLock(this._RWLockWatchers);
                }
                if (list != null)
                {
                    foreach (EventHandler <PrefChangeEventArgs> handler in list)
                    {
                        try
                        {
                            handler(this, e);
                        }
                        catch (Exception exception)
                        {
                            SDVPApplication.ReportException(exception);
                        }
                    }
                }
            }
            catch (Exception exception2)
            {
                SDVPApplication.ReportException(exception2);
            }
        }
Ejemplo n.º 12
0
 internal byte[] TakeEntity()
 {
     byte[] bytes;
     try
     {
         bytes = new byte[this.m_responseData.Length - this.iEntityBodyOffset];
         this.m_responseData.Position = this.iEntityBodyOffset;
         this.m_responseData.Read(bytes, 0, bytes.Length);
     }
     catch (OutOfMemoryException exception)
     {
         SDVPApplication.ReportException(exception, "HTTP Response Too Large");
         bytes = Encoding.ASCII.GetBytes("Web Browser: Out of memory");
         this.m_session.PoisonServerPipe();
     }
     this.FreeResponseDataBuffer();
     return(bytes);
 }
Ejemplo n.º 13
0
 internal static bool exportRootToDesktop()
 {
     try
     {
         byte[] bytes = getRootCertBytes();
         if (bytes != null)
         {
             File.WriteAllBytes(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + @"\ASRoot.cer", bytes);
             return(true);
         }
     }
     catch (Exception exception)
     {
         SDVPApplication.ReportException(exception);
         return(false);
     }
     return(false);
 }
Ejemplo n.º 14
0
 public void FailSession(int iError, string sErrorStatusText, string sErrorBody)
 {
     this.m_session.SetBitFlag(SessionFlags.ResponseGeneratedBySDVP, true);
     if ((iError >= 400) && (sErrorBody.Length < 0x200))
     {
         sErrorBody = sErrorBody.PadRight(0x200, ' ');
     }
     this.m_session.responseBodyBytes = Encoding.UTF8.GetBytes(sErrorBody);
     this.m_session.oResponse.headers = new HTTPResponseHeaders(Browser.oHeaderEncoding);
     this.m_session.oResponse.headers.HTTPResponseCode   = iError;
     this.m_session.oResponse.headers.HTTPResponseStatus = iError.ToString() + " " + sErrorStatusText;
     this.m_session.oResponse.headers.Add("Content-Type", "text/html; charset=UTF-8");
     this.m_session.oResponse.headers.Add("Connection", "close");
     this.m_session.oResponse.headers.Add("Timestamp", DateTime.Now.ToString("HH:mm:ss.fff"));
     this.m_session.state = SessionStates.Aborted;
     SDVPApplication.DoBeforeReturningError(this.m_session);
     this.m_session.ReturnResponse(false);
 }
Ejemplo n.º 15
0
 private bool isResponseBodyComplete()
 {
     if (this.m_session.HTTPMethodIs("HEAD"))
     {
         return(true);
     }
     if (this.m_session.HTTPMethodIs("CONNECT") && (this.m_inHeaders.HTTPResponseCode == 200))
     {
         return(true);
     }
     if (((this.m_inHeaders.HTTPResponseCode == 0xcc) || (this.m_inHeaders.HTTPResponseCode == 0xcd)) || (this.m_inHeaders.HTTPResponseCode == 0x130))
     {
         if (this.m_inHeaders.Exists("Content-Length") && ("0" != this.m_inHeaders["Content-Length"].Trim()))
         {
             SDVPApplication.HandleHTTPError(this.m_session, SessionFlags.ProtocolViolationInResponse, false, true, "This type of HTTP response MUST NOT contain a body, but a non-zero content-length was returned.");
             return(true);
         }
         return(true);
     }
     if (this.m_inHeaders.ExistsAndEquals("Transfer-Encoding", "chunked"))
     {
         long num;
         if (this._lngLastChunkInfoOffset < this.iEntityBodyOffset)
         {
             this._lngLastChunkInfoOffset = this.iEntityBodyOffset;
         }
         return(Utilities.IsChunkedBodyComplete(this.m_session, this.m_responseData, this._lngLastChunkInfoOffset, out this._lngLastChunkInfoOffset, out num));
     }
     if (this.m_inHeaders.Exists("Content-Length"))
     {
         long num2;
         if (long.TryParse(this.m_inHeaders["Content-Length"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out num2) && (num2 >= 0L))
         {
             return(this.m_responseTotalDataCount >= (this.iEntityBodyOffset + num2));
         }
         SDVPApplication.HandleHTTPError(this.m_session, SessionFlags.ProtocolViolationInResponse, true, true, "Content-Length response header is not a valid unsigned integer.\nContent-Length: " + this.m_inHeaders["Content-Length"]);
         return(true);
     }
     if ((!this.m_inHeaders.ExistsAndEquals("Connection", "close") && !this.m_inHeaders.ExistsAndEquals("Proxy-Connection", "close")) && ((this.m_inHeaders.HTTPVersion == "HTTP/1.1") || this.m_inHeaders.ExistsAndContains("Connection", "Keep-Alive")))
     {
         SDVPApplication.HandleHTTPError(this.m_session, SessionFlags.ProtocolViolationInResponse, true, true, "No Connection: close, no Content-Length. No way to tell if the response is complete.");
     }
     return(false);
 }
Ejemplo n.º 16
0
        private static bool ConfirmServerCertificate(Session oS, string sExpectedCN, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            CertificateValidity oValidity = CertificateValidity.Default;

            SDVPApplication.CheckOverrideCertificatePolicy(oS, sExpectedCN, certificate, chain, sslPolicyErrors, ref oValidity);
            switch (oValidity)
            {
            case CertificateValidity.ForceInvalid:
                return(false);

            case CertificateValidity.ForceValid:
                return(true);
            }
            if ((oValidity == CertificateValidity.ConfirmWithUser) || ((sslPolicyErrors != SslPolicyErrors.None) && !Browser.IgnoreServerCertErrors))
            {
                return(false);
            }
            return(true);
        }
Ejemplo n.º 17
0
 public bool Detach()
 {
     if (!this._bIsAttached)
     {
         return(true);
     }
     if (Browser.bIsViewOnly)
     {
         return(true);
     }
     _setDynamicRegistryKey(false);
     if (this.oAllConnectoids.UnhookAllConnections())
     {
         this._bIsAttached = false;
         SDVPApplication.OnSDVPDetach();
         this.WriteAutoProxyPACFile(false);
         return(true);
     }
     return(false);
 }
Ejemplo n.º 18
0
 private void NetworkChange_NetworkAddressChanged(object sender, EventArgs e)
 {
     try
     {
         DNSResolver.ClearCache();
         //SDVPApplication.Log.LogString("NetworkAddressChanged.");
         if (this.oAutoProxy != null)
         {
             this.oAutoProxy.iAutoProxySuccessCount = 0;
         }
         if ((Browser.bForwardToGateway && (this.piPrior != null)) && this.piPrior.bUseManualProxies)
         {
             this._DetermineGatewayIPEndPoints();
         }
     }
     catch (Exception exception)
     {
         SDVPApplication.ReportException(exception);
     }
 }
Ejemplo n.º 19
0
 private void RunTunnel()
 {
     if (SDVPApplication.oProxy != null)
     {
         try
         {
             IPEndPoint ipepForwardHTTPS = null;
             if (this._mySession.oFlags["x-overrideGateway"] != null)
             {
                 if (string.Equals("DIRECT", this._mySession.oFlags["x-overrideGateway"], StringComparison.OrdinalIgnoreCase))
                 {
                     this._mySession.bypassGateway = true;
                 }
                 else
                 {
                     ipepForwardHTTPS = Utilities.IPEndPointFromHostPortString(this._mySession.oFlags["x-overrideGateway"]);
                 }
             }
             else if (!this._mySession.bypassGateway)
             {
                 int tickCount = Environment.TickCount;
                 ipepForwardHTTPS = SDVPApplication.oProxy.FindGatewayForOrigin("https", this._mySession.oFlags["x-overrideHost"] ?? this._mySession.PathAndQuery);
                 this._mySession.Timers.GatewayDeterminationTime = Environment.TickCount - tickCount;
             }
             if (ipepForwardHTTPS != null)
             {
                 this.TunnelToGateway(ipepForwardHTTPS);
             }
             else
             {
                 this.TunnelDirectly();
             }
         }
         catch (Exception exception)
         {
             SDVPApplication.ReportException(exception, "Uncaught Exception in Tunnel; Session #" + this._mySession.id.ToString());
         }
     }
 }
Ejemplo n.º 20
0
 internal bool SecureClientPipeDirect(X509Certificate2 certServer)
 {
     try
     {
         base._httpsStream = new SslStream(new NetworkStream(base._baseSocket, false), false);
         base._httpsStream.AuthenticateAsServer(certServer, _bWantClientCert, Browser.oAcceptedClientHTTPSProtocols, false);
         return(true);
     }
     catch (Exception exception)
     {
         //SDVPApplication.Log.LogFormat("Secure client pipe failed: {0}{1}.", new object[] { exception.Message, (exception.InnerException == null) ? string.Empty : (" InnerException: " + exception.InnerException.Message) });
         SDVPApplication.DebugSpew("Secure client pipe failed: " + exception.Message);
         try
         {
             base.End();
         }
         catch (Exception)
         {
         }
     }
     return(false);
 }
Ejemplo n.º 21
0
        private static void VistaClearTracks(bool bClearFiles, bool bClearCookies)
        {
            int num = 0;

            if (bClearCookies)
            {
                num = 2;
            }
            if (bClearFiles)
            {
                num = 0x100c;
            }
            try
            {
                using (Process.Start("rundll32.exe", "inetcpl.cpl,ClearMyTracksByProcess " + num.ToString()))
                {
                }
            }
            catch (Exception exception)
            {
                SDVPApplication.DoNotifyUser("Failed to launch ClearMyTracksByProcess.\n" + exception.Message, "Error");
            }
        }
Ejemplo n.º 22
0
 private void _indicateTunnelFailure(int iResponseCode, string sErr)
 {
     try
     {
         this._mySession.oResponse.headers                    = new HTTPResponseHeaders();
         this._mySession.oResponse.headers.HTTPVersion        = this._mySession.oRequest.headers.HTTPVersion;
         this._mySession.oResponse.headers.HTTPResponseCode   = iResponseCode;
         this._mySession.oResponse.headers.HTTPResponseStatus = (iResponseCode == 0x1f6) ? "502 Gateway Connection failure" : "504 Connection Failed";
         this._mySession.oResponse.headers.Add("Connection", "close");
         this._mySession.responseBodyBytes = Encoding.UTF8.GetBytes("[Web Browser] " + this._mySession.oResponse.headers.HTTPResponseStatus + ": " + sErr + "<BR>Timestamp: " + DateTime.Now.ToString("HH:mm:ss.fff"));
         SDVPApplication.DoBeforeReturningError(this._mySession);
         this.socketClient.Send(this._mySession.oResponse.headers.ToByteArray(true, true));
         this.socketClient.Send(this._mySession.responseBodyBytes);
         this.socketClient.Shutdown(SocketShutdown.Both);
         if (this.socketRemote != null)
         {
             this.socketRemote.Close();
         }
     }
     catch (Exception)
     {
     }
 }
Ejemplo n.º 23
0
        private static ICertificateProvider LoadOverrideCertProvider()
        {
            string stringPref = SDVPApplication.Prefs.GetStringPref("SDVP.certmaker.assembly", Browser.GetPath("App") + "CertMaker.dll");

            if (File.Exists(stringPref))
            {
                Assembly assembly;
                try
                {
                    assembly = Assembly.LoadFrom(stringPref);
                    if (!Utilities.SDVPMeetsVersionRequirement(assembly, "Certificate Maker"))
                    {
                        return(null);
                    }
                }
                catch (Exception exception)
                {
                    SDVPApplication.LogAddonException(exception, "Failed to load CertMaker" + stringPref);
                    return(null);
                }
                foreach (Type type in assembly.GetExportedTypes())
                {
                    if ((!type.IsAbstract && type.IsPublic) && (type.IsClass && typeof(ICertificateProvider).IsAssignableFrom(type)))
                    {
                        try
                        {
                            return((ICertificateProvider)Activator.CreateInstance(type));
                        }
                        catch (Exception exception2)
                        {
                            SDVPApplication.DoNotifyUser(string.Format("[Web Browser] Failure loading {0} CertMaker from {1}: {2}\n\n{3}\n\n{4}", new object[] { type.Name, assembly.CodeBase, exception2.Message, exception2.StackTrace, exception2.InnerException }), "Load Error");
                        }
                    }
                }
            }
            return(null);
        }
Ejemplo n.º 24
0
 internal static void EnsureFoldersExist()
 {
     try
     {
         if (!Directory.Exists(GetPath("Captures")))
         {
             Directory.CreateDirectory(GetPath("Captures"));
         }
         if (!Directory.Exists(GetPath("Requests")))
         {
             Directory.CreateDirectory(GetPath("Requests"));
         }
         if (!Directory.Exists(GetPath("Responses")))
         {
             Directory.CreateDirectory(GetPath("Responses"));
         }
         if (!Directory.Exists(GetPath("Scripts")))
         {
             Directory.CreateDirectory(GetPath("Scripts"));
         }
     }
     catch (Exception exception)
     {
         SDVPApplication.DoNotifyUser(exception.ToString(), "Folder Creation Failed");
     }
     try
     {
         if ((!SDVPApplication.Prefs.GetBoolPref("SDVP.script.delaycreate", true) && !File.Exists(GetPath("CustomRules"))) && File.Exists(GetPath("SampleRules")))
         {
             File.Copy(GetPath("SampleRules"), GetPath("CustomRules"));
         }
     }
     catch (Exception exception2)
     {
         SDVPApplication.DoNotifyUser(exception2.ToString(), "Initial file copies failed");
     }
 }
Ejemplo n.º 25
0
        internal static string[] GetConnectionNames()
        {
            if (Browser.bDebugSpew)
            {
                SDVPApplication.DebugSpew("WinINET indicates connectivity is via: " + GetConnectedState());
            }
            int lpcb       = Marshal.SizeOf(typeof(RASENTRYNAME));
            int lpcEntries = 0;

            RASENTRYNAME[] lprasentryname = new RASENTRYNAME[1];
            lprasentryname[0].dwSize = lpcb;
            uint num3 = RasEnumEntries(IntPtr.Zero, IntPtr.Zero, lprasentryname, ref lpcb, ref lpcEntries);

            if ((num3 != 0) && (0x25b != num3))
            {
                lpcEntries = 0;
            }
            string[] strArray = new string[lpcEntries + 1];
            strArray[0] = "DefaultLAN";
            if (lpcEntries != 0)
            {
                lprasentryname = new RASENTRYNAME[lpcEntries];
                for (int i = 0; i < lpcEntries; i++)
                {
                    lprasentryname[i].dwSize = Marshal.SizeOf(typeof(RASENTRYNAME));
                }
                if (RasEnumEntries(IntPtr.Zero, IntPtr.Zero, lprasentryname, ref lpcb, ref lpcEntries) != 0)
                {
                    return(strArray);
                }
                for (int j = 0; j < lpcEntries; j++)
                {
                    strArray[j + 1] = lprasentryname[j].szEntryName;
                }
            }
            return(strArray);
        }
Ejemplo n.º 26
0
        internal ServerPipe DequeuePipe(string sPoolKey, int iPID, int HackiForSession)
        {
            Queue <ServerPipe> queue;
            ServerPipe         pipe;
            Queue <ServerPipe> queue2;

            if (!Browser.bReuseServerSockets)
            {
                return(null);
            }
            lock (this.thePool)
            {
                if ((((iPID == 0) || !this.thePool.TryGetValue(string.Format("PID{0}*{1}", iPID, sPoolKey), out queue)) || (queue.Count < 1)) && (!this.thePool.TryGetValue(sPoolKey, out queue) || (queue.Count < 1)))
                {
                    return(null);
                }
            }
            Monitor.Enter(queue2 = queue);
            try
            {
                if (queue.Count == 0)
                {
                    return(null);
                }
                pipe = queue.Dequeue();
            }
            catch (Exception exception)
            {
                SDVPApplication.ReportException(exception);
                return(null);
            }
            finally
            {
                Monitor.Exit(queue2);
            }
            return(pipe);
        }
Ejemplo n.º 27
0
        private X509Certificate2 CreateCert(string sHostname, bool isRoot)
        {
            int    num;
            string str;

            if (!isRoot && (this.GetRootCertificate() == null))
            {
                try
                {
                    this.oRWLock.AcquireReaderLock(-1);
                    if ((this.LoadCertificateFromWindowsStore(sMakeCertRootCN, false) == null) && !this.CreateRootCertificate())
                    {
                        SDVPApplication.DoNotifyUser("Creation of the root certificate was not successful.", "Certificate Error");
                        return(null);
                    }
                }
                finally
                {
                    this.oRWLock.ReleaseReaderLock();
                }
            }
            if (sHostname.IndexOfAny(new char[] { '"', '\r', '\n' }) != -1)
            {
                return(null);
            }
            if (!File.Exists(this._sMakeCertLocation))
            {
                SDVPApplication.DoNotifyUser("Cannot locate:\n\t\"" + this._sMakeCertLocation + "\"\n\nPlease move makecert.exe to the Fiddler installation directory.", "MakeCert.exe not found");
                throw new FileNotFoundException("Cannot locate: " + this._sMakeCertLocation + ". Please move makecert.exe to the Fiddler installation directory.");
            }
            X509Certificate2 certificate = null;
            string           sParams     = string.Format(isRoot ? sMakeCertParamsEE : sMakeCertParamsEE, new object[] { sHostname, sMakeCertSubjectO, sMakeCertRootCN, DateTime.Now.AddDays(-7.0).ToString("MM/dd/yyyy", CultureInfo.InvariantCulture) });

            try
            {
                this.oRWLock.AcquireWriterLock(-1);
                X509Certificate2 certificate2 = this.LoadCertificateFromWindowsStore(sHostname, false);
                if (certificate2 != null)
                {
                    return(certificate2);
                }
                str = Utilities.GetExecutableOutput(this._sMakeCertLocation, sParams, out num);
                if (num == 0)
                {
                    int num2 = 5;
                    do
                    {
                        certificate = this.LoadCertificateFromWindowsStore(sHostname, false);
                        Thread.Sleep((int)(50 * (5 - num2)));
                        num2--;
                    }while ((certificate == null) && (num2 >= 0));
                }
                if (certificate != null)
                {
                    if (isRoot)
                    {
                        this.certRoot = certificate;
                    }
                    else
                    {
                        this.certServerCache.Add(sHostname, certificate);
                    }
                }
            }
            finally
            {
                this.oRWLock.ReleaseWriterLock();
            }
            if (certificate == null)
            {
                string sMessage = string.Format("Creation of the interception certificate failed.\n\nmakecert.exe returned {0}.\n\n{1}", num, str);
            }
            return(certificate);
        }
Ejemplo n.º 28
0
        private bool ScanAssemblyForTranscoders(Assembly assemblyInput)
        {
            bool flag     = false;
            bool boolPref = SDVPApplication.Prefs.GetBoolPref("SDVP.debug.extensions.verbose", false);

            try
            {
                if (!Utilities.SDVPMeetsVersionRequirement(assemblyInput, "Importers and Exporters"))
                {
                    //SDVPApplication.Log.LogFormat("Assembly {0} did not specify a RequiredVersionAttribute. Aborting load of transcoders.", new object[] { assemblyInput.CodeBase });
                    return(false);
                }
                foreach (Type type in assemblyInput.GetExportedTypes())
                {
                    if ((!type.IsAbstract && type.IsPublic) && type.IsClass)
                    {
                        if (typeof(ISessionImporter).IsAssignableFrom(type))
                        {
                            try
                            {
                                if (!this.AddToImportOrExportCollection(this.m_Importers, type))
                                {
                                    //SDVPApplication.Log.LogFormat("WARNING: SessionImporter {0} from {1} failed to specify any ImportExportFormat attributes.", new object[] { type.Name, assemblyInput.CodeBase });
                                }
                                else
                                {
                                    flag = true;
                                    if (boolPref)
                                    {
                                        //SDVPApplication.Log.LogFormat("    Added SessionImporter {0}", new object[] { type.FullName });
                                    }
                                }
                            }
                            catch (Exception exception)
                            {
                                SDVPApplication.DoNotifyUser(string.Format("[Web Browser] Failure loading {0} SessionImporter from {1}: {2}\n\n{3}\n\n{4}", new object[] { type.Name, assemblyInput.CodeBase, exception.Message, exception.StackTrace, exception.InnerException }), "Extension Load Error");
                            }
                        }
                        if (typeof(ISessionExporter).IsAssignableFrom(type))
                        {
                            try
                            {
                                if (!this.AddToImportOrExportCollection(this.m_Exporters, type))
                                {
                                    //SDVPApplication.Log.LogFormat("WARNING: SessionExporter {0} from {1} failed to specify any ImportExportFormat attributes.", new object[] { type.Name, assemblyInput.CodeBase });
                                }
                                else
                                {
                                    flag = true;
                                    if (boolPref)
                                    {
                                        //SDVPApplication.Log.LogFormat("    Added SessionExporter {0}", new object[] { type.FullName });
                                    }
                                }
                            }
                            catch (Exception exception2)
                            {
                                SDVPApplication.DoNotifyUser(string.Format("[Web Browser] Failure loading {0} SessionExporter from {1}: {2}\n\n{3}\n\n{4}", new object[] { type.Name, assemblyInput.CodeBase, exception2.Message, exception2.StackTrace, exception2.InnerException }), "Extension Load Error");
                            }
                        }
                    }
                }
            }
            catch (Exception exception3)
            {
                SDVPApplication.DoNotifyUser(string.Format("[Web Browser] Failure loading Importer/Exporter from {0}: {1}", assemblyInput.CodeBase, exception3.Message), "Extension Load Error");
                return(false);
            }
            return(flag);
        }
Ejemplo n.º 29
0
        private bool ParseRequestForHeaders()
        {
            int num;
            int num2;
            int num3;

            if ((this.m_requestData == null) || (this.iEntityBodyOffset < 4))
            {
                return(false);
            }
            this.m_headers = new HTTPRequestHeaders(Browser.oHeaderEncoding);
            byte[] arrRequest = this.m_requestData.GetBuffer();
            Parser.CrackRequestLine(arrRequest, out num2, out num3, out num);
            if ((num2 < 1) || (num3 < 1))
            {
                SDVPApplication.HandleHTTPError(this.m_session, SessionFlags.ProtocolViolationInRequest, true, false, "Incorrectly formed Request-Line");
                return(false);
            }
            this.m_headers.HTTPMethod  = Encoding.ASCII.GetString(arrRequest, 0, num2 - 1).ToUpper();
            this.m_headers.HTTPVersion = Encoding.ASCII.GetString(arrRequest, (num2 + num3) + 1, ((num - num3) - num2) - 2).Trim().ToUpper();
            int num4 = 0;

            if (arrRequest[num2] != 0x2f)
            {
                if (((num3 > 7) && (arrRequest[num2 + 4] == 0x3a)) && ((arrRequest[num2 + 5] == 0x2f) && (arrRequest[num2 + 6] == 0x2f)))
                {
                    this.m_headers.UriScheme = Encoding.ASCII.GetString(arrRequest, num2, 4);
                    num4  = num2 + 6;
                    num2 += 7;
                    num3 -= 7;
                }
                else if (((num3 > 8) && (arrRequest[num2 + 5] == 0x3a)) && ((arrRequest[num2 + 6] == 0x2f) && (arrRequest[num2 + 7] == 0x2f)))
                {
                    this.m_headers.UriScheme = Encoding.ASCII.GetString(arrRequest, num2, 5);
                    num4  = num2 + 7;
                    num2 += 8;
                    num3 -= 8;
                }
                else if (((num3 > 6) && (arrRequest[num2 + 3] == 0x3a)) && ((arrRequest[num2 + 4] == 0x2f) && (arrRequest[num2 + 5] == 0x2f)))
                {
                    this.m_headers.UriScheme = Encoding.ASCII.GetString(arrRequest, num2, 3);
                    num4  = num2 + 5;
                    num2 += 6;
                    num3 -= 6;
                }
            }
            if (num4 == 0)
            {
                if ((this.pipeClient != null) && this.pipeClient.bIsSecured)
                {
                    this.m_headers.UriScheme = "https";
                }
                else
                {
                    this.m_headers.UriScheme = "http";
                }
            }
            if (num4 > 0)
            {
                while (((num3 > 0) && (arrRequest[num2] != 0x2f)) && (arrRequest[num2] != 0x3f))
                {
                    num2++;
                    num3--;
                }
                if (num3 == 0)
                {
                    num2 = num4;
                    num3 = 1;
                }
                int index = num4 + 1;
                int count = num2 - index;
                if (count > 0)
                {
                    this.m_sHostFromURI = Browser.oHeaderEncoding.GetString(arrRequest, index, count);
                    if ((this.m_headers.UriScheme == "ftp") && this.m_sHostFromURI.Contains("@"))
                    {
                        int length = this.m_sHostFromURI.LastIndexOf("@") + 1;
                        this.m_headers._uriUserInfo = this.m_sHostFromURI.Substring(0, length);
                        this.m_sHostFromURI         = this.m_sHostFromURI.Substring(length);
                    }
                }
            }
            byte[] dst = new byte[num3];
            Buffer.BlockCopy(arrRequest, num2, dst, 0, num3);
            this.m_headers.RawPath = dst;
            string str = Browser.oHeaderEncoding.GetString(arrRequest, num, this.iEntityBodyOffset - num).Trim();

            arrRequest = null;
            if (str.Length >= 1)
            {
                string[] sHeaderLines = str.Replace("\r\n", "\n").Split(new char[] { '\n' });
                string   sErrors      = string.Empty;
                if (!Parser.ParseNVPHeaders(this.m_headers, sHeaderLines, 0, ref sErrors))
                {
                    SDVPApplication.HandleHTTPError(this.m_session, SessionFlags.ProtocolViolationInRequest, true, false, "Incorrectly formed request headers.\n" + sErrors);
                }
            }
            return(true);
        }
Ejemplo n.º 30
0
        internal bool ReadRequest()
        {
            if (this.m_requestData != null)
            {
                SDVPApplication.ReportException(new InvalidOperationException("ReadRequest called after requestData was null'd."));
                return(false);
            }
            if (this.pipeClient == null)
            {
                SDVPApplication.ReportException(new InvalidOperationException("ReadRequest called after pipeClient was null'd."));
                return(false);
            }
            this.m_requestData = new MemoryStream(0x1000);
            this.pipeClient.IncrementUse(0);
            this.m_session.SetBitFlag(SessionFlags.ClientPipeReused, this.pipeClient.iUseCount > 1);
            this.pipeClient.setReceiveTimeout();
            int  iMaxByteCount = 0;
            bool flag          = false;
            bool flag2         = false;

            byte[] arrBuffer = new byte[_cbClientReadBuffer];
            do
            {
                try
                {
                    iMaxByteCount = this.pipeClient.Receive(arrBuffer);
                }
                catch (Exception exception)
                {
                    SDVPApplication.DebugSpew("ReadRequest Failure: " + exception.Message);
                    flag = true;
                }
                if (iMaxByteCount <= 0)
                {
                    flag2 = true;
                    SDVPApplication.DebugSpew("ReadRequest read 0 bytes!!!!!");
                }
                else
                {
                    if (Browser.bDebugSpew)
                    {
                        SDVPApplication.DebugSpew("READ FROM: " + this.pipeClient.ToString() + ":\n" + Utilities.ByteArrayToHexView(arrBuffer, 0x20, iMaxByteCount));
                    }
                    if (this.m_requestData.Length == 0L)
                    {
                        this.m_session.Timers.ClientBeginRequest = DateTime.Now;
                        int index = 0;
                        while ((index < iMaxByteCount) && ((arrBuffer[index] == 13) || (arrBuffer[index] == 10)))
                        {
                            index++;
                        }
                        this.m_requestData.Write(arrBuffer, index, iMaxByteCount - index);
                    }
                    else
                    {
                        this.m_requestData.Write(arrBuffer, 0, iMaxByteCount);
                    }
                }
            }while ((!flag2 && !flag) && !this.isRequestComplete());
            arrBuffer = null;
            if (flag || (this.m_requestData.Length == 0L))
            {
                if ((this.pipeClient.iUseCount < 2) || (this.pipeClient.bIsSecured && (this.pipeClient.iUseCount < 3)))
                {
                    //SDVPApplication.Log.LogFormat("[Web Browser] Failed to read {0} request from ({1}) new client socket, port {2}.", new object[] { this.pipeClient.bIsSecured ? "HTTPS" : "HTTP", this.m_session.oFlags["X-ProcessInfo"], this.m_session.oFlags["X-CLIENTPORT"] });
                }
                this._freeRequestData();
                return(false);
            }
            if ((this.m_headers == null) || (this.m_session.state >= SessionStates.Done))
            {
                this._freeRequestData();
                return(false);
            }
            if ("CONNECT" == this.m_headers.HTTPMethod)
            {
                this.m_session.isTunnel = true;
                this.m_sHostFromURI     = this.m_session.PathAndQuery;
            }
            if (this.m_sHostFromURI != null)
            {
                if (this.m_headers.Exists("Host") && !Utilities.areOriginsEquivalent(this.m_sHostFromURI, this.m_headers["Host"], (this.m_session.isTunnel || this.m_session.isHTTPS) ? 0x1bb : (this.m_session.isFTP ? 0x15 : 80)))
                {
                    this.m_session.oFlags["X-Original-Host"] = this.m_headers["Host"];
                    this.m_headers["Host"] = this.m_sHostFromURI;
                }
                else if (!this.m_headers.Exists("Host"))
                {
                    if (this.m_headers.HTTPVersion.Equals("HTTP/1.1", StringComparison.OrdinalIgnoreCase))
                    {
                        this.m_session.oFlags["X-Original-Host"] = string.Empty;
                    }
                    this.m_headers["Host"] = this.m_sHostFromURI;
                }
                this.m_sHostFromURI = null;
            }
            if (!this.m_headers.Exists("Host"))
            {
                this._freeRequestData();
                return(false);
            }
            return(true);
        }