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