< prev index next >

src/java.base/share/classes/sun/security/ssl/ServerHandshakeContext.java

Print this page


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

  26 package sun.security.ssl;
  27 
  28 import java.io.IOException;
  29 import java.security.AlgorithmConstraints;
  30 import java.security.AccessController;












  31 import sun.security.util.LegacyAlgorithmConstraints;
  32 import sun.security.action.GetPropertyAction;
  33 import sun.security.action.GetLongAction;
































































  34 
  35 class ServerHandshakeContext extends HandshakeContext {
  36     // To prevent the TLS renegotiation issues, by setting system property
  37     // "jdk.tls.rejectClientInitiatedRenegotiation" to true, applications in
  38     // server side can disable all client initiated SSL renegotiations
  39     // regardless of the support of TLS protocols.
  40     //
  41     // By default, allow client initiated renegotiations.
  42     static final boolean rejectClientInitiatedRenego =
  43             Utilities.getBooleanProperty(
  44                 "jdk.tls.rejectClientInitiatedRenegotiation", false);
  45 
  46     // legacy algorithm constraints
  47     static final AlgorithmConstraints legacyAlgorithmConstraints =
  48             new LegacyAlgorithmConstraints(
  49                     LegacyAlgorithmConstraints.PROPERTY_TLS_LEGACY_ALGS,
  50                     new SSLAlgorithmDecomposer());
  51 
  52     // temporary authentication information
  53     SSLPossession interimAuthn;


















  54 
  55     StatusResponseManager.StaplingParameters stapleParams;
  56     CertificateMessage.CertificateEntry currentCertEntry;
  57     private static final long DEFAULT_STATUS_RESP_DELAY = 5000L;
  58     final long statusRespTimeout;




































  59 









  60 
  61     ServerHandshakeContext(SSLContextImpl sslContext,
  62             TransportContext conContext) throws IOException {
  63         super(sslContext, conContext);
  64         long respTimeOut = AccessController.doPrivileged(


  65                     new GetLongAction("jdk.tls.stapling.responseTimeout",
  66                         DEFAULT_STATUS_RESP_DELAY));
  67         statusRespTimeout = respTimeOut >= 0 ? respTimeOut :
  68                 DEFAULT_STATUS_RESP_DELAY;
  69         handshakeConsumers.put(
  70                 SSLHandshake.CLIENT_HELLO.id, SSLHandshake.CLIENT_HELLO);
  71     }
  72 


















  73     @Override
  74     void kickstart() throws IOException {
  75         if (!conContext.isNegotiated || kickstartMessageDelivered) {





















































































































































































































































































































































































































































































































































































































































































































































































































  76             return;
  77         }
  78 
  79         SSLHandshake.kickstart(this);
  80         kickstartMessageDelivered = true;
























  81     }
  82 }




  83 














































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































< prev index next >