Rfc3280CertPathUtilities.cs 66 KB

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