Rfc3281CertPathUtilities.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using System.Collections;
  5. using System.Globalization;
  6. using System.IO;
  7. using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
  8. using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
  9. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
  10. using BestHTTP.SecureProtocol.Org.BouncyCastle.Security.Certificates;
  11. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections;
  12. using BestHTTP.SecureProtocol.Org.BouncyCastle.X509;
  13. using BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store;
  14. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkix
  15. {
  16. internal class Rfc3281CertPathUtilities
  17. {
  18. internal static void ProcessAttrCert7(
  19. IX509AttributeCertificate attrCert,
  20. PkixCertPath certPath,
  21. PkixCertPath holderCertPath,
  22. PkixParameters pkixParams)
  23. {
  24. // TODO:
  25. // AA Controls
  26. // Attribute encryption
  27. // Proxy
  28. ISet critExtOids = attrCert.GetCriticalExtensionOids();
  29. // 7.1
  30. // process extensions
  31. // target information checked in step 6 / X509AttributeCertStoreSelector
  32. if (critExtOids.Contains(X509Extensions.TargetInformation.Id))
  33. {
  34. try
  35. {
  36. TargetInformation.GetInstance(PkixCertPathValidatorUtilities
  37. .GetExtensionValue(attrCert, X509Extensions.TargetInformation));
  38. }
  39. catch (Exception e)
  40. {
  41. throw new PkixCertPathValidatorException(
  42. "Target information extension could not be read.", e);
  43. }
  44. }
  45. critExtOids.Remove(X509Extensions.TargetInformation.Id);
  46. foreach (PkixAttrCertChecker checker in pkixParams.GetAttrCertCheckers())
  47. {
  48. checker.Check(attrCert, certPath, holderCertPath, critExtOids);
  49. }
  50. if (!critExtOids.IsEmpty)
  51. {
  52. throw new PkixCertPathValidatorException(
  53. "Attribute certificate contains unsupported critical extensions: "
  54. + critExtOids);
  55. }
  56. }
  57. /**
  58. * Checks if an attribute certificate is revoked.
  59. *
  60. * @param attrCert Attribute certificate to check if it is revoked.
  61. * @param paramsPKIX PKIX parameters.
  62. * @param issuerCert The issuer certificate of the attribute certificate
  63. * <code>attrCert</code>.
  64. * @param validDate The date when the certificate revocation status should
  65. * be checked.
  66. * @param certPathCerts The certificates of the certification path to be
  67. * checked.
  68. *
  69. * @throws CertPathValidatorException if the certificate is revoked or the
  70. * status cannot be checked or some error occurs.
  71. */
  72. internal static void CheckCrls(
  73. IX509AttributeCertificate attrCert,
  74. PkixParameters paramsPKIX,
  75. X509Certificate issuerCert,
  76. DateTime validDate,
  77. IList certPathCerts)
  78. {
  79. if (!paramsPKIX.IsRevocationEnabled)
  80. {
  81. return;
  82. }
  83. // check if revocation is available
  84. if (attrCert.GetExtensionValue(X509Extensions.NoRevAvail) != null)
  85. {
  86. if (attrCert.GetExtensionValue(X509Extensions.CrlDistributionPoints) != null
  87. || attrCert.GetExtensionValue(X509Extensions.AuthorityInfoAccess) != null)
  88. {
  89. throw new PkixCertPathValidatorException(
  90. "No rev avail extension is set, but also an AC revocation pointer.");
  91. }
  92. return;
  93. }
  94. CrlDistPoint crldp = null;
  95. try
  96. {
  97. crldp = CrlDistPoint.GetInstance(
  98. PkixCertPathValidatorUtilities.GetExtensionValue(
  99. attrCert, X509Extensions.CrlDistributionPoints));
  100. }
  101. catch (Exception e)
  102. {
  103. throw new PkixCertPathValidatorException(
  104. "CRL distribution point extension could not be read.", e);
  105. }
  106. try
  107. {
  108. PkixCertPathValidatorUtilities
  109. .AddAdditionalStoresFromCrlDistributionPoint(crldp, paramsPKIX);
  110. }
  111. catch (Exception e)
  112. {
  113. throw new PkixCertPathValidatorException(
  114. "No additional CRL locations could be decoded from CRL distribution point extension.", e);
  115. }
  116. CertStatus certStatus = new CertStatus();
  117. ReasonsMask reasonsMask = new ReasonsMask();
  118. Exception lastException = null;
  119. bool validCrlFound = false;
  120. // for each distribution point
  121. if (crldp != null)
  122. {
  123. DistributionPoint[] dps = null;
  124. try
  125. {
  126. dps = crldp.GetDistributionPoints();
  127. }
  128. catch (Exception e)
  129. {
  130. throw new PkixCertPathValidatorException(
  131. "Distribution points could not be read.", e);
  132. }
  133. try
  134. {
  135. for (int i = 0; i < dps.Length
  136. && certStatus.Status == CertStatus.Unrevoked
  137. && !reasonsMask.IsAllReasons; i++)
  138. {
  139. PkixParameters paramsPKIXClone = (PkixParameters) paramsPKIX
  140. .Clone();
  141. CheckCrl(dps[i], attrCert, paramsPKIXClone,
  142. validDate, issuerCert, certStatus, reasonsMask,
  143. certPathCerts);
  144. validCrlFound = true;
  145. }
  146. }
  147. catch (Exception e)
  148. {
  149. lastException = new Exception(
  150. "No valid CRL for distribution point found.", e);
  151. }
  152. }
  153. /*
  154. * If the revocation status has not been determined, repeat the
  155. * process above with any available CRLs not specified in a
  156. * distribution point but issued by the certificate issuer.
  157. */
  158. if (certStatus.Status == CertStatus.Unrevoked
  159. && !reasonsMask.IsAllReasons)
  160. {
  161. try
  162. {
  163. /*
  164. * assume a DP with both the reasons and the cRLIssuer
  165. * fields omitted and a distribution point name of the
  166. * certificate issuer.
  167. */
  168. X509Name issuer;
  169. try
  170. {
  171. issuer = X509Name.GetInstance(attrCert.Issuer.GetPrincipals()[0].GetEncoded());
  172. }
  173. catch (Exception e)
  174. {
  175. throw new Exception(
  176. "Issuer from certificate for CRL could not be reencoded.",
  177. e);
  178. }
  179. DistributionPoint dp = new DistributionPoint(
  180. new DistributionPointName(0, new GeneralNames(
  181. new GeneralName(GeneralName.DirectoryName, issuer))), null, null);
  182. PkixParameters paramsPKIXClone = (PkixParameters) paramsPKIX.Clone();
  183. CheckCrl(dp, attrCert, paramsPKIXClone, validDate,
  184. issuerCert, certStatus, reasonsMask, certPathCerts);
  185. validCrlFound = true;
  186. }
  187. catch (Exception e)
  188. {
  189. lastException = new Exception(
  190. "No valid CRL for distribution point found.", e);
  191. }
  192. }
  193. if (!validCrlFound)
  194. {
  195. throw new PkixCertPathValidatorException(
  196. "No valid CRL found.", lastException);
  197. }
  198. if (certStatus.Status != CertStatus.Unrevoked)
  199. {
  200. // This format is enforced by the NistCertPath tests
  201. string formattedDate = certStatus.RevocationDate.Value.ToString(
  202. "ddd MMM dd HH:mm:ss K yyyy");
  203. string message = "Attribute certificate revocation after "
  204. + formattedDate;
  205. message += ", reason: "
  206. + Rfc3280CertPathUtilities.CrlReasons[certStatus.Status];
  207. throw new PkixCertPathValidatorException(message);
  208. }
  209. if (!reasonsMask.IsAllReasons
  210. && certStatus.Status == CertStatus.Unrevoked)
  211. {
  212. certStatus.Status = CertStatus.Undetermined;
  213. }
  214. if (certStatus.Status == CertStatus.Undetermined)
  215. {
  216. throw new PkixCertPathValidatorException(
  217. "Attribute certificate status could not be determined.");
  218. }
  219. }
  220. internal static void AdditionalChecks(
  221. IX509AttributeCertificate attrCert,
  222. PkixParameters pkixParams)
  223. {
  224. // 1
  225. foreach (string oid in pkixParams.GetProhibitedACAttributes())
  226. {
  227. if (attrCert.GetAttributes(oid) != null)
  228. {
  229. throw new PkixCertPathValidatorException(
  230. "Attribute certificate contains prohibited attribute: "
  231. + oid + ".");
  232. }
  233. }
  234. foreach (string oid in pkixParams.GetNecessaryACAttributes())
  235. {
  236. if (attrCert.GetAttributes(oid) == null)
  237. {
  238. throw new PkixCertPathValidatorException(
  239. "Attribute certificate does not contain necessary attribute: "
  240. + oid + ".");
  241. }
  242. }
  243. }
  244. internal static void ProcessAttrCert5(
  245. IX509AttributeCertificate attrCert,
  246. PkixParameters pkixParams)
  247. {
  248. try
  249. {
  250. attrCert.CheckValidity(PkixCertPathValidatorUtilities.GetValidDate(pkixParams));
  251. }
  252. catch (CertificateExpiredException e)
  253. {
  254. throw new PkixCertPathValidatorException(
  255. "Attribute certificate is not valid.", e);
  256. }
  257. catch (CertificateNotYetValidException e)
  258. {
  259. throw new PkixCertPathValidatorException(
  260. "Attribute certificate is not valid.", e);
  261. }
  262. }
  263. internal static void ProcessAttrCert4(
  264. X509Certificate acIssuerCert,
  265. PkixParameters pkixParams)
  266. {
  267. ISet set = pkixParams.GetTrustedACIssuers();
  268. bool trusted = false;
  269. foreach (TrustAnchor anchor in set)
  270. {
  271. IDictionary symbols = X509Name.RFC2253Symbols;
  272. if (acIssuerCert.SubjectDN.ToString(false, symbols).Equals(anchor.CAName)
  273. || acIssuerCert.Equals(anchor.TrustedCert))
  274. {
  275. trusted = true;
  276. }
  277. }
  278. if (!trusted)
  279. {
  280. throw new PkixCertPathValidatorException(
  281. "Attribute certificate issuer is not directly trusted.");
  282. }
  283. }
  284. internal static void ProcessAttrCert3(
  285. X509Certificate acIssuerCert,
  286. PkixParameters pkixParams)
  287. {
  288. if (acIssuerCert.GetKeyUsage() != null
  289. && (!acIssuerCert.GetKeyUsage()[0] && !acIssuerCert.GetKeyUsage()[1]))
  290. {
  291. throw new PkixCertPathValidatorException(
  292. "Attribute certificate issuer public key cannot be used to validate digital signatures.");
  293. }
  294. if (acIssuerCert.GetBasicConstraints() != -1)
  295. {
  296. throw new PkixCertPathValidatorException(
  297. "Attribute certificate issuer is also a public key certificate issuer.");
  298. }
  299. }
  300. internal static PkixCertPathValidatorResult ProcessAttrCert2(
  301. PkixCertPath certPath,
  302. PkixParameters pkixParams)
  303. {
  304. PkixCertPathValidator validator = new PkixCertPathValidator();
  305. try
  306. {
  307. return validator.Validate(certPath, pkixParams);
  308. }
  309. catch (PkixCertPathValidatorException e)
  310. {
  311. throw new PkixCertPathValidatorException(
  312. "Certification path for issuer certificate of attribute certificate could not be validated.",
  313. e);
  314. }
  315. }
  316. /**
  317. * Searches for a holder public key certificate and verifies its
  318. * certification path.
  319. *
  320. * @param attrCert the attribute certificate.
  321. * @param pkixParams The PKIX parameters.
  322. * @return The certificate path of the holder certificate.
  323. * @throws Exception if
  324. * <ul>
  325. * <li>no public key certificate can be found although holder
  326. * information is given by an entity name or a base certificate
  327. * ID</li>
  328. * <li>support classes cannot be created</li>
  329. * <li>no certification path for the public key certificate can
  330. * be built</li>
  331. * </ul>
  332. */
  333. internal static PkixCertPath ProcessAttrCert1(
  334. IX509AttributeCertificate attrCert,
  335. PkixParameters pkixParams)
  336. {
  337. PkixCertPathBuilderResult result = null;
  338. // find holder PKCs
  339. ISet holderPKCs = new HashSet();
  340. if (attrCert.Holder.GetIssuer() != null)
  341. {
  342. X509CertStoreSelector selector = new X509CertStoreSelector();
  343. selector.SerialNumber = attrCert.Holder.SerialNumber;
  344. X509Name[] principals = attrCert.Holder.GetIssuer();
  345. for (int i = 0; i < principals.Length; i++)
  346. {
  347. try
  348. {
  349. // if (principals[i] is X500Principal)
  350. {
  351. selector.Issuer = principals[i];
  352. }
  353. holderPKCs.AddAll(PkixCertPathValidatorUtilities
  354. .FindCertificates(selector, pkixParams.GetStores()));
  355. }
  356. catch (Exception e)
  357. {
  358. throw new PkixCertPathValidatorException(
  359. "Public key certificate for attribute certificate cannot be searched.",
  360. e);
  361. }
  362. }
  363. if (holderPKCs.IsEmpty)
  364. {
  365. throw new PkixCertPathValidatorException(
  366. "Public key certificate specified in base certificate ID for attribute certificate cannot be found.");
  367. }
  368. }
  369. if (attrCert.Holder.GetEntityNames() != null)
  370. {
  371. X509CertStoreSelector selector = new X509CertStoreSelector();
  372. X509Name[] principals = attrCert.Holder.GetEntityNames();
  373. for (int i = 0; i < principals.Length; i++)
  374. {
  375. try
  376. {
  377. // if (principals[i] is X500Principal)
  378. {
  379. selector.Issuer = principals[i];
  380. }
  381. holderPKCs.AddAll(PkixCertPathValidatorUtilities
  382. .FindCertificates(selector, pkixParams.GetStores()));
  383. }
  384. catch (Exception e)
  385. {
  386. throw new PkixCertPathValidatorException(
  387. "Public key certificate for attribute certificate cannot be searched.",
  388. e);
  389. }
  390. }
  391. if (holderPKCs.IsEmpty)
  392. {
  393. throw new PkixCertPathValidatorException(
  394. "Public key certificate specified in entity name for attribute certificate cannot be found.");
  395. }
  396. }
  397. // verify cert paths for PKCs
  398. PkixBuilderParameters parameters = (PkixBuilderParameters)
  399. PkixBuilderParameters.GetInstance(pkixParams);
  400. PkixCertPathValidatorException lastException = null;
  401. foreach (X509Certificate cert in holderPKCs)
  402. {
  403. X509CertStoreSelector selector = new X509CertStoreSelector();
  404. selector.Certificate = cert;
  405. parameters.SetTargetConstraints(selector);
  406. PkixCertPathBuilder builder = new PkixCertPathBuilder();
  407. try
  408. {
  409. result = builder.Build(PkixBuilderParameters.GetInstance(parameters));
  410. }
  411. catch (PkixCertPathBuilderException e)
  412. {
  413. lastException = new PkixCertPathValidatorException(
  414. "Certification path for public key certificate of attribute certificate could not be build.",
  415. e);
  416. }
  417. }
  418. if (lastException != null)
  419. {
  420. throw lastException;
  421. }
  422. return result.CertPath;
  423. }
  424. /**
  425. *
  426. * Checks a distribution point for revocation information for the
  427. * certificate <code>attrCert</code>.
  428. *
  429. * @param dp The distribution point to consider.
  430. * @param attrCert The attribute certificate which should be checked.
  431. * @param paramsPKIX PKIX parameters.
  432. * @param validDate The date when the certificate revocation status should
  433. * be checked.
  434. * @param issuerCert Certificate to check if it is revoked.
  435. * @param reasonMask The reasons mask which is already checked.
  436. * @param certPathCerts The certificates of the certification path to be
  437. * checked.
  438. * @throws Exception if the certificate is revoked or the status
  439. * cannot be checked or some error occurs.
  440. */
  441. private static void CheckCrl(
  442. DistributionPoint dp,
  443. IX509AttributeCertificate attrCert,
  444. PkixParameters paramsPKIX,
  445. DateTime validDate,
  446. X509Certificate issuerCert,
  447. CertStatus certStatus,
  448. ReasonsMask reasonMask,
  449. IList certPathCerts)
  450. {
  451. /*
  452. * 4.3.6 No Revocation Available
  453. *
  454. * The noRevAvail extension, defined in [X.509-2000], allows an AC
  455. * issuer to indicate that no revocation information will be made
  456. * available for this AC.
  457. */
  458. if (attrCert.GetExtensionValue(X509Extensions.NoRevAvail) != null)
  459. {
  460. return;
  461. }
  462. DateTime currentDate = DateTime.UtcNow;
  463. if (validDate.CompareTo(currentDate) > 0)
  464. {
  465. throw new Exception("Validation time is in future.");
  466. }
  467. // (a)
  468. /*
  469. * We always get timely valid CRLs, so there is no step (a) (1).
  470. * "locally cached" CRLs are assumed to be in getStore(), additional
  471. * CRLs must be enabled in the ExtendedPkixParameters and are in
  472. * getAdditionalStore()
  473. */
  474. ISet crls = PkixCertPathValidatorUtilities.GetCompleteCrls(dp, attrCert,
  475. currentDate, paramsPKIX);
  476. bool validCrlFound = false;
  477. Exception lastException = null;
  478. IEnumerator crl_iter = crls.GetEnumerator();
  479. while (crl_iter.MoveNext()
  480. && certStatus.Status == CertStatus.Unrevoked
  481. && !reasonMask.IsAllReasons)
  482. {
  483. try
  484. {
  485. X509Crl crl = (X509Crl) crl_iter.Current;
  486. // (d)
  487. ReasonsMask interimReasonsMask = Rfc3280CertPathUtilities.ProcessCrlD(crl, dp);
  488. // (e)
  489. /*
  490. * The reasons mask is updated at the end, so only valid CRLs
  491. * can update it. If this CRL does not contain new reasons it
  492. * must be ignored.
  493. */
  494. if (!interimReasonsMask.HasNewReasons(reasonMask))
  495. {
  496. continue;
  497. }
  498. // (f)
  499. ISet keys = Rfc3280CertPathUtilities.ProcessCrlF(crl, attrCert,
  500. null, null, paramsPKIX, certPathCerts);
  501. // (g)
  502. AsymmetricKeyParameter pubKey = Rfc3280CertPathUtilities.ProcessCrlG(crl, keys);
  503. X509Crl deltaCRL = null;
  504. if (paramsPKIX.IsUseDeltasEnabled)
  505. {
  506. // get delta CRLs
  507. ISet deltaCRLs = PkixCertPathValidatorUtilities.GetDeltaCrls(
  508. currentDate, paramsPKIX, crl);
  509. // we only want one valid delta CRL
  510. // (h)
  511. deltaCRL = Rfc3280CertPathUtilities.ProcessCrlH(deltaCRLs, pubKey);
  512. }
  513. /*
  514. * CRL must be be valid at the current time, not the validation
  515. * time. If a certificate is revoked with reason keyCompromise,
  516. * cACompromise, it can be used for forgery, also for the past.
  517. * This reason may not be contained in older CRLs.
  518. */
  519. /*
  520. * in the chain model signatures stay valid also after the
  521. * certificate has been expired, so they do not have to be in
  522. * the CRL vality time
  523. */
  524. if (paramsPKIX.ValidityModel != PkixParameters.ChainValidityModel)
  525. {
  526. /*
  527. * if a certificate has expired, but was revoked, it is not
  528. * more in the CRL, so it would be regarded as valid if the
  529. * first check is not done
  530. */
  531. if (attrCert.NotAfter.CompareTo(crl.ThisUpdate) < 0)
  532. {
  533. throw new Exception(
  534. "No valid CRL for current time found.");
  535. }
  536. }
  537. Rfc3280CertPathUtilities.ProcessCrlB1(dp, attrCert, crl);
  538. // (b) (2)
  539. Rfc3280CertPathUtilities.ProcessCrlB2(dp, attrCert, crl);
  540. // (c)
  541. Rfc3280CertPathUtilities.ProcessCrlC(deltaCRL, crl, paramsPKIX);
  542. // (i)
  543. Rfc3280CertPathUtilities.ProcessCrlI(validDate, deltaCRL,
  544. attrCert, certStatus, paramsPKIX);
  545. // (j)
  546. Rfc3280CertPathUtilities.ProcessCrlJ(validDate, crl, attrCert,
  547. certStatus);
  548. // (k)
  549. if (certStatus.Status == CrlReason.RemoveFromCrl)
  550. {
  551. certStatus.Status = CertStatus.Unrevoked;
  552. }
  553. // update reasons mask
  554. reasonMask.AddReasons(interimReasonsMask);
  555. validCrlFound = true;
  556. }
  557. catch (Exception e)
  558. {
  559. lastException = e;
  560. }
  561. }
  562. if (!validCrlFound)
  563. {
  564. throw lastException;
  565. }
  566. }
  567. }
  568. }
  569. #pragma warning restore
  570. #endif