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 Certificate Authorities
 798             if (protocolVersion.useTLS12PlusSpec()) {
 799                 final CertificateAuthoritiesExtension certificateAuthoritiesExtension =
 800                         (CertificateAuthoritiesExtension)mesg.extensions.
 801                         get(ExtensionType.EXT_CERTIFICATE_AUTHORITIES);
 802                 if (certificateAuthoritiesExtension != null) {
 803                     session.setCertificateAuthorities(
 804                             certificateAuthoritiesExtension.getCertificateAuthorities());
 805                 }
 806             }
 807 
 808             // set the server name indication in the session
 809             List<SNIServerName> clientHelloSNI =
 810                     Collections.<SNIServerName>emptyList();
 811             if (clientHelloSNIExt != null) {
 812                 clientHelloSNI = clientHelloSNIExt.getServerNames();
 813             }
 814             session.setRequestedServerNames(clientHelloSNI);
 815 
 816             // set the handshake session
 817             setHandshakeSessionSE(session);
 818 
 819             // choose cipher suite and corresponding private key
 820             chooseCipherSuite(mesg);
 821 
 822             session.setSuite(cipherSuite);
 823             session.setLocalPrivateKey(privateKey);
 824 
 825             // chooseCompression(mesg);
 826 
 827             // set the negotiated maximum fragment in the session
 828             //
 829             // The protocol version and cipher suite have been negotiated
 830             // in previous processes.
 831             if (maxFragLenExt != null) {
 832                 int maxFragLen = maxFragLenExt.getMaxFragLen();
 833 
 834                 // More check of the requested "max_fragment_length" extension.
 835                 if (maximumPacketSize != 0) {
 836                     int estimatedMaxFragSize = cipherSuite.calculatePacketSize(
 837                             maxFragLen, protocolVersion, isDTLS);
 838                     if (estimatedMaxFragSize > maximumPacketSize) {
 839                         // For better interoperability, abort the maximum
 840                         // fragment length negotiation, rather than terminate
 841                         // the connection with a fatal alert.
 842                         maxFragLenExt = null;
 843 
 844                         // fatalSE(Alerts.alert_illegal_parameter,
 845                         //         "Not an allowed max_fragment_length value");
 846                     }
 847                 }
 848 
 849                 if (maxFragLenExt != null) {
 850                     session.setNegotiatedMaxFragSize(maxFragLen);
 851                 }
 852             }
 853 
 854             session.setMaximumPacketSize(maximumPacketSize);
 855         } else {
 856             // set the handshake session
 857             setHandshakeSessionSE(session);
 858         }
 859 
 860         if (protocolVersion.useTLS12PlusSpec()) {
 861             handshakeHash.setFinishedAlg(cipherSuite.prfAlg.getPRFHashAlg());
 862         }
 863 
 864         m1.cipherSuite = cipherSuite;
 865         m1.sessionId = session.getSessionId();
 866         m1.compression_method = session.getCompression();
 867 
 868         if (secureRenegotiation) {
 869             // For ServerHellos that are initial handshakes, then the
 870             // "renegotiated_connection" field in "renegotiation_info"
 871             // extension is of zero length.
 872             //
 873             // For ServerHellos that are renegotiating, this field contains
 874             // the concatenation of client_verify_data and server_verify_data.
 875             //
 876             // Note that for initial handshakes, both the clientVerifyData
 877             // variable and serverVerifyData variable are of zero length.
 878             HelloExtension serverHelloRI = new RenegotiationInfoExtension(
 879                                         clientVerifyData, serverVerifyData);
 880             m1.extensions.add(serverHelloRI);
 881         }
 882 
 883         if (!sniMatchers.isEmpty() && clientHelloSNIExt != null) {
 884             // When resuming a session, the server MUST NOT include a
 885             // server_name extension in the server hello.
 886             if (!resumingSession) {
 887                 ServerNameExtension serverHelloSNI = new ServerNameExtension();
 888                 m1.extensions.add(serverHelloSNI);
 889             }
 890         }
 891 
 892         if ((maxFragLenExt != null) && !resumingSession) {
 893             // When resuming a session, the server MUST NOT include a
 894             // max_fragment_length extension in the server hello.
 895             //
 896             // Otherwise, use the same value as the requested extension.
 897             m1.extensions.add(maxFragLenExt);
 898         }
 899 
 900         StaplingParameters staplingParams = processStapling(mesg);
 901         if (staplingParams != null) {
 902             // We now can safely assert status_request[_v2] in our
 903             // ServerHello, and know for certain that we can provide
 904             // responses back to this client for this connection.
 905             if (staplingParams.statusRespExt ==
 906                     ExtensionType.EXT_STATUS_REQUEST) {
 907                 m1.extensions.add(new CertStatusReqExtension());
 908             } else if (staplingParams.statusRespExt ==
 909                     ExtensionType.EXT_STATUS_REQUEST_V2) {
 910                 m1.extensions.add(new CertStatusReqListV2Extension());
 911             }
 912         }
 913 
 914         // Prepare the ALPN response
 915         if (clientHelloALPN != null) {
 916             List<String> peerAPs = clientHelloALPN.getPeerAPs();
 917 
 918             // check for a callback function
 919             if (hasAPCallback) {
 920                 if (conn != null) {
 921                     applicationProtocol =
 922                         appProtocolSelectorSSLSocket.apply(conn, peerAPs);
 923                 } else {
 924                     applicationProtocol =
 925                         appProtocolSelectorSSLEngine.apply(engine, peerAPs);
 926                 }
 927             }
 928 
 929             // check for no-match and that the selected name was also proposed
 930             // by the TLS peer
 931             if (applicationProtocol == null ||
 932                    (!applicationProtocol.isEmpty() &&
 933                         !peerAPs.contains(applicationProtocol))) {
 934 
 935                 fatalSE(Alerts.alert_no_application_protocol,
 936                     new SSLHandshakeException(
 937                         "No matching ALPN values"));
 938 
 939             } else if (!applicationProtocol.isEmpty()) {
 940                 m1.extensions.add(new ALPNExtension(applicationProtocol));
 941             }
 942         } else {
 943             // Nothing was negotiated, returned at end of the handshake
 944             applicationProtocol = "";
 945         }
 946 
 947         if (debug != null && Debug.isOn("handshake")) {
 948             m1.print(System.out);
 949             System.out.println("Cipher suite:  " + session.getSuite());
 950         }
 951         m1.write(output);
 952         handshakeState.update(m1, resumingSession);
 953 
 954         //
 955         // If we are resuming a session, we finish writing handshake
 956         // messages right now and then finish.
 957         //
 958         if (resumingSession) {
 959             calculateConnectionKeys(session.getMasterSecret());
 960             sendChangeCipherAndFinish(false);
 961 
 962             // expecting the final ChangeCipherSpec and Finished messages
 963             expectingFinishFlightSE();
 964 
 965             return;
 966         }
 967 
 968 
 969         /*
 970          * SECOND, write the server Certificate(s) if we need to.
 971          *
 972          * NOTE:  while an "anonymous RSA" mode is explicitly allowed by
 973          * the protocol, we can't support it since all of the SSL flavors
 974          * defined in the protocol spec are explicitly stated to require
 975          * using RSA certificates.
 976          */
 977         if (ClientKeyExchangeService.find(cipherSuite.keyExchange.name) != null) {
 978             // No external key exchange provider needs a cert now.
 979         } else if ((keyExchange != K_DH_ANON) && (keyExchange != K_ECDH_ANON)) {
 980             if (certs == null) {
 981                 throw new RuntimeException("no certificates");
 982             }
 983 
 984             CertificateMsg m2 = new CertificateMsg(certs);
 985 
 986             /*
 987              * Set local certs in the SSLSession, output
 988              * debug info, and then actually write to the client.
 989              */
 990             session.setLocalCertificates(certs);
 991             if (debug != null && Debug.isOn("handshake")) {
 992                 m2.print(System.out);
 993             }
 994             m2.write(output);
 995             handshakeState.update(m2, resumingSession);
 996 
 997             // XXX has some side effects with OS TCP buffering,
 998             // leave it out for now
 999 
1000             // let client verify chain in the meantime...
1001             // output.flush();
1002         } else {
1003             if (certs != null) {
1004                 throw new RuntimeException("anonymous keyexchange with certs");
1005             }
1006         }
1007 
1008         /**
1009          * The CertificateStatus message ... only if it is needed.
1010          * This would only be needed if we've established that this handshake
1011          * supports status stapling and there is at least one response to
1012          * return to the client.
1013          */
1014         if (staplingParams != null) {
1015             CertificateStatus csMsg = new CertificateStatus(
1016                     staplingParams.statReqType, certs,
1017                     staplingParams.responseMap);
1018             if (debug != null && Debug.isOn("handshake")) {
1019                 csMsg.print(System.out);
1020             }
1021             csMsg.write(output);
1022             handshakeState.update(csMsg, resumingSession);
1023         }
1024 
1025         /*
1026          * THIRD, the ServerKeyExchange message ... iff it's needed.
1027          *
1028          * It's usually needed unless there's an encryption-capable
1029          * RSA cert, or a D-H cert.  The notable exception is that
1030          * exportable ciphers used with big RSA keys need to downgrade
1031          * to use short RSA keys, even when the key/cert encrypts OK.
1032          */
1033 
1034         ServerKeyExchange m3;
1035         switch (keyExchange) {
1036         case K_RSA:
1037             // no server key exchange for RSA ciphersuites
1038             m3 = null;
1039             break;
1040         case K_RSA_EXPORT:
1041             if (JsseJce.getRSAKeyLength(certs[0].getPublicKey()) > 512) {
1042                 try {
1043                     m3 = new RSA_ServerKeyExchange(
1044                         tempPublicKey, privateKey,
1045                         clnt_random, svr_random,
1046                         sslContext.getSecureRandom());
1047                     privateKey = tempPrivateKey;
1048                 } catch (GeneralSecurityException e) {
1049                     m3 = null; // make compiler happy
1050                     throw new SSLException(
1051                             "Error generating RSA server key exchange", e);
1052                 }
1053             } else {
1054                 // RSA_EXPORT with short key, don't need ServerKeyExchange
1055                 m3 = null;
1056             }
1057             break;
1058         case K_DHE_RSA:
1059         case K_DHE_DSS:
1060             try {
1061                 m3 = new DH_ServerKeyExchange(dh,
1062                     privateKey,
1063                     clnt_random.random_bytes,
1064                     svr_random.random_bytes,
1065                     sslContext.getSecureRandom(),
1066                     preferableSignatureAlgorithm,
1067                     protocolVersion);
1068             } catch (GeneralSecurityException e) {
1069                 m3 = null; // make compiler happy
1070                 throw new SSLException(
1071                         "Error generating DH server key exchange", e);
1072             }
1073             break;
1074         case K_DH_ANON:
1075             m3 = new DH_ServerKeyExchange(dh, protocolVersion);
1076             break;
1077         case K_ECDHE_RSA:
1078         case K_ECDHE_ECDSA:
1079         case K_ECDH_ANON:
1080             try {
1081                 m3 = new ECDH_ServerKeyExchange(ecdh,
1082                     privateKey,
1083                     clnt_random.random_bytes,
1084                     svr_random.random_bytes,
1085                     sslContext.getSecureRandom(),
1086                     preferableSignatureAlgorithm,
1087                     protocolVersion);
1088             } catch (GeneralSecurityException e) {
1089                 m3 = null; // make compiler happy
1090                 throw new SSLException(
1091                         "Error generating ECDH server key exchange", e);
1092             }
1093             break;
1094         case K_ECDH_RSA:
1095         case K_ECDH_ECDSA:
1096             // ServerKeyExchange not used for fixed ECDH
1097             m3 = null;
1098             break;
1099         default:
1100             ClientKeyExchangeService p =
1101                     ClientKeyExchangeService.find(keyExchange.name);
1102             if (p != null) {
1103                 // No external key exchange provider needs a cert now.
1104                 m3 = null;
1105                 break;
1106             }
1107             throw new RuntimeException("internal error: " + keyExchange);
1108         }
1109         if (m3 != null) {
1110             if (debug != null && Debug.isOn("handshake")) {
1111                 m3.print(System.out);
1112             }
1113             m3.write(output);
1114             handshakeState.update(m3, resumingSession);
1115         }
1116 
1117         //
1118         // FOURTH, the CertificateRequest message.  The details of
1119         // the message can be affected by the key exchange algorithm
1120         // in use.  For example, certs with fixed Diffie-Hellman keys
1121         // are only useful with the DH_DSS and DH_RSA key exchange
1122         // algorithms.
1123         //
1124         // Needed only if server requires client to authenticate self.
1125         // Illegal for anonymous flavors, so we need to check that.
1126         //
1127         // No external key exchange provider needs a cert now.
1128         if (doClientAuth != ClientAuthType.CLIENT_AUTH_NONE &&
1129                 keyExchange != K_DH_ANON && keyExchange != K_ECDH_ANON &&
1130                 ClientKeyExchangeService.find(keyExchange.name) == null) {
1131 
1132             CertificateRequest m4;
1133             X509Certificate[] caCerts;
1134 
1135             Collection<SignatureAndHashAlgorithm> localSignAlgs = null;
1136             if (protocolVersion.useTLS12PlusSpec()) {
1137                 // We currently use all local upported signature and hash
1138                 // algorithms. However, to minimize the computation cost
1139                 // of requested hash algorithms, we may use a restricted
1140                 // set of signature algorithms in the future.
1141                 localSignAlgs = getLocalSupportedSignAlgs();
1142                 if (localSignAlgs.isEmpty()) {
1143                     throw new SSLHandshakeException(
1144                             "No supported signature algorithm");
1145                 }
1146 
1147                 Set<String> localHashAlgs =
1148                     SignatureAndHashAlgorithm.getHashAlgorithmNames(
1149                         localSignAlgs);
1150                 if (localHashAlgs.isEmpty()) {
1151                     throw new SSLHandshakeException(
1152                             "No supported signature algorithm");
1153                 }
1154             }
1155 
1156             caCerts = sslContext.getX509TrustManager().getAcceptedIssuers();
1157             m4 = new CertificateRequest(caCerts, keyExchange,
1158                                             localSignAlgs, protocolVersion);
1159 
1160             if (debug != null && Debug.isOn("handshake")) {
1161                 m4.print(System.out);
1162             }
1163             m4.write(output);
1164             handshakeState.update(m4, resumingSession);
1165         }
1166 
1167         /*
1168          * FIFTH, say ServerHelloDone.
1169          */
1170         ServerHelloDone m5 = new ServerHelloDone();
1171 
1172         if (debug != null && Debug.isOn("handshake")) {
1173             m5.print(System.out);
1174         }
1175         m5.write(output);
1176         handshakeState.update(m5, resumingSession);
1177 
1178         /*
1179          * Flush any buffered messages so the client will see them.
1180          * Ideally, all the messages above go in a single network level
1181          * message to the client.  Without big Certificate chains, it's
1182          * going to be the common case.
1183          */
1184         output.flush();
1185     }
1186 
1187     /*
1188      * Choose cipher suite from among those supported by client. Sets
1189      * the cipherSuite and keyExchange variables.
1190      */
1191     private void chooseCipherSuite(ClientHello mesg) throws IOException {
1192         CipherSuiteList prefered;
1193         CipherSuiteList proposed;
1194         if (preferLocalCipherSuites) {
1195             prefered = getActiveCipherSuites();
1196             proposed = mesg.getCipherSuites();
1197         } else {
1198             prefered = mesg.getCipherSuites();
1199             proposed = getActiveCipherSuites();
1200         }
1201 
1202         List<CipherSuite> legacySuites = new ArrayList<>();
1203         for (CipherSuite suite : prefered.collection()) {
1204             if (isNegotiable(proposed, suite) == false) {
1205                 continue;
1206             }
1207 
1208             if (doClientAuth == ClientAuthType.CLIENT_AUTH_REQUIRED) {
1209                 if ((suite.keyExchange == K_DH_ANON) ||
1210                     (suite.keyExchange == K_ECDH_ANON)) {
1211                     continue;
1212                 }
1213             }
1214 
1215             if (!legacyAlgorithmConstraints.permits(null, suite.name, null)) {
1216                 legacySuites.add(suite);
1217                 continue;
1218             }
1219 
1220             if (trySetCipherSuite(suite) == false) {
1221                 continue;
1222             }
1223 
1224             if (debug != null && Debug.isOn("handshake")) {
1225                 System.out.println("Standard ciphersuite chosen: " + suite);
1226             }
1227             return;
1228         }
1229 
1230         for (CipherSuite suite : legacySuites) {
1231             if (trySetCipherSuite(suite)) {
1232                 if (debug != null && Debug.isOn("handshake")) {
1233                     System.out.println("Legacy ciphersuite chosen: " + suite);
1234                 }
1235                 return;
1236             }
1237         }
1238 
1239         fatalSE(Alerts.alert_handshake_failure, "no cipher suites in common");
1240     }
1241 
1242     /**
1243      * Set the given CipherSuite, if possible. Return the result.
1244      * The call succeeds if the CipherSuite is available and we have
1245      * the necessary certificates to complete the handshake. We don't
1246      * check if the CipherSuite is actually enabled.
1247      *
1248      * If successful, this method also generates ephemeral keys if
1249      * required for this ciphersuite. This may take some time, so this
1250      * method should only be called if you really want to use the
1251      * CipherSuite.
1252      *
1253      * This method is called from chooseCipherSuite() in this class.
1254      */
1255     boolean trySetCipherSuite(CipherSuite suite) {
1256         /*
1257          * If we're resuming a session we know we can
1258          * support this key exchange algorithm and in fact
1259          * have already cached the result of it in
1260          * the session state.
1261          */
1262         if (resumingSession) {
1263             return true;
1264         }
1265 
1266         if (suite.isNegotiable() == false) {
1267             return false;
1268         }
1269 
1270         // must not negotiate the obsoleted weak cipher suites.
1271         if (protocolVersion.obsoletes(suite)) {
1272             return false;
1273         }
1274 
1275         // must not negotiate unsupported cipher suites.
1276         if (!protocolVersion.supports(suite)) {
1277             return false;
1278         }
1279 
1280         KeyExchange keyExchange = suite.keyExchange;
1281 
1282         // null out any existing references
1283         privateKey = null;
1284         certs = null;
1285         dh = null;
1286         tempPrivateKey = null;
1287         tempPublicKey = null;
1288 
1289         Collection<SignatureAndHashAlgorithm> supportedSignAlgs = null;
1290         if (protocolVersion.useTLS12PlusSpec()) {
1291             if (peerSupportedSignAlgs != null) {
1292                 supportedSignAlgs = peerSupportedSignAlgs;
1293             } else {
1294                 SignatureAndHashAlgorithm algorithm = null;
1295 
1296                 // we may optimize the performance
1297                 switch (keyExchange) {
1298                     // If the negotiated key exchange algorithm is one of
1299                     // (RSA, DHE_RSA, DH_RSA, RSA_PSK, ECDH_RSA, ECDHE_RSA),
1300                     // behave as if client had sent the value {sha1,rsa}.
1301                     case K_RSA:
1302                     case K_DHE_RSA:
1303                     case K_DH_RSA:
1304                     // case K_RSA_PSK:
1305                     case K_ECDH_RSA:
1306                     case K_ECDHE_RSA:
1307                         algorithm = SignatureAndHashAlgorithm.valueOf(
1308                                 HashAlgorithm.SHA1.value,
1309                                 SignatureAlgorithm.RSA.value, 0);
1310                         break;
1311                     // If the negotiated key exchange algorithm is one of
1312                     // (DHE_DSS, DH_DSS), behave as if the client had
1313                     // sent the value {sha1,dsa}.
1314                     case K_DHE_DSS:
1315                     case K_DH_DSS:
1316                         algorithm = SignatureAndHashAlgorithm.valueOf(
1317                                 HashAlgorithm.SHA1.value,
1318                                 SignatureAlgorithm.DSA.value, 0);
1319                         break;
1320                     // If the negotiated key exchange algorithm is one of
1321                     // (ECDH_ECDSA, ECDHE_ECDSA), behave as if the client
1322                     // had sent value {sha1,ecdsa}.
1323                     case K_ECDH_ECDSA:
1324                     case K_ECDHE_ECDSA:
1325                         algorithm = SignatureAndHashAlgorithm.valueOf(
1326                                 HashAlgorithm.SHA1.value,
1327                                 SignatureAlgorithm.ECDSA.value, 0);
1328                         break;
1329                     default:
1330                         // no peer supported signature algorithms
1331                 }
1332 
1333                 if (algorithm == null) {
1334                     supportedSignAlgs =
1335                         Collections.<SignatureAndHashAlgorithm>emptySet();
1336                 } else {
1337                     supportedSignAlgs =
1338                         new ArrayList<SignatureAndHashAlgorithm>(1);
1339                     supportedSignAlgs.add(algorithm);
1340 
1341                     supportedSignAlgs =
1342                             SignatureAndHashAlgorithm.getSupportedAlgorithms(
1343                                 algorithmConstraints, supportedSignAlgs);
1344 
1345                     // May be no default activated signature algorithm, but
1346                     // let the following process make the final decision.
1347                 }
1348 
1349                 // Sets the peer supported signature algorithm to use in KM
1350                 // temporarily.
1351                 session.setPeerSupportedSignatureAlgorithms(supportedSignAlgs);
1352             }
1353         }
1354 
1355         // The named group used for ECDHE and FFDHE.
1356         NamedGroup namedGroup = null;
1357         switch (keyExchange) {
1358         case K_RSA:
1359             // need RSA certs for authentication
1360             if (setupPrivateKeyAndChain("RSA") == false) {
1361                 return false;
1362             }
1363             break;
1364         case K_RSA_EXPORT:
1365             // need RSA certs for authentication
1366             if (setupPrivateKeyAndChain("RSA") == false) {
1367                 return false;
1368             }
1369 
1370             try {
1371                if (JsseJce.getRSAKeyLength(certs[0].getPublicKey()) > 512) {
1372                     if (!setupEphemeralRSAKeys(suite.exportable)) {
1373                         return false;
1374                     }
1375                }
1376             } catch (RuntimeException e) {
1377                 // could not determine keylength, ignore key
1378                 return false;
1379             }
1380             break;
1381         case K_DHE_RSA:
1382             // Is ephemeral DH cipher suite usable for the connection?
1383             //
1384             // [RFC 7919] If a compatible TLS server receives a Supported
1385             // Groups extension from a client that includes any FFDHE group
1386             // (i.e., any codepoint between 256 and 511, inclusive, even if
1387             // unknown to the server), and if none of the client-proposed
1388             // FFDHE groups are known and acceptable to the server, then
1389             // the server MUST NOT select an FFDHE cipher suite.  In this
1390             // case, the server SHOULD select an acceptable non-FFDHE cipher
1391             // suite from the client's offered list.  If the extension is
1392             // present with FFDHE groups, none of the client's offered
1393             // groups are acceptable by the server, and none of the client's
1394             // proposed non-FFDHE cipher suites are acceptable to the server,
1395             // the server MUST end the connection with a fatal TLS alert
1396             // of type insufficient_security(71).
1397             //
1398             // Note: For compatibility, if an application is customized to
1399             // use legacy sizes (512 bits for exportable cipher suites and
1400             // 768 bits for others), or the cipher suite is exportable, the
1401             // FFDHE extension will not be used.
1402             if ((!useLegacyEphemeralDHKeys) && (!suite.exportable) &&
1403                 (requestedGroups != null) && requestedGroups.hasFFDHEGroup()) {
1404 
1405                 namedGroup = requestedGroups.getPreferredGroup(
1406                     algorithmConstraints, NamedGroupType.NAMED_GROUP_FFDHE);
1407                 if (namedGroup == null) {
1408                     // no match found, cannot use this cipher suite.
1409                     return false;
1410                 }
1411             }
1412 
1413             // need RSA certs for authentication
1414             if (setupPrivateKeyAndChain("RSA") == false) {
1415                 return false;
1416             }
1417 
1418             // get preferable peer signature algorithm for server key exchange
1419             if (protocolVersion.useTLS12PlusSpec()) {
1420                 preferableSignatureAlgorithm =
1421                     SignatureAndHashAlgorithm.getPreferableAlgorithm(
1422                                         supportedSignAlgs, "RSA", privateKey);
1423                 if (preferableSignatureAlgorithm == null) {
1424                     if ((debug != null) && Debug.isOn("handshake")) {
1425                         System.out.println(
1426                                 "No signature and hash algorithm for cipher " +
1427                                 suite);
1428                     }
1429                     return false;
1430                 }
1431             }
1432 
1433             setupEphemeralDHKeys(namedGroup, suite.exportable, privateKey);
1434             break;
1435         case K_ECDHE_RSA:
1436             // Is ECDHE cipher suite usable for the connection?
1437             namedGroup = (requestedGroups != null) ?
1438                 requestedGroups.getPreferredGroup(
1439                     algorithmConstraints, NamedGroupType.NAMED_GROUP_ECDHE) :
1440                 SupportedGroupsExtension.getPreferredECGroup(
1441                     algorithmConstraints);
1442             if (namedGroup == null) {
1443                 // no match found, cannot use this ciphersuite
1444                 return false;
1445             }
1446 
1447             // need RSA certs for authentication
1448             if (setupPrivateKeyAndChain("RSA") == false) {
1449                 return false;
1450             }
1451 
1452             // get preferable peer signature algorithm for server key exchange
1453             if (protocolVersion.useTLS12PlusSpec()) {
1454                 preferableSignatureAlgorithm =
1455                     SignatureAndHashAlgorithm.getPreferableAlgorithm(
1456                                         supportedSignAlgs, "RSA", privateKey);
1457                 if (preferableSignatureAlgorithm == null) {
1458                     if ((debug != null) && Debug.isOn("handshake")) {
1459                         System.out.println(
1460                                 "No signature and hash algorithm for cipher " +
1461                                 suite);
1462                     }
1463                     return false;
1464                 }
1465             }
1466 
1467             setupEphemeralECDHKeys(namedGroup);
1468             break;
1469         case K_DHE_DSS:
1470             // Is ephemeral DH cipher suite usable for the connection?
1471             //
1472             // See comment in K_DHE_RSA case.
1473             if ((!useLegacyEphemeralDHKeys) && (!suite.exportable) &&
1474                 (requestedGroups != null) && requestedGroups.hasFFDHEGroup()) {
1475 
1476                 namedGroup = requestedGroups.getPreferredGroup(
1477                     algorithmConstraints, NamedGroupType.NAMED_GROUP_FFDHE);
1478                 if (namedGroup == null) {
1479                     // no match found, cannot use this cipher suite.
1480                     return false;
1481                 }
1482             }
1483 
1484             // get preferable peer signature algorithm for server key exchange
1485             if (protocolVersion.useTLS12PlusSpec()) {
1486                 preferableSignatureAlgorithm =
1487                     SignatureAndHashAlgorithm.getPreferableAlgorithm(
1488                                                 supportedSignAlgs, "DSA");
1489                 if (preferableSignatureAlgorithm == null) {
1490                     if ((debug != null) && Debug.isOn("handshake")) {
1491                         System.out.println(
1492                                 "No signature and hash algorithm for cipher " +
1493                                 suite);
1494                     }
1495                     return false;
1496                 }
1497             }
1498 
1499             // need DSS certs for authentication
1500             if (setupPrivateKeyAndChain("DSA") == false) {
1501                 return false;
1502             }
1503 
1504             setupEphemeralDHKeys(namedGroup, suite.exportable, privateKey);
1505             break;
1506         case K_ECDHE_ECDSA:
1507             // Is ECDHE cipher suite usable for the connection?
1508             namedGroup = (requestedGroups != null) ?
1509                 requestedGroups.getPreferredGroup(
1510                     algorithmConstraints, NamedGroupType.NAMED_GROUP_ECDHE) :
1511                 SupportedGroupsExtension.getPreferredECGroup(
1512                     algorithmConstraints);
1513             if (namedGroup == null) {
1514                 // no match found, cannot use this ciphersuite
1515                 return false;
1516             }
1517 
1518             // get preferable peer signature algorithm for server key exchange
1519             if (protocolVersion.useTLS12PlusSpec()) {
1520                 preferableSignatureAlgorithm =
1521                     SignatureAndHashAlgorithm.getPreferableAlgorithm(
1522                                             supportedSignAlgs, "ECDSA");
1523                 if (preferableSignatureAlgorithm == null) {
1524                     if ((debug != null) && Debug.isOn("handshake")) {
1525                         System.out.println(
1526                                 "No signature and hash algorithm for cipher " +
1527                                 suite);
1528                     }
1529                     return false;
1530                 }
1531             }
1532 
1533             // need EC cert
1534             if (setupPrivateKeyAndChain("EC") == false) {
1535                 return false;
1536             }
1537 
1538             setupEphemeralECDHKeys(namedGroup);
1539             break;
1540         case K_ECDH_RSA:
1541             // need EC cert
1542             if (setupPrivateKeyAndChain("EC") == false) {
1543                 return false;
1544             }
1545             setupStaticECDHKeys();
1546             break;
1547         case K_ECDH_ECDSA:
1548             // need EC cert
1549             if (setupPrivateKeyAndChain("EC") == false) {
1550                 return false;
1551             }
1552             setupStaticECDHKeys();
1553             break;
1554         case K_DH_ANON:
1555             // Is ephemeral DH cipher suite usable for the connection?
1556             //
1557             // See comment in K_DHE_RSA case.
1558             if ((!useLegacyEphemeralDHKeys) && (!suite.exportable) &&
1559                 (requestedGroups != null) && requestedGroups.hasFFDHEGroup()) {
1560                 namedGroup = requestedGroups.getPreferredGroup(
1561                     algorithmConstraints, NamedGroupType.NAMED_GROUP_FFDHE);
1562                 if (namedGroup == null) {
1563                     // no match found, cannot use this cipher suite.
1564                     return false;
1565                 }
1566             }
1567 
1568             // no certs needed for anonymous
1569             setupEphemeralDHKeys(namedGroup, suite.exportable, null);
1570             break;
1571         case K_ECDH_ANON:
1572             // Is ECDHE cipher suite usable for the connection?
1573             namedGroup = (requestedGroups != null) ?
1574                 requestedGroups.getPreferredGroup(
1575                     algorithmConstraints, NamedGroupType.NAMED_GROUP_ECDHE) :
1576                 SupportedGroupsExtension.getPreferredECGroup(
1577                     algorithmConstraints);
1578             if (namedGroup == null) {
1579                 // no match found, cannot use this ciphersuite
1580                 return false;
1581             }
1582 
1583             // no certs needed for anonymous
1584             setupEphemeralECDHKeys(namedGroup);
1585             break;
1586         default:
1587             ClientKeyExchangeService p =
1588                     ClientKeyExchangeService.find(keyExchange.name);
1589             if (p == null) {
1590                 // internal error, unknown key exchange
1591                 throw new RuntimeException(
1592                         "Unrecognized cipherSuite: " + suite);
1593             }
1594             // need service creds
1595             if (serviceCreds == null) {
1596                 AccessControlContext acc = getAccSE();
1597                 serviceCreds = p.getServiceCreds(acc);
1598                 if (serviceCreds != null) {
1599                     if (debug != null && Debug.isOn("handshake")) {
1600                         System.out.println("Using serviceCreds");
1601                     }
1602                 }
1603                 if (serviceCreds == null) {
1604                     return false;
1605                 }
1606             }
1607             break;
1608         }
1609         setCipherSuite(suite);
1610 
1611         // set the peer implicit supported signature algorithms
1612         if (protocolVersion.useTLS12PlusSpec()) {
1613             if (peerSupportedSignAlgs == null) {
1614                 setPeerSupportedSignAlgs(supportedSignAlgs);
1615                 // we had alreay update the session
1616             }
1617         }
1618         return true;
1619     }
1620 
1621     /*
1622      * Get some "ephemeral" RSA keys for this context. This means
1623      * generating them if it's not already been done.
1624      *
1625      * Note that we currently do not implement any ciphersuites that use
1626      * strong ephemeral RSA. (We do not support the EXPORT1024 ciphersuites
1627      * and standard RSA ciphersuites prohibit ephemeral mode for some reason)
1628      * This means that export is always true and 512 bit keys are generated.
1629      */
1630     private boolean setupEphemeralRSAKeys(boolean export) {
1631         KeyPair kp = sslContext.getEphemeralKeyManager().
1632                         getRSAKeyPair(export, sslContext.getSecureRandom());
1633         if (kp == null) {
1634             return false;
1635         } else {
1636             tempPublicKey = kp.getPublic();
1637             tempPrivateKey = kp.getPrivate();
1638             return true;
1639         }
1640     }
1641 
1642     /*
1643      * Acquire some "ephemeral" Diffie-Hellman  keys for this handshake.
1644      * We don't reuse these, for improved forward secrecy.
1645      */
1646     private void setupEphemeralDHKeys(
1647             NamedGroup namedGroup, boolean export, Key key) {
1648         // Are the client and server willing to negotiate FFDHE groups?
1649         if ((!useLegacyEphemeralDHKeys) && (!export) && (namedGroup != null)) {
1650             dh = new DHCrypt(namedGroup, sslContext.getSecureRandom());
1651 
1652             return;
1653         }   // Otherwise, the client is not compatible with FFDHE extension.
1654 
1655         /*
1656          * 768 bits ephemeral DH private keys were used to be used in
1657          * ServerKeyExchange except that exportable ciphers max out at 512
1658          * bits modulus values. We still adhere to this behavior in legacy
1659          * mode (system property "jdk.tls.ephemeralDHKeySize" is defined
1660          * as "legacy").
1661          *
1662          * Old JDK (JDK 7 and previous) releases don't support DH keys bigger
1663          * than 1024 bits. We have to consider the compatibility requirement.
1664          * 1024 bits DH key is always used for non-exportable cipher suites
1665          * in default mode (system property "jdk.tls.ephemeralDHKeySize"
1666          * is not defined).
1667          *
1668          * However, if applications want more stronger strength, setting
1669          * system property "jdk.tls.ephemeralDHKeySize" to "matched"
1670          * is a workaround to use ephemeral DH key which size matches the
1671          * corresponding authentication key. For example, if the public key
1672          * size of an authentication certificate is 2048 bits, then the
1673          * ephemeral DH key size should be 2048 bits accordingly unless
1674          * the cipher suite is exportable.  This key sizing scheme keeps
1675          * the cryptographic strength consistent between authentication
1676          * keys and key-exchange keys.
1677          *
1678          * Applications may also want to customize the ephemeral DH key size
1679          * to a fixed length for non-exportable cipher suites. This can be
1680          * approached by setting system property "jdk.tls.ephemeralDHKeySize"
1681          * to a valid positive integer between 1024 and 8192 bits, inclusive.
1682          *
1683          * Note that the minimum acceptable key size is 1024 bits except
1684          * exportable cipher suites or legacy mode.
1685          *
1686          * Note that per RFC 2246, the key size limit of DH is 512 bits for
1687          * exportable cipher suites.  Because of the weakness, exportable
1688          * cipher suites are deprecated since TLS v1.1 and they are not
1689          * enabled by default in Oracle provider. The legacy behavior is
1690          * reserved and 512 bits DH key is always used for exportable
1691          * cipher suites.
1692          */
1693         int keySize = export ? 512 : 1024;           // default mode
1694         if (!export) {
1695             if (useLegacyEphemeralDHKeys) {          // legacy mode
1696                 keySize = 768;
1697             } else if (useSmartEphemeralDHKeys) {    // matched mode
1698                 if (key != null) {
1699                     int ks = KeyUtil.getKeySize(key);
1700 
1701                     // DH parameter generation can be extremely slow, make
1702                     // sure to use one of the supported pre-computed DH
1703                     // parameters (see DHCrypt class).
1704                     //
1705                     // Old deployed applications may not be ready to support
1706                     // DH key sizes bigger than 2048 bits.  Please DON'T use
1707                     // value other than 1024 and 2048 at present.  May improve
1708                     // the underlying providers and key size limit in the
1709                     // future when the compatibility and interoperability
1710                     // impact is limited.
1711                     //
1712                     // keySize = ks <= 1024 ? 1024 : (ks >= 2048 ? 2048 : ks);
1713                     keySize = ks <= 1024 ? 1024 : 2048;
1714                 } // Otherwise, anonymous cipher suites, 1024-bit is used.
1715             } else if (customizedDHKeySize > 0) {    // customized mode
1716                 keySize = customizedDHKeySize;
1717             }
1718         }
1719 
1720         dh = new DHCrypt(keySize, sslContext.getSecureRandom());
1721     }
1722 
1723     /**
1724      * Setup the ephemeral ECDH parameters.
1725      */
1726     private void setupEphemeralECDHKeys(NamedGroup namedGroup) {
1727         ecdh = new ECDHCrypt(namedGroup, sslContext.getSecureRandom());
1728     }
1729 
1730     private void setupStaticECDHKeys() {
1731         // don't need to check whether the curve is supported, already done
1732         // in setupPrivateKeyAndChain().
1733         ecdh = new ECDHCrypt(privateKey, certs[0].getPublicKey());
1734     }
1735 
1736     /**
1737      * Retrieve the server key and certificate for the specified algorithm
1738      * from the KeyManager and set the instance variables.
1739      *
1740      * @return true if successful, false if not available or invalid
1741      */
1742     private boolean setupPrivateKeyAndChain(String algorithm) {
1743         X509ExtendedKeyManager km = sslContext.getX509KeyManager();
1744         String alias;
1745         if (conn != null) {
1746             alias = km.chooseServerAlias(algorithm, null, conn);
1747         } else {
1748             alias = km.chooseEngineServerAlias(algorithm, null, engine);
1749         }
1750         if (alias == null) {
1751             return false;
1752         }
1753         PrivateKey tempPrivateKey = km.getPrivateKey(alias);
1754         if (tempPrivateKey == null) {
1755             return false;
1756         }
1757         X509Certificate[] tempCerts = km.getCertificateChain(alias);
1758         if ((tempCerts == null) || (tempCerts.length == 0)) {
1759             return false;
1760         }
1761         String keyAlgorithm = algorithm.split("_")[0];
1762         PublicKey publicKey = tempCerts[0].getPublicKey();
1763         if ((tempPrivateKey.getAlgorithm().equals(keyAlgorithm) == false)
1764                 || (publicKey.getAlgorithm().equals(keyAlgorithm) == false)) {
1765             return false;
1766         }
1767         // For ECC certs, check whether we support the EC domain parameters.
1768         // If the client sent a SupportedEllipticCurves ClientHello extension,
1769         // check against that too.
1770         if (keyAlgorithm.equals("EC")) {
1771             if (publicKey instanceof ECPublicKey == false) {
1772                 return false;
1773             }
1774             ECParameterSpec params = ((ECPublicKey)publicKey).getParams();
1775             NamedGroup namedGroup = NamedGroup.valueOf(params);
1776             if ((namedGroup == null) ||
1777                 (!SupportedGroupsExtension.supports(namedGroup)) ||
1778                 ((requestedGroups != null) &&
1779                         !requestedGroups.contains(namedGroup.id))) {
1780                 return false;
1781             }
1782         }
1783         this.privateKey = tempPrivateKey;
1784         this.certs = tempCerts;
1785         return true;
1786     }
1787 
1788     /*
1789      * Returns premaster secret for external key exchange services.
1790      */
1791     private SecretKey clientKeyExchange(ClientKeyExchange mesg)
1792         throws IOException {
1793 
1794         if (debug != null && Debug.isOn("handshake")) {
1795             mesg.print(System.out);
1796         }
1797 
1798         // Record the principals involved in exchange
1799         session.setPeerPrincipal(mesg.getPeerPrincipal());
1800         session.setLocalPrincipal(mesg.getLocalPrincipal());
1801 
1802         return mesg.clientKeyExchange();
1803     }
1804 
1805     /*
1806      * Diffie Hellman key exchange is used when the server presented
1807      * D-H parameters in its certificate (signed using RSA or DSS/DSA),
1808      * or else the server presented no certificate but sent D-H params
1809      * in a ServerKeyExchange message.  Use of D-H is specified by the
1810      * cipher suite chosen.
1811      *
1812      * The message optionally contains the client's D-H public key (if
1813      * it wasn't not sent in a client certificate).  As always with D-H,
1814      * if a client and a server have each other's D-H public keys and
1815      * they use common algorithm parameters, they have a shared key
1816      * that's derived via the D-H calculation.  That key becomes the
1817      * pre-master secret.
1818      */
1819     private SecretKey clientKeyExchange(DHClientKeyExchange mesg)
1820             throws IOException {
1821 
1822         if (debug != null && Debug.isOn("handshake")) {
1823             mesg.print(System.out);
1824         }
1825 
1826         BigInteger publicKeyValue = mesg.getClientPublicKey();
1827 
1828         // check algorithm constraints
1829         dh.checkConstraints(algorithmConstraints, publicKeyValue);
1830 
1831         return dh.getAgreedSecret(publicKeyValue, false);
1832     }
1833 
1834     private SecretKey clientKeyExchange(ECDHClientKeyExchange mesg)
1835             throws IOException {
1836 
1837         if (debug != null && Debug.isOn("handshake")) {
1838             mesg.print(System.out);
1839         }
1840 
1841         byte[] publicPoint = mesg.getEncodedPoint();
1842 
1843         // check algorithm constraints
1844         ecdh.checkConstraints(algorithmConstraints, publicPoint);
1845 
1846         return ecdh.getAgreedSecret(publicPoint);
1847     }
1848 
1849     /*
1850      * Client wrote a message to verify the certificate it sent earlier.
1851      *
1852      * Note that this certificate isn't involved in key exchange.  Client
1853      * authentication messages are included in the checksums used to
1854      * validate the handshake (e.g. Finished messages).  Other than that,
1855      * the _exact_ identity of the client is less fundamental to protocol
1856      * security than its role in selecting keys via the pre-master secret.
1857      */
1858     private void clientCertificateVerify(CertificateVerify mesg)
1859             throws IOException {
1860 
1861         if (debug != null && Debug.isOn("handshake")) {
1862             mesg.print(System.out);
1863         }
1864 
1865         if (protocolVersion.useTLS12PlusSpec()) {
1866             SignatureAndHashAlgorithm signAlg =
1867                 mesg.getPreferableSignatureAlgorithm();
1868             if (signAlg == null) {
1869                 throw new SSLHandshakeException(
1870                         "Illegal CertificateVerify message");
1871             }
1872 
1873             String hashAlg =
1874                 SignatureAndHashAlgorithm.getHashAlgorithmName(signAlg);
1875             if (hashAlg == null || hashAlg.length() == 0) {
1876                 throw new SSLHandshakeException(
1877                         "No supported hash algorithm");
1878             }
1879         }
1880 
1881         try {
1882             PublicKey publicKey =
1883                 session.getPeerCertificates()[0].getPublicKey();
1884 
1885             boolean valid = mesg.verify(protocolVersion, handshakeHash,
1886                                         publicKey, session.getMasterSecret());
1887             if (valid == false) {
1888                 fatalSE(Alerts.alert_bad_certificate,
1889                             "certificate verify message signature error");
1890             }
1891         } catch (GeneralSecurityException e) {
1892             fatalSE(Alerts.alert_bad_certificate,
1893                 "certificate verify format error", e);
1894         }
1895 
1896         // reset the flag for clientCertificateVerify message
1897         needClientVerify = false;
1898     }
1899 
1900 
1901     /*
1902      * Client writes "finished" at the end of its handshake, after cipher
1903      * spec is changed.   We verify it and then send ours.
1904      *
1905      * When we're resuming a session, we'll have already sent our own
1906      * Finished message so just the verification is needed.
1907      */
1908     private void clientFinished(Finished mesg) throws IOException {
1909         if (debug != null && Debug.isOn("handshake")) {
1910             mesg.print(System.out);
1911         }
1912 
1913         /*
1914          * Verify if client did send the certificate when client
1915          * authentication was required, otherwise server should not proceed
1916          */
1917         if (doClientAuth == ClientAuthType.CLIENT_AUTH_REQUIRED) {
1918            // get X500Principal of the end-entity certificate for X509-based
1919            // ciphersuites, or Kerberos principal for Kerberos ciphersuites, etc
1920            session.getPeerPrincipal();
1921         }
1922 
1923         /*
1924          * Verify if client did send clientCertificateVerify message following
1925          * the client Certificate, otherwise server should not proceed
1926          */
1927         if (needClientVerify) {
1928                 fatalSE(Alerts.alert_handshake_failure,
1929                         "client did not send certificate verify message");
1930         }
1931 
1932         /*
1933          * Verify the client's message with the "before" digest of messages,
1934          * and forget about continuing to use that digest.
1935          */
1936         boolean verified = mesg.verify(handshakeHash, Finished.CLIENT,
1937             session.getMasterSecret());
1938 
1939         if (!verified) {
1940             fatalSE(Alerts.alert_handshake_failure,
1941                         "client 'finished' message doesn't verify");
1942             // NOTREACHED
1943         }
1944 
1945         /*
1946          * save client verify data for secure renegotiation
1947          */
1948         if (secureRenegotiation) {
1949             clientVerifyData = mesg.getVerifyData();
1950         }
1951 
1952         /*
1953          * OK, it verified.  If we're doing the full handshake, add that
1954          * "Finished" message to the hash of handshake messages, then send
1955          * the change_cipher_spec and Finished message.
1956          */
1957         if (!resumingSession) {
1958             sendChangeCipherAndFinish(true);
1959         } else {
1960             handshakeFinished = true;
1961         }
1962 
1963         /*
1964          * Update the session cache only after the handshake completed, else
1965          * we're open to an attack against a partially completed handshake.
1966          */
1967         session.setLastAccessedTime(System.currentTimeMillis());
1968         if (!resumingSession && session.isRejoinable()) {
1969             ((SSLSessionContextImpl)sslContext.engineGetServerSessionContext())
1970                 .put(session);
1971             if (debug != null && Debug.isOn("session")) {
1972                 System.out.println(
1973                     "%% Cached server session: " + session);
1974             }
1975         } else if (!resumingSession &&
1976                 debug != null && Debug.isOn("session")) {
1977             System.out.println(
1978                 "%% Didn't cache non-resumable server session: "
1979                 + session);
1980         }
1981     }
1982 
1983     /*
1984      * Compute finished message with the "server" digest (and then forget
1985      * about that digest, it can't be used again).
1986      */
1987     private void sendChangeCipherAndFinish(boolean finishedTag)
1988             throws IOException {
1989 
1990         // Reload if this message has been reserved.
1991         handshakeHash.reload();
1992 
1993         Finished mesg = new Finished(protocolVersion, handshakeHash,
1994             Finished.SERVER, session.getMasterSecret(), cipherSuite);
1995 
1996         /*
1997          * Send the change_cipher_spec record; then our Finished handshake
1998          * message will be the last handshake message.  Flush, and now we
1999          * are ready for application data!!
2000          */
2001         sendChangeCipherSpec(mesg, finishedTag);
2002 
2003         /*
2004          * save server verify data for secure renegotiation
2005          */
2006         if (secureRenegotiation) {
2007             serverVerifyData = mesg.getVerifyData();
2008         }
2009     }
2010 
2011 
2012     /*
2013      * Returns a HelloRequest message to kickstart renegotiations
2014      */
2015     @Override
2016     HandshakeMessage getKickstartMessage() {
2017         return new HelloRequest();
2018     }
2019 
2020 
2021     /*
2022      * Fault detected during handshake.
2023      */
2024     @Override
2025     void handshakeAlert(byte description) throws SSLProtocolException {
2026 
2027         String message = Alerts.alertDescription(description);
2028 
2029         if (debug != null && Debug.isOn("handshake")) {
2030             System.out.println("SSL -- handshake alert:  "
2031                 + message);
2032         }
2033 
2034         /*
2035          * It's ok to get a no_certificate alert from a client of which
2036          * we *requested* authentication information.
2037          * However, if we *required* it, then this is not acceptable.
2038          *
2039          * Anyone calling getPeerCertificates() on the
2040          * session will get an SSLPeerUnverifiedException.
2041          */
2042         if ((description == Alerts.alert_no_certificate) &&
2043                 (doClientAuth == ClientAuthType.CLIENT_AUTH_REQUESTED)) {
2044             return;
2045         }
2046 
2047         throw new SSLProtocolException("handshake alert: " + message);
2048     }
2049 
2050     /*
2051      * RSA key exchange is normally used.  The client encrypts a "pre-master
2052      * secret" with the server's public key, from the Certificate (or else
2053      * ServerKeyExchange) message that was sent to it by the server.  That's
2054      * decrypted using the private key before we get here.
2055      */
2056     private SecretKey clientKeyExchange(RSAClientKeyExchange mesg)
2057             throws IOException {
2058 
2059         if (debug != null && Debug.isOn("handshake")) {
2060             mesg.print(System.out);
2061         }
2062         return mesg.preMaster;
2063     }
2064 
2065     /*
2066      * Verify the certificate sent by the client. We'll only get one if we
2067      * sent a CertificateRequest to request client authentication. If we
2068      * are in TLS mode, the client may send a message with no certificates
2069      * to indicate it does not have an appropriate chain. (In SSLv3 mode,
2070      * it would send a no certificate alert).
2071      */
2072     private void clientCertificate(CertificateMsg mesg) throws IOException {
2073         if (debug != null && Debug.isOn("handshake")) {
2074             mesg.print(System.out);
2075         }
2076 
2077         X509Certificate[] peerCerts = mesg.getCertificateChain();
2078 
2079         if (peerCerts.length == 0) {
2080             /*
2081              * If the client authentication is only *REQUESTED* (e.g.
2082              * not *REQUIRED*, this is an acceptable condition.)
2083              */
2084             if (doClientAuth == ClientAuthType.CLIENT_AUTH_REQUESTED) {
2085                 return;
2086             } else {
2087                 fatalSE(Alerts.alert_bad_certificate,
2088                     "null cert chain");
2089             }
2090         }
2091 
2092         // ask the trust manager to verify the chain
2093         X509TrustManager tm = sslContext.getX509TrustManager();
2094 
2095         try {
2096             // find out the types of client authentication used
2097             PublicKey key = peerCerts[0].getPublicKey();
2098             String keyAlgorithm = key.getAlgorithm();
2099             String authType;
2100             if (keyAlgorithm.equals("RSA")) {
2101                 authType = "RSA";
2102             } else if (keyAlgorithm.equals("DSA")) {
2103                 authType = "DSA";
2104             } else if (keyAlgorithm.equals("EC")) {
2105                 authType = "EC";
2106             } else {
2107                 // unknown public key type
2108                 authType = "UNKNOWN";
2109             }
2110 
2111             if (tm instanceof X509ExtendedTrustManager) {
2112                 if (conn != null) {
2113                     ((X509ExtendedTrustManager)tm).checkClientTrusted(
2114                         peerCerts.clone(),
2115                         authType,
2116                         conn);
2117                 } else {
2118                     ((X509ExtendedTrustManager)tm).checkClientTrusted(
2119                         peerCerts.clone(),
2120                         authType,
2121                         engine);
2122                 }
2123             } else {
2124                 // Unlikely to happen, because we have wrapped the old
2125                 // X509TrustManager with the new X509ExtendedTrustManager.
2126                 throw new CertificateException(
2127                     "Improper X509TrustManager implementation");
2128             }
2129         } catch (CertificateException e) {
2130             // This will throw an exception, so include the original error.
2131             fatalSE(Alerts.alert_certificate_unknown, e);
2132         }
2133         // set the flag for clientCertificateVerify message
2134         needClientVerify = true;
2135 
2136         session.setPeerCertificates(peerCerts);
2137     }
2138 
2139     private StaplingParameters processStapling(ClientHello mesg) {
2140         StaplingParameters params = null;
2141         ExtensionType ext = null;
2142         StatusRequestType type = null;
2143         StatusRequest req = null;
2144         Map<X509Certificate, byte[]> responses;
2145 
2146         // If this feature has not been enabled, then no more processing
2147         // is necessary.  Also we will only staple if we're doing a full
2148         // handshake.
2149         if (!sslContext.isStaplingEnabled(false) || resumingSession) {
2150             return null;
2151         }
2152 
2153         // Check if the client has asserted the status_request[_v2] extension(s)
2154         CertStatusReqExtension statReqExt = (CertStatusReqExtension)
2155                     mesg.extensions.get(ExtensionType.EXT_STATUS_REQUEST);
2156         CertStatusReqListV2Extension statReqExtV2 =
2157                 (CertStatusReqListV2Extension)mesg.extensions.get(
2158                         ExtensionType.EXT_STATUS_REQUEST_V2);
2159 
2160         // Determine which type of stapling we are doing and assert the
2161         // proper extension in the server hello.
2162         // Favor status_request_v2 over status_request and ocsp_multi
2163         // over ocsp.
2164         // If multiple ocsp or ocsp_multi types exist, select the first
2165         // instance of a given type.  Also since we don't support ResponderId
2166         // selection yet, only accept a request if the ResponderId field
2167         // is empty.
2168         if (statReqExtV2 != null) {             // RFC 6961 stapling
2169             ext = ExtensionType.EXT_STATUS_REQUEST_V2;
2170             List<CertStatusReqItemV2> reqItems =
2171                     statReqExtV2.getRequestItems();
2172             int ocspIdx = -1;
2173             int ocspMultiIdx = -1;
2174             for (int pos = 0; (pos < reqItems.size() &&
2175                     (ocspIdx == -1 || ocspMultiIdx == -1)); pos++) {
2176                 CertStatusReqItemV2 item = reqItems.get(pos);
2177                 StatusRequestType curType = item.getType();
2178                 if (ocspIdx < 0 && curType == StatusRequestType.OCSP) {
2179                     OCSPStatusRequest ocspReq =
2180                             (OCSPStatusRequest)item.getRequest();
2181                     if (ocspReq.getResponderIds().isEmpty()) {
2182                         ocspIdx = pos;
2183                     }
2184                 } else if (ocspMultiIdx < 0 &&
2185                         curType == StatusRequestType.OCSP_MULTI) {
2186                     // If the type is OCSP, then the request
2187                     // is guaranteed to be OCSPStatusRequest
2188                     OCSPStatusRequest ocspReq =
2189                             (OCSPStatusRequest)item.getRequest();
2190                     if (ocspReq.getResponderIds().isEmpty()) {
2191                         ocspMultiIdx = pos;
2192                     }
2193                 }
2194             }
2195             if (ocspMultiIdx >= 0) {
2196                 type = reqItems.get(ocspMultiIdx).getType();
2197                 req = reqItems.get(ocspMultiIdx).getRequest();
2198             } else if (ocspIdx >= 0) {
2199                 type = reqItems.get(ocspIdx).getType();
2200                 req = reqItems.get(ocspIdx).getRequest();
2201             } else {
2202                 if (debug != null && Debug.isOn("handshake")) {
2203                     System.out.println("Warning: No suitable request " +
2204                             "found in the status_request_v2 extension.");
2205                 }
2206             }
2207         }
2208 
2209         // Only attempt to process a status_request extension if:
2210         // * The status_request extension is set AND
2211         // * either the status_request_v2 extension is not present OR
2212         // * none of the underlying OCSPStatusRequest structures is suitable
2213         // for stapling.
2214         // If either of the latter two bullet items is true the ext, type and
2215         // req variables should all be null.  If any are null we will try
2216         // processing an asserted status_request.
2217         if ((statReqExt != null) &&
2218                (ext == null || type == null || req == null)) {
2219             ext = ExtensionType.EXT_STATUS_REQUEST;
2220             type = statReqExt.getType();
2221             if (type == StatusRequestType.OCSP) {
2222                 // If the type is OCSP, then the request is guaranteed
2223                 // to be OCSPStatusRequest
2224                 OCSPStatusRequest ocspReq =
2225                         (OCSPStatusRequest)statReqExt.getRequest();
2226                 if (ocspReq.getResponderIds().isEmpty()) {
2227                     req = ocspReq;
2228                 } else {
2229                     if (debug != null && Debug.isOn("handshake")) {
2230                         req = null;
2231                         System.out.println("Warning: No suitable request " +
2232                                 "found in the status_request extension.");
2233                     }
2234                 }
2235             }
2236         }
2237 
2238         // If, after walking through the extensions we were unable to
2239         // find a suitable StatusRequest, then stapling is disabled.
2240         // The ext, type and req variables must have been set to continue.
2241         if (type == null || req == null || ext == null) {
2242             return null;
2243         }
2244 
2245         // Get the OCSP responses from the StatusResponseManager
2246         StatusResponseManager statRespMgr =
2247                 sslContext.getStatusResponseManager();
2248         if (statRespMgr != null) {
2249             responses = statRespMgr.get(type, req, certs, statusRespTimeout,
2250                     TimeUnit.MILLISECONDS);
2251             if (!responses.isEmpty()) {
2252                 // If this RFC 6066-style stapling (SSL cert only) then the
2253                 // response cannot be zero length
2254                 if (type == StatusRequestType.OCSP) {
2255                     byte[] respDER = responses.get(certs[0]);
2256                     if (respDER == null || respDER.length <= 0) {
2257                         return null;
2258                     }
2259                 }
2260                 params = new StaplingParameters(ext, type, req, responses);
2261             }
2262         } else {
2263             // This should not happen, but if lazy initialization of the
2264             // StatusResponseManager doesn't occur we should turn off stapling.
2265             if (debug != null && Debug.isOn("handshake")) {
2266                 System.out.println("Warning: lazy initialization " +
2267                         "of the StatusResponseManager failed.  " +
2268                         "Stapling has been disabled.");
2269             }
2270         }
2271 
2272         return params;
2273     }
2274 
2275     /**
2276      * Inner class used to hold stapling parameters needed by the handshaker
2277      * when stapling is active.
2278      */
2279     private class StaplingParameters {
2280         private final ExtensionType statusRespExt;
2281         private final StatusRequestType statReqType;
2282         private final StatusRequest statReqData;
2283         private final Map<X509Certificate, byte[]> responseMap;
2284 
2285         StaplingParameters(ExtensionType ext, StatusRequestType type,
2286                 StatusRequest req, Map<X509Certificate, byte[]> responses) {
2287             statusRespExt = ext;
2288             statReqType = type;
2289             statReqData = req;
2290             responseMap = responses;
2291         }
2292     }
2293 }