Asn1InputStream.cs 16 KB

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