Checksum.java 12.5 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 2000, 2019, 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 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
 */

/*
 *  (C) Copyright IBM Corp. 1999 All Rights Reserved.
 *  Copyright 1997 The Open Group Research Institute.  All rights reserved.
 */

package sun.security.krb5;

import java.util.Arrays;
import sun.security.util.*;
import sun.security.krb5.internal.*;
import sun.security.krb5.internal.crypto.*;
import java.io.IOException;
import java.math.BigInteger;

/**
 * This class encapsulates the concept of a Kerberos checksum.
 */
public class Checksum {

    private int cksumType;
    private byte[] checksum;

    // ----------------------------------------------+-------------+-----------
    //                      Checksum type            |sumtype      |checksum
    //                                               |value        | size
    // ----------------------------------------------+-------------+-----------
    public static final int CKSUMTYPE_NULL          = 0;               // 0
    public static final int CKSUMTYPE_CRC32         = 1;               // 4
    public static final int CKSUMTYPE_RSA_MD4       = 2;               // 16
    public static final int CKSUMTYPE_RSA_MD4_DES   = 3;               // 24
    public static final int CKSUMTYPE_DES_MAC       = 4;               // 16
    public static final int CKSUMTYPE_DES_MAC_K     = 5;               // 8
    public static final int CKSUMTYPE_RSA_MD4_DES_K = 6;               // 16
    public static final int CKSUMTYPE_RSA_MD5       = 7;               // 16
    public static final int CKSUMTYPE_RSA_MD5_DES   = 8;               // 24

     // draft-ietf-krb-wg-crypto-07.txt
    public static final int CKSUMTYPE_HMAC_SHA1_DES3_KD = 12;          // 20

    // draft-raeburn-krb-rijndael-krb-07.txt
    public static final int CKSUMTYPE_HMAC_SHA1_96_AES128 = 15;        // 96
    public static final int CKSUMTYPE_HMAC_SHA1_96_AES256 = 16;        // 96

    // draft-brezak-win2k-krb-rc4-hmac-04.txt
    public static final int CKSUMTYPE_HMAC_MD5_ARCFOUR = -138;

72
    // default checksum type, -1 if not set
D
duke 已提交
73 74 75 76 77
    static int CKSUMTYPE_DEFAULT;
    static int SAFECKSUMTYPE_DEFAULT;

    private static boolean DEBUG = Krb5.DEBUG;
    static {
W
weijun 已提交
78 79 80 81
        initStatic();
    }

    public static void initStatic() {
D
duke 已提交
82 83 84 85
        String temp = null;
        Config cfg = null;
        try {
            cfg = Config.getInstance();
W
weijun 已提交
86
            temp = cfg.get("libdefaults", "default_checksum");
87 88 89 90 91
            if (temp != null) {
                CKSUMTYPE_DEFAULT = Config.getType(temp);
            } else {
                CKSUMTYPE_DEFAULT = -1;
            }
D
duke 已提交
92 93 94
        } catch (Exception exc) {
            if (DEBUG) {
                System.out.println("Exception in getting default checksum "+
95 96
                                   "value from the configuration. " +
                                   "No default checksum set.");
D
duke 已提交
97 98
                exc.printStackTrace();
            }
99
            CKSUMTYPE_DEFAULT = -1;
D
duke 已提交
100 101 102 103
        }


        try {
W
weijun 已提交
104
            temp = cfg.get("libdefaults", "safe_checksum_type");
D
duke 已提交
105 106
            if (temp != null)
                {
W
weijun 已提交
107
                    SAFECKSUMTYPE_DEFAULT = Config.getType(temp);
D
duke 已提交
108
                } else {
109
                    SAFECKSUMTYPE_DEFAULT = -1;
D
duke 已提交
110 111 112 113 114
                }
        } catch (Exception exc) {
            if (DEBUG) {
                System.out.println("Exception in getting safe default " +
                                   "checksum value " +
115 116
                                   "from the configuration Setting.  " +
                                   "No safe default checksum set.");
D
duke 已提交
117 118
                exc.printStackTrace();
            }
119
            SAFECKSUMTYPE_DEFAULT = -1;
D
duke 已提交
120 121 122 123 124
        }
    }

    /**
     * Constructs a new Checksum using the raw data and type.
125 126 127 128 129 130 131 132 133 134 135
     *
     * This constructor is only used by Authenticator Checksum
     * {@link sun.security.jgss.krb5.InitialToken.OverloadedChecksum}
     * where the checksum type must be 0x8003
     * (see https://tools.ietf.org/html/rfc4121#section-4.1.1)
     * and checksum field/value is used to convey service flags,
     * channel bindings, and optional delegation information.
     * This special type does NOT have a {@link CksumType} and has its
     * own calculating and verification rules. It does has the same
     * ASN.1 encoding though.
     *
D
duke 已提交
136 137 138 139 140 141 142 143 144
     * @data the byte array of checksum.
     * @new_cksumType the type of checksum.
     */
    public Checksum(byte[] data, int new_cksumType) {
        cksumType = new_cksumType;
        checksum = data;
    }

    /**
145 146 147 148 149 150 151 152 153 154
     * Constructs a new Checksum by calculating over the data using
     * the specified checksum type. If the checksum is unkeyed, key
     * and usage are ignored.
     *
     * @param new_cksumType the type of checksum. If set to -1, the
     *      {@linkplain EType#checksumType() mandatory checksum type}
     *      for the encryption type of {@code key} will be used
     * @param data the data that needs to be performed a checksum calculation on
     * @param key the key used by a keyed checksum
     * @param usage the usage used by a keyed checksum
D
duke 已提交
155
     */
156 157 158 159 160
    public Checksum(int new_cksumType, byte[] data,
                    EncryptionKey key, int usage)
            throws KdcErrException, KrbApErrException, KrbCryptoException {
        if (new_cksumType == -1) {
            cksumType = EType.getInstance(key.getEType()).checksumType();
D
duke 已提交
161
        } else {
162
            cksumType = new_cksumType;
D
duke 已提交
163
        }
164 165
        checksum = CksumType.getInstance(cksumType).calculateChecksum(
                    data, data.length, key.getBytes(), usage);
D
duke 已提交
166 167 168 169 170
    }

    /**
     * Verifies the keyed checksum over the data passed in.
     */
171 172
    public boolean verifyKeyedChecksum(byte[] data, EncryptionKey key, int usage)
            throws KdcErrException, KrbApErrException, KrbCryptoException {
D
duke 已提交
173
        CksumType cksumEngine = CksumType.getInstance(cksumType);
174
        if (!cksumEngine.isKeyed()) {
D
duke 已提交
175
            throw new KrbApErrException(Krb5.KRB_AP_ERR_INAPP_CKSUM);
176
        } else {
177 178
            return cksumEngine.verifyChecksum(
                    data, data.length, key.getBytes(), checksum, usage);
179 180 181
        }
    }

182 183 184 185 186 187 188 189 190 191 192 193 194 195 196

    /**
     * Verifies the checksum over the data passed in. The checksum might
     * be a keyed or not.
     *
     * ===============  ATTENTION! Use with care  ==================
     * According to https://tools.ietf.org/html/rfc3961#section-6.1,
     * An unkeyed checksum should only be used "in limited circumstances
     * where the lack of a key does not provide a window for an attack,
     * preferably as part of an encrypted message".
     */
    public boolean verifyAnyChecksum(byte[] data, EncryptionKey key, int usage)
            throws KdcErrException, KrbCryptoException {
        return CksumType.getInstance(cksumType).verifyChecksum(
                data, data.length, key.getBytes(), checksum, usage);
D
duke 已提交
197 198 199
    }

    boolean isEqual(Checksum cksum) throws KdcErrException {
200
        if (cksumType != cksum.cksumType) {
D
duke 已提交
201
            return false;
202
        }
203
        return CksumType.isChecksumEqual(checksum, cksum.checksum);
D
duke 已提交
204 205 206 207 208 209 210 211 212 213
    }

    /**
     * Constructs an instance of Checksum from an ASN.1 encoded representation.
     * @param encoding a single DER-encoded value.
     * @exception Asn1Exception if an error occurs while decoding an ASN1
     * encoded data.
     * @exception IOException if an I/O error occurs while reading encoded data.
     *
     */
214
    public Checksum(DerValue encoding) throws Asn1Exception, IOException {
D
duke 已提交
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 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
        DerValue der;
        if (encoding.getTag() != DerValue.tag_Sequence) {
            throw new Asn1Exception(Krb5.ASN1_BAD_ID);
        }
        der = encoding.getData().getDerValue();
        if ((der.getTag() & (byte)0x1F) == (byte)0x00) {
            cksumType = der.getData().getBigInteger().intValue();
        }
        else
            throw new Asn1Exception(Krb5.ASN1_BAD_ID);
        der = encoding.getData().getDerValue();
        if ((der.getTag() & (byte)0x1F) == (byte)0x01) {
            checksum = der.getData().getOctetString();
        }
        else
            throw new Asn1Exception(Krb5.ASN1_BAD_ID);
        if (encoding.getData().available() > 0) {
            throw new Asn1Exception(Krb5.ASN1_BAD_ID);
        }
    }

    /**
     * Encodes a Checksum object.
     * <xmp>
     * Checksum    ::= SEQUENCE {
     *         cksumtype   [0] Int32,
     *         checksum    [1] OCTET STRING
     * }
     * </xmp>
     *
     * <p>
     * This definition reflects the Network Working Group RFC 4120
     * specification available at
     * <a href="http://www.ietf.org/rfc/rfc4120.txt">
     * http://www.ietf.org/rfc/rfc4120.txt</a>.
     * @return byte array of enocded Checksum.
     * @exception Asn1Exception if an error occurs while decoding an
     * ASN1 encoded data.
     * @exception IOException if an I/O error occurs while reading
     * encoded data.
     *
     */
    public byte[] asn1Encode() throws Asn1Exception, IOException {
        DerOutputStream bytes = new DerOutputStream();
        DerOutputStream temp = new DerOutputStream();
        temp.putInteger(BigInteger.valueOf(cksumType));
        bytes.write(DerValue.createTag(DerValue.TAG_CONTEXT,
                                       true, (byte)0x00), temp);
        temp = new DerOutputStream();
        temp.putOctetString(checksum);
        bytes.write(DerValue.createTag(DerValue.TAG_CONTEXT,
                                       true, (byte)0x01), temp);
        temp = new DerOutputStream();
        temp.write(DerValue.tag_Sequence, bytes);
        return temp.toByteArray();
    }


    /**
     * Parse (unmarshal) a checksum object from a DER input stream.  This form
     * parsing might be used when expanding a value which is part of
     * a constructed sequence and uses explicitly tagged type.
     *
     * @exception Asn1Exception if an error occurs while decoding an
     * ASN1 encoded data.
     * @exception IOException if an I/O error occurs while reading
     * encoded data.
     * @param data the Der input stream value, which contains one or more
     * marshaled value.
     * @param explicitTag tag number.
     * @param optional indicates if this data field is optional
     * @return an instance of Checksum.
     *
     */
    public static Checksum parse(DerInputStream data,
                                 byte explicitTag, boolean optional)
        throws Asn1Exception, IOException {

        if ((optional) &&
            (((byte)data.peekByte() & (byte)0x1F) != explicitTag)) {
            return null;
        }
        DerValue der = data.getDerValue();
        if (explicitTag != (der.getTag() & (byte)0x1F))  {
            throw new Asn1Exception(Krb5.ASN1_BAD_ID);
        } else {
            DerValue subDer = der.getData().getDerValue();
            return new Checksum(subDer);
        }
    }

    /**
     * Returns the raw bytes of the checksum, not in ASN.1 encoded form.
     */
    public final byte[] getBytes() {
        return checksum;
    }

    public final int getType() {
        return cksumType;
    }

    @Override public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (!(obj instanceof Checksum)) {
            return false;
        }

        try {
            return isEqual((Checksum)obj);
        } catch (KdcErrException kee) {
            return false;
        }
    }

    @Override public int hashCode() {
        int result = 17;
        result = 37 * result + cksumType;
        if (checksum != null) {
            result = 37 * result + Arrays.hashCode(checksum);
        }
        return result;
    }
}