8249783: Simplify DerValue and DerInputStream

Reviewed-by: valeriep
This commit is contained in:
Weijun Wang 2020-10-01 18:55:35 +00:00
parent 9230c2aaae
commit 3c4e824aa5
8 changed files with 867 additions and 1501 deletions

View File

@ -372,19 +372,18 @@ class DerIndefLenConverter {
* This may block.
*
* @param in the input stream with tag and lenByte already read
* @param lenByte the length of the length field to remember
* @param tag the tag to remember
* @return a DER byte array
* @throws IOException if not all indef len BER
* can be resolved or another I/O error happens
*/
public static byte[] convertStream(InputStream in, byte lenByte, byte tag)
public static byte[] convertStream(InputStream in, byte tag)
throws IOException {
int offset = 2; // for tag and length bytes
int readLen = in.available();
byte[] indefData = new byte[readLen + offset];
indefData[0] = tag;
indefData[1] = lenByte;
indefData[1] = (byte)0x80;
while (true) {
int bytesRead = in.readNBytes(indefData, offset, readLen);
if (bytesRead != readLen) {

View File

@ -1,475 +0,0 @@
/*
* Copyright (c) 1996, 2020, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.security.util;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Date;
import sun.util.calendar.CalendarDate;
import sun.util.calendar.CalendarSystem;
/**
* DER input buffer ... this is the main abstraction in the DER library
* which actively works with the "untyped byte stream" abstraction. It
* does so with impunity, since it's not intended to be exposed to
* anyone who could violate the "typed value stream" DER model and hence
* corrupt the input stream of DER values.
*
* @author David Brownell
*/
class DerInputBuffer extends ByteArrayInputStream implements Cloneable {
boolean allowBER = true;
// used by sun/security/util/DerInputBuffer/DerInputBufferEqualsHashCode.java
DerInputBuffer(byte[] buf) {
this(buf, true);
}
DerInputBuffer(byte[] buf, boolean allowBER) {
super(buf);
this.allowBER = allowBER;
}
DerInputBuffer(byte[] buf, int offset, int len, boolean allowBER) {
super(buf, offset, len);
this.allowBER = allowBER;
}
DerInputBuffer dup() {
try {
DerInputBuffer retval = (DerInputBuffer)clone();
retval.mark(Integer.MAX_VALUE);
return retval;
} catch (CloneNotSupportedException e) {
throw new IllegalArgumentException(e.toString());
}
}
byte[] toByteArray() {
int len = available();
if (len <= 0)
return null;
byte[] retval = new byte[len];
System.arraycopy(buf, pos, retval, 0, len);
return retval;
}
int peek() throws IOException {
if (pos >= count)
throw new IOException("out of data");
else
return buf[pos];
}
/**
* Compares this DerInputBuffer for equality with the specified
* object.
*/
public boolean equals(Object other) {
if (other instanceof DerInputBuffer)
return equals((DerInputBuffer)other);
else
return false;
}
boolean equals(DerInputBuffer other) {
if (this == other)
return true;
int max = this.available();
if (other.available() != max)
return false;
for (int i = 0; i < max; i++) {
if (this.buf[this.pos + i] != other.buf[other.pos + i]) {
return false;
}
}
return true;
}
/**
* Returns a hashcode for this DerInputBuffer.
*
* @return a hashcode for this DerInputBuffer.
*/
public int hashCode() {
int retval = 0;
int len = available();
int p = pos;
for (int i = 0; i < len; i++)
retval += buf[p + i] * i;
return retval;
}
void truncate(int len) throws IOException {
if (len > available())
throw new IOException("insufficient data");
count = pos + len;
}
/**
* Returns the integer which takes up the specified number
* of bytes in this buffer as a BigInteger.
* @param len the number of bytes to use.
* @param makePositive whether to always return a positive value,
* irrespective of actual encoding
* @return the integer as a BigInteger.
*/
BigInteger getBigInteger(int len, boolean makePositive) throws IOException {
if (len > available())
throw new IOException("short read of integer");
if (len == 0) {
throw new IOException("Invalid encoding: zero length Int value");
}
byte[] bytes = new byte[len];
System.arraycopy(buf, pos, bytes, 0, len);
skip(len);
// BER allows leading 0s but DER does not
if (!allowBER && (len >= 2 && (bytes[0] == 0) && (bytes[1] >= 0))) {
throw new IOException("Invalid encoding: redundant leading 0s");
}
if (makePositive) {
return new BigInteger(1, bytes);
} else {
return new BigInteger(bytes);
}
}
/**
* Returns the integer which takes up the specified number
* of bytes in this buffer.
* @throws IOException if the result is not within the valid
* range for integer, i.e. between Integer.MIN_VALUE and
* Integer.MAX_VALUE.
* @param len the number of bytes to use.
* @return the integer.
*/
public int getInteger(int len) throws IOException {
BigInteger result = getBigInteger(len, false);
if (result.compareTo(BigInteger.valueOf(Integer.MIN_VALUE)) < 0) {
throw new IOException("Integer below minimum valid value");
}
if (result.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) > 0) {
throw new IOException("Integer exceeds maximum valid value");
}
return result.intValue();
}
/**
* Returns the bit string which takes up the specified
* number of bytes in this buffer.
*/
public byte[] getBitString(int len) throws IOException {
if (len > available())
throw new IOException("short read of bit string");
if (len == 0) {
throw new IOException("Invalid encoding: zero length bit string");
}
int numOfPadBits = buf[pos];
if ((numOfPadBits < 0) || (numOfPadBits > 7)) {
throw new IOException("Invalid number of padding bits");
}
// minus the first byte which indicates the number of padding bits
byte[] retval = new byte[len - 1];
System.arraycopy(buf, pos + 1, retval, 0, len - 1);
if (numOfPadBits != 0) {
// get rid of the padding bits
retval[len - 2] &= (0xff << numOfPadBits);
}
skip(len);
return retval;
}
/**
* Returns the bit string which takes up the rest of this buffer.
*/
byte[] getBitString() throws IOException {
return getBitString(available());
}
/**
* Returns the bit string which takes up the rest of this buffer.
* The bit string need not be byte-aligned.
*/
BitArray getUnalignedBitString() throws IOException {
if (pos >= count)
return null;
/*
* Just copy the data into an aligned, padded octet buffer,
* and consume the rest of the buffer.
*/
int len = available();
int unusedBits = buf[pos] & 0xff;
if (unusedBits > 7 ) {
throw new IOException("Invalid value for unused bits: " + unusedBits);
}
byte[] bits = new byte[len - 1];
// number of valid bits
int length = (bits.length == 0) ? 0 : bits.length * 8 - unusedBits;
System.arraycopy(buf, pos + 1, bits, 0, len - 1);
BitArray bitArray = new BitArray(length, bits);
pos = count;
return bitArray;
}
/**
* Returns the UTC Time value that takes up the specified number
* of bytes in this buffer.
* @param len the number of bytes to use
*/
public Date getUTCTime(int len) throws IOException {
if (len > available())
throw new IOException("short read of DER UTC Time");
if (len < 11 || len > 17)
throw new IOException("DER UTC Time length error");
return getTime(len, false);
}
/**
* Returns the Generalized Time value that takes up the specified
* number of bytes in this buffer.
* @param len the number of bytes to use
*/
public Date getGeneralizedTime(int len) throws IOException {
if (len > available())
throw new IOException("short read of DER Generalized Time");
if (len < 13)
throw new IOException("DER Generalized Time length error");
return getTime(len, true);
}
/**
* Private helper routine to extract time from the der value.
* @param len the number of bytes to use
* @param generalized true if Generalized Time is to be read, false
* if UTC Time is to be read.
*/
private Date getTime(int len, boolean generalized) throws IOException {
/*
* UTC time encoded as ASCII chars:
* YYMMDDhhmmZ
* YYMMDDhhmmssZ
* YYMMDDhhmm+hhmm
* YYMMDDhhmm-hhmm
* YYMMDDhhmmss+hhmm
* YYMMDDhhmmss-hhmm
* UTC Time is broken in storing only two digits of year.
* If YY < 50, we assume 20YY;
* if YY >= 50, we assume 19YY, as per RFC 5280.
*
* Generalized time has a four-digit year and allows any
* precision specified in ISO 8601. However, for our purposes,
* we will only allow the same format as UTC time, except that
* fractional seconds (millisecond precision) are supported.
*/
int year, month, day, hour, minute, second, millis;
String type = null;
if (generalized) {
type = "Generalized";
year = 1000 * toDigit(buf[pos++], type);
year += 100 * toDigit(buf[pos++], type);
year += 10 * toDigit(buf[pos++], type);
year += toDigit(buf[pos++], type);
len -= 2; // For the two extra YY
} else {
type = "UTC";
year = 10 * toDigit(buf[pos++], type);
year += toDigit(buf[pos++], type);
if (year < 50) // origin 2000
year += 2000;
else
year += 1900; // origin 1900
}
month = 10 * toDigit(buf[pos++], type);
month += toDigit(buf[pos++], type);
day = 10 * toDigit(buf[pos++], type);
day += toDigit(buf[pos++], type);
hour = 10 * toDigit(buf[pos++], type);
hour += toDigit(buf[pos++], type);
minute = 10 * toDigit(buf[pos++], type);
minute += toDigit(buf[pos++], type);
len -= 10; // YYMMDDhhmm
/*
* We allow for non-encoded seconds, even though the
* IETF-PKIX specification says that the seconds should
* always be encoded even if it is zero.
*/
millis = 0;
if (len > 2) {
second = 10 * toDigit(buf[pos++], type);
second += toDigit(buf[pos++], type);
len -= 2;
// handle fractional seconds (if present)
if (generalized && (buf[pos] == '.' || buf[pos] == ',')) {
len --;
if (len == 0) {
throw new IOException("Parse " + type +
" time, empty fractional part");
}
pos++;
int precision = 0;
while (buf[pos] != 'Z' &&
buf[pos] != '+' &&
buf[pos] != '-') {
// Validate all digits in the fractional part but
// store millisecond precision only
int thisDigit = toDigit(buf[pos], type);
precision++;
len--;
if (len == 0) {
throw new IOException("Parse " + type +
" time, invalid fractional part");
}
pos++;
switch (precision) {
case 1:
millis += 100 * thisDigit;
break;
case 2:
millis += 10 * thisDigit;
break;
case 3:
millis += thisDigit;
break;
}
}
if (precision == 0) {
throw new IOException("Parse " + type +
" time, empty fractional part");
}
}
} else
second = 0;
if (month == 0 || day == 0
|| month > 12 || day > 31
|| hour >= 24 || minute >= 60 || second >= 60)
throw new IOException("Parse " + type + " time, invalid format");
/*
* Generalized time can theoretically allow any precision,
* but we're not supporting that.
*/
CalendarSystem gcal = CalendarSystem.getGregorianCalendar();
CalendarDate date = gcal.newCalendarDate(null); // no time zone
date.setDate(year, month, day);
date.setTimeOfDay(hour, minute, second, millis);
long time = gcal.getTime(date);
/*
* Finally, "Z" or "+hhmm" or "-hhmm" ... offsets change hhmm
*/
if (! (len == 1 || len == 5))
throw new IOException("Parse " + type + " time, invalid offset");
int hr, min;
switch (buf[pos++]) {
case '+':
if (len != 5) {
throw new IOException("Parse " + type + " time, invalid offset");
}
hr = 10 * toDigit(buf[pos++], type);
hr += toDigit(buf[pos++], type);
min = 10 * toDigit(buf[pos++], type);
min += toDigit(buf[pos++], type);
if (hr >= 24 || min >= 60)
throw new IOException("Parse " + type + " time, +hhmm");
time -= ((hr * 60) + min) * 60 * 1000;
break;
case '-':
if (len != 5) {
throw new IOException("Parse " + type + " time, invalid offset");
}
hr = 10 * toDigit(buf[pos++], type);
hr += toDigit(buf[pos++], type);
min = 10 * toDigit(buf[pos++], type);
min += toDigit(buf[pos++], type);
if (hr >= 24 || min >= 60)
throw new IOException("Parse " + type + " time, -hhmm");
time += ((hr * 60) + min) * 60 * 1000;
break;
case 'Z':
if (len != 1) {
throw new IOException("Parse " + type + " time, invalid format");
}
break;
default:
throw new IOException("Parse " + type + " time, garbage offset");
}
return new Date(time);
}
/**
* Converts byte (represented as a char) to int.
* @throws IOException if integer is not a valid digit in the specified
* radix (10)
*/
private static int toDigit(byte b, String type) throws IOException {
if (b < '0' || b > '9') {
throw new IOException("Parse " + type + " time, invalid format");
}
return b - '0';
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 1996, 2019, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1996, 2020, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -28,11 +28,8 @@ package sun.security.util;
import java.io.InputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Date;
import java.util.Vector;
import static java.nio.charset.StandardCharsets.*;
/**
* A DER input stream, used for parsing ASN.1 DER-encoded data such as
@ -59,510 +56,173 @@ import static java.nio.charset.StandardCharsets.*;
public class DerInputStream {
/*
* This version only supports fully buffered DER. This is easy to
* work with, though if large objects are manipulated DER becomes
* awkward to deal with. That's where BER is useful, since BER
* handles streaming data relatively well.
*/
DerInputBuffer buffer;
// The static part
final byte[] data;
final int start; // inclusive
final int end; // exclusive
final boolean allowBER;
/** The DER tag of the value; one of the tag_ constants. */
public byte tag;
// The moving part
int pos;
int mark;
/**
* Create a DER input stream from a data buffer. The buffer is not
* copied, it is shared. Accordingly, the buffer should be treated
* as read-only.
* Constructs a DerInputStream by assigning all its fields.
*
* @param data the buffer from which to create the string (CONSUMED)
* No checking on arguments since all callers are internal.
* {@code data} should never be null even if length is 0.
*/
public DerInputStream(byte[] data, int start, int length, boolean allowBER) {
this.data = data;
this.start = start;
this.end = start + length;
this.allowBER = allowBER;
this.pos = start;
this.mark = start;
}
public DerInputStream(byte[] data) throws IOException {
init(data, 0, data.length, true);
this(data, 0, data.length, true);
}
/**
* Create a DER input stream from part of a data buffer with
* additional arg to control whether DER checks are enforced.
* The buffer is not copied, it is shared. Accordingly, the
* buffer should be treated as read-only.
*
* @param data the buffer from which to create the string (CONSUMED)
* @param offset the first index of <em>data</em> which will
* be read as DER input in the new stream
* @param len how long a chunk of the buffer to use,
* starting at "offset"
* @param allowBER whether to allow constructed indefinite-length
* encoding as well as tolerate leading 0s
*/
public DerInputStream(byte[] data, int offset, int len,
boolean allowBER) throws IOException {
init(data, offset, len, allowBER);
}
/**
* Create a DER input stream from part of a data buffer.
* The buffer is not copied, it is shared. Accordingly, the
* buffer should be treated as read-only.
*
* @param data the buffer from which to create the string (CONSUMED)
* @param offset the first index of <em>data</em> which will
* be read as DER input in the new stream
* @param len how long a chunk of the buffer to use,
* starting at "offset"
*/
public DerInputStream(byte[] data, int offset, int len) throws IOException {
init(data, offset, len, true);
}
/*
* private helper routine
*/
private void init(byte[] data, int offset, int len, boolean allowBER) throws IOException {
if ((offset+2 > data.length) || (offset+len > data.length)) {
throw new IOException("Encoding bytes too short");
}
// check for indefinite length encoding
if (DerIndefLenConverter.isIndefinite(data[offset+1])) {
if (!allowBER) {
throw new IOException("Indefinite length BER encoding found");
} else {
byte[] inData = new byte[len];
System.arraycopy(data, offset, inData, 0, len);
DerIndefLenConverter derIn = new DerIndefLenConverter();
byte[] result = derIn.convertBytes(inData);
if (result == null) {
throw new IOException("not all indef len BER resolved");
} else {
buffer = new DerInputBuffer(result, allowBER);
}
}
} else {
buffer = new DerInputBuffer(data, offset, len, allowBER);
}
buffer.mark(Integer.MAX_VALUE);
}
DerInputStream(DerInputBuffer buf) {
buffer = buf;
buffer.mark(Integer.MAX_VALUE);
this(data, offset, len, true);
}
/**
* Creates a new DER input stream from part of this input stream.
*
* @param len how long a chunk of the current input stream to use,
* starting at the current position.
* @param do_skip true if the existing data in the input stream should
* be skipped. If this value is false, the next data read
* on this stream and the newly created stream will be the
* same.
*/
public DerInputStream subStream(int len, boolean do_skip)
throws IOException {
DerInputBuffer newbuf = buffer.dup();
newbuf.truncate(len);
if (do_skip) {
buffer.skip(len);
}
return new DerInputStream(newbuf);
}
/**
* Return what has been written to this DerInputStream
* as a byte array. Useful for debugging.
* Returns the remaining unread bytes, or, all bytes if none read yet.
*/
public byte[] toByteArray() {
return buffer.toByteArray();
return Arrays.copyOfRange(data, pos, end);
}
/*
* PRIMITIVES -- these are "universal" ASN.1 simple types.
/**
* Reads a DerValue from this stream. After the call, the data pointer
* is right after this DerValue so that the next call will read the
* next DerValue.
*
* INTEGER, ENUMERATED, BIT STRING, OCTET STRING, NULL
* OBJECT IDENTIFIER, SEQUENCE (OF), SET (OF)
* UTF8String, PrintableString, T61String, IA5String, UTCTime,
* GeneralizedTime, BMPString.
* Note: UniversalString not supported till encoder is available.
*/
/**
* Get an integer from the input stream as an integer.
*
* @return the integer held in this DER input stream.
*/
public int getInteger() throws IOException {
if (buffer.read() != DerValue.tag_Integer) {
throw new IOException("DER input, Integer tag error");
}
return buffer.getInteger(getDefiniteLength(buffer));
}
/**
* Get a integer from the input stream as a BigInteger object.
*
* @return the integer held in this DER input stream.
*/
public BigInteger getBigInteger() throws IOException {
if (buffer.read() != DerValue.tag_Integer) {
throw new IOException("DER input, Integer tag error");
}
return buffer.getBigInteger(getDefiniteLength(buffer), false);
}
/**
* Returns an ASN.1 INTEGER value as a positive BigInteger.
* This is just to deal with implementations that incorrectly encode
* some values as negative.
*
* @return the integer held in this DER value as a BigInteger.
*/
public BigInteger getPositiveBigInteger() throws IOException {
if (buffer.read() != DerValue.tag_Integer) {
throw new IOException("DER input, Integer tag error");
}
return buffer.getBigInteger(getDefiniteLength(buffer), true);
}
/**
* Get an enumerated from the input stream.
*
* @return the integer held in this DER input stream.
*/
public int getEnumerated() throws IOException {
if (buffer.read() != DerValue.tag_Enumerated) {
throw new IOException("DER input, Enumerated tag error");
}
return buffer.getInteger(getDefiniteLength(buffer));
}
/**
* Get a bit string from the input stream. Padded bits (if any)
* will be stripped off before the bit string is returned.
*/
public byte[] getBitString() throws IOException {
if (buffer.read() != DerValue.tag_BitString)
throw new IOException("DER input not an bit string");
return buffer.getBitString(getDefiniteLength(buffer));
}
/**
* Get a bit string from the input stream. The bit string need
* not be byte-aligned.
*/
public BitArray getUnalignedBitString() throws IOException {
if (buffer.read() != DerValue.tag_BitString) {
throw new IOException("DER input not a bit string");
}
int length = getDefiniteLength(buffer);
if (length == 0) {
return new BitArray(0);
}
/*
* First byte = number of excess bits in the last octet of the
* representation.
*/
length--;
int excessBits = buffer.read();
if (excessBits < 0) {
throw new IOException("Unused bits of bit string invalid");
}
int validBits = length*8 - excessBits;
if (validBits < 0) {
throw new IOException("Valid bits of bit string invalid");
}
byte[] repn = new byte[length];
if ((length != 0) && (buffer.read(repn) != length)) {
throw new IOException("Short read of DER bit string");
}
return new BitArray(validBits, repn);
}
/**
* Returns an ASN.1 OCTET STRING from the input stream.
*/
public byte[] getOctetString() throws IOException {
if (buffer.read() != DerValue.tag_OctetString)
throw new IOException("DER input not an octet string");
int length = getDefiniteLength(buffer);
byte[] retval = new byte[length];
if ((length != 0) && (buffer.read(retval) != length))
throw new IOException("Short read of DER octet string");
return retval;
}
/**
* Returns the asked number of bytes from the input stream.
*/
public void getBytes(byte[] val) throws IOException {
if ((val.length != 0) && (buffer.read(val) != val.length)) {
throw new IOException("Short read of DER octet string");
}
}
/**
* Reads an encoded null value from the input stream.
*/
public void getNull() throws IOException {
if (buffer.read() != DerValue.tag_Null || buffer.read() != 0)
throw new IOException("getNull, bad data");
}
/**
* Reads an X.200 style Object Identifier from the stream.
*/
public ObjectIdentifier getOID() throws IOException {
return new ObjectIdentifier(this);
}
/**
* Return a sequence of encoded entities. ASN.1 sequences are
* ordered, and they are often used, like a "struct" in C or C++,
* to group data values. They may have optional or context
* specific values.
*
* @param startLen guess about how long the sequence will be
* (used to initialize an auto-growing data structure)
* @return array of the values in the sequence
*/
public DerValue[] getSequence(int startLen) throws IOException {
tag = (byte)buffer.read();
if (tag != DerValue.tag_Sequence)
throw new IOException("Sequence tag error");
return readVector(startLen);
}
/**
* Return a set of encoded entities. ASN.1 sets are unordered,
* though DER may specify an order for some kinds of sets (such
* as the attributes in an X.500 relative distinguished name)
* to facilitate binary comparisons of encoded values.
*
* @param startLen guess about how large the set will be
* (used to initialize an auto-growing data structure)
* @return array of the values in the sequence
*/
public DerValue[] getSet(int startLen) throws IOException {
tag = (byte)buffer.read();
if (tag != DerValue.tag_Set)
throw new IOException("Set tag error");
return readVector(startLen);
}
/**
* Return a set of encoded entities. ASN.1 sets are unordered,
* though DER may specify an order for some kinds of sets (such
* as the attributes in an X.500 relative distinguished name)
* to facilitate binary comparisons of encoded values.
*
* @param startLen guess about how large the set will be
* (used to initialize an auto-growing data structure)
* @param implicit if true tag is assumed implicit.
* @return array of the values in the sequence
*/
public DerValue[] getSet(int startLen, boolean implicit)
throws IOException {
tag = (byte)buffer.read();
if (!implicit) {
if (tag != DerValue.tag_Set) {
throw new IOException("Set tag error");
}
}
return (readVector(startLen));
}
/*
* Read a "vector" of values ... set or sequence have the
* same encoding, except for the initial tag, so both use
* this same helper routine.
*/
protected DerValue[] readVector(int startLen) throws IOException {
DerInputStream newstr;
byte lenByte = (byte)buffer.read();
int len = getLength(lenByte, buffer);
if (len == -1) {
// indefinite length encoding found
buffer = new DerInputBuffer(
DerIndefLenConverter.convertStream(buffer, lenByte, tag),
buffer.allowBER);
if (tag != buffer.read())
throw new IOException("Indefinite length encoding" +
" not supported");
len = DerInputStream.getDefiniteLength(buffer);
}
if (len == 0)
// return empty array instead of null, which should be
// used only for missing optionals
return new DerValue[0];
/*
* Create a temporary stream from which to read the data,
* unless it's not really needed.
*/
if (buffer.available() == len)
newstr = this;
else
newstr = subStream(len, true);
/*
* Pull values out of the stream.
*/
Vector<DerValue> vec = new Vector<>(startLen);
DerValue value;
do {
value = new DerValue(newstr.buffer, buffer.allowBER);
vec.addElement(value);
} while (newstr.available() > 0);
if (newstr.available() != 0)
throw new IOException("Extra data at end of vector");
/*
* Now stick them into the array we're returning.
*/
int i, max = vec.size();
DerValue[] retval = new DerValue[max];
for (i = 0; i < max; i++)
retval[i] = vec.elementAt(i);
return retval;
}
/**
* Get a single DER-encoded value from the input stream.
* It can often be useful to pull a value from the stream
* and defer parsing it. For example, you can pull a nested
* sequence out with one call, and only examine its elements
* later when you really need to.
* @return the read DerValue.
* @throws IOException if a DerValue cannot be constructed starting from
* this position because of byte shortage or encoding error.
*/
public DerValue getDerValue() throws IOException {
return new DerValue(buffer);
DerValue result = new DerValue(
this.data, this.pos, this.end - this.pos, this.allowBER, true);
if (result.buffer != this.data) {
// Indefinite length observed. Unused bytes in data are appended
// to the end of return value by DerIndefLenConverter::convertBytes
// and stay inside result.buffer.
int unused = result.buffer.length - result.end;
this.pos = this.data.length - unused;
} else {
this.pos = result.end;
}
return result;
}
// The following getXyz methods are mostly shorthands for getDerValue().getXyz().
public int getInteger() throws IOException {
return getDerValue().getInteger();
}
public BigInteger getBigInteger() throws IOException {
return getDerValue().getBigInteger();
}
public BigInteger getPositiveBigInteger() throws IOException {
return getDerValue().getPositiveBigInteger();
}
public int getEnumerated() throws IOException {
return getDerValue().getEnumerated();
}
public byte[] getBitString() throws IOException {
return getDerValue().getBitString();
}
public BitArray getUnalignedBitString() throws IOException {
return getDerValue().getUnalignedBitString();
}
public byte[] getOctetString() throws IOException {
// Not identical to DerValue::getOctetString. This method
// does not accept constructed OCTET STRING.
DerValue v = getDerValue();
if (v.tag != DerValue.tag_OctetString) {
throw new IOException("DER input not an octet string");
}
return v.getOctetString();
}
public void getNull() throws IOException {
getDerValue().getNull();
}
public ObjectIdentifier getOID() throws IOException {
return getDerValue().getOID();
}
/**
* Read a string that was encoded as a UTF8String DER value.
*/
public String getUTF8String() throws IOException {
return readString(DerValue.tag_UTF8String, "UTF-8", UTF_8);
return getDerValue().getUTF8String();
}
/**
* Read a string that was encoded as a PrintableString DER value.
*/
public String getPrintableString() throws IOException {
return readString(DerValue.tag_PrintableString, "Printable",
US_ASCII);
return getDerValue().getPrintableString();
}
/**
* Read a string that was encoded as a T61String DER value.
*/
public String getT61String() throws IOException {
/*
* Works for common characters between T61 and ASCII.
*/
return readString(DerValue.tag_T61String, "T61", ISO_8859_1);
return getDerValue().getT61String();
}
/**
* Read a string that was encoded as a IA5String DER value.
*/
public String getIA5String() throws IOException {
return readString(DerValue.tag_IA5String, "IA5", US_ASCII);
}
/**
* Read a string that was encoded as a BMPString DER value.
*/
public String getBMPString() throws IOException {
return readString(DerValue.tag_BMPString, "BMP", UTF_16BE);
return getDerValue().getBMPString();
}
public String getIA5String() throws IOException {
return getDerValue().getIA5String();
}
/**
* Read a string that was encoded as a GeneralString DER value.
*/
public String getGeneralString() throws IOException {
return readString(DerValue.tag_GeneralString, "General",
US_ASCII);
return getDerValue().getGeneralString();
}
/**
* Private helper routine to read an encoded string from the input
* stream.
* @param stringTag the tag for the type of string to read
* @param stringName a name to display in error messages
* @param enc the encoder to use to interpret the data. Should
* correspond to the stringTag above.
*/
private String readString(byte stringTag, String stringName,
Charset charset) throws IOException {
if (buffer.read() != stringTag)
throw new IOException("DER input not a " +
stringName + " string");
int length = getDefiniteLength(buffer);
byte[] retval = new byte[length];
if ((length != 0) && (buffer.read(retval) != length))
throw new IOException("Short read of DER " +
stringName + " string");
return new String(retval, charset);
}
/**
* Get a UTC encoded time value from the input stream.
*/
public Date getUTCTime() throws IOException {
if (buffer.read() != DerValue.tag_UtcTime)
throw new IOException("DER input, UTCtime tag invalid ");
return buffer.getUTCTime(getDefiniteLength(buffer));
return getDerValue().getUTCTime();
}
/**
* Get a Generalized encoded time value from the input stream.
*/
public Date getGeneralizedTime() throws IOException {
if (buffer.read() != DerValue.tag_GeneralizedTime)
throw new IOException("DER input, GeneralizedTime tag invalid ");
return buffer.getGeneralizedTime(getDefiniteLength(buffer));
return getDerValue().getGeneralizedTime();
}
/*
* Get a byte from the input stream.
*/
// package private
int getByte() throws IOException {
return (0x00ff & buffer.read());
// Read a series of DerValue objects which is the sub-elements
// of a SEQUENCE and SET.
public DerValue[] getSequence(int startLen) throws IOException {
return getDerValue().subs(DerValue.tag_Sequence, startLen);
}
public DerValue[] getSet(int startLen) throws IOException {
return getDerValue().subs(DerValue.tag_Set, startLen);
}
public DerValue[] getSet(int startLen, boolean implicit) throws IOException {
if (implicit) {
return getDerValue().subs((byte) 0, startLen);
} else {
return getSet(startLen);
}
}
public int peekByte() throws IOException {
return buffer.peek();
if (pos == end) {
throw new IOException("At end");
}
return data[pos];
}
// package private
int getLength() throws IOException {
return getLength(buffer);
}
/*
/**
* Get a length from the input stream, allowing for at most 32 bits of
* encoding to be used. (Not the same as getting a tagged integer!)
*
@ -570,38 +230,26 @@ public class DerInputStream {
* @exception IOException on parsing error or unsupported lengths.
*/
static int getLength(InputStream in) throws IOException {
return getLength(in.read(), in);
}
/*
* Get a length from the input stream, allowing for at most 32 bits of
* encoding to be used. (Not the same as getting a tagged integer!)
*
* @return the length or -1 if indefinite length found.
* @exception IOException on parsing error or unsupported lengths.
*/
static int getLength(int lenByte, InputStream in) throws IOException {
int value, tmp;
int lenByte = in.read();
if (lenByte == -1) {
throw new IOException("Short read of DER length");
}
if (lenByte == 0x80) {
return -1;
}
int value, tmp;
String mdName = "DerInputStream.getLength(): ";
tmp = lenByte;
if ((tmp & 0x080) == 0x00) { // short form, 1 byte datum
value = tmp;
} else { // long form or indefinite
} else { // long form
tmp &= 0x07f;
/*
* NOTE: tmp == 0 indicates indefinite length encoded data.
* tmp > 4 indicates more than 4Gb of data.
*/
if (tmp == 0)
return -1;
if (tmp < 0 || tmp > 4)
throw new IOException(mdName + "lengthTag=" + tmp + ", "
+ ((tmp < 0) ? "incorrect DER encoding." : "too big."));
// tmp > 4 indicates more than 4Gb of data.
if (tmp > 4) {
throw new IOException(mdName + "lengthTag=" + tmp + ", too big.");
}
value = 0x0ff & in.read();
tmp--;
@ -622,12 +270,8 @@ public class DerInputStream {
return value;
}
int getDefiniteLength() throws IOException {
return getDefiniteLength(buffer);
}
/*
* Get a length from the input stream.
* Get a definite length from the input stream.
*
* @return the length
* @exception IOException on parsing error or if indefinite length found.
@ -643,22 +287,22 @@ public class DerInputStream {
/**
* Mark the current position in the buffer, so that
* a later call to <code>reset</code> will return here.
* The {@code readAheadLimit} is useless here because
* all data is available and we can go to anywhere at will.
*/
public void mark(int value) { buffer.mark(value); }
public void mark(int readAheadLimit) { mark = pos; }
/**
* Return to the position of the last <code>mark</code>
* call. A mark is implicitly set at the beginning of
* the stream when it is created.
*/
public void reset() { buffer.reset(); }
public void reset() { pos = mark; }
/**
* Returns the number of bytes available for reading.
* This is most useful for testing whether the stream is
* empty.
*/
public int available() { return buffer.available(); }
public int available() { return end - pos; }
}

File diff suppressed because it is too large Load Diff

View File

@ -138,12 +138,13 @@ public final class ObjectIdentifier implements Serializable {
componentLen = comp.length;
}
// Check the estimated size before it is too later.
// Check the estimated size before it is too late. The check
// will be performed again in init().
checkOidSize(componentLen);
init(comp, componentLen);
} else {
checkOidSize(encoding.length);
check(encoding);
}
}
@ -244,64 +245,20 @@ public final class ObjectIdentifier implements Serializable {
}
}
/**
* Constructor, from an ASN.1 encoded input stream.
* Validity check NOT included.
* The encoding of the ID in the stream uses "DER", a BER/1 subset.
* In this case, that means a triple { typeId, length, data }.
*
* <P><STRONG>NOTE:</STRONG> When an exception is thrown, the
* input stream has not been returned to its "initial" state.
*
* @param in DER-encoded data holding an object ID
* @exception IOException indicates a decoding error
*/
public ObjectIdentifier(DerInputStream in) throws IOException {
byte type_id;
int bufferEnd;
/*
* Object IDs are a "universal" type, and their tag needs only
* one byte of encoding. Verify that the tag of this datum
* is that of an object ID.
*
* Then get and check the length of the ID's encoding. We set
* up so that we can use in.available() to check for the end of
* this value in the data stream.
*/
type_id = (byte)in.getByte();
if (type_id != DerValue.tag_ObjectId)
throw new IOException (
"ObjectIdentifier() -- data isn't an object ID"
+ " (tag = " + type_id + ")"
);
int len = in.getDefiniteLength();
checkOidSize(len);
if (len > in.available()) {
throw new IOException("ObjectIdentifier length exceeds " +
"data available. Length: " + len + ", Available: " +
in.available());
}
encoding = new byte[len];
in.getBytes(encoding);
// Called by DerValue::getOID. No need to clone input.
ObjectIdentifier(byte[] encoding) throws IOException {
checkOidSize(encoding.length);
check(encoding);
this.encoding = encoding;
}
/*
* Constructor, from the rest of a DER input buffer;
* the tag and length have been removed/verified
* Validity check NOT included.
/**
* Reads an ObjectIdentifier from a DerInputStream.
* @param in the input stream
* @throws IOException if there is an encoding error
*/
ObjectIdentifier(DerInputBuffer buf) throws IOException {
DerInputStream in = new DerInputStream(buf);
int len = in.available();
checkOidSize(len);
encoding = new byte[len];
in.getBytes(encoding);
check(encoding);
public ObjectIdentifier(DerInputStream in) throws IOException {
encoding = in.getDerValue().getOID().encoding;
}
private void init(int[] components, int length) throws IOException {

View File

@ -1,111 +0,0 @@
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @author Gary Ellison
* @bug 4170635
* @summary Verify equals()/hashCode() contract honored
* @modules java.base/sun.security.util:+open
* java.base/sun.security.x509
* @run main/othervm/policy=Allow.policy DerInputBufferEqualsHashCode
*/
import java.io.*;
import sun.security.util.*;
import sun.security.x509.*;
import java.lang.reflect.*;
public class DerInputBufferEqualsHashCode {
public static void main(String[] args) throws Exception {
String name1 = "CN=eve s. dropper";
DerOutputStream deros;
byte[] ba;
// encode
X500Name dn1 = new X500Name(name1);
deros = new DerOutputStream();
dn1.encode(deros);
ba = deros.toByteArray();
GetDIBConstructor a = new GetDIBConstructor();
java.security.AccessController.doPrivileged(a);
Constructor c = a.getCons();
Object[] objs = new Object[1];
objs[0] = ba;
Object db1 = null, db2 = null;
try {
db1 = c.newInstance(objs);
db2 = c.newInstance(objs);
} catch (Exception e) {
System.out.println("Caught unexpected exception " + e);
throw e;
}
if ( (db1.equals(db2)) == (db1.hashCode()==db2.hashCode()) )
System.out.println("PASSED");
else
throw new Exception("FAILED equals()/hashCode() contract");
}
}
class GetDIBConstructor implements java.security.PrivilegedExceptionAction {
private Class dibClass = null;
private Constructor dibCons = null;
public Object run() throws Exception {
try {
dibClass = Class.forName("sun.security.util.DerInputBuffer");
Constructor[] cons = dibClass.getDeclaredConstructors();
int i;
for (i = 0; i < cons.length; i++) {
Class [] parms = cons[i].getParameterTypes();
if (parms.length == 1) {
if (parms[0].getName().equalsIgnoreCase("[B")) {
cons[i].setAccessible(true);
break;
}
}
}
dibCons = cons[i];
} catch (Exception e) {
System.out.println("Caught unexpected exception " + e);
throw e;
}
return dibCons;
}
public Constructor getCons(){
return dibCons;
}
}

View File

@ -0,0 +1,58 @@
/*
* Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8249783
* @summary read very deep constructed OCTET STRING
* @modules java.base/sun.security.util
* @library /test/lib
*/
import jdk.test.lib.Asserts;
import jdk.test.lib.Utils;
import sun.security.util.DerInputStream;
import sun.security.util.DerValue;
import java.io.IOException;
public class DeepOctets {
public static void main(String[] args) throws Exception {
byte[] input = {
0x24, 24,
0x24, 8, 4, 2, 'a', 'b', 4, 2, 'c', 'd',
0x24, 8, 4, 2, 'e', 'f', 4, 2, 'g', 'h',
4, 2, 'i', 'j'
};
// DerValue::getOctetString supports constructed BER
byte[] s = new DerValue(input).getOctetString();
Asserts.assertEQ(new String(s), "abcdefghij");
// DerInputStream::getOctetString does not
Utils.runAndCheckException(
() -> new DerInputStream(input).getOctetString(),
IOException.class);
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2008, 2020, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -23,23 +23,78 @@
/*
* @test
* @bug 6731685
* @bug 6731685 8249783
* @summary CertificateFactory.generateCertificates throws IOException on PKCS7 cert chain
* @modules java.base/sun.security.util
* @library /test/lib
*/
import java.io.*;
import java.lang.reflect.Field;
import java.util.Arrays;
import jdk.test.lib.Asserts;
import jdk.test.lib.Utils;
import jdk.test.lib.hexdump.HexPrinter;
import sun.security.util.*;
public class Indefinite {
public static void main(String[] args) throws Exception {
byte[] input = {
// An OCTET-STRING in 2 parts
4, (byte)0x80, 4, 2, 'a', 'b', 4, 2, 'c', 'd', 0, 0,
// Garbage follows, may be falsely recognized as EOC
0, 0, 0, 0
};
new DerValue(new ByteArrayInputStream(input));
// Indefinite length with trailing bytes
test(true, new byte[] {
// An OCTET-STRING in 2 parts
0x24, (byte) 0x80, 4, 2, 'a', 'b', 4, 2, 'c', 'd', 0, 0,
// Garbage follows, may be falsely recognized as EOC
0, 0, 0, 0,
// and more
7, 8, 9, 10});
// Definite length with trailing bytes
test(false, new byte[] {
4, 4, 'a', 'b', 'c', 'd',
0, 0, 0, 0, 7, 8, 9, 10 });
}
static void test(boolean indefinite, byte[] input) throws Exception {
// 1. parse stream
InputStream ins = new ByteArrayInputStream(input);
DerValue v = new DerValue(ins);
Asserts.assertEQ(new String(v.getOctetString()), "abcd");
if (indefinite) {
// Trailing bytes might be consumed by the conversion but can
// be found in DerValue "after end".
Field buffer = DerValue.class.getDeclaredField("buffer");
Field end = DerValue.class.getDeclaredField("end");
buffer.setAccessible(true);
end.setAccessible(true);
int bufferLen = ((byte[])buffer.get(v)).length;
int endPos = end.getInt(v);
// Data "after end": bufferLen - endPos
// Data remained in stream: ins.available()x`
Asserts.assertEQ(bufferLen - endPos + ins.available(), 8);
} else {
// Trailing bytes remain in the stream for definite length
Asserts.assertEQ(ins.available(), 8);
}
// 2. parse DerInputStream
DerInputStream ds = new DerInputStream(input);
Asserts.assertEQ(new String(ds.getDerValue().getOctetString()), "abcd");
Asserts.assertEQ(ds.available(), 8);
Asserts.assertTrue(Arrays.equals(ds.toByteArray(),
new byte[]{0,0,0,0,7,8,9,10}));
// 3. Parse full byte array
Utils.runAndCheckException(() -> new DerValue(input),
e -> Asserts.assertTrue(e instanceof IOException
&& e.getMessage().equals("extra data at the end")));
// 4. Parse exact byte array
Asserts.assertEQ(new String(new DerValue(Arrays.copyOf(input, input.length - 8))
.getOctetString()), "abcd");
}
}