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