1 /*
   2  * Copyright (c) 1996, 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 
  27 package sun.security.ssl;
  28 
  29 import java.io.*;
  30 import java.util.*;
  31 import java.security.*;
  32 import java.security.NoSuchAlgorithmException;
  33 import java.security.AccessController;
  34 import java.security.AlgorithmConstraints;
  35 import java.security.AccessControlContext;
  36 import java.security.PrivilegedExceptionAction;
  37 import java.security.PrivilegedActionException;
  38 
  39 import javax.crypto.*;
  40 import javax.crypto.spec.*;
  41 
  42 import javax.net.ssl.*;
  43 import sun.misc.HexDumpEncoder;
  44 
  45 import sun.security.internal.spec.*;
  46 import sun.security.internal.interfaces.TlsMasterSecret;
  47 
  48 import sun.security.ssl.HandshakeMessage.*;
  49 import sun.security.ssl.CipherSuite.*;
  50 
  51 import static sun.security.ssl.CipherSuite.PRF.*;
  52 import static sun.security.ssl.CipherSuite.CipherType.*;
  53 
  54 /**
  55  * Handshaker ... processes handshake records from an SSL V3.0
  56  * data stream, handling all the details of the handshake protocol.
  57  *
  58  * Note that the real protocol work is done in two subclasses, the  base
  59  * class just provides the control flow and key generation framework.
  60  *
  61  * @author David Brownell
  62  */
  63 abstract class Handshaker {
  64 
  65     // protocol version being established using this Handshaker
  66     ProtocolVersion protocolVersion;
  67 
  68     // the currently active protocol version during a renegotiation
  69     ProtocolVersion     activeProtocolVersion;
  70 
  71     // security parameters for secure renegotiation.
  72     boolean             secureRenegotiation;
  73     byte[]              clientVerifyData;
  74     byte[]              serverVerifyData;
  75 
  76     // Is it an initial negotiation  or a renegotiation?
  77     boolean                     isInitialHandshake;
  78 
  79     // List of enabled protocols
  80     private ProtocolList        enabledProtocols;
  81 
  82     // List of enabled CipherSuites
  83     private CipherSuiteList     enabledCipherSuites;
  84 
  85     // The endpoint identification protocol
  86     String              identificationProtocol;
  87 
  88     // The cryptographic algorithm constraints
  89     private AlgorithmConstraints    algorithmConstraints = null;
  90 
  91     // Local supported signature and algorithms
  92     Collection<SignatureAndHashAlgorithm> localSupportedSignAlgs;
  93 
  94     // Peer supported signature and algorithms
  95     Collection<SignatureAndHashAlgorithm> peerSupportedSignAlgs;
  96 
  97     /*
  98 
  99     /*
 100      * List of active protocols
 101      *
 102      * Active protocols is a subset of enabled protocols, and will
 103      * contain only those protocols that have vaild cipher suites
 104      * enabled.
 105      */
 106     private ProtocolList       activeProtocols;
 107 
 108     /*
 109      * List of active cipher suites
 110      *
 111      * Active cipher suites is a subset of enabled cipher suites, and will
 112      * contain only those cipher suites available for the active protocols.
 113      */
 114     private CipherSuiteList    activeCipherSuites;
 115 
 116     // The server name indication and matchers
 117     List<SNIServerName>         serverNames =
 118                                     Collections.<SNIServerName>emptyList();
 119     Collection<SNIMatcher>      sniMatchers =
 120                                     Collections.<SNIMatcher>emptyList();
 121 
 122     private boolean             isClient;
 123     private boolean             needCertVerify;
 124 
 125     SSLSocketImpl               conn = null;
 126     SSLEngineImpl               engine = null;
 127 
 128     HandshakeHash               handshakeHash;
 129     HandshakeInStream           input;
 130     HandshakeOutStream          output;
 131     int                         state;
 132     SSLContextImpl              sslContext;
 133     RandomCookie                clnt_random, svr_random;
 134     SSLSessionImpl              session;
 135 
 136     // current CipherSuite. Never null, initially SSL_NULL_WITH_NULL_NULL
 137     CipherSuite         cipherSuite;
 138 
 139     // current key exchange. Never null, initially K_NULL
 140     KeyExchange         keyExchange;
 141 
 142     /* True if this session is being resumed (fast handshake) */
 143     boolean             resumingSession;
 144 
 145     /* True if it's OK to start a new SSL session */
 146     boolean             enableNewSession;
 147 
 148     // Whether local cipher suites preference should be honored during
 149     // handshaking?
 150     //
 151     // Note that in this provider, this option only applies to server side.
 152     // Local cipher suites preference is always honored in client side in
 153     // this provider.
 154     boolean preferLocalCipherSuites = false;
 155 
 156     // Whether to send TLS_FALLBACK_SCSV as part of the cipher suite
 157     // list in the Client Hello.
 158     boolean sendFallbackSCSV;
 159 
 160     // Temporary storage for the individual keys. Set by
 161     // calculateConnectionKeys() and cleared once the ciphers are
 162     // activated.
 163     private SecretKey clntWriteKey, svrWriteKey;
 164     private IvParameterSpec clntWriteIV, svrWriteIV;
 165     private SecretKey clntMacSecret, svrMacSecret;
 166 
 167     /*
 168      * Delegated task subsystem data structures.
 169      *
 170      * If thrown is set, we need to propagate this back immediately
 171      * on entry into processMessage().
 172      *
 173      * Data is protected by the SSLEngine.this lock.
 174      */
 175     private volatile boolean taskDelegated = false;
 176     private volatile DelegatedTask<?> delegatedTask = null;
 177     private volatile Exception thrown = null;
 178 
 179     // Could probably use a java.util.concurrent.atomic.AtomicReference
 180     // here instead of using this lock.  Consider changing.
 181     private Object thrownLock = new Object();
 182 
 183     /* Class and subclass dynamic debugging support */
 184     static final Debug debug = Debug.getInstance("ssl");
 185 
 186     // By default, disable the unsafe legacy session renegotiation
 187     static final boolean allowUnsafeRenegotiation = Debug.getBooleanProperty(
 188                     "sun.security.ssl.allowUnsafeRenegotiation", false);
 189 
 190     // For maximum interoperability and backward compatibility, RFC 5746
 191     // allows server (or client) to accept ClientHello (or ServerHello)
 192     // message without the secure renegotiation_info extension or SCSV.
 193     //
 194     // For maximum security, RFC 5746 also allows server (or client) to
 195     // reject such message with a fatal "handshake_failure" alert.
 196     //
 197     // By default, allow such legacy hello messages.
 198     static final boolean allowLegacyHelloMessages = Debug.getBooleanProperty(
 199                     "sun.security.ssl.allowLegacyHelloMessages", true);
 200 
 201     // To prevent the TLS renegotiation issues, by setting system property
 202     // "jdk.tls.rejectClientInitiatedRenegotiation" to true, applications in
 203     // server side can disable all client initiated SSL renegotiations
 204     // regardless of the support of TLS protocols.
 205     //
 206     // By default, allow client initiated renegotiations.
 207     static final boolean rejectClientInitiatedRenego =
 208             Debug.getBooleanProperty(
 209                 "jdk.tls.rejectClientInitiatedRenegotiation", false);
 210 
 211     // need to dispose the object when it is invalidated
 212     boolean invalidated;
 213 
 214     Handshaker(SSLSocketImpl c, SSLContextImpl context,
 215             ProtocolList enabledProtocols, boolean needCertVerify,
 216             boolean isClient, ProtocolVersion activeProtocolVersion,
 217             boolean isInitialHandshake, boolean secureRenegotiation,
 218             byte[] clientVerifyData, byte[] serverVerifyData) {
 219         this.conn = c;
 220         init(context, enabledProtocols, needCertVerify, isClient,
 221             activeProtocolVersion, isInitialHandshake, secureRenegotiation,
 222             clientVerifyData, serverVerifyData);
 223     }
 224 
 225     Handshaker(SSLEngineImpl engine, SSLContextImpl context,
 226             ProtocolList enabledProtocols, boolean needCertVerify,
 227             boolean isClient, ProtocolVersion activeProtocolVersion,
 228             boolean isInitialHandshake, boolean secureRenegotiation,
 229             byte[] clientVerifyData, byte[] serverVerifyData) {
 230         this.engine = engine;
 231         init(context, enabledProtocols, needCertVerify, isClient,
 232             activeProtocolVersion, isInitialHandshake, secureRenegotiation,
 233             clientVerifyData, serverVerifyData);
 234     }
 235 
 236     private void init(SSLContextImpl context, ProtocolList enabledProtocols,
 237             boolean needCertVerify, boolean isClient,
 238             ProtocolVersion activeProtocolVersion,
 239             boolean isInitialHandshake, boolean secureRenegotiation,
 240             byte[] clientVerifyData, byte[] serverVerifyData) {
 241 
 242         if (debug != null && Debug.isOn("handshake")) {
 243             System.out.println(
 244                 "Allow unsafe renegotiation: " + allowUnsafeRenegotiation +
 245                 "\nAllow legacy hello messages: " + allowLegacyHelloMessages +
 246                 "\nIs initial handshake: " + isInitialHandshake +
 247                 "\nIs secure renegotiation: " + secureRenegotiation);
 248         }
 249 
 250         this.sslContext = context;
 251         this.isClient = isClient;
 252         this.needCertVerify = needCertVerify;
 253         this.activeProtocolVersion = activeProtocolVersion;
 254         this.isInitialHandshake = isInitialHandshake;
 255         this.secureRenegotiation = secureRenegotiation;
 256         this.clientVerifyData = clientVerifyData;
 257         this.serverVerifyData = serverVerifyData;
 258         enableNewSession = true;
 259         invalidated = false;
 260 
 261         setCipherSuite(CipherSuite.C_NULL);
 262         setEnabledProtocols(enabledProtocols);
 263 
 264         if (conn != null) {
 265             algorithmConstraints = new SSLAlgorithmConstraints(conn, true);
 266         } else {        // engine != null
 267             algorithmConstraints = new SSLAlgorithmConstraints(engine, true);
 268         }
 269 
 270 
 271         //
 272         // In addition to the connection state machine, controlling
 273         // how the connection deals with the different sorts of records
 274         // that get sent (notably handshake transitions!), there's
 275         // also a handshaking state machine that controls message
 276         // sequencing.
 277         //
 278         // It's a convenient artifact of the protocol that this can,
 279         // with only a couple of minor exceptions, be driven by the
 280         // type constant for the last message seen:  except for the
 281         // client's cert verify, those constants are in a convenient
 282         // order to drastically simplify state machine checking.
 283         //
 284         state = -2;  // initialized but not activated
 285     }
 286 
 287     /*
 288      * Reroutes calls to the SSLSocket or SSLEngine (*SE).
 289      *
 290      * We could have also done it by extra classes
 291      * and letting them override, but this seemed much
 292      * less involved.
 293      */
 294     void fatalSE(byte b, String diagnostic) throws IOException {
 295         fatalSE(b, diagnostic, null);
 296     }
 297 
 298     void fatalSE(byte b, Throwable cause) throws IOException {
 299         fatalSE(b, null, cause);
 300     }
 301 
 302     void fatalSE(byte b, String diagnostic, Throwable cause)
 303             throws IOException {
 304         if (conn != null) {
 305             conn.fatal(b, diagnostic, cause);
 306         } else {
 307             engine.fatal(b, diagnostic, cause);
 308         }
 309     }
 310 
 311     void warningSE(byte b) {
 312         if (conn != null) {
 313             conn.warning(b);
 314         } else {
 315             engine.warning(b);
 316         }
 317     }
 318 
 319     // ONLY used by ClientHandshaker to setup the peer host in SSLSession.
 320     String getHostSE() {
 321         if (conn != null) {
 322             return conn.getHost();
 323         } else {
 324             return engine.getPeerHost();
 325         }
 326     }
 327 
 328     // ONLY used by ServerHandshaker to setup the peer host in SSLSession.
 329     String getHostAddressSE() {
 330         if (conn != null) {
 331             return conn.getInetAddress().getHostAddress();
 332         } else {
 333             /*
 334              * This is for caching only, doesn't matter that's is really
 335              * a hostname.  The main thing is that it doesn't do
 336              * a reverse DNS lookup, potentially slowing things down.
 337              */
 338             return engine.getPeerHost();
 339         }
 340     }
 341 
 342     int getPortSE() {
 343         if (conn != null) {
 344             return conn.getPort();
 345         } else {
 346             return engine.getPeerPort();
 347         }
 348     }
 349 
 350     int getLocalPortSE() {
 351         if (conn != null) {
 352             return conn.getLocalPort();
 353         } else {
 354             return -1;
 355         }
 356     }
 357 
 358     AccessControlContext getAccSE() {
 359         if (conn != null) {
 360             return conn.getAcc();
 361         } else {
 362             return engine.getAcc();
 363         }
 364     }
 365 
 366     String getEndpointIdentificationAlgorithmSE() {
 367         SSLParameters paras;
 368         if (conn != null) {
 369             paras = conn.getSSLParameters();
 370         } else {
 371             paras = engine.getSSLParameters();
 372         }
 373 
 374         return paras.getEndpointIdentificationAlgorithm();
 375     }
 376 
 377     private void setVersionSE(ProtocolVersion protocolVersion) {
 378         if (conn != null) {
 379             conn.setVersion(protocolVersion);
 380         } else {
 381             engine.setVersion(protocolVersion);
 382         }
 383     }
 384 
 385     /**
 386      * Set the active protocol version and propagate it to the SSLSocket
 387      * and our handshake streams. Called from ClientHandshaker
 388      * and ServerHandshaker with the negotiated protocol version.
 389      */
 390     void setVersion(ProtocolVersion protocolVersion) {
 391         this.protocolVersion = protocolVersion;
 392         setVersionSE(protocolVersion);
 393 
 394         output.r.setVersion(protocolVersion);
 395     }
 396 
 397     /**
 398      * Set the enabled protocols. Called from the constructor or
 399      * SSLSocketImpl/SSLEngineImpl.setEnabledProtocols() (if the
 400      * handshake is not yet in progress).
 401      */
 402     void setEnabledProtocols(ProtocolList enabledProtocols) {
 403         activeCipherSuites = null;
 404         activeProtocols = null;
 405 
 406         this.enabledProtocols = enabledProtocols;
 407     }
 408 
 409     /**
 410      * Set the enabled cipher suites. Called from
 411      * SSLSocketImpl/SSLEngineImpl.setEnabledCipherSuites() (if the
 412      * handshake is not yet in progress).
 413      */
 414     void setEnabledCipherSuites(CipherSuiteList enabledCipherSuites) {
 415         activeCipherSuites = null;
 416         activeProtocols = null;
 417         this.enabledCipherSuites = enabledCipherSuites;
 418     }
 419 
 420     /**
 421      * Set the algorithm constraints. Called from the constructor or
 422      * SSLSocketImpl/SSLEngineImpl.setAlgorithmConstraints() (if the
 423      * handshake is not yet in progress).
 424      */
 425     void setAlgorithmConstraints(AlgorithmConstraints algorithmConstraints) {
 426         activeCipherSuites = null;
 427         activeProtocols = null;
 428 
 429         this.algorithmConstraints =
 430             new SSLAlgorithmConstraints(algorithmConstraints);
 431         this.localSupportedSignAlgs = null;
 432     }
 433 
 434     Collection<SignatureAndHashAlgorithm> getLocalSupportedSignAlgs() {
 435         if (localSupportedSignAlgs == null) {
 436             localSupportedSignAlgs =
 437                 SignatureAndHashAlgorithm.getSupportedAlgorithms(
 438                                                     algorithmConstraints);
 439         }
 440 
 441         return localSupportedSignAlgs;
 442     }
 443 
 444     void setPeerSupportedSignAlgs(
 445             Collection<SignatureAndHashAlgorithm> algorithms) {
 446         peerSupportedSignAlgs =
 447             new ArrayList<SignatureAndHashAlgorithm>(algorithms);
 448     }
 449 
 450     Collection<SignatureAndHashAlgorithm> getPeerSupportedSignAlgs() {
 451         return peerSupportedSignAlgs;
 452     }
 453 
 454 
 455     /**
 456      * Set the identification protocol. Called from the constructor or
 457      * SSLSocketImpl/SSLEngineImpl.setIdentificationProtocol() (if the
 458      * handshake is not yet in progress).
 459      */
 460     void setIdentificationProtocol(String protocol) {
 461         this.identificationProtocol = protocol;
 462     }
 463 
 464     /**
 465      * Sets the server name indication of the handshake.
 466      */
 467     void setSNIServerNames(List<SNIServerName> serverNames) {
 468         // The serverNames parameter is unmodifiable.
 469         this.serverNames = serverNames;
 470     }
 471 
 472     /**
 473      * Sets the server name matchers of the handshaking.
 474      */
 475     void setSNIMatchers(Collection<SNIMatcher> sniMatchers) {
 476         // The sniMatchers parameter is unmodifiable.
 477         this.sniMatchers = sniMatchers;
 478     }
 479 
 480     /**
 481      * Sets the cipher suites preference.
 482      */
 483     void setUseCipherSuitesOrder(boolean on) {
 484         this.preferLocalCipherSuites = on;
 485     }
 486 
 487     /**
 488      * Sets whether to send TLS_FALLBACK_SCSV.
 489      */
 490     void setSendFallbackSCSV(boolean on) {
 491         this.sendFallbackSCSV = on;
 492     }
 493 
 494     /**
 495      * Prior to handshaking, activate the handshake and initialize the version,
 496      * input stream and output stream.
 497      */
 498     void activate(ProtocolVersion helloVersion) throws IOException {
 499         if (activeProtocols == null) {
 500             activeProtocols = getActiveProtocols();
 501         }
 502 
 503         if (activeProtocols.collection().isEmpty() ||
 504                 activeProtocols.max.v == ProtocolVersion.NONE.v) {
 505             throw new SSLHandshakeException("No appropriate protocol");
 506         }
 507 
 508         if (activeCipherSuites == null) {
 509             activeCipherSuites = getActiveCipherSuites();
 510         }
 511 
 512         if (activeCipherSuites.collection().isEmpty()) {
 513             throw new SSLHandshakeException("No appropriate cipher suite");
 514         }
 515 
 516         // temporary protocol version until the actual protocol version
 517         // is negotiated in the Hello exchange. This affects the record
 518         // version we sent with the ClientHello.
 519         if (!isInitialHandshake) {
 520             protocolVersion = activeProtocolVersion;
 521         } else {
 522             protocolVersion = activeProtocols.max;
 523         }
 524 
 525         if (helloVersion == null || helloVersion.v == ProtocolVersion.NONE.v) {
 526             helloVersion = activeProtocols.helloVersion;
 527         }
 528 
 529         // We accumulate digests of the handshake messages so that
 530         // we can read/write CertificateVerify and Finished messages,
 531         // getting assurance against some particular active attacks.
 532         handshakeHash = new HandshakeHash(needCertVerify);
 533 
 534         // Generate handshake input/output stream.
 535         input = new HandshakeInStream(handshakeHash);
 536         if (conn != null) {
 537             output = new HandshakeOutStream(protocolVersion, helloVersion,
 538                                         handshakeHash, conn);
 539             conn.getAppInputStream().r.setHandshakeHash(handshakeHash);
 540             conn.getAppInputStream().r.setHelloVersion(helloVersion);
 541             conn.getAppOutputStream().r.setHelloVersion(helloVersion);
 542         } else {
 543             output = new HandshakeOutStream(protocolVersion, helloVersion,
 544                                         handshakeHash, engine);
 545             engine.inputRecord.setHandshakeHash(handshakeHash);
 546             engine.inputRecord.setHelloVersion(helloVersion);
 547             engine.outputRecord.setHelloVersion(helloVersion);
 548         }
 549 
 550         // move state to activated
 551         state = -1;
 552     }
 553 
 554     /**
 555      * Set cipherSuite and keyExchange to the given CipherSuite.
 556      * Does not perform any verification that this is a valid selection,
 557      * this must be done before calling this method.
 558      */
 559     void setCipherSuite(CipherSuite s) {
 560         this.cipherSuite = s;
 561         this.keyExchange = s.keyExchange;
 562     }
 563 
 564     /**
 565      * Check if the given ciphersuite is enabled and available within the
 566      * current active cipher suites.
 567      *
 568      * Does not check if the required server certificates are available.
 569      */
 570     boolean isNegotiable(CipherSuite s) {
 571         if (activeCipherSuites == null) {
 572             activeCipherSuites = getActiveCipherSuites();
 573         }
 574 
 575         return isNegotiable(activeCipherSuites, s);
 576     }
 577 
 578     /**
 579      * Check if the given ciphersuite is enabled and available within the
 580      * proposed cipher suite list.
 581      *
 582      * Does not check if the required server certificates are available.
 583      */
 584     final static boolean isNegotiable(CipherSuiteList proposed, CipherSuite s) {
 585         return proposed.contains(s) && s.isNegotiable();
 586     }
 587 
 588     /**
 589      * Check if the given protocol version is enabled and available.
 590      */
 591     boolean isNegotiable(ProtocolVersion protocolVersion) {
 592         if (activeProtocols == null) {
 593             activeProtocols = getActiveProtocols();
 594         }
 595 
 596         return activeProtocols.contains(protocolVersion);
 597     }
 598 
 599     /**
 600      * Select a protocol version from the list. Called from
 601      * ServerHandshaker to negotiate protocol version.
 602      *
 603      * Return the lower of the protocol version suggested in the
 604      * clien hello and the highest supported by the server.
 605      */
 606     ProtocolVersion selectProtocolVersion(ProtocolVersion protocolVersion) {
 607         if (activeProtocols == null) {
 608             activeProtocols = getActiveProtocols();
 609         }
 610 
 611         return activeProtocols.selectProtocolVersion(protocolVersion);
 612     }
 613 
 614     /**
 615      * Get the active cipher suites.
 616      *
 617      * In TLS 1.1, many weak or vulnerable cipher suites were obsoleted,
 618      * such as TLS_RSA_EXPORT_WITH_RC4_40_MD5. The implementation MUST NOT
 619      * negotiate these cipher suites in TLS 1.1 or later mode.
 620      *
 621      * Therefore, when the active protocols only include TLS 1.1 or later,
 622      * the client cannot request to negotiate those obsoleted cipher
 623      * suites.  That is, the obsoleted suites should not be included in the
 624      * client hello. So we need to create a subset of the enabled cipher
 625      * suites, the active cipher suites, which does not contain obsoleted
 626      * cipher suites of the minimum active protocol.
 627      *
 628      * Return empty list instead of null if no active cipher suites.
 629      */
 630     CipherSuiteList getActiveCipherSuites() {
 631         if (activeCipherSuites == null) {
 632             if (activeProtocols == null) {
 633                 activeProtocols = getActiveProtocols();
 634             }
 635 
 636             ArrayList<CipherSuite> suites = new ArrayList<>();
 637             if (!(activeProtocols.collection().isEmpty()) &&
 638                     activeProtocols.min.v != ProtocolVersion.NONE.v) {
 639                 for (CipherSuite suite : enabledCipherSuites.collection()) {
 640                     if (suite.obsoleted > activeProtocols.min.v &&
 641                             suite.supported <= activeProtocols.max.v) {
 642                         if (algorithmConstraints.permits(
 643                                 EnumSet.of(CryptoPrimitive.KEY_AGREEMENT),
 644                                 suite.name, null)) {
 645                             suites.add(suite);
 646                         }
 647                     } else if (debug != null && Debug.isOn("verbose")) {
 648                         if (suite.obsoleted <= activeProtocols.min.v) {
 649                             System.out.println(
 650                                 "Ignoring obsoleted cipher suite: " + suite);
 651                         } else {
 652                             System.out.println(
 653                                 "Ignoring unsupported cipher suite: " + suite);
 654                         }
 655                     }
 656                 }
 657             }
 658             activeCipherSuites = new CipherSuiteList(suites);
 659         }
 660 
 661         return activeCipherSuites;
 662     }
 663 
 664     /*
 665      * Get the active protocol versions.
 666      *
 667      * In TLS 1.1, many weak or vulnerable cipher suites were obsoleted,
 668      * such as TLS_RSA_EXPORT_WITH_RC4_40_MD5. The implementation MUST NOT
 669      * negotiate these cipher suites in TLS 1.1 or later mode.
 670      *
 671      * For example, if "TLS_RSA_EXPORT_WITH_RC4_40_MD5" is the
 672      * only enabled cipher suite, the client cannot request TLS 1.1 or
 673      * later, even though TLS 1.1 or later is enabled.  We need to create a
 674      * subset of the enabled protocols, called the active protocols, which
 675      * contains protocols appropriate to the list of enabled Ciphersuites.
 676      *
 677      * Return empty list instead of null if no active protocol versions.
 678      */
 679     ProtocolList getActiveProtocols() {
 680         if (activeProtocols == null) {
 681             boolean enabledSSL20Hello = false;
 682             ArrayList<ProtocolVersion> protocols = new ArrayList<>(4);
 683             for (ProtocolVersion protocol : enabledProtocols.collection()) {
 684                 // Need not to check the SSL20Hello protocol.
 685                 if (protocol.v == ProtocolVersion.SSL20Hello.v) {
 686                     enabledSSL20Hello = true;
 687                     continue;
 688                 }
 689 
 690                 boolean found = false;
 691                 for (CipherSuite suite : enabledCipherSuites.collection()) {
 692                     if (suite.isAvailable() && suite.obsoleted > protocol.v &&
 693                                                suite.supported <= protocol.v) {
 694                         if (algorithmConstraints.permits(
 695                                 EnumSet.of(CryptoPrimitive.KEY_AGREEMENT),
 696                                 suite.name, null)) {
 697                             protocols.add(protocol);
 698                             found = true;
 699                             break;
 700                         } else if (debug != null && Debug.isOn("verbose")) {
 701                             System.out.println(
 702                                 "Ignoring disabled cipher suite: " + suite +
 703                                  " for " + protocol);
 704                         }
 705                     } else if (debug != null && Debug.isOn("verbose")) {
 706                         System.out.println(
 707                             "Ignoring unsupported cipher suite: " + suite +
 708                                  " for " + protocol);
 709                     }
 710                 }
 711                 if (!found && (debug != null) && Debug.isOn("handshake")) {
 712                     System.out.println(
 713                         "No available cipher suite for " + protocol);
 714                 }
 715             }
 716 
 717             if (!protocols.isEmpty() && enabledSSL20Hello) {
 718                 protocols.add(ProtocolVersion.SSL20Hello);
 719             }
 720 
 721             activeProtocols = new ProtocolList(protocols);
 722         }
 723 
 724         return activeProtocols;
 725     }
 726 
 727     /**
 728      * As long as handshaking has not activated, we can
 729      * change whether session creations are allowed.
 730      *
 731      * Callers should do their own checking if handshaking
 732      * has activated.
 733      */
 734     void setEnableSessionCreation(boolean newSessions) {
 735         enableNewSession = newSessions;
 736     }
 737 
 738     /**
 739      * Create a new read cipher and return it to caller.
 740      */
 741     CipherBox newReadCipher() throws NoSuchAlgorithmException {
 742         BulkCipher cipher = cipherSuite.cipher;
 743         CipherBox box;
 744         if (isClient) {
 745             box = cipher.newCipher(protocolVersion, svrWriteKey, svrWriteIV,
 746                                    sslContext.getSecureRandom(), false);
 747             svrWriteKey = null;
 748             svrWriteIV = null;
 749         } else {
 750             box = cipher.newCipher(protocolVersion, clntWriteKey, clntWriteIV,
 751                                    sslContext.getSecureRandom(), false);
 752             clntWriteKey = null;
 753             clntWriteIV = null;
 754         }
 755         return box;
 756     }
 757 
 758     /**
 759      * Create a new write cipher and return it to caller.
 760      */
 761     CipherBox newWriteCipher() throws NoSuchAlgorithmException {
 762         BulkCipher cipher = cipherSuite.cipher;
 763         CipherBox box;
 764         if (isClient) {
 765             box = cipher.newCipher(protocolVersion, clntWriteKey, clntWriteIV,
 766                                    sslContext.getSecureRandom(), true);
 767             clntWriteKey = null;
 768             clntWriteIV = null;
 769         } else {
 770             box = cipher.newCipher(protocolVersion, svrWriteKey, svrWriteIV,
 771                                    sslContext.getSecureRandom(), true);
 772             svrWriteKey = null;
 773             svrWriteIV = null;
 774         }
 775         return box;
 776     }
 777 
 778     /**
 779      * Create a new read MAC and return it to caller.
 780      */
 781     Authenticator newReadAuthenticator()
 782             throws NoSuchAlgorithmException, InvalidKeyException {
 783 
 784         Authenticator authenticator = null;
 785         if (cipherSuite.cipher.cipherType == AEAD_CIPHER) {
 786             authenticator = new Authenticator(protocolVersion);
 787         } else {
 788             MacAlg macAlg = cipherSuite.macAlg;
 789             if (isClient) {
 790                 authenticator = macAlg.newMac(protocolVersion, svrMacSecret);
 791                 svrMacSecret = null;
 792             } else {
 793                 authenticator = macAlg.newMac(protocolVersion, clntMacSecret);
 794                 clntMacSecret = null;
 795             }
 796         }
 797 
 798         return authenticator;
 799     }
 800 
 801     /**
 802      * Create a new write MAC and return it to caller.
 803      */
 804     Authenticator newWriteAuthenticator()
 805             throws NoSuchAlgorithmException, InvalidKeyException {
 806 
 807         Authenticator authenticator = null;
 808         if (cipherSuite.cipher.cipherType == AEAD_CIPHER) {
 809             authenticator = new Authenticator(protocolVersion);
 810         } else {
 811             MacAlg macAlg = cipherSuite.macAlg;
 812             if (isClient) {
 813                 authenticator = macAlg.newMac(protocolVersion, clntMacSecret);
 814                 clntMacSecret = null;
 815             } else {
 816                 authenticator = macAlg.newMac(protocolVersion, svrMacSecret);
 817                 svrMacSecret = null;
 818             }
 819         }
 820 
 821         return authenticator;
 822     }
 823 
 824     /*
 825      * Returns true iff the handshake sequence is done, so that
 826      * this freshly created session can become the current one.
 827      */
 828     boolean isDone() {
 829         return state == HandshakeMessage.ht_finished;
 830     }
 831 
 832 
 833     /*
 834      * Returns the session which was created through this
 835      * handshake sequence ... should be called after isDone()
 836      * returns true.
 837      */
 838     SSLSessionImpl getSession() {
 839         return session;
 840     }
 841 
 842     /*
 843      * Set the handshake session
 844      */
 845     void setHandshakeSessionSE(SSLSessionImpl handshakeSession) {
 846         if (conn != null) {
 847             conn.setHandshakeSession(handshakeSession);
 848         } else {
 849             engine.setHandshakeSession(handshakeSession);
 850         }
 851     }
 852 
 853     /*
 854      * Returns true if renegotiation is in use for this connection.
 855      */
 856     boolean isSecureRenegotiation() {
 857         return secureRenegotiation;
 858     }
 859 
 860     /*
 861      * Returns the verify_data from the Finished message sent by the client.
 862      */
 863     byte[] getClientVerifyData() {
 864         return clientVerifyData;
 865     }
 866 
 867     /*
 868      * Returns the verify_data from the Finished message sent by the server.
 869      */
 870     byte[] getServerVerifyData() {
 871         return serverVerifyData;
 872     }
 873 
 874     /*
 875      * This routine is fed SSL handshake records when they become available,
 876      * and processes messages found therein.
 877      */
 878     void process_record(InputRecord r, boolean expectingFinished)
 879             throws IOException {
 880 
 881         checkThrown();
 882 
 883         /*
 884          * Store the incoming handshake data, then see if we can
 885          * now process any completed handshake messages
 886          */
 887         input.incomingRecord(r);
 888 
 889         /*
 890          * We don't need to create a separate delegatable task
 891          * for finished messages.
 892          */
 893         if ((conn != null) || expectingFinished) {
 894             processLoop();
 895         } else {
 896             delegateTask(new PrivilegedExceptionAction<Void>() {
 897                 @Override
 898                 public Void run() throws Exception {
 899                     processLoop();
 900                     return null;
 901                 }
 902             });
 903         }
 904     }
 905 
 906     /*
 907      * On input, we hash messages one at a time since servers may need
 908      * to access an intermediate hash to validate a CertificateVerify
 909      * message.
 910      *
 911      * Note that many handshake messages can come in one record (and often
 912      * do, to reduce network resource utilization), and one message can also
 913      * require multiple records (e.g. very large Certificate messages).
 914      */
 915     void processLoop() throws IOException {
 916 
 917         // need to read off 4 bytes at least to get the handshake
 918         // message type and length.
 919         while (input.available() >= 4) {
 920             byte messageType;
 921             int messageLen;
 922 
 923             /*
 924              * See if we can read the handshake message header, and
 925              * then the entire handshake message.  If not, wait till
 926              * we can read and process an entire message.
 927              */
 928             input.mark(4);
 929 
 930             messageType = (byte)input.getInt8();
 931             messageLen = input.getInt24();
 932 
 933             if (input.available() < messageLen) {
 934                 input.reset();
 935                 return;
 936             }
 937 
 938             /*
 939              * Process the message.  We require
 940              * that processMessage() consumes the entire message.  In
 941              * lieu of explicit error checks (how?!) we assume that the
 942              * data will look like garbage on encoding/processing errors,
 943              * and that other protocol code will detect such errors.
 944              *
 945              * Note that digesting is normally deferred till after the
 946              * message has been processed, though to process at least the
 947              * client's Finished message (i.e. send the server's) we need
 948              * to acccelerate that digesting.
 949              *
 950              * Also, note that hello request messages are never hashed;
 951              * that includes the hello request header, too.
 952              */
 953             if (messageType == HandshakeMessage.ht_hello_request) {
 954                 input.reset();
 955                 processMessage(messageType, messageLen);
 956                 input.ignore(4 + messageLen);
 957             } else {
 958                 input.mark(messageLen);
 959                 processMessage(messageType, messageLen);
 960                 input.digestNow();
 961             }
 962         }
 963     }
 964 
 965 
 966     /**
 967      * Returns true iff the handshaker has been activated.
 968      *
 969      * In activated state, the handshaker may not send any messages out.
 970      */
 971     boolean activated() {
 972         return state >= -1;
 973     }
 974 
 975     /**
 976      * Returns true iff the handshaker has sent any messages.
 977      */
 978     boolean started() {
 979         return state >= 0;  // 0: HandshakeMessage.ht_hello_request
 980                             // 1: HandshakeMessage.ht_client_hello
 981     }
 982 
 983 
 984     /*
 985      * Used to kickstart the negotiation ... either writing a
 986      * ClientHello or a HelloRequest as appropriate, whichever
 987      * the subclass returns.  NOP if handshaking's already started.
 988      */
 989     void kickstart() throws IOException {
 990         if (state >= 0) {
 991             return;
 992         }
 993 
 994         HandshakeMessage m = getKickstartMessage();
 995 
 996         if (debug != null && Debug.isOn("handshake")) {
 997             m.print(System.out);
 998         }
 999         m.write(output);
1000         output.flush();
1001 
1002         state = m.messageType();
1003     }
1004 
1005     /**
1006      * Both client and server modes can start handshaking; but the
1007      * message they send to do so is different.
1008      */
1009     abstract HandshakeMessage getKickstartMessage() throws SSLException;
1010 
1011     /*
1012      * Client and Server side protocols are each driven though this
1013      * call, which processes a single message and drives the appropriate
1014      * side of the protocol state machine (depending on the subclass).
1015      */
1016     abstract void processMessage(byte messageType, int messageLen)
1017         throws IOException;
1018 
1019     /*
1020      * Most alerts in the protocol relate to handshaking problems.
1021      * Alerts are detected as the connection reads data.
1022      */
1023     abstract void handshakeAlert(byte description) throws SSLProtocolException;
1024 
1025     /*
1026      * Sends a change cipher spec message and updates the write side
1027      * cipher state so that future messages use the just-negotiated spec.
1028      */
1029     void sendChangeCipherSpec(Finished mesg, boolean lastMessage)
1030             throws IOException {
1031 
1032         output.flush(); // i.e. handshake data
1033 
1034         /*
1035          * The write cipher state is protected by the connection write lock
1036          * so we must grab it while making the change. We also
1037          * make sure no writes occur between sending the ChangeCipherSpec
1038          * message, installing the new cipher state, and sending the
1039          * Finished message.
1040          *
1041          * We already hold SSLEngine/SSLSocket "this" by virtue
1042          * of this being called from the readRecord code.
1043          */
1044         OutputRecord r;
1045         if (conn != null) {
1046             r = new OutputRecord(Record.ct_change_cipher_spec);
1047         } else {
1048             r = new EngineOutputRecord(Record.ct_change_cipher_spec, engine);
1049         }
1050 
1051         r.setVersion(protocolVersion);
1052         r.write(1);     // single byte of data
1053 
1054         if (conn != null) {
1055             conn.writeLock.lock();
1056             try {
1057                 conn.writeRecord(r);
1058                 conn.changeWriteCiphers();
1059                 if (debug != null && Debug.isOn("handshake")) {
1060                     mesg.print(System.out);
1061                 }
1062                 mesg.write(output);
1063                 output.flush();
1064             } finally {
1065                 conn.writeLock.unlock();
1066             }
1067         } else {
1068             synchronized (engine.writeLock) {
1069                 engine.writeRecord((EngineOutputRecord)r);
1070                 engine.changeWriteCiphers();
1071                 if (debug != null && Debug.isOn("handshake")) {
1072                     mesg.print(System.out);
1073                 }
1074                 mesg.write(output);
1075 
1076                 if (lastMessage) {
1077                     output.setFinishedMsg();
1078                 }
1079                 output.flush();
1080             }
1081         }
1082     }
1083 
1084     /*
1085      * Single access point to key calculation logic.  Given the
1086      * pre-master secret and the nonces from client and server,
1087      * produce all the keying material to be used.
1088      */
1089     void calculateKeys(SecretKey preMasterSecret, ProtocolVersion version) {
1090         SecretKey master = calculateMasterSecret(preMasterSecret, version);
1091         session.setMasterSecret(master);
1092         calculateConnectionKeys(master);
1093     }
1094 
1095 
1096     /*
1097      * Calculate the master secret from its various components.  This is
1098      * used for key exchange by all cipher suites.
1099      *
1100      * The master secret is the catenation of three MD5 hashes, each
1101      * consisting of the pre-master secret and a SHA1 hash.  Those three
1102      * SHA1 hashes are of (different) constant strings, the pre-master
1103      * secret, and the nonces provided by the client and the server.
1104      */
1105     private SecretKey calculateMasterSecret(SecretKey preMasterSecret,
1106             ProtocolVersion requestedVersion) {
1107 
1108         if (debug != null && Debug.isOn("keygen")) {
1109             HexDumpEncoder      dump = new HexDumpEncoder();
1110 
1111             System.out.println("SESSION KEYGEN:");
1112 
1113             System.out.println("PreMaster Secret:");
1114             printHex(dump, preMasterSecret.getEncoded());
1115 
1116             // Nonces are dumped with connection keygen, no
1117             // benefit to doing it twice
1118         }
1119 
1120         // What algs/params do we need to use?
1121         String masterAlg;
1122         PRF prf;
1123 
1124         if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
1125             masterAlg = "SunTls12MasterSecret";
1126             prf = cipherSuite.prfAlg;
1127         } else {
1128             masterAlg = "SunTlsMasterSecret";
1129             prf = P_NONE;
1130         }
1131 
1132         String prfHashAlg = prf.getPRFHashAlg();
1133         int prfHashLength = prf.getPRFHashLength();
1134         int prfBlockSize = prf.getPRFBlockSize();
1135 
1136         TlsMasterSecretParameterSpec spec = new TlsMasterSecretParameterSpec(
1137                 preMasterSecret, protocolVersion.major, protocolVersion.minor,
1138                 clnt_random.random_bytes, svr_random.random_bytes,
1139                 prfHashAlg, prfHashLength, prfBlockSize);
1140 
1141         try {
1142             KeyGenerator kg = JsseJce.getKeyGenerator(masterAlg);
1143             kg.init(spec);
1144             return kg.generateKey();
1145         } catch (InvalidAlgorithmParameterException |
1146                 NoSuchAlgorithmException iae) {
1147             // unlikely to happen, otherwise, must be a provider exception
1148             //
1149             // For RSA premaster secrets, do not signal a protocol error
1150             // due to the Bleichenbacher attack. See comments further down.
1151             if (debug != null && Debug.isOn("handshake")) {
1152                 System.out.println("RSA master secret generation error:");
1153                 iae.printStackTrace(System.out);
1154             }
1155             throw new ProviderException(iae);
1156 
1157         }
1158     }
1159 
1160     /*
1161      * Calculate the keys needed for this connection, once the session's
1162      * master secret has been calculated.  Uses the master key and nonces;
1163      * the amount of keying material generated is a function of the cipher
1164      * suite that's been negotiated.
1165      *
1166      * This gets called both on the "full handshake" (where we exchanged
1167      * a premaster secret and started a new session) as well as on the
1168      * "fast handshake" (where we just resumed a pre-existing session).
1169      */
1170     void calculateConnectionKeys(SecretKey masterKey) {
1171         /*
1172          * For both the read and write sides of the protocol, we use the
1173          * master to generate MAC secrets and cipher keying material.  Block
1174          * ciphers need initialization vectors, which we also generate.
1175          *
1176          * First we figure out how much keying material is needed.
1177          */
1178         int hashSize = cipherSuite.macAlg.size;
1179         boolean is_exportable = cipherSuite.exportable;
1180         BulkCipher cipher = cipherSuite.cipher;
1181         int expandedKeySize = is_exportable ? cipher.expandedKeySize : 0;
1182 
1183         // Which algs/params do we need to use?
1184         String keyMaterialAlg;
1185         PRF prf;
1186 
1187         if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
1188             keyMaterialAlg = "SunTls12KeyMaterial";
1189             prf = cipherSuite.prfAlg;
1190         } else {
1191             keyMaterialAlg = "SunTlsKeyMaterial";
1192             prf = P_NONE;
1193         }
1194 
1195         String prfHashAlg = prf.getPRFHashAlg();
1196         int prfHashLength = prf.getPRFHashLength();
1197         int prfBlockSize = prf.getPRFBlockSize();
1198 
1199         // TLS v1.1 or later uses an explicit IV in CBC cipher suites to
1200         // protect against the CBC attacks.  AEAD/GCM cipher suites in TLS
1201         // v1.2 or later use a fixed IV as the implicit part of the partially
1202         // implicit nonce technique described in RFC 5116.
1203         int ivSize = cipher.ivSize;
1204         if (cipher.cipherType == AEAD_CIPHER) {
1205             ivSize = cipher.fixedIvSize;
1206         } else if (protocolVersion.v >= ProtocolVersion.TLS11.v &&
1207                 cipher.cipherType == BLOCK_CIPHER) {
1208             ivSize = 0;
1209         }
1210 
1211         TlsKeyMaterialParameterSpec spec = new TlsKeyMaterialParameterSpec(
1212             masterKey, protocolVersion.major, protocolVersion.minor,
1213             clnt_random.random_bytes, svr_random.random_bytes,
1214             cipher.algorithm, cipher.keySize, expandedKeySize,
1215             ivSize, hashSize,
1216             prfHashAlg, prfHashLength, prfBlockSize);
1217 
1218         try {
1219             KeyGenerator kg = JsseJce.getKeyGenerator(keyMaterialAlg);
1220             kg.init(spec);
1221             TlsKeyMaterialSpec keySpec = (TlsKeyMaterialSpec)kg.generateKey();
1222 
1223             // Return null if cipher keys are not supposed to be generated.
1224             clntWriteKey = keySpec.getClientCipherKey();
1225             svrWriteKey = keySpec.getServerCipherKey();
1226 
1227             // Return null if IVs are not supposed to be generated.
1228             clntWriteIV = keySpec.getClientIv();
1229             svrWriteIV = keySpec.getServerIv();
1230 
1231             // Return null if MAC keys are not supposed to be generated.
1232             clntMacSecret = keySpec.getClientMacKey();
1233             svrMacSecret = keySpec.getServerMacKey();
1234         } catch (GeneralSecurityException e) {
1235             throw new ProviderException(e);
1236         }
1237 
1238         //
1239         // Dump the connection keys as they're generated.
1240         //
1241         if (debug != null && Debug.isOn("keygen")) {
1242             synchronized (System.out) {
1243                 HexDumpEncoder  dump = new HexDumpEncoder();
1244 
1245                 System.out.println("CONNECTION KEYGEN:");
1246 
1247                 // Inputs:
1248                 System.out.println("Client Nonce:");
1249                 printHex(dump, clnt_random.random_bytes);
1250                 System.out.println("Server Nonce:");
1251                 printHex(dump, svr_random.random_bytes);
1252                 System.out.println("Master Secret:");
1253                 printHex(dump, masterKey.getEncoded());
1254 
1255                 // Outputs:
1256                 if (clntMacSecret != null) {
1257                     System.out.println("Client MAC write Secret:");
1258                     printHex(dump, clntMacSecret.getEncoded());
1259                     System.out.println("Server MAC write Secret:");
1260                     printHex(dump, svrMacSecret.getEncoded());
1261                 } else {
1262                     System.out.println("... no MAC keys used for this cipher");
1263                 }
1264 
1265                 if (clntWriteKey != null) {
1266                     System.out.println("Client write key:");
1267                     printHex(dump, clntWriteKey.getEncoded());
1268                     System.out.println("Server write key:");
1269                     printHex(dump, svrWriteKey.getEncoded());
1270                 } else {
1271                     System.out.println("... no encryption keys used");
1272                 }
1273 
1274                 if (clntWriteIV != null) {
1275                     System.out.println("Client write IV:");
1276                     printHex(dump, clntWriteIV.getIV());
1277                     System.out.println("Server write IV:");
1278                     printHex(dump, svrWriteIV.getIV());
1279                 } else {
1280                     if (protocolVersion.v >= ProtocolVersion.TLS11.v) {
1281                         System.out.println(
1282                                 "... no IV derived for this protocol");
1283                     } else {
1284                         System.out.println("... no IV used for this cipher");
1285                     }
1286                 }
1287                 System.out.flush();
1288             }
1289         }
1290     }
1291 
1292     private static void printHex(HexDumpEncoder dump, byte[] bytes) {
1293         if (bytes == null) {
1294             System.out.println("(key bytes not available)");
1295         } else {
1296             try {
1297                 dump.encodeBuffer(bytes, System.out);
1298             } catch (IOException e) {
1299                 // just for debugging, ignore this
1300             }
1301         }
1302     }
1303 
1304     /**
1305      * Throw an SSLException with the specified message and cause.
1306      * Shorthand until a new SSLException constructor is added.
1307      * This method never returns.
1308      */
1309     static void throwSSLException(String msg, Throwable cause)
1310             throws SSLException {
1311         SSLException e = new SSLException(msg);
1312         e.initCause(cause);
1313         throw e;
1314     }
1315 
1316 
1317     /*
1318      * Implement a simple task delegator.
1319      *
1320      * We are currently implementing this as a single delegator, may
1321      * try for parallel tasks later.  Client Authentication could
1322      * benefit from this, where ClientKeyExchange/CertificateVerify
1323      * could be carried out in parallel.
1324      */
1325     class DelegatedTask<E> implements Runnable {
1326 
1327         private PrivilegedExceptionAction<E> pea;
1328 
1329         DelegatedTask(PrivilegedExceptionAction<E> pea) {
1330             this.pea = pea;
1331         }
1332 
1333         public void run() {
1334             synchronized (engine) {
1335                 try {
1336                     AccessController.doPrivileged(pea, engine.getAcc());
1337                 } catch (PrivilegedActionException pae) {
1338                     thrown = pae.getException();
1339                 } catch (RuntimeException rte) {
1340                     thrown = rte;
1341                 }
1342                 delegatedTask = null;
1343                 taskDelegated = false;
1344             }
1345         }
1346     }
1347 
1348     private <T> void delegateTask(PrivilegedExceptionAction<T> pea) {
1349         delegatedTask = new DelegatedTask<T>(pea);
1350         taskDelegated = false;
1351         thrown = null;
1352     }
1353 
1354     DelegatedTask<?> getTask() {
1355         if (!taskDelegated) {
1356             taskDelegated = true;
1357             return delegatedTask;
1358         } else {
1359             return null;
1360         }
1361     }
1362 
1363     /*
1364      * See if there are any tasks which need to be delegated
1365      *
1366      * Locked by SSLEngine.this.
1367      */
1368     boolean taskOutstanding() {
1369         return (delegatedTask != null);
1370     }
1371 
1372     /*
1373      * The previous caller failed for some reason, report back the
1374      * Exception.  We won't worry about Error's.
1375      *
1376      * Locked by SSLEngine.this.
1377      */
1378     void checkThrown() throws SSLException {
1379         synchronized (thrownLock) {
1380             if (thrown != null) {
1381 
1382                 String msg = thrown.getMessage();
1383 
1384                 if (msg == null) {
1385                     msg = "Delegated task threw Exception/Error";
1386                 }
1387 
1388                 /*
1389                  * See what the underlying type of exception is.  We should
1390                  * throw the same thing.  Chain thrown to the new exception.
1391                  */
1392                 Exception e = thrown;
1393                 thrown = null;
1394 
1395                 if (e instanceof RuntimeException) {
1396                     throw new RuntimeException(msg, e);
1397                 } else if (e instanceof SSLHandshakeException) {
1398                     throw (SSLHandshakeException)
1399                         new SSLHandshakeException(msg).initCause(e);
1400                 } else if (e instanceof SSLKeyException) {
1401                     throw (SSLKeyException)
1402                         new SSLKeyException(msg).initCause(e);
1403                 } else if (e instanceof SSLPeerUnverifiedException) {
1404                     throw (SSLPeerUnverifiedException)
1405                         new SSLPeerUnverifiedException(msg).initCause(e);
1406                 } else if (e instanceof SSLProtocolException) {
1407                     throw (SSLProtocolException)
1408                         new SSLProtocolException(msg).initCause(e);
1409                 } else {
1410                     /*
1411                      * If it's SSLException or any other Exception,
1412                      * we'll wrap it in an SSLException.
1413                      */
1414                     throw new SSLException(msg, e);
1415                 }
1416             }
1417         }
1418     }
1419 }