1/*
2 * Copyright (c) 2014, 2015, 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 com.oracle.security.ucrypto;
27
28import java.util.Arrays;
29import java.util.WeakHashMap;
30import java.util.Collections;
31import java.util.Map;
32
33import java.security.AlgorithmParameters;
34import java.security.InvalidAlgorithmParameterException;
35import java.security.InvalidKeyException;
36import java.security.Key;
37import java.security.PublicKey;
38import java.security.PrivateKey;
39import java.security.spec.RSAPrivateCrtKeySpec;
40import java.security.spec.RSAPrivateKeySpec;
41import java.security.spec.RSAPublicKeySpec;
42import java.security.interfaces.RSAKey;
43import java.security.interfaces.RSAPrivateCrtKey;
44import java.security.interfaces.RSAPrivateKey;
45import java.security.interfaces.RSAPublicKey;
46
47import java.security.KeyFactory;
48import java.security.NoSuchAlgorithmException;
49import java.security.SecureRandom;
50
51import java.security.spec.AlgorithmParameterSpec;
52import java.security.spec.InvalidParameterSpecException;
53import java.security.spec.InvalidKeySpecException;
54
55import javax.crypto.BadPaddingException;
56import javax.crypto.Cipher;
57import javax.crypto.CipherSpi;
58import javax.crypto.SecretKey;
59import javax.crypto.IllegalBlockSizeException;
60import javax.crypto.NoSuchPaddingException;
61import javax.crypto.ShortBufferException;
62
63import javax.crypto.spec.SecretKeySpec;
64
65import sun.security.internal.spec.TlsRsaPremasterSecretParameterSpec;
66import sun.security.jca.JCAUtil;
67import sun.security.util.KeyUtil;
68
69/**
70 * Asymmetric Cipher wrapper class utilizing ucrypto APIs. This class
71 * currently supports
72 * - RSA/ECB/NOPADDING
73 * - RSA/ECB/PKCS1PADDING
74 *
75 * @since 9
76 */
77public class NativeRSACipher extends CipherSpi {
78    // fields set in constructor
79    private final UcryptoMech mech;
80    private final int padLen;
81    private final NativeRSAKeyFactory keyFactory;
82    private AlgorithmParameterSpec spec;
83    private SecureRandom random;
84
85    // Keep a cache of RSA keys and their RSA NativeKey for reuse.
86    // When the RSA key is gc'ed, we let NativeKey phatom references cleanup
87    // the native allocation
88    private static final Map<Key, NativeKey> keyList =
89            Collections.synchronizedMap(new WeakHashMap<Key, NativeKey>());
90
91    //
92    // fields (re)set in every init()
93    //
94    private NativeKey key = null;
95    private int outputSize = 0; // e.g. modulus size in bytes
96    private boolean encrypt = true;
97    private byte[] buffer;
98    private int bufOfs = 0;
99
100    // public implementation classes
101    public static final class NoPadding extends NativeRSACipher {
102        public NoPadding() throws NoSuchAlgorithmException {
103            super(UcryptoMech.CRYPTO_RSA_X_509, 0);
104        }
105    }
106
107    public static final class PKCS1Padding extends NativeRSACipher {
108        public PKCS1Padding() throws NoSuchAlgorithmException {
109            super(UcryptoMech.CRYPTO_RSA_PKCS, 11);
110        }
111    }
112
113    NativeRSACipher(UcryptoMech mech, int padLen)
114        throws NoSuchAlgorithmException {
115        this.mech = mech;
116        this.padLen = padLen;
117        this.keyFactory = new NativeRSAKeyFactory();
118    }
119
120    @Override
121    protected void engineSetMode(String mode) throws NoSuchAlgorithmException {
122        // Disallow change of mode for now since currently it's explicitly
123        // defined in transformation strings
124        throw new NoSuchAlgorithmException("Unsupported mode " + mode);
125    }
126
127    // see JCE spec
128    @Override
129    protected void engineSetPadding(String padding)
130            throws NoSuchPaddingException {
131        // Disallow change of padding for now since currently it's explicitly
132        // defined in transformation strings
133        throw new NoSuchPaddingException("Unsupported padding " + padding);
134    }
135
136    // see JCE spec
137    @Override
138    protected int engineGetBlockSize() {
139        return 0;
140    }
141
142    // see JCE spec
143    @Override
144    protected synchronized int engineGetOutputSize(int inputLen) {
145        return outputSize;
146    }
147
148    // see JCE spec
149    @Override
150    protected byte[] engineGetIV() {
151        return null;
152    }
153
154    // see JCE spec
155    @Override
156    protected AlgorithmParameters engineGetParameters() {
157        return null;
158    }
159
160    @Override
161    protected int engineGetKeySize(Key key) throws InvalidKeyException {
162        if (!(key instanceof RSAKey)) {
163            throw new InvalidKeyException("RSAKey required. Got: " +
164                key.getClass().getName());
165        }
166        int n = ((RSAKey)key).getModulus().bitLength();
167        // strip off the leading extra 0x00 byte prefix
168        int realByteSize = (n + 7) >> 3;
169        return realByteSize * 8;
170    }
171
172    // see JCE spec
173    @Override
174    protected synchronized void engineInit(int opmode, Key key, SecureRandom random)
175            throws InvalidKeyException {
176        try {
177            engineInit(opmode, key, (AlgorithmParameterSpec)null, random);
178        } catch (InvalidAlgorithmParameterException e) {
179            throw new InvalidKeyException("init() failed", e);
180        }
181    }
182
183    // see JCE spec
184    @Override
185    @SuppressWarnings("deprecation")
186    protected synchronized void engineInit(int opmode, Key newKey,
187            AlgorithmParameterSpec params, SecureRandom random)
188            throws InvalidKeyException, InvalidAlgorithmParameterException {
189        if (newKey == null) {
190            throw new InvalidKeyException("Key cannot be null");
191        }
192        if (opmode != Cipher.ENCRYPT_MODE &&
193            opmode != Cipher.DECRYPT_MODE &&
194            opmode != Cipher.WRAP_MODE &&
195            opmode != Cipher.UNWRAP_MODE) {
196            throw new InvalidAlgorithmParameterException
197                ("Unsupported mode: " + opmode);
198        }
199        if (params != null) {
200            if (!(params instanceof TlsRsaPremasterSecretParameterSpec)) {
201                throw new InvalidAlgorithmParameterException(
202                        "No Parameters can be specified");
203            }
204            spec = params;
205            if (random == null) {
206                random = JCAUtil.getSecureRandom();
207            }
208            this.random = random;   // for TLS RSA premaster secret
209        }
210        boolean doEncrypt = (opmode == Cipher.ENCRYPT_MODE || opmode == Cipher.WRAP_MODE);
211
212        // Make sure the proper opmode uses the proper key
213        if (doEncrypt && (!(newKey instanceof RSAPublicKey))) {
214            throw new InvalidKeyException("RSAPublicKey required for encryption." +
215                " Received: " + newKey.getClass().getName());
216        } else if (!doEncrypt && (!(newKey instanceof RSAPrivateKey))) {
217            throw new InvalidKeyException("RSAPrivateKey required for decryption." +
218                " Received: " + newKey.getClass().getName());
219        }
220
221        NativeKey nativeKey = null;
222        // Check keyList cache for a nativeKey
223        nativeKey = keyList.get(newKey);
224        if (nativeKey == null) {
225            // With no existing nativeKey for this newKey, create one
226            if (doEncrypt) {
227                RSAPublicKey publicKey = (RSAPublicKey) newKey;
228                try {
229                    nativeKey = (NativeKey) keyFactory.engineGeneratePublic
230                        (new RSAPublicKeySpec(publicKey.getModulus(), publicKey.getPublicExponent()));
231                } catch (InvalidKeySpecException ikse) {
232                    throw new InvalidKeyException(ikse);
233                }
234            } else {
235                try {
236                    if (newKey instanceof RSAPrivateCrtKey) {
237                        RSAPrivateCrtKey privateKey = (RSAPrivateCrtKey) newKey;
238                        nativeKey = (NativeKey) keyFactory.engineGeneratePrivate
239                            (new RSAPrivateCrtKeySpec(privateKey.getModulus(),
240                                                      privateKey.getPublicExponent(),
241                                                      privateKey.getPrivateExponent(),
242                                                      privateKey.getPrimeP(),
243                                                      privateKey.getPrimeQ(),
244                                                      privateKey.getPrimeExponentP(),
245                                                      privateKey.getPrimeExponentQ(),
246                                                      privateKey.getCrtCoefficient()));
247                    } else if (newKey instanceof RSAPrivateKey) {
248                        RSAPrivateKey privateKey = (RSAPrivateKey) newKey;
249                        nativeKey = (NativeKey) keyFactory.engineGeneratePrivate
250                            (new RSAPrivateKeySpec(privateKey.getModulus(),
251                                                   privateKey.getPrivateExponent()));
252                    } else {
253                        throw new InvalidKeyException("Unsupported type of RSAPrivateKey." +
254                            " Received: " + newKey.getClass().getName());
255                    }
256                } catch (InvalidKeySpecException ikse) {
257                    throw new InvalidKeyException(ikse);
258                }
259            }
260
261            // Add nativeKey to keyList cache and associate it with newKey
262            keyList.put(newKey, nativeKey);
263        }
264
265        init(doEncrypt, nativeKey);
266    }
267
268    // see JCE spec
269    @Override
270    protected synchronized void engineInit(int opmode, Key key, AlgorithmParameters params,
271            SecureRandom random)
272            throws InvalidKeyException, InvalidAlgorithmParameterException {
273        if (params != null) {
274            throw new InvalidAlgorithmParameterException("No Parameters can be specified");
275        }
276        engineInit(opmode, key, (AlgorithmParameterSpec) null, random);
277    }
278
279    // see JCE spec
280    @Override
281    protected synchronized byte[] engineUpdate(byte[] in, int inOfs, int inLen) {
282        if (inLen > 0) {
283            update(in, inOfs, inLen);
284        }
285        return null;
286    }
287
288    // see JCE spec
289    @Override
290    protected synchronized int engineUpdate(byte[] in, int inOfs, int inLen, byte[] out,
291            int outOfs) throws ShortBufferException {
292        if (out.length - outOfs < outputSize) {
293            throw new ShortBufferException("Output buffer too small. outputSize: " +
294                outputSize + ". out.length: " + out.length + ". outOfs: " + outOfs);
295        }
296        if (inLen > 0) {
297            update(in, inOfs, inLen);
298        }
299        return 0;
300    }
301
302    // see JCE spec
303    @Override
304    protected synchronized byte[] engineDoFinal(byte[] in, int inOfs, int inLen)
305            throws IllegalBlockSizeException, BadPaddingException {
306        byte[] out = new byte[outputSize];
307        try {
308            // delegate to the other engineDoFinal(...) method
309            int actualLen = engineDoFinal(in, inOfs, inLen, out, 0);
310            if (actualLen != outputSize) {
311                return Arrays.copyOf(out, actualLen);
312            } else {
313                return out;
314            }
315        } catch (ShortBufferException e) {
316            throw new UcryptoException("Internal Error", e);
317        }
318    }
319
320    // see JCE spec
321    @Override
322    protected synchronized int engineDoFinal(byte[] in, int inOfs, int inLen, byte[] out,
323                                             int outOfs)
324        throws ShortBufferException, IllegalBlockSizeException,
325               BadPaddingException {
326        if (inLen != 0) {
327            update(in, inOfs, inLen);
328        }
329        return doFinal(out, outOfs, out.length - outOfs);
330    }
331
332
333    // see JCE spec
334    @Override
335    protected synchronized byte[] engineWrap(Key key) throws IllegalBlockSizeException,
336                                                             InvalidKeyException {
337        try {
338            byte[] encodedKey = key.getEncoded();
339            if ((encodedKey == null) || (encodedKey.length == 0)) {
340                throw new InvalidKeyException("Cannot get an encoding of " +
341                                              "the key to be wrapped");
342            }
343            if (encodedKey.length > buffer.length) {
344                throw new InvalidKeyException("Key is too long for wrapping. " +
345                    "encodedKey.length: " + encodedKey.length +
346                    ". buffer.length: " + buffer.length);
347            }
348            return engineDoFinal(encodedKey, 0, encodedKey.length);
349        } catch (BadPaddingException e) {
350            // Should never happen for key wrapping
351            throw new UcryptoException("Internal Error", e);
352        }
353    }
354
355    // see JCE spec
356    @Override
357    @SuppressWarnings("deprecation")
358    protected synchronized Key engineUnwrap(byte[] wrappedKey,
359            String wrappedKeyAlgorithm, int wrappedKeyType)
360            throws InvalidKeyException, NoSuchAlgorithmException {
361
362        if (wrappedKey.length > buffer.length) {
363            throw new InvalidKeyException("Key is too long for unwrapping." +
364                " wrappedKey.length: " + wrappedKey.length +
365                ". buffer.length: " + buffer.length);
366        }
367
368        boolean isTlsRsaPremasterSecret =
369                wrappedKeyAlgorithm.equals("TlsRsaPremasterSecret");
370        Exception failover = null;
371
372        byte[] encodedKey = null;
373        try {
374            encodedKey = engineDoFinal(wrappedKey, 0, wrappedKey.length);
375        } catch (BadPaddingException bpe) {
376            if (isTlsRsaPremasterSecret) {
377                failover = bpe;
378            } else {
379                throw new InvalidKeyException("Unwrapping failed", bpe);
380            }
381        } catch (Exception e) {
382            throw new InvalidKeyException("Unwrapping failed", e);
383        }
384
385        if (isTlsRsaPremasterSecret) {
386            if (!(spec instanceof TlsRsaPremasterSecretParameterSpec)) {
387                throw new IllegalStateException(
388                        "No TlsRsaPremasterSecretParameterSpec specified");
389            }
390
391            // polish the TLS premaster secret
392            encodedKey = KeyUtil.checkTlsPreMasterSecretKey(
393                ((TlsRsaPremasterSecretParameterSpec)spec).getClientVersion(),
394                ((TlsRsaPremasterSecretParameterSpec)spec).getServerVersion(),
395                random, encodedKey, (failover != null));
396        }
397
398        return NativeCipher.constructKey(wrappedKeyType,
399                encodedKey, wrappedKeyAlgorithm);
400    }
401
402    /**
403     * calls ucrypto_encrypt(...) or ucrypto_decrypt(...)
404     * @return the length of output or an negative error status code
405     */
406    private native static int nativeAtomic(int mech, boolean encrypt,
407                                           long keyValue, int keyLength,
408                                           byte[] in, int inLen,
409                                           byte[] out, int ouOfs, int outLen);
410
411    // do actual initialization
412    private void init(boolean encrypt, NativeKey key) {
413        this.encrypt = encrypt;
414        this.key = key;
415        try {
416            this.outputSize = engineGetKeySize(key)/8;
417        } catch (InvalidKeyException ike) {
418            throw new UcryptoException("Internal Error", ike);
419        }
420        this.buffer = new byte[outputSize];
421        this.bufOfs = 0;
422    }
423
424    // store the specified input into the internal buffer
425    private void update(byte[] in, int inOfs, int inLen) {
426        if ((inLen <= 0) || (in == null)) {
427            return;
428        }
429        // buffer bytes internally until doFinal is called
430        if ((bufOfs + inLen + (encrypt? padLen:0)) > buffer.length) {
431            // lead to IllegalBlockSizeException when doFinal() is called
432            bufOfs = buffer.length + 1;
433            return;
434        }
435        System.arraycopy(in, inOfs, buffer, bufOfs, inLen);
436        bufOfs += inLen;
437    }
438
439    // return the actual non-negative output length
440    private int doFinal(byte[] out, int outOfs, int outLen)
441            throws ShortBufferException, IllegalBlockSizeException,
442            BadPaddingException {
443        if (bufOfs > buffer.length) {
444            throw new IllegalBlockSizeException(
445                "Data must not be longer than " +
446                (buffer.length - (encrypt ? padLen : 0)) + " bytes");
447        }
448        if (outLen < outputSize) {
449            throw new ShortBufferException();
450        }
451        try {
452            long keyValue = key.value();
453            int k = nativeAtomic(mech.value(), encrypt, keyValue,
454                                 key.length(), buffer, bufOfs,
455                                 out, outOfs, outLen);
456            if (k < 0) {
457                if ( k == -16 || k == -64) {
458                    // -16: CRYPTO_ENCRYPTED_DATA_INVALID
459                    // -64: CKR_ENCRYPTED_DATA_INVALID, see bug 17459266
460                    UcryptoException ue = new UcryptoException(16);
461                    BadPaddingException bpe =
462                        new BadPaddingException("Invalid encryption data");
463                    bpe.initCause(ue);
464                    throw bpe;
465                }
466                throw new UcryptoException(-k);
467            }
468
469            return k;
470        } finally {
471            bufOfs = 0;
472        }
473    }
474}
475