1 /*
   2  * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 
  24 /*
  25  * @test
  26  * @bug 8044860
  27  * @summary Vectors and fixed length fields should be verified
  28  *          for allowed sizes.
  29  * @modules java.base/sun.security.ssl
  30  * @run main/othervm LengthCheckTest
  31  * @key randomness
  32  */
  33 
  34 /**
  35  * A SSLEngine usage example which simplifies the presentation
  36  * by removing the I/O and multi-threading concerns.
  37  *
  38  * The test creates two SSLEngines, simulating a client and server.
  39  * The "transport" layer consists two byte buffers:  think of them
  40  * as directly connected pipes.
  41  *
  42  * Note, this is a *very* simple example: real code will be much more
  43  * involved.  For example, different threading and I/O models could be
  44  * used, transport mechanisms could close unexpectedly, and so on.
  45  *
  46  * When this application runs, notice that several messages
  47  * (wrap/unwrap) pass before any application data is consumed or
  48  * produced.  (For more information, please see the SSL/TLS
  49  * specifications.)  There may several steps for a successful handshake,
  50  * so it's typical to see the following series of operations:
  51  *
  52  *      client          server          message
  53  *      ======          ======          =======
  54  *      wrap()          ...             ClientHello
  55  *      ...             unwrap()        ClientHello
  56  *      ...             wrap()          ServerHello/Certificate
  57  *      unwrap()        ...             ServerHello/Certificate
  58  *      wrap()          ...             ClientKeyExchange
  59  *      wrap()          ...             ChangeCipherSpec
  60  *      wrap()          ...             Finished
  61  *      ...             unwrap()        ClientKeyExchange
  62  *      ...             unwrap()        ChangeCipherSpec
  63  *      ...             unwrap()        Finished
  64  *      ...             wrap()          ChangeCipherSpec
  65  *      ...             wrap()          Finished
  66  *      unwrap()        ...             ChangeCipherSpec
  67  *      unwrap()        ...             Finished
  68  */
  69 
  70 import javax.net.ssl.*;
  71 import javax.net.ssl.SSLEngineResult.*;
  72 import java.io.*;
  73 import java.security.*;
  74 import java.nio.*;
  75 import java.util.List;
  76 import java.util.ArrayList;
  77 import sun.security.ssl.ProtocolVersion;
  78 
  79 public class LengthCheckTest {
  80 
  81     /*
  82      * Enables logging of the SSLEngine operations.
  83      */
  84     private static final boolean logging = true;
  85 
  86     /*
  87      * Enables the JSSE system debugging system property:
  88      *
  89      *     -Djavax.net.debug=all
  90      *
  91      * This gives a lot of low-level information about operations underway,
  92      * including specific handshake messages, and might be best examined
  93      * after gaining some familiarity with this application.
  94      */
  95     private static final boolean debug = false;
  96     private static final boolean dumpBufs = true;
  97 
  98     private final SSLContext sslc;
  99 
 100     private SSLEngine clientEngine;     // client Engine
 101     private ByteBuffer clientOut;       // write side of clientEngine
 102     private ByteBuffer clientIn;        // read side of clientEngine
 103 
 104     private SSLEngine serverEngine;     // server Engine
 105     private ByteBuffer serverOut;       // write side of serverEngine
 106     private ByteBuffer serverIn;        // read side of serverEngine
 107 
 108     private HandshakeTest handshakeTest;
 109 
 110     /*
 111      * For data transport, this example uses local ByteBuffers.  This
 112      * isn't really useful, but the purpose of this example is to show
 113      * SSLEngine concepts, not how to do network transport.
 114      */
 115     private ByteBuffer cTOs;            // "reliable" transport client->server
 116     private ByteBuffer sTOc;            // "reliable" transport server->client
 117 
 118     /*
 119      * The following is to set up the keystores.
 120      */
 121     private static final String pathToStores = "../../../../javax/net/ssl/etc";
 122     private static final String keyStoreFile = "keystore";
 123     private static final String trustStoreFile = "truststore";
 124     private static final String passwd = "passphrase";
 125 
 126     private static final String keyFilename =
 127             System.getProperty("test.src", ".") + "/" + pathToStores +
 128                 "/" + keyStoreFile;
 129     private static final String trustFilename =
 130             System.getProperty("test.src", ".") + "/" + pathToStores +
 131                 "/" + trustStoreFile;
 132 
 133     // Define a few basic TLS record and message types we might need
 134     private static final int TLS_RECTYPE_CCS = 0x14;
 135     private static final int TLS_RECTYPE_ALERT = 0x15;
 136     private static final int TLS_RECTYPE_HANDSHAKE = 0x16;
 137     private static final int TLS_RECTYPE_APPDATA = 0x17;
 138 
 139     private static final int TLS_HS_HELLO_REQUEST = 0x00;
 140     private static final int TLS_HS_CLIENT_HELLO = 0x01;
 141     private static final int TLS_HS_SERVER_HELLO = 0x02;
 142     private static final int TLS_HS_CERTIFICATE = 0x0B;
 143     private static final int TLS_HS_SERVER_KEY_EXCHG = 0x0C;
 144     private static final int TLS_HS_CERT_REQUEST = 0x0D;
 145     private static final int TLS_HS_SERVER_HELLO_DONE = 0x0E;
 146     private static final int TLS_HS_CERT_VERIFY = 0x0F;
 147     private static final int TLS_HS_CLIENT_KEY_EXCHG = 0x10;
 148     private static final int TLS_HS_FINISHED = 0x14;
 149 
 150     // We're not going to define all the alert types in TLS, just
 151     // the ones we think we'll need to reference by name.
 152     private static final int TLS_ALERT_LVL_WARNING = 0x01;
 153     private static final int TLS_ALERT_LVL_FATAL = 0x02;
 154 
 155     private static final int TLS_ALERT_UNEXPECTED_MSG = 0x0A;
 156     private static final int TLS_ALERT_HANDSHAKE_FAILURE = 0x28;
 157     private static final int TLS_ALERT_INTERNAL_ERROR = 0x50;
 158 
 159     public interface HandshakeTest {
 160         void execTest() throws Exception;
 161     }
 162 
 163     public final HandshakeTest servSendLongID = new HandshakeTest() {
 164         @Override
 165         public void execTest() throws Exception {
 166             boolean gotException = false;
 167             SSLEngineResult clientResult;   // results from client's last op
 168             SSLEngineResult serverResult;   // results from server's last op
 169 
 170             log("\n==== Test: Client receives 64-byte session ID ====");
 171 
 172             // Send Client Hello
 173             clientResult = clientEngine.wrap(clientOut, cTOs);
 174             log("client wrap: ", clientResult);
 175             runDelegatedTasks(clientResult, clientEngine);
 176             cTOs.flip();
 177             dumpByteBuffer("CLIENT-TO-SERVER", cTOs);
 178 
 179             // Server consumes Client Hello
 180             serverResult = serverEngine.unwrap(cTOs, serverIn);
 181             log("server unwrap: ", serverResult);
 182             runDelegatedTasks(serverResult, serverEngine);
 183             cTOs.compact();
 184 
 185             // Server generates ServerHello/Cert/Done record
 186             serverResult = serverEngine.wrap(serverOut, sTOc);
 187             log("server wrap: ", serverResult);
 188             runDelegatedTasks(serverResult, serverEngine);
 189             sTOc.flip();
 190 
 191             // Intercept the ServerHello messages and instead send
 192             // one that has a 64-byte session ID.
 193             if (isTlsMessage(sTOc, TLS_RECTYPE_HANDSHAKE,
 194                         TLS_HS_SERVER_HELLO)) {
 195                 ArrayList<ByteBuffer> recList = splitRecord(sTOc);
 196 
 197                 // Use the original ServerHello as a template to craft one
 198                 // with a longer-than-allowed session ID.
 199                 ByteBuffer servHelloBuf =
 200                         createEvilServerHello(recList.get(0), 64);
 201 
 202                 recList.set(0, servHelloBuf);
 203 
 204                 // Now send each ByteBuffer (each being a complete
 205                 // TLS record) into the client-side unwrap.
 206                 for (ByteBuffer bBuf : recList) {
 207                     dumpByteBuffer("SERVER-TO-CLIENT", bBuf);
 208                     try {
 209                         clientResult = clientEngine.unwrap(bBuf, clientIn);
 210                     } catch (SSLProtocolException e) {
 211                         log("Received expected SSLProtocolException: " + e);
 212                         gotException = true;
 213                     }
 214                     log("client unwrap: ", clientResult);
 215                     runDelegatedTasks(clientResult, clientEngine);
 216                 }
 217             } else {
 218                 dumpByteBuffer("SERVER-TO-CLIENT", sTOc);
 219                 log("client unwrap: ", clientResult);
 220                 runDelegatedTasks(clientResult, clientEngine);
 221             }
 222             sTOc.compact();
 223 
 224             // The Client should now send a TLS Alert
 225             clientResult = clientEngine.wrap(clientOut, cTOs);
 226             log("client wrap: ", clientResult);
 227             runDelegatedTasks(clientResult, clientEngine);
 228             cTOs.flip();
 229             dumpByteBuffer("CLIENT-TO-SERVER", cTOs);
 230 
 231             // At this point we can verify that both an exception
 232             // was thrown and the proper action (a TLS alert) was
 233             // sent back to the server.
 234             if (gotException == false ||
 235                 !isTlsMessage(cTOs, TLS_RECTYPE_ALERT, TLS_ALERT_LVL_FATAL,
 236                         TLS_ALERT_INTERNAL_ERROR)) {
 237                 throw new SSLException(
 238                     "Client failed to throw Alert:fatal:internal_error");
 239             }
 240         }
 241     };
 242 
 243     public final HandshakeTest clientSendLongID = new HandshakeTest() {
 244         @Override
 245         public void execTest() throws Exception {
 246             boolean gotException = false;
 247             SSLEngineResult clientResult;   // results from client's last op
 248             SSLEngineResult serverResult;   // results from server's last op
 249 
 250             log("\n==== Test: Server receives 64-byte session ID ====");
 251 
 252             // Send Client Hello
 253             ByteBuffer evilClientHello = createEvilClientHello(64);
 254             dumpByteBuffer("CLIENT-TO-SERVER", evilClientHello);
 255 
 256             try {
 257                 // Server consumes Client Hello
 258                 serverResult = serverEngine.unwrap(evilClientHello, serverIn);
 259                 log("server unwrap: ", serverResult);
 260                 runDelegatedTasks(serverResult, serverEngine);
 261                 evilClientHello.compact();
 262 
 263                 // Under normal circumstances this should be a ServerHello
 264                 // But should throw an exception instead due to the invalid
 265                 // session ID.
 266                 serverResult = serverEngine.wrap(serverOut, sTOc);
 267                 log("server wrap: ", serverResult);
 268                 runDelegatedTasks(serverResult, serverEngine);
 269                 sTOc.flip();
 270                 dumpByteBuffer("SERVER-TO-CLIENT", sTOc);
 271             } catch (SSLProtocolException ssle) {
 272                 log("Received expected SSLProtocolException: " + ssle);
 273                 gotException = true;
 274             }
 275 
 276             // We expect to see the server generate an alert here
 277             serverResult = serverEngine.wrap(serverOut, sTOc);
 278             log("server wrap: ", serverResult);
 279             runDelegatedTasks(serverResult, serverEngine);
 280             sTOc.flip();
 281             dumpByteBuffer("SERVER-TO-CLIENT", sTOc);
 282 
 283             // At this point we can verify that both an exception
 284             // was thrown and the proper action (a TLS alert) was
 285             // sent back to the client.
 286             if (gotException == false ||
 287                 !isTlsMessage(sTOc, TLS_RECTYPE_ALERT, TLS_ALERT_LVL_FATAL,
 288                         TLS_ALERT_INTERNAL_ERROR)) {
 289                 throw new SSLException(
 290                     "Server failed to throw Alert:fatal:internal_error");
 291             }
 292         }
 293     };
 294 
 295 
 296     /*
 297      * Main entry point for this test.
 298      */
 299     public static void main(String args[]) throws Exception {
 300         List<LengthCheckTest> ccsTests = new ArrayList<>();
 301 
 302         if (debug) {
 303             System.setProperty("javax.net.debug", "ssl");
 304         }
 305 
 306         ccsTests.add(new LengthCheckTest("ServSendLongID"));
 307         ccsTests.add(new LengthCheckTest("ClientSendLongID"));
 308 
 309         for (LengthCheckTest test : ccsTests) {
 310             test.runTest();
 311         }
 312 
 313         System.out.println("Test Passed.");
 314     }
 315 
 316     /*
 317      * Create an initialized SSLContext to use for these tests.
 318      */
 319     public LengthCheckTest(String testName) throws Exception {
 320 
 321         KeyStore ks = KeyStore.getInstance("JKS");
 322         KeyStore ts = KeyStore.getInstance("JKS");
 323 
 324         char[] passphrase = "passphrase".toCharArray();
 325 
 326         ks.load(new FileInputStream(keyFilename), passphrase);
 327         ts.load(new FileInputStream(trustFilename), passphrase);
 328 
 329         KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
 330         kmf.init(ks, passphrase);
 331 
 332         TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
 333         tmf.init(ts);
 334 
 335         SSLContext sslCtx = SSLContext.getInstance("TLS");
 336 
 337         sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
 338 
 339         sslc = sslCtx;
 340 
 341         switch (testName) {
 342             case "ServSendLongID":
 343                 handshakeTest = servSendLongID;
 344                 break;
 345             case "ClientSendLongID":
 346                 handshakeTest = clientSendLongID;
 347                 break;
 348             default:
 349                 throw new IllegalArgumentException("Unknown test name: " +
 350                         testName);
 351         }
 352     }
 353 
 354     /*
 355      * Run the test.
 356      *
 357      * Sit in a tight loop, both engines calling wrap/unwrap regardless
 358      * of whether data is available or not.  We do this until both engines
 359      * report back they are closed.
 360      *
 361      * The main loop handles all of the I/O phases of the SSLEngine's
 362      * lifetime:
 363      *
 364      *     initial handshaking
 365      *     application data transfer
 366      *     engine closing
 367      *
 368      * One could easily separate these phases into separate
 369      * sections of code.
 370      */
 371     private void runTest() throws Exception {
 372         boolean dataDone = false;
 373 
 374         createSSLEngines();
 375         createBuffers();
 376 
 377         handshakeTest.execTest();
 378     }
 379 
 380     /*
 381      * Using the SSLContext created during object creation,
 382      * create/configure the SSLEngines we'll use for this test.
 383      */
 384     private void createSSLEngines() throws Exception {
 385         /*
 386          * Configure the serverEngine to act as a server in the SSL/TLS
 387          * handshake.  Also, require SSL client authentication.
 388          */
 389         serverEngine = sslc.createSSLEngine();
 390         serverEngine.setUseClientMode(false);
 391         serverEngine.setNeedClientAuth(false);
 392 
 393         /*
 394          * Similar to above, but using client mode instead.
 395          */
 396         clientEngine = sslc.createSSLEngine("client", 80);
 397         clientEngine.setUseClientMode(true);
 398 
 399         // In order to make a test that will be backwards compatible
 400         // going back to JDK 5, force the handshake to be TLS 1.0 and
 401         // use one of the older cipher suites.
 402         clientEngine.setEnabledProtocols(new String[]{"TLSv1"});
 403         clientEngine.setEnabledCipherSuites(
 404                 new String[]{"TLS_RSA_WITH_AES_128_CBC_SHA"});
 405     }
 406 
 407     /*
 408      * Create and size the buffers appropriately.
 409      */
 410     private void createBuffers() {
 411 
 412         /*
 413          * We'll assume the buffer sizes are the same
 414          * between client and server.
 415          */
 416         SSLSession session = clientEngine.getSession();
 417         int appBufferMax = session.getApplicationBufferSize();
 418         int netBufferMax = session.getPacketBufferSize();
 419 
 420         /*
 421          * We'll make the input buffers a bit bigger than the max needed
 422          * size, so that unwrap()s following a successful data transfer
 423          * won't generate BUFFER_OVERFLOWS.
 424          *
 425          * We'll use a mix of direct and indirect ByteBuffers for
 426          * tutorial purposes only.  In reality, only use direct
 427          * ByteBuffers when they give a clear performance enhancement.
 428          */
 429         clientIn = ByteBuffer.allocate(appBufferMax + 50);
 430         serverIn = ByteBuffer.allocate(appBufferMax + 50);
 431 
 432         cTOs = ByteBuffer.allocateDirect(netBufferMax);
 433         sTOc = ByteBuffer.allocateDirect(netBufferMax);
 434 
 435         clientOut = ByteBuffer.wrap("Hi Server, I'm Client".getBytes());
 436         serverOut = ByteBuffer.wrap("Hello Client, I'm Server".getBytes());
 437     }
 438 
 439     /*
 440      * If the result indicates that we have outstanding tasks to do,
 441      * go ahead and run them in this thread.
 442      */
 443     private static void runDelegatedTasks(SSLEngineResult result,
 444             SSLEngine engine) throws Exception {
 445 
 446         if (result.getHandshakeStatus() == HandshakeStatus.NEED_TASK) {
 447             Runnable runnable;
 448             while ((runnable = engine.getDelegatedTask()) != null) {
 449                 log("\trunning delegated task...");
 450                 runnable.run();
 451             }
 452             HandshakeStatus hsStatus = engine.getHandshakeStatus();
 453             if (hsStatus == HandshakeStatus.NEED_TASK) {
 454                 throw new Exception(
 455                     "handshake shouldn't need additional tasks");
 456             }
 457             log("\tnew HandshakeStatus: " + hsStatus);
 458         }
 459     }
 460 
 461     private static boolean isEngineClosed(SSLEngine engine) {
 462         return (engine.isOutboundDone() && engine.isInboundDone());
 463     }
 464 
 465     /*
 466      * Simple check to make sure everything came across as expected.
 467      */
 468     private static void checkTransfer(ByteBuffer a, ByteBuffer b)
 469             throws Exception {
 470         a.flip();
 471         b.flip();
 472 
 473         if (!a.equals(b)) {
 474             throw new Exception("Data didn't transfer cleanly");
 475         } else {
 476             log("\tData transferred cleanly");
 477         }
 478 
 479         a.position(a.limit());
 480         b.position(b.limit());
 481         a.limit(a.capacity());
 482         b.limit(b.capacity());
 483     }
 484 
 485     /*
 486      * Logging code
 487      */
 488     private static boolean resultOnce = true;
 489 
 490     private static void log(String str, SSLEngineResult result) {
 491         if (!logging) {
 492             return;
 493         }
 494         if (resultOnce) {
 495             resultOnce = false;
 496             System.out.println("The format of the SSLEngineResult is: \n" +
 497                 "\t\"getStatus() / getHandshakeStatus()\" +\n" +
 498                 "\t\"bytesConsumed() / bytesProduced()\"\n");
 499         }
 500         HandshakeStatus hsStatus = result.getHandshakeStatus();
 501         log(str +
 502             result.getStatus() + "/" + hsStatus + ", " +
 503             result.bytesConsumed() + "/" + result.bytesProduced() +
 504             " bytes");
 505         if (hsStatus == HandshakeStatus.FINISHED) {
 506             log("\t...ready for application data");
 507         }
 508     }
 509 
 510     private static void log(String str) {
 511         if (logging) {
 512             System.out.println(str);
 513         }
 514     }
 515 
 516     /**
 517      * Split a record consisting of multiple TLS handshake messages
 518      * into individual TLS records, each one in a ByteBuffer of its own.
 519      *
 520      * @param tlsRecord A ByteBuffer containing the tls record data.
 521      *        The position of the buffer should be at the first byte
 522      *        in the TLS record data.
 523      *
 524      * @return An ArrayList consisting of one or more ByteBuffers.  Each
 525      *         ByteBuffer will contain a single TLS record with one message.
 526      *         That message will be taken from the input record.  The order
 527      *         of the messages in the ArrayList will be the same as they
 528      *         were in the input record.
 529      */
 530     private ArrayList<ByteBuffer> splitRecord(ByteBuffer tlsRecord) {
 531         SSLSession session = clientEngine.getSession();
 532         int netBufferMax = session.getPacketBufferSize();
 533         ArrayList<ByteBuffer> recordList = new ArrayList<>();
 534 
 535         if (tlsRecord.hasRemaining()) {
 536             int type = Byte.toUnsignedInt(tlsRecord.get());
 537             byte ver_major = tlsRecord.get();
 538             byte ver_minor = tlsRecord.get();
 539             int recLen = Short.toUnsignedInt(tlsRecord.getShort());
 540             byte[] newMsgData = null;
 541             while (tlsRecord.hasRemaining()) {
 542                 ByteBuffer newRecord = ByteBuffer.allocateDirect(netBufferMax);
 543                 switch (type) {
 544                     case TLS_RECTYPE_CCS:
 545                     case TLS_RECTYPE_ALERT:
 546                     case TLS_RECTYPE_APPDATA:
 547                         // None of our tests have multiple non-handshake
 548                         // messages coalesced into a single record.
 549                         break;
 550                     case TLS_RECTYPE_HANDSHAKE:
 551                         newMsgData = getHandshakeMessage(tlsRecord);
 552                         break;
 553                 }
 554 
 555                 // Put a new TLS record on the destination ByteBuffer
 556                 newRecord.put((byte)type);
 557                 newRecord.put(ver_major);
 558                 newRecord.put(ver_minor);
 559                 newRecord.putShort((short)newMsgData.length);
 560 
 561                 // Now add the message content itself and attach to the
 562                 // returned ArrayList
 563                 newRecord.put(newMsgData);
 564                 newRecord.flip();
 565                 recordList.add(newRecord);
 566             }
 567         }
 568 
 569         return recordList;
 570     }
 571 
 572     private static ByteBuffer createEvilClientHello(int sessIdLen) {
 573         ByteBuffer newRecord = ByteBuffer.allocateDirect(4096);
 574 
 575         // Lengths will initially be place holders until we determine the
 576         // finished length of the ByteBuffer.  Then we'll go back and scribble
 577         // in the correct lengths.
 578 
 579         newRecord.put((byte)TLS_RECTYPE_HANDSHAKE);     // Record type
 580         newRecord.putShort((short)0x0301);              // Protocol (TLS 1.0)
 581         newRecord.putShort((short)0);                   // Length place holder
 582 
 583         newRecord.putInt(TLS_HS_CLIENT_HELLO << 24);    // HS type and length
 584         newRecord.putShort((short)0x0301);
 585         newRecord.putInt((int)(System.currentTimeMillis() / 1000));
 586         SecureRandom sr = new SecureRandom();
 587         byte[] randBuf = new byte[28];
 588         sr.nextBytes(randBuf);
 589         newRecord.put(randBuf);                         // Client Random
 590         newRecord.put((byte)sessIdLen);                 // Session ID length
 591         if (sessIdLen > 0) {
 592             byte[] sessId = new byte[sessIdLen];
 593             sr.nextBytes(sessId);
 594             newRecord.put(sessId);                      // Session ID
 595         }
 596         newRecord.putShort((short)2);                   // 2 bytes of ciphers
 597         newRecord.putShort((short)0x002F);              // TLS_RSA_AES_CBC_SHA
 598         newRecord.putShort((short)0x0100);              // only null compression
 599         newRecord.putShort((short)5);                   // 5 bytes of extensions
 600         newRecord.putShort((short)0xFF01);              // Renegotiation info
 601         newRecord.putShort((short)1);
 602         newRecord.put((byte)0);                         // No reneg info exts
 603 
 604         // Go back and fill in the correct length values for the record
 605         // and handshake message headers.
 606         int recordLength = newRecord.position();
 607         newRecord.putShort(3, (short)(recordLength - 5));
 608         int newTypeAndLen = (newRecord.getInt(5) & 0xFF000000) |
 609                 ((recordLength - 9) & 0x00FFFFFF);
 610         newRecord.putInt(5, newTypeAndLen);
 611 
 612         newRecord.flip();
 613         return newRecord;
 614     }
 615 
 616     private static ByteBuffer createEvilServerHello(ByteBuffer origHello,
 617             int newSessIdLen) {
 618         if (newSessIdLen < 0 || newSessIdLen > Byte.MAX_VALUE) {
 619             throw new RuntimeException("Length must be 0 <= X <= 127");
 620         }
 621 
 622         ByteBuffer newRecord = ByteBuffer.allocateDirect(4096);
 623         // Copy the bytes from the old hello to the new up to the session ID
 624         // field.  We will go back later and fill in a new length field in
 625         // the record header.  This includes the record header (5 bytes), the
 626         // Handshake message header (4 bytes), protocol version (2 bytes),
 627         // and the random (32 bytes).
 628         ByteBuffer scratchBuffer = origHello.slice();
 629         scratchBuffer.limit(43);
 630         newRecord.put(scratchBuffer);
 631 
 632         // Advance the position in the originial hello buffer past the
 633         // session ID.
 634         origHello.position(43);
 635         int origIDLen = Byte.toUnsignedInt(origHello.get());
 636         if (origIDLen > 0) {
 637             // Skip over the session ID
 638             origHello.position(origHello.position() + origIDLen);
 639         }
 640 
 641         // Now add our own sessionID to the new record
 642         SecureRandom sr = new SecureRandom();
 643         byte[] sessId = new byte[newSessIdLen];
 644         sr.nextBytes(sessId);
 645         newRecord.put((byte)newSessIdLen);
 646         newRecord.put(sessId);
 647 
 648         // Create another slice in the original buffer, based on the position
 649         // past the session ID.  Copy the remaining bytes into the new
 650         // hello buffer.  Then go back and fix up the length
 651         newRecord.put(origHello.slice());
 652 
 653         // Go back and fill in the correct length values for the record
 654         // and handshake message headers.
 655         int recordLength = newRecord.position();
 656         newRecord.putShort(3, (short)(recordLength - 5));
 657         int newTypeAndLen = (newRecord.getInt(5) & 0xFF000000) |
 658                 ((recordLength - 9) & 0x00FFFFFF);
 659         newRecord.putInt(5, newTypeAndLen);
 660 
 661         newRecord.flip();
 662         return newRecord;
 663     }
 664 
 665     /**
 666      * Look at an incoming TLS record and see if it is the desired
 667      * record type, and where appropriate the correct subtype.
 668      *
 669      * @param srcRecord The input TLS record to be evaluated.  This
 670      *        method will only look at the leading message if multiple
 671      *        TLS handshake messages are coalesced into a single record.
 672      * @param reqRecType The requested TLS record type
 673      * @param recParams Zero or more integer sub type fields.  For CCS
 674      *        and ApplicationData, no params are used.  For handshake records,
 675      *        one value corresponding to the HandshakeType is required.
 676      *        For Alerts, two values corresponding to AlertLevel and
 677      *        AlertDescription are necessary.
 678      *
 679      * @return true if the proper handshake message is the first one
 680      *         in the input record, false otherwise.
 681      */
 682     private boolean isTlsMessage(ByteBuffer srcRecord, int reqRecType,
 683             int... recParams) {
 684         boolean foundMsg = false;
 685 
 686         if (srcRecord.hasRemaining()) {
 687             srcRecord.mark();
 688 
 689             // Grab the fields from the TLS Record
 690             int recordType = Byte.toUnsignedInt(srcRecord.get());
 691             byte ver_major = srcRecord.get();
 692             byte ver_minor = srcRecord.get();
 693             int recLen = Short.toUnsignedInt(srcRecord.getShort());
 694 
 695             if (recordType == reqRecType) {
 696                 // For any zero-length recParams, making sure the requested
 697                 // type is sufficient.
 698                 if (recParams.length == 0) {
 699                     foundMsg = true;
 700                 } else {
 701                     switch (recordType) {
 702                         case TLS_RECTYPE_CCS:
 703                         case TLS_RECTYPE_APPDATA:
 704                             // We really shouldn't find ourselves here, but
 705                             // if someone asked for these types and had more
 706                             // recParams we can ignore them.
 707                             foundMsg = true;
 708                             break;
 709                         case TLS_RECTYPE_ALERT:
 710                             // Needs two params, AlertLevel and AlertDescription
 711                             if (recParams.length != 2) {
 712                                 throw new RuntimeException(
 713                                     "Test for Alert requires level and desc.");
 714                             } else {
 715                                 int level = Byte.toUnsignedInt(srcRecord.get());
 716                                 int desc = Byte.toUnsignedInt(srcRecord.get());
 717                                 if (level == recParams[0] &&
 718                                         desc == recParams[1]) {
 719                                     foundMsg = true;
 720                                 }
 721                             }
 722                             break;
 723                         case TLS_RECTYPE_HANDSHAKE:
 724                             // Needs one parameter, HandshakeType
 725                             if (recParams.length != 1) {
 726                                 throw new RuntimeException(
 727                                     "Test for Handshake requires only HS type");
 728                             } else {
 729                                 // Go into the first handhshake message in the
 730                                 // record and grab the handshake message header.
 731                                 // All we need to do is parse out the leading
 732                                 // byte.
 733                                 int msgHdr = srcRecord.getInt();
 734                                 int msgType = (msgHdr >> 24) & 0x000000FF;
 735                                 if (msgType == recParams[0]) {
 736                                 foundMsg = true;
 737                             }
 738                         }
 739                         break;
 740                     }
 741                 }
 742             }
 743 
 744             srcRecord.reset();
 745         }
 746 
 747         return foundMsg;
 748     }
 749 
 750     private byte[] getHandshakeMessage(ByteBuffer srcRecord) {
 751         // At the start of this routine, the position should be lined up
 752         // at the first byte of a handshake message.  Mark this location
 753         // so we can return to it after reading the type and length.
 754         srcRecord.mark();
 755         int msgHdr = srcRecord.getInt();
 756         int type = (msgHdr >> 24) & 0x000000FF;
 757         int length = msgHdr & 0x00FFFFFF;
 758 
 759         // Create a byte array that has enough space for the handshake
 760         // message header and body.
 761         byte[] data = new byte[length + 4];
 762         srcRecord.reset();
 763         srcRecord.get(data, 0, length + 4);
 764 
 765         return (data);
 766     }
 767 
 768     /**
 769      * Hex-dumps a ByteBuffer to stdout.
 770      */
 771     private static void dumpByteBuffer(String header, ByteBuffer bBuf) {
 772         if (dumpBufs == false) {
 773             return;
 774         }
 775 
 776         int bufLen = bBuf.remaining();
 777         if (bufLen > 0) {
 778             bBuf.mark();
 779 
 780             // We expect the position of the buffer to be at the
 781             // beginning of a TLS record.  Get the type, version and length.
 782             int type = Byte.toUnsignedInt(bBuf.get());
 783             int ver_major = Byte.toUnsignedInt(bBuf.get());
 784             int ver_minor = Byte.toUnsignedInt(bBuf.get());
 785             int recLen = Short.toUnsignedInt(bBuf.getShort());
 786             ProtocolVersion pv = ProtocolVersion.valueOf(ver_major, ver_minor);
 787 
 788             log("===== " + header + " (" + tlsRecType(type) + " / " +
 789                 pv + " / " + bufLen + " bytes) =====");
 790             bBuf.reset();
 791             for (int i = 0; i < bufLen; i++) {
 792                 if (i != 0 && i % 16 == 0) {
 793                     System.out.print("\n");
 794                 }
 795                 System.out.format("%02X ", bBuf.get(i));
 796             }
 797             log("\n===============================================");
 798             bBuf.reset();
 799         }
 800     }
 801 
 802     private static String tlsRecType(int type) {
 803         switch (type) {
 804             case 20:
 805                 return "Change Cipher Spec";
 806             case 21:
 807                 return "Alert";
 808             case 22:
 809                 return "Handshake";
 810             case 23:
 811                 return "Application Data";
 812             default:
 813                 return ("Unknown (" + type + ")");
 814         }
 815     }
 816 }