DerInputBuffer.java 15.4 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 1996, 2020, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6
 * 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
7
 * published by the Free Software Foundation.  Oracle designates this
D
duke 已提交
8
 * particular file as subject to the "Classpath" exception as provided
9
 * by Oracle in the LICENSE file that accompanied this code.
D
duke 已提交
10 11 12 13 14 15 16 17 18 19 20
 *
 * 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.
 *
21 22 23
 * 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.
D
duke 已提交
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
 */

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 {

46
    boolean allowBER = true;
D
duke 已提交
47

48 49 50 51 52 53 54 55 56 57 58
    // 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) {
D
duke 已提交
59
        super(buf, offset, len);
60
        this.allowBER = allowBER;
D
duke 已提交
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
    }

    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);

159 160
        // BER allows leading 0s but DER does not
        if (!allowBER && (len >= 2 && (bytes[0] == 0) && (bytes[1] >= 0))) {
I
igerasim 已提交
161 162 163
            throw new IOException("Invalid encoding: redundant leading 0s");
        }

D
duke 已提交
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 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
        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");

277
        if (len < 13)
D
duke 已提交
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
            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;
302
         * if YY >= 50, we assume 19YY, as per RFC 5280.
D
duke 已提交
303 304 305 306 307 308 309 310 311 312 313 314
         *
         * 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";
315 316 317 318
            year = 1000 * toDigit(buf[pos++], type);
            year += 100 * toDigit(buf[pos++], type);
            year += 10 * toDigit(buf[pos++], type);
            year += toDigit(buf[pos++], type);
D
duke 已提交
319 320 321
            len -= 2; // For the two extra YY
        } else {
            type = "UTC";
322 323
            year = 10 * toDigit(buf[pos++], type);
            year += toDigit(buf[pos++], type);
D
duke 已提交
324 325 326 327 328 329 330

            if (year < 50)              // origin 2000
                year += 2000;
            else
                year += 1900;   // origin 1900
        }

331 332
        month = 10 * toDigit(buf[pos++], type);
        month += toDigit(buf[pos++], type);
D
duke 已提交
333

334 335
        day = 10 * toDigit(buf[pos++], type);
        day += toDigit(buf[pos++], type);
D
duke 已提交
336

337 338
        hour = 10 * toDigit(buf[pos++], type);
        hour += toDigit(buf[pos++], type);
D
duke 已提交
339

340 341
        minute = 10 * toDigit(buf[pos++], type);
        minute += toDigit(buf[pos++], type);
D
duke 已提交
342 343 344 345 346 347 348 349 350 351

        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;
352
        if (len > 2) {
353 354
            second = 10 * toDigit(buf[pos++], type);
            second += toDigit(buf[pos++], type);
D
duke 已提交
355 356
            len -= 2;
            // handle fractional seconds (if present)
357
            if (generalized && (buf[pos] == '.' || buf[pos] == ',')) {
D
duke 已提交
358
                len --;
359 360 361 362
                if (len == 0) {
                    throw new IOException("Parse " + type +
                            " time, empty fractional part");
                }
D
duke 已提交
363 364
                pos++;
                int precision = 0;
365 366 367 368 369
                while (buf[pos] != 'Z' &&
                       buf[pos] != '+' &&
                       buf[pos] != '-') {
                    // Validate all digits in the fractional part but
                    // store millisecond precision only
370
                    int thisDigit = toDigit(buf[pos], type);
D
duke 已提交
371
                    precision++;
372 373 374 375 376
                    len--;
                    if (len == 0) {
                        throw new IOException("Parse " + type +
                                " time, invalid fractional part");
                    }
377 378 379 380 381 382 383 384 385 386 387 388
                    pos++;
                    switch (precision) {
                        case 1:
                            millis += 100 * thisDigit;
                            break;
                        case 2:
                            millis += 10 * thisDigit;
                            break;
                        case 3:
                            millis += thisDigit;
                            break;
                    }
D
duke 已提交
389
                }
390 391 392
                if (precision == 0) {
                    throw new IOException("Parse " + type +
                            " time, empty fractional part");
D
duke 已提交
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
                }
            }
        } 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 '+':
423 424 425
            if (len != 5) {
                throw new IOException("Parse " + type + " time, invalid offset");
            }
426 427 428 429
            hr = 10 * toDigit(buf[pos++], type);
            hr += toDigit(buf[pos++], type);
            min = 10 * toDigit(buf[pos++], type);
            min += toDigit(buf[pos++], type);
D
duke 已提交
430 431 432 433 434 435 436 437

            if (hr >= 24 || min >= 60)
                throw new IOException("Parse " + type + " time, +hhmm");

            time -= ((hr * 60) + min) * 60 * 1000;
            break;

        case '-':
438 439 440
            if (len != 5) {
                throw new IOException("Parse " + type + " time, invalid offset");
            }
441 442 443 444
            hr = 10 * toDigit(buf[pos++], type);
            hr += toDigit(buf[pos++], type);
            min = 10 * toDigit(buf[pos++], type);
            min += toDigit(buf[pos++], type);
D
duke 已提交
445 446 447 448 449 450 451 452

            if (hr >= 24 || min >= 60)
                throw new IOException("Parse " + type + " time, -hhmm");

            time += ((hr * 60) + min) * 60 * 1000;
            break;

        case 'Z':
453 454 455
            if (len != 1) {
                throw new IOException("Parse " + type + " time, invalid format");
            }
D
duke 已提交
456 457 458 459 460 461 462
            break;

        default:
            throw new IOException("Parse " + type + " time, garbage offset");
        }
        return new Date(time);
    }
463 464 465 466 467 468 469 470 471 472 473 474

    /**
     * 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';
    }
D
duke 已提交
475
}