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 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.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  *
  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     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     /**
 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;
 158         this.cipher = null;
 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;
 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.v >= ProtocolVersion.TLS11.v) {
 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 == 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.v >= ProtocolVersion.TLS11.v) {
 495                     if (newLen < blockSize) {
 496                         throw new BadPaddingException("invalid explicit IV");
 497                     }
 498                 }
 499             }
 500             return newLen;
 501         } catch (ShortBufferException e) {
 502             // unlikely to happen, we should have enough buffer space here
 503             throw new ArrayIndexOutOfBoundsException(e.toString());
 504         }
 505     }
 506 
 507 
 508     /*
 509      * Decrypts a block of data, returning the size of the
 510      * resulting block if padding was required.  position and limit
 511      * point to the end of the decrypted/depadded data.  The initial
 512      * limit and new limit may be different, given we may
 513      * have stripped off some padding bytes.
 514      *
 515      *  @see decrypt(byte[], int, int)
 516      */
 517     int decrypt(ByteBuffer bb, int tagLen) throws BadPaddingException {
 518 
 519         int len = bb.remaining();
 520 
 521         if (cipher == null) {
 522             bb.position(bb.limit());
 523             return len;
 524         }
 525 
 526         try {
 527             /*
 528              * Decrypt "in-place".
 529              */
 530             int pos = bb.position();
 531             ByteBuffer dup = bb.duplicate();
 532             int newLen;
 533             if (cipherType == AEAD_CIPHER) {
 534                 try {
 535                     newLen = cipher.doFinal(dup, bb);
 536                 } catch (IllegalBlockSizeException ibse) {
 537                     // unlikely to happen
 538                     throw new RuntimeException(
 539                         "Cipher error in AEAD mode \"" + ibse.getMessage() +
 540                         " \"in JCE provider " + cipher.getProvider().getName());
 541                 }
 542             } else {
 543                 newLen = cipher.update(dup, bb);
 544                 if (newLen != len) {
 545                     // catch BouncyCastle buffering error
 546                     throw new RuntimeException("Cipher buffering error " +
 547                         "in JCE provider " + cipher.getProvider().getName());
 548                 }
 549             }
 550 
 551             // reset the limit to the end of the decryted data
 552             bb.limit(pos + newLen);
 553 
 554             if (debug != null && Debug.isOn("plaintext")) {
 555                 try {
 556                     HexDumpEncoder hd = new HexDumpEncoder();
 557 
 558                     System.out.println(
 559                         "Padded plaintext after DECRYPTION:  len = "
 560                         + newLen);
 561 
 562                     hd.encodeBuffer(
 563                         bb.duplicate().position(pos), System.out);
 564                 } catch (IOException e) { }
 565             }
 566 
 567             /*
 568              * Remove the block padding.
 569              */
 570             if (cipherType == BLOCK_CIPHER) {
 571                 int blockSize = cipher.getBlockSize();
 572                 bb.position(pos);
 573                 newLen = removePadding(bb, tagLen, blockSize, protocolVersion);
 574 
 575                 // check the explicit IV of TLS v1.1 or later
 576                 if (protocolVersion.v >= ProtocolVersion.TLS11.v) {
 577                     if (newLen < blockSize) {
 578                         throw new BadPaddingException("invalid explicit IV");
 579                     }
 580 
 581                     // reset the position to the end of the decrypted data
 582                     bb.position(bb.limit());
 583                 }
 584             }
 585             return newLen;
 586         } catch (ShortBufferException e) {
 587             // unlikely to happen, we should have enough buffer space here
 588             throw new ArrayIndexOutOfBoundsException(e.toString());
 589         }
 590     }
 591 
 592     private static int addPadding(byte[] buf, int offset, int len,
 593             int blockSize) {
 594         int     newlen = len + 1;
 595         byte    pad;
 596         int     i;
 597 
 598         if ((newlen % blockSize) != 0) {
 599             newlen += blockSize - 1;
 600             newlen -= newlen % blockSize;
 601         }
 602         pad = (byte) (newlen - len);
 603 
 604         if (buf.length < (newlen + offset)) {
 605             throw new IllegalArgumentException("no space to pad buffer");
 606         }
 607 
 608         /*
 609          * TLS version of the padding works for both SSLv3 and TLSv1
 610          */
 611         for (i = 0, offset += len; i < pad; i++) {
 612             buf [offset++] = (byte) (pad - 1);
 613         }
 614         return newlen;
 615     }
 616 
 617     /*
 618      * Apply the padding to the buffer.
 619      *
 620      * Limit is advanced to the new buffer length.
 621      * Position is equal to limit.
 622      */
 623     private static int addPadding(ByteBuffer bb, int blockSize) {
 624 
 625         int     len = bb.remaining();
 626         int     offset = bb.position();
 627 
 628         int     newlen = len + 1;
 629         byte    pad;
 630         int     i;
 631 
 632         if ((newlen % blockSize) != 0) {
 633             newlen += blockSize - 1;
 634             newlen -= newlen % blockSize;
 635         }
 636         pad = (byte) (newlen - len);
 637 
 638         /*
 639          * Update the limit to what will be padded.
 640          */
 641         bb.limit(newlen + offset);
 642 
 643         /*
 644          * TLS version of the padding works for both SSLv3 and TLSv1
 645          */
 646         for (i = 0, offset += len; i < pad; i++) {
 647             bb.put(offset++, (byte) (pad - 1));
 648         }
 649 
 650         bb.position(offset);
 651         bb.limit(offset);
 652 
 653         return newlen;
 654     }
 655 
 656     /*
 657      * A constant-time check of the padding.
 658      *
 659      * NOTE that we are checking both the padding and the padLen bytes here.
 660      *
 661      * The caller MUST ensure that the len parameter is a positive number.
 662      */
 663     private static int[] checkPadding(
 664             byte[] buf, int offset, int len, byte pad) {
 665 
 666         if (len <= 0) {
 667             throw new RuntimeException("padding len must be positive");
 668         }
 669 
 670         // An array of hits is used to prevent Hotspot optimization for
 671         // the purpose of a constant-time check.
 672         int[] results = {0, 0};    // {missed #, matched #}
 673         for (int i = 0; i <= 256;) {
 674             for (int j = 0; j < len && i <= 256; j++, i++) {     // j <= i
 675                 if (buf[offset + j] != pad) {
 676                     results[0]++;       // mismatched padding data
 677                 } else {
 678                     results[1]++;       // matched padding data
 679                 }
 680             }
 681         }
 682 
 683         return results;
 684     }
 685 
 686     /*
 687      * A constant-time check of the padding.
 688      *
 689      * NOTE that we are checking both the padding and the padLen bytes here.
 690      *
 691      * The caller MUST ensure that the bb parameter has remaining.
 692      */
 693     private static int[] checkPadding(ByteBuffer bb, byte pad) {
 694 
 695         if (!bb.hasRemaining()) {
 696             throw new RuntimeException("hasRemaining() must be positive");
 697         }
 698 
 699         // An array of hits is used to prevent Hotspot optimization for
 700         // the purpose of a constant-time check.
 701         int[] results = {0, 0};    // {missed #, matched #}
 702         bb.mark();
 703         for (int i = 0; i <= 256; bb.reset()) {
 704             for (; bb.hasRemaining() && i <= 256; i++) {
 705                 if (bb.get() != pad) {
 706                     results[0]++;       // mismatched padding data
 707                 } else {
 708                     results[1]++;       // matched padding data
 709                 }
 710             }
 711         }
 712 
 713         return results;
 714     }
 715 
 716     /*
 717      * Typical TLS padding format for a 64 bit block cipher is as follows:
 718      *   xx xx xx xx xx xx xx 00
 719      *   xx xx xx xx xx xx 01 01
 720      *   ...
 721      *   xx 06 06 06 06 06 06 06
 722      *   07 07 07 07 07 07 07 07
 723      * TLS also allows any amount of padding from 1 and 256 bytes as long
 724      * as it makes the data a multiple of the block size
 725      */
 726     private static int removePadding(byte[] buf, int offset, int len,
 727             int tagLen, int blockSize,
 728             ProtocolVersion protocolVersion) throws BadPaddingException {
 729 
 730         // last byte is length byte (i.e. actual padding length - 1)
 731         int padOffset = offset + len - 1;
 732         int padLen = buf[padOffset] & 0xFF;
 733 
 734         int newLen = len - (padLen + 1);
 735         if ((newLen - tagLen) < 0) {
 736             // If the buffer is not long enough to contain the padding plus
 737             // a MAC tag, do a dummy constant-time padding check.
 738             //
 739             // Note that it is a dummy check, so we won't care about what is
 740             // the actual padding data.
 741             checkPadding(buf, offset, len, (byte)(padLen & 0xFF));
 742 
 743             throw new BadPaddingException("Invalid Padding length: " + padLen);
 744         }
 745 
 746         // The padding data should be filled with the padding length value.
 747         int[] results = checkPadding(buf, offset + newLen,
 748                         padLen + 1, (byte)(padLen & 0xFF));
 749         if (protocolVersion.v >= ProtocolVersion.TLS10.v) {
 750             if (results[0] != 0) {          // padding data has invalid bytes
 751                 throw new BadPaddingException("Invalid TLS padding data");
 752             }
 753         } else { // SSLv3
 754             // SSLv3 requires 0 <= length byte < block size
 755             // some implementations do 1 <= length byte <= block size,
 756             // so accept that as well
 757             // v3 does not require any particular value for the other bytes
 758             if (padLen > blockSize) {
 759                 throw new BadPaddingException("Invalid SSLv3 padding");
 760             }
 761         }
 762         return newLen;
 763     }
 764 
 765     /*
 766      * Position/limit is equal the removed padding.
 767      */
 768     private static int removePadding(ByteBuffer bb,
 769             int tagLen, int blockSize,
 770             ProtocolVersion protocolVersion) throws BadPaddingException {
 771 
 772         int len = bb.remaining();
 773         int offset = bb.position();
 774 
 775         // last byte is length byte (i.e. actual padding length - 1)
 776         int padOffset = offset + len - 1;
 777         int padLen = bb.get(padOffset) & 0xFF;
 778 
 779         int newLen = len - (padLen + 1);
 780         if ((newLen - tagLen) < 0) {
 781             // If the buffer is not long enough to contain the padding plus
 782             // a MAC tag, do a dummy constant-time padding check.
 783             //
 784             // Note that it is a dummy check, so we won't care about what is
 785             // the actual padding data.
 786             checkPadding(bb.duplicate(), (byte)(padLen & 0xFF));
 787 
 788             throw new BadPaddingException("Invalid Padding length: " + padLen);
 789         }
 790 
 791         // The padding data should be filled with the padding length value.
 792         int[] results = checkPadding(
 793                 bb.duplicate().position(offset + newLen),
 794                 (byte)(padLen & 0xFF));
 795         if (protocolVersion.v >= ProtocolVersion.TLS10.v) {
 796             if (results[0] != 0) {          // padding data has invalid bytes
 797                 throw new BadPaddingException("Invalid TLS padding data");
 798             }
 799         } else { // SSLv3
 800             // SSLv3 requires 0 <= length byte < block size
 801             // some implementations do 1 <= length byte <= block size,
 802             // so accept that as well
 803             // v3 does not require any particular value for the other bytes
 804             if (padLen > blockSize) {
 805                 throw new BadPaddingException("Invalid SSLv3 padding");
 806             }
 807         }
 808 
 809         /*
 810          * Reset buffer limit to remove padding.
 811          */
 812         bb.position(offset + newLen);
 813         bb.limit(offset + newLen);
 814 
 815         return newLen;
 816     }
 817 
 818     /*
 819      * Dispose of any intermediate state in the underlying cipher.
 820      * For PKCS11 ciphers, this will release any attached sessions, and
 821      * thus make finalization faster.
 822      */
 823     void dispose() {
 824         try {
 825             if (cipher != null) {
 826                 // ignore return value.
 827                 cipher.doFinal();
 828             }
 829         } catch (Exception e) {
 830             // swallow all types of exceptions.
 831         }
 832     }
 833 
 834     /*
 835      * Does the cipher use CBC mode?
 836      *
 837      * @return true if the cipher use CBC mode, false otherwise.
 838      */
 839     boolean isCBCMode() {
 840         return cipherType == BLOCK_CIPHER;
 841     }
 842 
 843     /*
 844      * Does the cipher use AEAD mode?
 845      *
 846      * @return true if the cipher use AEAD mode, false otherwise.
 847      */
 848     boolean isAEADMode() {
 849         return cipherType == AEAD_CIPHER;
 850     }
 851 
 852     /*
 853      * Is the cipher null?
 854      *
 855      * @return true if the cipher is null, false otherwise.
 856      */
 857     boolean isNullCipher() {
 858         return cipher == null;
 859     }
 860 
 861     /*
 862      * Gets the explicit nonce/IV size of the cipher.
 863      *
 864      * The returned value is the SecurityParameters.record_iv_length in
 865      * RFC 4346/5246.  It is the size of explicit IV for CBC mode, and the
 866      * size of explicit nonce for AEAD mode.
 867      *
 868      * @return the explicit nonce size of the cipher.
 869      */
 870     int getExplicitNonceSize() {
 871         switch (cipherType) {
 872             case BLOCK_CIPHER:
 873                 // For block ciphers, the explicit IV length is of length
 874                 // SecurityParameters.record_iv_length, which is equal to
 875                 // the SecurityParameters.block_size.
 876                 if (protocolVersion.v >= ProtocolVersion.TLS11.v) {
 877                     return cipher.getBlockSize();
 878                 }
 879                 break;
 880             case AEAD_CIPHER:
 881                 return recordIvSize;
 882                         // It is also the length of sequence number, which is
 883                         // used as the nonce_explicit for AEAD cipher suites.
 884         }
 885 
 886         return 0;
 887     }
 888 
 889     /*
 890      * Applies the explicit nonce/IV to this cipher. This method is used to
 891      * decrypt an SSL/TLS input record.
 892      *
 893      * The returned value is the SecurityParameters.record_iv_length in
 894      * RFC 4346/5246.  It is the size of explicit IV for CBC mode, and the
 895      * size of explicit nonce for AEAD mode.
 896      *
 897      * @param  authenticator the authenticator to get the additional
 898      *         authentication data
 899      * @param  contentType the content type of the input record
 900      * @param  bb the byte buffer to get the explicit nonce from
 901      *
 902      * @return the explicit nonce size of the cipher.
 903      */
 904     int applyExplicitNonce(Authenticator authenticator, byte contentType,
 905             ByteBuffer bb) throws BadPaddingException {
 906         switch (cipherType) {
 907             case BLOCK_CIPHER:
 908                 // sanity check length of the ciphertext
 909                 int tagLen = (authenticator instanceof MAC) ?
 910                                     ((MAC)authenticator).MAClen() : 0;
 911                 if (tagLen != 0) {
 912                     if (!sanityCheck(tagLen, bb.remaining())) {
 913                         throw new BadPaddingException(
 914                                 "ciphertext sanity check failed");
 915                     }
 916                 }
 917 
 918                 // For block ciphers, the explicit IV length is of length
 919                 // SecurityParameters.record_iv_length, which is equal to
 920                 // the SecurityParameters.block_size.
 921                 if (protocolVersion.v >= ProtocolVersion.TLS11.v) {
 922                     return cipher.getBlockSize();
 923                 }
 924                 break;
 925             case AEAD_CIPHER:
 926                 if (bb.remaining() < (recordIvSize + tagSize)) {
 927                     throw new BadPaddingException(
 928                                         "invalid AEAD cipher fragment");
 929                 }
 930 
 931                 // initialize the AEAD cipher for the unique IV
 932                 byte[] iv = Arrays.copyOf(fixedIv,
 933                                     fixedIv.length + recordIvSize);
 934                 bb.get(iv, fixedIv.length, recordIvSize);
 935                 bb.position(bb.position() - recordIvSize);
 936                 GCMParameterSpec spec = new GCMParameterSpec(tagSize * 8, iv);
 937                 try {
 938                     cipher.init(mode, key, spec, random);
 939                 } catch (InvalidKeyException |
 940                             InvalidAlgorithmParameterException ikae) {
 941                     // unlikely to happen
 942                     throw new RuntimeException(
 943                                 "invalid key or spec in GCM mode", ikae);
 944                 }
 945 
 946                 // update the additional authentication data
 947                 byte[] aad = authenticator.acquireAuthenticationBytes(
 948                         contentType, bb.remaining() - recordIvSize - tagSize);
 949                 cipher.updateAAD(aad);
 950 
 951                 return recordIvSize;
 952                         // It is also the length of sequence number, which is
 953                         // used as the nonce_explicit for AEAD cipher suites.
 954         }
 955 
 956        return 0;
 957     }
 958 
 959     /*
 960      * Applies the explicit nonce/IV to this cipher. This method is used to
 961      * decrypt an SSL/TLS input record.
 962      *
 963      * The returned value is the SecurityParameters.record_iv_length in
 964      * RFC 4346/5246.  It is the size of explicit IV for CBC mode, and the
 965      * size of explicit nonce for AEAD mode.
 966      *
 967      * @param  authenticator the authenticator to get the additional
 968      *         authentication data
 969      * @param  contentType the content type of the input record
 970      * @param  buf the byte array to get the explicit nonce from
 971      * @param  offset the offset of the byte buffer
 972      * @param  cipheredLength the ciphered fragment length of the output
 973      *         record, it is the TLSCiphertext.length in RFC 4346/5246.
 974      *
 975      * @return the explicit nonce size of the cipher.
 976      */
 977     int applyExplicitNonce(Authenticator authenticator,
 978             byte contentType, byte[] buf, int offset,
 979             int cipheredLength) throws BadPaddingException {
 980 
 981         ByteBuffer bb = ByteBuffer.wrap(buf, offset, cipheredLength);
 982 
 983         return applyExplicitNonce(authenticator, contentType, bb);
 984     }
 985 
 986     /*
 987      * Creates the explicit nonce/IV to this cipher. This method is used to
 988      * encrypt an SSL/TLS output record.
 989      *
 990      * The size of the returned array is the SecurityParameters.record_iv_length
 991      * in RFC 4346/5246.  It is the size of explicit IV for CBC mode, and the
 992      * size of explicit nonce for AEAD mode.
 993      *
 994      * @param  authenticator the authenticator to get the additional
 995      *         authentication data
 996      * @param  contentType the content type of the input record
 997      * @param  fragmentLength the fragment length of the output record, it is
 998      *         the TLSCompressed.length in RFC 4346/5246.
 999      *
1000      * @return the explicit nonce of the cipher.
1001      */
1002     byte[] createExplicitNonce(Authenticator authenticator,
1003             byte contentType, int fragmentLength) {
1004 
1005         byte[] nonce = new byte[0];
1006         switch (cipherType) {
1007             case BLOCK_CIPHER:
1008                 if (protocolVersion.v >= ProtocolVersion.TLS11.v) {
1009                     // For block ciphers, the explicit IV length is of length
1010                     // SecurityParameters.record_iv_length, which is equal to
1011                     // the SecurityParameters.block_size.
1012                     //
1013                     // Generate a random number as the explicit IV parameter.
1014                     nonce = new byte[cipher.getBlockSize()];
1015                     random.nextBytes(nonce);
1016                 }
1017                 break;
1018             case AEAD_CIPHER:
1019                 // To be unique and aware of overflow-wrap, sequence number
1020                 // is used as the nonce_explicit of AEAD cipher suites.
1021                 nonce = authenticator.sequenceNumber();
1022 
1023                 // initialize the AEAD cipher for the unique IV
1024                 byte[] iv = Arrays.copyOf(fixedIv,
1025                                             fixedIv.length + nonce.length);
1026                 System.arraycopy(nonce, 0, iv, fixedIv.length, nonce.length);
1027                 GCMParameterSpec spec = new GCMParameterSpec(tagSize * 8, iv);
1028                 try {
1029                     cipher.init(mode, key, spec, random);
1030                 } catch (InvalidKeyException |
1031                             InvalidAlgorithmParameterException ikae) {
1032                     // unlikely to happen
1033                     throw new RuntimeException(
1034                                 "invalid key or spec in GCM mode", ikae);
1035                 }
1036 
1037                 // update the additional authentication data
1038                 byte[] aad = authenticator.acquireAuthenticationBytes(
1039                                                 contentType, fragmentLength);
1040                 cipher.updateAAD(aad);
1041                 break;
1042         }
1043 
1044         return nonce;
1045     }
1046 
1047     /*
1048      * Is this cipher available?
1049      *
1050      * This method can only be called by CipherSuite.BulkCipher.isAvailable()
1051      * to test the availability of a cipher suites.  Please DON'T use it in
1052      * other places, otherwise, the behavior may be unexpected because we may
1053      * initialize AEAD cipher improperly in the method.
1054      */
1055     Boolean isAvailable() {
1056         // We won't know whether a cipher for a particular key size is
1057         // available until the cipher is successfully initialized.
1058         //
1059         // We do not initialize AEAD cipher in the constructor.  Need to
1060         // initialize the cipher to ensure that the AEAD mode for a
1061         // particular key size is supported.
1062         if (cipherType == AEAD_CIPHER) {
1063             try {
1064                 Authenticator authenticator =
1065                     new Authenticator(protocolVersion);
1066                 byte[] nonce = authenticator.sequenceNumber();
1067                 byte[] iv = Arrays.copyOf(fixedIv,
1068                                             fixedIv.length + nonce.length);
1069                 System.arraycopy(nonce, 0, iv, fixedIv.length, nonce.length);
1070                 GCMParameterSpec spec = new GCMParameterSpec(tagSize * 8, iv);
1071 
1072                 cipher.init(mode, key, spec, random);
1073             } catch (Exception e) {
1074                 return Boolean.FALSE;
1075             }
1076         }   // Otherwise, we have initialized the cipher in the constructor.
1077 
1078         return Boolean.TRUE;
1079     }
1080 
1081     /**
1082      * Sanity check the length of a fragment before decryption.
1083      *
1084      * In CBC mode, check that the fragment length is one or multiple times
1085      * of the block size of the cipher suite, and is at least one (one is the
1086      * smallest size of padding in CBC mode) bigger than the tag size of the
1087      * MAC algorithm except the explicit IV size for TLS 1.1 or later.
1088      *
1089      * In non-CBC mode, check that the fragment length is not less than the
1090      * tag size of the MAC algorithm.
1091      *
1092      * @return true if the length of a fragment matches above requirements
1093      */
1094     private boolean sanityCheck(int tagLen, int fragmentLen) {
1095         if (!isCBCMode()) {
1096             return fragmentLen >= tagLen;
1097         }
1098 
1099         int blockSize = cipher.getBlockSize();
1100         if ((fragmentLen % blockSize) == 0) {
1101             int minimal = tagLen + 1;
1102             minimal = (minimal >= blockSize) ? minimal : blockSize;
1103             if (protocolVersion.v >= ProtocolVersion.TLS11.v) {
1104                 minimal += blockSize;   // plus the size of the explicit IV
1105             }
1106 
1107             return (fragmentLen >= minimal);
1108         }
1109 
1110         return false;
1111     }
1112 
1113 }