summary refs log tree commit diff
path: root/crypto/src/asn1/ASN1StreamParser.cs
blob: f896227f86387a0eca3ceb658e6b68b0547103f7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
using System;
using System.IO;

namespace Org.BouncyCastle.Asn1
{
	public class Asn1StreamParser
	{
		private readonly Stream _in;
		private readonly int _limit;

        private readonly byte[][] tmpBuffers;

        public Asn1StreamParser(Stream input)
			: this(input, Asn1InputStream.FindLimit(input))
		{
		}

        public Asn1StreamParser(byte[] encoding)
            : this(new MemoryStream(encoding, false), encoding.Length)
        {
        }

        public Asn1StreamParser(Stream input, int limit)
            : this(input, limit, new byte[16][])
		{
        }

        internal Asn1StreamParser(Stream input, int limit, byte[][] tmpBuffers)
        {
            if (!input.CanRead)
                throw new ArgumentException("Expected stream to be readable", "input");

            this._in = input;
            this._limit = limit;
            this.tmpBuffers = tmpBuffers;
        }

        internal IAsn1Convertible ReadIndef(int tagNo)
		{
			// Note: INDEF => CONSTRUCTED

			// TODO There are other tags that may be constructed (e.g. BIT_STRING)
			switch (tagNo)
			{
			case Asn1Tags.External:
				return new DerExternalParser(this);
			case Asn1Tags.OctetString:
				return new BerOctetStringParser(this);
			case Asn1Tags.Sequence:
				return new BerSequenceParser(this);
			case Asn1Tags.Set:
				return new BerSetParser(this);
			default:
				throw new Asn1Exception("unknown BER object encountered: 0x" + tagNo.ToString("X"));
			}
		}

		internal IAsn1Convertible ReadImplicit(bool constructed, int tagNo)
		{
			if (_in is IndefiniteLengthInputStream)
			{
				if (!constructed)
					throw new IOException("indefinite-length primitive encoding encountered");

				return ReadIndef(tagNo);
			}

			if (constructed)
			{
				switch (tagNo)
				{
				case Asn1Tags.Set:
					return new DerSetParser(this);
				case Asn1Tags.Sequence:
					return new DerSequenceParser(this);
				case Asn1Tags.OctetString:
					return new BerOctetStringParser(this);
				}
			}
			else
			{
				switch (tagNo)
				{
				case Asn1Tags.Set:
					throw new Asn1Exception("sequences must use constructed encoding (see X.690 8.9.1/8.10.1)");
				case Asn1Tags.Sequence:
					throw new Asn1Exception("sets must use constructed encoding (see X.690 8.11.1/8.12.1)");
				case Asn1Tags.OctetString:
					return new DerOctetStringParser((DefiniteLengthInputStream)_in);
				}
			}

			throw new Asn1Exception("implicit tagging not implemented");
		}

		internal Asn1Object ReadTaggedObject(int tagClass, int tagNo, bool constructed)
		{
            if (!constructed)
			{
                // Note: !CONSTRUCTED => IMPLICIT
                byte[] contentsOctets = ((DefiniteLengthInputStream)_in).ToArray();
                return Asn1TaggedObject.CreatePrimitive(tagClass, tagNo, contentsOctets);
			}

            bool isIL = (_in is IndefiniteLengthInputStream);
            Asn1EncodableVector contentsElements = ReadVector();
            return Asn1TaggedObject.CreateConstructed(tagClass, tagNo, isIL, contentsElements);
		}

		public virtual IAsn1Convertible ReadObject()
		{
			int tagHdr = _in.ReadByte();
			if (tagHdr == -1)
				return null;

			// turn off looking for "00" while we resolve the tag
			Set00Check(false);

			//
			// calculate tag number
			//
			int tagNo = Asn1InputStream.ReadTagNumber(_in, tagHdr);

			bool isConstructed = (tagHdr & Asn1Tags.Constructed) != 0;

			//
			// calculate length
			//
			int length = Asn1InputStream.ReadLength(_in, _limit,
                tagNo == Asn1Tags.OctetString || tagNo == Asn1Tags.Sequence || tagNo == Asn1Tags.Set ||
                tagNo == Asn1Tags.External);

			if (length < 0) // indefinite-length method
			{
				if (!isConstructed)
					throw new IOException("indefinite-length primitive encoding encountered");

                IndefiniteLengthInputStream indIn = new IndefiniteLengthInputStream(_in, _limit);
                Asn1StreamParser sp = new Asn1StreamParser(indIn, _limit, tmpBuffers);

                int tagClass = tagHdr & Asn1Tags.Private;
                if (0 != tagClass)
                {
                    if (Asn1Tags.Application == tagClass)
                        return new BerApplicationSpecificParser(tagNo, sp);

                    return new BerTaggedObjectParser(tagClass, tagNo, true, sp);
                }

                return sp.ReadIndef(tagNo);
			}
			else
			{
				DefiniteLengthInputStream defIn = new DefiniteLengthInputStream(_in, length, _limit);

                int tagClass = tagHdr & Asn1Tags.Private;
                if (0 != tagClass)
                {
                    Asn1StreamParser sub = new Asn1StreamParser(defIn, defIn.Remaining, tmpBuffers);

                    if (Asn1Tags.Application == tagClass)
                        return (DerApplicationSpecific)sub.ReadTaggedObject(tagClass, tagNo, isConstructed);

                    return new BerTaggedObjectParser(tagClass, tagNo, isConstructed, sub);
                }

                if (!isConstructed)
                {
                    // Some primitive encodings can be handled by parsers too...
                    switch (tagNo)
                    {
                    case Asn1Tags.OctetString:
                        return new DerOctetStringParser(defIn);
                    }

                    try
                    {
                        return Asn1InputStream.CreatePrimitiveDerObject(tagNo, defIn, tmpBuffers);
                    }
                    catch (ArgumentException e)
                    {
                        throw new Asn1Exception("corrupted stream detected", e);
                    }
                }

                Asn1StreamParser sp = new Asn1StreamParser(defIn, defIn.Remaining, tmpBuffers);

                // TODO There are other tags that may be constructed (e.g. BitString)
                switch (tagNo)
				{
				case Asn1Tags.OctetString:
					return new BerOctetStringParser(sp);
				case Asn1Tags.Sequence:
					return new DerSequenceParser(sp);
				case Asn1Tags.Set:
					return new DerSetParser(sp);
				case Asn1Tags.External:
					return new DerExternalParser(sp);
				default:
                    throw new IOException("unknown tag " + tagNo + " encountered");
                }
			}
		}

		private void Set00Check(
			bool enabled)
		{
			if (_in is IndefiniteLengthInputStream)
			{
				((IndefiniteLengthInputStream) _in).SetEofOn00(enabled);
			}
		}

        internal Asn1EncodableVector ReadVector()
        {
            IAsn1Convertible obj = ReadObject();
            if (null == obj)
                return new Asn1EncodableVector(0);

            Asn1EncodableVector v = new Asn1EncodableVector();
            do
            {
                v.Add(obj.ToAsn1Object());
            }
            while ((obj = ReadObject()) != null);
            return v;
        }
	}
}