Rfc3281CertPathUtilities.cs 18 KB

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