1 /*
   2  * Copyright (c) 2003, 2014, 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 package sun.security.ssl;
  27 
  28 import java.io.*;
  29 import java.nio.*;
  30 import java.nio.ReadOnlyBufferException;
  31 import java.util.LinkedList;
  32 import java.security.*;
  33 
  34 import javax.crypto.BadPaddingException;
  35 
  36 import javax.net.ssl.*;
  37 import javax.net.ssl.SSLEngineResult.*;
  38 
  39 import com.sun.net.ssl.internal.ssl.X509ExtendedTrustManager;
  40 
  41 /**
  42  * Implementation of an non-blocking SSLEngine.
  43  *
  44  * *Currently*, the SSLEngine code exists in parallel with the current
  45  * SSLSocket.  As such, the current implementation is using legacy code
  46  * with many of the same abstractions.  However, it varies in many
  47  * areas, most dramatically in the IO handling.
  48  *
  49  * There are three main I/O threads that can be existing in parallel:
  50  * wrap(), unwrap(), and beginHandshake().  We are encouraging users to
  51  * not call multiple instances of wrap or unwrap, because the data could
  52  * appear to flow out of the SSLEngine in a non-sequential order.  We
  53  * take all steps we can to at least make sure the ordering remains
  54  * consistent, but once the calls returns, anything can happen.  For
  55  * example, thread1 and thread2 both call wrap, thread1 gets the first
  56  * packet, thread2 gets the second packet, but thread2 gets control back
  57  * before thread1, and sends the data.  The receiving side would see an
  58  * out-of-order error.
  59  *
  60  * Handshaking is still done the same way as SSLSocket using the normal
  61  * InputStream/OutputStream abstactions.  We create
  62  * ClientHandshakers/ServerHandshakers, which produce/consume the
  63  * handshaking data.  The transfer of the data is largely handled by the
  64  * HandshakeInStream/HandshakeOutStreams.  Lastly, the
  65  * InputRecord/OutputRecords still have the same functionality, except
  66  * that they are overridden with EngineInputRecord/EngineOutputRecord,
  67  * which provide SSLEngine-specific functionality.
  68  *
  69  * Some of the major differences are:
  70  *
  71  * EngineInputRecord/EngineOutputRecord/EngineWriter:
  72  *
  73  *      In order to avoid writing whole new control flows for
  74  *      handshaking, and to reuse most of the same code, we kept most
  75  *      of the actual handshake code the same.  As usual, reading
  76  *      handshake data may trigger output of more handshake data, so
  77  *      what we do is write this data to internal buffers, and wait for
  78  *      wrap() to be called to give that data a ride.
  79  *
  80  *      All data is routed through
  81  *      EngineInputRecord/EngineOutputRecord.  However, all handshake
  82  *      data (ct_alert/ct_change_cipher_spec/ct_handshake) are passed
  83  *      through to the the underlying InputRecord/OutputRecord, and
  84  *      the data uses the internal buffers.
  85  *
  86  *      Application data is handled slightly different, we copy the data
  87  *      directly from the src to the dst buffers, and do all operations
  88  *      on those buffers, saving the overhead of multiple copies.
  89  *
  90  *      In the case of an inbound record, unwrap passes the inbound
  91  *      ByteBuffer to the InputRecord.  If the data is handshake data,
  92  *      the data is read into the InputRecord's internal buffer.  If
  93  *      the data is application data, the data is decoded directly into
  94  *      the dst buffer.
  95  *
  96  *      In the case of an outbound record, when the write to the
  97  *      "real" OutputStream's would normally take place, instead we
  98  *      call back up to the EngineOutputRecord's version of
  99  *      writeBuffer, at which time we capture the resulting output in a
 100  *      ByteBuffer, and send that back to the EngineWriter for internal
 101  *      storage.
 102  *
 103  *      EngineWriter is responsible for "handling" all outbound
 104  *      data, be it handshake or app data, and for returning the data
 105  *      to wrap() in the proper order.
 106  *
 107  * ClientHandshaker/ServerHandshaker/Handshaker:
 108  *      Methods which relied on SSLSocket now have work on either
 109  *      SSLSockets or SSLEngines.
 110  *
 111  * @author Brad Wetmore
 112  */
 113 final public class SSLEngineImpl extends SSLEngine {
 114 
 115     //
 116     // Fields and global comments
 117     //
 118 
 119     /*
 120      * There's a state machine associated with each connection, which
 121      * among other roles serves to negotiate session changes.
 122      *
 123      * - START with constructor, until the TCP connection's around.
 124      * - HANDSHAKE picks session parameters before allowing traffic.
 125      *          There are many substates due to sequencing requirements
 126      *          for handshake messages.
 127      * - DATA may be transmitted.
 128      * - RENEGOTIATE state allows concurrent data and handshaking
 129      *          traffic ("same" substates as HANDSHAKE), and terminates
 130      *          in selection of new session (and connection) parameters
 131      * - ERROR state immediately precedes abortive disconnect.
 132      * - CLOSED when one side closes down, used to start the shutdown
 133      *          process.  SSL connection objects are not reused.
 134      *
 135      * State affects what SSL record types may legally be sent:
 136      *
 137      * - Handshake ... only in HANDSHAKE and RENEGOTIATE states
 138      * - App Data ... only in DATA and RENEGOTIATE states
 139      * - Alert ... in HANDSHAKE, DATA, RENEGOTIATE
 140      *
 141      * Re what may be received:  same as what may be sent, except that
 142      * HandshakeRequest handshaking messages can come from servers even
 143      * in the application data state, to request entry to RENEGOTIATE.
 144      *
 145      * The state machine within HANDSHAKE and RENEGOTIATE states controls
 146      * the pending session, not the connection state, until the change
 147      * cipher spec and "Finished" handshake messages are processed and
 148      * make the "new" session become the current one.
 149      *
 150      * NOTE: details of the SMs always need to be nailed down better.
 151      * The text above illustrates the core ideas.
 152      *
 153      *                +---->-------+------>--------->-------+
 154      *                |            |                        |
 155      *     <-----<    ^            ^  <-----<               |
 156      *START>----->HANDSHAKE>----->DATA>----->RENEGOTIATE    |
 157      *                v            v               v        |
 158      *                |            |               |        |
 159      *                +------------+---------------+        |
 160      *                |                                     |
 161      *                v                                     |
 162      *               ERROR>------>----->CLOSED<--------<----+
 163      *
 164      * ALSO, note that the the purpose of handshaking (renegotiation is
 165      * included) is to assign a different, and perhaps new, session to
 166      * the connection.  The SSLv3 spec is a bit confusing on that new
 167      * protocol feature.
 168      */
 169     private int                 connectionState;
 170 
 171     private static final int    cs_START = 0;
 172     private static final int    cs_HANDSHAKE = 1;
 173     private static final int    cs_DATA = 2;
 174     private static final int    cs_RENEGOTIATE = 3;
 175     private static final int    cs_ERROR = 4;
 176     private static final int    cs_CLOSED = 6;
 177 
 178     /*
 179      * Once we're in state cs_CLOSED, we can continue to
 180      * wrap/unwrap until we finish sending/receiving the messages
 181      * for close_notify.  EngineWriter handles outboundDone.
 182      */
 183     private boolean             inboundDone = false;
 184 
 185     EngineWriter                writer;
 186 
 187     /*
 188      * The authentication context holds all information used to establish
 189      * who this end of the connection is (certificate chains, private keys,
 190      * etc) and who is trusted (e.g. as CAs or websites).
 191      */
 192     private SSLContextImpl      sslContext;
 193 
 194     /*
 195      * This connection is one of (potentially) many associated with
 196      * any given session.  The output of the handshake protocol is a
 197      * new session ... although all the protocol description talks
 198      * about changing the cipher spec (and it does change), in fact
 199      * that's incidental since it's done by changing everything that
 200      * is associated with a session at the same time.  (TLS/IETF may
 201      * change that to add client authentication w/o new key exchg.)
 202      */
 203     private SSLSessionImpl      sess;
 204     private Handshaker          handshaker;
 205 
 206     /*
 207      * Client authentication be off, requested, or required.
 208      *
 209      * This will be used by both this class and SSLSocket's variants.
 210      */
 211     static final byte           clauth_none = 0;
 212     static final byte           clauth_requested = 1;
 213     static final byte           clauth_required = 2;
 214 
 215     /*
 216      * Flag indicating that the engine has received a ChangeCipherSpec message.
 217      */
 218     private boolean             receivedCCS;
 219 
 220     /*
 221      * Flag indicating if the next record we receive MUST be a Finished
 222      * message. Temporarily set during the handshake to ensure that
 223      * a change cipher spec message is followed by a finished message.
 224      */
 225     private boolean             expectingFinished;
 226 
 227 
 228     /*
 229      * If someone tries to closeInbound() (say at End-Of-Stream)
 230      * our engine having received a close_notify, we need to
 231      * notify the app that we may have a truncation attack underway.
 232      */
 233     private boolean             recvCN;
 234 
 235     /*
 236      * For improved diagnostics, we detail connection closure
 237      * If the engine is closed (connectionState >= cs_ERROR),
 238      * closeReason != null indicates if the engine was closed
 239      * because of an error or because or normal shutdown.
 240      */
 241     private SSLException        closeReason;
 242 
 243     /*
 244      * Per-connection private state that doesn't change when the
 245      * session is changed.
 246      */
 247     private byte                        doClientAuth;
 248     private boolean                     enableSessionCreation = true;
 249     EngineInputRecord                   inputRecord;
 250     EngineOutputRecord                  outputRecord;
 251     private AccessControlContext        acc;
 252 
 253     // The cipher suites enabled for use on this connection.
 254     private CipherSuiteList             enabledCipherSuites;
 255 
 256     // hostname identification algorithm, the hostname identification is
 257     // disabled by default.
 258     private String                      identificationAlg = null;
 259 
 260     // Have we been told whether we're client or server?
 261     private boolean                     serverModeSet = false;
 262     private boolean                     roleIsServer;
 263 
 264     /*
 265      * The protocol versions enabled for use on this connection.
 266      *
 267      * Note: we support a pseudo protocol called SSLv2Hello which when
 268      * set will result in an SSL v2 Hello being sent with SSL (version 3.0)
 269      * or TLS (version 3.1, 3.2, etc.) version info.
 270      */
 271     private ProtocolList        enabledProtocols;
 272 
 273     /*
 274      * The SSL version associated with this connection.
 275      */
 276     private ProtocolVersion     protocolVersion = ProtocolVersion.DEFAULT;
 277 
 278     /*
 279      * Crypto state that's reinitialized when the session changes.
 280      */
 281     private MAC                 readMAC, writeMAC;
 282     private CipherBox           readCipher, writeCipher;
 283     // NOTE: compression state would be saved here
 284 
 285     /*
 286      * security parameters for secure renegotiation.
 287      */
 288     private boolean             secureRenegotiation;
 289     private byte[]              clientVerifyData;
 290     private byte[]              serverVerifyData;
 291 
 292     /*
 293      * READ ME * READ ME * READ ME * READ ME * READ ME * READ ME *
 294      * IMPORTANT STUFF TO UNDERSTANDING THE SYNCHRONIZATION ISSUES.
 295      * READ ME * READ ME * READ ME * READ ME * READ ME * READ ME *
 296      *
 297      * There are several locks here.
 298      *
 299      * The primary lock is the per-instance lock used by
 300      * synchronized(this) and the synchronized methods.  It controls all
 301      * access to things such as the connection state and variables which
 302      * affect handshaking.  If we are inside a synchronized method, we
 303      * can access the state directly, otherwise, we must use the
 304      * synchronized equivalents.
 305      *
 306      * Note that we must never acquire the <code>this</code> lock after
 307      * <code>writeLock</code> or run the risk of deadlock.
 308      *
 309      * Grab some coffee, and be careful with any code changes.
 310      */
 311     private Object              wrapLock;
 312     private Object              unwrapLock;
 313     Object                      writeLock;
 314 
 315     /*
 316      * Is it the first application record to write?
 317      */
 318     private boolean isFirstAppOutputRecord = true;
 319 
 320     /*
 321      * Class and subclass dynamic debugging support
 322      */
 323     private static final Debug debug = Debug.getInstance("ssl");
 324 
 325     //
 326     // Initialization/Constructors
 327     //
 328 
 329     /**
 330      * Constructor for an SSLEngine from SSLContext, without
 331      * host/port hints.  This Engine will not be able to cache
 332      * sessions, but must renegotiate everything by hand.
 333      */
 334     SSLEngineImpl(SSLContextImpl ctx) {
 335         super();
 336         init(ctx);
 337     }
 338 
 339     /**
 340      * Constructor for an SSLEngine from SSLContext.
 341      */
 342     SSLEngineImpl(SSLContextImpl ctx, String host, int port) {
 343         super(host, port);
 344         init(ctx);
 345     }
 346 
 347     /**
 348      * Initializes the Engine
 349      */
 350     private void init(SSLContextImpl ctx) {
 351         if (debug != null && Debug.isOn("ssl")) {
 352             System.out.println("Using SSLEngineImpl.");
 353         }
 354 
 355         sslContext = ctx;
 356         sess = SSLSessionImpl.nullSession;
 357 
 358         /*
 359          * State is cs_START until we initialize the handshaker.
 360          *
 361          * Apps using SSLEngine are probably going to be server.
 362          * Somewhat arbitrary choice.
 363          */
 364         roleIsServer = true;
 365         connectionState = cs_START;
 366         receivedCCS = false;
 367 
 368         /*
 369          * default read and write side cipher and MAC support
 370          *
 371          * Note:  compression support would go here too
 372          */
 373         readCipher = CipherBox.NULL;
 374         readMAC = MAC.NULL;
 375         writeCipher = CipherBox.NULL;
 376         writeMAC = MAC.NULL;
 377 
 378         // default security parameters for secure renegotiation
 379         secureRenegotiation = false;
 380         clientVerifyData = new byte[0];
 381         serverVerifyData = new byte[0];
 382 
 383         enabledCipherSuites =
 384                 sslContext.getDefaultCipherSuiteList(roleIsServer);
 385         enabledProtocols =
 386                 sslContext.getDefaultProtocolList(roleIsServer);
 387 
 388         wrapLock = new Object();
 389         unwrapLock = new Object();
 390         writeLock = new Object();
 391 
 392         /*
 393          * Save the Access Control Context.  This will be used later
 394          * for a couple of things, including providing a context to
 395          * run tasks in, and for determining which credentials
 396          * to use for Subject based (JAAS) decisions
 397          */
 398         acc = AccessController.getContext();
 399 
 400         /*
 401          * All outbound application data goes through this OutputRecord,
 402          * other data goes through their respective records created
 403          * elsewhere.  All inbound data goes through this one
 404          * input record.
 405          */
 406         outputRecord =
 407             new EngineOutputRecord(Record.ct_application_data, this);
 408         inputRecord = new EngineInputRecord(this);
 409         inputRecord.enableFormatChecks();
 410 
 411         writer = new EngineWriter();
 412     }
 413 
 414     /**
 415      * Initialize the handshaker object. This means:
 416      *
 417      *  . if a handshake is already in progress (state is cs_HANDSHAKE
 418      *    or cs_RENEGOTIATE), do nothing and return
 419      *
 420      *  . if the engine is already closed, throw an Exception (internal error)
 421      *
 422      *  . otherwise (cs_START or cs_DATA), create the appropriate handshaker
 423      *    object and advance the connection state (to cs_HANDSHAKE or
 424      *    cs_RENEGOTIATE, respectively).
 425      *
 426      * This method is called right after a new engine is created, when
 427      * starting renegotiation, or when changing client/server mode of the
 428      * engine.
 429      */
 430     private void initHandshaker() {
 431         switch (connectionState) {
 432 
 433         //
 434         // Starting a new handshake.
 435         //
 436         case cs_START:
 437         case cs_DATA:
 438             break;
 439 
 440         //
 441         // We're already in the middle of a handshake.
 442         //
 443         case cs_HANDSHAKE:
 444         case cs_RENEGOTIATE:
 445             return;
 446 
 447         //
 448         // Anyone allowed to call this routine is required to
 449         // do so ONLY if the connection state is reasonable...
 450         //
 451         default:
 452             throw new IllegalStateException("Internal error");
 453         }
 454 
 455         // state is either cs_START or cs_DATA
 456         if (connectionState == cs_START) {
 457             connectionState = cs_HANDSHAKE;
 458         } else { // cs_DATA
 459             connectionState = cs_RENEGOTIATE;
 460         }
 461         if (roleIsServer) {
 462             handshaker = new ServerHandshaker(this, sslContext,
 463                     enabledProtocols, doClientAuth,
 464                     protocolVersion, connectionState == cs_HANDSHAKE,
 465                     secureRenegotiation, clientVerifyData, serverVerifyData);
 466         } else {
 467             handshaker = new ClientHandshaker(this, sslContext,
 468                     enabledProtocols,
 469                     protocolVersion, connectionState == cs_HANDSHAKE,
 470                     secureRenegotiation, clientVerifyData, serverVerifyData);
 471         }
 472         handshaker.setEnabledCipherSuites(enabledCipherSuites);
 473         handshaker.setEnableSessionCreation(enableSessionCreation);
 474     }
 475 
 476     /*
 477      * Report the current status of the Handshaker
 478      */
 479     private HandshakeStatus getHSStatus(HandshakeStatus hss) {
 480 
 481         if (hss != null) {
 482             return hss;
 483         }
 484 
 485         synchronized (this) {
 486             if (writer.hasOutboundData()) {
 487                 return HandshakeStatus.NEED_WRAP;
 488             } else if (handshaker != null) {
 489                 if (handshaker.taskOutstanding()) {
 490                     return HandshakeStatus.NEED_TASK;
 491                 } else {
 492                     return HandshakeStatus.NEED_UNWRAP;
 493                 }
 494             } else if (connectionState == cs_CLOSED) {
 495                 /*
 496                  * Special case where we're closing, but
 497                  * still need the close_notify before we
 498                  * can officially be closed.
 499                  *
 500                  * Note isOutboundDone is taken care of by
 501                  * hasOutboundData() above.
 502                  */
 503                 if (!isInboundDone()) {
 504                     return HandshakeStatus.NEED_UNWRAP;
 505                 } // else not handshaking
 506             }
 507 
 508             return HandshakeStatus.NOT_HANDSHAKING;
 509         }
 510     }
 511 
 512     synchronized private void checkTaskThrown() throws SSLException {
 513         if (handshaker != null) {
 514             handshaker.checkThrown();
 515         }
 516     }
 517 
 518     //
 519     // Handshaking and connection state code
 520     //
 521 
 522     /*
 523      * Provides "this" synchronization for connection state.
 524      * Otherwise, you can access it directly.
 525      */
 526     synchronized private int getConnectionState() {
 527         return connectionState;
 528     }
 529 
 530     synchronized private void setConnectionState(int state) {
 531         connectionState = state;
 532     }
 533 
 534     /*
 535      * Get the Access Control Context.
 536      *
 537      * Used for a known context to
 538      * run tasks in, and for determining which credentials
 539      * to use for Subject-based (JAAS) decisions.
 540      */
 541     AccessControlContext getAcc() {
 542         return acc;
 543     }
 544 
 545     /*
 546      * Is a handshake currently underway?
 547      */
 548     public SSLEngineResult.HandshakeStatus getHandshakeStatus() {
 549         return getHSStatus(null);
 550     }
 551 
 552     /*
 553      * When a connection finishes handshaking by enabling use of a newly
 554      * negotiated session, each end learns about it in two halves (read,
 555      * and write).  When both read and write ciphers have changed, and the
 556      * last handshake message has been read, the connection has joined
 557      * (rejoined) the new session.
 558      *
 559      * NOTE:  The SSLv3 spec is rather unclear on the concepts here.
 560      * Sessions don't change once they're established (including cipher
 561      * suite and master secret) but connections can join them (and leave
 562      * them).  They're created by handshaking, though sometime handshaking
 563      * causes connections to join up with pre-established sessions.
 564      *
 565      * Synchronized on "this" from readRecord.
 566      */
 567     private void changeReadCiphers() throws SSLException {
 568         if (connectionState != cs_HANDSHAKE
 569                 && connectionState != cs_RENEGOTIATE) {
 570             throw new SSLProtocolException(
 571                 "State error, change cipher specs");
 572         }
 573 
 574         // ... create decompressor
 575 
 576         try {
 577             readCipher = handshaker.newReadCipher();
 578             readMAC = handshaker.newReadMAC();
 579         } catch (GeneralSecurityException e) {
 580             // "can't happen"
 581             throw (SSLException)new SSLException
 582                                 ("Algorithm missing:  ").initCause(e);
 583         }
 584     }
 585 
 586     /*
 587      * used by Handshaker to change the active write cipher, follows
 588      * the output of the CCS message.
 589      *
 590      * Also synchronized on "this" from readRecord/delegatedTask.
 591      */
 592     void changeWriteCiphers() throws SSLException {
 593         if (connectionState != cs_HANDSHAKE
 594                 && connectionState != cs_RENEGOTIATE) {
 595             throw new SSLProtocolException(
 596                 "State error, change cipher specs");
 597         }
 598 
 599         // ... create compressor
 600 
 601         try {
 602             writeCipher = handshaker.newWriteCipher();
 603             writeMAC = handshaker.newWriteMAC();
 604         } catch (GeneralSecurityException e) {
 605             // "can't happen"
 606             throw (SSLException)new SSLException
 607                                 ("Algorithm missing:  ").initCause(e);
 608         }
 609 
 610         // reset the flag of the first application record
 611         isFirstAppOutputRecord = true;
 612     }
 613 
 614     /*
 615      * Updates the SSL version associated with this connection.
 616      * Called from Handshaker once it has determined the negotiated version.
 617      */
 618     synchronized void setVersion(ProtocolVersion protocolVersion) {
 619         this.protocolVersion = protocolVersion;
 620         outputRecord.setVersion(protocolVersion);
 621     }
 622 
 623 
 624     /**
 625      * Kickstart the handshake if it is not already in progress.
 626      * This means:
 627      *
 628      *  . if handshaking is already underway, do nothing and return
 629      *
 630      *  . if the engine is not connected or already closed, throw an
 631      *    Exception.
 632      *
 633      *  . otherwise, call initHandshake() to initialize the handshaker
 634      *    object and progress the state. Then, send the initial
 635      *    handshaking message if appropriate (always on clients and
 636      *    on servers when renegotiating).
 637      */
 638     private synchronized void kickstartHandshake() throws IOException {
 639         switch (connectionState) {
 640 
 641         case cs_START:
 642             if (!serverModeSet) {
 643                 throw new IllegalStateException(
 644                     "Client/Server mode not yet set.");
 645             }
 646             initHandshaker();
 647             break;
 648 
 649         case cs_HANDSHAKE:
 650             // handshaker already setup, proceed
 651             break;
 652 
 653         case cs_DATA:
 654             if (!secureRenegotiation && !Handshaker.allowUnsafeRenegotiation) {
 655                 throw new SSLHandshakeException(
 656                         "Insecure renegotiation is not allowed");
 657             }
 658 
 659             if (!secureRenegotiation) {
 660                 if (debug != null && Debug.isOn("handshake")) {
 661                     System.out.println(
 662                         "Warning: Using insecure renegotiation");
 663                 }
 664             }
 665 
 666             // initialize the handshaker, move to cs_RENEGOTIATE
 667             initHandshaker();
 668             break;
 669 
 670         case cs_RENEGOTIATE:
 671             // handshaking already in progress, return
 672             return;
 673 
 674         default:
 675             // cs_ERROR/cs_CLOSED
 676             throw new SSLException("SSLEngine is closing/closed");
 677         }
 678 
 679         //
 680         // Kickstart handshake state machine if we need to ...
 681         //
 682         // Note that handshaker.kickstart() writes the message
 683         // to its HandshakeOutStream, which calls back into
 684         // SSLSocketImpl.writeRecord() to send it.
 685         //
 686         if (!handshaker.activated()) {
 687              // prior to handshaking, activate the handshake
 688             if (connectionState == cs_RENEGOTIATE) {
 689                 // don't use SSLv2Hello when renegotiating
 690                 handshaker.activate(protocolVersion);
 691             } else {
 692                 handshaker.activate(null);
 693             }
 694 
 695             if (handshaker instanceof ClientHandshaker) {
 696                 // send client hello
 697                 handshaker.kickstart();
 698             } else {    // instanceof ServerHandshaker
 699                 if (connectionState == cs_HANDSHAKE) {
 700                     // initial handshake, no kickstart message to send
 701                 } else {
 702                     // we want to renegotiate, send hello request
 703                     handshaker.kickstart();
 704 
 705                     // hello request is not included in the handshake
 706                     // hashes, reset them
 707                     handshaker.handshakeHash.reset();
 708                 }
 709             }
 710         }
 711     }
 712 
 713     /*
 714      * Start a SSLEngine handshake
 715      */
 716     public void beginHandshake() throws SSLException {
 717         try {
 718             kickstartHandshake();
 719         } catch (Exception e) {
 720             fatal(Alerts.alert_handshake_failure,
 721                 "Couldn't kickstart handshaking", e);
 722         }
 723     }
 724 
 725 
 726     //
 727     // Read/unwrap side
 728     //
 729 
 730 
 731     /**
 732      * Unwraps a buffer.  Does a variety of checks before grabbing
 733      * the unwrapLock, which blocks multiple unwraps from occuring.
 734      */
 735     public SSLEngineResult unwrap(ByteBuffer netData, ByteBuffer [] appData,
 736             int offset, int length) throws SSLException {
 737 
 738         EngineArgs ea = new EngineArgs(netData, appData, offset, length);
 739 
 740         try {
 741             synchronized (unwrapLock) {
 742                 return readNetRecord(ea);
 743             }
 744         } catch (Exception e) {
 745             /*
 746              * Don't reset position so it looks like we didn't
 747              * consume anything.  We did consume something, and it
 748              * got us into this situation, so report that much back.
 749              * Our days of consuming are now over anyway.
 750              */
 751             fatal(Alerts.alert_internal_error,
 752                 "problem wrapping app data", e);
 753             return null;  // make compiler happy
 754         } finally {
 755             /*
 756              * Just in case something failed to reset limits properly.
 757              */
 758             ea.resetLim();
 759         }
 760     }
 761 
 762     /*
 763      * Makes additional checks for unwrap, but this time more
 764      * specific to this packet and the current state of the machine.
 765      */
 766     private SSLEngineResult readNetRecord(EngineArgs ea) throws IOException {
 767 
 768         Status status = null;
 769         HandshakeStatus hsStatus = null;
 770 
 771         /*
 772          * See if the handshaker needs to report back some SSLException.
 773          */
 774         checkTaskThrown();
 775 
 776         /*
 777          * Check if we are closing/closed.
 778          */
 779         if (isInboundDone()) {
 780             return new SSLEngineResult(Status.CLOSED, getHSStatus(null), 0, 0);
 781         }
 782 
 783         /*
 784          * If we're still in cs_HANDSHAKE, make sure it's been
 785          * started.
 786          */
 787         synchronized (this) {
 788             if ((connectionState == cs_HANDSHAKE) ||
 789                     (connectionState == cs_START)) {
 790                 kickstartHandshake();
 791 
 792                 /*
 793                  * If there's still outbound data to flush, we
 794                  * can return without trying to unwrap anything.
 795                  */
 796                 hsStatus = getHSStatus(null);
 797 
 798                 if (hsStatus == HandshakeStatus.NEED_WRAP) {
 799                     return new SSLEngineResult(Status.OK, hsStatus, 0, 0);
 800                 }
 801             }
 802         }
 803 
 804         /*
 805          * Grab a copy of this if it doesn't already exist,
 806          * and we can use it several places before anything major
 807          * happens on this side.  Races aren't critical
 808          * here.
 809          */
 810         if (hsStatus == null) {
 811             hsStatus = getHSStatus(null);
 812         }
 813 
 814         /*
 815          * If we have a task outstanding, this *MUST* be done before
 816          * doing any more unwrapping, because we could be in the middle
 817          * of receiving a handshake message, for example, a finished
 818          * message which would change the ciphers.
 819          */
 820         if (hsStatus == HandshakeStatus.NEED_TASK) {
 821             return new SSLEngineResult(
 822                 Status.OK, hsStatus, 0, 0);
 823         }
 824 
 825         /*
 826          * Check the packet to make sure enough is here.
 827          * This will also indirectly check for 0 len packets.
 828          */
 829         int packetLen = inputRecord.bytesInCompletePacket(ea.netData);
 830 
 831         // Is this packet bigger than SSL/TLS normally allows?
 832         if (packetLen > sess.getPacketBufferSize()) {
 833             if (packetLen > Record.maxLargeRecordSize) {
 834                 throw new SSLProtocolException(
 835                     "Input SSL/TLS record too big: max = " +
 836                     Record.maxLargeRecordSize +
 837                     " len = " + packetLen);
 838             } else {
 839                 // Expand the expected maximum packet/application buffer
 840                 // sizes.
 841                 sess.expandBufferSizes();
 842             }
 843         }
 844 
 845         /*
 846          * Check for OVERFLOW.
 847          *
 848          * To be considered: We could delay enforcing the application buffer
 849          * free space requirement until after the initial handshaking.
 850          */
 851         if ((packetLen - Record.headerSize) > ea.getAppRemaining()) {
 852             return new SSLEngineResult(Status.BUFFER_OVERFLOW, hsStatus, 0, 0);
 853         }
 854 
 855         // check for UNDERFLOW.
 856         if ((packetLen == -1) || (ea.netData.remaining() < packetLen)) {
 857             return new SSLEngineResult(
 858                 Status.BUFFER_UNDERFLOW, hsStatus, 0, 0);
 859         }
 860 
 861         /*
 862          * We're now ready to actually do the read.
 863          * The only result code we really need to be exactly
 864          * right is the HS finished, for signaling to
 865          * HandshakeCompletedListeners.
 866          */
 867         try {
 868             hsStatus = readRecord(ea);
 869         } catch (SSLException e) {
 870             throw e;
 871         } catch (IOException e) {
 872             SSLException ex = new SSLException("readRecord");
 873             ex.initCause(e);
 874             throw ex;
 875         }
 876 
 877         /*
 878          * Check the various condition that we could be reporting.
 879          *
 880          * It's *possible* something might have happened between the
 881          * above and now, but it was better to minimally lock "this"
 882          * during the read process.  We'll return the current
 883          * status, which is more representative of the current state.
 884          *
 885          * status above should cover:  FINISHED, NEED_TASK
 886          */
 887         status = (isInboundDone() ? Status.CLOSED : Status.OK);
 888         hsStatus = getHSStatus(hsStatus);
 889 
 890         return new SSLEngineResult(status, hsStatus,
 891             ea.deltaNet(), ea.deltaApp());
 892     }
 893 
 894     /*
 895      * Actually do the read record processing.
 896      *
 897      * Returns a Status if it can make specific determinations
 898      * of the engine state.  In particular, we need to signal
 899      * that a handshake just completed.
 900      *
 901      * It would be nice to be symmetrical with the write side and move
 902      * the majority of this to EngineInputRecord, but there's too much
 903      * SSLEngine state to do that cleanly.  It must still live here.
 904      */
 905     private HandshakeStatus readRecord(EngineArgs ea) throws IOException {
 906 
 907         HandshakeStatus hsStatus = null;
 908 
 909         /*
 910          * The various operations will return new sliced BB's,
 911          * this will avoid having to worry about positions and
 912          * limits in the netBB.
 913          */
 914         ByteBuffer readBB = null;
 915         ByteBuffer decryptedBB = null;
 916 
 917         if (getConnectionState() != cs_ERROR) {
 918 
 919             /*
 920              * Read a record ... maybe emitting an alert if we get a
 921              * comprehensible but unsupported "hello" message during
 922              * format checking (e.g. V2).
 923              */
 924             try {
 925                 readBB = inputRecord.read(ea.netData);
 926             } catch (IOException e) {
 927                 fatal(Alerts.alert_unexpected_message, e);
 928             }
 929 
 930             /*
 931              * The basic SSLv3 record protection involves (optional)
 932              * encryption for privacy, and an integrity check ensuring
 933              * data origin authentication.  We do them both here, and
 934              * throw a fatal alert if the integrity check fails.
 935              */
 936             try {
 937                 decryptedBB = inputRecord.decrypt(readMAC, readCipher, readBB);
 938             } catch (BadPaddingException e) {
 939                 byte alertType = (inputRecord.contentType() ==
 940                     Record.ct_handshake) ?
 941                         Alerts.alert_handshake_failure :
 942                         Alerts.alert_bad_record_mac;
 943                 fatal(alertType, e.getMessage(), e);
 944             }
 945 
 946             // if (!inputRecord.decompress(c))
 947             //     fatal(Alerts.alert_decompression_failure,
 948             //     "decompression failure");
 949 
 950 
 951             /*
 952              * Process the record.
 953              */
 954 
 955             synchronized (this) {
 956                 switch (inputRecord.contentType()) {
 957                 case Record.ct_handshake:
 958                     /*
 959                      * Handshake messages always go to a pending session
 960                      * handshaker ... if there isn't one, create one.  This
 961                      * must work asynchronously, for renegotiation.
 962                      *
 963                      * NOTE that handshaking will either resume a session
 964                      * which was in the cache (and which might have other
 965                      * connections in it already), or else will start a new
 966                      * session (new keys exchanged) with just this connection
 967                      * in it.
 968                      */
 969                     initHandshaker();
 970                     if (!handshaker.activated()) {
 971                         // prior to handshaking, activate the handshake
 972                         if (connectionState == cs_RENEGOTIATE) {
 973                             // don't use SSLv2Hello when renegotiating
 974                             handshaker.activate(protocolVersion);
 975                         } else {
 976                             handshaker.activate(null);
 977                         }
 978                     }
 979 
 980                     /*
 981                      * process the handshake record ... may contain just
 982                      * a partial handshake message or multiple messages.
 983                      *
 984                      * The handshaker state machine will ensure that it's
 985                      * a finished message.
 986                      */
 987                     handshaker.process_record(inputRecord, expectingFinished);
 988                     expectingFinished = false;
 989 
 990                     if (handshaker.invalidated) {
 991                         handshaker = null;
 992                         receivedCCS = false;
 993                         // if state is cs_RENEGOTIATE, revert it to cs_DATA
 994                         if (connectionState == cs_RENEGOTIATE) {
 995                             connectionState = cs_DATA;
 996                         }
 997                     } else if (handshaker.isDone()) {
 998                         // reset the parameters for secure renegotiation.
 999                         secureRenegotiation =
1000                                         handshaker.isSecureRenegotiation();
1001                         clientVerifyData = handshaker.getClientVerifyData();
1002                         serverVerifyData = handshaker.getServerVerifyData();
1003 
1004                         sess = handshaker.getSession();
1005                         if (!writer.hasOutboundData()) {
1006                             hsStatus = HandshakeStatus.FINISHED;
1007                         }
1008                         handshaker = null;
1009                         connectionState = cs_DATA;
1010                         receivedCCS = false;
1011 
1012                         // No handshakeListeners here.  That's a
1013                         // SSLSocket thing.
1014                     } else if (handshaker.taskOutstanding()) {
1015                         hsStatus = HandshakeStatus.NEED_TASK;
1016                     }
1017                     break;
1018 
1019                 case Record.ct_application_data:
1020                     // Pass this right back up to the application.
1021                     if ((connectionState != cs_DATA)
1022                             && (connectionState != cs_RENEGOTIATE)
1023                             && (connectionState != cs_CLOSED)) {
1024                         throw new SSLProtocolException(
1025                             "Data received in non-data state: " +
1026                             connectionState);
1027                     }
1028 
1029                     if (expectingFinished) {
1030                         throw new SSLProtocolException
1031                                 ("Expecting finished message, received data");
1032                     }
1033 
1034                     /*
1035                      * Don't return data once the inbound side is
1036                      * closed.
1037                      */
1038                     if (!inboundDone) {
1039                         ea.scatter(decryptedBB.slice());
1040                     }
1041                     break;
1042 
1043                 case Record.ct_alert:
1044                     recvAlert();
1045                     break;
1046 
1047                 case Record.ct_change_cipher_spec:
1048                     if ((connectionState != cs_HANDSHAKE
1049                                 && connectionState != cs_RENEGOTIATE)
1050                             || !handshaker.sessionKeysCalculated()
1051                             || receivedCCS) {
1052                         // For the CCS message arriving in the wrong state
1053                         fatal(Alerts.alert_unexpected_message,
1054                                 "illegal change cipher spec msg, conn state = "
1055                                 + connectionState + ", handshake state = "
1056                                 + handshaker.state);
1057                     } else if (inputRecord.available() != 1
1058                             || inputRecord.read() != 1) {
1059                         // For structural/content issues with the CCS
1060                         fatal(Alerts.alert_unexpected_message,
1061                                 "Malformed change cipher spec msg");
1062                     }
1063 
1064                     // Once we've received CCS, update the flag.
1065                     // If the remote endpoint sends it again in this handshake
1066                     // we won't process it.
1067                     receivedCCS = true;
1068 
1069                     //
1070                     // The first message after a change_cipher_spec
1071                     // record MUST be a "Finished" handshake record,
1072                     // else it's a protocol violation.  We force this
1073                     // to be checked by a minor tweak to the state
1074                     // machine.
1075                     //
1076                     changeReadCiphers();
1077                     // next message MUST be a finished message
1078                     expectingFinished = true;
1079                     break;
1080 
1081                 default:
1082                     //
1083                     // TLS requires that unrecognized records be ignored.
1084                     //
1085                     if (debug != null && Debug.isOn("ssl")) {
1086                         System.out.println(threadName() +
1087                             ", Received record type: "
1088                             + inputRecord.contentType());
1089                     }
1090                     break;
1091                 } // switch
1092 
1093                 /*
1094                  * We only need to check the sequence number state for
1095                  * non-handshaking record.
1096                  *
1097                  * Note that in order to maintain the handshake status
1098                  * properly, we check the sequence number after the last
1099                  * record reading process. As we request renegotiation
1100                  * or close the connection for wrapped sequence number
1101                  * when there is enough sequence number space left to
1102                  * handle a few more records, so the sequence number
1103                  * of the last record cannot be wrapped.
1104                  */
1105                 if (connectionState < cs_ERROR && !isInboundDone() &&
1106                         (hsStatus == HandshakeStatus.NOT_HANDSHAKING)) {
1107                     if (checkSequenceNumber(readMAC,
1108                             inputRecord.contentType())) {
1109                         hsStatus = getHSStatus(null);
1110                     }
1111                 }
1112             } // synchronized (this)
1113         }
1114 
1115         return hsStatus;
1116     }
1117 
1118 
1119     //
1120     // write/wrap side
1121     //
1122 
1123 
1124     /**
1125      * Wraps a buffer.  Does a variety of checks before grabbing
1126      * the wrapLock, which blocks multiple wraps from occuring.
1127      */
1128     public SSLEngineResult wrap(ByteBuffer [] appData,
1129             int offset, int length, ByteBuffer netData) throws SSLException {
1130 
1131         EngineArgs ea = new EngineArgs(appData, offset, length, netData);
1132 
1133         /*
1134          * We can be smarter about using smaller buffer sizes later.
1135          * For now, force it to be large enough to handle any
1136          * valid SSL/TLS record.
1137          */
1138         if (netData.remaining() < outputRecord.maxRecordSize) {
1139             return new SSLEngineResult(
1140                 Status.BUFFER_OVERFLOW, getHSStatus(null), 0, 0);
1141         }
1142 
1143         try {
1144             synchronized (wrapLock) {
1145                 return writeAppRecord(ea);
1146             }
1147         } catch (Exception e) {
1148             ea.resetPos();
1149 
1150             fatal(Alerts.alert_internal_error,
1151                 "problem unwrapping net record", e);
1152             return null;  // make compiler happy
1153         } finally {
1154             /*
1155              * Just in case something didn't reset limits properly.
1156              */
1157             ea.resetLim();
1158         }
1159     }
1160 
1161     /*
1162      * Makes additional checks for unwrap, but this time more
1163      * specific to this packet and the current state of the machine.
1164      */
1165     private SSLEngineResult writeAppRecord(EngineArgs ea) throws IOException {
1166 
1167         Status status = null;
1168         HandshakeStatus hsStatus = null;
1169 
1170         /*
1171          * See if the handshaker needs to report back some SSLException.
1172          */
1173         checkTaskThrown();
1174 
1175         /*
1176          * short circuit if we're closed/closing.
1177          */
1178         if (writer.isOutboundDone()) {
1179             return new SSLEngineResult(Status.CLOSED, getHSStatus(null), 0, 0);
1180         }
1181 
1182         /*
1183          * If we're still in cs_HANDSHAKE, make sure it's been
1184          * started.
1185          */
1186         synchronized (this) {
1187             if ((connectionState == cs_HANDSHAKE) ||
1188                     (connectionState == cs_START)) {
1189                 kickstartHandshake();
1190 
1191                 /*
1192                  * If there's no HS data available to write, we can return
1193                  * without trying to wrap anything.
1194                  */
1195                 hsStatus = getHSStatus(null);
1196 
1197                 if (hsStatus == HandshakeStatus.NEED_UNWRAP) {
1198                     return new SSLEngineResult(Status.OK, hsStatus, 0, 0);
1199                 }
1200             }
1201         }
1202 
1203         /*
1204          * Grab a copy of this if it doesn't already exist,
1205          * and we can use it several places before anything major
1206          * happens on this side.  Races aren't critical
1207          * here.
1208          */
1209         if (hsStatus == null) {
1210             hsStatus = getHSStatus(null);
1211         }
1212 
1213         /*
1214          * If we have a task outstanding, this *MUST* be done before
1215          * doing any more wrapping, because we could be in the middle
1216          * of receiving a handshake message, for example, a finished
1217          * message which would change the ciphers.
1218          */
1219         if (hsStatus == HandshakeStatus.NEED_TASK) {
1220             return new SSLEngineResult(
1221                 Status.OK, hsStatus, 0, 0);
1222         }
1223 
1224         /*
1225          * This will obtain any waiting outbound data, or will
1226          * process the outbound appData.
1227          */
1228         try {
1229             synchronized (writeLock) {
1230                 hsStatus = writeRecord(outputRecord, ea);
1231             }
1232         } catch (SSLException e) {
1233             throw e;
1234         } catch (IOException e) {
1235             SSLException ex = new SSLException("Write problems");
1236             ex.initCause(e);
1237             throw ex;
1238         }
1239 
1240         /*
1241          * writeRecord might have reported some status.
1242          * Now check for the remaining cases.
1243          *
1244          * status above should cover:  NEED_WRAP/FINISHED
1245          */
1246         status = (isOutboundDone() ? Status.CLOSED : Status.OK);
1247         hsStatus = getHSStatus(hsStatus);
1248 
1249         return new SSLEngineResult(status, hsStatus,
1250             ea.deltaApp(), ea.deltaNet());
1251     }
1252 
1253     /*
1254      * Central point to write/get all of the outgoing data.
1255      */
1256     private HandshakeStatus writeRecord(EngineOutputRecord eor,
1257             EngineArgs ea) throws IOException {
1258 
1259         // eventually compress as well.
1260         HandshakeStatus hsStatus =
1261                 writer.writeRecord(eor, ea, writeMAC, writeCipher);
1262 
1263         /*
1264          * We only need to check the sequence number state for
1265          * non-handshaking record.
1266          *
1267          * Note that in order to maintain the handshake status
1268          * properly, we check the sequence number after the last
1269          * record writing process. As we request renegotiation
1270          * or close the connection for wrapped sequence number
1271          * when there is enough sequence number space left to
1272          * handle a few more records, so the sequence number
1273          * of the last record cannot be wrapped.
1274          */
1275         if (connectionState < cs_ERROR && !isOutboundDone() &&
1276                 (hsStatus == HandshakeStatus.NOT_HANDSHAKING)) {
1277             if (checkSequenceNumber(writeMAC, eor.contentType())) {
1278                 hsStatus = getHSStatus(null);
1279             }
1280         }
1281 
1282         /*
1283          * turn off the flag of the first application record if we really
1284          * consumed at least byte.
1285          */
1286         if (isFirstAppOutputRecord && ea.deltaApp() > 0) {
1287             isFirstAppOutputRecord = false;
1288         }
1289 
1290         return hsStatus;
1291     }
1292 
1293     /*
1294      * Need to split the payload except the following cases:
1295      *
1296      * 1. protocol version is TLS 1.1 or later;
1297      * 2. bulk cipher does not use CBC mode, including null bulk cipher suites.
1298      * 3. the payload is the first application record of a freshly
1299      *    negotiated TLS session.
1300      * 4. the CBC protection is disabled;
1301      *
1302      * More details, please refer to
1303      * EngineOutputRecord.write(EngineArgs, MAC, CipherBox).
1304      */
1305     boolean needToSplitPayload(CipherBox cipher, ProtocolVersion protocol) {
1306         return (protocol.v <= ProtocolVersion.TLS10.v) &&
1307                 cipher.isCBCMode() && !isFirstAppOutputRecord &&
1308                 Record.enableCBCProtection;
1309     }
1310 
1311     /*
1312      * Non-application OutputRecords go through here.
1313      */
1314     void writeRecord(EngineOutputRecord eor) throws IOException {
1315         // eventually compress as well.
1316         writer.writeRecord(eor, writeMAC, writeCipher);
1317 
1318         /*
1319          * Check the sequence number state
1320          *
1321          * Note that in order to maintain the connection I/O
1322          * properly, we check the sequence number after the last
1323          * record writing process. As we request renegotiation
1324          * or close the connection for wrapped sequence number
1325          * when there is enough sequence number space left to
1326          * handle a few more records, so the sequence number
1327          * of the last record cannot be wrapped.
1328          */
1329         if ((connectionState < cs_ERROR) && !isOutboundDone()) {
1330             checkSequenceNumber(writeMAC, eor.contentType());
1331         }
1332     }
1333 
1334     //
1335     // Close code
1336     //
1337 
1338     /**
1339      * Check the sequence number state
1340      *
1341      * RFC 4346 states that, "Sequence numbers are of type uint64 and
1342      * may not exceed 2^64-1.  Sequence numbers do not wrap. If a TLS
1343      * implementation would need to wrap a sequence number, it must
1344      * renegotiate instead."
1345      *
1346      * Return true if the handshake status may be changed.
1347      */
1348     private boolean checkSequenceNumber(MAC mac, byte type)
1349             throws IOException {
1350 
1351         /*
1352          * Don't bother to check the sequence number for error or
1353          * closed connections, or NULL MAC
1354          */
1355         if (connectionState >= cs_ERROR || mac == MAC.NULL) {
1356             return false;
1357         }
1358 
1359         /*
1360          * Conservatively, close the connection immediately when the
1361          * sequence number is close to overflow
1362          */
1363         if (mac.seqNumOverflow()) {
1364             /*
1365              * TLS protocols do not define a error alert for sequence
1366              * number overflow. We use handshake_failure error alert
1367              * for handshaking and bad_record_mac for other records.
1368              */
1369             if (debug != null && Debug.isOn("ssl")) {
1370                 System.out.println(threadName() +
1371                     ", sequence number extremely close to overflow " +
1372                     "(2^64-1 packets). Closing connection.");
1373             }
1374 
1375             fatal(Alerts.alert_handshake_failure, "sequence number overflow");
1376 
1377             return true; // make the compiler happy
1378         }
1379 
1380         /*
1381          * Ask for renegotiation when need to renew sequence number.
1382          *
1383          * Don't bother to kickstart the renegotiation when the local is
1384          * asking for it.
1385          */
1386         if ((type != Record.ct_handshake) && mac.seqNumIsHuge()) {
1387             if (debug != null && Debug.isOn("ssl")) {
1388                 System.out.println(threadName() + ", request renegotiation " +
1389                         "to avoid sequence number overflow");
1390             }
1391 
1392             beginHandshake();
1393             return true;
1394         }
1395 
1396         return false;
1397     }
1398 
1399     /**
1400      * Signals that no more outbound application data will be sent
1401      * on this <code>SSLEngine</code>.
1402      */
1403     private void closeOutboundInternal() {
1404 
1405         if ((debug != null) && Debug.isOn("ssl")) {
1406             System.out.println(threadName() + ", closeOutboundInternal()");
1407         }
1408 
1409         /*
1410          * Already closed, ignore
1411          */
1412         if (writer.isOutboundDone()) {
1413             return;
1414         }
1415 
1416         switch (connectionState) {
1417 
1418         /*
1419          * If we haven't even started yet, don't bother reading inbound.
1420          */
1421         case cs_START:
1422             writer.closeOutbound();
1423             inboundDone = true;
1424             break;
1425 
1426         case cs_ERROR:
1427         case cs_CLOSED:
1428             break;
1429 
1430         /*
1431          * Otherwise we indicate clean termination.
1432          */
1433         // case cs_HANDSHAKE:
1434         // case cs_DATA:
1435         // case cs_RENEGOTIATE:
1436         default:
1437             warning(Alerts.alert_close_notify);
1438             writer.closeOutbound();
1439             break;
1440         }
1441 
1442         connectionState = cs_CLOSED;
1443     }
1444 
1445     synchronized public void closeOutbound() {
1446         /*
1447          * Dump out a close_notify to the remote side
1448          */
1449         if ((debug != null) && Debug.isOn("ssl")) {
1450             System.out.println(threadName() + ", called closeOutbound()");
1451         }
1452 
1453         closeOutboundInternal();
1454     }
1455 
1456     /**
1457      * Returns the outbound application data closure state
1458      */
1459     public boolean isOutboundDone() {
1460         return writer.isOutboundDone();
1461     }
1462 
1463     /**
1464      * Signals that no more inbound network data will be sent
1465      * to this <code>SSLEngine</code>.
1466      */
1467     private void closeInboundInternal() {
1468 
1469         if ((debug != null) && Debug.isOn("ssl")) {
1470             System.out.println(threadName() + ", closeInboundInternal()");
1471         }
1472 
1473         /*
1474          * Already closed, ignore
1475          */
1476         if (inboundDone) {
1477             return;
1478         }
1479 
1480         closeOutboundInternal();
1481         inboundDone = true;
1482         connectionState = cs_CLOSED;
1483     }
1484 
1485     /*
1486      * Close the inbound side of the connection.  We grab the
1487      * lock here, and do the real work in the internal verison.
1488      * We do check for truncation attacks.
1489      */
1490     synchronized public void closeInbound() throws SSLException {
1491         /*
1492          * Currently closes the outbound side as well.  The IETF TLS
1493          * working group has expressed the opinion that 1/2 open
1494          * connections are not allowed by the spec.  May change
1495          * someday in the future.
1496          */
1497         if ((debug != null) && Debug.isOn("ssl")) {
1498             System.out.println(threadName() + ", called closeInbound()");
1499         }
1500 
1501         /*
1502          * No need to throw an Exception if we haven't even started yet.
1503          */
1504         if ((connectionState != cs_START) && !recvCN) {
1505             recvCN = true;  // Only receive the Exception once
1506             fatal(Alerts.alert_internal_error,
1507                 "Inbound closed before receiving peer's close_notify: " +
1508                 "possible truncation attack?");
1509         } else {
1510             /*
1511              * Currently, this is a no-op, but in case we change
1512              * the close inbound code later.
1513              */
1514             closeInboundInternal();
1515         }
1516     }
1517 
1518     /**
1519      * Returns the network inbound data closure state
1520      */
1521     synchronized public boolean isInboundDone() {
1522         return inboundDone;
1523     }
1524 
1525 
1526     //
1527     // Misc stuff
1528     //
1529 
1530 
1531     /**
1532      * Returns the current <code>SSLSession</code> for this
1533      * <code>SSLEngine</code>
1534      * <P>
1535      * These can be long lived, and frequently correspond to an
1536      * entire login session for some user.
1537      */
1538     synchronized public SSLSession getSession() {
1539         return sess;
1540     }
1541 
1542     /**
1543      * Returns a delegated <code>Runnable</code> task for
1544      * this <code>SSLEngine</code>.
1545      */
1546     synchronized public Runnable getDelegatedTask() {
1547         if (handshaker != null) {
1548             return handshaker.getTask();
1549         }
1550         return null;
1551     }
1552 
1553 
1554     //
1555     // EXCEPTION AND ALERT HANDLING
1556     //
1557 
1558     /*
1559      * Send a warning alert.
1560      */
1561     void warning(byte description) {
1562         sendAlert(Alerts.alert_warning, description);
1563     }
1564 
1565     synchronized void fatal(byte description, String diagnostic)
1566             throws SSLException {
1567         fatal(description, diagnostic, null);
1568     }
1569 
1570     synchronized void fatal(byte description, Throwable cause)
1571             throws SSLException {
1572         fatal(description, null, cause);
1573     }
1574 
1575     /*
1576      * We've got a fatal error here, so start the shutdown process.
1577      *
1578      * Because of the way the code was written, we have some code
1579      * calling fatal directly when the "description" is known
1580      * and some throwing Exceptions which are then caught by higher
1581      * levels which then call here.  This code needs to determine
1582      * if one of the lower levels has already started the process.
1583      *
1584      * We won't worry about Error's, if we have one of those,
1585      * we're in worse trouble.  Note:  the networking code doesn't
1586      * deal with Errors either.
1587      */
1588     synchronized void fatal(byte description, String diagnostic,
1589             Throwable cause) throws SSLException {
1590 
1591         /*
1592          * If we have no further information, make a general-purpose
1593          * message for folks to see.  We generally have one or the other.
1594          */
1595         if (diagnostic == null) {
1596             diagnostic = "General SSLEngine problem";
1597         }
1598         if (cause == null) {
1599             cause = Alerts.getSSLException(description, cause, diagnostic);
1600         }
1601 
1602         /*
1603          * If we've already shutdown because of an error,
1604          * there is nothing we can do except rethrow the exception.
1605          *
1606          * Most exceptions seen here will be SSLExceptions.
1607          * We may find the occasional Exception which hasn't been
1608          * converted to a SSLException, so we'll do it here.
1609          */
1610         if (closeReason != null) {
1611             if ((debug != null) && Debug.isOn("ssl")) {
1612                 System.out.println(threadName() +
1613                     ", fatal: engine already closed.  Rethrowing " +
1614                     cause.toString());
1615             }
1616             if (cause instanceof RuntimeException) {
1617                 throw (RuntimeException)cause;
1618             } else if (cause instanceof SSLException) {
1619                 throw (SSLException)cause;
1620             } else if (cause instanceof Exception) {
1621                 SSLException ssle = new SSLException(
1622                     "fatal SSLEngine condition");
1623                 ssle.initCause(cause);
1624                 throw ssle;
1625             }
1626         }
1627 
1628         if ((debug != null) && Debug.isOn("ssl")) {
1629             System.out.println(threadName()
1630                         + ", fatal error: " + description +
1631                         ": " + diagnostic + "\n" + cause.toString());
1632         }
1633 
1634         /*
1635          * Ok, this engine's going down.
1636          */
1637         int oldState = connectionState;
1638         connectionState = cs_ERROR;
1639 
1640         inboundDone = true;
1641 
1642         sess.invalidate();
1643 
1644         /*
1645          * If we haven't even started handshaking yet, no need
1646          * to generate the fatal close alert.
1647          */
1648         if (oldState != cs_START) {
1649             sendAlert(Alerts.alert_fatal, description);
1650         }
1651 
1652         if (cause instanceof SSLException) { // only true if != null
1653             closeReason = (SSLException)cause;
1654         } else {
1655             /*
1656              * Including RuntimeExceptions, but we'll throw those
1657              * down below.  The closeReason isn't used again,
1658              * except for null checks.
1659              */
1660             closeReason =
1661                 Alerts.getSSLException(description, cause, diagnostic);
1662         }
1663 
1664         writer.closeOutbound();
1665 
1666         connectionState = cs_CLOSED;
1667 
1668         if (cause instanceof RuntimeException) {
1669             throw (RuntimeException)cause;
1670         } else {
1671             throw closeReason;
1672         }
1673     }
1674 
1675     /*
1676      * Process an incoming alert ... caller must already have synchronized
1677      * access to "this".
1678      */
1679     private void recvAlert() throws IOException {
1680         byte level = (byte)inputRecord.read();
1681         byte description = (byte)inputRecord.read();
1682         if (description == -1) { // check for short message
1683             fatal(Alerts.alert_illegal_parameter, "Short alert message");
1684         }
1685 
1686         if (debug != null && (Debug.isOn("record") ||
1687                 Debug.isOn("handshake"))) {
1688             synchronized (System.out) {
1689                 System.out.print(threadName());
1690                 System.out.print(", RECV " + protocolVersion + " ALERT:  ");
1691                 if (level == Alerts.alert_fatal) {
1692                     System.out.print("fatal, ");
1693                 } else if (level == Alerts.alert_warning) {
1694                     System.out.print("warning, ");
1695                 } else {
1696                     System.out.print("<level " + (0x0ff & level) + ">, ");
1697                 }
1698                 System.out.println(Alerts.alertDescription(description));
1699             }
1700         }
1701 
1702         if (level == Alerts.alert_warning) {
1703             if (description == Alerts.alert_close_notify) {
1704                 if (connectionState == cs_HANDSHAKE) {
1705                     fatal(Alerts.alert_unexpected_message,
1706                                 "Received close_notify during handshake");
1707                 } else {
1708                     recvCN = true;
1709                     closeInboundInternal();  // reply to close
1710                 }
1711             } else {
1712 
1713                 //
1714                 // The other legal warnings relate to certificates,
1715                 // e.g. no_certificate, bad_certificate, etc; these
1716                 // are important to the handshaking code, which can
1717                 // also handle illegal protocol alerts if needed.
1718                 //
1719                 if (handshaker != null) {
1720                     handshaker.handshakeAlert(description);
1721                 }
1722             }
1723         } else { // fatal or unknown level
1724             String reason = "Received fatal alert: "
1725                 + Alerts.alertDescription(description);
1726             if (closeReason == null) {
1727                 closeReason = Alerts.getSSLException(description, reason);
1728             }
1729             fatal(Alerts.alert_unexpected_message, reason);
1730         }
1731     }
1732 
1733 
1734     /*
1735      * Emit alerts.  Caller must have synchronized with "this".
1736      */
1737     private void sendAlert(byte level, byte description) {
1738         // the connectionState cannot be cs_START
1739         if (connectionState >= cs_CLOSED) {
1740             return;
1741         }
1742 
1743         // For initial handshaking, don't send alert message to peer if
1744         // handshaker has not started.
1745         if (connectionState == cs_HANDSHAKE &&
1746             (handshaker == null || !handshaker.started())) {
1747             return;
1748         }
1749 
1750         EngineOutputRecord r = new EngineOutputRecord(Record.ct_alert, this);
1751         r.setVersion(protocolVersion);
1752 
1753         boolean useDebug = debug != null && Debug.isOn("ssl");
1754         if (useDebug) {
1755             synchronized (System.out) {
1756                 System.out.print(threadName());
1757                 System.out.print(", SEND " + protocolVersion + " ALERT:  ");
1758                 if (level == Alerts.alert_fatal) {
1759                     System.out.print("fatal, ");
1760                 } else if (level == Alerts.alert_warning) {
1761                     System.out.print("warning, ");
1762                 } else {
1763                     System.out.print("<level = " + (0x0ff & level) + ">, ");
1764                 }
1765                 System.out.println("description = "
1766                         + Alerts.alertDescription(description));
1767             }
1768         }
1769 
1770         r.write(level);
1771         r.write(description);
1772         try {
1773             writeRecord(r);
1774         } catch (IOException e) {
1775             if (useDebug) {
1776                 System.out.println(threadName() +
1777                     ", Exception sending alert: " + e);
1778             }
1779         }
1780     }
1781 
1782 
1783     //
1784     // VARIOUS OTHER METHODS (COMMON TO SSLSocket)
1785     //
1786 
1787 
1788     /**
1789      * Controls whether new connections may cause creation of new SSL
1790      * sessions.
1791      *
1792      * As long as handshaking has not started, we can change
1793      * whether we enable session creations.  Otherwise,
1794      * we will need to wait for the next handshake.
1795      */
1796     synchronized public void setEnableSessionCreation(boolean flag) {
1797         enableSessionCreation = flag;
1798 
1799         if ((handshaker != null) && !handshaker.activated()) {
1800             handshaker.setEnableSessionCreation(enableSessionCreation);
1801         }
1802     }
1803 
1804     /**
1805      * Returns true if new connections may cause creation of new SSL
1806      * sessions.
1807      */
1808     synchronized public boolean getEnableSessionCreation() {
1809         return enableSessionCreation;
1810     }
1811 
1812 
1813     /**
1814      * Sets the flag controlling whether a server mode engine
1815      * *REQUIRES* SSL client authentication.
1816      *
1817      * As long as handshaking has not started, we can change
1818      * whether client authentication is needed.  Otherwise,
1819      * we will need to wait for the next handshake.
1820      */
1821     synchronized public void setNeedClientAuth(boolean flag) {
1822         doClientAuth = (flag ?
1823             SSLEngineImpl.clauth_required : SSLEngineImpl.clauth_none);
1824 
1825         if ((handshaker != null) &&
1826                 (handshaker instanceof ServerHandshaker) &&
1827                 !handshaker.activated()) {
1828             ((ServerHandshaker) handshaker).setClientAuth(doClientAuth);
1829         }
1830     }
1831 
1832     synchronized public boolean getNeedClientAuth() {
1833         return (doClientAuth == SSLEngineImpl.clauth_required);
1834     }
1835 
1836     /**
1837      * Sets the flag controlling whether a server mode engine
1838      * *REQUESTS* SSL client authentication.
1839      *
1840      * As long as handshaking has not started, we can change
1841      * whether client authentication is requested.  Otherwise,
1842      * we will need to wait for the next handshake.
1843      */
1844     synchronized public void setWantClientAuth(boolean flag) {
1845         doClientAuth = (flag ?
1846             SSLEngineImpl.clauth_requested : SSLEngineImpl.clauth_none);
1847 
1848         if ((handshaker != null) &&
1849                 (handshaker instanceof ServerHandshaker) &&
1850                 !handshaker.activated()) {
1851             ((ServerHandshaker) handshaker).setClientAuth(doClientAuth);
1852         }
1853     }
1854 
1855     synchronized public boolean getWantClientAuth() {
1856         return (doClientAuth == SSLEngineImpl.clauth_requested);
1857     }
1858 
1859 
1860     /**
1861      * Sets the flag controlling whether the engine is in SSL
1862      * client or server mode.  Must be called before any SSL
1863      * traffic has started.
1864      */
1865     synchronized public void setUseClientMode(boolean flag) {
1866         switch (connectionState) {
1867 
1868         case cs_START:
1869             /*
1870              * If we need to change the engine mode and the enabled
1871              * protocols haven't specifically been set by the user,
1872              * change them to the corresponding default ones.
1873              */
1874             if (roleIsServer != (!flag) &&
1875                     sslContext.isDefaultProtocolList(enabledProtocols)) {
1876                 enabledProtocols = sslContext.getDefaultProtocolList(!flag);
1877             }
1878 
1879             roleIsServer = !flag;
1880             serverModeSet = true;
1881             break;
1882 
1883         case cs_HANDSHAKE:
1884             /*
1885              * If we have a handshaker, but haven't started
1886              * SSL traffic, we can throw away our current
1887              * handshaker, and start from scratch.  Don't
1888              * need to call doneConnect() again, we already
1889              * have the streams.
1890              */
1891             assert(handshaker != null);
1892             if (!handshaker.activated()) {
1893                 /*
1894                  * If we need to change the engine mode and the enabled
1895                  * protocols haven't specifically been set by the user,
1896                  * change them to the corresponding default ones.
1897                  */
1898                 if (roleIsServer != (!flag) &&
1899                         sslContext.isDefaultProtocolList(enabledProtocols)) {
1900                     enabledProtocols = sslContext.getDefaultProtocolList(!flag);
1901                 }
1902 
1903                 roleIsServer = !flag;
1904                 connectionState = cs_START;
1905                 initHandshaker();
1906                 break;
1907             }
1908 
1909             // If handshake has started, that's an error.  Fall through...
1910 
1911         default:
1912             if (debug != null && Debug.isOn("ssl")) {
1913                 System.out.println(threadName() +
1914                     ", setUseClientMode() invoked in state = " +
1915                     connectionState);
1916             }
1917 
1918             /*
1919              * We can let them continue if they catch this correctly,
1920              * we don't need to shut this down.
1921              */
1922             throw new IllegalArgumentException(
1923                 "Cannot change mode after SSL traffic has started");
1924         }
1925     }
1926 
1927     synchronized public boolean getUseClientMode() {
1928         return !roleIsServer;
1929     }
1930 
1931 
1932     /**
1933      * Returns the names of the cipher suites which could be enabled for use
1934      * on an SSL connection.  Normally, only a subset of these will actually
1935      * be enabled by default, since this list may include cipher suites which
1936      * do not support the mutual authentication of servers and clients, or
1937      * which do not protect data confidentiality.  Servers may also need
1938      * certain kinds of certificates to use certain cipher suites.
1939      *
1940      * @return an array of cipher suite names
1941      */
1942     public String[] getSupportedCipherSuites() {
1943         return sslContext.getSupportedCipherSuiteList().toStringArray();
1944     }
1945 
1946     /**
1947      * Controls which particular cipher suites are enabled for use on
1948      * this connection.  The cipher suites must have been listed by
1949      * getCipherSuites() as being supported.  Even if a suite has been
1950      * enabled, it might never be used if no peer supports it or the
1951      * requisite certificates (and private keys) are not available.
1952      *
1953      * @param suites Names of all the cipher suites to enable.
1954      */
1955     synchronized public void setEnabledCipherSuites(String[] suites) {
1956         enabledCipherSuites = new CipherSuiteList(suites);
1957         if ((handshaker != null) && !handshaker.activated()) {
1958             handshaker.setEnabledCipherSuites(enabledCipherSuites);
1959         }
1960     }
1961 
1962     /**
1963      * Returns the names of the SSL cipher suites which are currently enabled
1964      * for use on this connection.  When an SSL engine is first created,
1965      * all enabled cipher suites <em>(a)</em> protect data confidentiality,
1966      * by traffic encryption, and <em>(b)</em> can mutually authenticate
1967      * both clients and servers.  Thus, in some environments, this value
1968      * might be empty.
1969      *
1970      * @return an array of cipher suite names
1971      */
1972     synchronized public String[] getEnabledCipherSuites() {
1973         return enabledCipherSuites.toStringArray();
1974     }
1975 
1976 
1977     /**
1978      * Returns the protocols that are supported by this implementation.
1979      * A subset of the supported protocols may be enabled for this connection
1980      * @ returns an array of protocol names.
1981      */
1982     public String[] getSupportedProtocols() {
1983         return sslContext.getSuportedProtocolList().toStringArray();
1984     }
1985 
1986     /**
1987      * Controls which protocols are enabled for use on
1988      * this connection.  The protocols must have been listed by
1989      * getSupportedProtocols() as being supported.
1990      *
1991      * @param protocols protocols to enable.
1992      * @exception IllegalArgumentException when one of the protocols
1993      *  named by the parameter is not supported.
1994      */
1995     synchronized public void setEnabledProtocols(String[] protocols) {
1996         enabledProtocols = new ProtocolList(protocols);
1997         if ((handshaker != null) && !handshaker.activated()) {
1998             handshaker.setEnabledProtocols(enabledProtocols);
1999         }
2000     }
2001 
2002     synchronized public String[] getEnabledProtocols() {
2003         return enabledProtocols.toStringArray();
2004     }
2005 
2006     /**
2007      * Try to configure the endpoint identification algorithm of the engine.
2008      *
2009      * @param identificationAlgorithm the algorithm used to check the
2010      *          endpoint identity.
2011      * @return true if the identification algorithm configuration success.
2012      */
2013     synchronized public boolean trySetHostnameVerification(
2014         String identificationAlgorithm) {
2015         if (sslContext.getX509TrustManager() instanceof
2016                 X509ExtendedTrustManager) {
2017             this.identificationAlg = identificationAlgorithm;
2018             return true;
2019         } else {
2020             return false;
2021         }
2022     }
2023 
2024     /**
2025      * Returns the endpoint identification algorithm of the engine.
2026      */
2027     synchronized public String getHostnameVerification() {
2028         return identificationAlg;
2029     }
2030 
2031     /**
2032      * Return the name of the current thread. Utility method.
2033      */
2034     private static String threadName() {
2035         return Thread.currentThread().getName();
2036     }
2037 
2038     /*
2039      * Returns a boolean indicating whether the ChangeCipherSpec message
2040      * has been received for this handshake.
2041      */
2042     boolean receivedChangeCipherSpec() {
2043         return receivedCCS;
2044     }
2045 
2046     /**
2047      * Returns a printable representation of this end of the connection.
2048      */
2049     public String toString() {
2050         StringBuilder retval = new StringBuilder(80);
2051 
2052         retval.append(Integer.toHexString(hashCode()));
2053         retval.append("[");
2054         retval.append("SSLEngine[hostname=");
2055         String host = getPeerHost();
2056         retval.append((host == null) ? "null" : host);
2057         retval.append(" port=");
2058         retval.append(Integer.toString(getPeerPort()));
2059         retval.append("] ");
2060         retval.append(getSession().getCipherSuite());
2061         retval.append("]");
2062 
2063         return retval.toString();
2064     }
2065 }