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