author | ohair |
Tue, 25 May 2010 15:58:33 -0700 | |
changeset 5506 | 202f599c92aa |
parent 5182 | 62836694baeb |
child 6856 | 533f4ad71f88 |
permissions | -rw-r--r-- |
2 | 1 |
/* |
5506 | 2 |
* Copyright (c) 1996, 2009, Oracle and/or its affiliates. All rights reserved. |
2 | 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 |
|
5506 | 7 |
* published by the Free Software Foundation. Oracle designates this |
2 | 8 |
* particular file as subject to the "Classpath" exception as provided |
5506 | 9 |
* by Oracle in the LICENSE file that accompanied this code. |
2 | 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 |
* |
|
5506 | 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. |
|
2 | 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.MessageDigest; |
|
33 |
import java.security.NoSuchAlgorithmException; |
|
34 |
import java.security.AccessController; |
|
35 |
import java.security.AccessControlContext; |
|
36 |
import java.security.PrivilegedExceptionAction; |
|
37 |
import java.security.PrivilegedActionException; |
|
38 |
import java.security.cert.X509Certificate; |
|
39 |
||
40 |
import javax.crypto.*; |
|
41 |
import javax.crypto.spec.*; |
|
42 |
||
43 |
import javax.net.ssl.*; |
|
44 |
import sun.misc.HexDumpEncoder; |
|
45 |
||
46 |
import sun.security.internal.spec.*; |
|
47 |
import sun.security.internal.interfaces.TlsMasterSecret; |
|
48 |
||
49 |
import sun.security.ssl.HandshakeMessage.*; |
|
50 |
import sun.security.ssl.CipherSuite.*; |
|
51 |
||
52 |
/** |
|
53 |
* Handshaker ... processes handshake records from an SSL V3.0 |
|
54 |
* data stream, handling all the details of the handshake protocol. |
|
55 |
* |
|
56 |
* Note that the real protocol work is done in two subclasses, the base |
|
57 |
* class just provides the control flow and key generation framework. |
|
58 |
* |
|
59 |
* @author David Brownell |
|
60 |
*/ |
|
61 |
abstract class Handshaker { |
|
62 |
||
5182 | 63 |
// protocol version being established using this Handshaker |
2 | 64 |
ProtocolVersion protocolVersion; |
65 |
||
5182 | 66 |
// the currently active protocol version during a renegotiation |
67 |
ProtocolVersion activeProtocolVersion; |
|
68 |
||
2 | 69 |
// list of enabled protocols |
70 |
ProtocolList enabledProtocols; |
|
71 |
||
72 |
private boolean isClient; |
|
73 |
||
74 |
SSLSocketImpl conn = null; |
|
75 |
SSLEngineImpl engine = null; |
|
76 |
||
77 |
HandshakeHash handshakeHash; |
|
78 |
HandshakeInStream input; |
|
79 |
HandshakeOutStream output; |
|
80 |
int state; |
|
81 |
SSLContextImpl sslContext; |
|
82 |
RandomCookie clnt_random, svr_random; |
|
83 |
SSLSessionImpl session; |
|
84 |
||
85 |
// Temporary MD5 and SHA message digests. Must always be left |
|
86 |
// in reset state after use. |
|
87 |
private MessageDigest md5Tmp, shaTmp; |
|
88 |
||
89 |
// list of enabled CipherSuites |
|
90 |
CipherSuiteList enabledCipherSuites; |
|
91 |
||
92 |
// current CipherSuite. Never null, initially SSL_NULL_WITH_NULL_NULL |
|
93 |
CipherSuite cipherSuite; |
|
94 |
||
95 |
// current key exchange. Never null, initially K_NULL |
|
96 |
KeyExchange keyExchange; |
|
97 |
||
98 |
/* True if this session is being resumed (fast handshake) */ |
|
99 |
boolean resumingSession; |
|
100 |
||
101 |
/* True if it's OK to start a new SSL session */ |
|
102 |
boolean enableNewSession; |
|
103 |
||
104 |
// Temporary storage for the individual keys. Set by |
|
105 |
// calculateConnectionKeys() and cleared once the ciphers are |
|
106 |
// activated. |
|
107 |
private SecretKey clntWriteKey, svrWriteKey; |
|
108 |
private IvParameterSpec clntWriteIV, svrWriteIV; |
|
109 |
private SecretKey clntMacSecret, svrMacSecret; |
|
110 |
||
111 |
/* |
|
112 |
* Delegated task subsystem data structures. |
|
113 |
* |
|
114 |
* If thrown is set, we need to propagate this back immediately |
|
115 |
* on entry into processMessage(). |
|
116 |
* |
|
117 |
* Data is protected by the SSLEngine.this lock. |
|
118 |
*/ |
|
119 |
private volatile boolean taskDelegated = false; |
|
120 |
private volatile DelegatedTask delegatedTask = null; |
|
121 |
private volatile Exception thrown = null; |
|
122 |
||
123 |
// Could probably use a java.util.concurrent.atomic.AtomicReference |
|
124 |
// here instead of using this lock. Consider changing. |
|
125 |
private Object thrownLock = new Object(); |
|
126 |
||
127 |
/* Class and subclass dynamic debugging support */ |
|
128 |
static final Debug debug = Debug.getInstance("ssl"); |
|
129 |
||
5182 | 130 |
// By default, disable the unsafe legacy session renegotiation |
131 |
static final boolean renegotiable = Debug.getBooleanProperty( |
|
132 |
"sun.security.ssl.allowUnsafeRenegotiation", false); |
|
133 |
||
134 |
// need to dispose the object when it is invalidated |
|
135 |
boolean invalidated; |
|
136 |
||
2 | 137 |
Handshaker(SSLSocketImpl c, SSLContextImpl context, |
138 |
ProtocolList enabledProtocols, boolean needCertVerify, |
|
139 |
boolean isClient) { |
|
140 |
this.conn = c; |
|
141 |
init(context, enabledProtocols, needCertVerify, isClient); |
|
142 |
} |
|
143 |
||
144 |
Handshaker(SSLEngineImpl engine, SSLContextImpl context, |
|
145 |
ProtocolList enabledProtocols, boolean needCertVerify, |
|
146 |
boolean isClient) { |
|
147 |
this.engine = engine; |
|
148 |
init(context, enabledProtocols, needCertVerify, isClient); |
|
149 |
} |
|
150 |
||
151 |
private void init(SSLContextImpl context, ProtocolList enabledProtocols, |
|
152 |
boolean needCertVerify, boolean isClient) { |
|
153 |
||
154 |
this.sslContext = context; |
|
155 |
this.isClient = isClient; |
|
156 |
enableNewSession = true; |
|
5182 | 157 |
invalidated = false; |
2 | 158 |
|
159 |
setCipherSuite(CipherSuite.C_NULL); |
|
160 |
||
161 |
md5Tmp = JsseJce.getMD5(); |
|
162 |
shaTmp = JsseJce.getSHA(); |
|
163 |
||
164 |
// |
|
165 |
// We accumulate digests of the handshake messages so that |
|
166 |
// we can read/write CertificateVerify and Finished messages, |
|
167 |
// getting assurance against some particular active attacks. |
|
168 |
// |
|
169 |
handshakeHash = new HandshakeHash(needCertVerify); |
|
170 |
||
171 |
setEnabledProtocols(enabledProtocols); |
|
172 |
||
173 |
if (conn != null) { |
|
174 |
conn.getAppInputStream().r.setHandshakeHash(handshakeHash); |
|
175 |
} else { // engine != null |
|
176 |
engine.inputRecord.setHandshakeHash(handshakeHash); |
|
177 |
} |
|
178 |
||
179 |
||
180 |
// |
|
181 |
// In addition to the connection state machine, controlling |
|
182 |
// how the connection deals with the different sorts of records |
|
183 |
// that get sent (notably handshake transitions!), there's |
|
184 |
// also a handshaking state machine that controls message |
|
185 |
// sequencing. |
|
186 |
// |
|
187 |
// It's a convenient artifact of the protocol that this can, |
|
188 |
// with only a couple of minor exceptions, be driven by the |
|
189 |
// type constant for the last message seen: except for the |
|
190 |
// client's cert verify, those constants are in a convenient |
|
191 |
// order to drastically simplify state machine checking. |
|
192 |
// |
|
193 |
state = -1; |
|
194 |
} |
|
195 |
||
196 |
/* |
|
197 |
* Reroutes calls to the SSLSocket or SSLEngine (*SE). |
|
198 |
* |
|
199 |
* We could have also done it by extra classes |
|
200 |
* and letting them override, but this seemed much |
|
201 |
* less involved. |
|
202 |
*/ |
|
203 |
void fatalSE(byte b, String diagnostic) throws IOException { |
|
204 |
fatalSE(b, diagnostic, null); |
|
205 |
} |
|
206 |
||
207 |
void fatalSE(byte b, Throwable cause) throws IOException { |
|
208 |
fatalSE(b, null, cause); |
|
209 |
} |
|
210 |
||
211 |
void fatalSE(byte b, String diagnostic, Throwable cause) |
|
212 |
throws IOException { |
|
213 |
if (conn != null) { |
|
214 |
conn.fatal(b, diagnostic, cause); |
|
215 |
} else { |
|
216 |
engine.fatal(b, diagnostic, cause); |
|
217 |
} |
|
218 |
} |
|
219 |
||
220 |
void warningSE(byte b) { |
|
221 |
if (conn != null) { |
|
222 |
conn.warning(b); |
|
223 |
} else { |
|
224 |
engine.warning(b); |
|
225 |
} |
|
226 |
} |
|
227 |
||
228 |
String getHostSE() { |
|
229 |
if (conn != null) { |
|
230 |
return conn.getHost(); |
|
231 |
} else { |
|
232 |
return engine.getPeerHost(); |
|
233 |
} |
|
234 |
} |
|
235 |
||
236 |
String getHostAddressSE() { |
|
237 |
if (conn != null) { |
|
238 |
return conn.getInetAddress().getHostAddress(); |
|
239 |
} else { |
|
240 |
/* |
|
241 |
* This is for caching only, doesn't matter that's is really |
|
242 |
* a hostname. The main thing is that it doesn't do |
|
243 |
* a reverse DNS lookup, potentially slowing things down. |
|
244 |
*/ |
|
245 |
return engine.getPeerHost(); |
|
246 |
} |
|
247 |
} |
|
248 |
||
249 |
boolean isLoopbackSE() { |
|
250 |
if (conn != null) { |
|
251 |
return conn.getInetAddress().isLoopbackAddress(); |
|
252 |
} else { |
|
253 |
return false; |
|
254 |
} |
|
255 |
} |
|
256 |
||
257 |
int getPortSE() { |
|
258 |
if (conn != null) { |
|
259 |
return conn.getPort(); |
|
260 |
} else { |
|
261 |
return engine.getPeerPort(); |
|
262 |
} |
|
263 |
} |
|
264 |
||
265 |
int getLocalPortSE() { |
|
266 |
if (conn != null) { |
|
267 |
return conn.getLocalPort(); |
|
268 |
} else { |
|
269 |
return -1; |
|
270 |
} |
|
271 |
} |
|
272 |
||
273 |
String getHostnameVerificationSE() { |
|
274 |
if (conn != null) { |
|
275 |
return conn.getHostnameVerification(); |
|
276 |
} else { |
|
277 |
return engine.getHostnameVerification(); |
|
278 |
} |
|
279 |
} |
|
280 |
||
281 |
AccessControlContext getAccSE() { |
|
282 |
if (conn != null) { |
|
283 |
return conn.getAcc(); |
|
284 |
} else { |
|
285 |
return engine.getAcc(); |
|
286 |
} |
|
287 |
} |
|
288 |
||
289 |
private void setVersionSE(ProtocolVersion protocolVersion) { |
|
290 |
if (conn != null) { |
|
291 |
conn.setVersion(protocolVersion); |
|
292 |
} else { |
|
293 |
engine.setVersion(protocolVersion); |
|
294 |
} |
|
295 |
} |
|
296 |
||
297 |
/** |
|
298 |
* Set the active protocol version and propagate it to the SSLSocket |
|
299 |
* and our handshake streams. Called from ClientHandshaker |
|
300 |
* and ServerHandshaker with the negotiated protocol version. |
|
301 |
*/ |
|
302 |
void setVersion(ProtocolVersion protocolVersion) { |
|
303 |
this.protocolVersion = protocolVersion; |
|
304 |
setVersionSE(protocolVersion); |
|
305 |
output.r.setVersion(protocolVersion); |
|
306 |
} |
|
307 |
||
308 |
||
309 |
/** |
|
310 |
* Set the enabled protocols. Called from the constructor or |
|
311 |
* SSLSocketImpl.setEnabledProtocols() (if the handshake is not yet |
|
312 |
* in progress). |
|
313 |
*/ |
|
314 |
void setEnabledProtocols(ProtocolList enabledProtocols) { |
|
315 |
this.enabledProtocols = enabledProtocols; |
|
316 |
||
317 |
// temporary protocol version until the actual protocol version |
|
318 |
// is negotiated in the Hello exchange. This affects the record |
|
319 |
// version we sent with the ClientHello. Using max() as the record |
|
320 |
// version is not really correct but some implementations fail to |
|
321 |
// correctly negotiate TLS otherwise. |
|
322 |
protocolVersion = enabledProtocols.max; |
|
323 |
||
324 |
ProtocolVersion helloVersion = enabledProtocols.helloVersion; |
|
325 |
||
326 |
input = new HandshakeInStream(handshakeHash); |
|
327 |
||
328 |
if (conn != null) { |
|
329 |
output = new HandshakeOutStream(protocolVersion, helloVersion, |
|
330 |
handshakeHash, conn); |
|
331 |
conn.getAppInputStream().r.setHelloVersion(helloVersion); |
|
332 |
} else { |
|
333 |
output = new HandshakeOutStream(protocolVersion, helloVersion, |
|
334 |
handshakeHash, engine); |
|
335 |
engine.outputRecord.setHelloVersion(helloVersion); |
|
336 |
} |
|
337 |
||
338 |
} |
|
339 |
||
340 |
/** |
|
341 |
* Set cipherSuite and keyExchange to the given CipherSuite. |
|
342 |
* Does not perform any verification that this is a valid selection, |
|
343 |
* this must be done before calling this method. |
|
344 |
*/ |
|
345 |
void setCipherSuite(CipherSuite s) { |
|
346 |
this.cipherSuite = s; |
|
347 |
this.keyExchange = s.keyExchange; |
|
348 |
} |
|
349 |
||
350 |
/** |
|
351 |
* Check if the given ciphersuite is enabled and available. |
|
352 |
* (Enabled ciphersuites are always available unless the status has |
|
353 |
* changed due to change in JCE providers since it was enabled). |
|
354 |
* Does not check if the required server certificates are available. |
|
355 |
*/ |
|
356 |
boolean isEnabled(CipherSuite s) { |
|
357 |
return enabledCipherSuites.contains(s) && s.isAvailable(); |
|
358 |
} |
|
359 |
||
360 |
/** |
|
361 |
* As long as handshaking has not started, we can |
|
362 |
* change whether session creations are allowed. |
|
363 |
* |
|
364 |
* Callers should do their own checking if handshaking |
|
365 |
* has started. |
|
366 |
*/ |
|
367 |
void setEnableSessionCreation(boolean newSessions) { |
|
368 |
enableNewSession = newSessions; |
|
369 |
} |
|
370 |
||
371 |
/** |
|
372 |
* Create a new read cipher and return it to caller. |
|
373 |
*/ |
|
374 |
CipherBox newReadCipher() throws NoSuchAlgorithmException { |
|
375 |
BulkCipher cipher = cipherSuite.cipher; |
|
376 |
CipherBox box; |
|
377 |
if (isClient) { |
|
378 |
box = cipher.newCipher(protocolVersion, svrWriteKey, svrWriteIV, |
|
379 |
false); |
|
380 |
svrWriteKey = null; |
|
381 |
svrWriteIV = null; |
|
382 |
} else { |
|
383 |
box = cipher.newCipher(protocolVersion, clntWriteKey, clntWriteIV, |
|
384 |
false); |
|
385 |
clntWriteKey = null; |
|
386 |
clntWriteIV = null; |
|
387 |
} |
|
388 |
return box; |
|
389 |
} |
|
390 |
||
391 |
/** |
|
392 |
* Create a new write cipher and return it to caller. |
|
393 |
*/ |
|
394 |
CipherBox newWriteCipher() throws NoSuchAlgorithmException { |
|
395 |
BulkCipher cipher = cipherSuite.cipher; |
|
396 |
CipherBox box; |
|
397 |
if (isClient) { |
|
398 |
box = cipher.newCipher(protocolVersion, clntWriteKey, clntWriteIV, |
|
399 |
true); |
|
400 |
clntWriteKey = null; |
|
401 |
clntWriteIV = null; |
|
402 |
} else { |
|
403 |
box = cipher.newCipher(protocolVersion, svrWriteKey, svrWriteIV, |
|
404 |
true); |
|
405 |
svrWriteKey = null; |
|
406 |
svrWriteIV = null; |
|
407 |
} |
|
408 |
return box; |
|
409 |
} |
|
410 |
||
411 |
/** |
|
412 |
* Create a new read MAC and return it to caller. |
|
413 |
*/ |
|
414 |
MAC newReadMAC() throws NoSuchAlgorithmException, InvalidKeyException { |
|
415 |
MacAlg macAlg = cipherSuite.macAlg; |
|
416 |
MAC mac; |
|
417 |
if (isClient) { |
|
418 |
mac = macAlg.newMac(protocolVersion, svrMacSecret); |
|
419 |
svrMacSecret = null; |
|
420 |
} else { |
|
421 |
mac = macAlg.newMac(protocolVersion, clntMacSecret); |
|
422 |
clntMacSecret = null; |
|
423 |
} |
|
424 |
return mac; |
|
425 |
} |
|
426 |
||
427 |
/** |
|
428 |
* Create a new write MAC and return it to caller. |
|
429 |
*/ |
|
430 |
MAC newWriteMAC() throws NoSuchAlgorithmException, InvalidKeyException { |
|
431 |
MacAlg macAlg = cipherSuite.macAlg; |
|
432 |
MAC mac; |
|
433 |
if (isClient) { |
|
434 |
mac = macAlg.newMac(protocolVersion, clntMacSecret); |
|
435 |
clntMacSecret = null; |
|
436 |
} else { |
|
437 |
mac = macAlg.newMac(protocolVersion, svrMacSecret); |
|
438 |
svrMacSecret = null; |
|
439 |
} |
|
440 |
return mac; |
|
441 |
} |
|
442 |
||
443 |
/* |
|
444 |
* Returns true iff the handshake sequence is done, so that |
|
445 |
* this freshly created session can become the current one. |
|
446 |
*/ |
|
447 |
boolean isDone() { |
|
448 |
return state == HandshakeMessage.ht_finished; |
|
449 |
} |
|
450 |
||
451 |
||
452 |
/* |
|
453 |
* Returns the session which was created through this |
|
454 |
* handshake sequence ... should be called after isDone() |
|
455 |
* returns true. |
|
456 |
*/ |
|
457 |
SSLSessionImpl getSession() { |
|
458 |
return session; |
|
459 |
} |
|
460 |
||
461 |
/* |
|
462 |
* This routine is fed SSL handshake records when they become available, |
|
463 |
* and processes messages found therein. |
|
464 |
*/ |
|
465 |
void process_record(InputRecord r, boolean expectingFinished) |
|
466 |
throws IOException { |
|
467 |
||
468 |
checkThrown(); |
|
469 |
||
470 |
/* |
|
471 |
* Store the incoming handshake data, then see if we can |
|
472 |
* now process any completed handshake messages |
|
473 |
*/ |
|
474 |
input.incomingRecord(r); |
|
475 |
||
476 |
/* |
|
477 |
* We don't need to create a separate delegatable task |
|
478 |
* for finished messages. |
|
479 |
*/ |
|
480 |
if ((conn != null) || expectingFinished) { |
|
481 |
processLoop(); |
|
482 |
} else { |
|
483 |
delegateTask(new PrivilegedExceptionAction<Void>() { |
|
484 |
public Void run() throws Exception { |
|
485 |
processLoop(); |
|
486 |
return null; |
|
487 |
} |
|
488 |
}); |
|
489 |
} |
|
490 |
} |
|
491 |
||
492 |
/* |
|
493 |
* On input, we hash messages one at a time since servers may need |
|
494 |
* to access an intermediate hash to validate a CertificateVerify |
|
495 |
* message. |
|
496 |
* |
|
497 |
* Note that many handshake messages can come in one record (and often |
|
498 |
* do, to reduce network resource utilization), and one message can also |
|
499 |
* require multiple records (e.g. very large Certificate messages). |
|
500 |
*/ |
|
501 |
void processLoop() throws IOException { |
|
502 |
||
5182 | 503 |
// need to read off 4 bytes at least to get the handshake |
504 |
// message type and length. |
|
505 |
while (input.available() >= 4) { |
|
2 | 506 |
byte messageType; |
507 |
int messageLen; |
|
508 |
||
509 |
/* |
|
510 |
* See if we can read the handshake message header, and |
|
511 |
* then the entire handshake message. If not, wait till |
|
512 |
* we can read and process an entire message. |
|
513 |
*/ |
|
514 |
input.mark(4); |
|
515 |
||
516 |
messageType = (byte)input.getInt8(); |
|
517 |
messageLen = input.getInt24(); |
|
518 |
||
519 |
if (input.available() < messageLen) { |
|
520 |
input.reset(); |
|
521 |
return; |
|
522 |
} |
|
523 |
||
524 |
/* |
|
525 |
* Process the messsage. We require |
|
526 |
* that processMessage() consumes the entire message. In |
|
527 |
* lieu of explicit error checks (how?!) we assume that the |
|
528 |
* data will look like garbage on encoding/processing errors, |
|
529 |
* and that other protocol code will detect such errors. |
|
530 |
* |
|
531 |
* Note that digesting is normally deferred till after the |
|
532 |
* message has been processed, though to process at least the |
|
533 |
* client's Finished message (i.e. send the server's) we need |
|
534 |
* to acccelerate that digesting. |
|
535 |
* |
|
536 |
* Also, note that hello request messages are never hashed; |
|
537 |
* that includes the hello request header, too. |
|
538 |
*/ |
|
539 |
if (messageType == HandshakeMessage.ht_hello_request) { |
|
540 |
input.reset(); |
|
541 |
processMessage(messageType, messageLen); |
|
542 |
input.ignore(4 + messageLen); |
|
543 |
} else { |
|
544 |
input.mark(messageLen); |
|
545 |
processMessage(messageType, messageLen); |
|
546 |
input.digestNow(); |
|
547 |
} |
|
548 |
} |
|
549 |
} |
|
550 |
||
551 |
||
552 |
/** |
|
553 |
* Returns true iff the handshaker has sent any messages. |
|
554 |
* Server kickstarting is not as neat as it should be; we |
|
555 |
* need to create a new handshaker, this method lets us |
|
556 |
* know if we should. |
|
557 |
*/ |
|
558 |
boolean started() { |
|
559 |
return state >= 0; |
|
560 |
} |
|
561 |
||
562 |
||
563 |
/* |
|
564 |
* Used to kickstart the negotiation ... either writing a |
|
565 |
* ClientHello or a HelloRequest as appropriate, whichever |
|
566 |
* the subclass returns. NOP if handshaking's already started. |
|
567 |
*/ |
|
568 |
void kickstart() throws IOException { |
|
569 |
if (state >= 0) { |
|
570 |
return; |
|
571 |
} |
|
572 |
HandshakeMessage m = getKickstartMessage(); |
|
573 |
||
574 |
if (debug != null && Debug.isOn("handshake")) { |
|
575 |
m.print(System.out); |
|
576 |
} |
|
577 |
m.write(output); |
|
578 |
output.flush(); |
|
579 |
||
580 |
state = m.messageType(); |
|
581 |
} |
|
582 |
||
583 |
/** |
|
584 |
* Both client and server modes can start handshaking; but the |
|
585 |
* message they send to do so is different. |
|
586 |
*/ |
|
587 |
abstract HandshakeMessage getKickstartMessage() throws SSLException; |
|
588 |
||
589 |
/* |
|
590 |
* Client and Server side protocols are each driven though this |
|
591 |
* call, which processes a single message and drives the appropriate |
|
592 |
* side of the protocol state machine (depending on the subclass). |
|
593 |
*/ |
|
594 |
abstract void processMessage(byte messageType, int messageLen) |
|
595 |
throws IOException; |
|
596 |
||
597 |
/* |
|
598 |
* Most alerts in the protocol relate to handshaking problems. |
|
599 |
* Alerts are detected as the connection reads data. |
|
600 |
*/ |
|
601 |
abstract void handshakeAlert(byte description) throws SSLProtocolException; |
|
602 |
||
603 |
/* |
|
604 |
* Sends a change cipher spec message and updates the write side |
|
605 |
* cipher state so that future messages use the just-negotiated spec. |
|
606 |
*/ |
|
607 |
void sendChangeCipherSpec(Finished mesg, boolean lastMessage) |
|
608 |
throws IOException { |
|
609 |
||
610 |
output.flush(); // i.e. handshake data |
|
611 |
||
612 |
/* |
|
613 |
* The write cipher state is protected by the connection write lock |
|
614 |
* so we must grab it while making the change. We also |
|
615 |
* make sure no writes occur between sending the ChangeCipherSpec |
|
616 |
* message, installing the new cipher state, and sending the |
|
617 |
* Finished message. |
|
618 |
* |
|
619 |
* We already hold SSLEngine/SSLSocket "this" by virtue |
|
620 |
* of this being called from the readRecord code. |
|
621 |
*/ |
|
622 |
OutputRecord r; |
|
623 |
if (conn != null) { |
|
624 |
r = new OutputRecord(Record.ct_change_cipher_spec); |
|
625 |
} else { |
|
626 |
r = new EngineOutputRecord(Record.ct_change_cipher_spec, engine); |
|
627 |
} |
|
628 |
||
629 |
r.setVersion(protocolVersion); |
|
630 |
r.write(1); // single byte of data |
|
631 |
||
632 |
if (conn != null) { |
|
100
01ef29ca378f
6447412: Issue with socket.close() for ssl sockets when poweroff on other system
xuelei
parents:
2
diff
changeset
|
633 |
conn.writeLock.lock(); |
01ef29ca378f
6447412: Issue with socket.close() for ssl sockets when poweroff on other system
xuelei
parents:
2
diff
changeset
|
634 |
try { |
2 | 635 |
conn.writeRecord(r); |
636 |
conn.changeWriteCiphers(); |
|
637 |
if (debug != null && Debug.isOn("handshake")) { |
|
638 |
mesg.print(System.out); |
|
639 |
} |
|
640 |
mesg.write(output); |
|
641 |
output.flush(); |
|
100
01ef29ca378f
6447412: Issue with socket.close() for ssl sockets when poweroff on other system
xuelei
parents:
2
diff
changeset
|
642 |
} finally { |
01ef29ca378f
6447412: Issue with socket.close() for ssl sockets when poweroff on other system
xuelei
parents:
2
diff
changeset
|
643 |
conn.writeLock.unlock(); |
2 | 644 |
} |
645 |
} else { |
|
646 |
synchronized (engine.writeLock) { |
|
647 |
engine.writeRecord((EngineOutputRecord)r); |
|
648 |
engine.changeWriteCiphers(); |
|
649 |
if (debug != null && Debug.isOn("handshake")) { |
|
650 |
mesg.print(System.out); |
|
651 |
} |
|
652 |
mesg.write(output); |
|
653 |
||
654 |
if (lastMessage) { |
|
655 |
output.setFinishedMsg(); |
|
656 |
} |
|
657 |
output.flush(); |
|
658 |
} |
|
659 |
} |
|
660 |
} |
|
661 |
||
662 |
/* |
|
663 |
* Single access point to key calculation logic. Given the |
|
664 |
* pre-master secret and the nonces from client and server, |
|
665 |
* produce all the keying material to be used. |
|
666 |
*/ |
|
667 |
void calculateKeys(SecretKey preMasterSecret, ProtocolVersion version) { |
|
668 |
SecretKey master = calculateMasterSecret(preMasterSecret, version); |
|
669 |
session.setMasterSecret(master); |
|
670 |
calculateConnectionKeys(master); |
|
671 |
} |
|
672 |
||
673 |
||
674 |
/* |
|
675 |
* Calculate the master secret from its various components. This is |
|
676 |
* used for key exchange by all cipher suites. |
|
677 |
* |
|
678 |
* The master secret is the catenation of three MD5 hashes, each |
|
679 |
* consisting of the pre-master secret and a SHA1 hash. Those three |
|
680 |
* SHA1 hashes are of (different) constant strings, the pre-master |
|
681 |
* secret, and the nonces provided by the client and the server. |
|
682 |
*/ |
|
683 |
private SecretKey calculateMasterSecret(SecretKey preMasterSecret, |
|
684 |
ProtocolVersion requestedVersion) { |
|
685 |
TlsMasterSecretParameterSpec spec = new TlsMasterSecretParameterSpec |
|
686 |
(preMasterSecret, protocolVersion.major, protocolVersion.minor, |
|
687 |
clnt_random.random_bytes, svr_random.random_bytes); |
|
688 |
||
689 |
if (debug != null && Debug.isOn("keygen")) { |
|
690 |
HexDumpEncoder dump = new HexDumpEncoder(); |
|
691 |
||
692 |
System.out.println("SESSION KEYGEN:"); |
|
693 |
||
694 |
System.out.println("PreMaster Secret:"); |
|
695 |
printHex(dump, preMasterSecret.getEncoded()); |
|
696 |
||
697 |
// Nonces are dumped with connection keygen, no |
|
698 |
// benefit to doing it twice |
|
699 |
} |
|
700 |
||
701 |
SecretKey masterSecret; |
|
702 |
try { |
|
703 |
KeyGenerator kg = JsseJce.getKeyGenerator("SunTlsMasterSecret"); |
|
704 |
kg.init(spec); |
|
705 |
masterSecret = kg.generateKey(); |
|
706 |
} catch (GeneralSecurityException e) { |
|
707 |
// For RSA premaster secrets, do not signal a protocol error |
|
708 |
// due to the Bleichenbacher attack. See comments further down. |
|
709 |
if (!preMasterSecret.getAlgorithm().equals("TlsRsaPremasterSecret")) { |
|
710 |
throw new ProviderException(e); |
|
711 |
} |
|
712 |
if (debug != null && Debug.isOn("handshake")) { |
|
713 |
System.out.println("RSA master secret generation error:"); |
|
714 |
e.printStackTrace(System.out); |
|
715 |
System.out.println("Generating new random premaster secret"); |
|
716 |
} |
|
717 |
preMasterSecret = RSAClientKeyExchange.generateDummySecret(protocolVersion); |
|
718 |
// recursive call with new premaster secret |
|
719 |
return calculateMasterSecret(preMasterSecret, null); |
|
720 |
} |
|
721 |
||
722 |
// if no version check requested (client side handshake), |
|
723 |
// or version information is not available (not an RSA premaster secret), |
|
724 |
// return master secret immediately. |
|
725 |
if ((requestedVersion == null) || !(masterSecret instanceof TlsMasterSecret)) { |
|
726 |
return masterSecret; |
|
727 |
} |
|
728 |
TlsMasterSecret tlsKey = (TlsMasterSecret)masterSecret; |
|
729 |
int major = tlsKey.getMajorVersion(); |
|
730 |
int minor = tlsKey.getMinorVersion(); |
|
731 |
if ((major < 0) || (minor < 0)) { |
|
732 |
return masterSecret; |
|
733 |
} |
|
734 |
||
735 |
// check if the premaster secret version is ok |
|
736 |
// the specification says that it must be the maximum version supported |
|
737 |
// by the client from its ClientHello message. However, many |
|
738 |
// implementations send the negotiated version, so accept both |
|
739 |
// NOTE that we may be comparing two unsupported version numbers in |
|
740 |
// the second case, which is why we cannot use object reference |
|
741 |
// equality in this special case |
|
742 |
ProtocolVersion premasterVersion = ProtocolVersion.valueOf(major, minor); |
|
743 |
boolean versionMismatch = (premasterVersion != protocolVersion) && |
|
744 |
(premasterVersion.v != requestedVersion.v); |
|
745 |
||
746 |
||
747 |
if (versionMismatch == false) { |
|
748 |
// check passed, return key |
|
749 |
return masterSecret; |
|
750 |
} |
|
751 |
||
752 |
// Due to the Bleichenbacher attack, do not signal a protocol error. |
|
753 |
// Generate a random premaster secret and continue with the handshake, |
|
754 |
// which will fail when verifying the finished messages. |
|
755 |
// For more information, see comments in PreMasterSecret. |
|
756 |
if (debug != null && Debug.isOn("handshake")) { |
|
757 |
System.out.println("RSA PreMasterSecret version error: expected" |
|
758 |
+ protocolVersion + " or " + requestedVersion + ", decrypted: " |
|
759 |
+ premasterVersion); |
|
760 |
System.out.println("Generating new random premaster secret"); |
|
761 |
} |
|
762 |
preMasterSecret = RSAClientKeyExchange.generateDummySecret(protocolVersion); |
|
763 |
// recursive call with new premaster secret |
|
764 |
return calculateMasterSecret(preMasterSecret, null); |
|
765 |
} |
|
766 |
||
767 |
/* |
|
768 |
* Calculate the keys needed for this connection, once the session's |
|
769 |
* master secret has been calculated. Uses the master key and nonces; |
|
770 |
* the amount of keying material generated is a function of the cipher |
|
771 |
* suite that's been negotiated. |
|
772 |
* |
|
773 |
* This gets called both on the "full handshake" (where we exchanged |
|
774 |
* a premaster secret and started a new session) as well as on the |
|
775 |
* "fast handshake" (where we just resumed a pre-existing session). |
|
776 |
*/ |
|
777 |
void calculateConnectionKeys(SecretKey masterKey) { |
|
778 |
/* |
|
779 |
* For both the read and write sides of the protocol, we use the |
|
780 |
* master to generate MAC secrets and cipher keying material. Block |
|
781 |
* ciphers need initialization vectors, which we also generate. |
|
782 |
* |
|
783 |
* First we figure out how much keying material is needed. |
|
784 |
*/ |
|
785 |
int hashSize = cipherSuite.macAlg.size; |
|
786 |
boolean is_exportable = cipherSuite.exportable; |
|
787 |
BulkCipher cipher = cipherSuite.cipher; |
|
788 |
int keySize = cipher.keySize; |
|
789 |
int ivSize = cipher.ivSize; |
|
790 |
int expandedKeySize = is_exportable ? cipher.expandedKeySize : 0; |
|
791 |
||
792 |
TlsKeyMaterialParameterSpec spec = new TlsKeyMaterialParameterSpec |
|
793 |
(masterKey, protocolVersion.major, protocolVersion.minor, |
|
794 |
clnt_random.random_bytes, svr_random.random_bytes, |
|
795 |
cipher.algorithm, cipher.keySize, expandedKeySize, |
|
796 |
cipher.ivSize, hashSize); |
|
797 |
||
798 |
try { |
|
799 |
KeyGenerator kg = JsseJce.getKeyGenerator("SunTlsKeyMaterial"); |
|
800 |
kg.init(spec); |
|
801 |
TlsKeyMaterialSpec keySpec = (TlsKeyMaterialSpec)kg.generateKey(); |
|
802 |
||
803 |
clntWriteKey = keySpec.getClientCipherKey(); |
|
804 |
svrWriteKey = keySpec.getServerCipherKey(); |
|
805 |
||
806 |
clntWriteIV = keySpec.getClientIv(); |
|
807 |
svrWriteIV = keySpec.getServerIv(); |
|
808 |
||
809 |
clntMacSecret = keySpec.getClientMacKey(); |
|
810 |
svrMacSecret = keySpec.getServerMacKey(); |
|
811 |
} catch (GeneralSecurityException e) { |
|
812 |
throw new ProviderException(e); |
|
813 |
} |
|
814 |
||
815 |
// |
|
816 |
// Dump the connection keys as they're generated. |
|
817 |
// |
|
818 |
if (debug != null && Debug.isOn("keygen")) { |
|
819 |
synchronized (System.out) { |
|
820 |
HexDumpEncoder dump = new HexDumpEncoder(); |
|
821 |
||
822 |
System.out.println("CONNECTION KEYGEN:"); |
|
823 |
||
824 |
// Inputs: |
|
825 |
System.out.println("Client Nonce:"); |
|
826 |
printHex(dump, clnt_random.random_bytes); |
|
827 |
System.out.println("Server Nonce:"); |
|
828 |
printHex(dump, svr_random.random_bytes); |
|
829 |
System.out.println("Master Secret:"); |
|
830 |
printHex(dump, masterKey.getEncoded()); |
|
831 |
||
832 |
// Outputs: |
|
833 |
System.out.println("Client MAC write Secret:"); |
|
834 |
printHex(dump, clntMacSecret.getEncoded()); |
|
835 |
System.out.println("Server MAC write Secret:"); |
|
836 |
printHex(dump, svrMacSecret.getEncoded()); |
|
837 |
||
838 |
if (clntWriteKey != null) { |
|
839 |
System.out.println("Client write key:"); |
|
840 |
printHex(dump, clntWriteKey.getEncoded()); |
|
841 |
System.out.println("Server write key:"); |
|
842 |
printHex(dump, svrWriteKey.getEncoded()); |
|
843 |
} else { |
|
844 |
System.out.println("... no encryption keys used"); |
|
845 |
} |
|
846 |
||
847 |
if (clntWriteIV != null) { |
|
848 |
System.out.println("Client write IV:"); |
|
849 |
printHex(dump, clntWriteIV.getIV()); |
|
850 |
System.out.println("Server write IV:"); |
|
851 |
printHex(dump, svrWriteIV.getIV()); |
|
852 |
} else { |
|
853 |
System.out.println("... no IV used for this cipher"); |
|
854 |
} |
|
855 |
System.out.flush(); |
|
856 |
} |
|
857 |
} |
|
858 |
} |
|
859 |
||
860 |
private static void printHex(HexDumpEncoder dump, byte[] bytes) { |
|
861 |
if (bytes == null) { |
|
862 |
System.out.println("(key bytes not available)"); |
|
863 |
} else { |
|
864 |
try { |
|
865 |
dump.encodeBuffer(bytes, System.out); |
|
866 |
} catch (IOException e) { |
|
867 |
// just for debugging, ignore this |
|
868 |
} |
|
869 |
} |
|
870 |
} |
|
871 |
||
872 |
/** |
|
873 |
* Throw an SSLException with the specified message and cause. |
|
874 |
* Shorthand until a new SSLException constructor is added. |
|
875 |
* This method never returns. |
|
876 |
*/ |
|
877 |
static void throwSSLException(String msg, Throwable cause) |
|
878 |
throws SSLException { |
|
879 |
SSLException e = new SSLException(msg); |
|
880 |
e.initCause(cause); |
|
881 |
throw e; |
|
882 |
} |
|
883 |
||
884 |
||
885 |
/* |
|
886 |
* Implement a simple task delegator. |
|
887 |
* |
|
888 |
* We are currently implementing this as a single delegator, may |
|
889 |
* try for parallel tasks later. Client Authentication could |
|
890 |
* benefit from this, where ClientKeyExchange/CertificateVerify |
|
891 |
* could be carried out in parallel. |
|
892 |
*/ |
|
893 |
class DelegatedTask<E> implements Runnable { |
|
894 |
||
895 |
private PrivilegedExceptionAction<E> pea; |
|
896 |
||
897 |
DelegatedTask(PrivilegedExceptionAction<E> pea) { |
|
898 |
this.pea = pea; |
|
899 |
} |
|
900 |
||
901 |
public void run() { |
|
902 |
synchronized (engine) { |
|
903 |
try { |
|
904 |
AccessController.doPrivileged(pea, engine.getAcc()); |
|
905 |
} catch (PrivilegedActionException pae) { |
|
906 |
thrown = pae.getException(); |
|
907 |
} catch (RuntimeException rte) { |
|
908 |
thrown = rte; |
|
909 |
} |
|
910 |
delegatedTask = null; |
|
911 |
taskDelegated = false; |
|
912 |
} |
|
913 |
} |
|
914 |
} |
|
915 |
||
916 |
private <T> void delegateTask(PrivilegedExceptionAction<T> pea) { |
|
917 |
delegatedTask = new DelegatedTask<T>(pea); |
|
918 |
taskDelegated = false; |
|
919 |
thrown = null; |
|
920 |
} |
|
921 |
||
922 |
DelegatedTask getTask() { |
|
923 |
if (!taskDelegated) { |
|
924 |
taskDelegated = true; |
|
925 |
return delegatedTask; |
|
926 |
} else { |
|
927 |
return null; |
|
928 |
} |
|
929 |
} |
|
930 |
||
931 |
/* |
|
932 |
* See if there are any tasks which need to be delegated |
|
933 |
* |
|
934 |
* Locked by SSLEngine.this. |
|
935 |
*/ |
|
936 |
boolean taskOutstanding() { |
|
937 |
return (delegatedTask != null); |
|
938 |
} |
|
939 |
||
940 |
/* |
|
941 |
* The previous caller failed for some reason, report back the |
|
942 |
* Exception. We won't worry about Error's. |
|
943 |
* |
|
944 |
* Locked by SSLEngine.this. |
|
945 |
*/ |
|
946 |
void checkThrown() throws SSLException { |
|
947 |
synchronized (thrownLock) { |
|
948 |
if (thrown != null) { |
|
949 |
||
950 |
String msg = thrown.getMessage(); |
|
951 |
||
952 |
if (msg == null) { |
|
953 |
msg = "Delegated task threw Exception/Error"; |
|
954 |
} |
|
955 |
||
956 |
/* |
|
957 |
* See what the underlying type of exception is. We should |
|
958 |
* throw the same thing. Chain thrown to the new exception. |
|
959 |
*/ |
|
960 |
Exception e = thrown; |
|
961 |
thrown = null; |
|
962 |
||
963 |
if (e instanceof RuntimeException) { |
|
964 |
throw (RuntimeException) |
|
965 |
new RuntimeException(msg).initCause(e); |
|
966 |
} else if (e instanceof SSLHandshakeException) { |
|
967 |
throw (SSLHandshakeException) |
|
968 |
new SSLHandshakeException(msg).initCause(e); |
|
969 |
} else if (e instanceof SSLKeyException) { |
|
970 |
throw (SSLKeyException) |
|
971 |
new SSLKeyException(msg).initCause(e); |
|
972 |
} else if (e instanceof SSLPeerUnverifiedException) { |
|
973 |
throw (SSLPeerUnverifiedException) |
|
974 |
new SSLPeerUnverifiedException(msg).initCause(e); |
|
975 |
} else if (e instanceof SSLProtocolException) { |
|
976 |
throw (SSLProtocolException) |
|
977 |
new SSLProtocolException(msg).initCause(e); |
|
978 |
} else { |
|
979 |
/* |
|
980 |
* If it's SSLException or any other Exception, |
|
981 |
* we'll wrap it in an SSLException. |
|
982 |
*/ |
|
983 |
throw (SSLException) |
|
984 |
new SSLException(msg).initCause(e); |
|
985 |
} |
|
986 |
} |
|
987 |
} |
|
988 |
} |
|
989 |
} |