Пример #1
0
        public void UpgradeTls(TlsConfig tlsConfig)
        {
            if (tlsConfig == null)
            {
                throw new ArgumentNullException("tlsConfig");
            }

            lock (_readLocker)
            {
                lock (_writeLocker)
                {
                    const bool leaveInnerStreamOpen = false;

                    var enabledSslProtocols = tlsConfig.GetEnabledSslProtocols();

                    string errorMessage = null;

                    var sslStream = new SslStream(
                        _networkStream,
                        leaveInnerStreamOpen,
                        (sender, certificate, chain, sslPolicyErrors) =>
                        ValidateCertificates(chain, sslPolicyErrors, tlsConfig, out errorMessage)
                        );

                    try
                    {
                        sslStream.AuthenticateAsClient(_hostname, new X509Certificate2Collection(), enabledSslProtocols, tlsConfig.CheckCertificateRevocation);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(string.Format("{0} - {1}", ex.Message, errorMessage), ex);
                    }

                    _networkStream = sslStream;
                }
            }
        }
Пример #2
0
        private static bool ValidateCertificates(X509Chain chain, SslPolicyErrors sslPolicyErrors, TlsConfig tlsConfig, out string errorMessage)
        {
            errorMessage = null;

            if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNotAvailable) == SslPolicyErrors.RemoteCertificateNotAvailable)
            {
                errorMessage = chain.ChainStatus.GetErrors();
                return(false);
            }

            if (tlsConfig.InsecureSkipVerify || sslPolicyErrors == SslPolicyErrors.None)
            {
                return(true);
            }
            else
            {
                errorMessage = chain.ChainStatus.GetErrors();
                return(false);
            }
        }