Exemplo n.º 1
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, KPCONFIG.oAcceptedServerHTTPSProtocols, KProxyApplication.Prefs.GetBoolPref("KProxy.https.checkcertificaterevocation", false));
                iHandshakeTime = (int)stopwatch.ElapsedMilliseconds;
            }
            catch (Exception exception)
            {
                iHandshakeTime = (int)stopwatch.ElapsedMilliseconds;
                KProxyApplication.DebugSpew(exception.StackTrace + "\n" + exception.Message);
                return(false);
            }
            return(true);
        }
Exemplo n.º 2
0
        internal bool ResendRequest()
        {
            bool b = this.pipeServer != null;

            if (!this.ConnectToHost())
            {
                KProxyApplication.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.KProxyBeginRequest = 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());
                }
                KProxyApplication.DebugSpew("ResendRequest() failed: " + Utilities.DescribeException(exception));
                this.m_session.oRequest.FailSession(0x1f8, "Kavprot Proxy - 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);
        }
Exemplo n.º 3
0
        internal bool SecureClientPipe(string sHostname, HTTPResponseHeaders oHeaders)
        {
            X509Certificate2 certificate;

            try
            {
                certificate = CertMaker.FindCert(sHostname, true);
            }
            catch (Exception exception)
            {
                //KProxyApplication.Log.LogFormat("KProxy.https> Failed to obtain certificate for {0} due to {1}", new object[] { sHostname, exception.Message });
                certificate = null;
            }
            try
            {
                if (certificate == null)
                {
                    KProxyApplication.DoNotifyUser("Unable to find Certificate for " + sHostname, "HTTPS Interception Failure");
                    oHeaders.HTTPResponseCode   = 0x1f6;
                    oHeaders.HTTPResponseStatus = "502 KProxy unable to generate certificate";
                }
                if (KPCONFIG.bDebugSpew)
                {
                    KProxyApplication.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)
                {
                    KProxyApplication.DebugSpew("SecureClientPipe returning FALSE because HTTPResponseCode != 200");
                    return(false);
                }
                base._httpsStream = new SslStream(new NetworkStream(base._baseSocket, false), false);
                base._httpsStream.AuthenticateAsServer(certificate, _bWantClientCert, KPCONFIG.oAcceptedClientHTTPSProtocols, false);
                return(true);
            }
            catch (Exception exception2)
            {
                //KProxyApplication.Log.LogFormat("Secure client pipe failed: {0}{1}.", new object[] { exception2.Message, (exception2.InnerException == null) ? string.Empty : (" InnerException: " + exception2.InnerException.Message) });
                KProxyApplication.DebugSpew("Secure client pipe failed: " + exception2.Message);
                try
                {
                    base.End();
                }
                catch
                {
                }
            }
            return(false);
        }
Exemplo n.º 4
0
 internal bool SecureClientPipeDirect(X509Certificate2 certServer)
 {
     try
     {
         base._httpsStream = new SslStream(new NetworkStream(base._baseSocket, false), false);
         base._httpsStream.AuthenticateAsServer(certServer, _bWantClientCert, KPCONFIG.oAcceptedClientHTTPSProtocols, false);
         return(true);
     }
     catch (Exception exception)
     {
         //KProxyApplication.Log.LogFormat("Secure client pipe failed: {0}{1}.", new object[] { exception.Message, (exception.InnerException == null) ? string.Empty : (" InnerException: " + exception.InnerException.Message) });
         KProxyApplication.DebugSpew("Secure client pipe failed: " + exception.Message);
         try
         {
             base.End();
         }
         catch
         {
         }
     }
     return(false);
 }
Exemplo n.º 5
0
        internal static string[] GetConnectionNames()
        {
            if (KPCONFIG.bDebugSpew)
            {
                KProxyApplication.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);
        }
Exemplo n.º 6
0
        internal bool ReadRequest()
        {
            if (this.m_requestData != null)
            {
                KProxyApplication.ReportException(new InvalidOperationException("ReadRequest called after requestData was null'd."));
                return(false);
            }
            if (this.pipeClient == null)
            {
                KProxyApplication.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)
                {
                    KProxyApplication.DebugSpew("ReadRequest Failure: " + exception.Message);
                    flag = true;
                }
                if (iMaxByteCount <= 0)
                {
                    flag2 = true;
                    KProxyApplication.DebugSpew("ReadRequest read 0 bytes!!!!!");
                }
                else
                {
                    if (KPCONFIG.bDebugSpew)
                    {
                        KProxyApplication.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)))
                {
                    //KProxyApplication.Log.LogFormat("[Kavprot Proxy] 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);
        }
Exemplo n.º 7
0
        internal bool ReadResponse()
        {
            int  iMaxByteCount = 0;
            bool flag          = false;
            bool flag2         = false;
            bool flag3         = false;

            byte[] arrBuffer = new byte[_cbServerReadBuffer];
            do
            {
                try
                {
                    iMaxByteCount = this.pipeServer.Receive(arrBuffer);
                    if (0L == this.m_session.Timers.ServerBeginResponse.Ticks)
                    {
                        this.m_session.Timers.ServerBeginResponse = DateTime.Now;
                    }
                    if (iMaxByteCount <= 0)
                    {
                        flag = true;
                        KProxyApplication.DoReadResponseBuffer(this.m_session, arrBuffer, 0);
                    }
                    else
                    {
                        if (KPCONFIG.bDebugSpew)
                        {
                            KProxyApplication.DebugSpew(Utilities.ByteArrayToHexView(arrBuffer, 0x20, iMaxByteCount));
                        }
                        if (!KProxyApplication.DoReadResponseBuffer(this.m_session, arrBuffer, iMaxByteCount))
                        {
                            flag2 = true;
                        }
                        this.m_responseData.Write(arrBuffer, 0, iMaxByteCount);
                        this.m_responseTotalDataCount += iMaxByteCount;
                        if ((this.m_inHeaders == null) && this.GetHeaders())
                        {
                            this.m_session.Timers.KProxyGotResponseHeaders = DateTime.Now;
                            if ((this.m_session.state == SessionStates.Aborted) && this.m_session.isAnyFlagSet(SessionFlags.ProtocolViolationInResponse))
                            {
                                return(false);
                            }
                            KProxyApplication.DoResponseHeadersAvailable(this.m_session);
                            if (KPCONFIG.bStreamAudioVideo)
                            {
                                string str = this.m_inHeaders["Content-Type"];
                                if ((str.StartsWith("video/", StringComparison.OrdinalIgnoreCase) || str.StartsWith("audio/", StringComparison.OrdinalIgnoreCase)) || str.StartsWith("application/x-mms-framed", StringComparison.OrdinalIgnoreCase))
                                {
                                    this.m_session.bBufferResponse = false;
                                }
                            }
                            if (!this.m_session.bBufferResponse)
                            {
                                this.m_session.bBufferResponse = this.m_session.HTTPMethodIs("CONNECT");
                            }
                            if (!this.m_session.bBufferResponse && (this.m_session.oRequest.pipeClient == null))
                            {
                                this.m_session.bBufferResponse = true;
                            }
                            if ((!this.m_session.bBufferResponse && ((0x191 == this.m_inHeaders.HTTPResponseCode) || (0x197 == this.m_inHeaders.HTTPResponseCode))) && this.m_session.oFlags.ContainsKey("x-AutoAuth"))
                            {
                                this.m_session.bBufferResponse = true;
                            }
                            this.m_session.SetBitFlag(SessionFlags.ResponseStreamed, !this.m_session.bBufferResponse);
                            if (!this.m_session.bBufferResponse)
                            {
                                if (this.m_session.oFlags.ContainsKey("response-trickle-delay"))
                                {
                                    int num2 = int.Parse(this.m_session.oFlags["response-trickle-delay"]);
                                    this.m_session.oRequest.pipeClient.TransmitDelay = num2;
                                }
                                if (this.m_session.oFlags.ContainsKey("log-drop-response-body") || KProxyApplication.Prefs.GetBoolPref("KProxy.network.streaming.ForgetStreamedData", false))
                                {
                                    flag3 = true;
                                }
                            }
                        }
                        if ((this.m_inHeaders != null) && this.m_session.isFlagSet(SessionFlags.ResponseStreamed))
                        {
                            this.LeakResponseBytes();
                            if (flag3)
                            {
                                this.m_session.SetBitFlag(SessionFlags.ResponseBodyDropped, true);
                                if (this._lngLastChunkInfoOffset > -1L)
                                {
                                    this.ReleaseStreamedChunkedData();
                                }
                                else if (this.m_inHeaders.ExistsAndContains("Transfer-Encoding", "chunked"))
                                {
                                    this.ReleaseStreamedChunkedData();
                                }
                                else
                                {
                                    this.ReleaseStreamedData();
                                }
                            }
                        }
                    }
                }
                catch (Exception exception)
                {
                    flag2 = true;
                    if (exception is OperationCanceledException)
                    {
                        this.m_session.state = SessionStates.Aborted;
                    }
                    else if (exception is OutOfMemoryException)
                    {
                        KProxyApplication.ReportException(exception);
                        this.m_session.state = SessionStates.Aborted;
                    }
                    else
                    {
                    }
                }
            }while ((!flag && !flag2) && ((this.m_inHeaders == null) || !this.isResponseBodyComplete()));
            this.m_session.Timers.ServerDoneResponse = DateTime.Now;
            if (this.m_session.isFlagSet(SessionFlags.ResponseStreamed))
            {
                this.m_session.Timers.ClientDoneResponse = this.m_session.Timers.ServerDoneResponse;
            }
            if ((this.m_responseTotalDataCount == 0L) && (this.m_inHeaders == null))
            {
                flag2 = true;
            }
            arrBuffer = null;
            if (flag2)
            {
                this.m_responseData.Dispose();
                this.m_responseData = null;
                return(false);
            }
            if (this.m_inHeaders == null)
            {
                KProxyApplication.HandleHTTPError(this.m_session, SessionFlags.ProtocolViolationInResponse, true, true, "The Server did not return properly formatted HTTP Headers. Maybe missing altogether (e.g. HTTP/0.9), maybe only \\r\\r instead of \\r\\n\\r\\n?\n");
                this.m_session.SetBitFlag(SessionFlags.ResponseStreamed, false);
                this.m_inHeaders                    = new HTTPResponseHeaders(KPCONFIG.oHeaderEncoding);
                this.m_inHeaders.HTTPVersion        = "HTTP/1.0";
                this.m_inHeaders.HTTPResponseCode   = 200;
                this.m_inHeaders.HTTPResponseStatus = "200 This buggy server did not return headers";
                this.iEntityBodyOffset              = 0;
                return(true);
            }
            return(true);
        }