2 * SSL v2 handshake functions, and functions common to SSL2 and SSL3.
4 * ***** BEGIN LICENSE BLOCK *****
5 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
7 * The contents of this file are subject to the Mozilla Public License Version
8 * 1.1 (the "License"); you may not use this file except in compliance with
9 * the License. You may obtain a copy of the License at
10 * http://www.mozilla.org/MPL/
12 * Software distributed under the License is distributed on an "AS IS" basis,
13 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
14 * for the specific language governing rights and limitations under the
17 * The Original Code is the Netscape security libraries.
19 * The Initial Developer of the Original Code is
20 * Netscape Communications Corporation.
21 * Portions created by the Initial Developer are Copyright (C) 1994-2000
22 * the Initial Developer. All Rights Reserved.
25 * Dr Vipul Gupta <vipul.gupta@sun.com>, Sun Microsystems Laboratories
27 * Alternatively, the contents of this file may be used under the terms of
28 * either the GNU General Public License Version 2 or later (the "GPL"), or
29 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
30 * in which case the provisions of the GPL or the LGPL are applicable instead
31 * of those above. If you wish to allow use of your version of this file only
32 * under the terms of either the GPL or the LGPL, and not to allow others to
33 * use your version of this file under the terms of the MPL, indicate your
34 * decision by deleting the provisions above and replace them with the notice
35 * and other provisions required by the GPL or the LGPL. If you do not delete
36 * the provisions above, a recipient may use your version of this file under
37 * the terms of any one of the MPL, the GPL or the LGPL.
39 * ***** END LICENSE BLOCK ***** */
40 /* $Id: sslcon.c,v 1.35 2007/01/03 05:30:33 nelson%bolyard.com Exp $ */
46 #include "cryptohi.h" /* for SGN_ funcs */
47 #include "keyhi.h" /* for SECKEY_ high level functions. */
55 #include "prtime.h" /* for PR_Now() */
58 static PRBool policyWasSet
;
60 /* This ordered list is indexed by (SSL_CK_xx * 3) */
61 /* Second and third bytes are MSB and LSB of master key length. */
62 static const PRUint8 allCipherSuites
[] = {
64 SSL_CK_RC4_128_WITH_MD5
, 0x00, 0x80,
65 SSL_CK_RC4_128_EXPORT40_WITH_MD5
, 0x00, 0x80,
66 SSL_CK_RC2_128_CBC_WITH_MD5
, 0x00, 0x80,
67 SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5
, 0x00, 0x80,
68 SSL_CK_IDEA_128_CBC_WITH_MD5
, 0x00, 0x80,
69 SSL_CK_DES_64_CBC_WITH_MD5
, 0x00, 0x40,
70 SSL_CK_DES_192_EDE3_CBC_WITH_MD5
, 0x00, 0xC0,
74 #define ssl2_NUM_SUITES_IMPLEMENTED 6
76 /* This list is sent back to the client when the client-hello message
77 * contains no overlapping ciphers, so the client can report what ciphers
78 * are supported by the server. Unlike allCipherSuites (above), this list
79 * is sorted by descending preference, not by cipherSuite number.
81 static const PRUint8 implementedCipherSuites
[ssl2_NUM_SUITES_IMPLEMENTED
* 3] = {
82 SSL_CK_RC4_128_WITH_MD5
, 0x00, 0x80,
83 SSL_CK_RC2_128_CBC_WITH_MD5
, 0x00, 0x80,
84 SSL_CK_DES_192_EDE3_CBC_WITH_MD5
, 0x00, 0xC0,
85 SSL_CK_DES_64_CBC_WITH_MD5
, 0x00, 0x40,
86 SSL_CK_RC4_128_EXPORT40_WITH_MD5
, 0x00, 0x80,
87 SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5
, 0x00, 0x80
90 typedef struct ssl2SpecsStr
{
91 PRUint8 nkm
; /* do this many hashes to generate key material. */
92 PRUint8 nkd
; /* size of readKey and writeKey in bytes. */
95 CK_MECHANISM_TYPE mechanism
;
96 PRUint8 keyLen
; /* cipher symkey size in bytes. */
97 PRUint8 pubLen
; /* publicly reveal this many bytes of key. */
98 PRUint8 ivLen
; /* length of IV data at *ca. */
101 static const ssl2Specs ssl_Specs
[] = {
104 /* SSL_CK_RC4_128_WITH_MD5 */
105 { 2, 16, 1, 0, CKM_RC4
, 16, 0, 0, },
106 /* SSL_CK_RC4_128_EXPORT40_WITH_MD5 */
107 { 2, 16, 1, 0, CKM_RC4
, 16, 11, 0, },
108 /* SSL_CK_RC2_128_CBC_WITH_MD5 */
109 { 2, 16, 8, 3, CKM_RC2_CBC
, 16, 0, 8, },
110 /* SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5 */
111 { 2, 16, 8, 3, CKM_RC2_CBC
, 16, 11, 8, },
112 /* SSL_CK_IDEA_128_CBC_WITH_MD5 */
114 /* SSL_CK_DES_64_CBC_WITH_MD5 */
115 { 1, 8, 8, 3, CKM_DES_CBC
, 8, 0, 8, },
116 /* SSL_CK_DES_192_EDE3_CBC_WITH_MD5 */
117 { 3, 24, 8, 3, CKM_DES3_CBC
, 24, 0, 8, },
120 #define SET_ERROR_CODE /* reminder */
121 #define TEST_FOR_FAILURE /* reminder */
124 ** Put a string tag in the library so that we can examine an executable
125 ** and see what kind of security it supports.
127 const char *ssl_version
= "SECURITY_VERSION:"
138 const char * const ssl_cipherName
[] = {
148 "unknown", /* was fortezza, NO LONGER USED */
152 /* bit-masks, showing which SSLv2 suites are allowed.
153 * lsb corresponds to first cipher suite in allCipherSuites[].
155 static PRUint16 allowedByPolicy
; /* all off by default */
156 static PRUint16 maybeAllowedByPolicy
; /* all off by default */
157 static PRUint16 chosenPreference
= 0xff; /* all on by default */
159 /* bit values for the above two bit masks */
160 #define SSL_CB_RC4_128_WITH_MD5 (1 << SSL_CK_RC4_128_WITH_MD5)
161 #define SSL_CB_RC4_128_EXPORT40_WITH_MD5 (1 << SSL_CK_RC4_128_EXPORT40_WITH_MD5)
162 #define SSL_CB_RC2_128_CBC_WITH_MD5 (1 << SSL_CK_RC2_128_CBC_WITH_MD5)
163 #define SSL_CB_RC2_128_CBC_EXPORT40_WITH_MD5 (1 << SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5)
164 #define SSL_CB_IDEA_128_CBC_WITH_MD5 (1 << SSL_CK_IDEA_128_CBC_WITH_MD5)
165 #define SSL_CB_DES_64_CBC_WITH_MD5 (1 << SSL_CK_DES_64_CBC_WITH_MD5)
166 #define SSL_CB_DES_192_EDE3_CBC_WITH_MD5 (1 << SSL_CK_DES_192_EDE3_CBC_WITH_MD5)
167 #define SSL_CB_IMPLEMENTED \
168 (SSL_CB_RC4_128_WITH_MD5 | \
169 SSL_CB_RC4_128_EXPORT40_WITH_MD5 | \
170 SSL_CB_RC2_128_CBC_WITH_MD5 | \
171 SSL_CB_RC2_128_CBC_EXPORT40_WITH_MD5 | \
172 SSL_CB_DES_64_CBC_WITH_MD5 | \
173 SSL_CB_DES_192_EDE3_CBC_WITH_MD5)
176 /* Construct a socket's list of cipher specs from the global default values.
179 ssl2_ConstructCipherSpecs(sslSocket
*ss
)
182 unsigned int allowed
;
189 PORT_Assert( ss
->opt
.noLocks
|| ssl_Have1stHandshakeLock(ss
) );
192 PORT_Assert(ss
!= 0);
193 allowed
= !ss
->opt
.enableSSL2
? 0 :
194 (ss
->allowedByPolicy
& ss
->chosenPreference
& SSL_CB_IMPLEMENTED
);
201 /* Call ssl3_config_match_init() once here,
202 * instead of inside ssl3_ConstructV2CipherSpecsHack(),
203 * because the latter gets called twice below,
204 * and then again in ssl2_BeginClientHandshake().
206 ssl3_config_match_init(ss
);
208 /* ask SSL3 how many cipher suites it has. */
209 rv
= ssl3_ConstructV2CipherSpecsHack(ss
, NULL
, &ssl3_count
);
214 /* Allocate memory to hold cipher specs */
216 cs
= (PRUint8
*) PORT_Alloc(count
* 3);
218 PORT_SetError(SSL_ERROR_SSL_DISABLED
);
222 if (ss
->cipherSpecs
!= NULL
) {
223 PORT_Free(ss
->cipherSpecs
);
225 ss
->cipherSpecs
= cs
;
226 ss
->sizeCipherSpecs
= count
* 3;
228 /* fill in cipher specs for SSL2 cipher suites */
229 allowed
= !ss
->opt
.enableSSL2
? 0 :
230 (ss
->allowedByPolicy
& ss
->chosenPreference
& SSL_CB_IMPLEMENTED
);
231 for (i
= 0; i
< ssl2_NUM_SUITES_IMPLEMENTED
* 3; i
+= 3) {
232 const PRUint8
* hs
= implementedCipherSuites
+ i
;
233 int ok
= allowed
& (1U << hs
[0]);
242 /* now have SSL3 add its suites onto the end */
243 rv
= ssl3_ConstructV2CipherSpecsHack(ss
, cs
, &final_count
);
245 /* adjust for any difference between first pass and second pass */
246 ss
->sizeCipherSpecs
-= (ssl3_count
- final_count
) * 3;
251 /* This function is called immediately after ssl2_ConstructCipherSpecs()
252 ** at the beginning of a handshake. It detects cases where a protocol
253 ** (e.g. SSL2 or SSL3) is logically enabled, but all its cipher suites
254 ** for that protocol have been disabled. If such cases, it clears the
255 ** enable bit for the protocol. If no protocols remain enabled, or
256 ** if no cipher suites are found, it sets the error code and returns
257 ** SECFailure, otherwise it returns SECSuccess.
260 ssl2_CheckConfigSanity(sslSocket
*ss
)
262 unsigned int allowed
;
263 int ssl3CipherCount
= 0;
266 /* count the SSL2 and SSL3 enabled ciphers.
267 * if either is zero, clear the socket's enable for that protocol.
269 if (!ss
->cipherSpecs
)
272 allowed
= ss
->allowedByPolicy
& ss
->chosenPreference
;
274 ss
->opt
.enableSSL2
= PR_FALSE
; /* not really enabled if no ciphers */
276 /* ssl3_config_match_init was called in ssl2_ConstructCipherSpecs(). */
277 /* Ask how many ssl3 CipherSuites were enabled. */
278 rv
= ssl3_ConstructV2CipherSpecsHack(ss
, NULL
, &ssl3CipherCount
);
279 if (rv
!= SECSuccess
|| ssl3CipherCount
<= 0) {
280 ss
->opt
.enableSSL3
= PR_FALSE
; /* not really enabled if no ciphers */
281 ss
->opt
.enableTLS
= PR_FALSE
;
284 if (!ss
->opt
.enableSSL2
&& !ss
->opt
.enableSSL3
&& !ss
->opt
.enableTLS
) {
285 SSL_DBG(("%d: SSL[%d]: Can't handshake! both v2 and v3 disabled.",
286 SSL_GETPID(), ss
->fd
));
288 PORT_SetError(SSL_ERROR_SSL_DISABLED
);
295 * Since this is a global (not per-socket) setting, we cannot use the
296 * HandshakeLock to protect this. Probably want a global lock.
299 ssl2_SetPolicy(PRInt32 which
, PRInt32 policy
)
302 SECStatus rv
= SECSuccess
;
305 bitMask
= 1 << which
;
307 if (!(bitMask
& SSL_CB_IMPLEMENTED
)) {
308 PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE
);
312 if (policy
== SSL_ALLOWED
) {
313 allowedByPolicy
|= bitMask
;
314 maybeAllowedByPolicy
|= bitMask
;
315 } else if (policy
== SSL_RESTRICTED
) {
316 allowedByPolicy
&= ~bitMask
;
317 maybeAllowedByPolicy
|= bitMask
;
319 allowedByPolicy
&= ~bitMask
;
320 maybeAllowedByPolicy
&= ~bitMask
;
322 allowedByPolicy
&= SSL_CB_IMPLEMENTED
;
323 maybeAllowedByPolicy
&= SSL_CB_IMPLEMENTED
;
325 policyWasSet
= PR_TRUE
;
330 ssl2_GetPolicy(PRInt32 which
, PRInt32
*oPolicy
)
336 bitMask
= 1 << which
;
338 /* Caller assures oPolicy is not null. */
339 if (!(bitMask
& SSL_CB_IMPLEMENTED
)) {
340 PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE
);
341 *oPolicy
= SSL_NOT_ALLOWED
;
345 if (maybeAllowedByPolicy
& bitMask
) {
346 policy
= (allowedByPolicy
& bitMask
) ? SSL_ALLOWED
: SSL_RESTRICTED
;
348 policy
= SSL_NOT_ALLOWED
;
356 * Since this is a global (not per-socket) setting, we cannot use the
357 * HandshakeLock to protect this. Probably want a global lock.
358 * Called from SSL_CipherPrefSetDefault in sslsock.c
359 * These changes have no effect on any sslSockets already created.
362 ssl2_CipherPrefSetDefault(PRInt32 which
, PRBool enabled
)
367 bitMask
= 1 << which
;
369 if (!(bitMask
& SSL_CB_IMPLEMENTED
)) {
370 PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE
);
375 chosenPreference
|= bitMask
;
377 chosenPreference
&= ~bitMask
;
378 chosenPreference
&= SSL_CB_IMPLEMENTED
;
384 ssl2_CipherPrefGetDefault(PRInt32 which
, PRBool
*enabled
)
386 PRBool rv
= PR_FALSE
;
390 bitMask
= 1 << which
;
392 if (!(bitMask
& SSL_CB_IMPLEMENTED
)) {
393 PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE
);
398 rv
= (PRBool
)((chosenPreference
& bitMask
) != 0);
404 ssl2_CipherPrefSet(sslSocket
*ss
, PRInt32 which
, PRBool enabled
)
409 bitMask
= 1 << which
;
411 if (!(bitMask
& SSL_CB_IMPLEMENTED
)) {
412 PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE
);
417 ss
->chosenPreference
|= bitMask
;
419 ss
->chosenPreference
&= ~bitMask
;
420 ss
->chosenPreference
&= SSL_CB_IMPLEMENTED
;
426 ssl2_CipherPrefGet(sslSocket
*ss
, PRInt32 which
, PRBool
*enabled
)
428 PRBool rv
= PR_FALSE
;
432 bitMask
= 1 << which
;
434 if (!(bitMask
& SSL_CB_IMPLEMENTED
)) {
435 PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE
);
440 rv
= (PRBool
)((ss
->chosenPreference
& bitMask
) != 0);
446 /* copy global default policy into socket. */
448 ssl2_InitSocketPolicy(sslSocket
*ss
)
450 ss
->allowedByPolicy
= allowedByPolicy
;
451 ss
->maybeAllowedByPolicy
= maybeAllowedByPolicy
;
452 ss
->chosenPreference
= chosenPreference
;
456 /************************************************************************/
458 /* Called from ssl2_CreateSessionCypher(), which already holds handshake lock.
461 ssl2_CreateMAC(sslSecurityInfo
*sec
, SECItem
*readKey
, SECItem
*writeKey
,
464 switch (cipherChoice
) {
466 case SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5
:
467 case SSL_CK_RC2_128_CBC_WITH_MD5
:
468 case SSL_CK_RC4_128_EXPORT40_WITH_MD5
:
469 case SSL_CK_RC4_128_WITH_MD5
:
470 case SSL_CK_DES_64_CBC_WITH_MD5
:
471 case SSL_CK_DES_192_EDE3_CBC_WITH_MD5
:
472 sec
->hash
= HASH_GetHashObject(HASH_AlgMD5
);
473 SECITEM_CopyItem(0, &sec
->sendSecret
, writeKey
);
474 SECITEM_CopyItem(0, &sec
->rcvSecret
, readKey
);
478 PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP
);
481 sec
->hashcx
= (*sec
->hash
->create
)();
482 if (sec
->hashcx
== NULL
)
487 /************************************************************************
488 * All the Send functions below must acquire and release the socket's
492 /* Called from all the Send* functions below. */
494 ssl2_GetSendBuffer(sslSocket
*ss
, unsigned int len
)
496 SECStatus rv
= SECSuccess
;
498 PORT_Assert(ss
->opt
.noLocks
|| ssl_HaveXmitBufLock(ss
));
503 if (len
> ss
->sec
.ci
.sendBuf
.space
) {
504 rv
= sslBuffer_Grow(&ss
->sec
.ci
.sendBuf
, len
);
505 if (rv
!= SECSuccess
) {
506 SSL_DBG(("%d: SSL[%d]: ssl2_GetSendBuffer failed, tried to get %d bytes",
507 SSL_GETPID(), ss
->fd
, len
));
515 * ssl2_ClientSetupSessionCypher() <- ssl2_HandleServerHelloMessage()
516 * ssl2_HandleRequestCertificate() <- ssl2_HandleMessage() <-
518 * ssl2_HandleMessage() <- ssl_Do1stHandshake()
519 * ssl2_HandleServerHelloMessage() <- ssl_Do1stHandshake()
520 after ssl2_BeginClientHandshake()
521 * ssl2_RestartHandshakeAfterCertReq() <- Called from certdlgs.c in nav.
522 * ssl2_HandleClientHelloMessage() <- ssl_Do1stHandshake()
523 after ssl2_BeginServerHandshake()
525 * Acquires and releases the socket's xmitBufLock.
528 ssl2_SendErrorMessage(sslSocket
*ss
, int error
)
531 PRUint8 msg
[SSL_HL_ERROR_HBYTES
];
533 PORT_Assert( ss
->opt
.noLocks
|| ssl_Have1stHandshakeLock(ss
) );
535 msg
[0] = SSL_MT_ERROR
;
539 ssl_GetXmitBufLock(ss
); /***************************************/
541 SSL_TRC(3, ("%d: SSL[%d]: sending error %d", SSL_GETPID(), ss
->fd
, error
));
543 ss
->handshakeBegun
= 1;
544 rv
= (*ss
->sec
.send
)(ss
, msg
, sizeof(msg
), 0);
548 ssl_ReleaseXmitBufLock(ss
); /***************************************/
552 /* Called from ssl2_TryToFinish().
553 * Acquires and releases the socket's xmitBufLock.
556 ssl2_SendClientFinishedMessage(sslSocket
*ss
)
558 SECStatus rv
= SECSuccess
;
560 PRUint8 msg
[1 + SSL_CONNECTIONID_BYTES
];
562 PORT_Assert( ss
->opt
.noLocks
|| ssl_Have1stHandshakeLock(ss
) );
564 ssl_GetXmitBufLock(ss
); /***************************************/
566 if (ss
->sec
.ci
.sentFinished
== 0) {
567 ss
->sec
.ci
.sentFinished
= 1;
569 SSL_TRC(3, ("%d: SSL[%d]: sending client-finished",
570 SSL_GETPID(), ss
->fd
));
572 msg
[0] = SSL_MT_CLIENT_FINISHED
;
573 PORT_Memcpy(msg
+1, ss
->sec
.ci
.connectionID
,
574 sizeof(ss
->sec
.ci
.connectionID
));
576 DUMP_MSG(29, (ss
, msg
, 1 + sizeof(ss
->sec
.ci
.connectionID
)));
577 sent
= (*ss
->sec
.send
)(ss
, msg
, 1 + sizeof(ss
->sec
.ci
.connectionID
), 0);
578 rv
= (sent
>= 0) ? SECSuccess
: (SECStatus
)sent
;
580 ssl_ReleaseXmitBufLock(ss
); /***************************************/
585 * ssl2_HandleClientSessionKeyMessage() <- ssl2_HandleClientHelloMessage()
586 * ssl2_HandleClientHelloMessage() <- ssl_Do1stHandshake()
587 after ssl2_BeginServerHandshake()
588 * Acquires and releases the socket's xmitBufLock.
591 ssl2_SendServerVerifyMessage(sslSocket
*ss
)
598 PORT_Assert( ss
->opt
.noLocks
|| ssl_Have1stHandshakeLock(ss
) );
600 ssl_GetXmitBufLock(ss
); /***************************************/
602 sendLen
= 1 + SSL_CHALLENGE_BYTES
;
603 rv
= ssl2_GetSendBuffer(ss
, sendLen
);
604 if (rv
!= SECSuccess
) {
608 msg
= ss
->sec
.ci
.sendBuf
.buf
;
609 msg
[0] = SSL_MT_SERVER_VERIFY
;
610 PORT_Memcpy(msg
+1, ss
->sec
.ci
.clientChallenge
, SSL_CHALLENGE_BYTES
);
612 DUMP_MSG(29, (ss
, msg
, sendLen
));
613 sent
= (*ss
->sec
.send
)(ss
, msg
, sendLen
, 0);
615 rv
= (sent
>= 0) ? SECSuccess
: (SECStatus
)sent
;
618 ssl_ReleaseXmitBufLock(ss
); /***************************************/
622 /* Called from ssl2_TryToFinish().
623 * Acquires and releases the socket's xmitBufLock.
626 ssl2_SendServerFinishedMessage(sslSocket
*ss
)
631 SECStatus rv
= SECSuccess
;
633 PORT_Assert( ss
->opt
.noLocks
|| ssl_Have1stHandshakeLock(ss
) );
635 ssl_GetXmitBufLock(ss
); /***************************************/
637 if (ss
->sec
.ci
.sentFinished
== 0) {
638 ss
->sec
.ci
.sentFinished
= 1;
639 PORT_Assert(ss
->sec
.ci
.sid
!= 0);
640 sid
= ss
->sec
.ci
.sid
;
642 SSL_TRC(3, ("%d: SSL[%d]: sending server-finished",
643 SSL_GETPID(), ss
->fd
));
645 sendLen
= 1 + sizeof(sid
->u
.ssl2
.sessionID
);
646 rv
= ssl2_GetSendBuffer(ss
, sendLen
);
647 if (rv
!= SECSuccess
) {
651 msg
= ss
->sec
.ci
.sendBuf
.buf
;
652 msg
[0] = SSL_MT_SERVER_FINISHED
;
653 PORT_Memcpy(msg
+1, sid
->u
.ssl2
.sessionID
,
654 sizeof(sid
->u
.ssl2
.sessionID
));
656 DUMP_MSG(29, (ss
, msg
, sendLen
));
657 sent
= (*ss
->sec
.send
)(ss
, msg
, sendLen
, 0);
660 /* If send failed, it is now a bogus session-id */
661 (*ss
->sec
.uncache
)(sid
);
662 rv
= (SECStatus
)sent
;
663 } else if (!ss
->opt
.noCache
) {
664 /* Put the sid in session-id cache, (may already be there) */
665 (*ss
->sec
.cache
)(sid
);
672 ssl_ReleaseXmitBufLock(ss
); /***************************************/
676 /* Called from ssl2_ClientSetupSessionCypher() <-
677 * ssl2_HandleServerHelloMessage()
678 * after ssl2_BeginClientHandshake()
679 * Acquires and releases the socket's xmitBufLock.
682 ssl2_SendSessionKeyMessage(sslSocket
*ss
, int cipher
, int keySize
,
683 PRUint8
*ca
, int caLen
,
684 PRUint8
*ck
, int ckLen
,
685 PRUint8
*ek
, int ekLen
)
692 PORT_Assert( ss
->opt
.noLocks
|| ssl_Have1stHandshakeLock(ss
) );
694 ssl_GetXmitBufLock(ss
); /***************************************/
696 sendLen
= SSL_HL_CLIENT_MASTER_KEY_HBYTES
+ ckLen
+ ekLen
+ caLen
;
697 rv
= ssl2_GetSendBuffer(ss
, sendLen
);
698 if (rv
!= SECSuccess
)
701 SSL_TRC(3, ("%d: SSL[%d]: sending client-session-key",
702 SSL_GETPID(), ss
->fd
));
704 msg
= ss
->sec
.ci
.sendBuf
.buf
;
705 msg
[0] = SSL_MT_CLIENT_MASTER_KEY
;
707 msg
[2] = MSB(keySize
);
708 msg
[3] = LSB(keySize
);
715 PORT_Memcpy(msg
+SSL_HL_CLIENT_MASTER_KEY_HBYTES
, ck
, ckLen
);
716 PORT_Memcpy(msg
+SSL_HL_CLIENT_MASTER_KEY_HBYTES
+ckLen
, ek
, ekLen
);
717 PORT_Memcpy(msg
+SSL_HL_CLIENT_MASTER_KEY_HBYTES
+ckLen
+ekLen
, ca
, caLen
);
719 DUMP_MSG(29, (ss
, msg
, sendLen
));
720 sent
= (*ss
->sec
.send
)(ss
, msg
, sendLen
, 0);
721 rv
= (sent
>= 0) ? SECSuccess
: (SECStatus
)sent
;
723 ssl_ReleaseXmitBufLock(ss
); /***************************************/
727 /* Called from ssl2_TriggerNextMessage() <- ssl2_HandleMessage()
728 * Acquires and releases the socket's xmitBufLock.
731 ssl2_SendCertificateRequestMessage(sslSocket
*ss
)
738 PORT_Assert( ss
->opt
.noLocks
|| ssl_Have1stHandshakeLock(ss
) );
740 ssl_GetXmitBufLock(ss
); /***************************************/
742 sendLen
= SSL_HL_REQUEST_CERTIFICATE_HBYTES
+ SSL_CHALLENGE_BYTES
;
743 rv
= ssl2_GetSendBuffer(ss
, sendLen
);
744 if (rv
!= SECSuccess
)
747 SSL_TRC(3, ("%d: SSL[%d]: sending certificate request",
748 SSL_GETPID(), ss
->fd
));
750 /* Generate random challenge for client to encrypt */
751 PK11_GenerateRandom(ss
->sec
.ci
.serverChallenge
, SSL_CHALLENGE_BYTES
);
753 msg
= ss
->sec
.ci
.sendBuf
.buf
;
754 msg
[0] = SSL_MT_REQUEST_CERTIFICATE
;
755 msg
[1] = SSL_AT_MD5_WITH_RSA_ENCRYPTION
;
756 PORT_Memcpy(msg
+ SSL_HL_REQUEST_CERTIFICATE_HBYTES
,
757 ss
->sec
.ci
.serverChallenge
, SSL_CHALLENGE_BYTES
);
759 DUMP_MSG(29, (ss
, msg
, sendLen
));
760 sent
= (*ss
->sec
.send
)(ss
, msg
, sendLen
, 0);
761 rv
= (sent
>= 0) ? SECSuccess
: (SECStatus
)sent
;
763 ssl_ReleaseXmitBufLock(ss
); /***************************************/
767 /* Called from ssl2_HandleRequestCertificate() <- ssl2_HandleMessage()
768 * ssl2_RestartHandshakeAfterCertReq() <- (application)
769 * Acquires and releases the socket's xmitBufLock.
772 ssl2_SendCertificateResponseMessage(sslSocket
*ss
, SECItem
*cert
,
778 PORT_Assert( ss
->opt
.noLocks
|| ssl_Have1stHandshakeLock(ss
) );
780 ssl_GetXmitBufLock(ss
); /***************************************/
782 sendLen
= SSL_HL_CLIENT_CERTIFICATE_HBYTES
+ encCode
->len
+ cert
->len
;
783 rv
= ssl2_GetSendBuffer(ss
, sendLen
);
787 SSL_TRC(3, ("%d: SSL[%d]: sending certificate response",
788 SSL_GETPID(), ss
->fd
));
790 msg
= ss
->sec
.ci
.sendBuf
.buf
;
791 msg
[0] = SSL_MT_CLIENT_CERTIFICATE
;
792 msg
[1] = SSL_CT_X509_CERTIFICATE
;
793 msg
[2] = MSB(cert
->len
);
794 msg
[3] = LSB(cert
->len
);
795 msg
[4] = MSB(encCode
->len
);
796 msg
[5] = LSB(encCode
->len
);
797 PORT_Memcpy(msg
+ SSL_HL_CLIENT_CERTIFICATE_HBYTES
, cert
->data
, cert
->len
);
798 PORT_Memcpy(msg
+ SSL_HL_CLIENT_CERTIFICATE_HBYTES
+ cert
->len
,
799 encCode
->data
, encCode
->len
);
801 DUMP_MSG(29, (ss
, msg
, sendLen
));
802 rv
= (*ss
->sec
.send
)(ss
, msg
, sendLen
, 0);
807 ssl_ReleaseXmitBufLock(ss
); /***************************************/
811 /********************************************************************
812 ** Send functions above this line must aquire & release the socket's
814 ** All the ssl2_Send functions below this line are called vis ss->sec.send
815 ** and require that the caller hold the xmitBufLock.
819 ** Called from ssl2_SendStream, ssl2_SendBlock, but not from ssl2_SendClear.
822 ssl2_CalcMAC(PRUint8
* result
,
823 sslSecurityInfo
* sec
,
824 const PRUint8
* data
,
825 unsigned int dataLen
,
826 unsigned int paddingLen
)
828 const PRUint8
* secret
= sec
->sendSecret
.data
;
829 unsigned int secretLen
= sec
->sendSecret
.len
;
830 unsigned long sequenceNumber
= sec
->sendSequence
;
833 PRUint8 padding
[32];/* XXX max blocksize? */
835 if (!sec
->hash
|| !sec
->hash
->length
)
840 /* Reset hash function */
841 (*sec
->hash
->begin
)(sec
->hashcx
);
843 /* Feed hash the data */
844 (*sec
->hash
->update
)(sec
->hashcx
, secret
, secretLen
);
845 (*sec
->hash
->update
)(sec
->hashcx
, data
, dataLen
);
846 PORT_Memset(padding
, paddingLen
, paddingLen
);
847 (*sec
->hash
->update
)(sec
->hashcx
, padding
, paddingLen
);
849 seq
[0] = (PRUint8
) (sequenceNumber
>> 24);
850 seq
[1] = (PRUint8
) (sequenceNumber
>> 16);
851 seq
[2] = (PRUint8
) (sequenceNumber
>> 8);
852 seq
[3] = (PRUint8
) (sequenceNumber
);
854 PRINT_BUF(60, (0, "calc-mac secret:", secret
, secretLen
));
855 PRINT_BUF(60, (0, "calc-mac data:", data
, dataLen
));
856 PRINT_BUF(60, (0, "calc-mac padding:", padding
, paddingLen
));
857 PRINT_BUF(60, (0, "calc-mac seq:", seq
, 4));
859 (*sec
->hash
->update
)(sec
->hashcx
, seq
, 4);
862 (*sec
->hash
->end
)(sec
->hashcx
, result
, &nout
, sec
->hash
->length
);
868 ** Maximum transmission amounts. These are tiny bit smaller than they
869 ** need to be (they account for the MAC length plus some padding),
870 ** assuming the MAC is 16 bytes long and the padding is a max of 7 bytes
871 ** long. This gives an additional 9 bytes of slop to work within.
873 #define MAX_STREAM_CYPHER_LEN 0x7fe0
874 #define MAX_BLOCK_CYPHER_LEN 0x3fe0
877 ** Send some data in the clear.
878 ** Package up data with the length header and send it.
880 ** Return count of bytes succesfully written, or negative number (failure).
883 ssl2_SendClear(sslSocket
*ss
, const PRUint8
*in
, PRInt32 len
, PRInt32 flags
)
890 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveXmitBufLock(ss
) );
892 SSL_TRC(10, ("%d: SSL[%d]: sending %d bytes in the clear",
893 SSL_GETPID(), ss
->fd
, len
));
894 PRINT_BUF(50, (ss
, "clear data:", (PRUint8
*) in
, len
));
897 amount
= PR_MIN( len
, MAX_STREAM_CYPHER_LEN
);
898 if (amount
+ 2 > ss
->sec
.writeBuf
.space
) {
899 rv
= sslBuffer_Grow(&ss
->sec
.writeBuf
, amount
+ 2);
900 if (rv
!= SECSuccess
) {
905 out
= ss
->sec
.writeBuf
.buf
;
908 ** Construct message.
910 out
[0] = 0x80 | MSB(amount
);
911 out
[1] = LSB(amount
);
912 PORT_Memcpy(&out
[2], in
, amount
);
914 /* Now send the data */
915 rv
= ssl_DefSend(ss
, out
, amount
+ 2, flags
& ~ssl_SEND_FLAG_MASK
);
917 if (PORT_GetError() == PR_WOULD_BLOCK_ERROR
) {
920 /* Return short write if some data already went out... */
927 if ((unsigned)rv
< (amount
+ 2)) {
928 /* Short write. Save the data and return. */
929 if (ssl_SaveWriteData(ss
, out
+ rv
, amount
+ 2 - rv
)
934 ss
->sec
.sendSequence
++;
939 ss
->sec
.sendSequence
++;
949 ** Send some data, when using a stream cipher. Stream ciphers have a
950 ** block size of 1. Package up the data with the length header
954 ssl2_SendStream(sslSocket
*ss
, const PRUint8
*in
, PRInt32 len
, PRInt32 flags
)
965 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveXmitBufLock(ss
) );
967 SSL_TRC(10, ("%d: SSL[%d]: sending %d bytes using stream cipher",
968 SSL_GETPID(), ss
->fd
, len
));
969 PRINT_BUF(50, (ss
, "clear data:", (PRUint8
*) in
, len
));
972 ssl_GetSpecReadLock(ss
); /*************************************/
974 macLen
= ss
->sec
.hash
->length
;
975 amount
= PR_MIN( len
, MAX_STREAM_CYPHER_LEN
);
976 buflen
= amount
+ 2 + macLen
;
977 if (buflen
> ss
->sec
.writeBuf
.space
) {
978 rv
= sslBuffer_Grow(&ss
->sec
.writeBuf
, buflen
);
979 if (rv
!= SECSuccess
) {
983 out
= ss
->sec
.writeBuf
.buf
;
984 nout
= amount
+ macLen
;
985 out
[0] = 0x80 | MSB(nout
);
989 rv
= ssl2_CalcMAC(out
+2, /* put MAC here */
991 in
, amount
, /* input addr & length */
993 if (rv
!= SECSuccess
)
997 rv
= (*ss
->sec
.enc
)(ss
->sec
.writecx
, out
+2, &nout
, macLen
, out
+2, macLen
);
1000 /* Encrypt data from caller */
1001 rv
= (*ss
->sec
.enc
)(ss
->sec
.writecx
, out
+2+macLen
, &nout
, amount
, in
, amount
);
1004 ssl_ReleaseSpecReadLock(ss
); /*************************************/
1006 PRINT_BUF(50, (ss
, "encrypted data:", out
, buflen
));
1008 rv
= ssl_DefSend(ss
, out
, buflen
, flags
& ~ssl_SEND_FLAG_MASK
);
1010 if (PORT_GetError() == PR_WOULD_BLOCK_ERROR
) {
1011 SSL_TRC(50, ("%d: SSL[%d]: send stream would block, "
1012 "saving data", SSL_GETPID(), ss
->fd
));
1015 SSL_TRC(10, ("%d: SSL[%d]: send stream error %d",
1016 SSL_GETPID(), ss
->fd
, PORT_GetError()));
1017 /* Return short write if some data already went out... */
1024 if ((unsigned)rv
< buflen
) {
1025 /* Short write. Save the data and return. */
1026 if (ssl_SaveWriteData(ss
, out
+ rv
, buflen
- rv
) == SECFailure
) {
1030 ss
->sec
.sendSequence
++;
1035 ss
->sec
.sendSequence
++;
1045 ssl_ReleaseSpecReadLock(ss
);
1050 ** Send some data, when using a block cipher. Package up the data with
1051 ** the length header and send it.
1053 /* XXX assumes blocksize is > 7 */
1055 ssl2_SendBlock(sslSocket
*ss
, const PRUint8
*in
, PRInt32 len
, PRInt32 flags
)
1057 PRUint8
* out
; /* begining of output buffer. */
1058 PRUint8
* op
; /* next output byte goes here. */
1059 int rv
; /* value from funcs we called. */
1060 int count
= 0; /* this function's return value. */
1062 unsigned int hlen
; /* output record hdr len, 2 or 3 */
1063 unsigned int macLen
; /* MAC is this many bytes long. */
1064 int amount
; /* of plaintext to go in record. */
1065 unsigned int padding
; /* add this many padding byte. */
1066 int nout
; /* ciphertext size after header. */
1067 int buflen
; /* size of generated record. */
1069 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveXmitBufLock(ss
) );
1071 SSL_TRC(10, ("%d: SSL[%d]: sending %d bytes using block cipher",
1072 SSL_GETPID(), ss
->fd
, len
));
1073 PRINT_BUF(50, (ss
, "clear data:", in
, len
));
1076 ssl_GetSpecReadLock(ss
); /*************************************/
1078 macLen
= ss
->sec
.hash
->length
;
1079 /* Figure out how much to send, including mac and padding */
1080 amount
= PR_MIN( len
, MAX_BLOCK_CYPHER_LEN
);
1081 nout
= amount
+ macLen
;
1082 padding
= nout
& (ss
->sec
.blockSize
- 1);
1085 padding
= ss
->sec
.blockSize
- padding
;
1090 buflen
= hlen
+ nout
;
1091 if (buflen
> ss
->sec
.writeBuf
.space
) {
1092 rv
= sslBuffer_Grow(&ss
->sec
.writeBuf
, buflen
);
1093 if (rv
!= SECSuccess
) {
1097 out
= ss
->sec
.writeBuf
.buf
;
1099 /* Construct header */
1106 *op
++ = 0x80 | MSB(nout
);
1111 rv
= ssl2_CalcMAC(op
, /* MAC goes here. */
1113 in
, amount
, /* intput addr, len */
1115 if (rv
!= SECSuccess
)
1119 /* Copy in the input data */
1120 /* XXX could eliminate the copy by folding it into the encryption */
1121 PORT_Memcpy(op
, in
, amount
);
1124 PORT_Memset(op
, padding
, padding
);
1128 /* Encrypt result */
1129 rv
= (*ss
->sec
.enc
)(ss
->sec
.writecx
, out
+hlen
, &nout
, buflen
-hlen
,
1130 out
+hlen
, op
- (out
+ hlen
));
1134 ssl_ReleaseSpecReadLock(ss
); /*************************************/
1136 PRINT_BUF(50, (ss
, "final xmit data:", out
, op
- out
));
1138 rv
= ssl_DefSend(ss
, out
, op
- out
, flags
& ~ssl_SEND_FLAG_MASK
);
1140 if (PORT_GetError() == PR_WOULD_BLOCK_ERROR
) {
1143 SSL_TRC(10, ("%d: SSL[%d]: send block error %d",
1144 SSL_GETPID(), ss
->fd
, PORT_GetError()));
1145 /* Return short write if some data already went out... */
1152 if (rv
< (op
- out
)) {
1153 /* Short write. Save the data and return. */
1154 if (ssl_SaveWriteData(ss
, out
+ rv
, op
- out
- rv
) == SECFailure
) {
1158 ss
->sec
.sendSequence
++;
1163 ss
->sec
.sendSequence
++;
1173 ssl_ReleaseSpecReadLock(ss
);
1178 ** Called from: ssl2_HandleServerHelloMessage,
1179 ** ssl2_HandleClientSessionKeyMessage,
1180 ** ssl2_RestartHandshakeAfterServerCert,
1181 ** ssl2_HandleClientHelloMessage,
1185 ssl2_UseEncryptedSendFunc(sslSocket
*ss
)
1187 ssl_GetXmitBufLock(ss
);
1188 PORT_Assert(ss
->sec
.hashcx
!= 0);
1190 ss
->gs
.encrypted
= 1;
1191 ss
->sec
.send
= (ss
->sec
.blockSize
> 1) ? ssl2_SendBlock
: ssl2_SendStream
;
1192 ssl_ReleaseXmitBufLock(ss
);
1195 /* Called while initializing socket in ssl_CreateSecurityInfo().
1196 ** This function allows us to keep the name of ssl2_SendClear static.
1199 ssl2_UseClearSendFunc(sslSocket
*ss
)
1201 ss
->sec
.send
= ssl2_SendClear
;
1204 /************************************************************************
1205 ** END of Send functions. *
1206 *************************************************************************/
1208 /***********************************************************************
1209 * For SSL3, this gathers in and handles records/messages until either
1210 * the handshake is complete or application data is available.
1212 * For SSL2, this gathers in only the next SSLV2 record.
1214 * Called from ssl_Do1stHandshake() via function pointer ss->handshake.
1215 * Caller must hold handshake lock.
1216 * This function acquires and releases the RecvBufLock.
1218 * returns SECSuccess for success.
1219 * returns SECWouldBlock when that value is returned by ssl2_GatherRecord() or
1220 * ssl3_GatherCompleteHandshake().
1221 * returns SECFailure on all other errors.
1223 * The gather functions called by ssl_GatherRecord1stHandshake are expected
1224 * to return values interpreted as follows:
1225 * 1 : the function completed without error.
1226 * 0 : the function read EOF.
1227 * -1 : read error, or PR_WOULD_BLOCK_ERROR, or handleRecord error.
1228 * -2 : the function wants ssl_GatherRecord1stHandshake to be called again
1229 * immediately, by ssl_Do1stHandshake.
1231 * This code is similar to, and easily confused with, DoRecv() in sslsecur.c
1233 * This function is called from ssl_Do1stHandshake().
1234 * The following functions put ssl_GatherRecord1stHandshake into ss->handshake:
1235 * ssl2_HandleMessage
1236 * ssl2_HandleVerifyMessage
1237 * ssl2_HandleServerHelloMessage
1238 * ssl2_BeginClientHandshake
1239 * ssl2_HandleClientSessionKeyMessage
1240 * ssl2_RestartHandshakeAfterCertReq
1241 * ssl3_RestartHandshakeAfterCertReq
1242 * ssl2_RestartHandshakeAfterServerCert
1243 * ssl3_RestartHandshakeAfterServerCert
1244 * ssl2_HandleClientHelloMessage
1245 * ssl2_BeginServerHandshake
1248 ssl_GatherRecord1stHandshake(sslSocket
*ss
)
1252 PORT_Assert( ss
->opt
.noLocks
|| ssl_Have1stHandshakeLock(ss
) );
1254 ssl_GetRecvBufLock(ss
);
1256 if (ss
->version
>= SSL_LIBRARY_VERSION_3_0
) {
1257 /* Wait for handshake to complete, or application data to arrive. */
1258 rv
= ssl3_GatherCompleteHandshake(ss
, 0);
1260 /* See if we have a complete record */
1261 rv
= ssl2_GatherRecord(ss
, 0);
1263 SSL_TRC(10, ("%d: SSL[%d]: handshake gathering, rv=%d",
1264 SSL_GETPID(), ss
->fd
, rv
));
1266 ssl_ReleaseRecvBufLock(ss
);
1269 if (rv
== SECWouldBlock
) {
1270 /* Progress is blocked waiting for callback completion. */
1271 SSL_TRC(10, ("%d: SSL[%d]: handshake blocked (need %d)",
1272 SSL_GETPID(), ss
->fd
, ss
->gs
.remainder
));
1273 return SECWouldBlock
;
1277 PORT_SetError(PR_END_OF_FILE_ERROR
);
1279 return SECFailure
; /* rv is < 0 here. */
1282 SSL_TRC(10, ("%d: SSL[%d]: got handshake record of %d bytes",
1283 SSL_GETPID(), ss
->fd
, ss
->gs
.recordLen
));
1285 ss
->handshake
= 0; /* makes ssl_Do1stHandshake call ss->nextHandshake.*/
1289 /************************************************************************/
1291 /* Called from ssl2_ServerSetupSessionCypher()
1292 * ssl2_ClientSetupSessionCypher()
1295 ssl2_FillInSID(sslSessionID
* sid
,
1303 SSLSignType authAlgorithm
,
1304 PRUint32 authKeyBits
,
1306 PRUint32 keaKeyBits
)
1308 PORT_Assert(sid
->references
== 1);
1309 PORT_Assert(sid
->cached
== never_cached
);
1310 PORT_Assert(sid
->u
.ssl2
.masterKey
.data
== 0);
1311 PORT_Assert(sid
->u
.ssl2
.cipherArg
.data
== 0);
1313 sid
->version
= SSL_LIBRARY_VERSION_2
;
1315 sid
->u
.ssl2
.cipherType
= cipher
;
1316 sid
->u
.ssl2
.masterKey
.data
= (PRUint8
*) PORT_Alloc(keyLen
);
1317 if (!sid
->u
.ssl2
.masterKey
.data
) {
1320 PORT_Memcpy(sid
->u
.ssl2
.masterKey
.data
, keyData
, keyLen
);
1321 sid
->u
.ssl2
.masterKey
.len
= keyLen
;
1322 sid
->u
.ssl2
.keyBits
= keyBits
;
1323 sid
->u
.ssl2
.secretKeyBits
= secretKeyBits
;
1324 sid
->authAlgorithm
= authAlgorithm
;
1325 sid
->authKeyBits
= authKeyBits
;
1326 sid
->keaType
= keaType
;
1327 sid
->keaKeyBits
= keaKeyBits
;
1328 sid
->lastAccessTime
= sid
->creationTime
= ssl_Time();
1329 sid
->expirationTime
= sid
->creationTime
+ ssl_sid_timeout
;
1332 sid
->u
.ssl2
.cipherArg
.data
= (PRUint8
*) PORT_Alloc(caLen
);
1333 if (!sid
->u
.ssl2
.cipherArg
.data
) {
1336 sid
->u
.ssl2
.cipherArg
.len
= caLen
;
1337 PORT_Memcpy(sid
->u
.ssl2
.cipherArg
.data
, ca
, caLen
);
1343 ** Construct session keys given the masterKey (tied to the session-id),
1344 ** the client's challenge and the server's nonce.
1346 ** Called from ssl2_CreateSessionCypher() <-
1349 ssl2_ProduceKeys(sslSocket
* ss
,
1352 SECItem
* masterKey
,
1353 PRUint8
* challenge
,
1357 PK11Context
* cx
= 0;
1358 unsigned nkm
= 0; /* number of hashes to generate key mat. */
1359 unsigned nkd
= 0; /* size of readKey and writeKey. */
1365 PRUint8 km
[3*16]; /* buffer for key material. */
1370 PORT_Assert( ss
->opt
.noLocks
|| ssl_Have1stHandshakeLock(ss
) );
1373 cx
= PK11_CreateDigestContext(SEC_OID_MD5
);
1375 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE
);
1379 nkm
= ssl_Specs
[cipherType
].nkm
;
1380 nkd
= ssl_Specs
[cipherType
].nkd
;
1382 readKey
->data
= (PRUint8
*) PORT_Alloc(nkd
);
1387 writeKey
->data
= (PRUint8
*) PORT_Alloc(nkd
);
1388 if (!writeKey
->data
)
1390 writeKey
->len
= nkd
;
1392 /* Produce key material */
1394 for (i
= 0, off
= 0; i
< nkm
; i
++, off
+= 16) {
1395 rv
= PK11_DigestBegin(cx
);
1396 rv
|= PK11_DigestOp(cx
, masterKey
->data
, masterKey
->len
);
1397 rv
|= PK11_DigestOp(cx
, &countChar
, 1);
1398 rv
|= PK11_DigestOp(cx
, challenge
, SSL_CHALLENGE_BYTES
);
1399 rv
|= PK11_DigestOp(cx
, nonce
, SSL_CONNECTIONID_BYTES
);
1400 rv
|= PK11_DigestFinal(cx
, km
+off
, &part
, MD5_LENGTH
);
1401 if (rv
!= SECSuccess
) {
1402 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE
);
1410 PORT_Memcpy(readKey
->data
, km
, nkd
);
1411 PORT_Memcpy(writeKey
->data
, km
+ nkd
, nkd
);
1414 PK11_DestroyContext(cx
, PR_TRUE
);
1418 /* Called from ssl2_ServerSetupSessionCypher()
1419 ** <- ssl2_HandleClientSessionKeyMessage()
1420 ** <- ssl2_HandleClientHelloMessage()
1421 ** and from ssl2_ClientSetupSessionCypher()
1422 ** <- ssl2_HandleServerHelloMessage()
1425 ssl2_CreateSessionCypher(sslSocket
*ss
, sslSessionID
*sid
, PRBool isClient
)
1427 SECItem
* rk
= NULL
;
1428 SECItem
* wk
= NULL
;
1431 int cipherType
= sid
->u
.ssl2
.cipherType
;
1432 PK11SlotInfo
* slot
= NULL
;
1433 CK_MECHANISM_TYPE mechanism
;
1442 PORT_Assert( ss
->opt
.noLocks
|| ssl_Have1stHandshakeLock(ss
) );
1443 if((ss
->sec
.ci
.sid
== 0))
1444 goto sec_loser
; /* don't crash if asserts are off */
1446 /* Trying to cut down on all these switch statements that should be tables.
1447 * So, test cipherType once, here, and then use tables below.
1449 switch (cipherType
) {
1450 case SSL_CK_RC4_128_EXPORT40_WITH_MD5
:
1451 case SSL_CK_RC4_128_WITH_MD5
:
1452 case SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5
:
1453 case SSL_CK_RC2_128_CBC_WITH_MD5
:
1454 case SSL_CK_DES_64_CBC_WITH_MD5
:
1455 case SSL_CK_DES_192_EDE3_CBC_WITH_MD5
:
1459 SSL_DBG(("%d: SSL[%d]: ssl2_CreateSessionCypher: unknown cipher=%d",
1460 SSL_GETPID(), ss
->fd
, cipherType
));
1461 PORT_SetError(isClient
? SSL_ERROR_BAD_SERVER
: SSL_ERROR_BAD_CLIENT
);
1465 rk
= isClient
? &readKey
: &writeKey
;
1466 wk
= isClient
? &writeKey
: &readKey
;
1468 /* Produce the keys for this session */
1469 rv
= ssl2_ProduceKeys(ss
, &readKey
, &writeKey
, &sid
->u
.ssl2
.masterKey
,
1470 ss
->sec
.ci
.clientChallenge
, ss
->sec
.ci
.connectionID
,
1472 if (rv
!= SECSuccess
)
1474 PRINT_BUF(7, (ss
, "Session read-key: ", rk
->data
, rk
->len
));
1475 PRINT_BUF(7, (ss
, "Session write-key: ", wk
->data
, wk
->len
));
1477 PORT_Memcpy(ss
->sec
.ci
.readKey
, readKey
.data
, readKey
.len
);
1478 PORT_Memcpy(ss
->sec
.ci
.writeKey
, writeKey
.data
, writeKey
.len
);
1479 ss
->sec
.ci
.keySize
= readKey
.len
;
1482 rv
= ssl2_CreateMAC(&ss
->sec
, rk
, wk
, cipherType
);
1483 if (rv
!= SECSuccess
)
1486 /* First create the session key object */
1487 SSL_TRC(3, ("%d: SSL[%d]: using %s", SSL_GETPID(), ss
->fd
,
1488 ssl_cipherName
[cipherType
]));
1491 mechanism
= ssl_Specs
[cipherType
].mechanism
;
1493 /* set destructer before we call loser... */
1494 ss
->sec
.destroy
= (void (*)(void*, PRBool
)) PK11_DestroyContext
;
1495 slot
= PK11_GetBestSlot(mechanism
, ss
->pkcs11PinArg
);
1499 param
= PK11_ParamFromIV(mechanism
, &sid
->u
.ssl2
.cipherArg
);
1502 readcx
= PK11_CreateContextByRawKey(slot
, mechanism
, PK11_OriginUnwrap
,
1503 CKA_DECRYPT
, rk
, param
,
1505 SECITEM_FreeItem(param
, PR_TRUE
);
1509 /* build the client context */
1510 param
= PK11_ParamFromIV(mechanism
, &sid
->u
.ssl2
.cipherArg
);
1513 writecx
= PK11_CreateContextByRawKey(slot
, mechanism
, PK11_OriginUnwrap
,
1514 CKA_ENCRYPT
, wk
, param
,
1516 SECITEM_FreeItem(param
,PR_TRUE
);
1517 if (writecx
== NULL
)
1519 PK11_FreeSlot(slot
);
1522 ss
->sec
.enc
= (SSLCipher
) PK11_CipherOp
;
1523 ss
->sec
.dec
= (SSLCipher
) PK11_CipherOp
;
1524 ss
->sec
.readcx
= (void *) readcx
;
1525 ss
->sec
.writecx
= (void *) writecx
;
1526 ss
->sec
.blockSize
= ssl_Specs
[cipherType
].blockSize
;
1527 ss
->sec
.blockShift
= ssl_Specs
[cipherType
].blockShift
;
1528 ss
->sec
.cipherType
= sid
->u
.ssl2
.cipherType
;
1529 ss
->sec
.keyBits
= sid
->u
.ssl2
.keyBits
;
1530 ss
->sec
.secretKeyBits
= sid
->u
.ssl2
.secretKeyBits
;
1534 if (ss
->sec
.destroy
) {
1535 if (readcx
) (*ss
->sec
.destroy
)(readcx
, PR_TRUE
);
1536 if (writecx
) (*ss
->sec
.destroy
)(writecx
, PR_TRUE
);
1538 ss
->sec
.destroy
= NULL
;
1539 if (slot
) PK11_FreeSlot(slot
);
1546 SECITEM_ZfreeItem(rk
, PR_FALSE
);
1549 SECITEM_ZfreeItem(wk
, PR_FALSE
);
1555 ** Setup the server ciphers given information from a CLIENT-MASTER-KEY
1557 ** "ss" pointer to the ssl-socket object
1558 ** "cipher" the cipher type to use
1559 ** "keyBits" the size of the final cipher key
1560 ** "ck" the clear-key data
1561 ** "ckLen" the number of bytes of clear-key data
1562 ** "ek" the encrypted-key data
1563 ** "ekLen" the number of bytes of encrypted-key data
1564 ** "ca" the cipher-arg data
1565 ** "caLen" the number of bytes of cipher-arg data
1567 ** The MASTER-KEY is constructed by first decrypting the encrypted-key
1568 ** data. This produces the SECRET-KEY-DATA. The MASTER-KEY is composed by
1569 ** concatenating the clear-key data with the SECRET-KEY-DATA. This code
1570 ** checks to make sure that the client didn't send us an improper amount
1571 ** of SECRET-KEY-DATA (it restricts the length of that data to match the
1574 ** Called from ssl2_HandleClientSessionKeyMessage().
1577 ssl2_ServerSetupSessionCypher(sslSocket
*ss
, int cipher
, unsigned int keyBits
,
1578 PRUint8
*ck
, unsigned int ckLen
,
1579 PRUint8
*ek
, unsigned int ekLen
,
1580 PRUint8
*ca
, unsigned int caLen
)
1582 PRUint8
* dk
= NULL
; /* decrypted master key */
1584 sslServerCerts
* sc
= ss
->serverCerts
+ kt_rsa
;
1585 PRUint8
* kbuf
= 0; /* buffer for RSA decrypted data. */
1586 unsigned int ddLen
; /* length of RSA decrypted data in kbuf */
1587 unsigned int keySize
;
1588 unsigned int dkLen
; /* decrypted key length in bytes */
1591 PRUint16 allowed
; /* cipher kinds enabled and allowed by policy */
1592 PRUint8 mkbuf
[SSL_MAX_MASTER_KEY_BYTES
];
1594 PORT_Assert( ss
->opt
.noLocks
|| ssl_Have1stHandshakeLock(ss
) );
1595 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveRecvBufLock(ss
) );
1596 PORT_Assert((sc
->SERVERKEY
!= 0));
1597 PORT_Assert((ss
->sec
.ci
.sid
!= 0));
1598 sid
= ss
->sec
.ci
.sid
;
1600 /* Trying to cut down on all these switch statements that should be tables.
1601 * So, test cipherType once, here, and then use tables below.
1604 case SSL_CK_RC4_128_EXPORT40_WITH_MD5
:
1605 case SSL_CK_RC4_128_WITH_MD5
:
1606 case SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5
:
1607 case SSL_CK_RC2_128_CBC_WITH_MD5
:
1608 case SSL_CK_DES_64_CBC_WITH_MD5
:
1609 case SSL_CK_DES_192_EDE3_CBC_WITH_MD5
:
1613 SSL_DBG(("%d: SSL[%d]: ssl2_ServerSetupSessionCypher: unknown cipher=%d",
1614 SSL_GETPID(), ss
->fd
, cipher
));
1615 PORT_SetError(SSL_ERROR_BAD_CLIENT
);
1619 allowed
= ss
->allowedByPolicy
& ss
->chosenPreference
& SSL_CB_IMPLEMENTED
;
1620 if (!(allowed
& (1 << cipher
))) {
1621 /* client chose a kind we don't allow! */
1622 SSL_DBG(("%d: SSL[%d]: disallowed cipher=%d",
1623 SSL_GETPID(), ss
->fd
, cipher
));
1624 PORT_SetError(SSL_ERROR_BAD_CLIENT
);
1628 keySize
= ssl_Specs
[cipher
].keyLen
;
1629 if (keyBits
!= keySize
* BPB
) {
1630 SSL_DBG(("%d: SSL[%d]: invalid master secret key length=%d (bits)!",
1631 SSL_GETPID(), ss
->fd
, keyBits
));
1632 PORT_SetError(SSL_ERROR_BAD_CLIENT
);
1636 if (ckLen
!= ssl_Specs
[cipher
].pubLen
) {
1637 SSL_DBG(("%d: SSL[%d]: invalid clear key length, ckLen=%d (bytes)!",
1638 SSL_GETPID(), ss
->fd
, ckLen
));
1639 PORT_SetError(SSL_ERROR_BAD_CLIENT
);
1643 if (caLen
!= ssl_Specs
[cipher
].ivLen
) {
1644 SSL_DBG(("%d: SSL[%d]: invalid key args length, caLen=%d (bytes)!",
1645 SSL_GETPID(), ss
->fd
, caLen
));
1646 PORT_SetError(SSL_ERROR_BAD_CLIENT
);
1650 modulusLen
= PK11_GetPrivateModulusLen(sc
->SERVERKEY
);
1651 if (modulusLen
== -1) {
1652 /* XXX If the key is bad, then PK11_PubDecryptRaw will fail below. */
1655 if (ekLen
> modulusLen
|| ekLen
+ ckLen
< keySize
) {
1656 SSL_DBG(("%d: SSL[%d]: invalid encrypted key length, ekLen=%d (bytes)!",
1657 SSL_GETPID(), ss
->fd
, ekLen
));
1658 PORT_SetError(SSL_ERROR_BAD_CLIENT
);
1662 /* allocate the buffer to hold the decrypted portion of the key. */
1663 kbuf
= (PRUint8
*)PORT_Alloc(modulusLen
);
1667 dkLen
= keySize
- ckLen
;
1668 dk
= kbuf
+ modulusLen
- dkLen
;
1670 /* Decrypt encrypted half of the key.
1671 ** NOTE: PK11_PubDecryptRaw will barf on a non-RSA key. This is
1672 ** desired behavior here.
1674 rv
= PK11_PubDecryptRaw(sc
->SERVERKEY
, kbuf
, &ddLen
, modulusLen
, ek
, ekLen
);
1675 if (rv
!= SECSuccess
)
1678 /* Is the length of the decrypted data (ddLen) the expected value? */
1679 if (modulusLen
!= ddLen
)
1682 /* Cheaply verify that PKCS#1 was used to format the encryption block */
1683 if ((kbuf
[0] != 0x00) || (kbuf
[1] != 0x02) || (dk
[-1] != 0x00)) {
1684 SSL_DBG(("%d: SSL[%d]: strange encryption block",
1685 SSL_GETPID(), ss
->fd
));
1686 PORT_SetError(SSL_ERROR_BAD_CLIENT
);
1690 /* Make sure we're not subject to a version rollback attack. */
1691 if (ss
->opt
.enableSSL3
|| ss
->opt
.enableTLS
) {
1692 static const PRUint8 threes
[8] = { 0x03, 0x03, 0x03, 0x03,
1693 0x03, 0x03, 0x03, 0x03 };
1695 if (PORT_Memcmp(dk
- 8 - 1, threes
, 8) == 0) {
1696 PORT_SetError(SSL_ERROR_BAD_CLIENT
);
1702 /* Defense against the Bleichenbacher attack.
1703 * Provide the client with NO CLUES that the decrypted master key
1704 * was erroneous. Don't send any error messages.
1705 * Instead, Generate a completely bogus master key .
1707 PK11_GenerateRandom(dk
, dkLen
);
1711 ** Construct master key out of the pieces.
1714 PORT_Memcpy(mkbuf
, ck
, ckLen
);
1716 PORT_Memcpy(mkbuf
+ ckLen
, dk
, dkLen
);
1718 /* Fill in session-id */
1719 rv
= ssl2_FillInSID(sid
, cipher
, mkbuf
, keySize
, ca
, caLen
,
1720 keyBits
, keyBits
- (ckLen
<<3),
1721 ss
->sec
.authAlgorithm
, ss
->sec
.authKeyBits
,
1722 ss
->sec
.keaType
, ss
->sec
.keaKeyBits
);
1723 if (rv
!= SECSuccess
) {
1727 /* Create session ciphers */
1728 rv
= ssl2_CreateSessionCypher(ss
, sid
, PR_FALSE
);
1729 if (rv
!= SECSuccess
) {
1733 SSL_TRC(1, ("%d: SSL[%d]: server, using %s cipher, clear=%d total=%d",
1734 SSL_GETPID(), ss
->fd
, ssl_cipherName
[cipher
],
1735 ckLen
<<3, keySize
<<3));
1747 /************************************************************************/
1750 ** Rewrite the incoming cipher specs, comparing to list of specs we support,
1751 ** (ss->cipherSpecs) and eliminating anything we don't support
1753 * Note: Our list may contain SSL v3 ciphers.
1754 * We MUST NOT match on any of those.
1755 * Fortunately, this is easy to detect because SSLv3 ciphers have zero
1756 * in the first byte, and none of the SSLv2 ciphers do.
1758 * Called from ssl2_HandleClientHelloMessage().
1759 * Returns the number of bytes of "qualified cipher specs",
1760 * which is typically a multiple of 3, but will be zero if there are none.
1763 ssl2_QualifyCypherSpecs(sslSocket
*ss
,
1764 PRUint8
* cs
, /* cipher specs in client hello msg. */
1772 PRUint8 qualifiedSpecs
[ssl2_NUM_SUITES_IMPLEMENTED
* 3];
1774 PORT_Assert( ss
->opt
.noLocks
|| ssl_Have1stHandshakeLock(ss
) );
1775 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveRecvBufLock(ss
) );
1777 if (!ss
->cipherSpecs
) {
1778 SECStatus rv
= ssl2_ConstructCipherSpecs(ss
);
1779 if (rv
!= SECSuccess
|| !ss
->cipherSpecs
)
1783 PRINT_BUF(10, (ss
, "specs from client:", cs
, csLen
));
1784 qs
= qualifiedSpecs
;
1785 ms
= ss
->cipherSpecs
;
1786 for (mc
= ss
->sizeCipherSpecs
; mc
> 0; mc
-= 3, ms
+= 3) {
1789 for (hs
= cs
, hc
= csLen
; hc
> 0; hs
+= 3, hc
-= 3) {
1790 if ((hs
[0] == ms
[0]) &&
1793 /* Copy this cipher spec into the "keep" section */
1802 hc
= qs
- qualifiedSpecs
;
1803 PRINT_BUF(10, (ss
, "qualified specs from client:", qualifiedSpecs
, hc
));
1804 PORT_Memcpy(cs
, qualifiedSpecs
, hc
);
1809 ** Pick the best cipher we can find, given the array of server cipher
1810 ** specs. Returns cipher number (e.g. SSL_CK_*), or -1 for no overlap.
1811 ** If succesful, stores the master key size (bytes) in *pKeyLen.
1813 ** This is correct only for the client side, but presently
1814 ** this function is only called from
1815 ** ssl2_ClientSetupSessionCypher() <- ssl2_HandleServerHelloMessage()
1817 ** Note that most servers only return a single cipher suite in their
1818 ** ServerHello messages. So, the code below for finding the "best" cipher
1819 ** suite usually has only one choice. The client and server should send
1820 ** their cipher suite lists sorted in descending order by preference.
1823 ssl2_ChooseSessionCypher(sslSocket
*ss
,
1824 int hc
, /* number of cs's in hs. */
1825 PRUint8
* hs
, /* server hello's cipher suites. */
1826 int * pKeyLen
) /* out: sym key size in bytes. */
1831 int bestRealKeySize
;
1836 const PRUint8
* preferred
;
1837 static const PRUint8 noneSuch
[3] = { 0, 0, 0 };
1839 PORT_Assert( ss
->opt
.noLocks
|| ssl_Have1stHandshakeLock(ss
) );
1840 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveRecvBufLock(ss
) );
1842 if (!ss
->cipherSpecs
) {
1843 SECStatus rv
= ssl2_ConstructCipherSpecs(ss
);
1844 if (rv
!= SECSuccess
|| !ss
->cipherSpecs
)
1848 if (!ss
->preferredCipher
) {
1849 unsigned int allowed
= ss
->allowedByPolicy
& ss
->chosenPreference
&
1852 preferred
= implementedCipherSuites
;
1853 for (i
= ssl2_NUM_SUITES_IMPLEMENTED
; i
> 0; --i
) {
1854 if (0 != (allowed
& (1U << preferred
[0]))) {
1855 ss
->preferredCipher
= preferred
;
1862 preferred
= ss
->preferredCipher
? ss
->preferredCipher
: noneSuch
;
1864 ** Scan list of ciphers recieved from peer and look for a match in
1866 * Note: Our list may contain SSL v3 ciphers.
1867 * We MUST NOT match on any of those.
1868 * Fortunately, this is easy to detect because SSLv3 ciphers have zero
1869 * in the first byte, and none of the SSLv2 ciphers do.
1871 bestKeySize
= bestRealKeySize
= 0;
1874 for (i
= 0, ms
= ss
->cipherSpecs
; i
< ss
->sizeCipherSpecs
; i
+= 3, ms
+= 3) {
1875 if ((hs
[0] == preferred
[0]) &&
1876 (hs
[1] == preferred
[1]) &&
1877 (hs
[2] == preferred
[2]) &&
1879 /* Pick this cipher immediately! */
1880 *pKeyLen
= (((hs
[1] << 8) | hs
[2]) + 7) >> 3;
1883 if ((hs
[0] == ms
[0]) && (hs
[1] == ms
[1]) && (hs
[2] == ms
[2]) &&
1887 /* Use secret keySize to determine which cipher is best */
1888 realKeySize
= (hs
[1] << 8) | hs
[2];
1890 case SSL_CK_RC4_128_EXPORT40_WITH_MD5
:
1891 case SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5
:
1895 keySize
= realKeySize
;
1898 if (keySize
> bestKeySize
) {
1900 bestKeySize
= keySize
;
1901 bestRealKeySize
= realKeySize
;
1907 if (bestCypher
< 0) {
1909 ** No overlap between server and client. Re-examine server list
1910 ** to see what kind of ciphers it does support so that we can set
1911 ** the error code appropriately.
1913 if ((ohs
[0] == SSL_CK_RC4_128_WITH_MD5
) ||
1914 (ohs
[0] == SSL_CK_RC2_128_CBC_WITH_MD5
)) {
1915 PORT_SetError(SSL_ERROR_US_ONLY_SERVER
);
1916 } else if ((ohs
[0] == SSL_CK_RC4_128_EXPORT40_WITH_MD5
) ||
1917 (ohs
[0] == SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5
)) {
1918 PORT_SetError(SSL_ERROR_EXPORT_ONLY_SERVER
);
1920 PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP
);
1922 SSL_DBG(("%d: SSL[%d]: no cipher overlap", SSL_GETPID(), ss
->fd
));
1925 *pKeyLen
= (bestRealKeySize
+ 7) >> 3;
1933 ssl2_ClientHandleServerCert(sslSocket
*ss
, PRUint8
*certData
, int certLen
)
1935 CERTCertificate
*cert
= NULL
;
1938 certItem
.data
= certData
;
1939 certItem
.len
= certLen
;
1941 /* decode the certificate */
1942 cert
= CERT_NewTempCertificate(ss
->dbHandle
, &certItem
, NULL
,
1946 SSL_DBG(("%d: SSL[%d]: decode of server certificate fails",
1947 SSL_GETPID(), ss
->fd
));
1948 PORT_SetError(SSL_ERROR_BAD_CERTIFICATE
);
1954 if (ssl_trace
>= 1) {
1957 issuer
= CERT_NameToAscii(&cert
->issuer
);
1958 subject
= CERT_NameToAscii(&cert
->subject
);
1959 SSL_TRC(1,("%d: server certificate issuer: '%s'",
1960 SSL_GETPID(), issuer
? issuer
: "OOPS"));
1961 SSL_TRC(1,("%d: server name: '%s'",
1962 SSL_GETPID(), subject
? subject
: "OOPS"));
1969 ss
->sec
.peerCert
= cert
;
1975 * Format one block of data for public/private key encryption using
1976 * the rules defined in PKCS #1. SSL2 does this itself to handle the
1977 * rollback detection.
1979 #define RSA_BLOCK_MIN_PAD_LEN 8
1980 #define RSA_BLOCK_FIRST_OCTET 0x00
1981 #define RSA_BLOCK_AFTER_PAD_OCTET 0x00
1982 #define RSA_BLOCK_PUBLIC_OCTET 0x02
1984 ssl_FormatSSL2Block(unsigned modulusLen
, SECItem
*data
)
1986 unsigned char *block
;
1992 if (modulusLen
< data
->len
+ (3 + RSA_BLOCK_MIN_PAD_LEN
)) {
1993 PORT_SetError(SEC_ERROR_BAD_KEY
);
1996 block
= (unsigned char *) PORT_Alloc(modulusLen
);
2003 * All RSA blocks start with two octets:
2006 *bp
++ = RSA_BLOCK_FIRST_OCTET
;
2007 *bp
++ = RSA_BLOCK_PUBLIC_OCTET
;
2010 * 0x00 || BT || Pad || 0x00 || ActualData
2011 * 1 1 padLen 1 data->len
2012 * Pad is all non-zero random bytes.
2014 padLen
= modulusLen
- data
->len
- 3;
2015 PORT_Assert (padLen
>= RSA_BLOCK_MIN_PAD_LEN
);
2016 rv
= PK11_GenerateRandom(bp
, padLen
);
2017 if (rv
== SECFailure
) goto loser
;
2018 /* replace all the 'zero' bytes */
2019 for (i
= 0; i
< padLen
; i
++) {
2020 while (bp
[i
] == RSA_BLOCK_AFTER_PAD_OCTET
) {
2021 rv
= PK11_GenerateRandom(bp
+i
, 1);
2022 if (rv
== SECFailure
) goto loser
;
2026 *bp
++ = RSA_BLOCK_AFTER_PAD_OCTET
;
2027 PORT_Memcpy (bp
, data
->data
, data
->len
);
2031 if (block
) PORT_Free(block
);
2036 ** Given the server's public key and cipher specs, generate a session key
2037 ** that is ready to use for encrypting/decrypting the byte stream. At
2038 ** the same time, generate the SSL_MT_CLIENT_MASTER_KEY message and
2039 ** send it to the server.
2041 ** Called from ssl2_HandleServerHelloMessage()
2044 ssl2_ClientSetupSessionCypher(sslSocket
*ss
, PRUint8
*cs
, int csLen
)
2047 PRUint8
* ca
; /* points to iv data, or NULL if none. */
2048 PRUint8
* ekbuf
= 0;
2049 CERTCertificate
* cert
= 0;
2050 SECKEYPublicKey
* serverKey
= 0;
2051 unsigned modulusLen
= 0;
2054 int keyLen
; /* cipher symkey size in bytes. */
2055 int ckLen
; /* publicly reveal this many bytes of key. */
2056 int caLen
; /* length of IV data at *ca. */
2059 unsigned char *eblock
; /* holds unencrypted PKCS#1 formatted key. */
2060 SECItem rek
; /* holds portion of symkey to be encrypted. */
2062 PRUint8 keyData
[SSL_MAX_MASTER_KEY_BYTES
];
2065 PORT_Assert( ss
->opt
.noLocks
|| ssl_Have1stHandshakeLock(ss
) );
2069 sid
= ss
->sec
.ci
.sid
;
2070 PORT_Assert(sid
!= 0);
2072 cert
= ss
->sec
.peerCert
;
2074 serverKey
= CERT_ExtractPublicKey(cert
);
2076 SSL_DBG(("%d: SSL[%d]: extract public key failed: error=%d",
2077 SSL_GETPID(), ss
->fd
, PORT_GetError()));
2078 PORT_SetError(SSL_ERROR_BAD_CERTIFICATE
);
2083 ss
->sec
.authAlgorithm
= ssl_sign_rsa
;
2084 ss
->sec
.keaType
= ssl_kea_rsa
;
2085 ss
->sec
.keaKeyBits
= \
2086 ss
->sec
.authKeyBits
= SECKEY_PublicKeyStrengthInBits(serverKey
);
2088 /* Choose a compatible cipher with the server */
2090 cipher
= ssl2_ChooseSessionCypher(ss
, nc
, cs
, &keyLen
);
2092 /* ssl2_ChooseSessionCypher has set error code. */
2093 ssl2_SendErrorMessage(ss
, SSL_PE_NO_CYPHERS
);
2097 /* Generate the random keys */
2098 PK11_GenerateRandom(keyData
, sizeof(keyData
));
2101 ** Next, carve up the keys into clear and encrypted portions. The
2102 ** clear data is taken from the start of keyData and the encrypted
2103 ** portion from the remainder. Note that each of these portions is
2104 ** carved in half, one half for the read-key and one for the
2109 /* We know that cipher is a legit value here, because
2110 * ssl2_ChooseSessionCypher doesn't return bogus values.
2112 ckLen
= ssl_Specs
[cipher
].pubLen
; /* cleartext key length. */
2113 caLen
= ssl_Specs
[cipher
].ivLen
; /* IV length. */
2115 PORT_Assert(sizeof iv
>= caLen
);
2116 PK11_GenerateRandom(iv
, caLen
);
2120 /* Fill in session-id */
2121 rv
= ssl2_FillInSID(sid
, cipher
, keyData
, keyLen
,
2122 ca
, caLen
, keyLen
<< 3, (keyLen
- ckLen
) << 3,
2123 ss
->sec
.authAlgorithm
, ss
->sec
.authKeyBits
,
2124 ss
->sec
.keaType
, ss
->sec
.keaKeyBits
);
2125 if (rv
!= SECSuccess
) {
2129 SSL_TRC(1, ("%d: SSL[%d]: client, using %s cipher, clear=%d total=%d",
2130 SSL_GETPID(), ss
->fd
, ssl_cipherName
[cipher
],
2131 ckLen
<<3, keyLen
<<3));
2133 /* Now setup read and write ciphers */
2134 rv
= ssl2_CreateSessionCypher(ss
, sid
, PR_TRUE
);
2135 if (rv
!= SECSuccess
) {
2140 ** Fill in the encryption buffer with some random bytes. Then
2141 ** copy in the portion of the session key we are encrypting.
2143 modulusLen
= SECKEY_PublicKeyStrength(serverKey
);
2144 rek
.data
= keyData
+ ckLen
;
2145 rek
.len
= keyLen
- ckLen
;
2146 eblock
= ssl_FormatSSL2Block(modulusLen
, &rek
);
2150 /* Set up the padding for version 2 rollback detection. */
2151 /* XXX We should really use defines here */
2152 if (ss
->opt
.enableSSL3
|| ss
->opt
.enableTLS
) {
2153 PORT_Assert((modulusLen
- rek
.len
) > 12);
2154 PORT_Memset(eblock
+ modulusLen
- rek
.len
- 8 - 1, 0x03, 8);
2156 ekbuf
= (PRUint8
*) PORT_Alloc(modulusLen
);
2159 PRINT_BUF(10, (ss
, "master key encryption block:",
2160 eblock
, modulusLen
));
2162 /* Encrypt ekitem */
2163 rv
= PK11_PubEncryptRaw(serverKey
, ekbuf
, eblock
, modulusLen
,
2168 /* Now we have everything ready to send */
2169 rv
= ssl2_SendSessionKeyMessage(ss
, cipher
, keyLen
<< 3, ca
, caLen
,
2170 keyData
, ckLen
, ekbuf
, modulusLen
);
2171 if (rv
!= SECSuccess
) {
2182 PORT_Memset(keyData
, 0, sizeof(keyData
));
2183 PORT_ZFree(ekbuf
, modulusLen
);
2184 PORT_ZFree(eblock
, modulusLen
);
2185 SECKEY_DestroyPublicKey(serverKey
);
2189 /************************************************************************/
2192 * Called from ssl2_HandleMessage in response to SSL_MT_SERVER_FINISHED message.
2193 * Caller holds recvBufLock and handshakeLock
2196 ssl2_ClientRegSessionID(sslSocket
*ss
, PRUint8
*s
)
2198 sslSessionID
*sid
= ss
->sec
.ci
.sid
;
2200 /* Record entry in nonce cache */
2201 if (sid
->peerCert
== NULL
) {
2202 PORT_Memcpy(sid
->u
.ssl2
.sessionID
, s
, sizeof(sid
->u
.ssl2
.sessionID
));
2203 sid
->peerCert
= CERT_DupCertificate(ss
->sec
.peerCert
);
2206 if (!ss
->opt
.noCache
)
2207 (*ss
->sec
.cache
)(sid
);
2210 /* Called from ssl2_HandleMessage() */
2212 ssl2_TriggerNextMessage(sslSocket
*ss
)
2216 PORT_Assert( ss
->opt
.noLocks
|| ssl_Have1stHandshakeLock(ss
) );
2218 if ((ss
->sec
.ci
.requiredElements
& CIS_HAVE_CERTIFICATE
) &&
2219 !(ss
->sec
.ci
.sentElements
& CIS_HAVE_CERTIFICATE
)) {
2220 ss
->sec
.ci
.sentElements
|= CIS_HAVE_CERTIFICATE
;
2221 rv
= ssl2_SendCertificateRequestMessage(ss
);
2227 /* See if it's time to send our finished message, or if the handshakes are
2228 ** complete. Send finished message if appropriate.
2229 ** Returns SECSuccess unless anything goes wrong.
2231 ** Called from ssl2_HandleMessage,
2232 ** ssl2_HandleVerifyMessage
2233 ** ssl2_HandleServerHelloMessage
2234 ** ssl2_HandleClientSessionKeyMessage
2235 ** ssl2_RestartHandshakeAfterCertReq
2236 ** ssl2_RestartHandshakeAfterServerCert
2239 ssl2_TryToFinish(sslSocket
*ss
)
2244 PORT_Assert( ss
->opt
.noLocks
|| ssl_Have1stHandshakeLock(ss
) );
2246 e
= ss
->sec
.ci
.elements
;
2247 ef
= e
| CIS_HAVE_FINISHED
;
2248 if ((ef
& ss
->sec
.ci
.requiredElements
) == ss
->sec
.ci
.requiredElements
) {
2249 if (ss
->sec
.isServer
) {
2250 /* Send server finished message if we already didn't */
2251 rv
= ssl2_SendServerFinishedMessage(ss
);
2253 /* Send client finished message if we already didn't */
2254 rv
= ssl2_SendClientFinishedMessage(ss
);
2256 if (rv
!= SECSuccess
) {
2259 if ((e
& ss
->sec
.ci
.requiredElements
) == ss
->sec
.ci
.requiredElements
) {
2260 /* Totally finished */
2269 ** Called from ssl2_HandleRequestCertificate
2270 ** ssl2_RestartHandshakeAfterCertReq
2273 ssl2_SignResponse(sslSocket
*ss
,
2274 SECKEYPrivateKey
*key
,
2277 SGNContext
* sgn
= NULL
;
2278 PRUint8
* challenge
;
2280 SECStatus rv
= SECFailure
;
2282 PORT_Assert( ss
->opt
.noLocks
|| ssl_Have1stHandshakeLock(ss
) );
2284 challenge
= ss
->sec
.ci
.serverChallenge
;
2285 len
= ss
->sec
.ci
.serverChallengeLen
;
2287 /* Sign the expected data... */
2288 sgn
= SGN_NewContext(SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION
,key
);
2291 rv
= SGN_Begin(sgn
);
2292 if (rv
!= SECSuccess
)
2294 rv
= SGN_Update(sgn
, ss
->sec
.ci
.readKey
, ss
->sec
.ci
.keySize
);
2295 if (rv
!= SECSuccess
)
2297 rv
= SGN_Update(sgn
, ss
->sec
.ci
.writeKey
, ss
->sec
.ci
.keySize
);
2298 if (rv
!= SECSuccess
)
2300 rv
= SGN_Update(sgn
, challenge
, len
);
2301 if (rv
!= SECSuccess
)
2303 rv
= SGN_Update(sgn
, ss
->sec
.peerCert
->derCert
.data
,
2304 ss
->sec
.peerCert
->derCert
.len
);
2305 if (rv
!= SECSuccess
)
2307 rv
= SGN_End(sgn
, response
);
2308 if (rv
!= SECSuccess
)
2312 SGN_DestroyContext(sgn
, PR_TRUE
);
2313 return rv
== SECSuccess
? SECSuccess
: SECFailure
;
2317 ** Try to handle a request-certificate message. Get client's certificate
2318 ** and private key and sign a message for the server to see.
2319 ** Caller must hold handshakeLock
2321 ** Called from ssl2_HandleMessage().
2324 ssl2_HandleRequestCertificate(sslSocket
*ss
)
2326 CERTCertificate
* cert
= NULL
; /* app-selected client cert. */
2327 SECKEYPrivateKey
*key
= NULL
; /* priv key for cert. */
2335 * These things all need to be initialized before we can "goto loser".
2337 response
.data
= NULL
;
2339 /* get challenge info from connectionInfo */
2340 authType
= ss
->sec
.ci
.authType
;
2342 if (authType
!= SSL_AT_MD5_WITH_RSA_ENCRYPTION
) {
2343 SSL_TRC(7, ("%d: SSL[%d]: unsupported auth type 0x%x", SSL_GETPID(),
2348 /* Get certificate and private-key from client */
2349 if (!ss
->getClientAuthData
) {
2350 SSL_TRC(7, ("%d: SSL[%d]: client doesn't support client-auth",
2351 SSL_GETPID(), ss
->fd
));
2354 ret
= (*ss
->getClientAuthData
)(ss
->getClientAuthDataArg
, ss
->fd
,
2356 if ( ret
== SECWouldBlock
) {
2357 ssl_SetAlwaysBlock(ss
);
2365 /* check what the callback function returned */
2366 if ((!cert
) || (!key
)) {
2367 /* we are missing either the key or cert */
2369 /* got a cert, but no key - free it */
2370 CERT_DestroyCertificate(cert
);
2374 /* got a key, but no cert - free it */
2375 SECKEY_DestroyPrivateKey(key
);
2381 rv
= ssl2_SignResponse(ss
, key
, &response
);
2382 if ( rv
!= SECSuccess
) {
2387 /* Send response message */
2388 ret
= ssl2_SendCertificateResponseMessage(ss
, &cert
->derCert
, &response
);
2390 /* Now, remember the cert we sent. But first, forget any previous one. */
2391 if (ss
->sec
.localCert
) {
2392 CERT_DestroyCertificate(ss
->sec
.localCert
);
2394 ss
->sec
.localCert
= CERT_DupCertificate(cert
);
2395 PORT_Assert(!ss
->sec
.ci
.sid
->localCert
);
2396 if (ss
->sec
.ci
.sid
->localCert
) {
2397 CERT_DestroyCertificate(ss
->sec
.ci
.sid
->localCert
);
2399 ss
->sec
.ci
.sid
->localCert
= cert
;
2405 SSL_TRC(7, ("%d: SSL[%d]: no certificate (ret=%d)", SSL_GETPID(),
2407 ret
= ssl2_SendErrorMessage(ss
, SSL_PE_NO_CERTIFICATE
);
2412 CERT_DestroyCertificate(cert
);
2415 SECKEY_DestroyPrivateKey(key
);
2417 if ( response
.data
) {
2418 PORT_Free(response
.data
);
2425 ** Called from ssl2_HandleMessage for SSL_MT_CLIENT_CERTIFICATE message.
2426 ** Caller must hold HandshakeLock and RecvBufLock, since cd and response
2427 ** are contained in the gathered input data.
2430 ssl2_HandleClientCertificate(sslSocket
* ss
,
2431 PRUint8 certType
, /* XXX unused */
2435 unsigned int responseLen
)
2437 CERTCertificate
*cert
= NULL
;
2438 SECKEYPublicKey
*pubKey
= NULL
;
2439 VFYContext
* vfy
= NULL
;
2441 SECStatus rv
= SECFailure
;
2445 PORT_Assert( ss
->opt
.noLocks
|| ssl_Have1stHandshakeLock(ss
) );
2446 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveRecvBufLock(ss
) );
2448 /* Extract the certificate */
2450 certItem
.len
= cdLen
;
2452 cert
= CERT_NewTempCertificate(ss
->dbHandle
, &certItem
, NULL
,
2458 /* save the certificate, since the auth routine will need it */
2459 ss
->sec
.peerCert
= cert
;
2461 /* Extract the public key */
2462 pubKey
= CERT_ExtractPublicKey(cert
);
2466 /* Verify the response data... */
2467 rep
.data
= response
;
2468 rep
.len
= responseLen
;
2469 /* SSL 2.0 only supports RSA certs, so we don't have to worry about
2471 vfy
= VFY_CreateContext(pubKey
, &rep
, SEC_OID_PKCS1_RSA_ENCRYPTION
,
2475 rv
= VFY_Begin(vfy
);
2479 rv
= VFY_Update(vfy
, ss
->sec
.ci
.readKey
, ss
->sec
.ci
.keySize
);
2482 rv
= VFY_Update(vfy
, ss
->sec
.ci
.writeKey
, ss
->sec
.ci
.keySize
);
2485 rv
= VFY_Update(vfy
, ss
->sec
.ci
.serverChallenge
, SSL_CHALLENGE_BYTES
);
2489 derCert
= &ss
->serverCerts
[kt_rsa
].serverCert
->derCert
;
2490 rv
= VFY_Update(vfy
, derCert
->data
, derCert
->len
);
2497 /* Now ask the server application if it likes the certificate... */
2498 rv
= (SECStatus
) (*ss
->authCertificate
)(ss
->authCertificateArg
,
2499 ss
->fd
, PR_TRUE
, PR_TRUE
);
2500 /* Hey, it liked it. */
2501 if (SECSuccess
== rv
)
2505 ss
->sec
.peerCert
= NULL
;
2506 CERT_DestroyCertificate(cert
);
2509 VFY_DestroyContext(vfy
, PR_TRUE
);
2510 SECKEY_DestroyPublicKey(pubKey
);
2515 ** Handle remaining messages between client/server. Process finished
2516 ** messages from either side and any authentication requests.
2517 ** This should only be called for SSLv2 handshake messages,
2518 ** not for application data records.
2519 ** Caller must hold handshake lock.
2521 ** Called from ssl_Do1stHandshake().
2525 ssl2_HandleMessage(sslSocket
*ss
)
2529 unsigned len
, certType
, certLen
, responseLen
;
2533 PORT_Assert( ss
->opt
.noLocks
|| ssl_Have1stHandshakeLock(ss
) );
2535 ssl_GetRecvBufLock(ss
);
2537 data
= ss
->gs
.buf
.buf
+ ss
->gs
.recordOffset
;
2539 if (ss
->gs
.recordLen
< 1) {
2542 SSL_TRC(3, ("%d: SSL[%d]: received %d message",
2543 SSL_GETPID(), ss
->fd
, data
[0]));
2544 DUMP_MSG(29, (ss
, data
, ss
->gs
.recordLen
));
2547 case SSL_MT_CLIENT_FINISHED
:
2548 if (ss
->sec
.ci
.elements
& CIS_HAVE_FINISHED
) {
2549 SSL_DBG(("%d: SSL[%d]: dup client-finished message",
2550 SSL_GETPID(), ss
->fd
));
2554 /* See if nonce matches */
2555 len
= ss
->gs
.recordLen
- 1;
2557 if ((len
!= sizeof(ss
->sec
.ci
.connectionID
)) ||
2558 (PORT_Memcmp(ss
->sec
.ci
.connectionID
, cid
, len
) != 0)) {
2559 SSL_DBG(("%d: SSL[%d]: bad connection-id", SSL_GETPID(), ss
->fd
));
2560 PRINT_BUF(5, (ss
, "sent connection-id",
2561 ss
->sec
.ci
.connectionID
,
2562 sizeof(ss
->sec
.ci
.connectionID
)));
2563 PRINT_BUF(5, (ss
, "rcvd connection-id", cid
, len
));
2567 SSL_TRC(5, ("%d: SSL[%d]: got client finished, waiting for 0x%d",
2568 SSL_GETPID(), ss
->fd
,
2569 ss
->sec
.ci
.requiredElements
^ ss
->sec
.ci
.elements
));
2570 ss
->sec
.ci
.elements
|= CIS_HAVE_FINISHED
;
2573 case SSL_MT_SERVER_FINISHED
:
2574 if (ss
->sec
.ci
.elements
& CIS_HAVE_FINISHED
) {
2575 SSL_DBG(("%d: SSL[%d]: dup server-finished message",
2576 SSL_GETPID(), ss
->fd
));
2580 if (ss
->gs
.recordLen
- 1 != SSL2_SESSIONID_BYTES
) {
2581 SSL_DBG(("%d: SSL[%d]: bad server-finished message, len=%d",
2582 SSL_GETPID(), ss
->fd
, ss
->gs
.recordLen
));
2585 ssl2_ClientRegSessionID(ss
, data
+1);
2586 SSL_TRC(5, ("%d: SSL[%d]: got server finished, waiting for 0x%d",
2587 SSL_GETPID(), ss
->fd
,
2588 ss
->sec
.ci
.requiredElements
^ ss
->sec
.ci
.elements
));
2589 ss
->sec
.ci
.elements
|= CIS_HAVE_FINISHED
;
2592 case SSL_MT_REQUEST_CERTIFICATE
:
2593 len
= ss
->gs
.recordLen
- 2;
2594 if ((len
< SSL_MIN_CHALLENGE_BYTES
) ||
2595 (len
> SSL_MAX_CHALLENGE_BYTES
)) {
2597 SSL_DBG(("%d: SSL[%d]: bad cert request message: code len=%d",
2598 SSL_GETPID(), ss
->fd
, len
));
2602 /* save auth request info */
2603 ss
->sec
.ci
.authType
= data
[1];
2604 ss
->sec
.ci
.serverChallengeLen
= len
;
2605 PORT_Memcpy(ss
->sec
.ci
.serverChallenge
, data
+ 2, len
);
2607 rv
= ssl2_HandleRequestCertificate(ss
);
2608 if (rv
== SECWouldBlock
) {
2609 SSL_TRC(3, ("%d: SSL[%d]: async cert request",
2610 SSL_GETPID(), ss
->fd
));
2611 /* someone is handling this asynchronously */
2612 ssl_ReleaseRecvBufLock(ss
);
2613 return SECWouldBlock
;
2621 case SSL_MT_CLIENT_CERTIFICATE
:
2622 if (!ss
->authCertificate
) {
2623 /* Server asked for authentication and can't handle it */
2624 PORT_SetError(SSL_ERROR_BAD_SERVER
);
2627 if (ss
->gs
.recordLen
< SSL_HL_CLIENT_CERTIFICATE_HBYTES
) {
2632 certLen
= (data
[2] << 8) | data
[3];
2633 responseLen
= (data
[4] << 8) | data
[5];
2634 if (certType
!= SSL_CT_X509_CERTIFICATE
) {
2635 PORT_SetError(SSL_ERROR_UNSUPPORTED_CERTIFICATE_TYPE
);
2638 if (certLen
+ responseLen
+ SSL_HL_CLIENT_CERTIFICATE_HBYTES
2639 > ss
->gs
.recordLen
) {
2640 /* prevent overflow crash. */
2643 rv
= ssl2_HandleClientCertificate(ss
, data
[1],
2644 data
+ SSL_HL_CLIENT_CERTIFICATE_HBYTES
,
2646 data
+ SSL_HL_CLIENT_CERTIFICATE_HBYTES
+ certLen
,
2649 rv2
= ssl2_SendErrorMessage(ss
, SSL_PE_BAD_CERTIFICATE
);
2653 ss
->sec
.ci
.elements
|= CIS_HAVE_CERTIFICATE
;
2657 rv
= (data
[1] << 8) | data
[2];
2658 SSL_TRC(2, ("%d: SSL[%d]: got error message, error=0x%x",
2659 SSL_GETPID(), ss
->fd
, rv
));
2661 /* Convert protocol error number into API error number */
2663 case SSL_PE_NO_CYPHERS
:
2664 rv
= SSL_ERROR_NO_CYPHER_OVERLAP
;
2666 case SSL_PE_NO_CERTIFICATE
:
2667 rv
= SSL_ERROR_NO_CERTIFICATE
;
2669 case SSL_PE_BAD_CERTIFICATE
:
2670 rv
= SSL_ERROR_BAD_CERTIFICATE
;
2672 case SSL_PE_UNSUPPORTED_CERTIFICATE_TYPE
:
2673 rv
= SSL_ERROR_UNSUPPORTED_CERTIFICATE_TYPE
;
2678 /* XXX make certificate-request optionally fail... */
2683 SSL_DBG(("%d: SSL[%d]: unknown message %d",
2684 SSL_GETPID(), ss
->fd
, data
[0]));
2688 SSL_TRC(3, ("%d: SSL[%d]: handled %d message, required=0x%x got=0x%x",
2689 SSL_GETPID(), ss
->fd
, data
[0],
2690 ss
->sec
.ci
.requiredElements
, ss
->sec
.ci
.elements
));
2692 rv
= ssl2_TryToFinish(ss
);
2693 if (rv
!= SECSuccess
)
2696 ss
->gs
.recordLen
= 0;
2697 ssl_ReleaseRecvBufLock(ss
);
2699 if (ss
->handshake
== 0) {
2703 ss
->handshake
= ssl_GatherRecord1stHandshake
;
2704 ss
->nextHandshake
= ssl2_HandleMessage
;
2705 return ssl2_TriggerNextMessage(ss
);
2708 PORT_SetError(ss
->sec
.isServer
? SSL_ERROR_BAD_CLIENT
: SSL_ERROR_BAD_SERVER
);
2712 ssl_ReleaseRecvBufLock(ss
);
2716 /************************************************************************/
2718 /* Called from ssl_Do1stHandshake, after ssl2_HandleServerHelloMessage or
2719 ** ssl2_RestartHandshakeAfterServerCert.
2722 ssl2_HandleVerifyMessage(sslSocket
*ss
)
2727 PORT_Assert( ss
->opt
.noLocks
|| ssl_Have1stHandshakeLock(ss
) );
2728 ssl_GetRecvBufLock(ss
);
2730 data
= ss
->gs
.buf
.buf
+ ss
->gs
.recordOffset
;
2731 DUMP_MSG(29, (ss
, data
, ss
->gs
.recordLen
));
2732 if ((ss
->gs
.recordLen
!= 1 + SSL_CHALLENGE_BYTES
) ||
2733 (data
[0] != SSL_MT_SERVER_VERIFY
) ||
2734 PORT_Memcmp(data
+1, ss
->sec
.ci
.clientChallenge
, SSL_CHALLENGE_BYTES
)) {
2736 PORT_SetError(SSL_ERROR_BAD_SERVER
);
2739 ss
->sec
.ci
.elements
|= CIS_HAVE_VERIFY
;
2741 SSL_TRC(5, ("%d: SSL[%d]: got server-verify, required=0x%d got=0x%x",
2742 SSL_GETPID(), ss
->fd
, ss
->sec
.ci
.requiredElements
,
2743 ss
->sec
.ci
.elements
));
2745 rv
= ssl2_TryToFinish(ss
);
2749 ss
->gs
.recordLen
= 0;
2750 ssl_ReleaseRecvBufLock(ss
);
2752 if (ss
->handshake
== 0) {
2755 ss
->handshake
= ssl_GatherRecord1stHandshake
;
2756 ss
->nextHandshake
= ssl2_HandleMessage
;
2761 ssl_ReleaseRecvBufLock(ss
);
2765 /* Not static because ssl2_GatherData() tests ss->nextHandshake for this value.
2767 * Called from ssl_Do1stHandshake after ssl2_BeginClientHandshake()
2770 ssl2_HandleServerHelloMessage(sslSocket
*ss
)
2777 int needed
, sidHit
, certLen
, csLen
, cidLen
, certType
, err
;
2779 PORT_Assert( ss
->opt
.noLocks
|| ssl_Have1stHandshakeLock(ss
) );
2781 if (!ss
->opt
.enableSSL2
) {
2782 PORT_SetError(SSL_ERROR_SSL2_DISABLED
);
2786 ssl_GetRecvBufLock(ss
);
2788 PORT_Assert(ss
->sec
.ci
.sid
!= 0);
2789 sid
= ss
->sec
.ci
.sid
;
2791 data
= ss
->gs
.buf
.buf
+ ss
->gs
.recordOffset
;
2792 DUMP_MSG(29, (ss
, data
, ss
->gs
.recordLen
));
2794 /* Make sure first message has some data and is the server hello message */
2795 if ((ss
->gs
.recordLen
< SSL_HL_SERVER_HELLO_HBYTES
)
2796 || (data
[0] != SSL_MT_SERVER_HELLO
)) {
2797 if ((data
[0] == SSL_MT_ERROR
) && (ss
->gs
.recordLen
== 3)) {
2798 err
= (data
[1] << 8) | data
[2];
2799 if (err
== SSL_PE_NO_CYPHERS
) {
2800 PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP
);
2809 ss
->version
= (data
[3] << 8) | data
[4];
2810 certLen
= (data
[5] << 8) | data
[6];
2811 csLen
= (data
[7] << 8) | data
[8];
2812 cidLen
= (data
[9] << 8) | data
[10];
2813 cert
= data
+ SSL_HL_SERVER_HELLO_HBYTES
;
2814 cs
= cert
+ certLen
;
2817 ("%d: SSL[%d]: server-hello, hit=%d vers=%x certLen=%d csLen=%d cidLen=%d",
2818 SSL_GETPID(), ss
->fd
, sidHit
, ss
->version
, certLen
,
2820 if (ss
->version
!= SSL_LIBRARY_VERSION_2
) {
2821 if (ss
->version
< SSL_LIBRARY_VERSION_2
) {
2822 SSL_TRC(3, ("%d: SSL[%d]: demoting self (%x) to server version (%x)",
2823 SSL_GETPID(), ss
->fd
, SSL_LIBRARY_VERSION_2
,
2826 SSL_TRC(1, ("%d: SSL[%d]: server version is %x (we are %x)",
2827 SSL_GETPID(), ss
->fd
, ss
->version
, SSL_LIBRARY_VERSION_2
));
2828 /* server claims to be newer but does not follow protocol */
2829 PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION
);
2834 if ((SSL_HL_SERVER_HELLO_HBYTES
+ certLen
+ csLen
+ cidLen
2837 /* || cidLen < SSL_CONNECTIONID_BYTES || cidLen > 32 */
2842 /* Save connection-id.
2843 ** This code only saves the first 16 byte of the connectionID.
2844 ** If the connectionID is shorter than 16 bytes, it is zero-padded.
2846 if (cidLen
< sizeof ss
->sec
.ci
.connectionID
)
2847 memset(ss
->sec
.ci
.connectionID
, 0, sizeof ss
->sec
.ci
.connectionID
);
2848 cidLen
= PR_MIN(cidLen
, sizeof ss
->sec
.ci
.connectionID
);
2849 PORT_Memcpy(ss
->sec
.ci
.connectionID
, cs
+ csLen
, cidLen
);
2851 /* See if session-id hit */
2852 needed
= CIS_HAVE_MASTER_KEY
| CIS_HAVE_FINISHED
| CIS_HAVE_VERIFY
;
2854 if (certLen
|| csLen
) {
2855 /* Uh oh - bogus server */
2856 SSL_DBG(("%d: SSL[%d]: client, huh? hit=%d certLen=%d csLen=%d",
2857 SSL_GETPID(), ss
->fd
, sidHit
, certLen
, csLen
));
2862 SSL_TRC(1, ("%d: SSL[%d]: client, using nonce for peer=0x%08x "
2864 SSL_GETPID(), ss
->fd
, ss
->sec
.ci
.peer
, ss
->sec
.ci
.port
));
2865 ss
->sec
.peerCert
= CERT_DupCertificate(sid
->peerCert
);
2866 ss
->sec
.authAlgorithm
= sid
->authAlgorithm
;
2867 ss
->sec
.authKeyBits
= sid
->authKeyBits
;
2868 ss
->sec
.keaType
= sid
->keaType
;
2869 ss
->sec
.keaKeyBits
= sid
->keaKeyBits
;
2870 rv
= ssl2_CreateSessionCypher(ss
, sid
, PR_TRUE
);
2871 if (rv
!= SECSuccess
) {
2875 if (certType
!= SSL_CT_X509_CERTIFICATE
) {
2876 PORT_SetError(SSL_ERROR_UNSUPPORTED_CERTIFICATE_TYPE
);
2880 PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP
);
2881 SSL_DBG(("%d: SSL[%d]: no cipher overlap",
2882 SSL_GETPID(), ss
->fd
));
2886 SSL_DBG(("%d: SSL[%d]: client, huh? certLen=%d csLen=%d",
2887 SSL_GETPID(), ss
->fd
, certLen
, csLen
));
2891 if (sid
->cached
!= never_cached
) {
2892 /* Forget our session-id - server didn't like it */
2893 SSL_TRC(7, ("%d: SSL[%d]: server forgot me, uncaching session-id",
2894 SSL_GETPID(), ss
->fd
));
2895 (*ss
->sec
.uncache
)(sid
);
2897 ss
->sec
.ci
.sid
= sid
= (sslSessionID
*) PORT_ZAlloc(sizeof(sslSessionID
));
2901 sid
->references
= 1;
2902 sid
->addr
= ss
->sec
.ci
.peer
;
2903 sid
->port
= ss
->sec
.ci
.port
;
2906 /* decode the server's certificate */
2907 rv
= ssl2_ClientHandleServerCert(ss
, cert
, certLen
);
2908 if (rv
!= SECSuccess
) {
2909 if (PORT_GetError() == SSL_ERROR_BAD_CERTIFICATE
) {
2910 (void) ssl2_SendErrorMessage(ss
, SSL_PE_BAD_CERTIFICATE
);
2915 /* Setup new session cipher */
2916 rv
= ssl2_ClientSetupSessionCypher(ss
, cs
, csLen
);
2917 if (rv
!= SECSuccess
) {
2918 if (PORT_GetError() == SSL_ERROR_BAD_CERTIFICATE
) {
2919 (void) ssl2_SendErrorMessage(ss
, SSL_PE_BAD_CERTIFICATE
);
2925 /* Build up final list of required elements */
2926 ss
->sec
.ci
.elements
= CIS_HAVE_MASTER_KEY
;
2927 ss
->sec
.ci
.requiredElements
= needed
;
2930 /* verify the server's certificate. if sidHit, don't check signatures */
2931 rv
= (* ss
->authCertificate
)(ss
->authCertificateArg
, ss
->fd
,
2932 (PRBool
)(!sidHit
), PR_FALSE
);
2934 if (ss
->handleBadCert
) {
2935 rv
= (*ss
->handleBadCert
)(ss
->badCertArg
, ss
->fd
);
2937 if ( rv
== SECWouldBlock
) {
2938 /* someone will handle this connection asynchronously*/
2940 SSL_DBG(("%d: SSL[%d]: go to async cert handler",
2941 SSL_GETPID(), ss
->fd
));
2942 ssl_ReleaseRecvBufLock(ss
);
2943 ssl_SetAlwaysBlock(ss
);
2944 return SECWouldBlock
;
2947 SSL_DBG(("%d: SSL[%d]: server certificate is no good: error=%d",
2948 SSL_GETPID(), ss
->fd
, PORT_GetError()));
2954 SSL_DBG(("%d: SSL[%d]: server certificate is no good: error=%d",
2955 SSL_GETPID(), ss
->fd
, PORT_GetError()));
2961 ** At this point we have a completed session key and our session
2962 ** cipher is setup and ready to go. Switch to encrypted write routine
2963 ** as all future message data is to be encrypted.
2965 ssl2_UseEncryptedSendFunc(ss
);
2967 rv
= ssl2_TryToFinish(ss
);
2968 if (rv
!= SECSuccess
)
2971 ss
->gs
.recordLen
= 0;
2973 ssl_ReleaseRecvBufLock(ss
);
2975 if (ss
->handshake
== 0) {
2979 SSL_TRC(5, ("%d: SSL[%d]: got server-hello, required=0x%d got=0x%x",
2980 SSL_GETPID(), ss
->fd
, ss
->sec
.ci
.requiredElements
,
2981 ss
->sec
.ci
.elements
));
2982 ss
->handshake
= ssl_GatherRecord1stHandshake
;
2983 ss
->nextHandshake
= ssl2_HandleVerifyMessage
;
2987 PORT_SetError(SSL_ERROR_BAD_SERVER
);
2991 ssl_ReleaseRecvBufLock(ss
);
2995 /* Sends out the initial client Hello message on the connection.
2996 * Acquires and releases the socket's xmitBufLock.
2999 ssl2_BeginClientHandshake(sslSocket
*ss
)
3004 PRUint8
*localCipherSpecs
= NULL
;
3005 unsigned int localCipherSize
;
3007 int sendLen
, sidLen
= 0;
3010 PORT_Assert( ss
->opt
.noLocks
|| ssl_Have1stHandshakeLock(ss
) );
3012 ss
->sec
.isServer
= 0;
3013 ss
->sec
.sendSequence
= 0;
3014 ss
->sec
.rcvSequence
= 0;
3015 ssl_ChooseSessionIDProcs(&ss
->sec
);
3017 if (!ss
->cipherSpecs
) {
3018 rv
= ssl2_ConstructCipherSpecs(ss
);
3019 if (rv
!= SECSuccess
)
3023 /* count the SSL2 and SSL3 enabled ciphers.
3024 * if either is zero, clear the socket's enable for that protocol.
3026 rv
= ssl2_CheckConfigSanity(ss
);
3027 if (rv
!= SECSuccess
)
3030 /* Get peer name of server */
3031 rv
= ssl_GetPeerInfo(ss
);
3035 * On some HP-UX B.11.00 systems, getpeername() occasionally
3036 * fails with ENOTCONN after a successful completion of
3037 * non-blocking connect. I found that if we do a write()
3038 * and then retry getpeername(), it will work.
3040 if (PR_GetError() == PR_NOT_CONNECTED_ERROR
) {
3042 (void) PR_Write(ss
->fd
->lower
, &dummy
, 0);
3043 rv
= ssl_GetPeerInfo(ss
);
3053 SSL_TRC(3, ("%d: SSL[%d]: sending client-hello", SSL_GETPID(), ss
->fd
));
3055 /* Try to find server in our session-id cache */
3056 if (ss
->opt
.noCache
) {
3059 sid
= ssl_LookupSID(&ss
->sec
.ci
.peer
, ss
->sec
.ci
.port
, ss
->peerID
,
3062 while (sid
) { /* this isn't really a loop */
3063 /* if we're not doing this SID's protocol any more, drop it. */
3064 if (((sid
->version
< SSL_LIBRARY_VERSION_3_0
) && !ss
->opt
.enableSSL2
) ||
3065 ((sid
->version
== SSL_LIBRARY_VERSION_3_0
) && !ss
->opt
.enableSSL3
) ||
3066 ((sid
->version
> SSL_LIBRARY_VERSION_3_0
) && !ss
->opt
.enableTLS
)) {
3067 ss
->sec
.uncache(sid
);
3072 if (ss
->opt
.enableSSL2
&& sid
->version
< SSL_LIBRARY_VERSION_3_0
) {
3073 /* If the cipher in this sid is not enabled, drop it. */
3074 for (i
= 0; i
< ss
->sizeCipherSpecs
; i
+= 3) {
3075 if (ss
->cipherSpecs
[i
] == sid
->u
.ssl2
.cipherType
)
3078 if (i
>= ss
->sizeCipherSpecs
) {
3079 ss
->sec
.uncache(sid
);
3085 sidLen
= sizeof(sid
->u
.ssl2
.sessionID
);
3086 PRINT_BUF(4, (ss
, "client, found session-id:", sid
->u
.ssl2
.sessionID
,
3088 ss
->version
= sid
->version
;
3089 PORT_Assert(!ss
->sec
.localCert
);
3090 if (ss
->sec
.localCert
) {
3091 CERT_DestroyCertificate(ss
->sec
.localCert
);
3093 ss
->sec
.localCert
= CERT_DupCertificate(sid
->localCert
);
3094 break; /* this isn't really a loop */
3098 sid
= (sslSessionID
*) PORT_ZAlloc(sizeof(sslSessionID
));
3102 sid
->references
= 1;
3103 sid
->cached
= never_cached
;
3104 sid
->addr
= ss
->sec
.ci
.peer
;
3105 sid
->port
= ss
->sec
.ci
.port
;
3106 if (ss
->peerID
!= NULL
) {
3107 sid
->peerID
= PORT_Strdup(ss
->peerID
);
3109 if (ss
->url
!= NULL
) {
3110 sid
->urlSvrName
= PORT_Strdup(ss
->url
);
3113 ss
->sec
.ci
.sid
= sid
;
3115 PORT_Assert(sid
!= NULL
);
3117 if ((sid
->version
>= SSL_LIBRARY_VERSION_3_0
|| !ss
->opt
.v2CompatibleHello
) &&
3118 (ss
->opt
.enableSSL3
|| ss
->opt
.enableTLS
)) {
3120 ss
->gs
.state
= GS_INIT
;
3121 ss
->handshake
= ssl_GatherRecord1stHandshake
;
3123 /* ssl3_SendClientHello will override this if it succeeds. */
3124 ss
->version
= SSL_LIBRARY_VERSION_3_0
;
3126 ssl_GetXmitBufLock(ss
); /***************************************/
3127 ssl_GetSSL3HandshakeLock(ss
);
3128 rv
= ssl3_SendClientHello(ss
);
3129 ssl_ReleaseSSL3HandshakeLock(ss
);
3130 ssl_ReleaseXmitBufLock(ss
); /***************************************/
3134 #if defined(NSS_ENABLE_ECC) && !defined(NSS_ECC_MORE_THAN_SUITE_B)
3135 /* ensure we don't neogtiate ECC cipher suites with SSL2 hello */
3136 ssl3_DisableECCSuites(ss
, NULL
); /* disable all ECC suites */
3137 if (ss
->cipherSpecs
!= NULL
) {
3138 PORT_Free(ss
->cipherSpecs
);
3139 ss
->cipherSpecs
= NULL
;
3140 ss
->sizeCipherSpecs
= 0;
3144 if (!ss
->cipherSpecs
) {
3145 rv
= ssl2_ConstructCipherSpecs(ss
);
3150 localCipherSpecs
= ss
->cipherSpecs
;
3151 localCipherSize
= ss
->sizeCipherSpecs
;
3153 sendLen
= SSL_HL_CLIENT_HELLO_HBYTES
+ localCipherSize
+ sidLen
+
3154 SSL_CHALLENGE_BYTES
;
3156 /* Generate challenge bytes for server */
3157 PK11_GenerateRandom(ss
->sec
.ci
.clientChallenge
, SSL_CHALLENGE_BYTES
);
3159 ssl_GetXmitBufLock(ss
); /***************************************/
3161 rv
= ssl2_GetSendBuffer(ss
, sendLen
);
3165 /* Construct client-hello message */
3166 cp
= msg
= ss
->sec
.ci
.sendBuf
.buf
;
3167 msg
[0] = SSL_MT_CLIENT_HELLO
;
3168 if ( ss
->opt
.enableTLS
) {
3169 ss
->clientHelloVersion
= SSL_LIBRARY_VERSION_3_1_TLS
;
3170 } else if ( ss
->opt
.enableSSL3
) {
3171 ss
->clientHelloVersion
= SSL_LIBRARY_VERSION_3_0
;
3173 ss
->clientHelloVersion
= SSL_LIBRARY_VERSION_2
;
3176 msg
[1] = MSB(ss
->clientHelloVersion
);
3177 msg
[2] = LSB(ss
->clientHelloVersion
);
3178 msg
[3] = MSB(localCipherSize
);
3179 msg
[4] = LSB(localCipherSize
);
3180 msg
[5] = MSB(sidLen
);
3181 msg
[6] = LSB(sidLen
);
3182 msg
[7] = MSB(SSL_CHALLENGE_BYTES
);
3183 msg
[8] = LSB(SSL_CHALLENGE_BYTES
);
3184 cp
+= SSL_HL_CLIENT_HELLO_HBYTES
;
3185 PORT_Memcpy(cp
, localCipherSpecs
, localCipherSize
);
3186 cp
+= localCipherSize
;
3188 PORT_Memcpy(cp
, sid
->u
.ssl2
.sessionID
, sidLen
);
3191 PORT_Memcpy(cp
, ss
->sec
.ci
.clientChallenge
, SSL_CHALLENGE_BYTES
);
3193 /* Send it to the server */
3194 DUMP_MSG(29, (ss
, msg
, sendLen
));
3195 ss
->handshakeBegun
= 1;
3196 rv
= (*ss
->sec
.send
)(ss
, msg
, sendLen
, 0);
3198 ssl_ReleaseXmitBufLock(ss
); /***************************************/
3204 rv
= ssl3_StartHandshakeHash(ss
, msg
, sendLen
);
3209 /* Setup to receive servers hello message */
3210 ssl_GetRecvBufLock(ss
);
3211 ss
->gs
.recordLen
= 0;
3212 ssl_ReleaseRecvBufLock(ss
);
3214 ss
->handshake
= ssl_GatherRecord1stHandshake
;
3215 ss
->nextHandshake
= ssl2_HandleServerHelloMessage
;
3219 ssl_ReleaseXmitBufLock(ss
);
3224 /************************************************************************/
3226 /* Handle the CLIENT-MASTER-KEY message.
3227 ** Acquires and releases RecvBufLock.
3228 ** Called from ssl2_HandleClientHelloMessage().
3231 ssl2_HandleClientSessionKeyMessage(sslSocket
*ss
)
3237 unsigned int keyBits
;
3242 ssl_GetRecvBufLock(ss
);
3244 data
= ss
->gs
.buf
.buf
+ ss
->gs
.recordOffset
;
3245 DUMP_MSG(29, (ss
, data
, ss
->gs
.recordLen
));
3247 if ((ss
->gs
.recordLen
< SSL_HL_CLIENT_MASTER_KEY_HBYTES
)
3248 || (data
[0] != SSL_MT_CLIENT_MASTER_KEY
)) {
3252 keyBits
= (data
[2] << 8) | data
[3];
3253 ckLen
= (data
[4] << 8) | data
[5];
3254 ekLen
= (data
[6] << 8) | data
[7];
3255 caLen
= (data
[8] << 8) | data
[9];
3257 SSL_TRC(5, ("%d: SSL[%d]: session-key, cipher=%d keyBits=%d ckLen=%d ekLen=%d caLen=%d",
3258 SSL_GETPID(), ss
->fd
, cipher
, keyBits
, ckLen
, ekLen
, caLen
));
3260 if (ss
->gs
.recordLen
<
3261 SSL_HL_CLIENT_MASTER_KEY_HBYTES
+ ckLen
+ ekLen
+ caLen
) {
3262 SSL_DBG(("%d: SSL[%d]: protocol size mismatch dataLen=%d",
3263 SSL_GETPID(), ss
->fd
, ss
->gs
.recordLen
));
3267 /* Use info from client to setup session key */
3268 rv
= ssl2_ServerSetupSessionCypher(ss
, cipher
, keyBits
,
3269 data
+ SSL_HL_CLIENT_MASTER_KEY_HBYTES
, ckLen
,
3270 data
+ SSL_HL_CLIENT_MASTER_KEY_HBYTES
+ ckLen
, ekLen
,
3271 data
+ SSL_HL_CLIENT_MASTER_KEY_HBYTES
+ ckLen
+ ekLen
, caLen
);
3272 ss
->gs
.recordLen
= 0; /* we're done with this record. */
3274 ssl_ReleaseRecvBufLock(ss
);
3276 if (rv
!= SECSuccess
) {
3279 ss
->sec
.ci
.elements
|= CIS_HAVE_MASTER_KEY
;
3280 ssl2_UseEncryptedSendFunc(ss
);
3282 /* Send server verify message now that keys are established */
3283 rv
= ssl2_SendServerVerifyMessage(ss
);
3284 if (rv
!= SECSuccess
)
3287 rv
= ssl2_TryToFinish(ss
);
3288 if (rv
!= SECSuccess
)
3290 if (ss
->handshake
== 0) {
3294 SSL_TRC(5, ("%d: SSL[%d]: server: waiting for elements=0x%d",
3295 SSL_GETPID(), ss
->fd
,
3296 ss
->sec
.ci
.requiredElements
^ ss
->sec
.ci
.elements
));
3297 ss
->handshake
= ssl_GatherRecord1stHandshake
;
3298 ss
->nextHandshake
= ssl2_HandleMessage
;
3300 return ssl2_TriggerNextMessage(ss
);
3303 ssl_ReleaseRecvBufLock(ss
);
3304 PORT_SetError(SSL_ERROR_BAD_CLIENT
);
3312 * attempt to restart the handshake after asynchronously handling
3313 * a request for the client's certificate.
3316 * cert Client cert chosen by application.
3317 * key Private key associated with cert.
3319 * XXX: need to make ssl2 and ssl3 versions of this function agree on whether
3320 * they take the reference, or bump the ref count!
3324 * Caller holds 1stHandshakeLock.
3327 ssl2_RestartHandshakeAfterCertReq(sslSocket
* ss
,
3328 CERTCertificate
* cert
,
3329 SECKEYPrivateKey
* key
)
3332 SECStatus rv
= SECSuccess
;
3335 if (ss
->version
>= SSL_LIBRARY_VERSION_3_0
)
3338 response
.data
= NULL
;
3340 /* generate error if no cert or key */
3341 if ( ( cert
== NULL
) || ( key
== NULL
) ) {
3345 /* generate signed response to the challenge */
3346 rv
= ssl2_SignResponse(ss
, key
, &response
);
3347 if ( rv
!= SECSuccess
) {
3351 /* Send response message */
3352 ret
= ssl2_SendCertificateResponseMessage(ss
, &cert
->derCert
, &response
);
3357 /* try to finish the handshake */
3358 ret
= ssl2_TryToFinish(ss
);
3363 /* done with handshake */
3364 if (ss
->handshake
== 0) {
3369 /* continue handshake */
3370 ssl_GetRecvBufLock(ss
);
3371 ss
->gs
.recordLen
= 0;
3372 ssl_ReleaseRecvBufLock(ss
);
3374 ss
->handshake
= ssl_GatherRecord1stHandshake
;
3375 ss
->nextHandshake
= ssl2_HandleMessage
;
3376 ret
= ssl2_TriggerNextMessage(ss
);
3380 /* no cert - send error */
3381 ret
= ssl2_SendErrorMessage(ss
, SSL_PE_NO_CERTIFICATE
);
3387 /* free allocated data */
3388 if ( response
.data
) {
3389 PORT_Free(response
.data
);
3396 /* restart an SSL connection that we stopped to run certificate dialogs
3397 ** XXX Need to document here how an application marks a cert to show that
3398 ** the application has accepted it (overridden CERT_VerifyCert).
3402 * Caller holds 1stHandshakeLock.
3405 ssl2_RestartHandshakeAfterServerCert(sslSocket
*ss
)
3407 int rv
= SECSuccess
;
3409 if (ss
->version
>= SSL_LIBRARY_VERSION_3_0
)
3413 ** At this point we have a completed session key and our session
3414 ** cipher is setup and ready to go. Switch to encrypted write routine
3415 ** as all future message data is to be encrypted.
3417 ssl2_UseEncryptedSendFunc(ss
);
3419 rv
= ssl2_TryToFinish(ss
);
3420 if (rv
== SECSuccess
&& ss
->handshake
!= NULL
) {
3421 /* handshake is not yet finished. */
3423 SSL_TRC(5, ("%d: SSL[%d]: got server-hello, required=0x%d got=0x%x",
3424 SSL_GETPID(), ss
->fd
, ss
->sec
.ci
.requiredElements
,
3425 ss
->sec
.ci
.elements
));
3427 ssl_GetRecvBufLock(ss
);
3428 ss
->gs
.recordLen
= 0; /* mark it all used up. */
3429 ssl_ReleaseRecvBufLock(ss
);
3431 ss
->handshake
= ssl_GatherRecord1stHandshake
;
3432 ss
->nextHandshake
= ssl2_HandleVerifyMessage
;
3439 ** Handle the initial hello message from the client
3441 ** not static because ssl2_GatherData() tests ss->nextHandshake for this value.
3444 ssl2_HandleClientHelloMessage(sslSocket
*ss
)
3447 sslServerCerts
* sc
;
3448 CERTCertificate
*serverCert
;
3453 PRUint8
*cert
= NULL
;
3455 unsigned int challengeLen
;
3463 int gotXmitBufLock
= 0;
3464 #if defined(SOLARIS) && defined(i386)
3465 volatile PRUint8 hit
;
3469 PRUint8 csImpl
[sizeof implementedCipherSuites
];
3471 PORT_Assert( ss
->opt
.noLocks
|| ssl_Have1stHandshakeLock(ss
) );
3473 sc
= ss
->serverCerts
+ kt_rsa
;
3474 serverCert
= sc
->serverCert
;
3476 ssl_GetRecvBufLock(ss
);
3479 data
= ss
->gs
.buf
.buf
+ ss
->gs
.recordOffset
;
3480 DUMP_MSG(29, (ss
, data
, ss
->gs
.recordLen
));
3482 /* Make sure first message has some data and is the client hello message */
3483 if ((ss
->gs
.recordLen
< SSL_HL_CLIENT_HELLO_HBYTES
)
3484 || (data
[0] != SSL_MT_CLIENT_HELLO
)) {
3488 /* Get peer name of client */
3489 rv
= ssl_GetPeerInfo(ss
);
3490 if (rv
!= SECSuccess
) {
3494 /* Examine version information */
3496 * See if this might be a V2 client hello asking to use the V3 protocol
3498 if ((data
[0] == SSL_MT_CLIENT_HELLO
) &&
3499 (data
[1] >= MSB(SSL_LIBRARY_VERSION_3_0
)) &&
3500 (ss
->opt
.enableSSL3
|| ss
->opt
.enableTLS
)) {
3501 rv
= ssl3_HandleV2ClientHello(ss
, data
, ss
->gs
.recordLen
);
3502 if (rv
!= SECFailure
) { /* Success */
3503 ss
->handshake
= NULL
;
3504 ss
->nextHandshake
= ssl_GatherRecord1stHandshake
;
3505 ss
->securityHandshake
= NULL
;
3506 ss
->gs
.state
= GS_INIT
;
3508 /* ssl3_HandleV3ClientHello has set ss->version,
3509 ** and has gotten us a brand new sid.
3511 ss
->sec
.ci
.sid
->version
= ss
->version
;
3513 ssl_ReleaseRecvBufLock(ss
);
3516 /* Previously, there was a test here to see if SSL2 was enabled.
3517 ** If not, an error code was set, and SECFailure was returned,
3518 ** without sending any error code to the other end of the connection.
3519 ** That test has been removed. If SSL2 has been disabled, there
3520 ** should be no SSL2 ciphers enabled, and consequently, the code
3521 ** below should send the ssl2 error message SSL_PE_NO_CYPHERS.
3522 ** We now believe this is the correct thing to do, even when SSL2
3523 ** has been explicitly disabled by the application.
3526 /* Extract info from message */
3527 ss
->version
= (data
[1] << 8) | data
[2];
3529 /* If some client thinks ssl v2 is 2.0 instead of 0.2, we'll allow it. */
3530 if (ss
->version
>= SSL_LIBRARY_VERSION_3_0
) {
3531 ss
->version
= SSL_LIBRARY_VERSION_2
;
3534 csLen
= (data
[3] << 8) | data
[4];
3535 sdLen
= (data
[5] << 8) | data
[6];
3536 challengeLen
= (data
[7] << 8) | data
[8];
3537 cs
= data
+ SSL_HL_CLIENT_HELLO_HBYTES
;
3539 challenge
= sd
+ sdLen
;
3540 PRINT_BUF(7, (ss
, "server, client session-id value:", sd
, sdLen
));
3542 if (!csLen
|| (csLen
% 3) != 0 ||
3543 (sdLen
!= 0 && sdLen
!= SSL2_SESSIONID_BYTES
) ||
3544 challengeLen
< SSL_MIN_CHALLENGE_BYTES
||
3545 challengeLen
> SSL_MAX_CHALLENGE_BYTES
||
3546 (unsigned)ss
->gs
.recordLen
!=
3547 SSL_HL_CLIENT_HELLO_HBYTES
+ csLen
+ sdLen
+ challengeLen
) {
3548 SSL_DBG(("%d: SSL[%d]: bad client hello message, len=%d should=%d",
3549 SSL_GETPID(), ss
->fd
, ss
->gs
.recordLen
,
3550 SSL_HL_CLIENT_HELLO_HBYTES
+csLen
+sdLen
+challengeLen
));
3554 SSL_TRC(3, ("%d: SSL[%d]: client version is %x",
3555 SSL_GETPID(), ss
->fd
, ss
->version
));
3556 if (ss
->version
!= SSL_LIBRARY_VERSION_2
) {
3557 if (ss
->version
> SSL_LIBRARY_VERSION_2
) {
3559 ** Newer client than us. Things are ok because new clients
3560 ** are required to be backwards compatible with old servers.
3561 ** Change version number to our version number so that client
3564 ss
->version
= SSL_LIBRARY_VERSION_2
;
3566 SSL_TRC(1, ("%d: SSL[%d]: client version is %x (we are %x)",
3567 SSL_GETPID(), ss
->fd
, ss
->version
, SSL_LIBRARY_VERSION_2
));
3568 PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION
);
3573 /* Qualify cipher specs before returning them to client */
3574 csLen
= ssl2_QualifyCypherSpecs(ss
, cs
, csLen
);
3576 /* no overlap, send client our list of supported SSL v2 ciphers. */
3578 csLen
= sizeof implementedCipherSuites
;
3579 PORT_Memcpy(cs
, implementedCipherSuites
, csLen
);
3580 csLen
= ssl2_QualifyCypherSpecs(ss
, cs
, csLen
);
3582 /* We don't support any SSL v2 ciphers! */
3583 ssl2_SendErrorMessage(ss
, SSL_PE_NO_CYPHERS
);
3584 PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP
);
3587 /* Since this handhsake is going to fail, don't cache it. */
3588 ss
->opt
.noCache
= 1;
3591 /* Squirrel away the challenge for later */
3592 PORT_Memcpy(ss
->sec
.ci
.clientChallenge
, challenge
, challengeLen
);
3594 /* Examine message and see if session-id is good */
3595 ss
->sec
.ci
.elements
= 0;
3596 if (sdLen
> 0 && !ss
->opt
.noCache
) {
3597 SSL_TRC(7, ("%d: SSL[%d]: server, lookup client session-id for 0x%08x%08x%08x%08x",
3598 SSL_GETPID(), ss
->fd
, ss
->sec
.ci
.peer
.pr_s6_addr32
[0],
3599 ss
->sec
.ci
.peer
.pr_s6_addr32
[1],
3600 ss
->sec
.ci
.peer
.pr_s6_addr32
[2],
3601 ss
->sec
.ci
.peer
.pr_s6_addr32
[3]));
3602 sid
= (*ssl_sid_lookup
)(&ss
->sec
.ci
.peer
, sd
, sdLen
, ss
->dbHandle
);
3607 /* Got a good session-id. Short cut! */
3608 SSL_TRC(1, ("%d: SSL[%d]: server, using session-id for 0x%08x (age=%d)",
3609 SSL_GETPID(), ss
->fd
, ss
->sec
.ci
.peer
,
3610 ssl_Time() - sid
->creationTime
));
3611 PRINT_BUF(1, (ss
, "session-id value:", sd
, sdLen
));
3612 ss
->sec
.ci
.sid
= sid
;
3613 ss
->sec
.ci
.elements
= CIS_HAVE_MASTER_KEY
;
3618 ss
->sec
.authAlgorithm
= sid
->authAlgorithm
;
3619 ss
->sec
.authKeyBits
= sid
->authKeyBits
;
3620 ss
->sec
.keaType
= sid
->keaType
;
3621 ss
->sec
.keaKeyBits
= sid
->keaKeyBits
;
3623 rv
= ssl2_CreateSessionCypher(ss
, sid
, PR_FALSE
);
3624 if (rv
!= SECSuccess
) {
3628 SECItem
* derCert
= &serverCert
->derCert
;
3630 SSL_TRC(7, ("%d: SSL[%d]: server, lookup nonce missed",
3631 SSL_GETPID(), ss
->fd
));
3637 sid
= (sslSessionID
*) PORT_ZAlloc(sizeof(sslSessionID
));
3641 sid
->references
= 1;
3642 sid
->addr
= ss
->sec
.ci
.peer
;
3643 sid
->port
= ss
->sec
.ci
.port
;
3645 /* Invent a session-id */
3646 ss
->sec
.ci
.sid
= sid
;
3647 PK11_GenerateRandom(sid
->u
.ssl2
.sessionID
+2, SSL2_SESSIONID_BYTES
-2);
3650 sid
->u
.ssl2
.sessionID
[0] = MSB(pid
);
3651 sid
->u
.ssl2
.sessionID
[1] = LSB(pid
);
3652 cert
= derCert
->data
;
3653 certLen
= derCert
->len
;
3655 /* pretend that server sids remember the local cert. */
3656 PORT_Assert(!sid
->localCert
);
3657 if (sid
->localCert
) {
3658 CERT_DestroyCertificate(sid
->localCert
);
3660 sid
->localCert
= CERT_DupCertificate(serverCert
);
3662 ss
->sec
.authAlgorithm
= ssl_sign_rsa
;
3663 ss
->sec
.keaType
= ssl_kea_rsa
;
3664 ss
->sec
.keaKeyBits
= \
3665 ss
->sec
.authKeyBits
= ss
->serverCerts
[kt_rsa
].serverKeyBits
;
3668 /* server sids don't remember the local cert, so whether we found
3669 ** a sid or not, just "remember" we used the rsa server cert.
3671 if (ss
->sec
.localCert
) {
3672 CERT_DestroyCertificate(ss
->sec
.localCert
);
3674 ss
->sec
.localCert
= CERT_DupCertificate(serverCert
);
3676 /* Build up final list of required elements */
3677 ss
->sec
.ci
.requiredElements
= CIS_HAVE_MASTER_KEY
| CIS_HAVE_FINISHED
;
3678 if (ss
->opt
.requestCertificate
) {
3679 ss
->sec
.ci
.requiredElements
|= CIS_HAVE_CERTIFICATE
;
3681 ss
->sec
.ci
.sentElements
= 0;
3683 /* Send hello message back to client */
3684 sendLen
= SSL_HL_SERVER_HELLO_HBYTES
+ certLen
+ csLen
3685 + SSL_CONNECTIONID_BYTES
;
3687 ssl_GetXmitBufLock(ss
); gotXmitBufLock
= 1;
3688 rv
= ssl2_GetSendBuffer(ss
, sendLen
);
3689 if (rv
!= SECSuccess
) {
3693 SSL_TRC(3, ("%d: SSL[%d]: sending server-hello (%d)",
3694 SSL_GETPID(), ss
->fd
, sendLen
));
3696 msg
= ss
->sec
.ci
.sendBuf
.buf
;
3697 msg
[0] = SSL_MT_SERVER_HELLO
;
3699 msg
[2] = SSL_CT_X509_CERTIFICATE
;
3700 msg
[3] = MSB(ss
->version
);
3701 msg
[4] = LSB(ss
->version
);
3702 msg
[5] = MSB(certLen
);
3703 msg
[6] = LSB(certLen
);
3704 msg
[7] = MSB(csLen
);
3705 msg
[8] = LSB(csLen
);
3706 msg
[9] = MSB(SSL_CONNECTIONID_BYTES
);
3707 msg
[10] = LSB(SSL_CONNECTIONID_BYTES
);
3709 PORT_Memcpy(msg
+SSL_HL_SERVER_HELLO_HBYTES
, cert
, certLen
);
3712 PORT_Memcpy(msg
+SSL_HL_SERVER_HELLO_HBYTES
+certLen
, cs
, csLen
);
3714 PORT_Memcpy(msg
+SSL_HL_SERVER_HELLO_HBYTES
+certLen
+csLen
,
3715 ss
->sec
.ci
.connectionID
, SSL_CONNECTIONID_BYTES
);
3717 DUMP_MSG(29, (ss
, msg
, sendLen
));
3719 ss
->handshakeBegun
= 1;
3720 sent
= (*ss
->sec
.send
)(ss
, msg
, sendLen
, 0);
3724 ssl_ReleaseXmitBufLock(ss
); gotXmitBufLock
= 0;
3726 ss
->gs
.recordLen
= 0;
3727 ss
->handshake
= ssl_GatherRecord1stHandshake
;
3729 /* Old SID Session key is good. Go encrypted */
3730 ssl2_UseEncryptedSendFunc(ss
);
3732 /* Send server verify message now that keys are established */
3733 rv
= ssl2_SendServerVerifyMessage(ss
);
3734 if (rv
!= SECSuccess
)
3737 ss
->nextHandshake
= ssl2_HandleMessage
;
3738 ssl_ReleaseRecvBufLock(ss
);
3739 rv
= ssl2_TriggerNextMessage(ss
);
3742 ss
->nextHandshake
= ssl2_HandleClientSessionKeyMessage
;
3743 ssl_ReleaseRecvBufLock(ss
);
3747 PORT_SetError(SSL_ERROR_BAD_CLIENT
);
3751 if (gotXmitBufLock
) {
3752 ssl_ReleaseXmitBufLock(ss
); gotXmitBufLock
= 0;
3754 SSL_TRC(10, ("%d: SSL[%d]: server, wait for client-hello lossage",
3755 SSL_GETPID(), ss
->fd
));
3756 ssl_ReleaseRecvBufLock(ss
);
3761 ssl2_BeginServerHandshake(sslSocket
*ss
)
3764 sslServerCerts
* rsaAuth
= ss
->serverCerts
+ kt_rsa
;
3766 ss
->sec
.isServer
= 1;
3767 ssl_ChooseSessionIDProcs(&ss
->sec
);
3768 ss
->sec
.sendSequence
= 0;
3769 ss
->sec
.rcvSequence
= 0;
3771 /* don't turn on SSL2 if we don't have an RSA key and cert */
3772 if (!rsaAuth
->serverKeyPair
|| !rsaAuth
->SERVERKEY
||
3773 !rsaAuth
->serverCert
) {
3774 ss
->opt
.enableSSL2
= PR_FALSE
;
3777 if (!ss
->cipherSpecs
) {
3778 rv
= ssl2_ConstructCipherSpecs(ss
);
3779 if (rv
!= SECSuccess
)
3783 /* count the SSL2 and SSL3 enabled ciphers.
3784 * if either is zero, clear the socket's enable for that protocol.
3786 rv
= ssl2_CheckConfigSanity(ss
);
3787 if (rv
!= SECSuccess
)
3791 ** Generate connection-id. Always do this, even if things fail
3792 ** immediately. This way the random number generator is always
3793 ** rolling around, every time we get a connection.
3795 PK11_GenerateRandom(ss
->sec
.ci
.connectionID
,
3796 sizeof(ss
->sec
.ci
.connectionID
));
3798 ss
->gs
.recordLen
= 0;
3799 ss
->handshake
= ssl_GatherRecord1stHandshake
;
3800 ss
->nextHandshake
= ssl2_HandleClientHelloMessage
;
3807 /* This function doesn't really belong in this file.
3808 ** It's here to keep AIX compilers from optimizing it away,
3809 ** and not including it in the DSO.
3813 extern const char __nss_ssl_rcsid
[];
3814 extern const char __nss_ssl_sccsid
[];
3817 NSSSSL_VersionCheck(const char *importedVersion
)
3820 * This is the secret handshake algorithm.
3822 * This release has a simple version compatibility
3823 * check algorithm. This release is not backward
3824 * compatible with previous major releases. It is
3825 * not compatible with future major, minor, or
3828 volatile char c
; /* force a reference that won't get optimized away */
3830 c
= __nss_ssl_rcsid
[0] + __nss_ssl_sccsid
[0];
3831 return NSS_VersionCheck(importedVersion
);