1 /* |
|
2 * Copyright (c) 1996, 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 |
|
26 |
|
27 package sun.security.ssl; |
|
28 |
|
29 import java.io.ByteArrayInputStream; |
|
30 import java.io.IOException; |
|
31 import java.util.Hashtable; |
|
32 import java.util.Arrays; |
|
33 |
|
34 import java.security.*; |
|
35 import javax.crypto.*; |
|
36 import javax.crypto.spec.IvParameterSpec; |
|
37 import javax.crypto.spec.GCMParameterSpec; |
|
38 |
|
39 import java.nio.*; |
|
40 |
|
41 import sun.security.ssl.CipherSuite.*; |
|
42 import static sun.security.ssl.CipherSuite.*; |
|
43 import static sun.security.ssl.CipherSuite.CipherType.*; |
|
44 |
|
45 import sun.security.util.HexDumpEncoder; |
|
46 |
|
47 |
|
48 /** |
|
49 * This class handles bulk data enciphering/deciphering for each SSLv3 |
|
50 * message. This provides data confidentiality. Stream ciphers (such |
|
51 * as RC4) don't need to do padding; block ciphers (e.g. DES) need it. |
|
52 * |
|
53 * Individual instances are obtained by calling the static method |
|
54 * newCipherBox(), which should only be invoked by BulkCipher.newCipher(). |
|
55 * |
|
56 * In RFC 2246, with bock ciphers in CBC mode, the Initialization |
|
57 * Vector (IV) for the first record is generated with the other keys |
|
58 * and secrets when the security parameters are set. The IV for |
|
59 * subsequent records is the last ciphertext block from the previous |
|
60 * record. |
|
61 * |
|
62 * In RFC 4346, the implicit Initialization Vector (IV) is replaced |
|
63 * with an explicit IV to protect against CBC attacks. RFC 4346 |
|
64 * recommends two algorithms used to generated the per-record IV. |
|
65 * The implementation uses the algorithm (2)(b), as described at |
|
66 * section 6.2.3.2 of RFC 4346. |
|
67 * |
|
68 * The usage of IV in CBC block cipher can be illustrated in |
|
69 * the following diagrams. |
|
70 * |
|
71 * (random) |
|
72 * R P1 IV C1 |
|
73 * | | | | |
|
74 * SIV---+ |-----+ |-... |----- |------ |
|
75 * | | | | | | | | |
|
76 * +----+ | +----+ | +----+ | +----+ | |
|
77 * | Ek | | + Ek + | | Dk | | | Dk | | |
|
78 * +----+ | +----+ | +----+ | +----+ | |
|
79 * | | | | | | | | |
|
80 * |----| |----| SIV--+ |----| |-... |
|
81 * | | | | |
|
82 * IV C1 R P1 |
|
83 * (discard) |
|
84 * |
|
85 * CBC Encryption CBC Decryption |
|
86 * |
|
87 * NOTE that any ciphering involved in key exchange (e.g. with RSA) is |
|
88 * handled separately. |
|
89 * |
|
90 * @author David Brownell |
|
91 * @author Andreas Sterbenz |
|
92 */ |
|
93 final class CipherBox { |
|
94 |
|
95 // A CipherBox that implements the identity operation |
|
96 static final CipherBox NULL = new CipherBox(); |
|
97 |
|
98 /* Class and subclass dynamic debugging support */ |
|
99 private static final Debug debug = Debug.getInstance("ssl"); |
|
100 |
|
101 // the protocol version this cipher conforms to |
|
102 private final ProtocolVersion protocolVersion; |
|
103 |
|
104 // cipher object |
|
105 private final Cipher cipher; |
|
106 |
|
107 /** |
|
108 * secure random |
|
109 */ |
|
110 private SecureRandom random; |
|
111 |
|
112 /** |
|
113 * fixed IV, the implicit nonce of AEAD cipher suite, only apply to |
|
114 * AEAD cipher suites |
|
115 */ |
|
116 private final byte[] fixedIv; |
|
117 |
|
118 /** |
|
119 * the key, reserved only for AEAD cipher initialization |
|
120 */ |
|
121 private final Key key; |
|
122 |
|
123 /** |
|
124 * the operation mode, reserved for AEAD cipher initialization |
|
125 */ |
|
126 private final int mode; |
|
127 |
|
128 /** |
|
129 * the authentication tag size, only apply to AEAD cipher suites |
|
130 */ |
|
131 private final int tagSize; |
|
132 |
|
133 /** |
|
134 * the record IV length, only apply to AEAD cipher suites |
|
135 */ |
|
136 private final int recordIvSize; |
|
137 |
|
138 /** |
|
139 * cipher type |
|
140 */ |
|
141 private final CipherType cipherType; |
|
142 |
|
143 /** |
|
144 * Fixed masks of various block size, as the initial decryption IVs |
|
145 * for TLS 1.1 or later. |
|
146 * |
|
147 * For performance, we do not use random IVs. As the initial decryption |
|
148 * IVs will be discarded by TLS decryption processes, so the fixed masks |
|
149 * do not hurt cryptographic strength. |
|
150 */ |
|
151 private static Hashtable<Integer, IvParameterSpec> masks; |
|
152 |
|
153 /** |
|
154 * NULL cipherbox. Identity operation, no encryption. |
|
155 */ |
|
156 private CipherBox() { |
|
157 this.protocolVersion = ProtocolVersion.DEFAULT_TLS; |
|
158 this.cipher = null; |
|
159 this.cipherType = NULL_CIPHER; |
|
160 this.fixedIv = new byte[0]; |
|
161 this.key = null; |
|
162 this.mode = Cipher.ENCRYPT_MODE; // choose at random |
|
163 this.random = null; |
|
164 this.tagSize = 0; |
|
165 this.recordIvSize = 0; |
|
166 } |
|
167 |
|
168 /** |
|
169 * Construct a new CipherBox using the cipher transformation. |
|
170 * |
|
171 * @exception NoSuchAlgorithmException if no appropriate JCE Cipher |
|
172 * implementation could be found. |
|
173 */ |
|
174 private CipherBox(ProtocolVersion protocolVersion, BulkCipher bulkCipher, |
|
175 SecretKey key, IvParameterSpec iv, SecureRandom random, |
|
176 boolean encrypt) throws NoSuchAlgorithmException { |
|
177 try { |
|
178 this.protocolVersion = protocolVersion; |
|
179 this.cipher = JsseJce.getCipher(bulkCipher.transformation); |
|
180 this.mode = encrypt ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE; |
|
181 |
|
182 if (random == null) { |
|
183 random = JsseJce.getSecureRandom(); |
|
184 } |
|
185 this.random = random; |
|
186 this.cipherType = bulkCipher.cipherType; |
|
187 |
|
188 /* |
|
189 * RFC 4346 recommends two algorithms used to generated the |
|
190 * per-record IV. The implementation uses the algorithm (2)(b), |
|
191 * as described at section 6.2.3.2 of RFC 4346. |
|
192 * |
|
193 * As we don't care about the initial IV value for TLS 1.1 or |
|
194 * later, so if the "iv" parameter is null, we use the default |
|
195 * value generated by Cipher.init() for encryption, and a fixed |
|
196 * mask for decryption. |
|
197 */ |
|
198 if (iv == null && bulkCipher.ivSize != 0 && |
|
199 mode == Cipher.DECRYPT_MODE && |
|
200 protocolVersion.useTLS11PlusSpec()) { |
|
201 iv = getFixedMask(bulkCipher.ivSize); |
|
202 } |
|
203 |
|
204 if (cipherType == AEAD_CIPHER) { |
|
205 // AEAD must completely initialize the cipher for each packet, |
|
206 // and so we save initialization parameters for packet |
|
207 // processing time. |
|
208 |
|
209 // Set the tag size for AEAD cipher |
|
210 tagSize = bulkCipher.tagSize; |
|
211 |
|
212 // Reserve the key for AEAD cipher initialization |
|
213 this.key = key; |
|
214 |
|
215 fixedIv = iv.getIV(); |
|
216 if (fixedIv == null || |
|
217 fixedIv.length != bulkCipher.fixedIvSize) { |
|
218 throw new RuntimeException("Improper fixed IV for AEAD"); |
|
219 } |
|
220 |
|
221 // Set the record IV length for AEAD cipher |
|
222 recordIvSize = bulkCipher.ivSize - bulkCipher.fixedIvSize; |
|
223 |
|
224 // DON'T initialize the cipher for AEAD! |
|
225 } else { |
|
226 // CBC only requires one initialization during its lifetime |
|
227 // (future packets/IVs set the proper CBC state), so we can |
|
228 // initialize now. |
|
229 |
|
230 // Zeroize the variables that only apply to AEAD cipher |
|
231 this.tagSize = 0; |
|
232 this.fixedIv = new byte[0]; |
|
233 this.recordIvSize = 0; |
|
234 this.key = null; |
|
235 |
|
236 // Initialize the cipher |
|
237 cipher.init(mode, key, iv, random); |
|
238 } |
|
239 } catch (NoSuchAlgorithmException e) { |
|
240 throw e; |
|
241 } catch (Exception e) { |
|
242 throw new NoSuchAlgorithmException |
|
243 ("Could not create cipher " + bulkCipher, e); |
|
244 } catch (ExceptionInInitializerError e) { |
|
245 throw new NoSuchAlgorithmException |
|
246 ("Could not create cipher " + bulkCipher, e); |
|
247 } |
|
248 } |
|
249 |
|
250 /* |
|
251 * Factory method to obtain a new CipherBox object. |
|
252 */ |
|
253 static CipherBox newCipherBox(ProtocolVersion version, BulkCipher cipher, |
|
254 SecretKey key, IvParameterSpec iv, SecureRandom random, |
|
255 boolean encrypt) throws NoSuchAlgorithmException { |
|
256 if (cipher.allowed == false) { |
|
257 throw new NoSuchAlgorithmException("Unsupported cipher " + cipher); |
|
258 } |
|
259 |
|
260 if (cipher == BulkCipher.B_NULL) { |
|
261 return NULL; |
|
262 } else { |
|
263 return new CipherBox(version, cipher, key, iv, random, encrypt); |
|
264 } |
|
265 } |
|
266 |
|
267 /* |
|
268 * Get a fixed mask, as the initial decryption IVs for TLS 1.1 or later. |
|
269 */ |
|
270 private static IvParameterSpec getFixedMask(int ivSize) { |
|
271 if (masks == null) { |
|
272 masks = new Hashtable<Integer, IvParameterSpec>(5); |
|
273 } |
|
274 |
|
275 IvParameterSpec iv = masks.get(ivSize); |
|
276 if (iv == null) { |
|
277 iv = new IvParameterSpec(new byte[ivSize]); |
|
278 masks.put(ivSize, iv); |
|
279 } |
|
280 |
|
281 return iv; |
|
282 } |
|
283 |
|
284 /* |
|
285 * Encrypts a block of data, returning the size of the |
|
286 * resulting block. |
|
287 */ |
|
288 int encrypt(byte[] buf, int offset, int len) { |
|
289 if (cipher == null) { |
|
290 return len; |
|
291 } |
|
292 |
|
293 try { |
|
294 int blockSize = cipher.getBlockSize(); |
|
295 if (cipherType == BLOCK_CIPHER) { |
|
296 len = addPadding(buf, offset, len, blockSize); |
|
297 } |
|
298 |
|
299 if (debug != null && Debug.isOn("plaintext")) { |
|
300 try { |
|
301 HexDumpEncoder hd = new HexDumpEncoder(); |
|
302 |
|
303 System.out.println( |
|
304 "Padded plaintext before ENCRYPTION: len = " |
|
305 + len); |
|
306 hd.encodeBuffer( |
|
307 new ByteArrayInputStream(buf, offset, len), |
|
308 System.out); |
|
309 } catch (IOException e) { } |
|
310 } |
|
311 |
|
312 |
|
313 if (cipherType == AEAD_CIPHER) { |
|
314 try { |
|
315 return cipher.doFinal(buf, offset, len, buf, offset); |
|
316 } catch (IllegalBlockSizeException | BadPaddingException ibe) { |
|
317 // unlikely to happen |
|
318 throw new RuntimeException( |
|
319 "Cipher error in AEAD mode in JCE provider " + |
|
320 cipher.getProvider().getName(), ibe); |
|
321 } |
|
322 } else { |
|
323 int newLen = cipher.update(buf, offset, len, buf, offset); |
|
324 if (newLen != len) { |
|
325 // catch BouncyCastle buffering error |
|
326 throw new RuntimeException("Cipher buffering error " + |
|
327 "in JCE provider " + cipher.getProvider().getName()); |
|
328 } |
|
329 return newLen; |
|
330 } |
|
331 } catch (ShortBufferException e) { |
|
332 // unlikely to happen, we should have enough buffer space here |
|
333 throw new ArrayIndexOutOfBoundsException(e.toString()); |
|
334 } |
|
335 } |
|
336 |
|
337 /* |
|
338 * Encrypts a ByteBuffer block of data, returning the size of the |
|
339 * resulting block. |
|
340 * |
|
341 * The byte buffers position and limit initially define the amount |
|
342 * to encrypt. On return, the position and limit are |
|
343 * set to last position padded/encrypted. The limit may have changed |
|
344 * because of the added padding bytes. |
|
345 */ |
|
346 int encrypt(ByteBuffer bb, int outLimit) { |
|
347 |
|
348 int len = bb.remaining(); |
|
349 |
|
350 if (cipher == null) { |
|
351 bb.position(bb.limit()); |
|
352 return len; |
|
353 } |
|
354 |
|
355 int pos = bb.position(); |
|
356 |
|
357 int blockSize = cipher.getBlockSize(); |
|
358 if (cipherType == BLOCK_CIPHER) { |
|
359 // addPadding adjusts pos/limit |
|
360 len = addPadding(bb, blockSize); |
|
361 bb.position(pos); |
|
362 } |
|
363 |
|
364 if (debug != null && Debug.isOn("plaintext")) { |
|
365 try { |
|
366 HexDumpEncoder hd = new HexDumpEncoder(); |
|
367 |
|
368 System.out.println( |
|
369 "Padded plaintext before ENCRYPTION: len = " |
|
370 + len); |
|
371 hd.encodeBuffer(bb.duplicate(), System.out); |
|
372 |
|
373 } catch (IOException e) { } |
|
374 } |
|
375 |
|
376 /* |
|
377 * Encrypt "in-place". This does not add its own padding. |
|
378 */ |
|
379 ByteBuffer dup = bb.duplicate(); |
|
380 if (cipherType == AEAD_CIPHER) { |
|
381 try { |
|
382 int outputSize = cipher.getOutputSize(dup.remaining()); |
|
383 if (outputSize > bb.remaining()) { |
|
384 // need to expand the limit of the output buffer for |
|
385 // the authentication tag. |
|
386 // |
|
387 // DON'T worry about the buffer's capacity, we have |
|
388 // reserved space for the authentication tag. |
|
389 if (outLimit < pos + outputSize) { |
|
390 // unlikely to happen |
|
391 throw new ShortBufferException( |
|
392 "need more space in output buffer"); |
|
393 } |
|
394 bb.limit(pos + outputSize); |
|
395 } |
|
396 int newLen = cipher.doFinal(dup, bb); |
|
397 if (newLen != outputSize) { |
|
398 throw new RuntimeException( |
|
399 "Cipher buffering error in JCE provider " + |
|
400 cipher.getProvider().getName()); |
|
401 } |
|
402 return newLen; |
|
403 } catch (IllegalBlockSizeException | |
|
404 BadPaddingException | ShortBufferException ibse) { |
|
405 // unlikely to happen |
|
406 throw new RuntimeException( |
|
407 "Cipher error in AEAD mode in JCE provider " + |
|
408 cipher.getProvider().getName(), ibse); |
|
409 } |
|
410 } else { |
|
411 int newLen; |
|
412 try { |
|
413 newLen = cipher.update(dup, bb); |
|
414 } catch (ShortBufferException sbe) { |
|
415 // unlikely to happen |
|
416 throw new RuntimeException("Cipher buffering error " + |
|
417 "in JCE provider " + cipher.getProvider().getName()); |
|
418 } |
|
419 |
|
420 if (bb.position() != dup.position()) { |
|
421 throw new RuntimeException("bytebuffer padding error"); |
|
422 } |
|
423 |
|
424 if (newLen != len) { |
|
425 // catch BouncyCastle buffering error |
|
426 throw new RuntimeException("Cipher buffering error " + |
|
427 "in JCE provider " + cipher.getProvider().getName()); |
|
428 } |
|
429 return newLen; |
|
430 } |
|
431 } |
|
432 |
|
433 |
|
434 /* |
|
435 * Decrypts a block of data, returning the size of the |
|
436 * resulting block if padding was required. |
|
437 * |
|
438 * For SSLv3 and TLSv1.0, with block ciphers in CBC mode the |
|
439 * Initialization Vector (IV) for the first record is generated by |
|
440 * the handshake protocol, the IV for subsequent records is the |
|
441 * last ciphertext block from the previous record. |
|
442 * |
|
443 * From TLSv1.1, the implicit IV is replaced with an explicit IV to |
|
444 * protect against CBC attacks. |
|
445 * |
|
446 * Differentiating between bad_record_mac and decryption_failed alerts |
|
447 * may permit certain attacks against CBC mode. It is preferable to |
|
448 * uniformly use the bad_record_mac alert to hide the specific type of |
|
449 * the error. |
|
450 */ |
|
451 int decrypt(byte[] buf, int offset, int len, |
|
452 int tagLen) throws BadPaddingException { |
|
453 if (cipher == null) { |
|
454 return len; |
|
455 } |
|
456 |
|
457 try { |
|
458 int newLen; |
|
459 if (cipherType == AEAD_CIPHER) { |
|
460 try { |
|
461 newLen = cipher.doFinal(buf, offset, len, buf, offset); |
|
462 } catch (IllegalBlockSizeException ibse) { |
|
463 // unlikely to happen |
|
464 throw new RuntimeException( |
|
465 "Cipher error in AEAD mode in JCE provider " + |
|
466 cipher.getProvider().getName(), ibse); |
|
467 } |
|
468 } else { |
|
469 newLen = cipher.update(buf, offset, len, buf, offset); |
|
470 if (newLen != len) { |
|
471 // catch BouncyCastle buffering error |
|
472 throw new RuntimeException("Cipher buffering error " + |
|
473 "in JCE provider " + cipher.getProvider().getName()); |
|
474 } |
|
475 } |
|
476 if (debug != null && Debug.isOn("plaintext")) { |
|
477 try { |
|
478 HexDumpEncoder hd = new HexDumpEncoder(); |
|
479 |
|
480 System.out.println( |
|
481 "Padded plaintext after DECRYPTION: len = " |
|
482 + newLen); |
|
483 hd.encodeBuffer( |
|
484 new ByteArrayInputStream(buf, offset, newLen), |
|
485 System.out); |
|
486 } catch (IOException e) { } |
|
487 } |
|
488 |
|
489 if (cipherType == BLOCK_CIPHER) { |
|
490 int blockSize = cipher.getBlockSize(); |
|
491 newLen = removePadding( |
|
492 buf, offset, newLen, tagLen, blockSize, protocolVersion); |
|
493 |
|
494 if (protocolVersion.useTLS11PlusSpec()) { |
|
495 if (newLen < blockSize) { |
|
496 throw new BadPaddingException("The length after " + |
|
497 "padding removal (" + newLen + ") should be larger " + |
|
498 "than <" + blockSize + "> since explicit IV used"); |
|
499 } |
|
500 } |
|
501 } |
|
502 return newLen; |
|
503 } catch (ShortBufferException e) { |
|
504 // unlikely to happen, we should have enough buffer space here |
|
505 throw new ArrayIndexOutOfBoundsException(e.toString()); |
|
506 } |
|
507 } |
|
508 |
|
509 /* |
|
510 * Decrypts a block of data, returning the size of the |
|
511 * resulting block if padding was required. position and limit |
|
512 * point to the end of the decrypted/depadded data. The initial |
|
513 * limit and new limit may be different, given we may |
|
514 * have stripped off some padding bytes. |
|
515 * |
|
516 * @see decrypt(byte[], int, int) |
|
517 */ |
|
518 int decrypt(ByteBuffer bb, int tagLen) throws BadPaddingException { |
|
519 |
|
520 int len = bb.remaining(); |
|
521 |
|
522 if (cipher == null) { |
|
523 bb.position(bb.limit()); |
|
524 return len; |
|
525 } |
|
526 |
|
527 try { |
|
528 /* |
|
529 * Decrypt "in-place". |
|
530 */ |
|
531 int pos = bb.position(); |
|
532 ByteBuffer dup = bb.duplicate(); |
|
533 int newLen; |
|
534 if (cipherType == AEAD_CIPHER) { |
|
535 try { |
|
536 newLen = cipher.doFinal(dup, bb); |
|
537 } catch (IllegalBlockSizeException ibse) { |
|
538 // unlikely to happen |
|
539 throw new RuntimeException( |
|
540 "Cipher error in AEAD mode \"" + ibse.getMessage() + |
|
541 " \"in JCE provider " + cipher.getProvider().getName()); |
|
542 } |
|
543 } else { |
|
544 newLen = cipher.update(dup, bb); |
|
545 if (newLen != len) { |
|
546 // catch BouncyCastle buffering error |
|
547 throw new RuntimeException("Cipher buffering error " + |
|
548 "in JCE provider " + cipher.getProvider().getName()); |
|
549 } |
|
550 } |
|
551 |
|
552 // reset the limit to the end of the decryted data |
|
553 bb.limit(pos + newLen); |
|
554 |
|
555 if (debug != null && Debug.isOn("plaintext")) { |
|
556 try { |
|
557 HexDumpEncoder hd = new HexDumpEncoder(); |
|
558 |
|
559 System.out.println( |
|
560 "Padded plaintext after DECRYPTION: len = " |
|
561 + newLen); |
|
562 |
|
563 hd.encodeBuffer( |
|
564 bb.duplicate().position(pos), System.out); |
|
565 } catch (IOException e) { } |
|
566 } |
|
567 |
|
568 /* |
|
569 * Remove the block padding. |
|
570 */ |
|
571 if (cipherType == BLOCK_CIPHER) { |
|
572 int blockSize = cipher.getBlockSize(); |
|
573 bb.position(pos); |
|
574 newLen = removePadding(bb, tagLen, blockSize, protocolVersion); |
|
575 |
|
576 // check the explicit IV of TLS v1.1 or later |
|
577 if (protocolVersion.useTLS11PlusSpec()) { |
|
578 if (newLen < blockSize) { |
|
579 throw new BadPaddingException("The length after " + |
|
580 "padding removal (" + newLen + ") should be larger " + |
|
581 "than <" + blockSize + "> since explicit IV used"); |
|
582 } |
|
583 |
|
584 // reset the position to the end of the decrypted data |
|
585 bb.position(bb.limit()); |
|
586 } |
|
587 } |
|
588 return newLen; |
|
589 } catch (ShortBufferException e) { |
|
590 // unlikely to happen, we should have enough buffer space here |
|
591 throw new ArrayIndexOutOfBoundsException(e.toString()); |
|
592 } |
|
593 } |
|
594 |
|
595 private static int addPadding(byte[] buf, int offset, int len, |
|
596 int blockSize) { |
|
597 int newlen = len + 1; |
|
598 byte pad; |
|
599 int i; |
|
600 |
|
601 if ((newlen % blockSize) != 0) { |
|
602 newlen += blockSize - 1; |
|
603 newlen -= newlen % blockSize; |
|
604 } |
|
605 pad = (byte) (newlen - len); |
|
606 |
|
607 if (buf.length < (newlen + offset)) { |
|
608 throw new IllegalArgumentException("no space to pad buffer"); |
|
609 } |
|
610 |
|
611 /* |
|
612 * TLS version of the padding works for both SSLv3 and TLSv1 |
|
613 */ |
|
614 for (i = 0, offset += len; i < pad; i++) { |
|
615 buf [offset++] = (byte) (pad - 1); |
|
616 } |
|
617 return newlen; |
|
618 } |
|
619 |
|
620 /* |
|
621 * Apply the padding to the buffer. |
|
622 * |
|
623 * Limit is advanced to the new buffer length. |
|
624 * Position is equal to limit. |
|
625 */ |
|
626 private static int addPadding(ByteBuffer bb, int blockSize) { |
|
627 |
|
628 int len = bb.remaining(); |
|
629 int offset = bb.position(); |
|
630 |
|
631 int newlen = len + 1; |
|
632 byte pad; |
|
633 int i; |
|
634 |
|
635 if ((newlen % blockSize) != 0) { |
|
636 newlen += blockSize - 1; |
|
637 newlen -= newlen % blockSize; |
|
638 } |
|
639 pad = (byte) (newlen - len); |
|
640 |
|
641 /* |
|
642 * Update the limit to what will be padded. |
|
643 */ |
|
644 bb.limit(newlen + offset); |
|
645 |
|
646 /* |
|
647 * TLS version of the padding works for both SSLv3 and TLSv1 |
|
648 */ |
|
649 for (i = 0, offset += len; i < pad; i++) { |
|
650 bb.put(offset++, (byte) (pad - 1)); |
|
651 } |
|
652 |
|
653 bb.position(offset); |
|
654 bb.limit(offset); |
|
655 |
|
656 return newlen; |
|
657 } |
|
658 |
|
659 /* |
|
660 * A constant-time check of the padding. |
|
661 * |
|
662 * NOTE that we are checking both the padding and the padLen bytes here. |
|
663 * |
|
664 * The caller MUST ensure that the len parameter is a positive number. |
|
665 */ |
|
666 private static int[] checkPadding( |
|
667 byte[] buf, int offset, int len, byte pad) { |
|
668 |
|
669 if (len <= 0) { |
|
670 throw new RuntimeException("padding len must be positive"); |
|
671 } |
|
672 |
|
673 // An array of hits is used to prevent Hotspot optimization for |
|
674 // the purpose of a constant-time check. |
|
675 int[] results = {0, 0}; // {missed #, matched #} |
|
676 for (int i = 0; i <= 256;) { |
|
677 for (int j = 0; j < len && i <= 256; j++, i++) { // j <= i |
|
678 if (buf[offset + j] != pad) { |
|
679 results[0]++; // mismatched padding data |
|
680 } else { |
|
681 results[1]++; // matched padding data |
|
682 } |
|
683 } |
|
684 } |
|
685 |
|
686 return results; |
|
687 } |
|
688 |
|
689 /* |
|
690 * A constant-time check of the padding. |
|
691 * |
|
692 * NOTE that we are checking both the padding and the padLen bytes here. |
|
693 * |
|
694 * The caller MUST ensure that the bb parameter has remaining. |
|
695 */ |
|
696 private static int[] checkPadding(ByteBuffer bb, byte pad) { |
|
697 |
|
698 if (!bb.hasRemaining()) { |
|
699 throw new RuntimeException("hasRemaining() must be positive"); |
|
700 } |
|
701 |
|
702 // An array of hits is used to prevent Hotspot optimization for |
|
703 // the purpose of a constant-time check. |
|
704 int[] results = {0, 0}; // {missed #, matched #} |
|
705 bb.mark(); |
|
706 for (int i = 0; i <= 256; bb.reset()) { |
|
707 for (; bb.hasRemaining() && i <= 256; i++) { |
|
708 if (bb.get() != pad) { |
|
709 results[0]++; // mismatched padding data |
|
710 } else { |
|
711 results[1]++; // matched padding data |
|
712 } |
|
713 } |
|
714 } |
|
715 |
|
716 return results; |
|
717 } |
|
718 |
|
719 /* |
|
720 * Typical TLS padding format for a 64 bit block cipher is as follows: |
|
721 * xx xx xx xx xx xx xx 00 |
|
722 * xx xx xx xx xx xx 01 01 |
|
723 * ... |
|
724 * xx 06 06 06 06 06 06 06 |
|
725 * 07 07 07 07 07 07 07 07 |
|
726 * TLS also allows any amount of padding from 1 and 256 bytes as long |
|
727 * as it makes the data a multiple of the block size |
|
728 */ |
|
729 private static int removePadding(byte[] buf, int offset, int len, |
|
730 int tagLen, int blockSize, |
|
731 ProtocolVersion protocolVersion) throws BadPaddingException { |
|
732 |
|
733 // last byte is length byte (i.e. actual padding length - 1) |
|
734 int padOffset = offset + len - 1; |
|
735 int padLen = buf[padOffset] & 0xFF; |
|
736 |
|
737 int newLen = len - (padLen + 1); |
|
738 if ((newLen - tagLen) < 0) { |
|
739 // If the buffer is not long enough to contain the padding plus |
|
740 // a MAC tag, do a dummy constant-time padding check. |
|
741 // |
|
742 // Note that it is a dummy check, so we won't care about what is |
|
743 // the actual padding data. |
|
744 checkPadding(buf, offset, len, (byte)(padLen & 0xFF)); |
|
745 |
|
746 throw new BadPaddingException("Invalid Padding length: " + padLen); |
|
747 } |
|
748 |
|
749 // The padding data should be filled with the padding length value. |
|
750 int[] results = checkPadding(buf, offset + newLen, |
|
751 padLen + 1, (byte)(padLen & 0xFF)); |
|
752 if (protocolVersion.useTLS10PlusSpec()) { |
|
753 if (results[0] != 0) { // padding data has invalid bytes |
|
754 throw new BadPaddingException("Invalid TLS padding data"); |
|
755 } |
|
756 } else { // SSLv3 |
|
757 // SSLv3 requires 0 <= length byte < block size |
|
758 // some implementations do 1 <= length byte <= block size, |
|
759 // so accept that as well |
|
760 // v3 does not require any particular value for the other bytes |
|
761 if (padLen > blockSize) { |
|
762 throw new BadPaddingException("Padding length (" + |
|
763 padLen + ") of SSLv3 message should not be bigger " + |
|
764 "than the block size (" + blockSize + ")"); |
|
765 } |
|
766 } |
|
767 return newLen; |
|
768 } |
|
769 |
|
770 /* |
|
771 * Position/limit is equal the removed padding. |
|
772 */ |
|
773 private static int removePadding(ByteBuffer bb, |
|
774 int tagLen, int blockSize, |
|
775 ProtocolVersion protocolVersion) throws BadPaddingException { |
|
776 |
|
777 int len = bb.remaining(); |
|
778 int offset = bb.position(); |
|
779 |
|
780 // last byte is length byte (i.e. actual padding length - 1) |
|
781 int padOffset = offset + len - 1; |
|
782 int padLen = bb.get(padOffset) & 0xFF; |
|
783 |
|
784 int newLen = len - (padLen + 1); |
|
785 if ((newLen - tagLen) < 0) { |
|
786 // If the buffer is not long enough to contain the padding plus |
|
787 // a MAC tag, do a dummy constant-time padding check. |
|
788 // |
|
789 // Note that it is a dummy check, so we won't care about what is |
|
790 // the actual padding data. |
|
791 checkPadding(bb.duplicate(), (byte)(padLen & 0xFF)); |
|
792 |
|
793 throw new BadPaddingException("Invalid Padding length: " + padLen); |
|
794 } |
|
795 |
|
796 // The padding data should be filled with the padding length value. |
|
797 int[] results = checkPadding( |
|
798 bb.duplicate().position(offset + newLen), |
|
799 (byte)(padLen & 0xFF)); |
|
800 if (protocolVersion.useTLS10PlusSpec()) { |
|
801 if (results[0] != 0) { // padding data has invalid bytes |
|
802 throw new BadPaddingException("Invalid TLS padding data"); |
|
803 } |
|
804 } else { // SSLv3 |
|
805 // SSLv3 requires 0 <= length byte < block size |
|
806 // some implementations do 1 <= length byte <= block size, |
|
807 // so accept that as well |
|
808 // v3 does not require any particular value for the other bytes |
|
809 if (padLen > blockSize) { |
|
810 throw new BadPaddingException("Padding length (" + |
|
811 padLen + ") of SSLv3 message should not be bigger " + |
|
812 "than the block size (" + blockSize + ")"); |
|
813 } |
|
814 } |
|
815 |
|
816 /* |
|
817 * Reset buffer limit to remove padding. |
|
818 */ |
|
819 bb.position(offset + newLen); |
|
820 bb.limit(offset + newLen); |
|
821 |
|
822 return newLen; |
|
823 } |
|
824 |
|
825 /* |
|
826 * Dispose of any intermediate state in the underlying cipher. |
|
827 * For PKCS11 ciphers, this will release any attached sessions, and |
|
828 * thus make finalization faster. |
|
829 */ |
|
830 void dispose() { |
|
831 try { |
|
832 if (cipher != null) { |
|
833 // ignore return value. |
|
834 cipher.doFinal(); |
|
835 } |
|
836 } catch (Exception e) { |
|
837 // swallow all types of exceptions. |
|
838 } |
|
839 } |
|
840 |
|
841 /* |
|
842 * Does the cipher use CBC mode? |
|
843 * |
|
844 * @return true if the cipher use CBC mode, false otherwise. |
|
845 */ |
|
846 boolean isCBCMode() { |
|
847 return cipherType == BLOCK_CIPHER; |
|
848 } |
|
849 |
|
850 /* |
|
851 * Does the cipher use AEAD mode? |
|
852 * |
|
853 * @return true if the cipher use AEAD mode, false otherwise. |
|
854 */ |
|
855 boolean isAEADMode() { |
|
856 return cipherType == AEAD_CIPHER; |
|
857 } |
|
858 |
|
859 /* |
|
860 * Is the cipher null? |
|
861 * |
|
862 * @return true if the cipher is null, false otherwise. |
|
863 */ |
|
864 boolean isNullCipher() { |
|
865 return cipher == null; |
|
866 } |
|
867 |
|
868 /* |
|
869 * Gets the explicit nonce/IV size of the cipher. |
|
870 * |
|
871 * The returned value is the SecurityParameters.record_iv_length in |
|
872 * RFC 4346/5246. It is the size of explicit IV for CBC mode, and the |
|
873 * size of explicit nonce for AEAD mode. |
|
874 * |
|
875 * @return the explicit nonce size of the cipher. |
|
876 */ |
|
877 int getExplicitNonceSize() { |
|
878 switch (cipherType) { |
|
879 case BLOCK_CIPHER: |
|
880 // For block ciphers, the explicit IV length is of length |
|
881 // SecurityParameters.record_iv_length, which is equal to |
|
882 // the SecurityParameters.block_size. |
|
883 if (protocolVersion.useTLS11PlusSpec()) { |
|
884 return cipher.getBlockSize(); |
|
885 } |
|
886 break; |
|
887 case AEAD_CIPHER: |
|
888 return recordIvSize; |
|
889 // It is also the length of sequence number, which is |
|
890 // used as the nonce_explicit for AEAD cipher suites. |
|
891 } |
|
892 |
|
893 return 0; |
|
894 } |
|
895 |
|
896 /* |
|
897 * Applies the explicit nonce/IV to this cipher. This method is used to |
|
898 * decrypt an SSL/TLS input record. |
|
899 * |
|
900 * The returned value is the SecurityParameters.record_iv_length in |
|
901 * RFC 4346/5246. It is the size of explicit IV for CBC mode, and the |
|
902 * size of explicit nonce for AEAD mode. |
|
903 * |
|
904 * @param authenticator the authenticator to get the additional |
|
905 * authentication data |
|
906 * @param contentType the content type of the input record |
|
907 * @param bb the byte buffer to get the explicit nonce from |
|
908 * |
|
909 * @return the explicit nonce size of the cipher. |
|
910 */ |
|
911 int applyExplicitNonce(Authenticator authenticator, byte contentType, |
|
912 ByteBuffer bb, byte[] sequence) throws BadPaddingException { |
|
913 switch (cipherType) { |
|
914 case BLOCK_CIPHER: |
|
915 // sanity check length of the ciphertext |
|
916 int tagLen = (authenticator instanceof MAC) ? |
|
917 ((MAC)authenticator).MAClen() : 0; |
|
918 if (tagLen != 0) { |
|
919 if (!sanityCheck(tagLen, bb.remaining())) { |
|
920 throw new BadPaddingException( |
|
921 "ciphertext sanity check failed"); |
|
922 } |
|
923 } |
|
924 |
|
925 // For block ciphers, the explicit IV length is of length |
|
926 // SecurityParameters.record_iv_length, which is equal to |
|
927 // the SecurityParameters.block_size. |
|
928 if (protocolVersion.useTLS11PlusSpec()) { |
|
929 return cipher.getBlockSize(); |
|
930 } |
|
931 break; |
|
932 case AEAD_CIPHER: |
|
933 if (bb.remaining() < (recordIvSize + tagSize)) { |
|
934 throw new BadPaddingException( |
|
935 "Insufficient buffer remaining for AEAD cipher " + |
|
936 "fragment (" + bb.remaining() + "). Needs to be " + |
|
937 "more than or equal to IV size (" + recordIvSize + |
|
938 ") + tag size (" + tagSize + ")"); |
|
939 } |
|
940 |
|
941 // initialize the AEAD cipher for the unique IV |
|
942 byte[] iv = Arrays.copyOf(fixedIv, |
|
943 fixedIv.length + recordIvSize); |
|
944 bb.get(iv, fixedIv.length, recordIvSize); |
|
945 bb.position(bb.position() - recordIvSize); |
|
946 GCMParameterSpec spec = new GCMParameterSpec(tagSize * 8, iv); |
|
947 try { |
|
948 cipher.init(mode, key, spec, random); |
|
949 } catch (InvalidKeyException | |
|
950 InvalidAlgorithmParameterException ikae) { |
|
951 // unlikely to happen |
|
952 throw new RuntimeException( |
|
953 "invalid key or spec in GCM mode", ikae); |
|
954 } |
|
955 |
|
956 // update the additional authentication data |
|
957 byte[] aad = authenticator.acquireAuthenticationBytes( |
|
958 contentType, bb.remaining() - recordIvSize - tagSize, |
|
959 sequence); |
|
960 cipher.updateAAD(aad); |
|
961 |
|
962 return recordIvSize; |
|
963 // It is also the length of sequence number, which is |
|
964 // used as the nonce_explicit for AEAD cipher suites. |
|
965 } |
|
966 |
|
967 return 0; |
|
968 } |
|
969 |
|
970 /* |
|
971 * Creates the explicit nonce/IV to this cipher. This method is used to |
|
972 * encrypt an SSL/TLS output record. |
|
973 * |
|
974 * The size of the returned array is the SecurityParameters.record_iv_length |
|
975 * in RFC 4346/5246. It is the size of explicit IV for CBC mode, and the |
|
976 * size of explicit nonce for AEAD mode. |
|
977 * |
|
978 * @param authenticator the authenticator to get the additional |
|
979 * authentication data |
|
980 * @param contentType the content type of the input record |
|
981 * @param fragmentLength the fragment length of the output record, it is |
|
982 * the TLSCompressed.length in RFC 4346/5246. |
|
983 * |
|
984 * @return the explicit nonce of the cipher. |
|
985 */ |
|
986 byte[] createExplicitNonce(Authenticator authenticator, |
|
987 byte contentType, int fragmentLength) { |
|
988 |
|
989 byte[] nonce = new byte[0]; |
|
990 switch (cipherType) { |
|
991 case BLOCK_CIPHER: |
|
992 if (protocolVersion.useTLS11PlusSpec()) { |
|
993 // For block ciphers, the explicit IV length is of length |
|
994 // SecurityParameters.record_iv_length, which is equal to |
|
995 // the SecurityParameters.block_size. |
|
996 // |
|
997 // Generate a random number as the explicit IV parameter. |
|
998 nonce = new byte[cipher.getBlockSize()]; |
|
999 random.nextBytes(nonce); |
|
1000 } |
|
1001 break; |
|
1002 case AEAD_CIPHER: |
|
1003 // To be unique and aware of overflow-wrap, sequence number |
|
1004 // is used as the nonce_explicit of AEAD cipher suites. |
|
1005 nonce = authenticator.sequenceNumber(); |
|
1006 |
|
1007 // initialize the AEAD cipher for the unique IV |
|
1008 byte[] iv = Arrays.copyOf(fixedIv, |
|
1009 fixedIv.length + nonce.length); |
|
1010 System.arraycopy(nonce, 0, iv, fixedIv.length, nonce.length); |
|
1011 GCMParameterSpec spec = new GCMParameterSpec(tagSize * 8, iv); |
|
1012 try { |
|
1013 cipher.init(mode, key, spec, random); |
|
1014 } catch (InvalidKeyException | |
|
1015 InvalidAlgorithmParameterException ikae) { |
|
1016 // unlikely to happen |
|
1017 throw new RuntimeException( |
|
1018 "invalid key or spec in GCM mode", ikae); |
|
1019 } |
|
1020 |
|
1021 // Update the additional authentication data, using the |
|
1022 // implicit sequence number of the authenticator. |
|
1023 byte[] aad = authenticator.acquireAuthenticationBytes( |
|
1024 contentType, fragmentLength, null); |
|
1025 cipher.updateAAD(aad); |
|
1026 break; |
|
1027 } |
|
1028 |
|
1029 return nonce; |
|
1030 } |
|
1031 |
|
1032 // See also CipherSuite.calculatePacketSize(). |
|
1033 int calculatePacketSize(int fragmentSize, int macLen, int headerSize) { |
|
1034 int packetSize = fragmentSize; |
|
1035 if (cipher != null) { |
|
1036 int blockSize = cipher.getBlockSize(); |
|
1037 switch (cipherType) { |
|
1038 case BLOCK_CIPHER: |
|
1039 packetSize += macLen; |
|
1040 packetSize += 1; // 1 byte padding length field |
|
1041 packetSize += // use the minimal padding |
|
1042 (blockSize - (packetSize % blockSize)) % blockSize; |
|
1043 if (protocolVersion.useTLS11PlusSpec()) { |
|
1044 packetSize += blockSize; // explicit IV |
|
1045 } |
|
1046 |
|
1047 break; |
|
1048 case AEAD_CIPHER: |
|
1049 packetSize += recordIvSize; |
|
1050 packetSize += tagSize; |
|
1051 |
|
1052 break; |
|
1053 default: // NULL_CIPHER or STREAM_CIPHER |
|
1054 packetSize += macLen; |
|
1055 } |
|
1056 } |
|
1057 |
|
1058 return packetSize + headerSize; |
|
1059 } |
|
1060 |
|
1061 // See also CipherSuite.calculateFragSize(). |
|
1062 int calculateFragmentSize(int packetLimit, int macLen, int headerSize) { |
|
1063 int fragLen = packetLimit - headerSize; |
|
1064 if (cipher != null) { |
|
1065 int blockSize = cipher.getBlockSize(); |
|
1066 switch (cipherType) { |
|
1067 case BLOCK_CIPHER: |
|
1068 if (protocolVersion.useTLS11PlusSpec()) { |
|
1069 fragLen -= blockSize; // explicit IV |
|
1070 } |
|
1071 fragLen -= (fragLen % blockSize); // cannot hold a block |
|
1072 // No padding for a maximum fragment. |
|
1073 fragLen -= 1; // 1 byte padding length field: 0x00 |
|
1074 fragLen -= macLen; |
|
1075 |
|
1076 break; |
|
1077 case AEAD_CIPHER: |
|
1078 fragLen -= recordIvSize; |
|
1079 fragLen -= tagSize; |
|
1080 |
|
1081 break; |
|
1082 default: // NULL_CIPHER or STREAM_CIPHER |
|
1083 fragLen -= macLen; |
|
1084 } |
|
1085 } |
|
1086 |
|
1087 return fragLen; |
|
1088 } |
|
1089 |
|
1090 // Estimate the maximum fragment size of a received packet. |
|
1091 int estimateFragmentSize(int packetSize, int macLen, int headerSize) { |
|
1092 int fragLen = packetSize - headerSize; |
|
1093 if (cipher != null) { |
|
1094 int blockSize = cipher.getBlockSize(); |
|
1095 switch (cipherType) { |
|
1096 case BLOCK_CIPHER: |
|
1097 if (protocolVersion.useTLS11PlusSpec()) { |
|
1098 fragLen -= blockSize; // explicit IV |
|
1099 } |
|
1100 // No padding for a maximum fragment. |
|
1101 fragLen -= 1; // 1 byte padding length field: 0x00 |
|
1102 fragLen -= macLen; |
|
1103 |
|
1104 break; |
|
1105 case AEAD_CIPHER: |
|
1106 fragLen -= recordIvSize; |
|
1107 fragLen -= tagSize; |
|
1108 |
|
1109 break; |
|
1110 default: // NULL_CIPHER or STREAM_CIPHER |
|
1111 fragLen -= macLen; |
|
1112 } |
|
1113 } |
|
1114 |
|
1115 return fragLen; |
|
1116 } |
|
1117 |
|
1118 /** |
|
1119 * Sanity check the length of a fragment before decryption. |
|
1120 * |
|
1121 * In CBC mode, check that the fragment length is one or multiple times |
|
1122 * of the block size of the cipher suite, and is at least one (one is the |
|
1123 * smallest size of padding in CBC mode) bigger than the tag size of the |
|
1124 * MAC algorithm except the explicit IV size for TLS 1.1 or later. |
|
1125 * |
|
1126 * In non-CBC mode, check that the fragment length is not less than the |
|
1127 * tag size of the MAC algorithm. |
|
1128 * |
|
1129 * @return true if the length of a fragment matches above requirements |
|
1130 */ |
|
1131 private boolean sanityCheck(int tagLen, int fragmentLen) { |
|
1132 if (!isCBCMode()) { |
|
1133 return fragmentLen >= tagLen; |
|
1134 } |
|
1135 |
|
1136 int blockSize = cipher.getBlockSize(); |
|
1137 if ((fragmentLen % blockSize) == 0) { |
|
1138 int minimal = tagLen + 1; |
|
1139 minimal = (minimal >= blockSize) ? minimal : blockSize; |
|
1140 if (protocolVersion.useTLS11PlusSpec()) { |
|
1141 minimal += blockSize; // plus the size of the explicit IV |
|
1142 } |
|
1143 |
|
1144 return (fragmentLen >= minimal); |
|
1145 } |
|
1146 |
|
1147 return false; |
|
1148 } |
|
1149 |
|
1150 } |
|