I have a Windows certification authority that I am using to issue client authentication certificates via .net / c#. I have been able to successfully get it to issue certificates programmatically by calling the certification authority's API through COM. I issue a new certificate when I set up a client.

At runtime, these clients attach the certificates to requests to my server. How can I verify programmatically that an X509Certificate2 was signed by the root certificate of my certificate authority (and reject certificates signed by any other source)?

3 Answers
3

The part in the if (!isChainValid) block is to make a pretty error message. You don't have to use that if you don't want, but you should throw an error if the chain cannot be built. The chain elements are necessary to check for your root.

@HelloWorld Well if I was writing this today, I'd just use if (errors?.Length > 0) anyway. :) C# 6. Good to know; I didn't delve into the ToArray() implementation to see what happens if Select()'s IEnumerable returns no results.
– Chris BenardJan 25 '17 at 14:18

@ChrisBenard Is the code for checking that the certificate matches your known root really OK? That piece of code should match doing something like this and nearly always return true: chain.ChainElements.Cast<X509ChainElement>().All(x => x.Certificate.Thumbprint != "XX");
– OgglasNov 17 '17 at 22:00

@Ogglas “Any true” is not the same as “all false”. The code is right.
– Chris BenardNov 19 '17 at 0:20

1

@MattiasNordqvist If the certs are OK (not expired/revoked/etc) it will be true due to the usage of X509VerificationFlags.AllowUnknownCertificateAuthority. The later check by thumbprint is necessary to check for the authority you've placed in the chain with ExtraStore.Add().
– Chris BenardMar 21 '18 at 19:31

If you say you have a root (which is self-signed) certificate, then your only option is to keep this root certificate available on your server (without the private key of course) and perform certificate validation procedure against your root certificate. This is a mirrored situation to the web client validating server certificate chain.