View Javadoc
1   /*
2    * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
3    * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4    *
5    * This code is free software; you can redistribute it and/or modify it
6    * under the terms of the GNU General Public License version 2 only, as
7    * published by the Free Software Foundation.  Oracle designates this
8    * particular file as subject to the "Classpath" exception as provided
9    * by Oracle in the LICENSE file that accompanied this code.
10   *
11   * This code is distributed in the hope that it will be useful, but WITHOUT
12   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13   * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14   * version 2 for more details (a copy is included in the LICENSE file that
15   * accompanied this code).
16   *
17   * You should have received a copy of the GNU General Public License version
18   * 2 along with this work; if not, write to the Free Software Foundation,
19   * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20   *
21   * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22   * or visit www.oracle.com if you need additional information or have any
23   * questions.
24   */
25  
26  package sun.security.util;
27  
28  import java.io.InputStream;
29  import java.io.IOException;
30  import java.io.EOFException;
31  import java.util.Date;
32  import java.util.Vector;
33  import java.math.BigInteger;
34  import java.io.DataInputStream;
35  
36  /**
37   * A DER input stream, used for parsing ASN.1 DER-encoded data such as
38   * that found in X.509 certificates.  DER is a subset of BER/1, which has
39   * the advantage that it allows only a single encoding of primitive data.
40   * (High level data such as dates still support many encodings.)  That is,
41   * it uses the "Definite" Encoding Rules (DER) not the "Basic" ones (BER).
42   *
43   * <P>Note that, like BER/1, DER streams are streams of explicitly
44   * tagged data values.  Accordingly, this programming interface does
45   * not expose any variant of the java.io.InputStream interface, since
46   * that kind of input stream holds untagged data values and using that
47   * I/O model could prevent correct parsing of the DER data.
48   *
49   * <P>At this time, this class supports only a subset of the types of DER
50   * data encodings which are defined.  That subset is sufficient for parsing
51   * most X.509 certificates.
52   *
53   *
54   * @author David Brownell
55   * @author Amit Kapoor
56   * @author Hemma Prafullchandra
57   */
58  
59  public class DerInputStream {
60  
61      /*
62       * This version only supports fully buffered DER.  This is easy to
63       * work with, though if large objects are manipulated DER becomes
64       * awkward to deal with.  That's where BER is useful, since BER
65       * handles streaming data relatively well.
66       */
67      DerInputBuffer      buffer;
68  
69      /** The DER tag of the value; one of the tag_ constants. */
70      public byte         tag;
71  
72      /**
73       * Create a DER input stream from a data buffer.  The buffer is not
74       * copied, it is shared.  Accordingly, the buffer should be treated
75       * as read-only.
76       *
77       * @param data the buffer from which to create the string (CONSUMED)
78       */
79      public DerInputStream(byte[] data) throws IOException {
80          init(data, 0, data.length);
81      }
82  
83      /**
84       * Create a DER input stream from part of a data buffer.
85       * The buffer is not copied, it is shared.  Accordingly, the
86       * buffer should be treated as read-only.
87       *
88       * @param data the buffer from which to create the string (CONSUMED)
89       * @param offset the first index of <em>data</em> which will
90       *          be read as DER input in the new stream
91       * @param len how long a chunk of the buffer to use,
92       *          starting at "offset"
93       */
94      public DerInputStream(byte[] data, int offset, int len) throws IOException {
95          init(data, offset, len);
96      }
97  
98      /*
99       * private helper routine
100      */
101     private void init(byte[] data, int offset, int len) throws IOException {
102         if ((offset+2 > data.length) || (offset+len > data.length)) {
103             throw new IOException("Encoding bytes too short");
104         }
105         // check for indefinite length encoding
106         if (DerIndefLenConverter.isIndefinite(data[offset+1])) {
107             byte[] inData = new byte[len];
108             System.arraycopy(data, offset, inData, 0, len);
109 
110             DerIndefLenConverter derIn = new DerIndefLenConverter();
111             buffer = new DerInputBuffer(derIn.convert(inData));
112         } else
113             buffer = new DerInputBuffer(data, offset, len);
114         buffer.mark(Integer.MAX_VALUE);
115     }
116 
117     DerInputStream(DerInputBuffer buf) {
118         buffer = buf;
119         buffer.mark(Integer.MAX_VALUE);
120     }
121 
122     /**
123      * Creates a new DER input stream from part of this input stream.
124      *
125      * @param len how long a chunk of the current input stream to use,
126      *          starting at the current position.
127      * @param do_skip true if the existing data in the input stream should
128      *          be skipped.  If this value is false, the next data read
129      *          on this stream and the newly created stream will be the
130      *          same.
131      */
132     public DerInputStream subStream(int len, boolean do_skip)
133     throws IOException {
134         DerInputBuffer  newbuf = buffer.dup();
135 
136         newbuf.truncate(len);
137         if (do_skip) {
138             buffer.skip(len);
139         }
140         return new DerInputStream(newbuf);
141     }
142 
143     /**
144      * Return what has been written to this DerInputStream
145      * as a byte array. Useful for debugging.
146      */
147     public byte[] toByteArray() {
148         return buffer.toByteArray();
149     }
150 
151     /*
152      * PRIMITIVES -- these are "universal" ASN.1 simple types.
153      *
154      *  INTEGER, ENUMERATED, BIT STRING, OCTET STRING, NULL
155      *  OBJECT IDENTIFIER, SEQUENCE (OF), SET (OF)
156      *  UTF8String, PrintableString, T61String, IA5String, UTCTime,
157      *  GeneralizedTime, BMPString.
158      * Note: UniversalString not supported till encoder is available.
159      */
160 
161     /**
162      * Get an integer from the input stream as an integer.
163      *
164      * @return the integer held in this DER input stream.
165      */
166     public int getInteger() throws IOException {
167         if (buffer.read() != DerValue.tag_Integer) {
168             throw new IOException("DER input, Integer tag error");
169         }
170         return buffer.getInteger(getLength(buffer));
171     }
172 
173     /**
174      * Get a integer from the input stream as a BigInteger object.
175      *
176      * @return the integer held in this DER input stream.
177      */
178     public BigInteger getBigInteger() throws IOException {
179         if (buffer.read() != DerValue.tag_Integer) {
180             throw new IOException("DER input, Integer tag error");
181         }
182         return buffer.getBigInteger(getLength(buffer), false);
183     }
184 
185     /**
186      * Returns an ASN.1 INTEGER value as a positive BigInteger.
187      * This is just to deal with implementations that incorrectly encode
188      * some values as negative.
189      *
190      * @return the integer held in this DER value as a BigInteger.
191      */
192     public BigInteger getPositiveBigInteger() throws IOException {
193         if (buffer.read() != DerValue.tag_Integer) {
194             throw new IOException("DER input, Integer tag error");
195         }
196         return buffer.getBigInteger(getLength(buffer), true);
197     }
198 
199     /**
200      * Get an enumerated from the input stream.
201      *
202      * @return the integer held in this DER input stream.
203      */
204     public int getEnumerated() throws IOException {
205         if (buffer.read() != DerValue.tag_Enumerated) {
206             throw new IOException("DER input, Enumerated tag error");
207         }
208         return buffer.getInteger(getLength(buffer));
209     }
210 
211     /**
212      * Get a bit string from the input stream. Padded bits (if any)
213      * will be stripped off before the bit string is returned.
214      */
215     public byte[] getBitString() throws IOException {
216         if (buffer.read() != DerValue.tag_BitString)
217             throw new IOException("DER input not an bit string");
218 
219         return buffer.getBitString(getLength(buffer));
220     }
221 
222     /**
223      * Get a bit string from the input stream.  The bit string need
224      * not be byte-aligned.
225      */
226     public BitArray getUnalignedBitString() throws IOException {
227         if (buffer.read() != DerValue.tag_BitString)
228             throw new IOException("DER input not a bit string");
229 
230         int length = getLength(buffer) - 1;
231 
232         /*
233          * First byte = number of excess bits in the last octet of the
234          * representation.
235          */
236         int validBits = length*8 - buffer.read();
237 
238         byte[] repn = new byte[length];
239 
240         if ((length != 0) && (buffer.read(repn) != length))
241             throw new IOException("short read of DER bit string");
242         return new BitArray(validBits, repn);
243     }
244 
245     /**
246      * Returns an ASN.1 OCTET STRING from the input stream.
247      */
248     public byte[] getOctetString() throws IOException {
249         if (buffer.read() != DerValue.tag_OctetString)
250             throw new IOException("DER input not an octet string");
251 
252         int length = getLength(buffer);
253         byte[] retval = new byte[length];
254         if ((length != 0) && (buffer.read(retval) != length))
255             throw new IOException("short read of DER octet string");
256 
257         return retval;
258     }
259 
260     /**
261      * Returns the asked number of bytes from the input stream.
262      */
263     public void getBytes(byte[] val) throws IOException {
264         if ((val.length != 0) && (buffer.read(val) != val.length)) {
265             throw new IOException("short read of DER octet string");
266         }
267     }
268 
269     /**
270      * Reads an encoded null value from the input stream.
271      */
272     public void getNull() throws IOException {
273         if (buffer.read() != DerValue.tag_Null || buffer.read() != 0)
274             throw new IOException("getNull, bad data");
275     }
276 
277     /**
278      * Reads an X.200 style Object Identifier from the stream.
279      */
280     public ObjectIdentifier getOID() throws IOException {
281         return new ObjectIdentifier(this);
282     }
283 
284     /**
285      * Return a sequence of encoded entities.  ASN.1 sequences are
286      * ordered, and they are often used, like a "struct" in C or C++,
287      * to group data values.  They may have optional or context
288      * specific values.
289      *
290      * @param startLen guess about how long the sequence will be
291      *          (used to initialize an auto-growing data structure)
292      * @return array of the values in the sequence
293      */
294     public DerValue[] getSequence(int startLen) throws IOException {
295         tag = (byte)buffer.read();
296         if (tag != DerValue.tag_Sequence)
297             throw new IOException("Sequence tag error");
298         return readVector(startLen);
299     }
300 
301     /**
302      * Return a set of encoded entities.  ASN.1 sets are unordered,
303      * though DER may specify an order for some kinds of sets (such
304      * as the attributes in an X.500 relative distinguished name)
305      * to facilitate binary comparisons of encoded values.
306      *
307      * @param startLen guess about how large the set will be
308      *          (used to initialize an auto-growing data structure)
309      * @return array of the values in the sequence
310      */
311     public DerValue[] getSet(int startLen) throws IOException {
312         tag = (byte)buffer.read();
313         if (tag != DerValue.tag_Set)
314             throw new IOException("Set tag error");
315         return readVector(startLen);
316     }
317 
318     /**
319      * Return a set of encoded entities.  ASN.1 sets are unordered,
320      * though DER may specify an order for some kinds of sets (such
321      * as the attributes in an X.500 relative distinguished name)
322      * to facilitate binary comparisons of encoded values.
323      *
324      * @param startLen guess about how large the set will be
325      *          (used to initialize an auto-growing data structure)
326      * @param implicit if true tag is assumed implicit.
327      * @return array of the values in the sequence
328      */
329     public DerValue[] getSet(int startLen, boolean implicit)
330         throws IOException {
331         tag = (byte)buffer.read();
332         if (!implicit) {
333             if (tag != DerValue.tag_Set) {
334                 throw new IOException("Set tag error");
335             }
336         }
337         return (readVector(startLen));
338     }
339 
340     /*
341      * Read a "vector" of values ... set or sequence have the
342      * same encoding, except for the initial tag, so both use
343      * this same helper routine.
344      */
345     protected DerValue[] readVector(int startLen) throws IOException {
346         DerInputStream  newstr;
347 
348         byte lenByte = (byte)buffer.read();
349         int len = getLength((lenByte & 0xff), buffer);
350 
351         if (len == -1) {
352            // indefinite length encoding found
353            int readLen = buffer.available();
354            int offset = 2;     // for tag and length bytes
355            byte[] indefData = new byte[readLen + offset];
356            indefData[0] = tag;
357            indefData[1] = lenByte;
358            DataInputStream dis = new DataInputStream(buffer);
359            dis.readFully(indefData, offset, readLen);
360            dis.close();
361            DerIndefLenConverter derIn = new DerIndefLenConverter();
362            buffer = new DerInputBuffer(derIn.convert(indefData));
363            if (tag != buffer.read())
364                 throw new IOException("Indefinite length encoding" +
365                         " not supported");
366            len = DerInputStream.getLength(buffer);
367         }
368 
369         if (len == 0)
370             // return empty array instead of null, which should be
371             // used only for missing optionals
372             return new DerValue[0];
373 
374         /*
375          * Create a temporary stream from which to read the data,
376          * unless it's not really needed.
377          */
378         if (buffer.available() == len)
379             newstr = this;
380         else
381             newstr = subStream(len, true);
382 
383         /*
384          * Pull values out of the stream.
385          */
386         Vector<DerValue> vec = new Vector<DerValue>(startLen);
387         DerValue value;
388 
389         do {
390             value = new DerValue(newstr.buffer);
391             vec.addElement(value);
392         } while (newstr.available() > 0);
393 
394         if (newstr.available() != 0)
395             throw new IOException("extra data at end of vector");
396 
397         /*
398          * Now stick them into the array we're returning.
399          */
400         int             i, max = vec.size();
401         DerValue[]      retval = new DerValue[max];
402 
403         for (i = 0; i < max; i++)
404             retval[i] = vec.elementAt(i);
405 
406         return retval;
407     }
408 
409     /**
410      * Get a single DER-encoded value from the input stream.
411      * It can often be useful to pull a value from the stream
412      * and defer parsing it.  For example, you can pull a nested
413      * sequence out with one call, and only examine its elements
414      * later when you really need to.
415      */
416     public DerValue getDerValue() throws IOException {
417         return new DerValue(buffer);
418     }
419 
420     /**
421      * Read a string that was encoded as a UTF8String DER value.
422      */
423     public String getUTF8String() throws IOException {
424         return readString(DerValue.tag_UTF8String, "UTF-8", "UTF8");
425     }
426 
427     /**
428      * Read a string that was encoded as a PrintableString DER value.
429      */
430     public String getPrintableString() throws IOException {
431         return readString(DerValue.tag_PrintableString, "Printable",
432                           "ASCII");
433     }
434 
435     /**
436      * Read a string that was encoded as a T61String DER value.
437      */
438     public String getT61String() throws IOException {
439         /*
440          * Works for common characters between T61 and ASCII.
441          */
442         return readString(DerValue.tag_T61String, "T61", "ISO-8859-1");
443     }
444 
445     /**
446      * Read a string that was encoded as a IA5tring DER value.
447      */
448     public String getIA5String() throws IOException {
449         return readString(DerValue.tag_IA5String, "IA5", "ASCII");
450     }
451 
452     /**
453      * Read a string that was encoded as a BMPString DER value.
454      */
455     public String getBMPString() throws IOException {
456         return readString(DerValue.tag_BMPString, "BMP",
457                           "UnicodeBigUnmarked");
458     }
459 
460     /**
461      * Read a string that was encoded as a GeneralString DER value.
462      */
463     public String getGeneralString() throws IOException {
464         return readString(DerValue.tag_GeneralString, "General",
465                           "ASCII");
466     }
467 
468     /**
469      * Private helper routine to read an encoded string from the input
470      * stream.
471      * @param stringTag the tag for the type of string to read
472      * @param stringName a name to display in error messages
473      * @param enc the encoder to use to interpret the data. Should
474      * correspond to the stringTag above.
475      */
476     private String readString(byte stringTag, String stringName,
477                               String enc) throws IOException {
478 
479         if (buffer.read() != stringTag)
480             throw new IOException("DER input not a " +
481                                   stringName + " string");
482 
483         int length = getLength(buffer);
484         byte[] retval = new byte[length];
485         if ((length != 0) && (buffer.read(retval) != length))
486             throw new IOException("short read of DER " +
487                                   stringName + " string");
488 
489         return new String(retval, enc);
490     }
491 
492     /**
493      * Get a UTC encoded time value from the input stream.
494      */
495     public Date getUTCTime() throws IOException {
496         if (buffer.read() != DerValue.tag_UtcTime)
497             throw new IOException("DER input, UTCtime tag invalid ");
498         return buffer.getUTCTime(getLength(buffer));
499     }
500 
501     /**
502      * Get a Generalized encoded time value from the input stream.
503      */
504     public Date getGeneralizedTime() throws IOException {
505         if (buffer.read() != DerValue.tag_GeneralizedTime)
506             throw new IOException("DER input, GeneralizedTime tag invalid ");
507         return buffer.getGeneralizedTime(getLength(buffer));
508     }
509 
510     /*
511      * Get a byte from the input stream.
512      */
513     // package private
514     int getByte() throws IOException {
515         return (0x00ff & buffer.read());
516     }
517 
518     public int peekByte() throws IOException {
519         return buffer.peek();
520     }
521 
522     // package private
523     int getLength() throws IOException {
524         return getLength(buffer);
525     }
526 
527     /*
528      * Get a length from the input stream, allowing for at most 32 bits of
529      * encoding to be used.  (Not the same as getting a tagged integer!)
530      *
531      * @return the length or -1 if indefinite length found.
532      * @exception IOException on parsing error or unsupported lengths.
533      */
534     static int getLength(InputStream in) throws IOException {
535         return getLength(in.read(), in);
536     }
537 
538     /*
539      * Get a length from the input stream, allowing for at most 32 bits of
540      * encoding to be used.  (Not the same as getting a tagged integer!)
541      *
542      * @return the length or -1 if indefinite length found.
543      * @exception IOException on parsing error or unsupported lengths.
544      */
545     static int getLength(int lenByte, InputStream in) throws IOException {
546         int value, tmp;
547 
548         tmp = lenByte;
549         if ((tmp & 0x080) == 0x00) { // short form, 1 byte datum
550             value = tmp;
551         } else {                     // long form or indefinite
552             tmp &= 0x07f;
553 
554             /*
555              * NOTE:  tmp == 0 indicates indefinite length encoded data.
556              * tmp > 4 indicates more than 4Gb of data.
557              */
558             if (tmp == 0)
559                 return -1;
560             if (tmp < 0 || tmp > 4)
561                 throw new IOException("DerInputStream.getLength(): lengthTag="
562                     + tmp + ", "
563                     + ((tmp < 0) ? "incorrect DER encoding." : "too big."));
564 
565             for (value = 0; tmp > 0; tmp --) {
566                 value <<= 8;
567                 value += 0x0ff & in.read();
568             }
569         }
570         return value;
571     }
572 
573     /**
574      * Mark the current position in the buffer, so that
575      * a later call to <code>reset</code> will return here.
576      */
577     public void mark(int value) { buffer.mark(value); }
578 
579 
580     /**
581      * Return to the position of the last <code>mark</code>
582      * call.  A mark is implicitly set at the beginning of
583      * the stream when it is created.
584      */
585     public void reset() { buffer.reset(); }
586 
587 
588     /**
589      * Returns the number of bytes available for reading.
590      * This is most useful for testing whether the stream is
591      * empty.
592      */
593     public int available() { return buffer.available(); }
594 }