X509Crl.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using System.Collections;
  5. using System.Text;
  6. using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
  7. using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Utilities;
  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.Utilities.Encoders;
  17. using BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Extension;
  18. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Operators;
  19. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509
  20. {
  21. /**
  22. * The following extensions are listed in RFC 2459 as relevant to CRLs
  23. *
  24. * Authority Key Identifier
  25. * Issuer Alternative Name
  26. * CRL Number
  27. * Delta CRL Indicator (critical)
  28. * Issuing Distribution Point (critical)
  29. */
  30. public class X509Crl
  31. : X509ExtensionBase
  32. // TODO Add interface Crl?
  33. {
  34. private readonly CertificateList c;
  35. private readonly string sigAlgName;
  36. private readonly byte[] sigAlgParams;
  37. private readonly bool isIndirect;
  38. public X509Crl(
  39. CertificateList c)
  40. {
  41. this.c = c;
  42. try
  43. {
  44. this.sigAlgName = X509SignatureUtilities.GetSignatureName(c.SignatureAlgorithm);
  45. if (c.SignatureAlgorithm.Parameters != null)
  46. {
  47. this.sigAlgParams = ((Asn1Encodable)c.SignatureAlgorithm.Parameters).GetDerEncoded();
  48. }
  49. else
  50. {
  51. this.sigAlgParams = null;
  52. }
  53. this.isIndirect = IsIndirectCrl;
  54. }
  55. catch (Exception e)
  56. {
  57. throw new CrlException("CRL contents invalid: " + e);
  58. }
  59. }
  60. protected override X509Extensions GetX509Extensions()
  61. {
  62. return c.Version >= 2
  63. ? c.TbsCertList.Extensions
  64. : null;
  65. }
  66. public virtual byte[] GetEncoded()
  67. {
  68. try
  69. {
  70. return c.GetDerEncoded();
  71. }
  72. catch (Exception e)
  73. {
  74. throw new CrlException(e.ToString());
  75. }
  76. }
  77. public virtual void Verify(
  78. AsymmetricKeyParameter publicKey)
  79. {
  80. Verify(new Asn1VerifierFactoryProvider(publicKey));
  81. }
  82. /// <summary>
  83. /// Verify the CRL's signature using a verifier created using the passed in verifier provider.
  84. /// </summary>
  85. /// <param name="verifierProvider">An appropriate provider for verifying the CRL's signature.</param>
  86. /// <returns>True if the signature is valid.</returns>
  87. /// <exception cref="Exception">If verifier provider is not appropriate or the CRL algorithm is invalid.</exception>
  88. public virtual void Verify(
  89. IVerifierFactoryProvider verifierProvider)
  90. {
  91. CheckSignature(verifierProvider.CreateVerifierFactory(c.SignatureAlgorithm));
  92. }
  93. protected virtual void CheckSignature(
  94. IVerifierFactory verifier)
  95. {
  96. if (!c.SignatureAlgorithm.Equals(c.TbsCertList.Signature))
  97. {
  98. throw new CrlException("Signature algorithm on CertificateList does not match TbsCertList.");
  99. }
  100. Asn1Encodable parameters = c.SignatureAlgorithm.Parameters;
  101. IStreamCalculator streamCalculator = verifier.CreateCalculator();
  102. byte[] b = this.GetTbsCertList();
  103. streamCalculator.Stream.Write(b, 0, b.Length);
  104. BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(streamCalculator.Stream);
  105. if (!((IVerifier)streamCalculator.GetResult()).IsVerified(this.GetSignature()))
  106. {
  107. throw new InvalidKeyException("CRL does not verify with supplied public key.");
  108. }
  109. }
  110. public virtual int Version
  111. {
  112. get { return c.Version; }
  113. }
  114. public virtual X509Name IssuerDN
  115. {
  116. get { return c.Issuer; }
  117. }
  118. public virtual DateTime ThisUpdate
  119. {
  120. get { return c.ThisUpdate.ToDateTime(); }
  121. }
  122. public virtual DateTimeObject NextUpdate
  123. {
  124. get
  125. {
  126. return c.NextUpdate == null
  127. ? null
  128. : new DateTimeObject(c.NextUpdate.ToDateTime());
  129. }
  130. }
  131. private ISet LoadCrlEntries()
  132. {
  133. ISet entrySet = new HashSet();
  134. IEnumerable certs = c.GetRevokedCertificateEnumeration();
  135. X509Name previousCertificateIssuer = IssuerDN;
  136. foreach (CrlEntry entry in certs)
  137. {
  138. X509CrlEntry crlEntry = new X509CrlEntry(entry, isIndirect, previousCertificateIssuer);
  139. entrySet.Add(crlEntry);
  140. previousCertificateIssuer = crlEntry.GetCertificateIssuer();
  141. }
  142. return entrySet;
  143. }
  144. public virtual X509CrlEntry GetRevokedCertificate(
  145. BigInteger serialNumber)
  146. {
  147. IEnumerable certs = c.GetRevokedCertificateEnumeration();
  148. X509Name previousCertificateIssuer = IssuerDN;
  149. foreach (CrlEntry entry in certs)
  150. {
  151. X509CrlEntry crlEntry = new X509CrlEntry(entry, isIndirect, previousCertificateIssuer);
  152. if (serialNumber.Equals(entry.UserCertificate.Value))
  153. {
  154. return crlEntry;
  155. }
  156. previousCertificateIssuer = crlEntry.GetCertificateIssuer();
  157. }
  158. return null;
  159. }
  160. public virtual ISet GetRevokedCertificates()
  161. {
  162. ISet entrySet = LoadCrlEntries();
  163. if (entrySet.Count > 0)
  164. {
  165. return entrySet; // TODO? Collections.unmodifiableSet(entrySet);
  166. }
  167. return null;
  168. }
  169. public virtual byte[] GetTbsCertList()
  170. {
  171. try
  172. {
  173. return c.TbsCertList.GetDerEncoded();
  174. }
  175. catch (Exception e)
  176. {
  177. throw new CrlException(e.ToString());
  178. }
  179. }
  180. public virtual byte[] GetSignature()
  181. {
  182. return c.GetSignatureOctets();
  183. }
  184. public virtual string SigAlgName
  185. {
  186. get { return sigAlgName; }
  187. }
  188. public virtual string SigAlgOid
  189. {
  190. get { return c.SignatureAlgorithm.Algorithm.Id; }
  191. }
  192. public virtual byte[] GetSigAlgParams()
  193. {
  194. return Arrays.Clone(sigAlgParams);
  195. }
  196. public override bool Equals(
  197. object obj)
  198. {
  199. if (obj == this)
  200. return true;
  201. X509Crl other = obj as X509Crl;
  202. if (other == null)
  203. return false;
  204. return c.Equals(other.c);
  205. // NB: May prefer this implementation of Equals if more than one certificate implementation in play
  206. //return Arrays.AreEqual(this.GetEncoded(), other.GetEncoded());
  207. }
  208. public override int GetHashCode()
  209. {
  210. return c.GetHashCode();
  211. }
  212. /**
  213. * Returns a string representation of this CRL.
  214. *
  215. * @return a string representation of this CRL.
  216. */
  217. public override string ToString()
  218. {
  219. StringBuilder buf = new StringBuilder();
  220. string nl = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.NewLine;
  221. buf.Append(" Version: ").Append(this.Version).Append(nl);
  222. buf.Append(" IssuerDN: ").Append(this.IssuerDN).Append(nl);
  223. buf.Append(" This update: ").Append(this.ThisUpdate).Append(nl);
  224. buf.Append(" Next update: ").Append(this.NextUpdate).Append(nl);
  225. buf.Append(" Signature Algorithm: ").Append(this.SigAlgName).Append(nl);
  226. byte[] sig = this.GetSignature();
  227. buf.Append(" Signature: ");
  228. buf.Append(Hex.ToHexString(sig, 0, 20)).Append(nl);
  229. for (int i = 20; i < sig.Length; i += 20)
  230. {
  231. int count = System.Math.Min(20, sig.Length - i);
  232. buf.Append(" ");
  233. buf.Append(Hex.ToHexString(sig, i, count)).Append(nl);
  234. }
  235. X509Extensions extensions = c.TbsCertList.Extensions;
  236. if (extensions != null)
  237. {
  238. IEnumerator e = extensions.ExtensionOids.GetEnumerator();
  239. if (e.MoveNext())
  240. {
  241. buf.Append(" Extensions: ").Append(nl);
  242. }
  243. do
  244. {
  245. DerObjectIdentifier oid = (DerObjectIdentifier) e.Current;
  246. X509Extension ext = extensions.GetExtension(oid);
  247. if (ext.Value != null)
  248. {
  249. Asn1Object asn1Value = X509ExtensionUtilities.FromExtensionValue(ext.Value);
  250. buf.Append(" critical(").Append(ext.IsCritical).Append(") ");
  251. try
  252. {
  253. if (oid.Equals(X509Extensions.CrlNumber))
  254. {
  255. buf.Append(new CrlNumber(DerInteger.GetInstance(asn1Value).PositiveValue)).Append(nl);
  256. }
  257. else if (oid.Equals(X509Extensions.DeltaCrlIndicator))
  258. {
  259. buf.Append(
  260. "Base CRL: "
  261. + new CrlNumber(DerInteger.GetInstance(
  262. asn1Value).PositiveValue))
  263. .Append(nl);
  264. }
  265. else if (oid.Equals(X509Extensions.IssuingDistributionPoint))
  266. {
  267. buf.Append(IssuingDistributionPoint.GetInstance((Asn1Sequence) asn1Value)).Append(nl);
  268. }
  269. else if (oid.Equals(X509Extensions.CrlDistributionPoints))
  270. {
  271. buf.Append(CrlDistPoint.GetInstance((Asn1Sequence) asn1Value)).Append(nl);
  272. }
  273. else if (oid.Equals(X509Extensions.FreshestCrl))
  274. {
  275. buf.Append(CrlDistPoint.GetInstance((Asn1Sequence) asn1Value)).Append(nl);
  276. }
  277. else
  278. {
  279. buf.Append(oid.Id);
  280. buf.Append(" value = ").Append(
  281. Asn1Dump.DumpAsString(asn1Value))
  282. .Append(nl);
  283. }
  284. }
  285. catch (Exception)
  286. {
  287. buf.Append(oid.Id);
  288. buf.Append(" value = ").Append("*****").Append(nl);
  289. }
  290. }
  291. else
  292. {
  293. buf.Append(nl);
  294. }
  295. }
  296. while (e.MoveNext());
  297. }
  298. ISet certSet = GetRevokedCertificates();
  299. if (certSet != null)
  300. {
  301. foreach (X509CrlEntry entry in certSet)
  302. {
  303. buf.Append(entry);
  304. buf.Append(nl);
  305. }
  306. }
  307. return buf.ToString();
  308. }
  309. /**
  310. * Checks whether the given certificate is on this CRL.
  311. *
  312. * @param cert the certificate to check for.
  313. * @return true if the given certificate is on this CRL,
  314. * false otherwise.
  315. */
  316. // public bool IsRevoked(
  317. // Certificate cert)
  318. // {
  319. // if (!cert.getType().Equals("X.509"))
  320. // {
  321. // throw new RuntimeException("X.509 CRL used with non X.509 Cert");
  322. // }
  323. public virtual bool IsRevoked(
  324. X509Certificate cert)
  325. {
  326. CrlEntry[] certs = c.GetRevokedCertificates();
  327. if (certs != null)
  328. {
  329. // BigInteger serial = ((X509Certificate)cert).SerialNumber;
  330. BigInteger serial = cert.SerialNumber;
  331. for (int i = 0; i < certs.Length; i++)
  332. {
  333. if (certs[i].UserCertificate.Value.Equals(serial))
  334. {
  335. return true;
  336. }
  337. }
  338. }
  339. return false;
  340. }
  341. protected virtual bool IsIndirectCrl
  342. {
  343. get
  344. {
  345. Asn1OctetString idp = GetExtensionValue(X509Extensions.IssuingDistributionPoint);
  346. bool isIndirect = false;
  347. try
  348. {
  349. if (idp != null)
  350. {
  351. isIndirect = IssuingDistributionPoint.GetInstance(
  352. X509ExtensionUtilities.FromExtensionValue(idp)).IsIndirectCrl;
  353. }
  354. }
  355. catch (Exception e)
  356. {
  357. // TODO
  358. // throw new ExtCrlException("Exception reading IssuingDistributionPoint", e);
  359. throw new CrlException("Exception reading IssuingDistributionPoint" + e);
  360. }
  361. return isIndirect;
  362. }
  363. }
  364. }
  365. }
  366. #pragma warning restore
  367. #endif