1 /*
2 * Copyright (c) 1996, 2014, 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.NoSuchAlgorithmException;
33 import java.security.AccessController;
34 import java.security.AlgorithmConstraints;
35 import java.security.AccessControlContext;
36 import java.security.PrivilegedExceptionAction;
37 import java.security.PrivilegedActionException;
38
39 import javax.crypto.*;
40 import javax.crypto.spec.*;
41
42 import javax.net.ssl.*;
43 import sun.misc.HexDumpEncoder;
44
45 import sun.security.internal.spec.*;
46 import sun.security.internal.interfaces.TlsMasterSecret;
47
48 import sun.security.ssl.HandshakeMessage.*;
49 import sun.security.ssl.CipherSuite.*;
50
51 import static sun.security.ssl.CipherSuite.PRF.*;
52 import static sun.security.ssl.CipherSuite.CipherType.*;
53
54 /**
55 * Handshaker ... processes handshake records from an SSL V3.0
56 * data stream, handling all the details of the handshake protocol.
57 *
58 * Note that the real protocol work is done in two subclasses, the base
59 * class just provides the control flow and key generation framework.
60 *
61 * @author David Brownell
62 */
63 abstract class Handshaker {
64
65 // protocol version being established using this Handshaker
66 ProtocolVersion protocolVersion;
67
68 // the currently active protocol version during a renegotiation
69 ProtocolVersion activeProtocolVersion;
70
71 // security parameters for secure renegotiation.
72 boolean secureRenegotiation;
73 byte[] clientVerifyData;
74 byte[] serverVerifyData;
75
76 // Is it an initial negotiation or a renegotiation?
77 boolean isInitialHandshake;
78
79 // List of enabled protocols
80 private ProtocolList enabledProtocols;
81
82 // List of enabled CipherSuites
83 private CipherSuiteList enabledCipherSuites;
84
85 // The endpoint identification protocol
86 String identificationProtocol;
87
88 // The cryptographic algorithm constraints
89 private AlgorithmConstraints algorithmConstraints = null;
90
91 // Local supported signature and algorithms
92 Collection<SignatureAndHashAlgorithm> localSupportedSignAlgs;
93
94 // Peer supported signature and algorithms
95 Collection<SignatureAndHashAlgorithm> peerSupportedSignAlgs;
96
97 /*
98
99 /*
100 * List of active protocols
101 *
102 * Active protocols is a subset of enabled protocols, and will
103 * contain only those protocols that have vaild cipher suites
104 * enabled.
105 */
106 private ProtocolList activeProtocols;
107
108 /*
109 * List of active cipher suites
110 *
111 * Active cipher suites is a subset of enabled cipher suites, and will
112 * contain only those cipher suites available for the active protocols.
113 */
114 private CipherSuiteList activeCipherSuites;
115
116 // The server name indication and matchers
117 List<SNIServerName> serverNames =
118 Collections.<SNIServerName>emptyList();
119 Collection<SNIMatcher> sniMatchers =
120 Collections.<SNIMatcher>emptyList();
121
122 private boolean isClient;
123 private boolean needCertVerify;
124
125 SSLSocketImpl conn = null;
126 SSLEngineImpl engine = null;
127
128 HandshakeHash handshakeHash;
129 HandshakeInStream input;
130 HandshakeOutStream output;
131 int state;
132 SSLContextImpl sslContext;
133 RandomCookie clnt_random, svr_random;
134 SSLSessionImpl session;
135
136 // current CipherSuite. Never null, initially SSL_NULL_WITH_NULL_NULL
137 CipherSuite cipherSuite;
138
139 // current key exchange. Never null, initially K_NULL
140 KeyExchange keyExchange;
141
142 /* True if this session is being resumed (fast handshake) */
143 boolean resumingSession;
144
145 /* True if it's OK to start a new SSL session */
146 boolean enableNewSession;
147
148 // Whether local cipher suites preference should be honored during
149 // handshaking?
150 //
151 // Note that in this provider, this option only applies to server side.
152 // Local cipher suites preference is always honored in client side in
153 // this provider.
154 boolean preferLocalCipherSuites = false;
155
156 // Temporary storage for the individual keys. Set by
157 // calculateConnectionKeys() and cleared once the ciphers are
158 // activated.
159 private SecretKey clntWriteKey, svrWriteKey;
160 private IvParameterSpec clntWriteIV, svrWriteIV;
161 private SecretKey clntMacSecret, svrMacSecret;
162
163 /*
164 * Delegated task subsystem data structures.
165 *
166 * If thrown is set, we need to propagate this back immediately
167 * on entry into processMessage().
168 *
169 * Data is protected by the SSLEngine.this lock.
170 */
171 private volatile boolean taskDelegated = false;
172 private volatile DelegatedTask<?> delegatedTask = null;
173 private volatile Exception thrown = null;
174
175 // Could probably use a java.util.concurrent.atomic.AtomicReference
176 // here instead of using this lock. Consider changing.
177 private Object thrownLock = new Object();
178
179 /* Class and subclass dynamic debugging support */
180 static final Debug debug = Debug.getInstance("ssl");
181
182 // By default, disable the unsafe legacy session renegotiation
183 static final boolean allowUnsafeRenegotiation = Debug.getBooleanProperty(
184 "sun.security.ssl.allowUnsafeRenegotiation", false);
185
186 // For maximum interoperability and backward compatibility, RFC 5746
187 // allows server (or client) to accept ClientHello (or ServerHello)
188 // message without the secure renegotiation_info extension or SCSV.
189 //
190 // For maximum security, RFC 5746 also allows server (or client) to
191 // reject such message with a fatal "handshake_failure" alert.
192 //
193 // By default, allow such legacy hello messages.
194 static final boolean allowLegacyHelloMessages = Debug.getBooleanProperty(
195 "sun.security.ssl.allowLegacyHelloMessages", true);
196
197 // To prevent the TLS renegotiation issues, by setting system property
198 // "jdk.tls.rejectClientInitiatedRenegotiation" to true, applications in
199 // server side can disable all client initiated SSL renegotiations
200 // regardless of the support of TLS protocols.
201 //
202 // By default, allow client initiated renegotiations.
203 static final boolean rejectClientInitiatedRenego =
204 Debug.getBooleanProperty(
205 "jdk.tls.rejectClientInitiatedRenegotiation", false);
206
207 // need to dispose the object when it is invalidated
208 boolean invalidated;
209
210 Handshaker(SSLSocketImpl c, SSLContextImpl context,
211 ProtocolList enabledProtocols, boolean needCertVerify,
212 boolean isClient, ProtocolVersion activeProtocolVersion,
213 boolean isInitialHandshake, boolean secureRenegotiation,
214 byte[] clientVerifyData, byte[] serverVerifyData) {
215 this.conn = c;
216 init(context, enabledProtocols, needCertVerify, isClient,
217 activeProtocolVersion, isInitialHandshake, secureRenegotiation,
218 clientVerifyData, serverVerifyData);
219 }
220
221 Handshaker(SSLEngineImpl engine, SSLContextImpl context,
222 ProtocolList enabledProtocols, boolean needCertVerify,
223 boolean isClient, ProtocolVersion activeProtocolVersion,
224 boolean isInitialHandshake, boolean secureRenegotiation,
225 byte[] clientVerifyData, byte[] serverVerifyData) {
226 this.engine = engine;
227 init(context, enabledProtocols, needCertVerify, isClient,
228 activeProtocolVersion, isInitialHandshake, secureRenegotiation,
229 clientVerifyData, serverVerifyData);
230 }
231
232 private void init(SSLContextImpl context, ProtocolList enabledProtocols,
233 boolean needCertVerify, boolean isClient,
234 ProtocolVersion activeProtocolVersion,
235 boolean isInitialHandshake, boolean secureRenegotiation,
236 byte[] clientVerifyData, byte[] serverVerifyData) {
237
238 if (debug != null && Debug.isOn("handshake")) {
239 System.out.println(
240 "Allow unsafe renegotiation: " + allowUnsafeRenegotiation +
241 "\nAllow legacy hello messages: " + allowLegacyHelloMessages +
242 "\nIs initial handshake: " + isInitialHandshake +
243 "\nIs secure renegotiation: " + secureRenegotiation);
244 }
245
246 this.sslContext = context;
247 this.isClient = isClient;
248 this.needCertVerify = needCertVerify;
249 this.activeProtocolVersion = activeProtocolVersion;
250 this.isInitialHandshake = isInitialHandshake;
251 this.secureRenegotiation = secureRenegotiation;
252 this.clientVerifyData = clientVerifyData;
253 this.serverVerifyData = serverVerifyData;
254 enableNewSession = true;
255 invalidated = false;
256
257 setCipherSuite(CipherSuite.C_NULL);
258 setEnabledProtocols(enabledProtocols);
259
260 if (conn != null) {
261 algorithmConstraints = new SSLAlgorithmConstraints(conn, true);
262 } else { // engine != null
263 algorithmConstraints = new SSLAlgorithmConstraints(engine, true);
264 }
265
266
267 //
268 // In addition to the connection state machine, controlling
269 // how the connection deals with the different sorts of records
270 // that get sent (notably handshake transitions!), there's
271 // also a handshaking state machine that controls message
272 // sequencing.
273 //
274 // It's a convenient artifact of the protocol that this can,
275 // with only a couple of minor exceptions, be driven by the
276 // type constant for the last message seen: except for the
277 // client's cert verify, those constants are in a convenient
278 // order to drastically simplify state machine checking.
279 //
280 state = -2; // initialized but not activated
281 }
282
283 /*
284 * Reroutes calls to the SSLSocket or SSLEngine (*SE).
285 *
286 * We could have also done it by extra classes
287 * and letting them override, but this seemed much
288 * less involved.
289 */
290 void fatalSE(byte b, String diagnostic) throws IOException {
291 fatalSE(b, diagnostic, null);
292 }
293
294 void fatalSE(byte b, Throwable cause) throws IOException {
295 fatalSE(b, null, cause);
296 }
297
298 void fatalSE(byte b, String diagnostic, Throwable cause)
299 throws IOException {
300 if (conn != null) {
301 conn.fatal(b, diagnostic, cause);
302 } else {
303 engine.fatal(b, diagnostic, cause);
304 }
305 }
306
307 void warningSE(byte b) {
308 if (conn != null) {
309 conn.warning(b);
310 } else {
311 engine.warning(b);
312 }
313 }
314
315 // ONLY used by ClientHandshaker to setup the peer host in SSLSession.
316 String getHostSE() {
317 if (conn != null) {
318 return conn.getHost();
319 } else {
320 return engine.getPeerHost();
321 }
322 }
323
324 // ONLY used by ServerHandshaker to setup the peer host in SSLSession.
325 String getHostAddressSE() {
326 if (conn != null) {
327 return conn.getInetAddress().getHostAddress();
328 } else {
329 /*
330 * This is for caching only, doesn't matter that's is really
331 * a hostname. The main thing is that it doesn't do
332 * a reverse DNS lookup, potentially slowing things down.
333 */
334 return engine.getPeerHost();
335 }
336 }
337
338 int getPortSE() {
339 if (conn != null) {
340 return conn.getPort();
341 } else {
342 return engine.getPeerPort();
343 }
344 }
345
346 int getLocalPortSE() {
347 if (conn != null) {
348 return conn.getLocalPort();
349 } else {
350 return -1;
351 }
352 }
353
354 AccessControlContext getAccSE() {
355 if (conn != null) {
356 return conn.getAcc();
357 } else {
358 return engine.getAcc();
359 }
360 }
361
362 String getEndpointIdentificationAlgorithmSE() {
363 SSLParameters paras;
364 if (conn != null) {
365 paras = conn.getSSLParameters();
366 } else {
367 paras = engine.getSSLParameters();
368 }
369
370 return paras.getEndpointIdentificationAlgorithm();
371 }
372
373 private void setVersionSE(ProtocolVersion protocolVersion) {
374 if (conn != null) {
375 conn.setVersion(protocolVersion);
376 } else {
377 engine.setVersion(protocolVersion);
378 }
379 }
380
381 /**
382 * Set the active protocol version and propagate it to the SSLSocket
383 * and our handshake streams. Called from ClientHandshaker
384 * and ServerHandshaker with the negotiated protocol version.
385 */
386 void setVersion(ProtocolVersion protocolVersion) {
387 this.protocolVersion = protocolVersion;
388 setVersionSE(protocolVersion);
389
390 output.r.setVersion(protocolVersion);
391 }
392
393 /**
394 * Set the enabled protocols. Called from the constructor or
395 * SSLSocketImpl/SSLEngineImpl.setEnabledProtocols() (if the
396 * handshake is not yet in progress).
397 */
398 void setEnabledProtocols(ProtocolList enabledProtocols) {
399 activeCipherSuites = null;
400 activeProtocols = null;
401
402 this.enabledProtocols = enabledProtocols;
403 }
404
405 /**
406 * Set the enabled cipher suites. Called from
407 * SSLSocketImpl/SSLEngineImpl.setEnabledCipherSuites() (if the
408 * handshake is not yet in progress).
409 */
410 void setEnabledCipherSuites(CipherSuiteList enabledCipherSuites) {
411 activeCipherSuites = null;
412 activeProtocols = null;
413 this.enabledCipherSuites = enabledCipherSuites;
414 }
415
416 /**
417 * Set the algorithm constraints. Called from the constructor or
418 * SSLSocketImpl/SSLEngineImpl.setAlgorithmConstraints() (if the
419 * handshake is not yet in progress).
420 */
421 void setAlgorithmConstraints(AlgorithmConstraints algorithmConstraints) {
422 activeCipherSuites = null;
423 activeProtocols = null;
424
425 this.algorithmConstraints =
426 new SSLAlgorithmConstraints(algorithmConstraints);
427 this.localSupportedSignAlgs = null;
428 }
429
430 Collection<SignatureAndHashAlgorithm> getLocalSupportedSignAlgs() {
431 if (localSupportedSignAlgs == null) {
432 localSupportedSignAlgs =
433 SignatureAndHashAlgorithm.getSupportedAlgorithms(
434 algorithmConstraints);
435 }
436
437 return localSupportedSignAlgs;
438 }
439
440 void setPeerSupportedSignAlgs(
441 Collection<SignatureAndHashAlgorithm> algorithms) {
442 peerSupportedSignAlgs =
443 new ArrayList<SignatureAndHashAlgorithm>(algorithms);
444 }
445
446 Collection<SignatureAndHashAlgorithm> getPeerSupportedSignAlgs() {
447 return peerSupportedSignAlgs;
448 }
449
450
451 /**
452 * Set the identification protocol. Called from the constructor or
453 * SSLSocketImpl/SSLEngineImpl.setIdentificationProtocol() (if the
454 * handshake is not yet in progress).
455 */
456 void setIdentificationProtocol(String protocol) {
457 this.identificationProtocol = protocol;
458 }
459
460 /**
461 * Sets the server name indication of the handshake.
462 */
463 void setSNIServerNames(List<SNIServerName> serverNames) {
464 // The serverNames parameter is unmodifiable.
465 this.serverNames = serverNames;
466 }
467
468 /**
469 * Sets the server name matchers of the handshaking.
470 */
471 void setSNIMatchers(Collection<SNIMatcher> sniMatchers) {
472 // The sniMatchers parameter is unmodifiable.
473 this.sniMatchers = sniMatchers;
474 }
475
476 /**
477 * Sets the cipher suites preference.
478 */
479 void setUseCipherSuitesOrder(boolean on) {
480 this.preferLocalCipherSuites = on;
481 }
482
483 /**
484 * Prior to handshaking, activate the handshake and initialize the version,
485 * input stream and output stream.
486 */
487 void activate(ProtocolVersion helloVersion) throws IOException {
488 if (activeProtocols == null) {
489 activeProtocols = getActiveProtocols();
490 }
491
492 if (activeProtocols.collection().isEmpty() ||
493 activeProtocols.max.v == ProtocolVersion.NONE.v) {
494 throw new SSLHandshakeException("No appropriate protocol");
495 }
496
497 if (activeCipherSuites == null) {
498 activeCipherSuites = getActiveCipherSuites();
499 }
500
501 if (activeCipherSuites.collection().isEmpty()) {
502 throw new SSLHandshakeException("No appropriate cipher suite");
503 }
504
505 // temporary protocol version until the actual protocol version
506 // is negotiated in the Hello exchange. This affects the record
507 // version we sent with the ClientHello.
508 if (!isInitialHandshake) {
509 protocolVersion = activeProtocolVersion;
510 } else {
511 protocolVersion = activeProtocols.max;
512 }
513
514 if (helloVersion == null || helloVersion.v == ProtocolVersion.NONE.v) {
515 helloVersion = activeProtocols.helloVersion;
516 }
517
518 // We accumulate digests of the handshake messages so that
519 // we can read/write CertificateVerify and Finished messages,
520 // getting assurance against some particular active attacks.
521 handshakeHash = new HandshakeHash(needCertVerify);
522
523 // Generate handshake input/output stream.
524 input = new HandshakeInStream(handshakeHash);
525 if (conn != null) {
526 output = new HandshakeOutStream(protocolVersion, helloVersion,
527 handshakeHash, conn);
528 conn.getAppInputStream().r.setHandshakeHash(handshakeHash);
529 conn.getAppInputStream().r.setHelloVersion(helloVersion);
530 conn.getAppOutputStream().r.setHelloVersion(helloVersion);
531 } else {
532 output = new HandshakeOutStream(protocolVersion, helloVersion,
533 handshakeHash, engine);
534 engine.inputRecord.setHandshakeHash(handshakeHash);
535 engine.inputRecord.setHelloVersion(helloVersion);
536 engine.outputRecord.setHelloVersion(helloVersion);
537 }
538
539 // move state to activated
540 state = -1;
541 }
542
543 /**
544 * Set cipherSuite and keyExchange to the given CipherSuite.
545 * Does not perform any verification that this is a valid selection,
546 * this must be done before calling this method.
547 */
548 void setCipherSuite(CipherSuite s) {
549 this.cipherSuite = s;
550 this.keyExchange = s.keyExchange;
551 }
552
553 /**
554 * Check if the given ciphersuite is enabled and available within the
555 * current active cipher suites.
556 *
557 * Does not check if the required server certificates are available.
558 */
559 boolean isNegotiable(CipherSuite s) {
560 if (activeCipherSuites == null) {
561 activeCipherSuites = getActiveCipherSuites();
562 }
563
564 return isNegotiable(activeCipherSuites, s);
565 }
566
567 /**
568 * Check if the given ciphersuite is enabled and available within the
569 * proposed cipher suite list.
570 *
571 * Does not check if the required server certificates are available.
572 */
573 final static boolean isNegotiable(CipherSuiteList proposed, CipherSuite s) {
574 return proposed.contains(s) && s.isNegotiable();
575 }
576
577 /**
578 * Check if the given protocol version is enabled and available.
579 */
580 boolean isNegotiable(ProtocolVersion protocolVersion) {
581 if (activeProtocols == null) {
582 activeProtocols = getActiveProtocols();
583 }
584
585 return activeProtocols.contains(protocolVersion);
586 }
587
588 /**
589 * Select a protocol version from the list. Called from
590 * ServerHandshaker to negotiate protocol version.
591 *
592 * Return the lower of the protocol version suggested in the
593 * clien hello and the highest supported by the server.
594 */
595 ProtocolVersion selectProtocolVersion(ProtocolVersion protocolVersion) {
596 if (activeProtocols == null) {
597 activeProtocols = getActiveProtocols();
598 }
599
600 return activeProtocols.selectProtocolVersion(protocolVersion);
601 }
602
603 /**
604 * Get the active cipher suites.
605 *
606 * In TLS 1.1, many weak or vulnerable cipher suites were obsoleted,
607 * such as TLS_RSA_EXPORT_WITH_RC4_40_MD5. The implementation MUST NOT
608 * negotiate these cipher suites in TLS 1.1 or later mode.
609 *
610 * Therefore, when the active protocols only include TLS 1.1 or later,
611 * the client cannot request to negotiate those obsoleted cipher
612 * suites. That is, the obsoleted suites should not be included in the
613 * client hello. So we need to create a subset of the enabled cipher
614 * suites, the active cipher suites, which does not contain obsoleted
615 * cipher suites of the minimum active protocol.
616 *
617 * Return empty list instead of null if no active cipher suites.
618 */
619 CipherSuiteList getActiveCipherSuites() {
620 if (activeCipherSuites == null) {
621 if (activeProtocols == null) {
622 activeProtocols = getActiveProtocols();
623 }
624
625 ArrayList<CipherSuite> suites = new ArrayList<>();
626 if (!(activeProtocols.collection().isEmpty()) &&
627 activeProtocols.min.v != ProtocolVersion.NONE.v) {
628 for (CipherSuite suite : enabledCipherSuites.collection()) {
629 if (suite.obsoleted > activeProtocols.min.v &&
630 suite.supported <= activeProtocols.max.v) {
631 if (algorithmConstraints.permits(
632 EnumSet.of(CryptoPrimitive.KEY_AGREEMENT),
633 suite.name, null)) {
634 suites.add(suite);
635 }
636 } else if (debug != null && Debug.isOn("verbose")) {
637 if (suite.obsoleted <= activeProtocols.min.v) {
638 System.out.println(
639 "Ignoring obsoleted cipher suite: " + suite);
640 } else {
641 System.out.println(
642 "Ignoring unsupported cipher suite: " + suite);
643 }
644 }
645 }
646 }
647 activeCipherSuites = new CipherSuiteList(suites);
648 }
649
650 return activeCipherSuites;
651 }
652
653 /*
654 * Get the active protocol versions.
655 *
656 * In TLS 1.1, many weak or vulnerable cipher suites were obsoleted,
657 * such as TLS_RSA_EXPORT_WITH_RC4_40_MD5. The implementation MUST NOT
658 * negotiate these cipher suites in TLS 1.1 or later mode.
659 *
660 * For example, if "TLS_RSA_EXPORT_WITH_RC4_40_MD5" is the
661 * only enabled cipher suite, the client cannot request TLS 1.1 or
662 * later, even though TLS 1.1 or later is enabled. We need to create a
663 * subset of the enabled protocols, called the active protocols, which
664 * contains protocols appropriate to the list of enabled Ciphersuites.
665 *
666 * Return empty list instead of null if no active protocol versions.
667 */
668 ProtocolList getActiveProtocols() {
669 if (activeProtocols == null) {
670 boolean enabledSSL20Hello = false;
671 ArrayList<ProtocolVersion> protocols = new ArrayList<>(4);
672 for (ProtocolVersion protocol : enabledProtocols.collection()) {
673 // Need not to check the SSL20Hello protocol.
674 if (protocol.v == ProtocolVersion.SSL20Hello.v) {
675 enabledSSL20Hello = true;
676 continue;
677 }
678
679 boolean found = false;
680 for (CipherSuite suite : enabledCipherSuites.collection()) {
681 if (suite.isAvailable() && suite.obsoleted > protocol.v &&
682 suite.supported <= protocol.v) {
683 if (algorithmConstraints.permits(
684 EnumSet.of(CryptoPrimitive.KEY_AGREEMENT),
685 suite.name, null)) {
686 protocols.add(protocol);
687 found = true;
688 break;
689 } else if (debug != null && Debug.isOn("verbose")) {
690 System.out.println(
691 "Ignoring disabled cipher suite: " + suite +
692 " for " + protocol);
693 }
694 } else if (debug != null && Debug.isOn("verbose")) {
695 System.out.println(
696 "Ignoring unsupported cipher suite: " + suite +
697 " for " + protocol);
698 }
699 }
700 if (!found && (debug != null) && Debug.isOn("handshake")) {
701 System.out.println(
702 "No available cipher suite for " + protocol);
703 }
704 }
705
706 if (!protocols.isEmpty() && enabledSSL20Hello) {
707 protocols.add(ProtocolVersion.SSL20Hello);
708 }
709
710 activeProtocols = new ProtocolList(protocols);
711 }
712
713 return activeProtocols;
714 }
715
716 /**
717 * As long as handshaking has not activated, we can
718 * change whether session creations are allowed.
719 *
720 * Callers should do their own checking if handshaking
721 * has activated.
722 */
723 void setEnableSessionCreation(boolean newSessions) {
724 enableNewSession = newSessions;
725 }
726
727 /**
728 * Create a new read cipher and return it to caller.
729 */
730 CipherBox newReadCipher() throws NoSuchAlgorithmException {
731 BulkCipher cipher = cipherSuite.cipher;
732 CipherBox box;
733 if (isClient) {
734 box = cipher.newCipher(protocolVersion, svrWriteKey, svrWriteIV,
735 sslContext.getSecureRandom(), false);
736 svrWriteKey = null;
737 svrWriteIV = null;
738 } else {
739 box = cipher.newCipher(protocolVersion, clntWriteKey, clntWriteIV,
740 sslContext.getSecureRandom(), false);
741 clntWriteKey = null;
742 clntWriteIV = null;
743 }
744 return box;
745 }
746
747 /**
748 * Create a new write cipher and return it to caller.
749 */
750 CipherBox newWriteCipher() throws NoSuchAlgorithmException {
751 BulkCipher cipher = cipherSuite.cipher;
752 CipherBox box;
753 if (isClient) {
754 box = cipher.newCipher(protocolVersion, clntWriteKey, clntWriteIV,
755 sslContext.getSecureRandom(), true);
756 clntWriteKey = null;
757 clntWriteIV = null;
758 } else {
759 box = cipher.newCipher(protocolVersion, svrWriteKey, svrWriteIV,
760 sslContext.getSecureRandom(), true);
761 svrWriteKey = null;
762 svrWriteIV = null;
763 }
764 return box;
765 }
766
767 /**
768 * Create a new read MAC and return it to caller.
769 */
770 Authenticator newReadAuthenticator()
771 throws NoSuchAlgorithmException, InvalidKeyException {
772
773 Authenticator authenticator = null;
774 if (cipherSuite.cipher.cipherType == AEAD_CIPHER) {
775 authenticator = new Authenticator(protocolVersion);
776 } else {
777 MacAlg macAlg = cipherSuite.macAlg;
778 if (isClient) {
779 authenticator = macAlg.newMac(protocolVersion, svrMacSecret);
780 svrMacSecret = null;
781 } else {
782 authenticator = macAlg.newMac(protocolVersion, clntMacSecret);
783 clntMacSecret = null;
784 }
785 }
786
787 return authenticator;
788 }
789
790 /**
791 * Create a new write MAC and return it to caller.
792 */
793 Authenticator newWriteAuthenticator()
794 throws NoSuchAlgorithmException, InvalidKeyException {
795
796 Authenticator authenticator = null;
797 if (cipherSuite.cipher.cipherType == AEAD_CIPHER) {
798 authenticator = new Authenticator(protocolVersion);
799 } else {
800 MacAlg macAlg = cipherSuite.macAlg;
801 if (isClient) {
802 authenticator = macAlg.newMac(protocolVersion, clntMacSecret);
803 clntMacSecret = null;
804 } else {
805 authenticator = macAlg.newMac(protocolVersion, svrMacSecret);
806 svrMacSecret = null;
807 }
808 }
809
810 return authenticator;
811 }
812
813 /*
814 * Returns true iff the handshake sequence is done, so that
815 * this freshly created session can become the current one.
816 */
817 boolean isDone() {
818 return state == HandshakeMessage.ht_finished;
819 }
820
821
822 /*
823 * Returns the session which was created through this
824 * handshake sequence ... should be called after isDone()
825 * returns true.
826 */
827 SSLSessionImpl getSession() {
828 return session;
829 }
830
831 /*
832 * Set the handshake session
833 */
834 void setHandshakeSessionSE(SSLSessionImpl handshakeSession) {
835 if (conn != null) {
836 conn.setHandshakeSession(handshakeSession);
837 } else {
838 engine.setHandshakeSession(handshakeSession);
839 }
840 }
841
842 /*
843 * Returns true if renegotiation is in use for this connection.
844 */
845 boolean isSecureRenegotiation() {
846 return secureRenegotiation;
847 }
848
849 /*
850 * Returns the verify_data from the Finished message sent by the client.
851 */
852 byte[] getClientVerifyData() {
853 return clientVerifyData;
854 }
855
856 /*
857 * Returns the verify_data from the Finished message sent by the server.
858 */
859 byte[] getServerVerifyData() {
860 return serverVerifyData;
861 }
862
863 /*
864 * This routine is fed SSL handshake records when they become available,
865 * and processes messages found therein.
866 */
867 void process_record(InputRecord r, boolean expectingFinished)
868 throws IOException {
869
870 checkThrown();
871
872 /*
873 * Store the incoming handshake data, then see if we can
874 * now process any completed handshake messages
875 */
876 input.incomingRecord(r);
877
878 /*
879 * We don't need to create a separate delegatable task
880 * for finished messages.
881 */
882 if ((conn != null) || expectingFinished) {
883 processLoop();
884 } else {
885 delegateTask(new PrivilegedExceptionAction<Void>() {
886 @Override
887 public Void run() throws Exception {
888 processLoop();
889 return null;
890 }
891 });
892 }
893 }
894
895 /*
896 * On input, we hash messages one at a time since servers may need
897 * to access an intermediate hash to validate a CertificateVerify
898 * message.
899 *
900 * Note that many handshake messages can come in one record (and often
901 * do, to reduce network resource utilization), and one message can also
902 * require multiple records (e.g. very large Certificate messages).
903 */
904 void processLoop() throws IOException {
905
906 // need to read off 4 bytes at least to get the handshake
907 // message type and length.
908 while (input.available() >= 4) {
909 byte messageType;
910 int messageLen;
911
912 /*
913 * See if we can read the handshake message header, and
914 * then the entire handshake message. If not, wait till
915 * we can read and process an entire message.
916 */
917 input.mark(4);
918
919 messageType = (byte)input.getInt8();
920 messageLen = input.getInt24();
921
922 if (input.available() < messageLen) {
923 input.reset();
924 return;
925 }
926
927 /*
928 * Process the message. We require
929 * that processMessage() consumes the entire message. In
930 * lieu of explicit error checks (how?!) we assume that the
931 * data will look like garbage on encoding/processing errors,
932 * and that other protocol code will detect such errors.
933 *
934 * Note that digesting is normally deferred till after the
935 * message has been processed, though to process at least the
936 * client's Finished message (i.e. send the server's) we need
937 * to acccelerate that digesting.
938 *
939 * Also, note that hello request messages are never hashed;
940 * that includes the hello request header, too.
941 */
942 if (messageType == HandshakeMessage.ht_hello_request) {
943 input.reset();
944 processMessage(messageType, messageLen);
945 input.ignore(4 + messageLen);
946 } else {
947 input.mark(messageLen);
948 processMessage(messageType, messageLen);
949 input.digestNow();
950 }
951 }
952 }
953
954
955 /**
956 * Returns true iff the handshaker has been activated.
957 *
958 * In activated state, the handshaker may not send any messages out.
959 */
960 boolean activated() {
961 return state >= -1;
962 }
963
964 /**
965 * Returns true iff the handshaker has sent any messages.
966 */
967 boolean started() {
968 return state >= 0; // 0: HandshakeMessage.ht_hello_request
969 // 1: HandshakeMessage.ht_client_hello
970 }
971
972
973 /*
974 * Used to kickstart the negotiation ... either writing a
975 * ClientHello or a HelloRequest as appropriate, whichever
976 * the subclass returns. NOP if handshaking's already started.
977 */
978 void kickstart() throws IOException {
979 if (state >= 0) {
980 return;
981 }
982
983 HandshakeMessage m = getKickstartMessage();
984
985 if (debug != null && Debug.isOn("handshake")) {
986 m.print(System.out);
987 }
988 m.write(output);
989 output.flush();
990
991 state = m.messageType();
992 }
993
994 /**
995 * Both client and server modes can start handshaking; but the
996 * message they send to do so is different.
997 */
998 abstract HandshakeMessage getKickstartMessage() throws SSLException;
999
1000 /*
1001 * Client and Server side protocols are each driven though this
1002 * call, which processes a single message and drives the appropriate
1003 * side of the protocol state machine (depending on the subclass).
1004 */
1005 abstract void processMessage(byte messageType, int messageLen)
1006 throws IOException;
1007
1008 /*
1009 * Most alerts in the protocol relate to handshaking problems.
1010 * Alerts are detected as the connection reads data.
1011 */
1012 abstract void handshakeAlert(byte description) throws SSLProtocolException;
1013
1014 /*
1015 * Sends a change cipher spec message and updates the write side
1016 * cipher state so that future messages use the just-negotiated spec.
1017 */
1018 void sendChangeCipherSpec(Finished mesg, boolean lastMessage)
1019 throws IOException {
1020
1021 output.flush(); // i.e. handshake data
1022
1023 /*
1024 * The write cipher state is protected by the connection write lock
1025 * so we must grab it while making the change. We also
1026 * make sure no writes occur between sending the ChangeCipherSpec
1027 * message, installing the new cipher state, and sending the
1028 * Finished message.
1029 *
1030 * We already hold SSLEngine/SSLSocket "this" by virtue
1031 * of this being called from the readRecord code.
1032 */
1033 OutputRecord r;
1034 if (conn != null) {
1035 r = new OutputRecord(Record.ct_change_cipher_spec);
1036 } else {
1037 r = new EngineOutputRecord(Record.ct_change_cipher_spec, engine);
1038 }
1039
1040 r.setVersion(protocolVersion);
1041 r.write(1); // single byte of data
1042
1043 if (conn != null) {
1044 conn.writeLock.lock();
1045 try {
1046 conn.writeRecord(r);
1047 conn.changeWriteCiphers();
1048 if (debug != null && Debug.isOn("handshake")) {
1049 mesg.print(System.out);
1050 }
1051 mesg.write(output);
1052 output.flush();
1053 } finally {
1054 conn.writeLock.unlock();
1055 }
1056 } else {
1057 synchronized (engine.writeLock) {
1058 engine.writeRecord((EngineOutputRecord)r);
1059 engine.changeWriteCiphers();
1060 if (debug != null && Debug.isOn("handshake")) {
1061 mesg.print(System.out);
1062 }
1063 mesg.write(output);
1064
1065 if (lastMessage) {
1066 output.setFinishedMsg();
1067 }
1068 output.flush();
1069 }
1070 }
1071 }
1072
1073 /*
1074 * Single access point to key calculation logic. Given the
1075 * pre-master secret and the nonces from client and server,
1076 * produce all the keying material to be used.
1077 */
1078 void calculateKeys(SecretKey preMasterSecret, ProtocolVersion version) {
1079 SecretKey master = calculateMasterSecret(preMasterSecret, version);
1080 session.setMasterSecret(master);
1081 calculateConnectionKeys(master);
1082 }
1083
1084
1085 /*
1086 * Calculate the master secret from its various components. This is
1087 * used for key exchange by all cipher suites.
1088 *
1089 * The master secret is the catenation of three MD5 hashes, each
1090 * consisting of the pre-master secret and a SHA1 hash. Those three
1091 * SHA1 hashes are of (different) constant strings, the pre-master
1092 * secret, and the nonces provided by the client and the server.
1093 */
1094 private SecretKey calculateMasterSecret(SecretKey preMasterSecret,
1095 ProtocolVersion requestedVersion) {
1096
1097 if (debug != null && Debug.isOn("keygen")) {
1098 HexDumpEncoder dump = new HexDumpEncoder();
1099
1100 System.out.println("SESSION KEYGEN:");
1101
1102 System.out.println("PreMaster Secret:");
1103 printHex(dump, preMasterSecret.getEncoded());
1104
1105 // Nonces are dumped with connection keygen, no
1106 // benefit to doing it twice
1107 }
1108
1109 // What algs/params do we need to use?
1110 String masterAlg;
1111 PRF prf;
1112
1113 if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
1114 masterAlg = "SunTls12MasterSecret";
1115 prf = cipherSuite.prfAlg;
1116 } else {
1117 masterAlg = "SunTlsMasterSecret";
1118 prf = P_NONE;
1119 }
1120
1121 String prfHashAlg = prf.getPRFHashAlg();
1122 int prfHashLength = prf.getPRFHashLength();
1123 int prfBlockSize = prf.getPRFBlockSize();
1124
1125 TlsMasterSecretParameterSpec spec = new TlsMasterSecretParameterSpec(
1126 preMasterSecret, protocolVersion.major, protocolVersion.minor,
1127 clnt_random.random_bytes, svr_random.random_bytes,
1128 prfHashAlg, prfHashLength, prfBlockSize);
1129
1130 try {
1131 KeyGenerator kg = JsseJce.getKeyGenerator(masterAlg);
1132 kg.init(spec);
1133 return kg.generateKey();
1134 } catch (InvalidAlgorithmParameterException |
1135 NoSuchAlgorithmException iae) {
1136 // unlikely to happen, otherwise, must be a provider exception
1137 //
1138 // For RSA premaster secrets, do not signal a protocol error
1139 // due to the Bleichenbacher attack. See comments further down.
1140 if (debug != null && Debug.isOn("handshake")) {
1141 System.out.println("RSA master secret generation error:");
1142 iae.printStackTrace(System.out);
1143 }
1144 throw new ProviderException(iae);
1145
1146 }
1147 }
1148
1149 /*
1150 * Calculate the keys needed for this connection, once the session's
1151 * master secret has been calculated. Uses the master key and nonces;
1152 * the amount of keying material generated is a function of the cipher
1153 * suite that's been negotiated.
1154 *
1155 * This gets called both on the "full handshake" (where we exchanged
1156 * a premaster secret and started a new session) as well as on the
1157 * "fast handshake" (where we just resumed a pre-existing session).
1158 */
1159 void calculateConnectionKeys(SecretKey masterKey) {
1160 /*
1161 * For both the read and write sides of the protocol, we use the
1162 * master to generate MAC secrets and cipher keying material. Block
1163 * ciphers need initialization vectors, which we also generate.
1164 *
1165 * First we figure out how much keying material is needed.
1166 */
1167 int hashSize = cipherSuite.macAlg.size;
1168 boolean is_exportable = cipherSuite.exportable;
1169 BulkCipher cipher = cipherSuite.cipher;
1170 int expandedKeySize = is_exportable ? cipher.expandedKeySize : 0;
1171
1172 // Which algs/params do we need to use?
1173 String keyMaterialAlg;
1174 PRF prf;
1175
1176 if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
1177 keyMaterialAlg = "SunTls12KeyMaterial";
1178 prf = cipherSuite.prfAlg;
1179 } else {
1180 keyMaterialAlg = "SunTlsKeyMaterial";
1181 prf = P_NONE;
1182 }
1183
1184 String prfHashAlg = prf.getPRFHashAlg();
1185 int prfHashLength = prf.getPRFHashLength();
1186 int prfBlockSize = prf.getPRFBlockSize();
1187
1188 // TLS v1.1 or later uses an explicit IV in CBC cipher suites to
1189 // protect against the CBC attacks. AEAD/GCM cipher suites in TLS
1190 // v1.2 or later use a fixed IV as the implicit part of the partially
1191 // implicit nonce technique described in RFC 5116.
1192 int ivSize = cipher.ivSize;
1193 if (cipher.cipherType == AEAD_CIPHER) {
1194 ivSize = cipher.fixedIvSize;
1195 } else if (protocolVersion.v >= ProtocolVersion.TLS11.v &&
1196 cipher.cipherType == BLOCK_CIPHER) {
1197 ivSize = 0;
1198 }
1199
1200 TlsKeyMaterialParameterSpec spec = new TlsKeyMaterialParameterSpec(
1201 masterKey, protocolVersion.major, protocolVersion.minor,
1202 clnt_random.random_bytes, svr_random.random_bytes,
1203 cipher.algorithm, cipher.keySize, expandedKeySize,
1204 ivSize, hashSize,
1205 prfHashAlg, prfHashLength, prfBlockSize);
1206
1207 try {
1208 KeyGenerator kg = JsseJce.getKeyGenerator(keyMaterialAlg);
1209 kg.init(spec);
1210 TlsKeyMaterialSpec keySpec = (TlsKeyMaterialSpec)kg.generateKey();
1211
1212 // Return null if cipher keys are not supposed to be generated.
1213 clntWriteKey = keySpec.getClientCipherKey();
1214 svrWriteKey = keySpec.getServerCipherKey();
1215
1216 // Return null if IVs are not supposed to be generated.
1217 clntWriteIV = keySpec.getClientIv();
1218 svrWriteIV = keySpec.getServerIv();
1219
1220 // Return null if MAC keys are not supposed to be generated.
1221 clntMacSecret = keySpec.getClientMacKey();
1222 svrMacSecret = keySpec.getServerMacKey();
1223 } catch (GeneralSecurityException e) {
1224 throw new ProviderException(e);
1225 }
1226
1227 //
1228 // Dump the connection keys as they're generated.
1229 //
1230 if (debug != null && Debug.isOn("keygen")) {
1231 synchronized (System.out) {
1232 HexDumpEncoder dump = new HexDumpEncoder();
1233
1234 System.out.println("CONNECTION KEYGEN:");
1235
1236 // Inputs:
1237 System.out.println("Client Nonce:");
1238 printHex(dump, clnt_random.random_bytes);
1239 System.out.println("Server Nonce:");
1240 printHex(dump, svr_random.random_bytes);
1241 System.out.println("Master Secret:");
1242 printHex(dump, masterKey.getEncoded());
1243
1244 // Outputs:
1245 if (clntMacSecret != null) {
1246 System.out.println("Client MAC write Secret:");
1247 printHex(dump, clntMacSecret.getEncoded());
1248 System.out.println("Server MAC write Secret:");
1249 printHex(dump, svrMacSecret.getEncoded());
1250 } else {
1251 System.out.println("... no MAC keys used for this cipher");
1252 }
1253
1254 if (clntWriteKey != null) {
1255 System.out.println("Client write key:");
1256 printHex(dump, clntWriteKey.getEncoded());
1257 System.out.println("Server write key:");
1258 printHex(dump, svrWriteKey.getEncoded());
1259 } else {
1260 System.out.println("... no encryption keys used");
1261 }
1262
1263 if (clntWriteIV != null) {
1264 System.out.println("Client write IV:");
1265 printHex(dump, clntWriteIV.getIV());
1266 System.out.println("Server write IV:");
1267 printHex(dump, svrWriteIV.getIV());
1268 } else {
1269 if (protocolVersion.v >= ProtocolVersion.TLS11.v) {
1270 System.out.println(
1271 "... no IV derived for this protocol");
1272 } else {
1273 System.out.println("... no IV used for this cipher");
1274 }
1275 }
1276 System.out.flush();
1277 }
1278 }
1279 }
1280
1281 private static void printHex(HexDumpEncoder dump, byte[] bytes) {
1282 if (bytes == null) {
1283 System.out.println("(key bytes not available)");
1284 } else {
1285 try {
1286 dump.encodeBuffer(bytes, System.out);
1287 } catch (IOException e) {
1288 // just for debugging, ignore this
1289 }
1290 }
1291 }
1292
1293 /**
1294 * Throw an SSLException with the specified message and cause.
1295 * Shorthand until a new SSLException constructor is added.
1296 * This method never returns.
1297 */
1298 static void throwSSLException(String msg, Throwable cause)
1299 throws SSLException {
1300 SSLException e = new SSLException(msg);
1301 e.initCause(cause);
1302 throw e;
1303 }
1304
1305
1306 /*
1307 * Implement a simple task delegator.
1308 *
1309 * We are currently implementing this as a single delegator, may
1310 * try for parallel tasks later. Client Authentication could
1311 * benefit from this, where ClientKeyExchange/CertificateVerify
1312 * could be carried out in parallel.
1313 */
1314 class DelegatedTask<E> implements Runnable {
1315
1316 private PrivilegedExceptionAction<E> pea;
1317
1318 DelegatedTask(PrivilegedExceptionAction<E> pea) {
1319 this.pea = pea;
1320 }
1321
1322 public void run() {
1323 synchronized (engine) {
1324 try {
1325 AccessController.doPrivileged(pea, engine.getAcc());
1326 } catch (PrivilegedActionException pae) {
1327 thrown = pae.getException();
1328 } catch (RuntimeException rte) {
1329 thrown = rte;
1330 }
1331 delegatedTask = null;
1332 taskDelegated = false;
1333 }
1334 }
1335 }
1336
1337 private <T> void delegateTask(PrivilegedExceptionAction<T> pea) {
1338 delegatedTask = new DelegatedTask<T>(pea);
1339 taskDelegated = false;
1340 thrown = null;
1341 }
1342
1343 DelegatedTask<?> getTask() {
1344 if (!taskDelegated) {
1345 taskDelegated = true;
1346 return delegatedTask;
1347 } else {
1348 return null;
1349 }
1350 }
1351
1352 /*
1353 * See if there are any tasks which need to be delegated
1354 *
1355 * Locked by SSLEngine.this.
1356 */
1357 boolean taskOutstanding() {
1358 return (delegatedTask != null);
1359 }
1360
1361 /*
1362 * The previous caller failed for some reason, report back the
1363 * Exception. We won't worry about Error's.
1364 *
1365 * Locked by SSLEngine.this.
1366 */
1367 void checkThrown() throws SSLException {
1368 synchronized (thrownLock) {
1369 if (thrown != null) {
1370
1371 String msg = thrown.getMessage();
1372
1373 if (msg == null) {
1374 msg = "Delegated task threw Exception/Error";
1375 }
1376
1377 /*
1378 * See what the underlying type of exception is. We should
1379 * throw the same thing. Chain thrown to the new exception.
1380 */
1381 Exception e = thrown;
1382 thrown = null;
1383
1384 if (e instanceof RuntimeException) {
1385 throw new RuntimeException(msg, e);
1386 } else if (e instanceof SSLHandshakeException) {
1387 throw (SSLHandshakeException)
1388 new SSLHandshakeException(msg).initCause(e);
1389 } else if (e instanceof SSLKeyException) {
1390 throw (SSLKeyException)
1391 new SSLKeyException(msg).initCause(e);
1392 } else if (e instanceof SSLPeerUnverifiedException) {
1393 throw (SSLPeerUnverifiedException)
1394 new SSLPeerUnverifiedException(msg).initCause(e);
1395 } else if (e instanceof SSLProtocolException) {
1396 throw (SSLProtocolException)
1397 new SSLProtocolException(msg).initCause(e);
1398 } else {
1399 /*
1400 * If it's SSLException or any other Exception,
1401 * we'll wrap it in an SSLException.
1402 */
1403 throw new SSLException(msg, e);
1404 }
1405 }
1406 }
1407 }
1408 }