Ejemplo n.º 1
0
        public X509Certificate2 FindIssuerCertificate(X509Certificate2 serverX509Certificate2)
        {
            X509Certificate2 issuerX509Certificate2 = null;

            // Find the issuer certificate
            X509Chain x509Chain = new X509Chain();

            x509Chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
            x509Chain.Build(serverX509Certificate2);

            // Iterate though the chain, to validate if it contain a valid root vertificate
            X509ChainElementCollection             x509ChainElementCollection = x509Chain.ChainElements;
            X509ChainElementEnumerator             enumerator = x509ChainElementCollection.GetEnumerator();
            X509ChainElement                       x509ChainElement;
            X509Certificate2                       x509Certificate2 = null;
            IDictionary <string, X509Certificate2> map = new Dictionary <string, X509Certificate2>();

            // At this point, the certificate is not valid, until a
            // it is proved that it has a valid root certificate
            while (enumerator.MoveNext())
            {
                x509ChainElement = enumerator.Current;
                x509Certificate2 = x509ChainElement.Certificate;
                map.Add(x509Certificate2.Subject, x509Certificate2);
            }

            if (map.ContainsKey(serverX509Certificate2.Issuer))
            {
                issuerX509Certificate2 = map[serverX509Certificate2.Issuer];
            }

            return(issuerX509Certificate2);
        }
Ejemplo n.º 2
0
 private X509CertificateClaimSet(X509ChainElementCollection elements, int index)
 {
     this.expirationTime = System.IdentityModel.SecurityUtils.MinUtcDateTime;
     this.elements       = elements;
     this.index          = index;
     this.certificate    = elements[index].Certificate;
 }
        public static void ShowCertAndChain(X509Certificate cert, X509Chain chain)
        {
            StringBuilder sb = new StringBuilder();

            if (null != cert)
            {
                ShowX509Certificate(sb, cert);
            }

            if (null != chain)
            {
                sb.Append("-X509Chain(Start)-" + System.Environment.NewLine);
                ////sb.Append(string.Format("Cert.ChainStatus='{0}'", string.Join(",", chain.ChainStatus.ToList())) + System.Environment.NewLine);

                foreach (X509ChainStatus cstat in chain.ChainStatus)
                {
                    sb.Append(string.Format("X509ChainStatus::'{0}'-'{1}'", cstat.Status.ToString(), cstat.StatusInformation) + System.Environment.NewLine);
                }

                X509ChainElementCollection ces = chain.ChainElements;
                ShowX509ChainElementCollection(sb, ces);
                sb.Append("-X509Chain(End)-" + System.Environment.NewLine);
            }

            string result = sb.ToString();

            Console.WriteLine(result);
        }
Ejemplo n.º 4
0
        public static bool RemoteCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            X509ChainElementCollection x509ChainElementCollection = chain.ChainElements;

            foreach (X509ChainElement chainElement in x509ChainElementCollection)
            {
                X509Certificate2  cert        = chainElement.Certificate;
                X509ChainStatus[] chainStatus = chainElement.ChainElementStatus;
                string            info        = chainElement.Information;

                // Get the raw bytes so we can write it:
                string name    = cert.GetNameInfo(X509NameType.SimpleName, false);
                byte[] rawCert = cert.GetRawCertData();

                // Substitute characters that foul up a shell script or batch file
                string outputName = (name.Replace(' ', '_')).Replace('*', '_').Replace('(', '_').Replace(')', '_') + ".cer";

                using (FileStream fs = new FileStream(outputName, FileMode.Create, FileAccess.Write))
                {
                    fs.Write(rawCert, 0, rawCert.Length);
                }
            }

            return(true);
        }
Ejemplo n.º 5
0
        private void AssertCert(X509Certificate2 cert, bool expectValidCert)
        {
            X509Chain       chainBuilder = new X509Chain();
            X509ChainPolicy policy       = new X509ChainPolicy();

            policy.VerificationFlags = X509VerificationFlags.IgnoreWrongUsage;
            chainBuilder.ChainPolicy = policy;


            chainBuilder.Build(cert);
            X509ChainElementCollection chainElements = chainBuilder.ChainElements;

            // If we don't have a trust chain, then we obviously have a problem...
            Assert.False(chainElements.IsNullOrEmpty(), string.Format("Can't find a trust chain: {0} ", cert.Subject));

            // walk the chain starting at the leaf and see if we hit any issues
            foreach (X509ChainElement chainElement in chainElements)
            {
                if (expectValidCert)
                {
                    AssertChainHasNoProblems(chainElement);
                }
                else
                {
                    AssertChainHasProblems(chainElement);
                }
            }
        }
Ejemplo n.º 6
0
    public static void Test(X509IncludeOption include)
    {
        cert = EndCert;
        X509Chain chain = new X509Chain();

        chain.Build(cert);

        X509ChainElementCollection lmnts = chain.ChainElements;

        KeyInfoX509Data data = new KeyInfoX509Data(cert, include);
        ArrayList       al   = data.Certificates;

        if (al == null)
        {
            return;
        }
        for (int i = 0; i < al.Count; i++)
        {
            rv = lmnts[i].Certificate.ToString(true) == ((X509Certificate)al[i]).ToString(true);
            if (!rv)
            {
                Console.WriteLine("i  = " + i.ToString() + " and include=" + include.ToString());
            }
        }
        Console.WriteLine("*************************************************************");
    }
Ejemplo n.º 7
0
        private static bool ValidationCheck(object sender, X509Certificate certificate, X509Chain chain,
                                            SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors != SslPolicyErrors.None)
            {
                return(false);
            }
            if (chain.ChainPolicy.VerificationFlags == X509VerificationFlags.NoFlag &&
                chain.ChainPolicy.RevocationMode == X509RevocationMode.Online)
            {
                return(true);
            }

            X509Chain newChain = new X509Chain();
            X509ChainElementCollection chainElements = chain.ChainElements;

            for (int i = 1; i < chainElements.Count - 1; i++)
            {
                newChain.ChainPolicy.ExtraStore.Add(chainElements[i].Certificate);
            }

            // Use chainElements[0].Certificate since it's the right cert already
            // in X509Certificate2 form, preventing a cast or the sometimes-dangerous
            // X509Certificate2(X509Certificate) constructor.
            // If the chain build successfully it matches all our policy requests,
            // if it fails, it either failed to build (which is unlikely, since we already had one)
            // or it failed policy (like it's revoked).
            return(newChain.Build(chainElements[0].Certificate));
        }
Ejemplo n.º 8
0
    public override string GetIssuerName(SecurityToken securityToken)
    {
        X509SecurityToken x509Token = securityToken as X509SecurityToken;

        if (x509Token != null)
        {
            // The following check is to allow only trusted issuers of the STS token
            if (String.Equals(x509Token.Certificate.SubjectName.Name, "CN=localhost"))
            {
                return(x509Token.Certificate.SubjectName.Name);
            }

            // The following check is to allow only trusted issuers for the client certificate.
            if (HttpContext.Current != null && HttpContext.Current.Request != null && HttpContext.Current.Request.ClientCertificate != null &&
                HttpContext.Current.Request.ClientCertificate.IsPresent && HttpContext.Current.Request.ClientCertificate.IsValid)
            {
                X509Certificate2 clientCertificate = new X509Certificate2(HttpContext.Current.Request.ClientCertificate.Certificate);

                // Get the issuer of the client certificate
                X509Chain chain = new X509Chain();
                chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
                chain.Build(clientCertificate);
                X509ChainElementCollection elements = chain.ChainElements;

                X509Certificate2 issuerCert = null;
                if (elements.Count > 1)
                {
                    issuerCert = elements[1].Certificate;
                }
                else
                {
                    // This is a self-issued certificate.
                    issuerCert = clientCertificate;
                }

                string issuerCertThumbprint = issuerCert.Thumbprint;

                // Reset the state of the certificate and free resources associated with it.
                for (int i = 1; i < elements.Count; ++i)
                {
                    elements[i].Certificate.Reset();
                }

                // The implementation below currently accepts all client certificates and returns the SubjectName as the issuer name. This is intended only for illustration purposes.
                // In production, consider doing additional validation based on the issuer of the client certificate to return an appropriate issuer name.
                // DO NOT use this sample code ‘as is’ in production code.

                // Ensure that the issuer of the client certificate as obtained from the transport, matches the issuer token passed in to this method.
                if (!StringComparer.Ordinal.Equals(issuerCertThumbprint, x509Token.Certificate.Thumbprint))
                {
                    throw new SecurityTokenException("Issuer of the client certificate as obtained from the transport does not match the issuer token passed in to this method.");
                }

                return(x509Token.Certificate.SubjectName.Name);
            }
        }

        throw new SecurityTokenException("Untrusted issuer.");
    }
Ejemplo n.º 9
0
        public X509Certificate2 Load()
        {
            if (!File.Exists(Filename))
            {
                Logger.LogError("Cannot load certificate because the file does not exist: {0}", Filename);
                return(null);
            }

            Logger.Log("Loading...");
            X509Certificate2 certificate = null;

            try
            {
                certificate = new X509Certificate2(Filename, Password);
            }
            catch (Exception e)
            {
                Logger.LogError(e, "Failed to load certificate: {0}");
                return(null);
            }

            Logger.Log("Verifying...");
            X509Chain chain = new X509Chain();

            chain.ChainPolicy.RevocationFlag      = X509RevocationFlag.EndCertificateOnly;
            chain.ChainPolicy.RevocationMode      = X509RevocationMode.NoCheck;
            chain.ChainPolicy.UrlRetrievalTimeout = TimeSpan.FromSeconds(5);
            chain.ChainPolicy.VerificationFlags   = X509VerificationFlags.AllowUnknownCertificateAuthority | X509VerificationFlags.IgnoreCertificateAuthorityRevocationUnknown;

            bool happy = chain.Build(certificate);
            bool valid = true;

            //Get elements
            X509ChainElementCollection elements = chain.ChainElements;

            Logger.Log($"Chain built with {elements.Count} elements, happy={happy}");

            //Make sure each element is okay
            for (int i = 0; i < elements.Count; i++)
            {
                X509ChainElement element = elements[i];
                Logger.Log($" > Element {i}: {element.Certificate.GetNameInfo(X509NameType.SimpleName, false)}");
                foreach (X509ChainStatus status in element.ChainElementStatus)
                {
                    Logger.LogError($" >>> {status.Status}: {status.StatusInformation}");
                    valid = false;
                }
            }

            //Final check
            if (!happy && !valid)
            {
                Logger.LogError("Failed to load certificate! Happy: {0}, Valid: {1}", happy, valid);
                return(null);
            }

            //return the certificate
            return(certificate);
        }
 public override void Reset()
 {
     if (elements != null)
     {
         nativeCertificateChain.handle = UnityTls.NativeInterface.UNITYTLS_INVALID_HANDLE;
         elements.Clear();
         elements = null;
     }
 }
Ejemplo n.º 11
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);
        }
Ejemplo n.º 12
0
        public KeyInfoX509Data(X509Certificate cert, X509IncludeOption includeOption)
        {
            if (cert == null)
            {
                throw new ArgumentNullException(nameof(cert));
            }

            X509Certificate2           certificate = new X509Certificate2(cert);
            X509ChainElementCollection elements    = null;
            X509Chain chain = null;

            switch (includeOption)
            {
            case X509IncludeOption.ExcludeRoot:
                // Build the certificate chain
                chain = new X509Chain();
                chain.Build(certificate);

                // Can't honor the option if we only have a partial chain.
                if ((chain.ChainStatus.Length > 0) &&
                    ((chain.ChainStatus[0].Status & X509ChainStatusFlags.PartialChain) == X509ChainStatusFlags.PartialChain))
                {
                    throw new CryptographicException(SR.Cryptography_Partial_Chain);
                }

                elements = (X509ChainElementCollection)chain.ChainElements;
                for (int index = 0; index < (Utils.IsSelfSigned(chain) ? 1 : elements.Count - 1); index++)
                {
                    AddCertificate(elements[index].Certificate);
                }
                break;

            case X509IncludeOption.EndCertOnly:
                AddCertificate(certificate);
                break;

            case X509IncludeOption.WholeChain:
                // Build the certificate chain
                chain = new X509Chain();
                chain.Build(certificate);

                // Can't honor the option if we only have a partial chain.
                if ((chain.ChainStatus.Length > 0) &&
                    ((chain.ChainStatus[0].Status & X509ChainStatusFlags.PartialChain) == X509ChainStatusFlags.PartialChain))
                {
                    throw new CryptographicException(SR.Cryptography_Partial_Chain);
                }

                elements = (X509ChainElementCollection)chain.ChainElements;
                foreach (X509ChainElement element in elements)
                {
                    AddCertificate(element.Certificate);
                }
                break;
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Initializes a new instance of the <see cref="X509ChainElementCollectionWrap"/> class.
        /// </summary>
        /// <param name="collection">
        /// The collection.
        /// </param>
        public void Initialize(X509ChainElementCollection collection)
        {
            this.elements = new IX509ChainElement[collection.Count];
            var elementFactory = new X509ChainElementFactory(this.file, this.path);

            for (var i = 0; i < this.elements.Length; i++)
            {
                this.elements[i] = elementFactory.Create(collection[i]);
            }
        }
Ejemplo n.º 14
0
        private static ICollection <X509Certificate> GetCertChainCollectionFromAlias()
        {
            X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);

            store.Open(OpenFlags.ReadOnly);

            // If you get compilation error after on X509Certificate2UI class, then Project->Add Reference -> Add System.Security
            X509Certificate2Collection selectedCert = X509Certificate2UI.SelectFromCollection(store.Certificates, null, null, X509SelectionFlag.SingleSelection);

            storedSelectedCert = selectedCert;
            //Org.BouncyCastle.X509.X509Certificate[] chain = null;
            ICollection <X509Certificate> certChain = new List <X509Certificate>();

            /*
             * Org.BouncyCastle.X509.X509CertificateParser cp = new Org.BouncyCastle.X509.X509CertificateParser();
             * chain = new Org.BouncyCastle.X509.X509Certificate[] {
             *   cp.ReadCertificate(certificate.RawData)};
             * foreach (Org.BouncyCastle.X509.X509Certificate c in chain)
             *  Console.WriteLine(c);
             */

            X509Chain ch = new X509Chain();

            try {
                ch.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
                ch.Build(selectedCert[0]);
                X509ChainElementCollection chainElems = ch.ChainElements;
            } catch (Exception exception) {
                throw exception;
            }


            foreach (X509ChainElement element in ch.ChainElements)
            {
                //element.Certificate
                //cp.ReadCertificate(element.Certificate.RawData);
                X509Certificate x509cert = new X509Certificate(element.Certificate.RawData);


                certChain.Add(x509cert);
                Console.WriteLine("Element Subject: {0}", element.Certificate.Subject);
                Console.WriteLine("Element issuer name: {0}", element.Certificate.Issuer);


                if (ch.ChainStatus.Length > 1)
                {
                    for (int index = 0; index < element.ChainElementStatus.Length; index++)
                    {
                        Console.WriteLine(element.ChainElementStatus[index].Status);
                        Console.WriteLine(element.ChainElementStatus[index].StatusInformation);
                    }
                }
            }
            return(certChain);
        }
                protected override void EstablishContext()
                {
                    base.EstablishContext();

                    var collection = new X509Chain();

                    collection.Build(new X509Certificate2(LiebherrRootCaCertificateRawCertData));
                    this.SpecifiedCollection = collection.ChainElements;

                    this.ExpectedCount = 1;
                }
Ejemplo n.º 16
0
        internal static bool IsSelfSigned(X509Chain chain)
        {
            X509ChainElementCollection chainElements = chain.ChainElements;

            if (chainElements.Count != 1)
            {
                return(false);
            }
            X509Certificate2 certificate = chainElements[0].Certificate;

            return(string.Compare(certificate.SubjectName.Name, certificate.IssuerName.Name, StringComparison.OrdinalIgnoreCase) == 0);
        }
Ejemplo n.º 17
0
        private void TestOCSP()
        {
            OcspLookup ocspLookup = new OcspLookup();

            X509Store certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);

            certStore.Open(OpenFlags.ReadOnly);

            string serial = "4c 05 5a 37";

            X509Certificate2Collection collection = certStore.Certificates.Find(X509FindType.FindBySerialNumber, serial, true);
            X509Certificate2           cert       = null;

            if (collection.Count > 0)
            {
                cert = collection[0];
            }
            else
            {
                // the certificate not found
                throw new NotImplementedException("The certificate was not found.");
            }

            X509Chain x509Chain = new X509Chain();

            x509Chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
            x509Chain.Build(cert);

            // Iterate though the chain, to validate if it contain a valid root vertificate
            X509ChainElementCollection             x509ChainElementCollection = x509Chain.ChainElements;
            X509ChainElementEnumerator             enumerator = x509ChainElementCollection.GetEnumerator();
            X509ChainElement                       x509ChainElement;
            X509Certificate2                       x509Certificate2 = null;
            IDictionary <string, X509Certificate2> map  = new Dictionary <string, X509Certificate2>();
            IList <X509Certificate2>               list = new List <X509Certificate2>();

            // At this point, the certificate is not valid, until a
            // it is proved that it has a valid root certificate
            while (enumerator.MoveNext())
            {
                x509ChainElement = enumerator.Current;
                x509Certificate2 = x509ChainElement.Certificate;
                list.Add(x509Certificate2);
            }



            ocspLookup.RevocationResponseOnline(list[0], list[1], "http://ocsp.systemtest8.trust2408.com/responder");
        }
Ejemplo n.º 18
0
 public static Int32 IndexOf(this X509ChainElementCollection collection, X509ChainElement item)
 {
     if (collection == null)
     {
         return(-1);
     }
     for (Int32 index = 0; index < collection.Count; index++)
     {
         if (collection[index].Certificate.Equals(item.Certificate))
         {
             return(index);
         }
     }
     return(-1);
 }
        public KeyInfoX509Data(X509Certificate cert, X509IncludeOption includeOption)
        {
            if (cert == null)
            {
                throw new ArgumentNullException("cert");
            }
            X509Certificate2           certificate   = new X509Certificate2(cert);
            X509ChainElementCollection chainElements = null;
            X509Chain chain = null;

            switch (includeOption)
            {
            case X509IncludeOption.ExcludeRoot:
                chain = new X509Chain();
                chain.Build(certificate);
                if ((chain.ChainStatus.Length > 0) && ((chain.ChainStatus[0].Status & X509ChainStatusFlags.PartialChain) == X509ChainStatusFlags.PartialChain))
                {
                    throw new CryptographicException(-2146762486);
                }
                chainElements = chain.ChainElements;
                for (int i = 0; i < (System.Security.Cryptography.X509Certificates.X509Utils.IsSelfSigned(chain) ? 1 : (chainElements.Count - 1)); i++)
                {
                    this.AddCertificate(chainElements[i].Certificate);
                }
                return;

            case X509IncludeOption.EndCertOnly:
                this.AddCertificate(certificate);
                return;

            case X509IncludeOption.WholeChain:
            {
                chain = new X509Chain();
                chain.Build(certificate);
                if ((chain.ChainStatus.Length > 0) && ((chain.ChainStatus[0].Status & X509ChainStatusFlags.PartialChain) == X509ChainStatusFlags.PartialChain))
                {
                    throw new CryptographicException(-2146762486);
                }
                X509ChainElementEnumerator enumerator = chain.ChainElements.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    X509ChainElement current = enumerator.Current;
                    this.AddCertificate(current.Certificate);
                }
                return;
            }
            }
        }
Ejemplo n.º 20
0
 public override void Reset()
 {
     if (certificates != null)
     {
         foreach (var certificate in certificates)
         {
             certificate.Dispose();
         }
         certificates = null;
     }
     if (elements != null)
     {
         elements.Clear();
         elements = null;
     }
 }
Ejemplo n.º 21
0
        internal static string GetCertificateIssuerName(X509Certificate2 certificate, IssuerNameRegistry issuerNameRegistry)
        {
            if (certificate == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("certificate");
            }

            if (issuerNameRegistry == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("issuerNameRegistry");
            }

            X509Chain chain = new X509Chain();

            chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
            chain.Build(certificate);
            X509ChainElementCollection elements = chain.ChainElements;

            string issuer = null;

            if (elements.Count > 1)
            {
                using (X509SecurityToken token = new X509SecurityToken(elements[1].Certificate))
                {
                    issuer = issuerNameRegistry.GetIssuerName(token);
                }
            }
            else
            {
                // This is a self-issued certificate. Use the thumbprint of the current certificate.
                using (X509SecurityToken token = new X509SecurityToken(certificate))
                {
                    issuer = issuerNameRegistry.GetIssuerName(token);
                }
            }

            for (int i = 1; i < elements.Count; ++i)
            {
                // Resets the state of the certificate and frees resources associated with it.
                elements[i].Certificate.Reset();
            }

            return(issuer);
        }
Ejemplo n.º 22
0
        private void AddCertificate(X509Certificate2 cert, UnsignedProperties unsignedProperties, bool addCert, IEnumerable <string> ocspServers, IEnumerable <X509Crl> crlList, FirmaXades.Crypto.DigestMethod digestMethod, X509Certificate2[] extraCerts = null)
        {
            if (addCert)
            {
                if (CertificateChecked(cert, unsignedProperties))
                {
                    return;
                }
                string str   = Guid.NewGuid().ToString();
                Cert   cert2 = new Cert();
                cert2.IssuerSerial.X509IssuerName   = cert.IssuerName.Name;
                cert2.IssuerSerial.X509SerialNumber = cert.GetSerialNumberAsDecimalString();
                DigestUtil.SetCertDigest(cert.GetRawCertData(), digestMethod, cert2.CertDigest);
                cert2.URI = "#Cert" + str;
                unsignedProperties.UnsignedSignatureProperties.CompleteCertificateRefs.CertRefs.CertCollection.Add(cert2);
                EncapsulatedX509Certificate encapsulatedX509Certificate = new EncapsulatedX509Certificate();
                encapsulatedX509Certificate.Id      = "Cert" + str;
                encapsulatedX509Certificate.PkiData = cert.GetRawCertData();
                unsignedProperties.UnsignedSignatureProperties.CertificateValues.EncapsulatedX509CertificateCollection.Add(encapsulatedX509Certificate);
            }
            X509ChainElementCollection chainElements = CertUtil.GetCertChain(cert, extraCerts).ChainElements;

            if (chainElements.Count > 1)
            {
                X509ChainElementEnumerator enumerator = chainElements.GetEnumerator();
                enumerator.MoveNext();
                enumerator.MoveNext();
                if (!ValidateCertificateByCRL(unsignedProperties, cert, enumerator.Current.Certificate, crlList, digestMethod))
                {
                    X509Certificate2[] array = ValidateCertificateByOCSP(unsignedProperties, cert, enumerator.Current.Certificate, ocspServers, digestMethod);
                    if (array != null)
                    {
                        X509Certificate2 x509Certificate = DetermineStartCert(new List <X509Certificate2>(array));
                        if (x509Certificate.IssuerName.Name != enumerator.Current.Certificate.SubjectName.Name)
                        {
                            X509Chain certChain = CertUtil.GetCertChain(x509Certificate, array);
                            AddCertificate(certChain.ChainElements[1].Certificate, unsignedProperties, true, ocspServers, crlList, digestMethod, array);
                        }
                    }
                }
                AddCertificate(enumerator.Current.Certificate, unsignedProperties, true, ocspServers, crlList, digestMethod, extraCerts);
            }
        }
        private static void ShowX509ChainElementCollection(StringBuilder sb, X509ChainElementCollection ces)
        {
            int x509ChainElementCount = 0;

            foreach (X509ChainElement ce in ces)
            {
                sb.Append(string.Empty + System.Environment.NewLine);
                sb.Append(string.Format("----X509ChainElementNumber:{0}", ++x509ChainElementCount) + System.Environment.NewLine);
                sb.Append(string.Format("X509ChainElement.Cert.SubjectName.Name='{0}'", ce.Certificate.SubjectName.Name) + System.Environment.NewLine);
                sb.Append(string.Format("X509ChainElement.Cert.Issuer='{0}'", ce.Certificate.Issuer) + System.Environment.NewLine);
                sb.Append(string.Format("X509ChainElement.Cert.Thumbprint='{0}'", ce.Certificate.Thumbprint) + System.Environment.NewLine);
                sb.Append(string.Format("X509ChainElement.Cert.HasPrivateKey='{0}'", ce.Certificate.HasPrivateKey) + System.Environment.NewLine);

                X509Certificate2 cert2 = ce.Certificate as X509Certificate2;
                ShowX509Certificate2(sb, cert2);

                ShowX509Extensions(sb, cert2.Subject, ce.Certificate.Extensions);
            }
        }
Ejemplo n.º 24
0
        public KeyInfoX509Data(X509Certificate cert, X509IncludeOption includeOption)
        {
            if (cert == null)
            {
                throw new ArgumentNullException(nameof(cert));
            }
            X509Certificate2 certificate = new X509Certificate2(cert);

            switch (includeOption)
            {
            case X509IncludeOption.ExcludeRoot:
                X509Chain chain = new X509Chain();
                chain.Build(certificate);
                if (chain.ChainStatus.Length != 0 && (chain.ChainStatus[0].Status & X509ChainStatusFlags.PartialChain) == X509ChainStatusFlags.PartialChain)
                {
                    throw new CryptographicException(-2146762486);
                }
                X509ChainElementCollection chainElements = chain.ChainElements;
                for (int index = 0; index < (X509Utils.IsSelfSigned(chain) ? 1 : chainElements.Count - 1); ++index)
                {
                    this.AddCertificate((X509Certificate)chainElements[index].Certificate);
                }
                break;

            case X509IncludeOption.EndCertOnly:
                this.AddCertificate((X509Certificate)certificate);
                break;

            case X509IncludeOption.WholeChain:
                X509Chain x509Chain = new X509Chain();
                x509Chain.Build(certificate);
                if (x509Chain.ChainStatus.Length != 0 && (x509Chain.ChainStatus[0].Status & X509ChainStatusFlags.PartialChain) == X509ChainStatusFlags.PartialChain)
                {
                    throw new CryptographicException(-2146762486);
                }
                foreach (X509ChainElement chainElement in x509Chain.ChainElements)
                {
                    this.AddCertificate((X509Certificate)chainElement.Certificate);
                }
                break;
            }
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Validate network ssl certificate, you can use certificate validation on your config for more security
        /// example : request.ServerCertificateValidationCallback = ValidationCallback;
        /// </summary>
        public static bool ValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors != SslPolicyErrors.None)
            {
                return(false);
            }
            if (chain.ChainPolicy.VerificationFlags == X509VerificationFlags.NoFlag &&
                chain.ChainPolicy.RevocationMode == X509RevocationMode.Online)
            {
                return(true);
            }
            X509Chain newChain = new X509Chain();
            X509ChainElementCollection chainElements = chain.ChainElements;

            for (int i = 1; i < chainElements.Count - 1; i++)
            {
                newChain.ChainPolicy.ExtraStore.Add(chainElements[i].Certificate);
            }

            return(newChain.Build(chainElements[0].Certificate));
        }
Ejemplo n.º 26
0
 public static Boolean Contains(this X509ChainElementCollection collection, X509ChainElement item)
 {
     return(collection.Cast <X509ChainElement>().Any(x => item.Certificate.Equals(item.Certificate)));
 }
Ejemplo n.º 27
0
 public static X509ChainElement Item(this X509ChainElementCollection collection, X509ChainElement item)
 {
     return(collection.Count == 0
                         ? null
                         : collection.Cast <X509ChainElement>().FirstOrDefault(x => x.Certificate.Thumbprint == item.Certificate.Thumbprint));
 }
Ejemplo n.º 28
0
        internal SignerInfoAsn Sign(
            ReadOnlyMemory <byte> data,
            string contentTypeOid,
            bool silent,
            out X509Certificate2Collection chainCerts)
        {
            HashAlgorithmName hashAlgorithmName = PkcsHelpers.GetDigestAlgorithm(DigestAlgorithm);
            IncrementalHash   hasher            = IncrementalHash.CreateHash(hashAlgorithmName);

            hasher.AppendData(data.Span);
            byte[] dataHash = hasher.GetHashAndReset();

            SignerInfoAsn newSignerInfo = new SignerInfoAsn();

            newSignerInfo.DigestAlgorithm.Algorithm = DigestAlgorithm;

            // If the user specified attributes (not null, count > 0) we need attributes.
            // If the content type is null we're counter-signing, and need the message digest attr.
            // If the content type is otherwise not-data we need to record it as the content-type attr.
            if (SignedAttributes?.Count > 0 || contentTypeOid != Oids.Pkcs7Data)
            {
                List <AttributeAsn> signedAttrs = BuildAttributes(SignedAttributes);

                using (var writer = new AsnWriter(AsnEncodingRules.DER))
                {
                    writer.WriteOctetString(dataHash);
                    signedAttrs.Add(
                        new AttributeAsn
                    {
                        AttrType   = new Oid(Oids.MessageDigest, Oids.MessageDigest),
                        AttrValues = new[] { new ReadOnlyMemory <byte>(writer.Encode()) },
                    });
                }

                if (contentTypeOid != null)
                {
                    using (var writer = new AsnWriter(AsnEncodingRules.DER))
                    {
                        writer.WriteObjectIdentifier(contentTypeOid);
                        signedAttrs.Add(
                            new AttributeAsn
                        {
                            AttrType   = new Oid(Oids.ContentType, Oids.ContentType),
                            AttrValues = new[] { new ReadOnlyMemory <byte>(writer.Encode()) },
                        });
                    }
                }

                // Use the serializer/deserializer to DER-normalize the attribute order.
                SignedAttributesSet signedAttrsSet = new SignedAttributesSet();
                signedAttrsSet.SignedAttributes = PkcsHelpers.NormalizeAttributeSet(
                    signedAttrs.ToArray(),
                    normalized => hasher.AppendData(normalized));

                // Since this contains user data in a context where BER is permitted, use BER.
                // There shouldn't be any observable difference here between BER and DER, though,
                // since the top level fields were written by NormalizeSet.
                using (AsnWriter attrsWriter = new AsnWriter(AsnEncodingRules.BER))
                {
                    signedAttrsSet.Encode(attrsWriter);
                    newSignerInfo.SignedAttributes = attrsWriter.Encode();
                }

                dataHash = hasher.GetHashAndReset();
            }

            switch (SignerIdentifierType)
            {
            case SubjectIdentifierType.IssuerAndSerialNumber:
                byte[] serial = Certificate.GetSerialNumber();
                Array.Reverse(serial);

                newSignerInfo.Sid.IssuerAndSerialNumber = new IssuerAndSerialNumberAsn
                {
                    Issuer       = Certificate.IssuerName.RawData,
                    SerialNumber = serial,
                };

                newSignerInfo.Version = 1;
                break;

            case SubjectIdentifierType.SubjectKeyIdentifier:
                newSignerInfo.Sid.SubjectKeyIdentifier = PkcsPal.Instance.GetSubjectKeyIdentifier(Certificate);
                newSignerInfo.Version = 3;
                break;

            case SubjectIdentifierType.NoSignature:
                newSignerInfo.Sid.IssuerAndSerialNumber = new IssuerAndSerialNumberAsn
                {
                    Issuer       = SubjectIdentifier.DummySignerEncodedValue,
                    SerialNumber = new byte[1],
                };
                newSignerInfo.Version = 1;
                break;

            default:
                Debug.Fail($"Unresolved SignerIdentifierType value: {SignerIdentifierType}");
                throw new CryptographicException();
            }

            if (UnsignedAttributes != null && UnsignedAttributes.Count > 0)
            {
                List <AttributeAsn> attrs = BuildAttributes(UnsignedAttributes);

                newSignerInfo.UnsignedAttributes = PkcsHelpers.NormalizeAttributeSet(attrs.ToArray());
            }

            bool signed;
            Oid  signatureAlgorithm;
            ReadOnlyMemory <byte> signatureValue;

            if (SignerIdentifierType == SubjectIdentifierType.NoSignature)
            {
                signatureAlgorithm = new Oid(Oids.NoSignature, null);
                signatureValue     = dataHash;
                signed             = true;
            }
            else
            {
                signed = CmsSignature.Sign(
                    dataHash,
                    hashAlgorithmName,
                    Certificate,
                    PrivateKey,
                    silent,
                    out signatureAlgorithm,
                    out signatureValue);
            }

            if (!signed)
            {
                throw new CryptographicException(SR.Cryptography_Cms_CannotDetermineSignatureAlgorithm);
            }

            newSignerInfo.SignatureValue = signatureValue;
            newSignerInfo.SignatureAlgorithm.Algorithm = signatureAlgorithm;

            X509Certificate2Collection certs = new X509Certificate2Collection();

            certs.AddRange(Certificates);

            if (SignerIdentifierType != SubjectIdentifierType.NoSignature)
            {
                if (IncludeOption == X509IncludeOption.EndCertOnly)
                {
                    certs.Add(Certificate);
                }
                else if (IncludeOption != X509IncludeOption.None)
                {
                    X509Chain chain = new X509Chain();
                    chain.ChainPolicy.RevocationMode    = X509RevocationMode.NoCheck;
                    chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags;

                    if (!chain.Build(Certificate))
                    {
                        foreach (X509ChainStatus status in chain.ChainStatus)
                        {
                            if (status.Status == X509ChainStatusFlags.PartialChain)
                            {
                                throw new CryptographicException(SR.Cryptography_Cms_IncompleteCertChain);
                            }
                        }
                    }

                    X509ChainElementCollection elements = chain.ChainElements;
                    int count = elements.Count;
                    int last  = count - 1;

                    if (last == 0)
                    {
                        // If there's always one cert treat it as EE, not root.
                        last = -1;
                    }

                    for (int i = 0; i < count; i++)
                    {
                        X509Certificate2 cert = elements[i].Certificate;

                        if (i == last &&
                            IncludeOption == X509IncludeOption.ExcludeRoot &&
                            cert.SubjectName.RawData.AsSpan().SequenceEqual(cert.IssuerName.RawData))
                        {
                            break;
                        }

                        certs.Add(cert);
                    }
                }
            }

            chainCerts = certs;
            return(newSignerInfo);
        }
Ejemplo n.º 29
0
 X509CertificateClaimSet(X509ChainElementCollection elements, int index)
 {
     this.elements    = elements;
     this.index       = index;
     this.certificate = elements[index].Certificate;
 }
Ejemplo n.º 30
0
        private static void SetCertificate(SafeSslHandle sslContext, X509Certificate2 certificate)
        {
            Debug.Assert(sslContext != null, "sslContext != null");
            Debug.Assert(certificate != null, "certificate != null");
            Debug.Assert(certificate.HasPrivateKey, "certificate.HasPrivateKey");

            X509Chain chain = TLSCertificateExtensions.BuildNewChain(
                certificate,
                includeClientApplicationPolicy: false) !;

            using (chain)
            {
                X509ChainElementCollection elements = chain.ChainElements;

                // We need to leave off the EE (first) and root (last) certificate from the intermediates.
                X509Certificate2[] intermediateCerts = elements.Count < 3
                    ? Array.Empty <X509Certificate2>()
                    : new X509Certificate2[elements.Count - 2];

                // Build an array which is [
                //   SecIdentityRef for EE cert,
                //   SecCertificateRef for intermed0,
                //   SecCertificateREf for intermed1,
                //   ...
                // ]
                IntPtr[] ptrs = new IntPtr[intermediateCerts.Length + 1];

                for (int i = 0; i < intermediateCerts.Length; i++)
                {
                    X509Certificate2 intermediateCert = elements[i + 1].Certificate !;

                    if (intermediateCert.HasPrivateKey)
                    {
                        // In the unlikely event that we get a certificate with a private key from
                        // a chain, clear it to the certificate.
                        //
                        // The current value of intermediateCert is still in elements, which will
                        // get Disposed at the end of this method.  The new value will be
                        // in the intermediate certs array, which also gets serially Disposed.
                        intermediateCert = new X509Certificate2(intermediateCert.RawData);
                    }

                    intermediateCerts[i] = intermediateCert;
                    ptrs[i + 1]          = intermediateCert.Handle;
                }

                ptrs[0] = certificate.Handle;

                Interop.AppleCrypto.SslSetCertificate(sslContext, ptrs);

                // The X509Chain created all new certs for us, so Dispose them.
                // And since the intermediateCerts could have been new instances, Dispose them, too
                for (int i = 0; i < elements.Count; i++)
                {
                    elements[i].Certificate !.Dispose();

                    if (i < intermediateCerts.Length)
                    {
                        intermediateCerts[i].Dispose();
                    }
                }
            }
        }
Ejemplo n.º 31
0
		public X509Chain (bool useMachineContext) 
		{
			_machineContext = useMachineContext;
			_elements = new X509ChainElementCollection ();
			_policy = new X509ChainPolicy ();
		}