PkixCertPathValidatorUtilities.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using System.Collections;
  5. using System.IO;
  6. using System.Text;
  7. using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
  8. using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.IsisMtt;
  9. using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
  10. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
  11. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
  12. using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
  13. using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
  14. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  15. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections;
  16. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Date;
  17. using BestHTTP.SecureProtocol.Org.BouncyCastle.X509;
  18. using BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Extension;
  19. using BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store;
  20. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkix
  21. {
  22. /// <summary>
  23. /// Summary description for PkixCertPathValidatorUtilities.
  24. /// </summary>
  25. public class PkixCertPathValidatorUtilities
  26. {
  27. private static readonly PkixCrlUtilities CrlUtilities = new PkixCrlUtilities();
  28. internal static readonly string ANY_POLICY = "2.5.29.32.0";
  29. internal static readonly string CRL_NUMBER = X509Extensions.CrlNumber.Id;
  30. /// <summary>
  31. /// key usage bits
  32. /// </summary>
  33. internal static readonly int KEY_CERT_SIGN = 5;
  34. internal static readonly int CRL_SIGN = 6;
  35. internal static readonly string[] crlReasons = new string[]
  36. {
  37. "unspecified",
  38. "keyCompromise",
  39. "cACompromise",
  40. "affiliationChanged",
  41. "superseded",
  42. "cessationOfOperation",
  43. "certificateHold",
  44. "unknown",
  45. "removeFromCRL",
  46. "privilegeWithdrawn",
  47. "aACompromise"
  48. };
  49. /// <summary>
  50. /// Search the given Set of TrustAnchor's for one that is the
  51. /// issuer of the given X509 certificate.
  52. /// </summary>
  53. /// <param name="cert">the X509 certificate</param>
  54. /// <param name="trustAnchors">a Set of TrustAnchor's</param>
  55. /// <returns>the <code>TrustAnchor</code> object if found or
  56. /// <code>null</code> if not.
  57. /// </returns>
  58. /// @exception
  59. internal static TrustAnchor FindTrustAnchor(
  60. X509Certificate cert,
  61. ISet trustAnchors)
  62. {
  63. IEnumerator iter = trustAnchors.GetEnumerator();
  64. TrustAnchor trust = null;
  65. AsymmetricKeyParameter trustPublicKey = null;
  66. Exception invalidKeyEx = null;
  67. X509CertStoreSelector certSelectX509 = new X509CertStoreSelector();
  68. try
  69. {
  70. certSelectX509.Subject = GetIssuerPrincipal(cert);
  71. }
  72. catch (IOException ex)
  73. {
  74. throw new Exception("Cannot set subject search criteria for trust anchor.", ex);
  75. }
  76. while (iter.MoveNext() && trust == null)
  77. {
  78. trust = (TrustAnchor) iter.Current;
  79. if (trust.TrustedCert != null)
  80. {
  81. if (certSelectX509.Match(trust.TrustedCert))
  82. {
  83. trustPublicKey = trust.TrustedCert.GetPublicKey();
  84. }
  85. else
  86. {
  87. trust = null;
  88. }
  89. }
  90. else if (trust.CAName != null && trust.CAPublicKey != null)
  91. {
  92. try
  93. {
  94. X509Name certIssuer = GetIssuerPrincipal(cert);
  95. X509Name caName = new X509Name(trust.CAName);
  96. if (certIssuer.Equivalent(caName, true))
  97. {
  98. trustPublicKey = trust.CAPublicKey;
  99. }
  100. else
  101. {
  102. trust = null;
  103. }
  104. }
  105. catch (InvalidParameterException)
  106. {
  107. trust = null;
  108. }
  109. }
  110. else
  111. {
  112. trust = null;
  113. }
  114. if (trustPublicKey != null)
  115. {
  116. try
  117. {
  118. cert.Verify(trustPublicKey);
  119. }
  120. catch (Exception ex)
  121. {
  122. invalidKeyEx = ex;
  123. trust = null;
  124. }
  125. }
  126. }
  127. if (trust == null && invalidKeyEx != null)
  128. {
  129. throw new Exception("TrustAnchor found but certificate validation failed.", invalidKeyEx);
  130. }
  131. return trust;
  132. }
  133. internal static bool IsIssuerTrustAnchor(
  134. X509Certificate cert,
  135. ISet trustAnchors)
  136. {
  137. try
  138. {
  139. return FindTrustAnchor(cert, trustAnchors) != null;
  140. }
  141. catch (Exception e)
  142. {
  143. return false;
  144. }
  145. }
  146. internal static void AddAdditionalStoresFromAltNames(
  147. X509Certificate cert,
  148. PkixParameters pkixParams)
  149. {
  150. // if in the IssuerAltName extension an URI
  151. // is given, add an additinal X.509 store
  152. if (cert.GetIssuerAlternativeNames() != null)
  153. {
  154. IEnumerator it = cert.GetIssuerAlternativeNames().GetEnumerator();
  155. while (it.MoveNext())
  156. {
  157. // look for URI
  158. IList list = (IList)it.Current;
  159. //if (list[0].Equals(new Integer(GeneralName.UniformResourceIdentifier)))
  160. if (list[0].Equals(GeneralName.UniformResourceIdentifier))
  161. {
  162. // found
  163. string temp = (string)list[1];
  164. PkixCertPathValidatorUtilities.AddAdditionalStoreFromLocation(temp, pkixParams);
  165. }
  166. }
  167. }
  168. }
  169. internal static DateTime GetValidDate(PkixParameters paramsPKIX)
  170. {
  171. DateTimeObject validDate = paramsPKIX.Date;
  172. if (validDate == null)
  173. return DateTime.UtcNow;
  174. return validDate.Value;
  175. }
  176. /// <summary>
  177. /// Returns the issuer of an attribute certificate or certificate.
  178. /// </summary>
  179. /// <param name="cert">The attribute certificate or certificate.</param>
  180. /// <returns>The issuer as <code>X500Principal</code>.</returns>
  181. internal static X509Name GetIssuerPrincipal(
  182. object cert)
  183. {
  184. if (cert is X509Certificate)
  185. {
  186. return ((X509Certificate)cert).IssuerDN;
  187. }
  188. else
  189. {
  190. return ((IX509AttributeCertificate)cert).Issuer.GetPrincipals()[0];
  191. }
  192. }
  193. internal static bool IsSelfIssued(
  194. X509Certificate cert)
  195. {
  196. return cert.SubjectDN.Equivalent(cert.IssuerDN, true);
  197. }
  198. internal static AlgorithmIdentifier GetAlgorithmIdentifier(
  199. AsymmetricKeyParameter key)
  200. {
  201. try
  202. {
  203. SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(key);
  204. return info.AlgorithmID;
  205. }
  206. catch (Exception e)
  207. {
  208. throw new PkixCertPathValidatorException("Subject public key cannot be decoded.", e);
  209. }
  210. }
  211. internal static bool IsAnyPolicy(
  212. ISet policySet)
  213. {
  214. return policySet == null || policySet.Contains(ANY_POLICY) || policySet.Count == 0;
  215. }
  216. internal static void AddAdditionalStoreFromLocation(
  217. string location,
  218. PkixParameters pkixParams)
  219. {
  220. if (pkixParams.IsAdditionalLocationsEnabled)
  221. {
  222. try
  223. {
  224. if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(location, "ldap://"))
  225. {
  226. // ldap://directory.d-trust.net/CN=D-TRUST
  227. // Qualified CA 2003 1:PN,O=D-Trust GmbH,C=DE
  228. // skip "ldap://"
  229. location = location.Substring(7);
  230. // after first / baseDN starts
  231. string url;//, baseDN;
  232. int slashPos = location.IndexOf('/');
  233. if (slashPos != -1)
  234. {
  235. url = "ldap://" + location.Substring(0, slashPos);
  236. // baseDN = location.Substring(slashPos);
  237. }
  238. else
  239. {
  240. url = "ldap://" + location;
  241. // baseDN = nsull;
  242. }
  243. throw BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateNotImplementedException("LDAP cert/CRL stores");
  244. // use all purpose parameters
  245. //X509LDAPCertStoreParameters ldapParams = new X509LDAPCertStoreParameters.Builder(
  246. // url, baseDN).build();
  247. //pkixParams.AddAdditionalStore(X509Store.getInstance(
  248. // "CERTIFICATE/LDAP", ldapParams));
  249. //pkixParams.AddAdditionalStore(X509Store.getInstance(
  250. // "CRL/LDAP", ldapParams));
  251. //pkixParams.AddAdditionalStore(X509Store.getInstance(
  252. // "ATTRIBUTECERTIFICATE/LDAP", ldapParams));
  253. //pkixParams.AddAdditionalStore(X509Store.getInstance(
  254. // "CERTIFICATEPAIR/LDAP", ldapParams));
  255. }
  256. }
  257. catch (Exception)
  258. {
  259. // cannot happen
  260. throw new Exception("Exception adding X.509 stores.");
  261. }
  262. }
  263. }
  264. private static BigInteger GetSerialNumber(
  265. object cert)
  266. {
  267. if (cert is X509Certificate)
  268. {
  269. return ((X509Certificate)cert).SerialNumber;
  270. }
  271. else
  272. {
  273. return ((X509V2AttributeCertificate)cert).SerialNumber;
  274. }
  275. }
  276. //
  277. // policy checking
  278. //
  279. internal static ISet GetQualifierSet(Asn1Sequence qualifiers)
  280. {
  281. ISet pq = new HashSet();
  282. if (qualifiers == null)
  283. {
  284. return pq;
  285. }
  286. foreach (Asn1Encodable ae in qualifiers)
  287. {
  288. try
  289. {
  290. // pq.Add(PolicyQualifierInfo.GetInstance(Asn1Object.FromByteArray(ae.GetEncoded())));
  291. pq.Add(PolicyQualifierInfo.GetInstance(ae.ToAsn1Object()));
  292. }
  293. catch (IOException ex)
  294. {
  295. throw new PkixCertPathValidatorException("Policy qualifier info cannot be decoded.", ex);
  296. }
  297. }
  298. return pq;
  299. }
  300. internal static PkixPolicyNode RemovePolicyNode(
  301. PkixPolicyNode validPolicyTree,
  302. IList[] policyNodes,
  303. PkixPolicyNode _node)
  304. {
  305. PkixPolicyNode _parent = (PkixPolicyNode)_node.Parent;
  306. if (validPolicyTree == null)
  307. {
  308. return null;
  309. }
  310. if (_parent == null)
  311. {
  312. for (int j = 0; j < policyNodes.Length; j++)
  313. {
  314. policyNodes[j] = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
  315. }
  316. return null;
  317. }
  318. else
  319. {
  320. _parent.RemoveChild(_node);
  321. RemovePolicyNodeRecurse(policyNodes, _node);
  322. return validPolicyTree;
  323. }
  324. }
  325. private static void RemovePolicyNodeRecurse(IList[] policyNodes, PkixPolicyNode _node)
  326. {
  327. policyNodes[_node.Depth].Remove(_node);
  328. if (_node.HasChildren)
  329. {
  330. foreach (PkixPolicyNode _child in _node.Children)
  331. {
  332. RemovePolicyNodeRecurse(policyNodes, _child);
  333. }
  334. }
  335. }
  336. internal static void PrepareNextCertB1(
  337. int i,
  338. IList[] policyNodes,
  339. string id_p,
  340. IDictionary m_idp,
  341. X509Certificate cert)
  342. {
  343. bool idp_found = false;
  344. IEnumerator nodes_i = policyNodes[i].GetEnumerator();
  345. while (nodes_i.MoveNext())
  346. {
  347. PkixPolicyNode node = (PkixPolicyNode)nodes_i.Current;
  348. if (node.ValidPolicy.Equals(id_p))
  349. {
  350. idp_found = true;
  351. node.ExpectedPolicies = (ISet)m_idp[id_p];
  352. break;
  353. }
  354. }
  355. if (!idp_found)
  356. {
  357. nodes_i = policyNodes[i].GetEnumerator();
  358. while (nodes_i.MoveNext())
  359. {
  360. PkixPolicyNode node = (PkixPolicyNode)nodes_i.Current;
  361. if (ANY_POLICY.Equals(node.ValidPolicy))
  362. {
  363. ISet pq = null;
  364. Asn1Sequence policies = null;
  365. try
  366. {
  367. policies = DerSequence.GetInstance(GetExtensionValue(cert, X509Extensions.CertificatePolicies));
  368. }
  369. catch (Exception e)
  370. {
  371. throw new Exception("Certificate policies cannot be decoded.", e);
  372. }
  373. IEnumerator enm = policies.GetEnumerator();
  374. while (enm.MoveNext())
  375. {
  376. PolicyInformation pinfo = null;
  377. try
  378. {
  379. pinfo = PolicyInformation.GetInstance(enm.Current);
  380. }
  381. catch (Exception ex)
  382. {
  383. throw new Exception("Policy information cannot be decoded.", ex);
  384. }
  385. if (ANY_POLICY.Equals(pinfo.PolicyIdentifier.Id))
  386. {
  387. try
  388. {
  389. pq = GetQualifierSet(pinfo.PolicyQualifiers);
  390. }
  391. catch (PkixCertPathValidatorException ex)
  392. {
  393. throw new PkixCertPathValidatorException(
  394. "Policy qualifier info set could not be built.", ex);
  395. }
  396. break;
  397. }
  398. }
  399. bool ci = false;
  400. ISet critExtOids = cert.GetCriticalExtensionOids();
  401. if (critExtOids != null)
  402. {
  403. ci = critExtOids.Contains(X509Extensions.CertificatePolicies.Id);
  404. }
  405. PkixPolicyNode p_node = (PkixPolicyNode)node.Parent;
  406. if (ANY_POLICY.Equals(p_node.ValidPolicy))
  407. {
  408. PkixPolicyNode c_node = new PkixPolicyNode(
  409. BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(), i,
  410. (ISet)m_idp[id_p],
  411. p_node, pq, id_p, ci);
  412. p_node.AddChild(c_node);
  413. policyNodes[i].Add(c_node);
  414. }
  415. break;
  416. }
  417. }
  418. }
  419. }
  420. internal static PkixPolicyNode PrepareNextCertB2(
  421. int i,
  422. IList[] policyNodes,
  423. string id_p,
  424. PkixPolicyNode validPolicyTree)
  425. {
  426. int pos = 0;
  427. // Copy to avoid RemoveAt calls interfering with enumeration
  428. foreach (PkixPolicyNode node in BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(policyNodes[i]))
  429. {
  430. if (node.ValidPolicy.Equals(id_p))
  431. {
  432. PkixPolicyNode p_node = (PkixPolicyNode)node.Parent;
  433. p_node.RemoveChild(node);
  434. // Removal of element at current iterator position not supported in C#
  435. //nodes_i.remove();
  436. policyNodes[i].RemoveAt(pos);
  437. for (int k = (i - 1); k >= 0; k--)
  438. {
  439. IList nodes = policyNodes[k];
  440. for (int l = 0; l < nodes.Count; l++)
  441. {
  442. PkixPolicyNode node2 = (PkixPolicyNode)nodes[l];
  443. if (!node2.HasChildren)
  444. {
  445. validPolicyTree = RemovePolicyNode(validPolicyTree, policyNodes, node2);
  446. if (validPolicyTree == null)
  447. break;
  448. }
  449. }
  450. }
  451. }
  452. else
  453. {
  454. ++pos;
  455. }
  456. }
  457. return validPolicyTree;
  458. }
  459. internal static void GetCertStatus(
  460. DateTime validDate,
  461. X509Crl crl,
  462. Object cert,
  463. CertStatus certStatus)
  464. {
  465. X509Crl bcCRL = null;
  466. try
  467. {
  468. bcCRL = new X509Crl(CertificateList.GetInstance((Asn1Sequence)Asn1Sequence.FromByteArray(crl.GetEncoded())));
  469. }
  470. catch (Exception exception)
  471. {
  472. throw new Exception("Bouncy Castle X509Crl could not be created.", exception);
  473. }
  474. X509CrlEntry crl_entry = (X509CrlEntry)bcCRL.GetRevokedCertificate(GetSerialNumber(cert));
  475. if (crl_entry == null)
  476. return;
  477. X509Name issuer = GetIssuerPrincipal(cert);
  478. if (issuer.Equivalent(crl_entry.GetCertificateIssuer(), true)
  479. || issuer.Equivalent(crl.IssuerDN, true))
  480. {
  481. DerEnumerated reasonCode = null;
  482. if (crl_entry.HasExtensions)
  483. {
  484. try
  485. {
  486. reasonCode = DerEnumerated.GetInstance(
  487. GetExtensionValue(crl_entry, X509Extensions.ReasonCode));
  488. }
  489. catch (Exception e)
  490. {
  491. throw new Exception(
  492. "Reason code CRL entry extension could not be decoded.",
  493. e);
  494. }
  495. }
  496. // for reason keyCompromise, caCompromise, aACompromise or
  497. // unspecified
  498. if (!(validDate.Ticks < crl_entry.RevocationDate.Ticks)
  499. || reasonCode == null
  500. || reasonCode.Value.TestBit(0)
  501. || reasonCode.Value.TestBit(1)
  502. || reasonCode.Value.TestBit(2)
  503. || reasonCode.Value.TestBit(8))
  504. {
  505. if (reasonCode != null) // (i) or (j) (1)
  506. {
  507. certStatus.Status = reasonCode.Value.SignValue;
  508. }
  509. else // (i) or (j) (2)
  510. {
  511. certStatus.Status = CrlReason.Unspecified;
  512. }
  513. certStatus.RevocationDate = new DateTimeObject(crl_entry.RevocationDate);
  514. }
  515. }
  516. }
  517. /**
  518. * Return the next working key inheriting DSA parameters if necessary.
  519. * <p>
  520. * This methods inherits DSA parameters from the indexed certificate or
  521. * previous certificates in the certificate chain to the returned
  522. * <code>PublicKey</code>. The list is searched upwards, meaning the end
  523. * certificate is at position 0 and previous certificates are following.
  524. * </p>
  525. * <p>
  526. * If the indexed certificate does not contain a DSA key this method simply
  527. * returns the public key. If the DSA key already contains DSA parameters
  528. * the key is also only returned.
  529. * </p>
  530. *
  531. * @param certs The certification path.
  532. * @param index The index of the certificate which contains the public key
  533. * which should be extended with DSA parameters.
  534. * @return The public key of the certificate in list position
  535. * <code>index</code> extended with DSA parameters if applicable.
  536. * @throws Exception if DSA parameters cannot be inherited.
  537. */
  538. internal static AsymmetricKeyParameter GetNextWorkingKey(
  539. IList certs,
  540. int index)
  541. {
  542. //Only X509Certificate
  543. X509Certificate cert = (X509Certificate)certs[index];
  544. AsymmetricKeyParameter pubKey = cert.GetPublicKey();
  545. if (!(pubKey is DsaPublicKeyParameters))
  546. return pubKey;
  547. DsaPublicKeyParameters dsaPubKey = (DsaPublicKeyParameters)pubKey;
  548. if (dsaPubKey.Parameters != null)
  549. return dsaPubKey;
  550. for (int i = index + 1; i < certs.Count; i++)
  551. {
  552. X509Certificate parentCert = (X509Certificate)certs[i];
  553. pubKey = parentCert.GetPublicKey();
  554. if (!(pubKey is DsaPublicKeyParameters))
  555. {
  556. throw new PkixCertPathValidatorException(
  557. "DSA parameters cannot be inherited from previous certificate.");
  558. }
  559. DsaPublicKeyParameters prevDSAPubKey = (DsaPublicKeyParameters)pubKey;
  560. if (prevDSAPubKey.Parameters == null)
  561. continue;
  562. DsaParameters dsaParams = prevDSAPubKey.Parameters;
  563. try
  564. {
  565. return new DsaPublicKeyParameters(dsaPubKey.Y, dsaParams);
  566. }
  567. catch (Exception exception)
  568. {
  569. throw new Exception(exception.Message);
  570. }
  571. }
  572. throw new PkixCertPathValidatorException("DSA parameters cannot be inherited from previous certificate.");
  573. }
  574. internal static DateTime GetValidCertDateFromValidityModel(
  575. PkixParameters paramsPkix,
  576. PkixCertPath certPath,
  577. int index)
  578. {
  579. if (paramsPkix.ValidityModel != PkixParameters.ChainValidityModel)
  580. {
  581. return GetValidDate(paramsPkix);
  582. }
  583. // if end cert use given signing/encryption/... time
  584. if (index <= 0)
  585. {
  586. return PkixCertPathValidatorUtilities.GetValidDate(paramsPkix);
  587. // else use time when previous cert was created
  588. }
  589. if (index - 1 == 0)
  590. {
  591. DerGeneralizedTime dateOfCertgen = null;
  592. try
  593. {
  594. X509Certificate cert = (X509Certificate)certPath.Certificates[index - 1];
  595. Asn1OctetString extVal = cert.GetExtensionValue(
  596. IsisMttObjectIdentifiers.IdIsisMttATDateOfCertGen);
  597. dateOfCertgen = DerGeneralizedTime.GetInstance(extVal);
  598. }
  599. catch (ArgumentException)
  600. {
  601. throw new Exception(
  602. "Date of cert gen extension could not be read.");
  603. }
  604. if (dateOfCertgen != null)
  605. {
  606. try
  607. {
  608. return dateOfCertgen.ToDateTime();
  609. }
  610. catch (ArgumentException e)
  611. {
  612. throw new Exception(
  613. "Date from date of cert gen extension could not be parsed.",
  614. e);
  615. }
  616. }
  617. }
  618. return ((X509Certificate)certPath.Certificates[index - 1]).NotBefore;
  619. }
  620. /// <summary>
  621. /// Return a Collection of all certificates or attribute certificates found
  622. /// in the X509Store's that are matching the certSelect criteriums.
  623. /// </summary>
  624. /// <param name="certSelect">a {@link Selector} object that will be used to select
  625. /// the certificates</param>
  626. /// <param name="certStores">a List containing only X509Store objects. These
  627. /// are used to search for certificates.</param>
  628. /// <returns>a Collection of all found <see cref="X509Certificate"/> or
  629. /// <see cref="BestHTTP.SecureProtocol.Org.BouncyCastle.X509.IX509AttributeCertificate"/> objects.
  630. /// May be empty but never <code>null</code>.</returns>
  631. /// <exception cref="Exception"></exception>
  632. internal static ICollection FindCertificates(
  633. X509CertStoreSelector certSelect,
  634. IList certStores)
  635. {
  636. ISet certs = new HashSet();
  637. foreach (IX509Store certStore in certStores)
  638. {
  639. try
  640. {
  641. // certs.AddAll(certStore.GetMatches(certSelect));
  642. foreach (X509Certificate c in certStore.GetMatches(certSelect))
  643. {
  644. certs.Add(c);
  645. }
  646. }
  647. catch (Exception e)
  648. {
  649. throw new Exception("Problem while picking certificates from X.509 store.", e);
  650. }
  651. }
  652. return certs;
  653. }
  654. /**
  655. * Add the CRL issuers from the cRLIssuer field of the distribution point or
  656. * from the certificate if not given to the issuer criterion of the
  657. * <code>selector</code>.
  658. * <p>
  659. * The <code>issuerPrincipals</code> are a collection with a single
  660. * <code>X500Principal</code> for <code>X509Certificate</code>s. For
  661. * {@link X509AttributeCertificate}s the issuer may contain more than one
  662. * <code>X500Principal</code>.
  663. * </p>
  664. *
  665. * @param dp The distribution point.
  666. * @param issuerPrincipals The issuers of the certificate or attribute
  667. * certificate which contains the distribution point.
  668. * @param selector The CRL selector.
  669. * @param pkixParams The PKIX parameters containing the cert stores.
  670. * @throws Exception if an exception occurs while processing.
  671. * @throws ClassCastException if <code>issuerPrincipals</code> does not
  672. * contain only <code>X500Principal</code>s.
  673. */
  674. internal static void GetCrlIssuersFromDistributionPoint(
  675. DistributionPoint dp,
  676. ICollection issuerPrincipals,
  677. X509CrlStoreSelector selector,
  678. PkixParameters pkixParams)
  679. {
  680. IList issuers = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
  681. // indirect CRL
  682. if (dp.CrlIssuer != null)
  683. {
  684. GeneralName[] genNames = dp.CrlIssuer.GetNames();
  685. // look for a DN
  686. for (int j = 0; j < genNames.Length; j++)
  687. {
  688. if (genNames[j].TagNo == GeneralName.DirectoryName)
  689. {
  690. try
  691. {
  692. issuers.Add(X509Name.GetInstance(genNames[j].Name.ToAsn1Object()));
  693. }
  694. catch (IOException e)
  695. {
  696. throw new Exception(
  697. "CRL issuer information from distribution point cannot be decoded.",
  698. e);
  699. }
  700. }
  701. }
  702. }
  703. else
  704. {
  705. /*
  706. * certificate issuer is CRL issuer, distributionPoint field MUST be
  707. * present.
  708. */
  709. if (dp.DistributionPointName == null)
  710. {
  711. throw new Exception(
  712. "CRL issuer is omitted from distribution point but no distributionPoint field present.");
  713. }
  714. // add and check issuer principals
  715. for (IEnumerator it = issuerPrincipals.GetEnumerator(); it.MoveNext(); )
  716. {
  717. issuers.Add((X509Name)it.Current);
  718. }
  719. }
  720. // TODO: is not found although this should correctly add the rel name. selector of Sun is buggy here or PKI test case is invalid
  721. // distributionPoint
  722. // if (dp.getDistributionPoint() != null)
  723. // {
  724. // // look for nameRelativeToCRLIssuer
  725. // if (dp.getDistributionPoint().getType() == DistributionPointName.NAME_RELATIVE_TO_CRL_ISSUER)
  726. // {
  727. // // append fragment to issuer, only one
  728. // // issuer can be there, if this is given
  729. // if (issuers.size() != 1)
  730. // {
  731. // throw new AnnotatedException(
  732. // "nameRelativeToCRLIssuer field is given but more than one CRL issuer is given.");
  733. // }
  734. // DEREncodable relName = dp.getDistributionPoint().getName();
  735. // Iterator it = issuers.iterator();
  736. // List issuersTemp = new ArrayList(issuers.size());
  737. // while (it.hasNext())
  738. // {
  739. // Enumeration e = null;
  740. // try
  741. // {
  742. // e = ASN1Sequence.getInstance(
  743. // new ASN1InputStream(((X500Principal) it.next())
  744. // .getEncoded()).readObject()).getObjects();
  745. // }
  746. // catch (IOException ex)
  747. // {
  748. // throw new AnnotatedException(
  749. // "Cannot decode CRL issuer information.", ex);
  750. // }
  751. // ASN1EncodableVector v = new ASN1EncodableVector();
  752. // while (e.hasMoreElements())
  753. // {
  754. // v.add((DEREncodable) e.nextElement());
  755. // }
  756. // v.add(relName);
  757. // issuersTemp.add(new X500Principal(new DERSequence(v)
  758. // .getDEREncoded()));
  759. // }
  760. // issuers.clear();
  761. // issuers.addAll(issuersTemp);
  762. // }
  763. // }
  764. selector.Issuers = issuers;
  765. }
  766. /**
  767. * Fetches complete CRLs according to RFC 3280.
  768. *
  769. * @param dp The distribution point for which the complete CRL
  770. * @param cert The <code>X509Certificate</code> or
  771. * {@link org.bouncycastle.x509.X509AttributeCertificate} for
  772. * which the CRL should be searched.
  773. * @param currentDate The date for which the delta CRLs must be valid.
  774. * @param paramsPKIX The extended PKIX parameters.
  775. * @return A <code>Set</code> of <code>X509CRL</code>s with complete
  776. * CRLs.
  777. * @throws Exception if an exception occurs while picking the CRLs
  778. * or no CRLs are found.
  779. */
  780. internal static ISet GetCompleteCrls(
  781. DistributionPoint dp,
  782. object cert,
  783. DateTime currentDate,
  784. PkixParameters paramsPKIX)
  785. {
  786. X509CrlStoreSelector crlselect = new X509CrlStoreSelector();
  787. try
  788. {
  789. ISet issuers = new HashSet();
  790. if (cert is X509V2AttributeCertificate)
  791. {
  792. issuers.Add(((X509V2AttributeCertificate)cert)
  793. .Issuer.GetPrincipals()[0]);
  794. }
  795. else
  796. {
  797. issuers.Add(GetIssuerPrincipal(cert));
  798. }
  799. PkixCertPathValidatorUtilities.GetCrlIssuersFromDistributionPoint(dp, issuers, crlselect, paramsPKIX);
  800. }
  801. catch (Exception e)
  802. {
  803. throw new Exception("Could not get issuer information from distribution point.", e);
  804. }
  805. if (cert is X509Certificate)
  806. {
  807. crlselect.CertificateChecking = (X509Certificate)cert;
  808. }
  809. else if (cert is X509V2AttributeCertificate)
  810. {
  811. crlselect.AttrCertChecking = (IX509AttributeCertificate)cert;
  812. }
  813. crlselect.CompleteCrlEnabled = true;
  814. ISet crls = CrlUtilities.FindCrls(crlselect, paramsPKIX, currentDate);
  815. if (crls.IsEmpty)
  816. {
  817. if (cert is IX509AttributeCertificate)
  818. {
  819. IX509AttributeCertificate aCert = (IX509AttributeCertificate)cert;
  820. throw new Exception("No CRLs found for issuer \"" + aCert.Issuer.GetPrincipals()[0] + "\"");
  821. }
  822. else
  823. {
  824. X509Certificate xCert = (X509Certificate)cert;
  825. throw new Exception("No CRLs found for issuer \"" + xCert.IssuerDN + "\"");
  826. }
  827. }
  828. return crls;
  829. }
  830. /**
  831. * Fetches delta CRLs according to RFC 3280 section 5.2.4.
  832. *
  833. * @param currentDate The date for which the delta CRLs must be valid.
  834. * @param paramsPKIX The extended PKIX parameters.
  835. * @param completeCRL The complete CRL the delta CRL is for.
  836. * @return A <code>Set</code> of <code>X509CRL</code>s with delta CRLs.
  837. * @throws Exception if an exception occurs while picking the delta
  838. * CRLs.
  839. */
  840. internal static ISet GetDeltaCrls(
  841. DateTime currentDate,
  842. PkixParameters paramsPKIX,
  843. X509Crl completeCRL)
  844. {
  845. X509CrlStoreSelector deltaSelect = new X509CrlStoreSelector();
  846. // 5.2.4 (a)
  847. try
  848. {
  849. IList deltaSelectIssuer = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
  850. deltaSelectIssuer.Add(completeCRL.IssuerDN);
  851. deltaSelect.Issuers = deltaSelectIssuer;
  852. }
  853. catch (IOException e)
  854. {
  855. throw new Exception("Cannot extract issuer from CRL.", e);
  856. }
  857. BigInteger completeCRLNumber = null;
  858. try
  859. {
  860. Asn1Object asn1Object = GetExtensionValue(completeCRL, X509Extensions.CrlNumber);
  861. if (asn1Object != null)
  862. {
  863. completeCRLNumber = CrlNumber.GetInstance(asn1Object).PositiveValue;
  864. }
  865. }
  866. catch (Exception e)
  867. {
  868. throw new Exception(
  869. "CRL number extension could not be extracted from CRL.", e);
  870. }
  871. // 5.2.4 (b)
  872. byte[] idp = null;
  873. try
  874. {
  875. Asn1Object obj = GetExtensionValue(completeCRL, X509Extensions.IssuingDistributionPoint);
  876. if (obj != null)
  877. {
  878. idp = obj.GetDerEncoded();
  879. }
  880. }
  881. catch (Exception e)
  882. {
  883. throw new Exception(
  884. "Issuing distribution point extension value could not be read.",
  885. e);
  886. }
  887. // 5.2.4 (d)
  888. deltaSelect.MinCrlNumber = (completeCRLNumber == null)
  889. ? null
  890. : completeCRLNumber.Add(BigInteger.One);
  891. deltaSelect.IssuingDistributionPoint = idp;
  892. deltaSelect.IssuingDistributionPointEnabled = true;
  893. // 5.2.4 (c)
  894. deltaSelect.MaxBaseCrlNumber = completeCRLNumber;
  895. // find delta CRLs
  896. ISet temp = CrlUtilities.FindCrls(deltaSelect, paramsPKIX, currentDate);
  897. ISet result = new HashSet();
  898. foreach (X509Crl crl in temp)
  899. {
  900. if (isDeltaCrl(crl))
  901. {
  902. result.Add(crl);
  903. }
  904. }
  905. return result;
  906. }
  907. private static bool isDeltaCrl(
  908. X509Crl crl)
  909. {
  910. ISet critical = crl.GetCriticalExtensionOids();
  911. return critical.Contains(X509Extensions.DeltaCrlIndicator.Id);
  912. }
  913. internal static ICollection FindCertificates(
  914. X509AttrCertStoreSelector certSelect,
  915. IList certStores)
  916. {
  917. ISet certs = new HashSet();
  918. foreach (IX509Store certStore in certStores)
  919. {
  920. try
  921. {
  922. // certs.AddAll(certStore.GetMatches(certSelect));
  923. foreach (X509V2AttributeCertificate ac in certStore.GetMatches(certSelect))
  924. {
  925. certs.Add(ac);
  926. }
  927. }
  928. catch (Exception e)
  929. {
  930. throw new Exception(
  931. "Problem while picking certificates from X.509 store.", e);
  932. }
  933. }
  934. return certs;
  935. }
  936. internal static void AddAdditionalStoresFromCrlDistributionPoint(
  937. CrlDistPoint crldp,
  938. PkixParameters pkixParams)
  939. {
  940. if (crldp != null)
  941. {
  942. DistributionPoint[] dps = null;
  943. try
  944. {
  945. dps = crldp.GetDistributionPoints();
  946. }
  947. catch (Exception e)
  948. {
  949. throw new Exception(
  950. "Distribution points could not be read.", e);
  951. }
  952. for (int i = 0; i < dps.Length; i++)
  953. {
  954. DistributionPointName dpn = dps[i].DistributionPointName;
  955. // look for URIs in fullName
  956. if (dpn != null)
  957. {
  958. if (dpn.PointType == DistributionPointName.FullName)
  959. {
  960. GeneralName[] genNames = GeneralNames.GetInstance(
  961. dpn.Name).GetNames();
  962. // look for an URI
  963. for (int j = 0; j < genNames.Length; j++)
  964. {
  965. if (genNames[j].TagNo == GeneralName.UniformResourceIdentifier)
  966. {
  967. string location = DerIA5String.GetInstance(
  968. genNames[j].Name).GetString();
  969. PkixCertPathValidatorUtilities.AddAdditionalStoreFromLocation(
  970. location, pkixParams);
  971. }
  972. }
  973. }
  974. }
  975. }
  976. }
  977. }
  978. internal static bool ProcessCertD1i(
  979. int index,
  980. IList[] policyNodes,
  981. DerObjectIdentifier pOid,
  982. ISet pq)
  983. {
  984. IList policyNodeVec = policyNodes[index - 1];
  985. for (int j = 0; j < policyNodeVec.Count; j++)
  986. {
  987. PkixPolicyNode node = (PkixPolicyNode)policyNodeVec[j];
  988. ISet expectedPolicies = node.ExpectedPolicies;
  989. if (expectedPolicies.Contains(pOid.Id))
  990. {
  991. ISet childExpectedPolicies = new HashSet();
  992. childExpectedPolicies.Add(pOid.Id);
  993. PkixPolicyNode child = new PkixPolicyNode(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(),
  994. index,
  995. childExpectedPolicies,
  996. node,
  997. pq,
  998. pOid.Id,
  999. false);
  1000. node.AddChild(child);
  1001. policyNodes[index].Add(child);
  1002. return true;
  1003. }
  1004. }
  1005. return false;
  1006. }
  1007. internal static void ProcessCertD1ii(
  1008. int index,
  1009. IList[] policyNodes,
  1010. DerObjectIdentifier _poid,
  1011. ISet _pq)
  1012. {
  1013. IList policyNodeVec = policyNodes[index - 1];
  1014. for (int j = 0; j < policyNodeVec.Count; j++)
  1015. {
  1016. PkixPolicyNode _node = (PkixPolicyNode)policyNodeVec[j];
  1017. if (ANY_POLICY.Equals(_node.ValidPolicy))
  1018. {
  1019. ISet _childExpectedPolicies = new HashSet();
  1020. _childExpectedPolicies.Add(_poid.Id);
  1021. PkixPolicyNode _child = new PkixPolicyNode(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(),
  1022. index,
  1023. _childExpectedPolicies,
  1024. _node,
  1025. _pq,
  1026. _poid.Id,
  1027. false);
  1028. _node.AddChild(_child);
  1029. policyNodes[index].Add(_child);
  1030. return;
  1031. }
  1032. }
  1033. }
  1034. /**
  1035. * Find the issuer certificates of a given certificate.
  1036. *
  1037. * @param cert
  1038. * The certificate for which an issuer should be found.
  1039. * @param pkixParams
  1040. * @return A <code>Collection</code> object containing the issuer
  1041. * <code>X509Certificate</code>s. Never <code>null</code>.
  1042. *
  1043. * @exception Exception
  1044. * if an error occurs.
  1045. */
  1046. internal static ICollection FindIssuerCerts(
  1047. X509Certificate cert,
  1048. PkixBuilderParameters pkixParams)
  1049. {
  1050. X509CertStoreSelector certSelect = new X509CertStoreSelector();
  1051. ISet certs = new HashSet();
  1052. try
  1053. {
  1054. certSelect.Subject = cert.IssuerDN;
  1055. }
  1056. catch (IOException ex)
  1057. {
  1058. throw new Exception(
  1059. "Subject criteria for certificate selector to find issuer certificate could not be set.", ex);
  1060. }
  1061. try
  1062. {
  1063. certs.AddAll(PkixCertPathValidatorUtilities.FindCertificates(certSelect, pkixParams.GetStores()));
  1064. certs.AddAll(PkixCertPathValidatorUtilities.FindCertificates(certSelect, pkixParams.GetAdditionalStores()));
  1065. }
  1066. catch (Exception e)
  1067. {
  1068. throw new Exception("Issuer certificate cannot be searched.", e);
  1069. }
  1070. return certs;
  1071. }
  1072. /// <summary>
  1073. /// Extract the value of the given extension, if it exists.
  1074. /// </summary>
  1075. /// <param name="ext">The extension object.</param>
  1076. /// <param name="oid">The object identifier to obtain.</param>
  1077. /// <returns>Asn1Object</returns>
  1078. /// <exception cref="Exception">if the extension cannot be read.</exception>
  1079. internal static Asn1Object GetExtensionValue(
  1080. IX509Extension ext,
  1081. DerObjectIdentifier oid)
  1082. {
  1083. Asn1OctetString bytes = ext.GetExtensionValue(oid);
  1084. if (bytes == null)
  1085. return null;
  1086. return X509ExtensionUtilities.FromExtensionValue(bytes);
  1087. }
  1088. }
  1089. }
  1090. #pragma warning restore
  1091. #endif