Ejemplo n.º 1
0
        public static string GetSslErrorsString(this SslPolicyErrors spe)
        {
            Log.Start();
#if DEBUG
            Log.Debug("(GetSslErrorsString) Policy Value: {0}", spe.ToString());
#endif
#if !DEBUG && VERBOSE
            Log.Verbose("(GetSslErrorsString) Policy Value: {0}", spe.ToString());
#endif
            switch (spe)
            {
            case SslPolicyErrors.RemoteCertificateChainErrors:
                return("Remote Certificate Chain Errors");

            case SslPolicyErrors.RemoteCertificateNameMismatch:
                return("Remote Certificate Name Mismatch");

            case SslPolicyErrors.RemoteCertificateNotAvailable:
                return("Remote Certificate Not Available");

            default:
            case SslPolicyErrors.None:
                return("");
            }
        }
Ejemplo n.º 2
0
        public bool ValidateCertificateSSL(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors err)
        {
#if DEBUG_CertificateSSL
            stConsole.WriteHeader(
                "SSL Validate Certificate: " + Environment.NewLine +
                "- SSL Policy Errors: " + err.ToString() + Environment.NewLine +
                "- X509 Certificate: " + cert.ToString()
                );
#endif
            if (this.wHttpFakeCeretSSL)
            {
                return(true);
            }
            if (err == System.Net.Security.SslPolicyErrors.None)
            {
                return(true);
            }
            if (this.wHttpExtMessage)
            {
                this.iLog.ToLogAndLine(
                    System.Reflection.MethodBase.GetCurrentMethod(),
                    string.Format(
                        fmtLog[1],
                        global::stNet.Properties.Resources.httpError,
                        cert.Subject,
                        err.ToString()
                        )
                    );
            }
            return(false);
        }
Ejemplo n.º 3
0
        public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
#if !UNITY_EDITOR
            System.Console.WriteLine("NET: SSL Cert: " + sslPolicyErrors.ToString());
#else
            Debug.LogWarning("SSL Cert Error: " + sslPolicyErrors.ToString());
#endif
            return(true);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Validates the remote certificate.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="certificate">The certificate.</param>
        /// <param name="chain">The chain.</param>
        /// <param name="sslPolicyErrors">The SSL policy errors.</param>
        /// <returns></returns>
        private bool ValidateRemoteCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors == SslPolicyErrors.None)
            {
                return(true);
            }

            if (!AllowUnstrustedCertificate)
            {
                OnError(new Exception(sslPolicyErrors.ToString()));
                return(false);
            }

                        #if DEBUG
            //In debug mode, ignore certificate name mismatch error
            if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNameMismatch) == SslPolicyErrors.RemoteCertificateNameMismatch)
            {
                return(true);
            }
                        #endif

            //Not a remote certificate error
            if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors) == 0)
            {
                OnError(new Exception(sslPolicyErrors.ToString()));
                return(false);
            }

            if (chain != null && chain.ChainStatus != null)
            {
                foreach (X509ChainStatus status in chain.ChainStatus)
                {
                    if ((certificate.Subject == certificate.Issuer) &&
                        (status.Status == X509ChainStatusFlags.UntrustedRoot))
                    {
                        // Self-signed certificates with an untrusted root are valid.
                        continue;
                    }
                    else
                    {
                        if (status.Status != X509ChainStatusFlags.NoError)
                        {
                            OnError(new Exception(sslPolicyErrors.ToString()));
                            // If there are any other errors in the certificate chain, the certificate is invalid,
                            // so the method returns false.
                            return(false);
                        }
                    }
                }
            }

            // When processing reaches this line, the only errors in the certificate chain are
            // untrusted root errors for self-signed certificates. These certificates are valid
            // for default Exchange server installations, so return true.
            return(true);
        }
Ejemplo n.º 5
0
        // The following method is invoked by the RemoteCertificateValidationDelegate.
        public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            string error       = "";
            int    numfindings = 0;

            if (sslPolicyErrors.ToString().Contains("RemoteCertificateNameMismatch"))
            {
                numfindings++;
                error = error + numfindings.ToString() + ") There was a naming mismatch between the host connected to and its SSL certificate.\r\n\r\n\r\n";
            }
            if (sslPolicyErrors.ToString().Contains("RemoteCertificateChainErrors"))
            {
                error = error + "One or more errors were also found while validating the certificate chain for the server's SSL certificate.\r\n\r\n";
            }
            if (filteroff)
            {
                X509Chain certChain = chain;

                // build the cert chain from the remote cert
                certChain.ChainPolicy.RevocationMode = X509RevocationMode.Online;
                // this is a security auditing tool, check the whole chain
                certChain.ChainPolicy.RevocationFlag    = X509RevocationFlag.EntireChain;
                certChain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags;
                certChain.ChainPolicy.VerificationTime  = DateTime.Now;
                // allow up to a minute for this
                certChain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 0, 30);

                try
                {
                    certChain.Build(new X509Certificate2(certificate));
                }
                catch (AuthenticationException)
                {
                    //ignore here, handled in the other check
                }
                foreach (X509ChainElement element in chain.ChainElements)
                {
                    if (certChain.ChainStatus.Length > 1)
                    {
                        error = error + "Certificate issuer name: " + element.Certificate.Issuer + "\r\n";
                        error = error + "Certificate valid until: " + element.Certificate.NotAfter.ToString() + "\r\n";
                        error = error + "Certificate is valid: " + element.Certificate.Verify().ToString() + "\r\n\r\n";
                        for (int index = 0; index < element.ChainElementStatus.Length; index++)
                        {
                            numfindings++;
                            error = error + numfindings.ToString() + ") " + element.ChainElementStatus[index].Status.ToString() + "\r\n\r\n";
                            error = error + element.ChainElementStatus[index].StatusInformation + "\r\n\r\n";
                        }
                    }
                }
            }
            throw new AuthenticationException(error);
            // Do not allow this client to communicate with unauthenticated servers.
        }
Ejemplo n.º 6
0
        private bool ValidateRemoteCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            RemoteCertificateValidationCallback serverCertificateValidationCallback = ServicePointManager.ServerCertificateValidationCallback;

            if (serverCertificateValidationCallback != null)
            {
                return(serverCertificateValidationCallback(sender, certificate, chain, sslPolicyErrors));
            }
            if (sslPolicyErrors == SslPolicyErrors.None)
            {
                return(true);
            }
            if (base.Security.AllowNameMismatchCertificate)
            {
                sslPolicyErrors &= ~SslPolicyErrors.RemoteCertificateNameMismatch;
            }
            if (base.Security.AllowCertificateChainErrors)
            {
                sslPolicyErrors &= ~SslPolicyErrors.RemoteCertificateChainErrors;
            }
            if (sslPolicyErrors == SslPolicyErrors.None)
            {
                return(true);
            }
            if (!base.Security.AllowUnstrustedCertificate)
            {
                OnError(new Exception(sslPolicyErrors.ToString()));
                return(false);
            }
            if (sslPolicyErrors != 0 && sslPolicyErrors != SslPolicyErrors.RemoteCertificateChainErrors)
            {
                OnError(new Exception(sslPolicyErrors.ToString()));
                return(false);
            }
            if (chain != null && chain.ChainStatus != null)
            {
                X509ChainStatus[] chainStatus = chain.ChainStatus;
                for (int i = 0; i < chainStatus.Length; i++)
                {
                    X509ChainStatus x509ChainStatus = chainStatus[i];
                    if ((!(certificate.Subject == certificate.Issuer) || x509ChainStatus.Status != X509ChainStatusFlags.UntrustedRoot) && x509ChainStatus.Status != 0)
                    {
                        OnError(new Exception(sslPolicyErrors.ToString()));
                        return(false);
                    }
                }
            }
            return(true);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Get list of SSL policy errors with descriptions.
        /// This method checks SSL policy errors and mapping them to user-friendly descriptions.
        /// To update SSL policy errors description please update <see cref="_sslPolicyErrorsMapping"/>.
        /// </summary>
        /// <returns>Diagnostic data as a formatted string</returns>
        public static string ResolveSslPolicyErrorsMessage(SslPolicyErrors sslErrors)
        {
            string diagInfoHeader = $"SSL Policy Errors";
            var    diagInfo       = new List <KeyValuePair <string, string> >();

            if (sslErrors == SslPolicyErrors.None)
            {
                diagInfo.Add(new KeyValuePair <string, string>(sslErrors.ToString(), _sslPolicyErrorsMapping[sslErrors]));
                return(GetFormattedData(diagInfoHeader, diagInfo));
            }

            // Since we can get several SSL policy errors we should check all of them
            foreach (SslPolicyErrors errorCode in Enum.GetValues(typeof(SslPolicyErrors)))
            {
                if ((sslErrors & errorCode) != 0)
                {
                    string errorValue   = errorCode.ToString();
                    string errorMessage = string.Empty;

                    if (!_sslPolicyErrorsMapping.TryGetValue(errorCode, out errorMessage))
                    {
                        errorMessage = "Could not resolve related error message";
                    }

                    diagInfo.Add(new KeyValuePair <string, string>(errorValue, errorMessage));
                }
            }

            return(GetFormattedData(diagInfoHeader, diagInfo));
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Validate the server cert.  SSLPolicyErrors will be
        /// pre-filled with the errors you got.
        ///
        /// If there is an error in the cert, OnIvalidCertificate will be called.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="certificate"></param>
        /// <param name="chain"></param>
        /// <param name="sslPolicyErrors"></param>
        /// <returns></returns>
        protected bool ValidateServerCertificate(object sender,
                                                 X509Certificate certificate,
                                                 X509Chain chain,
                                                 SslPolicyErrors sslPolicyErrors)
        {
            // Note: Don't write servers with Jabber-Net, please.  :)
            if (m_server)
            {
                return(true);
            }

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

            if ((sslPolicyErrors & (sslPolicyErrors ^ AllowedSSLErrors)) == SslPolicyErrors.None)
            {
                // Huh.  Maybe there should be a listener method for this.
                return(true);
            }

            if (m_listener.OnInvalidCertificate(this, certificate, chain, sslPolicyErrors))
            {
                return(true);
            }

            Debug.WriteLine("Certificate error: {0}", sslPolicyErrors.ToString());

            // Do not allow this client to communicate with unauthenticated servers.
            return(false);
        }
Ejemplo n.º 9
0
 private bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
 {
     if (sslPolicyErrors == SslPolicyErrors.None || this.trustAnyCertificate)
     {
         return(true);
     }
     if (certificate != null)
     {
         this.certificateError = string.Format(CultureInfo.InvariantCulture, " {0}\r\n", new object[]
         {
             certificate.Subject
         });
     }
     this.certificateError = string.Format(CultureInfo.InvariantCulture, "Name:{0} SslPolicyErrors:{1}", new object[]
     {
         this.certificateError,
         sslPolicyErrors.ToString()
     });
     if (chain != null)
     {
         foreach (X509ChainStatus x509ChainStatus in chain.ChainStatus)
         {
             this.certificateError = string.Format(CultureInfo.InvariantCulture, "{0} {1} {2} {3} {4}", new object[]
             {
                 this.certificateError,
                 Environment.NewLine,
                 x509ChainStatus.Status.ToString(),
                 Environment.NewLine,
                 x509ChainStatus.StatusInformation
             });
         }
     }
     return(false);
 }
Ejemplo n.º 10
0
        public async Task UseCallback_BadCertificate_ExpectedPolicyErrors(string url, SslPolicyErrors expectedErrors)
        {
            if (!BackendSupportsCustomCertificateHandlingAndClientSupportsDHECipherSuites)
            {
                return;
            }

            if (PlatformDetection.IsUap)
            {
                // UAP HTTP stack caches connections per-process. This causes interference when these tests run in
                // the same process as the other tests. Each test needs to be isolated to its own process.
                // See dicussion: https://github.com/dotnet/corefx/issues/21945
                RemoteInvoke((remoteUrl, remoteExpectedErrors, useManagedHandlerString) =>
                {
                    UseCallback_BadCertificate_ExpectedPolicyErrors_Helper(
                        remoteUrl,
                        bool.Parse(useManagedHandlerString),
                        (SslPolicyErrors)Enum.Parse(typeof(SslPolicyErrors), remoteExpectedErrors)).Wait();

                    return(SuccessExitCode);
                }, url, expectedErrors.ToString(), UseManagedHandler.ToString()).Dispose();
            }
            else
            {
                await UseCallback_BadCertificate_ExpectedPolicyErrors_Helper(url, UseManagedHandler, expectedErrors);
            }
        }
Ejemplo n.º 11
0
        private static bool OnCertificateValidation(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            Console.WriteLine("Server Certificate Issued To: {0}", certificate.Subject);

            Console.WriteLine("Server Certificate Issued By: {0}", certificate.Issuer);


            // Return true if there are no policy errors

            // The certificate can also be manually verified to

            //make sure it meets your specific // policies by

            //   interrogating the x509Certificate object.

            if (errors != SslPolicyErrors.None)
            {
                Console.WriteLine("Server Certificate Validation Error");

                Console.WriteLine(errors.ToString());

                return(false);
            }

            else
            {
                Console.WriteLine("No Certificate Validation Errors");

                return(true);
            }
        }
Ejemplo n.º 12
0
 private static bool RemoteCertificateValidationCallback(Object sender, X509Certificate certificate, X509Chain chain,
                                                         SslPolicyErrors sslPolicyErrors)
 {
     System.Console.Out.WriteLine("Certificate Issuer = " + (certificate == null?"null":certificate.Issuer));
     System.Console.Out.WriteLine("Certificate Error = " + sslPolicyErrors.ToString());
     return(true);
 }
Ejemplo n.º 13
0
        private bool ValidateServerCertificate(object sender,
                                               X509Certificate certificate,
                                               X509Chain chain,
                                               SslPolicyErrors sslPolicyErrors)
        {
            Tracer.DebugFormat("ValidateServerCertificate: Issued By {0}", certificate.Issuer);
            if (sslPolicyErrors == SslPolicyErrors.None)
            {
                return(true);
            }

            Tracer.WarnFormat("Certificate error: {0}", sslPolicyErrors.ToString());
            if (sslPolicyErrors == SslPolicyErrors.RemoteCertificateChainErrors)
            {
                Tracer.Error("Chain Status errors: ");
                foreach (X509ChainStatus status in chain.ChainStatus)
                {
                    Tracer.Error("*** Chain Status error: " + status.Status);
                    Tracer.Error("*** Chain Status information: " + status.StatusInformation);
                }
            }
            else if (sslPolicyErrors == SslPolicyErrors.RemoteCertificateNameMismatch)
            {
                Tracer.Error("Mismatch between Remote Cert Name.");
            }
            else if (sslPolicyErrors == SslPolicyErrors.RemoteCertificateNotAvailable)
            {
                Tracer.Error("The Remote Certificate was not Available.");
            }

            // Configuration may or may not allow us to connect with an invliad broker cert.
            return(AcceptInvalidBrokerCert);
        }
Ejemplo n.º 14
0
        private bool CertificateValidationCallBack(object sender,
                                                   X509Certificate certificate,
                                                   X509Chain chain,
                                                   SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors != SslPolicyErrors.None)
            {
                Failure(String.Format("Certificate errors: {0}", sslPolicyErrors.ToString()), Url.AbsoluteUri);
                return(false);
            }

            DateTime expirationTime;

            if (DateTime.TryParse(certificate.GetExpirationDateString(), out expirationTime))
            {
                TimeSpan expiringIn = expirationTime - DateTime.UtcNow;
                if (expiringIn < TimeSpan.FromDays(10))
                {
                    Degraded(String.Format("Certificate is about to expire! Expiration Date: {0}", expirationTime), Url.AbsoluteUri);
                }
                Success(String.Format("Certificate is ok. Expiring in {0} days.", (int)expiringIn.TotalDays), Url.AbsoluteUri);
            }
            else
            {
                Failure(String.Format("Unable to parse certificate expiration date. Expiration value: " + certificate.GetExpirationDateString()));
            }
            return(true);
        }
Ejemplo n.º 15
0
        private bool CertificateValidationCallback(object sender, X509Certificate certificate,
                                                   X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors == SslPolicyErrors.None)
            {
                return(true);
            }

            if (sslPolicyErrors == SslPolicyErrors.RemoteCertificateChainErrors)
            {
                Console.WriteLine($"The X509Chain.ChainStatus returned an array of " +
                                  $"X509ChainStatus objects containing error information.");
            }
            else if (sslPolicyErrors == SslPolicyErrors.RemoteCertificateNameMismatch)
            {
                Console.WriteLine("There was a mismatch of the name on a certificate.");
            }
            else if (sslPolicyErrors == SslPolicyErrors.RemoteCertificateNotAvailable)
            {
                Console.WriteLine("No certificate was available.");
            }
            else
            {
                Console.WriteLine("SSL Certificate Validation Error!");
            }

            Console.WriteLine("");
            Console.WriteLine("SSL Certificate Validation Error!");
            Console.WriteLine(sslPolicyErrors.ToString());

            return(false);
        }
Ejemplo n.º 16
0
        private static bool ServerCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            var request = sender as HttpWebRequest;

            var host = request != null
                                ? request.Host
                                : GetHostFromFullAddress(sender as string) ?? "unknown";

            if (sslPolicyErrors != SslPolicyErrors.None)
            {
                Mvx.Resolve <ILogger>().LogMessage("WARNING: Following certificate was not found as valid. \n website: {0} \n certificate: {1} \n cause: {2}",
                                                   host,
                                                   certificate.ToString(true),
                                                   sslPolicyErrors.ToString());

                return(false);
            }

            // If the certificate is valid but not part of our pinned certs.
            if (request == null || Hosts.None(host.EndsWith))
            {
                return(true);
            }

            var publicKeyString = certificate.GetPublicKeyString();

            return(PinnedKeys.Any(p => p.Equals(publicKeyString, StringComparison.InvariantCultureIgnoreCase)));
        }
Ejemplo n.º 17
0
        private static bool cb_cert(
            object sender,
            X509Certificate certificate,
            X509Chain chain,
            SslPolicyErrors policyErrors)
        {
            bool flag = policyErrors == SslPolicyErrors.None;

            if (Link.nocheck || certificate == null)
            {
                return(true);
            }
            stat.imsg("Certificate validation test {0} {1} {2}", (object)flag, (object)certificate.Subject, (object)policyErrors.ToString());
            if (!flag)
            {
                if (Link.certs_check(certificate.Subject))
                {
                    flag = true;
                }
                if (!flag)
                {
                    stat.imsg("Bad Certificate: " + certificate.Subject + " " + policyErrors.ToString() + ", shall we accept it?");
                    Link.certs_add(certificate.Subject);
                    flag = true;
                }
            }
            return(flag);
        }
Ejemplo n.º 18
0
        public bool OnValidationCallback(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors errors)
        {
            if (errors.ToString() != "None")
            {
                MessageBox.Show("Please click yes on the next dialog box.\nThis will allow us to install the Net7 certificate.", "Certificate Install",
                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                try
                {
                    X509Store Certificate = new X509Store(StoreName.Root);

                    X509Certificate2 cert2 = new X509Certificate2(cert);

                    Certificate.Open(OpenFlags.ReadWrite);

                    // Add Certificate
                    Certificate.Add(cert2);
                    Certificate.Close();
                }
                catch (Exception e)
                {
                    MessageBox.Show("Error installing certificate: " + e.ToString());
                }
            }
            else
            {
                MessageBox.Show("Certificate is installed!");
            }

            // Remove this message
            ServicePointManager.ServerCertificateValidationCallback = null;

            return true;
        }
Ejemplo n.º 19
0
        public bool OnValidationCallback(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors errors)
        {
            if (errors.ToString() != "None")
            {
                MessageBox.Show("Please click yes on the next dialog box.\nThis will allow us to install the Net7 certificate.", "Certificate Install",
                                MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                try
                {
                    X509Store Certificate = new X509Store(StoreName.Root);

                    X509Certificate2 cert2 = new X509Certificate2(cert);

                    Certificate.Open(OpenFlags.ReadWrite);

                    // Add Certificate
                    Certificate.Add(cert2);
                    Certificate.Close();
                }
                catch (Exception e)
                {
                    MessageBox.Show("Error installing certificate: " + e.ToString());
                }
            }
            else
            {
                MessageBox.Show("Certificate is installed!");
            }

            // Remove this message
            ServicePointManager.ServerCertificateValidationCallback = null;

            return(true);
        }
Ejemplo n.º 20
0
        private bool ValidateServerCertificate(object sender,
                                               X509Certificate certificate,
                                               X509Chain chain,
                                               SslPolicyErrors sslPolicyErrors)
        {
            try
            {
                _certificate = new X509Certificate2(certificate);

                var msg = $"Domain {_domain.Uri}: " +
                          $"{certificate.Subject} " +
                          $"from {certificate.GetEffectiveDateString()} " +
                          $"to {certificate.GetExpirationDateString()} | " +
                          $"issued by {certificate.Issuer} | " +
                          $"policy errors: {sslPolicyErrors.ToString()} | " +
                          $"verify result: {_certificate.Verify()}";

                _messages.Add(msg);
                _logger.LogDebug(msg);

                return(true);
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Error validating certificate");
                return(false);
            }
        }
Ejemplo n.º 21
0
        public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors == SslPolicyErrors.None)
            {
                return(true);
            }

            throw new Exception(sslPolicyErrors.ToString());
        }
Ejemplo n.º 22
0
        private bool ServerCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors != SslPolicyErrors.None)
            {
                _logger.LogError(sslPolicyErrors.ToString());
            }

            return(true);
        }
Ejemplo n.º 23
0
        private bool ServerValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors)
        {
            // save for debugging
            this.Certificate  = certificate.ToString();
            this.PolicyErrors = policyErrors.ToString();

            // certificate is accepted
            return(true);
        }
Ejemplo n.º 24
0
        private bool ValidateRemoteCertificate(
            object sender,
            X509Certificate certificate,
            X509Chain chain,
            SslPolicyErrors sslPolicyErrors)
        {
            RemoteCertificateValidationCallback validationCallback = ServicePointManager.ServerCertificateValidationCallback;

            if (validationCallback != null)
            {
                return(validationCallback(sender, certificate, chain, sslPolicyErrors));
            }
            if (sslPolicyErrors == SslPolicyErrors.None)
            {
                return(true);
            }
            if (!this.AllowUnstrustedCertificate)
            {
                this.OnError(new Exception(sslPolicyErrors.ToString()));
                return(false);
            }

            if (sslPolicyErrors != SslPolicyErrors.None && sslPolicyErrors != SslPolicyErrors.RemoteCertificateChainErrors)
            {
                this.OnError(new Exception(sslPolicyErrors.ToString()));
                return(false);
            }

            if (chain != null && chain.ChainStatus != null)
            {
                foreach (X509ChainStatus chainStatu in chain.ChainStatus)
                {
                    if ((!(certificate.Subject == certificate.Issuer) ||
                         chainStatu.Status != X509ChainStatusFlags.UntrustedRoot) &&
                        chainStatu.Status != X509ChainStatusFlags.NoError)
                    {
                        this.OnError(new Exception(sslPolicyErrors.ToString()));
                        return(false);
                    }
                }
            }

            return(true);
        }
Ejemplo n.º 25
0
        private bool ValidateCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors == SslPolicyErrors.None)
            {
                return(true);
            }

            Log.Send($"Server certificate failed to validate: {sslPolicyErrors.ToString()}", LogLevel.Warning);
            return(false);
        }
Ejemplo n.º 26
0
        private bool ServicePointManager_ServerCertificateValidationCallback(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors != SslPolicyErrors.None)
            {
                Trace.TraceWarning("Certification error found: {0}", sslPolicyErrors.ToString());
                return(ConfigurationAccessor.IgnoreCertificationError);
            }

            return(true);
        }
 static bool CertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
 {
     if (sslPolicyErrors != SslPolicyErrors.None)
     {
         if (sslPolicyErrors == SslPolicyErrors.RemoteCertificateChainErrors)
         {
             //Make sure the only error is an untrusted root
             //(because we're assuming it's a self-signed certificate and
             // we're going to check it against an internal list of public keys)
             bool failed = false;
             foreach (X509ChainStatus status in chain.ChainStatus)
             {
                 if (status.Status != X509ChainStatusFlags.UntrustedRoot)
                 {
                     failed = true;
                     break;
                 }
             }
             //Pull the public key out of the certificate
             NodePublicKey key = NodePublicKey.BuildWith(new FieldPublicKey(certificate.GetPublicKeyString()));
             if (!failed && PublicKeyRingHasKey(key))
             {
                 return(true);
             }
             else
             {
                 Console.WriteLine("SSL Certificate Validation Error!");
                 Console.WriteLine(sslPolicyErrors.ToString());
                 return(false);
             }
         }
         else
         {
             Console.WriteLine("SSL Certificate Validation Error!");
             Console.WriteLine(sslPolicyErrors.ToString());
             return(false);
         }
     }
     else
     {
         return(true);
     }
 }
Ejemplo n.º 28
0
        /// <summary>
        /// Validate that the reverseProxySslThumbprint matches the reverse proxy cert thumbrint installed on ServiceFabric nodes
        /// </summary>
        /// <returns></returns>
        private static bool ValidateRemoteCert(HttpRequestMessage sender, X509Certificate2 certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            // If cert is known, return true
            if (!string.IsNullOrEmpty(_ReverseProxySslThumbprint) && (certificate.Thumbprint.ToLower() == _ReverseProxySslThumbprint.ToLower()))
            {
                return(true);
            }
            else
            {
                // If there are any ssl policy errors, log it
                if (sslPolicyErrors != System.Net.Security.SslPolicyErrors.None)
                {
                    ServiceEventSource.Current.Message($"ReverseProxySslError: {sslPolicyErrors.ToString()}");
                    _StaticLogger.LogInformation($"ReverseProxySslError: {sslPolicyErrors.ToString()}");
                }

                return(sslPolicyErrors == System.Net.Security.SslPolicyErrors.None);
            }
        }
 private static bool CertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
 {
     bool ok = true;
     if(sslPolicyErrors != SslPolicyErrors.None)
     {
         Console.WriteLine("SSL Certificate Validation Error!........");
         Console.WriteLine(sslPolicyErrors.ToString());
         ok = false;
     }
     return ok;
 }
Ejemplo n.º 30
0
 public CertificateValidationForm(string hostName, X509Certificate certificate,
                                  X509Chain chain,
                                  SslPolicyErrors sslPolicyErrors)
 {
     InitializeComponent();
     _certificate     = certificate;
     _chain           = chain;
     _sslPolicyErrors = sslPolicyErrors;
     this.Text       += hostName;
     label1.Text      = sslPolicyErrors.ToString() + "\n" + "Do you want to continue";
 }
Ejemplo n.º 31
0
        public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors == SslPolicyErrors.None)
            {
                return(true);
            }

            Trace.WriteLine("Certificate error: {0}", sslPolicyErrors.ToString());
            // Do not allow this client to communicate with unauthenticated servers.
            return(false);
        }
Ejemplo n.º 32
0
 static bool AllTrustedValidationCallback(object req, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
 {
     Debug.WriteLine("protocol: " + ((HttpWebRequest)req).ProtocolVersion.ToString());
     Debug.WriteLine("cert: " + certificate.Subject);
     foreach (X509ChainElement el in chain.ChainElements)
     {
         Debug.WriteLine("chain: " + el.Certificate.Subject);
     }
     Debug.WriteLine("policyerror: " + (errors.ToString()));
     return(true);
 }
Ejemplo n.º 33
0
		private static bool ValidateServerCertificate
			(Object sender, X509Certificate certificate,
			 X509Chain chain, SslPolicyErrors sslPolicyErrors)
		{
			if (sslPolicyErrors == SslPolicyErrors.None)
				return true;
			else
			{
				//TODO:Potential for options for certificate validation!
#if DEBUG_CRYPTO
				Console.Error.WriteLine(String.Format("Invalid Cert {0}: {1}",certificate.Subject,sslPolicyErrors.ToString()));
#endif
				return true;
			}
		}  
        private bool ValidateRemoteCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors != SslPolicyErrors.None)
            {
                Console.WriteLine("SSL Certificate Validation Error!");
                Console.WriteLine(sslPolicyErrors.ToString());
                Console.WriteLine("Chain status:");
                foreach (var s in chain.ChainStatus)
                {
                    Console.WriteLine("\t" + s.Status + " : " + s.StatusInformation);
                }
                return false;
            }

            return true;
        }
Ejemplo n.º 35
0
        public static bool ValidateServerCertificate (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
#if !UNITY_EDITOR
            System.Console.WriteLine( "NET: SSL Cert: " + sslPolicyErrors.ToString() );
#else
            Debug.LogWarning("SSL Cert Error: " + sslPolicyErrors.ToString ());
#endif
            return true;
        }
 private bool ServerCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
 {
     var msg = string.Format(CultureInfo.InvariantCulture, "Validating SSL with an ignore setting of ({0})", this.ignoreSslErrors);
     this.LogMessage(msg, Severity.Informational, Verbosity.Detailed);
     msg = string.Format(CultureInfo.InvariantCulture, "Current Result: ({0})", sslPolicyErrors.ToString());
     this.LogMessage(msg, Severity.Informational, Verbosity.Detailed);
     if (sslPolicyErrors == SslPolicyErrors.None)
     {
         return true;
     }
     return this.ignoreSslErrors;
 }
Ejemplo n.º 37
0
 public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
 {
     Debug.LogWarning ("SSL Cert Error:" + sslPolicyErrors.ToString ());
     return true;
 }
Ejemplo n.º 38
0
        private static bool OnCertificateValidation(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            Console.WriteLine("Server Certificate Issued To: {0}", certificate.Subject);

            Console.WriteLine("Server Certificate Issued By: {0}", certificate.Issuer);

            // Return true if there are no policy errors

            // The certificate can also be manually verified to

            //make sure it meets your specific // policies by

            //   interrogating the x509Certificate object.

            if (errors != SslPolicyErrors.None) {

                Console.WriteLine("Server Certificate Validation Error");

                Console.WriteLine(errors.ToString());

                return false;

            }

            else {

                Console.WriteLine("No Certificate Validation Errors");

                return true;

            }
        }
Ejemplo n.º 39
0
        private static bool ValidateServerCertificate(
            object sender,
            X509Certificate certificate,
            X509Chain chain,
            SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors != SslPolicyErrors.None)
            {
                Debug.WriteLine("SOCKET: Certificate error: {0}", sslPolicyErrors.ToString());
                return false;
            }

            Debug.WriteLine("SOCKET: No Certificate errors.");
            return true;
        }
Ejemplo n.º 40
0
        /////////////////////////////////////////////////////
        //                                                 //
        // ValidateRemoteClientCertificate()               //
        //                                                 //
        /////////////////////////////////////////////////////
        //Description:  enforces SSL certificate validation
        //              rules as chosen by user.
        //
        //Returns:      true if valid
        /////////////////////////////////////////////////////
        internal bool ValidateRemoteClientCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            //yay, no errors.
            if (sslPolicyErrors == SslPolicyErrors.None)
                return true;

            WriteConnectionLog("CONNECT:  Detected SSL policy errors:  " + sslPolicyErrors.ToString());

            //ignore name mismatch errors in certificate?
            if (sslPolicyErrors == SslPolicyErrors.RemoteCertificateNameMismatch)
                //if (this.IgnoreRemoteCertIgnoreNameMismatchError)
                    return true;

            //ignore chain errors in certificate?
            if (sslPolicyErrors == SslPolicyErrors.RemoteCertificateChainErrors)
                //if (this.IgnoreRemoteCertIgnoreChainErrors)
                    return true;

            //refuse communication
            return false;
        }
        /// <summary>
        /// Validates the remote certificate.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="certificate">The certificate.</param>
        /// <param name="chain">The chain.</param>
        /// <param name="sslPolicyErrors">The SSL policy errors.</param>
        /// <returns></returns>
        private bool ValidateRemoteCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            var callback = ServicePointManager.ServerCertificateValidationCallback;

            if (callback != null)
                return callback(sender, certificate, chain, sslPolicyErrors);

            if (sslPolicyErrors == SslPolicyErrors.None)
                return true;

            if (!AllowUnstrustedCertificate)
            {
                OnError(new Exception(sslPolicyErrors.ToString()));
                return false;
            }

#if DEBUG
            //In debug mode, ignore certificate name mismatch error
            if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNameMismatch) == SslPolicyErrors.RemoteCertificateNameMismatch)
            {
                return true;
            }
#endif

            //Not only a remote certificate error
            if (sslPolicyErrors != SslPolicyErrors.None && sslPolicyErrors != SslPolicyErrors.RemoteCertificateChainErrors)
            {
                OnError(new Exception(sslPolicyErrors.ToString()));
                return false;
            }

            if (chain != null && chain.ChainStatus != null)
            {
                foreach (X509ChainStatus status in chain.ChainStatus)
                {
                    if ((certificate.Subject == certificate.Issuer) &&
                       (status.Status == X509ChainStatusFlags.UntrustedRoot))
                    {
                        // Self-signed certificates with an untrusted root are valid. 
                        continue;
                    }
                    else
                    {
                        if (status.Status != X509ChainStatusFlags.NoError)
                        {
                            OnError(new Exception(sslPolicyErrors.ToString()));
                            // If there are any other errors in the certificate chain, the certificate is invalid,
                            // so the method returns false.
                            return false;
                        }
                    }
                }
            }

            // When processing reaches this line, the only errors in the certificate chain are 
            // untrusted root errors for self-signed certificates. These certificates are valid
            // for default Exchange server installations, so return true.
            return true;
        }
Ejemplo n.º 42
0
 protected virtual bool OnRemoteCertValidation(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors errors)
 {
     bool flag = false;
     RemoteCertValidation validate = RemoteCertValidation.CreateInstance();
     flag = validate.Validation(cert, errors);
     if (!flag)
     {
         this.mTrace.WriteString(this.mTracekind, string.Format("+ {0,-16} : {1}", "RemoteCertValidation", string.Format("Errors:{0}", errors.ToString())));
         this.mTimer.Enabled = false;
         this.RemoteError((X509Certificate2) cert, errors, validate);
         if (validate.Validated)
         {
             this.mTrace.WriteString(this.mTracekind, string.Format("+ {0,-16} : {1}", "RemoteCertValidation", "Request Retry"));
             this.mTimer.Enabled = true;
             return true;
         }
         ServicePointManager.ServerCertificateValidationCallback = null;
     }
     return flag;
 }
Ejemplo n.º 43
0
        /// <summary>
        /// Validate the server cert.  SSLPolicyErrors will be
        /// pre-filled with the errors you got.
        ///
        /// If there is an error in the cert, OnIvalidCertificate will be called.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="certificate"></param>
        /// <param name="chain"></param>
        /// <param name="sslPolicyErrors"></param>
        /// <returns></returns>
        protected bool ValidateServerCertificate(object sender,
                                                 X509Certificate certificate,
                                                 X509Chain chain,
                                                 SslPolicyErrors sslPolicyErrors)
        {
            // Note: Don't write servers with Jabber-Net, please.  :)
            if (m_server)
            {
                return true;
            }

            if (sslPolicyErrors == SslPolicyErrors.None)
                return true;

            if ((sslPolicyErrors & (sslPolicyErrors ^ AllowedSSLErrors)) == SslPolicyErrors.None)
            {
                // Huh.  Maybe there should be a listener method for this.
                return true;
            }

            if (m_listener.OnInvalidCertificate(this, certificate, chain, sslPolicyErrors))
                return true;

            Debug.WriteLine("Certificate error: {0}", sslPolicyErrors.ToString());

            // Do not allow this client to communicate with unauthenticated servers.
            return false;
        }
Ejemplo n.º 44
0
		static bool CertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) {
			if (sslPolicyErrors != SslPolicyErrors.None) {
				Console.WriteLine("SSL Certificate Validation Error!");
				Console.WriteLine(sslPolicyErrors.ToString());
				return false;
			} else {
				return true;
			}
		}
Ejemplo n.º 45
0
        static bool CertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors != SslPolicyErrors.None)
            {
                if (sslPolicyErrors == SslPolicyErrors.RemoteCertificateChainErrors)
                {
                    //Make sure the only error is an untrusted root
                    //(because we're assuming it's a self-signed certificate and 
                    // we're going to check it against an internal list of public keys)
                    bool failed = false;
                    foreach (X509ChainStatus status in chain.ChainStatus)
                    {
                        if (status.Status != X509ChainStatusFlags.UntrustedRoot)
                        {
                            failed = true;
                            break;
                        }
                    }
                    //Pull the public key out of the certificate
                    NodePublicKey key = NodePublicKey.BuildWith(new FieldPublicKey(certificate.GetPublicKeyString()));
                    if (!failed && PublicKeyRingHasKey(key))
                    {
                        return true;
                    }
                    else
                    {
                        Console.WriteLine("SSL Certificate Validation Error!");
                        Console.WriteLine(sslPolicyErrors.ToString());
                        return false;
                    }
                }
                else
                {
                    Console.WriteLine("SSL Certificate Validation Error!");
                    Console.WriteLine(sslPolicyErrors.ToString());
                    return false;
                }

            }
            else
                return true;
        }
Ejemplo n.º 46
0
        private bool ServicePointManager_ServerCertificateValidationCallback(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors != SslPolicyErrors.None)
            {
                Trace.TraceWarning("Certification error found: {0}", sslPolicyErrors.ToString());
                return ConfigurationAccessor.IgnoreCertificationError;
            }

            return true;
        }
Ejemplo n.º 47
0
        /// <summary>
        /// Certificate validation callback.
        /// </summary>
        private static bool ValidateRemoteCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
        {
            // If the certificate is a valid, signed certificate, return true.
            if (error == System.Net.Security.SslPolicyErrors.None)
            {
                return true;
            }

            Console.WriteLine("X509Certificate [{0}] Policy Error: '{1}'",
                cert.Subject,
                error.ToString());

            return false;
        }
Ejemplo n.º 48
0
        private bool CertificateValidationCallBack(object sender,
                                                   X509Certificate certificate,
                                                   X509Chain chain,
                                                   SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors != SslPolicyErrors.None)
            {
                Failure(String.Format("Certificate errors: {0}", sslPolicyErrors.ToString()), Url.AbsoluteUri);
                return false;
            }

            DateTime expirationTime;
            if (DateTime.TryParse(certificate.GetExpirationDateString(), out expirationTime))
            {
                TimeSpan expiringIn = expirationTime - DateTime.UtcNow;
                if (expiringIn < TimeSpan.FromDays(10))
                {
                    Degraded(String.Format("Certificate is about to expire! Expiration Date: {0}", expirationTime), Url.AbsoluteUri);
                }
                Success(String.Format("Certificate is ok. Expiring in {0} days.", (int)expiringIn.TotalDays), Url.AbsoluteUri);
            }
            else
            {
                Failure(String.Format("Unable to parse certificate expiration date. Expiration value: " + certificate.GetExpirationDateString()));
            }
            return true;
        }
Ejemplo n.º 49
0
 private bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
 {
     if (sslPolicyErrors == SslPolicyErrors.None)
     {
         return true;
     }
     Log("Server certificate error: " + sslPolicyErrors.ToString());
     return false;
 }
Ejemplo n.º 50
0
 public APNSCertificateException(SslPolicyErrors sslPolicyErrors)
     : base(sslPolicyErrors.ToString())
 {
     this.sslPolicyErrors = sslPolicyErrors;
 }
Ejemplo n.º 51
0
        private bool ValidateServerCertificate(object sender,
                                               X509Certificate certificate,
                                               X509Chain chain,
                                               SslPolicyErrors sslPolicyErrors)
        {
            Tracer.DebugFormat("ValidateServerCertificate: Issued By {0}", certificate.Issuer);
            if(sslPolicyErrors == SslPolicyErrors.None)
            {
                return true;
            }

            Tracer.WarnFormat("Certificate error: {0}", sslPolicyErrors.ToString());
            if(sslPolicyErrors == SslPolicyErrors.RemoteCertificateChainErrors)
            {
                Tracer.Error("Chain Status errors: ");
                foreach( X509ChainStatus status in chain.ChainStatus )
                {
                    Tracer.Error("*** Chain Status error: " + status.Status);
                    Tracer.Error("*** Chain Status information: " + status.StatusInformation);
                }
            }
            else if(sslPolicyErrors == SslPolicyErrors.RemoteCertificateNameMismatch)
            {
                Tracer.Error("Mismatch between Remote Cert Name.");
            }
            else if(sslPolicyErrors == SslPolicyErrors.RemoteCertificateNotAvailable)
            {
                Tracer.Error("The Remote Certificate was not Available.");
            }

            // Configuration may or may not allow us to connect with an invliad broker cert.
            return AcceptInvalidBrokerCert;
        }
Ejemplo n.º 52
0
        static bool CertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            if (AllowBadSsl)
                return true;

            if (sslPolicyErrors != SslPolicyErrors.None)
            {
                Console.WriteLine("[SSL ERROR] " + sslPolicyErrors.ToString());
                return false;
            }
            else
                return true;
        }
Ejemplo n.º 53
0
 private static bool validateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
 {
     Debug.Print(sslPolicyErrors.ToString());
     return true; // Dont care about server's cert
 }