jdk/src/java.security.jgss/share/classes/sun/security/ssl/krb5/KerberosPreMasterSecret.java
changeset 34071 654e1a23e215
parent 34070 792098bae87e
parent 31008 5b500c93ce48
child 34072 287dc5c0072b
equal deleted inserted replaced
34070:792098bae87e 34071:654e1a23e215
     1 /*
       
     2  * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
       
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
       
     4  *
       
     5  * This code is free software; you can redistribute it and/or modify it
       
     6  * under the terms of the GNU General Public License version 2 only, as
       
     7  * published by the Free Software Foundation.  Oracle designates this
       
     8  * particular file as subject to the "Classpath" exception as provided
       
     9  * by Oracle in the LICENSE file that accompanied this code.
       
    10  *
       
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
       
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
       
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
       
    14  * version 2 for more details (a copy is included in the LICENSE file that
       
    15  * accompanied this code).
       
    16  *
       
    17  * You should have received a copy of the GNU General Public License version
       
    18  * 2 along with this work; if not, write to the Free Software Foundation,
       
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
       
    20  *
       
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
       
    22  * or visit www.oracle.com if you need additional information or have any
       
    23  * questions.
       
    24  */
       
    25 
       
    26 package sun.security.ssl.krb5;
       
    27 
       
    28 import java.io.*;
       
    29 import java.security.*;
       
    30 import java.util.Arrays;
       
    31 
       
    32 import javax.net.ssl.*;
       
    33 
       
    34 import sun.security.krb5.EncryptionKey;
       
    35 import sun.security.krb5.EncryptedData;
       
    36 import sun.security.krb5.KrbException;
       
    37 import sun.security.krb5.internal.crypto.KeyUsage;
       
    38 
       
    39 import sun.security.ssl.Debug;
       
    40 import sun.security.ssl.HandshakeInStream;
       
    41 import sun.security.ssl.HandshakeMessage;
       
    42 import sun.security.ssl.ProtocolVersion;
       
    43 
       
    44 /**
       
    45  * This is the Kerberos premaster secret in the Kerberos client key
       
    46  * exchange message (CLIENT --> SERVER); it holds the
       
    47  * Kerberos-encrypted pre-master secret. The secret is encrypted using the
       
    48  * Kerberos session key.  The padding and size of the resulting message
       
    49  * depends on the session key type, but the pre-master secret is
       
    50  * always exactly 48 bytes.
       
    51  *
       
    52  */
       
    53 final class KerberosPreMasterSecret {
       
    54 
       
    55     private ProtocolVersion protocolVersion; // preMaster [0,1]
       
    56     private byte preMaster[];           // 48 bytes
       
    57     private byte encrypted[];
       
    58 
       
    59     /**
       
    60      * Constructor used by client to generate premaster secret.
       
    61      *
       
    62      * Client randomly creates a pre-master secret and encrypts it
       
    63      * using the Kerberos session key; only the server can decrypt
       
    64      * it, using the session key available in the service ticket.
       
    65      *
       
    66      * @param protocolVersion used to set preMaster[0,1]
       
    67      * @param generator random number generator for generating premaster secret
       
    68      * @param sessionKey Kerberos session key for encrypting premaster secret
       
    69      */
       
    70     KerberosPreMasterSecret(ProtocolVersion protocolVersion,
       
    71         SecureRandom generator, EncryptionKey sessionKey) throws IOException {
       
    72 
       
    73         if (sessionKey.getEType() ==
       
    74             EncryptedData.ETYPE_DES3_CBC_HMAC_SHA1_KD) {
       
    75             throw new IOException(
       
    76                "session keys with des3-cbc-hmac-sha1-kd encryption type " +
       
    77                "are not supported for TLS Kerberos cipher suites");
       
    78         }
       
    79 
       
    80         this.protocolVersion = protocolVersion;
       
    81         preMaster = generatePreMaster(generator, protocolVersion);
       
    82 
       
    83         // Encrypt premaster secret
       
    84         try {
       
    85             EncryptedData eData = new EncryptedData(sessionKey, preMaster,
       
    86                 KeyUsage.KU_UNKNOWN);
       
    87             encrypted = eData.getBytes();  // not ASN.1 encoded.
       
    88 
       
    89         } catch (KrbException e) {
       
    90             throw (SSLKeyException)new SSLKeyException
       
    91                 ("Kerberos premaster secret error").initCause(e);
       
    92         }
       
    93     }
       
    94 
       
    95     /*
       
    96      * Constructor used by server to decrypt encrypted premaster secret.
       
    97      * The protocol version in preMaster[0,1] must match either currentVersion
       
    98      * or clientVersion, otherwise, the premaster secret is set to
       
    99      * a random one to foil possible attack.
       
   100      *
       
   101      * @param currentVersion version of protocol being used
       
   102      * @param clientVersion version requested by client
       
   103      * @param generator random number generator used to generate
       
   104      *        bogus premaster secret if premaster secret verification fails
       
   105      * @param input input stream from which to read the encrypted
       
   106      *        premaster secret
       
   107      * @param sessionKey Kerberos session key to be used for decryption
       
   108      */
       
   109     KerberosPreMasterSecret(ProtocolVersion currentVersion,
       
   110         ProtocolVersion clientVersion,
       
   111         SecureRandom generator, HandshakeInStream input,
       
   112         EncryptionKey sessionKey) throws IOException {
       
   113 
       
   114          // Extract encrypted premaster secret from message
       
   115          encrypted = input.getBytes16();
       
   116 
       
   117          if (HandshakeMessage.debug != null && Debug.isOn("handshake")) {
       
   118             if (encrypted != null) {
       
   119                 Debug.println(System.out,
       
   120                      "encrypted premaster secret", encrypted);
       
   121             }
       
   122          }
       
   123 
       
   124         if (sessionKey.getEType() ==
       
   125             EncryptedData.ETYPE_DES3_CBC_HMAC_SHA1_KD) {
       
   126             throw new IOException(
       
   127                "session keys with des3-cbc-hmac-sha1-kd encryption type " +
       
   128                "are not supported for TLS Kerberos cipher suites");
       
   129         }
       
   130 
       
   131         // Decrypt premaster secret
       
   132         try {
       
   133             EncryptedData data = new EncryptedData(sessionKey.getEType(),
       
   134                         null /* optional kvno */, encrypted);
       
   135 
       
   136             byte[] temp = data.decrypt(sessionKey, KeyUsage.KU_UNKNOWN);
       
   137             if (HandshakeMessage.debug != null && Debug.isOn("handshake")) {
       
   138                  if (encrypted != null) {
       
   139                      Debug.println(System.out,
       
   140                          "decrypted premaster secret", temp);
       
   141                  }
       
   142             }
       
   143 
       
   144             // Remove padding bytes after decryption. Only DES and DES3 have
       
   145             // paddings and we don't support DES3 in TLS (see above)
       
   146 
       
   147             if (temp.length == 52 &&
       
   148                     data.getEType() == EncryptedData.ETYPE_DES_CBC_CRC) {
       
   149                 // For des-cbc-crc, 4 paddings. Value can be 0x04 or 0x00.
       
   150                 if (paddingByteIs(temp, 52, (byte)4) ||
       
   151                         paddingByteIs(temp, 52, (byte)0)) {
       
   152                     temp = Arrays.copyOf(temp, 48);
       
   153                 }
       
   154             } else if (temp.length == 56 &&
       
   155                     data.getEType() == EncryptedData.ETYPE_DES_CBC_MD5) {
       
   156                 // For des-cbc-md5, 8 paddings with 0x08, or no padding
       
   157                 if (paddingByteIs(temp, 56, (byte)8)) {
       
   158                     temp = Arrays.copyOf(temp, 48);
       
   159                 }
       
   160             }
       
   161 
       
   162             preMaster = temp;
       
   163 
       
   164             protocolVersion = ProtocolVersion.valueOf(preMaster[0],
       
   165                  preMaster[1]);
       
   166             if (HandshakeMessage.debug != null && Debug.isOn("handshake")) {
       
   167                  System.out.println("Kerberos PreMasterSecret version: "
       
   168                         + protocolVersion);
       
   169             }
       
   170         } catch (Exception e) {
       
   171             // catch exception & process below
       
   172             preMaster = null;
       
   173             protocolVersion = currentVersion;
       
   174         }
       
   175 
       
   176         // check if the premaster secret version is ok
       
   177         // the specification says that it must be the maximum version supported
       
   178         // by the client from its ClientHello message. However, many
       
   179         // old implementations send the negotiated version, so accept both
       
   180         // for SSL v3.0 and TLS v1.0.
       
   181         // NOTE that we may be comparing two unsupported version numbers in
       
   182         // the second case, which is why we cannot use object references
       
   183         // equality in this special case
       
   184         boolean versionMismatch = (protocolVersion.v != clientVersion.v);
       
   185 
       
   186         /*
       
   187          * we never checked the client_version in server side
       
   188          * for TLS v1.0 and SSL v3.0. For compatibility, we
       
   189          * maintain this behavior.
       
   190          */
       
   191         if (versionMismatch && (clientVersion.v <= 0x0301)) {
       
   192             versionMismatch = (protocolVersion.v != currentVersion.v);
       
   193         }
       
   194 
       
   195         /*
       
   196          * Bogus decrypted ClientKeyExchange? If so, conjure a
       
   197          * a random preMaster secret that will fail later during
       
   198          * Finished message processing. This is a countermeasure against
       
   199          * the "interactive RSA PKCS#1 encryption envelop attack" reported
       
   200          * in June 1998. Preserving the executation path will
       
   201          * mitigate timing attacks and force consistent error handling
       
   202          * that will prevent an attacking client from differentiating
       
   203          * different kinds of decrypted ClientKeyExchange bogosities.
       
   204          */
       
   205          if ((preMaster == null) || (preMaster.length != 48)
       
   206                 || versionMismatch) {
       
   207             if (HandshakeMessage.debug != null && Debug.isOn("handshake")) {
       
   208                 System.out.println("Kerberos PreMasterSecret error, "
       
   209                                    + "generating random secret");
       
   210                 if (preMaster != null) {
       
   211                     Debug.println(System.out, "Invalid secret", preMaster);
       
   212                 }
       
   213             }
       
   214 
       
   215             /*
       
   216              * Randomize the preMaster secret with the
       
   217              * ClientHello.client_version, as will produce invalid master
       
   218              * secret to prevent the attacks.
       
   219              */
       
   220             preMaster = generatePreMaster(generator, clientVersion);
       
   221             protocolVersion = clientVersion;
       
   222         }
       
   223     }
       
   224 
       
   225     /**
       
   226      * Checks if all paddings of data are b
       
   227      * @param data the block with padding
       
   228      * @param len length of data, >= 48
       
   229      * @param b expected padding byte
       
   230      */
       
   231     private static boolean paddingByteIs(byte[] data, int len, byte b) {
       
   232         for (int i=48; i<len; i++) {
       
   233             if (data[i] != b) return false;
       
   234         }
       
   235         return true;
       
   236     }
       
   237 
       
   238     /*
       
   239      * Used by server to generate premaster secret in case of
       
   240      * problem decoding ticket.
       
   241      *
       
   242      * @param protocolVersion used for preMaster[0,1]
       
   243      * @param generator random number generator to use for generating secret.
       
   244      */
       
   245     KerberosPreMasterSecret(ProtocolVersion protocolVersion,
       
   246         SecureRandom generator) {
       
   247 
       
   248         this.protocolVersion = protocolVersion;
       
   249         preMaster = generatePreMaster(generator, protocolVersion);
       
   250     }
       
   251 
       
   252     private static byte[] generatePreMaster(SecureRandom rand,
       
   253         ProtocolVersion ver) {
       
   254 
       
   255         byte[] pm = new byte[48];
       
   256         rand.nextBytes(pm);
       
   257         pm[0] = ver.major;
       
   258         pm[1] = ver.minor;
       
   259 
       
   260         return pm;
       
   261     }
       
   262 
       
   263     // Clone not needed; internal use only
       
   264     byte[] getUnencrypted() {
       
   265         return preMaster;
       
   266     }
       
   267 
       
   268     // Clone not needed; internal use only
       
   269     byte[] getEncrypted() {
       
   270         return encrypted;
       
   271     }
       
   272 }