bc-csharp icon indicating copy to clipboard operation
bc-csharp copied to clipboard

PkixCertPath SortCerts() sporadically fails with unsorted lists

Open invidious9000 opened this issue 8 years ago • 2 comments

Given a certificate chain with the following structure: Root -> Intermediate -> End Entity

If this list of certs is put into something like a Hashset eventually it will end up this order: [ End Entity, Root, Intermediate ]

The first condition check for okay is false because the certs are not already sorted so the method proceeds to second for-loop.

In iteration i=0 cert will be "End Entity", which is not the issuer of any other certs, so found = false and the "End Entity" cert is removed from the input certs list and added to retList and then i increments. certs is an ArrayList so the indexes 'move up' as a result of RemoveAt()

Now in iteration i=1 the cert being evaluated is "Intermediate" which was an issuer of End Entity but now incorrectly fails that condition check because "End Entity" has been removed from certs list. This causes "Intermediate" to also be removed from certs list and added to retList.

This increments retList.Count to > 1 which returns retList early and causes downstream chain validation failure.

Here's a reduced example:

2018-07-11_04h28_26

Specifically maps to this chunk of code in PkixCertPath:

			// find end-entity cert
            IList retList = Platform.CreateArrayList(certs.Count);
            IList orig = Platform.CreateArrayList(certs);

			for (int i = 0; i < certs.Count; i++)
			{
				X509Certificate cert = (X509Certificate)certs[i];
				bool           found = false;

				X509Name subject = cert.SubjectDN;
				foreach (X509Certificate c in certs)
				{
					if (c.IssuerDN.Equivalent(subject, true))
					{
						found = true;
						break;
					}
				}

				if (!found)
				{
					retList.Add(cert);
					certs.RemoveAt(i);
				}
			}

			// can only have one end entity cert - something's wrong, give up.
			if (retList.Count > 1)
				return orig;

invidious9000 avatar Jul 11 '18 10:07 invidious9000

Something like this works (inefficiently) and may need some coercion to satisfy any platform constraints.

Assumptions:

  • self-signed cert must be present (isCa)
  • no duplicates in input certs list (enforceable with Hashset)
  • size of returned list must match size of provided list
IList SortCerts(IList certs)
        {
            var certList = (from object cert in certs select cert as Cert).ToList();
            if (certs.Count < 2) return certList;

            var rootCert = certList.SingleOrDefault(cert => cert.Issuer == cert.Name);
            if (rootCert == null) throw new CryptoException("No caCert in path");

            var chain = new LinkedList<Cert>();
            chain.AddFirst(rootCert);
            certList.Remove(rootCert);

            var changesMade = true;
            while (changesMade)
            {
                foreach (var cert in certList)
                {
                    foreach (var innerCert in chain)
                    {
                        if (cert.Issuer == innerCert.Name && !chain.Contains(cert))
                        {
                            chain.AddBefore(chain.Find(innerCert) ?? throw new Exception(), cert);
                            changesMade = true;
                            break;
                        }

                        if (cert.Name == innerCert.Issuer && !chain.Contains(cert))
                        {
                            chain.AddAfter(chain.Find(innerCert) ?? throw new Exception(), cert);
                            changesMade = true;
                            break;
                        }

                        changesMade = false;
                    }
                }
            }

            var chainOrdered = true;
            var leafIssuer = chain.First.Value.Issuer;
            foreach (var cert in chain.Skip(1))
            {
                if (leafIssuer == cert.Name)
                {
                    leafIssuer = cert.Issuer;
                }
                else
                {
                    chainOrdered = false;
                    break;
                }
            }

            return chainOrdered && chain.Count == certs.Count
                ? chain.ToList()
                : throw new CryptoException("Invalid path");
        }

It produces output that looks like this:

image

invidious9000 avatar Jul 12 '18 06:07 invidious9000

This got finally fixed in the recent 2.7.0 release (by creating a temp copy of the original list).

peterdettman avatar Sep 03 '26 15:09 peterdettman