Exemplo n.º 1
0
        /// <summary>
        ///     Creates a TCP connection to server
        /// </summary>
        /// <param name="remoteHostName">The remote hostname.</param>
        /// <param name="remotePort">The remote port.</param>
        /// <param name="httpVersion">The http version to use.</param>
        /// <param name="isHttps">Is this a HTTPS request.</param>
        /// <param name="sslProtocol">The SSL protocol.</param>
        /// <param name="applicationProtocols">The list of HTTPS application level protocol to negotiate if needed.</param>
        /// <param name="isConnect">Is this a CONNECT request.</param>
        /// <param name="proxyServer">The current ProxyServer instance.</param>
        /// <param name="sessionArgs">The http session.</param>
        /// <param name="upStreamEndPoint">The local upstream endpoint to make request via.</param>
        /// <param name="externalProxy">The external proxy to make request via.</param>
        /// <param name="cacheKey">The connection cache key</param>
        /// <param name="cancellationToken">The cancellation token for this async task.</param>
        /// <returns></returns>
        private async Task <TcpServerConnection> createServerConnection(string remoteHostName, int remotePort,
                                                                        Version httpVersion, bool isHttps, SslProtocols sslProtocol, List <SslApplicationProtocol>?applicationProtocols, bool isConnect,
                                                                        RequestStateBase state, IPEndPoint?upStreamEndPoint, IExternalProxy?externalProxy, string cacheKey,
                                                                        CancellationToken cancellationToken)
        {
            var proxyServer = state.Server;
            var sessionArgs = state.session;

            // deny connection to proxy end points to avoid infinite connection loop.
            if (Server.ProxyEndPoints.Any(x => x.Port == remotePort) &&
                NetworkHelper.IsLocalIpAddress(remoteHostName))
            {
                throw new Exception($"A client is making HTTP request to one of the listening ports of this proxy {remoteHostName}:{remotePort}");
            }

            if (externalProxy != null)
            {
                if (Server.ProxyEndPoints.Any(x => x.Port == externalProxy.Port) &&
                    NetworkHelper.IsLocalIpAddress(externalProxy.HostName))
                {
                    throw new Exception($"A client is making HTTP request via external proxy to one of the listening ports of this proxy {remoteHostName}:{remotePort}");
                }
            }

            bool useUpstreamProxy1 = false;

            // check if external proxy is set for HTTP/HTTPS
            if (externalProxy != null && !(externalProxy.HostName == remoteHostName && externalProxy.Port == remotePort))
            {
                useUpstreamProxy1 = true;

                // check if we need to ByPass
                if (externalProxy.BypassLocalhost && NetworkHelper.IsLocalIpAddress(remoteHostName))
                {
                    useUpstreamProxy1 = false;
                }
            }

            if (!useUpstreamProxy1)
            {
                externalProxy = null;
            }

            TcpClient?       tcpClient = null;
            HttpServerStream?stream    = null;

            SslApplicationProtocol negotiatedApplicationProtocol = default;

            bool retry = true;
            var  enabledSslProtocols = sslProtocol;

retry:
            try
            {
                string hostname = externalProxy != null ? externalProxy.HostName : remoteHostName;
                int    port     = externalProxy?.Port ?? remotePort;

                var ipAddresses = await Dns.GetHostAddressesAsync(hostname);

                if (ipAddresses == null || ipAddresses.Length == 0)
                {
                    throw new Exception($"Could not resolve the hostname {hostname}");
                }

                if (sessionArgs != null)
                {
                    sessionArgs.TimeLine["Dns Resolved"] = DateTime.Now;
                }

                Array.Sort(ipAddresses, (x, y) => x.AddressFamily.CompareTo(y.AddressFamily));

                Exception?lastException = null;
                for (int i = 0; i < ipAddresses.Length; i++)
                {
                    try
                    {
                        var ipAddress = ipAddresses[i];
                        if (upStreamEndPoint == null)
                        {
                            tcpClient = new TcpClient(ipAddress.AddressFamily);
                        }
                        else
                        {
                            tcpClient = new TcpClient(upStreamEndPoint);
                        }

                        tcpClient.NoDelay        = proxyServer.NoDelay;
                        tcpClient.ReceiveTimeout = proxyServer.ConnectionTimeOutSeconds * 1000;
                        tcpClient.SendTimeout    = proxyServer.ConnectionTimeOutSeconds * 1000;
                        tcpClient.LingerState    = new LingerOption(true, proxyServer.TcpTimeWaitSeconds);

                        if (proxyServer.ReuseSocket && RunTime.IsSocketReuseAvailable)
                        {
                            tcpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                        }

                        var connectTask = tcpClient.ConnectAsync(ipAddress, port);
                        await Task.WhenAny(connectTask, Task.Delay(proxyServer.ConnectTimeOutSeconds * 1000));

                        if (!connectTask.IsCompleted || !tcpClient.Connected)
                        {
                            // here we can just do some cleanup and let the loop continue since
                            // we will either get a connection or wind up with a null tcpClient
                            // which will throw
                            try
                            {
                                connectTask.Dispose();
                            }
                            catch
                            {
                                // ignore
                            }
                            try
                            {
#if NET45
                                tcpClient?.Close();
#else
                                tcpClient?.Dispose();
#endif
                                tcpClient = null;
                            }
                            catch
                            {
                                // ignore
                            }

                            continue;
                        }

                        break;
                    }
                    catch (Exception e)
                    {
                        // dispose the current TcpClient and try the next address
                        lastException = e;
#if NET45
                        tcpClient?.Close();
#else
                        tcpClient?.Dispose();
#endif
                        tcpClient = null;
                    }
                }

                if (tcpClient == null)
                {
                    if (sessionArgs != null && proxyServer.CustomUpStreamProxyFailureFunc != null)
                    {
                        var newUpstreamProxy = await proxyServer.CustomUpStreamProxyFailureFunc(sessionArgs);

                        if (newUpstreamProxy != null)
                        {
                            sessionArgs.CustomUpStreamProxyUsed = newUpstreamProxy;
                            sessionArgs.TimeLine["Retrying Upstream Proxy Connection"] = DateTime.Now;
                            return(await createServerConnection(remoteHostName, remotePort, httpVersion, isHttps, sslProtocol, applicationProtocols, isConnect, state, upStreamEndPoint, externalProxy, cacheKey, cancellationToken));
                        }
                    }

                    throw new Exception($"Could not establish connection to {hostname}", lastException);
                }

                if (sessionArgs != null)
                {
                    sessionArgs.TimeLine["Connection Established"] = DateTime.Now;
                }

                await proxyServer.InvokeServerConnectionCreateEvent(tcpClient);

                stream = new HttpServerStream(tcpClient.GetStream(), proxyServer.BufferPool);

                if (externalProxy != null && (isConnect || isHttps))
                {
                    var authority      = $"{remoteHostName}:{remotePort}".GetByteString();
                    var connectRequest = new ConnectRequest(authority)
                    {
                        IsHttps           = isHttps,
                        RequestUriString8 = authority,
                        HttpVersion       = httpVersion
                    };

                    connectRequest.Headers.AddHeader(KnownHeaders.Connection, KnownHeaders.ConnectionKeepAlive);

                    if (!string.IsNullOrEmpty(externalProxy.UserName) && externalProxy.Password != null)
                    {
                        connectRequest.Headers.AddHeader(HttpHeader.ProxyConnectionKeepAlive);
                        connectRequest.Headers.AddHeader(HttpHeader.GetProxyAuthorizationHeader(externalProxy.UserName, externalProxy.Password));
                    }

                    await stream.WriteRequestAsync(connectRequest, cancellationToken);

                    var httpStatus = await stream.ReadResponseStatus(cancellationToken);

                    if (httpStatus.StatusCode != 200 && !httpStatus.Description.EqualsIgnoreCase("OK") &&
                        !httpStatus.Description.EqualsIgnoreCase("Connection Established"))
                    {
                        throw new Exception("Upstream proxy failed to create a secure tunnel");
                    }

                    await stream.ReadAndIgnoreAllLinesAsync(cancellationToken);
                }

                if (isHttps)
                {
                    var sslStream = new SslStream(stream, false, state.ValidateServerCertificate,
                                                  state.SelectClientCertificate);
                    stream = new HttpServerStream(sslStream, proxyServer.BufferPool);

                    var options = new SslClientAuthenticationOptions
                    {
                        ApplicationProtocols           = applicationProtocols,
                        TargetHost                     = remoteHostName,
                        ClientCertificates             = null !,
                        EnabledSslProtocols            = enabledSslProtocols,
                        CertificateRevocationCheckMode = proxyServer.CheckCertificateRevocation
                    };
                    await sslStream.AuthenticateAsClientAsync(options, cancellationToken);

#if NETSTANDARD2_1
                    negotiatedApplicationProtocol = sslStream.NegotiatedApplicationProtocol;
#endif

                    if (sessionArgs != null)
                    {
                        sessionArgs.TimeLine["HTTPS Established"] = DateTime.Now;
                    }
                }
            }
            catch (IOException ex) when(ex.HResult == unchecked ((int)0x80131620) && retry && enabledSslProtocols >= SslProtocols.Tls11)
            {
                stream?.Dispose();
                tcpClient?.Close();

                enabledSslProtocols = SslProtocols.Tls;
                retry = false;
                goto retry;
            }
            catch (Exception)
            {
                stream?.Dispose();
                tcpClient?.Close();
                throw;
            }

            return(new TcpServerConnection(proxyServer, tcpClient, stream, remoteHostName, remotePort, isHttps,
                                           negotiatedApplicationProtocol, httpVersion, externalProxy, upStreamEndPoint, cacheKey));
        }
Exemplo n.º 2
0
        /// <summary>
        ///     Creates a TCP connection to server
        /// </summary>
        /// <param name="remoteHostName">The remote hostname.</param>
        /// <param name="remotePort">The remote port.</param>
        /// <param name="httpVersion">The http version to use.</param>
        /// <param name="isHttps">Is this a HTTPS request.</param>
        /// <param name="sslProtocol">The SSL protocol.</param>
        /// <param name="applicationProtocols">The list of HTTPS application level protocol to negotiate if needed.</param>
        /// <param name="isConnect">Is this a CONNECT request.</param>
        /// <param name="proxyServer">The current ProxyServer instance.</param>
        /// <param name="sessionArgs">The http session.</param>
        /// <param name="upStreamEndPoint">The local upstream endpoint to make request via.</param>
        /// <param name="externalProxy">The external proxy to make request via.</param>
        /// <param name="cacheKey">The connection cache key</param>
        /// <param name="cancellationToken">The cancellation token for this async task.</param>
        /// <returns></returns>
        private async Task <TcpServerConnection> createServerConnection(string remoteHostName, int remotePort,
                                                                        Version httpVersion, bool isHttps, SslProtocols sslProtocol, List <SslApplicationProtocol>?applicationProtocols, bool isConnect,
                                                                        ProxyServer proxyServer, SessionEventArgsBase sessionArgs, IPEndPoint?upStreamEndPoint, IExternalProxy?externalProxy, string cacheKey,
                                                                        CancellationToken cancellationToken)
        {
            // deny connection to proxy end points to avoid infinite connection loop.
            if (Server.ProxyEndPoints.Any(x => x.Port == remotePort) &&
                NetworkHelper.IsLocalIpAddress(remoteHostName))
            {
                throw new Exception($"A client is making HTTP request to one of the listening ports of this proxy {remoteHostName}:{remotePort}");
            }

            if (externalProxy != null)
            {
                if (Server.ProxyEndPoints.Any(x => x.Port == externalProxy.Port) &&
                    NetworkHelper.IsLocalIpAddress(externalProxy.HostName))
                {
                    throw new Exception($"A client is making HTTP request via external proxy to one of the listening ports of this proxy {remoteHostName}:{remotePort}");
                }
            }

            if (isHttps && sslProtocol == SslProtocols.None)
            {
                sslProtocol = proxyServer.SupportedSslProtocols;
            }

            bool useUpstreamProxy1 = false;

            // check if external proxy is set for HTTP/HTTPS
            if (externalProxy != null && !(externalProxy.HostName == remoteHostName && externalProxy.Port == remotePort))
            {
                useUpstreamProxy1 = true;

                // check if we need to ByPass
                if (externalProxy.BypassLocalhost && NetworkHelper.IsLocalIpAddress(remoteHostName))
                {
                    useUpstreamProxy1 = false;
                }
            }

            if (!useUpstreamProxy1)
            {
                externalProxy = null;
            }

            Socket?          tcpServerSocket = null;
            HttpServerStream?stream          = null;

            SslApplicationProtocol negotiatedApplicationProtocol = default;

            bool retry = true;
            var  enabledSslProtocols = sslProtocol;

retry:
            try
            {
                bool   socks    = externalProxy != null && externalProxy.ProxyType != ExternalProxyType.Http;
                string hostname = remoteHostName;
                int    port     = remotePort;

                if (externalProxy != null && externalProxy.ProxyType == ExternalProxyType.Http)
                {
                    hostname = externalProxy.HostName;
                    port     = externalProxy.Port;
                }

                var ipAddresses = await Dns.GetHostAddressesAsync(hostname);

                if (ipAddresses == null || ipAddresses.Length == 0)
                {
                    throw new Exception($"Could not resolve the hostname {hostname}");
                }

                if (sessionArgs != null)
                {
                    sessionArgs.TimeLine["Dns Resolved"] = DateTime.UtcNow;
                }

                Array.Sort(ipAddresses, (x, y) => x.AddressFamily.CompareTo(y.AddressFamily));

                Exception?lastException = null;
                for (int i = 0; i < ipAddresses.Length; i++)
                {
                    try
                    {
                        var ipAddress     = ipAddresses[i];
                        var addressFamily = upStreamEndPoint?.AddressFamily ?? ipAddress.AddressFamily;

                        if (socks)
                        {
                            var proxySocket = new ProxySocket.ProxySocket(addressFamily, SocketType.Stream, ProtocolType.Tcp);
                            proxySocket.ProxyType = externalProxy !.ProxyType == ExternalProxyType.Socks4
                                ? ProxyTypes.Socks4
                                : ProxyTypes.Socks5;

                            var proxyIpAddresses = await Dns.GetHostAddressesAsync(externalProxy.HostName);

                            proxySocket.ProxyEndPoint = new IPEndPoint(proxyIpAddresses[0], externalProxy.Port);
                            if (!string.IsNullOrEmpty(externalProxy.UserName) && externalProxy.Password != null)
                            {
                                proxySocket.ProxyUser = externalProxy.UserName;
                                proxySocket.ProxyPass = externalProxy.Password;
                            }

                            tcpServerSocket = proxySocket;
                        }
                        else
                        {
                            tcpServerSocket = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp);
                        }

                        if (upStreamEndPoint != null)
                        {
                            tcpServerSocket.Bind(upStreamEndPoint);
                        }

                        tcpServerSocket.NoDelay        = proxyServer.NoDelay;
                        tcpServerSocket.ReceiveTimeout = proxyServer.ConnectionTimeOutSeconds * 1000;
                        tcpServerSocket.SendTimeout    = proxyServer.ConnectionTimeOutSeconds * 1000;
                        tcpServerSocket.LingerState    = new LingerOption(true, proxyServer.TcpTimeWaitSeconds);

                        if (proxyServer.ReuseSocket && RunTime.IsSocketReuseAvailable)
                        {
                            tcpServerSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                        }

                        var connectTask = socks
                            ? ProxySocketConnectionTaskFactory.CreateTask((ProxySocket.ProxySocket)tcpServerSocket, ipAddress, port)
                            : SocketConnectionTaskFactory.CreateTask(tcpServerSocket, ipAddress, port);

                        await Task.WhenAny(connectTask, Task.Delay(proxyServer.ConnectTimeOutSeconds * 1000, cancellationToken));

                        if (!connectTask.IsCompleted || !tcpServerSocket.Connected)
                        {
                            // here we can just do some cleanup and let the loop continue since
                            // we will either get a connection or wind up with a null tcpClient
                            // which will throw
                            try
                            {
                                connectTask.Dispose();
                            }
                            catch
                            {
                                // ignore
                            }
                            try
                            {
#if NET45
                                tcpServerSocket?.Close();
#else
                                tcpServerSocket?.Dispose();
#endif
                                tcpServerSocket = null;
                            }
                            catch
                            {
                                // ignore
                            }

                            continue;
                        }

                        break;
                    }
                    catch (Exception e)
                    {
                        // dispose the current TcpClient and try the next address
                        lastException = e;
#if NET45
                        tcpServerSocket?.Close();
#else
                        tcpServerSocket?.Dispose();
#endif
                        tcpServerSocket = null;
                    }
                }

                if (tcpServerSocket == null)
                {
                    if (sessionArgs != null && proxyServer.CustomUpStreamProxyFailureFunc != null)
                    {
                        var newUpstreamProxy = await proxyServer.CustomUpStreamProxyFailureFunc(sessionArgs);

                        if (newUpstreamProxy != null)
                        {
                            sessionArgs.CustomUpStreamProxyUsed = newUpstreamProxy;
                            sessionArgs.TimeLine["Retrying Upstream Proxy Connection"] = DateTime.UtcNow;
                            return(await createServerConnection(remoteHostName, remotePort, httpVersion, isHttps, sslProtocol, applicationProtocols, isConnect, proxyServer, sessionArgs, upStreamEndPoint, externalProxy, cacheKey, cancellationToken));
                        }
                    }

                    throw new Exception($"Could not establish connection to {hostname}", lastException);
                }

                if (sessionArgs != null)
                {
                    sessionArgs.TimeLine["Connection Established"] = DateTime.UtcNow;
                }

                await proxyServer.InvokeServerConnectionCreateEvent(tcpServerSocket);

                stream = new HttpServerStream(new NetworkStream(tcpServerSocket, true), proxyServer.BufferPool, cancellationToken);

                if ((externalProxy != null && externalProxy.ProxyType == ExternalProxyType.Http) && (isConnect || isHttps))
                {
                    var authority      = $"{remoteHostName}:{remotePort}".GetByteString();
                    var connectRequest = new ConnectRequest(authority)
                    {
                        IsHttps           = isHttps,
                        RequestUriString8 = authority,
                        HttpVersion       = httpVersion
                    };

                    connectRequest.Headers.AddHeader(KnownHeaders.Connection, KnownHeaders.ConnectionKeepAlive);

                    if (!string.IsNullOrEmpty(externalProxy.UserName) && externalProxy.Password != null)
                    {
                        connectRequest.Headers.AddHeader(HttpHeader.ProxyConnectionKeepAlive);
                        connectRequest.Headers.AddHeader(HttpHeader.GetProxyAuthorizationHeader(externalProxy.UserName, externalProxy.Password));
                    }

                    await stream.WriteRequestAsync(connectRequest, cancellationToken);

                    var httpStatus = await stream.ReadResponseStatus(cancellationToken);

                    if (httpStatus.StatusCode != 200 && !httpStatus.Description.EqualsIgnoreCase("OK") &&
                        !httpStatus.Description.EqualsIgnoreCase("Connection Established"))
                    {
                        throw new Exception("Upstream proxy failed to create a secure tunnel");
                    }

                    await stream.ReadAndIgnoreAllLinesAsync(cancellationToken);
                }

                if (isHttps)
                {
                    var sslStream = new SslStream(stream, false,
                                                  (sender, certificate, chain, sslPolicyErrors) =>
                                                  proxyServer.ValidateServerCertificate(sender, sessionArgs, certificate, chain,
                                                                                        sslPolicyErrors),
                                                  (sender, targetHost, localCertificates, remoteCertificate, acceptableIssuers) =>
                                                  proxyServer.SelectClientCertificate(sender, sessionArgs, targetHost, localCertificates,
                                                                                      remoteCertificate, acceptableIssuers));
                    stream = new HttpServerStream(sslStream, proxyServer.BufferPool, cancellationToken);

                    var options = new SslClientAuthenticationOptions
                    {
                        ApplicationProtocols           = applicationProtocols,
                        TargetHost                     = remoteHostName,
                        ClientCertificates             = null !,
                        EnabledSslProtocols            = enabledSslProtocols,
                        CertificateRevocationCheckMode = proxyServer.CheckCertificateRevocation
                    };
                    await sslStream.AuthenticateAsClientAsync(options, cancellationToken);

#if NETSTANDARD2_1
                    negotiatedApplicationProtocol = sslStream.NegotiatedApplicationProtocol;
#endif

                    if (sessionArgs != null)
                    {
                        sessionArgs.TimeLine["HTTPS Established"] = DateTime.UtcNow;
                    }
                }
            }
            catch (IOException ex) when(ex.HResult == unchecked ((int)0x80131620) && retry && enabledSslProtocols >= SslProtocols.Tls11)
            {
                stream?.Dispose();
                tcpServerSocket?.Close();

                // Specifying Tls11 and/or Tls12 will disable the usage of Ssl3, even if it has been included.
                // https://docs.microsoft.com/en-us/dotnet/api/system.servicemodel.tcptransportsecurity.sslprotocols?view=dotnet-plat-ext-3.1
                enabledSslProtocols = proxyServer.SupportedSslProtocols & (SslProtocols)0xff;

                if (enabledSslProtocols == SslProtocols.None)
                {
                    throw;
                }

                retry = false;
                goto retry;
            }
            catch (AuthenticationException ex) when(ex.HResult == unchecked ((int)0x80131501) && retry && enabledSslProtocols >= SslProtocols.Tls11)
            {
                stream?.Dispose();
                tcpServerSocket?.Close();

                // Specifying Tls11 and/or Tls12 will disable the usage of Ssl3, even if it has been included.
                // https://docs.microsoft.com/en-us/dotnet/api/system.servicemodel.tcptransportsecurity.sslprotocols?view=dotnet-plat-ext-3.1
                enabledSslProtocols = proxyServer.SupportedSslProtocols & (SslProtocols)0xff;

                if (enabledSslProtocols == SslProtocols.None)
                {
                    throw;
                }

                retry = false;
                goto retry;
            }
            catch (Exception)
            {
                stream?.Dispose();
                tcpServerSocket?.Close();
                throw;
            }

            return(new TcpServerConnection(proxyServer, tcpServerSocket, stream, remoteHostName, remotePort, isHttps,
                                           negotiatedApplicationProtocol, httpVersion, externalProxy, upStreamEndPoint, cacheKey));
        }