Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/sun/security/util/DerInputStream.java
38830 views
/*1* Copyright (c) 1996, 2017, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package sun.security.util;2627import java.io.InputStream;28import java.io.IOException;29import java.io.EOFException;30import java.util.Date;31import java.util.Vector;32import java.math.BigInteger;33import java.io.DataInputStream;3435/**36* A DER input stream, used for parsing ASN.1 DER-encoded data such as37* that found in X.509 certificates. DER is a subset of BER/1, which has38* the advantage that it allows only a single encoding of primitive data.39* (High level data such as dates still support many encodings.) That is,40* it uses the "Definite" Encoding Rules (DER) not the "Basic" ones (BER).41*42* <P>Note that, like BER/1, DER streams are streams of explicitly43* tagged data values. Accordingly, this programming interface does44* not expose any variant of the java.io.InputStream interface, since45* that kind of input stream holds untagged data values and using that46* I/O model could prevent correct parsing of the DER data.47*48* <P>At this time, this class supports only a subset of the types of DER49* data encodings which are defined. That subset is sufficient for parsing50* most X.509 certificates.51*52*53* @author David Brownell54* @author Amit Kapoor55* @author Hemma Prafullchandra56*/5758public class DerInputStream {5960/*61* This version only supports fully buffered DER. This is easy to62* work with, though if large objects are manipulated DER becomes63* awkward to deal with. That's where BER is useful, since BER64* handles streaming data relatively well.65*/66DerInputBuffer buffer;6768/** The DER tag of the value; one of the tag_ constants. */69public byte tag;7071/**72* Create a DER input stream from a data buffer. The buffer is not73* copied, it is shared. Accordingly, the buffer should be treated74* as read-only.75*76* @param data the buffer from which to create the string (CONSUMED)77*/78public DerInputStream(byte[] data) throws IOException {79init(data, 0, data.length, true);80}8182/**83* Create a DER input stream from part of a data buffer with84* additional arg to control whether DER checks are enforced.85* The buffer is not copied, it is shared. Accordingly, the86* 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 will90* be read as DER input in the new stream91* @param len how long a chunk of the buffer to use,92* starting at "offset"93* @param allowBER whether to allow constructed indefinite-length94* encoding as well as tolerate leading 0s95*/96public DerInputStream(byte[] data, int offset, int len,97boolean allowBER) throws IOException {98init(data, offset, len, allowBER);99}100101/**102* Create a DER input stream from part of a data buffer.103* The buffer is not copied, it is shared. Accordingly, the104* buffer should be treated as read-only.105*106* @param data the buffer from which to create the string (CONSUMED)107* @param offset the first index of <em>data</em> which will108* be read as DER input in the new stream109* @param len how long a chunk of the buffer to use,110* starting at "offset"111*/112public DerInputStream(byte[] data, int offset, int len) throws IOException {113init(data, offset, len, true);114}115116/*117* private helper routine118*/119private void init(byte[] data, int offset, int len, boolean allowBER) throws IOException {120if ((offset+2 > data.length) || (offset+len > data.length)) {121throw new IOException("Encoding bytes too short");122}123// check for indefinite length encoding124if (DerIndefLenConverter.isIndefinite(data[offset+1])) {125if (!allowBER) {126throw new IOException("Indefinite length BER encoding found");127} else {128byte[] inData = new byte[len];129System.arraycopy(data, offset, inData, 0, len);130131DerIndefLenConverter derIn = new DerIndefLenConverter();132buffer = new DerInputBuffer(derIn.convert(inData), allowBER);133}134} else {135buffer = new DerInputBuffer(data, offset, len, allowBER);136}137buffer.mark(Integer.MAX_VALUE);138}139140DerInputStream(DerInputBuffer buf) {141buffer = buf;142buffer.mark(Integer.MAX_VALUE);143}144145/**146* Creates a new DER input stream from part of this input stream.147*148* @param len how long a chunk of the current input stream to use,149* starting at the current position.150* @param do_skip true if the existing data in the input stream should151* be skipped. If this value is false, the next data read152* on this stream and the newly created stream will be the153* same.154*/155public DerInputStream subStream(int len, boolean do_skip)156throws IOException {157DerInputBuffer newbuf = buffer.dup();158159newbuf.truncate(len);160if (do_skip) {161buffer.skip(len);162}163return new DerInputStream(newbuf);164}165166/**167* Return what has been written to this DerInputStream168* as a byte array. Useful for debugging.169*/170public byte[] toByteArray() {171return buffer.toByteArray();172}173174/*175* PRIMITIVES -- these are "universal" ASN.1 simple types.176*177* INTEGER, ENUMERATED, BIT STRING, OCTET STRING, NULL178* OBJECT IDENTIFIER, SEQUENCE (OF), SET (OF)179* UTF8String, PrintableString, T61String, IA5String, UTCTime,180* GeneralizedTime, BMPString.181* Note: UniversalString not supported till encoder is available.182*/183184/**185* Get an integer from the input stream as an integer.186*187* @return the integer held in this DER input stream.188*/189public int getInteger() throws IOException {190if (buffer.read() != DerValue.tag_Integer) {191throw new IOException("DER input, Integer tag error");192}193return buffer.getInteger(getDefiniteLength(buffer));194}195196/**197* Get a integer from the input stream as a BigInteger object.198*199* @return the integer held in this DER input stream.200*/201public BigInteger getBigInteger() throws IOException {202if (buffer.read() != DerValue.tag_Integer) {203throw new IOException("DER input, Integer tag error");204}205return buffer.getBigInteger(getDefiniteLength(buffer), false);206}207208/**209* Returns an ASN.1 INTEGER value as a positive BigInteger.210* This is just to deal with implementations that incorrectly encode211* some values as negative.212*213* @return the integer held in this DER value as a BigInteger.214*/215public BigInteger getPositiveBigInteger() throws IOException {216if (buffer.read() != DerValue.tag_Integer) {217throw new IOException("DER input, Integer tag error");218}219return buffer.getBigInteger(getDefiniteLength(buffer), true);220}221222/**223* Get an enumerated from the input stream.224*225* @return the integer held in this DER input stream.226*/227public int getEnumerated() throws IOException {228if (buffer.read() != DerValue.tag_Enumerated) {229throw new IOException("DER input, Enumerated tag error");230}231return buffer.getInteger(getDefiniteLength(buffer));232}233234/**235* Get a bit string from the input stream. Padded bits (if any)236* will be stripped off before the bit string is returned.237*/238public byte[] getBitString() throws IOException {239if (buffer.read() != DerValue.tag_BitString)240throw new IOException("DER input not an bit string");241242return buffer.getBitString(getDefiniteLength(buffer));243}244245/**246* Get a bit string from the input stream. The bit string need247* not be byte-aligned.248*/249public BitArray getUnalignedBitString() throws IOException {250if (buffer.read() != DerValue.tag_BitString) {251throw new IOException("DER input not a bit string");252}253254int length = getDefiniteLength(buffer);255256if (length == 0) {257return new BitArray(0);258}259260/*261* First byte = number of excess bits in the last octet of the262* representation.263*/264length--;265int excessBits = buffer.read();266if (excessBits < 0) {267throw new IOException("Unused bits of bit string invalid");268}269int validBits = length*8 - excessBits;270if (validBits < 0) {271throw new IOException("Valid bits of bit string invalid");272}273274byte[] repn = new byte[length];275276if ((length != 0) && (buffer.read(repn) != length)) {277throw new IOException("Short read of DER bit string");278}279280return new BitArray(validBits, repn);281}282283/**284* Returns an ASN.1 OCTET STRING from the input stream.285*/286public byte[] getOctetString() throws IOException {287if (buffer.read() != DerValue.tag_OctetString)288throw new IOException("DER input not an octet string");289290int length = getDefiniteLength(buffer);291byte[] retval = new byte[length];292if ((length != 0) && (buffer.read(retval) != length))293throw new IOException("Short read of DER octet string");294295return retval;296}297298/**299* Returns the asked number of bytes from the input stream.300*/301public void getBytes(byte[] val) throws IOException {302if ((val.length != 0) && (buffer.read(val) != val.length)) {303throw new IOException("Short read of DER octet string");304}305}306307/**308* Reads an encoded null value from the input stream.309*/310public void getNull() throws IOException {311if (buffer.read() != DerValue.tag_Null || buffer.read() != 0)312throw new IOException("getNull, bad data");313}314315/**316* Reads an X.200 style Object Identifier from the stream.317*/318public ObjectIdentifier getOID() throws IOException {319return new ObjectIdentifier(this);320}321322/**323* Return a sequence of encoded entities. ASN.1 sequences are324* ordered, and they are often used, like a "struct" in C or C++,325* to group data values. They may have optional or context326* specific values.327*328* @param startLen guess about how long the sequence will be329* (used to initialize an auto-growing data structure)330* @return array of the values in the sequence331*/332public DerValue[] getSequence(int startLen) throws IOException {333tag = (byte)buffer.read();334if (tag != DerValue.tag_Sequence)335throw new IOException("Sequence tag error");336return readVector(startLen);337}338339/**340* Return a set of encoded entities. ASN.1 sets are unordered,341* though DER may specify an order for some kinds of sets (such342* as the attributes in an X.500 relative distinguished name)343* to facilitate binary comparisons of encoded values.344*345* @param startLen guess about how large the set will be346* (used to initialize an auto-growing data structure)347* @return array of the values in the sequence348*/349public DerValue[] getSet(int startLen) throws IOException {350tag = (byte)buffer.read();351if (tag != DerValue.tag_Set)352throw new IOException("Set tag error");353return readVector(startLen);354}355356/**357* Return a set of encoded entities. ASN.1 sets are unordered,358* though DER may specify an order for some kinds of sets (such359* as the attributes in an X.500 relative distinguished name)360* to facilitate binary comparisons of encoded values.361*362* @param startLen guess about how large the set will be363* (used to initialize an auto-growing data structure)364* @param implicit if true tag is assumed implicit.365* @return array of the values in the sequence366*/367public DerValue[] getSet(int startLen, boolean implicit)368throws IOException {369tag = (byte)buffer.read();370if (!implicit) {371if (tag != DerValue.tag_Set) {372throw new IOException("Set tag error");373}374}375return (readVector(startLen));376}377378/*379* Read a "vector" of values ... set or sequence have the380* same encoding, except for the initial tag, so both use381* this same helper routine.382*/383protected DerValue[] readVector(int startLen) throws IOException {384DerInputStream newstr;385386byte lenByte = (byte)buffer.read();387int len = getLength(lenByte, buffer);388389if (len == -1) {390// indefinite length encoding found391int readLen = buffer.available();392int offset = 2; // for tag and length bytes393byte[] indefData = new byte[readLen + offset];394indefData[0] = tag;395indefData[1] = lenByte;396DataInputStream dis = new DataInputStream(buffer);397dis.readFully(indefData, offset, readLen);398dis.close();399DerIndefLenConverter derIn = new DerIndefLenConverter();400buffer = new DerInputBuffer(derIn.convert(indefData), buffer.allowBER);401402if (tag != buffer.read())403throw new IOException("Indefinite length encoding" +404" not supported");405len = DerInputStream.getDefiniteLength(buffer);406}407408if (len == 0)409// return empty array instead of null, which should be410// used only for missing optionals411return new DerValue[0];412413/*414* Create a temporary stream from which to read the data,415* unless it's not really needed.416*/417if (buffer.available() == len)418newstr = this;419else420newstr = subStream(len, true);421422/*423* Pull values out of the stream.424*/425Vector<DerValue> vec = new Vector<DerValue>(startLen);426DerValue value;427428do {429value = new DerValue(newstr.buffer, buffer.allowBER);430vec.addElement(value);431} while (newstr.available() > 0);432433if (newstr.available() != 0)434throw new IOException("Extra data at end of vector");435436/*437* Now stick them into the array we're returning.438*/439int i, max = vec.size();440DerValue[] retval = new DerValue[max];441442for (i = 0; i < max; i++)443retval[i] = vec.elementAt(i);444445return retval;446}447448/**449* Get a single DER-encoded value from the input stream.450* It can often be useful to pull a value from the stream451* and defer parsing it. For example, you can pull a nested452* sequence out with one call, and only examine its elements453* later when you really need to.454*/455public DerValue getDerValue() throws IOException {456return new DerValue(buffer);457}458459/**460* Read a string that was encoded as a UTF8String DER value.461*/462public String getUTF8String() throws IOException {463return readString(DerValue.tag_UTF8String, "UTF-8", "UTF8");464}465466/**467* Read a string that was encoded as a PrintableString DER value.468*/469public String getPrintableString() throws IOException {470return readString(DerValue.tag_PrintableString, "Printable",471"ASCII");472}473474/**475* Read a string that was encoded as a T61String DER value.476*/477public String getT61String() throws IOException {478/*479* Works for common characters between T61 and ASCII.480*/481return readString(DerValue.tag_T61String, "T61", "ISO-8859-1");482}483484/**485* Read a string that was encoded as a IA5tring DER value.486*/487public String getIA5String() throws IOException {488return readString(DerValue.tag_IA5String, "IA5", "ASCII");489}490491/**492* Read a string that was encoded as a BMPString DER value.493*/494public String getBMPString() throws IOException {495return readString(DerValue.tag_BMPString, "BMP",496"UnicodeBigUnmarked");497}498499/**500* Read a string that was encoded as a GeneralString DER value.501*/502public String getGeneralString() throws IOException {503return readString(DerValue.tag_GeneralString, "General",504"ASCII");505}506507/**508* Private helper routine to read an encoded string from the input509* stream.510* @param stringTag the tag for the type of string to read511* @param stringName a name to display in error messages512* @param enc the encoder to use to interpret the data. Should513* correspond to the stringTag above.514*/515private String readString(byte stringTag, String stringName,516String enc) throws IOException {517518if (buffer.read() != stringTag)519throw new IOException("DER input not a " +520stringName + " string");521522int length = getDefiniteLength(buffer);523byte[] retval = new byte[length];524if ((length != 0) && (buffer.read(retval) != length))525throw new IOException("Short read of DER " +526stringName + " string");527528return new String(retval, enc);529}530531/**532* Get a UTC encoded time value from the input stream.533*/534public Date getUTCTime() throws IOException {535if (buffer.read() != DerValue.tag_UtcTime)536throw new IOException("DER input, UTCtime tag invalid ");537return buffer.getUTCTime(getDefiniteLength(buffer));538}539540/**541* Get a Generalized encoded time value from the input stream.542*/543public Date getGeneralizedTime() throws IOException {544if (buffer.read() != DerValue.tag_GeneralizedTime)545throw new IOException("DER input, GeneralizedTime tag invalid ");546return buffer.getGeneralizedTime(getDefiniteLength(buffer));547}548549/*550* Get a byte from the input stream.551*/552// package private553int getByte() throws IOException {554return (0x00ff & buffer.read());555}556557public int peekByte() throws IOException {558return buffer.peek();559}560561// package private562int getLength() throws IOException {563return getLength(buffer);564}565566/*567* Get a length from the input stream, allowing for at most 32 bits of568* encoding to be used. (Not the same as getting a tagged integer!)569*570* @return the length or -1 if indefinite length found.571* @exception IOException on parsing error or unsupported lengths.572*/573static int getLength(InputStream in) throws IOException {574return getLength(in.read(), in);575}576577/*578* Get a length from the input stream, allowing for at most 32 bits of579* encoding to be used. (Not the same as getting a tagged integer!)580*581* @return the length or -1 if indefinite length found.582* @exception IOException on parsing error or unsupported lengths.583*/584static int getLength(int lenByte, InputStream in) throws IOException {585int value, tmp;586if (lenByte == -1) {587throw new IOException("Short read of DER length");588}589590String mdName = "DerInputStream.getLength(): ";591tmp = lenByte;592if ((tmp & 0x080) == 0x00) { // short form, 1 byte datum593value = tmp;594} else { // long form or indefinite595tmp &= 0x07f;596597/*598* NOTE: tmp == 0 indicates indefinite length encoded data.599* tmp > 4 indicates more than 4Gb of data.600*/601if (tmp == 0)602return -1;603if (tmp < 0 || tmp > 4)604throw new IOException(mdName + "lengthTag=" + tmp + ", "605+ ((tmp < 0) ? "incorrect DER encoding." : "too big."));606607value = 0x0ff & in.read();608tmp--;609if (value == 0) {610// DER requires length value be encoded in minimum number of bytes611throw new IOException(mdName + "Redundant length bytes found");612}613while (tmp-- > 0) {614value <<= 8;615value += 0x0ff & in.read();616}617if (value < 0) {618throw new IOException(mdName + "Invalid length bytes");619} else if (value <= 127) {620throw new IOException(mdName + "Should use short form for length");621}622}623return value;624}625626int getDefiniteLength() throws IOException {627return getDefiniteLength(buffer);628}629630/*631* Get a length from the input stream.632*633* @return the length634* @exception IOException on parsing error or if indefinite length found.635*/636static int getDefiniteLength(InputStream in) throws IOException {637int len = getLength(in);638if (len < 0) {639throw new IOException("Indefinite length encoding not supported");640}641return len;642}643644/**645* Mark the current position in the buffer, so that646* a later call to <code>reset</code> will return here.647*/648public void mark(int value) { buffer.mark(value); }649650651/**652* Return to the position of the last <code>mark</code>653* call. A mark is implicitly set at the beginning of654* the stream when it is created.655*/656public void reset() { buffer.reset(); }657658659/**660* Returns the number of bytes available for reading.661* This is most useful for testing whether the stream is662* empty.663*/664public int available() { return buffer.available(); }665}666667668