PkixCertPathValidatorUtilities.cs 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216
  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)
  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. return;
  482. }
  483. int reasonCodeValue = CrlReason.Unspecified;
  484. if (crl_entry.HasExtensions)
  485. {
  486. try
  487. {
  488. Asn1Object extValue = GetExtensionValue(crl_entry, X509Extensions.ReasonCode);
  489. DerEnumerated reasonCode = DerEnumerated.GetInstance(extValue);
  490. if (null != reasonCode)
  491. {
  492. reasonCodeValue = reasonCode.IntValueExact;
  493. }
  494. }
  495. catch (Exception e)
  496. {
  497. throw new Exception("Reason code CRL entry extension could not be decoded.", e);
  498. }
  499. }
  500. DateTime revocationDate = crl_entry.RevocationDate;
  501. if (validDate.Ticks < revocationDate.Ticks)
  502. {
  503. switch (reasonCodeValue)
  504. {
  505. case CrlReason.Unspecified:
  506. case CrlReason.KeyCompromise:
  507. case CrlReason.CACompromise:
  508. case CrlReason.AACompromise:
  509. break;
  510. default:
  511. return;
  512. }
  513. }
  514. // (i) or (j)
  515. certStatus.Status = reasonCodeValue;
  516. certStatus.RevocationDate = new DateTimeObject(revocationDate);
  517. }
  518. /**
  519. * Return the next working key inheriting DSA parameters if necessary.
  520. * <p>
  521. * This methods inherits DSA parameters from the indexed certificate or
  522. * previous certificates in the certificate chain to the returned
  523. * <code>PublicKey</code>. The list is searched upwards, meaning the end
  524. * certificate is at position 0 and previous certificates are following.
  525. * </p>
  526. * <p>
  527. * If the indexed certificate does not contain a DSA key this method simply
  528. * returns the public key. If the DSA key already contains DSA parameters
  529. * the key is also only returned.
  530. * </p>
  531. *
  532. * @param certs The certification path.
  533. * @param index The index of the certificate which contains the public key
  534. * which should be extended with DSA parameters.
  535. * @return The public key of the certificate in list position
  536. * <code>index</code> extended with DSA parameters if applicable.
  537. * @throws Exception if DSA parameters cannot be inherited.
  538. */
  539. internal static AsymmetricKeyParameter GetNextWorkingKey(
  540. IList certs,
  541. int index)
  542. {
  543. //Only X509Certificate
  544. X509Certificate cert = (X509Certificate)certs[index];
  545. AsymmetricKeyParameter pubKey = cert.GetPublicKey();
  546. if (!(pubKey is DsaPublicKeyParameters))
  547. return pubKey;
  548. DsaPublicKeyParameters dsaPubKey = (DsaPublicKeyParameters)pubKey;
  549. if (dsaPubKey.Parameters != null)
  550. return dsaPubKey;
  551. for (int i = index + 1; i < certs.Count; i++)
  552. {
  553. X509Certificate parentCert = (X509Certificate)certs[i];
  554. pubKey = parentCert.GetPublicKey();
  555. if (!(pubKey is DsaPublicKeyParameters))
  556. {
  557. throw new PkixCertPathValidatorException(
  558. "DSA parameters cannot be inherited from previous certificate.");
  559. }
  560. DsaPublicKeyParameters prevDSAPubKey = (DsaPublicKeyParameters)pubKey;
  561. if (prevDSAPubKey.Parameters == null)
  562. continue;
  563. DsaParameters dsaParams = prevDSAPubKey.Parameters;
  564. try
  565. {
  566. return new DsaPublicKeyParameters(dsaPubKey.Y, dsaParams);
  567. }
  568. catch (Exception exception)
  569. {
  570. throw new Exception(exception.Message);
  571. }
  572. }
  573. throw new PkixCertPathValidatorException("DSA parameters cannot be inherited from previous certificate.");
  574. }
  575. internal static DateTime GetValidCertDateFromValidityModel(
  576. PkixParameters paramsPkix,
  577. PkixCertPath certPath,
  578. int index)
  579. {
  580. if (paramsPkix.ValidityModel != PkixParameters.ChainValidityModel)
  581. {
  582. return GetValidDate(paramsPkix);
  583. }
  584. // if end cert use given signing/encryption/... time
  585. if (index <= 0)
  586. {
  587. return PkixCertPathValidatorUtilities.GetValidDate(paramsPkix);
  588. // else use time when previous cert was created
  589. }
  590. if (index - 1 == 0)
  591. {
  592. DerGeneralizedTime dateOfCertgen = null;
  593. try
  594. {
  595. X509Certificate cert = (X509Certificate)certPath.Certificates[index - 1];
  596. Asn1OctetString extVal = cert.GetExtensionValue(
  597. IsisMttObjectIdentifiers.IdIsisMttATDateOfCertGen);
  598. dateOfCertgen = DerGeneralizedTime.GetInstance(extVal);
  599. }
  600. catch (ArgumentException)
  601. {
  602. throw new Exception(
  603. "Date of cert gen extension could not be read.");
  604. }
  605. if (dateOfCertgen != null)
  606. {
  607. try
  608. {
  609. return dateOfCertgen.ToDateTime();
  610. }
  611. catch (ArgumentException e)
  612. {
  613. throw new Exception(
  614. "Date from date of cert gen extension could not be parsed.",
  615. e);
  616. }
  617. }
  618. }
  619. return ((X509Certificate)certPath.Certificates[index - 1]).NotBefore;
  620. }
  621. /// <summary>
  622. /// Return a Collection of all certificates or attribute certificates found
  623. /// in the X509Store's that are matching the certSelect criteriums.
  624. /// </summary>
  625. /// <param name="certSelect">a {@link Selector} object that will be used to select
  626. /// the certificates</param>
  627. /// <param name="certStores">a List containing only X509Store objects. These
  628. /// are used to search for certificates.</param>
  629. /// <returns>a Collection of all found <see cref="X509Certificate"/> or
  630. /// <see cref="BestHTTP.SecureProtocol.Org.BouncyCastle.X509.IX509AttributeCertificate"/> objects.
  631. /// May be empty but never <code>null</code>.</returns>
  632. /// <exception cref="Exception"></exception>
  633. internal static ICollection FindCertificates(
  634. X509CertStoreSelector certSelect,
  635. IList certStores)
  636. {
  637. ISet certs = new HashSet();
  638. foreach (IX509Store certStore in certStores)
  639. {
  640. try
  641. {
  642. // certs.AddAll(certStore.GetMatches(certSelect));
  643. foreach (X509Certificate c in certStore.GetMatches(certSelect))
  644. {
  645. certs.Add(c);
  646. }
  647. }
  648. catch (Exception e)
  649. {
  650. throw new Exception("Problem while picking certificates from X.509 store.", e);
  651. }
  652. }
  653. return certs;
  654. }
  655. /**
  656. * Add the CRL issuers from the cRLIssuer field of the distribution point or
  657. * from the certificate if not given to the issuer criterion of the
  658. * <code>selector</code>.
  659. * <p>
  660. * The <code>issuerPrincipals</code> are a collection with a single
  661. * <code>X500Principal</code> for <code>X509Certificate</code>s. For
  662. * {@link X509AttributeCertificate}s the issuer may contain more than one
  663. * <code>X500Principal</code>.
  664. * </p>
  665. *
  666. * @param dp The distribution point.
  667. * @param issuerPrincipals The issuers of the certificate or attribute
  668. * certificate which contains the distribution point.
  669. * @param selector The CRL selector.
  670. * @param pkixParams The PKIX parameters containing the cert stores.
  671. * @throws Exception if an exception occurs while processing.
  672. * @throws ClassCastException if <code>issuerPrincipals</code> does not
  673. * contain only <code>X500Principal</code>s.
  674. */
  675. internal static void GetCrlIssuersFromDistributionPoint(
  676. DistributionPoint dp,
  677. ICollection issuerPrincipals,
  678. X509CrlStoreSelector selector,
  679. PkixParameters pkixParams)
  680. {
  681. IList issuers = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
  682. // indirect CRL
  683. if (dp.CrlIssuer != null)
  684. {
  685. GeneralName[] genNames = dp.CrlIssuer.GetNames();
  686. // look for a DN
  687. for (int j = 0; j < genNames.Length; j++)
  688. {
  689. if (genNames[j].TagNo == GeneralName.DirectoryName)
  690. {
  691. try
  692. {
  693. issuers.Add(X509Name.GetInstance(genNames[j].Name.ToAsn1Object()));
  694. }
  695. catch (IOException e)
  696. {
  697. throw new Exception(
  698. "CRL issuer information from distribution point cannot be decoded.",
  699. e);
  700. }
  701. }
  702. }
  703. }
  704. else
  705. {
  706. /*
  707. * certificate issuer is CRL issuer, distributionPoint field MUST be
  708. * present.
  709. */
  710. if (dp.DistributionPointName == null)
  711. {
  712. throw new Exception(
  713. "CRL issuer is omitted from distribution point but no distributionPoint field present.");
  714. }
  715. // add and check issuer principals
  716. for (IEnumerator it = issuerPrincipals.GetEnumerator(); it.MoveNext(); )
  717. {
  718. issuers.Add((X509Name)it.Current);
  719. }
  720. }
  721. // TODO: is not found although this should correctly add the rel name. selector of Sun is buggy here or PKI test case is invalid
  722. // distributionPoint
  723. // if (dp.getDistributionPoint() != null)
  724. // {
  725. // // look for nameRelativeToCRLIssuer
  726. // if (dp.getDistributionPoint().getType() == DistributionPointName.NAME_RELATIVE_TO_CRL_ISSUER)
  727. // {
  728. // // append fragment to issuer, only one
  729. // // issuer can be there, if this is given
  730. // if (issuers.size() != 1)
  731. // {
  732. // throw new AnnotatedException(
  733. // "nameRelativeToCRLIssuer field is given but more than one CRL issuer is given.");
  734. // }
  735. // DEREncodable relName = dp.getDistributionPoint().getName();
  736. // Iterator it = issuers.iterator();
  737. // List issuersTemp = new ArrayList(issuers.size());
  738. // while (it.hasNext())
  739. // {
  740. // Enumeration e = null;
  741. // try
  742. // {
  743. // e = ASN1Sequence.getInstance(
  744. // new ASN1InputStream(((X500Principal) it.next())
  745. // .getEncoded()).readObject()).getObjects();
  746. // }
  747. // catch (IOException ex)
  748. // {
  749. // throw new AnnotatedException(
  750. // "Cannot decode CRL issuer information.", ex);
  751. // }
  752. // ASN1EncodableVector v = new ASN1EncodableVector();
  753. // while (e.hasMoreElements())
  754. // {
  755. // v.add((DEREncodable) e.nextElement());
  756. // }
  757. // v.add(relName);
  758. // issuersTemp.add(new X500Principal(new DERSequence(v)
  759. // .getDEREncoded()));
  760. // }
  761. // issuers.clear();
  762. // issuers.addAll(issuersTemp);
  763. // }
  764. // }
  765. selector.Issuers = issuers;
  766. }
  767. /**
  768. * Fetches complete CRLs according to RFC 3280.
  769. *
  770. * @param dp The distribution point for which the complete CRL
  771. * @param cert The <code>X509Certificate</code> or
  772. * {@link org.bouncycastle.x509.X509AttributeCertificate} for
  773. * which the CRL should be searched.
  774. * @param currentDate The date for which the delta CRLs must be valid.
  775. * @param paramsPKIX The extended PKIX parameters.
  776. * @return A <code>Set</code> of <code>X509CRL</code>s with complete
  777. * CRLs.
  778. * @throws Exception if an exception occurs while picking the CRLs
  779. * or no CRLs are found.
  780. */
  781. internal static ISet GetCompleteCrls(
  782. DistributionPoint dp,
  783. object cert,
  784. DateTime currentDate,
  785. PkixParameters paramsPKIX)
  786. {
  787. X509CrlStoreSelector crlselect = new X509CrlStoreSelector();
  788. try
  789. {
  790. ISet issuers = new HashSet();
  791. if (cert is X509V2AttributeCertificate)
  792. {
  793. issuers.Add(((X509V2AttributeCertificate)cert)
  794. .Issuer.GetPrincipals()[0]);
  795. }
  796. else
  797. {
  798. issuers.Add(GetIssuerPrincipal(cert));
  799. }
  800. PkixCertPathValidatorUtilities.GetCrlIssuersFromDistributionPoint(dp, issuers, crlselect, paramsPKIX);
  801. }
  802. catch (Exception e)
  803. {
  804. throw new Exception("Could not get issuer information from distribution point.", e);
  805. }
  806. if (cert is X509Certificate)
  807. {
  808. crlselect.CertificateChecking = (X509Certificate)cert;
  809. }
  810. else if (cert is X509V2AttributeCertificate)
  811. {
  812. crlselect.AttrCertChecking = (IX509AttributeCertificate)cert;
  813. }
  814. crlselect.CompleteCrlEnabled = true;
  815. ISet crls = CrlUtilities.FindCrls(crlselect, paramsPKIX, currentDate);
  816. if (crls.IsEmpty)
  817. {
  818. if (cert is IX509AttributeCertificate)
  819. {
  820. IX509AttributeCertificate aCert = (IX509AttributeCertificate)cert;
  821. throw new Exception("No CRLs found for issuer \"" + aCert.Issuer.GetPrincipals()[0] + "\"");
  822. }
  823. else
  824. {
  825. X509Certificate xCert = (X509Certificate)cert;
  826. throw new Exception("No CRLs found for issuer \"" + xCert.IssuerDN + "\"");
  827. }
  828. }
  829. return crls;
  830. }
  831. /**
  832. * Fetches delta CRLs according to RFC 3280 section 5.2.4.
  833. *
  834. * @param currentDate The date for which the delta CRLs must be valid.
  835. * @param paramsPKIX The extended PKIX parameters.
  836. * @param completeCRL The complete CRL the delta CRL is for.
  837. * @return A <code>Set</code> of <code>X509CRL</code>s with delta CRLs.
  838. * @throws Exception if an exception occurs while picking the delta
  839. * CRLs.
  840. */
  841. internal static ISet GetDeltaCrls(
  842. DateTime currentDate,
  843. PkixParameters paramsPKIX,
  844. X509Crl completeCRL)
  845. {
  846. X509CrlStoreSelector deltaSelect = new X509CrlStoreSelector();
  847. // 5.2.4 (a)
  848. try
  849. {
  850. IList deltaSelectIssuer = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
  851. deltaSelectIssuer.Add(completeCRL.IssuerDN);
  852. deltaSelect.Issuers = deltaSelectIssuer;
  853. }
  854. catch (IOException e)
  855. {
  856. throw new Exception("Cannot extract issuer from CRL.", e);
  857. }
  858. BigInteger completeCRLNumber = null;
  859. try
  860. {
  861. Asn1Object asn1Object = GetExtensionValue(completeCRL, X509Extensions.CrlNumber);
  862. if (asn1Object != null)
  863. {
  864. completeCRLNumber = CrlNumber.GetInstance(asn1Object).PositiveValue;
  865. }
  866. }
  867. catch (Exception e)
  868. {
  869. throw new Exception(
  870. "CRL number extension could not be extracted from CRL.", e);
  871. }
  872. // 5.2.4 (b)
  873. byte[] idp = null;
  874. try
  875. {
  876. Asn1Object obj = GetExtensionValue(completeCRL, X509Extensions.IssuingDistributionPoint);
  877. if (obj != null)
  878. {
  879. idp = obj.GetDerEncoded();
  880. }
  881. }
  882. catch (Exception e)
  883. {
  884. throw new Exception(
  885. "Issuing distribution point extension value could not be read.",
  886. e);
  887. }
  888. // 5.2.4 (d)
  889. deltaSelect.MinCrlNumber = (completeCRLNumber == null)
  890. ? null
  891. : completeCRLNumber.Add(BigInteger.One);
  892. deltaSelect.IssuingDistributionPoint = idp;
  893. deltaSelect.IssuingDistributionPointEnabled = true;
  894. // 5.2.4 (c)
  895. deltaSelect.MaxBaseCrlNumber = completeCRLNumber;
  896. // find delta CRLs
  897. ISet temp = CrlUtilities.FindCrls(deltaSelect, paramsPKIX, currentDate);
  898. ISet result = new HashSet();
  899. foreach (X509Crl crl in temp)
  900. {
  901. if (isDeltaCrl(crl))
  902. {
  903. result.Add(crl);
  904. }
  905. }
  906. return result;
  907. }
  908. private static bool isDeltaCrl(
  909. X509Crl crl)
  910. {
  911. ISet critical = crl.GetCriticalExtensionOids();
  912. return critical.Contains(X509Extensions.DeltaCrlIndicator.Id);
  913. }
  914. internal static ICollection FindCertificates(
  915. X509AttrCertStoreSelector certSelect,
  916. IList certStores)
  917. {
  918. ISet certs = new HashSet();
  919. foreach (IX509Store certStore in certStores)
  920. {
  921. try
  922. {
  923. // certs.AddAll(certStore.GetMatches(certSelect));
  924. foreach (X509V2AttributeCertificate ac in certStore.GetMatches(certSelect))
  925. {
  926. certs.Add(ac);
  927. }
  928. }
  929. catch (Exception e)
  930. {
  931. throw new Exception(
  932. "Problem while picking certificates from X.509 store.", e);
  933. }
  934. }
  935. return certs;
  936. }
  937. internal static void AddAdditionalStoresFromCrlDistributionPoint(
  938. CrlDistPoint crldp,
  939. PkixParameters pkixParams)
  940. {
  941. if (crldp != null)
  942. {
  943. DistributionPoint[] dps = null;
  944. try
  945. {
  946. dps = crldp.GetDistributionPoints();
  947. }
  948. catch (Exception e)
  949. {
  950. throw new Exception(
  951. "Distribution points could not be read.", e);
  952. }
  953. for (int i = 0; i < dps.Length; i++)
  954. {
  955. DistributionPointName dpn = dps[i].DistributionPointName;
  956. // look for URIs in fullName
  957. if (dpn != null)
  958. {
  959. if (dpn.PointType == DistributionPointName.FullName)
  960. {
  961. GeneralName[] genNames = GeneralNames.GetInstance(
  962. dpn.Name).GetNames();
  963. // look for an URI
  964. for (int j = 0; j < genNames.Length; j++)
  965. {
  966. if (genNames[j].TagNo == GeneralName.UniformResourceIdentifier)
  967. {
  968. string location = DerIA5String.GetInstance(
  969. genNames[j].Name).GetString();
  970. PkixCertPathValidatorUtilities.AddAdditionalStoreFromLocation(
  971. location, pkixParams);
  972. }
  973. }
  974. }
  975. }
  976. }
  977. }
  978. }
  979. internal static bool ProcessCertD1i(
  980. int index,
  981. IList[] policyNodes,
  982. DerObjectIdentifier pOid,
  983. ISet pq)
  984. {
  985. IList policyNodeVec = policyNodes[index - 1];
  986. for (int j = 0; j < policyNodeVec.Count; j++)
  987. {
  988. PkixPolicyNode node = (PkixPolicyNode)policyNodeVec[j];
  989. ISet expectedPolicies = node.ExpectedPolicies;
  990. if (expectedPolicies.Contains(pOid.Id))
  991. {
  992. ISet childExpectedPolicies = new HashSet();
  993. childExpectedPolicies.Add(pOid.Id);
  994. PkixPolicyNode child = new PkixPolicyNode(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(),
  995. index,
  996. childExpectedPolicies,
  997. node,
  998. pq,
  999. pOid.Id,
  1000. false);
  1001. node.AddChild(child);
  1002. policyNodes[index].Add(child);
  1003. return true;
  1004. }
  1005. }
  1006. return false;
  1007. }
  1008. internal static void ProcessCertD1ii(
  1009. int index,
  1010. IList[] policyNodes,
  1011. DerObjectIdentifier _poid,
  1012. ISet _pq)
  1013. {
  1014. IList policyNodeVec = policyNodes[index - 1];
  1015. for (int j = 0; j < policyNodeVec.Count; j++)
  1016. {
  1017. PkixPolicyNode _node = (PkixPolicyNode)policyNodeVec[j];
  1018. if (ANY_POLICY.Equals(_node.ValidPolicy))
  1019. {
  1020. ISet _childExpectedPolicies = new HashSet();
  1021. _childExpectedPolicies.Add(_poid.Id);
  1022. PkixPolicyNode _child = new PkixPolicyNode(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(),
  1023. index,
  1024. _childExpectedPolicies,
  1025. _node,
  1026. _pq,
  1027. _poid.Id,
  1028. false);
  1029. _node.AddChild(_child);
  1030. policyNodes[index].Add(_child);
  1031. return;
  1032. }
  1033. }
  1034. }
  1035. /**
  1036. * Find the issuer certificates of a given certificate.
  1037. *
  1038. * @param cert
  1039. * The certificate for which an issuer should be found.
  1040. * @param pkixParams
  1041. * @return A <code>Collection</code> object containing the issuer
  1042. * <code>X509Certificate</code>s. Never <code>null</code>.
  1043. *
  1044. * @exception Exception
  1045. * if an error occurs.
  1046. */
  1047. internal static ICollection FindIssuerCerts(
  1048. X509Certificate cert,
  1049. PkixBuilderParameters pkixParams)
  1050. {
  1051. X509CertStoreSelector certSelect = new X509CertStoreSelector();
  1052. ISet certs = new HashSet();
  1053. try
  1054. {
  1055. certSelect.Subject = cert.IssuerDN;
  1056. }
  1057. catch (IOException ex)
  1058. {
  1059. throw new Exception(
  1060. "Subject criteria for certificate selector to find issuer certificate could not be set.", ex);
  1061. }
  1062. try
  1063. {
  1064. certs.AddAll(PkixCertPathValidatorUtilities.FindCertificates(certSelect, pkixParams.GetStores()));
  1065. certs.AddAll(PkixCertPathValidatorUtilities.FindCertificates(certSelect, pkixParams.GetAdditionalStores()));
  1066. }
  1067. catch (Exception e)
  1068. {
  1069. throw new Exception("Issuer certificate cannot be searched.", e);
  1070. }
  1071. return certs;
  1072. }
  1073. /// <summary>
  1074. /// Extract the value of the given extension, if it exists.
  1075. /// </summary>
  1076. /// <param name="ext">The extension object.</param>
  1077. /// <param name="oid">The object identifier to obtain.</param>
  1078. /// <returns>Asn1Object</returns>
  1079. /// <exception cref="Exception">if the extension cannot be read.</exception>
  1080. internal static Asn1Object GetExtensionValue(
  1081. IX509Extension ext,
  1082. DerObjectIdentifier oid)
  1083. {
  1084. Asn1OctetString bytes = ext.GetExtensionValue(oid);
  1085. if (bytes == null)
  1086. return null;
  1087. return X509ExtensionUtilities.FromExtensionValue(bytes);
  1088. }
  1089. }
  1090. }
  1091. #pragma warning restore
  1092. #endif