1 /*
   2  * Copyright (c) 1996, 2017, 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.util.concurrent.TimeUnit;
  32 import java.security.*;
  33 import java.security.cert.*;
  34 import java.security.interfaces.*;
  35 import java.security.spec.ECParameterSpec;
  36 import java.math.BigInteger;
  37 import java.util.function.BiFunction;
  38 
  39 import javax.crypto.SecretKey;
  40 import javax.net.ssl.*;
  41 
  42 import sun.security.action.GetLongAction;
  43 import sun.security.util.KeyUtil;
  44 import sun.security.util.LegacyAlgorithmConstraints;
  45 import sun.security.action.GetPropertyAction;
  46 import sun.security.ssl.HandshakeMessage.*;
  47 import sun.security.ssl.CipherSuite.*;
  48 import sun.security.ssl.SignatureAndHashAlgorithm.*;
  49 import static sun.security.ssl.CipherSuite.KeyExchange.*;
  50 
  51 /**
  52  * ServerHandshaker does the protocol handshaking from the point
  53  * of view of a server.  It is driven asychronously by handshake messages
  54  * as delivered by the parent Handshaker class, and also uses
  55  * common functionality (e.g. key generation) that is provided there.
  56  *
  57  * @author David Brownell
  58  */
  59 final class ServerHandshaker extends Handshaker {
  60 
  61     // The default number of milliseconds the handshaker will wait for
  62     // revocation status responses.
  63     private static final long DEFAULT_STATUS_RESP_DELAY = 5000;
  64 
  65     // is the server going to require the client to authenticate?
  66     private ClientAuthType      doClientAuth;
  67 
  68     // our authentication info
  69     private X509Certificate[]   certs;
  70     private PrivateKey          privateKey;
  71 
  72     private Object              serviceCreds;
  73 
  74     // flag to check for clientCertificateVerify message
  75     private boolean             needClientVerify = false;
  76 
  77     /*
  78      * For exportable ciphersuites using non-exportable key sizes, we use
  79      * ephemeral RSA keys. We could also do anonymous RSA in the same way
  80      * but there are no such ciphersuites currently defined.
  81      */
  82     private PrivateKey          tempPrivateKey;
  83     private PublicKey           tempPublicKey;
  84 
  85     /*
  86      * For anonymous and ephemeral Diffie-Hellman key exchange, we use
  87      * ephemeral Diffie-Hellman keys.
  88      */
  89     private DHCrypt dh;
  90 
  91     // Helper for ECDH based key exchanges
  92     private ECDHCrypt ecdh;
  93 
  94     // version request by the client in its ClientHello
  95     // we remember it for the RSA premaster secret version check
  96     private ProtocolVersion clientRequestedVersion;
  97 
  98     // client supported elliptic curves
  99     private SupportedGroupsExtension requestedGroups;
 100 
 101     // the preferable signature algorithm used by ServerKeyExchange message
 102     SignatureAndHashAlgorithm preferableSignatureAlgorithm;
 103 
 104     // Flag to use smart ephemeral DH key which size matches the corresponding
 105     // authentication key
 106     private static final boolean useSmartEphemeralDHKeys;
 107 
 108     // Flag to use legacy ephemeral DH key which size is 512 bits for
 109     // exportable cipher suites, and 768 bits for others
 110     private static final boolean useLegacyEphemeralDHKeys;
 111 
 112     // The customized ephemeral DH key size for non-exportable cipher suites.
 113     private static final int customizedDHKeySize;
 114 
 115     // legacy algorithm constraints
 116     private static final AlgorithmConstraints legacyAlgorithmConstraints =
 117             new LegacyAlgorithmConstraints(
 118                     LegacyAlgorithmConstraints.PROPERTY_TLS_LEGACY_ALGS,
 119                     new SSLAlgorithmDecomposer());
 120 
 121     private long statusRespTimeout;
 122 
 123     static {
 124         String property = GetPropertyAction
 125                 .privilegedGetProperty("jdk.tls.ephemeralDHKeySize");
 126         if (property == null || property.length() == 0) {
 127             useLegacyEphemeralDHKeys = false;
 128             useSmartEphemeralDHKeys = false;
 129             customizedDHKeySize = -1;
 130         } else if ("matched".equals(property)) {
 131             useLegacyEphemeralDHKeys = false;
 132             useSmartEphemeralDHKeys = true;
 133             customizedDHKeySize = -1;
 134         } else if ("legacy".equals(property)) {
 135             useLegacyEphemeralDHKeys = true;
 136             useSmartEphemeralDHKeys = false;
 137             customizedDHKeySize = -1;
 138         } else {
 139             useLegacyEphemeralDHKeys = false;
 140             useSmartEphemeralDHKeys = false;
 141 
 142             try {
 143                 // DH parameter generation can be extremely slow, best to
 144                 // use one of the supported pre-computed DH parameters
 145                 // (see DHCrypt class).
 146                 customizedDHKeySize = Integer.parseUnsignedInt(property);
 147                 if (customizedDHKeySize < 1024 || customizedDHKeySize > 8192 ||
 148                         (customizedDHKeySize & 0x3f) != 0) {
 149                     throw new IllegalArgumentException(
 150                         "Unsupported customized DH key size: " +
 151                         customizedDHKeySize + ". " +
 152                         "The key size must be multiple of 64, " +
 153                         "and can only range from 1024 to 8192 (inclusive)");
 154                 }
 155             } catch (NumberFormatException nfe) {
 156                 throw new IllegalArgumentException(
 157                         "Invalid system property jdk.tls.ephemeralDHKeySize");
 158             }
 159         }
 160     }
 161 
 162     /*
 163      * Constructor ... use the keys found in the auth context.
 164      */
 165     ServerHandshaker(SSLSocketImpl socket, SSLContextImpl context,
 166             ProtocolList enabledProtocols, ClientAuthType clientAuth,
 167             ProtocolVersion activeProtocolVersion, boolean isInitialHandshake,
 168             boolean secureRenegotiation,
 169             byte[] clientVerifyData, byte[] serverVerifyData) {
 170 
 171         super(socket, context, enabledProtocols,
 172                 (clientAuth != ClientAuthType.CLIENT_AUTH_NONE), false,
 173                 activeProtocolVersion, isInitialHandshake, secureRenegotiation,
 174                 clientVerifyData, serverVerifyData);
 175         doClientAuth = clientAuth;
 176         statusRespTimeout = AccessController.doPrivileged(
 177                     new GetLongAction("jdk.tls.stapling.responseTimeout",
 178                         DEFAULT_STATUS_RESP_DELAY));
 179         statusRespTimeout = statusRespTimeout >= 0 ? statusRespTimeout :
 180                 DEFAULT_STATUS_RESP_DELAY;
 181     }
 182 
 183     /*
 184      * Constructor ... use the keys found in the auth context.
 185      */
 186     ServerHandshaker(SSLEngineImpl engine, SSLContextImpl context,
 187             ProtocolList enabledProtocols, ClientAuthType clientAuth,
 188             ProtocolVersion activeProtocolVersion,
 189             boolean isInitialHandshake, boolean secureRenegotiation,
 190             byte[] clientVerifyData, byte[] serverVerifyData,
 191             boolean isDTLS) {
 192 
 193         super(engine, context, enabledProtocols,
 194                 (clientAuth != ClientAuthType.CLIENT_AUTH_NONE), false,
 195                 activeProtocolVersion, isInitialHandshake, secureRenegotiation,
 196                 clientVerifyData, serverVerifyData, isDTLS);
 197         doClientAuth = clientAuth;
 198         statusRespTimeout = AccessController.doPrivileged(
 199                     new GetLongAction("jdk.tls.stapling.responseTimeout",
 200                         DEFAULT_STATUS_RESP_DELAY));
 201         statusRespTimeout = statusRespTimeout >= 0 ? statusRespTimeout :
 202                 DEFAULT_STATUS_RESP_DELAY;
 203     }
 204 
 205     /*
 206      * As long as handshaking has not started, we can change
 207      * whether client authentication is required.  Otherwise,
 208      * we will need to wait for the next handshake.
 209      */
 210     void setClientAuth(ClientAuthType clientAuth) {
 211         doClientAuth = clientAuth;
 212     }
 213 
 214     /*
 215      * This routine handles all the server side handshake messages, one at
 216      * a time.  Given the message type (and in some cases the pending cipher
 217      * spec) it parses the type-specific message.  Then it calls a function
 218      * that handles that specific message.
 219      *
 220      * It updates the state machine as each message is processed, and writes
 221      * responses as needed using the connection in the constructor.
 222      */
 223     @Override
 224     void processMessage(byte type, int message_len)
 225             throws IOException {
 226 
 227         // check the handshake state
 228         handshakeState.check(type);
 229 
 230         switch (type) {
 231             case HandshakeMessage.ht_client_hello:
 232                 ClientHello ch = new ClientHello(input, message_len, isDTLS);
 233                 handshakeState.update(ch, resumingSession);
 234 
 235                 /*
 236                  * send it off for processing.
 237                  */
 238                 this.clientHello(ch);
 239                 break;
 240 
 241             case HandshakeMessage.ht_certificate:
 242                 if (doClientAuth == ClientAuthType.CLIENT_AUTH_NONE) {
 243                     fatalSE(Alerts.alert_unexpected_message,
 244                                 "client sent unsolicited cert chain");
 245                     // NOTREACHED
 246                 }
 247                 CertificateMsg certificateMsg = new CertificateMsg(input);
 248                 handshakeState.update(certificateMsg, resumingSession);
 249                 this.clientCertificate(certificateMsg);
 250                 break;
 251 
 252             case HandshakeMessage.ht_client_key_exchange:
 253                 SecretKey preMasterSecret;
 254                 switch (keyExchange) {
 255                 case K_RSA:
 256                 case K_RSA_EXPORT:
 257                     /*
 258                      * The client's pre-master secret is decrypted using
 259                      * either the server's normal private RSA key, or the
 260                      * temporary one used for non-export or signing-only
 261                      * certificates/keys.
 262                      */
 263                     RSAClientKeyExchange pms = new RSAClientKeyExchange(
 264                             protocolVersion, clientRequestedVersion,
 265                             sslContext.getSecureRandom(), input,
 266                             message_len, privateKey);
 267                     handshakeState.update(pms, resumingSession);
 268                     preMasterSecret = this.clientKeyExchange(pms);
 269                     break;
 270                 case K_DHE_RSA:
 271                 case K_DHE_DSS:
 272                 case K_DH_ANON:
 273                     /*
 274                      * The pre-master secret is derived using the normal
 275                      * Diffie-Hellman calculation.   Note that the main
 276                      * protocol difference in these five flavors is in how
 277                      * the ServerKeyExchange message was constructed!
 278                      */
 279                     DHClientKeyExchange dhcke = new DHClientKeyExchange(input);
 280                     handshakeState.update(dhcke, resumingSession);
 281                     preMasterSecret = this.clientKeyExchange(dhcke);
 282                     break;
 283                 case K_ECDH_RSA:
 284                 case K_ECDH_ECDSA:
 285                 case K_ECDHE_RSA:
 286                 case K_ECDHE_ECDSA:
 287                 case K_ECDH_ANON:
 288                     ECDHClientKeyExchange ecdhcke =
 289                                     new ECDHClientKeyExchange(input);
 290                     handshakeState.update(ecdhcke, resumingSession);
 291                     preMasterSecret = this.clientKeyExchange(ecdhcke);
 292                     break;
 293                 default:
 294                     ClientKeyExchangeService p =
 295                             ClientKeyExchangeService.find(keyExchange.name);
 296                     if (p == null) {
 297                         throw new SSLProtocolException
 298                                 ("Unrecognized key exchange: " + keyExchange);
 299                     }
 300                     byte[] encodedTicket = input.getBytes16();
 301                     input.getBytes16();
 302                     byte[] secret = input.getBytes16();
 303                     ClientKeyExchange cke = p.createServerExchange(protocolVersion,
 304                             clientRequestedVersion,
 305                             sslContext.getSecureRandom(),
 306                             encodedTicket,
 307                             secret,
 308                             this.getAccSE(), serviceCreds);
 309                     handshakeState.update(cke, resumingSession);
 310                     preMasterSecret = this.clientKeyExchange(cke);
 311                     break;
 312                 }
 313 
 314                 //
 315                 // All keys are calculated from the premaster secret
 316                 // and the exchanged nonces in the same way.
 317                 //
 318                 calculateKeys(preMasterSecret, clientRequestedVersion);
 319                 break;
 320 
 321             case HandshakeMessage.ht_certificate_verify:
 322                 CertificateVerify cvm =
 323                         new CertificateVerify(input,
 324                             getLocalSupportedSignAlgs(), protocolVersion);
 325                 handshakeState.update(cvm, resumingSession);
 326                 this.clientCertificateVerify(cvm);
 327 
 328                 break;
 329 
 330             case HandshakeMessage.ht_finished:
 331                 Finished cfm =
 332                     new Finished(protocolVersion, input, cipherSuite);
 333                 handshakeState.update(cfm, resumingSession);
 334                 this.clientFinished(cfm);
 335 
 336                 break;
 337 
 338             default:
 339                 throw new SSLProtocolException(
 340                         "Illegal server handshake msg, " + type);
 341         }
 342 
 343     }
 344 
 345 
 346     /*
 347      * ClientHello presents the server with a bunch of options, to which the
 348      * server replies with a ServerHello listing the ones which this session
 349      * will use.  If needed, it also writes its Certificate plus in some cases
 350      * a ServerKeyExchange message.  It may also write a CertificateRequest,
 351      * to elicit a client certificate.
 352      *
 353      * All these messages are terminated by a ServerHelloDone message.  In
 354      * most cases, all this can be sent in a single Record.
 355      */
 356     private void clientHello(ClientHello mesg) throws IOException {
 357         if (debug != null && Debug.isOn("handshake")) {
 358             mesg.print(System.out);
 359         }
 360 
 361         // Reject client initiated renegotiation?
 362         //
 363         // If server side should reject client-initiated renegotiation,
 364         // send an alert_handshake_failure fatal alert, not a no_renegotiation
 365         // warning alert (no_renegotiation must be a warning: RFC 2246).
 366         // no_renegotiation might seem more natural at first, but warnings
 367         // are not appropriate because the sending party does not know how
 368         // the receiving party will behave.  This state must be treated as
 369         // a fatal server condition.
 370         //
 371         // This will not have any impact on server initiated renegotiation.
 372         if (rejectClientInitiatedRenego && !isInitialHandshake &&
 373                 !serverHelloRequested) {
 374             fatalSE(Alerts.alert_handshake_failure,
 375                 "Client initiated renegotiation is not allowed");
 376         }
 377 
 378         // check the server name indication if required
 379         ServerNameExtension clientHelloSNIExt = (ServerNameExtension)
 380                     mesg.extensions.get(ExtensionType.EXT_SERVER_NAME);
 381         if (!sniMatchers.isEmpty()) {
 382             // we do not reject client without SNI extension
 383             if (clientHelloSNIExt != null &&
 384                         !clientHelloSNIExt.isMatched(sniMatchers)) {
 385                 fatalSE(Alerts.alert_unrecognized_name,
 386                     "Unrecognized server name indication");
 387             }
 388         }
 389 
 390         // Does the message include security renegotiation indication?
 391         boolean renegotiationIndicated = false;
 392 
 393         // check the TLS_EMPTY_RENEGOTIATION_INFO_SCSV
 394         CipherSuiteList cipherSuites = mesg.getCipherSuites();
 395         if (cipherSuites.contains(CipherSuite.C_SCSV)) {
 396             renegotiationIndicated = true;
 397             if (isInitialHandshake) {
 398                 secureRenegotiation = true;
 399             } else {
 400                 // abort the handshake with a fatal handshake_failure alert
 401                 if (secureRenegotiation) {
 402                     fatalSE(Alerts.alert_handshake_failure,
 403                         "The SCSV is present in a secure renegotiation");
 404                 } else {
 405                     fatalSE(Alerts.alert_handshake_failure,
 406                         "The SCSV is present in a insecure renegotiation");
 407                 }
 408             }
 409         }
 410 
 411         // check the "renegotiation_info" extension
 412         RenegotiationInfoExtension clientHelloRI = (RenegotiationInfoExtension)
 413                     mesg.extensions.get(ExtensionType.EXT_RENEGOTIATION_INFO);
 414         if (clientHelloRI != null) {
 415             renegotiationIndicated = true;
 416             if (isInitialHandshake) {
 417                 // verify the length of the "renegotiated_connection" field
 418                 if (!clientHelloRI.isEmpty()) {
 419                     // abort the handshake with a fatal handshake_failure alert
 420                     fatalSE(Alerts.alert_handshake_failure,
 421                         "The renegotiation_info field is not empty");
 422                 }
 423 
 424                 secureRenegotiation = true;
 425             } else {
 426                 if (!secureRenegotiation) {
 427                     // unexpected RI extension for insecure renegotiation,
 428                     // abort the handshake with a fatal handshake_failure alert
 429                     fatalSE(Alerts.alert_handshake_failure,
 430                         "The renegotiation_info is present in a insecure " +
 431                         "renegotiation");
 432                 }
 433 
 434                 // verify the client_verify_data value
 435                 if (!MessageDigest.isEqual(clientVerifyData,
 436                                 clientHelloRI.getRenegotiatedConnection())) {
 437                     fatalSE(Alerts.alert_handshake_failure,
 438                         "Incorrect verify data in ClientHello " +
 439                         "renegotiation_info message");
 440                 }
 441             }
 442         } else if (!isInitialHandshake && secureRenegotiation) {
 443            // if the connection's "secure_renegotiation" flag is set to TRUE
 444            // and the "renegotiation_info" extension is not present, abort
 445            // the handshake.
 446             fatalSE(Alerts.alert_handshake_failure,
 447                         "Inconsistent secure renegotiation indication");
 448         }
 449 
 450         // if there is no security renegotiation indication or the previous
 451         // handshake is insecure.
 452         if (!renegotiationIndicated || !secureRenegotiation) {
 453             if (isInitialHandshake) {
 454                 if (!allowLegacyHelloMessages) {
 455                     // abort the handshake with a fatal handshake_failure alert
 456                     fatalSE(Alerts.alert_handshake_failure,
 457                         "Failed to negotiate the use of secure renegotiation");
 458                 }
 459 
 460                 // continue with legacy ClientHello
 461                 if (debug != null && Debug.isOn("handshake")) {
 462                     System.out.println("Warning: No renegotiation " +
 463                         "indication in ClientHello, allow legacy ClientHello");
 464                 }
 465             } else if (!allowUnsafeRenegotiation) {
 466                 // abort the handshake
 467                 if (activeProtocolVersion.useTLS10PlusSpec()) {
 468                     // respond with a no_renegotiation warning
 469                     warningSE(Alerts.alert_no_renegotiation);
 470 
 471                     // invalidate the handshake so that the caller can
 472                     // dispose this object.
 473                     invalidated = true;
 474 
 475                     // If there is still unread block in the handshake
 476                     // input stream, it would be truncated with the disposal
 477                     // and the next handshake message will become incomplete.
 478                     //
 479                     // However, according to SSL/TLS specifications, no more
 480                     // handshake message could immediately follow ClientHello
 481                     // or HelloRequest. But in case of any improper messages,
 482                     // we'd better check to ensure there is no remaining bytes
 483                     // in the handshake input stream.
 484                     if (input.available() > 0) {
 485                         fatalSE(Alerts.alert_unexpected_message,
 486                             "ClientHello followed by an unexpected  " +
 487                             "handshake message");
 488                     }
 489 
 490                     return;
 491                 } else {
 492                     // For SSLv3, send the handshake_failure fatal error.
 493                     // Note that SSLv3 does not define a no_renegotiation
 494                     // alert like TLSv1. However we cannot ignore the message
 495                     // simply, otherwise the other side was waiting for a
 496                     // response that would never come.
 497                     fatalSE(Alerts.alert_handshake_failure,
 498                         "Renegotiation is not allowed");
 499                 }
 500             } else {   // !isInitialHandshake && allowUnsafeRenegotiation
 501                 // continue with unsafe renegotiation.
 502                 if (debug != null && Debug.isOn("handshake")) {
 503                     System.out.println(
 504                             "Warning: continue with insecure renegotiation");
 505                 }
 506             }
 507         }
 508 
 509         // check the "max_fragment_length" extension
 510         MaxFragmentLengthExtension maxFragLenExt = (MaxFragmentLengthExtension)
 511                     mesg.extensions.get(ExtensionType.EXT_MAX_FRAGMENT_LENGTH);
 512         if ((maxFragLenExt != null) && (maximumPacketSize != 0)) {
 513             // Not yet consider the impact of IV/MAC/padding.
 514             int estimatedMaxFragSize = maximumPacketSize;
 515             if (isDTLS) {
 516                 estimatedMaxFragSize -= DTLSRecord.headerSize;
 517             } else {
 518                 estimatedMaxFragSize -= SSLRecord.headerSize;
 519             }
 520 
 521             if (maxFragLenExt.getMaxFragLen() > estimatedMaxFragSize) {
 522                 // For better interoperability, abort the maximum fragment
 523                 // length negotiation, rather than terminate the connection
 524                 // with a fatal alert.
 525                 maxFragLenExt = null;
 526 
 527                 // fatalSE(Alerts.alert_illegal_parameter,
 528                 //         "Not an allowed max_fragment_length value");
 529             }
 530         }
 531 
 532         // check the ALPN extension
 533         ALPNExtension clientHelloALPN = (ALPNExtension)
 534             mesg.extensions.get(ExtensionType.EXT_ALPN);
 535 
 536         // Use the application protocol callback when provided.
 537         // Otherwise use the local list of application protocols.
 538         boolean hasAPCallback =
 539             ((engine != null && appProtocolSelectorSSLEngine != null) ||
 540                 (conn != null && appProtocolSelectorSSLSocket != null));
 541 
 542         if (!hasAPCallback) {
 543             if ((clientHelloALPN != null) && (localApl.length > 0)) {
 544 
 545                 // Intersect the requested and the locally supported,
 546                 // and save for later.
 547                 String negotiatedValue = null;
 548                 List<String> protocols = clientHelloALPN.getPeerAPs();
 549 
 550                 // Use server preference order
 551                 for (String ap : localApl) {
 552                     if (protocols.contains(ap)) {
 553                         negotiatedValue = ap;
 554                         break;
 555                     }
 556                 }
 557 
 558                 if (negotiatedValue == null) {
 559                     fatalSE(Alerts.alert_no_application_protocol,
 560                         new SSLHandshakeException(
 561                             "No matching ALPN values"));
 562                 }
 563                 applicationProtocol = negotiatedValue;
 564 
 565             } else {
 566                 applicationProtocol = "";
 567             }
 568         }  // Otherwise, applicationProtocol will be set by the callback.
 569 
 570         session = null; // forget about the current session
 571         //
 572         // Here we go down either of two paths:  (a) the fast one, where
 573         // the client's asked to rejoin an existing session, and the server
 574         // permits this; (b) the other one, where a new session is created.
 575         //
 576         if (mesg.sessionId.length() != 0) {
 577             // client is trying to resume a session, let's see...
 578 
 579             SSLSessionImpl previous = ((SSLSessionContextImpl)sslContext
 580                         .engineGetServerSessionContext())
 581                         .get(mesg.sessionId.getId());
 582             //
 583             // Check if we can use the fast path, resuming a session.  We
 584             // can do so iff we have a valid record for that session, and
 585             // the cipher suite for that session was on the list which the
 586             // client requested, and if we're not forgetting any needed
 587             // authentication on the part of the client.
 588             //
 589             if (previous != null) {
 590                 resumingSession = previous.isRejoinable();
 591 
 592                 if (resumingSession) {
 593                     ProtocolVersion oldVersion = previous.getProtocolVersion();
 594                     // cannot resume session with different version
 595                     if (oldVersion != protocolVersion) {
 596                         resumingSession = false;
 597                     }
 598                 }
 599 
 600                 // cannot resume session with different server name indication
 601                 if (resumingSession) {
 602                     List<SNIServerName> oldServerNames =
 603                             previous.getRequestedServerNames();
 604                     if (clientHelloSNIExt != null) {
 605                         if (!clientHelloSNIExt.isIdentical(oldServerNames)) {
 606                             resumingSession = false;
 607                         }
 608                     } else if (!oldServerNames.isEmpty()) {
 609                         resumingSession = false;
 610                     }
 611 
 612                     if (!resumingSession &&
 613                             debug != null && Debug.isOn("handshake")) {
 614                         System.out.println(
 615                             "The requested server name indication " +
 616                             "is not identical to the previous one");
 617                     }
 618                 }
 619 
 620                 if (resumingSession &&
 621                         (doClientAuth == ClientAuthType.CLIENT_AUTH_REQUIRED)) {
 622                     try {
 623                         previous.getPeerPrincipal();
 624                     } catch (SSLPeerUnverifiedException e) {
 625                         resumingSession = false;
 626                     }
 627                 }
 628 
 629                 // validate subject identity
 630                 if (resumingSession) {
 631                     CipherSuite suite = previous.getSuite();
 632                     ClientKeyExchangeService p =
 633                             ClientKeyExchangeService.find(suite.keyExchange.name);
 634                     if (p != null) {
 635                         Principal localPrincipal = previous.getLocalPrincipal();
 636 
 637                         if (p.isRelated(
 638                                 false, getAccSE(), localPrincipal)) {
 639                             if (debug != null && Debug.isOn("session"))
 640                                 System.out.println("Subject can" +
 641                                         " provide creds for princ");
 642                         } else {
 643                             resumingSession = false;
 644                             if (debug != null && Debug.isOn("session"))
 645                                 System.out.println("Subject cannot" +
 646                                         " provide creds for princ");
 647                         }
 648                     }
 649                 }
 650 
 651                 if (resumingSession) {
 652                     CipherSuite suite = previous.getSuite();
 653                     // verify that the ciphersuite from the cached session
 654                     // is in the list of client requested ciphersuites and
 655                     // we have it enabled
 656                     if ((isNegotiable(suite) == false) ||
 657                             (mesg.getCipherSuites().contains(suite) == false)) {
 658                         resumingSession = false;
 659                     } else {
 660                         // everything looks ok, set the ciphersuite
 661                         // this should be done last when we are sure we
 662                         // will resume
 663                         setCipherSuite(suite);
 664                     }
 665                 }
 666 
 667                 if (resumingSession) {
 668                     session = previous;
 669                     if (debug != null &&
 670                         (Debug.isOn("handshake") || Debug.isOn("session"))) {
 671                         System.out.println("%% Resuming " + session);
 672                     }
 673                 }
 674             }
 675         }   // else client did not try to resume
 676 
 677         // cookie exchange
 678         if (isDTLS && !resumingSession) {
 679              HelloCookieManager hcMgr = sslContext.getHelloCookieManager();
 680              if ((mesg.cookie == null) || (mesg.cookie.length == 0) ||
 681                     (!hcMgr.isValid(mesg))) {
 682 
 683                 //
 684                 // Perform cookie exchange for DTLS handshaking if no cookie
 685                 // or the cookie is invalid in the ClientHello message.
 686                 //
 687                 HelloVerifyRequest m0 = new HelloVerifyRequest(hcMgr, mesg);
 688 
 689                 if (debug != null && Debug.isOn("handshake")) {
 690                     m0.print(System.out);
 691                 }
 692 
 693                 m0.write(output);
 694                 handshakeState.update(m0, resumingSession);
 695                 output.flush();
 696 
 697                 return;
 698             }
 699         }
 700 
 701         /*
 702          * FIRST, construct the ServerHello using the options and priorities
 703          * from the ClientHello.  Update the (pending) cipher spec as we do
 704          * so, and save the client's version to protect against rollback
 705          * attacks.
 706          *
 707          * There are a bunch of minor tasks here, and one major one: deciding
 708          * if the short or the full handshake sequence will be used.
 709          */
 710         ServerHello m1 = new ServerHello();
 711 
 712         clientRequestedVersion = mesg.protocolVersion;
 713 
 714         // select a proper protocol version.
 715         ProtocolVersion selectedVersion =
 716                selectProtocolVersion(clientRequestedVersion);
 717         if (selectedVersion == null ||
 718                 selectedVersion.v == ProtocolVersion.SSL20Hello.v) {
 719             fatalSE(Alerts.alert_handshake_failure,
 720                 "Client requested protocol " + clientRequestedVersion +
 721                 " not enabled or not supported");
 722         }
 723 
 724         handshakeHash.protocolDetermined(selectedVersion);
 725         setVersion(selectedVersion);
 726 
 727         m1.protocolVersion = protocolVersion;
 728 
 729         //
 730         // random ... save client and server values for later use
 731         // in computing the master secret (from pre-master secret)
 732         // and thence the other crypto keys.
 733         //
 734         // NOTE:  this use of three inputs to generating _each_ set
 735         // of ciphers slows things down, but it does increase the
 736         // security since each connection in the session can hold
 737         // its own authenticated (and strong) keys.  One could make
 738         // creation of a session a rare thing...
 739         //
 740         clnt_random = mesg.clnt_random;
 741         svr_random = new RandomCookie(sslContext.getSecureRandom());
 742         m1.svr_random = svr_random;
 743 
 744         //
 745         // If client hasn't specified a session we can resume, start a
 746         // new one and choose its cipher suite and compression options.
 747         // Unless new session creation is disabled for this connection!
 748         //
 749         if (session == null) {
 750             if (!enableNewSession) {
 751                 throw new SSLException("Client did not resume a session");
 752             }
 753 
 754             requestedGroups = (SupportedGroupsExtension)
 755                     mesg.extensions.get(ExtensionType.EXT_SUPPORTED_GROUPS);
 756 
 757             // We only need to handle the "signature_algorithm" extension
 758             // for full handshakes and TLS 1.2 or later.
 759             if (protocolVersion.useTLS12PlusSpec()) {
 760                 SignatureAlgorithmsExtension signAlgs =
 761                     (SignatureAlgorithmsExtension)mesg.extensions.get(
 762                                     ExtensionType.EXT_SIGNATURE_ALGORITHMS);
 763                 if (signAlgs != null) {
 764                     Collection<SignatureAndHashAlgorithm> peerSignAlgs =
 765                                             signAlgs.getSignAlgorithms();
 766                     if (peerSignAlgs == null || peerSignAlgs.isEmpty()) {
 767                         throw new SSLHandshakeException(
 768                             "No peer supported signature algorithms");
 769                     }
 770 
 771                     Collection<SignatureAndHashAlgorithm>
 772                         supportedPeerSignAlgs =
 773                             SignatureAndHashAlgorithm.getSupportedAlgorithms(
 774                                 algorithmConstraints, peerSignAlgs);
 775                     if (supportedPeerSignAlgs.isEmpty()) {
 776                         throw new SSLHandshakeException(
 777                             "No signature and hash algorithm in common");
 778                     }
 779 
 780                     setPeerSupportedSignAlgs(supportedPeerSignAlgs);
 781                 } // else, need to use peer implicit supported signature algs
 782             }
 783 
 784             session = new SSLSessionImpl(protocolVersion, CipherSuite.C_NULL,
 785                         getLocalSupportedSignAlgs(),
 786                         sslContext.getSecureRandom(),
 787                         getHostAddressSE(), getPortSE());
 788 
 789             if (protocolVersion.useTLS12PlusSpec()) {
 790                 if (peerSupportedSignAlgs != null) {
 791                     session.setPeerSupportedSignatureAlgorithms(
 792                             peerSupportedSignAlgs);
 793                 }   // else, we will set the implicit peer supported signature
 794                     // algorithms in chooseCipherSuite()
 795             }
 796 
 797             // set the server name indication in the session
 798             List<SNIServerName> clientHelloSNI =
 799                     Collections.<SNIServerName>emptyList();
 800             if (clientHelloSNIExt != null) {
 801                 clientHelloSNI = clientHelloSNIExt.getServerNames();
 802             }
 803             session.setRequestedServerNames(clientHelloSNI);
 804 
 805             // set the handshake session
 806             setHandshakeSessionSE(session);
 807 
 808             // choose cipher suite and corresponding private key
 809             chooseCipherSuite(mesg);
 810 
 811             session.setSuite(cipherSuite);
 812             session.setLocalPrivateKey(privateKey);
 813 
 814             // chooseCompression(mesg);
 815 
 816             // set the negotiated maximum fragment in the session
 817             //
 818             // The protocol version and cipher suite have been negotiated
 819             // in previous processes.
 820             if (maxFragLenExt != null) {
 821                 int maxFragLen = maxFragLenExt.getMaxFragLen();
 822 
 823                 // More check of the requested "max_fragment_length" extension.
 824                 if (maximumPacketSize != 0) {
 825                     int estimatedMaxFragSize = cipherSuite.calculatePacketSize(
 826                             maxFragLen, protocolVersion, isDTLS);
 827                     if (estimatedMaxFragSize > maximumPacketSize) {
 828                         // For better interoperability, abort the maximum
 829                         // fragment length negotiation, rather than terminate
 830                         // the connection with a fatal alert.
 831                         maxFragLenExt = null;
 832 
 833                         // fatalSE(Alerts.alert_illegal_parameter,
 834                         //         "Not an allowed max_fragment_length value");
 835                     }
 836                 }
 837 
 838                 if (maxFragLenExt != null) {
 839                     session.setNegotiatedMaxFragSize(maxFragLen);
 840                 }
 841             }
 842 
 843             session.setMaximumPacketSize(maximumPacketSize);
 844         } else {
 845             // set the handshake session
 846             setHandshakeSessionSE(session);
 847         }
 848 
 849         if (protocolVersion.useTLS12PlusSpec()) {
 850             handshakeHash.setFinishedAlg(cipherSuite.prfAlg.getPRFHashAlg());
 851         }
 852 
 853         m1.cipherSuite = cipherSuite;
 854         m1.sessionId = session.getSessionId();
 855         m1.compression_method = session.getCompression();
 856 
 857         if (secureRenegotiation) {
 858             // For ServerHellos that are initial handshakes, then the
 859             // "renegotiated_connection" field in "renegotiation_info"
 860             // extension is of zero length.
 861             //
 862             // For ServerHellos that are renegotiating, this field contains
 863             // the concatenation of client_verify_data and server_verify_data.
 864             //
 865             // Note that for initial handshakes, both the clientVerifyData
 866             // variable and serverVerifyData variable are of zero length.
 867             HelloExtension serverHelloRI = new RenegotiationInfoExtension(
 868                                         clientVerifyData, serverVerifyData);
 869             m1.extensions.add(serverHelloRI);
 870         }
 871 
 872         if (!sniMatchers.isEmpty() && clientHelloSNIExt != null) {
 873             // When resuming a session, the server MUST NOT include a
 874             // server_name extension in the server hello.
 875             if (!resumingSession) {
 876                 ServerNameExtension serverHelloSNI = new ServerNameExtension();
 877                 m1.extensions.add(serverHelloSNI);
 878             }
 879         }
 880 
 881         if ((maxFragLenExt != null) && !resumingSession) {
 882             // When resuming a session, the server MUST NOT include a
 883             // max_fragment_length extension in the server hello.
 884             //
 885             // Otherwise, use the same value as the requested extension.
 886             m1.extensions.add(maxFragLenExt);
 887         }
 888 
 889         StaplingParameters staplingParams = processStapling(mesg);
 890         if (staplingParams != null) {
 891             // We now can safely assert status_request[_v2] in our
 892             // ServerHello, and know for certain that we can provide
 893             // responses back to this client for this connection.
 894             if (staplingParams.statusRespExt ==
 895                     ExtensionType.EXT_STATUS_REQUEST) {
 896                 m1.extensions.add(new CertStatusReqExtension());
 897             } else if (staplingParams.statusRespExt ==
 898                     ExtensionType.EXT_STATUS_REQUEST_V2) {
 899                 m1.extensions.add(new CertStatusReqListV2Extension());
 900             }
 901         }
 902 
 903         // Prepare the ALPN response
 904         if (clientHelloALPN != null) {
 905             List<String> peerAPs = clientHelloALPN.getPeerAPs();
 906 
 907             // check for a callback function
 908             if (hasAPCallback) {
 909                 if (conn != null) {
 910                     applicationProtocol =
 911                         appProtocolSelectorSSLSocket.apply(conn, peerAPs);
 912                 } else {
 913                     applicationProtocol =
 914                         appProtocolSelectorSSLEngine.apply(engine, peerAPs);
 915                 }
 916             }
 917 
 918             // check for no-match and that the selected name was also proposed
 919             // by the TLS peer
 920             if (applicationProtocol == null ||
 921                    (!applicationProtocol.isEmpty() &&
 922                         !peerAPs.contains(applicationProtocol))) {
 923 
 924                 fatalSE(Alerts.alert_no_application_protocol,
 925                     new SSLHandshakeException(
 926                         "No matching ALPN values"));
 927 
 928             } else if (!applicationProtocol.isEmpty()) {
 929                 m1.extensions.add(new ALPNExtension(applicationProtocol));
 930             }
 931         } else {
 932             // Nothing was negotiated, returned at end of the handshake
 933             applicationProtocol = "";
 934         }
 935 
 936         if (debug != null && Debug.isOn("handshake")) {
 937             m1.print(System.out);
 938             System.out.println("Cipher suite:  " + session.getSuite());
 939         }
 940         m1.write(output);
 941         handshakeState.update(m1, resumingSession);
 942 
 943         //
 944         // If we are resuming a session, we finish writing handshake
 945         // messages right now and then finish.
 946         //
 947         if (resumingSession) {
 948             calculateConnectionKeys(session.getMasterSecret());
 949             sendChangeCipherAndFinish(false);
 950 
 951             // expecting the final ChangeCipherSpec and Finished messages
 952             expectingFinishFlightSE();
 953 
 954             return;
 955         }
 956 
 957 
 958         /*
 959          * SECOND, write the server Certificate(s) if we need to.
 960          *
 961          * NOTE:  while an "anonymous RSA" mode is explicitly allowed by
 962          * the protocol, we can't support it since all of the SSL flavors
 963          * defined in the protocol spec are explicitly stated to require
 964          * using RSA certificates.
 965          */
 966         if (ClientKeyExchangeService.find(cipherSuite.keyExchange.name) != null) {
 967             // No external key exchange provider needs a cert now.
 968         } else if ((keyExchange != K_DH_ANON) && (keyExchange != K_ECDH_ANON)) {
 969             if (certs == null) {
 970                 throw new RuntimeException("no certificates");
 971             }
 972 
 973             CertificateMsg m2 = new CertificateMsg(certs);
 974 
 975             /*
 976              * Set local certs in the SSLSession, output
 977              * debug info, and then actually write to the client.
 978              */
 979             session.setLocalCertificates(certs);
 980             if (debug != null && Debug.isOn("handshake")) {
 981                 m2.print(System.out);
 982             }
 983             m2.write(output);
 984             handshakeState.update(m2, resumingSession);
 985 
 986             // XXX has some side effects with OS TCP buffering,
 987             // leave it out for now
 988 
 989             // let client verify chain in the meantime...
 990             // output.flush();
 991         } else {
 992             if (certs != null) {
 993                 throw new RuntimeException("anonymous keyexchange with certs");
 994             }
 995         }
 996 
 997         /**
 998          * The CertificateStatus message ... only if it is needed.
 999          * This would only be needed if we've established that this handshake
1000          * supports status stapling and there is at least one response to
1001          * return to the client.
1002          */
1003         if (staplingParams != null) {
1004             CertificateStatus csMsg = new CertificateStatus(
1005                     staplingParams.statReqType, certs,
1006                     staplingParams.responseMap);
1007             if (debug != null && Debug.isOn("handshake")) {
1008                 csMsg.print(System.out);
1009             }
1010             csMsg.write(output);
1011             handshakeState.update(csMsg, resumingSession);
1012         }
1013 
1014         /*
1015          * THIRD, the ServerKeyExchange message ... iff it's needed.
1016          *
1017          * It's usually needed unless there's an encryption-capable
1018          * RSA cert, or a D-H cert.  The notable exception is that
1019          * exportable ciphers used with big RSA keys need to downgrade
1020          * to use short RSA keys, even when the key/cert encrypts OK.
1021          */
1022 
1023         ServerKeyExchange m3;
1024         switch (keyExchange) {
1025         case K_RSA:
1026             // no server key exchange for RSA ciphersuites
1027             m3 = null;
1028             break;
1029         case K_RSA_EXPORT:
1030             if (JsseJce.getRSAKeyLength(certs[0].getPublicKey()) > 512) {
1031                 try {
1032                     m3 = new RSA_ServerKeyExchange(
1033                         tempPublicKey, privateKey,
1034                         clnt_random, svr_random,
1035                         sslContext.getSecureRandom());
1036                     privateKey = tempPrivateKey;
1037                 } catch (GeneralSecurityException e) {
1038                     m3 = null; // make compiler happy
1039                     throw new SSLException(
1040                             "Error generating RSA server key exchange", e);
1041                 }
1042             } else {
1043                 // RSA_EXPORT with short key, don't need ServerKeyExchange
1044                 m3 = null;
1045             }
1046             break;
1047         case K_DHE_RSA:
1048         case K_DHE_DSS:
1049             try {
1050                 m3 = new DH_ServerKeyExchange(dh,
1051                     privateKey,
1052                     clnt_random.random_bytes,
1053                     svr_random.random_bytes,
1054                     sslContext.getSecureRandom(),
1055                     preferableSignatureAlgorithm,
1056                     protocolVersion);
1057             } catch (GeneralSecurityException e) {
1058                 m3 = null; // make compiler happy
1059                 throw new SSLException(
1060                         "Error generating DH server key exchange", e);
1061             }
1062             break;
1063         case K_DH_ANON:
1064             m3 = new DH_ServerKeyExchange(dh, protocolVersion);
1065             break;
1066         case K_ECDHE_RSA:
1067         case K_ECDHE_ECDSA:
1068         case K_ECDH_ANON:
1069             try {
1070                 m3 = new ECDH_ServerKeyExchange(ecdh,
1071                     privateKey,
1072                     clnt_random.random_bytes,
1073                     svr_random.random_bytes,
1074                     sslContext.getSecureRandom(),
1075                     preferableSignatureAlgorithm,
1076                     protocolVersion);
1077             } catch (GeneralSecurityException e) {
1078                 m3 = null; // make compiler happy
1079                 throw new SSLException(
1080                         "Error generating ECDH server key exchange", e);
1081             }
1082             break;
1083         case K_ECDH_RSA:
1084         case K_ECDH_ECDSA:
1085             // ServerKeyExchange not used for fixed ECDH
1086             m3 = null;
1087             break;
1088         default:
1089             ClientKeyExchangeService p =
1090                     ClientKeyExchangeService.find(keyExchange.name);
1091             if (p != null) {
1092                 // No external key exchange provider needs a cert now.
1093                 m3 = null;
1094                 break;
1095             }
1096             throw new RuntimeException("internal error: " + keyExchange);
1097         }
1098         if (m3 != null) {
1099             if (debug != null && Debug.isOn("handshake")) {
1100                 m3.print(System.out);
1101             }
1102             m3.write(output);
1103             handshakeState.update(m3, resumingSession);
1104         }
1105 
1106         //
1107         // FOURTH, the CertificateRequest message.  The details of
1108         // the message can be affected by the key exchange algorithm
1109         // in use.  For example, certs with fixed Diffie-Hellman keys
1110         // are only useful with the DH_DSS and DH_RSA key exchange
1111         // algorithms.
1112         //
1113         // Needed only if server requires client to authenticate self.
1114         // Illegal for anonymous flavors, so we need to check that.
1115         //
1116         // No external key exchange provider needs a cert now.
1117         if (doClientAuth != ClientAuthType.CLIENT_AUTH_NONE &&
1118                 keyExchange != K_DH_ANON && keyExchange != K_ECDH_ANON &&
1119                 ClientKeyExchangeService.find(keyExchange.name) == null) {
1120 
1121             CertificateRequest m4;
1122             X509Certificate[] caCerts;
1123 
1124             Collection<SignatureAndHashAlgorithm> localSignAlgs = null;
1125             if (protocolVersion.useTLS12PlusSpec()) {
1126                 // We currently use all local upported signature and hash
1127                 // algorithms. However, to minimize the computation cost
1128                 // of requested hash algorithms, we may use a restricted
1129                 // set of signature algorithms in the future.
1130                 localSignAlgs = getLocalSupportedSignAlgs();
1131                 if (localSignAlgs.isEmpty()) {
1132                     throw new SSLHandshakeException(
1133                             "No supported signature algorithm");
1134                 }
1135 
1136                 Set<String> localHashAlgs =
1137                     SignatureAndHashAlgorithm.getHashAlgorithmNames(
1138                         localSignAlgs);
1139                 if (localHashAlgs.isEmpty()) {
1140                     throw new SSLHandshakeException(
1141                             "No supported signature algorithm");
1142                 }
1143             }
1144 
1145             caCerts = sslContext.getX509TrustManager().getAcceptedIssuers();
1146             m4 = new CertificateRequest(caCerts, keyExchange,
1147                                             localSignAlgs, protocolVersion);
1148 
1149             if (debug != null && Debug.isOn("handshake")) {
1150                 m4.print(System.out);
1151             }
1152             m4.write(output);
1153             handshakeState.update(m4, resumingSession);
1154         }
1155 
1156         /*
1157          * FIFTH, say ServerHelloDone.
1158          */
1159         ServerHelloDone m5 = new ServerHelloDone();
1160 
1161         if (debug != null && Debug.isOn("handshake")) {
1162             m5.print(System.out);
1163         }
1164         m5.write(output);
1165         handshakeState.update(m5, resumingSession);
1166 
1167         /*
1168          * Flush any buffered messages so the client will see them.
1169          * Ideally, all the messages above go in a single network level
1170          * message to the client.  Without big Certificate chains, it's
1171          * going to be the common case.
1172          */
1173         output.flush();
1174     }
1175 
1176     /*
1177      * Choose cipher suite from among those supported by client. Sets
1178      * the cipherSuite and keyExchange variables.
1179      */
1180     private void chooseCipherSuite(ClientHello mesg) throws IOException {
1181         CipherSuiteList prefered;
1182         CipherSuiteList proposed;
1183         if (preferLocalCipherSuites) {
1184             prefered = getActiveCipherSuites();
1185             proposed = mesg.getCipherSuites();
1186         } else {
1187             prefered = mesg.getCipherSuites();
1188             proposed = getActiveCipherSuites();
1189         }
1190 
1191         List<CipherSuite> legacySuites = new ArrayList<>();
1192         for (CipherSuite suite : prefered.collection()) {
1193             if (isNegotiable(proposed, suite) == false) {
1194                 continue;
1195             }
1196 
1197             if (doClientAuth == ClientAuthType.CLIENT_AUTH_REQUIRED) {
1198                 if ((suite.keyExchange == K_DH_ANON) ||
1199                     (suite.keyExchange == K_ECDH_ANON)) {
1200                     continue;
1201                 }
1202             }
1203 
1204             if (!legacyAlgorithmConstraints.permits(null, suite.name, null)) {
1205                 legacySuites.add(suite);
1206                 continue;
1207             }
1208 
1209             if (trySetCipherSuite(suite) == false) {
1210                 continue;
1211             }
1212 
1213             if (debug != null && Debug.isOn("handshake")) {
1214                 System.out.println("Standard ciphersuite chosen: " + suite);
1215             }
1216             return;
1217         }
1218 
1219         for (CipherSuite suite : legacySuites) {
1220             if (trySetCipherSuite(suite)) {
1221                 if (debug != null && Debug.isOn("handshake")) {
1222                     System.out.println("Legacy ciphersuite chosen: " + suite);
1223                 }
1224                 return;
1225             }
1226         }
1227 
1228         fatalSE(Alerts.alert_handshake_failure, "no cipher suites in common");
1229     }
1230 
1231     /**
1232      * Set the given CipherSuite, if possible. Return the result.
1233      * The call succeeds if the CipherSuite is available and we have
1234      * the necessary certificates to complete the handshake. We don't
1235      * check if the CipherSuite is actually enabled.
1236      *
1237      * If successful, this method also generates ephemeral keys if
1238      * required for this ciphersuite. This may take some time, so this
1239      * method should only be called if you really want to use the
1240      * CipherSuite.
1241      *
1242      * This method is called from chooseCipherSuite() in this class.
1243      */
1244     boolean trySetCipherSuite(CipherSuite suite) {
1245         /*
1246          * If we're resuming a session we know we can
1247          * support this key exchange algorithm and in fact
1248          * have already cached the result of it in
1249          * the session state.
1250          */
1251         if (resumingSession) {
1252             return true;
1253         }
1254 
1255         if (suite.isNegotiable() == false) {
1256             return false;
1257         }
1258 
1259         // must not negotiate the obsoleted weak cipher suites.
1260         if (protocolVersion.obsoletes(suite)) {
1261             return false;
1262         }
1263 
1264         // must not negotiate unsupported cipher suites.
1265         if (!protocolVersion.supports(suite)) {
1266             return false;
1267         }
1268 
1269         KeyExchange keyExchange = suite.keyExchange;
1270 
1271         // null out any existing references
1272         privateKey = null;
1273         certs = null;
1274         dh = null;
1275         tempPrivateKey = null;
1276         tempPublicKey = null;
1277 
1278         Collection<SignatureAndHashAlgorithm> supportedSignAlgs = null;
1279         if (protocolVersion.useTLS12PlusSpec()) {
1280             if (peerSupportedSignAlgs != null) {
1281                 supportedSignAlgs = peerSupportedSignAlgs;
1282             } else {
1283                 SignatureAndHashAlgorithm algorithm = null;
1284 
1285                 // we may optimize the performance
1286                 switch (keyExchange) {
1287                     // If the negotiated key exchange algorithm is one of
1288                     // (RSA, DHE_RSA, DH_RSA, RSA_PSK, ECDH_RSA, ECDHE_RSA),
1289                     // behave as if client had sent the value {sha1,rsa}.
1290                     case K_RSA:
1291                     case K_DHE_RSA:
1292                     case K_DH_RSA:
1293                     // case K_RSA_PSK:
1294                     case K_ECDH_RSA:
1295                     case K_ECDHE_RSA:
1296                         algorithm = SignatureAndHashAlgorithm.valueOf(
1297                                 HashAlgorithm.SHA1.value,
1298                                 SignatureAlgorithm.RSA.value, 0);
1299                         break;
1300                     // If the negotiated key exchange algorithm is one of
1301                     // (DHE_DSS, DH_DSS), behave as if the client had
1302                     // sent the value {sha1,dsa}.
1303                     case K_DHE_DSS:
1304                     case K_DH_DSS:
1305                         algorithm = SignatureAndHashAlgorithm.valueOf(
1306                                 HashAlgorithm.SHA1.value,
1307                                 SignatureAlgorithm.DSA.value, 0);
1308                         break;
1309                     // If the negotiated key exchange algorithm is one of
1310                     // (ECDH_ECDSA, ECDHE_ECDSA), behave as if the client
1311                     // had sent value {sha1,ecdsa}.
1312                     case K_ECDH_ECDSA:
1313                     case K_ECDHE_ECDSA:
1314                         algorithm = SignatureAndHashAlgorithm.valueOf(
1315                                 HashAlgorithm.SHA1.value,
1316                                 SignatureAlgorithm.ECDSA.value, 0);
1317                         break;
1318                     default:
1319                         // no peer supported signature algorithms
1320                 }
1321 
1322                 if (algorithm == null) {
1323                     supportedSignAlgs =
1324                         Collections.<SignatureAndHashAlgorithm>emptySet();
1325                 } else {
1326                     supportedSignAlgs =
1327                         new ArrayList<SignatureAndHashAlgorithm>(1);
1328                     supportedSignAlgs.add(algorithm);
1329 
1330                     supportedSignAlgs =
1331                             SignatureAndHashAlgorithm.getSupportedAlgorithms(
1332                                 algorithmConstraints, supportedSignAlgs);
1333 
1334                     // May be no default activated signature algorithm, but
1335                     // let the following process make the final decision.
1336                 }
1337 
1338                 // Sets the peer supported signature algorithm to use in KM
1339                 // temporarily.
1340                 session.setPeerSupportedSignatureAlgorithms(supportedSignAlgs);
1341             }
1342         }
1343 
1344         // The named group used for ECDHE and FFDHE.
1345         NamedGroup namedGroup = null;
1346         switch (keyExchange) {
1347         case K_RSA:
1348             // need RSA certs for authentication
1349             if (setupPrivateKeyAndChain("RSA") == false) {
1350                 return false;
1351             }
1352             break;
1353         case K_RSA_EXPORT:
1354             // need RSA certs for authentication
1355             if (setupPrivateKeyAndChain("RSA") == false) {
1356                 return false;
1357             }
1358 
1359             try {
1360                if (JsseJce.getRSAKeyLength(certs[0].getPublicKey()) > 512) {
1361                     if (!setupEphemeralRSAKeys(suite.exportable)) {
1362                         return false;
1363                     }
1364                }
1365             } catch (RuntimeException e) {
1366                 // could not determine keylength, ignore key
1367                 return false;
1368             }
1369             break;
1370         case K_DHE_RSA:
1371             // Is ephemeral DH cipher suite usable for the connection?
1372             //
1373             // [RFC 7919] If a compatible TLS server receives a Supported
1374             // Groups extension from a client that includes any FFDHE group
1375             // (i.e., any codepoint between 256 and 511, inclusive, even if
1376             // unknown to the server), and if none of the client-proposed
1377             // FFDHE groups are known and acceptable to the server, then
1378             // the server MUST NOT select an FFDHE cipher suite.  In this
1379             // case, the server SHOULD select an acceptable non-FFDHE cipher
1380             // suite from the client's offered list.  If the extension is
1381             // present with FFDHE groups, none of the client's offered
1382             // groups are acceptable by the server, and none of the client's
1383             // proposed non-FFDHE cipher suites are acceptable to the server,
1384             // the server MUST end the connection with a fatal TLS alert
1385             // of type insufficient_security(71).
1386             //
1387             // Note: For compatibility, if an application is customized to
1388             // use legacy sizes (512 bits for exportable cipher suites and
1389             // 768 bits for others), or the cipher suite is exportable, the
1390             // FFDHE extension will not be used.
1391             if ((!useLegacyEphemeralDHKeys) && (!suite.exportable) &&
1392                 (requestedGroups != null) && requestedGroups.hasFFDHEGroup()) {
1393 
1394                 namedGroup = requestedGroups.getPreferredGroup(
1395                     algorithmConstraints, NamedGroupType.NAMED_GROUP_FFDHE);
1396                 if (namedGroup == null) {
1397                     // no match found, cannot use this cipher suite.
1398                     return false;
1399                 }
1400             }
1401 
1402             // need RSA certs for authentication
1403             if (setupPrivateKeyAndChain("RSA") == false) {
1404                 return false;
1405             }
1406 
1407             // get preferable peer signature algorithm for server key exchange
1408             if (protocolVersion.useTLS12PlusSpec()) {
1409                 preferableSignatureAlgorithm =
1410                     SignatureAndHashAlgorithm.getPreferableAlgorithm(
1411                                         supportedSignAlgs, "RSA", privateKey);
1412                 if (preferableSignatureAlgorithm == null) {
1413                     if ((debug != null) && Debug.isOn("handshake")) {
1414                         System.out.println(
1415                                 "No signature and hash algorithm for cipher " +
1416                                 suite);
1417                     }
1418                     return false;
1419                 }
1420             }
1421 
1422             setupEphemeralDHKeys(namedGroup, suite.exportable, privateKey);
1423             break;
1424         case K_ECDHE_RSA:
1425             // Is ECDHE cipher suite usable for the connection?
1426             namedGroup = (requestedGroups != null) ?
1427                 requestedGroups.getPreferredGroup(
1428                     algorithmConstraints, NamedGroupType.NAMED_GROUP_ECDHE) :
1429                 SupportedGroupsExtension.getPreferredECGroup(
1430                     algorithmConstraints);
1431             if (namedGroup == null) {
1432                 // no match found, cannot use this ciphersuite
1433                 return false;
1434             }
1435 
1436             // need RSA certs for authentication
1437             if (setupPrivateKeyAndChain("RSA") == false) {
1438                 return false;
1439             }
1440 
1441             // get preferable peer signature algorithm for server key exchange
1442             if (protocolVersion.useTLS12PlusSpec()) {
1443                 preferableSignatureAlgorithm =
1444                     SignatureAndHashAlgorithm.getPreferableAlgorithm(
1445                                         supportedSignAlgs, "RSA", privateKey);
1446                 if (preferableSignatureAlgorithm == null) {
1447                     if ((debug != null) && Debug.isOn("handshake")) {
1448                         System.out.println(
1449                                 "No signature and hash algorithm for cipher " +
1450                                 suite);
1451                     }
1452                     return false;
1453                 }
1454             }
1455 
1456             setupEphemeralECDHKeys(namedGroup);
1457             break;
1458         case K_DHE_DSS:
1459             // Is ephemeral DH cipher suite usable for the connection?
1460             //
1461             // See comment in K_DHE_RSA case.
1462             if ((!useLegacyEphemeralDHKeys) && (!suite.exportable) &&
1463                 (requestedGroups != null) && requestedGroups.hasFFDHEGroup()) {
1464 
1465                 namedGroup = requestedGroups.getPreferredGroup(
1466                     algorithmConstraints, NamedGroupType.NAMED_GROUP_FFDHE);
1467                 if (namedGroup == null) {
1468                     // no match found, cannot use this cipher suite.
1469                     return false;
1470                 }
1471             }
1472 
1473             // get preferable peer signature algorithm for server key exchange
1474             if (protocolVersion.useTLS12PlusSpec()) {
1475                 preferableSignatureAlgorithm =
1476                     SignatureAndHashAlgorithm.getPreferableAlgorithm(
1477                                                 supportedSignAlgs, "DSA");
1478                 if (preferableSignatureAlgorithm == null) {
1479                     if ((debug != null) && Debug.isOn("handshake")) {
1480                         System.out.println(
1481                                 "No signature and hash algorithm for cipher " +
1482                                 suite);
1483                     }
1484                     return false;
1485                 }
1486             }
1487 
1488             // need DSS certs for authentication
1489             if (setupPrivateKeyAndChain("DSA") == false) {
1490                 return false;
1491             }
1492 
1493             setupEphemeralDHKeys(namedGroup, suite.exportable, privateKey);
1494             break;
1495         case K_ECDHE_ECDSA:
1496             // Is ECDHE cipher suite usable for the connection?
1497             namedGroup = (requestedGroups != null) ?
1498                 requestedGroups.getPreferredGroup(
1499                     algorithmConstraints, NamedGroupType.NAMED_GROUP_ECDHE) :
1500                 SupportedGroupsExtension.getPreferredECGroup(
1501                     algorithmConstraints);
1502             if (namedGroup == null) {
1503                 // no match found, cannot use this ciphersuite
1504                 return false;
1505             }
1506 
1507             // get preferable peer signature algorithm for server key exchange
1508             if (protocolVersion.useTLS12PlusSpec()) {
1509                 preferableSignatureAlgorithm =
1510                     SignatureAndHashAlgorithm.getPreferableAlgorithm(
1511                                             supportedSignAlgs, "ECDSA");
1512                 if (preferableSignatureAlgorithm == null) {
1513                     if ((debug != null) && Debug.isOn("handshake")) {
1514                         System.out.println(
1515                                 "No signature and hash algorithm for cipher " +
1516                                 suite);
1517                     }
1518                     return false;
1519                 }
1520             }
1521 
1522             // need EC cert
1523             if (setupPrivateKeyAndChain("EC") == false) {
1524                 return false;
1525             }
1526 
1527             setupEphemeralECDHKeys(namedGroup);
1528             break;
1529         case K_ECDH_RSA:
1530             // need EC cert
1531             if (setupPrivateKeyAndChain("EC") == false) {
1532                 return false;
1533             }
1534             setupStaticECDHKeys();
1535             break;
1536         case K_ECDH_ECDSA:
1537             // need EC cert
1538             if (setupPrivateKeyAndChain("EC") == false) {
1539                 return false;
1540             }
1541             setupStaticECDHKeys();
1542             break;
1543         case K_DH_ANON:
1544             // Is ephemeral DH cipher suite usable for the connection?
1545             //
1546             // See comment in K_DHE_RSA case.
1547             if ((!useLegacyEphemeralDHKeys) && (!suite.exportable) &&
1548                 (requestedGroups != null) && requestedGroups.hasFFDHEGroup()) {
1549                 namedGroup = requestedGroups.getPreferredGroup(
1550                     algorithmConstraints, NamedGroupType.NAMED_GROUP_FFDHE);
1551                 if (namedGroup == null) {
1552                     // no match found, cannot use this cipher suite.
1553                     return false;
1554                 }
1555             }
1556 
1557             // no certs needed for anonymous
1558             setupEphemeralDHKeys(namedGroup, suite.exportable, null);
1559             break;
1560         case K_ECDH_ANON:
1561             // Is ECDHE cipher suite usable for the connection?
1562             namedGroup = (requestedGroups != null) ?
1563                 requestedGroups.getPreferredGroup(
1564                     algorithmConstraints, NamedGroupType.NAMED_GROUP_ECDHE) :
1565                 SupportedGroupsExtension.getPreferredECGroup(
1566                     algorithmConstraints);
1567             if (namedGroup == null) {
1568                 // no match found, cannot use this ciphersuite
1569                 return false;
1570             }
1571 
1572             // no certs needed for anonymous
1573             setupEphemeralECDHKeys(namedGroup);
1574             break;
1575         default:
1576             ClientKeyExchangeService p =
1577                     ClientKeyExchangeService.find(keyExchange.name);
1578             if (p == null) {
1579                 // internal error, unknown key exchange
1580                 throw new RuntimeException(
1581                         "Unrecognized cipherSuite: " + suite);
1582             }
1583             // need service creds
1584             if (serviceCreds == null) {
1585                 AccessControlContext acc = getAccSE();
1586                 serviceCreds = p.getServiceCreds(acc);
1587                 if (serviceCreds != null) {
1588                     if (debug != null && Debug.isOn("handshake")) {
1589                         System.out.println("Using serviceCreds");
1590                     }
1591                 }
1592                 if (serviceCreds == null) {
1593                     return false;
1594                 }
1595             }
1596             break;
1597         }
1598         setCipherSuite(suite);
1599 
1600         // set the peer implicit supported signature algorithms
1601         if (protocolVersion.useTLS12PlusSpec()) {
1602             if (peerSupportedSignAlgs == null) {
1603                 setPeerSupportedSignAlgs(supportedSignAlgs);
1604                 // we had alreay update the session
1605             }
1606         }
1607         return true;
1608     }
1609 
1610     /*
1611      * Get some "ephemeral" RSA keys for this context. This means
1612      * generating them if it's not already been done.
1613      *
1614      * Note that we currently do not implement any ciphersuites that use
1615      * strong ephemeral RSA. (We do not support the EXPORT1024 ciphersuites
1616      * and standard RSA ciphersuites prohibit ephemeral mode for some reason)
1617      * This means that export is always true and 512 bit keys are generated.
1618      */
1619     private boolean setupEphemeralRSAKeys(boolean export) {
1620         KeyPair kp = sslContext.getEphemeralKeyManager().
1621                         getRSAKeyPair(export, sslContext.getSecureRandom());
1622         if (kp == null) {
1623             return false;
1624         } else {
1625             tempPublicKey = kp.getPublic();
1626             tempPrivateKey = kp.getPrivate();
1627             return true;
1628         }
1629     }
1630 
1631     /*
1632      * Acquire some "ephemeral" Diffie-Hellman  keys for this handshake.
1633      * We don't reuse these, for improved forward secrecy.
1634      */
1635     private void setupEphemeralDHKeys(
1636             NamedGroup namedGroup, boolean export, Key key) {
1637         // Are the client and server willing to negotiate FFDHE groups?
1638         if ((!useLegacyEphemeralDHKeys) && (!export) && (namedGroup != null)) {
1639             dh = new DHCrypt(namedGroup, sslContext.getSecureRandom());
1640 
1641             return;
1642         }   // Otherwise, the client is not compatible with FFDHE extension.
1643 
1644         /*
1645          * 768 bits ephemeral DH private keys were used to be used in
1646          * ServerKeyExchange except that exportable ciphers max out at 512
1647          * bits modulus values. We still adhere to this behavior in legacy
1648          * mode (system property "jdk.tls.ephemeralDHKeySize" is defined
1649          * as "legacy").
1650          *
1651          * Old JDK (JDK 7 and previous) releases don't support DH keys bigger
1652          * than 1024 bits. We have to consider the compatibility requirement.
1653          * 1024 bits DH key is always used for non-exportable cipher suites
1654          * in default mode (system property "jdk.tls.ephemeralDHKeySize"
1655          * is not defined).
1656          *
1657          * However, if applications want more stronger strength, setting
1658          * system property "jdk.tls.ephemeralDHKeySize" to "matched"
1659          * is a workaround to use ephemeral DH key which size matches the
1660          * corresponding authentication key. For example, if the public key
1661          * size of an authentication certificate is 2048 bits, then the
1662          * ephemeral DH key size should be 2048 bits accordingly unless
1663          * the cipher suite is exportable.  This key sizing scheme keeps
1664          * the cryptographic strength consistent between authentication
1665          * keys and key-exchange keys.
1666          *
1667          * Applications may also want to customize the ephemeral DH key size
1668          * to a fixed length for non-exportable cipher suites. This can be
1669          * approached by setting system property "jdk.tls.ephemeralDHKeySize"
1670          * to a valid positive integer between 1024 and 8192 bits, inclusive.
1671          *
1672          * Note that the minimum acceptable key size is 1024 bits except
1673          * exportable cipher suites or legacy mode.
1674          *
1675          * Note that per RFC 2246, the key size limit of DH is 512 bits for
1676          * exportable cipher suites.  Because of the weakness, exportable
1677          * cipher suites are deprecated since TLS v1.1 and they are not
1678          * enabled by default in Oracle provider. The legacy behavior is
1679          * reserved and 512 bits DH key is always used for exportable
1680          * cipher suites.
1681          */
1682         int keySize = export ? 512 : 1024;           // default mode
1683         if (!export) {
1684             if (useLegacyEphemeralDHKeys) {          // legacy mode
1685                 keySize = 768;
1686             } else if (useSmartEphemeralDHKeys) {    // matched mode
1687                 if (key != null) {
1688                     int ks = KeyUtil.getKeySize(key);
1689 
1690                     // DH parameter generation can be extremely slow, make
1691                     // sure to use one of the supported pre-computed DH
1692                     // parameters (see DHCrypt class).
1693                     //
1694                     // Old deployed applications may not be ready to support
1695                     // DH key sizes bigger than 2048 bits.  Please DON'T use
1696                     // value other than 1024 and 2048 at present.  May improve
1697                     // the underlying providers and key size limit in the
1698                     // future when the compatibility and interoperability
1699                     // impact is limited.
1700                     //
1701                     // keySize = ks <= 1024 ? 1024 : (ks >= 2048 ? 2048 : ks);
1702                     keySize = ks <= 1024 ? 1024 : 2048;
1703                 } // Otherwise, anonymous cipher suites, 1024-bit is used.
1704             } else if (customizedDHKeySize > 0) {    // customized mode
1705                 keySize = customizedDHKeySize;
1706             }
1707         }
1708 
1709         dh = new DHCrypt(keySize, sslContext.getSecureRandom());
1710     }
1711 
1712     /**
1713      * Setup the ephemeral ECDH parameters.
1714      */
1715     private void setupEphemeralECDHKeys(NamedGroup namedGroup) {
1716         ecdh = new ECDHCrypt(namedGroup, sslContext.getSecureRandom());
1717     }
1718 
1719     private void setupStaticECDHKeys() {
1720         // don't need to check whether the curve is supported, already done
1721         // in setupPrivateKeyAndChain().
1722         ecdh = new ECDHCrypt(privateKey, certs[0].getPublicKey());
1723     }
1724 
1725     /**
1726      * Retrieve the server key and certificate for the specified algorithm
1727      * from the KeyManager and set the instance variables.
1728      *
1729      * @return true if successful, false if not available or invalid
1730      */
1731     private boolean setupPrivateKeyAndChain(String algorithm) {
1732         X509ExtendedKeyManager km = sslContext.getX509KeyManager();
1733         String alias;
1734         if (conn != null) {
1735             alias = km.chooseServerAlias(algorithm, null, conn);
1736         } else {
1737             alias = km.chooseEngineServerAlias(algorithm, null, engine);
1738         }
1739         if (alias == null) {
1740             return false;
1741         }
1742         PrivateKey tempPrivateKey = km.getPrivateKey(alias);
1743         if (tempPrivateKey == null) {
1744             return false;
1745         }
1746         X509Certificate[] tempCerts = km.getCertificateChain(alias);
1747         if ((tempCerts == null) || (tempCerts.length == 0)) {
1748             return false;
1749         }
1750         String keyAlgorithm = algorithm.split("_")[0];
1751         PublicKey publicKey = tempCerts[0].getPublicKey();
1752         if ((tempPrivateKey.getAlgorithm().equals(keyAlgorithm) == false)
1753                 || (publicKey.getAlgorithm().equals(keyAlgorithm) == false)) {
1754             return false;
1755         }
1756         // For ECC certs, check whether we support the EC domain parameters.
1757         // If the client sent a SupportedEllipticCurves ClientHello extension,
1758         // check against that too.
1759         if (keyAlgorithm.equals("EC")) {
1760             if (publicKey instanceof ECPublicKey == false) {
1761                 return false;
1762             }
1763             ECParameterSpec params = ((ECPublicKey)publicKey).getParams();
1764             NamedGroup namedGroup = NamedGroup.valueOf(params);
1765             if ((namedGroup == null) ||
1766                 (!SupportedGroupsExtension.supports(namedGroup)) ||
1767                 ((requestedGroups != null) &&
1768                         !requestedGroups.contains(namedGroup.id))) {
1769                 return false;
1770             }
1771         }
1772         this.privateKey = tempPrivateKey;
1773         this.certs = tempCerts;
1774         return true;
1775     }
1776 
1777     /*
1778      * Returns premaster secret for external key exchange services.
1779      */
1780     private SecretKey clientKeyExchange(ClientKeyExchange mesg)
1781         throws IOException {
1782 
1783         if (debug != null && Debug.isOn("handshake")) {
1784             mesg.print(System.out);
1785         }
1786 
1787         // Record the principals involved in exchange
1788         session.setPeerPrincipal(mesg.getPeerPrincipal());
1789         session.setLocalPrincipal(mesg.getLocalPrincipal());
1790 
1791         return mesg.clientKeyExchange();
1792     }
1793 
1794     /*
1795      * Diffie Hellman key exchange is used when the server presented
1796      * D-H parameters in its certificate (signed using RSA or DSS/DSA),
1797      * or else the server presented no certificate but sent D-H params
1798      * in a ServerKeyExchange message.  Use of D-H is specified by the
1799      * cipher suite chosen.
1800      *
1801      * The message optionally contains the client's D-H public key (if
1802      * it wasn't not sent in a client certificate).  As always with D-H,
1803      * if a client and a server have each other's D-H public keys and
1804      * they use common algorithm parameters, they have a shared key
1805      * that's derived via the D-H calculation.  That key becomes the
1806      * pre-master secret.
1807      */
1808     private SecretKey clientKeyExchange(DHClientKeyExchange mesg)
1809             throws IOException {
1810 
1811         if (debug != null && Debug.isOn("handshake")) {
1812             mesg.print(System.out);
1813         }
1814 
1815         BigInteger publicKeyValue = mesg.getClientPublicKey();
1816 
1817         // check algorithm constraints
1818         dh.checkConstraints(algorithmConstraints, publicKeyValue);
1819 
1820         return dh.getAgreedSecret(publicKeyValue, false);
1821     }
1822 
1823     private SecretKey clientKeyExchange(ECDHClientKeyExchange mesg)
1824             throws IOException {
1825 
1826         if (debug != null && Debug.isOn("handshake")) {
1827             mesg.print(System.out);
1828         }
1829 
1830         byte[] publicPoint = mesg.getEncodedPoint();
1831 
1832         // check algorithm constraints
1833         ecdh.checkConstraints(algorithmConstraints, publicPoint);
1834 
1835         return ecdh.getAgreedSecret(publicPoint);
1836     }
1837 
1838     /*
1839      * Client wrote a message to verify the certificate it sent earlier.
1840      *
1841      * Note that this certificate isn't involved in key exchange.  Client
1842      * authentication messages are included in the checksums used to
1843      * validate the handshake (e.g. Finished messages).  Other than that,
1844      * the _exact_ identity of the client is less fundamental to protocol
1845      * security than its role in selecting keys via the pre-master secret.
1846      */
1847     private void clientCertificateVerify(CertificateVerify mesg)
1848             throws IOException {
1849 
1850         if (debug != null && Debug.isOn("handshake")) {
1851             mesg.print(System.out);
1852         }
1853 
1854         if (protocolVersion.useTLS12PlusSpec()) {
1855             SignatureAndHashAlgorithm signAlg =
1856                 mesg.getPreferableSignatureAlgorithm();
1857             if (signAlg == null) {
1858                 throw new SSLHandshakeException(
1859                         "Illegal CertificateVerify message");
1860             }
1861 
1862             String hashAlg =
1863                 SignatureAndHashAlgorithm.getHashAlgorithmName(signAlg);
1864             if (hashAlg == null || hashAlg.length() == 0) {
1865                 throw new SSLHandshakeException(
1866                         "No supported hash algorithm");
1867             }
1868         }
1869 
1870         try {
1871             PublicKey publicKey =
1872                 session.getPeerCertificates()[0].getPublicKey();
1873 
1874             boolean valid = mesg.verify(protocolVersion, handshakeHash,
1875                                         publicKey, session.getMasterSecret());
1876             if (valid == false) {
1877                 fatalSE(Alerts.alert_bad_certificate,
1878                             "certificate verify message signature error");
1879             }
1880         } catch (GeneralSecurityException e) {
1881             fatalSE(Alerts.alert_bad_certificate,
1882                 "certificate verify format error", e);
1883         }
1884 
1885         // reset the flag for clientCertificateVerify message
1886         needClientVerify = false;
1887     }
1888 
1889 
1890     /*
1891      * Client writes "finished" at the end of its handshake, after cipher
1892      * spec is changed.   We verify it and then send ours.
1893      *
1894      * When we're resuming a session, we'll have already sent our own
1895      * Finished message so just the verification is needed.
1896      */
1897     private void clientFinished(Finished mesg) throws IOException {
1898         if (debug != null && Debug.isOn("handshake")) {
1899             mesg.print(System.out);
1900         }
1901 
1902         /*
1903          * Verify if client did send the certificate when client
1904          * authentication was required, otherwise server should not proceed
1905          */
1906         if (doClientAuth == ClientAuthType.CLIENT_AUTH_REQUIRED) {
1907            // get X500Principal of the end-entity certificate for X509-based
1908            // ciphersuites, or Kerberos principal for Kerberos ciphersuites, etc
1909            session.getPeerPrincipal();
1910         }
1911 
1912         /*
1913          * Verify if client did send clientCertificateVerify message following
1914          * the client Certificate, otherwise server should not proceed
1915          */
1916         if (needClientVerify) {
1917                 fatalSE(Alerts.alert_handshake_failure,
1918                         "client did not send certificate verify message");
1919         }
1920 
1921         /*
1922          * Verify the client's message with the "before" digest of messages,
1923          * and forget about continuing to use that digest.
1924          */
1925         boolean verified = mesg.verify(handshakeHash, Finished.CLIENT,
1926             session.getMasterSecret());
1927 
1928         if (!verified) {
1929             fatalSE(Alerts.alert_handshake_failure,
1930                         "client 'finished' message doesn't verify");
1931             // NOTREACHED
1932         }
1933 
1934         /*
1935          * save client verify data for secure renegotiation
1936          */
1937         if (secureRenegotiation) {
1938             clientVerifyData = mesg.getVerifyData();
1939         }
1940 
1941         /*
1942          * OK, it verified.  If we're doing the full handshake, add that
1943          * "Finished" message to the hash of handshake messages, then send
1944          * the change_cipher_spec and Finished message.
1945          */
1946         if (!resumingSession) {
1947             sendChangeCipherAndFinish(true);
1948         } else {
1949             handshakeFinished = true;
1950         }
1951 
1952         /*
1953          * Update the session cache only after the handshake completed, else
1954          * we're open to an attack against a partially completed handshake.
1955          */
1956         session.setLastAccessedTime(System.currentTimeMillis());
1957         if (!resumingSession && session.isRejoinable()) {
1958             ((SSLSessionContextImpl)sslContext.engineGetServerSessionContext())
1959                 .put(session);
1960             if (debug != null && Debug.isOn("session")) {
1961                 System.out.println(
1962                     "%% Cached server session: " + session);
1963             }
1964         } else if (!resumingSession &&
1965                 debug != null && Debug.isOn("session")) {
1966             System.out.println(
1967                 "%% Didn't cache non-resumable server session: "
1968                 + session);
1969         }
1970     }
1971 
1972     /*
1973      * Compute finished message with the "server" digest (and then forget
1974      * about that digest, it can't be used again).
1975      */
1976     private void sendChangeCipherAndFinish(boolean finishedTag)
1977             throws IOException {
1978 
1979         // Reload if this message has been reserved.
1980         handshakeHash.reload();
1981 
1982         Finished mesg = new Finished(protocolVersion, handshakeHash,
1983             Finished.SERVER, session.getMasterSecret(), cipherSuite);
1984 
1985         /*
1986          * Send the change_cipher_spec record; then our Finished handshake
1987          * message will be the last handshake message.  Flush, and now we
1988          * are ready for application data!!
1989          */
1990         sendChangeCipherSpec(mesg, finishedTag);
1991 
1992         /*
1993          * save server verify data for secure renegotiation
1994          */
1995         if (secureRenegotiation) {
1996             serverVerifyData = mesg.getVerifyData();
1997         }
1998     }
1999 
2000 
2001     /*
2002      * Returns a HelloRequest message to kickstart renegotiations
2003      */
2004     @Override
2005     HandshakeMessage getKickstartMessage() {
2006         return new HelloRequest();
2007     }
2008 
2009 
2010     /*
2011      * Fault detected during handshake.
2012      */
2013     @Override
2014     void handshakeAlert(byte description) throws SSLProtocolException {
2015 
2016         String message = Alerts.alertDescription(description);
2017 
2018         if (debug != null && Debug.isOn("handshake")) {
2019             System.out.println("SSL -- handshake alert:  "
2020                 + message);
2021         }
2022 
2023         /*
2024          * It's ok to get a no_certificate alert from a client of which
2025          * we *requested* authentication information.
2026          * However, if we *required* it, then this is not acceptable.
2027          *
2028          * Anyone calling getPeerCertificates() on the
2029          * session will get an SSLPeerUnverifiedException.
2030          */
2031         if ((description == Alerts.alert_no_certificate) &&
2032                 (doClientAuth == ClientAuthType.CLIENT_AUTH_REQUESTED)) {
2033             return;
2034         }
2035 
2036         throw new SSLProtocolException("handshake alert: " + message);
2037     }
2038 
2039     /*
2040      * RSA key exchange is normally used.  The client encrypts a "pre-master
2041      * secret" with the server's public key, from the Certificate (or else
2042      * ServerKeyExchange) message that was sent to it by the server.  That's
2043      * decrypted using the private key before we get here.
2044      */
2045     private SecretKey clientKeyExchange(RSAClientKeyExchange mesg)
2046             throws IOException {
2047 
2048         if (debug != null && Debug.isOn("handshake")) {
2049             mesg.print(System.out);
2050         }
2051         return mesg.preMaster;
2052     }
2053 
2054     /*
2055      * Verify the certificate sent by the client. We'll only get one if we
2056      * sent a CertificateRequest to request client authentication. If we
2057      * are in TLS mode, the client may send a message with no certificates
2058      * to indicate it does not have an appropriate chain. (In SSLv3 mode,
2059      * it would send a no certificate alert).
2060      */
2061     private void clientCertificate(CertificateMsg mesg) throws IOException {
2062         if (debug != null && Debug.isOn("handshake")) {
2063             mesg.print(System.out);
2064         }
2065 
2066         X509Certificate[] peerCerts = mesg.getCertificateChain();
2067 
2068         if (peerCerts.length == 0) {
2069             /*
2070              * If the client authentication is only *REQUESTED* (e.g.
2071              * not *REQUIRED*, this is an acceptable condition.)
2072              */
2073             if (doClientAuth == ClientAuthType.CLIENT_AUTH_REQUESTED) {
2074                 return;
2075             } else {
2076                 fatalSE(Alerts.alert_bad_certificate,
2077                     "null cert chain");
2078             }
2079         }
2080 
2081         // ask the trust manager to verify the chain
2082         X509TrustManager tm = sslContext.getX509TrustManager();
2083 
2084         try {
2085             // find out the types of client authentication used
2086             PublicKey key = peerCerts[0].getPublicKey();
2087             String keyAlgorithm = key.getAlgorithm();
2088             String authType;
2089             if (keyAlgorithm.equals("RSA")) {
2090                 authType = "RSA";
2091             } else if (keyAlgorithm.equals("DSA")) {
2092                 authType = "DSA";
2093             } else if (keyAlgorithm.equals("EC")) {
2094                 authType = "EC";
2095             } else {
2096                 // unknown public key type
2097                 authType = "UNKNOWN";
2098             }
2099 
2100             if (tm instanceof X509ExtendedTrustManager) {
2101                 if (conn != null) {
2102                     ((X509ExtendedTrustManager)tm).checkClientTrusted(
2103                         peerCerts.clone(),
2104                         authType,
2105                         conn);
2106                 } else {
2107                     ((X509ExtendedTrustManager)tm).checkClientTrusted(
2108                         peerCerts.clone(),
2109                         authType,
2110                         engine);
2111                 }
2112             } else {
2113                 // Unlikely to happen, because we have wrapped the old
2114                 // X509TrustManager with the new X509ExtendedTrustManager.
2115                 throw new CertificateException(
2116                     "Improper X509TrustManager implementation");
2117             }
2118         } catch (CertificateException e) {
2119             // This will throw an exception, so include the original error.
2120             fatalSE(Alerts.alert_certificate_unknown, e);
2121         }
2122         // set the flag for clientCertificateVerify message
2123         needClientVerify = true;
2124 
2125         session.setPeerCertificates(peerCerts);
2126     }
2127 
2128     private StaplingParameters processStapling(ClientHello mesg) {
2129         StaplingParameters params = null;
2130         ExtensionType ext = null;
2131         StatusRequestType type = null;
2132         StatusRequest req = null;
2133         Map<X509Certificate, byte[]> responses;
2134 
2135         // If this feature has not been enabled, then no more processing
2136         // is necessary.  Also we will only staple if we're doing a full
2137         // handshake.
2138         if (!sslContext.isStaplingEnabled(false) || resumingSession) {
2139             return null;
2140         }
2141 
2142         // Check if the client has asserted the status_request[_v2] extension(s)
2143         CertStatusReqExtension statReqExt = (CertStatusReqExtension)
2144                     mesg.extensions.get(ExtensionType.EXT_STATUS_REQUEST);
2145         CertStatusReqListV2Extension statReqExtV2 =
2146                 (CertStatusReqListV2Extension)mesg.extensions.get(
2147                         ExtensionType.EXT_STATUS_REQUEST_V2);
2148 
2149         // Determine which type of stapling we are doing and assert the
2150         // proper extension in the server hello.
2151         // Favor status_request_v2 over status_request and ocsp_multi
2152         // over ocsp.
2153         // If multiple ocsp or ocsp_multi types exist, select the first
2154         // instance of a given type.  Also since we don't support ResponderId
2155         // selection yet, only accept a request if the ResponderId field
2156         // is empty.
2157         if (statReqExtV2 != null) {             // RFC 6961 stapling
2158             ext = ExtensionType.EXT_STATUS_REQUEST_V2;
2159             List<CertStatusReqItemV2> reqItems =
2160                     statReqExtV2.getRequestItems();
2161             int ocspIdx = -1;
2162             int ocspMultiIdx = -1;
2163             for (int pos = 0; (pos < reqItems.size() &&
2164                     (ocspIdx == -1 || ocspMultiIdx == -1)); pos++) {
2165                 CertStatusReqItemV2 item = reqItems.get(pos);
2166                 StatusRequestType curType = item.getType();
2167                 if (ocspIdx < 0 && curType == StatusRequestType.OCSP) {
2168                     OCSPStatusRequest ocspReq =
2169                             (OCSPStatusRequest)item.getRequest();
2170                     if (ocspReq.getResponderIds().isEmpty()) {
2171                         ocspIdx = pos;
2172                     }
2173                 } else if (ocspMultiIdx < 0 &&
2174                         curType == StatusRequestType.OCSP_MULTI) {
2175                     // If the type is OCSP, then the request
2176                     // is guaranteed to be OCSPStatusRequest
2177                     OCSPStatusRequest ocspReq =
2178                             (OCSPStatusRequest)item.getRequest();
2179                     if (ocspReq.getResponderIds().isEmpty()) {
2180                         ocspMultiIdx = pos;
2181                     }
2182                 }
2183             }
2184             if (ocspMultiIdx >= 0) {
2185                 type = reqItems.get(ocspMultiIdx).getType();
2186                 req = reqItems.get(ocspMultiIdx).getRequest();
2187             } else if (ocspIdx >= 0) {
2188                 type = reqItems.get(ocspIdx).getType();
2189                 req = reqItems.get(ocspIdx).getRequest();
2190             } else {
2191                 if (debug != null && Debug.isOn("handshake")) {
2192                     System.out.println("Warning: No suitable request " +
2193                             "found in the status_request_v2 extension.");
2194                 }
2195             }
2196         }
2197 
2198         // Only attempt to process a status_request extension if:
2199         // * The status_request extension is set AND
2200         // * either the status_request_v2 extension is not present OR
2201         // * none of the underlying OCSPStatusRequest structures is suitable
2202         // for stapling.
2203         // If either of the latter two bullet items is true the ext, type and
2204         // req variables should all be null.  If any are null we will try
2205         // processing an asserted status_request.
2206         if ((statReqExt != null) &&
2207                (ext == null || type == null || req == null)) {
2208             ext = ExtensionType.EXT_STATUS_REQUEST;
2209             type = statReqExt.getType();
2210             if (type == StatusRequestType.OCSP) {
2211                 // If the type is OCSP, then the request is guaranteed
2212                 // to be OCSPStatusRequest
2213                 OCSPStatusRequest ocspReq =
2214                         (OCSPStatusRequest)statReqExt.getRequest();
2215                 if (ocspReq.getResponderIds().isEmpty()) {
2216                     req = ocspReq;
2217                 } else {
2218                     if (debug != null && Debug.isOn("handshake")) {
2219                         req = null;
2220                         System.out.println("Warning: No suitable request " +
2221                                 "found in the status_request extension.");
2222                     }
2223                 }
2224             }
2225         }
2226 
2227         // If, after walking through the extensions we were unable to
2228         // find a suitable StatusRequest, then stapling is disabled.
2229         // The ext, type and req variables must have been set to continue.
2230         if (type == null || req == null || ext == null) {
2231             return null;
2232         }
2233 
2234         // Get the OCSP responses from the StatusResponseManager
2235         StatusResponseManager statRespMgr =
2236                 sslContext.getStatusResponseManager();
2237         if (statRespMgr != null) {
2238             responses = statRespMgr.get(type, req, certs, statusRespTimeout,
2239                     TimeUnit.MILLISECONDS);
2240             if (!responses.isEmpty()) {
2241                 // If this RFC 6066-style stapling (SSL cert only) then the
2242                 // response cannot be zero length
2243                 if (type == StatusRequestType.OCSP) {
2244                     byte[] respDER = responses.get(certs[0]);
2245                     if (respDER == null || respDER.length <= 0) {
2246                         return null;
2247                     }
2248                 }
2249                 params = new StaplingParameters(ext, type, req, responses);
2250             }
2251         } else {
2252             // This should not happen, but if lazy initialization of the
2253             // StatusResponseManager doesn't occur we should turn off stapling.
2254             if (debug != null && Debug.isOn("handshake")) {
2255                 System.out.println("Warning: lazy initialization " +
2256                         "of the StatusResponseManager failed.  " +
2257                         "Stapling has been disabled.");
2258             }
2259         }
2260 
2261         return params;
2262     }
2263 
2264     /**
2265      * Inner class used to hold stapling parameters needed by the handshaker
2266      * when stapling is active.
2267      */
2268     private class StaplingParameters {
2269         private final ExtensionType statusRespExt;
2270         private final StatusRequestType statReqType;
2271         private final StatusRequest statReqData;
2272         private final Map<X509Certificate, byte[]> responseMap;
2273 
2274         StaplingParameters(ExtensionType ext, StatusRequestType type,
2275                 StatusRequest req, Map<X509Certificate, byte[]> responses) {
2276             statusRespExt = ext;
2277             statReqType = type;
2278             statReqData = req;
2279             responseMap = responses;
2280         }
2281     }
2282 }