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