author | xuelei |
Fri, 01 Mar 2013 02:34:34 -0800 | |
changeset 16045 | 9d08c3b9a6a0 |
parent 14664 | e71aa0962e70 |
child 16067 | 36055e4b5305 |
permissions | -rw-r--r-- |
2 | 1 |
/* |
16045 | 2 |
* Copyright (c) 1996, 2012, Oracle and/or its affiliates. All rights reserved. |
2 | 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 |
|
5506 | 7 |
* published by the Free Software Foundation. Oracle designates this |
2 | 8 |
* particular file as subject to the "Classpath" exception as provided |
5506 | 9 |
* by Oracle in the LICENSE file that accompanied this code. |
2 | 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 |
* |
|
5506 | 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. |
|
2 | 24 |
*/ |
25 |
||
26 |
||
27 |
package sun.security.ssl; |
|
28 |
||
29 |
import java.io.ByteArrayInputStream; |
|
30 |
import java.io.IOException; |
|
7039 | 31 |
import java.util.Hashtable; |
16045 | 32 |
import java.util.Arrays; |
2 | 33 |
|
34 |
import java.security.*; |
|
35 |
import javax.crypto.*; |
|
36 |
import javax.crypto.spec.IvParameterSpec; |
|
16045 | 37 |
import javax.crypto.spec.GCMParameterSpec; |
2 | 38 |
|
39 |
import java.nio.*; |
|
40 |
||
41 |
import sun.security.ssl.CipherSuite.*; |
|
42 |
import static sun.security.ssl.CipherSuite.*; |
|
16045 | 43 |
import static sun.security.ssl.CipherSuite.CipherType.*; |
2 | 44 |
|
45 |
import sun.misc.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 |
* |
|
7039 | 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 |
* |
|
2 | 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 |
final static 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 |
/** |
|
7039 | 108 |
* secure random |
109 |
*/ |
|
110 |
private SecureRandom random; |
|
111 |
||
112 |
/** |
|
16045 | 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 |
|
10915 | 125 |
*/ |
16045 | 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; |
|
10915 | 142 |
|
143 |
/** |
|
7039 | 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 |
/** |
|
2 | 154 |
* NULL cipherbox. Identity operation, no encryption. |
155 |
*/ |
|
156 |
private CipherBox() { |
|
157 |
this.protocolVersion = ProtocolVersion.DEFAULT; |
|
158 |
this.cipher = null; |
|
16045 | 159 |
this.cipherType = STREAM_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; |
|
2 | 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, |
|
7039 | 175 |
SecretKey key, IvParameterSpec iv, SecureRandom random, |
176 |
boolean encrypt) throws NoSuchAlgorithmException { |
|
2 | 177 |
try { |
178 |
this.protocolVersion = protocolVersion; |
|
179 |
this.cipher = JsseJce.getCipher(bulkCipher.transformation); |
|
16045 | 180 |
this.mode = encrypt ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE; |
7039 | 181 |
|
182 |
if (random == null) { |
|
183 |
random = JsseJce.getSecureRandom(); |
|
184 |
} |
|
185 |
this.random = random; |
|
16045 | 186 |
this.cipherType = bulkCipher.cipherType; |
7039 | 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.v >= ProtocolVersion.TLS11.v) { |
|
201 |
iv = getFixedMask(bulkCipher.ivSize); |
|
202 |
} |
|
203 |
||
16045 | 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 |
} |
|
7039 | 220 |
|
16045 | 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); |
|
2 | 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, |
|
7039 | 254 |
SecretKey key, IvParameterSpec iv, SecureRandom random, |
255 |
boolean encrypt) throws NoSuchAlgorithmException { |
|
2 | 256 |
if (cipher.allowed == false) { |
257 |
throw new NoSuchAlgorithmException("Unsupported cipher " + cipher); |
|
258 |
} |
|
7039 | 259 |
|
2 | 260 |
if (cipher == B_NULL) { |
261 |
return NULL; |
|
262 |
} else { |
|
7039 | 263 |
return new CipherBox(version, cipher, key, iv, random, encrypt); |
2 | 264 |
} |
265 |
} |
|
266 |
||
267 |
/* |
|
7039 | 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 |
/* |
|
2 | 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 |
} |
|
7039 | 292 |
|
2 | 293 |
try { |
16045 | 294 |
int blockSize = cipher.getBlockSize(); |
295 |
if (cipherType == BLOCK_CIPHER) { |
|
2 | 296 |
len = addPadding(buf, offset, len, blockSize); |
297 |
} |
|
16045 | 298 |
|
2 | 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 |
} |
|
16045 | 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; |
|
2 | 330 |
} |
331 |
} catch (ShortBufferException e) { |
|
16045 | 332 |
// unlikely to happen, we should have enough buffer space here |
2 | 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 |
*/ |
|
16045 | 346 |
int encrypt(ByteBuffer bb, int outLimit) { |
2 | 347 |
|
348 |
int len = bb.remaining(); |
|
349 |
||
350 |
if (cipher == null) { |
|
351 |
bb.position(bb.limit()); |
|
352 |
return len; |
|
353 |
} |
|
354 |
||
16045 | 355 |
int pos = bb.position(); |
2 | 356 |
|
16045 | 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 |
} |
|
7039 | 363 |
|
16045 | 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 |
} |
|
7039 | 375 |
|
16045 | 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); |
|
7039 | 395 |
} |
16045 | 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); |
|
2 | 409 |
} |
16045 | 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()); |
|
2 | 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. |
|
7039 | 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. |
|
2 | 450 |
*/ |
451 |
int decrypt(byte[] buf, int offset, int len) throws BadPaddingException { |
|
452 |
if (cipher == null) { |
|
453 |
return len; |
|
454 |
} |
|
7039 | 455 |
|
2 | 456 |
try { |
16045 | 457 |
int newLen; |
458 |
if (cipherType == AEAD_CIPHER) { |
|
459 |
try { |
|
460 |
newLen = cipher.doFinal(buf, offset, len, buf, offset); |
|
461 |
} catch (IllegalBlockSizeException ibse) { |
|
462 |
// unlikely to happen |
|
463 |
throw new RuntimeException( |
|
464 |
"Cipher error in AEAD mode in JCE provider " + |
|
465 |
cipher.getProvider().getName(), ibse); |
|
466 |
} |
|
467 |
} else { |
|
468 |
newLen = cipher.update(buf, offset, len, buf, offset); |
|
469 |
if (newLen != len) { |
|
470 |
// catch BouncyCastle buffering error |
|
471 |
throw new RuntimeException("Cipher buffering error " + |
|
472 |
"in JCE provider " + cipher.getProvider().getName()); |
|
473 |
} |
|
2 | 474 |
} |
475 |
if (debug != null && Debug.isOn("plaintext")) { |
|
476 |
try { |
|
477 |
HexDumpEncoder hd = new HexDumpEncoder(); |
|
478 |
||
479 |
System.out.println( |
|
480 |
"Padded plaintext after DECRYPTION: len = " |
|
481 |
+ newLen); |
|
482 |
hd.encodeBuffer( |
|
483 |
new ByteArrayInputStream(buf, offset, newLen), |
|
484 |
System.out); |
|
485 |
} catch (IOException e) { } |
|
486 |
} |
|
16045 | 487 |
|
488 |
if (cipherType == BLOCK_CIPHER) { |
|
489 |
int blockSize = cipher.getBlockSize(); |
|
2 | 490 |
newLen = removePadding(buf, offset, newLen, |
491 |
blockSize, protocolVersion); |
|
7039 | 492 |
|
493 |
if (protocolVersion.v >= ProtocolVersion.TLS11.v) { |
|
494 |
if (newLen < blockSize) { |
|
495 |
throw new BadPaddingException("invalid explicit IV"); |
|
496 |
} |
|
497 |
} |
|
2 | 498 |
} |
499 |
return newLen; |
|
500 |
} catch (ShortBufferException e) { |
|
16045 | 501 |
// unlikely to happen, we should have enough buffer space here |
2 | 502 |
throw new ArrayIndexOutOfBoundsException(e.toString()); |
503 |
} |
|
504 |
} |
|
505 |
||
506 |
||
507 |
/* |
|
508 |
* Decrypts a block of data, returning the size of the |
|
509 |
* resulting block if padding was required. position and limit |
|
510 |
* point to the end of the decrypted/depadded data. The initial |
|
511 |
* limit and new limit may be different, given we may |
|
512 |
* have stripped off some padding bytes. |
|
7039 | 513 |
* |
514 |
* @see decrypt(byte[], int, int) |
|
2 | 515 |
*/ |
516 |
int decrypt(ByteBuffer bb) throws BadPaddingException { |
|
517 |
||
518 |
int len = bb.remaining(); |
|
519 |
||
520 |
if (cipher == null) { |
|
521 |
bb.position(bb.limit()); |
|
522 |
return len; |
|
523 |
} |
|
524 |
||
525 |
try { |
|
526 |
/* |
|
527 |
* Decrypt "in-place". |
|
528 |
*/ |
|
529 |
int pos = bb.position(); |
|
530 |
ByteBuffer dup = bb.duplicate(); |
|
16045 | 531 |
int newLen; |
532 |
if (cipherType == AEAD_CIPHER) { |
|
533 |
try { |
|
534 |
newLen = cipher.doFinal(dup, bb); |
|
535 |
} catch (IllegalBlockSizeException ibse) { |
|
536 |
// unlikely to happen |
|
537 |
throw new RuntimeException( |
|
538 |
"Cipher error in AEAD mode \"" + ibse.getMessage() + |
|
539 |
" \"in JCE provider " + cipher.getProvider().getName()); |
|
540 |
} |
|
541 |
} else { |
|
542 |
newLen = cipher.update(dup, bb); |
|
543 |
if (newLen != len) { |
|
544 |
// catch BouncyCastle buffering error |
|
545 |
throw new RuntimeException("Cipher buffering error " + |
|
546 |
"in JCE provider " + cipher.getProvider().getName()); |
|
547 |
} |
|
2 | 548 |
} |
549 |
||
16045 | 550 |
// reset the limit to the end of the decryted data |
551 |
bb.limit(pos + newLen); |
|
552 |
||
2 | 553 |
if (debug != null && Debug.isOn("plaintext")) { |
554 |
try { |
|
555 |
HexDumpEncoder hd = new HexDumpEncoder(); |
|
556 |
||
557 |
System.out.println( |
|
558 |
"Padded plaintext after DECRYPTION: len = " |
|
559 |
+ newLen); |
|
560 |
||
16045 | 561 |
hd.encodeBuffer( |
562 |
(ByteBuffer)bb.duplicate().position(pos), System.out); |
|
2 | 563 |
} catch (IOException e) { } |
564 |
} |
|
565 |
||
566 |
/* |
|
567 |
* Remove the block padding. |
|
568 |
*/ |
|
16045 | 569 |
if (cipherType == BLOCK_CIPHER) { |
570 |
int blockSize = cipher.getBlockSize(); |
|
2 | 571 |
bb.position(pos); |
572 |
newLen = removePadding(bb, blockSize, protocolVersion); |
|
7039 | 573 |
|
16045 | 574 |
// check the explicit IV of TLS v1.1 or later |
7039 | 575 |
if (protocolVersion.v >= ProtocolVersion.TLS11.v) { |
576 |
if (newLen < blockSize) { |
|
577 |
throw new BadPaddingException("invalid explicit IV"); |
|
578 |
} |
|
579 |
||
580 |
// reset the position to the end of the decrypted data |
|
16045 | 581 |
bb.position(bb.limit()); |
7039 | 582 |
} |
2 | 583 |
} |
584 |
return newLen; |
|
585 |
} catch (ShortBufferException e) { |
|
16045 | 586 |
// unlikely to happen, we should have enough buffer space here |
587 |
throw new ArrayIndexOutOfBoundsException(e.toString()); |
|
2 | 588 |
} |
589 |
} |
|
590 |
||
591 |
private static int addPadding(byte[] buf, int offset, int len, |
|
592 |
int blockSize) { |
|
593 |
int newlen = len + 1; |
|
594 |
byte pad; |
|
595 |
int i; |
|
596 |
||
597 |
if ((newlen % blockSize) != 0) { |
|
598 |
newlen += blockSize - 1; |
|
599 |
newlen -= newlen % blockSize; |
|
600 |
} |
|
601 |
pad = (byte) (newlen - len); |
|
602 |
||
603 |
if (buf.length < (newlen + offset)) { |
|
604 |
throw new IllegalArgumentException("no space to pad buffer"); |
|
605 |
} |
|
606 |
||
607 |
/* |
|
608 |
* TLS version of the padding works for both SSLv3 and TLSv1 |
|
609 |
*/ |
|
610 |
for (i = 0, offset += len; i < pad; i++) { |
|
611 |
buf [offset++] = (byte) (pad - 1); |
|
612 |
} |
|
613 |
return newlen; |
|
614 |
} |
|
615 |
||
616 |
/* |
|
617 |
* Apply the padding to the buffer. |
|
618 |
* |
|
619 |
* Limit is advanced to the new buffer length. |
|
620 |
* Position is equal to limit. |
|
621 |
*/ |
|
622 |
private static int addPadding(ByteBuffer bb, int blockSize) { |
|
623 |
||
624 |
int len = bb.remaining(); |
|
625 |
int offset = bb.position(); |
|
626 |
||
627 |
int newlen = len + 1; |
|
628 |
byte pad; |
|
629 |
int i; |
|
630 |
||
631 |
if ((newlen % blockSize) != 0) { |
|
632 |
newlen += blockSize - 1; |
|
633 |
newlen -= newlen % blockSize; |
|
634 |
} |
|
635 |
pad = (byte) (newlen - len); |
|
636 |
||
637 |
/* |
|
638 |
* Update the limit to what will be padded. |
|
639 |
*/ |
|
640 |
bb.limit(newlen + offset); |
|
641 |
||
642 |
/* |
|
643 |
* TLS version of the padding works for both SSLv3 and TLSv1 |
|
644 |
*/ |
|
645 |
for (i = 0, offset += len; i < pad; i++) { |
|
646 |
bb.put(offset++, (byte) (pad - 1)); |
|
647 |
} |
|
648 |
||
649 |
bb.position(offset); |
|
650 |
bb.limit(offset); |
|
651 |
||
652 |
return newlen; |
|
653 |
} |
|
654 |
||
655 |
||
656 |
/* |
|
657 |
* Typical TLS padding format for a 64 bit block cipher is as follows: |
|
658 |
* xx xx xx xx xx xx xx 00 |
|
659 |
* xx xx xx xx xx xx 01 01 |
|
660 |
* ... |
|
661 |
* xx 06 06 06 06 06 06 06 |
|
662 |
* 07 07 07 07 07 07 07 07 |
|
663 |
* TLS also allows any amount of padding from 1 and 256 bytes as long |
|
664 |
* as it makes the data a multiple of the block size |
|
665 |
*/ |
|
666 |
private static int removePadding(byte[] buf, int offset, int len, |
|
667 |
int blockSize, ProtocolVersion protocolVersion) |
|
668 |
throws BadPaddingException { |
|
669 |
// last byte is length byte (i.e. actual padding length - 1) |
|
670 |
int padOffset = offset + len - 1; |
|
671 |
int pad = buf[padOffset] & 0x0ff; |
|
672 |
||
673 |
int newlen = len - (pad + 1); |
|
674 |
if (newlen < 0) { |
|
675 |
throw new BadPaddingException("Padding length invalid: " + pad); |
|
676 |
} |
|
677 |
||
678 |
if (protocolVersion.v >= ProtocolVersion.TLS10.v) { |
|
679 |
for (int i = 1; i <= pad; i++) { |
|
680 |
int val = buf[padOffset - i] & 0xff; |
|
681 |
if (val != pad) { |
|
682 |
throw new BadPaddingException |
|
683 |
("Invalid TLS padding: " + val); |
|
684 |
} |
|
685 |
} |
|
686 |
} else { // SSLv3 |
|
687 |
// SSLv3 requires 0 <= length byte < block size |
|
688 |
// some implementations do 1 <= length byte <= block size, |
|
689 |
// so accept that as well |
|
690 |
// v3 does not require any particular value for the other bytes |
|
691 |
if (pad > blockSize) { |
|
692 |
throw new BadPaddingException("Invalid SSLv3 padding: " + pad); |
|
693 |
} |
|
694 |
} |
|
695 |
return newlen; |
|
696 |
} |
|
697 |
||
698 |
/* |
|
699 |
* Position/limit is equal the removed padding. |
|
700 |
*/ |
|
701 |
private static int removePadding(ByteBuffer bb, |
|
702 |
int blockSize, ProtocolVersion protocolVersion) |
|
703 |
throws BadPaddingException { |
|
704 |
||
705 |
int len = bb.remaining(); |
|
706 |
int offset = bb.position(); |
|
707 |
||
708 |
// last byte is length byte (i.e. actual padding length - 1) |
|
709 |
int padOffset = offset + len - 1; |
|
710 |
int pad = bb.get(padOffset) & 0x0ff; |
|
711 |
||
712 |
int newlen = len - (pad + 1); |
|
713 |
if (newlen < 0) { |
|
714 |
throw new BadPaddingException("Padding length invalid: " + pad); |
|
715 |
} |
|
716 |
||
717 |
/* |
|
718 |
* We could zero the padding area, but not much useful |
|
719 |
* information there. |
|
720 |
*/ |
|
721 |
if (protocolVersion.v >= ProtocolVersion.TLS10.v) { |
|
722 |
bb.put(padOffset, (byte)0); // zero the padding. |
|
723 |
for (int i = 1; i <= pad; i++) { |
|
724 |
int val = bb.get(padOffset - i) & 0xff; |
|
725 |
if (val != pad) { |
|
726 |
throw new BadPaddingException |
|
727 |
("Invalid TLS padding: " + val); |
|
728 |
} |
|
729 |
} |
|
730 |
} else { // SSLv3 |
|
731 |
// SSLv3 requires 0 <= length byte < block size |
|
732 |
// some implementations do 1 <= length byte <= block size, |
|
733 |
// so accept that as well |
|
734 |
// v3 does not require any particular value for the other bytes |
|
735 |
if (pad > blockSize) { |
|
736 |
throw new BadPaddingException("Invalid SSLv3 padding: " + pad); |
|
737 |
} |
|
738 |
} |
|
739 |
||
740 |
/* |
|
741 |
* Reset buffer limit to remove padding. |
|
742 |
*/ |
|
743 |
bb.position(offset + newlen); |
|
744 |
bb.limit(offset + newlen); |
|
745 |
||
746 |
return newlen; |
|
747 |
} |
|
1763
0a6b65d56746
6750401: SSL stress test with GF leads to 32 bit max process size in less than 5 minutes,with PCKS11 provider
wetmore
parents:
2
diff
changeset
|
748 |
|
0a6b65d56746
6750401: SSL stress test with GF leads to 32 bit max process size in less than 5 minutes,with PCKS11 provider
wetmore
parents:
2
diff
changeset
|
749 |
/* |
0a6b65d56746
6750401: SSL stress test with GF leads to 32 bit max process size in less than 5 minutes,with PCKS11 provider
wetmore
parents:
2
diff
changeset
|
750 |
* Dispose of any intermediate state in the underlying cipher. |
0a6b65d56746
6750401: SSL stress test with GF leads to 32 bit max process size in less than 5 minutes,with PCKS11 provider
wetmore
parents:
2
diff
changeset
|
751 |
* For PKCS11 ciphers, this will release any attached sessions, and |
0a6b65d56746
6750401: SSL stress test with GF leads to 32 bit max process size in less than 5 minutes,with PCKS11 provider
wetmore
parents:
2
diff
changeset
|
752 |
* thus make finalization faster. |
0a6b65d56746
6750401: SSL stress test with GF leads to 32 bit max process size in less than 5 minutes,with PCKS11 provider
wetmore
parents:
2
diff
changeset
|
753 |
*/ |
0a6b65d56746
6750401: SSL stress test with GF leads to 32 bit max process size in less than 5 minutes,with PCKS11 provider
wetmore
parents:
2
diff
changeset
|
754 |
void dispose() { |
0a6b65d56746
6750401: SSL stress test with GF leads to 32 bit max process size in less than 5 minutes,with PCKS11 provider
wetmore
parents:
2
diff
changeset
|
755 |
try { |
0a6b65d56746
6750401: SSL stress test with GF leads to 32 bit max process size in less than 5 minutes,with PCKS11 provider
wetmore
parents:
2
diff
changeset
|
756 |
if (cipher != null) { |
0a6b65d56746
6750401: SSL stress test with GF leads to 32 bit max process size in less than 5 minutes,with PCKS11 provider
wetmore
parents:
2
diff
changeset
|
757 |
// ignore return value. |
0a6b65d56746
6750401: SSL stress test with GF leads to 32 bit max process size in less than 5 minutes,with PCKS11 provider
wetmore
parents:
2
diff
changeset
|
758 |
cipher.doFinal(); |
0a6b65d56746
6750401: SSL stress test with GF leads to 32 bit max process size in less than 5 minutes,with PCKS11 provider
wetmore
parents:
2
diff
changeset
|
759 |
} |
16045 | 760 |
} catch (Exception e) { |
761 |
// swallow all types of exceptions. |
|
1763
0a6b65d56746
6750401: SSL stress test with GF leads to 32 bit max process size in less than 5 minutes,with PCKS11 provider
wetmore
parents:
2
diff
changeset
|
762 |
} |
0a6b65d56746
6750401: SSL stress test with GF leads to 32 bit max process size in less than 5 minutes,with PCKS11 provider
wetmore
parents:
2
diff
changeset
|
763 |
} |
0a6b65d56746
6750401: SSL stress test with GF leads to 32 bit max process size in less than 5 minutes,with PCKS11 provider
wetmore
parents:
2
diff
changeset
|
764 |
|
10915 | 765 |
/* |
766 |
* Does the cipher use CBC mode? |
|
767 |
* |
|
768 |
* @return true if the cipher use CBC mode, false otherwise. |
|
769 |
*/ |
|
770 |
boolean isCBCMode() { |
|
16045 | 771 |
return cipherType == BLOCK_CIPHER; |
772 |
} |
|
773 |
||
774 |
/* |
|
775 |
* Does the cipher use AEAD mode? |
|
776 |
* |
|
777 |
* @return true if the cipher use AEAD mode, false otherwise. |
|
778 |
*/ |
|
779 |
boolean isAEADMode() { |
|
780 |
return cipherType == AEAD_CIPHER; |
|
781 |
} |
|
782 |
||
783 |
/* |
|
784 |
* Is the cipher null? |
|
785 |
* |
|
786 |
* @return true if the cipher is null, false otherwise. |
|
787 |
*/ |
|
788 |
boolean isNullCipher() { |
|
789 |
return cipher == null; |
|
790 |
} |
|
791 |
||
792 |
/* |
|
793 |
* Gets the explicit nonce/IV size of the cipher. |
|
794 |
* |
|
795 |
* The returned value is the SecurityParameters.record_iv_length in |
|
796 |
* RFC 4346/5246. It is the size of explicit IV for CBC mode, and the |
|
797 |
* size of explicit nonce for AEAD mode. |
|
798 |
* |
|
799 |
* @return the explicit nonce size of the cipher. |
|
800 |
*/ |
|
801 |
int getExplicitNonceSize() { |
|
802 |
switch (cipherType) { |
|
803 |
case BLOCK_CIPHER: |
|
804 |
// For block ciphers, the explicit IV length is of length |
|
805 |
// SecurityParameters.record_iv_length, which is equal to |
|
806 |
// the SecurityParameters.block_size. |
|
807 |
if (protocolVersion.v >= ProtocolVersion.TLS11.v) { |
|
808 |
return cipher.getBlockSize(); |
|
809 |
} |
|
810 |
break; |
|
811 |
case AEAD_CIPHER: |
|
812 |
return recordIvSize; |
|
813 |
// It is also the length of sequence number, which is |
|
814 |
// used as the nonce_explicit for AEAD cipher suites. |
|
815 |
} |
|
816 |
||
817 |
return 0; |
|
818 |
} |
|
819 |
||
820 |
/* |
|
821 |
* Applies the explicit nonce/IV to this cipher. This method is used to |
|
822 |
* decrypt an SSL/TLS input record. |
|
823 |
* |
|
824 |
* The returned value is the SecurityParameters.record_iv_length in |
|
825 |
* RFC 4346/5246. It is the size of explicit IV for CBC mode, and the |
|
826 |
* size of explicit nonce for AEAD mode. |
|
827 |
* |
|
828 |
* @param authenticator the authenticator to get the additional |
|
829 |
* authentication data |
|
830 |
* @param contentType the content type of the input record |
|
831 |
* @param bb the byte buffer to get the explicit nonce from |
|
832 |
* |
|
833 |
* @return the explicit nonce size of the cipher. |
|
834 |
*/ |
|
835 |
int applyExplicitNonce(Authenticator authenticator, byte contentType, |
|
836 |
ByteBuffer bb) throws BadPaddingException { |
|
837 |
switch (cipherType) { |
|
838 |
case BLOCK_CIPHER: |
|
839 |
// For block ciphers, the explicit IV length is of length |
|
840 |
// SecurityParameters.record_iv_length, which is equal to |
|
841 |
// the SecurityParameters.block_size. |
|
842 |
if (protocolVersion.v >= ProtocolVersion.TLS11.v) { |
|
843 |
return cipher.getBlockSize(); |
|
844 |
} |
|
845 |
break; |
|
846 |
case AEAD_CIPHER: |
|
847 |
if (bb.remaining() < (recordIvSize + tagSize)) { |
|
848 |
throw new BadPaddingException( |
|
849 |
"invalid AEAD cipher fragment"); |
|
850 |
} |
|
851 |
||
852 |
// initialize the AEAD cipher for the unique IV |
|
853 |
byte[] iv = Arrays.copyOf(fixedIv, |
|
854 |
fixedIv.length + recordIvSize); |
|
855 |
bb.get(iv, fixedIv.length, recordIvSize); |
|
856 |
bb.position(bb.position() - recordIvSize); |
|
857 |
GCMParameterSpec spec = new GCMParameterSpec(tagSize * 8, iv); |
|
858 |
try { |
|
859 |
cipher.init(mode, key, spec, random); |
|
860 |
} catch (InvalidKeyException | |
|
861 |
InvalidAlgorithmParameterException ikae) { |
|
862 |
// unlikely to happen |
|
863 |
throw new RuntimeException( |
|
864 |
"invalid key or spec in GCM mode", ikae); |
|
865 |
} |
|
866 |
||
867 |
// update the additional authentication data |
|
868 |
byte[] aad = authenticator.acquireAuthenticationBytes( |
|
869 |
contentType, bb.remaining() - recordIvSize - tagSize); |
|
870 |
cipher.updateAAD(aad); |
|
871 |
||
872 |
return recordIvSize; |
|
873 |
// It is also the length of sequence number, which is |
|
874 |
// used as the nonce_explicit for AEAD cipher suites. |
|
875 |
} |
|
876 |
||
877 |
return 0; |
|
878 |
} |
|
879 |
||
880 |
/* |
|
881 |
* Applies the explicit nonce/IV to this cipher. This method is used to |
|
882 |
* decrypt an SSL/TLS input record. |
|
883 |
* |
|
884 |
* The returned value is the SecurityParameters.record_iv_length in |
|
885 |
* RFC 4346/5246. It is the size of explicit IV for CBC mode, and the |
|
886 |
* size of explicit nonce for AEAD mode. |
|
887 |
* |
|
888 |
* @param authenticator the authenticator to get the additional |
|
889 |
* authentication data |
|
890 |
* @param contentType the content type of the input record |
|
891 |
* @param buf the byte array to get the explicit nonce from |
|
892 |
* @param offset the offset of the byte buffer |
|
893 |
* @param cipheredLength the ciphered fragment length of the output |
|
894 |
* record, it is the TLSCiphertext.length in RFC 4346/5246. |
|
895 |
* |
|
896 |
* @return the explicit nonce size of the cipher. |
|
897 |
*/ |
|
898 |
int applyExplicitNonce(Authenticator authenticator, |
|
899 |
byte contentType, byte[] buf, int offset, |
|
900 |
int cipheredLength) throws BadPaddingException { |
|
901 |
||
902 |
ByteBuffer bb = ByteBuffer.wrap(buf, offset, cipheredLength); |
|
903 |
||
904 |
return applyExplicitNonce(authenticator, contentType, bb); |
|
905 |
} |
|
906 |
||
907 |
/* |
|
908 |
* Creates the explicit nonce/IV to this cipher. This method is used to |
|
909 |
* encrypt an SSL/TLS output record. |
|
910 |
* |
|
911 |
* The size of the returned array is the SecurityParameters.record_iv_length |
|
912 |
* in RFC 4346/5246. It is the size of explicit IV for CBC mode, and the |
|
913 |
* size of explicit nonce for AEAD mode. |
|
914 |
* |
|
915 |
* @param authenticator the authenticator to get the additional |
|
916 |
* authentication data |
|
917 |
* @param contentType the content type of the input record |
|
918 |
* @param fragmentLength the fragment length of the output record, it is |
|
919 |
* the TLSCompressed.length in RFC 4346/5246. |
|
920 |
* |
|
921 |
* @return the explicit nonce of the cipher. |
|
922 |
*/ |
|
923 |
byte[] createExplicitNonce(Authenticator authenticator, |
|
924 |
byte contentType, int fragmentLength) { |
|
925 |
||
926 |
byte[] nonce = new byte[0]; |
|
927 |
switch (cipherType) { |
|
928 |
case BLOCK_CIPHER: |
|
929 |
if (protocolVersion.v >= ProtocolVersion.TLS11.v) { |
|
930 |
// For block ciphers, the explicit IV length is of length |
|
931 |
// SecurityParameters.record_iv_length, which is equal to |
|
932 |
// the SecurityParameters.block_size. |
|
933 |
// |
|
934 |
// Generate a random number as the explicit IV parameter. |
|
935 |
nonce = new byte[cipher.getBlockSize()]; |
|
936 |
random.nextBytes(nonce); |
|
937 |
} |
|
938 |
break; |
|
939 |
case AEAD_CIPHER: |
|
940 |
// To be unique and aware of overflow-wrap, sequence number |
|
941 |
// is used as the nonce_explicit of AEAD cipher suites. |
|
942 |
nonce = authenticator.sequenceNumber(); |
|
943 |
||
944 |
// initialize the AEAD cipher for the unique IV |
|
945 |
byte[] iv = Arrays.copyOf(fixedIv, |
|
946 |
fixedIv.length + nonce.length); |
|
947 |
System.arraycopy(nonce, 0, iv, fixedIv.length, nonce.length); |
|
948 |
GCMParameterSpec spec = new GCMParameterSpec(tagSize * 8, iv); |
|
949 |
try { |
|
950 |
cipher.init(mode, key, spec, random); |
|
951 |
} catch (InvalidKeyException | |
|
952 |
InvalidAlgorithmParameterException ikae) { |
|
953 |
// unlikely to happen |
|
954 |
throw new RuntimeException( |
|
955 |
"invalid key or spec in GCM mode", ikae); |
|
956 |
} |
|
957 |
||
958 |
// update the additional authentication data |
|
959 |
byte[] aad = authenticator.acquireAuthenticationBytes( |
|
960 |
contentType, fragmentLength); |
|
961 |
cipher.updateAAD(aad); |
|
962 |
break; |
|
963 |
} |
|
964 |
||
965 |
return nonce; |
|
966 |
} |
|
967 |
||
968 |
/* |
|
969 |
* Is this cipher available? |
|
970 |
* |
|
971 |
* This method can only be called by CipherSuite.BulkCipher.isAvailable() |
|
972 |
* to test the availability of a cipher suites. Please DON'T use it in |
|
973 |
* other places, otherwise, the behavior may be unexpected because we may |
|
974 |
* initialize AEAD cipher improperly in the method. |
|
975 |
*/ |
|
976 |
Boolean isAvailable() { |
|
977 |
// We won't know whether a cipher for a particular key size is |
|
978 |
// available until the cipher is successfully initialized. |
|
979 |
// |
|
980 |
// We do not initialize AEAD cipher in the constructor. Need to |
|
981 |
// initialize the cipher to ensure that the AEAD mode for a |
|
982 |
// particular key size is supported. |
|
983 |
if (cipherType == AEAD_CIPHER) { |
|
984 |
try { |
|
985 |
Authenticator authenticator = |
|
986 |
new Authenticator(protocolVersion); |
|
987 |
byte[] nonce = authenticator.sequenceNumber(); |
|
988 |
byte[] iv = Arrays.copyOf(fixedIv, |
|
989 |
fixedIv.length + nonce.length); |
|
990 |
System.arraycopy(nonce, 0, iv, fixedIv.length, nonce.length); |
|
991 |
GCMParameterSpec spec = new GCMParameterSpec(tagSize * 8, iv); |
|
992 |
||
993 |
cipher.init(mode, key, spec, random); |
|
994 |
} catch (Exception e) { |
|
995 |
return Boolean.FALSE; |
|
996 |
} |
|
997 |
} // Otherwise, we have initialized the cipher in the constructor. |
|
998 |
||
999 |
return Boolean.TRUE; |
|
10915 | 1000 |
} |
2 | 1001 |
} |