Пример #1
0
        public static ValueTask <SslStream> EstablishSslConnectionAsync(SslClientAuthenticationOptions sslOptions, HttpRequestMessage request, Stream stream, CancellationToken cancellationToken)
        {
            // If there's a cert validation callback, and if it came from HttpClientHandler,
            // wrap the original delegate in order to change the sender to be the request message (expected by HttpClientHandler's delegate).
            RemoteCertificateValidationCallback callback = sslOptions.RemoteCertificateValidationCallback;

            if (callback != null && callback.Target is CertificateCallbackMapper mapper)
            {
                sslOptions = sslOptions.ShallowClone(); // Clone as we're about to mutate it and don't want to affect the cached copy
                Func <HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> localFromHttpClientHandler = mapper.FromHttpClientHandler;
                HttpRequestMessage localRequest = request;
                sslOptions.RemoteCertificateValidationCallback = (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) =>
                                                                 localFromHttpClientHandler(localRequest, certificate as X509Certificate2, chain, sslPolicyErrors);
            }
            ////Crack emby: Bypass remote ssl check
            //if (request.RequestUri.Host.Contains("mb3admin.com"))
            //{
            //    Uri oldUri = request.RequestUri;
            //    Uri newUri = new Uri(oldUri.AbsoluteUri.Replace("mb3admin.com", "crackemby.neko.re"));
            //    request.RequestUri = newUri;
            //}
            //这里的 hash 是我的证书
            //sslOptions.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => certificate.GetCertHashString().ToLower() == "8a83b00510792399caef93a366695ce37988046c";
            // Create the SslStream, authenticate, and return it.
            return(EstablishSslConnectionAsyncCore(stream, sslOptions, cancellationToken));
        }
Пример #2
0
        public HttpConnectionSettings Clone()
        {
            // Force creation of the cookie container if needed, so the original and clone share the same instance.
            if (_useCookies && _cookieContainer == null)
            {
                _cookieContainer = new CookieContainer();
            }

            return(new HttpConnectionSettings()
            {
                _allowAutoRedirect = _allowAutoRedirect,
                _automaticDecompression = _automaticDecompression,
                _cookieContainer = _cookieContainer,
                _connectTimeout = _connectTimeout,
                _credentials = _credentials,
                _defaultProxyCredentials = _defaultProxyCredentials,
                _expect100ContinueTimeout = _expect100ContinueTimeout,
                _maxAutomaticRedirections = _maxAutomaticRedirections,
                _maxConnectionsPerServer = _maxConnectionsPerServer,
                _maxHttpVersion = _maxHttpVersion,
                _maxResponseDrainSize = _maxResponseDrainSize,
                _maxResponseDrainTime = _maxResponseDrainTime,
                _maxResponseHeadersLength = _maxResponseHeadersLength,
                _pooledConnectionLifetime = _pooledConnectionLifetime,
                _pooledConnectionIdleTimeout = _pooledConnectionIdleTimeout,
                _preAuthenticate = _preAuthenticate,
                _properties = _properties,
                _proxy = _proxy,
                _sslOptions = _sslOptions?.ShallowClone(), // shallow clone the options for basic prevention of mutation issues while processing
                _useCookies = _useCookies,
                _useProxy = _useProxy,
            });
        }
Пример #3
0
        public static async ValueTask <SslStream> EstablishSslConnectionAsync(SslClientAuthenticationOptions sslOptions, HttpRequestMessage request, Stream stream, CancellationToken cancellationToken)
        {
            // If there's a cert validation callback, and if it came from HttpClientHandler,
            // wrap the original delegate in order to change the sender to be the request message (expected by HttpClientHandler's delegate).
            RemoteCertificateValidationCallback callback = sslOptions.RemoteCertificateValidationCallback;

            if (callback != null && callback.Target is CertificateCallbackMapper mapper)
            {
                sslOptions = sslOptions.ShallowClone(); // Clone as we're about to mutate it and don't want to affect the cached copy
                Func <HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> localFromHttpClientHandler = mapper.FromHttpClientHandler;
                HttpRequestMessage localRequest = request;
                sslOptions.RemoteCertificateValidationCallback = (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) =>
                                                                 localFromHttpClientHandler(localRequest, certificate as X509Certificate2, chain, sslPolicyErrors);
            }

            // Create the SslStream, authenticate, and return it.
            var sslStream = new SslStream(stream);

            try
            {
                await sslStream.AuthenticateAsClientAsync(sslOptions, cancellationToken).ConfigureAwait(false);
            }
            catch (Exception e)
            {
                sslStream.Dispose();
                throw new HttpRequestException(SR.net_http_ssl_connection_failed, e);
            }
            return(sslStream);
        }
Пример #4
0
        /// <summary>Creates a copy of the settings but with some values normalized to suit the implementation.</summary>
        public HttpConnectionSettings CloneAndNormalize()
        {
            // Force creation of the cookie container if needed, so the original and clone share the same instance.
            if (_useCookies && _cookieContainer == null)
            {
                _cookieContainer = new CookieContainer();
            }

            var settings = new HttpConnectionSettings()
            {
                _allowAutoRedirect               = _allowAutoRedirect,
                _automaticDecompression          = _automaticDecompression,
                _cookieContainer                 = _cookieContainer,
                _connectTimeout                  = _connectTimeout,
                _credentials                     = _credentials,
                _defaultProxyCredentials         = _defaultProxyCredentials,
                _defaultCredentialsUsedForProxy  = _defaultCredentialsUsedForProxy,
                _defaultCredentialsUsedForServer = _defaultCredentialsUsedForServer,
                _expect100ContinueTimeout        = _expect100ContinueTimeout,
                _maxAutomaticRedirections        = _maxAutomaticRedirections,
                _maxConnectionsPerServer         = _maxConnectionsPerServer,
                _maxHttpVersion                  = _maxHttpVersion,
                _maxResponseDrainSize            = _maxResponseDrainSize,
                _maxResponseDrainTime            = _maxResponseDrainTime,
                _maxResponseHeadersLength        = _maxResponseHeadersLength,
                _pooledConnectionLifetime        = _pooledConnectionLifetime,
                _pooledConnectionIdleTimeout     = _pooledConnectionIdleTimeout,
                _preAuthenticate                 = _preAuthenticate,
                _properties                     = _properties,
                _proxy                          = _proxy,
                _sslOptions                     = _sslOptions?.ShallowClone(), // shallow clone the options for basic prevention of mutation issues while processing
                _useCookies                     = _useCookies,
                _useProxy                       = _useProxy,
                _keepAlivePingTimeout           = _keepAlivePingTimeout,
                _keepAlivePingDelay             = _keepAlivePingDelay,
                _keepAlivePingPolicy            = _keepAlivePingPolicy,
                _requestHeaderEncodingSelector  = _requestHeaderEncodingSelector,
                _responseHeaderEncodingSelector = _responseHeaderEncodingSelector,
                _enableMultipleHttp2Connections = _enableMultipleHttp2Connections,
                _connectCallback                = _connectCallback,
                _plaintextStreamFilter          = _plaintextStreamFilter,
                _initialHttp2StreamWindowSize   = _initialHttp2StreamWindowSize,
                _activityHeadersPropagator      = _activityHeadersPropagator,
            };

            // TODO: Remove if/when QuicImplementationProvider is removed from System.Net.Quic.
            if (HttpConnectionPool.IsHttp3Supported())
            {
                settings._quicImplementationProvider = _quicImplementationProvider;
            }

            return(settings);
        }
        /// <summary>Creates a copy of the settings but with some values normalized to suit the implementation.</summary>
        public HttpConnectionSettings CloneAndNormalize()
        {
            // Force creation of the cookie container if needed, so the original and clone share the same instance.
            if (_useCookies && _cookieContainer == null)
            {
                _cookieContainer = new CookieContainer();
            }

            var settings = new HttpConnectionSettings()
            {
                _allowAutoRedirect               = _allowAutoRedirect,
                _automaticDecompression          = _automaticDecompression,
                _cookieContainer                 = _cookieContainer,
                _connectTimeout                  = _connectTimeout,
                _credentials                     = _credentials,
                _defaultProxyCredentials         = _defaultProxyCredentials,
                _defaultCredentialsUsedForProxy  = _defaultCredentialsUsedForProxy,
                _defaultCredentialsUsedForServer = _defaultCredentialsUsedForServer,
                _expect100ContinueTimeout        = _expect100ContinueTimeout,
                _maxAutomaticRedirections        = _maxAutomaticRedirections,
                _maxConnectionsPerServer         = _maxConnectionsPerServer,
                _maxHttpVersion                  = _maxHttpVersion,
                _maxResponseDrainSize            = _maxResponseDrainSize,
                _maxResponseDrainTime            = _maxResponseDrainTime,
                _maxResponseHeadersLength        = _maxResponseHeadersLength,
                _pooledConnectionLifetime        = _pooledConnectionLifetime,
                _pooledConnectionIdleTimeout     = _pooledConnectionIdleTimeout,
                _preAuthenticate                 = _preAuthenticate,
                _properties                     = _properties,
                _proxy                          = _proxy,
                _sslOptions                     = _sslOptions?.ShallowClone(), // shallow clone the options for basic prevention of mutation issues while processing
                _useCookies                     = _useCookies,
                _useProxy                       = _useProxy,
                _keepAlivePingTimeout           = _keepAlivePingTimeout,
                _keepAlivePingDelay             = _keepAlivePingDelay,
                _keepAlivePingPolicy            = _keepAlivePingPolicy,
                _requestHeaderEncodingSelector  = _requestHeaderEncodingSelector,
                _responseHeaderEncodingSelector = _responseHeaderEncodingSelector,
                _enableMultipleHttp2Connections = _enableMultipleHttp2Connections,
                _connectCallback                = _connectCallback,
                _plaintextStreamFilter          = _plaintextStreamFilter
            };

            // TODO: Replace with Platform-Guard Assertion Annotations once https://github.com/dotnet/runtime/issues/44922 is finished
            // TODO: Remove if/when QuicImplementationProvider is removed from System.Net.Quic.
            if ((OperatingSystem.IsLinux() && !OperatingSystem.IsAndroid()) || OperatingSystem.IsWindows() || OperatingSystem.IsMacOS())
            {
                settings._quicImplementationProvider = _quicImplementationProvider;
            }

            return(settings);
        }
        private static ValueTask <SslStream> EstablishSslConnectionAsync(SslClientAuthenticationOptions sslOptions, HttpRequestMessage request, Stream stream, CancellationToken cancellationToken)
        {
            RemoteCertificateValidationCallback callback = sslOptions.RemoteCertificateValidationCallback;

            if (callback != null && callback.Target is CertificateCallbackMapper mapper)
            {
                sslOptions = sslOptions.ShallowClone();
                Func <HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> localFromHttpClientHandler = mapper.FromHttpClientHandler;
                HttpRequestMessage localRequest = request;
                sslOptions.RemoteCertificateValidationCallback = (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) =>
                                                                 localFromHttpClientHandler(localRequest, certificate as X509Certificate2, chain, sslPolicyErrors);
            }

            return(EstablishSslConnectionAsyncCore(stream, sslOptions, cancellationToken));
        }
        /// <summary>Creates a copy of the settings but with some values normalized to suit the implementation.</summary>
        public HttpConnectionSettings CloneAndNormalize()
        {
            // Force creation of the cookie container if needed, so the original and clone share the same instance.
            if (_useCookies && _cookieContainer == null)
            {
                _cookieContainer = new CookieContainer();
            }

            // The implementation uses Environment.TickCount to track connection lifetimes, as Environment.TickCount
            // is measurable faster than DateTime.UtcNow / Stopwatch.GetTimestamp, and we do it at least once per request.
            // However, besides its lower resolution (which is fine for SocketHttpHandler's needs), due to being based on
            // an Int32 rather than Int64, the difference between two tick counts is at most ~49 days.  This means that
            // specifying a connection idle or lifetime of greater than 49 days would cause it to never be reached.  The
            // chances of a connection being open anywhere near that long is close to zero, as is the chance that someone
            // would choose to specify such a long timeout, but regardless, we avoid issues by capping the timeouts.
            TimeSpan timeLimit = TimeSpan.FromDays(40); // something super long but significantly less than the 49 day limit
            TimeSpan pooledConnectionLifetime    = _pooledConnectionLifetime < timeLimit ? _pooledConnectionLifetime : timeLimit;
            TimeSpan pooledConnectionIdleTimeout = _pooledConnectionIdleTimeout < timeLimit ? _pooledConnectionIdleTimeout : timeLimit;

            return(new HttpConnectionSettings()
            {
                _allowAutoRedirect = _allowAutoRedirect,
                _automaticDecompression = _automaticDecompression,
                _cookieContainer = _cookieContainer,
                _connectTimeout = _connectTimeout,
                _credentials = _credentials,
                _defaultProxyCredentials = _defaultProxyCredentials,
                _expect100ContinueTimeout = _expect100ContinueTimeout,
                _maxAutomaticRedirections = _maxAutomaticRedirections,
                _maxConnectionsPerServer = _maxConnectionsPerServer,
                _maxHttpVersion = _maxHttpVersion,
                _maxResponseDrainSize = _maxResponseDrainSize,
                _maxResponseDrainTime = _maxResponseDrainTime,
                _maxResponseHeadersLength = _maxResponseHeadersLength,
                _pooledConnectionLifetime = pooledConnectionLifetime,
                _pooledConnectionIdleTimeout = pooledConnectionIdleTimeout,
                _preAuthenticate = _preAuthenticate,
                _properties = _properties,
                _proxy = _proxy,
                _sslOptions = _sslOptions?.ShallowClone(), // shallow clone the options for basic prevention of mutation issues while processing
                _useCookies = _useCookies,
                _useProxy = _useProxy,
                _allowUnencryptedHttp2 = _allowUnencryptedHttp2,
            });
        }
Пример #8
0
        public static ValueTask <SslStream> EstablishSslConnectionAsync(SslClientAuthenticationOptions sslOptions, HttpRequestMessage request, Stream stream, CancellationToken cancellationToken)
        {
            // If there's a cert validation callback, and if it came from HttpClientHandler,
            // wrap the original delegate in order to change the sender to be the request message (expected by HttpClientHandler's delegate).
            RemoteCertificateValidationCallback callback = sslOptions.RemoteCertificateValidationCallback;

            if (callback != null && callback.Target is CertificateCallbackMapper mapper)
            {
                sslOptions = sslOptions.ShallowClone(); // Clone as we're about to mutate it and don't want to affect the cached copy
                Func <HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> localFromHttpClientHandler = mapper.FromHttpClientHandler;
                HttpRequestMessage localRequest = request;
                sslOptions.RemoteCertificateValidationCallback = (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) =>
                                                                 localFromHttpClientHandler(localRequest, certificate as X509Certificate2, chain, sslPolicyErrors);
            }

            // Create the SslStream, authenticate, and return it.
            return(EstablishSslConnectionAsyncCore(stream, sslOptions, cancellationToken));
        }
Пример #9
0
        /// <summary>Creates a copy of the settings but with some values normalized to suit the implementation.</summary>
        public HttpConnectionSettings CloneAndNormalize()
        {
            // Force creation of the cookie container if needed, so the original and clone share the same instance.
            if (_useCookies && _cookieContainer == null)
            {
                _cookieContainer = new CookieContainer();
            }

            return(new HttpConnectionSettings()
            {
                _allowAutoRedirect = _allowAutoRedirect,
                _automaticDecompression = _automaticDecompression,
                _cookieContainer = _cookieContainer,
                _connectTimeout = _connectTimeout,
                _credentials = _credentials,
                _defaultProxyCredentials = _defaultProxyCredentials,
                _defaultCredentialsUsedForProxy = _defaultCredentialsUsedForProxy,
                _defaultCredentialsUsedForServer = _defaultCredentialsUsedForServer,
                _expect100ContinueTimeout = _expect100ContinueTimeout,
                _maxAutomaticRedirections = _maxAutomaticRedirections,
                _maxConnectionsPerServer = _maxConnectionsPerServer,
                _maxHttpVersion = _maxHttpVersion,
                _maxResponseDrainSize = _maxResponseDrainSize,
                _maxResponseDrainTime = _maxResponseDrainTime,
                _maxResponseHeadersLength = _maxResponseHeadersLength,
                _pooledConnectionLifetime = _pooledConnectionLifetime,
                _pooledConnectionIdleTimeout = _pooledConnectionIdleTimeout,
                _preAuthenticate = _preAuthenticate,
                _properties = _properties,
                _proxy = _proxy,
                _sslOptions = _sslOptions?.ShallowClone(), // shallow clone the options for basic prevention of mutation issues while processing
                _useCookies = _useCookies,
                _useProxy = _useProxy,
                _keepAlivePingTimeout = _keepAlivePingTimeout,
                _keepAlivePingDelay = _keepAlivePingDelay,
                _keepAlivePingPolicy = _keepAlivePingPolicy,
                _requestHeaderEncodingSelector = _requestHeaderEncodingSelector,
                _responseHeaderEncodingSelector = _responseHeaderEncodingSelector,
                _enableMultipleHttp2Connections = _enableMultipleHttp2Connections,
                _connectionFactory = _connectionFactory,
                _plaintextFilter = _plaintextFilter
            });
        }
Пример #10
0
 public HttpConnectionSettings Clone() =>
 new HttpConnectionSettings()
 {
     _allowAutoRedirect           = _allowAutoRedirect,
     _automaticDecompression      = _automaticDecompression,
     _cookieContainer             = _cookieContainer,
     _credentials                 = _credentials,
     _defaultProxyCredentials     = _defaultProxyCredentials,
     _maxAutomaticRedirections    = _maxAutomaticRedirections,
     _maxConnectionsPerServer     = _maxConnectionsPerServer,
     _maxResponseHeadersLength    = _maxResponseHeadersLength,
     _pooledConnectionLifetime    = _pooledConnectionLifetime,
     _pooledConnectionIdleTimeout = _pooledConnectionIdleTimeout,
     _preAuthenticate             = _preAuthenticate,
     _properties = _properties,
     _proxy      = _proxy,
     _sslOptions = _sslOptions?.ShallowClone(),     // shallow clone the options for basic prevention of mutation issues while processing
     _useCookies = _useCookies,
     _useProxy   = _useProxy,
 };
Пример #11
0
        private static SslClientAuthenticationOptions SetUpRemoteCertificateValidationCallback(SslClientAuthenticationOptions sslOptions, HttpRequestMessage request)
        {
            // If there's a cert validation callback, and if it came from HttpClientHandler,
            // wrap the original delegate in order to change the sender to be the request message (expected by HttpClientHandler's delegate).
            RemoteCertificateValidationCallback?callback = sslOptions.RemoteCertificateValidationCallback;

            if (callback != null && callback.Target is CertificateCallbackMapper mapper)
            {
                sslOptions = sslOptions.ShallowClone(); // Clone as we're about to mutate it and don't want to affect the cached copy
                Func <HttpRequestMessage, X509Certificate2?, X509Chain?, SslPolicyErrors, bool> localFromHttpClientHandler = mapper.FromHttpClientHandler;
                HttpRequestMessage localRequest = request;
                sslOptions.RemoteCertificateValidationCallback = (object sender, X509Certificate? certificate, X509Chain? chain, SslPolicyErrors sslPolicyErrors) =>
                {
                    Debug.Assert(localRequest != null);
                    bool result = localFromHttpClientHandler(localRequest, certificate as X509Certificate2, chain, sslPolicyErrors);
                    localRequest = null !; // ensure the SslOptions and this callback don't keep the first HttpRequestMessage alive indefinitely
                    return(result);
                };
            }

            return(sslOptions);
        }