Asn1InputStream.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using System.Diagnostics;
  5. using System.IO;
  6. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  7. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO;
  8. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1
  9. {
  10. /**
  11. * a general purpose ASN.1 decoder - note: this class differs from the
  12. * others in that it returns null after it has read the last object in
  13. * the stream. If an ASN.1 Null is encountered a Der/BER Null object is
  14. * returned.
  15. */
  16. public class Asn1InputStream
  17. : FilterStream
  18. {
  19. private readonly int limit;
  20. internal readonly byte[][] tmpBuffers;
  21. internal static int FindLimit(Stream input)
  22. {
  23. if (input is LimitedInputStream)
  24. return ((LimitedInputStream)input).Limit;
  25. if (input is Asn1InputStream)
  26. return ((Asn1InputStream)input).Limit;
  27. if (input is MemoryStream)
  28. {
  29. MemoryStream mem = (MemoryStream)input;
  30. return (int)(mem.Length - mem.Position);
  31. }
  32. return int.MaxValue;
  33. }
  34. public Asn1InputStream(Stream input)
  35. : this(input, FindLimit(input))
  36. {
  37. }
  38. /**
  39. * Create an ASN1InputStream based on the input byte array. The length of DER objects in
  40. * the stream is automatically limited to the length of the input array.
  41. *
  42. * @param input array containing ASN.1 encoded data.
  43. */
  44. public Asn1InputStream(byte[] input)
  45. : this(new MemoryStream(input, false), input.Length)
  46. {
  47. }
  48. /**
  49. * Create an ASN1InputStream where no DER object will be longer than limit.
  50. *
  51. * @param input stream containing ASN.1 encoded data.
  52. * @param limit maximum size of a DER encoded object.
  53. */
  54. public Asn1InputStream(Stream input, int limit)
  55. : this(input, limit, new byte[16][])
  56. {
  57. }
  58. internal Asn1InputStream(Stream input, int limit, byte[][] tmpBuffers)
  59. : base(input)
  60. {
  61. this.limit = limit;
  62. this.tmpBuffers = tmpBuffers;
  63. }
  64. /**
  65. * build an object given its tag and the number of bytes to construct it from.
  66. */
  67. private Asn1Object BuildObject(
  68. int tag,
  69. int tagNo,
  70. int length)
  71. {
  72. bool isConstructed = (tag & Asn1Tags.Constructed) != 0;
  73. DefiniteLengthInputStream defIn = new DefiniteLengthInputStream(this, length, limit);
  74. int tagClass = tag & Asn1Tags.Private;
  75. if (0 != tagClass)
  76. {
  77. if ((tag & Asn1Tags.Application) != 0)
  78. return new DerApplicationSpecific(isConstructed, tagNo, defIn.ToArray());
  79. return new Asn1StreamParser(defIn, defIn.Remaining, tmpBuffers).ReadTaggedObject(isConstructed, tagNo);
  80. }
  81. if (!isConstructed)
  82. return CreatePrimitiveDerObject(tagNo, defIn, tmpBuffers);
  83. switch (tagNo)
  84. {
  85. case Asn1Tags.BitString:
  86. {
  87. return BuildConstructedBitString(ReadVector(defIn));
  88. }
  89. case Asn1Tags.OctetString:
  90. {
  91. //
  92. // yes, people actually do this...
  93. //
  94. return BuildConstructedOctetString(ReadVector(defIn));
  95. }
  96. case Asn1Tags.Sequence:
  97. return CreateDerSequence(defIn);
  98. case Asn1Tags.Set:
  99. return CreateDerSet(defIn);
  100. case Asn1Tags.External:
  101. return new DerExternal(ReadVector(defIn));
  102. default:
  103. throw new IOException("unknown tag " + tagNo + " encountered");
  104. }
  105. }
  106. internal virtual Asn1EncodableVector ReadVector()
  107. {
  108. Asn1Object o = ReadObject();
  109. if (null == o)
  110. return new Asn1EncodableVector(0);
  111. Asn1EncodableVector v = new Asn1EncodableVector();
  112. do
  113. {
  114. v.Add(o);
  115. }
  116. while ((o = ReadObject()) != null);
  117. return v;
  118. }
  119. internal virtual Asn1EncodableVector ReadVector(DefiniteLengthInputStream defIn)
  120. {
  121. int remaining = defIn.Remaining;
  122. if (remaining < 1)
  123. return new Asn1EncodableVector(0);
  124. return new Asn1InputStream(defIn, remaining, tmpBuffers).ReadVector();
  125. }
  126. internal virtual DerSequence CreateDerSequence(
  127. DefiniteLengthInputStream dIn)
  128. {
  129. return DerSequence.FromVector(ReadVector(dIn));
  130. }
  131. internal virtual DerSet CreateDerSet(
  132. DefiniteLengthInputStream dIn)
  133. {
  134. return DerSet.FromVector(ReadVector(dIn), false);
  135. }
  136. public Asn1Object ReadObject()
  137. {
  138. int tag = ReadByte();
  139. if (tag <= 0)
  140. {
  141. if (tag == 0)
  142. throw new IOException("unexpected end-of-contents marker");
  143. return null;
  144. }
  145. int tagNo = ReadTagNumber(this, tag);
  146. int length = ReadLength(this, limit, false);
  147. if (length >= 0)
  148. {
  149. // definite-length
  150. try
  151. {
  152. return BuildObject(tag, tagNo, length);
  153. }
  154. catch (ArgumentException e)
  155. {
  156. throw new Asn1Exception("corrupted stream detected", e);
  157. }
  158. }
  159. // indefinite-length
  160. if (0 == (tag & Asn1Tags.Constructed))
  161. throw new IOException("indefinite-length primitive encoding encountered");
  162. IndefiniteLengthInputStream indIn = new IndefiniteLengthInputStream(this, limit);
  163. Asn1StreamParser sp = new Asn1StreamParser(indIn, limit, tmpBuffers);
  164. int tagClass = tag & Asn1Tags.Private;
  165. if (0 != tagClass)
  166. {
  167. if ((tag & Asn1Tags.Application) != 0)
  168. return new BerApplicationSpecificParser(tagNo, sp).ToAsn1Object();
  169. return new BerTaggedObjectParser(true, tagNo, sp).ToAsn1Object();
  170. }
  171. // TODO There are other tags that may be constructed (e.g. BitString)
  172. switch (tagNo)
  173. {
  174. case Asn1Tags.OctetString:
  175. return BerOctetStringParser.Parse(sp);
  176. case Asn1Tags.Sequence:
  177. return BerSequenceParser.Parse(sp);
  178. case Asn1Tags.Set:
  179. return BerSetParser.Parse(sp);
  180. case Asn1Tags.External:
  181. return DerExternalParser.Parse(sp);
  182. default:
  183. throw new IOException("unknown BER object encountered");
  184. }
  185. }
  186. internal virtual DerBitString BuildConstructedBitString(Asn1EncodableVector contentsElements)
  187. {
  188. DerBitString[] bitStrings = new DerBitString[contentsElements.Count];
  189. for (int i = 0; i != bitStrings.Length; i++)
  190. {
  191. DerBitString bitString = contentsElements[i] as DerBitString;
  192. if (null == bitString)
  193. throw new Asn1Exception("unknown object encountered in constructed BIT STRING: "
  194. + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(contentsElements[i]));
  195. bitStrings[i] = bitString;
  196. }
  197. // TODO Probably ought to be DLBitString
  198. return new BerBitString(bitStrings);
  199. }
  200. internal virtual Asn1OctetString BuildConstructedOctetString(Asn1EncodableVector contentsElements)
  201. {
  202. Asn1OctetString[] octetStrings = new Asn1OctetString[contentsElements.Count];
  203. for (int i = 0; i != octetStrings.Length; i++)
  204. {
  205. Asn1OctetString octetString = contentsElements[i] as Asn1OctetString;
  206. if (null == octetString)
  207. throw new Asn1Exception("unknown object encountered in constructed OCTET STRING: "
  208. + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(contentsElements[i]));
  209. octetStrings[i] = octetString;
  210. }
  211. // TODO Probably ought to be DerOctetString (no DLOctetString available)
  212. return new BerOctetString(octetStrings);
  213. }
  214. internal virtual int Limit
  215. {
  216. get { return limit; }
  217. }
  218. internal static int ReadTagNumber(Stream s, int tag)
  219. {
  220. int tagNo = tag & 0x1f;
  221. //
  222. // with tagged object tag number is bottom 5 bits, or stored at the start of the content
  223. //
  224. if (tagNo == 0x1f)
  225. {
  226. tagNo = 0;
  227. int b = s.ReadByte();
  228. if (b < 31)
  229. {
  230. if (b < 0)
  231. throw new EndOfStreamException("EOF found inside tag value.");
  232. throw new IOException("corrupted stream - high tag number < 31 found");
  233. }
  234. // X.690-0207 8.1.2.4.2
  235. // "c) bits 7 to 1 of the first subsequent octet shall not all be zero."
  236. if ((b & 0x7f) == 0)
  237. throw new IOException("corrupted stream - invalid high tag number found");
  238. while ((b & 0x80) != 0)
  239. {
  240. if (((uint)tagNo >> 24) != 0U)
  241. throw new IOException("Tag number more than 31 bits");
  242. tagNo |= b & 0x7f;
  243. tagNo <<= 7;
  244. b = s.ReadByte();
  245. if (b < 0)
  246. throw new EndOfStreamException("EOF found inside tag value.");
  247. }
  248. tagNo |= b & 0x7f;
  249. }
  250. return tagNo;
  251. }
  252. internal static int ReadLength(Stream s, int limit, bool isParsing)
  253. {
  254. int length = s.ReadByte();
  255. if (0U == ((uint)length >> 7))
  256. {
  257. // definite-length short form
  258. return length;
  259. }
  260. if (0x80 == length)
  261. {
  262. // indefinite-length
  263. return -1;
  264. }
  265. if (length < 0)
  266. {
  267. throw new EndOfStreamException("EOF found when length expected");
  268. }
  269. if (0xFF == length)
  270. {
  271. throw new IOException("invalid long form definite-length 0xFF");
  272. }
  273. int octetsCount = length & 0x7F, octetsPos = 0;
  274. length = 0;
  275. do
  276. {
  277. int octet = s.ReadByte();
  278. if (octet < 0)
  279. throw new EndOfStreamException("EOF found reading length");
  280. if (((uint)length >> 23) != 0U)
  281. throw new IOException("long form definite-length more than 31 bits");
  282. length = (length << 8) + octet;
  283. }
  284. while (++octetsPos < octetsCount);
  285. if (length >= limit && !isParsing) // after all we must have read at least 1 byte
  286. throw new IOException("corrupted stream - out of bounds length found: " + length + " >= " + limit);
  287. return length;
  288. }
  289. private static byte[] GetBuffer(DefiniteLengthInputStream defIn, byte[][] tmpBuffers)
  290. {
  291. int len = defIn.Remaining;
  292. if (len >= tmpBuffers.Length)
  293. {
  294. return defIn.ToArray();
  295. }
  296. byte[] buf = tmpBuffers[len];
  297. if (buf == null)
  298. {
  299. buf = tmpBuffers[len] = new byte[len];
  300. }
  301. defIn.ReadAllIntoByteArray(buf);
  302. return buf;
  303. }
  304. private static char[] GetBmpCharBuffer(DefiniteLengthInputStream defIn)
  305. {
  306. int remainingBytes = defIn.Remaining;
  307. if (0 != (remainingBytes & 1))
  308. throw new IOException("malformed BMPString encoding encountered");
  309. char[] str = new char[remainingBytes / 2];
  310. int stringPos = 0;
  311. byte[] buf = new byte[8];
  312. while (remainingBytes >= 8)
  313. {
  314. if (Streams.ReadFully(defIn, buf, 0, 8) != 8)
  315. throw new EndOfStreamException("EOF encountered in middle of BMPString");
  316. str[stringPos ] = (char)((buf[0] << 8) | (buf[1] & 0xFF));
  317. str[stringPos + 1] = (char)((buf[2] << 8) | (buf[3] & 0xFF));
  318. str[stringPos + 2] = (char)((buf[4] << 8) | (buf[5] & 0xFF));
  319. str[stringPos + 3] = (char)((buf[6] << 8) | (buf[7] & 0xFF));
  320. stringPos += 4;
  321. remainingBytes -= 8;
  322. }
  323. if (remainingBytes > 0)
  324. {
  325. if (Streams.ReadFully(defIn, buf, 0, remainingBytes) != remainingBytes)
  326. throw new EndOfStreamException("EOF encountered in middle of BMPString");
  327. int bufPos = 0;
  328. do
  329. {
  330. int b1 = buf[bufPos++] << 8;
  331. int b2 = buf[bufPos++] & 0xFF;
  332. str[stringPos++] = (char)(b1 | b2);
  333. }
  334. while (bufPos < remainingBytes);
  335. }
  336. if (0 != defIn.Remaining || str.Length != stringPos)
  337. throw new InvalidOperationException();
  338. return str;
  339. }
  340. internal static Asn1Object CreatePrimitiveDerObject(
  341. int tagNo,
  342. DefiniteLengthInputStream defIn,
  343. byte[][] tmpBuffers)
  344. {
  345. switch (tagNo)
  346. {
  347. case Asn1Tags.BmpString:
  348. return new DerBmpString(GetBmpCharBuffer(defIn));
  349. case Asn1Tags.Boolean:
  350. return DerBoolean.FromOctetString(GetBuffer(defIn, tmpBuffers));
  351. case Asn1Tags.Enumerated:
  352. return DerEnumerated.FromOctetString(GetBuffer(defIn, tmpBuffers));
  353. case Asn1Tags.ObjectIdentifier:
  354. // TODO Ideally only clone if we used a buffer
  355. return DerObjectIdentifier.CreatePrimitive(GetBuffer(defIn, tmpBuffers), true);
  356. }
  357. byte[] bytes = defIn.ToArray();
  358. switch (tagNo)
  359. {
  360. case Asn1Tags.BitString:
  361. return DerBitString.CreatePrimitive(bytes);
  362. case Asn1Tags.GeneralizedTime:
  363. return new DerGeneralizedTime(bytes);
  364. case Asn1Tags.GeneralString:
  365. return new DerGeneralString(bytes);
  366. case Asn1Tags.GraphicString:
  367. return new DerGraphicString(bytes);
  368. case Asn1Tags.IA5String:
  369. return new DerIA5String(bytes);
  370. case Asn1Tags.Integer:
  371. return new DerInteger(bytes, false);
  372. case Asn1Tags.Null:
  373. {
  374. if (0 != bytes.Length)
  375. throw new InvalidOperationException("malformed NULL encoding encountered");
  376. return DerNull.Instance;
  377. }
  378. case Asn1Tags.NumericString:
  379. return new DerNumericString(bytes);
  380. case Asn1Tags.OctetString:
  381. return new DerOctetString(bytes);
  382. case Asn1Tags.PrintableString:
  383. return new DerPrintableString(bytes);
  384. case Asn1Tags.T61String:
  385. return new DerT61String(bytes);
  386. case Asn1Tags.UniversalString:
  387. return new DerUniversalString(bytes);
  388. case Asn1Tags.UtcTime:
  389. return new DerUtcTime(bytes);
  390. case Asn1Tags.Utf8String:
  391. return new DerUtf8String(bytes);
  392. case Asn1Tags.VideotexString:
  393. return new DerVideotexString(bytes);
  394. case Asn1Tags.VisibleString:
  395. return new DerVisibleString(bytes);
  396. default:
  397. throw new IOException("unknown tag " + tagNo + " encountered");
  398. }
  399. }
  400. }
  401. }
  402. #pragma warning restore
  403. #endif