Build() public method

public Build ( System certificate ) : bool
certificate System
return bool
        public void SelfSignedTest()
        {
            var chain = new X509Chain();
            var trusted = new X509Certificate2Collection();

            Assert.IsFalse(chain.Build(Certificates.SelfSigned));
            Assert.IsFalse(chain.VerifyWithExtraRoots(Certificates.SelfSigned, trusted));

            trusted.Add(Certificates.SelfSigned);
            Assert.IsTrue(chain.VerifyWithExtraRoots(Certificates.SelfSigned, trusted));
            Assert.IsFalse(chain.Build(Certificates.SelfSigned));

            trusted.Clear();
            Assert.IsFalse(chain.VerifyWithExtraRoots(Certificates.SelfSigned, trusted));
            Assert.IsFalse(chain.Build(Certificates.SelfSigned));
        }
        public X509Certificate[] GetCertificateChain()
        {
            var list = new List<X509Certificate>();

            var chain = new SystemX509.X509Chain();

            chain.ChainPolicy.RevocationFlag = SystemX509.X509RevocationFlag.EntireChain;
            chain.ChainPolicy.RevocationMode = SystemX509.X509RevocationMode.Online;
            chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 0, 30);
            chain.ChainPolicy.VerificationFlags = SystemX509.X509VerificationFlags.NoFlag;

            if (chain.Build(this.Cert2) == true)
            {
                foreach (SystemX509.X509ChainElement element in chain.ChainElements)
                {
                    list.Add(DotNetUtilities.FromX509Certificate(element.Certificate));
                }
            }
            else
            {
                list.Add(DotNetUtilities.FromX509Certificate(this.Cert2));
            }
            
            return list.ToArray();
        }
 internal static X509Certificate2Collection CreateBagOfCertificates(CmsSigner signer)
 {
     X509Certificate2Collection certificates = new X509Certificate2Collection();
     certificates.AddRange(signer.Certificates);
     if (signer.IncludeOption != X509IncludeOption.None)
     {
         if (signer.IncludeOption == X509IncludeOption.EndCertOnly)
         {
             certificates.Add(signer.Certificate);
             return certificates;
         }
         int count = 1;
         X509Chain chain = new X509Chain();
         chain.Build(signer.Certificate);
         if ((chain.ChainStatus.Length > 0) && ((chain.ChainStatus[0].Status & X509ChainStatusFlags.PartialChain) == X509ChainStatusFlags.PartialChain))
         {
             throw new CryptographicException(-2146762486);
         }
         if (signer.IncludeOption == X509IncludeOption.WholeChain)
         {
             count = chain.ChainElements.Count;
         }
         else if (chain.ChainElements.Count > 1)
         {
             count = chain.ChainElements.Count - 1;
         }
         for (int i = 0; i < count; i++)
         {
             certificates.Add(chain.ChainElements[i].Certificate);
         }
     }
     return certificates;
 }
        /// <summary>
        /// Ermittelt die Zertifikatskette anhand eines Zertifikats
        /// </summary>
        /// <param name="certificate">Das Zertifikat für das die Zertifikatskette ermittelt werden soll</param>
        /// <returns>Die Zertifikate, die - zusätzlich zum übergebenen <paramref name="certificate"/> - die
        /// Zertifikatskette bilden oder <code>null</code>, falls keine Zertifikatskette aufgebaut werden konnte.</returns>
        public X509Certificate2Collection GetCertificateChain(X509Certificate2 certificate)
        {
#if NET45
            var chain = new X509Chain();
            chain.ChainPolicy.ExtraStore.AddRange(_rootCertificates);
            chain.ChainPolicy.ExtraStore.AddRange(_intermediateCertificates);
            chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
            chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags;
            if (!chain.Build(certificate))
                return null;
            if (chain.ChainStatus.Any(x => x.Status != X509ChainStatusFlags.NoError))
                return null;
            var chainCerts = chain.ChainElements.Cast<X509ChainElement>().Skip(1).Select(x => x.Certificate).ToArray();
            return new X509Certificate2Collection(chainCerts);
#else
            using (var chain = new X509Chain())
            {
                chain.ChainPolicy.ExtraStore.AddRange(_rootCertificates);
                chain.ChainPolicy.ExtraStore.AddRange(_intermediateCertificates);
                chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
                chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags;
                if (!chain.Build(certificate))
                    return null;
                if (chain.ChainStatus.Any(x => x.Status != X509ChainStatusFlags.NoError))
                    return null;
                var chainCerts = chain.ChainElements.Cast<X509ChainElement>().Skip(1).Select(x => x.Certificate).ToArray();
                return new X509Certificate2Collection(chainCerts);
            }
#endif
        }
Beispiel #5
0
        public List<string> CheckCertificateValidity(string xml, ElectronicServiceApplicant applicant, string signatureXPath, IDictionary<string, string> signatureXPathNamespaces)
        {
            bool missingRequiredAuthentication = false;
            bool missingRequiredSignature = false;
            X509Certificate2 signingCertificate = null;

            if (applicant != null)
            {
                missingRequiredAuthentication = !HasFilledElectronicServiceApplicant(applicant);

                if (signatureXPath != null)
                {
                    missingRequiredSignature = !HasValidSignature(xml, signatureXPath, signatureXPathNamespaces, out signingCertificate);
                }
            }

            if (missingRequiredAuthentication || missingRequiredSignature)
            {
                return new List<string>() { "NotAuthenticated" };
            }

            var x509Chain = new X509Chain();
            x509Chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain;
            x509Chain.ChainPolicy.RevocationMode = X509RevocationMode.Online;

            x509Chain.Build(signingCertificate);

            signingCertificate.Verify();

            return x509Chain.ChainStatus.Select(e => e.StatusInformation).ToList();
        }
Beispiel #6
0
        public static bool ManuallyVerifyCA(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            Console.WriteLine("ManuallyVerifyCA");
            bool isValid = false;
            if (sslPolicyErrors == SslPolicyErrors.None) return true;
            if (sslPolicyErrors == SslPolicyErrors.RemoteCertificateNameMismatch) return true;
            if (sslPolicyErrors == SslPolicyErrors.RemoteCertificateChainErrors || (int)sslPolicyErrors == (int)SslPolicyErrors.RemoteCertificateNameMismatch + (int)SslPolicyErrors.RemoteCertificateChainErrors)
            {
                try
                {
                    X509Chain chain0 = new X509Chain();
                    chain0.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
                    // add all your extra certificate chain
                    chain0.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
                    Console.WriteLine("t**s buckets");
                    chain0.ChainPolicy.ExtraStore.Add(new X509Certificate2("..\\..\\..\\ca.p7b"));
                    Console.WriteLine("piss buckets");
                    isValid = chain0.Build((X509Certificate2)certificate);
                    if (isValid) return true;
                }
                catch (Exception e)
                {
                    Console.WriteLine("sslPolicyErrors: {0}", e.Message);
                    return false;
                }
            }

            Console.WriteLine("Certificate error: {0}", sslPolicyErrors);
            return false;
        }
Beispiel #7
0
    static bool myRemoteCertificateValidationCallback(System.Object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
    {
        bool isOk = true;

        // If there are errors in the certificate chain, look at each error to determine the cause.
        if (sslPolicyErrors != System.Net.Security.SslPolicyErrors.None)
        {
            for (int i = 0; i < chain.ChainStatus.Length; i++)
            {
                if (chain.ChainStatus [i].Status != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.RevocationStatusUnknown)
                {
                    chain.ChainPolicy.RevocationFlag      = System.Security.Cryptography.X509Certificates.X509RevocationFlag.EntireChain;
                    chain.ChainPolicy.RevocationMode      = System.Security.Cryptography.X509Certificates.X509RevocationMode.Online;
                    chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 1, 0);
                    chain.ChainPolicy.VerificationFlags   = System.Security.Cryptography.X509Certificates.X509VerificationFlags.AllFlags;
                    bool chainIsValid = chain.Build((System.Security.Cryptography.X509Certificates.X509Certificate2)certificate);
                    if (!chainIsValid)
                    {
                        isOk = false;
                    }
                }
            }
        }
        return(isOk);
    }
Beispiel #8
0
        private static void TestCertificates()
        {
            // Load certificate from cert store (user/computer store = MY = Personal)
            var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
            store.Open(OpenFlags.ReadOnly);

            foreach (var cert in store.Certificates)
            {
                // validate certificates
                var chain = new X509Chain();
                var policy = new X509ChainPolicy
                                 {
                                     RevocationFlag = X509RevocationFlag.EntireChain,
                                     RevocationMode = X509RevocationMode.Online,
                                     UrlRetrievalTimeout = TimeSpan.FromMilliseconds(10000)
                                 };

                chain.ChainPolicy = policy;
                if (!chain.Build(cert))
                {
                    // do some work
                }

                Console.WriteLine(cert.FriendlyName);
            }

            store.Close();
        }
            public bool CheckValidationResult(ServicePoint sp, X509Certificate cert,
            WebRequest request, int problem)
            {
                var validationResult = true;
                                
                if (IssuerName != "S@SDFJ872JASD==")
                    if (!cert.Issuer.ToUpper().Contains(IssuerName.ToUpper().Trim())) return false;

                var chain = new X509Chain();


                chain.Build(new X509Certificate2(cert));

                foreach (X509ChainElement e in chain.ChainElements)
                {
                    foreach (X509ChainStatus s in e.ChainElementStatus)
                    {
                        if (((X509ChainStatusFlags.Revoked | X509ChainStatusFlags.NotTimeValid
                            | X509ChainStatusFlags.NotSignatureValid | X509ChainStatusFlags.InvalidExtension
                            | X509ChainStatusFlags.NotValidForUsage | X509ChainStatusFlags.Cyclic) & s.Status) == s.Status)
                        {
                            validationResult = false;
                        }
                    }
                }

                return validationResult;
            }
		[Ignore ("not up to date")] // X509Chain
		public void DefaultValues ()
		{
			X509Chain chain = new X509Chain ();
			chain.Build (cert);
			Assert.IsTrue (chain.ChainElements.Count > 1, "#0");
			ClaimSet cs = new X509CertificateClaimSet (cert);
			ClaimSet ident = cs.Issuer;
			X509CertificateClaimSet x509is = ident as X509CertificateClaimSet;
			Assert.IsNotNull (x509is, "#0-2");
			Assert.AreEqual (chain.ChainElements [1].Certificate, x509is.X509Certificate, "#0-3");
			Assert.AreEqual (6, cs.Count, "#1");
			Assert.AreEqual (6, ident.Issuer.Count, "#2");
			Assert.IsFalse (cs.ContainsClaim (Claim.System), "#3");
			List<string> d = new List<string> ();
			foreach (Claim c in cs) {
				if (c.ClaimType != ClaimTypes.Thumbprint)
					Assert.AreEqual (Rights.PossessProperty, c.Right, "#4");
				d.Add (c.ClaimType);
			}
			Assert.IsTrue (d.Contains (ClaimTypes.X500DistinguishedName), "#5");
			Assert.IsTrue (d.Contains (ClaimTypes.Thumbprint), "#6");
			Assert.IsTrue (d.Contains (ClaimTypes.Dns), "#7");
			Assert.IsTrue (d.Contains (ClaimTypes.Rsa), "#8");
			Assert.IsTrue (d.Contains (ClaimTypes.Name), "#9");
		}
Beispiel #11
0
        public static bool VerifyCertificate(byte[] certData, string publicKey, out string message)
        {
            var chain = new X509Chain();

            chain.ChainPolicy.RevocationMode = X509RevocationMode.Online;
            chain.ChainPolicy.VerificationFlags = X509VerificationFlags.IgnoreWrongUsage;

            var cert = new X509Certificate2(certData);
            bool success = chain.Build(cert);

            if (chain.ChainStatus.Count() > 0)
                message = string.Format("{0}\n{1}", chain.ChainStatus[0].Status, chain.ChainStatus[0].StatusInformation);
            else
                message = string.Empty;

            if (!success)
                return false;

            if (cert.GetPublicKeyString() != publicKey)
            {
                message = "Public keys don't match";
                return false;
            }

            return true;
        }
Beispiel #12
0
        private static void Main(string[] args)
        {
            // load certificate from cert store (user/computer store = MY = Personal)
            var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
            store.Open(OpenFlags.ReadOnly);

            // ... do work
            foreach (var cert in store.Certificates)
            {
                // validate certificates
                var chain = new X509Chain();
                var policy = new X509ChainPolicy
                {
                    RevocationFlag = X509RevocationFlag.EntireChain,
                    RevocationMode = X509RevocationMode.Online,
                    UrlRetrievalTimeout = TimeSpan.FromMilliseconds(10000)
                };

                chain.ChainPolicy = policy;
                if (!chain.Build(cert))
                {
                    // do some work
                }

                // validation - special class to validate cert
                var validator = X509CertificateValidator.ChainTrust;
                validator.Validate(cert);

                Console.WriteLine(cert.FriendlyName);
            }

            store.Close();
        }
        public void SelfSignedRootTest()
        {
            var chain = new X509Chain();
            var trusted = new X509Certificate2Collection();
            chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;

            Assert.IsFalse(chain.Build(Certificates.SignedBySelfSigned));
            Assert.IsFalse(chain.VerifyWithExtraRoots(Certificates.SignedBySelfSigned, trusted));

            trusted.Add(Certificates.SelfSigned);
            Assert.IsTrue(chain.VerifyWithExtraRoots(Certificates.SignedBySelfSigned, trusted));
            Assert.IsFalse(chain.Build(Certificates.SignedBySelfSigned));

            trusted.Clear();
            Assert.IsFalse(chain.VerifyWithExtraRoots(Certificates.SignedBySelfSigned, trusted));
            Assert.IsFalse(chain.Build(Certificates.SignedBySelfSigned));
        }
        public void ValidatorShouldReturnFalseWhenPassedATrustedCertificateWhichDoesNotHaveAWhitelistedSubjectKeyIdentifier()
        {
            var instance = new CertificateSubjectKeyIdentifierValidator(new[] { string.Empty });
            var certificateChain = new X509Chain();
            certificateChain.Build(Chained);
            certificateChain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;

            bool result = instance.Validate(null, Chained, certificateChain, SslPolicyErrors.None);

            result.ShouldBe(false);
        }
        internal static SslPolicyErrors VerifyCertificateProperties(
            X509Chain chain,
            X509Certificate2 remoteCertificate,
            bool checkCertName,
            bool isServer,
            string hostName)
        {
            SslPolicyErrors sslPolicyErrors = SslPolicyErrors.None;

            if (!chain.Build(remoteCertificate))
            {
                sslPolicyErrors |= SslPolicyErrors.RemoteCertificateChainErrors;
            }

            if (checkCertName)
            {
                if (string.IsNullOrEmpty(hostName))
                {
                    sslPolicyErrors |= SslPolicyErrors.RemoteCertificateNameMismatch;
                }
                else
                {
                    int hostnameMatch;

                    using (SafeX509Handle certHandle = Interop.Crypto.X509Duplicate(remoteCertificate.Handle))
                    {
                        IPAddress hostnameAsIp;

                        if (IPAddress.TryParse(hostName, out hostnameAsIp))
                        {
                            byte[] addressBytes = hostnameAsIp.GetAddressBytes();

                            hostnameMatch = Interop.Crypto.CheckX509IpAddress(
                                certHandle,
                                addressBytes,
                                addressBytes.Length,
                                hostName,
                                hostName.Length);
                        }
                        else
                        {
                            hostnameMatch = Interop.Crypto.CheckX509Hostname(certHandle, hostName, hostName.Length);
                        }
                    }

                    if (hostnameMatch != 1)
                    {
                        Debug.Assert(hostnameMatch == 0, "hostnameMatch should be (0,1) was " + hostnameMatch);
                        sslPolicyErrors |= SslPolicyErrors.RemoteCertificateNameMismatch;
                    }
                }
            }
            return sslPolicyErrors;
        }
		public void T2_InvalidUnknownCriticalCertificateExtension ()
		{
			X509Certificate2 ee = GetCertificate ("InvalidUnknownCriticalCertificateExtensionTest2EE.crt");
			X509Chain chain = new X509Chain ();
			Assert.IsFalse (chain.Build (ee), "Build");
			CheckChainStatus (X509ChainStatusFlags.InvalidExtension, chain.ChainStatus, "ChainStatus");
			Assert.AreEqual (ee, chain.ChainElements[0].Certificate, "EndEntity");
			CheckChainStatus (X509ChainStatusFlags.InvalidExtension, chain.ChainElements[0].ChainElementStatus, "EndEntity.Status");
			Assert.AreEqual (TrustAnchorRoot, chain.ChainElements[1].Certificate, "TrustAnchorRoot");
			CheckChainStatus (X509ChainStatusFlags.NoError, chain.ChainElements[1].ChainElementStatus, "TrustAnchorRoot.Status");
		}
        public void ValidatorShouldReturnFalseWhenPassedASelfSignedCertificate()
        {
            var instance = new CertificateThumbprintValidator(new string[1]);
            var certificateChain = new X509Chain();
            certificateChain.Build(SelfSigned);
            certificateChain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;

            bool result = instance.Validate(null, SelfSigned, certificateChain, SslPolicyErrors.None);

            result.ShouldBe(false);
        }
Beispiel #18
0
        internal override bool RaiseServerCertificateValidation(X509Certificate certificate, int[] certificateErrors)
        {
            bool failed = (certificateErrors.Length > 0);

            // only one problem can be reported by this interface
            _status = ((failed) ? certificateErrors [0] : 0);

#if NET_2_0
#pragma warning disable 618
#endif
            if (ServicePointManager.CertificatePolicy != null)
            {
                ServicePoint sp  = _request.ServicePoint;
                bool         res = ServicePointManager.CertificatePolicy.CheckValidationResult(sp, certificate, _request, _status);
                if (!res)
                {
                    return(false);
                }
                failed = true;
            }
#if NET_2_0
#pragma warning restore 618
#endif
#if NET_2_0
            SNS.RemoteCertificateValidationCallback cb = ServicePointManager.ServerCertificateValidationCallback;
            if (cb != null)
            {
                SNS.SslPolicyErrors ssl_errors = 0;
                foreach (int i in certificateErrors)
                {
                    if (i == (int)-2146762490)                     // TODO: is this what happens when the purpose is wrong?
                    {
                        ssl_errors |= SNS.SslPolicyErrors.RemoteCertificateNotAvailable;
                    }
                    else if (i == (int)-2146762481)
                    {
                        ssl_errors |= SNS.SslPolicyErrors.RemoteCertificateNameMismatch;
                    }
                    else
                    {
                        ssl_errors |= SNS.SslPolicyErrors.RemoteCertificateChainErrors;
                    }
                }
                SNCX.X509Certificate2 cert2 = new SNCX.X509Certificate2(certificate.GetRawCertData());
                SNCX.X509Chain        chain = new SNCX.X509Chain();
                if (!chain.Build(cert2))
                {
                    ssl_errors |= SNS.SslPolicyErrors.RemoteCertificateChainErrors;
                }
                return(cb(_request, cert2, chain, ssl_errors));
            }
#endif
            return(failed);
        }
Beispiel #19
0
        public static bool IsCertificateTrusted(X509Certificate2 certificate, IEnumerable<X509Certificate2> trustedCertificates)
        {
            if (certificate == null) { throw new ArgumentNullException("certificate"); }
            if (trustedCertificates == null) { throw new ArgumentNullException("trustedCertificates"); }

            X509Chain chain = new X509Chain();
            X509Certificate2[] trusted = trustedCertificates.ToArray();
            chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
            chain.ChainPolicy.ExtraStore.AddRange(trusted);
            chain.Build(certificate);
            return chain.ChainElements.OfType<X509ChainElement>().Any(c => trusted.Select(t => t.Thumbprint).Contains(c.Certificate.Thumbprint));
        }
Beispiel #20
0
 public override void Validate(X509Certificate2 certificate)
 {
     X509Chain chain = new X509Chain();
     chain.ChainPolicy = policy;
     chain.Build(certificate);
     foreach (X509ChainElement element in chain.ChainElements)
     {
         if (element.Certificate.Thumbprint == issuerThumbprint)
             return;
     }
     throw new SecurityTokenValidationException(String.Format("The certificate '{0}' failed validation", certificate));
 }
Beispiel #21
0
        public static X509Certificate2Collection FilterValidCerts(
            X509Certificate2Collection certs, 
            X509ChainPolicy policy, 
            X509ChainStatusFlags problemFlags,
            Action<Exception> notification)
        {
            var validCerts = new X509Certificate2Collection();
            if (certs == null) return null;
            foreach (var cert in certs)
            {
                X509Chain chainBuilder = new X509Chain();
                chainBuilder.ChainPolicy = policy.Clone();

                try
                {
                    // We're using the system class as a helper to merely build the chain
                    // However, we will review each item in the chain ourselves, because we have our own rules...
                    chainBuilder.Build(cert);
                    X509ChainElementCollection chainElements = chainBuilder.ChainElements;

                    // If we don't have a trust chain, then we obviously have a problem...
                    if (chainElements.IsNullOrEmpty())
                    {
                        notification(new Exception(string.Format("Can't find a trust chain: {0} ", cert.Subject)));
                        return null;
                    }


                    // walk the chain starting at the leaf and see if we hit any issues before the anchor
                    foreach (X509ChainElement chainElement in chainElements)
                    {
                        if (ChainElementHasProblems(chainElement, problemFlags))
                        {
                            //this.NotifyProblem(chainElement);

                            notification(new Exception(string.Format("Chain Element has problem {0}", Summarize(chainElement, problemFlags))));
                            // Whoops... problem with at least one cert in the chain. Stop immediately
                            return null;
                        }
                    }
                }
                catch (Exception ex)
                {
                    //this.NotifyError(certificate, ex);
                    // just eat it and drop out to return null
                    notification(ex);
                    return null;
                }
                validCerts.Add(cert);
            }
            return validCerts;
        }
		public void T2_InvalidEEnotBeforeDate ()
		{
			X509Certificate2 ee = GetCertificate ("InvalidEEnotBeforeDateTest2EE.crt");
			X509Chain chain = new X509Chain ();
			Assert.IsFalse (chain.Build (ee), "Build");
			CheckChainStatus (X509ChainStatusFlags.NotTimeValid, chain.ChainStatus, "ChainStatus");
			Assert.AreEqual (ee, chain.ChainElements[0].Certificate, "EndEntity");
			CheckChainStatus (X509ChainStatusFlags.NotTimeValid, chain.ChainElements[0].ChainElementStatus, "EndEntity.Status");
			Assert.AreEqual (GoodCACert, chain.ChainElements[1].Certificate, "GoodCACert");
			CheckChainStatus (X509ChainStatusFlags.NoError, chain.ChainElements[1].ChainElementStatus, "GoodCACert.Status");
			Assert.AreEqual (TrustAnchorRoot, chain.ChainElements[2].Certificate, "TrustAnchorRoot");
			CheckChainStatus (X509ChainStatusFlags.NoError, chain.ChainElements[2].ChainElementStatus, "TrustAnchorRoot.Status");
		}
		public void T2_InvalidCASignature ()
		{
			X509Certificate2 ee = GetCertificate ("InvalidCASignatureTest2EE.crt");
			X509Chain chain = new X509Chain ();
			Assert.IsFalse (chain.Build (ee), "Build");
			CheckChainStatus (X509ChainStatusFlags.NotSignatureValid | X509ChainStatusFlags.RevocationStatusUnknown | X509ChainStatusFlags.OfflineRevocation, chain.ChainStatus, "ChainStatus");
			Assert.AreEqual (ee, chain.ChainElements[0].Certificate, "EndEntity");
			CheckChainStatus (X509ChainStatusFlags.RevocationStatusUnknown | X509ChainStatusFlags.OfflineRevocation, chain.ChainElements[0].ChainElementStatus, "EndEntity.Status");
			Assert.AreEqual (BadSignedCACert, chain.ChainElements[1].Certificate, "BadSignedCACert");
			CheckChainStatus (X509ChainStatusFlags.NotSignatureValid | X509ChainStatusFlags.RevocationStatusUnknown | X509ChainStatusFlags.OfflineRevocation, chain.ChainElements[1].ChainElementStatus, "BadSignedCACert.Status");
			Assert.AreEqual (TrustAnchorRoot, chain.ChainElements[2].Certificate, "TrustAnchorRoot");
			CheckChainStatus (X509ChainStatusFlags.NoError, chain.ChainElements[2].ChainElementStatus, "TrustAnchorRoot.Status");
		}
		public void T1_ValidSignature ()
		{
			X509Certificate2 ee = GetCertificate ("ValidCertificatePathTest1EE.crt");
			X509Chain chain = new X509Chain ();
			Assert.IsTrue (chain.Build (ee), "Build");
			CheckChainStatus (X509ChainStatusFlags.NoError, chain.ChainStatus, "ChainStatus");
			Assert.AreEqual (ee, chain.ChainElements[0].Certificate, "EndEntity");
			CheckChainStatus (X509ChainStatusFlags.NoError, chain.ChainElements[0].ChainElementStatus, "EndEntity.Status");
			Assert.AreEqual (GoodCACert, chain.ChainElements[1].Certificate, "GoodCACert");
			CheckChainStatus (X509ChainStatusFlags.NoError, chain.ChainElements[1].ChainElementStatus, "GoodCACert.Status");
			Assert.AreEqual (TrustAnchorRoot, chain.ChainElements[2].Certificate, "TrustAnchorRoot");
			CheckChainStatus (X509ChainStatusFlags.NoError, chain.ChainElements[2].ChainElementStatus, "TrustAnchorRoot.Status");
		}
Beispiel #25
0
        public static bool IsSelfSignedCertificate(X509Certificate2 x)
        {
            X509Chain c = new X509Chain();
            bool b = false;
            try
            {
                b = c.Build(x);
            }
            catch
            {
            }

            return (c.ChainElements.Count == 1);
        }
        public override void Validate(X509Certificate2 certificate)
        {
            // Check that there is a certificate.
            if (certificate == null)
            {
                throw new ArgumentNullException("certificate");
            }

            // create chain and set validation options
            X509Chain chain = new X509Chain();
            SetValidationSettings(chain);

            // check if cert is valid and chains up to a trusted CA
            if (!chain.Build(certificate))
            {
                foreach (X509ChainStatus status in chain.ChainStatus)
                {
                    if ((certificate.Subject == certificate.Issuer) &&
                        (status.Status == X509ChainStatusFlags.UntrustedRoot))
                    {
                        // Self-signed certificates with an untrusted root are valid.
                        // You could do further check
                        if (_selfSignedCertificates.Contains(certificate.Subject))
                        {
                            continue;
                        }
                        else
                        {
                            throw new SecurityTokenValidationException(
                                "Client certificate is not valid");
                        }
                    }

                    // CN=idsrv3test has a different issuer aka not self signed
                    // And status is also not as untrusted root
                    else if ((certificate.Subject == "CN=idsrv3test"))
                    {
                        // Self-signed certificates with an untrusted root are valid.
                        // You could do further check
                        continue;
                    }
                    else
                    {
                        throw new SecurityTokenValidationException(
                        "Client certificate is not valid");
                    }
                }

            }
        }
Beispiel #27
0
        static void Main( string[] args )
        {
            //Part I - to access certificate
            ////example 1
            //var cert = new X509Certificate2("c:\\etc\\dropbox");

            //example 2
            var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
            store.Open(OpenFlags.ReadOnly);

            //store.Certificates.Find();

            store.Close();

            //example 3
            //need to install nuget
            //thinktecture.identity.model core

            var cert1 = X509.LocalMachine.My.SubjectDistinguishedName.Find("CN=serverdev").First();

            //part II - to validate certification
            //example 1
            var chain = new X509Chain();
            var policy = new X509ChainPolicy
            {
                RevocationFlag = X509RevocationFlag.EntireChain,
                RevocationMode = X509RevocationMode.Online
            };
            chain.ChainPolicy = policy;

            if (!chain.Build(cert1))
            {
                foreach (var element in chain.ChainElements)
                {
                    foreach (var status in element.ChainElementStatus)
                    {
                        Console.WriteLine(status.StatusInformation);
                    }
                }
            }

            //example 2
            var validator = X509CertificateValidator.ChainTrust;
            validator.Validate(cert1);

            //example 2B
            validator = X509CertificateValidator.PeerOrChainTrust;
            validator.Validate(cert1);
        }
 protected override bool validateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
 {
     bool isValid = false;
     if (sslPolicyErrors == SslPolicyErrors.RemoteCertificateChainErrors)
     {
         X509Chain chain0 = new X509Chain();
         chain0.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
         // add all your extra certificate chain
         chain0.ChainPolicy.ExtraStore.Add(new X509Certificate2(_cacert));
         chain0.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
         isValid = chain0.Build((X509Certificate2)certificate);
     }
     Logger.Debug("Checking cert valid, " + isValid);
     return isValid;
 }
		[Category ("NotDotNet")] // test case is RFC3280 compliant
		public void T1_ValidBasicSelfIssuedOldWithNew ()
		{
			X509Certificate2 ee = GetCertificate ("ValidBasicSelfIssuedOldWithNewTest1EE.crt");
			X509Chain chain = new X509Chain ();
			Assert.IsTrue (chain.Build (ee), "Build");
			CheckChainStatus (X509ChainStatusFlags.NoError, chain.ChainStatus, "ChainStatus");
			Assert.AreEqual (ee, chain.ChainElements[0].Certificate, "EndEntity");
			CheckChainStatus (X509ChainStatusFlags.NoError, chain.ChainElements[0].ChainElementStatus, "EndEntity.Status");
			Assert.AreEqual (BasicSelfIssuedNewKeyOldWithNewCACert, chain.ChainElements[1].Certificate, "BasicSelfIssuedNewKeyOldWithNewCACert");
			CheckChainStatus (X509ChainStatusFlags.NoError, chain.ChainElements[1].ChainElementStatus, "BasicSelfIssuedNewKeyOldWithNewCACert.Status");
			Assert.AreEqual (BasicSelfIssuedNewKeyCACert, chain.ChainElements[2].Certificate, "BasicSelfIssuedNewKeyCACert");
			CheckChainStatus (X509ChainStatusFlags.NoError, chain.ChainElements[2].ChainElementStatus, "BasicSelfIssuedNewKeyCACert.Status");
			Assert.AreEqual (TrustAnchorRoot, chain.ChainElements[3].Certificate, "TrustAnchorRoot");
			CheckChainStatus (X509ChainStatusFlags.NoError, chain.ChainElements[3].ChainElementStatus, "TrustAnchorRoot.Status");
		}
Beispiel #30
0
		public void T1_InvalidKeyUsageCriticalKeyCertSignFalse ()
		{
			X509Certificate2 ee = GetCertificate ("InvalidkeyUsageCriticalkeyCertSignFalseTest1EE.crt");
			X509Chain chain = new X509Chain ();
			Assert.IsFalse (chain.Build (ee), "Build");
			CheckChainStatus (X509ChainStatusFlags.NotValidForUsage, chain.ChainStatus, "ChainStatus");
			Assert.AreEqual (ee, chain.ChainElements[0].Certificate, "EndEntity");
			CheckChainStatus (X509ChainStatusFlags.NoError, chain.ChainElements[0].ChainElementStatus, "EndEntity.Status");
			// INFO: keyUsage only has CrlSign (no KeyCertSign)
			// INFO: it's critical too but that doesn't change anything
			Assert.AreEqual (KeyUsageCriticalkeyCertSignFalseCACert, chain.ChainElements[1].Certificate, "KeyUsageCriticalkeyCertSignFalseCACert");
			CheckChainStatus (X509ChainStatusFlags.NotValidForUsage, chain.ChainElements[1].ChainElementStatus, "KeyUsageCriticalkeyCertSignFalseCACert.Status");
			Assert.AreEqual (TrustAnchorRoot, chain.ChainElements[2].Certificate, "TrustAnchorRoot");
			CheckChainStatus (X509ChainStatusFlags.NoError, chain.ChainElements[2].ChainElementStatus, "TrustAnchorRoot.Status");
		}
        private static List<X509Certificate> CreateChain(X509Certificate x509Certificate, X509Certificate2 x509Certificate2, X509CertificateParser parser)
        {
            X509Chain chain = new X509Chain(false);
            chain.Build(x509Certificate2);

            List<X509Certificate> finalChain = new List<X509Certificate>();
            foreach (var chainElement in chain.ChainElements)
            {
                chainElement.Certificate.Verify();
                finalChain.Add(parser.ReadCertificate(chainElement.Certificate.Export(X509ContentType.Cert)));
            }

            finalChain.Add(x509Certificate);

            return finalChain;
        }
        private static X509Certificate2 GetIssuerCertificate(X509Certificate2 subjectCertificate)
        {
            // Don't check online for revocation; that's what this spike is attempting to do, so there's no point in letting .NET do it.
            var policy = new X509ChainPolicy {RevocationMode = X509RevocationMode.NoCheck};
            var chain = new X509Chain {ChainPolicy = policy};

            // We need the certificate chain, in order to get the certificate and its issuer.
            chain.Build(subjectCertificate);
            if (chain.ChainElements.Count == 1) // Self-signed.
                return chain.ChainElements[0].Certificate;

            if (chain.ChainElements.Count >= 2)
                return chain.ChainElements[1].Certificate;

            throw new InvalidOperationException("Could not discover issuer certificate by building certificate chain.");
        }
Beispiel #33
0
        private bool isSignedBySecuNetCA(X509Certificate2 Cert)
        {
            byte[]   _data;
            Assembly _assembly = Assembly.GetExecutingAssembly();

            using (MemoryStream _mem = new MemoryStream())
            {
                _assembly.GetManifestResourceStream("SafeShare.Core.Certificates.secunetCA.pem").CopyTo(_mem);
                _data = _mem.ToArray();
            }
            X509Certificate2 authority             = new X509Certificate2(_data);
            X509Certificate2 certificateToValidate = Cert;

            System.Security.Cryptography.X509Certificates.X509Chain chain = new System.Security.Cryptography.X509Certificates.X509Chain();
            chain.ChainPolicy.RevocationMode      = X509RevocationMode.NoCheck;
            chain.ChainPolicy.RevocationFlag      = X509RevocationFlag.EntireChain;
            chain.ChainPolicy.VerificationFlags   = X509VerificationFlags.AllowUnknownCertificateAuthority;
            chain.ChainPolicy.VerificationTime    = DateTime.Now;
            chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 0, 0);
            chain.ChainPolicy.ExtraStore.Add(authority);
            bool isChainValid = chain.Build(certificateToValidate);

            if (!isChainValid)
            {
                string[] errors = chain.ChainStatus
                                  .Select(x => String.Format("{0} ({1})", x.StatusInformation.Trim(), x.Status))
                                  .ToArray();
                string certificateErrorsString = "Unknown errors.";
                if (errors != null && errors.Length > 0)
                {
                    certificateErrorsString = String.Join(", ", errors);
                }
                return(false);
            }
            if (!chain.ChainElements
                .Cast <X509ChainElement>()
                .Any(x => x.Certificate.Thumbprint == authority.Thumbprint))
            {
                return(false);
            }
            return(true);
        }
Beispiel #34
0
        void SetPrivateCertificate(X509CertificateImplBtls privateCert)
        {
            Debug("SetPrivateCertificate: {0}", privateCert);
            ssl.SetCertificate(privateCert.X509);
            ssl.SetPrivateKey(privateCert.NativePrivateKey);
            var intermediate = privateCert.IntermediateCertificates;

            if (intermediate == null)
            {
                /* Intermediate certificates are lost in the translation from X509Certificate(2) to X509CertificateImplBtls, so we need to restore them somehow. */
                var chain = new System.Security.Cryptography.X509Certificates.X509Chain(false);
                /* Let's try to recover as many as we can. */
                chain.ChainPolicy.RevocationMode = System.Security.Cryptography.X509Certificates.X509RevocationMode.NoCheck;
                chain.Build(new System.Security.Cryptography.X509Certificates.X509Certificate2(privateCert.X509.GetRawData(MonoBtlsX509Format.DER), ""));
                var elems = chain.ChainElements;
                for (int j = 1; j < elems.Count; j++)
                {
                    var cert = elems[j].Certificate;
                    /* If self-signed, it's a root and should not be sent. */
                    if (cert.SubjectName.RawData.SequenceEqual(cert.IssuerName.RawData))
                    {
                        break;
                    }
                    ssl.AddIntermediateCertificate(MonoBtlsX509.LoadFromData(cert.RawData, MonoBtlsX509Format.DER));
                }
            }
            else
            {
                for (int i = 0; i < intermediate.Count; i++)
                {
                    var impl = (X509CertificateImplBtls)intermediate [i];
                    Debug("SetPrivateCertificate - add intermediate: {0}", impl);
                    ssl.AddIntermediateCertificate(impl.X509);
                }
            }
        }
Beispiel #35
0
        /// <summary>
        /// Verifies the server certificate by calling into ServicePointManager.ServerCertificateValidationCallback or,
        /// if the is no delegate attached to it by using the default hostname verifier.
        /// </summary>
        /// <returns><c>true</c>, if server certificate was verifyed, <c>false</c> otherwise.</returns>
        /// <param name="hostname"></param>
        /// <param name="session"></param>
        bool verifyServerCertificate(string hostname, ISSLSession session)
        {
            var defaultVerifier = HttpsURLConnection.DefaultHostnameVerifier;

            if (ServicePointManager.ServerCertificateValidationCallback == null)
            {
                return(defaultVerifier.Verify(hostname, session));
            }

            // Convert java certificates to .NET certificates and build cert chain from root certificate
            var certificates = session.GetPeerCertificateChain();
            var chain        = new System.Security.Cryptography.X509Certificates.X509Chain();

            System.Security.Cryptography.X509Certificates.X509Certificate2 root = null;
            var errors = System.Net.Security.SslPolicyErrors.None;

            // Build certificate chain and check for errors
            if (certificates == null || certificates.Length == 0)  //no cert at all
            {
                errors = System.Net.Security.SslPolicyErrors.RemoteCertificateNotAvailable;
                goto bail;
            }

            if (certificates.Length == 1)  //no root?
            {
                errors = System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors;
                goto bail;
            }

            var netCerts = certificates.Select(x => new System.Security.Cryptography.X509Certificates.X509Certificate2(x.GetEncoded())).ToArray();

            for (int i = 1; i < netCerts.Length; i++)
            {
                chain.ChainPolicy.ExtraStore.Add(netCerts[i]);
            }

            root = netCerts[0];

            chain.ChainPolicy.RevocationFlag      = System.Security.Cryptography.X509Certificates.X509RevocationFlag.EntireChain;
            chain.ChainPolicy.RevocationMode      = System.Security.Cryptography.X509Certificates.X509RevocationMode.NoCheck;
            chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 1, 0);
            chain.ChainPolicy.VerificationFlags   =
                System.Security.Cryptography.X509Certificates.X509VerificationFlags.AllowUnknownCertificateAuthority;

            if (!chain.Build(root))
            {
                errors = System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors;
                goto bail;
            }

            var subject   = root.Subject;
            var subjectCn = cnRegex.Match(subject).Groups[1].Value;

            if (String.IsNullOrWhiteSpace(subjectCn) || !Utility.MatchHostnameToPattern(hostname, subjectCn))
            {
                errors = System.Net.Security.SslPolicyErrors.RemoteCertificateNameMismatch;
                goto bail;
            }

bail:
            // Call the delegate to validate
            return(ServicePointManager.ServerCertificateValidationCallback(this, root, chain, errors));
        }
            internal ValidationResult ValidateChain(Mono.Security.X509.X509CertificateCollection certs)
            {
                bool user_denied = false;

                if (certs == null || certs.Count == 0)
                {
                    return(null);
                }
                ICertificatePolicy certificatePolicy = ServicePointManager.CertificatePolicy;

                System.Net.Security.RemoteCertificateValidationCallback serverCertificateValidationCallback = ServicePointManager.ServerCertificateValidationCallback;
                System.Security.Cryptography.X509Certificates.X509Chain x509Chain = new System.Security.Cryptography.X509Certificates.X509Chain();
                x509Chain.ChainPolicy = new System.Security.Cryptography.X509Certificates.X509ChainPolicy();
                for (int i = 1; i < certs.Count; i++)
                {
                    System.Security.Cryptography.X509Certificates.X509Certificate2 certificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(certs[i].RawData);
                    x509Chain.ChainPolicy.ExtraStore.Add(certificate);
                }
                System.Security.Cryptography.X509Certificates.X509Certificate2 x509Certificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(certs[0].RawData);
                int num = 0;

                System.Net.Security.SslPolicyErrors sslPolicyErrors = System.Net.Security.SslPolicyErrors.None;
                try
                {
                    if (!x509Chain.Build(x509Certificate))
                    {
                        sslPolicyErrors |= ServicePointManager.ChainValidationHelper.GetErrorsFromChain(x509Chain);
                    }
                }
                catch (Exception arg)
                {
                    Console.Error.WriteLine("ERROR building certificate chain: {0}", arg);
                    Console.Error.WriteLine("Please, report this problem to the Mono team");
                    sslPolicyErrors |= System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors;
                }
                if (!ServicePointManager.ChainValidationHelper.CheckCertificateUsage(x509Certificate))
                {
                    sslPolicyErrors |= System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors;
                    num              = -2146762490;
                }
                if (!ServicePointManager.ChainValidationHelper.CheckServerIdentity(certs[0], this.Host))
                {
                    sslPolicyErrors |= System.Net.Security.SslPolicyErrors.RemoteCertificateNameMismatch;
                    num              = -2146762481;
                }
                bool flag = false;

                try
                {
                    OSX509Certificates.SecTrustResult secTrustResult = OSX509Certificates.TrustEvaluateSsl(certs);
                    flag = (secTrustResult == OSX509Certificates.SecTrustResult.Proceed || secTrustResult == OSX509Certificates.SecTrustResult.Unspecified);
                }
                catch
                {
                }
                if (flag)
                {
                    num             = 0;
                    sslPolicyErrors = System.Net.Security.SslPolicyErrors.None;
                }
                if (certificatePolicy != null && (!(certificatePolicy is DefaultCertificatePolicy) || serverCertificateValidationCallback == null))
                {
                    ServicePoint   srvPoint       = null;
                    HttpWebRequest httpWebRequest = this.sender as HttpWebRequest;
                    if (httpWebRequest != null)
                    {
                        srvPoint = httpWebRequest.ServicePoint;
                    }
                    if (num == 0 && sslPolicyErrors != System.Net.Security.SslPolicyErrors.None)
                    {
                        num = ServicePointManager.ChainValidationHelper.GetStatusFromChain(x509Chain);
                    }
                    flag        = certificatePolicy.CheckValidationResult(srvPoint, x509Certificate, httpWebRequest, num);
                    user_denied = (!flag && !(certificatePolicy is DefaultCertificatePolicy));
                }
                if (serverCertificateValidationCallback != null)
                {
                    flag        = serverCertificateValidationCallback(this.sender, x509Certificate, x509Chain, sslPolicyErrors);
                    user_denied = !flag;
                }
                return(new ValidationResult(flag, user_denied, num));
            }
Beispiel #37
0
        /// <summary>
        /// Validates the web certificates.
        /// </summary>
        /// <returns>
        /// <c>true</c>, if web certificates was validated, <c>false</c> otherwise.
        /// </returns>
        /// <param name='sender'>
        /// <c>Object</c> usually parsed as WebRequest or HttpWebRequest.
        /// </param>
        /// <param name='endCert'>
        /// Certificate consumed in the request.
        /// </param>
        /// <param name='chain'>
        /// Certificate chain total or partial.
        /// </param>
        /// <param name='Errors'>
        /// Policy errors found during the chain build process.
        /// </param>
        public static bool ValidateWebCertificates(Object sender, System.Security.Cryptography.X509Certificates.X509Certificate endCert, System.Security.Cryptography.X509Certificates.X509Chain chain, SslPolicyErrors Errors)
        {
            var    request    = sender as WebRequest;
            string requestUri = request.RequestUri.ToString();


            SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation");
            bool bErrorsFound = false;

            try {
                X509Certificate BCCert = Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(endCert);
                if (!CertificateIsTheSame(BCCert))
                {
                    chain.Build(new System.Security.Cryptography.X509Certificates.X509Certificate2(endCert.GetRawCertData()));
                    if (Errors.Equals(SslPolicyErrors.None))
                    {
                        if (chain == null || chain.ChainElements == null || chain.ChainElements.Count == 0)
                        {
                            SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation. Chain is empty");
                            bErrorsFound = true;
                        }
                        else
                        {
                            SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation. Chain Element count: " + chain.ChainElements.Count);
                        }

                        if (CertIsSelfSigned(BCCert))
                        {
                            SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation. End Certificate is Self Signed");
                            bErrorsFound = true;
                        }
                        else
                        {
                            SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation. End Certificate NOT Self Signed");
                        }


                        if (ValidateFingerprints)
                        {
                            SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation. VALIDATING Fingerprint");
                            if (!VerifyFingerprint(endCert, requestUri))
                            {
                                SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation. Invalid Fingerprint");
                                bErrorsFound = true;
                            }
                            else
                            {
                                SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation. Valid Fingerprint");
                            }
                        }
                        else
                        {
                            SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation. DO NOT validate Fingerprint");
                        }

                        /*foreach (System.Security.Cryptography.X509Certificates.X509ChainElement cert in chain.ChainElements) {
                         *      X509Certificate BCCerto = Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate (cert.Certificate);
                         *      if(CertIsSelfSigned(BCCerto)){
                         *              SystemLogger.Log (SystemLogger.Module.PLATFORM, "*************** SELF SIGNED Certificate: CERT NAME " + BCCerto.SubjectDN.ToString() + " ;ID = " + BCCerto.SerialNumber);
                         *              if(cert.Certificate.SerialNumber.Equals(chain.ChainElements[chain.ChainElements.Count-1].Certificate.SerialNumber)){
                         *                      string[] stringSeparators = new string[] {";"};
                         *                      string[] valids = _VALIDROOTAUTHORITIES.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
                         *                      foreach(String validRoot in valids){
                         *                              SystemLogger.Log (SystemLogger.Module.PLATFORM, "*************** SELF SIGNED Certificate check ["+validRoot+"]: "+cert.Certificate.SerialNumber+":"+chain.ChainElements[chain.ChainElements.Count-1].Certificate.SerialNumber);
                         *                              if(BCCerto.SubjectDN.ToString().Contains(validRoot)){
                         *                                      bErrorsFound = false;
                         *                              } else {
                         *                                      bErrorsFound = true;
                         *                              }
                         *                      }
                         *              }else {
                         *                      bErrorsFound = true;
                         *              }
                         *
                         *
                         *      }else{
                         *              SystemLogger.Log (SystemLogger.Module.PLATFORM, "*************** CERT NAME " + BCCerto.SubjectDN.ToString() + " ;ID = " + BCCerto.SerialNumber);
                         *      }
                         *
                         *      if(!CertIsValidNow(BCCerto)) bErrorsFound = true;
                         * }*/

                        //if (chain.ChainElements.Count > 1 && !VerifyCertificateOCSP(chain)) bCertIsOk = true;

                        //if (chain.ChainElements.Count > 1) bCertIsOk = true;
                        // DO NOT check OCSP revocation URLs. The time consuming this is expensive.
                        // TODO make this configurable and asynchronously in the case of enabled
                        // !VerifyCertificateOCSP(chain)  ---> ASYNC
                        SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** OCSP Verification (certificate revocation check) is DISABLED for this build");

                        if (!bErrorsFound)
                        {
                            myCertificateList.Add(BCCert.GetHashCode(), DateTime.Now);
                            SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation. Valid Certificate");
                            return(true);
                        }
                        else
                        {
                            SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation. Invalid Certificate");
                            return(false);
                        }
                    }
                    else if (Errors.Equals(SslPolicyErrors.RemoteCertificateChainErrors))
                    {
                        SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation: Errors found in the certificate chain.");

                        SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation: Checking chain status information for each element in the chain");
                        foreach (System.Security.Cryptography.X509Certificates.X509ChainElement element in chain.ChainElements)
                        {
                            SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation: Checking chain element... " + element.Information);

                            if (chain.ChainStatus != null && chain.ChainStatus.Length >= 0)
                            {
                                SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation: Chain Status array is not empty");
                                for (int index = 0; index < element.ChainElementStatus.Length; index++)
                                {
                                    SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation: chain element status: "
                                                     + element.ChainElementStatus[index].Status);
                                    SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation: chain element status information: "
                                                     + element.ChainElementStatus[index].StatusInformation);
                                }
                            }
                        }
                    }
                    else if (Errors.Equals(SslPolicyErrors.RemoteCertificateNameMismatch))
                    {
                        SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation: The certificate contains errors.");
                    }
                    else if (Errors.Equals(SslPolicyErrors.RemoteCertificateNotAvailable))
                    {
                        SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation: The certificate is not available");
                    }

                    SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation. Policy Errors: " + Errors);
                    return(false);
                }
                else                    //Trusted certificate
                {
                    SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation. Trusted Certificate");
                    return(true);
                }
            } catch (Exception e) {
                SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation: Unhandled exception: " + e.Message);
                return(false);
            }
        }