Rfc3280CertPathUtilities.cs 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
  7. using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
  8. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
  9. using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
  10. using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
  11. using BestHTTP.SecureProtocol.Org.BouncyCastle.Security.Certificates;
  12. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  13. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections;
  14. using BestHTTP.SecureProtocol.Org.BouncyCastle.X509;
  15. using BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store;
  16. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkix
  17. {
  18. internal static class Rfc3280CertPathUtilities
  19. {
  20. private static readonly PkixCrlUtilities CrlUtilities = new PkixCrlUtilities();
  21. internal static readonly string ANY_POLICY = "2.5.29.32.0";
  22. // key usage bits
  23. internal static readonly int KEY_CERT_SIGN = 5;
  24. internal static readonly int CRL_SIGN = 6;
  25. /**
  26. * If the complete CRL includes an issuing distribution point (IDP) CRL
  27. * extension check the following:
  28. * <p>
  29. * (i) If the distribution point name is present in the IDP CRL extension
  30. * and the distribution field is present in the DP, then verify that one of
  31. * the names in the IDP matches one of the names in the DP. If the
  32. * distribution point name is present in the IDP CRL extension and the
  33. * distribution field is omitted from the DP, then verify that one of the
  34. * names in the IDP matches one of the names in the cRLIssuer field of the
  35. * DP.
  36. * </p>
  37. * <p>
  38. * (ii) If the onlyContainsUserCerts boolean is asserted in the IDP CRL
  39. * extension, verify that the certificate does not include the basic
  40. * constraints extension with the cA boolean asserted.
  41. * </p>
  42. * <p>
  43. * (iii) If the onlyContainsCACerts boolean is asserted in the IDP CRL
  44. * extension, verify that the certificate includes the basic constraints
  45. * extension with the cA boolean asserted.
  46. * </p>
  47. * <p>
  48. * (iv) Verify that the onlyContainsAttributeCerts boolean is not asserted.
  49. * </p>
  50. *
  51. * @param dp The distribution point.
  52. * @param cert The certificate.
  53. * @param crl The CRL.
  54. * @throws AnnotatedException if one of the conditions is not met or an error occurs.
  55. */
  56. internal static void ProcessCrlB2(DistributionPoint dp, object cert, X509Crl crl)
  57. {
  58. IssuingDistributionPoint idp;
  59. try
  60. {
  61. idp = IssuingDistributionPoint.GetInstance(PkixCertPathValidatorUtilities.GetExtensionValue(crl, X509Extensions.IssuingDistributionPoint));
  62. }
  63. catch (Exception e)
  64. {
  65. throw new Exception("0 Issuing distribution point extension could not be decoded.", e);
  66. }
  67. // (b) (2) (i)
  68. // distribution point name is present
  69. if (idp != null)
  70. {
  71. if (idp.DistributionPoint != null)
  72. {
  73. // make list of names
  74. DistributionPointName dpName = IssuingDistributionPoint.GetInstance(idp).DistributionPoint;
  75. var names = new List<GeneralName>();
  76. if (dpName.PointType == DistributionPointName.FullName)
  77. {
  78. GeneralName[] genNames = GeneralNames.GetInstance(dpName.Name).GetNames();
  79. for (int j = 0; j < genNames.Length; j++)
  80. {
  81. names.Add(genNames[j]);
  82. }
  83. }
  84. if (dpName.PointType == DistributionPointName.NameRelativeToCrlIssuer)
  85. {
  86. var seq = Asn1Sequence.GetInstance(crl.IssuerDN.ToAsn1Object());
  87. Asn1EncodableVector vec = new Asn1EncodableVector(seq.Count + 1);
  88. foreach (var element in seq)
  89. {
  90. vec.Add(element);
  91. }
  92. vec.Add(dpName.Name);
  93. names.Add(new GeneralName(X509Name.GetInstance(new DerSequence(vec))));
  94. }
  95. bool matches = false;
  96. // verify that one of the names in the IDP matches one
  97. // of the names in the DP.
  98. if (dp.DistributionPointName != null)
  99. {
  100. dpName = dp.DistributionPointName;
  101. GeneralName[] genNames = null;
  102. if (dpName.PointType == DistributionPointName.FullName)
  103. {
  104. genNames = GeneralNames.GetInstance(dpName.Name).GetNames();
  105. }
  106. if (dpName.PointType == DistributionPointName.NameRelativeToCrlIssuer)
  107. {
  108. if (dp.CrlIssuer != null)
  109. {
  110. genNames = dp.CrlIssuer.GetNames();
  111. }
  112. else
  113. {
  114. genNames = new GeneralName[1];
  115. try
  116. {
  117. genNames[0] = new GeneralName(
  118. PkixCertPathValidatorUtilities.GetIssuerPrincipal(cert));
  119. }
  120. catch (IOException e)
  121. {
  122. throw new Exception("Could not read certificate issuer.", e);
  123. }
  124. }
  125. for (int j = 0; j < genNames.Length; j++)
  126. {
  127. var seq = Asn1Sequence.GetInstance(genNames[j].Name.ToAsn1Object());
  128. Asn1EncodableVector vec = new Asn1EncodableVector(seq.Count + 1);
  129. foreach (var element in seq)
  130. {
  131. vec.Add(element);
  132. }
  133. vec.Add(dpName.Name);
  134. genNames[j] = new GeneralName(X509Name.GetInstance(new DerSequence(vec)));
  135. }
  136. }
  137. if (genNames != null)
  138. {
  139. for (int j = 0; j < genNames.Length; j++)
  140. {
  141. if (names.Contains(genNames[j]))
  142. {
  143. matches = true;
  144. break;
  145. }
  146. }
  147. }
  148. if (!matches)
  149. {
  150. throw new Exception(
  151. "No match for certificate CRL issuing distribution point name to cRLIssuer CRL distribution point.");
  152. }
  153. }
  154. // verify that one of the names in
  155. // the IDP matches one of the names in the cRLIssuer field of
  156. // the DP
  157. else
  158. {
  159. if (dp.CrlIssuer == null)
  160. {
  161. throw new Exception("Either the cRLIssuer or the distributionPoint field must "
  162. + "be contained in DistributionPoint.");
  163. }
  164. GeneralName[] genNames = dp.CrlIssuer.GetNames();
  165. for (int j = 0; j < genNames.Length; j++)
  166. {
  167. if (names.Contains(genNames[j]))
  168. {
  169. matches = true;
  170. break;
  171. }
  172. }
  173. if (!matches)
  174. {
  175. throw new Exception(
  176. "No match for certificate CRL issuing distribution point name to cRLIssuer CRL distribution point.");
  177. }
  178. }
  179. }
  180. BasicConstraints bc = null;
  181. try
  182. {
  183. bc = BasicConstraints.GetInstance(PkixCertPathValidatorUtilities.GetExtensionValue(
  184. (IX509Extension)cert, X509Extensions.BasicConstraints));
  185. }
  186. catch (Exception e)
  187. {
  188. throw new Exception("Basic constraints extension could not be decoded.", e);
  189. }
  190. //if (cert is X509Certificate)
  191. {
  192. // (b) (2) (ii)
  193. if (idp.OnlyContainsUserCerts && ((bc != null) && bc.IsCA()))
  194. {
  195. throw new Exception("CA Cert CRL only contains user certificates.");
  196. }
  197. // (b) (2) (iii)
  198. if (idp.OnlyContainsCACerts && (bc == null || !bc.IsCA()))
  199. {
  200. throw new Exception("End CRL only contains CA certificates.");
  201. }
  202. }
  203. // (b) (2) (iv)
  204. if (idp.OnlyContainsAttributeCerts)
  205. {
  206. throw new Exception("onlyContainsAttributeCerts boolean is asserted.");
  207. }
  208. }
  209. }
  210. /// <exception cref="PkixCertPathValidatorException"/>
  211. internal static void ProcessCertBC(
  212. PkixCertPath certPath,
  213. int index,
  214. PkixNameConstraintValidator nameConstraintValidator)
  215. {
  216. var certs = certPath.Certificates;
  217. X509Certificate cert = certs[index];
  218. int n = certs.Count;
  219. // i as defined in the algorithm description
  220. int i = n - index;
  221. //
  222. // (b), (c) permitted and excluded subtree checking.
  223. //
  224. if (!(PkixCertPathValidatorUtilities.IsSelfIssued(cert) && (i < n)))
  225. {
  226. X509Name principal = cert.SubjectDN;
  227. Asn1Sequence dns;
  228. try
  229. {
  230. dns = Asn1Sequence.GetInstance(principal.GetEncoded());
  231. }
  232. catch (Exception e)
  233. {
  234. throw new PkixCertPathValidatorException(
  235. "Exception extracting subject name when checking subtrees.", e, index);
  236. }
  237. try
  238. {
  239. nameConstraintValidator.CheckPermittedDN(dns);
  240. nameConstraintValidator.CheckExcludedDN(dns);
  241. }
  242. catch (PkixNameConstraintValidatorException e)
  243. {
  244. throw new PkixCertPathValidatorException(
  245. "Subtree check for certificate subject failed.", e, index);
  246. }
  247. GeneralNames altName = null;
  248. try
  249. {
  250. altName = GeneralNames.GetInstance(
  251. PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.SubjectAlternativeName));
  252. }
  253. catch (Exception e)
  254. {
  255. throw new PkixCertPathValidatorException(
  256. "Subject alternative name extension could not be decoded.", e, index);
  257. }
  258. var emails = X509Name.GetInstance(dns).GetValueList(X509Name.EmailAddress);
  259. foreach (string email in emails)
  260. {
  261. GeneralName emailAsGeneralName = new GeneralName(GeneralName.Rfc822Name, email);
  262. try
  263. {
  264. nameConstraintValidator.checkPermitted(emailAsGeneralName);
  265. nameConstraintValidator.checkExcluded(emailAsGeneralName);
  266. }
  267. catch (PkixNameConstraintValidatorException ex)
  268. {
  269. throw new PkixCertPathValidatorException(
  270. "Subtree check for certificate subject alternative email failed.", ex, index);
  271. }
  272. }
  273. if (altName != null)
  274. {
  275. GeneralName[] genNames = null;
  276. try
  277. {
  278. genNames = altName.GetNames();
  279. }
  280. catch (Exception e)
  281. {
  282. throw new PkixCertPathValidatorException(
  283. "Subject alternative name contents could not be decoded.", e, index);
  284. }
  285. foreach (GeneralName genName in genNames)
  286. {
  287. try
  288. {
  289. nameConstraintValidator.checkPermitted(genName);
  290. nameConstraintValidator.checkExcluded(genName);
  291. }
  292. catch (PkixNameConstraintValidatorException e)
  293. {
  294. throw new PkixCertPathValidatorException(
  295. "Subtree check for certificate subject alternative name failed.", e, index);
  296. }
  297. }
  298. }
  299. }
  300. }
  301. /// <exception cref="PkixCertPathValidatorException"/>
  302. internal static void PrepareNextCertA(PkixCertPath certPath, int index)
  303. {
  304. var certs = certPath.Certificates;
  305. X509Certificate cert = certs[index];
  306. //
  307. //
  308. // (a) check the policy mappings
  309. //
  310. Asn1Sequence pm;
  311. try
  312. {
  313. pm = Asn1Sequence.GetInstance(
  314. PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.PolicyMappings));
  315. }
  316. catch (Exception ex)
  317. {
  318. throw new PkixCertPathValidatorException(
  319. "Policy mappings extension could not be decoded.", ex, index);
  320. }
  321. if (pm != null)
  322. {
  323. Asn1Sequence mappings = pm;
  324. for (int j = 0; j < mappings.Count; j++)
  325. {
  326. DerObjectIdentifier issuerDomainPolicy;
  327. DerObjectIdentifier subjectDomainPolicy;
  328. try
  329. {
  330. Asn1Sequence mapping = Asn1Sequence.GetInstance(mappings[j]);
  331. issuerDomainPolicy = DerObjectIdentifier.GetInstance(mapping[0]);
  332. subjectDomainPolicy = DerObjectIdentifier.GetInstance(mapping[1]);
  333. }
  334. catch (Exception e)
  335. {
  336. throw new PkixCertPathValidatorException(
  337. "Policy mappings extension contents could not be decoded.", e, index);
  338. }
  339. if (ANY_POLICY.Equals(issuerDomainPolicy.Id))
  340. throw new PkixCertPathValidatorException(
  341. "IssuerDomainPolicy is anyPolicy", null, index);
  342. if (ANY_POLICY.Equals(subjectDomainPolicy.Id))
  343. throw new PkixCertPathValidatorException(
  344. "SubjectDomainPolicy is anyPolicy,", null, index);
  345. }
  346. }
  347. }
  348. /// <exception cref="PkixCertPathValidatorException"/>
  349. internal static PkixPolicyNode ProcessCertD(PkixCertPath certPath, int index, ISet<string> acceptablePolicies,
  350. PkixPolicyNode validPolicyTree, IList<PkixPolicyNode>[] policyNodes, int inhibitAnyPolicy)
  351. {
  352. var certs = certPath.Certificates;
  353. X509Certificate cert = certs[index];
  354. int n = certs.Count;
  355. // i as defined in the algorithm description
  356. int i = n - index;
  357. //
  358. // (d) policy Information checking against initial policy and
  359. // policy mapping
  360. //
  361. Asn1Sequence certPolicies;
  362. try
  363. {
  364. certPolicies = Asn1Sequence.GetInstance(
  365. PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.CertificatePolicies));
  366. }
  367. catch (Exception e)
  368. {
  369. throw new PkixCertPathValidatorException(
  370. "Could not read certificate policies extension from certificate.", e, index);
  371. }
  372. if (certPolicies != null && validPolicyTree != null)
  373. {
  374. //
  375. // (d) (1)
  376. //
  377. var pols = new HashSet<string>();
  378. foreach (Asn1Encodable ae in certPolicies)
  379. {
  380. PolicyInformation pInfo = PolicyInformation.GetInstance(ae.ToAsn1Object());
  381. DerObjectIdentifier pOid = pInfo.PolicyIdentifier;
  382. pols.Add(pOid.Id);
  383. if (!ANY_POLICY.Equals(pOid.Id))
  384. {
  385. ISet<PolicyQualifierInfo> pq;
  386. try
  387. {
  388. pq = PkixCertPathValidatorUtilities.GetQualifierSet(pInfo.PolicyQualifiers);
  389. }
  390. catch (PkixCertPathValidatorException ex)
  391. {
  392. throw new PkixCertPathValidatorException(
  393. "Policy qualifier info set could not be build.", ex, index);
  394. }
  395. bool match = PkixCertPathValidatorUtilities.ProcessCertD1i(i, policyNodes, pOid, pq);
  396. if (!match)
  397. {
  398. PkixCertPathValidatorUtilities.ProcessCertD1ii(i, policyNodes, pOid, pq);
  399. }
  400. }
  401. }
  402. if (acceptablePolicies.Count < 1 || acceptablePolicies.Contains(ANY_POLICY))
  403. {
  404. acceptablePolicies.Clear();
  405. acceptablePolicies.UnionWith(pols);
  406. }
  407. else
  408. {
  409. var t1 = new HashSet<string>();
  410. foreach (var o in acceptablePolicies)
  411. {
  412. if (pols.Contains(o))
  413. {
  414. t1.Add(o);
  415. }
  416. }
  417. acceptablePolicies.Clear();
  418. acceptablePolicies.UnionWith(t1);
  419. }
  420. //
  421. // (d) (2)
  422. //
  423. if ((inhibitAnyPolicy > 0) || ((i < n) && PkixCertPathValidatorUtilities.IsSelfIssued(cert)))
  424. {
  425. foreach (Asn1Encodable ae in certPolicies)
  426. {
  427. PolicyInformation pInfo = PolicyInformation.GetInstance(ae.ToAsn1Object());
  428. if (ANY_POLICY.Equals(pInfo.PolicyIdentifier.Id))
  429. {
  430. var _apq = PkixCertPathValidatorUtilities.GetQualifierSet(pInfo.PolicyQualifiers);
  431. foreach (var _node in policyNodes[i - 1])
  432. {
  433. foreach (var _policy in _node.ExpectedPolicies)
  434. {
  435. bool _found = false;
  436. foreach (PkixPolicyNode _child in _node.Children)
  437. {
  438. if (_policy.Equals(_child.ValidPolicy))
  439. {
  440. _found = true;
  441. break;
  442. }
  443. }
  444. if (!_found)
  445. {
  446. var _newChildExpectedPolicies = new HashSet<string>();
  447. _newChildExpectedPolicies.Add(_policy);
  448. var _newChild = new PkixPolicyNode(new List<PkixPolicyNode>(), i,
  449. _newChildExpectedPolicies, _node, _apq, _policy, false);
  450. _node.AddChild(_newChild);
  451. policyNodes[i].Add(_newChild);
  452. }
  453. }
  454. }
  455. break;
  456. }
  457. }
  458. }
  459. PkixPolicyNode _validPolicyTree = validPolicyTree;
  460. //
  461. // (d) (3)
  462. //
  463. for (int j = i - 1; j >= 0; j--)
  464. {
  465. var nodes = policyNodes[j];
  466. for (int k = 0; k < nodes.Count; k++)
  467. {
  468. var node = nodes[k];
  469. if (!node.HasChildren)
  470. {
  471. _validPolicyTree = PkixCertPathValidatorUtilities.RemovePolicyNode(_validPolicyTree,
  472. policyNodes, node);
  473. if (_validPolicyTree == null)
  474. break;
  475. }
  476. }
  477. }
  478. //
  479. // d (4)
  480. //
  481. var criticalExtensionOids = cert.GetCriticalExtensionOids();
  482. if (criticalExtensionOids != null)
  483. {
  484. bool critical = criticalExtensionOids.Contains(X509Extensions.CertificatePolicies.Id);
  485. foreach (var node in policyNodes[i])
  486. {
  487. node.IsCritical = critical;
  488. }
  489. }
  490. return _validPolicyTree;
  491. }
  492. return null;
  493. }
  494. /**
  495. * If the DP includes cRLIssuer, then verify that the issuer field in the
  496. * complete CRL matches cRLIssuer in the DP and that the complete CRL
  497. * contains an
  498. * g distribution point extension with the indirectCRL
  499. * boolean asserted. Otherwise, verify that the CRL issuer matches the
  500. * certificate issuer.
  501. *
  502. * @param dp The distribution point.
  503. * @param cert The certificate ot attribute certificate.
  504. * @param crl The CRL for <code>cert</code>.
  505. * @throws AnnotatedException if one of the above conditions does not apply or an error
  506. * occurs.
  507. */
  508. internal static void ProcessCrlB1(DistributionPoint dp, object cert, X509Crl crl)
  509. {
  510. Asn1Object idp = PkixCertPathValidatorUtilities.GetExtensionValue(
  511. crl, X509Extensions.IssuingDistributionPoint);
  512. bool isIndirect = false;
  513. if (idp != null)
  514. {
  515. if (IssuingDistributionPoint.GetInstance(idp).IsIndirectCrl)
  516. {
  517. isIndirect = true;
  518. }
  519. }
  520. byte[] issuerBytes = crl.IssuerDN.GetEncoded();
  521. bool matchIssuer = false;
  522. if (dp.CrlIssuer != null)
  523. {
  524. GeneralName[] genNames = dp.CrlIssuer.GetNames();
  525. for (int j = 0; j < genNames.Length; j++)
  526. {
  527. if (genNames[j].TagNo == GeneralName.DirectoryName)
  528. {
  529. try
  530. {
  531. if (Arrays.AreEqual(genNames[j].Name.GetEncoded(), issuerBytes))
  532. {
  533. matchIssuer = true;
  534. }
  535. }
  536. catch (IOException e)
  537. {
  538. throw new Exception(
  539. "CRL issuer information from distribution point cannot be decoded.", e);
  540. }
  541. }
  542. }
  543. if (matchIssuer && !isIndirect)
  544. {
  545. throw new Exception("Distribution point contains cRLIssuer field but CRL is not indirect.");
  546. }
  547. if (!matchIssuer)
  548. {
  549. throw new Exception("CRL issuer of CRL does not match CRL issuer of distribution point.");
  550. }
  551. }
  552. else
  553. {
  554. if (crl.IssuerDN.Equivalent(PkixCertPathValidatorUtilities.GetIssuerPrincipal(cert), true))
  555. {
  556. matchIssuer = true;
  557. }
  558. }
  559. if (!matchIssuer)
  560. {
  561. throw new Exception("Cannot find matching CRL issuer for certificate.");
  562. }
  563. }
  564. internal static ReasonsMask ProcessCrlD(X509Crl crl, DistributionPoint dp)
  565. //throws AnnotatedException
  566. {
  567. IssuingDistributionPoint idp;
  568. try
  569. {
  570. idp = IssuingDistributionPoint.GetInstance(PkixCertPathValidatorUtilities.GetExtensionValue(crl, X509Extensions.IssuingDistributionPoint));
  571. }
  572. catch (Exception e)
  573. {
  574. throw new Exception("issuing distribution point extension could not be decoded.", e);
  575. }
  576. // (d) (1)
  577. if (idp != null && idp.OnlySomeReasons != null && dp.Reasons != null)
  578. {
  579. return new ReasonsMask(dp.Reasons.IntValue).Intersect(new ReasonsMask(idp.OnlySomeReasons.IntValue));
  580. }
  581. // (d) (4)
  582. if ((idp == null || idp.OnlySomeReasons == null) && dp.Reasons == null)
  583. {
  584. return ReasonsMask.AllReasons;
  585. }
  586. // (d) (2) and (d)(3)
  587. ReasonsMask dpReasons;
  588. if (dp.Reasons == null)
  589. {
  590. dpReasons = ReasonsMask.AllReasons;
  591. }
  592. else
  593. {
  594. dpReasons = new ReasonsMask(dp.Reasons.IntValue);
  595. }
  596. ReasonsMask idpReasons;
  597. if (idp == null)
  598. {
  599. idpReasons = ReasonsMask.AllReasons;
  600. }
  601. else
  602. {
  603. idpReasons = new ReasonsMask(idp.OnlySomeReasons.IntValue);
  604. }
  605. return dpReasons.Intersect(idpReasons);
  606. }
  607. /**
  608. * Obtain and validate the certification path for the complete CRL issuer.
  609. * If a key usage extension is present in the CRL issuer's certificate,
  610. * verify that the cRLSign bit is set.
  611. *
  612. * @param crl CRL which contains revocation information for the certificate
  613. * <code>cert</code>.
  614. * @param cert The attribute certificate or certificate to check if it is
  615. * revoked.
  616. * @param defaultCRLSignCert The issuer certificate of the certificate <code>cert</code>.
  617. * @param defaultCRLSignKey The public key of the issuer certificate
  618. * <code>defaultCRLSignCert</code>.
  619. * @param paramsPKIX paramsPKIX PKIX parameters.
  620. * @param certPathCerts The certificates on the certification path.
  621. * @return A <code>Set</code> with all keys of possible CRL issuer
  622. * certificates.
  623. * @throws AnnotatedException if the CRL is not valid or the status cannot be checked or
  624. * some error occurs.
  625. */
  626. internal static ISet<AsymmetricKeyParameter> ProcessCrlF(
  627. X509Crl crl,
  628. object cert,
  629. X509Certificate defaultCRLSignCert,
  630. AsymmetricKeyParameter defaultCRLSignKey,
  631. PkixParameters paramsPKIX,
  632. IList<X509Certificate> certPathCerts)
  633. {
  634. // (f)
  635. // get issuer from CRL
  636. X509CertStoreSelector certSelector = new X509CertStoreSelector();
  637. try
  638. {
  639. certSelector.Subject = crl.IssuerDN;
  640. }
  641. catch (IOException e)
  642. {
  643. throw new Exception(
  644. "Subject criteria for certificate selector to find issuer certificate for CRL could not be set.", e);
  645. }
  646. // get CRL signing certs
  647. var signingCerts = new HashSet<X509Certificate>();
  648. try
  649. {
  650. CollectionUtilities.CollectMatches(signingCerts, certSelector, paramsPKIX.GetStoresCert());
  651. }
  652. catch (Exception e)
  653. {
  654. throw new Exception("Issuer certificate for CRL cannot be searched.", e);
  655. }
  656. signingCerts.Add(defaultCRLSignCert);
  657. var validCerts = new List<X509Certificate>();
  658. var validKeys = new List<AsymmetricKeyParameter>();
  659. foreach (X509Certificate signingCert in signingCerts)
  660. {
  661. /*
  662. * CA of the certificate, for which this CRL is checked, has also
  663. * signed CRL, so skip the path validation, because is already done
  664. */
  665. if (signingCert.Equals(defaultCRLSignCert))
  666. {
  667. validCerts.Add(signingCert);
  668. validKeys.Add(defaultCRLSignKey);
  669. continue;
  670. }
  671. try
  672. {
  673. PkixCertPathBuilder builder = new PkixCertPathBuilder();
  674. certSelector = new X509CertStoreSelector();
  675. certSelector.Certificate = signingCert;
  676. PkixBuilderParameters parameters = PkixBuilderParameters.GetInstance(paramsPKIX);
  677. parameters.SetTargetConstraintsCert(certSelector);
  678. /*
  679. * if signingCert is placed not higher on the cert path a
  680. * dependency loop results. CRL for cert is checked, but
  681. * signingCert is needed for checking the CRL which is dependent
  682. * on checking cert because it is higher in the cert path and so
  683. * signing signingCert transitively. so, revocation is disabled,
  684. * forgery attacks of the CRL are detected in this outer loop
  685. * for all other it must be enabled to prevent forgery attacks
  686. */
  687. if (certPathCerts.Contains(signingCert))
  688. {
  689. parameters.IsRevocationEnabled = false;
  690. }
  691. else
  692. {
  693. parameters.IsRevocationEnabled = true;
  694. }
  695. var certs = builder.Build(parameters).CertPath.Certificates;
  696. validCerts.Add(signingCert);
  697. validKeys.Add(PkixCertPathValidatorUtilities.GetNextWorkingKey(certs, 0));
  698. }
  699. catch (PkixCertPathBuilderException e)
  700. {
  701. throw new Exception("CertPath for CRL signer failed to validate.", e);
  702. }
  703. catch (PkixCertPathValidatorException e)
  704. {
  705. throw new Exception("Public key of issuer certificate of CRL could not be retrieved.", e);
  706. }
  707. }
  708. var checkKeys = new HashSet<AsymmetricKeyParameter>();
  709. Exception lastException = null;
  710. for (int i = 0; i < validCerts.Count; i++)
  711. {
  712. X509Certificate signCert = (X509Certificate)validCerts[i];
  713. bool[] keyusage = signCert.GetKeyUsage();
  714. if (keyusage != null && (keyusage.Length < 7 || !keyusage[CRL_SIGN]))
  715. {
  716. lastException = new Exception(
  717. "Issuer certificate key usage extension does not permit CRL signing.");
  718. }
  719. else
  720. {
  721. checkKeys.Add(validKeys[i]);
  722. }
  723. }
  724. if ((checkKeys.Count == 0) && lastException == null)
  725. {
  726. throw new Exception("Cannot find a valid issuer certificate.");
  727. }
  728. if ((checkKeys.Count == 0) && lastException != null)
  729. {
  730. throw lastException;
  731. }
  732. return checkKeys;
  733. }
  734. internal static AsymmetricKeyParameter ProcessCrlG(X509Crl crl, ISet<AsymmetricKeyParameter> keys)
  735. {
  736. Exception lastException = null;
  737. foreach (AsymmetricKeyParameter key in keys)
  738. {
  739. try
  740. {
  741. crl.Verify(key);
  742. return key;
  743. }
  744. catch (Exception e)
  745. {
  746. lastException = e;
  747. }
  748. }
  749. throw new Exception("Cannot verify CRL.", lastException);
  750. }
  751. internal static X509Crl ProcessCrlH(ISet<X509Crl> deltaCrls, AsymmetricKeyParameter key)
  752. {
  753. Exception lastException = null;
  754. foreach (X509Crl crl in deltaCrls)
  755. {
  756. try
  757. {
  758. crl.Verify(key);
  759. return crl;
  760. }
  761. catch (Exception e)
  762. {
  763. lastException = e;
  764. }
  765. }
  766. if (lastException != null)
  767. {
  768. throw new Exception("Cannot verify delta CRL.", lastException);
  769. }
  770. return null;
  771. }
  772. /**
  773. * Checks a distribution point for revocation information for the
  774. * certificate <code>cert</code>.
  775. *
  776. * @param dp The distribution point to consider.
  777. * @param paramsPKIX PKIX parameters.
  778. * @param cert Certificate to check if it is revoked.
  779. * @param validDate The date when the certificate revocation status should be
  780. * checked.
  781. * @param defaultCRLSignCert The issuer certificate of the certificate <code>cert</code>.
  782. * @param defaultCRLSignKey The public key of the issuer certificate
  783. * <code>defaultCRLSignCert</code>.
  784. * @param certStatus The current certificate revocation status.
  785. * @param reasonMask The reasons mask which is already checked.
  786. * @param certPathCerts The certificates of the certification path.
  787. * @throws AnnotatedException if the certificate is revoked or the status cannot be checked
  788. * or some error occurs.
  789. */
  790. private static void CheckCrl(
  791. DistributionPoint dp,
  792. PkixParameters paramsPKIX,
  793. X509Certificate cert,
  794. DateTime validDate,
  795. X509Certificate defaultCRLSignCert,
  796. AsymmetricKeyParameter defaultCRLSignKey,
  797. CertStatus certStatus,
  798. ReasonsMask reasonMask,
  799. IList<X509Certificate> certPathCerts)
  800. {
  801. DateTime currentDate = DateTime.UtcNow;
  802. if (validDate.Ticks > currentDate.Ticks)
  803. {
  804. throw new Exception("Validation time is in future.");
  805. }
  806. // (a)
  807. /*
  808. * We always get timely valid CRLs, so there is no step (a) (1).
  809. * "locally cached" CRLs are assumed to be in getStore(), additional
  810. * CRLs must be enabled in the ExtendedPKIXParameters and are in
  811. * getAdditionalStore()
  812. */
  813. ISet<X509Crl> crls = PkixCertPathValidatorUtilities.GetCompleteCrls(dp, cert, currentDate, paramsPKIX);
  814. bool validCrlFound = false;
  815. Exception lastException = null;
  816. var crl_iter = crls.GetEnumerator();
  817. while (crl_iter.MoveNext() && certStatus.Status == CertStatus.Unrevoked && !reasonMask.IsAllReasons)
  818. {
  819. try
  820. {
  821. X509Crl crl = crl_iter.Current;
  822. // (d)
  823. ReasonsMask interimReasonsMask = ProcessCrlD(crl, dp);
  824. // (e)
  825. /*
  826. * The reasons mask is updated at the end, so only valid CRLs
  827. * can update it. If this CRL does not contain new reasons it
  828. * must be ignored.
  829. */
  830. if (!interimReasonsMask.HasNewReasons(reasonMask))
  831. {
  832. continue;
  833. }
  834. // (f)
  835. var keys = ProcessCrlF(crl, cert, defaultCRLSignCert, defaultCRLSignKey, paramsPKIX, certPathCerts);
  836. // (g)
  837. AsymmetricKeyParameter key = ProcessCrlG(crl, keys);
  838. X509Crl deltaCRL = null;
  839. if (paramsPKIX.IsUseDeltasEnabled)
  840. {
  841. // get delta CRLs
  842. ISet<X509Crl> deltaCRLs = PkixCertPathValidatorUtilities.GetDeltaCrls(currentDate, paramsPKIX, crl);
  843. // we only want one valid delta CRL
  844. // (h)
  845. deltaCRL = ProcessCrlH(deltaCRLs, key);
  846. }
  847. /*
  848. * CRL must be be valid at the current time, not the validation
  849. * time. If a certificate is revoked with reason keyCompromise,
  850. * cACompromise, it can be used for forgery, also for the past.
  851. * This reason may not be contained in older CRLs.
  852. */
  853. /*
  854. * in the chain model signatures stay valid also after the
  855. * certificate has been expired, so they do not have to be in
  856. * the CRL validity time
  857. */
  858. if (paramsPKIX.ValidityModel != PkixParameters.ChainValidityModel)
  859. {
  860. /*
  861. * if a certificate has expired, but was revoked, it is not
  862. * more in the CRL, so it would be regarded as valid if the
  863. * first check is not done
  864. */
  865. if (cert.NotAfter.Ticks < crl.ThisUpdate.Ticks)
  866. {
  867. throw new Exception("No valid CRL for current time found.");
  868. }
  869. }
  870. ProcessCrlB1(dp, cert, crl);
  871. // (b) (2)
  872. ProcessCrlB2(dp, cert, crl);
  873. // (c)
  874. ProcessCrlC(deltaCRL, crl, paramsPKIX);
  875. // (i)
  876. ProcessCrlI(validDate, deltaCRL, cert, certStatus, paramsPKIX);
  877. // (j)
  878. ProcessCrlJ(validDate, crl, cert, certStatus);
  879. // (k)
  880. if (certStatus.Status == CrlReason.RemoveFromCrl)
  881. {
  882. certStatus.Status = CertStatus.Unrevoked;
  883. }
  884. // update reasons mask
  885. reasonMask.AddReasons(interimReasonsMask);
  886. var criticalExtensions = crl.GetCriticalExtensionOids();
  887. if (criticalExtensions != null)
  888. {
  889. criticalExtensions = new HashSet<string>(criticalExtensions);
  890. criticalExtensions.Remove(X509Extensions.IssuingDistributionPoint.Id);
  891. criticalExtensions.Remove(X509Extensions.DeltaCrlIndicator.Id);
  892. if (criticalExtensions.Count > 0)
  893. throw new Exception("CRL contains unsupported critical extensions.");
  894. }
  895. if (deltaCRL != null)
  896. {
  897. criticalExtensions = deltaCRL.GetCriticalExtensionOids();
  898. if (criticalExtensions != null)
  899. {
  900. criticalExtensions = new HashSet<string>(criticalExtensions);
  901. criticalExtensions.Remove(X509Extensions.IssuingDistributionPoint.Id);
  902. criticalExtensions.Remove(X509Extensions.DeltaCrlIndicator.Id);
  903. if (criticalExtensions.Count > 0)
  904. throw new Exception("Delta CRL contains unsupported critical extension.");
  905. }
  906. }
  907. validCrlFound = true;
  908. }
  909. catch (Exception e)
  910. {
  911. lastException = e;
  912. }
  913. }
  914. if (!validCrlFound)
  915. {
  916. throw lastException;
  917. }
  918. }
  919. /**
  920. * Checks a certificate if it is revoked.
  921. *
  922. * @param paramsPKIX PKIX parameters.
  923. * @param cert Certificate to check if it is revoked.
  924. * @param validDate The date when the certificate revocation status should be
  925. * checked.
  926. * @param sign The issuer certificate of the certificate <code>cert</code>.
  927. * @param workingPublicKey The public key of the issuer certificate <code>sign</code>.
  928. * @param certPathCerts The certificates of the certification path.
  929. * @throws AnnotatedException if the certificate is revoked or the status cannot be checked
  930. * or some error occurs.
  931. */
  932. internal static void CheckCrls(
  933. PkixParameters paramsPKIX,
  934. X509Certificate cert,
  935. DateTime validDate,
  936. X509Certificate sign,
  937. AsymmetricKeyParameter workingPublicKey,
  938. IList<X509Certificate> certPathCerts)
  939. {
  940. Exception lastException = null;
  941. CrlDistPoint crldp;
  942. try
  943. {
  944. crldp = CrlDistPoint.GetInstance(PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.CrlDistributionPoints));
  945. }
  946. catch (Exception e)
  947. {
  948. throw new Exception("CRL distribution point extension could not be read.", e);
  949. }
  950. try
  951. {
  952. PkixCertPathValidatorUtilities.AddAdditionalStoresFromCrlDistributionPoint(crldp, paramsPKIX);
  953. }
  954. catch (Exception e)
  955. {
  956. throw new Exception(
  957. "No additional CRL locations could be decoded from CRL distribution point extension.", e);
  958. }
  959. CertStatus certStatus = new CertStatus();
  960. ReasonsMask reasonsMask = new ReasonsMask();
  961. bool validCrlFound = false;
  962. // for each distribution point
  963. if (crldp != null)
  964. {
  965. DistributionPoint[] dps;
  966. try
  967. {
  968. dps = crldp.GetDistributionPoints();
  969. }
  970. catch (Exception e)
  971. {
  972. throw new Exception("Distribution points could not be read.", e);
  973. }
  974. if (dps != null)
  975. {
  976. for (int i = 0; i < dps.Length && certStatus.Status == CertStatus.Unrevoked && !reasonsMask.IsAllReasons; i++)
  977. {
  978. PkixParameters paramsPKIXClone = (PkixParameters)paramsPKIX.Clone();
  979. try
  980. {
  981. CheckCrl(dps[i], paramsPKIXClone, cert, validDate, sign, workingPublicKey, certStatus,
  982. reasonsMask, certPathCerts);
  983. validCrlFound = true;
  984. }
  985. catch (Exception e)
  986. {
  987. lastException = e;
  988. }
  989. }
  990. }
  991. }
  992. /*
  993. * If the revocation status has not been determined, repeat the process
  994. * above with any available CRLs not specified in a distribution point
  995. * but issued by the certificate issuer.
  996. */
  997. if (certStatus.Status == CertStatus.Unrevoked && !reasonsMask.IsAllReasons)
  998. {
  999. try
  1000. {
  1001. /*
  1002. * assume a DP with both the reasons and the cRLIssuer fields
  1003. * omitted and a distribution point name of the certificate
  1004. * issuer.
  1005. */
  1006. X509Name issuer;
  1007. try
  1008. {
  1009. issuer = X509Name.GetInstance(cert.IssuerDN.GetEncoded());
  1010. }
  1011. catch (Exception e)
  1012. {
  1013. throw new Exception("Issuer from certificate for CRL could not be reencoded.", e);
  1014. }
  1015. DistributionPoint dp = new DistributionPoint(new DistributionPointName(0, new GeneralNames(
  1016. new GeneralName(GeneralName.DirectoryName, issuer))), null, null);
  1017. PkixParameters paramsPKIXClone = (PkixParameters)paramsPKIX.Clone();
  1018. CheckCrl(dp, paramsPKIXClone, cert, validDate, sign, workingPublicKey, certStatus, reasonsMask,
  1019. certPathCerts);
  1020. validCrlFound = true;
  1021. }
  1022. catch (Exception e)
  1023. {
  1024. lastException = e;
  1025. }
  1026. }
  1027. if (!validCrlFound)
  1028. {
  1029. throw lastException;
  1030. }
  1031. if (certStatus.Status != CertStatus.Unrevoked)
  1032. {
  1033. // This format is enforced by the NistCertPath tests
  1034. string formattedDate = certStatus.RevocationDate.Value.ToString(
  1035. "ddd MMM dd HH:mm:ss K yyyy");
  1036. string message = "Certificate revocation after " + formattedDate;
  1037. message += ", reason: " + CrlReasons[certStatus.Status];
  1038. throw new Exception(message);
  1039. }
  1040. if (!reasonsMask.IsAllReasons && certStatus.Status == CertStatus.Unrevoked)
  1041. {
  1042. certStatus.Status = CertStatus.Undetermined;
  1043. }
  1044. if (certStatus.Status == CertStatus.Undetermined)
  1045. {
  1046. throw new Exception("Certificate status could not be determined.");
  1047. }
  1048. }
  1049. /// <exception cref="PkixCertPathValidatorException"/>
  1050. internal static PkixPolicyNode PrepareCertB(PkixCertPath certPath, int index,
  1051. IList<PkixPolicyNode>[] policyNodes, PkixPolicyNode validPolicyTree, int policyMapping)
  1052. {
  1053. var certs = certPath.Certificates;
  1054. X509Certificate cert = certs[index];
  1055. int n = certs.Count;
  1056. // i as defined in the algorithm description
  1057. int i = n - index;
  1058. // (b)
  1059. //
  1060. Asn1Sequence pm;
  1061. try
  1062. {
  1063. pm = Asn1Sequence.GetInstance(
  1064. PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.PolicyMappings));
  1065. }
  1066. catch (Exception ex)
  1067. {
  1068. throw new PkixCertPathValidatorException(
  1069. "Policy mappings extension could not be decoded.", ex, index);
  1070. }
  1071. PkixPolicyNode _validPolicyTree = validPolicyTree;
  1072. if (pm != null)
  1073. {
  1074. Asn1Sequence mappings = pm;
  1075. var m_idp = new Dictionary<string, ISet<string>>();
  1076. var s_idp = new HashSet<string>();
  1077. for (int j = 0; j < mappings.Count; j++)
  1078. {
  1079. Asn1Sequence mapping = (Asn1Sequence)mappings[j];
  1080. string id_p = ((DerObjectIdentifier)mapping[0]).Id;
  1081. string sd_p = ((DerObjectIdentifier)mapping[1]).Id;
  1082. ISet<string> tmp;
  1083. if (m_idp.TryGetValue(id_p, out tmp))
  1084. {
  1085. tmp.Add(sd_p);
  1086. }
  1087. else
  1088. {
  1089. tmp = new HashSet<string>();
  1090. tmp.Add(sd_p);
  1091. m_idp[id_p] = tmp;
  1092. s_idp.Add(id_p);
  1093. }
  1094. }
  1095. foreach (var id_p in s_idp)
  1096. {
  1097. //
  1098. // (1)
  1099. //
  1100. if (policyMapping > 0)
  1101. {
  1102. bool idp_found = false;
  1103. foreach (PkixPolicyNode node in policyNodes[i])
  1104. {
  1105. if (node.ValidPolicy.Equals(id_p))
  1106. {
  1107. idp_found = true;
  1108. node.ExpectedPolicies = CollectionUtilities.GetValueOrNull(m_idp, id_p);
  1109. break;
  1110. }
  1111. }
  1112. if (!idp_found)
  1113. {
  1114. foreach (PkixPolicyNode node in policyNodes[i])
  1115. {
  1116. if (ANY_POLICY.Equals(node.ValidPolicy))
  1117. {
  1118. Asn1Sequence policies = null;
  1119. try
  1120. {
  1121. policies = (Asn1Sequence)PkixCertPathValidatorUtilities.GetExtensionValue(cert,
  1122. X509Extensions.CertificatePolicies);
  1123. }
  1124. catch (Exception e)
  1125. {
  1126. throw new PkixCertPathValidatorException(
  1127. "Certificate policies extension could not be decoded.", e, index);
  1128. }
  1129. ISet<PolicyQualifierInfo> pq = null;
  1130. foreach (Asn1Encodable ae in policies)
  1131. {
  1132. PolicyInformation pinfo = null;
  1133. try
  1134. {
  1135. pinfo = PolicyInformation.GetInstance(ae.ToAsn1Object());
  1136. }
  1137. catch (Exception ex)
  1138. {
  1139. throw new PkixCertPathValidatorException(
  1140. "Policy information could not be decoded.", ex, index);
  1141. }
  1142. if (ANY_POLICY.Equals(pinfo.PolicyIdentifier.Id))
  1143. {
  1144. try
  1145. {
  1146. pq = PkixCertPathValidatorUtilities
  1147. .GetQualifierSet(pinfo.PolicyQualifiers);
  1148. }
  1149. catch (PkixCertPathValidatorException ex)
  1150. {
  1151. throw new PkixCertPathValidatorException(
  1152. "Policy qualifier info set could not be decoded.", ex, index);
  1153. }
  1154. break;
  1155. }
  1156. }
  1157. bool ci = false;
  1158. var critExtOids = cert.GetCriticalExtensionOids();
  1159. if (critExtOids != null)
  1160. {
  1161. ci = critExtOids.Contains(X509Extensions.CertificatePolicies.Id);
  1162. }
  1163. PkixPolicyNode p_node = node.Parent;
  1164. if (ANY_POLICY.Equals(p_node.ValidPolicy))
  1165. {
  1166. var c_node = new PkixPolicyNode(new List<PkixPolicyNode>(), i,
  1167. CollectionUtilities.GetValueOrNull(m_idp, id_p), p_node, pq, id_p, ci);
  1168. p_node.AddChild(c_node);
  1169. policyNodes[i].Add(c_node);
  1170. }
  1171. break;
  1172. }
  1173. }
  1174. }
  1175. //
  1176. // (2)
  1177. //
  1178. }
  1179. else if (policyMapping <= 0)
  1180. {
  1181. foreach (var node in new List<PkixPolicyNode>(policyNodes[i]))
  1182. {
  1183. if (node.ValidPolicy.Equals(id_p))
  1184. {
  1185. node.Parent.RemoveChild(node);
  1186. for (int k = i - 1; k >= 0; k--)
  1187. {
  1188. foreach (var node2 in new List<PkixPolicyNode>(policyNodes[k]))
  1189. {
  1190. if (!node2.HasChildren)
  1191. {
  1192. _validPolicyTree = PkixCertPathValidatorUtilities.RemovePolicyNode(
  1193. _validPolicyTree, policyNodes, node2);
  1194. if (_validPolicyTree == null)
  1195. break;
  1196. }
  1197. }
  1198. }
  1199. }
  1200. }
  1201. }
  1202. }
  1203. }
  1204. return _validPolicyTree;
  1205. }
  1206. internal static ISet<X509Crl>[] ProcessCrlA1ii(
  1207. DateTime currentDate,
  1208. PkixParameters paramsPKIX,
  1209. X509Certificate cert,
  1210. X509Crl crl)
  1211. {
  1212. X509CrlStoreSelector crlselect = new X509CrlStoreSelector();
  1213. crlselect.CertificateChecking = cert;
  1214. try
  1215. {
  1216. var issuer = new List<X509Name>();
  1217. issuer.Add(crl.IssuerDN);
  1218. crlselect.Issuers = issuer;
  1219. }
  1220. catch (IOException e)
  1221. {
  1222. throw new Exception("Cannot extract issuer from CRL." + e, e);
  1223. }
  1224. crlselect.CompleteCrlEnabled = true;
  1225. ISet<X509Crl> completeSet = CrlUtilities.FindCrls(crlselect, paramsPKIX, currentDate);
  1226. var deltaSet = new HashSet<X509Crl>();
  1227. if (paramsPKIX.IsUseDeltasEnabled)
  1228. {
  1229. // get delta CRL(s)
  1230. try
  1231. {
  1232. deltaSet.UnionWith(PkixCertPathValidatorUtilities.GetDeltaCrls(currentDate, paramsPKIX, crl));
  1233. }
  1234. catch (Exception e)
  1235. {
  1236. throw new Exception("Exception obtaining delta CRLs.", e);
  1237. }
  1238. }
  1239. return new []{ completeSet, deltaSet };
  1240. }
  1241. internal static ISet<X509Crl> ProcessCrlA1i(
  1242. DateTime currentDate,
  1243. PkixParameters paramsPKIX,
  1244. X509Certificate cert,
  1245. X509Crl crl)
  1246. {
  1247. var deltaSet = new HashSet<X509Crl>();
  1248. if (paramsPKIX.IsUseDeltasEnabled)
  1249. {
  1250. CrlDistPoint freshestCRL;
  1251. try
  1252. {
  1253. freshestCRL = CrlDistPoint.GetInstance(
  1254. PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.FreshestCrl));
  1255. }
  1256. catch (Exception e)
  1257. {
  1258. throw new Exception("Freshest CRL extension could not be decoded from certificate.", e);
  1259. }
  1260. if (freshestCRL == null)
  1261. {
  1262. try
  1263. {
  1264. freshestCRL = CrlDistPoint.GetInstance(PkixCertPathValidatorUtilities.GetExtensionValue(crl,
  1265. X509Extensions.FreshestCrl));
  1266. }
  1267. catch (Exception e)
  1268. {
  1269. throw new Exception("Freshest CRL extension could not be decoded from CRL.", e);
  1270. }
  1271. }
  1272. if (freshestCRL != null)
  1273. {
  1274. try
  1275. {
  1276. PkixCertPathValidatorUtilities.AddAdditionalStoresFromCrlDistributionPoint(freshestCRL,
  1277. paramsPKIX);
  1278. }
  1279. catch (Exception e)
  1280. {
  1281. throw new Exception(
  1282. "No new delta CRL locations could be added from Freshest CRL extension.", e);
  1283. }
  1284. // get delta CRL(s)
  1285. try
  1286. {
  1287. deltaSet.UnionWith(PkixCertPathValidatorUtilities.GetDeltaCrls(currentDate, paramsPKIX, crl));
  1288. }
  1289. catch (Exception e)
  1290. {
  1291. throw new Exception("Exception obtaining delta CRLs.", e);
  1292. }
  1293. }
  1294. }
  1295. return deltaSet;
  1296. }
  1297. internal static void ProcessCertF(
  1298. PkixCertPath certPath,
  1299. int index,
  1300. PkixPolicyNode validPolicyTree,
  1301. int explicitPolicy)
  1302. {
  1303. //
  1304. // (f)
  1305. //
  1306. if (explicitPolicy <= 0 && validPolicyTree == null)
  1307. {
  1308. throw new PkixCertPathValidatorException(
  1309. "No valid policy tree found when one expected.", null, index);
  1310. }
  1311. }
  1312. internal static void ProcessCertA(
  1313. PkixCertPath certPath,
  1314. PkixParameters paramsPKIX,
  1315. int index,
  1316. AsymmetricKeyParameter workingPublicKey,
  1317. X509Name workingIssuerName,
  1318. X509Certificate sign)
  1319. {
  1320. var certs = certPath.Certificates;
  1321. X509Certificate cert = certs[index];
  1322. //
  1323. // (a) verify
  1324. //
  1325. try
  1326. {
  1327. // (a) (1)
  1328. //
  1329. cert.Verify(workingPublicKey);
  1330. }
  1331. catch (GeneralSecurityException e)
  1332. {
  1333. throw new PkixCertPathValidatorException("Could not validate certificate signature.", e, index);
  1334. }
  1335. try
  1336. {
  1337. // (a) (2)
  1338. //
  1339. cert.CheckValidity(PkixCertPathValidatorUtilities
  1340. .GetValidCertDateFromValidityModel(paramsPKIX, certPath, index));
  1341. }
  1342. catch (CertificateExpiredException e)
  1343. {
  1344. throw new PkixCertPathValidatorException("Could not validate certificate: " + e.Message, e, index);
  1345. }
  1346. catch (CertificateNotYetValidException e)
  1347. {
  1348. throw new PkixCertPathValidatorException("Could not validate certificate: " + e.Message, e, index);
  1349. }
  1350. catch (Exception e)
  1351. {
  1352. throw new PkixCertPathValidatorException("Could not validate time of certificate.", e, index);
  1353. }
  1354. //
  1355. // (a) (3)
  1356. //
  1357. if (paramsPKIX.IsRevocationEnabled)
  1358. {
  1359. try
  1360. {
  1361. CheckCrls(paramsPKIX, cert, PkixCertPathValidatorUtilities.GetValidCertDateFromValidityModel(paramsPKIX,
  1362. certPath, index), sign, workingPublicKey, certs);
  1363. }
  1364. catch (Exception e)
  1365. {
  1366. Exception cause = e.InnerException;
  1367. if (cause == null)
  1368. {
  1369. cause = e;
  1370. }
  1371. throw new PkixCertPathValidatorException(e.Message, cause, index);
  1372. }
  1373. }
  1374. //
  1375. // (a) (4) name chaining
  1376. //
  1377. X509Name issuer = PkixCertPathValidatorUtilities.GetIssuerPrincipal(cert);
  1378. if (!issuer.Equivalent(workingIssuerName, true))
  1379. {
  1380. throw new PkixCertPathValidatorException("IssuerName(" + issuer
  1381. + ") does not match SubjectName(" + workingIssuerName + ") of signing certificate.", null, index);
  1382. }
  1383. }
  1384. internal static int PrepareNextCertI1(PkixCertPath certPath, int index, int explicitPolicy)
  1385. {
  1386. var certs = certPath.Certificates;
  1387. X509Certificate cert = certs[index];
  1388. //
  1389. // (i)
  1390. //
  1391. Asn1Sequence pc;
  1392. try
  1393. {
  1394. pc = Asn1Sequence.GetInstance(
  1395. PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.PolicyConstraints));
  1396. }
  1397. catch (Exception e)
  1398. {
  1399. throw new PkixCertPathValidatorException(
  1400. "Policy constraints extension cannot be decoded.", e, index);
  1401. }
  1402. if (pc != null)
  1403. {
  1404. foreach (var policyConstraint in pc)
  1405. {
  1406. try
  1407. {
  1408. Asn1TaggedObject constraint = Asn1TaggedObject.GetInstance(policyConstraint);
  1409. if (constraint.HasContextTag(0))
  1410. {
  1411. int tmpInt = DerInteger.GetInstance(constraint, false).IntValueExact;
  1412. if (tmpInt < explicitPolicy)
  1413. return tmpInt;
  1414. break;
  1415. }
  1416. }
  1417. catch (ArgumentException e)
  1418. {
  1419. throw new PkixCertPathValidatorException(
  1420. "Policy constraints extension contents cannot be decoded.", e, index);
  1421. }
  1422. }
  1423. }
  1424. return explicitPolicy;
  1425. }
  1426. /// <exception cref="PkixCertPathValidatorException"/>
  1427. internal static int PrepareNextCertI2(
  1428. PkixCertPath certPath,
  1429. int index,
  1430. int policyMapping)
  1431. {
  1432. var certs = certPath.Certificates;
  1433. X509Certificate cert = certs[index];
  1434. //
  1435. // (i)
  1436. //
  1437. Asn1Sequence pc = null;
  1438. try
  1439. {
  1440. pc = Asn1Sequence.GetInstance(
  1441. PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.PolicyConstraints));
  1442. }
  1443. catch (Exception e)
  1444. {
  1445. throw new PkixCertPathValidatorException("Policy constraints extension cannot be decoded.", e, index);
  1446. }
  1447. if (pc != null)
  1448. {
  1449. foreach (var policyConstraint in pc)
  1450. {
  1451. try
  1452. {
  1453. Asn1TaggedObject constraint = Asn1TaggedObject.GetInstance(policyConstraint);
  1454. if (constraint.HasContextTag(1))
  1455. {
  1456. int tmpInt = DerInteger.GetInstance(constraint, false).IntValueExact;
  1457. if (tmpInt < policyMapping)
  1458. return tmpInt;
  1459. break;
  1460. }
  1461. }
  1462. catch (ArgumentException e)
  1463. {
  1464. throw new PkixCertPathValidatorException(
  1465. "Policy constraints extension contents cannot be decoded.", e, index);
  1466. }
  1467. }
  1468. }
  1469. return policyMapping;
  1470. }
  1471. /// <exception cref="PkixCertPathValidatorException"/>
  1472. internal static void PrepareNextCertG(
  1473. PkixCertPath certPath,
  1474. int index,
  1475. PkixNameConstraintValidator nameConstraintValidator)
  1476. {
  1477. var certs = certPath.Certificates;
  1478. X509Certificate cert = certs[index];
  1479. //
  1480. // (g) handle the name constraints extension
  1481. //
  1482. NameConstraints nc = null;
  1483. try
  1484. {
  1485. Asn1Sequence ncSeq = Asn1Sequence.GetInstance(
  1486. PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.NameConstraints));
  1487. if (ncSeq != null)
  1488. {
  1489. nc = new NameConstraints(ncSeq);
  1490. }
  1491. }
  1492. catch (Exception e)
  1493. {
  1494. throw new PkixCertPathValidatorException(
  1495. "Name constraints extension could not be decoded.", e, index);
  1496. }
  1497. if (nc != null)
  1498. {
  1499. //
  1500. // (g) (1) permitted subtrees
  1501. //
  1502. Asn1Sequence permitted = nc.PermittedSubtrees;
  1503. if (permitted != null)
  1504. {
  1505. try
  1506. {
  1507. nameConstraintValidator.IntersectPermittedSubtree(permitted);
  1508. }
  1509. catch (Exception ex)
  1510. {
  1511. throw new PkixCertPathValidatorException(
  1512. "Permitted subtrees cannot be build from name constraints extension.", ex, index);
  1513. }
  1514. }
  1515. //
  1516. // (g) (2) excluded subtrees
  1517. //
  1518. Asn1Sequence excluded = nc.ExcludedSubtrees;
  1519. if (excluded != null)
  1520. {
  1521. try
  1522. {
  1523. foreach (var excludedSubtree in excluded)
  1524. {
  1525. GeneralSubtree subtree = GeneralSubtree.GetInstance(excludedSubtree);
  1526. nameConstraintValidator.AddExcludedSubtree(subtree);
  1527. }
  1528. }
  1529. catch (Exception ex)
  1530. {
  1531. throw new PkixCertPathValidatorException(
  1532. "Excluded subtrees cannot be build from name constraints extension.", ex, index);
  1533. }
  1534. }
  1535. }
  1536. }
  1537. /// <exception cref="PkixCertPathValidatorException"/>
  1538. internal static int PrepareNextCertJ(
  1539. PkixCertPath certPath,
  1540. int index,
  1541. int inhibitAnyPolicy)
  1542. {
  1543. var certs = certPath.Certificates;
  1544. X509Certificate cert = certs[index];
  1545. //
  1546. // (j)
  1547. //
  1548. DerInteger iap = null;
  1549. try
  1550. {
  1551. iap = DerInteger.GetInstance(
  1552. PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.InhibitAnyPolicy));
  1553. }
  1554. catch (Exception e)
  1555. {
  1556. throw new PkixCertPathValidatorException("Inhibit any-policy extension cannot be decoded.", e, index);
  1557. }
  1558. if (iap != null)
  1559. {
  1560. int _inhibitAnyPolicy = iap.IntValueExact;
  1561. if (_inhibitAnyPolicy < inhibitAnyPolicy)
  1562. return _inhibitAnyPolicy;
  1563. }
  1564. return inhibitAnyPolicy;
  1565. }
  1566. /// <exception cref="PkixCertPathValidatorException"/>
  1567. internal static void PrepareNextCertK(
  1568. PkixCertPath certPath,
  1569. int index)
  1570. {
  1571. var certs = certPath.Certificates;
  1572. X509Certificate cert = certs[index];
  1573. //
  1574. // (k)
  1575. //
  1576. BasicConstraints bc;
  1577. try
  1578. {
  1579. bc = BasicConstraints.GetInstance(
  1580. PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.BasicConstraints));
  1581. }
  1582. catch (Exception e)
  1583. {
  1584. throw new PkixCertPathValidatorException("Basic constraints extension cannot be decoded.", e, index);
  1585. }
  1586. if (bc != null)
  1587. {
  1588. if (!(bc.IsCA()))
  1589. throw new PkixCertPathValidatorException("Not a CA certificate");
  1590. }
  1591. else
  1592. {
  1593. throw new PkixCertPathValidatorException("Intermediate certificate lacks BasicConstraints");
  1594. }
  1595. }
  1596. /// <exception cref="PkixCertPathValidatorException"/>
  1597. internal static int PrepareNextCertL(
  1598. PkixCertPath certPath,
  1599. int index,
  1600. int maxPathLength)
  1601. {
  1602. var certs = certPath.Certificates;
  1603. X509Certificate cert = certs[index];
  1604. //
  1605. // (l)
  1606. //
  1607. if (!PkixCertPathValidatorUtilities.IsSelfIssued(cert))
  1608. {
  1609. if (maxPathLength <= 0)
  1610. throw new PkixCertPathValidatorException("Max path length not greater than zero", null, index);
  1611. return maxPathLength - 1;
  1612. }
  1613. return maxPathLength;
  1614. }
  1615. /// <exception cref="PkixCertPathValidatorException"/>
  1616. internal static int PrepareNextCertM(
  1617. PkixCertPath certPath,
  1618. int index,
  1619. int maxPathLength)
  1620. {
  1621. var certs = certPath.Certificates;
  1622. X509Certificate cert = certs[index];
  1623. //
  1624. // (m)
  1625. //
  1626. BasicConstraints bc;
  1627. try
  1628. {
  1629. bc = BasicConstraints.GetInstance(
  1630. PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.BasicConstraints));
  1631. }
  1632. catch (Exception e)
  1633. {
  1634. throw new PkixCertPathValidatorException("Basic constraints extension cannot be decoded.", e, index);
  1635. }
  1636. if (bc != null)
  1637. {
  1638. BigInteger _pathLengthConstraint = bc.PathLenConstraint;
  1639. if (_pathLengthConstraint != null)
  1640. {
  1641. int _plc = _pathLengthConstraint.IntValue;
  1642. if (_plc < maxPathLength)
  1643. {
  1644. return _plc;
  1645. }
  1646. }
  1647. }
  1648. return maxPathLength;
  1649. }
  1650. /// <exception cref="PkixCertPathValidatorException"/>
  1651. internal static void PrepareNextCertN(
  1652. PkixCertPath certPath,
  1653. int index)
  1654. {
  1655. var certs = certPath.Certificates;
  1656. X509Certificate cert = certs[index];
  1657. //
  1658. // (n)
  1659. //
  1660. bool[] _usage = cert.GetKeyUsage();
  1661. if ((_usage != null) && !_usage[KEY_CERT_SIGN])
  1662. {
  1663. throw new PkixCertPathValidatorException(
  1664. "Issuer certificate keyusage extension is critical and does not permit key signing.", null, index);
  1665. }
  1666. }
  1667. /// <exception cref="PkixCertPathValidatorException"/>
  1668. internal static void PrepareNextCertO(PkixCertPath certPath, int index, ISet<string> criticalExtensions,
  1669. IList<PkixCertPathChecker> checkers)
  1670. {
  1671. var certs = certPath.Certificates;
  1672. X509Certificate cert = certs[index];
  1673. //
  1674. // (o)
  1675. //
  1676. foreach (var checker in checkers)
  1677. {
  1678. try
  1679. {
  1680. checker.Check(cert, criticalExtensions);
  1681. }
  1682. catch (PkixCertPathValidatorException e)
  1683. {
  1684. throw new PkixCertPathValidatorException(e.Message, e.InnerException, index);
  1685. }
  1686. }
  1687. if (criticalExtensions.Count > 0)
  1688. {
  1689. throw new PkixCertPathValidatorException("Certificate has unsupported critical extension.", null, index);
  1690. }
  1691. }
  1692. internal static int PrepareNextCertH1(
  1693. PkixCertPath certPath,
  1694. int index,
  1695. int explicitPolicy)
  1696. {
  1697. var certs = certPath.Certificates;
  1698. X509Certificate cert = certs[index];
  1699. //
  1700. // (h)
  1701. //
  1702. if (!PkixCertPathValidatorUtilities.IsSelfIssued(cert))
  1703. {
  1704. //
  1705. // (1)
  1706. //
  1707. if (explicitPolicy != 0)
  1708. return explicitPolicy - 1;
  1709. }
  1710. return explicitPolicy;
  1711. }
  1712. internal static int PrepareNextCertH2(
  1713. PkixCertPath certPath,
  1714. int index,
  1715. int policyMapping)
  1716. {
  1717. var certs = certPath.Certificates;
  1718. X509Certificate cert = certs[index];
  1719. //
  1720. // (h)
  1721. //
  1722. if (!PkixCertPathValidatorUtilities.IsSelfIssued(cert))
  1723. {
  1724. //
  1725. // (2)
  1726. //
  1727. if (policyMapping != 0)
  1728. return policyMapping - 1;
  1729. }
  1730. return policyMapping;
  1731. }
  1732. internal static int PrepareNextCertH3(
  1733. PkixCertPath certPath,
  1734. int index,
  1735. int inhibitAnyPolicy)
  1736. {
  1737. var certs = certPath.Certificates;
  1738. X509Certificate cert = certs[index];
  1739. //
  1740. // (h)
  1741. //
  1742. if (!PkixCertPathValidatorUtilities.IsSelfIssued(cert))
  1743. {
  1744. //
  1745. // (3)
  1746. //
  1747. if (inhibitAnyPolicy != 0)
  1748. return inhibitAnyPolicy - 1;
  1749. }
  1750. return inhibitAnyPolicy;
  1751. }
  1752. internal static int WrapupCertA(
  1753. int explicitPolicy,
  1754. X509Certificate cert)
  1755. {
  1756. //
  1757. // (a)
  1758. //
  1759. if (!PkixCertPathValidatorUtilities.IsSelfIssued(cert) && (explicitPolicy != 0))
  1760. {
  1761. explicitPolicy--;
  1762. }
  1763. return explicitPolicy;
  1764. }
  1765. /// <exception cref="PkixCertPathValidatorException"/>
  1766. internal static int WrapupCertB(
  1767. PkixCertPath certPath,
  1768. int index,
  1769. int explicitPolicy)
  1770. {
  1771. var certs = certPath.Certificates;
  1772. X509Certificate cert = certs[index];
  1773. //
  1774. // (b)
  1775. //
  1776. Asn1Sequence pc;
  1777. try
  1778. {
  1779. pc = Asn1Sequence.GetInstance(
  1780. PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.PolicyConstraints));
  1781. }
  1782. catch (Exception e)
  1783. {
  1784. throw new PkixCertPathValidatorException("Policy constraints could not be decoded.", e, index);
  1785. }
  1786. if (pc != null)
  1787. {
  1788. foreach (var policyConstraint in pc)
  1789. {
  1790. Asn1TaggedObject constraint = Asn1TaggedObject.GetInstance(policyConstraint);
  1791. if (constraint.HasContextTag(0))
  1792. {
  1793. int tmpInt;
  1794. try
  1795. {
  1796. tmpInt = DerInteger.GetInstance(constraint, false).IntValueExact;
  1797. }
  1798. catch (Exception e)
  1799. {
  1800. throw new PkixCertPathValidatorException(
  1801. "Policy constraints requireExplicitPolicy field could not be decoded.", e, index);
  1802. }
  1803. if (tmpInt == 0)
  1804. return 0;
  1805. break;
  1806. }
  1807. }
  1808. }
  1809. return explicitPolicy;
  1810. }
  1811. /// <exception cref="PkixCertPathValidatorException"/>
  1812. internal static void WrapupCertF(PkixCertPath certPath, int index, IList<PkixCertPathChecker> checkers,
  1813. ISet<string> criticalExtensions)
  1814. {
  1815. var certs = certPath.Certificates;
  1816. X509Certificate cert = certs[index];
  1817. foreach (var checker in checkers)
  1818. {
  1819. try
  1820. {
  1821. checker.Check(cert, criticalExtensions);
  1822. }
  1823. catch (PkixCertPathValidatorException e)
  1824. {
  1825. throw new PkixCertPathValidatorException("Additional certificate path checker failed.", e, index);
  1826. }
  1827. }
  1828. if (criticalExtensions.Count > 0)
  1829. {
  1830. throw new PkixCertPathValidatorException("Certificate has unsupported critical extension",
  1831. null, index);
  1832. }
  1833. }
  1834. internal static PkixPolicyNode WrapupCertG(PkixCertPath certPath, PkixParameters paramsPKIX,
  1835. ISet<string> userInitialPolicySet, int index, IList<PkixPolicyNode>[] policyNodes,
  1836. PkixPolicyNode validPolicyTree, ISet<string> acceptablePolicies)
  1837. {
  1838. int n = certPath.Certificates.Count;
  1839. //
  1840. // (g)
  1841. //
  1842. PkixPolicyNode intersection;
  1843. //
  1844. // (g) (i)
  1845. //
  1846. if (validPolicyTree == null)
  1847. {
  1848. if (paramsPKIX.IsExplicitPolicyRequired)
  1849. {
  1850. throw new PkixCertPathValidatorException(
  1851. "Explicit policy requested but none available.", null, index);
  1852. }
  1853. intersection = null;
  1854. }
  1855. else if (PkixCertPathValidatorUtilities.IsAnyPolicy(userInitialPolicySet)) // (g) (ii)
  1856. {
  1857. if (paramsPKIX.IsExplicitPolicyRequired)
  1858. {
  1859. if (acceptablePolicies.Count < 1)
  1860. {
  1861. throw new PkixCertPathValidatorException(
  1862. "Explicit policy requested but none available.", null, index);
  1863. }
  1864. var _validPolicyNodeSet = new HashSet<PkixPolicyNode>();
  1865. foreach (var _nodeDepth in policyNodes)
  1866. {
  1867. foreach (var _node in _nodeDepth)
  1868. {
  1869. if (ANY_POLICY.Equals(_node.ValidPolicy))
  1870. {
  1871. foreach (var o in _node.Children)
  1872. {
  1873. _validPolicyNodeSet.Add(o);
  1874. }
  1875. }
  1876. }
  1877. }
  1878. foreach (var _node in _validPolicyNodeSet)
  1879. {
  1880. if (!acceptablePolicies.Contains(_node.ValidPolicy))
  1881. {
  1882. // TODO?
  1883. // validPolicyTree =
  1884. // removePolicyNode(validPolicyTree, policyNodes,
  1885. // _node);
  1886. }
  1887. }
  1888. if (validPolicyTree != null)
  1889. {
  1890. for (int j = n - 1; j >= 0; j--)
  1891. {
  1892. var nodes = policyNodes[j];
  1893. for (int k = 0; k < nodes.Count; k++)
  1894. {
  1895. var node = nodes[k];
  1896. if (!node.HasChildren)
  1897. {
  1898. validPolicyTree = PkixCertPathValidatorUtilities.RemovePolicyNode(
  1899. validPolicyTree, policyNodes, node);
  1900. }
  1901. }
  1902. }
  1903. }
  1904. }
  1905. intersection = validPolicyTree;
  1906. }
  1907. else
  1908. {
  1909. //
  1910. // (g) (iii)
  1911. //
  1912. // This implementation is not exactly same as the one described in
  1913. // RFC3280.
  1914. // However, as far as the validation result is concerned, both
  1915. // produce
  1916. // adequate result. The only difference is whether AnyPolicy is
  1917. // remain
  1918. // in the policy tree or not.
  1919. //
  1920. // (g) (iii) 1
  1921. //
  1922. var _validPolicyNodeSet = new HashSet<PkixPolicyNode>();
  1923. foreach (var _nodeDepth in policyNodes)
  1924. {
  1925. foreach (var _node in _nodeDepth)
  1926. {
  1927. if (ANY_POLICY.Equals(_node.ValidPolicy))
  1928. {
  1929. foreach (PkixPolicyNode _c_node in _node.Children)
  1930. {
  1931. if (!ANY_POLICY.Equals(_c_node.ValidPolicy))
  1932. {
  1933. _validPolicyNodeSet.Add(_c_node);
  1934. }
  1935. }
  1936. }
  1937. }
  1938. }
  1939. //
  1940. // (g) (iii) 2
  1941. //
  1942. foreach (var _node in _validPolicyNodeSet)
  1943. {
  1944. if (!userInitialPolicySet.Contains(_node.ValidPolicy))
  1945. {
  1946. validPolicyTree = PkixCertPathValidatorUtilities.RemovePolicyNode(validPolicyTree, policyNodes,
  1947. _node);
  1948. }
  1949. }
  1950. //
  1951. // (g) (iii) 4
  1952. //
  1953. if (validPolicyTree != null)
  1954. {
  1955. for (int j = n - 1; j >= 0; j--)
  1956. {
  1957. var nodes = policyNodes[j];
  1958. for (int k = 0; k < nodes.Count; k++)
  1959. {
  1960. var node = nodes[k];
  1961. if (!node.HasChildren)
  1962. {
  1963. validPolicyTree = PkixCertPathValidatorUtilities.RemovePolicyNode(validPolicyTree,
  1964. policyNodes, node);
  1965. }
  1966. }
  1967. }
  1968. }
  1969. intersection = validPolicyTree;
  1970. }
  1971. return intersection;
  1972. }
  1973. /**
  1974. * If use-deltas is set, verify the issuer and scope of the delta CRL.
  1975. *
  1976. * @param deltaCRL The delta CRL.
  1977. * @param completeCRL The complete CRL.
  1978. * @param pkixParams The PKIX paramaters.
  1979. * @throws AnnotatedException if an exception occurs.
  1980. */
  1981. internal static void ProcessCrlC(
  1982. X509Crl deltaCRL,
  1983. X509Crl completeCRL,
  1984. PkixParameters pkixParams)
  1985. {
  1986. if (deltaCRL == null)
  1987. return;
  1988. IssuingDistributionPoint completeidp = null;
  1989. try
  1990. {
  1991. completeidp = IssuingDistributionPoint.GetInstance(
  1992. PkixCertPathValidatorUtilities.GetExtensionValue(completeCRL, X509Extensions.IssuingDistributionPoint));
  1993. }
  1994. catch (Exception e)
  1995. {
  1996. throw new Exception("000 Issuing distribution point extension could not be decoded.", e);
  1997. }
  1998. if (pkixParams.IsUseDeltasEnabled)
  1999. {
  2000. // (c) (1)
  2001. if (!deltaCRL.IssuerDN.Equivalent(completeCRL.IssuerDN, true))
  2002. throw new Exception("Complete CRL issuer does not match delta CRL issuer.");
  2003. // (c) (2)
  2004. IssuingDistributionPoint deltaidp = null;
  2005. try
  2006. {
  2007. deltaidp = IssuingDistributionPoint.GetInstance(
  2008. PkixCertPathValidatorUtilities.GetExtensionValue(deltaCRL, X509Extensions.IssuingDistributionPoint));
  2009. }
  2010. catch (Exception e)
  2011. {
  2012. throw new Exception(
  2013. "Issuing distribution point extension from delta CRL could not be decoded.", e);
  2014. }
  2015. if (!Org.BouncyCastle.Utilities.Platform.Equals(completeidp, deltaidp))
  2016. {
  2017. throw new Exception(
  2018. "Issuing distribution point extension from delta CRL and complete CRL does not match.");
  2019. }
  2020. // (c) (3)
  2021. Asn1Object completeKeyIdentifier = null;
  2022. try
  2023. {
  2024. completeKeyIdentifier = PkixCertPathValidatorUtilities.GetExtensionValue(
  2025. completeCRL, X509Extensions.AuthorityKeyIdentifier);
  2026. }
  2027. catch (Exception e)
  2028. {
  2029. throw new Exception(
  2030. "Authority key identifier extension could not be extracted from complete CRL.", e);
  2031. }
  2032. Asn1Object deltaKeyIdentifier = null;
  2033. try
  2034. {
  2035. deltaKeyIdentifier = PkixCertPathValidatorUtilities.GetExtensionValue(
  2036. deltaCRL, X509Extensions.AuthorityKeyIdentifier);
  2037. }
  2038. catch (Exception e)
  2039. {
  2040. throw new Exception(
  2041. "Authority key identifier extension could not be extracted from delta CRL.", e);
  2042. }
  2043. if (completeKeyIdentifier == null)
  2044. throw new Exception("CRL authority key identifier is null.");
  2045. if (deltaKeyIdentifier == null)
  2046. throw new Exception("Delta CRL authority key identifier is null.");
  2047. if (!completeKeyIdentifier.Equals(deltaKeyIdentifier))
  2048. {
  2049. throw new Exception(
  2050. "Delta CRL authority key identifier does not match complete CRL authority key identifier.");
  2051. }
  2052. }
  2053. }
  2054. internal static void ProcessCrlI(
  2055. DateTime validDate,
  2056. X509Crl deltacrl,
  2057. object cert,
  2058. CertStatus certStatus,
  2059. PkixParameters pkixParams)
  2060. {
  2061. if (pkixParams.IsUseDeltasEnabled && deltacrl != null)
  2062. {
  2063. PkixCertPathValidatorUtilities.GetCertStatus(validDate, deltacrl, cert, certStatus);
  2064. }
  2065. }
  2066. internal static void ProcessCrlJ(
  2067. DateTime validDate,
  2068. X509Crl completecrl,
  2069. object cert,
  2070. CertStatus certStatus)
  2071. {
  2072. if (certStatus.Status == CertStatus.Unrevoked)
  2073. {
  2074. PkixCertPathValidatorUtilities.GetCertStatus(validDate, completecrl, cert, certStatus);
  2075. }
  2076. }
  2077. internal static PkixPolicyNode ProcessCertE(
  2078. PkixCertPath certPath,
  2079. int index,
  2080. PkixPolicyNode validPolicyTree)
  2081. {
  2082. var certs = certPath.Certificates;
  2083. X509Certificate cert = certs[index];
  2084. //
  2085. // (e)
  2086. //
  2087. Asn1Sequence certPolicies = null;
  2088. try
  2089. {
  2090. certPolicies = Asn1Sequence.GetInstance(
  2091. PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.CertificatePolicies));
  2092. }
  2093. catch (Exception e)
  2094. {
  2095. throw new PkixCertPathValidatorException("Could not read certificate policies extension from certificate.",
  2096. e, index);
  2097. }
  2098. if (certPolicies == null)
  2099. {
  2100. validPolicyTree = null;
  2101. }
  2102. return validPolicyTree;
  2103. }
  2104. internal static readonly string[] CrlReasons = new string[]
  2105. {
  2106. "unspecified",
  2107. "keyCompromise",
  2108. "cACompromise",
  2109. "affiliationChanged",
  2110. "superseded",
  2111. "cessationOfOperation",
  2112. "certificateHold",
  2113. "unknown",
  2114. "removeFromCRL",
  2115. "privilegeWithdrawn",
  2116. "aACompromise"
  2117. };
  2118. }
  2119. }
  2120. #pragma warning restore
  2121. #endif