Rfc3280CertPathUtilities.cs 66 KB

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