コード例 #1
0
        public override bool ValidateServerCertificate(Uri uri, X509Certificate2 certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            if (_verifyHostname)
            {
                if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNameMismatch))
                {
                    Logger?.Error(null, $"{GetType().Name}: Certificate '{certificate.Subject}' does not match with host name '{uri.Host}'.");
                    return(false);
                }
            }

            var result = !sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateChainErrors);

            if (_useMachineCtx || chain.ChainPolicy.RevocationFlag != _revocationScope ||
                chain.ChainPolicy.RevocationMode != _revocationMode)
            {
                result = BuildChain(certificate, chain.ChainPolicy.ExtraStore, out var newChain);
                if (!result)
                {
                    Logger?.Error(null,
                                  $"{GetType().Name}: Certificate '{certificate.Subject}' failed validation. Reason: {CertHelper.ChainStatusToText(newChain.ChainStatus)}");
                }
            }

            return(result);
        }
コード例 #2
0
ファイル: TransferClient.cs プロジェクト: gkowieski/vm
        /// <summary>
        /// Callback to validate a server certificate.
        /// </summary>
        /// <remarks>
        /// The default implementation here allows for self-signed certificate within the intranet and
        /// the local computer otherwise it fails if the server certificate is not kosher.
        /// </remarks>
        bool ServerCertificateValidation(
            object sender,
            X509Certificate serverCertificate,
            X509Chain chain,
            SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors == SslPolicyErrors.None)
            {
                return(true);
            }

            if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateChainErrors) ||
                sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNameMismatch))
            {
                // allow self-signed certificates
                var z = Zone.CreateFromUrl(((WebRequest)sender).RequestUri.ToString());

                if (z.SecurityZone == SecurityZone.Intranet ||
                    z.SecurityZone == SecurityZone.MyComputer)
                {
                    return(true);
                }
            }

            return(false);
        }
コード例 #3
0
        private static bool CheckValidationResult(HttpRequestMessage message, X509Certificate2 certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            bool result = true;

            if (sslPolicyErrors == SslPolicyErrors.None)
            {
                return(result);
            }

            if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateChainErrors))
            {
                result &= _settings.WillIgnoreSSLCertificate.Value;
            }

            if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNameMismatch))
            {
                result &= _settings.WillIgnoreSSLHostname.Value;
            }

            if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNotAvailable))
            {
                result = false;
            }

            return(result);
        }
        public static int[] GetLdapCertProblems(X509Certificate certificate, X509Chain chain,
                                                SslPolicyErrors sslPolicyErrors, ILog log = null)
        {
            var certificateErrors = new List <int>();

            try
            {
                if (sslPolicyErrors == SslPolicyErrors.None)
                {
                    return(certificateErrors.ToArray());
                }

                var expDate = DateTime.Parse(certificate.GetExpirationDateString()).ToUniversalTime();
                var utcNow  = DateTime.UtcNow;
                if (expDate < utcNow && expDate.AddDays(1) >= utcNow)
                {
                    certificateErrors.Add((int)LdapCertificateProblem.CertExpired);
                }

                if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateChainErrors))
                {
                    certificateErrors.Add((int)LdapCertificateProblem.CertMalformed);
                }

                if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNameMismatch))
                {
                    if (log != null)
                    {
                        log.WarnFormat("GetLdapCertProblems: {0}",
                                       Enum.GetName(typeof(SslPolicyErrors), LdapCertificateProblem.CertCnNoMatch));
                    }

                    certificateErrors.Add((int)LdapCertificateProblem.CertCnNoMatch);
                }

                if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNotAvailable))
                {
                    if (log != null)
                    {
                        log.WarnFormat("GetLdapCertProblems: {0}",
                                       Enum.GetName(typeof(SslPolicyErrors), LdapCertificateProblem.CertCnNoMatch));
                    }

                    certificateErrors.Add((int)LdapCertificateProblem.CertUntrustedCa);
                }
            }
            catch (Exception ex)
            {
                if (log != null)
                {
                    log.ErrorFormat("GetLdapCertProblems() failed. Error: {0}", ex);
                }
                certificateErrors.Add((int)LdapCertificateProblem.CertUnrecognizedError);
            }

            return(certificateErrors.ToArray());
        }
コード例 #5
0
        private static bool IsValidRemoteParty(
            object sender,
            X509Certificate certificate,
            X509Chain chain,
            SslPolicyErrors errors)
        {
            if (errors.HasFlag(SslPolicyErrors.RemoteCertificateNotAvailable) ||
                errors.HasFlag(SslPolicyErrors.RemoteCertificateNameMismatch))
            {
                return(false);
            }

            return(true); //TODO
        }
コード例 #6
0
        static bool ServerCertificateCustomValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors)
        {
            foreach (var element in chain.ChainElements)
            {
                Log.Debug("Element name: {0}", element.Certificate.SubjectName.Name);
                Log.Debug("Element issuer name: {0}", element.Certificate.Issuer);
                Log.Debug("Element certificate valid until: {0}", element.Certificate.NotAfter);
                Log.Debug("Element certificate is valid: {0}", element.Certificate.Verify());
                Log.Debug("Element error status length: {0}", element.ChainElementStatus.Length);
                Log.Debug("Element information: {0}", element.Information);
                Log.Debug("Number of element extensions: {0}", element.Certificate.Extensions.Count);
                Log.Debug("Number of ChainElementStatuses: {0}", element.ChainElementStatus.Length);
                if (element.ChainElementStatus.Length > 0)
                {
                    for (int index = 0; index < element.ChainElementStatus.Length; index++)
                    {
                        Log.Debug("{0}: {1}", element.ChainElementStatus[index].Status, element.ChainElementStatus[index].StatusInformation);
                    }
                }
                Console.WriteLine(Environment.NewLine);
            }
            if (policyErrors == SslPolicyErrors.None)
            {
                Log.Debug("No TLS Policy Errors.");
                return(true);
            }

            if (policyErrors.HasFlag(SslPolicyErrors.RemoteCertificateChainErrors))
            {
                Log.Debug("TLS Policy Chain Errors");

                foreach (var status in chain.ChainStatus)
                {
                    Log.Debug($"Chain Status: {status.StatusInformation}");
                }
            }

            if (policyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNameMismatch))
            {
                Log.Debug("TLS Remote Certificate Name Mismatch");
            }

            if (policyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNotAvailable))
            {
                Log.Debug("TLS Remote Certificate Not Available");
            }

            return(false);
        }
コード例 #7
0
 public static bool ValidationCallback(HttpRequestMessage req, X509Certificate2 cert, X509Chain chain, SslPolicyErrors errors)
 {
     if (errors.HasFlag(SslPolicyErrors.RemoteCertificateNotAvailable))
     {
         return(false);
     }
     if (errors.HasFlag(SslPolicyErrors.RemoteCertificateNameMismatch))
     {
         return(false);
     }
     return(new X509Chain()
     {
         ChainPolicy = policy
     }.Build(cert));
 }
コード例 #8
0
        public override bool ValidateServerCertificate(Uri uri, X509Certificate2 certificate, X509Chain chain,
                                                       SslPolicyErrors sslPolicyErrors)
        {
            var now = DateTime.Now;

            if (_verifyHostname)
            {
                if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNameMismatch))
                {
                    Logger?.Error(null,
                                  $"{GetType().Name}: Certificate '{certificate.Subject}' does not match with host name '{uri.Host}'.");
                    return(false);
                }
            }

            if (!CertHelper.CheckValidity(certificate, now))
            {
                Logger?.Error(null,
                              $"{GetType().Name}: Certificate '{certificate.Subject}' is not valid at the time of validity check '{now}'.");
                return(false);
            }

            for (var i = chain.ChainElements.Count - 1; i >= 0; i--)
            {
                if (CertHelper.FindCertificate(_trustedCertificates, chain.ChainElements[i].Certificate))
                {
                    Logger?.Info($"{GetType().Name}: Trusting {uri} with certificate '{certificate.Subject}'.");
                    return(true);
                }
            }

            Logger?.Error(null,
                          $"{GetType().Name}: Unable to locate a certificate for {uri} in provided trusted certificates.");
            return(false);
        }
コード例 #9
0
        private bool CertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors == SslPolicyErrors.None)
            {
                return(true);
            }

            logger.LogError(
                "SMTP Server's certificate {CertificateSubject} issued by {CertificateIssuer} with thumbprint {CertificateThumbprint} and expiration date {CertificateExpirationDate} is considered invalid with {SslPolicyErrors} policy errors",
                certificate.Subject,
                certificate.Issuer,
                certificate.GetCertHashString(),
                certificate.GetExpirationDateString(),
                sslPolicyErrors);

            if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateChainErrors) && chain?.ChainStatus != null)
            {
                foreach (var chainStatus in chain.ChainStatus)
                {
                    logger.LogError("Status: {Status} - {StatusInformation}", chainStatus.Status, chainStatus.StatusInformation);
                }
            }

            return(false);
        }
コード例 #10
0
        public virtual void ValidateHttpEndpoint(Models.Endpoint endpoint, X509Chain?chain, SslPolicyErrors sslPolicyErrors)
        {
            if (endpoint.GetHttpIgnoreTlsCerts())
            {
                return; // Everything is OK
            }

            chain ??= new X509Chain();
            var customCertPem = endpoint.GetHttpCustomTlsCert();

            if (!string.IsNullOrWhiteSpace(customCertPem))
            {
                if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNotAvailable))
                {
                    // Unacceptable errors are present; throw
                    throw GetAppropriateException(false, chain, sslPolicyErrors, false);
                }
                foreach (var el in chain.ChainElements)
                {
                    if (el.ChainElementStatus != null && el.ChainElementStatus.Length > 0)
                    {
                        foreach (var status in el.ChainElementStatus)
                        {
                            if (status.Status == X509ChainStatusFlags.NoError)
                            {
                                continue;
                            }
                            if (status.Status.HasFlag(X509ChainStatusFlags.Cyclic) || status.Status.HasFlag(X509ChainStatusFlags.ExplicitDistrust) || status.Status.HasFlag(X509ChainStatusFlags.NotSignatureValid) || status.Status.HasFlag(X509ChainStatusFlags.Revoked))
                            {
                                // Unacceptable errors are present; throw
                                throw GetAppropriateException(false, chain, sslPolicyErrors, false);
                            }
                        }
                    }
                }

                // Everything looks good so far; load the custom cert
                var cert = LoadCert(false, customCertPem);

                foreach (var el in chain.ChainElements)
                {
                    if (el.Certificate.Thumbprint.Equals(cert.Thumbprint))
                    {
                        // Got a matching cert; everything is okay
                        return;
                    }
                }

                throw GetAppropriateException(false, chain, sslPolicyErrors, true);
            }
            else
            {
                // Use existing status information
                if (sslPolicyErrors == SslPolicyErrors.None)
                {
                    return; // OK
                }
                throw GetAppropriateException(false, chain, sslPolicyErrors, false);
            }
        }
コード例 #11
0
        public override bool ValidateServerCertificate(Uri uri, X509Certificate2 certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            var now = DateTime.Now;

            if (_verifyHostname)
            {
                if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNameMismatch))
                {
                    Logger?.Error(null, $"{GetType().Name}: Certificate '{certificate.Subject}' does not match with host name '{uri.Host}'.");
                    return(false);
                }
            }

            if (!CertHelper.CheckValidity(certificate, now))
            {
                Logger?.Error(null, $"{GetType().Name}: Certificate '{certificate.Subject}' is not valid at the time of validity check '{now}'.");
                return(false);
            }

            if (CertHelper.FindCertificate(_location, StoreName.TrustedPeople, certificate))
            {
                if (CertHelper.FindCertificate(_location, StoreName.Disallowed, certificate))
                {
                    Logger?.Error(null, $"{GetType().Name}: Certificate '{certificate.Subject}' is found in '{_location}\\Disallowed` store.");
                    return(false);
                }

                Logger?.Info($"{GetType().Name}: Trusting {uri} with certificate '{certificate.Subject}'.");
                return(true);
            }

            Logger?.Error(null, $"{GetType().Name}: Unable to locate a certificate for {uri} in '{_location}\\TrustedPeople` store.");
            return(false);
        }
コード例 #12
0
        private bool RemoteCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain,
                                                         SslPolicyErrors sslPolicyErrors, NetworkConfig clientNetworkConfig)
        {
            if (sslPolicyErrors == SslPolicyErrors.None)
            {
                return(true);
            }

            var validation = true;

            if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateChainErrors))
            {
                var isValidateChain = clientNetworkConfig.SslConfig.ValidateCertificateChain;
                if (isValidateChain)
                {
                    Logger.Warning("Certificate error:" + sslPolicyErrors);
                    validation = false;
                }
                else
                {
                    Logger.Info("SSL Configured to ignore Certificate chain validation. Ignoring:");
                }
                foreach (var status in chain.ChainStatus)
                {
                    Logger.Info("Certificate chain status:" + status.StatusInformation);
                }
            }
            if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNameMismatch))
            {
                var isValidateName = clientNetworkConfig.SslConfig.ValidateCertificateName;
                if (isValidateName)
                {
                    Logger.Warning("Certificate error:" + sslPolicyErrors);
                    validation = false;
                }
                else
                {
                    Logger.Info("Certificate name mismatched but client is configured to ignore Certificate name validation.");
                }
            }
            if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNotAvailable))
            {
                Logger.Warning("Certificate error:" + sslPolicyErrors);
                validation = false;
            }
            return(validation);
        }
コード例 #13
0
        /// <summary>
        /// Validates that terminal webservers are using a certificate that was signed
        /// by the BlockChyp root CA.
        /// </summary>
        /// <param name="request">The HTTP request.</param>
        /// <param name="cert">The server certificate served with the request.</param>
        /// <param name="chain">The certificate chain served with the request.</param>
        /// <param name="sslPolicyErrors">SSL verification failures.</param>
        public static bool ValidateTerminalCertificate(
            object request,
            X509Certificate2 cert,
            X509Chain chain,
            SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors == SslPolicyErrors.None)
            {
                return(true);
            }

            if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNotAvailable))
            {
                // Terminals should always serve a certificate.
                return(false);
            }

            if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateChainErrors))
            {
                // First, ignore that the root CA is unknown. We'll check that
                // the root of the chain matches our root CA at the end.
                chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
                chain.ChainPolicy.ExtraStore.Add(blockChypRootCertificate.Value);

                // Validate that the chain can be built.
                if (!chain.Build(cert) || chain.ChainElements.Count == 0)
                {
                    return(false);
                }

                // Now we know that the chain is valid, so we only have to
                // prove that the root of the chain is our root CA.
                if (chain.ChainElements[chain.ChainElements.Count - 1].Certificate.Thumbprint != blockChypRootCertificate.Value.Thumbprint)
                {
                    return(false);
                }
            }

            // Terminals on the local network use a static common name.
            if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNameMismatch))
            {
                return(cert.GetNameInfo(X509NameType.SimpleName, false) == TerminalCommonName);
            }

            return(false);
        }
コード例 #14
0
            static bool ValidateMyCert(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors sslErr)
            {
                bool returnValue = true;

                if (!splunkAddress.ToLower().StartsWith("https"))
                {
                    return(true);
                }

                if (sslErr.HasFlag(SslPolicyErrors.RemoteCertificateChainErrors))
                {
                    myLogger.LogError($"There are errors in the remote certificate chain.");
                    returnValue = false;
                }
                if (sslErr.HasFlag(SslPolicyErrors.RemoteCertificateNotAvailable))
                {
                    myLogger.LogError($"The remote certificate is not available.");
                    returnValue = false;
                }

                var caCertCommonName = getEnvironmentVariable("CA_CERT_COMMONNAME", "SplunkServerDefaultCert");
                var subjectName      = chain.ChainElements[0].Certificate.SubjectName.Name;

                //subjectName = "O=SplunkUser, CN=SplunkServerDefaultCert"

                string[] subjectNameParts = subjectName.Split(',');
                string   cn = "";

                foreach (var split in subjectNameParts)
                {
                    if (split.Trim().StartsWith("CN"))
                    {
                        cn = split.Split("=")[1];
                    }
                }

                myLogger.LogTrace($"commonName = {cn}");

                if (cn != caCertCommonName)
                {
                    returnValue = false;
                }

                return(returnValue);
            }
コード例 #15
0
        public virtual void ValidateLdap(X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            if (_settingsService.Ldap_SslIgnoreValidity)
            {
                return; // Everything is OK
            }

            if (!string.IsNullOrWhiteSpace(_settingsService.Ldap_SslValidCert))
            {
                if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNotAvailable))
                {
                    // Unacceptable errors are present; throw
                    throw GetAppropriateException(true, chain, sslPolicyErrors, false);
                }
                foreach (var el in chain.ChainElements)
                {
                    if (el.ChainElementStatus != null && el.ChainElementStatus.Length > 0)
                    {
                        foreach (var status in el.ChainElementStatus)
                        {
                            if (status.Status == X509ChainStatusFlags.NoError)
                            {
                                continue;
                            }
                            if (status.Status.HasFlag(X509ChainStatusFlags.Cyclic) || status.Status.HasFlag(X509ChainStatusFlags.ExplicitDistrust) || status.Status.HasFlag(X509ChainStatusFlags.NotSignatureValid) || status.Status.HasFlag(X509ChainStatusFlags.Revoked))
                            {
                                // Unacceptable errors are present; throw
                                throw GetAppropriateException(true, chain, sslPolicyErrors, false);
                            }
                        }
                    }
                }

                // Everything looks good so far; load the custom cert
                var cert = LoadCert(true, _settingsService.Ldap_SslValidCert);

                foreach (var el in chain.ChainElements)
                {
                    if (el.Certificate.Thumbprint.Equals(cert.Thumbprint))
                    {
                        // Got a matching cert; everything is okay
                        return;
                    }
                }

                throw GetAppropriateException(true, chain, sslPolicyErrors, true);
            }
            else
            {
                // Use existing status information
                if (sslPolicyErrors == SslPolicyErrors.None)
                {
                    return; // OK
                }
                throw GetAppropriateException(true, chain, sslPolicyErrors, false);
            }
        }
コード例 #16
0
        /// <summary>
        /// (internal for tests only)
        /// Validates a certificate.
        /// </summary>
        internal bool ValidateCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors policyErrors)
        {
            if (policyErrors == SslPolicyErrors.None)
            {
                return(true);
            }

            var validation = true;

            if (policyErrors.HasFlag(SslPolicyErrors.RemoteCertificateChainErrors))
            {
                if (_options.ValidateCertificateChain)
                {
                    _logger.LogWarning($"SSL certificate error: {policyErrors} (chain status: " +
                                       $" {string.Join(", ", chain.ChainStatus.Select(x => x.StatusInformation))}).");
                    validation = false;
                }
                else
                {
                    _logger.LogInformation("SSL certificate errors (chain validation) ignored by client configuration.");
                }
            }

            if (policyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNameMismatch))
            {
                if (_options.ValidateCertificateName)
                {
                    _logger.LogWarning($"SSL certificate error: {policyErrors}.");
                    validation = false;
                }
                else
                {
                    _logger.LogInformation("SSL certificate errors (name validation) ignored by client configuration.");
                }
            }

            if (policyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNotAvailable))
            {
                _logger.LogWarning($"SSL certificate error: {policyErrors}.");
                validation = false;
            }

            return(validation);
        }
コード例 #17
0
        private bool ValidateCertificate(object s, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
        {
            if (error.HasFlag(SslPolicyErrors.RemoteCertificateNameMismatch) || error.HasFlag(SslPolicyErrors.RemoteCertificateChainErrors))
            {
                // This is for local deployments. DevFabric generates its own certificate for load-balancing / port forwarding.
                const string AzureDevFabricCertificateSubject = "CN=127.0.0.1, O=TESTING ONLY, OU=Windows Azure DevFabric";
                if (cert.Subject == AzureDevFabricCertificateSubject)
                {
                    return(true);
                }
                var cert2 = new X509Certificate2(cert);
                if (this._trustedRestSubject == cert2.Subject && cert2.Thumbprint == this._trustedRestCertificateHash)
                {
                    return(true);
                }
            }

            return(error == SslPolicyErrors.None);
        }
コード例 #18
0
        private Exception GetAppropriateException(bool ldap, X509Chain chain, SslPolicyErrors sslPolicyErrors, bool customCertMismatch)
        {
            var stb = new StringBuilder();

            if (customCertMismatch)
            {
                stb.Append("\r\n✯ The certificate chain does not contain the custom certificate:");
                foreach (var el in chain.ChainElements)
                {
                    stb.Append($"\r\n  → Subject=\"{el.Certificate.Subject}\" (Thumbprint={el.Certificate.Thumbprint}) ");
                }
            }
            if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNameMismatch))
            {
                stb.Append("\r\n✯ The certificate name is mismatched");
            }
            if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNotAvailable))
            {
                stb.Append("\r\n✯ The certificate is unavailable");
            }
            if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateChainErrors) && !customCertMismatch)
            {
                stb.Append("\r\n✯ The certificate chain has errors:");
                foreach (var el in chain.ChainElements)
                {
                    stb.Append($"\r\n  → Subject=\"{el.Certificate.Subject}\" (Thumbprint={el.Certificate.Thumbprint}) ");
                    if (el.ChainElementStatus == null || el.ChainElementStatus.Length == 0)
                    {
                        stb.Append("[OK]");
                    }
                    else
                    {
                        foreach (var status in el.ChainElementStatus)
                        {
                            stb.Append($"[{status.StatusInformation.Trim()}]");
                        }
                    }
                }
            }

            return(SslException.CreateException(ldap, stb.ToString().Trim()));
        }
コード例 #19
0
        private bool ServerCertificateValidationCallback(object sender,
                                                         X509Certificate certificate,
                                                         X509Chain chain,
                                                         SslPolicyErrors sslpolicyerrors
                                                         )
        {
            if (sslpolicyerrors.HasFlag(SslPolicyErrors.None))
            {
                return(true);
            }

            if (
                sslpolicyerrors.HasFlag(SslPolicyErrors.RemoteCertificateNameMismatch) &&
                sslpolicyerrors.HasFlag(SslPolicyErrors.RemoteCertificateNotAvailable) &&
                allowSelfSigned)
            {
                return(true);
            }

            return(false);
        }
コード例 #20
0
 private bool CertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
 {
     if (!(IPAddress.IsLoopback(IpAddress)))
     {
         if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNameMismatch) ||
             certificate.GetCertHashString() != CertificateHash)
         {
             return(false);
         }
     }
     return(true);
 }
コード例 #21
0
        public static bool ValidateClient(object sender, X509Certificate remoteCertificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            // If we are not requiring a client certificate remote certificate will be null
            if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNotAvailable) && _clientCertRequired)
            {
                Console.WriteLine("Client Certificate Was Not Provided");
                return(false);
            }

            Console.WriteLine($"SSL Policy Errors: {sslPolicyErrors}");
            return(true);
        }
コード例 #22
0
        private bool ValidateServerCertificate(object sender, X509Certificate?certificate, X509Chain?chain, SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors == SslPolicyErrors.None)
            {
                return(true);
            }

            if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNotAvailable))
            {
                return(false);
            }

            if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNameMismatch) && _verifyCertificateName)
            {
                return(false);
            }

            if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateChainErrors) && _verifyCertificateAuthority)
            {
                if (_trustedCertificateAuthority is null || chain is null || certificate is null)
                {
                    return(false);
                }

                chain.ChainPolicy.ExtraStore.Add(_trustedCertificateAuthority);
                _ = chain.Build((X509Certificate2)certificate);

                for (var i = 0; i < chain.ChainElements.Count; i++)
                {
                    if (chain.ChainElements[i].Certificate.Thumbprint == _trustedCertificateAuthority.Thumbprint)
                    {
                        return(true);
                    }
                }

                return(false);
            }

            return(true);
        }
コード例 #23
0
        static bool CustomSSLCertificateValidation(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
        {
#if DEBUG
            //IMPORTANT - This should not be used in production code.
            //The purpose of this is to allow the use of a mismatching SSL certificate,
            //which is not expected to be required in third party or production.
            //This setting may create a "Man in the Middle" vulnerability.
            return(false == error.HasFlag(SslPolicyErrors.RemoteCertificateNotAvailable));
#else
            //This is the safe version of the above code.
            return(error == SslPolicyErrors.None);
#endif
        }
コード例 #24
0
        public override bool ValidateServerCertificate(Uri uri, X509Certificate2 certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            if (_verifyHostname)
            {
                if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNameMismatch))
                {
                    Logger?.Error(null, $"{GetType().Name}: Certificate '{certificate.Subject}' does not match with host name '{uri.Host}'.");
                    return(false);
                }
            }

            Logger?.Info($"{GetType().Name}: Trusting {uri} with provided certificate '{certificate.Subject}'.");
            return(true);
        }
コード例 #25
0
        /// <summary>
        /// Called by the US.OpenServer.Server and the US.OpenServer.Client.Client
        /// to verify the remote Secure Sockets Layer (SSL) certificate used for
        /// authentication.
        /// </summary>
        /// <param name="sender">An object that contains state information for this validation.</param>
        /// <param name="certificate">The certificate used to authenticate the remote party.</param>
        /// <param name="chain">The chain of certificate authorities associated with the remote certificate.</param>
        /// <param name="sslPolicyErrors">One or more errors associated with the remote certificate.</param>
        /// <returns>True if the specified certificate is accepted for authentication, otherwise False.</returns>
        public bool TlsCertificateValidationCallback(
            object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNameMismatch))
            {
                Log(Level.Error, "[TLS] Remote certificate name mismatch.");
                return(false);
            }

            if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNotAvailable))
            {
                if (TlsConfiguration.RequireRemoteCertificate)
                {
                    Log(Level.Error, "[TLS] Remote certificate not available.");
                    return(false);
                }
                else
                {
                    Log(Level.Debug, "[TLS] Remote certificate not available.");
                }
            }

            if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateChainErrors))
            {
                if (!TlsConfiguration.AllowCertificateChainErrors)
                {
                    Log(Level.Error, "[TLS] Remote certificate contains chain errors.");
                    return(false);
                }
                else
                {
                    Log(Level.Debug, "[TLS] Remote certificate contains chain errors.");
                }
            }
            Log(Level.Info, "[TLS] Certificate validated.");
            return(true);
        }
コード例 #26
0
        private bool ServerCheckValidation(object sender, X509Certificate certificate,
                                           X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors == SslPolicyErrors.None)
            {
                return(true);
            }

            if (settings.SslMode == MySqlSslMode.Preferred ||
                settings.SslMode == MySqlSslMode.Required)
            {
                //Tolerate all certificate errors.
                return(true);
            }

            if ((settings.SslMode == MySqlSslMode.VerifyCA ||
                 settings.SslMode == MySqlSslMode.VerifyFull) &&
                settings.CACertificateFile != null)
            {
                var result = chain.ChainStatus.Length == 1 &&
                             chain.ChainStatus[0].Status == X509ChainStatusFlags.UntrustedRoot &&
                             chain.ChainElements[chain.ChainElements.Count - 1].Certificate.Thumbprint.Equals(new X509Certificate2(settings.CACertificateFile).Thumbprint);
                if (settings.SslMode == MySqlSslMode.VerifyCA)
                {
                    return(result && !sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNotAvailable));
                }
                if (settings.SslMode == MySqlSslMode.VerifyFull)
                {
                    return(result &&
                           !sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNameMismatch) &&
                           !sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNotAvailable));
                }
            }

            return(false);
        }
コード例 #27
0
        private bool ValidateCertificateHttpHandler(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            if (_cancellationToken.IsCancellationRequested)
            {
                return(false);
            }

            IsVerified = sslPolicyErrors == SslPolicyErrors.None;
            if (IsVerified)
            {
                return(true);
            }

            if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNotAvailable))
            {
                Log.WriteLine(LogVerbosity.Minimal, MessageCategory.Error, Resources.Error_NoBrokerCertificate);
                _console.WriteError(Resources.Error_NoBrokerCertificate.FormatInvariant(Name));
                return(false);
            }

            lock (_verificationLock) {
                if (ConnectionInfo.IsUrlBased && ConnectionInfo.Uri.IsLoopback)
                {
                    return(true);
                }

                if (_certificateValidationResult.HasValue)
                {
                    return(_certificateValidationResult.Value);
                }

                Log.Write(LogVerbosity.Minimal, MessageCategory.General, Resources.Trace_SSLPolicyErrors.FormatInvariant(sslPolicyErrors));
                var hashString = GetCertHashString(certificate.GetCertHash());
                if (_certificateHash == null || !_certificateHash.EqualsOrdinal(hashString))
                {
                    Log.Write(LogVerbosity.Minimal, MessageCategory.Warning, Resources.Trace_UntrustedCertificate.FormatInvariant(certificate.Subject));

                    var message = Resources.CertificateSecurityWarning.FormatInvariant(ConnectionInfo.Uri.Host);
                    _certificateValidationResult = _services.Security().ValidateX509Certificate(certificate, message);
                    if (_certificateValidationResult.Value)
                    {
                        _certificateHash = hashString;
                    }
                }
                return(_certificateValidationResult ?? false);
            }
        }
コード例 #28
0
ファイル: RemoteBrokerClient.cs プロジェクト: Microsoft/RTVS
        private bool ValidateCertificateHttpHandler(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) {
            if (_cancellationToken.IsCancellationRequested) {
                return false;
            }

            IsVerified = sslPolicyErrors == SslPolicyErrors.None;
            if (IsVerified) {
                return true;
            }

            if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNotAvailable)) {
                Log.WriteAsync(LogVerbosity.Minimal, MessageCategory.Error, Resources.Error_NoBrokerCertificate).DoNotWait();
                _console.Write(Resources.Error_NoBrokerCertificate.FormatInvariant(Name));
                return false;
            }

            if (_services.MainThread.ThreadId == Thread.CurrentThread.ManagedThreadId) {
                // Prevent potential deadlock if handler enters on background thread, then re-enters on main thread
                // before ValidateX509CertificateAsync is able to transition to the UI thread.
                // At worst the connection fails
                return _certificateValidationResult.HasValue ? _certificateValidationResult.Value : false;
            }

            lock (_verificationLock) {
                if (_certificateValidationResult.HasValue) {
                    return _certificateValidationResult.Value;
                }

                var hashString = certificate.GetCertHashString();
                if (_certificateHash == null || !_certificateHash.EqualsOrdinal(hashString)) {
                    Log.WriteAsync(LogVerbosity.Minimal, MessageCategory.Warning, Resources.Trace_UntrustedCertificate.FormatInvariant(certificate.Subject)).DoNotWait();

                    var message = Resources.CertificateSecurityWarning.FormatInvariant(Uri.Host);
                    var task = _services.Security.ValidateX509CertificateAsync(certificate, message, _cancellationToken);
                    _services.Tasks.Wait(task, _cancellationToken);

                    _certificateValidationResult = task.Result;
                    if (_certificateValidationResult.Value) {
                        _certificateHash = hashString;
                    }
                }
                return _certificateValidationResult.HasValue ? _certificateValidationResult.Value : false;
            }
        }
コード例 #29
0
        private bool ValidateCertificateHttpHandler(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            IsVerified = sslPolicyErrors == SslPolicyErrors.None;
            if (!IsVerified)
            {
                if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNotAvailable))
                {
                    Log.WriteAsync(LogVerbosity.Minimal, MessageCategory.Error, Resources.Error_NoBrokerCertificate);
                    _console.Write(Resources.Error_NoBrokerCertificate);
                }
                else
                {
                    Log.WriteAsync(LogVerbosity.Minimal, MessageCategory.Warning, Resources.Trace_UntrustedCertificate.FormatInvariant(certificate.Subject)).DoNotWait();

                    var message = Resources.CertificateSecurityWarning.FormatInvariant(Uri.Host);
                    return(_services.Security.ValidateX509CertificateAsync(certificate, message).GetAwaiter().GetResult());
                }
            }
            return(IsVerified);
        }
        /// <summary>
        /// SSl Cert Validation Callback
        /// </summary>
        /// <param name="requestMessage">Http request message.</param>
        /// <param name="caCert">Server certificate.</param>
        /// <param name="clientCertificate">Client certificate</param>
        /// <param name="chain">Chain</param>
        /// <param name="sslPolicyErrors">SSL policy errors</param>
        /// <returns>true if valid cert</returns>
        internal bool CertificateValidationCallBack(
#pragma warning disable CA1801 // Unused by design
            HttpRequestMessage requestMessage,
#pragma warning restore CA1801 // Restore the warning
            X509Certificate2 caCert,
            X509Certificate2 clientCertificate,
            X509Chain chain,
            SslPolicyErrors sslPolicyErrors)
        {
            // If the certificate is a valid, signed certificate, return true.
            if (sslPolicyErrors == SslPolicyErrors.None)
            {
                _logger.LogTrace("This is a valid signed certificate.");
                return(true);
            }

            _logger.LogTrace("Not a authority signed certificate.");
            _logger.LogTrace("Server Cert RAW: {0}{1}", Environment.NewLine, Convert.ToBase64String(caCert.RawData));

            // When there is Remote Certificate Chain Error, verify the chain relation between the client and server certificates.
            if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateChainErrors))
            {
                _logger.LogTrace("Building certificate chain.");
                chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
                // add all your extra certificate chain
                chain.ChainPolicy.ExtraStore.Add(caCert);
                chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
                _logger.LogTrace("Client Cert RAW: {0}{1}", Environment.NewLine, Convert.ToBase64String(clientCertificate.RawData));
                bool isValid = chain.Build(clientCertificate);
                _logger.LogTrace("Is Chain successfully built: {0}", isValid);
                return(isValid);
            }

            // In all other cases, return false.
            _logger.LogError("SSL Certificate validation failed.");
            return(false);
        }
コード例 #31
0
        private bool MqttClient_CertificateValidationCallback(X509Certificate arg1, X509Chain arg2, SslPolicyErrors arg3, IMqttClientOptions arg4)
        {
            try
            {
                if (arg3 == SslPolicyErrors.None)
                {
                    return(true);
                }

                if (arg3.HasFlag(SslPolicyErrors.RemoteCertificateChainErrors))
                {
                    arg2.ChainPolicy.RevocationMode    = X509RevocationMode.NoCheck;
                    arg2.ChainPolicy.VerificationFlags = X509VerificationFlags.NoFlag;
                    arg2.ChainPolicy.ExtraStore.Add(_serverRootCa);

                    arg2.Build((X509Certificate2)_serverRootCa);
                    var res = arg2.ChainElements.Cast <X509ChainElement>().Any(a => a.Certificate.Thumbprint == _serverRootCa.Thumbprint);
                    return(res);
                }
            }
            catch { }

            return(false);
        }
コード例 #32
0
ファイル: Session.cs プロジェクト: liemqv/DotNetOpenServerSDK
        /// <summary>
        /// Called by the US.OpenServer.Server and the US.OpenServer.Client.Client
        /// to verify the remote Secure Sockets Layer (SSL) certificate used for
        /// authentication.
        /// </summary>
        /// <param name="sender">An object that contains state information for this validation.</param>
        /// <param name="certificate">The certificate used to authenticate the remote party.</param>
        /// <param name="chain">The chain of certificate authorities associated with the remote certificate.</param>
        /// <param name="sslPolicyErrors">One or more errors associated with the remote certificate.</param>
        /// <returns>True if the specified certificate is accepted for authentication, otherwise False.</returns>
        public bool TlsCertificateValidationCallback(
            object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNameMismatch))
            {
                Log(Level.Error, "[TLS] Remote certificate name mismatch.");
                return false;
            }

            if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNotAvailable))
            {
                if (TlsConfiguration.RequireRemoteCertificate)
                {
                    Log(Level.Error, "[TLS] Remote certificate not available.");
                    return false;
                }
                else
                {
                    Log(Level.Debug, "[TLS] Remote certificate not available.");
                }
            }

            if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateChainErrors))
            {
                if (!TlsConfiguration.AllowCertificateChainErrors)
                {
                    Log(Level.Error, "[TLS] Remote certificate contains chain errors.");
                    return false;
                }
                else
                {
                    Log(Level.Debug, "[TLS] Remote certificate contains chain errors.");
                }
            }
            Log(Level.Info, "[TLS] Certificate validated.");
            return true;
        }
コード例 #33
0
ファイル: Xtaller.cs プロジェクト: skw0rm/Xtall
        private bool CheckServerCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            var serverName = (sender is string) ? sender : ((WebRequest)sender).RequestUri.Host;
            _strategy.LogAction("verifying the server certificate for requested server '{0}'", serverName);
            if (sslPolicyErrors != SslPolicyErrors.None)
            {
                var reasons = new List<string>();
                if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNotAvailable))
                    reasons.Add("the certificate was not returned");
                if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNameMismatch))
                    reasons.Add(string.Format("the certificate name ({0}) does not match the requested server name",
                                              cert.Subject));
                if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateChainErrors))
                {
                    reasons.Add(string.Format("the certificate chain has errors ({0})",
                                              string.Join("; ", chain.ChainStatus.Select(x => x.StatusInformation))));
                }
                _strategy.LogStatus("The server is not trusted: {0}.", string.Join("; ", reasons));
                return false;
            }

            _strategy.LogAction("verifying that actual server '{0}' was trusted", cert.Subject);
            var m = Regex.Match(cert.Subject, "O=(?'orgid'[^,]+)");
            if (!m.Success)
            {
                _strategy.LogStatus("could not find the organization ID in the certificate subject");
                return false;
            }
            var g = m.Groups["orgid"];
            if (g == null)
            {
                _strategy.LogStatus("could not find the organization ID in the certificate subject (regex said it was there but didn't return it)");
                return false;
            }

            var orgId = g.Value;

            /* TODO
            if (!_info.TrustedOrgIds.Contains(orgId))
            {
                _environment.LogStatus("organization '{0}' is not trusted", orgId);
                return false;
            }
            */
            _strategy.LogStatus("the server is trusted.");
            return true;
        }
コード例 #34
0
        bool ValidateCertificate(object sender, X509Certificate clientCertificate, X509Chain chain, SslPolicyErrors sslpolicyerrors)
        {
            if (sslpolicyerrors.HasFlag(SslPolicyErrors.RemoteCertificateNotAvailable))
                return false;

            return options.ClientCertificateValidator(new X509Certificate2(clientCertificate)) == CertificateValidationResult.Valid;
        }
        private bool ValidateCertificate(object s, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
        {
            if (error.HasFlag(SslPolicyErrors.RemoteCertificateNameMismatch) || error.HasFlag(SslPolicyErrors.RemoteCertificateChainErrors))
            {

                // This is for local deployments. DevFabric generates its own certificate for load-balancing / port forwarding.
                const string AzureDevFabricCertificateSubject = "CN=127.0.0.1, O=TESTING ONLY, OU=Windows Azure DevFabric";
                if (cert.Subject == AzureDevFabricCertificateSubject)
                {
                    return true;
                }
                var cert2 = new X509Certificate2(cert);
                if (this._trustedRestSubject == cert2.Subject && cert2.Thumbprint == this._trustedRestCertificateHash)
                {
                    return true;
                }
            }

            return error == SslPolicyErrors.None;
        }
コード例 #36
0
        private bool RemoteCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors, ClientNetworkConfig clientNetworkConfig)
        {
            if (sslPolicyErrors == SslPolicyErrors.None)
            {
                return true;
            }

            var validation = true;

            if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateChainErrors))
            {
                var isValidateChain = clientNetworkConfig.GetSSLConfig().IsValidateCertificateChain();
                if (isValidateChain)
                {
                    Logger.Warning("Certificate error:" + sslPolicyErrors);
                    validation = false;
                }
                else
                {
                    Logger.Info("SSL Configured to ignore Certificate chain validation. Ignoring:");
                }
                foreach (var status in chain.ChainStatus)
                {
                    Logger.Info("Certificate chain status:" + status.StatusInformation);
                }
            }
            if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNameMismatch))
            {
                var isValidateName = clientNetworkConfig.GetSSLConfig().IsValidateCertificateName();
                if (isValidateName)
                {
                    Logger.Warning("Certificate error:" + sslPolicyErrors);
                    validation = false;
                }
                else
                {
                    Logger.Info("Certificate name mismatched but client is configured to ignore Certificate name validation.");
                }
            }
            if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNotAvailable))
            {
                Logger.Warning("Certificate error:" + sslPolicyErrors);
                validation = false;
            }
            return validation;
        }