1 /*
2  * Copyright 2016 The Android Open Source Project
3  * Copyright (c) 2012,2016 Oracle and/or its affiliates. All rights reserved.
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This code is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License version 2 only, as
8  * published by the Free Software Foundation.  Oracle designates this
9  * particular file as subject to the "Classpath" exception as provided
10  * by Oracle in the LICENSE file that accompanied this code.
11  *
12  * This code is distributed in the hope that it will be useful, but WITHOUT
13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15  * version 2 for more details (a copy is included in the LICENSE file that
16  * accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License version
19  * 2 along with this work; if not, write to the Free Software Foundation,
20  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21  *
22  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
23  * or visit www.oracle.com if you need additional information or have any
24  * questions.
25  */
26 
27 package sun.security.util;
28 
29 import java.security.Key;
30 import java.security.interfaces.ECKey;
31 import java.security.interfaces.RSAKey;
32 import java.security.interfaces.DSAKey;
33 import java.security.interfaces.DSAParams;
34 import java.security.SecureRandom;
35 import java.security.spec.ECParameterSpec;
36 import javax.crypto.SecretKey;
37 import javax.crypto.interfaces.DHKey;
38 
39 /**
40  * A utility class to get key length, valiate keys, etc.
41  */
42 public final class KeyUtil {
43 
44     /**
45      * Returns the key size of the given key object in bits.
46      *
47      * @param key the key object, cannot be null
48      * @return the key size of the given key object in bits, or -1 if the
49      *       key size is not accessible
50      */
getKeySize(Key key)51     public static final int getKeySize(Key key) {
52         int size = -1;
53 
54         if (key instanceof Length) {
55             try {
56                 Length ruler = (Length)key;
57                 size = ruler.length();
58             } catch (UnsupportedOperationException usoe) {
59                 // ignore the exception
60             }
61 
62             if (size >= 0) {
63                 return size;
64             }
65         }
66 
67         // try to parse the length from key specification
68         if (key instanceof SecretKey) {
69             SecretKey sk = (SecretKey)key;
70             String format = sk.getFormat();
71             if ("RAW".equals(format) && sk.getEncoded() != null) {
72                 size = (sk.getEncoded().length * 8);
73             }   // Otherwise, it may be a unextractable key of PKCS#11, or
74                 // a key we are not able to handle.
75         } else if (key instanceof RSAKey) {
76             RSAKey pubk = (RSAKey)key;
77             size = pubk.getModulus().bitLength();
78         } else if (key instanceof ECKey) {
79             ECKey pubk = (ECKey)key;
80             // BEGIN Android-changed
81             // Was: size = pubk.getParams().getOrder().bitLength();
82             ECParameterSpec params = pubk.getParams();
83             // According to RFC 3279 section 2.3.5, EC keys are allowed
84             // to inherit parameters in an X.509 certificate issuer's
85             // key parameters, so the parameters may be null. The parent
86             // key will be rejected if its parameters don't pass, so this
87             // is okay.
88             if (params != null) {
89                 size = params.getOrder().bitLength();
90             }
91             // END Android-changed
92         } else if (key instanceof DSAKey) {
93             DSAKey pubk = (DSAKey)key;
94             DSAParams params = pubk.getParams();    // params can be null
95             size = (params != null) ? params.getP().bitLength() : -1;
96         } else if (key instanceof DHKey) {
97             DHKey pubk = (DHKey)key;
98             size = pubk.getParams().getP().bitLength();
99         }   // Otherwise, it may be a unextractable key of PKCS#11, or
100             // a key we are not able to handle.
101 
102         return size;
103     }
104 
105     // BEGIN Android-removed
106     /*
107     /**
108      * Returns whether the key is valid or not.
109      * <P>
110      * Note that this method is only apply to DHPublicKey at present.
111      *
112      * @param  publicKey
113      *         the key object, cannot be null
114      *
115      * @throws NullPointerException if {@code publicKey} is null
116      * @throws InvalidKeyException if {@code publicKey} is invalid
117      *
118     public static final void validate(Key key)
119             throws InvalidKeyException {
120         if (key == null) {
121             throw new NullPointerException(
122                 "The key to be validated cannot be null");
123         }
124 
125         if (key instanceof DHPublicKey) {
126             validateDHPublicKey((DHPublicKey)key);
127         }
128     }
129 
130 
131     /**
132      * Returns whether the key spec is valid or not.
133      * <P>
134      * Note that this method is only apply to DHPublicKeySpec at present.
135      *
136      * @param  keySpec
137      *         the key spec object, cannot be null
138      *
139      * @throws NullPointerException if {@code keySpec} is null
140      * @throws InvalidKeyException if {@code keySpec} is invalid
141      *
142     public static final void validate(KeySpec keySpec)
143             throws InvalidKeyException {
144         if (keySpec == null) {
145             throw new NullPointerException(
146                 "The key spec to be validated cannot be null");
147         }
148 
149         if (keySpec instanceof DHPublicKeySpec) {
150             validateDHPublicKey((DHPublicKeySpec)keySpec);
151         }
152     }
153 
154     /**
155      * Returns whether the specified provider is Oracle provider or not.
156      *
157      * @param  providerName
158      *         the provider name
159      * @return true if, and only if, the provider of the specified
160      *         {@code providerName} is Oracle provider
161      *
162     public static final boolean isOracleJCEProvider(String providerName) {
163         return providerName != null &&
164                 (providerName.equals("SunJCE") ||
165                     providerName.equals("SunMSCAPI") ||
166                     providerName.equals("OracleUcrypto") ||
167                     providerName.startsWith("SunPKCS11"));
168     }
169 
170     /**
171      * Check the format of TLS PreMasterSecret.
172      * <P>
173      * To avoid vulnerabilities described by section 7.4.7.1, RFC 5246,
174      * treating incorrectly formatted message blocks and/or mismatched
175      * version numbers in a manner indistinguishable from correctly
176      * formatted RSA blocks.
177      *
178      * RFC 5246 describes the approach as :
179      *
180      *  1. Generate a string R of 48 random bytes
181      *
182      *  2. Decrypt the message to recover the plaintext M
183      *
184      *  3. If the PKCS#1 padding is not correct, or the length of message
185      *     M is not exactly 48 bytes:
186      *        pre_master_secret = R
187      *     else If ClientHello.client_version <= TLS 1.0, and version
188      *     number check is explicitly disabled:
189      *        premaster secret = M
190      *     else If M[0..1] != ClientHello.client_version:
191      *        premaster secret = R
192      *     else:
193      *        premaster secret = M
194      *
195      * Note that #2 should have completed before the call to this method.
196      *
197      * @param  clientVersion the version of the TLS protocol by which the
198      *         client wishes to communicate during this session
199      * @param  serverVersion the negotiated version of the TLS protocol which
200      *         contains the lower of that suggested by the client in the client
201      *         hello and the highest supported by the server.
202      * @param  encoded the encoded key in its "RAW" encoding format
203      * @param  isFailover whether or not the previous decryption of the
204      *         encrypted PreMasterSecret message run into problem
205      * @return the polished PreMasterSecret key in its "RAW" encoding format
206      *
207     public static byte[] checkTlsPreMasterSecretKey(
208             int clientVersion, int serverVersion, SecureRandom random,
209             byte[] encoded, boolean isFailOver) {
210 
211         if (random == null) {
212             random = JCAUtil.getSecureRandom();
213         }
214         byte[] replacer = new byte[48];
215         random.nextBytes(replacer);
216 
217         if (!isFailOver && (encoded != null)) {
218             // check the length
219             if (encoded.length != 48) {
220                 // private, don't need to clone the byte array.
221                 return replacer;
222             }
223 
224             int encodedVersion =
225                     ((encoded[0] & 0xFF) << 8) | (encoded[1] & 0xFF);
226             if (clientVersion != encodedVersion) {
227                 if (clientVersion > 0x0301 ||               // 0x0301: TLSv1
228                        serverVersion != encodedVersion) {
229                     encoded = replacer;
230                 }   // Otherwise, For compatibility, we maintain the behavior
231                     // that the version in pre_master_secret can be the
232                     // negotiated version for TLS v1.0 and SSL v3.0.
233             }
234 
235             // private, don't need to clone the byte array.
236             return encoded;
237         }
238 
239         // private, don't need to clone the byte array.
240         return replacer;
241     }
242 
243     /**
244      * Returns whether the Diffie-Hellman public key is valid or not.
245      *
246      * Per RFC 2631 and NIST SP800-56A, the following algorithm is used to
247      * validate Diffie-Hellman public keys:
248      * 1. Verify that y lies within the interval [2,p-1]. If it does not,
249      *    the key is invalid.
250      * 2. Compute y^q mod p. If the result == 1, the key is valid.
251      *    Otherwise the key is invalid.
252      *
253     private static void validateDHPublicKey(DHPublicKey publicKey)
254             throws InvalidKeyException {
255         DHParameterSpec paramSpec = publicKey.getParams();
256 
257         BigInteger p = paramSpec.getP();
258         BigInteger g = paramSpec.getG();
259         BigInteger y = publicKey.getY();
260 
261         validateDHPublicKey(p, g, y);
262     }
263 
264     private static void validateDHPublicKey(DHPublicKeySpec publicKeySpec)
265             throws InvalidKeyException {
266         validateDHPublicKey(publicKeySpec.getP(),
267             publicKeySpec.getG(), publicKeySpec.getY());
268     }
269 
270     private static void validateDHPublicKey(BigInteger p,
271             BigInteger g, BigInteger y) throws InvalidKeyException {
272 
273         // For better interoperability, the interval is limited to [2, p-2].
274         BigInteger leftOpen = BigInteger.ONE;
275         BigInteger rightOpen = p.subtract(BigInteger.ONE);
276         if (y.compareTo(leftOpen) <= 0) {
277             throw new InvalidKeyException(
278                     "Diffie-Hellman public key is too small");
279         }
280         if (y.compareTo(rightOpen) >= 0) {
281             throw new InvalidKeyException(
282                     "Diffie-Hellman public key is too large");
283         }
284 
285         // y^q mod p == 1?
286         // Unable to perform this check as q is unknown in this circumstance.
287 
288         // p is expected to be prime.  However, it is too expensive to check
289         // that p is prime.  Instead, in order to mitigate the impact of
290         // non-prime values, we check that y is not a factor of p.
291         BigInteger r = p.remainder(y);
292         if (r.equals(BigInteger.ZERO)) {
293             throw new InvalidKeyException("Invalid Diffie-Hellman parameters");
294         }
295     }
296 
297     /**
298      * Trim leading (most significant) zeroes from the result.
299      *
300      * @throws NullPointerException if {@code b} is null
301      *
302     public static byte[] trimZeroes(byte[] b) {
303         int i = 0;
304         while ((i < b.length - 1) && (b[i] == 0)) {
305             i++;
306         }
307         if (i == 0) {
308             return b;
309         }
310         byte[] t = new byte[b.length - i];
311         System.arraycopy(b, i, t, 0, t.length);
312         return t;
313     }
314     */
315     // END Android-removed
316 
317 }
318