X509Crl.cs 14 KB

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