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.28.2.6 2006/11/14 01:12:08 wtchang%redhat.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)
1584
PRUint8 * kbuf = 0; /* buffer for RSA decrypted data. */
1585
unsigned int el1; /* length of RSA decrypted data in kbuf */
1586
unsigned int keySize;
1587
unsigned int modulusLen;
1589
PRUint8 mkbuf[SSL_MAX_MASTER_KEY_BYTES];
1590
sslServerCerts * sc = ss->serverCerts + kt_rsa;
1592
PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) );
1593
PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
1594
PORT_Assert((sc->SERVERKEY != 0));
1595
PORT_Assert((ss->sec.ci.sid != 0));
1596
sid = ss->sec.ci.sid;
1598
keySize = (keyBits + 7) >> 3;
1599
/* Is the message just way too big? */
1600
if (keySize > SSL_MAX_MASTER_KEY_BYTES) {
1602
SSL_DBG(("%d: SSL[%d]: keySize=%d ckLen=%d max session key size=%d",
1603
SSL_GETPID(), ss->fd, keySize, ckLen,
1604
SSL_MAX_MASTER_KEY_BYTES));
1605
PORT_SetError(SSL_ERROR_BAD_CLIENT);
1610
/* Trying to cut down on all these switch statements that should be tables.
1611
* So, test cipherType once, here, and then use tables below.
1614
case SSL_CK_RC4_128_EXPORT40_WITH_MD5:
1615
case SSL_CK_RC4_128_WITH_MD5:
1616
case SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5:
1617
case SSL_CK_RC2_128_CBC_WITH_MD5:
1618
case SSL_CK_DES_64_CBC_WITH_MD5:
1619
case SSL_CK_DES_192_EDE3_CBC_WITH_MD5:
1623
SSL_DBG(("%d: SSL[%d]: ssl2_ServerSetupSessionCypher: unknown cipher=%d",
1624
SSL_GETPID(), ss->fd, cipher));
1625
PORT_SetError(SSL_ERROR_BAD_CLIENT);
1629
/* For export ciphers, make sure they didn't send too much key data. */
1630
if (ckLen != ssl_Specs[cipher].pubLen) {
1631
SSL_DBG(("%d: SSL[%d]: odd secret key size, keySize=%d ckLen=%d!",
1632
SSL_GETPID(), ss->fd, keySize, ckLen));
1633
/* Somebody tried to sneak by a strange secret key */
1634
PORT_SetError(SSL_ERROR_BAD_CLIENT);
1638
/* allocate the buffer to hold the decrypted portion of the key. */
1639
/* XXX Haven't done any range check on ekLen. */
1640
kbuf = (PRUint8*) PORT_Alloc(ekLen);
1646
** Decrypt encrypted half of the key. Note that encrypted half has
1647
** been made to match the modulus size of our public key using
1648
** PKCS#1. keySize is the real size of the data that is interesting.
1649
** NOTE: PK11_PubDecryptRaw will barf on a non-RSA key. This is
1650
** desired behavior here.
1652
rv = PK11_PubDecryptRaw(sc->SERVERKEY, kbuf, &el1, ekLen, ek, ekLen);
1653
if (rv != SECSuccess)
1656
modulusLen = PK11_GetPrivateModulusLen(sc->SERVERKEY);
1657
if (modulusLen == -1) {
1658
/* If the key was really bad, then PK11_pubDecryptRaw
1659
* would have failed, therefore the we must assume that the card
1660
* is just being a pain and not giving us the modulus... but it
1661
* should be the same size as the encrypted key length, so use it
1662
* and keep cranking */
1665
/* Is the length of the decrypted data (el1) the expected value? */
1666
if (modulusLen != el1)
1669
/* Cheaply verify that PKCS#1 was used to format the encryption block */
1670
kk = kbuf + modulusLen - (keySize - ckLen);
1671
if ((kbuf[0] != 0x00) || (kbuf[1] != 0x02) || (kk[-1] != 0x00)) {
1673
SSL_DBG(("%d: SSL[%d]: strange encryption block",
1674
SSL_GETPID(), ss->fd));
1675
PORT_SetError(SSL_ERROR_BAD_CLIENT);
1679
/* Make sure we're not subject to a version rollback attack. */
1680
if (ss->opt.enableSSL3 || ss->opt.enableTLS) {
1681
PRUint8 threes[8] = { 0x03, 0x03, 0x03, 0x03,
1682
0x03, 0x03, 0x03, 0x03 };
1684
if (PORT_Memcmp(kk - 8 - 1, threes, 8) == 0) {
1685
PORT_SetError(SSL_ERROR_BAD_CLIENT);
1691
/* Defense against the Bleichenbacher attack.
1692
* Provide the client with NO CLUES that the decrypted master key
1693
* was erroneous. Don't send any error messages.
1694
* Instead, Generate a completely bogus master key .
1696
PK11_GenerateRandom(kbuf, ekLen);
1698
kk = kbuf + ekLen - (keySize-ckLen);
1703
** Construct master key out of the pieces.
1706
PORT_Memcpy(mkbuf, ck, ckLen);
1708
PORT_Memcpy(mkbuf+ckLen, kk, keySize-ckLen);
1710
/* Fill in session-id */
1711
rv = ssl2_FillInSID(sid, cipher, mkbuf, keySize, ca, caLen,
1712
keyBits, keyBits - (ckLen<<3),
1713
ss->sec.authAlgorithm, ss->sec.authKeyBits,
1714
ss->sec.keaType, ss->sec.keaKeyBits);
1715
if (rv != SECSuccess) {
1719
/* Create session ciphers */
1720
rv = ssl2_CreateSessionCypher(ss, sid, PR_FALSE);
1721
if (rv != SECSuccess) {
1725
SSL_TRC(1, ("%d: SSL[%d]: server, using %s cipher, clear=%d total=%d",
1726
SSL_GETPID(), ss->fd, ssl_cipherName[cipher],
1727
ckLen<<3, keySize<<3));
1739
/************************************************************************/
1742
** Rewrite the incoming cipher specs, comparing to list of specs we support,
1743
** (ss->cipherSpecs) and eliminating anything we don't support
1745
* Note: Our list may contain SSL v3 ciphers.
1746
* We MUST NOT match on any of those.
1747
* Fortunately, this is easy to detect because SSLv3 ciphers have zero
1748
* in the first byte, and none of the SSLv2 ciphers do.
1750
* Called from ssl2_HandleClientHelloMessage().
1751
* Returns the number of bytes of "qualified cipher specs",
1752
* which is typically a multiple of 3, but will be zero if there are none.
1755
ssl2_QualifyCypherSpecs(sslSocket *ss,
1756
PRUint8 * cs, /* cipher specs in client hello msg. */
1764
PRUint8 qualifiedSpecs[ssl2_NUM_SUITES_IMPLEMENTED * 3];
1766
PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) );
1767
PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
1769
if (!ss->cipherSpecs) {
1770
SECStatus rv = ssl2_ConstructCipherSpecs(ss);
1771
if (rv != SECSuccess || !ss->cipherSpecs)
1775
PRINT_BUF(10, (ss, "specs from client:", cs, csLen));
1776
qs = qualifiedSpecs;
1777
ms = ss->cipherSpecs;
1778
for (mc = ss->sizeCipherSpecs; mc > 0; mc -= 3, ms += 3) {
1781
for (hs = cs, hc = csLen; hc > 0; hs += 3, hc -= 3) {
1782
if ((hs[0] == ms[0]) &&
1785
/* Copy this cipher spec into the "keep" section */
1794
hc = qs - qualifiedSpecs;
1795
PRINT_BUF(10, (ss, "qualified specs from client:", qualifiedSpecs, hc));
1796
PORT_Memcpy(cs, qualifiedSpecs, hc);
1801
** Pick the best cipher we can find, given the array of server cipher
1802
** specs. Returns cipher number (e.g. SSL_CK_*), or -1 for no overlap.
1803
** If succesful, stores the master key size (bytes) in *pKeyLen.
1805
** This is correct only for the client side, but presently
1806
** this function is only called from
1807
** ssl2_ClientSetupSessionCypher() <- ssl2_HandleServerHelloMessage()
1809
** Note that most servers only return a single cipher suite in their
1810
** ServerHello messages. So, the code below for finding the "best" cipher
1811
** suite usually has only one choice. The client and server should send
1812
** their cipher suite lists sorted in descending order by preference.
1815
ssl2_ChooseSessionCypher(sslSocket *ss,
1816
int hc, /* number of cs's in hs. */
1817
PRUint8 * hs, /* server hello's cipher suites. */
1818
int * pKeyLen) /* out: sym key size in bytes. */
1823
int bestRealKeySize;
1828
const PRUint8 * preferred;
1829
static const PRUint8 noneSuch[3] = { 0, 0, 0 };
1831
PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) );
1832
PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
1834
if (!ss->cipherSpecs) {
1835
SECStatus rv = ssl2_ConstructCipherSpecs(ss);
1836
if (rv != SECSuccess || !ss->cipherSpecs)
1840
if (!ss->preferredCipher) {
1841
unsigned int allowed = ss->allowedByPolicy & ss->chosenPreference &
1844
preferred = implementedCipherSuites;
1845
for (i = ssl2_NUM_SUITES_IMPLEMENTED; i > 0; --i) {
1846
if (0 != (allowed & (1U << preferred[0]))) {
1847
ss->preferredCipher = preferred;
1854
preferred = ss->preferredCipher ? ss->preferredCipher : noneSuch;
1856
** Scan list of ciphers recieved from peer and look for a match in
1858
* Note: Our list may contain SSL v3 ciphers.
1859
* We MUST NOT match on any of those.
1860
* Fortunately, this is easy to detect because SSLv3 ciphers have zero
1861
* in the first byte, and none of the SSLv2 ciphers do.
1863
bestKeySize = bestRealKeySize = 0;
1866
for (i = 0, ms = ss->cipherSpecs; i < ss->sizeCipherSpecs; i += 3, ms += 3) {
1867
if ((hs[0] == preferred[0]) &&
1868
(hs[1] == preferred[1]) &&
1869
(hs[2] == preferred[2]) &&
1871
/* Pick this cipher immediately! */
1872
*pKeyLen = (((hs[1] << 8) | hs[2]) + 7) >> 3;
1875
if ((hs[0] == ms[0]) && (hs[1] == ms[1]) && (hs[2] == ms[2]) &&
1879
/* Use secret keySize to determine which cipher is best */
1880
realKeySize = (hs[1] << 8) | hs[2];
1882
case SSL_CK_RC4_128_EXPORT40_WITH_MD5:
1883
case SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5:
1887
keySize = realKeySize;
1890
if (keySize > bestKeySize) {
1892
bestKeySize = keySize;
1893
bestRealKeySize = realKeySize;
1899
if (bestCypher < 0) {
1901
** No overlap between server and client. Re-examine server list
1902
** to see what kind of ciphers it does support so that we can set
1903
** the error code appropriately.
1905
if ((ohs[0] == SSL_CK_RC4_128_WITH_MD5) ||
1906
(ohs[0] == SSL_CK_RC2_128_CBC_WITH_MD5)) {
1907
PORT_SetError(SSL_ERROR_US_ONLY_SERVER);
1908
} else if ((ohs[0] == SSL_CK_RC4_128_EXPORT40_WITH_MD5) ||
1909
(ohs[0] == SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5)) {
1910
PORT_SetError(SSL_ERROR_EXPORT_ONLY_SERVER);
1912
PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
1914
SSL_DBG(("%d: SSL[%d]: no cipher overlap", SSL_GETPID(), ss->fd));
1917
*pKeyLen = (bestRealKeySize + 7) >> 3;
1925
ssl2_ClientHandleServerCert(sslSocket *ss, PRUint8 *certData, int certLen)
1927
CERTCertificate *cert = NULL;
1930
certItem.data = certData;
1931
certItem.len = certLen;
1933
/* decode the certificate */
1934
cert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL,
1938
SSL_DBG(("%d: SSL[%d]: decode of server certificate fails",
1939
SSL_GETPID(), ss->fd));
1940
PORT_SetError(SSL_ERROR_BAD_CERTIFICATE);
1946
if (ssl_trace >= 1) {
1949
issuer = CERT_NameToAscii(&cert->issuer);
1950
subject = CERT_NameToAscii(&cert->subject);
1951
SSL_TRC(1,("%d: server certificate issuer: '%s'",
1952
SSL_GETPID(), issuer ? issuer : "OOPS"));
1953
SSL_TRC(1,("%d: server name: '%s'",
1954
SSL_GETPID(), subject ? subject : "OOPS"));
1961
ss->sec.peerCert = cert;
1967
* Format one block of data for public/private key encryption using
1968
* the rules defined in PKCS #1. SSL2 does this itself to handle the
1969
* rollback detection.
1971
#define RSA_BLOCK_MIN_PAD_LEN 8
1972
#define RSA_BLOCK_FIRST_OCTET 0x00
1973
#define RSA_BLOCK_AFTER_PAD_OCTET 0x00
1974
#define RSA_BLOCK_PUBLIC_OCTET 0x02
1976
ssl_FormatSSL2Block(unsigned modulusLen, SECItem *data)
1978
unsigned char *block;
1984
PORT_Assert (data->len <= (modulusLen - (3 + RSA_BLOCK_MIN_PAD_LEN)));
1985
block = (unsigned char *) PORT_Alloc(modulusLen);
1992
* All RSA blocks start with two octets:
1995
*bp++ = RSA_BLOCK_FIRST_OCTET;
1996
*bp++ = RSA_BLOCK_PUBLIC_OCTET;
1999
* 0x00 || BT || Pad || 0x00 || ActualData
2000
* 1 1 padLen 1 data->len
2001
* Pad is all non-zero random bytes.
2003
padLen = modulusLen - data->len - 3;
2004
PORT_Assert (padLen >= RSA_BLOCK_MIN_PAD_LEN);
2005
rv = PK11_GenerateRandom(bp, padLen);
2006
if (rv == SECFailure) goto loser;
2007
/* replace all the 'zero' bytes */
2008
for (i = 0; i < padLen; i++) {
2009
while (bp[i] == RSA_BLOCK_AFTER_PAD_OCTET) {
2010
rv = PK11_GenerateRandom(bp+i, 1);
2011
if (rv == SECFailure) goto loser;
2015
*bp++ = RSA_BLOCK_AFTER_PAD_OCTET;
2016
PORT_Memcpy (bp, data->data, data->len);
2020
if (block) PORT_Free(block);
2025
** Given the server's public key and cipher specs, generate a session key
2026
** that is ready to use for encrypting/decrypting the byte stream. At
2027
** the same time, generate the SSL_MT_CLIENT_MASTER_KEY message and
2028
** send it to the server.
2030
** Called from ssl2_HandleServerHelloMessage()
2033
ssl2_ClientSetupSessionCypher(sslSocket *ss, PRUint8 *cs, int csLen)
2036
PRUint8 * ca; /* points to iv data, or NULL if none. */
2037
PRUint8 * ekbuf = 0;
2038
CERTCertificate * cert = 0;
2039
SECKEYPublicKey * serverKey = 0;
2040
unsigned modulusLen = 0;
2043
int keyLen; /* cipher symkey size in bytes. */
2044
int ckLen; /* publicly reveal this many bytes of key. */
2045
int caLen; /* length of IV data at *ca. */
2048
unsigned char *eblock; /* holds unencrypted PKCS#1 formatted key. */
2049
SECItem rek; /* holds portion of symkey to be encrypted. */
2051
PRUint8 keyData[SSL_MAX_MASTER_KEY_BYTES];
2054
PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) );
2058
sid = ss->sec.ci.sid;
2059
PORT_Assert(sid != 0);
2061
cert = ss->sec.peerCert;
2063
serverKey = CERT_ExtractPublicKey(cert);
2065
SSL_DBG(("%d: SSL[%d]: extract public key failed: error=%d",
2066
SSL_GETPID(), ss->fd, PORT_GetError()));
2067
PORT_SetError(SSL_ERROR_BAD_CERTIFICATE);
2072
ss->sec.authAlgorithm = ssl_sign_rsa;
2073
ss->sec.keaType = ssl_kea_rsa;
2074
ss->sec.keaKeyBits = \
2075
ss->sec.authKeyBits = SECKEY_PublicKeyStrengthInBits(serverKey);
2077
/* Choose a compatible cipher with the server */
2079
cipher = ssl2_ChooseSessionCypher(ss, nc, cs, &keyLen);
2081
/* ssl2_ChooseSessionCypher has set error code. */
2082
ssl2_SendErrorMessage(ss, SSL_PE_NO_CYPHERS);
2086
/* Generate the random keys */
2087
PK11_GenerateRandom(keyData, sizeof(keyData));
2090
** Next, carve up the keys into clear and encrypted portions. The
2091
** clear data is taken from the start of keyData and the encrypted
2092
** portion from the remainder. Note that each of these portions is
2093
** carved in half, one half for the read-key and one for the
2098
/* We know that cipher is a legit value here, because
2099
* ssl2_ChooseSessionCypher doesn't return bogus values.
2101
ckLen = ssl_Specs[cipher].pubLen; /* cleartext key length. */
2102
caLen = ssl_Specs[cipher].ivLen; /* IV length. */
2104
PORT_Assert(sizeof iv >= caLen);
2105
PK11_GenerateRandom(iv, caLen);
2109
/* Fill in session-id */
2110
rv = ssl2_FillInSID(sid, cipher, keyData, keyLen,
2111
ca, caLen, keyLen << 3, (keyLen - ckLen) << 3,
2112
ss->sec.authAlgorithm, ss->sec.authKeyBits,
2113
ss->sec.keaType, ss->sec.keaKeyBits);
2114
if (rv != SECSuccess) {
2118
SSL_TRC(1, ("%d: SSL[%d]: client, using %s cipher, clear=%d total=%d",
2119
SSL_GETPID(), ss->fd, ssl_cipherName[cipher],
2120
ckLen<<3, keyLen<<3));
2122
/* Now setup read and write ciphers */
2123
rv = ssl2_CreateSessionCypher(ss, sid, PR_TRUE);
2124
if (rv != SECSuccess) {
2129
** Fill in the encryption buffer with some random bytes. Then
2130
** copy in the portion of the session key we are encrypting.
2132
modulusLen = SECKEY_PublicKeyStrength(serverKey);
2133
rek.data = keyData + ckLen;
2134
rek.len = keyLen - ckLen;
2135
eblock = ssl_FormatSSL2Block(modulusLen, &rek);
2139
/* Set up the padding for version 2 rollback detection. */
2140
/* XXX We should really use defines here */
2141
if (ss->opt.enableSSL3 || ss->opt.enableTLS) {
2142
PORT_Assert((modulusLen - rek.len) > 12);
2143
PORT_Memset(eblock + modulusLen - rek.len - 8 - 1, 0x03, 8);
2145
ekbuf = (PRUint8*) PORT_Alloc(modulusLen);
2148
PRINT_BUF(10, (ss, "master key encryption block:",
2149
eblock, modulusLen));
2151
/* Encrypt ekitem */
2152
rv = PK11_PubEncryptRaw(serverKey, ekbuf, eblock, modulusLen,
2157
/* Now we have everything ready to send */
2158
rv = ssl2_SendSessionKeyMessage(ss, cipher, keyLen << 3, ca, caLen,
2159
keyData, ckLen, ekbuf, modulusLen);
2160
if (rv != SECSuccess) {
2171
PORT_Memset(keyData, 0, sizeof(keyData));
2172
PORT_ZFree(ekbuf, modulusLen);
2173
PORT_ZFree(eblock, modulusLen);
2174
SECKEY_DestroyPublicKey(serverKey);
2178
/************************************************************************/
2181
* Called from ssl2_HandleMessage in response to SSL_MT_SERVER_FINISHED message.
2182
* Caller holds recvBufLock and handshakeLock
2185
ssl2_ClientRegSessionID(sslSocket *ss, PRUint8 *s)
2187
sslSessionID *sid = ss->sec.ci.sid;
2189
/* Record entry in nonce cache */
2190
if (sid->peerCert == NULL) {
2191
PORT_Memcpy(sid->u.ssl2.sessionID, s, sizeof(sid->u.ssl2.sessionID));
2192
sid->peerCert = CERT_DupCertificate(ss->sec.peerCert);
2195
if (!ss->opt.noCache)
2196
(*ss->sec.cache)(sid);
2199
/* Called from ssl2_HandleMessage() */
2201
ssl2_TriggerNextMessage(sslSocket *ss)
2205
PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) );
2207
if ((ss->sec.ci.requiredElements & CIS_HAVE_CERTIFICATE) &&
2208
!(ss->sec.ci.sentElements & CIS_HAVE_CERTIFICATE)) {
2209
ss->sec.ci.sentElements |= CIS_HAVE_CERTIFICATE;
2210
rv = ssl2_SendCertificateRequestMessage(ss);
2216
/* See if it's time to send our finished message, or if the handshakes are
2217
** complete. Send finished message if appropriate.
2218
** Returns SECSuccess unless anything goes wrong.
2220
** Called from ssl2_HandleMessage,
2221
** ssl2_HandleVerifyMessage
2222
** ssl2_HandleServerHelloMessage
2223
** ssl2_HandleClientSessionKeyMessage
2224
** ssl2_RestartHandshakeAfterCertReq
2225
** ssl2_RestartHandshakeAfterServerCert
2228
ssl2_TryToFinish(sslSocket *ss)
2233
PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) );
2235
e = ss->sec.ci.elements;
2236
ef = e | CIS_HAVE_FINISHED;
2237
if ((ef & ss->sec.ci.requiredElements) == ss->sec.ci.requiredElements) {
2238
if (ss->sec.isServer) {
2239
/* Send server finished message if we already didn't */
2240
rv = ssl2_SendServerFinishedMessage(ss);
2242
/* Send client finished message if we already didn't */
2243
rv = ssl2_SendClientFinishedMessage(ss);
2245
if (rv != SECSuccess) {
2248
if ((e & ss->sec.ci.requiredElements) == ss->sec.ci.requiredElements) {
2249
/* Totally finished */
2258
** Called from ssl2_HandleRequestCertificate
2259
** ssl2_RestartHandshakeAfterCertReq
2262
ssl2_SignResponse(sslSocket *ss,
2263
SECKEYPrivateKey *key,
2266
SGNContext * sgn = NULL;
2267
PRUint8 * challenge;
2269
SECStatus rv = SECFailure;
2271
PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) );
2273
challenge = ss->sec.ci.serverChallenge;
2274
len = ss->sec.ci.serverChallengeLen;
2276
/* Sign the expected data... */
2277
sgn = SGN_NewContext(SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION,key);
2280
rv = SGN_Begin(sgn);
2281
if (rv != SECSuccess)
2283
rv = SGN_Update(sgn, ss->sec.ci.readKey, ss->sec.ci.keySize);
2284
if (rv != SECSuccess)
2286
rv = SGN_Update(sgn, ss->sec.ci.writeKey, ss->sec.ci.keySize);
2287
if (rv != SECSuccess)
2289
rv = SGN_Update(sgn, challenge, len);
2290
if (rv != SECSuccess)
2292
rv = SGN_Update(sgn, ss->sec.peerCert->derCert.data,
2293
ss->sec.peerCert->derCert.len);
2294
if (rv != SECSuccess)
2296
rv = SGN_End(sgn, response);
2297
if (rv != SECSuccess)
2301
SGN_DestroyContext(sgn, PR_TRUE);
2302
return rv == SECSuccess ? SECSuccess : SECFailure;
2306
** Try to handle a request-certificate message. Get client's certificate
2307
** and private key and sign a message for the server to see.
2308
** Caller must hold handshakeLock
2310
** Called from ssl2_HandleMessage().
2313
ssl2_HandleRequestCertificate(sslSocket *ss)
2315
CERTCertificate * cert = NULL; /* app-selected client cert. */
2316
SECKEYPrivateKey *key = NULL; /* priv key for cert. */
2324
* These things all need to be initialized before we can "goto loser".
2326
response.data = NULL;
2328
/* get challenge info from connectionInfo */
2329
authType = ss->sec.ci.authType;
2331
if (authType != SSL_AT_MD5_WITH_RSA_ENCRYPTION) {
2332
SSL_TRC(7, ("%d: SSL[%d]: unsupported auth type 0x%x", SSL_GETPID(),
2337
/* Get certificate and private-key from client */
2338
if (!ss->getClientAuthData) {
2339
SSL_TRC(7, ("%d: SSL[%d]: client doesn't support client-auth",
2340
SSL_GETPID(), ss->fd));
2343
ret = (*ss->getClientAuthData)(ss->getClientAuthDataArg, ss->fd,
2345
if ( ret == SECWouldBlock ) {
2346
ssl_SetAlwaysBlock(ss);
2354
/* check what the callback function returned */
2355
if ((!cert) || (!key)) {
2356
/* we are missing either the key or cert */
2358
/* got a cert, but no key - free it */
2359
CERT_DestroyCertificate(cert);
2363
/* got a key, but no cert - free it */
2364
SECKEY_DestroyPrivateKey(key);
2370
rv = ssl2_SignResponse(ss, key, &response);
2371
if ( rv != SECSuccess ) {
2376
/* Send response message */
2377
ret = ssl2_SendCertificateResponseMessage(ss, &cert->derCert, &response);
2379
/* Now, remember the cert we sent. But first, forget any previous one. */
2380
if (ss->sec.localCert) {
2381
CERT_DestroyCertificate(ss->sec.localCert);
2383
ss->sec.localCert = CERT_DupCertificate(cert);
2384
PORT_Assert(!ss->sec.ci.sid->localCert);
2385
if (ss->sec.ci.sid->localCert) {
2386
CERT_DestroyCertificate(ss->sec.ci.sid->localCert);
2388
ss->sec.ci.sid->localCert = cert;
2394
SSL_TRC(7, ("%d: SSL[%d]: no certificate (ret=%d)", SSL_GETPID(),
2396
ret = ssl2_SendErrorMessage(ss, SSL_PE_NO_CERTIFICATE);
2401
CERT_DestroyCertificate(cert);
2404
SECKEY_DestroyPrivateKey(key);
2406
if ( response.data ) {
2407
PORT_Free(response.data);
2414
** Called from ssl2_HandleMessage for SSL_MT_CLIENT_CERTIFICATE message.
2415
** Caller must hold HandshakeLock and RecvBufLock, since cd and response
2416
** are contained in the gathered input data.
2419
ssl2_HandleClientCertificate(sslSocket * ss,
2420
PRUint8 certType, /* XXX unused */
2424
unsigned int responseLen)
2426
CERTCertificate *cert = NULL;
2427
SECKEYPublicKey *pubKey = NULL;
2428
VFYContext * vfy = NULL;
2430
SECStatus rv = SECFailure;
2434
PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) );
2435
PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
2437
/* Extract the certificate */
2439
certItem.len = cdLen;
2441
cert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL,
2447
/* save the certificate, since the auth routine will need it */
2448
ss->sec.peerCert = cert;
2450
/* Extract the public key */
2451
pubKey = CERT_ExtractPublicKey(cert);
2455
/* Verify the response data... */
2456
rep.data = response;
2457
rep.len = responseLen;
2458
/* SSL 2.0 only supports RSA certs, so we don't have to worry about
2460
vfy = VFY_CreateContext(pubKey, &rep, SEC_OID_PKCS1_RSA_ENCRYPTION,
2464
rv = VFY_Begin(vfy);
2468
rv = VFY_Update(vfy, ss->sec.ci.readKey, ss->sec.ci.keySize);
2471
rv = VFY_Update(vfy, ss->sec.ci.writeKey, ss->sec.ci.keySize);
2474
rv = VFY_Update(vfy, ss->sec.ci.serverChallenge, SSL_CHALLENGE_BYTES);
2478
derCert = &ss->serverCerts[kt_rsa].serverCert->derCert;
2479
rv = VFY_Update(vfy, derCert->data, derCert->len);
2486
/* Now ask the server application if it likes the certificate... */
2487
rv = (SECStatus) (*ss->authCertificate)(ss->authCertificateArg,
2488
ss->fd, PR_TRUE, PR_TRUE);
2489
/* Hey, it liked it. */
2490
if (SECSuccess == rv)
2494
ss->sec.peerCert = NULL;
2495
CERT_DestroyCertificate(cert);
2498
VFY_DestroyContext(vfy, PR_TRUE);
2499
SECKEY_DestroyPublicKey(pubKey);
2504
** Handle remaining messages between client/server. Process finished
2505
** messages from either side and any authentication requests.
2506
** This should only be called for SSLv2 handshake messages,
2507
** not for application data records.
2508
** Caller must hold handshake lock.
2510
** Called from ssl_Do1stHandshake().
2514
ssl2_HandleMessage(sslSocket *ss)
2518
unsigned len, certType, certLen, responseLen;
2522
PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) );
2524
ssl_GetRecvBufLock(ss);
2526
data = ss->gs.buf.buf + ss->gs.recordOffset;
2528
if (ss->gs.recordLen < 1) {
2531
SSL_TRC(3, ("%d: SSL[%d]: received %d message",
2532
SSL_GETPID(), ss->fd, data[0]));
2533
DUMP_MSG(29, (ss, data, ss->gs.recordLen));
2536
case SSL_MT_CLIENT_FINISHED:
2537
if (ss->sec.ci.elements & CIS_HAVE_FINISHED) {
2538
SSL_DBG(("%d: SSL[%d]: dup client-finished message",
2539
SSL_GETPID(), ss->fd));
2543
/* See if nonce matches */
2544
len = ss->gs.recordLen - 1;
2546
if ((len != sizeof(ss->sec.ci.connectionID)) ||
2547
(PORT_Memcmp(ss->sec.ci.connectionID, cid, len) != 0)) {
2548
SSL_DBG(("%d: SSL[%d]: bad connection-id", SSL_GETPID(), ss->fd));
2549
PRINT_BUF(5, (ss, "sent connection-id",
2550
ss->sec.ci.connectionID,
2551
sizeof(ss->sec.ci.connectionID)));
2552
PRINT_BUF(5, (ss, "rcvd connection-id", cid, len));
2556
SSL_TRC(5, ("%d: SSL[%d]: got client finished, waiting for 0x%d",
2557
SSL_GETPID(), ss->fd,
2558
ss->sec.ci.requiredElements ^ ss->sec.ci.elements));
2559
ss->sec.ci.elements |= CIS_HAVE_FINISHED;
2562
case SSL_MT_SERVER_FINISHED:
2563
if (ss->sec.ci.elements & CIS_HAVE_FINISHED) {
2564
SSL_DBG(("%d: SSL[%d]: dup server-finished message",
2565
SSL_GETPID(), ss->fd));
2569
if (ss->gs.recordLen - 1 != SSL2_SESSIONID_BYTES) {
2570
SSL_DBG(("%d: SSL[%d]: bad server-finished message, len=%d",
2571
SSL_GETPID(), ss->fd, ss->gs.recordLen));
2574
ssl2_ClientRegSessionID(ss, data+1);
2575
SSL_TRC(5, ("%d: SSL[%d]: got server finished, waiting for 0x%d",
2576
SSL_GETPID(), ss->fd,
2577
ss->sec.ci.requiredElements ^ ss->sec.ci.elements));
2578
ss->sec.ci.elements |= CIS_HAVE_FINISHED;
2581
case SSL_MT_REQUEST_CERTIFICATE:
2582
len = ss->gs.recordLen - 2;
2583
if ((len < SSL_MIN_CHALLENGE_BYTES) ||
2584
(len > SSL_MAX_CHALLENGE_BYTES)) {
2586
SSL_DBG(("%d: SSL[%d]: bad cert request message: code len=%d",
2587
SSL_GETPID(), ss->fd, len));
2591
/* save auth request info */
2592
ss->sec.ci.authType = data[1];
2593
ss->sec.ci.serverChallengeLen = len;
2594
PORT_Memcpy(ss->sec.ci.serverChallenge, data + 2, len);
2596
rv = ssl2_HandleRequestCertificate(ss);
2597
if (rv == SECWouldBlock) {
2598
SSL_TRC(3, ("%d: SSL[%d]: async cert request",
2599
SSL_GETPID(), ss->fd));
2600
/* someone is handling this asynchronously */
2601
ssl_ReleaseRecvBufLock(ss);
2602
return SECWouldBlock;
2610
case SSL_MT_CLIENT_CERTIFICATE:
2611
if (!ss->authCertificate) {
2612
/* Server asked for authentication and can't handle it */
2613
PORT_SetError(SSL_ERROR_BAD_SERVER);
2616
if (ss->gs.recordLen < SSL_HL_CLIENT_CERTIFICATE_HBYTES) {
2621
certLen = (data[2] << 8) | data[3];
2622
responseLen = (data[4] << 8) | data[5];
2623
if (certType != SSL_CT_X509_CERTIFICATE) {
2624
PORT_SetError(SSL_ERROR_UNSUPPORTED_CERTIFICATE_TYPE);
2627
if (certLen + responseLen + SSL_HL_CLIENT_CERTIFICATE_HBYTES
2628
> ss->gs.recordLen) {
2629
/* prevent overflow crash. */
2632
rv = ssl2_HandleClientCertificate(ss, data[1],
2633
data + SSL_HL_CLIENT_CERTIFICATE_HBYTES,
2635
data + SSL_HL_CLIENT_CERTIFICATE_HBYTES + certLen,
2638
rv2 = ssl2_SendErrorMessage(ss, SSL_PE_BAD_CERTIFICATE);
2642
ss->sec.ci.elements |= CIS_HAVE_CERTIFICATE;
2646
rv = (data[1] << 8) | data[2];
2647
SSL_TRC(2, ("%d: SSL[%d]: got error message, error=0x%x",
2648
SSL_GETPID(), ss->fd, rv));
2650
/* Convert protocol error number into API error number */
2652
case SSL_PE_NO_CYPHERS:
2653
rv = SSL_ERROR_NO_CYPHER_OVERLAP;
2655
case SSL_PE_NO_CERTIFICATE:
2656
rv = SSL_ERROR_NO_CERTIFICATE;
2658
case SSL_PE_BAD_CERTIFICATE:
2659
rv = SSL_ERROR_BAD_CERTIFICATE;
2661
case SSL_PE_UNSUPPORTED_CERTIFICATE_TYPE:
2662
rv = SSL_ERROR_UNSUPPORTED_CERTIFICATE_TYPE;
2667
/* XXX make certificate-request optionally fail... */
2672
SSL_DBG(("%d: SSL[%d]: unknown message %d",
2673
SSL_GETPID(), ss->fd, data[0]));
2677
SSL_TRC(3, ("%d: SSL[%d]: handled %d message, required=0x%x got=0x%x",
2678
SSL_GETPID(), ss->fd, data[0],
2679
ss->sec.ci.requiredElements, ss->sec.ci.elements));
2681
rv = ssl2_TryToFinish(ss);
2682
if (rv != SECSuccess)
2685
ss->gs.recordLen = 0;
2686
ssl_ReleaseRecvBufLock(ss);
2688
if (ss->handshake == 0) {
2692
ss->handshake = ssl_GatherRecord1stHandshake;
2693
ss->nextHandshake = ssl2_HandleMessage;
2694
return ssl2_TriggerNextMessage(ss);
2697
PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT : SSL_ERROR_BAD_SERVER);
2701
ssl_ReleaseRecvBufLock(ss);
2705
/************************************************************************/
2707
/* Called from ssl_Do1stHandshake, after ssl2_HandleServerHelloMessage or
2708
** ssl2_RestartHandshakeAfterServerCert.
2711
ssl2_HandleVerifyMessage(sslSocket *ss)
2716
PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) );
2717
ssl_GetRecvBufLock(ss);
2719
data = ss->gs.buf.buf + ss->gs.recordOffset;
2720
DUMP_MSG(29, (ss, data, ss->gs.recordLen));
2721
if ((ss->gs.recordLen != 1 + SSL_CHALLENGE_BYTES) ||
2722
(data[0] != SSL_MT_SERVER_VERIFY) ||
2723
PORT_Memcmp(data+1, ss->sec.ci.clientChallenge, SSL_CHALLENGE_BYTES)) {
2725
PORT_SetError(SSL_ERROR_BAD_SERVER);
2728
ss->sec.ci.elements |= CIS_HAVE_VERIFY;
2730
SSL_TRC(5, ("%d: SSL[%d]: got server-verify, required=0x%d got=0x%x",
2731
SSL_GETPID(), ss->fd, ss->sec.ci.requiredElements,
2732
ss->sec.ci.elements));
2734
rv = ssl2_TryToFinish(ss);
2738
ss->gs.recordLen = 0;
2739
ssl_ReleaseRecvBufLock(ss);
2741
if (ss->handshake == 0) {
2744
ss->handshake = ssl_GatherRecord1stHandshake;
2745
ss->nextHandshake = ssl2_HandleMessage;
2750
ssl_ReleaseRecvBufLock(ss);
2754
/* Not static because ssl2_GatherData() tests ss->nextHandshake for this value.
2756
* Called from ssl_Do1stHandshake after ssl2_BeginClientHandshake()
2759
ssl2_HandleServerHelloMessage(sslSocket *ss)
2766
int needed, sidHit, certLen, csLen, cidLen, certType, err;
2768
PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) );
2770
if (!ss->opt.enableSSL2) {
2771
PORT_SetError(SSL_ERROR_SSL2_DISABLED);
2775
ssl_GetRecvBufLock(ss);
2777
PORT_Assert(ss->sec.ci.sid != 0);
2778
sid = ss->sec.ci.sid;
2780
data = ss->gs.buf.buf + ss->gs.recordOffset;
2781
DUMP_MSG(29, (ss, data, ss->gs.recordLen));
2783
/* Make sure first message has some data and is the server hello message */
2784
if ((ss->gs.recordLen < SSL_HL_SERVER_HELLO_HBYTES)
2785
|| (data[0] != SSL_MT_SERVER_HELLO)) {
2786
if ((data[0] == SSL_MT_ERROR) && (ss->gs.recordLen == 3)) {
2787
err = (data[1] << 8) | data[2];
2788
if (err == SSL_PE_NO_CYPHERS) {
2789
PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
2798
ss->version = (data[3] << 8) | data[4];
2799
certLen = (data[5] << 8) | data[6];
2800
csLen = (data[7] << 8) | data[8];
2801
cidLen = (data[9] << 8) | data[10];
2802
cert = data + SSL_HL_SERVER_HELLO_HBYTES;
2803
cs = cert + certLen;
2806
("%d: SSL[%d]: server-hello, hit=%d vers=%x certLen=%d csLen=%d cidLen=%d",
2807
SSL_GETPID(), ss->fd, sidHit, ss->version, certLen,
2809
if (ss->version != SSL_LIBRARY_VERSION_2) {
2810
if (ss->version < SSL_LIBRARY_VERSION_2) {
2811
SSL_TRC(3, ("%d: SSL[%d]: demoting self (%x) to server version (%x)",
2812
SSL_GETPID(), ss->fd, SSL_LIBRARY_VERSION_2,
2815
SSL_TRC(1, ("%d: SSL[%d]: server version is %x (we are %x)",
2816
SSL_GETPID(), ss->fd, ss->version, SSL_LIBRARY_VERSION_2));
2817
/* server claims to be newer but does not follow protocol */
2818
PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION);
2823
if ((SSL_HL_SERVER_HELLO_HBYTES + certLen + csLen + cidLen
2826
/* || cidLen < SSL_CONNECTIONID_BYTES || cidLen > 32 */
2831
/* Save connection-id.
2832
** This code only saves the first 16 byte of the connectionID.
2833
** If the connectionID is shorter than 16 bytes, it is zero-padded.
2835
if (cidLen < sizeof ss->sec.ci.connectionID)
2836
memset(ss->sec.ci.connectionID, 0, sizeof ss->sec.ci.connectionID);
2837
cidLen = PR_MIN(cidLen, sizeof ss->sec.ci.connectionID);
2838
PORT_Memcpy(ss->sec.ci.connectionID, cs + csLen, cidLen);
2840
/* See if session-id hit */
2841
needed = CIS_HAVE_MASTER_KEY | CIS_HAVE_FINISHED | CIS_HAVE_VERIFY;
2843
if (certLen || csLen) {
2844
/* Uh oh - bogus server */
2845
SSL_DBG(("%d: SSL[%d]: client, huh? hit=%d certLen=%d csLen=%d",
2846
SSL_GETPID(), ss->fd, sidHit, certLen, csLen));
2851
SSL_TRC(1, ("%d: SSL[%d]: client, using nonce for peer=0x%08x "
2853
SSL_GETPID(), ss->fd, ss->sec.ci.peer, ss->sec.ci.port));
2854
ss->sec.peerCert = CERT_DupCertificate(sid->peerCert);
2855
ss->sec.authAlgorithm = sid->authAlgorithm;
2856
ss->sec.authKeyBits = sid->authKeyBits;
2857
ss->sec.keaType = sid->keaType;
2858
ss->sec.keaKeyBits = sid->keaKeyBits;
2859
rv = ssl2_CreateSessionCypher(ss, sid, PR_TRUE);
2860
if (rv != SECSuccess) {
2864
if (certType != SSL_CT_X509_CERTIFICATE) {
2865
PORT_SetError(SSL_ERROR_UNSUPPORTED_CERTIFICATE_TYPE);
2869
PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
2870
SSL_DBG(("%d: SSL[%d]: no cipher overlap",
2871
SSL_GETPID(), ss->fd));
2875
SSL_DBG(("%d: SSL[%d]: client, huh? certLen=%d csLen=%d",
2876
SSL_GETPID(), ss->fd, certLen, csLen));
2880
if (sid->cached != never_cached) {
2881
/* Forget our session-id - server didn't like it */
2882
SSL_TRC(7, ("%d: SSL[%d]: server forgot me, uncaching session-id",
2883
SSL_GETPID(), ss->fd));
2884
(*ss->sec.uncache)(sid);
2886
ss->sec.ci.sid = sid = (sslSessionID*) PORT_ZAlloc(sizeof(sslSessionID));
2890
sid->references = 1;
2891
sid->addr = ss->sec.ci.peer;
2892
sid->port = ss->sec.ci.port;
2895
/* decode the server's certificate */
2896
rv = ssl2_ClientHandleServerCert(ss, cert, certLen);
2897
if (rv != SECSuccess) {
2898
if (PORT_GetError() == SSL_ERROR_BAD_CERTIFICATE) {
2899
(void) ssl2_SendErrorMessage(ss, SSL_PE_BAD_CERTIFICATE);
2904
/* Setup new session cipher */
2905
rv = ssl2_ClientSetupSessionCypher(ss, cs, csLen);
2906
if (rv != SECSuccess) {
2907
if (PORT_GetError() == SSL_ERROR_BAD_CERTIFICATE) {
2908
(void) ssl2_SendErrorMessage(ss, SSL_PE_BAD_CERTIFICATE);
2914
/* Build up final list of required elements */
2915
ss->sec.ci.elements = CIS_HAVE_MASTER_KEY;
2916
ss->sec.ci.requiredElements = needed;
2919
/* verify the server's certificate. if sidHit, don't check signatures */
2920
rv = (* ss->authCertificate)(ss->authCertificateArg, ss->fd,
2921
(PRBool)(!sidHit), PR_FALSE);
2923
if (ss->handleBadCert) {
2924
rv = (*ss->handleBadCert)(ss->badCertArg, ss->fd);
2926
if ( rv == SECWouldBlock ) {
2927
/* someone will handle this connection asynchronously*/
2929
SSL_DBG(("%d: SSL[%d]: go to async cert handler",
2930
SSL_GETPID(), ss->fd));
2931
ssl_ReleaseRecvBufLock(ss);
2932
ssl_SetAlwaysBlock(ss);
2933
return SECWouldBlock;
2936
SSL_DBG(("%d: SSL[%d]: server certificate is no good: error=%d",
2937
SSL_GETPID(), ss->fd, PORT_GetError()));
2943
SSL_DBG(("%d: SSL[%d]: server certificate is no good: error=%d",
2944
SSL_GETPID(), ss->fd, PORT_GetError()));
2950
** At this point we have a completed session key and our session
2951
** cipher is setup and ready to go. Switch to encrypted write routine
2952
** as all future message data is to be encrypted.
2954
ssl2_UseEncryptedSendFunc(ss);
2956
rv = ssl2_TryToFinish(ss);
2957
if (rv != SECSuccess)
2960
ss->gs.recordLen = 0;
2962
ssl_ReleaseRecvBufLock(ss);
2964
if (ss->handshake == 0) {
2968
SSL_TRC(5, ("%d: SSL[%d]: got server-hello, required=0x%d got=0x%x",
2969
SSL_GETPID(), ss->fd, ss->sec.ci.requiredElements,
2970
ss->sec.ci.elements));
2971
ss->handshake = ssl_GatherRecord1stHandshake;
2972
ss->nextHandshake = ssl2_HandleVerifyMessage;
2976
PORT_SetError(SSL_ERROR_BAD_SERVER);
2980
ssl_ReleaseRecvBufLock(ss);
2984
/* Sends out the initial client Hello message on the connection.
2985
* Acquires and releases the socket's xmitBufLock.
2988
ssl2_BeginClientHandshake(sslSocket *ss)
2993
PRUint8 *localCipherSpecs = NULL;
2994
unsigned int localCipherSize;
2996
int sendLen, sidLen = 0;
2999
PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) );
3001
ss->sec.isServer = 0;
3002
ss->sec.sendSequence = 0;
3003
ss->sec.rcvSequence = 0;
3004
ssl_ChooseSessionIDProcs(&ss->sec);
3006
if (!ss->cipherSpecs) {
3007
rv = ssl2_ConstructCipherSpecs(ss);
3008
if (rv != SECSuccess)
3012
/* count the SSL2 and SSL3 enabled ciphers.
3013
* if either is zero, clear the socket's enable for that protocol.
3015
rv = ssl2_CheckConfigSanity(ss);
3016
if (rv != SECSuccess)
3019
/* Get peer name of server */
3020
rv = ssl_GetPeerInfo(ss);
3024
* On some HP-UX B.11.00 systems, getpeername() occasionally
3025
* fails with ENOTCONN after a successful completion of
3026
* non-blocking connect. I found that if we do a write()
3027
* and then retry getpeername(), it will work.
3029
if (PR_GetError() == PR_NOT_CONNECTED_ERROR) {
3031
(void) PR_Write(ss->fd->lower, &dummy, 0);
3032
rv = ssl_GetPeerInfo(ss);
3042
SSL_TRC(3, ("%d: SSL[%d]: sending client-hello", SSL_GETPID(), ss->fd));
3044
/* Try to find server in our session-id cache */
3045
if (ss->opt.noCache) {
3048
sid = ssl_LookupSID(&ss->sec.ci.peer, ss->sec.ci.port, ss->peerID,
3051
while (sid) { /* this isn't really a loop */
3052
/* if we're not doing this SID's protocol any more, drop it. */
3053
if (((sid->version < SSL_LIBRARY_VERSION_3_0) && !ss->opt.enableSSL2) ||
3054
((sid->version == SSL_LIBRARY_VERSION_3_0) && !ss->opt.enableSSL3) ||
3055
((sid->version > SSL_LIBRARY_VERSION_3_0) && !ss->opt.enableTLS)) {
3056
ss->sec.uncache(sid);
3061
if (ss->opt.enableSSL2 && sid->version < SSL_LIBRARY_VERSION_3_0) {
3062
/* If the cipher in this sid is not enabled, drop it. */
3063
for (i = 0; i < ss->sizeCipherSpecs; i += 3) {
3064
if (ss->cipherSpecs[i] == sid->u.ssl2.cipherType)
3067
if (i >= ss->sizeCipherSpecs) {
3068
ss->sec.uncache(sid);
3074
sidLen = sizeof(sid->u.ssl2.sessionID);
3075
PRINT_BUF(4, (ss, "client, found session-id:", sid->u.ssl2.sessionID,
3077
ss->version = sid->version;
3078
PORT_Assert(!ss->sec.localCert);
3079
if (ss->sec.localCert) {
3080
CERT_DestroyCertificate(ss->sec.localCert);
3082
ss->sec.localCert = CERT_DupCertificate(sid->localCert);
3083
break; /* this isn't really a loop */
3087
sid = (sslSessionID*) PORT_ZAlloc(sizeof(sslSessionID));
3091
sid->references = 1;
3092
sid->cached = never_cached;
3093
sid->addr = ss->sec.ci.peer;
3094
sid->port = ss->sec.ci.port;
3095
if (ss->peerID != NULL) {
3096
sid->peerID = PORT_Strdup(ss->peerID);
3098
if (ss->url != NULL) {
3099
sid->urlSvrName = PORT_Strdup(ss->url);
3102
ss->sec.ci.sid = sid;
3104
PORT_Assert(sid != NULL);
3106
if ((sid->version >= SSL_LIBRARY_VERSION_3_0 || !ss->opt.v2CompatibleHello) &&
3107
(ss->opt.enableSSL3 || ss->opt.enableTLS)) {
3109
ss->gs.state = GS_INIT;
3110
ss->handshake = ssl_GatherRecord1stHandshake;
3112
/* ssl3_SendClientHello will override this if it succeeds. */
3113
ss->version = SSL_LIBRARY_VERSION_3_0;
3115
ssl_GetXmitBufLock(ss); /***************************************/
3116
ssl_GetSSL3HandshakeLock(ss);
3117
rv = ssl3_SendClientHello(ss);
3118
ssl_ReleaseSSL3HandshakeLock(ss);
3119
ssl_ReleaseXmitBufLock(ss); /***************************************/
3123
#if defined(NSS_ENABLE_ECC) && !defined(NSS_ECC_MORE_THAN_SUITE_B)
3124
/* ensure we don't neogtiate ECC cipher suites with SSL2 hello */
3125
ssl3_DisableECCSuites(ss, NULL); /* disable all ECC suites */
3126
if (ss->cipherSpecs != NULL) {
3127
PORT_Free(ss->cipherSpecs);
3128
ss->cipherSpecs = NULL;
3129
ss->sizeCipherSpecs = 0;
3133
if (!ss->cipherSpecs) {
3134
rv = ssl2_ConstructCipherSpecs(ss);
3139
localCipherSpecs = ss->cipherSpecs;
3140
localCipherSize = ss->sizeCipherSpecs;
3142
sendLen = SSL_HL_CLIENT_HELLO_HBYTES + localCipherSize + sidLen +
3143
SSL_CHALLENGE_BYTES;
3145
/* Generate challenge bytes for server */
3146
PK11_GenerateRandom(ss->sec.ci.clientChallenge, SSL_CHALLENGE_BYTES);
3148
ssl_GetXmitBufLock(ss); /***************************************/
3150
rv = ssl2_GetSendBuffer(ss, sendLen);
3154
/* Construct client-hello message */
3155
cp = msg = ss->sec.ci.sendBuf.buf;
3156
msg[0] = SSL_MT_CLIENT_HELLO;
3157
if ( ss->opt.enableTLS ) {
3158
ss->clientHelloVersion = SSL_LIBRARY_VERSION_3_1_TLS;
3159
} else if ( ss->opt.enableSSL3 ) {
3160
ss->clientHelloVersion = SSL_LIBRARY_VERSION_3_0;
3162
ss->clientHelloVersion = SSL_LIBRARY_VERSION_2;
3165
msg[1] = MSB(ss->clientHelloVersion);
3166
msg[2] = LSB(ss->clientHelloVersion);
3167
msg[3] = MSB(localCipherSize);
3168
msg[4] = LSB(localCipherSize);
3169
msg[5] = MSB(sidLen);
3170
msg[6] = LSB(sidLen);
3171
msg[7] = MSB(SSL_CHALLENGE_BYTES);
3172
msg[8] = LSB(SSL_CHALLENGE_BYTES);
3173
cp += SSL_HL_CLIENT_HELLO_HBYTES;
3174
PORT_Memcpy(cp, localCipherSpecs, localCipherSize);
3175
cp += localCipherSize;
3177
PORT_Memcpy(cp, sid->u.ssl2.sessionID, sidLen);
3180
PORT_Memcpy(cp, ss->sec.ci.clientChallenge, SSL_CHALLENGE_BYTES);
3182
/* Send it to the server */
3183
DUMP_MSG(29, (ss, msg, sendLen));
3184
ss->handshakeBegun = 1;
3185
rv = (*ss->sec.send)(ss, msg, sendLen, 0);
3187
ssl_ReleaseXmitBufLock(ss); /***************************************/
3193
rv = ssl3_StartHandshakeHash(ss, msg, sendLen);
3198
/* Setup to receive servers hello message */
3199
ssl_GetRecvBufLock(ss);
3200
ss->gs.recordLen = 0;
3201
ssl_ReleaseRecvBufLock(ss);
3203
ss->handshake = ssl_GatherRecord1stHandshake;
3204
ss->nextHandshake = ssl2_HandleServerHelloMessage;
3208
ssl_ReleaseXmitBufLock(ss);
3213
/************************************************************************/
3215
/* Handle the CLIENT-MASTER-KEY message.
3216
** Acquires and releases RecvBufLock.
3217
** Called from ssl2_HandleClientHelloMessage().
3220
ssl2_HandleClientSessionKeyMessage(sslSocket *ss)
3226
unsigned int keySize;
3231
ssl_GetRecvBufLock(ss);
3233
data = ss->gs.buf.buf + ss->gs.recordOffset;
3234
DUMP_MSG(29, (ss, data, ss->gs.recordLen));
3236
if ((ss->gs.recordLen < SSL_HL_CLIENT_MASTER_KEY_HBYTES)
3237
|| (data[0] != SSL_MT_CLIENT_MASTER_KEY)) {
3241
keySize = (data[2] << 8) | data[3];
3242
ckLen = (data[4] << 8) | data[5];
3243
ekLen = (data[6] << 8) | data[7];
3244
caLen = (data[8] << 8) | data[9];
3246
SSL_TRC(5, ("%d: SSL[%d]: session-key, cipher=%d keySize=%d ckLen=%d ekLen=%d caLen=%d",
3247
SSL_GETPID(), ss->fd, cipher, keySize, ckLen, ekLen, caLen));
3249
if (ss->gs.recordLen <
3250
SSL_HL_CLIENT_MASTER_KEY_HBYTES + ckLen + ekLen + caLen) {
3251
SSL_DBG(("%d: SSL[%d]: protocol size mismatch dataLen=%d",
3252
SSL_GETPID(), ss->fd, ss->gs.recordLen));
3256
/* Use info from client to setup session key */
3257
/* XXX should validate cipher&keySize are in our array */
3258
rv = ssl2_ServerSetupSessionCypher(ss, cipher, keySize,
3259
data + SSL_HL_CLIENT_MASTER_KEY_HBYTES, ckLen,
3260
data + SSL_HL_CLIENT_MASTER_KEY_HBYTES + ckLen, ekLen,
3261
data + SSL_HL_CLIENT_MASTER_KEY_HBYTES + ckLen + ekLen, caLen);
3262
ss->gs.recordLen = 0; /* we're done with this record. */
3264
ssl_ReleaseRecvBufLock(ss);
3266
if (rv != SECSuccess) {
3269
ss->sec.ci.elements |= CIS_HAVE_MASTER_KEY;
3270
ssl2_UseEncryptedSendFunc(ss);
3272
/* Send server verify message now that keys are established */
3273
rv = ssl2_SendServerVerifyMessage(ss);
3274
if (rv != SECSuccess)
3277
rv = ssl2_TryToFinish(ss);
3278
if (rv != SECSuccess)
3280
if (ss->handshake == 0) {
3284
SSL_TRC(5, ("%d: SSL[%d]: server: waiting for elements=0x%d",
3285
SSL_GETPID(), ss->fd, ss->sec.ci.requiredElements ^ ss->sec.ci.elements));
3286
ss->handshake = ssl_GatherRecord1stHandshake;
3287
ss->nextHandshake = ssl2_HandleMessage;
3289
return ssl2_TriggerNextMessage(ss);
3292
ssl_ReleaseRecvBufLock(ss);
3293
PORT_SetError(SSL_ERROR_BAD_CLIENT);
3301
* attempt to restart the handshake after asynchronously handling
3302
* a request for the client's certificate.
3305
* cert Client cert chosen by application.
3306
* key Private key associated with cert.
3308
* XXX: need to make ssl2 and ssl3 versions of this function agree on whether
3309
* they take the reference, or bump the ref count!
3313
* Caller holds 1stHandshakeLock.
3316
ssl2_RestartHandshakeAfterCertReq(sslSocket * ss,
3317
CERTCertificate * cert,
3318
SECKEYPrivateKey * key)
3321
SECStatus rv = SECSuccess;
3324
if (ss->version >= SSL_LIBRARY_VERSION_3_0)
3327
response.data = NULL;
3329
/* generate error if no cert or key */
3330
if ( ( cert == NULL ) || ( key == NULL ) ) {
3334
/* generate signed response to the challenge */
3335
rv = ssl2_SignResponse(ss, key, &response);
3336
if ( rv != SECSuccess ) {
3340
/* Send response message */
3341
ret = ssl2_SendCertificateResponseMessage(ss, &cert->derCert, &response);
3346
/* try to finish the handshake */
3347
ret = ssl2_TryToFinish(ss);
3352
/* done with handshake */
3353
if (ss->handshake == 0) {
3358
/* continue handshake */
3359
ssl_GetRecvBufLock(ss);
3360
ss->gs.recordLen = 0;
3361
ssl_ReleaseRecvBufLock(ss);
3363
ss->handshake = ssl_GatherRecord1stHandshake;
3364
ss->nextHandshake = ssl2_HandleMessage;
3365
ret = ssl2_TriggerNextMessage(ss);
3369
/* no cert - send error */
3370
ret = ssl2_SendErrorMessage(ss, SSL_PE_NO_CERTIFICATE);
3376
/* free allocated data */
3377
if ( response.data ) {
3378
PORT_Free(response.data);
3385
/* restart an SSL connection that we stopped to run certificate dialogs
3386
** XXX Need to document here how an application marks a cert to show that
3387
** the application has accepted it (overridden CERT_VerifyCert).
3391
* Caller holds 1stHandshakeLock.
3394
ssl2_RestartHandshakeAfterServerCert(sslSocket *ss)
3396
int rv = SECSuccess;
3398
if (ss->version >= SSL_LIBRARY_VERSION_3_0)
3402
** At this point we have a completed session key and our session
3403
** cipher is setup and ready to go. Switch to encrypted write routine
3404
** as all future message data is to be encrypted.
3406
ssl2_UseEncryptedSendFunc(ss);
3408
rv = ssl2_TryToFinish(ss);
3409
if (rv == SECSuccess && ss->handshake != NULL) {
3410
/* handshake is not yet finished. */
3412
SSL_TRC(5, ("%d: SSL[%d]: got server-hello, required=0x%d got=0x%x",
3413
SSL_GETPID(), ss->fd, ss->sec.ci.requiredElements,
3414
ss->sec.ci.elements));
3416
ssl_GetRecvBufLock(ss);
3417
ss->gs.recordLen = 0; /* mark it all used up. */
3418
ssl_ReleaseRecvBufLock(ss);
3420
ss->handshake = ssl_GatherRecord1stHandshake;
3421
ss->nextHandshake = ssl2_HandleVerifyMessage;
3428
** Handle the initial hello message from the client
3430
** not static because ssl2_GatherData() tests ss->nextHandshake for this value.
3433
ssl2_HandleClientHelloMessage(sslSocket *ss)
3436
sslServerCerts * sc;
3437
CERTCertificate *serverCert;
3442
PRUint8 *cert = NULL;
3444
unsigned int challengeLen;
3452
int gotXmitBufLock = 0;
3453
#if defined(SOLARIS) && defined(i386)
3454
volatile PRUint8 hit;
3458
PRUint8 csImpl[sizeof implementedCipherSuites];
3460
PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) );
3462
sc = ss->serverCerts + kt_rsa;
3463
serverCert = sc->serverCert;
3465
ssl_GetRecvBufLock(ss);
3468
data = ss->gs.buf.buf + ss->gs.recordOffset;
3469
DUMP_MSG(29, (ss, data, ss->gs.recordLen));
3471
/* Make sure first message has some data and is the client hello message */
3472
if ((ss->gs.recordLen < SSL_HL_CLIENT_HELLO_HBYTES)
3473
|| (data[0] != SSL_MT_CLIENT_HELLO)) {
3477
/* Get peer name of client */
3478
rv = ssl_GetPeerInfo(ss);
3479
if (rv != SECSuccess) {
3483
/* Examine version information */
3485
* See if this might be a V2 client hello asking to use the V3 protocol
3487
if ((data[0] == SSL_MT_CLIENT_HELLO) &&
3488
(data[1] >= MSB(SSL_LIBRARY_VERSION_3_0)) &&
3489
(ss->opt.enableSSL3 || ss->opt.enableTLS)) {
3490
rv = ssl3_HandleV2ClientHello(ss, data, ss->gs.recordLen);
3491
if (rv != SECFailure) { /* Success */
3492
ss->handshake = NULL;
3493
ss->nextHandshake = ssl_GatherRecord1stHandshake;
3494
ss->securityHandshake = NULL;
3495
ss->gs.state = GS_INIT;
3497
/* ssl3_HandleV3ClientHello has set ss->version,
3498
** and has gotten us a brand new sid.
3500
ss->sec.ci.sid->version = ss->version;
3502
ssl_ReleaseRecvBufLock(ss);
3505
/* Previously, there was a test here to see if SSL2 was enabled.
3506
** If not, an error code was set, and SECFailure was returned,
3507
** without sending any error code to the other end of the connection.
3508
** That test has been removed. If SSL2 has been disabled, there
3509
** should be no SSL2 ciphers enabled, and consequently, the code
3510
** below should send the ssl2 error message SSL_PE_NO_CYPHERS.
3511
** We now believe this is the correct thing to do, even when SSL2
3512
** has been explicitly disabled by the application.
3515
/* Extract info from message */
3516
ss->version = (data[1] << 8) | data[2];
3518
/* If some client thinks ssl v2 is 2.0 instead of 0.2, we'll allow it. */
3519
if (ss->version >= SSL_LIBRARY_VERSION_3_0) {
3520
ss->version = SSL_LIBRARY_VERSION_2;
3523
csLen = (data[3] << 8) | data[4];
3524
sdLen = (data[5] << 8) | data[6];
3525
challengeLen = (data[7] << 8) | data[8];
3526
cs = data + SSL_HL_CLIENT_HELLO_HBYTES;
3528
challenge = sd + sdLen;
3529
PRINT_BUF(7, (ss, "server, client session-id value:", sd, sdLen));
3531
if (!csLen || (csLen % 3) != 0 ||
3532
(sdLen != 0 && sdLen != SSL2_SESSIONID_BYTES) ||
3533
challengeLen < SSL_MIN_CHALLENGE_BYTES ||
3534
challengeLen > SSL_MAX_CHALLENGE_BYTES ||
3535
(unsigned)ss->gs.recordLen !=
3536
SSL_HL_CLIENT_HELLO_HBYTES + csLen + sdLen + challengeLen) {
3537
SSL_DBG(("%d: SSL[%d]: bad client hello message, len=%d should=%d",
3538
SSL_GETPID(), ss->fd, ss->gs.recordLen,
3539
SSL_HL_CLIENT_HELLO_HBYTES+csLen+sdLen+challengeLen));
3543
SSL_TRC(3, ("%d: SSL[%d]: client version is %x",
3544
SSL_GETPID(), ss->fd, ss->version));
3545
if (ss->version != SSL_LIBRARY_VERSION_2) {
3546
if (ss->version > SSL_LIBRARY_VERSION_2) {
3548
** Newer client than us. Things are ok because new clients
3549
** are required to be backwards compatible with old servers.
3550
** Change version number to our version number so that client
3553
ss->version = SSL_LIBRARY_VERSION_2;
3555
SSL_TRC(1, ("%d: SSL[%d]: client version is %x (we are %x)",
3556
SSL_GETPID(), ss->fd, ss->version, SSL_LIBRARY_VERSION_2));
3557
PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION);
3562
/* Qualify cipher specs before returning them to client */
3563
csLen = ssl2_QualifyCypherSpecs(ss, cs, csLen);
3565
/* no overlap, send client our list of supported SSL v2 ciphers. */
3567
csLen = sizeof implementedCipherSuites;
3568
PORT_Memcpy(cs, implementedCipherSuites, csLen);
3569
csLen = ssl2_QualifyCypherSpecs(ss, cs, csLen);
3571
/* We don't support any SSL v2 ciphers! */
3572
ssl2_SendErrorMessage(ss, SSL_PE_NO_CYPHERS);
3573
PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
3576
/* Since this handhsake is going to fail, don't cache it. */
3577
ss->opt.noCache = 1;
3580
/* Squirrel away the challenge for later */
3581
PORT_Memcpy(ss->sec.ci.clientChallenge, challenge, challengeLen);
3583
/* Examine message and see if session-id is good */
3584
ss->sec.ci.elements = 0;
3585
if (sdLen > 0 && !ss->opt.noCache) {
3586
SSL_TRC(7, ("%d: SSL[%d]: server, lookup client session-id for 0x%08x%08x%08x%08x",
3587
SSL_GETPID(), ss->fd, ss->sec.ci.peer.pr_s6_addr32[0],
3588
ss->sec.ci.peer.pr_s6_addr32[1],
3589
ss->sec.ci.peer.pr_s6_addr32[2],
3590
ss->sec.ci.peer.pr_s6_addr32[3]));
3591
sid = (*ssl_sid_lookup)(&ss->sec.ci.peer, sd, sdLen, ss->dbHandle);
3596
/* Got a good session-id. Short cut! */
3597
SSL_TRC(1, ("%d: SSL[%d]: server, using session-id for 0x%08x (age=%d)",
3598
SSL_GETPID(), ss->fd, ss->sec.ci.peer,
3599
ssl_Time() - sid->creationTime));
3600
PRINT_BUF(1, (ss, "session-id value:", sd, sdLen));
3601
ss->sec.ci.sid = sid;
3602
ss->sec.ci.elements = CIS_HAVE_MASTER_KEY;
3607
ss->sec.authAlgorithm = sid->authAlgorithm;
3608
ss->sec.authKeyBits = sid->authKeyBits;
3609
ss->sec.keaType = sid->keaType;
3610
ss->sec.keaKeyBits = sid->keaKeyBits;
3612
rv = ssl2_CreateSessionCypher(ss, sid, PR_FALSE);
3613
if (rv != SECSuccess) {
3617
SECItem * derCert = &serverCert->derCert;
3619
SSL_TRC(7, ("%d: SSL[%d]: server, lookup nonce missed",
3620
SSL_GETPID(), ss->fd));
3626
sid = (sslSessionID*) PORT_ZAlloc(sizeof(sslSessionID));
3630
sid->references = 1;
3631
sid->addr = ss->sec.ci.peer;
3632
sid->port = ss->sec.ci.port;
3634
/* Invent a session-id */
3635
ss->sec.ci.sid = sid;
3636
PK11_GenerateRandom(sid->u.ssl2.sessionID+2, SSL2_SESSIONID_BYTES-2);
3639
sid->u.ssl2.sessionID[0] = MSB(pid);
3640
sid->u.ssl2.sessionID[1] = LSB(pid);
3641
cert = derCert->data;
3642
certLen = derCert->len;
3644
/* pretend that server sids remember the local cert. */
3645
PORT_Assert(!sid->localCert);
3646
if (sid->localCert) {
3647
CERT_DestroyCertificate(sid->localCert);
3649
sid->localCert = CERT_DupCertificate(serverCert);
3651
ss->sec.authAlgorithm = ssl_sign_rsa;
3652
ss->sec.keaType = ssl_kea_rsa;
3653
ss->sec.keaKeyBits = \
3654
ss->sec.authKeyBits = ss->serverCerts[kt_rsa].serverKeyBits;
3657
/* server sids don't remember the local cert, so whether we found
3658
** a sid or not, just "remember" we used the rsa server cert.
3660
if (ss->sec.localCert) {
3661
CERT_DestroyCertificate(ss->sec.localCert);
3663
ss->sec.localCert = CERT_DupCertificate(serverCert);
3665
/* Build up final list of required elements */
3666
ss->sec.ci.requiredElements = CIS_HAVE_MASTER_KEY | CIS_HAVE_FINISHED;
3667
if (ss->opt.requestCertificate) {
3668
ss->sec.ci.requiredElements |= CIS_HAVE_CERTIFICATE;
3670
ss->sec.ci.sentElements = 0;
3672
/* Send hello message back to client */
3673
sendLen = SSL_HL_SERVER_HELLO_HBYTES + certLen + csLen
3674
+ SSL_CONNECTIONID_BYTES;
3676
ssl_GetXmitBufLock(ss); gotXmitBufLock = 1;
3677
rv = ssl2_GetSendBuffer(ss, sendLen);
3678
if (rv != SECSuccess) {
3682
SSL_TRC(3, ("%d: SSL[%d]: sending server-hello (%d)",
3683
SSL_GETPID(), ss->fd, sendLen));
3685
msg = ss->sec.ci.sendBuf.buf;
3686
msg[0] = SSL_MT_SERVER_HELLO;
3688
msg[2] = SSL_CT_X509_CERTIFICATE;
3689
msg[3] = MSB(ss->version);
3690
msg[4] = LSB(ss->version);
3691
msg[5] = MSB(certLen);
3692
msg[6] = LSB(certLen);
3693
msg[7] = MSB(csLen);
3694
msg[8] = LSB(csLen);
3695
msg[9] = MSB(SSL_CONNECTIONID_BYTES);
3696
msg[10] = LSB(SSL_CONNECTIONID_BYTES);
3698
PORT_Memcpy(msg+SSL_HL_SERVER_HELLO_HBYTES, cert, certLen);
3701
PORT_Memcpy(msg+SSL_HL_SERVER_HELLO_HBYTES+certLen, cs, csLen);
3703
PORT_Memcpy(msg+SSL_HL_SERVER_HELLO_HBYTES+certLen+csLen,
3704
ss->sec.ci.connectionID, SSL_CONNECTIONID_BYTES);
3706
DUMP_MSG(29, (ss, msg, sendLen));
3708
ss->handshakeBegun = 1;
3709
sent = (*ss->sec.send)(ss, msg, sendLen, 0);
3713
ssl_ReleaseXmitBufLock(ss); gotXmitBufLock = 0;
3715
ss->gs.recordLen = 0;
3716
ss->handshake = ssl_GatherRecord1stHandshake;
3718
/* Old SID Session key is good. Go encrypted */
3719
ssl2_UseEncryptedSendFunc(ss);
3721
/* Send server verify message now that keys are established */
3722
rv = ssl2_SendServerVerifyMessage(ss);
3723
if (rv != SECSuccess)
3726
ss->nextHandshake = ssl2_HandleMessage;
3727
ssl_ReleaseRecvBufLock(ss);
3728
rv = ssl2_TriggerNextMessage(ss);
3731
ss->nextHandshake = ssl2_HandleClientSessionKeyMessage;
3732
ssl_ReleaseRecvBufLock(ss);
3736
PORT_SetError(SSL_ERROR_BAD_CLIENT);
3740
if (gotXmitBufLock) {
3741
ssl_ReleaseXmitBufLock(ss); gotXmitBufLock = 0;
3743
SSL_TRC(10, ("%d: SSL[%d]: server, wait for client-hello lossage",
3744
SSL_GETPID(), ss->fd));
3745
ssl_ReleaseRecvBufLock(ss);
3750
ssl2_BeginServerHandshake(sslSocket *ss)
3753
sslServerCerts * rsaAuth = ss->serverCerts + kt_rsa;
3755
ss->sec.isServer = 1;
3756
ssl_ChooseSessionIDProcs(&ss->sec);
3757
ss->sec.sendSequence = 0;
3758
ss->sec.rcvSequence = 0;
3760
/* don't turn on SSL2 if we don't have an RSA key and cert */
3761
if (!rsaAuth->serverKeyPair || !rsaAuth->SERVERKEY ||
3762
!rsaAuth->serverCert) {
3763
ss->opt.enableSSL2 = PR_FALSE;
3766
if (!ss->cipherSpecs) {
3767
rv = ssl2_ConstructCipherSpecs(ss);
3768
if (rv != SECSuccess)
3772
/* count the SSL2 and SSL3 enabled ciphers.
3773
* if either is zero, clear the socket's enable for that protocol.
3775
rv = ssl2_CheckConfigSanity(ss);
3776
if (rv != SECSuccess)
3780
** Generate connection-id. Always do this, even if things fail
3781
** immediately. This way the random number generator is always
3782
** rolling around, every time we get a connection.
3784
PK11_GenerateRandom(ss->sec.ci.connectionID,
3785
sizeof(ss->sec.ci.connectionID));
3787
ss->gs.recordLen = 0;
3788
ss->handshake = ssl_GatherRecord1stHandshake;
3789
ss->nextHandshake = ssl2_HandleClientHelloMessage;
3796
/* This function doesn't really belong in this file.
3797
** It's here to keep AIX compilers from optimizing it away,
3798
** and not including it in the DSO.
3802
extern const char __nss_ssl_rcsid[];
3803
extern const char __nss_ssl_sccsid[];
3806
NSSSSL_VersionCheck(const char *importedVersion)
3809
* This is the secret handshake algorithm.
3811
* This release has a simple version compatibility
3812
* check algorithm. This release is not backward
3813
* compatible with previous major releases. It is
3814
* not compatible with future major, minor, or
3817
volatile char c; /* force a reference that won't get optimized away */
3819
c = __nss_ssl_rcsid[0] + __nss_ssl_sccsid[0];
3820
return NSS_VersionCheck(importedVersion);