1/*
2 * Copyright (c) 2005, 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
26package sun.security.pkcs11;
27
28import java.util.*;
29
30import java.security.*;
31import java.security.spec.AlgorithmParameterSpec;
32
33import javax.crypto.*;
34import javax.crypto.spec.*;
35
36import sun.security.internal.spec.*;
37import sun.security.internal.interfaces.TlsMasterSecret;
38
39import static sun.security.pkcs11.TemplateManager.*;
40import sun.security.pkcs11.wrapper.*;
41import 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 */
50public 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    // whether SSLv3 is supported
72    private final boolean supportSSLv3;
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        // Given the current lookup order specified in SunPKCS11.java,
82        // if CKM_SSL3_KEY_AND_MAC_DERIVE is not used to construct this object,
83        // it means that this mech is disabled or unsupported.
84        this.supportSSLv3 = (mechanism == CKM_SSL3_KEY_AND_MAC_DERIVE);
85    }
86
87    protected void engineInit(SecureRandom random) {
88        throw new InvalidParameterException(MSG);
89    }
90
91    @SuppressWarnings("deprecation")
92    protected void engineInit(AlgorithmParameterSpec params,
93            SecureRandom random) throws InvalidAlgorithmParameterException {
94        if (params instanceof TlsKeyMaterialParameterSpec == false) {
95            throw new InvalidAlgorithmParameterException(MSG);
96        }
97
98        TlsKeyMaterialParameterSpec spec = (TlsKeyMaterialParameterSpec)params;
99        int version = (spec.getMajorVersion() << 8) | spec.getMinorVersion();
100
101        if ((version == 0x0300 && !supportSSLv3) || (version < 0x0300) ||
102            (version > 0x0302)) {
103             throw new InvalidAlgorithmParameterException
104                    ("Only" + (supportSSLv3? " SSL 3.0,": "") +
105                     " TLS 1.0, and TLS 1.1 are supported (0x" +
106                     Integer.toHexString(version) + ")");
107        }
108        try {
109            p11Key = P11SecretKeyFactory.convertKey
110                            (token, spec.getMasterSecret(), "TlsMasterSecret");
111        } catch (InvalidKeyException e) {
112            throw new InvalidAlgorithmParameterException("init() failed", e);
113        }
114        this.spec = spec;
115        this.mechanism = (version == 0x0300)?
116            CKM_SSL3_KEY_AND_MAC_DERIVE : CKM_TLS_KEY_AND_MAC_DERIVE;
117    }
118
119    protected void engineInit(int keysize, SecureRandom random) {
120        throw new InvalidParameterException(MSG);
121    }
122
123    @SuppressWarnings("deprecation")
124    protected SecretKey engineGenerateKey() {
125        if (spec == null) {
126            throw new IllegalStateException
127                ("TlsKeyMaterialGenerator must be initialized");
128        }
129        int macBits = spec.getMacKeyLength() << 3;
130        int ivBits = spec.getIvLength() << 3;
131
132        int expandedKeyBits = spec.getExpandedCipherKeyLength() << 3;
133        int keyBits = spec.getCipherKeyLength() << 3;
134        boolean isExportable;
135        if (expandedKeyBits != 0) {
136            isExportable = true;
137        } else {
138            isExportable = false;
139            expandedKeyBits = keyBits;
140        }
141
142        CK_SSL3_RANDOM_DATA random = new CK_SSL3_RANDOM_DATA
143                            (spec.getClientRandom(), spec.getServerRandom());
144        CK_SSL3_KEY_MAT_PARAMS params = new CK_SSL3_KEY_MAT_PARAMS
145                            (macBits, keyBits, ivBits, isExportable, random);
146
147        String cipherAlgorithm = spec.getCipherAlgorithm();
148        long keyType = P11SecretKeyFactory.getKeyType(cipherAlgorithm);
149        if (keyType < 0) {
150            if (keyBits != 0) {
151                throw new ProviderException
152                            ("Unknown algorithm: " + spec.getCipherAlgorithm());
153            } else {
154                // NULL encryption ciphersuites
155                keyType = CKK_GENERIC_SECRET;
156            }
157        }
158
159        Session session = null;
160        try {
161            session = token.getObjSession();
162            CK_ATTRIBUTE[] attributes;
163            if (keyBits != 0) {
164                attributes = new CK_ATTRIBUTE[] {
165                    new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY),
166                    new CK_ATTRIBUTE(CKA_KEY_TYPE, keyType),
167                    new CK_ATTRIBUTE(CKA_VALUE_LEN, expandedKeyBits >> 3),
168                };
169            } else {
170                // ciphersuites with NULL ciphers
171                attributes = new CK_ATTRIBUTE[0];
172            }
173            attributes = token.getAttributes
174                (O_GENERATE, CKO_SECRET_KEY, keyType, attributes);
175            // the returned keyID is a dummy, ignore
176            long keyID = token.p11.C_DeriveKey(session.id(),
177                new CK_MECHANISM(mechanism, params), p11Key.keyID, attributes);
178
179            CK_SSL3_KEY_MAT_OUT out = params.pReturnedKeyMaterial;
180            // Note that the MAC keys do not inherit all attributes from the
181            // template, but they do inherit the sensitive/extractable/token
182            // flags, which is all P11Key cares about.
183            SecretKey clientMacKey, serverMacKey;
184
185            // The MAC size may be zero for GCM mode.
186            //
187            // PKCS11 does not support GCM mode as the author made the comment,
188            // so the macBits is unlikely to be zero. It's only a place holder.
189            if (macBits != 0) {
190                clientMacKey = P11Key.secretKey
191                    (session, out.hClientMacSecret, "MAC", macBits, attributes);
192                serverMacKey = P11Key.secretKey
193                    (session, out.hServerMacSecret, "MAC", macBits, attributes);
194            } else {
195                clientMacKey = null;
196                serverMacKey = null;
197            }
198
199            SecretKey clientCipherKey, serverCipherKey;
200            if (keyBits != 0) {
201                clientCipherKey = P11Key.secretKey(session, out.hClientKey,
202                        cipherAlgorithm, expandedKeyBits, attributes);
203                serverCipherKey = P11Key.secretKey(session, out.hServerKey,
204                        cipherAlgorithm, expandedKeyBits, attributes);
205            } else {
206                clientCipherKey = null;
207                serverCipherKey = null;
208            }
209            IvParameterSpec clientIv = (out.pIVClient == null)
210                                    ? null : new IvParameterSpec(out.pIVClient);
211            IvParameterSpec serverIv = (out.pIVServer == null)
212                                    ? null : new IvParameterSpec(out.pIVServer);
213
214            return new TlsKeyMaterialSpec(clientMacKey, serverMacKey,
215                    clientCipherKey, clientIv, serverCipherKey, serverIv);
216
217        } catch (Exception e) {
218            throw new ProviderException("Could not generate key", e);
219        } finally {
220            token.releaseSession(session);
221        }
222    }
223
224}
225