1 /*
   2  * Copyright (c) 2005, 2014, 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.pkcs11;
  27 
  28 import java.util.*;
  29 
  30 import java.security.*;
  31 import java.security.spec.AlgorithmParameterSpec;
  32 
  33 import javax.crypto.*;
  34 import javax.crypto.spec.*;
  35 
  36 import sun.security.internal.spec.*;
  37 import sun.security.internal.interfaces.TlsMasterSecret;
  38 
  39 import static sun.security.pkcs11.TemplateManager.*;
  40 import sun.security.pkcs11.wrapper.*;
  41 import static sun.security.pkcs11.wrapper.PKCS11Constants.*;
  42 
  43 /**
  44  * KeyGenerator to calculate the SSL/TLS key material (cipher keys and ivs,
  45  * mac keys) from the master secret.
  46  *
  47  * @author  Andreas Sterbenz
  48  * @since   1.6
  49  */
  50 public final class P11TlsKeyMaterialGenerator extends KeyGeneratorSpi {
  51 
  52     private final static String MSG = "TlsKeyMaterialGenerator must be "
  53         + "initialized using a TlsKeyMaterialParameterSpec";
  54 
  55     // token instance
  56     private final Token token;
  57 
  58     // algorithm name
  59     private final String algorithm;
  60 
  61     // mechanism id
  62     private long mechanism;
  63 
  64     // parameter spec
  65     @SuppressWarnings("deprecation")
  66     private TlsKeyMaterialParameterSpec spec;
  67 
  68     // master secret as a P11Key
  69     private P11Key p11Key;
  70 
  71     // version, e.g. 0x0301
  72     private int version;
  73 
  74     P11TlsKeyMaterialGenerator(Token token, String algorithm, long mechanism)
  75             throws PKCS11Exception {
  76         super();
  77         this.token = token;
  78         this.algorithm = algorithm;
  79         this.mechanism = mechanism;
  80     }
  81 
  82     protected void engineInit(SecureRandom random) {
  83         throw new InvalidParameterException(MSG);
  84     }
  85 
  86     @SuppressWarnings("deprecation")
  87     protected void engineInit(AlgorithmParameterSpec params,
  88             SecureRandom random) throws InvalidAlgorithmParameterException {
  89         if (params instanceof TlsKeyMaterialParameterSpec == false) {
  90             throw new InvalidAlgorithmParameterException(MSG);
  91         }
  92         this.spec = (TlsKeyMaterialParameterSpec)params;
  93         try {
  94             p11Key = P11SecretKeyFactory.convertKey
  95                             (token, spec.getMasterSecret(), "TlsMasterSecret");
  96         } catch (InvalidKeyException e) {
  97             throw new InvalidAlgorithmParameterException("init() failed", e);
  98         }
  99         version = (spec.getMajorVersion() << 8) | spec.getMinorVersion();
 100         if ((version < 0x0300) && (version > 0x0302)) {
 101             throw new InvalidAlgorithmParameterException
 102                     ("Only SSL 3.0, TLS 1.0, and TLS 1.1 are supported");
 103         }
 104         // we assume the token supports both the CKM_SSL3_* and the CKM_TLS_*
 105         // mechanisms
 106     }
 107 
 108     protected void engineInit(int keysize, SecureRandom random) {
 109         throw new InvalidParameterException(MSG);
 110     }
 111 
 112     @SuppressWarnings("deprecation")
 113     protected SecretKey engineGenerateKey() {
 114         if (spec == null) {
 115             throw new IllegalStateException
 116                 ("TlsKeyMaterialGenerator must be initialized");
 117         }
 118         mechanism = (version == 0x0300) ? CKM_SSL3_KEY_AND_MAC_DERIVE
 119                                          : CKM_TLS_KEY_AND_MAC_DERIVE;
 120         int macBits = spec.getMacKeyLength() << 3;
 121         int ivBits = spec.getIvLength() << 3;
 122 
 123         int expandedKeyBits = spec.getExpandedCipherKeyLength() << 3;
 124         int keyBits = spec.getCipherKeyLength() << 3;
 125         boolean isExportable;
 126         if (expandedKeyBits != 0) {
 127             isExportable = true;
 128         } else {
 129             isExportable = false;
 130             expandedKeyBits = keyBits;
 131         }
 132 
 133         CK_SSL3_RANDOM_DATA random = new CK_SSL3_RANDOM_DATA
 134                             (spec.getClientRandom(), spec.getServerRandom());
 135         CK_SSL3_KEY_MAT_PARAMS params = new CK_SSL3_KEY_MAT_PARAMS
 136                             (macBits, keyBits, ivBits, isExportable, random);
 137 
 138         String cipherAlgorithm = spec.getCipherAlgorithm();
 139         long keyType = P11SecretKeyFactory.getKeyType(cipherAlgorithm);
 140         if (keyType < 0) {
 141             if (keyBits != 0) {
 142                 throw new ProviderException
 143                             ("Unknown algorithm: " + spec.getCipherAlgorithm());
 144             } else {
 145                 // NULL encryption ciphersuites
 146                 keyType = CKK_GENERIC_SECRET;
 147             }
 148         }
 149 
 150         Session session = null;
 151         try {
 152             session = token.getObjSession();
 153             CK_ATTRIBUTE[] attributes;
 154             if (keyBits != 0) {
 155                 attributes = new CK_ATTRIBUTE[] {
 156                     new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY),
 157                     new CK_ATTRIBUTE(CKA_KEY_TYPE, keyType),
 158                     new CK_ATTRIBUTE(CKA_VALUE_LEN, expandedKeyBits >> 3),
 159                 };
 160             } else {
 161                 // ciphersuites with NULL ciphers
 162                 attributes = new CK_ATTRIBUTE[0];
 163             }
 164             attributes = token.getAttributes
 165                 (O_GENERATE, CKO_SECRET_KEY, keyType, attributes);
 166             // the returned keyID is a dummy, ignore
 167             long keyID = token.p11.C_DeriveKey(session.id(),
 168                 new CK_MECHANISM(mechanism, params), p11Key.keyID, attributes);
 169 
 170             CK_SSL3_KEY_MAT_OUT out = params.pReturnedKeyMaterial;
 171             // Note that the MAC keys do not inherit all attributes from the
 172             // template, but they do inherit the sensitive/extractable/token
 173             // flags, which is all P11Key cares about.
 174             SecretKey clientMacKey, serverMacKey;
 175 
 176             // The MAC size may be zero for GCM mode.
 177             //
 178             // PKCS11 does not support GCM mode as the author made the comment,
 179             // so the macBits is unlikely to be zero. It's only a place holder.
 180             if (macBits != 0) {
 181                 clientMacKey = P11Key.secretKey
 182                     (session, out.hClientMacSecret, "MAC", macBits, attributes);
 183                 serverMacKey = P11Key.secretKey
 184                     (session, out.hServerMacSecret, "MAC", macBits, attributes);
 185             } else {
 186                 clientMacKey = null;
 187                 serverMacKey = null;
 188             }
 189 
 190             SecretKey clientCipherKey, serverCipherKey;
 191             if (keyBits != 0) {
 192                 clientCipherKey = P11Key.secretKey(session, out.hClientKey,
 193                         cipherAlgorithm, expandedKeyBits, attributes);
 194                 serverCipherKey = P11Key.secretKey(session, out.hServerKey,
 195                         cipherAlgorithm, expandedKeyBits, attributes);
 196             } else {
 197                 clientCipherKey = null;
 198                 serverCipherKey = null;
 199             }
 200             IvParameterSpec clientIv = (out.pIVClient == null)
 201                                     ? null : new IvParameterSpec(out.pIVClient);
 202             IvParameterSpec serverIv = (out.pIVServer == null)
 203                                     ? null : new IvParameterSpec(out.pIVServer);
 204 
 205             return new TlsKeyMaterialSpec(clientMacKey, serverMacKey,
 206                     clientCipherKey, clientIv, serverCipherKey, serverIv);
 207 
 208         } catch (Exception e) {
 209             throw new ProviderException("Could not generate key", e);
 210         } finally {
 211             token.releaseSession(session);
 212         }
 213     }
 214 
 215 }