1 /*
   2  * Copyright (c) 1996, 2016, 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 
  27 package sun.security.ssl;
  28 
  29 import java.io.*;
  30 import java.security.*;
  31 
  32 import javax.crypto.*;
  33 
  34 import javax.net.ssl.*;
  35 
  36 import sun.security.internal.spec.TlsRsaPremasterSecretParameterSpec;
  37 import sun.security.util.KeyUtil;
  38 
  39 /**
  40  * This is the client key exchange message (CLIENT --> SERVER) used with
  41  * all RSA key exchanges; it holds the RSA-encrypted pre-master secret.
  42  *
  43  * The message is encrypted using PKCS #1 block type 02 encryption with the
  44  * server's public key.  The padding and resulting message size is a function
  45  * of this server's public key modulus size, but the pre-master secret is
  46  * always exactly 48 bytes.
  47  *
  48  */
  49 final class RSAClientKeyExchange extends HandshakeMessage {
  50 
  51     /*
  52      * The following field values were encrypted with the server's public
  53      * key (or temp key from server key exchange msg) and are presented
  54      * here in DECRYPTED form.
  55      */
  56     private ProtocolVersion protocolVersion; // preMaster [0,1]
  57     SecretKey preMaster;
  58     private byte[] encrypted;           // same size as public modulus
  59 
  60     /*
  61      * Client randomly creates a pre-master secret and encrypts it
  62      * using the server's RSA public key; only the server can decrypt
  63      * it, using its RSA private key.  Result is the same size as the
  64      * server's public key, and uses PKCS #1 block format 02.
  65      */
  66     @SuppressWarnings("deprecation")
  67     RSAClientKeyExchange(ProtocolVersion protocolVersion,
  68             ProtocolVersion maxVersion,
  69             SecureRandom generator, PublicKey publicKey) throws IOException {
  70         if (publicKey.getAlgorithm().equals("RSA") == false) {
  71             throw new SSLKeyException("Public key not of type RSA: " + 
  72                 publicKey.getAlgorithm());
  73         }
  74         this.protocolVersion = protocolVersion;
  75 
  76         try {
  77             String s = protocolVersion.useTLS12PlusSpec() ?
  78                 "SunTls12RsaPremasterSecret" : "SunTlsRsaPremasterSecret";
  79             KeyGenerator kg = JsseJce.getKeyGenerator(s);
  80             kg.init(new TlsRsaPremasterSecretParameterSpec(
  81                     maxVersion.v, protocolVersion.v), generator);
  82             preMaster = kg.generateKey();
  83 
  84             Cipher cipher = JsseJce.getCipher(JsseJce.CIPHER_RSA_PKCS1);
  85             cipher.init(Cipher.WRAP_MODE, publicKey, generator);
  86             encrypted = cipher.wrap(preMaster);
  87         } catch (GeneralSecurityException e) {
  88             throw (SSLKeyException)new SSLKeyException
  89                                 ("RSA premaster secret error").initCause(e);
  90         }
  91     }
  92 
  93     /*
  94      * Server gets the PKCS #1 (block format 02) data, decrypts
  95      * it with its private key.
  96      */
  97     @SuppressWarnings("deprecation")
  98     RSAClientKeyExchange(ProtocolVersion currentVersion,
  99             ProtocolVersion maxVersion,
 100             SecureRandom generator, HandshakeInStream input,
 101             int messageSize, PrivateKey privateKey) throws IOException {
 102 
 103         if (privateKey.getAlgorithm().equals("RSA") == false) {
 104             throw new SSLKeyException("Private key not of type RSA: " + 
 105                  privateKey.getAlgorithm());
 106         }
 107 
 108         if (currentVersion.useTLS10PlusSpec()) {
 109             encrypted = input.getBytes16();
 110         } else {
 111             encrypted = new byte [messageSize];
 112             if (input.read(encrypted) != messageSize) {
 113                 throw new SSLProtocolException(
 114                         "SSL: read PreMasterSecret: short read");
 115             }
 116         }
 117 
 118         byte[] encoded = null;
 119         try {
 120             boolean needFailover = false;
 121             Cipher cipher = JsseJce.getCipher(JsseJce.CIPHER_RSA_PKCS1);
 122             try {
 123                 // Try UNWRAP_MODE mode firstly.
 124                 cipher.init(Cipher.UNWRAP_MODE, privateKey,
 125                         new TlsRsaPremasterSecretParameterSpec(
 126                                 maxVersion.v, currentVersion.v),
 127                         generator);
 128 
 129                 // The provider selection can be delayed, please don't call
 130                 // any Cipher method before the call to Cipher.init().
 131                 needFailover = !KeyUtil.isOracleJCEProvider(
 132                         cipher.getProvider().getName());
 133             } catch (InvalidKeyException | UnsupportedOperationException iue) {
 134                 if (debug != null && Debug.isOn("handshake")) {
 135                     System.out.println("The Cipher provider " +
 136                         cipher.getProvider().getName() +
 137                         " caused exception: " + iue.getMessage());
 138                 }
 139 
 140                 needFailover = true;
 141             }
 142 
 143             if (needFailover) {
 144                 // Use DECRYPT_MODE and dispose the previous initialization.
 145                 cipher.init(Cipher.DECRYPT_MODE, privateKey);
 146                 boolean failed = false;
 147                 try {
 148                     encoded = cipher.doFinal(encrypted);
 149                 } catch (BadPaddingException bpe) {
 150                     // Note: encoded == null
 151                     failed = true;
 152                 }
 153                 encoded = KeyUtil.checkTlsPreMasterSecretKey(
 154                                 maxVersion.v, currentVersion.v,
 155                                 generator, encoded, failed);
 156                 preMaster = generatePreMasterSecret(
 157                                 maxVersion.v, currentVersion.v,
 158                                 encoded, generator);
 159             } else {
 160                 // the cipher should have been initialized
 161                 preMaster = (SecretKey)cipher.unwrap(encrypted,
 162                         "TlsRsaPremasterSecret", Cipher.SECRET_KEY);
 163             }
 164         } catch (InvalidKeyException ibk) {
 165             // the message is too big to process with RSA
 166             throw new SSLException(
 167                 "Unable to process PreMasterSecret", ibk);
 168         } catch (Exception e) {
 169             // unlikely to happen, otherwise, must be a provider exception
 170             if (debug != null && Debug.isOn("handshake")) {
 171                 System.out.println("RSA premaster secret decryption error:");
 172                 e.printStackTrace(System.out);
 173             }
 174             throw new RuntimeException("Could not generate dummy secret", e);
 175         }
 176     }
 177 
 178     // generate a premaster secret with the specified version number
 179     @SuppressWarnings("deprecation")
 180     private static SecretKey generatePreMasterSecret(
 181             int clientVersion, int serverVersion,
 182             byte[] encodedSecret, SecureRandom generator) {
 183 
 184         if (debug != null && Debug.isOn("handshake")) {
 185             System.out.println("Generating a premaster secret");
 186         }
 187 
 188         try {
 189             String s = ((clientVersion >= ProtocolVersion.TLS12.v) ?
 190                 "SunTls12RsaPremasterSecret" : "SunTlsRsaPremasterSecret");
 191             KeyGenerator kg = JsseJce.getKeyGenerator(s);
 192             kg.init(new TlsRsaPremasterSecretParameterSpec(
 193                     clientVersion, serverVersion, encodedSecret),
 194                     generator);
 195             return kg.generateKey();
 196         } catch (InvalidAlgorithmParameterException |
 197                 NoSuchAlgorithmException iae) {
 198             // unlikely to happen, otherwise, must be a provider exception
 199             if (debug != null && Debug.isOn("handshake")) {
 200                 System.out.println("RSA premaster secret generation error:");
 201                 iae.printStackTrace(System.out);
 202             }
 203             throw new RuntimeException("Could not generate premaster secret", iae);
 204         }
 205     }
 206 
 207     @Override
 208     int messageType() {
 209         return ht_client_key_exchange;
 210     }
 211 
 212     @Override
 213     int messageLength() {
 214         if (protocolVersion.useTLS10PlusSpec()) {
 215             return encrypted.length + 2;
 216         } else {
 217             return encrypted.length;
 218         }
 219     }
 220 
 221     @Override
 222     void send(HandshakeOutStream s) throws IOException {
 223         if (protocolVersion.useTLS10PlusSpec()) {
 224             s.putBytes16(encrypted);
 225         } else {
 226             s.write(encrypted);
 227         }
 228     }
 229 
 230     @Override
 231     void print(PrintStream s) throws IOException {
 232         s.println("*** ClientKeyExchange, RSA PreMasterSecret, " +
 233                                                         protocolVersion);
 234     }
 235 }