~ubuntu-branches/ubuntu/lucid/seamonkey/lucid-security

« back to all changes in this revision

Viewing changes to security/nss-fips/lib/ssl/sslcon.c

  • Committer: Bazaar Package Importer
  • Author(s): Fabien Tassin
  • Date: 2008-07-29 21:29:02 UTC
  • mfrom: (1.1.4 upstream)
  • Revision ID: james.westby@ubuntu.com-20080729212902-spm9kpvchp9udwbw
Tags: 1.1.11+nobinonly-0ubuntu1
* New security upstream release: 1.1.11 (LP: #218534)
  Fixes USN-602-1, USN-619-1, USN-623-1 and USN-629-1
* Refresh diverged patch:
  - update debian/patches/80_security_build.patch
* Fix FTBFS with missing -lfontconfig
  - add debian/patches/11_fix_ftbfs_with_fontconfig.patch
  - update debian/patches/series
* Build with default gcc (hardy: 4.2, intrepid: 4.3)
  - update debian/rules
  - update debian/control

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/* 
 
2
 * SSL v2 handshake functions, and functions common to SSL2 and SSL3.
 
3
 *
 
4
 * ***** BEGIN LICENSE BLOCK *****
 
5
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 
6
 *
 
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/
 
11
 *
 
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
 
15
 * License.
 
16
 *
 
17
 * The Original Code is the Netscape security libraries.
 
18
 *
 
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.
 
23
 *
 
24
 * Contributor(s):
 
25
 *   Dr Vipul Gupta <vipul.gupta@sun.com>, Sun Microsystems Laboratories
 
26
 *
 
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.
 
38
 *
 
39
 * ***** END LICENSE BLOCK ***** */
 
40
/* $Id: sslcon.c,v 1.28.2.6 2006/11/14 01:12:08 wtchang%redhat.com Exp $ */
 
41
 
 
42
#include "nssrenam.h"
 
43
#include "cert.h"
 
44
#include "secitem.h"
 
45
#include "sechash.h"
 
46
#include "cryptohi.h"           /* for SGN_ funcs */
 
47
#include "keyhi.h"              /* for SECKEY_ high level functions. */
 
48
#include "ssl.h"
 
49
#include "sslimpl.h"
 
50
#include "sslproto.h"
 
51
#include "ssl3prot.h"
 
52
#include "sslerr.h"
 
53
#include "pk11func.h"
 
54
#include "prinit.h"
 
55
#include "prtime.h"     /* for PR_Now() */
 
56
 
 
57
#define XXX
 
58
static PRBool policyWasSet;
 
59
 
 
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[] = {
 
63
    0,                                          0,    0,
 
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,
 
71
    0,                                          0,    0
 
72
};
 
73
 
 
74
#define ssl2_NUM_SUITES_IMPLEMENTED 6
 
75
 
 
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. 
 
80
 */
 
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
 
88
};
 
89
 
 
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. */
 
93
    PRUint8           blockSize;
 
94
    PRUint8           blockShift;
 
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.    */
 
99
} ssl2Specs;
 
100
 
 
101
static const ssl2Specs ssl_Specs[] = {
 
102
/* NONE                                 */ 
 
103
                                {  0,  0, 0, 0, },
 
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         */ 
 
113
                                {  0,  0, 0, 0, },
 
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, },
 
118
};
 
119
 
 
120
#define SET_ERROR_CODE    /* reminder */
 
121
#define TEST_FOR_FAILURE  /* reminder */
 
122
 
 
123
/*
 
124
** Put a string tag in the library so that we can examine an executable
 
125
** and see what kind of security it supports.
 
126
*/
 
127
const char *ssl_version = "SECURITY_VERSION:"
 
128
                        " +us"
 
129
                        " +export"
 
130
#ifdef TRACE
 
131
                        " +trace"
 
132
#endif
 
133
#ifdef DEBUG
 
134
                        " +debug"
 
135
#endif
 
136
                        ;
 
137
 
 
138
const char * const ssl_cipherName[] = {
 
139
    "unknown",
 
140
    "RC4",
 
141
    "RC4-Export",
 
142
    "RC2-CBC",
 
143
    "RC2-CBC-Export",
 
144
    "IDEA-CBC",
 
145
    "DES-CBC",
 
146
    "DES-EDE3-CBC",
 
147
    "unknown",
 
148
    "unknown", /* was fortezza, NO LONGER USED */
 
149
};
 
150
 
 
151
 
 
152
/* bit-masks, showing which SSLv2 suites are allowed.
 
153
 * lsb corresponds to first cipher suite in allCipherSuites[].
 
154
 */
 
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 */
 
158
 
 
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)
 
174
 
 
175
 
 
176
/* Construct a socket's list of cipher specs from the global default values.
 
177
 */
 
178
static SECStatus
 
179
ssl2_ConstructCipherSpecs(sslSocket *ss) 
 
180
{
 
181
    PRUint8 *           cs              = NULL;
 
182
    unsigned int        allowed;
 
183
    unsigned int        count;
 
184
    int                 ssl3_count      = 0;
 
185
    int                 final_count;
 
186
    int                 i;
 
187
    SECStatus           rv;
 
188
 
 
189
    PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) );
 
190
 
 
191
    count = 0;
 
192
    PORT_Assert(ss != 0);
 
193
    allowed = !ss->opt.enableSSL2 ? 0 :
 
194
        (ss->allowedByPolicy & ss->chosenPreference & SSL_CB_IMPLEMENTED);
 
195
    while (allowed) {
 
196
        if (allowed & 1) 
 
197
            ++count;
 
198
        allowed >>= 1;
 
199
    }
 
200
 
 
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().
 
205
     */
 
206
    ssl3_config_match_init(ss);
 
207
 
 
208
    /* ask SSL3 how many cipher suites it has. */
 
209
    rv = ssl3_ConstructV2CipherSpecsHack(ss, NULL, &ssl3_count);
 
210
    if (rv < 0) 
 
211
        return rv;
 
212
    count += ssl3_count;
 
213
 
 
214
    /* Allocate memory to hold cipher specs */
 
215
    if (count > 0)
 
216
        cs = (PRUint8*) PORT_Alloc(count * 3);
 
217
    else
 
218
        PORT_SetError(SSL_ERROR_SSL_DISABLED);
 
219
    if (cs == NULL)
 
220
        return SECFailure;
 
221
 
 
222
    if (ss->cipherSpecs != NULL) {
 
223
        PORT_Free(ss->cipherSpecs);
 
224
    }
 
225
    ss->cipherSpecs     = cs;
 
226
    ss->sizeCipherSpecs = count * 3;
 
227
 
 
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]);
 
234
        if (ok) {
 
235
            cs[0] = hs[0];
 
236
            cs[1] = hs[1];
 
237
            cs[2] = hs[2];
 
238
            cs += 3;
 
239
        }
 
240
    }
 
241
 
 
242
    /* now have SSL3 add its suites onto the end */
 
243
    rv = ssl3_ConstructV2CipherSpecsHack(ss, cs, &final_count);
 
244
    
 
245
    /* adjust for any difference between first pass and second pass */
 
246
    ss->sizeCipherSpecs -= (ssl3_count - final_count) * 3;
 
247
 
 
248
    return rv;
 
249
}
 
250
 
 
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.
 
258
*/
 
259
static SECStatus
 
260
ssl2_CheckConfigSanity(sslSocket *ss)
 
261
{
 
262
    unsigned int      allowed;
 
263
    int               ssl3CipherCount = 0;
 
264
    SECStatus         rv;
 
265
 
 
266
    /* count the SSL2 and SSL3 enabled ciphers.
 
267
     * if either is zero, clear the socket's enable for that protocol.
 
268
     */
 
269
    if (!ss->cipherSpecs)
 
270
        goto disabled;
 
271
 
 
272
    allowed = ss->allowedByPolicy & ss->chosenPreference;
 
273
    if (! allowed)
 
274
        ss->opt.enableSSL2 = PR_FALSE; /* not really enabled if no ciphers */
 
275
 
 
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;
 
282
    }
 
283
 
 
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));
 
287
disabled:
 
288
        PORT_SetError(SSL_ERROR_SSL_DISABLED);
 
289
        return SECFailure;
 
290
    }
 
291
    return SECSuccess;
 
292
}
 
293
 
 
294
/* 
 
295
 * Since this is a global (not per-socket) setting, we cannot use the
 
296
 * HandshakeLock to protect this.  Probably want a global lock.
 
297
 */
 
298
SECStatus
 
299
ssl2_SetPolicy(PRInt32 which, PRInt32 policy)
 
300
{
 
301
    PRUint32  bitMask;
 
302
    SECStatus rv       = SECSuccess;
 
303
 
 
304
    which &= 0x000f;
 
305
    bitMask = 1 << which;
 
306
 
 
307
    if (!(bitMask & SSL_CB_IMPLEMENTED)) {
 
308
        PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE);
 
309
        return SECFailure;
 
310
    }
 
311
 
 
312
    if (policy == SSL_ALLOWED) {
 
313
        allowedByPolicy         |= bitMask;
 
314
        maybeAllowedByPolicy    |= bitMask;
 
315
    } else if (policy == SSL_RESTRICTED) {
 
316
        allowedByPolicy         &= ~bitMask;
 
317
        maybeAllowedByPolicy    |= bitMask;
 
318
    } else {
 
319
        allowedByPolicy         &= ~bitMask;
 
320
        maybeAllowedByPolicy    &= ~bitMask;
 
321
    }
 
322
    allowedByPolicy             &= SSL_CB_IMPLEMENTED;
 
323
    maybeAllowedByPolicy        &= SSL_CB_IMPLEMENTED;
 
324
 
 
325
    policyWasSet = PR_TRUE;
 
326
    return rv;
 
327
}
 
328
 
 
329
SECStatus
 
330
ssl2_GetPolicy(PRInt32 which, PRInt32 *oPolicy)
 
331
{
 
332
    PRUint32     bitMask;
 
333
    PRInt32      policy;
 
334
 
 
335
    which &= 0x000f;
 
336
    bitMask = 1 << which;
 
337
 
 
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;
 
342
        return SECFailure;
 
343
    }
 
344
 
 
345
    if (maybeAllowedByPolicy & bitMask) {
 
346
        policy = (allowedByPolicy & bitMask) ? SSL_ALLOWED : SSL_RESTRICTED;
 
347
    } else {
 
348
        policy = SSL_NOT_ALLOWED;
 
349
    }
 
350
 
 
351
    *oPolicy = policy;
 
352
    return SECSuccess;
 
353
}
 
354
 
 
355
/* 
 
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. 
 
360
 */
 
361
SECStatus
 
362
ssl2_CipherPrefSetDefault(PRInt32 which, PRBool enabled)
 
363
{
 
364
    PRUint32     bitMask;
 
365
    
 
366
    which &= 0x000f;
 
367
    bitMask = 1 << which;
 
368
 
 
369
    if (!(bitMask & SSL_CB_IMPLEMENTED)) {
 
370
        PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE);
 
371
        return SECFailure;
 
372
    }
 
373
 
 
374
    if (enabled)
 
375
        chosenPreference |= bitMask;
 
376
    else
 
377
        chosenPreference &= ~bitMask;
 
378
    chosenPreference &= SSL_CB_IMPLEMENTED;
 
379
 
 
380
    return SECSuccess;
 
381
}
 
382
 
 
383
SECStatus 
 
384
ssl2_CipherPrefGetDefault(PRInt32 which, PRBool *enabled)
 
385
{
 
386
    PRBool       rv       = PR_FALSE;
 
387
    PRUint32     bitMask;
 
388
 
 
389
    which &= 0x000f;
 
390
    bitMask = 1 << which;
 
391
 
 
392
    if (!(bitMask & SSL_CB_IMPLEMENTED)) {
 
393
        PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE);
 
394
        *enabled = PR_FALSE;
 
395
        return SECFailure;
 
396
    }
 
397
 
 
398
    rv = (PRBool)((chosenPreference & bitMask) != 0);
 
399
    *enabled = rv;
 
400
    return SECSuccess;
 
401
}
 
402
 
 
403
SECStatus 
 
404
ssl2_CipherPrefSet(sslSocket *ss, PRInt32 which, PRBool enabled)
 
405
{
 
406
    PRUint32     bitMask;
 
407
    
 
408
    which &= 0x000f;
 
409
    bitMask = 1 << which;
 
410
 
 
411
    if (!(bitMask & SSL_CB_IMPLEMENTED)) {
 
412
        PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE);
 
413
        return SECFailure;
 
414
    }
 
415
 
 
416
    if (enabled)
 
417
        ss->chosenPreference |= bitMask;
 
418
    else
 
419
        ss->chosenPreference &= ~bitMask;
 
420
    ss->chosenPreference &= SSL_CB_IMPLEMENTED;
 
421
 
 
422
    return SECSuccess;
 
423
}
 
424
 
 
425
SECStatus 
 
426
ssl2_CipherPrefGet(sslSocket *ss, PRInt32 which, PRBool *enabled)
 
427
{
 
428
    PRBool       rv       = PR_FALSE;
 
429
    PRUint32     bitMask;
 
430
 
 
431
    which &= 0x000f;
 
432
    bitMask = 1 << which;
 
433
 
 
434
    if (!(bitMask & SSL_CB_IMPLEMENTED)) {
 
435
        PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE);
 
436
        *enabled = PR_FALSE;
 
437
        return SECFailure;
 
438
    }
 
439
 
 
440
    rv = (PRBool)((ss->chosenPreference & bitMask) != 0);
 
441
    *enabled = rv;
 
442
    return SECSuccess;
 
443
}
 
444
 
 
445
 
 
446
/* copy global default policy into socket. */
 
447
void      
 
448
ssl2_InitSocketPolicy(sslSocket *ss)
 
449
{
 
450
    ss->allowedByPolicy         = allowedByPolicy;
 
451
    ss->maybeAllowedByPolicy    = maybeAllowedByPolicy;
 
452
    ss->chosenPreference        = chosenPreference;
 
453
}
 
454
 
 
455
 
 
456
/************************************************************************/
 
457
 
 
458
/* Called from ssl2_CreateSessionCypher(), which already holds handshake lock.
 
459
 */
 
460
static SECStatus
 
461
ssl2_CreateMAC(sslSecurityInfo *sec, SECItem *readKey, SECItem *writeKey, 
 
462
          int cipherChoice)
 
463
{
 
464
    switch (cipherChoice) {
 
465
 
 
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);
 
475
        break;
 
476
 
 
477
      default:
 
478
        PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
 
479
        return SECFailure;
 
480
    }
 
481
    sec->hashcx = (*sec->hash->create)();
 
482
    if (sec->hashcx == NULL)
 
483
        return SECFailure;
 
484
    return SECSuccess;
 
485
}
 
486
 
 
487
/************************************************************************
 
488
 * All the Send functions below must acquire and release the socket's 
 
489
 * xmitBufLock.
 
490
 */
 
491
 
 
492
/* Called from all the Send* functions below. */
 
493
static SECStatus
 
494
ssl2_GetSendBuffer(sslSocket *ss, unsigned int len)
 
495
{
 
496
    SECStatus rv = SECSuccess;
 
497
 
 
498
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
 
499
 
 
500
    if (len < 128) {
 
501
        len = 128;
 
502
    }
 
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));
 
508
            rv = SECFailure;
 
509
        }
 
510
    }
 
511
    return rv;
 
512
}
 
513
 
 
514
/* Called from:
 
515
 * ssl2_ClientSetupSessionCypher() <- ssl2_HandleServerHelloMessage()
 
516
 * ssl2_HandleRequestCertificate()     <- ssl2_HandleMessage() <- 
 
517
                                        ssl_Do1stHandshake()
 
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()
 
524
 * 
 
525
 * Acquires and releases the socket's xmitBufLock.
 
526
 */     
 
527
int
 
528
ssl2_SendErrorMessage(sslSocket *ss, int error)
 
529
{
 
530
    int rv;
 
531
    PRUint8 msg[SSL_HL_ERROR_HBYTES];
 
532
 
 
533
    PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) );
 
534
 
 
535
    msg[0] = SSL_MT_ERROR;
 
536
    msg[1] = MSB(error);
 
537
    msg[2] = LSB(error);
 
538
 
 
539
    ssl_GetXmitBufLock(ss);    /***************************************/
 
540
 
 
541
    SSL_TRC(3, ("%d: SSL[%d]: sending error %d", SSL_GETPID(), ss->fd, error));
 
542
 
 
543
    ss->handshakeBegun = 1;
 
544
    rv = (*ss->sec.send)(ss, msg, sizeof(msg), 0);
 
545
    if (rv >= 0) {
 
546
        rv = SECSuccess;
 
547
    }
 
548
    ssl_ReleaseXmitBufLock(ss);    /***************************************/
 
549
    return rv;
 
550
}
 
551
 
 
552
/* Called from ssl2_TryToFinish().  
 
553
 * Acquires and releases the socket's xmitBufLock.
 
554
 */
 
555
static SECStatus
 
556
ssl2_SendClientFinishedMessage(sslSocket *ss)
 
557
{
 
558
    SECStatus        rv    = SECSuccess;
 
559
    int              sent;
 
560
    PRUint8    msg[1 + SSL_CONNECTIONID_BYTES];
 
561
 
 
562
    PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) );
 
563
 
 
564
    ssl_GetXmitBufLock(ss);    /***************************************/
 
565
 
 
566
    if (ss->sec.ci.sentFinished == 0) {
 
567
        ss->sec.ci.sentFinished = 1;
 
568
 
 
569
        SSL_TRC(3, ("%d: SSL[%d]: sending client-finished",
 
570
                    SSL_GETPID(), ss->fd));
 
571
 
 
572
        msg[0] = SSL_MT_CLIENT_FINISHED;
 
573
        PORT_Memcpy(msg+1, ss->sec.ci.connectionID, 
 
574
                    sizeof(ss->sec.ci.connectionID));
 
575
 
 
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;
 
579
    }
 
580
    ssl_ReleaseXmitBufLock(ss);    /***************************************/
 
581
    return rv;
 
582
}
 
583
 
 
584
/* Called from 
 
585
 * ssl2_HandleClientSessionKeyMessage() <- ssl2_HandleClientHelloMessage()
 
586
 * ssl2_HandleClientHelloMessage()  <- ssl_Do1stHandshake() 
 
587
                                      after ssl2_BeginServerHandshake()
 
588
 * Acquires and releases the socket's xmitBufLock.
 
589
 */
 
590
static SECStatus
 
591
ssl2_SendServerVerifyMessage(sslSocket *ss)
 
592
{
 
593
    PRUint8 *        msg;
 
594
    int              sendLen;
 
595
    int              sent;
 
596
    SECStatus        rv;
 
597
 
 
598
    PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) );
 
599
 
 
600
    ssl_GetXmitBufLock(ss);    /***************************************/
 
601
 
 
602
    sendLen = 1 + SSL_CHALLENGE_BYTES;
 
603
    rv = ssl2_GetSendBuffer(ss, sendLen);
 
604
    if (rv != SECSuccess) {
 
605
        goto done;
 
606
    }
 
607
 
 
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);
 
611
 
 
612
    DUMP_MSG(29, (ss, msg, sendLen));
 
613
    sent = (*ss->sec.send)(ss, msg, sendLen, 0);
 
614
 
 
615
    rv = (sent >= 0) ? SECSuccess : (SECStatus)sent;
 
616
 
 
617
done:
 
618
    ssl_ReleaseXmitBufLock(ss);    /***************************************/
 
619
    return rv;
 
620
}
 
621
 
 
622
/* Called from ssl2_TryToFinish(). 
 
623
 * Acquires and releases the socket's xmitBufLock.
 
624
 */
 
625
static SECStatus
 
626
ssl2_SendServerFinishedMessage(sslSocket *ss)
 
627
{
 
628
    sslSessionID *   sid;
 
629
    PRUint8 *        msg;
 
630
    int              sendLen, sent;
 
631
    SECStatus        rv    = SECSuccess;
 
632
 
 
633
    PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) );
 
634
 
 
635
    ssl_GetXmitBufLock(ss);    /***************************************/
 
636
 
 
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;
 
641
 
 
642
        SSL_TRC(3, ("%d: SSL[%d]: sending server-finished",
 
643
                    SSL_GETPID(), ss->fd));
 
644
 
 
645
        sendLen = 1 + sizeof(sid->u.ssl2.sessionID);
 
646
        rv = ssl2_GetSendBuffer(ss, sendLen);
 
647
        if (rv != SECSuccess) {
 
648
            goto done;
 
649
        }
 
650
 
 
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));
 
655
 
 
656
        DUMP_MSG(29, (ss, msg, sendLen));
 
657
        sent = (*ss->sec.send)(ss, msg, sendLen, 0);
 
658
 
 
659
        if (sent < 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);
 
666
            rv = SECSuccess;
 
667
        }
 
668
        ssl_FreeSID(sid);
 
669
        ss->sec.ci.sid = 0;
 
670
    }
 
671
done:
 
672
    ssl_ReleaseXmitBufLock(ss);    /***************************************/
 
673
    return rv;
 
674
}
 
675
 
 
676
/* Called from ssl2_ClientSetupSessionCypher() <- 
 
677
 *                                              ssl2_HandleServerHelloMessage() 
 
678
 *                                           after ssl2_BeginClientHandshake()
 
679
 * Acquires and releases the socket's xmitBufLock.
 
680
 */
 
681
static SECStatus
 
682
ssl2_SendSessionKeyMessage(sslSocket *ss, int cipher, int keySize,
 
683
                      PRUint8 *ca, int caLen,
 
684
                      PRUint8 *ck, int ckLen,
 
685
                      PRUint8 *ek, int ekLen)
 
686
{
 
687
    PRUint8 *        msg;
 
688
    int              sendLen;
 
689
    int              sent;
 
690
    SECStatus        rv;
 
691
 
 
692
    PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) );
 
693
 
 
694
    ssl_GetXmitBufLock(ss);    /***************************************/
 
695
 
 
696
    sendLen = SSL_HL_CLIENT_MASTER_KEY_HBYTES + ckLen + ekLen + caLen;
 
697
    rv = ssl2_GetSendBuffer(ss, sendLen);
 
698
    if (rv != SECSuccess) 
 
699
        goto done;
 
700
 
 
701
    SSL_TRC(3, ("%d: SSL[%d]: sending client-session-key",
 
702
                SSL_GETPID(), ss->fd));
 
703
 
 
704
    msg = ss->sec.ci.sendBuf.buf;
 
705
    msg[0] = SSL_MT_CLIENT_MASTER_KEY;
 
706
    msg[1] = cipher;
 
707
    msg[2] = MSB(keySize);
 
708
    msg[3] = LSB(keySize);
 
709
    msg[4] = MSB(ckLen);
 
710
    msg[5] = LSB(ckLen);
 
711
    msg[6] = MSB(ekLen);
 
712
    msg[7] = LSB(ekLen);
 
713
    msg[8] = MSB(caLen);
 
714
    msg[9] = LSB(caLen);
 
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);
 
718
 
 
719
    DUMP_MSG(29, (ss, msg, sendLen));
 
720
    sent = (*ss->sec.send)(ss, msg, sendLen, 0);
 
721
    rv = (sent >= 0) ? SECSuccess : (SECStatus)sent;
 
722
done:
 
723
    ssl_ReleaseXmitBufLock(ss);    /***************************************/
 
724
    return rv;
 
725
}
 
726
 
 
727
/* Called from ssl2_TriggerNextMessage() <- ssl2_HandleMessage() 
 
728
 * Acquires and releases the socket's xmitBufLock.
 
729
 */
 
730
static SECStatus
 
731
ssl2_SendCertificateRequestMessage(sslSocket *ss)
 
732
{
 
733
    PRUint8 *        msg;
 
734
    int              sent;
 
735
    int              sendLen;
 
736
    SECStatus        rv;
 
737
 
 
738
    PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) );
 
739
 
 
740
    ssl_GetXmitBufLock(ss);    /***************************************/
 
741
 
 
742
    sendLen = SSL_HL_REQUEST_CERTIFICATE_HBYTES + SSL_CHALLENGE_BYTES;
 
743
    rv = ssl2_GetSendBuffer(ss, sendLen);
 
744
    if (rv != SECSuccess) 
 
745
        goto done;
 
746
 
 
747
    SSL_TRC(3, ("%d: SSL[%d]: sending certificate request",
 
748
                SSL_GETPID(), ss->fd));
 
749
 
 
750
    /* Generate random challenge for client to encrypt */
 
751
    PK11_GenerateRandom(ss->sec.ci.serverChallenge, SSL_CHALLENGE_BYTES);
 
752
 
 
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);
 
758
 
 
759
    DUMP_MSG(29, (ss, msg, sendLen));
 
760
    sent = (*ss->sec.send)(ss, msg, sendLen, 0);
 
761
    rv = (sent >= 0) ? SECSuccess : (SECStatus)sent;
 
762
done:
 
763
    ssl_ReleaseXmitBufLock(ss);    /***************************************/
 
764
    return rv;
 
765
}
 
766
 
 
767
/* Called from ssl2_HandleRequestCertificate() <- ssl2_HandleMessage()
 
768
 *             ssl2_RestartHandshakeAfterCertReq() <- (application)
 
769
 * Acquires and releases the socket's xmitBufLock.
 
770
 */
 
771
static int
 
772
ssl2_SendCertificateResponseMessage(sslSocket *ss, SECItem *cert, 
 
773
                                    SECItem *encCode)
 
774
{
 
775
    PRUint8 *msg;
 
776
    int rv, sendLen;
 
777
 
 
778
    PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) );
 
779
 
 
780
    ssl_GetXmitBufLock(ss);    /***************************************/
 
781
 
 
782
    sendLen = SSL_HL_CLIENT_CERTIFICATE_HBYTES + encCode->len + cert->len;
 
783
    rv = ssl2_GetSendBuffer(ss, sendLen);
 
784
    if (rv) 
 
785
        goto done;
 
786
 
 
787
    SSL_TRC(3, ("%d: SSL[%d]: sending certificate response",
 
788
                SSL_GETPID(), ss->fd));
 
789
 
 
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);
 
800
 
 
801
    DUMP_MSG(29, (ss, msg, sendLen));
 
802
    rv = (*ss->sec.send)(ss, msg, sendLen, 0);
 
803
    if (rv >= 0) {
 
804
        rv = SECSuccess;
 
805
    }
 
806
done:
 
807
    ssl_ReleaseXmitBufLock(ss);    /***************************************/
 
808
    return rv;
 
809
}
 
810
 
 
811
/********************************************************************
 
812
**  Send functions above this line must aquire & release the socket's   
 
813
**      xmitBufLock.  
 
814
** All the ssl2_Send functions below this line are called vis ss->sec.send
 
815
**      and require that the caller hold the xmitBufLock.
 
816
*/
 
817
 
 
818
/*
 
819
** Called from ssl2_SendStream, ssl2_SendBlock, but not from ssl2_SendClear.
 
820
*/
 
821
static SECStatus
 
822
ssl2_CalcMAC(PRUint8             * result, 
 
823
             sslSecurityInfo     * sec,
 
824
             const PRUint8       * data, 
 
825
             unsigned int          dataLen,
 
826
             unsigned int          paddingLen)
 
827
{
 
828
    const PRUint8 *      secret         = sec->sendSecret.data;
 
829
    unsigned int         secretLen      = sec->sendSecret.len;
 
830
    unsigned long        sequenceNumber = sec->sendSequence;
 
831
    unsigned int         nout;
 
832
    PRUint8              seq[4];
 
833
    PRUint8              padding[32];/* XXX max blocksize? */
 
834
 
 
835
    if (!sec->hash || !sec->hash->length)
 
836
        return SECSuccess;
 
837
    if (!sec->hashcx)
 
838
        return SECFailure;
 
839
 
 
840
    /* Reset hash function */
 
841
    (*sec->hash->begin)(sec->hashcx);
 
842
 
 
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);
 
848
 
 
849
    seq[0] = (PRUint8) (sequenceNumber >> 24);
 
850
    seq[1] = (PRUint8) (sequenceNumber >> 16);
 
851
    seq[2] = (PRUint8) (sequenceNumber >> 8);
 
852
    seq[3] = (PRUint8) (sequenceNumber);
 
853
 
 
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));
 
858
 
 
859
    (*sec->hash->update)(sec->hashcx, seq, 4);
 
860
 
 
861
    /* Get result */
 
862
    (*sec->hash->end)(sec->hashcx, result, &nout, sec->hash->length);
 
863
 
 
864
    return SECSuccess;
 
865
}
 
866
 
 
867
/*
 
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.
 
872
*/
 
873
#define MAX_STREAM_CYPHER_LEN   0x7fe0
 
874
#define MAX_BLOCK_CYPHER_LEN    0x3fe0
 
875
 
 
876
/*
 
877
** Send some data in the clear. 
 
878
** Package up data with the length header and send it.
 
879
**
 
880
** Return count of bytes succesfully written, or negative number (failure).
 
881
*/
 
882
static PRInt32 
 
883
ssl2_SendClear(sslSocket *ss, const PRUint8 *in, PRInt32 len, PRInt32 flags)
 
884
{
 
885
    PRUint8         * out;
 
886
    int               rv;
 
887
    int               amount;
 
888
    int               count     = 0;
 
889
 
 
890
    PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
 
891
 
 
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));
 
895
 
 
896
    while (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) {
 
901
                count = rv;
 
902
                break;
 
903
            }
 
904
        }
 
905
        out = ss->sec.writeBuf.buf;
 
906
 
 
907
        /*
 
908
        ** Construct message.
 
909
        */
 
910
        out[0] = 0x80 | MSB(amount);
 
911
        out[1] = LSB(amount);
 
912
        PORT_Memcpy(&out[2], in, amount);
 
913
 
 
914
        /* Now send the data */
 
915
        rv = ssl_DefSend(ss, out, amount + 2, flags & ~ssl_SEND_FLAG_MASK);
 
916
        if (rv < 0) {
 
917
            if (PORT_GetError() == PR_WOULD_BLOCK_ERROR) {
 
918
                rv = 0;
 
919
            } else {
 
920
                /* Return short write if some data already went out... */
 
921
                if (count == 0)
 
922
                    count = rv;
 
923
                break;
 
924
            }
 
925
        }
 
926
 
 
927
        if ((unsigned)rv < (amount + 2)) {
 
928
            /* Short write.  Save the data and return. */
 
929
            if (ssl_SaveWriteData(ss, out + rv, amount + 2 - rv) 
 
930
                == SECFailure) {
 
931
                count = SECFailure;
 
932
            } else {
 
933
                count += amount;
 
934
                ss->sec.sendSequence++;
 
935
            }
 
936
            break;
 
937
        }
 
938
 
 
939
        ss->sec.sendSequence++;
 
940
        in    += amount;
 
941
        count += amount;
 
942
        len   -= amount;
 
943
    }
 
944
 
 
945
    return count;
 
946
}
 
947
 
 
948
/*
 
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
 
951
** and send it.
 
952
*/
 
953
static PRInt32 
 
954
ssl2_SendStream(sslSocket *ss, const PRUint8 *in, PRInt32 len, PRInt32 flags)
 
955
{
 
956
    PRUint8       *  out;
 
957
    int              rv;
 
958
    int              count      = 0;
 
959
 
 
960
    int              amount;
 
961
    PRUint8          macLen;
 
962
    int              nout;
 
963
    int              buflen;
 
964
 
 
965
    PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
 
966
 
 
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));
 
970
 
 
971
    while (len) {
 
972
        ssl_GetSpecReadLock(ss);  /*************************************/
 
973
 
 
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) {
 
980
                goto loser;
 
981
            }
 
982
        }
 
983
        out    = ss->sec.writeBuf.buf;
 
984
        nout   = amount + macLen;
 
985
        out[0] = 0x80 | MSB(nout);
 
986
        out[1] = LSB(nout);
 
987
 
 
988
        /* Calculate MAC */
 
989
        rv = ssl2_CalcMAC(out+2,                /* put MAC here */
 
990
                          &ss->sec, 
 
991
                          in, amount,           /* input addr & length */
 
992
                          0);                   /* no padding */
 
993
        if (rv != SECSuccess) 
 
994
            goto loser;
 
995
 
 
996
        /* Encrypt MAC */
 
997
        rv = (*ss->sec.enc)(ss->sec.writecx, out+2, &nout, macLen, out+2, macLen);
 
998
        if (rv) goto loser;
 
999
 
 
1000
        /* Encrypt data from caller */
 
1001
        rv = (*ss->sec.enc)(ss->sec.writecx, out+2+macLen, &nout, amount, in, amount);
 
1002
        if (rv) goto loser;
 
1003
 
 
1004
        ssl_ReleaseSpecReadLock(ss);  /*************************************/
 
1005
 
 
1006
        PRINT_BUF(50, (ss, "encrypted data:", out, buflen));
 
1007
 
 
1008
        rv = ssl_DefSend(ss, out, buflen, flags & ~ssl_SEND_FLAG_MASK);
 
1009
        if (rv < 0) {
 
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));
 
1013
                rv = 0;
 
1014
            } else {
 
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... */
 
1018
                if (count == 0)
 
1019
                    count = rv;
 
1020
                goto done;
 
1021
            }
 
1022
        }
 
1023
 
 
1024
        if ((unsigned)rv < buflen) {
 
1025
            /* Short write.  Save the data and return. */
 
1026
            if (ssl_SaveWriteData(ss, out + rv, buflen - rv) == SECFailure) {
 
1027
                count = SECFailure;
 
1028
            } else {
 
1029
                count += amount;
 
1030
                ss->sec.sendSequence++;
 
1031
            }
 
1032
            goto done;
 
1033
        }
 
1034
 
 
1035
        ss->sec.sendSequence++;
 
1036
        in    += amount;
 
1037
        count += amount;
 
1038
        len   -= amount;
 
1039
    }
 
1040
 
 
1041
done:
 
1042
    return count;
 
1043
 
 
1044
loser:
 
1045
    ssl_ReleaseSpecReadLock(ss);
 
1046
    return SECFailure;
 
1047
}
 
1048
 
 
1049
/*
 
1050
** Send some data, when using a block cipher. Package up the data with
 
1051
** the length header and send it.
 
1052
*/
 
1053
/* XXX assumes blocksize is > 7 */
 
1054
static PRInt32
 
1055
ssl2_SendBlock(sslSocket *ss, const PRUint8 *in, PRInt32 len, PRInt32 flags)
 
1056
{
 
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. */
 
1061
 
 
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.     */
 
1068
 
 
1069
    PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
 
1070
 
 
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));
 
1074
 
 
1075
    while (len) {
 
1076
        ssl_GetSpecReadLock(ss);  /*************************************/
 
1077
 
 
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);
 
1083
        if (padding) {
 
1084
            hlen    = 3;
 
1085
            padding = ss->sec.blockSize - padding;
 
1086
            nout   += padding;
 
1087
        } else {
 
1088
            hlen = 2;
 
1089
        }
 
1090
        buflen = hlen + nout;
 
1091
        if (buflen > ss->sec.writeBuf.space) {
 
1092
            rv = sslBuffer_Grow(&ss->sec.writeBuf, buflen);
 
1093
            if (rv != SECSuccess) {
 
1094
                goto loser;
 
1095
            }
 
1096
        }
 
1097
        out = ss->sec.writeBuf.buf;
 
1098
 
 
1099
        /* Construct header */
 
1100
        op = out;
 
1101
        if (padding) {
 
1102
            *op++ = MSB(nout);
 
1103
            *op++ = LSB(nout);
 
1104
            *op++ = padding;
 
1105
        } else {
 
1106
            *op++ = 0x80 | MSB(nout);
 
1107
            *op++ = LSB(nout);
 
1108
        }
 
1109
 
 
1110
        /* Calculate MAC */
 
1111
        rv = ssl2_CalcMAC(op,           /* MAC goes here. */
 
1112
                          &ss->sec, 
 
1113
                          in, amount,   /* intput addr, len */
 
1114
                          padding);
 
1115
        if (rv != SECSuccess) 
 
1116
            goto loser;
 
1117
        op += macLen;
 
1118
 
 
1119
        /* Copy in the input data */
 
1120
        /* XXX could eliminate the copy by folding it into the encryption */
 
1121
        PORT_Memcpy(op, in, amount);
 
1122
        op += amount;
 
1123
        if (padding) {
 
1124
            PORT_Memset(op, padding, padding);
 
1125
            op += padding;
 
1126
        }
 
1127
 
 
1128
        /* Encrypt result */
 
1129
        rv = (*ss->sec.enc)(ss->sec.writecx, out+hlen, &nout, buflen-hlen,
 
1130
                         out+hlen, op - (out + hlen));
 
1131
        if (rv) 
 
1132
            goto loser;
 
1133
 
 
1134
        ssl_ReleaseSpecReadLock(ss);  /*************************************/
 
1135
 
 
1136
        PRINT_BUF(50, (ss, "final xmit data:", out, op - out));
 
1137
 
 
1138
        rv = ssl_DefSend(ss, out, op - out, flags & ~ssl_SEND_FLAG_MASK);
 
1139
        if (rv < 0) {
 
1140
            if (PORT_GetError() == PR_WOULD_BLOCK_ERROR) {
 
1141
                rv = 0;
 
1142
            } else {
 
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... */
 
1146
                if (count == 0)
 
1147
                    count = rv;
 
1148
                goto done;
 
1149
            }
 
1150
        }
 
1151
 
 
1152
        if (rv < (op - out)) {
 
1153
            /* Short write.  Save the data and return. */
 
1154
            if (ssl_SaveWriteData(ss, out + rv, op - out - rv) == SECFailure) {
 
1155
                count = SECFailure;
 
1156
            } else {
 
1157
                count += amount;
 
1158
                ss->sec.sendSequence++;
 
1159
            }
 
1160
            goto done;
 
1161
        }
 
1162
 
 
1163
        ss->sec.sendSequence++;
 
1164
        in    += amount;
 
1165
        count += amount;
 
1166
        len   -= amount;
 
1167
    }
 
1168
 
 
1169
done:
 
1170
    return count;
 
1171
 
 
1172
loser:
 
1173
    ssl_ReleaseSpecReadLock(ss);
 
1174
    return SECFailure;
 
1175
}
 
1176
 
 
1177
/*
 
1178
** Called from: ssl2_HandleServerHelloMessage,
 
1179
**              ssl2_HandleClientSessionKeyMessage,
 
1180
**              ssl2_RestartHandshakeAfterServerCert,
 
1181
**              ssl2_HandleClientHelloMessage,
 
1182
**              
 
1183
*/
 
1184
static void
 
1185
ssl2_UseEncryptedSendFunc(sslSocket *ss)
 
1186
{
 
1187
    ssl_GetXmitBufLock(ss);
 
1188
    PORT_Assert(ss->sec.hashcx != 0);
 
1189
 
 
1190
    ss->gs.encrypted = 1;
 
1191
    ss->sec.send = (ss->sec.blockSize > 1) ? ssl2_SendBlock : ssl2_SendStream;
 
1192
    ssl_ReleaseXmitBufLock(ss);
 
1193
}
 
1194
 
 
1195
/* Called while initializing socket in ssl_CreateSecurityInfo().
 
1196
** This function allows us to keep the name of ssl2_SendClear static.
 
1197
*/
 
1198
void
 
1199
ssl2_UseClearSendFunc(sslSocket *ss)
 
1200
{
 
1201
    ss->sec.send = ssl2_SendClear;
 
1202
}
 
1203
 
 
1204
/************************************************************************
 
1205
**                      END of Send functions.                          * 
 
1206
*************************************************************************/
 
1207
 
 
1208
/***********************************************************************
 
1209
 * For SSL3, this gathers in and handles records/messages until either 
 
1210
 *      the handshake is complete or application data is available.
 
1211
 *
 
1212
 * For SSL2, this gathers in only the next SSLV2 record.
 
1213
 *
 
1214
 * Called from ssl_Do1stHandshake() via function pointer ss->handshake.
 
1215
 * Caller must hold handshake lock.
 
1216
 * This function acquires and releases the RecvBufLock.
 
1217
 *
 
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.
 
1222
 *
 
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.
 
1230
 *
 
1231
 * This code is similar to, and easily confused with, DoRecv() in sslsecur.c
 
1232
 *
 
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
 
1246
 */
 
1247
SECStatus
 
1248
ssl_GatherRecord1stHandshake(sslSocket *ss)
 
1249
{
 
1250
    int rv;
 
1251
 
 
1252
    PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) );
 
1253
 
 
1254
    ssl_GetRecvBufLock(ss);
 
1255
 
 
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);
 
1259
    } else {
 
1260
        /* See if we have a complete record */
 
1261
        rv = ssl2_GatherRecord(ss, 0);
 
1262
    }
 
1263
    SSL_TRC(10, ("%d: SSL[%d]: handshake gathering, rv=%d",
 
1264
                 SSL_GETPID(), ss->fd, rv));
 
1265
 
 
1266
    ssl_ReleaseRecvBufLock(ss);
 
1267
 
 
1268
    if (rv <= 0) {
 
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;
 
1274
        }
 
1275
        if (rv == 0) {
 
1276
            /* EOF. Loser  */
 
1277
            PORT_SetError(PR_END_OF_FILE_ERROR);
 
1278
        }
 
1279
        return SECFailure;      /* rv is < 0 here. */
 
1280
    }
 
1281
 
 
1282
    SSL_TRC(10, ("%d: SSL[%d]: got handshake record of %d bytes",
 
1283
                 SSL_GETPID(), ss->fd, ss->gs.recordLen));
 
1284
 
 
1285
    ss->handshake = 0;  /* makes ssl_Do1stHandshake call ss->nextHandshake.*/
 
1286
    return SECSuccess;
 
1287
}
 
1288
 
 
1289
/************************************************************************/
 
1290
 
 
1291
/* Called from ssl2_ServerSetupSessionCypher()
 
1292
 *             ssl2_ClientSetupSessionCypher()
 
1293
 */
 
1294
static SECStatus
 
1295
ssl2_FillInSID(sslSessionID * sid, 
 
1296
          int            cipher,
 
1297
          PRUint8       *keyData, 
 
1298
          int            keyLen,
 
1299
          PRUint8       *ca, 
 
1300
          int            caLen,
 
1301
          int            keyBits, 
 
1302
          int            secretKeyBits,
 
1303
          SSLSignType    authAlgorithm,
 
1304
          PRUint32       authKeyBits,
 
1305
          SSLKEAType     keaType,
 
1306
          PRUint32       keaKeyBits)
 
1307
{
 
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);
 
1312
 
 
1313
    sid->version = SSL_LIBRARY_VERSION_2;
 
1314
 
 
1315
    sid->u.ssl2.cipherType = cipher;
 
1316
    sid->u.ssl2.masterKey.data = (PRUint8*) PORT_Alloc(keyLen);
 
1317
    if (!sid->u.ssl2.masterKey.data) {
 
1318
        return SECFailure;
 
1319
    }
 
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;
 
1330
 
 
1331
    if (caLen) {
 
1332
        sid->u.ssl2.cipherArg.data = (PRUint8*) PORT_Alloc(caLen);
 
1333
        if (!sid->u.ssl2.cipherArg.data) {
 
1334
            return SECFailure;
 
1335
        }
 
1336
        sid->u.ssl2.cipherArg.len = caLen;
 
1337
        PORT_Memcpy(sid->u.ssl2.cipherArg.data, ca, caLen);
 
1338
    }
 
1339
    return SECSuccess;
 
1340
}
 
1341
 
 
1342
/*
 
1343
** Construct session keys given the masterKey (tied to the session-id),
 
1344
** the client's challenge and the server's nonce.
 
1345
**
 
1346
** Called from ssl2_CreateSessionCypher() <-
 
1347
*/
 
1348
static SECStatus
 
1349
ssl2_ProduceKeys(sslSocket *    ss, 
 
1350
            SECItem *      readKey, 
 
1351
            SECItem *      writeKey,
 
1352
            SECItem *      masterKey, 
 
1353
            PRUint8 *      challenge,
 
1354
            PRUint8 *      nonce, 
 
1355
            int            cipherType)
 
1356
{
 
1357
    PK11Context * cx        = 0;
 
1358
    unsigned      nkm       = 0; /* number of hashes to generate key mat. */
 
1359
    unsigned      nkd       = 0; /* size of readKey and writeKey. */
 
1360
    unsigned      part;
 
1361
    unsigned      i;
 
1362
    unsigned      off;
 
1363
    SECStatus     rv;
 
1364
    PRUint8       countChar;
 
1365
    PRUint8       km[3*16];     /* buffer for key material. */
 
1366
 
 
1367
    readKey->data = 0;
 
1368
    writeKey->data = 0;
 
1369
 
 
1370
    PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) );
 
1371
 
 
1372
    rv = SECSuccess;
 
1373
    cx = PK11_CreateDigestContext(SEC_OID_MD5);
 
1374
    if (cx == NULL) {
 
1375
        ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
 
1376
        return SECFailure;
 
1377
    }
 
1378
 
 
1379
    nkm = ssl_Specs[cipherType].nkm;
 
1380
    nkd = ssl_Specs[cipherType].nkd;
 
1381
 
 
1382
    readKey->data = (PRUint8*) PORT_Alloc(nkd);
 
1383
    if (!readKey->data) 
 
1384
        goto loser;
 
1385
    readKey->len = nkd;
 
1386
 
 
1387
    writeKey->data = (PRUint8*) PORT_Alloc(nkd);
 
1388
    if (!writeKey->data) 
 
1389
        goto loser;
 
1390
    writeKey->len = nkd;
 
1391
 
 
1392
    /* Produce key material */
 
1393
    countChar = '0';
 
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);
 
1403
            rv = SECFailure;
 
1404
            goto loser;
 
1405
        }
 
1406
        countChar++;
 
1407
    }
 
1408
 
 
1409
    /* Produce keys */
 
1410
    PORT_Memcpy(readKey->data,  km,       nkd);
 
1411
    PORT_Memcpy(writeKey->data, km + nkd, nkd);
 
1412
 
 
1413
loser:
 
1414
    PK11_DestroyContext(cx, PR_TRUE);
 
1415
    return rv;
 
1416
}
 
1417
 
 
1418
/* Called from ssl2_ServerSetupSessionCypher() 
 
1419
**                  <- ssl2_HandleClientSessionKeyMessage()
 
1420
**                          <- ssl2_HandleClientHelloMessage()
 
1421
** and from    ssl2_ClientSetupSessionCypher() 
 
1422
**                  <- ssl2_HandleServerHelloMessage()
 
1423
*/
 
1424
static SECStatus
 
1425
ssl2_CreateSessionCypher(sslSocket *ss, sslSessionID *sid, PRBool isClient)
 
1426
{
 
1427
    SECItem         * rk = NULL;
 
1428
    SECItem         * wk = NULL;
 
1429
    SECItem *         param;
 
1430
    SECStatus         rv;
 
1431
    int               cipherType  = sid->u.ssl2.cipherType;
 
1432
    PK11SlotInfo *    slot        = NULL;
 
1433
    CK_MECHANISM_TYPE mechanism;
 
1434
    SECItem           readKey;
 
1435
    SECItem           writeKey;
 
1436
 
 
1437
    void *readcx = 0;
 
1438
    void *writecx = 0;
 
1439
    readKey.data = 0;
 
1440
    writeKey.data = 0;
 
1441
 
 
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 */
 
1445
 
 
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. 
 
1448
     */
 
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:
 
1456
        break;
 
1457
 
 
1458
    default:
 
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);
 
1462
        goto sec_loser;
 
1463
    }
 
1464
 
 
1465
    rk = isClient ? &readKey  : &writeKey;
 
1466
    wk = isClient ? &writeKey : &readKey;
 
1467
 
 
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,
 
1471
                     cipherType);
 
1472
    if (rv != SECSuccess) 
 
1473
        goto loser;
 
1474
    PRINT_BUF(7, (ss, "Session read-key: ", rk->data, rk->len));
 
1475
    PRINT_BUF(7, (ss, "Session write-key: ", wk->data, wk->len));
 
1476
 
 
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;
 
1480
 
 
1481
    /* Setup the MAC */
 
1482
    rv = ssl2_CreateMAC(&ss->sec, rk, wk, cipherType);
 
1483
    if (rv != SECSuccess) 
 
1484
        goto loser;
 
1485
 
 
1486
    /* First create the session key object */
 
1487
    SSL_TRC(3, ("%d: SSL[%d]: using %s", SSL_GETPID(), ss->fd,
 
1488
            ssl_cipherName[cipherType]));
 
1489
 
 
1490
 
 
1491
    mechanism  = ssl_Specs[cipherType].mechanism;
 
1492
 
 
1493
    /* set destructer before we call loser... */
 
1494
    ss->sec.destroy = (void (*)(void*, PRBool)) PK11_DestroyContext;
 
1495
    slot = PK11_GetBestSlot(mechanism, ss->pkcs11PinArg);
 
1496
    if (slot == NULL)
 
1497
        goto loser;
 
1498
 
 
1499
    param = PK11_ParamFromIV(mechanism, &sid->u.ssl2.cipherArg);
 
1500
    if (param == NULL)
 
1501
        goto loser;
 
1502
    readcx = PK11_CreateContextByRawKey(slot, mechanism, PK11_OriginUnwrap,
 
1503
                                        CKA_DECRYPT, rk, param,
 
1504
                                        ss->pkcs11PinArg);
 
1505
    SECITEM_FreeItem(param, PR_TRUE);
 
1506
    if (readcx == NULL)
 
1507
        goto loser;
 
1508
 
 
1509
    /* build the client context */
 
1510
    param = PK11_ParamFromIV(mechanism, &sid->u.ssl2.cipherArg);
 
1511
    if (param == NULL)
 
1512
        goto loser;
 
1513
    writecx = PK11_CreateContextByRawKey(slot, mechanism, PK11_OriginUnwrap,
 
1514
                                         CKA_ENCRYPT, wk, param,
 
1515
                                         ss->pkcs11PinArg);
 
1516
    SECITEM_FreeItem(param,PR_TRUE);
 
1517
    if (writecx == NULL)
 
1518
        goto loser;
 
1519
    PK11_FreeSlot(slot);
 
1520
 
 
1521
    rv = SECSuccess;
 
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;
 
1531
    goto done;
 
1532
 
 
1533
  loser:
 
1534
    if (ss->sec.destroy) {
 
1535
        if (readcx)  (*ss->sec.destroy)(readcx, PR_TRUE);
 
1536
        if (writecx) (*ss->sec.destroy)(writecx, PR_TRUE);
 
1537
    }
 
1538
    ss->sec.destroy = NULL;
 
1539
    if (slot) PK11_FreeSlot(slot);
 
1540
 
 
1541
  sec_loser:
 
1542
    rv = SECFailure;
 
1543
 
 
1544
  done:
 
1545
    if (rk) {
 
1546
        SECITEM_ZfreeItem(rk, PR_FALSE);
 
1547
    }
 
1548
    if (wk) {
 
1549
        SECITEM_ZfreeItem(wk, PR_FALSE);
 
1550
    }
 
1551
    return rv;
 
1552
}
 
1553
 
 
1554
/*
 
1555
** Setup the server ciphers given information from a CLIENT-MASTER-KEY
 
1556
** message.
 
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
 
1566
**
 
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
 
1572
** spec).
 
1573
**
 
1574
** Called from ssl2_HandleClientSessionKeyMessage().
 
1575
*/
 
1576
static SECStatus
 
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)
 
1581
{
 
1582
    PRUint8           *kk = NULL;
 
1583
    sslSessionID *    sid;
 
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;
 
1588
    SECStatus         rv;
 
1589
    PRUint8           mkbuf[SSL_MAX_MASTER_KEY_BYTES];
 
1590
    sslServerCerts  * sc = ss->serverCerts + kt_rsa;
 
1591
 
 
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;
 
1597
 
 
1598
    keySize = (keyBits + 7) >> 3;
 
1599
    /* Is the message just way too big? */
 
1600
    if (keySize > SSL_MAX_MASTER_KEY_BYTES) {
 
1601
        /* bummer */
 
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);
 
1606
        goto loser;
 
1607
    }
 
1608
 
 
1609
 
 
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. 
 
1612
     */
 
1613
    switch (cipher) {
 
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:
 
1620
        break;
 
1621
 
 
1622
    default:
 
1623
        SSL_DBG(("%d: SSL[%d]: ssl2_ServerSetupSessionCypher: unknown cipher=%d",
 
1624
                 SSL_GETPID(), ss->fd, cipher));
 
1625
        PORT_SetError(SSL_ERROR_BAD_CLIENT);
 
1626
        goto loser;
 
1627
    }
 
1628
 
 
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);
 
1635
        goto loser;
 
1636
    }
 
1637
 
 
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);
 
1641
    if (!kbuf) {
 
1642
        goto loser;
 
1643
    }
 
1644
 
 
1645
    /*
 
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.
 
1651
    */
 
1652
    rv = PK11_PubDecryptRaw(sc->SERVERKEY, kbuf, &el1, ekLen, ek, ekLen);
 
1653
    if (rv != SECSuccess) 
 
1654
        goto hide_loser;
 
1655
 
 
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 */
 
1663
        modulusLen = ekLen;
 
1664
    }
 
1665
    /* Is the length of the decrypted data (el1) the expected value? */
 
1666
    if (modulusLen != el1) 
 
1667
        goto hide_loser;
 
1668
 
 
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)) {
 
1672
        /* Tsk tsk. */
 
1673
        SSL_DBG(("%d: SSL[%d]: strange encryption block",
 
1674
                 SSL_GETPID(), ss->fd));
 
1675
        PORT_SetError(SSL_ERROR_BAD_CLIENT);
 
1676
        goto hide_loser;
 
1677
    }
 
1678
 
 
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 };
 
1683
        
 
1684
        if (PORT_Memcmp(kk - 8 - 1, threes, 8) == 0) {
 
1685
            PORT_SetError(SSL_ERROR_BAD_CLIENT);
 
1686
            goto hide_loser;
 
1687
        }
 
1688
    }
 
1689
    if (0) {
 
1690
hide_loser:
 
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 .
 
1695
         */
 
1696
        PK11_GenerateRandom(kbuf, ekLen);
 
1697
        if (!kk) {
 
1698
            kk = kbuf + ekLen - (keySize-ckLen);
 
1699
        }
 
1700
    }
 
1701
 
 
1702
    /*
 
1703
    ** Construct master key out of the pieces.
 
1704
    */
 
1705
    if (ckLen) {
 
1706
        PORT_Memcpy(mkbuf, ck, ckLen);
 
1707
    }
 
1708
    PORT_Memcpy(mkbuf+ckLen, kk, keySize-ckLen);
 
1709
 
 
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) {
 
1716
        goto loser;
 
1717
    }
 
1718
 
 
1719
    /* Create session ciphers */
 
1720
    rv = ssl2_CreateSessionCypher(ss, sid, PR_FALSE);
 
1721
    if (rv != SECSuccess) {
 
1722
        goto loser;
 
1723
    }
 
1724
 
 
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));
 
1728
    rv = SECSuccess;
 
1729
    goto done;
 
1730
 
 
1731
  loser:
 
1732
    rv = SECFailure;
 
1733
 
 
1734
  done:
 
1735
    PORT_Free(kbuf);
 
1736
    return rv;
 
1737
}
 
1738
 
 
1739
/************************************************************************/
 
1740
 
 
1741
/*
 
1742
** Rewrite the incoming cipher specs, comparing to list of specs we support,
 
1743
** (ss->cipherSpecs) and eliminating anything we don't support
 
1744
**
 
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.
 
1749
*
 
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.
 
1753
*/
 
1754
static int
 
1755
ssl2_QualifyCypherSpecs(sslSocket *ss, 
 
1756
                        PRUint8 *  cs, /* cipher specs in client hello msg. */
 
1757
                        int        csLen)
 
1758
{
 
1759
    PRUint8 *    ms;
 
1760
    PRUint8 *    hs;
 
1761
    PRUint8 *    qs;
 
1762
    int          mc;
 
1763
    int          hc;
 
1764
    PRUint8      qualifiedSpecs[ssl2_NUM_SUITES_IMPLEMENTED * 3];
 
1765
 
 
1766
    PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) );
 
1767
    PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss)   );
 
1768
 
 
1769
    if (!ss->cipherSpecs) {
 
1770
        SECStatus rv = ssl2_ConstructCipherSpecs(ss);
 
1771
        if (rv != SECSuccess || !ss->cipherSpecs) 
 
1772
            return 0;
 
1773
    }
 
1774
 
 
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) {
 
1779
        if (ms[0] == 0)
 
1780
            continue;
 
1781
        for (hs = cs, hc = csLen; hc > 0; hs += 3, hc -= 3) {
 
1782
            if ((hs[0] == ms[0]) &&
 
1783
                (hs[1] == ms[1]) &&
 
1784
                (hs[2] == ms[2])) {
 
1785
                /* Copy this cipher spec into the "keep" section */
 
1786
                qs[0] = hs[0];
 
1787
                qs[1] = hs[1];
 
1788
                qs[2] = hs[2];
 
1789
                qs   += 3;
 
1790
                break;
 
1791
            }
 
1792
        }
 
1793
    }
 
1794
    hc = qs - qualifiedSpecs;
 
1795
    PRINT_BUF(10, (ss, "qualified specs from client:", qualifiedSpecs, hc));
 
1796
    PORT_Memcpy(cs, qualifiedSpecs, hc);
 
1797
    return hc;
 
1798
}
 
1799
 
 
1800
/*
 
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.
 
1804
**
 
1805
** This is correct only for the client side, but presently
 
1806
** this function is only called from 
 
1807
**      ssl2_ClientSetupSessionCypher() <- ssl2_HandleServerHelloMessage()
 
1808
**
 
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.
 
1813
*/
 
1814
static int
 
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. */
 
1819
{
 
1820
    PRUint8 *       ms;
 
1821
    unsigned int    i;
 
1822
    int             bestKeySize;
 
1823
    int             bestRealKeySize;
 
1824
    int             bestCypher;
 
1825
    int             keySize;
 
1826
    int             realKeySize;
 
1827
    PRUint8 *       ohs               = hs;
 
1828
    const PRUint8 * preferred;
 
1829
    static const PRUint8 noneSuch[3] = { 0, 0, 0 };
 
1830
 
 
1831
    PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) );
 
1832
    PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss)   );
 
1833
 
 
1834
    if (!ss->cipherSpecs) {
 
1835
        SECStatus rv = ssl2_ConstructCipherSpecs(ss);
 
1836
        if (rv != SECSuccess || !ss->cipherSpecs) 
 
1837
            goto loser;
 
1838
    }
 
1839
 
 
1840
    if (!ss->preferredCipher) {
 
1841
        unsigned int allowed = ss->allowedByPolicy & ss->chosenPreference &
 
1842
                               SSL_CB_IMPLEMENTED;
 
1843
        if (allowed) {
 
1844
            preferred = implementedCipherSuites;
 
1845
            for (i = ssl2_NUM_SUITES_IMPLEMENTED; i > 0; --i) {
 
1846
                if (0 != (allowed & (1U << preferred[0]))) {
 
1847
                    ss->preferredCipher = preferred;
 
1848
                    break;
 
1849
                }
 
1850
                preferred += 3;
 
1851
            }
 
1852
        }
 
1853
    }
 
1854
    preferred = ss->preferredCipher ? ss->preferredCipher : noneSuch;
 
1855
    /*
 
1856
    ** Scan list of ciphers recieved from peer and look for a match in
 
1857
    ** our list.  
 
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.
 
1862
    */
 
1863
    bestKeySize = bestRealKeySize = 0;
 
1864
    bestCypher = -1;
 
1865
    while (--hc >= 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]) &&
 
1870
                 hs[0] != 0) {
 
1871
                /* Pick this cipher immediately! */
 
1872
                *pKeyLen = (((hs[1] << 8) | hs[2]) + 7) >> 3;
 
1873
                return hs[0];
 
1874
            }
 
1875
            if ((hs[0] == ms[0]) && (hs[1] == ms[1]) && (hs[2] == ms[2]) &&
 
1876
                 hs[0] != 0) {
 
1877
                /* Found a match */
 
1878
 
 
1879
                /* Use secret keySize to determine which cipher is best */
 
1880
                realKeySize = (hs[1] << 8) | hs[2];
 
1881
                switch (hs[0]) {
 
1882
                  case SSL_CK_RC4_128_EXPORT40_WITH_MD5:
 
1883
                  case SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5:
 
1884
                    keySize = 40;
 
1885
                    break;
 
1886
                  default:
 
1887
                    keySize = realKeySize;
 
1888
                    break;
 
1889
                }
 
1890
                if (keySize > bestKeySize) {
 
1891
                    bestCypher = hs[0];
 
1892
                    bestKeySize = keySize;
 
1893
                    bestRealKeySize = realKeySize;
 
1894
                }
 
1895
            }
 
1896
        }
 
1897
        hs += 3;
 
1898
    }
 
1899
    if (bestCypher < 0) {
 
1900
        /*
 
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.
 
1904
        */
 
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);
 
1911
        } else {
 
1912
            PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
 
1913
        }
 
1914
        SSL_DBG(("%d: SSL[%d]: no cipher overlap", SSL_GETPID(), ss->fd));
 
1915
        goto loser;
 
1916
    }
 
1917
    *pKeyLen = (bestRealKeySize + 7) >> 3;
 
1918
    return bestCypher;
 
1919
 
 
1920
  loser:
 
1921
    return -1;
 
1922
}
 
1923
 
 
1924
static SECStatus
 
1925
ssl2_ClientHandleServerCert(sslSocket *ss, PRUint8 *certData, int certLen)
 
1926
{
 
1927
    CERTCertificate *cert      = NULL;
 
1928
    SECItem          certItem;
 
1929
 
 
1930
    certItem.data = certData;
 
1931
    certItem.len  = certLen;
 
1932
 
 
1933
    /* decode the certificate */
 
1934
    cert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL,
 
1935
                                   PR_FALSE, PR_TRUE);
 
1936
    
 
1937
    if (cert == NULL) {
 
1938
        SSL_DBG(("%d: SSL[%d]: decode of server certificate fails",
 
1939
                 SSL_GETPID(), ss->fd));
 
1940
        PORT_SetError(SSL_ERROR_BAD_CERTIFICATE);
 
1941
        return SECFailure;
 
1942
    }
 
1943
 
 
1944
#ifdef TRACE
 
1945
    {
 
1946
        if (ssl_trace >= 1) {
 
1947
            char *issuer;
 
1948
            char *subject;
 
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"));
 
1955
            PORT_Free(issuer);
 
1956
            PORT_Free(subject);
 
1957
        }
 
1958
    }
 
1959
#endif
 
1960
 
 
1961
    ss->sec.peerCert = cert;
 
1962
    return SECSuccess;
 
1963
}
 
1964
 
 
1965
 
 
1966
/*
 
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.
 
1970
 */
 
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
 
1975
unsigned char *
 
1976
ssl_FormatSSL2Block(unsigned modulusLen, SECItem *data)
 
1977
{
 
1978
    unsigned char *block;
 
1979
    unsigned char *bp;
 
1980
    int padLen;
 
1981
    SECStatus rv;
 
1982
    int i;
 
1983
 
 
1984
    PORT_Assert (data->len <= (modulusLen - (3 + RSA_BLOCK_MIN_PAD_LEN)));
 
1985
    block = (unsigned char *) PORT_Alloc(modulusLen);
 
1986
    if (block == NULL)
 
1987
        return NULL;
 
1988
 
 
1989
    bp = block;
 
1990
 
 
1991
    /*
 
1992
     * All RSA blocks start with two octets:
 
1993
     *  0x00 || BlockType
 
1994
     */
 
1995
    *bp++ = RSA_BLOCK_FIRST_OCTET;
 
1996
    *bp++ = RSA_BLOCK_PUBLIC_OCTET;
 
1997
 
 
1998
    /*
 
1999
     * 0x00 || BT || Pad || 0x00 || ActualData
 
2000
     *   1      1   padLen    1      data->len
 
2001
     * Pad is all non-zero random bytes.
 
2002
     */
 
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;
 
2012
        }
 
2013
    }
 
2014
    bp += padLen;
 
2015
    *bp++ = RSA_BLOCK_AFTER_PAD_OCTET;
 
2016
    PORT_Memcpy (bp, data->data, data->len);
 
2017
 
 
2018
    return block;
 
2019
loser:
 
2020
    if (block) PORT_Free(block);
 
2021
    return NULL;
 
2022
}
 
2023
 
 
2024
/*
 
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.
 
2029
**
 
2030
** Called from ssl2_HandleServerHelloMessage()
 
2031
*/
 
2032
static SECStatus
 
2033
ssl2_ClientSetupSessionCypher(sslSocket *ss, PRUint8 *cs, int csLen)
 
2034
{
 
2035
    sslSessionID *    sid;
 
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;
 
2041
    SECStatus         rv;
 
2042
    int               cipher;
 
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.    */
 
2046
    int               nc;
 
2047
 
 
2048
    unsigned char *eblock;      /* holds unencrypted PKCS#1 formatted key. */
 
2049
    SECItem           rek;      /* holds portion of symkey to be encrypted. */
 
2050
 
 
2051
    PRUint8           keyData[SSL_MAX_MASTER_KEY_BYTES];
 
2052
    PRUint8           iv     [8];
 
2053
 
 
2054
    PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) );
 
2055
 
 
2056
    eblock = NULL;
 
2057
 
 
2058
    sid = ss->sec.ci.sid;
 
2059
    PORT_Assert(sid != 0);
 
2060
 
 
2061
    cert = ss->sec.peerCert;
 
2062
    
 
2063
    serverKey = CERT_ExtractPublicKey(cert);
 
2064
    if (!serverKey) {
 
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);
 
2068
        rv = SECFailure;
 
2069
        goto loser2;
 
2070
    }
 
2071
 
 
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);
 
2076
 
 
2077
    /* Choose a compatible cipher with the server */
 
2078
    nc = csLen / 3;
 
2079
    cipher = ssl2_ChooseSessionCypher(ss, nc, cs, &keyLen);
 
2080
    if (cipher < 0) {
 
2081
        /* ssl2_ChooseSessionCypher has set error code. */
 
2082
        ssl2_SendErrorMessage(ss, SSL_PE_NO_CYPHERS);
 
2083
        goto loser;
 
2084
    }
 
2085
 
 
2086
    /* Generate the random keys */
 
2087
    PK11_GenerateRandom(keyData, sizeof(keyData));
 
2088
 
 
2089
    /*
 
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
 
2094
    ** write-key.
 
2095
    */
 
2096
    ca = 0;
 
2097
 
 
2098
    /* We know that cipher is a legit value here, because 
 
2099
     * ssl2_ChooseSessionCypher doesn't return bogus values.
 
2100
     */
 
2101
    ckLen = ssl_Specs[cipher].pubLen;   /* cleartext key length. */
 
2102
    caLen = ssl_Specs[cipher].ivLen;    /* IV length.           */
 
2103
    if (caLen) {
 
2104
        PORT_Assert(sizeof iv >= caLen);
 
2105
        PK11_GenerateRandom(iv, caLen);
 
2106
        ca = iv;
 
2107
    }
 
2108
 
 
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) {
 
2115
        goto loser;
 
2116
    }
 
2117
 
 
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));
 
2121
 
 
2122
    /* Now setup read and write ciphers */
 
2123
    rv = ssl2_CreateSessionCypher(ss, sid, PR_TRUE);
 
2124
    if (rv != SECSuccess) {
 
2125
        goto loser;
 
2126
    }
 
2127
 
 
2128
    /*
 
2129
    ** Fill in the encryption buffer with some random bytes. Then 
 
2130
    ** copy in the portion of the session key we are encrypting.
 
2131
    */
 
2132
    modulusLen = SECKEY_PublicKeyStrength(serverKey);
 
2133
    rek.data   = keyData + ckLen;
 
2134
    rek.len    = keyLen  - ckLen;
 
2135
    eblock = ssl_FormatSSL2Block(modulusLen, &rek);
 
2136
    if (eblock == NULL) 
 
2137
        goto loser;
 
2138
 
 
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);
 
2144
    }
 
2145
    ekbuf = (PRUint8*) PORT_Alloc(modulusLen);
 
2146
    if (!ekbuf) 
 
2147
        goto loser;
 
2148
    PRINT_BUF(10, (ss, "master key encryption block:",
 
2149
                   eblock, modulusLen));
 
2150
 
 
2151
    /* Encrypt ekitem */
 
2152
    rv = PK11_PubEncryptRaw(serverKey, ekbuf, eblock, modulusLen,
 
2153
                                                ss->pkcs11PinArg);
 
2154
    if (rv) 
 
2155
        goto loser;
 
2156
 
 
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) {
 
2161
        goto loser;
 
2162
    }
 
2163
    rv = SECSuccess;
 
2164
    goto done;
 
2165
 
 
2166
  loser:
 
2167
    rv = SECFailure;
 
2168
 
 
2169
  loser2:
 
2170
  done:
 
2171
    PORT_Memset(keyData, 0, sizeof(keyData));
 
2172
    PORT_ZFree(ekbuf, modulusLen);
 
2173
    PORT_ZFree(eblock, modulusLen);
 
2174
    SECKEY_DestroyPublicKey(serverKey);
 
2175
    return rv;
 
2176
}
 
2177
 
 
2178
/************************************************************************/
 
2179
 
 
2180
/* 
 
2181
 * Called from ssl2_HandleMessage in response to SSL_MT_SERVER_FINISHED message.
 
2182
 * Caller holds recvBufLock and handshakeLock
 
2183
 */
 
2184
static void
 
2185
ssl2_ClientRegSessionID(sslSocket *ss, PRUint8 *s)
 
2186
{
 
2187
    sslSessionID *sid = ss->sec.ci.sid;
 
2188
 
 
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);
 
2193
 
 
2194
    }
 
2195
    if (!ss->opt.noCache)
 
2196
        (*ss->sec.cache)(sid);
 
2197
}
 
2198
 
 
2199
/* Called from ssl2_HandleMessage() */
 
2200
static SECStatus
 
2201
ssl2_TriggerNextMessage(sslSocket *ss)
 
2202
{
 
2203
    SECStatus        rv;
 
2204
 
 
2205
    PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) );
 
2206
 
 
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);
 
2211
        return rv;
 
2212
    }
 
2213
    return SECSuccess;
 
2214
}
 
2215
 
 
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.
 
2219
**
 
2220
** Called from ssl2_HandleMessage,
 
2221
**             ssl2_HandleVerifyMessage 
 
2222
**             ssl2_HandleServerHelloMessage
 
2223
**             ssl2_HandleClientSessionKeyMessage
 
2224
**             ssl2_RestartHandshakeAfterCertReq
 
2225
**             ssl2_RestartHandshakeAfterServerCert
 
2226
*/
 
2227
static SECStatus
 
2228
ssl2_TryToFinish(sslSocket *ss)
 
2229
{
 
2230
    SECStatus        rv;
 
2231
    char             e, ef;
 
2232
 
 
2233
    PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) );
 
2234
 
 
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);
 
2241
        } else {
 
2242
            /* Send client finished message if we already didn't */
 
2243
            rv = ssl2_SendClientFinishedMessage(ss);
 
2244
        }
 
2245
        if (rv != SECSuccess) {
 
2246
            return rv;
 
2247
        }
 
2248
        if ((e & ss->sec.ci.requiredElements) == ss->sec.ci.requiredElements) {
 
2249
            /* Totally finished */
 
2250
            ss->handshake = 0;
 
2251
            return SECSuccess;
 
2252
        }
 
2253
    }
 
2254
    return SECSuccess;
 
2255
}
 
2256
 
 
2257
/*
 
2258
** Called from ssl2_HandleRequestCertificate
 
2259
**             ssl2_RestartHandshakeAfterCertReq
 
2260
*/
 
2261
static SECStatus
 
2262
ssl2_SignResponse(sslSocket *ss,
 
2263
             SECKEYPrivateKey *key,
 
2264
             SECItem *response)
 
2265
{
 
2266
    SGNContext *     sgn = NULL;
 
2267
    PRUint8 *        challenge;
 
2268
    unsigned int     len;
 
2269
    SECStatus        rv         = SECFailure;
 
2270
    
 
2271
    PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) );
 
2272
 
 
2273
    challenge = ss->sec.ci.serverChallenge;
 
2274
    len = ss->sec.ci.serverChallengeLen;
 
2275
    
 
2276
    /* Sign the expected data... */
 
2277
    sgn = SGN_NewContext(SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION,key);
 
2278
    if (!sgn) 
 
2279
        goto done;
 
2280
    rv = SGN_Begin(sgn);
 
2281
    if (rv != SECSuccess) 
 
2282
        goto done;
 
2283
    rv = SGN_Update(sgn, ss->sec.ci.readKey, ss->sec.ci.keySize);
 
2284
    if (rv != SECSuccess) 
 
2285
        goto done;
 
2286
    rv = SGN_Update(sgn, ss->sec.ci.writeKey, ss->sec.ci.keySize);
 
2287
    if (rv != SECSuccess) 
 
2288
        goto done;
 
2289
    rv = SGN_Update(sgn, challenge, len);
 
2290
    if (rv != SECSuccess) 
 
2291
        goto done;
 
2292
    rv = SGN_Update(sgn, ss->sec.peerCert->derCert.data, 
 
2293
                         ss->sec.peerCert->derCert.len);
 
2294
    if (rv != SECSuccess) 
 
2295
        goto done;
 
2296
    rv = SGN_End(sgn, response);
 
2297
    if (rv != SECSuccess) 
 
2298
        goto done;
 
2299
 
 
2300
done:
 
2301
    SGN_DestroyContext(sgn, PR_TRUE);
 
2302
    return rv == SECSuccess ? SECSuccess : SECFailure;
 
2303
}
 
2304
 
 
2305
/*
 
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 
 
2309
**
 
2310
** Called from ssl2_HandleMessage().
 
2311
*/
 
2312
static int
 
2313
ssl2_HandleRequestCertificate(sslSocket *ss)
 
2314
{
 
2315
    CERTCertificate * cert      = NULL; /* app-selected client cert. */
 
2316
    SECKEYPrivateKey *key       = NULL; /* priv key for cert. */
 
2317
    SECStatus         rv;
 
2318
    SECItem           response;
 
2319
    int               ret       = 0;
 
2320
    PRUint8           authType;
 
2321
 
 
2322
 
 
2323
    /*
 
2324
     * These things all need to be initialized before we can "goto loser".
 
2325
     */
 
2326
    response.data = NULL;
 
2327
 
 
2328
    /* get challenge info from connectionInfo */
 
2329
    authType = ss->sec.ci.authType;
 
2330
 
 
2331
    if (authType != SSL_AT_MD5_WITH_RSA_ENCRYPTION) {
 
2332
        SSL_TRC(7, ("%d: SSL[%d]: unsupported auth type 0x%x", SSL_GETPID(),
 
2333
                    ss->fd, authType));
 
2334
        goto no_cert_error;
 
2335
    }
 
2336
 
 
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));
 
2341
        goto no_cert_error;
 
2342
    }
 
2343
    ret = (*ss->getClientAuthData)(ss->getClientAuthDataArg, ss->fd,
 
2344
                                   NULL, &cert, &key);
 
2345
    if ( ret == SECWouldBlock ) {
 
2346
        ssl_SetAlwaysBlock(ss);
 
2347
        goto done;
 
2348
    }
 
2349
 
 
2350
    if (ret) {
 
2351
        goto no_cert_error;
 
2352
    }
 
2353
 
 
2354
    /* check what the callback function returned */
 
2355
    if ((!cert) || (!key)) {
 
2356
        /* we are missing either the key or cert */
 
2357
        if (cert) {
 
2358
            /* got a cert, but no key - free it */
 
2359
            CERT_DestroyCertificate(cert);
 
2360
            cert = NULL;
 
2361
        }
 
2362
        if (key) {
 
2363
            /* got a key, but no cert - free it */
 
2364
            SECKEY_DestroyPrivateKey(key);
 
2365
            key = NULL;
 
2366
        }
 
2367
        goto no_cert_error;
 
2368
    }
 
2369
 
 
2370
    rv = ssl2_SignResponse(ss, key, &response);
 
2371
    if ( rv != SECSuccess ) {
 
2372
        ret = -1;
 
2373
        goto loser;
 
2374
    }
 
2375
 
 
2376
    /* Send response message */
 
2377
    ret = ssl2_SendCertificateResponseMessage(ss, &cert->derCert, &response);
 
2378
 
 
2379
    /* Now, remember the cert we sent. But first, forget any previous one. */
 
2380
    if (ss->sec.localCert) {
 
2381
        CERT_DestroyCertificate(ss->sec.localCert);
 
2382
    }
 
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);
 
2387
    }
 
2388
    ss->sec.ci.sid->localCert = cert;
 
2389
    cert = NULL;
 
2390
 
 
2391
    goto done;
 
2392
 
 
2393
  no_cert_error:
 
2394
    SSL_TRC(7, ("%d: SSL[%d]: no certificate (ret=%d)", SSL_GETPID(),
 
2395
                ss->fd, ret));
 
2396
    ret = ssl2_SendErrorMessage(ss, SSL_PE_NO_CERTIFICATE);
 
2397
 
 
2398
  loser:
 
2399
  done:
 
2400
    if ( cert ) {
 
2401
        CERT_DestroyCertificate(cert);
 
2402
    }
 
2403
    if ( key ) {
 
2404
        SECKEY_DestroyPrivateKey(key);
 
2405
    }
 
2406
    if ( response.data ) {
 
2407
        PORT_Free(response.data);
 
2408
    }
 
2409
    
 
2410
    return ret;
 
2411
}
 
2412
 
 
2413
/*
 
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.
 
2417
*/
 
2418
static SECStatus
 
2419
ssl2_HandleClientCertificate(sslSocket *    ss, 
 
2420
                             PRUint8        certType,   /* XXX unused */
 
2421
                             PRUint8 *      cd, 
 
2422
                             unsigned int   cdLen,
 
2423
                             PRUint8 *      response,
 
2424
                             unsigned int   responseLen)
 
2425
{
 
2426
    CERTCertificate *cert       = NULL;
 
2427
    SECKEYPublicKey *pubKey     = NULL;
 
2428
    VFYContext *     vfy        = NULL;
 
2429
    SECItem *        derCert;
 
2430
    SECStatus        rv         = SECFailure;
 
2431
    SECItem          certItem;
 
2432
    SECItem          rep;
 
2433
 
 
2434
    PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) );
 
2435
    PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss)   );
 
2436
 
 
2437
    /* Extract the certificate */
 
2438
    certItem.data = cd;
 
2439
    certItem.len  = cdLen;
 
2440
 
 
2441
    cert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL,
 
2442
                                   PR_FALSE, PR_TRUE);
 
2443
    if (cert == NULL) {
 
2444
        goto loser;
 
2445
    }
 
2446
 
 
2447
    /* save the certificate, since the auth routine will need it */
 
2448
    ss->sec.peerCert = cert;
 
2449
 
 
2450
    /* Extract the public key */
 
2451
    pubKey = CERT_ExtractPublicKey(cert);
 
2452
    if (!pubKey) 
 
2453
        goto loser;
 
2454
    
 
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
 
2459
     * DSA here. */
 
2460
    vfy = VFY_CreateContext(pubKey, &rep, SEC_OID_PKCS1_RSA_ENCRYPTION,
 
2461
                            ss->pkcs11PinArg);
 
2462
    if (!vfy) 
 
2463
        goto loser;
 
2464
    rv = VFY_Begin(vfy);
 
2465
    if (rv) 
 
2466
        goto loser;
 
2467
 
 
2468
    rv = VFY_Update(vfy, ss->sec.ci.readKey, ss->sec.ci.keySize);
 
2469
    if (rv) 
 
2470
        goto loser;
 
2471
    rv = VFY_Update(vfy, ss->sec.ci.writeKey, ss->sec.ci.keySize);
 
2472
    if (rv) 
 
2473
        goto loser;
 
2474
    rv = VFY_Update(vfy, ss->sec.ci.serverChallenge, SSL_CHALLENGE_BYTES);
 
2475
    if (rv) 
 
2476
        goto loser;
 
2477
 
 
2478
    derCert = &ss->serverCerts[kt_rsa].serverCert->derCert;
 
2479
    rv = VFY_Update(vfy, derCert->data, derCert->len);
 
2480
    if (rv) 
 
2481
        goto loser;
 
2482
    rv = VFY_End(vfy);
 
2483
    if (rv) 
 
2484
        goto loser;
 
2485
 
 
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) 
 
2491
        goto done;
 
2492
 
 
2493
loser:
 
2494
    ss->sec.peerCert = NULL;
 
2495
    CERT_DestroyCertificate(cert);
 
2496
 
 
2497
done:
 
2498
    VFY_DestroyContext(vfy, PR_TRUE);
 
2499
    SECKEY_DestroyPublicKey(pubKey);
 
2500
    return rv;
 
2501
}
 
2502
 
 
2503
/*
 
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.
 
2509
**
 
2510
** Called from ssl_Do1stHandshake().
 
2511
** 
 
2512
*/
 
2513
static SECStatus
 
2514
ssl2_HandleMessage(sslSocket *ss)
 
2515
{
 
2516
    PRUint8 *        data;
 
2517
    PRUint8 *        cid;
 
2518
    unsigned         len, certType, certLen, responseLen;
 
2519
    int              rv;
 
2520
    int              rv2;
 
2521
 
 
2522
    PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) );
 
2523
 
 
2524
    ssl_GetRecvBufLock(ss);
 
2525
 
 
2526
    data = ss->gs.buf.buf + ss->gs.recordOffset;
 
2527
 
 
2528
    if (ss->gs.recordLen < 1) {
 
2529
        goto bad_peer;
 
2530
    }
 
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));
 
2534
 
 
2535
    switch (data[0]) {
 
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));
 
2540
            goto bad_peer;
 
2541
        }
 
2542
 
 
2543
        /* See if nonce matches */
 
2544
        len = ss->gs.recordLen - 1;
 
2545
        cid = data + 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));
 
2553
            goto bad_peer;
 
2554
        }
 
2555
 
 
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;
 
2560
        break;
 
2561
 
 
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));
 
2566
            goto bad_peer;
 
2567
        }
 
2568
 
 
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));
 
2572
            goto bad_peer;
 
2573
        }
 
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;
 
2579
        break;
 
2580
 
 
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)) {
 
2585
            /* Bad challenge */
 
2586
            SSL_DBG(("%d: SSL[%d]: bad cert request message: code len=%d",
 
2587
                     SSL_GETPID(), ss->fd, len));
 
2588
            goto bad_peer;
 
2589
        }
 
2590
        
 
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);
 
2595
        
 
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;
 
2603
        }
 
2604
        if (rv) {
 
2605
            SET_ERROR_CODE
 
2606
            goto loser;
 
2607
        }
 
2608
        break;
 
2609
 
 
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);
 
2614
            goto loser;
 
2615
        }
 
2616
        if (ss->gs.recordLen < SSL_HL_CLIENT_CERTIFICATE_HBYTES) {
 
2617
            SET_ERROR_CODE
 
2618
            goto loser;
 
2619
        }
 
2620
        certType    = data[1];
 
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);
 
2625
            goto loser;
 
2626
        }
 
2627
        if (certLen + responseLen + SSL_HL_CLIENT_CERTIFICATE_HBYTES 
 
2628
            > ss->gs.recordLen) {
 
2629
            /* prevent overflow crash. */
 
2630
            rv = SECFailure;
 
2631
        } else
 
2632
        rv = ssl2_HandleClientCertificate(ss, data[1],
 
2633
                data + SSL_HL_CLIENT_CERTIFICATE_HBYTES,
 
2634
                certLen,
 
2635
                data + SSL_HL_CLIENT_CERTIFICATE_HBYTES + certLen,
 
2636
                responseLen);
 
2637
        if (rv) {
 
2638
            rv2 = ssl2_SendErrorMessage(ss, SSL_PE_BAD_CERTIFICATE);
 
2639
            SET_ERROR_CODE
 
2640
            goto loser;
 
2641
        }
 
2642
        ss->sec.ci.elements |= CIS_HAVE_CERTIFICATE;
 
2643
        break;
 
2644
 
 
2645
    case SSL_MT_ERROR:
 
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));
 
2649
 
 
2650
        /* Convert protocol error number into API error number */
 
2651
        switch (rv) {
 
2652
          case SSL_PE_NO_CYPHERS:
 
2653
            rv = SSL_ERROR_NO_CYPHER_OVERLAP;
 
2654
            break;
 
2655
          case SSL_PE_NO_CERTIFICATE:
 
2656
            rv = SSL_ERROR_NO_CERTIFICATE;
 
2657
            break;
 
2658
          case SSL_PE_BAD_CERTIFICATE:
 
2659
            rv = SSL_ERROR_BAD_CERTIFICATE;
 
2660
            break;
 
2661
          case SSL_PE_UNSUPPORTED_CERTIFICATE_TYPE:
 
2662
            rv = SSL_ERROR_UNSUPPORTED_CERTIFICATE_TYPE;
 
2663
            break;
 
2664
          default:
 
2665
            goto bad_peer;
 
2666
        }
 
2667
        /* XXX make certificate-request optionally fail... */
 
2668
        PORT_SetError(rv);
 
2669
        goto loser;
 
2670
 
 
2671
    default:
 
2672
        SSL_DBG(("%d: SSL[%d]: unknown message %d",
 
2673
                 SSL_GETPID(), ss->fd, data[0]));
 
2674
        goto loser;
 
2675
    }
 
2676
 
 
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));
 
2680
 
 
2681
    rv = ssl2_TryToFinish(ss);
 
2682
    if (rv != SECSuccess) 
 
2683
        goto loser;
 
2684
 
 
2685
    ss->gs.recordLen = 0;
 
2686
    ssl_ReleaseRecvBufLock(ss);
 
2687
 
 
2688
    if (ss->handshake == 0) {
 
2689
        return SECSuccess;
 
2690
    }
 
2691
 
 
2692
    ss->handshake     = ssl_GatherRecord1stHandshake;
 
2693
    ss->nextHandshake = ssl2_HandleMessage;
 
2694
    return ssl2_TriggerNextMessage(ss);
 
2695
 
 
2696
  bad_peer:
 
2697
    PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT : SSL_ERROR_BAD_SERVER);
 
2698
    /* FALL THROUGH */
 
2699
 
 
2700
  loser:
 
2701
    ssl_ReleaseRecvBufLock(ss);
 
2702
    return SECFailure;
 
2703
}
 
2704
 
 
2705
/************************************************************************/
 
2706
 
 
2707
/* Called from ssl_Do1stHandshake, after ssl2_HandleServerHelloMessage or 
 
2708
** ssl2_RestartHandshakeAfterServerCert.
 
2709
*/
 
2710
static SECStatus
 
2711
ssl2_HandleVerifyMessage(sslSocket *ss)
 
2712
{
 
2713
    PRUint8 *        data;
 
2714
    SECStatus        rv;
 
2715
 
 
2716
    PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) );
 
2717
    ssl_GetRecvBufLock(ss);
 
2718
 
 
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)) {
 
2724
        /* Bad server */
 
2725
        PORT_SetError(SSL_ERROR_BAD_SERVER);
 
2726
        goto loser;
 
2727
    }
 
2728
    ss->sec.ci.elements |= CIS_HAVE_VERIFY;
 
2729
 
 
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));
 
2733
 
 
2734
    rv = ssl2_TryToFinish(ss);
 
2735
    if (rv) 
 
2736
        goto loser;
 
2737
 
 
2738
    ss->gs.recordLen = 0;
 
2739
    ssl_ReleaseRecvBufLock(ss);
 
2740
 
 
2741
    if (ss->handshake == 0) {
 
2742
        return SECSuccess;
 
2743
    }
 
2744
    ss->handshake         = ssl_GatherRecord1stHandshake;
 
2745
    ss->nextHandshake     = ssl2_HandleMessage;
 
2746
    return SECSuccess;
 
2747
 
 
2748
 
 
2749
  loser:
 
2750
    ssl_ReleaseRecvBufLock(ss);
 
2751
    return SECFailure;
 
2752
}
 
2753
 
 
2754
/* Not static because ssl2_GatherData() tests ss->nextHandshake for this value.
 
2755
 * ICK! 
 
2756
 * Called from ssl_Do1stHandshake after ssl2_BeginClientHandshake()
 
2757
 */
 
2758
SECStatus
 
2759
ssl2_HandleServerHelloMessage(sslSocket *ss)
 
2760
{
 
2761
    sslSessionID *   sid;
 
2762
    PRUint8 *        cert;
 
2763
    PRUint8 *        cs;
 
2764
    PRUint8 *        data;
 
2765
    SECStatus        rv; 
 
2766
    int              needed, sidHit, certLen, csLen, cidLen, certType, err;
 
2767
 
 
2768
    PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) );
 
2769
 
 
2770
    if (!ss->opt.enableSSL2) {
 
2771
        PORT_SetError(SSL_ERROR_SSL2_DISABLED);
 
2772
        return SECFailure;
 
2773
    }
 
2774
 
 
2775
    ssl_GetRecvBufLock(ss);
 
2776
 
 
2777
    PORT_Assert(ss->sec.ci.sid != 0);
 
2778
    sid = ss->sec.ci.sid;
 
2779
 
 
2780
    data = ss->gs.buf.buf + ss->gs.recordOffset;
 
2781
    DUMP_MSG(29, (ss, data, ss->gs.recordLen));
 
2782
 
 
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);
 
2790
                goto loser;
 
2791
            }
 
2792
        }
 
2793
        goto bad_server;
 
2794
    }
 
2795
 
 
2796
    sidHit      = data[1];
 
2797
    certType    = data[2];
 
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;
 
2804
 
 
2805
    SSL_TRC(5,
 
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,
 
2808
             csLen, cidLen));
 
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,
 
2813
                      ss->version));
 
2814
        } else {
 
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);
 
2819
          goto loser;
 
2820
        }
 
2821
    }
 
2822
 
 
2823
    if ((SSL_HL_SERVER_HELLO_HBYTES + certLen + csLen + cidLen 
 
2824
                                                  > ss->gs.recordLen)
 
2825
        || (csLen % 3) != 0   
 
2826
        /* || cidLen < SSL_CONNECTIONID_BYTES || cidLen > 32  */
 
2827
        ) {
 
2828
        goto bad_server;
 
2829
    }
 
2830
 
 
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.
 
2834
    */
 
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);
 
2839
 
 
2840
    /* See if session-id hit */
 
2841
    needed = CIS_HAVE_MASTER_KEY | CIS_HAVE_FINISHED | CIS_HAVE_VERIFY;
 
2842
    if (sidHit) {
 
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));
 
2847
            goto bad_server;
 
2848
        }
 
2849
 
 
2850
        /* Total winner. */
 
2851
        SSL_TRC(1, ("%d: SSL[%d]: client, using nonce for peer=0x%08x "
 
2852
                    "port=0x%04x",
 
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) {
 
2861
            goto loser;
 
2862
        }
 
2863
    } else {
 
2864
        if (certType != SSL_CT_X509_CERTIFICATE) {
 
2865
            PORT_SetError(SSL_ERROR_UNSUPPORTED_CERTIFICATE_TYPE);
 
2866
            goto loser;
 
2867
        }
 
2868
        if (csLen == 0) {
 
2869
            PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
 
2870
            SSL_DBG(("%d: SSL[%d]: no cipher overlap",
 
2871
                     SSL_GETPID(), ss->fd));
 
2872
            goto loser;
 
2873
        }
 
2874
        if (certLen == 0) {
 
2875
            SSL_DBG(("%d: SSL[%d]: client, huh? certLen=%d csLen=%d",
 
2876
                     SSL_GETPID(), ss->fd, certLen, csLen));
 
2877
            goto bad_server;
 
2878
        }
 
2879
 
 
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);
 
2885
            ssl_FreeSID(sid);
 
2886
            ss->sec.ci.sid = sid = (sslSessionID*) PORT_ZAlloc(sizeof(sslSessionID));
 
2887
            if (!sid) {
 
2888
                goto loser;
 
2889
            }
 
2890
            sid->references = 1;
 
2891
            sid->addr = ss->sec.ci.peer;
 
2892
            sid->port = ss->sec.ci.port;
 
2893
        }
 
2894
 
 
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);
 
2900
            }
 
2901
            goto loser;
 
2902
        }
 
2903
 
 
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);
 
2909
            }
 
2910
            goto loser;
 
2911
        }
 
2912
    }
 
2913
 
 
2914
    /* Build up final list of required elements */
 
2915
    ss->sec.ci.elements         = CIS_HAVE_MASTER_KEY;
 
2916
    ss->sec.ci.requiredElements = needed;
 
2917
 
 
2918
  if (!sidHit) {
 
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);
 
2922
    if (rv) {
 
2923
        if (ss->handleBadCert) {
 
2924
            rv = (*ss->handleBadCert)(ss->badCertArg, ss->fd);
 
2925
            if ( rv ) {
 
2926
                if ( rv == SECWouldBlock ) {
 
2927
                    /* someone will handle this connection asynchronously*/
 
2928
 
 
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;
 
2934
                }
 
2935
                /* cert is bad */
 
2936
                SSL_DBG(("%d: SSL[%d]: server certificate is no good: error=%d",
 
2937
                         SSL_GETPID(), ss->fd, PORT_GetError()));
 
2938
                goto loser;
 
2939
 
 
2940
            }
 
2941
            /* cert is good */
 
2942
        } else {
 
2943
            SSL_DBG(("%d: SSL[%d]: server certificate is no good: error=%d",
 
2944
                     SSL_GETPID(), ss->fd, PORT_GetError()));
 
2945
            goto loser;
 
2946
        }
 
2947
    }
 
2948
  }
 
2949
    /*
 
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.
 
2953
    */
 
2954
    ssl2_UseEncryptedSendFunc(ss);
 
2955
 
 
2956
    rv = ssl2_TryToFinish(ss);
 
2957
    if (rv != SECSuccess) 
 
2958
        goto loser;
 
2959
 
 
2960
    ss->gs.recordLen = 0;
 
2961
 
 
2962
    ssl_ReleaseRecvBufLock(ss);
 
2963
 
 
2964
    if (ss->handshake == 0) {
 
2965
        return SECSuccess;
 
2966
    }
 
2967
 
 
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;
 
2973
    return SECSuccess;
 
2974
 
 
2975
  bad_server:
 
2976
    PORT_SetError(SSL_ERROR_BAD_SERVER);
 
2977
    /* FALL THROUGH */
 
2978
 
 
2979
  loser:
 
2980
    ssl_ReleaseRecvBufLock(ss);
 
2981
    return SECFailure;
 
2982
}
 
2983
 
 
2984
/* Sends out the initial client Hello message on the connection.
 
2985
 * Acquires and releases the socket's xmitBufLock.
 
2986
 */
 
2987
SECStatus
 
2988
ssl2_BeginClientHandshake(sslSocket *ss)
 
2989
{
 
2990
    sslSessionID      *sid;
 
2991
    PRUint8           *msg;
 
2992
    PRUint8           *cp;
 
2993
    PRUint8           *localCipherSpecs = NULL;
 
2994
    unsigned int      localCipherSize;
 
2995
    unsigned int      i;
 
2996
    int               sendLen, sidLen = 0;
 
2997
    SECStatus         rv;
 
2998
 
 
2999
    PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) );
 
3000
 
 
3001
    ss->sec.isServer     = 0;
 
3002
    ss->sec.sendSequence = 0;
 
3003
    ss->sec.rcvSequence  = 0;
 
3004
    ssl_ChooseSessionIDProcs(&ss->sec);
 
3005
 
 
3006
    if (!ss->cipherSpecs) {
 
3007
        rv = ssl2_ConstructCipherSpecs(ss);
 
3008
        if (rv != SECSuccess)
 
3009
            goto loser;
 
3010
    }
 
3011
 
 
3012
    /* count the SSL2 and SSL3 enabled ciphers.
 
3013
     * if either is zero, clear the socket's enable for that protocol.
 
3014
     */
 
3015
    rv = ssl2_CheckConfigSanity(ss);
 
3016
    if (rv != SECSuccess)
 
3017
        goto loser;
 
3018
 
 
3019
    /* Get peer name of server */
 
3020
    rv = ssl_GetPeerInfo(ss);
 
3021
    if (rv < 0) {
 
3022
#ifdef HPUX11
 
3023
        /*
 
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.
 
3028
         */
 
3029
        if (PR_GetError() == PR_NOT_CONNECTED_ERROR) {
 
3030
            char dummy;
 
3031
            (void) PR_Write(ss->fd->lower, &dummy, 0);
 
3032
            rv = ssl_GetPeerInfo(ss);
 
3033
            if (rv < 0) {
 
3034
                goto loser;
 
3035
            }
 
3036
        }
 
3037
#else
 
3038
        goto loser;
 
3039
#endif
 
3040
    }
 
3041
 
 
3042
    SSL_TRC(3, ("%d: SSL[%d]: sending client-hello", SSL_GETPID(), ss->fd));
 
3043
 
 
3044
    /* Try to find server in our session-id cache */
 
3045
    if (ss->opt.noCache) {
 
3046
        sid = NULL;
 
3047
    } else {
 
3048
        sid = ssl_LookupSID(&ss->sec.ci.peer, ss->sec.ci.port, ss->peerID, 
 
3049
                            ss->url);
 
3050
    }
 
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);
 
3057
            ssl_FreeSID(sid);
 
3058
            sid = NULL;
 
3059
            break;
 
3060
        }
 
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)
 
3065
                    break;
 
3066
            }
 
3067
            if (i >= ss->sizeCipherSpecs) {
 
3068
                ss->sec.uncache(sid);
 
3069
                ssl_FreeSID(sid);
 
3070
                sid = NULL;
 
3071
                break;
 
3072
            }
 
3073
        }
 
3074
        sidLen = sizeof(sid->u.ssl2.sessionID);
 
3075
        PRINT_BUF(4, (ss, "client, found session-id:", sid->u.ssl2.sessionID,
 
3076
                      sidLen));
 
3077
        ss->version = sid->version;
 
3078
        PORT_Assert(!ss->sec.localCert);
 
3079
        if (ss->sec.localCert) {
 
3080
            CERT_DestroyCertificate(ss->sec.localCert);
 
3081
        }
 
3082
        ss->sec.localCert     = CERT_DupCertificate(sid->localCert);
 
3083
        break;  /* this isn't really a loop */
 
3084
    } 
 
3085
    if (!sid) {
 
3086
        sidLen = 0;
 
3087
        sid = (sslSessionID*) PORT_ZAlloc(sizeof(sslSessionID));
 
3088
        if (!sid) {
 
3089
            goto loser;
 
3090
        }
 
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);
 
3097
        }
 
3098
        if (ss->url != NULL) {
 
3099
            sid->urlSvrName = PORT_Strdup(ss->url);
 
3100
        }
 
3101
    }
 
3102
    ss->sec.ci.sid = sid;
 
3103
 
 
3104
    PORT_Assert(sid != NULL);
 
3105
 
 
3106
    if ((sid->version >= SSL_LIBRARY_VERSION_3_0 || !ss->opt.v2CompatibleHello) &&
 
3107
        (ss->opt.enableSSL3 || ss->opt.enableTLS)) {
 
3108
 
 
3109
        ss->gs.state      = GS_INIT;
 
3110
        ss->handshake     = ssl_GatherRecord1stHandshake;
 
3111
 
 
3112
        /* ssl3_SendClientHello will override this if it succeeds. */
 
3113
        ss->version       = SSL_LIBRARY_VERSION_3_0;
 
3114
 
 
3115
        ssl_GetXmitBufLock(ss);    /***************************************/
 
3116
        ssl_GetSSL3HandshakeLock(ss);
 
3117
        rv =  ssl3_SendClientHello(ss);
 
3118
        ssl_ReleaseSSL3HandshakeLock(ss);
 
3119
        ssl_ReleaseXmitBufLock(ss); /***************************************/
 
3120
 
 
3121
        return rv;
 
3122
    }
 
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;
 
3130
    }
 
3131
#endif
 
3132
 
 
3133
    if (!ss->cipherSpecs) {
 
3134
        rv = ssl2_ConstructCipherSpecs(ss);
 
3135
        if (rv < 0) {
 
3136
            return rv;
 
3137
        }
 
3138
    }
 
3139
    localCipherSpecs = ss->cipherSpecs;
 
3140
    localCipherSize  = ss->sizeCipherSpecs;
 
3141
 
 
3142
    sendLen = SSL_HL_CLIENT_HELLO_HBYTES + localCipherSize + sidLen +
 
3143
        SSL_CHALLENGE_BYTES;
 
3144
 
 
3145
    /* Generate challenge bytes for server */
 
3146
    PK11_GenerateRandom(ss->sec.ci.clientChallenge, SSL_CHALLENGE_BYTES);
 
3147
 
 
3148
    ssl_GetXmitBufLock(ss);    /***************************************/
 
3149
 
 
3150
    rv = ssl2_GetSendBuffer(ss, sendLen);
 
3151
    if (rv) 
 
3152
        goto unlock_loser;
 
3153
 
 
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;
 
3161
    } else {
 
3162
        ss->clientHelloVersion = SSL_LIBRARY_VERSION_2;
 
3163
    }
 
3164
    
 
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;
 
3176
    if (sidLen) {
 
3177
        PORT_Memcpy(cp, sid->u.ssl2.sessionID, sidLen);
 
3178
        cp += sidLen;
 
3179
    }
 
3180
    PORT_Memcpy(cp, ss->sec.ci.clientChallenge, SSL_CHALLENGE_BYTES);
 
3181
 
 
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);
 
3186
 
 
3187
    ssl_ReleaseXmitBufLock(ss);    /***************************************/
 
3188
 
 
3189
    if (rv < 0) {
 
3190
        goto loser;
 
3191
    }
 
3192
 
 
3193
    rv = ssl3_StartHandshakeHash(ss, msg, sendLen);
 
3194
    if (rv < 0) {
 
3195
        goto loser;
 
3196
    }
 
3197
 
 
3198
    /* Setup to receive servers hello message */
 
3199
    ssl_GetRecvBufLock(ss);
 
3200
    ss->gs.recordLen = 0;
 
3201
    ssl_ReleaseRecvBufLock(ss);
 
3202
 
 
3203
    ss->handshake     = ssl_GatherRecord1stHandshake;
 
3204
    ss->nextHandshake = ssl2_HandleServerHelloMessage;
 
3205
    return SECSuccess;
 
3206
 
 
3207
unlock_loser:
 
3208
    ssl_ReleaseXmitBufLock(ss);
 
3209
loser:
 
3210
    return SECFailure;
 
3211
}
 
3212
 
 
3213
/************************************************************************/
 
3214
 
 
3215
/* Handle the CLIENT-MASTER-KEY message. 
 
3216
** Acquires and releases RecvBufLock.
 
3217
** Called from ssl2_HandleClientHelloMessage(). 
 
3218
*/
 
3219
static SECStatus
 
3220
ssl2_HandleClientSessionKeyMessage(sslSocket *ss)
 
3221
{
 
3222
    PRUint8 *        data;
 
3223
    unsigned int     caLen;
 
3224
    unsigned int     ckLen;
 
3225
    unsigned int     ekLen;
 
3226
    unsigned int     keySize;
 
3227
    int              cipher;
 
3228
    SECStatus        rv;
 
3229
 
 
3230
 
 
3231
    ssl_GetRecvBufLock(ss);
 
3232
 
 
3233
    data = ss->gs.buf.buf + ss->gs.recordOffset;
 
3234
    DUMP_MSG(29, (ss, data, ss->gs.recordLen));
 
3235
 
 
3236
    if ((ss->gs.recordLen < SSL_HL_CLIENT_MASTER_KEY_HBYTES)
 
3237
        || (data[0] != SSL_MT_CLIENT_MASTER_KEY)) {
 
3238
        goto bad_client;
 
3239
    }
 
3240
    cipher  = data[1];
 
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];
 
3245
 
 
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));
 
3248
 
 
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));
 
3253
        goto bad_client;
 
3254
    }
 
3255
 
 
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. */
 
3263
 
 
3264
    ssl_ReleaseRecvBufLock(ss);
 
3265
 
 
3266
    if (rv != SECSuccess) {
 
3267
        goto loser;
 
3268
    }
 
3269
    ss->sec.ci.elements |= CIS_HAVE_MASTER_KEY;
 
3270
    ssl2_UseEncryptedSendFunc(ss);
 
3271
 
 
3272
    /* Send server verify message now that keys are established */
 
3273
    rv = ssl2_SendServerVerifyMessage(ss);
 
3274
    if (rv != SECSuccess) 
 
3275
        goto loser;
 
3276
 
 
3277
    rv = ssl2_TryToFinish(ss);
 
3278
    if (rv != SECSuccess) 
 
3279
        goto loser;
 
3280
    if (ss->handshake == 0) {
 
3281
        return SECSuccess;
 
3282
    }
 
3283
 
 
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;
 
3288
 
 
3289
    return ssl2_TriggerNextMessage(ss);
 
3290
 
 
3291
bad_client:
 
3292
    ssl_ReleaseRecvBufLock(ss);
 
3293
    PORT_SetError(SSL_ERROR_BAD_CLIENT);
 
3294
    /* FALLTHROUGH */
 
3295
 
 
3296
loser:
 
3297
    return SECFailure;
 
3298
}
 
3299
 
 
3300
/*
 
3301
 * attempt to restart the handshake after asynchronously handling
 
3302
 * a request for the client's certificate.
 
3303
 *
 
3304
 * inputs:  
 
3305
 *      cert    Client cert chosen by application.
 
3306
 *      key     Private key associated with cert.  
 
3307
 *
 
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!
 
3310
 *
 
3311
 * Return value: XXX
 
3312
 *
 
3313
 * Caller holds 1stHandshakeLock.
 
3314
 */
 
3315
int
 
3316
ssl2_RestartHandshakeAfterCertReq(sslSocket *          ss,
 
3317
                                  CERTCertificate *    cert, 
 
3318
                                  SECKEYPrivateKey *   key)
 
3319
{
 
3320
    int              ret;
 
3321
    SECStatus        rv          = SECSuccess;
 
3322
    SECItem          response;
 
3323
 
 
3324
    if (ss->version >= SSL_LIBRARY_VERSION_3_0) 
 
3325
        return SECFailure;
 
3326
 
 
3327
    response.data = NULL;
 
3328
 
 
3329
    /* generate error if no cert or key */
 
3330
    if ( ( cert == NULL ) || ( key == NULL ) ) {
 
3331
        goto no_cert;
 
3332
    }
 
3333
    
 
3334
    /* generate signed response to the challenge */
 
3335
    rv = ssl2_SignResponse(ss, key, &response);
 
3336
    if ( rv != SECSuccess ) {
 
3337
        goto no_cert;
 
3338
    }
 
3339
    
 
3340
    /* Send response message */
 
3341
    ret = ssl2_SendCertificateResponseMessage(ss, &cert->derCert, &response);
 
3342
    if (ret) {
 
3343
        goto no_cert;
 
3344
    }
 
3345
 
 
3346
    /* try to finish the handshake */
 
3347
    ret = ssl2_TryToFinish(ss);
 
3348
    if (ret) {
 
3349
        goto loser;
 
3350
    }
 
3351
    
 
3352
    /* done with handshake */
 
3353
    if (ss->handshake == 0) {
 
3354
        ret = SECSuccess;
 
3355
        goto done;
 
3356
    }
 
3357
 
 
3358
    /* continue handshake */
 
3359
    ssl_GetRecvBufLock(ss);
 
3360
    ss->gs.recordLen = 0;
 
3361
    ssl_ReleaseRecvBufLock(ss);
 
3362
 
 
3363
    ss->handshake     = ssl_GatherRecord1stHandshake;
 
3364
    ss->nextHandshake = ssl2_HandleMessage;
 
3365
    ret = ssl2_TriggerNextMessage(ss);
 
3366
    goto done;
 
3367
    
 
3368
no_cert:
 
3369
    /* no cert - send error */
 
3370
    ret = ssl2_SendErrorMessage(ss, SSL_PE_NO_CERTIFICATE);
 
3371
    goto done;
 
3372
    
 
3373
loser:
 
3374
    ret = SECFailure;
 
3375
done:
 
3376
    /* free allocated data */
 
3377
    if ( response.data ) {
 
3378
        PORT_Free(response.data);
 
3379
    }
 
3380
    
 
3381
    return ret;
 
3382
}
 
3383
 
 
3384
 
 
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).
 
3388
 *
 
3389
 * Return value: XXX
 
3390
 *
 
3391
 * Caller holds 1stHandshakeLock.
 
3392
*/
 
3393
int
 
3394
ssl2_RestartHandshakeAfterServerCert(sslSocket *ss)
 
3395
{
 
3396
    int rv      = SECSuccess;
 
3397
 
 
3398
    if (ss->version >= SSL_LIBRARY_VERSION_3_0) 
 
3399
        return SECFailure;
 
3400
 
 
3401
    /* SSL 2
 
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.
 
3405
    */
 
3406
    ssl2_UseEncryptedSendFunc(ss);
 
3407
 
 
3408
    rv = ssl2_TryToFinish(ss);
 
3409
    if (rv == SECSuccess && ss->handshake != NULL) {    
 
3410
        /* handshake is not yet finished. */
 
3411
 
 
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));
 
3415
 
 
3416
        ssl_GetRecvBufLock(ss);
 
3417
        ss->gs.recordLen = 0;   /* mark it all used up. */
 
3418
        ssl_ReleaseRecvBufLock(ss);
 
3419
 
 
3420
        ss->handshake     = ssl_GatherRecord1stHandshake;
 
3421
        ss->nextHandshake = ssl2_HandleVerifyMessage;
 
3422
    }
 
3423
 
 
3424
    return rv;
 
3425
}
 
3426
 
 
3427
/*
 
3428
** Handle the initial hello message from the client
 
3429
**
 
3430
** not static because ssl2_GatherData() tests ss->nextHandshake for this value.
 
3431
*/
 
3432
SECStatus
 
3433
ssl2_HandleClientHelloMessage(sslSocket *ss)
 
3434
{
 
3435
    sslSessionID    *sid;
 
3436
    sslServerCerts * sc;
 
3437
    CERTCertificate *serverCert;
 
3438
    PRUint8         *msg;
 
3439
    PRUint8         *data;
 
3440
    PRUint8         *cs;
 
3441
    PRUint8         *sd;
 
3442
    PRUint8         *cert = NULL;
 
3443
    PRUint8         *challenge;
 
3444
    unsigned int    challengeLen;
 
3445
    SECStatus       rv; 
 
3446
    int             csLen;
 
3447
    int             sendLen;
 
3448
    int             sdLen;
 
3449
    int             certLen;
 
3450
    int             pid;
 
3451
    int             sent;
 
3452
    int             gotXmitBufLock = 0;
 
3453
#if defined(SOLARIS) && defined(i386)
 
3454
    volatile PRUint8 hit;
 
3455
#else
 
3456
    int             hit;
 
3457
#endif
 
3458
    PRUint8         csImpl[sizeof implementedCipherSuites];
 
3459
 
 
3460
    PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) );
 
3461
 
 
3462
    sc = ss->serverCerts + kt_rsa;
 
3463
    serverCert = sc->serverCert;
 
3464
 
 
3465
    ssl_GetRecvBufLock(ss);
 
3466
 
 
3467
 
 
3468
    data = ss->gs.buf.buf + ss->gs.recordOffset;
 
3469
    DUMP_MSG(29, (ss, data, ss->gs.recordLen));
 
3470
 
 
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)) {
 
3474
        goto bad_client;
 
3475
    }
 
3476
 
 
3477
    /* Get peer name of client */
 
3478
    rv = ssl_GetPeerInfo(ss);
 
3479
    if (rv != SECSuccess) {
 
3480
        goto loser;
 
3481
    }
 
3482
 
 
3483
    /* Examine version information */
 
3484
    /*
 
3485
     * See if this might be a V2 client hello asking to use the V3 protocol
 
3486
     */
 
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;
 
3496
 
 
3497
            /* ssl3_HandleV3ClientHello has set ss->version,
 
3498
            ** and has gotten us a brand new sid.  
 
3499
            */
 
3500
            ss->sec.ci.sid->version  = ss->version;
 
3501
        }
 
3502
        ssl_ReleaseRecvBufLock(ss);
 
3503
        return rv;
 
3504
    }
 
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.
 
3513
    */
 
3514
 
 
3515
    /* Extract info from message */
 
3516
    ss->version = (data[1] << 8) | data[2];
 
3517
 
 
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;
 
3521
    }
 
3522
    
 
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;
 
3527
    sd           = cs + csLen;
 
3528
    challenge    = sd + sdLen;
 
3529
    PRINT_BUF(7, (ss, "server, client session-id value:", sd, sdLen));
 
3530
 
 
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));
 
3540
        goto bad_client;
 
3541
    }
 
3542
 
 
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) {
 
3547
            /*
 
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
 
3551
            ** knows whats up.
 
3552
            */
 
3553
            ss->version = SSL_LIBRARY_VERSION_2;
 
3554
        } else {
 
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);
 
3558
            goto loser;
 
3559
        }
 
3560
    }
 
3561
 
 
3562
    /* Qualify cipher specs before returning them to client */
 
3563
    csLen = ssl2_QualifyCypherSpecs(ss, cs, csLen);
 
3564
    if (csLen == 0) {
 
3565
        /* no overlap, send client our list of supported SSL v2 ciphers. */
 
3566
        cs    = csImpl;
 
3567
        csLen = sizeof implementedCipherSuites;
 
3568
        PORT_Memcpy(cs, implementedCipherSuites, csLen);
 
3569
        csLen = ssl2_QualifyCypherSpecs(ss, cs, csLen);
 
3570
        if (csLen == 0) {
 
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);
 
3574
          goto loser;
 
3575
        }
 
3576
        /* Since this handhsake is going to fail, don't cache it. */
 
3577
        ss->opt.noCache = 1; 
 
3578
    }
 
3579
 
 
3580
    /* Squirrel away the challenge for later */
 
3581
    PORT_Memcpy(ss->sec.ci.clientChallenge, challenge, challengeLen);
 
3582
 
 
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);
 
3592
    } else {
 
3593
        sid = NULL;
 
3594
    }
 
3595
    if (sid) {
 
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;
 
3603
        hit = 1;
 
3604
        certLen = 0;
 
3605
        csLen = 0;
 
3606
 
 
3607
        ss->sec.authAlgorithm = sid->authAlgorithm;
 
3608
        ss->sec.authKeyBits   = sid->authKeyBits;
 
3609
        ss->sec.keaType       = sid->keaType;
 
3610
        ss->sec.keaKeyBits    = sid->keaKeyBits;
 
3611
 
 
3612
        rv = ssl2_CreateSessionCypher(ss, sid, PR_FALSE);
 
3613
        if (rv != SECSuccess) {
 
3614
            goto loser;
 
3615
        }
 
3616
    } else {
 
3617
        SECItem * derCert   = &serverCert->derCert;
 
3618
 
 
3619
        SSL_TRC(7, ("%d: SSL[%d]: server, lookup nonce missed",
 
3620
                    SSL_GETPID(), ss->fd));
 
3621
        if (!serverCert) {
 
3622
            SET_ERROR_CODE
 
3623
            goto loser;
 
3624
        }
 
3625
        hit = 0;
 
3626
        sid = (sslSessionID*) PORT_ZAlloc(sizeof(sslSessionID));
 
3627
        if (!sid) {
 
3628
            goto loser;
 
3629
        }
 
3630
        sid->references = 1;
 
3631
        sid->addr = ss->sec.ci.peer;
 
3632
        sid->port = ss->sec.ci.port;
 
3633
 
 
3634
        /* Invent a session-id */
 
3635
        ss->sec.ci.sid = sid;
 
3636
        PK11_GenerateRandom(sid->u.ssl2.sessionID+2, SSL2_SESSIONID_BYTES-2);
 
3637
 
 
3638
        pid = SSL_GETPID();
 
3639
        sid->u.ssl2.sessionID[0] = MSB(pid);
 
3640
        sid->u.ssl2.sessionID[1] = LSB(pid);
 
3641
        cert    = derCert->data;
 
3642
        certLen = derCert->len;
 
3643
 
 
3644
        /* pretend that server sids remember the local cert. */
 
3645
        PORT_Assert(!sid->localCert);
 
3646
        if (sid->localCert) {
 
3647
            CERT_DestroyCertificate(sid->localCert);
 
3648
        }
 
3649
        sid->localCert     = CERT_DupCertificate(serverCert);
 
3650
 
 
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;
 
3655
    }
 
3656
 
 
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.
 
3659
    */
 
3660
    if (ss->sec.localCert) {
 
3661
        CERT_DestroyCertificate(ss->sec.localCert);
 
3662
    }
 
3663
    ss->sec.localCert     = CERT_DupCertificate(serverCert);
 
3664
 
 
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;
 
3669
    }
 
3670
    ss->sec.ci.sentElements = 0;
 
3671
 
 
3672
    /* Send hello message back to client */
 
3673
    sendLen = SSL_HL_SERVER_HELLO_HBYTES + certLen + csLen
 
3674
            + SSL_CONNECTIONID_BYTES;
 
3675
 
 
3676
    ssl_GetXmitBufLock(ss); gotXmitBufLock = 1;
 
3677
    rv = ssl2_GetSendBuffer(ss, sendLen);
 
3678
    if (rv != SECSuccess) {
 
3679
        goto loser;
 
3680
    }
 
3681
 
 
3682
    SSL_TRC(3, ("%d: SSL[%d]: sending server-hello (%d)",
 
3683
                SSL_GETPID(), ss->fd, sendLen));
 
3684
 
 
3685
    msg = ss->sec.ci.sendBuf.buf;
 
3686
    msg[0] = SSL_MT_SERVER_HELLO;
 
3687
    msg[1] = hit;
 
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);
 
3697
    if (certLen) {
 
3698
        PORT_Memcpy(msg+SSL_HL_SERVER_HELLO_HBYTES, cert, certLen);
 
3699
    }
 
3700
    if (csLen) {
 
3701
        PORT_Memcpy(msg+SSL_HL_SERVER_HELLO_HBYTES+certLen, cs, csLen);
 
3702
    }
 
3703
    PORT_Memcpy(msg+SSL_HL_SERVER_HELLO_HBYTES+certLen+csLen, 
 
3704
                ss->sec.ci.connectionID, SSL_CONNECTIONID_BYTES);
 
3705
 
 
3706
    DUMP_MSG(29, (ss, msg, sendLen));
 
3707
 
 
3708
    ss->handshakeBegun = 1;
 
3709
    sent = (*ss->sec.send)(ss, msg, sendLen, 0);
 
3710
    if (sent < 0) {
 
3711
        goto loser;
 
3712
    }
 
3713
    ssl_ReleaseXmitBufLock(ss); gotXmitBufLock = 0;
 
3714
 
 
3715
    ss->gs.recordLen = 0;
 
3716
    ss->handshake = ssl_GatherRecord1stHandshake;
 
3717
    if (hit) {
 
3718
        /* Old SID Session key is good. Go encrypted */
 
3719
        ssl2_UseEncryptedSendFunc(ss);
 
3720
 
 
3721
        /* Send server verify message now that keys are established */
 
3722
        rv = ssl2_SendServerVerifyMessage(ss);
 
3723
        if (rv != SECSuccess) 
 
3724
            goto loser;
 
3725
 
 
3726
        ss->nextHandshake = ssl2_HandleMessage;
 
3727
        ssl_ReleaseRecvBufLock(ss);
 
3728
        rv = ssl2_TriggerNextMessage(ss);
 
3729
        return rv;
 
3730
    }
 
3731
    ss->nextHandshake = ssl2_HandleClientSessionKeyMessage;
 
3732
    ssl_ReleaseRecvBufLock(ss);
 
3733
    return SECSuccess;
 
3734
 
 
3735
  bad_client:
 
3736
    PORT_SetError(SSL_ERROR_BAD_CLIENT);
 
3737
    /* FALLTHROUGH */
 
3738
 
 
3739
  loser:
 
3740
    if (gotXmitBufLock) {
 
3741
        ssl_ReleaseXmitBufLock(ss); gotXmitBufLock = 0;
 
3742
    }
 
3743
    SSL_TRC(10, ("%d: SSL[%d]: server, wait for client-hello lossage",
 
3744
                 SSL_GETPID(), ss->fd));
 
3745
    ssl_ReleaseRecvBufLock(ss);
 
3746
    return SECFailure;
 
3747
}
 
3748
 
 
3749
SECStatus
 
3750
ssl2_BeginServerHandshake(sslSocket *ss)
 
3751
{
 
3752
    SECStatus        rv;
 
3753
    sslServerCerts * rsaAuth = ss->serverCerts + kt_rsa;
 
3754
 
 
3755
    ss->sec.isServer = 1;
 
3756
    ssl_ChooseSessionIDProcs(&ss->sec);
 
3757
    ss->sec.sendSequence = 0;
 
3758
    ss->sec.rcvSequence = 0;
 
3759
 
 
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;
 
3764
    }
 
3765
 
 
3766
    if (!ss->cipherSpecs) {
 
3767
        rv = ssl2_ConstructCipherSpecs(ss);
 
3768
        if (rv != SECSuccess)
 
3769
            goto loser;
 
3770
    }
 
3771
 
 
3772
    /* count the SSL2 and SSL3 enabled ciphers.
 
3773
     * if either is zero, clear the socket's enable for that protocol.
 
3774
     */
 
3775
    rv = ssl2_CheckConfigSanity(ss);
 
3776
    if (rv != SECSuccess)
 
3777
        goto loser;
 
3778
 
 
3779
    /*
 
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.
 
3783
    */
 
3784
    PK11_GenerateRandom(ss->sec.ci.connectionID, 
 
3785
                        sizeof(ss->sec.ci.connectionID));
 
3786
 
 
3787
    ss->gs.recordLen = 0;
 
3788
    ss->handshake     = ssl_GatherRecord1stHandshake;
 
3789
    ss->nextHandshake = ssl2_HandleClientHelloMessage;
 
3790
    return SECSuccess;
 
3791
 
 
3792
loser:
 
3793
    return SECFailure;
 
3794
}
 
3795
 
 
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.
 
3799
*/
 
3800
 
 
3801
#include "nss.h"
 
3802
extern const char __nss_ssl_rcsid[];
 
3803
extern const char __nss_ssl_sccsid[];
 
3804
 
 
3805
PRBool
 
3806
NSSSSL_VersionCheck(const char *importedVersion)
 
3807
{
 
3808
    /*
 
3809
     * This is the secret handshake algorithm.
 
3810
     *
 
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
 
3815
     * patch releases.
 
3816
     */
 
3817
    volatile char c; /* force a reference that won't get optimized away */
 
3818
 
 
3819
    c = __nss_ssl_rcsid[0] + __nss_ssl_sccsid[0]; 
 
3820
    return NSS_VersionCheck(importedVersion);
 
3821
}