• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 1996, 2013, 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 
33 import java.security.*;
34 import javax.crypto.*;
35 import javax.crypto.spec.SecretKeySpec;
36 import javax.crypto.spec.IvParameterSpec;
37 
38 import java.nio.*;
39 
40 import sun.security.ssl.CipherSuite.*;
41 import static sun.security.ssl.CipherSuite.*;
42 
43 import sun.misc.HexDumpEncoder;
44 
45 
46 /**
47  * This class handles bulk data enciphering/deciphering for each SSLv3
48  * message.  This provides data confidentiality.  Stream ciphers (such
49  * as RC4) don't need to do padding; block ciphers (e.g. DES) need it.
50  *
51  * Individual instances are obtained by calling the static method
52  * newCipherBox(), which should only be invoked by BulkCipher.newCipher().
53  *
54  * In RFC 2246, with bock ciphers in CBC mode, the Initialization
55  * Vector (IV) for the first record is generated with the other keys
56  * and secrets when the security parameters are set.  The IV for
57  * subsequent records is the last ciphertext block from the previous
58  * record.
59  *
60  * In RFC 4346, the implicit Initialization Vector (IV) is replaced
61  * with an explicit IV to protect against CBC attacks.  RFC 4346
62  * recommends two algorithms used to generated the per-record IV.
63  * The implementation uses the algorithm (2)(b), as described at
64  * section 6.2.3.2 of RFC 4346.
65  *
66  * The usage of IV in CBC block cipher can be illustrated in
67  * the following diagrams.
68  *
69  *   (random)
70  *        R         P1                    IV        C1
71  *        |          |                     |         |
72  *  SIV---+    |-----+    |-...            |-----    |------
73  *        |    |     |    |                |    |    |     |
74  *     +----+  |  +----+  |             +----+  |  +----+  |
75  *     | Ek |  |  + Ek +  |             | Dk |  |  | Dk |  |
76  *     +----+  |  +----+  |             +----+  |  +----+  |
77  *        |    |     |    |                |    |    |     |
78  *        |----|     |----|           SIV--+    |----|     |-...
79  *        |          |                     |       |
80  *       IV         C1                     R      P1
81  *                                     (discard)
82  *
83  *       CBC Encryption                    CBC Decryption
84  *
85  * NOTE that any ciphering involved in key exchange (e.g. with RSA) is
86  * handled separately.
87  *
88  * @author David Brownell
89  * @author Andreas Sterbenz
90  */
91 final class CipherBox {
92 
93     // A CipherBox that implements the identity operation
94     final static CipherBox NULL = new CipherBox();
95 
96     /* Class and subclass dynamic debugging support */
97     private static final Debug debug = Debug.getInstance("ssl");
98 
99     // the protocol version this cipher conforms to
100     private final ProtocolVersion protocolVersion;
101 
102     // cipher object
103     private final Cipher cipher;
104 
105     /**
106      * Cipher blocksize, 0 for stream ciphers
107      */
108     private int blockSize;
109 
110     /**
111      * secure random
112      */
113     private SecureRandom random;
114 
115     /**
116      * Is the cipher of CBC mode?
117      */
118     private final boolean isCBCMode;
119 
120     /**
121      * Fixed masks of various block size, as the initial decryption IVs
122      * for TLS 1.1 or later.
123      *
124      * For performance, we do not use random IVs. As the initial decryption
125      * IVs will be discarded by TLS decryption processes, so the fixed masks
126      * do not hurt cryptographic strength.
127      */
128     private static Hashtable<Integer, IvParameterSpec> masks;
129 
130     /**
131      * NULL cipherbox. Identity operation, no encryption.
132      */
CipherBox()133     private CipherBox() {
134         this.protocolVersion = ProtocolVersion.DEFAULT;
135         this.cipher = null;
136         this.isCBCMode = false;
137     }
138 
139     /**
140      * Construct a new CipherBox using the cipher transformation.
141      *
142      * @exception NoSuchAlgorithmException if no appropriate JCE Cipher
143      * implementation could be found.
144      */
CipherBox(ProtocolVersion protocolVersion, BulkCipher bulkCipher, SecretKey key, IvParameterSpec iv, SecureRandom random, boolean encrypt)145     private CipherBox(ProtocolVersion protocolVersion, BulkCipher bulkCipher,
146             SecretKey key, IvParameterSpec iv, SecureRandom random,
147             boolean encrypt) throws NoSuchAlgorithmException {
148         try {
149             this.protocolVersion = protocolVersion;
150             this.cipher = JsseJce.getCipher(bulkCipher.transformation);
151             int mode = encrypt ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE;
152 
153             if (random == null) {
154                 random = JsseJce.getSecureRandom();
155             }
156             this.random = random;
157             this.isCBCMode = bulkCipher.isCBCMode;
158 
159             /*
160              * RFC 4346 recommends two algorithms used to generated the
161              * per-record IV. The implementation uses the algorithm (2)(b),
162              * as described at section 6.2.3.2 of RFC 4346.
163              *
164              * As we don't care about the initial IV value for TLS 1.1 or
165              * later, so if the "iv" parameter is null, we use the default
166              * value generated by Cipher.init() for encryption, and a fixed
167              * mask for decryption.
168              */
169             if (iv == null && bulkCipher.ivSize != 0 &&
170                     mode == Cipher.DECRYPT_MODE &&
171                     protocolVersion.v >= ProtocolVersion.TLS11.v) {
172                 iv = getFixedMask(bulkCipher.ivSize);
173             }
174 
175             cipher.init(mode, key, iv, random);
176 
177             // Do not call getBlockSize until after init()
178             // otherwise we would disrupt JCE delayed provider selection
179             blockSize = cipher.getBlockSize();
180             // some providers implement getBlockSize() incorrectly
181             if (blockSize == 1) {
182                 blockSize = 0;
183             }
184         } catch (NoSuchAlgorithmException e) {
185             throw e;
186         } catch (Exception e) {
187             throw new NoSuchAlgorithmException
188                     ("Could not create cipher " + bulkCipher, e);
189         } catch (ExceptionInInitializerError e) {
190             throw new NoSuchAlgorithmException
191                     ("Could not create cipher " + bulkCipher, e);
192         }
193     }
194 
195     /*
196      * Factory method to obtain a new CipherBox object.
197      */
newCipherBox(ProtocolVersion version, BulkCipher cipher, SecretKey key, IvParameterSpec iv, SecureRandom random, boolean encrypt)198     static CipherBox newCipherBox(ProtocolVersion version, BulkCipher cipher,
199             SecretKey key, IvParameterSpec iv, SecureRandom random,
200             boolean encrypt) throws NoSuchAlgorithmException {
201         if (cipher.allowed == false) {
202             throw new NoSuchAlgorithmException("Unsupported cipher " + cipher);
203         }
204 
205         if (cipher == B_NULL) {
206             return NULL;
207         } else {
208             return new CipherBox(version, cipher, key, iv, random, encrypt);
209         }
210     }
211 
212     /*
213      * Get a fixed mask, as the initial decryption IVs for TLS 1.1 or later.
214      */
getFixedMask(int ivSize)215     private static IvParameterSpec getFixedMask(int ivSize) {
216         if (masks == null) {
217             masks = new Hashtable<Integer, IvParameterSpec>(5);
218         }
219 
220         IvParameterSpec iv = masks.get(ivSize);
221         if (iv == null) {
222             iv = new IvParameterSpec(new byte[ivSize]);
223             masks.put(ivSize, iv);
224         }
225 
226         return iv;
227     }
228 
229     /*
230      * Encrypts a block of data, returning the size of the
231      * resulting block.
232      */
encrypt(byte[] buf, int offset, int len)233     int encrypt(byte[] buf, int offset, int len) {
234         if (cipher == null) {
235             return len;
236         }
237 
238         try {
239             if (blockSize != 0) {
240                 // TLSv1.1 needs a IV block
241                 if (protocolVersion.v >= ProtocolVersion.TLS11.v) {
242                     // generate a random number
243                     byte[] prefix = new byte[blockSize];
244                     random.nextBytes(prefix);
245 
246                     // move forward the plaintext
247                     System.arraycopy(buf, offset,
248                                      buf, offset + prefix.length, len);
249 
250                     // prefix the plaintext
251                     System.arraycopy(prefix, 0,
252                                      buf, offset, prefix.length);
253 
254                     len += prefix.length;
255                 }
256 
257                 len = addPadding(buf, offset, len, blockSize);
258             }
259             if (debug != null && Debug.isOn("plaintext")) {
260                 try {
261                     HexDumpEncoder hd = new HexDumpEncoder();
262 
263                     System.out.println(
264                         "Padded plaintext before ENCRYPTION:  len = "
265                         + len);
266                     hd.encodeBuffer(
267                         new ByteArrayInputStream(buf, offset, len),
268                         System.out);
269                 } catch (IOException e) { }
270             }
271             int newLen = cipher.update(buf, offset, len, buf, offset);
272             if (newLen != len) {
273                 // catch BouncyCastle buffering error
274                 throw new RuntimeException("Cipher buffering error " +
275                     "in JCE provider " + cipher.getProvider().getName());
276             }
277             return newLen;
278         } catch (ShortBufferException e) {
279             throw new ArrayIndexOutOfBoundsException(e.toString());
280         }
281     }
282 
283     /*
284      * Encrypts a ByteBuffer block of data, returning the size of the
285      * resulting block.
286      *
287      * The byte buffers position and limit initially define the amount
288      * to encrypt.  On return, the position and limit are
289      * set to last position padded/encrypted.  The limit may have changed
290      * because of the added padding bytes.
291      */
encrypt(ByteBuffer bb)292     int encrypt(ByteBuffer bb) {
293 
294         int len = bb.remaining();
295 
296         if (cipher == null) {
297             bb.position(bb.limit());
298             return len;
299         }
300 
301         try {
302             int pos = bb.position();
303 
304             if (blockSize != 0) {
305                 // TLSv1.1 needs a IV block
306                 if (protocolVersion.v >= ProtocolVersion.TLS11.v) {
307                     // generate a random number
308                     byte[] prefix = new byte[blockSize];
309                     random.nextBytes(prefix);
310 
311                     // move forward the plaintext
312                     byte[] buf = null;
313                     int limit = bb.limit();
314                     if (bb.hasArray()) {
315                         int arrayOffset = bb.arrayOffset();
316                         buf = bb.array();
317                         System.arraycopy(buf, arrayOffset + pos,
318                             buf, arrayOffset + pos + prefix.length,
319                             limit - pos);
320                         bb.limit(limit + prefix.length);
321                     } else {
322                         buf = new byte[limit - pos];
323                         bb.get(buf, 0, limit - pos);
324                         bb.position(pos + prefix.length);
325                         bb.limit(limit + prefix.length);
326                         bb.put(buf);
327                     }
328                     bb.position(pos);
329 
330                     // prefix the plaintext
331                     bb.put(prefix);
332                     bb.position(pos);
333                 }
334 
335                 // addPadding adjusts pos/limit
336                 len = addPadding(bb, blockSize);
337                 bb.position(pos);
338             }
339             if (debug != null && Debug.isOn("plaintext")) {
340                 try {
341                     HexDumpEncoder hd = new HexDumpEncoder();
342 
343                     System.out.println(
344                         "Padded plaintext before ENCRYPTION:  len = "
345                         + len);
346                     hd.encodeBuffer(bb, System.out);
347 
348                 } catch (IOException e) { }
349                 /*
350                  * reset back to beginning
351                  */
352                 bb.position(pos);
353             }
354 
355             /*
356              * Encrypt "in-place".  This does not add its own padding.
357              */
358             ByteBuffer dup = bb.duplicate();
359             int newLen = cipher.update(dup, bb);
360 
361             if (bb.position() != dup.position()) {
362                 throw new RuntimeException("bytebuffer padding error");
363             }
364 
365             if (newLen != len) {
366                 // catch BouncyCastle buffering error
367                 throw new RuntimeException("Cipher buffering error " +
368                     "in JCE provider " + cipher.getProvider().getName());
369             }
370             return newLen;
371         } catch (ShortBufferException e) {
372             RuntimeException exc = new RuntimeException(e.toString());
373             exc.initCause(e);
374             throw exc;
375         }
376     }
377 
378 
379     /*
380      * Decrypts a block of data, returning the size of the
381      * resulting block if padding was required.
382      *
383      * For SSLv3 and TLSv1.0, with block ciphers in CBC mode the
384      * Initialization Vector (IV) for the first record is generated by
385      * the handshake protocol, the IV for subsequent records is the
386      * last ciphertext block from the previous record.
387      *
388      * From TLSv1.1, the implicit IV is replaced with an explicit IV to
389      * protect against CBC attacks.
390      *
391      * Differentiating between bad_record_mac and decryption_failed alerts
392      * may permit certain attacks against CBC mode. It is preferable to
393      * uniformly use the bad_record_mac alert to hide the specific type of
394      * the error.
395      */
decrypt(byte[] buf, int offset, int len, int tagLen)396     int decrypt(byte[] buf, int offset, int len,
397             int tagLen) throws BadPaddingException {
398         if (cipher == null) {
399             return len;
400         }
401 
402         try {
403             int newLen = cipher.update(buf, offset, len, buf, offset);
404             if (newLen != len) {
405                 // catch BouncyCastle buffering error
406                 throw new RuntimeException("Cipher buffering error " +
407                     "in JCE provider " + cipher.getProvider().getName());
408             }
409             if (debug != null && Debug.isOn("plaintext")) {
410                 try {
411                     HexDumpEncoder hd = new HexDumpEncoder();
412 
413                     System.out.println(
414                         "Padded plaintext after DECRYPTION:  len = "
415                         + newLen);
416                     hd.encodeBuffer(
417                         new ByteArrayInputStream(buf, offset, newLen),
418                         System.out);
419                 } catch (IOException e) { }
420             }
421 
422             if (blockSize != 0) {
423                 newLen = removePadding(
424                     buf, offset, newLen, tagLen, blockSize, protocolVersion);
425 
426                 if (protocolVersion.v >= ProtocolVersion.TLS11.v) {
427                     if (newLen < blockSize) {
428                         throw new BadPaddingException("invalid explicit IV");
429                     }
430 
431                     // discards the first cipher block, the IV component.
432                     System.arraycopy(buf, offset + blockSize,
433                                      buf, offset, newLen - blockSize);
434 
435                     newLen -= blockSize;
436                 }
437             }
438             return newLen;
439         } catch (ShortBufferException e) {
440             throw new ArrayIndexOutOfBoundsException(e.toString());
441         }
442     }
443 
444 
445     /*
446      * Decrypts a block of data, returning the size of the
447      * resulting block if padding was required.  position and limit
448      * point to the end of the decrypted/depadded data.  The initial
449      * limit and new limit may be different, given we may
450      * have stripped off some padding bytes.
451      *
452      *  @see decrypt(byte[], int, int)
453      */
decrypt(ByteBuffer bb, int tagLen)454     int decrypt(ByteBuffer bb, int tagLen) throws BadPaddingException {
455 
456         int len = bb.remaining();
457 
458         if (cipher == null) {
459             bb.position(bb.limit());
460             return len;
461         }
462 
463         try {
464             /*
465              * Decrypt "in-place".
466              */
467             int pos = bb.position();
468             ByteBuffer dup = bb.duplicate();
469             int newLen = cipher.update(dup, bb);
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 
484                     hd.encodeBuffer(
485                         (ByteBuffer)bb.duplicate().position(pos), System.out);
486                 } catch (IOException e) { }
487             }
488 
489             /*
490              * Remove the block padding.
491              */
492             if (blockSize != 0) {
493                 bb.position(pos);
494                 newLen = removePadding(
495                     bb, tagLen, blockSize, protocolVersion);
496 
497                 if (protocolVersion.v >= ProtocolVersion.TLS11.v) {
498                     if (newLen < blockSize) {
499                         throw new BadPaddingException("invalid explicit IV");
500                     }
501 
502                     // discards the first cipher block, the IV component.
503                     byte[] buf = null;
504                     int limit = bb.limit();
505                     if (bb.hasArray()) {
506                         int arrayOffset = bb.arrayOffset();
507                         buf = bb.array();
508                         System.arraycopy(buf, arrayOffset + pos + blockSize,
509                             buf, arrayOffset + pos, limit - pos - blockSize);
510                         bb.limit(limit - blockSize);
511                     } else {
512                         buf = new byte[limit - pos - blockSize];
513                         bb.position(pos + blockSize);
514                         bb.get(buf);
515                         bb.position(pos);
516                         bb.put(buf);
517                         bb.limit(limit - blockSize);
518                     }
519 
520                     // reset the position to the end of the decrypted data
521                     limit = bb.limit();
522                     bb.position(limit);
523                 }
524             }
525             return newLen;
526         } catch (ShortBufferException e) {
527             RuntimeException exc = new RuntimeException(e.toString());
528             exc.initCause(e);
529             throw exc;
530         }
531     }
532 
addPadding(byte[] buf, int offset, int len, int blockSize)533     private static int addPadding(byte[] buf, int offset, int len,
534             int blockSize) {
535         int     newlen = len + 1;
536         byte    pad;
537         int     i;
538 
539         if ((newlen % blockSize) != 0) {
540             newlen += blockSize - 1;
541             newlen -= newlen % blockSize;
542         }
543         pad = (byte) (newlen - len);
544 
545         if (buf.length < (newlen + offset)) {
546             throw new IllegalArgumentException("no space to pad buffer");
547         }
548 
549         /*
550          * TLS version of the padding works for both SSLv3 and TLSv1
551          */
552         for (i = 0, offset += len; i < pad; i++) {
553             buf [offset++] = (byte) (pad - 1);
554         }
555         return newlen;
556     }
557 
558     /*
559      * Apply the padding to the buffer.
560      *
561      * Limit is advanced to the new buffer length.
562      * Position is equal to limit.
563      */
addPadding(ByteBuffer bb, int blockSize)564     private static int addPadding(ByteBuffer bb, int blockSize) {
565 
566         int     len = bb.remaining();
567         int     offset = bb.position();
568 
569         int     newlen = len + 1;
570         byte    pad;
571         int     i;
572 
573         if ((newlen % blockSize) != 0) {
574             newlen += blockSize - 1;
575             newlen -= newlen % blockSize;
576         }
577         pad = (byte) (newlen - len);
578 
579         /*
580          * Update the limit to what will be padded.
581          */
582         bb.limit(newlen + offset);
583 
584         /*
585          * TLS version of the padding works for both SSLv3 and TLSv1
586          */
587         for (i = 0, offset += len; i < pad; i++) {
588             bb.put(offset++, (byte) (pad - 1));
589         }
590 
591         bb.position(offset);
592         bb.limit(offset);
593 
594         return newlen;
595     }
596 
597     /*
598      * A constant-time check of the padding.
599      *
600      * NOTE that we are checking both the padding and the padLen bytes here.
601      *
602      * The caller MUST ensure that the len parameter is a positive number.
603      */
checkPadding( byte[] buf, int offset, int len, byte pad)604     private static int[] checkPadding(
605             byte[] buf, int offset, int len, byte pad) {
606 
607         if (len <= 0) {
608             throw new RuntimeException("padding len must be positive");
609         }
610 
611         // An array of hits is used to prevent Hotspot optimization for
612         // the purpose of a constant-time check.
613         int[] results = {0, 0};    // {missed #, matched #}
614         for (int i = 0; i <= 256;) {
615             for (int j = 0; j < len && i <= 256; j++, i++) {     // j <= i
616                 if (buf[offset + j] != pad) {
617                     results[0]++;       // mismatched padding data
618                 } else {
619                     results[1]++;       // matched padding data
620                 }
621             }
622         }
623 
624         return results;
625     }
626 
627     /*
628      * A constant-time check of the padding.
629      *
630      * NOTE that we are checking both the padding and the padLen bytes here.
631      *
632      * The caller MUST ensure that the bb parameter has remaining.
633      */
checkPadding(ByteBuffer bb, byte pad)634     private static int[] checkPadding(ByteBuffer bb, byte pad) {
635 
636         if (!bb.hasRemaining()) {
637             throw new RuntimeException("hasRemaining() must be positive");
638         }
639 
640         // An array of hits is used to prevent Hotspot optimization for
641         // the purpose of a constant-time check.
642         int[] results = {0, 0};    // {missed #, matched #}
643         bb.mark();
644         for (int i = 0; i <= 256; bb.reset()) {
645             for (; bb.hasRemaining() && i <= 256; i++) {
646                 if (bb.get() != pad) {
647                     results[0]++;       // mismatched padding data
648                 } else {
649                     results[1]++;       // matched padding data
650                 }
651             }
652         }
653 
654         return results;
655     }
656 
657     /*
658      * Typical TLS padding format for a 64 bit block cipher is as follows:
659      *   xx xx xx xx xx xx xx 00
660      *   xx xx xx xx xx xx 01 01
661      *   ...
662      *   xx 06 06 06 06 06 06 06
663      *   07 07 07 07 07 07 07 07
664      * TLS also allows any amount of padding from 1 and 256 bytes as long
665      * as it makes the data a multiple of the block size
666      */
removePadding(byte[] buf, int offset, int len, int tagLen, int blockSize, ProtocolVersion protocolVersion)667     private static int removePadding(byte[] buf, int offset, int len,
668             int tagLen, int blockSize,
669             ProtocolVersion protocolVersion) throws BadPaddingException {
670 
671         // last byte is length byte (i.e. actual padding length - 1)
672         int padOffset = offset + len - 1;
673         int padLen = buf[padOffset] & 0xFF;
674 
675         int newLen = len - (padLen + 1);
676         if ((newLen - tagLen) < 0) {
677             // If the buffer is not long enough to contain the padding plus
678             // a MAC tag, do a dummy constant-time padding check.
679             //
680             // Note that it is a dummy check, so we won't care about what is
681             // the actual padding data.
682             checkPadding(buf, offset, len, (byte)(padLen & 0xFF));
683 
684             throw new BadPaddingException("Invalid Padding length: " + padLen);
685         }
686 
687         // The padding data should be filled with the padding length value.
688         int[] results = checkPadding(buf, offset + newLen,
689                         padLen + 1, (byte)(padLen & 0xFF));
690         if (protocolVersion.v >= ProtocolVersion.TLS10.v) {
691             if (results[0] != 0) {          // padding data has invalid bytes
692                 throw new BadPaddingException("Invalid TLS padding data");
693             }
694         } else { // SSLv3
695             // SSLv3 requires 0 <= length byte < block size
696             // some implementations do 1 <= length byte <= block size,
697             // so accept that as well
698             // v3 does not require any particular value for the other bytes
699             if (padLen > blockSize) {
700                 throw new BadPaddingException("Invalid SSLv3 padding");
701             }
702         }
703         return newLen;
704     }
705 
706     /*
707      * Position/limit is equal the removed padding.
708      */
removePadding(ByteBuffer bb, int tagLen, int blockSize, ProtocolVersion protocolVersion)709     private static int removePadding(ByteBuffer bb,
710             int tagLen, int blockSize,
711             ProtocolVersion protocolVersion) throws BadPaddingException {
712 
713         int len = bb.remaining();
714         int offset = bb.position();
715 
716         // last byte is length byte (i.e. actual padding length - 1)
717         int padOffset = offset + len - 1;
718         int padLen = bb.get(padOffset) & 0xFF;
719 
720         int newLen = len - (padLen + 1);
721         if ((newLen - tagLen) < 0) {
722             // If the buffer is not long enough to contain the padding plus
723             // a MAC tag, do a dummy constant-time padding check.
724             //
725             // Note that it is a dummy check, so we won't care about what is
726             // the actual padding data.
727             checkPadding(bb.duplicate(), (byte)(padLen & 0xFF));
728 
729             throw new BadPaddingException("Invalid Padding length: " + padLen);
730         }
731 
732         // The padding data should be filled with the padding length value.
733         int[] results = checkPadding(
734                 (ByteBuffer)bb.duplicate().position(offset + newLen),
735                 (byte)(padLen & 0xFF));
736         if (protocolVersion.v >= ProtocolVersion.TLS10.v) {
737             if (results[0] != 0) {          // padding data has invalid bytes
738                 throw new BadPaddingException("Invalid TLS padding data");
739             }
740         } else { // SSLv3
741             // SSLv3 requires 0 <= length byte < block size
742             // some implementations do 1 <= length byte <= block size,
743             // so accept that as well
744             // v3 does not require any particular value for the other bytes
745             if (padLen > blockSize) {
746                 throw new BadPaddingException("Invalid SSLv3 padding");
747             }
748         }
749 
750         /*
751          * Reset buffer limit to remove padding.
752          */
753         bb.position(offset + newLen);
754         bb.limit(offset + newLen);
755 
756         return newLen;
757     }
758 
759     /*
760      * Dispose of any intermediate state in the underlying cipher.
761      * For PKCS11 ciphers, this will release any attached sessions, and
762      * thus make finalization faster.
763      */
dispose()764     void dispose() {
765         try {
766             if (cipher != null) {
767                 // ignore return value.
768                 cipher.doFinal();
769             }
770         } catch (GeneralSecurityException e) {
771             // swallow for now.
772         }
773     }
774 
775     /*
776      * Does the cipher use CBC mode?
777      *
778      * @return true if the cipher use CBC mode, false otherwise.
779      */
isCBCMode()780     boolean isCBCMode() {
781         return isCBCMode;
782     }
783 
784     /**
785      * Is the cipher null?
786      *
787      * @return true if the cipher is null, false otherwise.
788      */
isNullCipher()789     boolean isNullCipher() {
790         return cipher == null;
791     }
792 
793     /**
794      * Sanity check the length of a fragment before decryption.
795      *
796      * In CBC mode, check that the fragment length is one or multiple times
797      * of the block size of the cipher suite, and is at least one (one is the
798      * smallest size of padding in CBC mode) bigger than the tag size of the
799      * MAC algorithm except the explicit IV size for TLS 1.1 or later.
800      *
801      * In non-CBC mode, check that the fragment length is not less than the
802      * tag size of the MAC algorithm.
803      *
804      * @return true if the length of a fragment matches above requirements
805      */
sanityCheck(int tagLen, int fragmentLen)806     boolean sanityCheck(int tagLen, int fragmentLen) {
807         if (!isCBCMode) {
808             return fragmentLen >= tagLen;
809         }
810 
811         if ((fragmentLen % blockSize) == 0) {
812             int minimal = tagLen + 1;
813             minimal = (minimal >= blockSize) ? minimal : blockSize;
814             if (protocolVersion.v >= ProtocolVersion.TLS11.v) {
815                 minimal += blockSize;   // plus the size of the explicit IV
816             }
817 
818             return (fragmentLen >= minimal);
819         }
820 
821         return false;
822     }
823 
824 }
825