f46a470def7a9bf3f2d7ada6558ac0fdf000c3bc
[platform/upstream/nss.git] / nss / lib / ssl / ssl3con.c
1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3  * SSL3 Protocol
4  *
5  * This Source Code Form is subject to the terms of the Mozilla Public
6  * License, v. 2.0. If a copy of the MPL was not distributed with this
7  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
8
9 /* TODO(ekr): Implement HelloVerifyRequest on server side. OK for now. */
10
11 #include "cert.h"
12 #include "ssl.h"
13 #include "cryptohi.h"   /* for DSAU_ stuff */
14 #include "keyhi.h"
15 #include "secder.h"
16 #include "secitem.h"
17 #include "sechash.h"
18
19 #include "sslimpl.h"
20 #include "sslproto.h"
21 #include "sslerr.h"
22 #include "prtime.h"
23 #include "prinrval.h"
24 #include "prerror.h"
25 #include "pratom.h"
26 #include "prthread.h"
27
28 #include "pk11func.h"
29 #include "secmod.h"
30 #ifndef NO_PKCS11_BYPASS
31 #include "blapi.h"
32 #endif
33
34 #include <stdio.h>
35 #ifdef NSS_ENABLE_ZLIB
36 #include "zlib.h"
37 #endif
38
39 #ifndef PK11_SETATTRS
40 #define PK11_SETATTRS(x,id,v,l) (x)->type = (id); \
41                 (x)->pValue=(v); (x)->ulValueLen = (l);
42 #endif
43
44 static SECStatus ssl3_AuthCertificate(sslSocket *ss);
45 static void      ssl3_CleanupPeerCerts(sslSocket *ss);
46 static PK11SymKey *ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec,
47                                        PK11SlotInfo * serverKeySlot);
48 static SECStatus ssl3_DeriveMasterSecret(sslSocket *ss, PK11SymKey *pms);
49 static SECStatus ssl3_DeriveConnectionKeysPKCS11(sslSocket *ss);
50 static SECStatus ssl3_HandshakeFailure(      sslSocket *ss);
51 static SECStatus ssl3_InitState(             sslSocket *ss);
52 static SECStatus ssl3_SendCertificate(       sslSocket *ss);
53 static SECStatus ssl3_SendCertificateStatus( sslSocket *ss);
54 static SECStatus ssl3_SendEmptyCertificate(  sslSocket *ss);
55 static SECStatus ssl3_SendCertificateRequest(sslSocket *ss);
56 static SECStatus ssl3_SendNextProto(         sslSocket *ss);
57 static SECStatus ssl3_SendFinished(          sslSocket *ss, PRInt32 flags);
58 static SECStatus ssl3_SendServerHello(       sslSocket *ss);
59 static SECStatus ssl3_SendServerHelloDone(   sslSocket *ss);
60 static SECStatus ssl3_SendServerKeyExchange( sslSocket *ss);
61 static SECStatus ssl3_UpdateHandshakeHashes( sslSocket *ss,
62                                              const unsigned char *b,
63                                              unsigned int l);
64 static SECStatus ssl3_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags);
65 static int       ssl3_OIDToTLSHashAlgorithm(SECOidTag oid);
66
67 static SECStatus Null_Cipher(void *ctx, unsigned char *output, int *outputLen,
68                              int maxOutputLen, const unsigned char *input,
69                              int inputLen);
70 #ifndef NO_PKCS11_BYPASS
71 static SECStatus ssl3_AESGCMBypass(ssl3KeyMaterial *keys, PRBool doDecrypt,
72                                    unsigned char *out, int *outlen, int maxout,
73                                    const unsigned char *in, int inlen,
74                                    const unsigned char *additionalData,
75                                    int additionalDataLen);
76 #endif
77
78 #define MAX_SEND_BUF_LENGTH 32000 /* watch for 16-bit integer overflow */
79 #define MIN_SEND_BUF_LENGTH  4000
80
81 /* This list of SSL3 cipher suites is sorted in descending order of
82  * precedence (desirability).  It only includes cipher suites we implement.
83  * This table is modified by SSL3_SetPolicy(). The ordering of cipher suites
84  * in this table must match the ordering in SSL_ImplementedCiphers (sslenum.c)
85  */
86 static ssl3CipherSuiteCfg cipherSuites[ssl_V3_SUITES_IMPLEMENTED] = {
87    /*      cipher_suite                     policy       enabled   isPresent */
88 #ifdef NSS_ENABLE_ECC
89  { TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE},
90  { TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,   SSL_ALLOWED, PR_FALSE, PR_FALSE},
91 #endif /* NSS_ENABLE_ECC */
92  { TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,     SSL_ALLOWED, PR_TRUE,  PR_FALSE},
93  { TLS_RSA_WITH_AES_128_GCM_SHA256,         SSL_ALLOWED, PR_TRUE,  PR_FALSE},
94
95 #ifdef NSS_ENABLE_ECC
96  { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,    SSL_ALLOWED, PR_FALSE, PR_FALSE},
97  { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,      SSL_ALLOWED, PR_FALSE, PR_FALSE},
98 #endif /* NSS_ENABLE_ECC */
99  { TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA,   SSL_ALLOWED, PR_FALSE, PR_FALSE},
100  { TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA,   SSL_ALLOWED, PR_FALSE, PR_FALSE},
101  { TLS_DHE_RSA_WITH_AES_256_CBC_SHA,        SSL_ALLOWED, PR_TRUE,  PR_FALSE},
102  { TLS_DHE_RSA_WITH_AES_256_CBC_SHA256,     SSL_ALLOWED, PR_TRUE,  PR_FALSE},
103  { TLS_DHE_DSS_WITH_AES_256_CBC_SHA,        SSL_ALLOWED, PR_TRUE,  PR_FALSE},
104 #ifdef NSS_ENABLE_ECC
105  { TLS_ECDH_RSA_WITH_AES_256_CBC_SHA,       SSL_ALLOWED, PR_FALSE, PR_FALSE},
106  { TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA,     SSL_ALLOWED, PR_FALSE, PR_FALSE},
107 #endif /* NSS_ENABLE_ECC */
108  { TLS_RSA_WITH_CAMELLIA_256_CBC_SHA,       SSL_ALLOWED, PR_FALSE, PR_FALSE},
109  { TLS_RSA_WITH_AES_256_CBC_SHA,            SSL_ALLOWED, PR_TRUE,  PR_FALSE},
110  { TLS_RSA_WITH_AES_256_CBC_SHA256,         SSL_ALLOWED, PR_TRUE,  PR_FALSE},
111
112 #ifdef NSS_ENABLE_ECC
113  { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,    SSL_ALLOWED, PR_FALSE, PR_FALSE},
114  { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE},
115  { TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,        SSL_ALLOWED, PR_FALSE, PR_FALSE},
116  { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,      SSL_ALLOWED, PR_FALSE, PR_FALSE},
117  { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,   SSL_ALLOWED, PR_FALSE, PR_FALSE},
118  { TLS_ECDHE_RSA_WITH_RC4_128_SHA,          SSL_ALLOWED, PR_FALSE, PR_FALSE},
119 #endif /* NSS_ENABLE_ECC */
120  { TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA,   SSL_ALLOWED, PR_FALSE, PR_FALSE},
121  { TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA,   SSL_ALLOWED, PR_FALSE, PR_FALSE},
122  { TLS_DHE_RSA_WITH_AES_128_CBC_SHA,        SSL_ALLOWED, PR_TRUE,  PR_FALSE},
123  { TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,     SSL_ALLOWED, PR_TRUE,  PR_FALSE},
124  { TLS_DHE_DSS_WITH_AES_128_CBC_SHA,        SSL_ALLOWED, PR_TRUE,  PR_FALSE},
125  { TLS_DHE_DSS_WITH_RC4_128_SHA,            SSL_ALLOWED, PR_FALSE, PR_FALSE},
126 #ifdef NSS_ENABLE_ECC
127  { TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,       SSL_ALLOWED, PR_FALSE, PR_FALSE},
128  { TLS_ECDH_RSA_WITH_RC4_128_SHA,           SSL_ALLOWED, PR_FALSE, PR_FALSE},
129  { TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,     SSL_ALLOWED, PR_FALSE, PR_FALSE},
130  { TLS_ECDH_ECDSA_WITH_RC4_128_SHA,         SSL_ALLOWED, PR_FALSE, PR_FALSE},
131 #endif /* NSS_ENABLE_ECC */
132  { TLS_RSA_WITH_SEED_CBC_SHA,               SSL_ALLOWED, PR_FALSE, PR_FALSE},
133  { TLS_RSA_WITH_CAMELLIA_128_CBC_SHA,       SSL_ALLOWED, PR_FALSE, PR_FALSE},
134  { TLS_RSA_WITH_AES_128_CBC_SHA,            SSL_ALLOWED, PR_TRUE,  PR_FALSE},
135  { TLS_RSA_WITH_AES_128_CBC_SHA256,         SSL_ALLOWED, PR_TRUE,  PR_FALSE},
136  { SSL_RSA_WITH_RC4_128_SHA,                SSL_ALLOWED, PR_TRUE,  PR_FALSE},
137  { SSL_RSA_WITH_RC4_128_MD5,                SSL_ALLOWED, PR_TRUE,  PR_FALSE},
138
139 #ifdef NSS_ENABLE_ECC
140  { TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA,   SSL_ALLOWED, PR_FALSE, PR_FALSE},
141  { TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,     SSL_ALLOWED, PR_FALSE, PR_FALSE},
142 #endif /* NSS_ENABLE_ECC */
143  { SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA,       SSL_ALLOWED, PR_TRUE,  PR_FALSE},
144  { SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA,       SSL_ALLOWED, PR_TRUE,  PR_FALSE},
145 #ifdef NSS_ENABLE_ECC
146  { TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA,      SSL_ALLOWED, PR_FALSE, PR_FALSE},
147  { TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA,    SSL_ALLOWED, PR_FALSE, PR_FALSE},
148 #endif /* NSS_ENABLE_ECC */
149  { SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA,      SSL_ALLOWED, PR_FALSE, PR_FALSE},
150  { SSL_RSA_WITH_3DES_EDE_CBC_SHA,           SSL_ALLOWED, PR_TRUE,  PR_FALSE},
151
152
153  { SSL_DHE_RSA_WITH_DES_CBC_SHA,            SSL_ALLOWED, PR_FALSE, PR_FALSE},
154  { SSL_DHE_DSS_WITH_DES_CBC_SHA,            SSL_ALLOWED, PR_FALSE, PR_FALSE},
155  { SSL_RSA_FIPS_WITH_DES_CBC_SHA,           SSL_ALLOWED, PR_FALSE, PR_FALSE},
156  { SSL_RSA_WITH_DES_CBC_SHA,                SSL_ALLOWED, PR_FALSE, PR_FALSE},
157  { TLS_RSA_EXPORT1024_WITH_RC4_56_SHA,      SSL_ALLOWED, PR_FALSE, PR_FALSE},
158  { TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA,     SSL_ALLOWED, PR_FALSE, PR_FALSE},
159
160  { SSL_RSA_EXPORT_WITH_RC4_40_MD5,          SSL_ALLOWED, PR_FALSE, PR_FALSE},
161  { SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5,      SSL_ALLOWED, PR_FALSE, PR_FALSE},
162
163 #ifdef NSS_ENABLE_ECC
164  { TLS_ECDHE_ECDSA_WITH_NULL_SHA,           SSL_ALLOWED, PR_FALSE, PR_FALSE},
165  { TLS_ECDHE_RSA_WITH_NULL_SHA,             SSL_ALLOWED, PR_FALSE, PR_FALSE},
166  { TLS_ECDH_RSA_WITH_NULL_SHA,              SSL_ALLOWED, PR_FALSE, PR_FALSE},
167  { TLS_ECDH_ECDSA_WITH_NULL_SHA,            SSL_ALLOWED, PR_FALSE, PR_FALSE},
168 #endif /* NSS_ENABLE_ECC */
169  { SSL_RSA_WITH_NULL_SHA,                   SSL_ALLOWED, PR_FALSE, PR_FALSE},
170  { TLS_RSA_WITH_NULL_SHA256,                SSL_ALLOWED, PR_FALSE, PR_FALSE},
171  { SSL_RSA_WITH_NULL_MD5,                   SSL_ALLOWED, PR_FALSE, PR_FALSE},
172 };
173
174 /* This list of SSL3 compression methods is sorted in descending order of
175  * precedence (desirability).  It only includes compression methods we
176  * implement.
177  */
178 static const /*SSLCompressionMethod*/ PRUint8 compressions [] = {
179 #ifdef NSS_ENABLE_ZLIB
180     ssl_compression_deflate,
181 #endif
182     ssl_compression_null
183 };
184
185 static const int compressionMethodsCount =
186     sizeof(compressions) / sizeof(compressions[0]);
187
188 /* compressionEnabled returns true iff the compression algorithm is enabled
189  * for the given SSL socket. */
190 static PRBool
191 compressionEnabled(sslSocket *ss, SSLCompressionMethod compression)
192 {
193     switch (compression) {
194     case ssl_compression_null:
195         return PR_TRUE;  /* Always enabled */
196 #ifdef NSS_ENABLE_ZLIB
197     case ssl_compression_deflate:
198         return ss->opt.enableDeflate;
199 #endif
200     default:
201         return PR_FALSE;
202     }
203 }
204
205 static const /*SSL3ClientCertificateType */ PRUint8 certificate_types [] = {
206     ct_RSA_sign,
207 #ifdef NSS_ENABLE_ECC
208     ct_ECDSA_sign,
209 #endif /* NSS_ENABLE_ECC */
210     ct_DSS_sign,
211 };
212
213 /* This block is the contents of the supported_signature_algorithms field of
214  * our TLS 1.2 CertificateRequest message, in wire format. See
215  * https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1
216  *
217  * This block contains only sha256 entries because we only support TLS 1.2
218  * CertificateVerify messages that use the handshake hash. */
219 static const PRUint8 supported_signature_algorithms[] = {
220     tls_hash_sha256, tls_sig_rsa,
221 #ifdef NSS_ENABLE_ECC
222     tls_hash_sha256, tls_sig_ecdsa,
223 #endif
224     tls_hash_sha256, tls_sig_dsa,
225 };
226
227 #define EXPORT_RSA_KEY_LENGTH 64        /* bytes */
228
229
230 /* This global item is used only in servers.  It is is initialized by
231 ** SSL_ConfigSecureServer(), and is used in ssl3_SendCertificateRequest().
232 */
233 CERTDistNames *ssl3_server_ca_list = NULL;
234 static SSL3Statistics ssl3stats;
235
236 /* indexed by SSL3BulkCipher */
237 static const ssl3BulkCipherDef bulk_cipher_defs[] = {
238     /*                                       |--------- Lengths --------| */
239     /* cipher             calg               k  s  type         i  b  t  n */
240     /*                                       e  e               v  l  a  o */
241     /*                                       y  c               |  o  g  n */
242     /*                                       |  r               |  c  |  c */
243     /*                                       |  e               |  k  |  e */
244     /*                                       |  t               |  |  |  | */
245     {cipher_null,         calg_null,         0, 0, type_stream, 0, 0, 0, 0},
246     {cipher_rc4,          calg_rc4,         16,16, type_stream, 0, 0, 0, 0},
247     {cipher_rc4_40,       calg_rc4,         16, 5, type_stream, 0, 0, 0, 0},
248     {cipher_rc4_56,       calg_rc4,         16, 7, type_stream, 0, 0, 0, 0},
249     {cipher_rc2,          calg_rc2,         16,16, type_block,  8, 8, 0, 0},
250     {cipher_rc2_40,       calg_rc2,         16, 5, type_block,  8, 8, 0, 0},
251     {cipher_des,          calg_des,          8, 8, type_block,  8, 8, 0, 0},
252     {cipher_3des,         calg_3des,        24,24, type_block,  8, 8, 0, 0},
253     {cipher_des40,        calg_des,          8, 5, type_block,  8, 8, 0, 0},
254     {cipher_idea,         calg_idea,        16,16, type_block,  8, 8, 0, 0},
255     {cipher_aes_128,      calg_aes,         16,16, type_block, 16,16, 0, 0},
256     {cipher_aes_256,      calg_aes,         32,32, type_block, 16,16, 0, 0},
257     {cipher_camellia_128, calg_camellia,    16,16, type_block, 16,16, 0, 0},
258     {cipher_camellia_256, calg_camellia,    32,32, type_block, 16,16, 0, 0},
259     {cipher_seed,         calg_seed,        16,16, type_block, 16,16, 0, 0},
260     {cipher_aes_128_gcm,  calg_aes_gcm,     16,16, type_aead,   4, 0,16, 8},
261     {cipher_missing,      calg_null,         0, 0, type_stream, 0, 0, 0, 0},
262 };
263
264 static const ssl3KEADef kea_defs[] = 
265 { /* indexed by SSL3KeyExchangeAlgorithm */
266     /* kea              exchKeyType signKeyType is_limited limit  tls_keygen */
267     {kea_null,           kt_null,     sign_null, PR_FALSE,   0, PR_FALSE},
268     {kea_rsa,            kt_rsa,      sign_rsa,  PR_FALSE,   0, PR_FALSE},
269     {kea_rsa_export,     kt_rsa,      sign_rsa,  PR_TRUE,  512, PR_FALSE},
270     {kea_rsa_export_1024,kt_rsa,      sign_rsa,  PR_TRUE, 1024, PR_FALSE},
271     {kea_dh_dss,         kt_dh,       sign_dsa,  PR_FALSE,   0, PR_FALSE},
272     {kea_dh_dss_export,  kt_dh,       sign_dsa,  PR_TRUE,  512, PR_FALSE},
273     {kea_dh_rsa,         kt_dh,       sign_rsa,  PR_FALSE,   0, PR_FALSE},
274     {kea_dh_rsa_export,  kt_dh,       sign_rsa,  PR_TRUE,  512, PR_FALSE},
275     {kea_dhe_dss,        kt_dh,       sign_dsa,  PR_FALSE,   0, PR_FALSE},
276     {kea_dhe_dss_export, kt_dh,       sign_dsa,  PR_TRUE,  512, PR_FALSE},
277     {kea_dhe_rsa,        kt_dh,       sign_rsa,  PR_FALSE,   0, PR_FALSE},
278     {kea_dhe_rsa_export, kt_dh,       sign_rsa,  PR_TRUE,  512, PR_FALSE},
279     {kea_dh_anon,        kt_dh,       sign_null, PR_FALSE,   0, PR_FALSE},
280     {kea_dh_anon_export, kt_dh,       sign_null, PR_TRUE,  512, PR_FALSE},
281     {kea_rsa_fips,       kt_rsa,      sign_rsa,  PR_FALSE,   0, PR_TRUE },
282 #ifdef NSS_ENABLE_ECC
283     {kea_ecdh_ecdsa,     kt_ecdh,     sign_ecdsa,  PR_FALSE, 0, PR_FALSE},
284     {kea_ecdhe_ecdsa,    kt_ecdh,     sign_ecdsa,  PR_FALSE,   0, PR_FALSE},
285     {kea_ecdh_rsa,       kt_ecdh,     sign_rsa,  PR_FALSE,   0, PR_FALSE},
286     {kea_ecdhe_rsa,      kt_ecdh,     sign_rsa,  PR_FALSE,   0, PR_FALSE},
287     {kea_ecdh_anon,      kt_ecdh,     sign_null,  PR_FALSE,   0, PR_FALSE},
288 #endif /* NSS_ENABLE_ECC */
289 };
290
291 /* must use ssl_LookupCipherSuiteDef to access */
292 static const ssl3CipherSuiteDef cipher_suite_defs[] = 
293 {
294 /*  cipher_suite                    bulk_cipher_alg mac_alg key_exchange_alg */
295
296     {SSL_NULL_WITH_NULL_NULL,       cipher_null,   mac_null, kea_null},
297     {SSL_RSA_WITH_NULL_MD5,         cipher_null,   mac_md5, kea_rsa},
298     {SSL_RSA_WITH_NULL_SHA,         cipher_null,   mac_sha, kea_rsa},
299     {TLS_RSA_WITH_NULL_SHA256,      cipher_null,   hmac_sha256, kea_rsa},
300     {SSL_RSA_EXPORT_WITH_RC4_40_MD5,cipher_rc4_40, mac_md5, kea_rsa_export},
301     {SSL_RSA_WITH_RC4_128_MD5,      cipher_rc4,    mac_md5, kea_rsa},
302     {SSL_RSA_WITH_RC4_128_SHA,      cipher_rc4,    mac_sha, kea_rsa},
303     {SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5,
304                                     cipher_rc2_40, mac_md5, kea_rsa_export},
305 #if 0 /* not implemented */
306     {SSL_RSA_WITH_IDEA_CBC_SHA,     cipher_idea,   mac_sha, kea_rsa},
307     {SSL_RSA_EXPORT_WITH_DES40_CBC_SHA,
308                                     cipher_des40,  mac_sha, kea_rsa_export},
309 #endif
310     {SSL_RSA_WITH_DES_CBC_SHA,      cipher_des,    mac_sha, kea_rsa},
311     {SSL_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des,   mac_sha, kea_rsa},
312     {SSL_DHE_DSS_WITH_DES_CBC_SHA,  cipher_des,    mac_sha, kea_dhe_dss},
313     {SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA,
314                                     cipher_3des,   mac_sha, kea_dhe_dss},
315     {TLS_DHE_DSS_WITH_RC4_128_SHA,  cipher_rc4,    mac_sha, kea_dhe_dss},
316 #if 0 /* not implemented */
317     {SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA,
318                                     cipher_des40,  mac_sha, kea_dh_dss_export},
319     {SSL_DH_DSS_DES_CBC_SHA,        cipher_des,    mac_sha, kea_dh_dss},
320     {SSL_DH_DSS_3DES_CBC_SHA,       cipher_3des,   mac_sha, kea_dh_dss},
321     {SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA,
322                                     cipher_des40,  mac_sha, kea_dh_rsa_export},
323     {SSL_DH_RSA_DES_CBC_SHA,        cipher_des,    mac_sha, kea_dh_rsa},
324     {SSL_DH_RSA_3DES_CBC_SHA,       cipher_3des,   mac_sha, kea_dh_rsa},
325     {SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA,
326                                     cipher_des40,  mac_sha, kea_dh_dss_export},
327     {SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA,
328                                     cipher_des40,  mac_sha, kea_dh_rsa_export},
329 #endif
330     {SSL_DHE_RSA_WITH_DES_CBC_SHA,  cipher_des,    mac_sha, kea_dhe_rsa},
331     {SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA,
332                                     cipher_3des,   mac_sha, kea_dhe_rsa},
333 #if 0
334     {SSL_DH_ANON_EXPORT_RC4_40_MD5, cipher_rc4_40, mac_md5, kea_dh_anon_export},
335     {SSL_DH_ANON_EXPORT_WITH_DES40_CBC_SHA,
336                                     cipher_des40,  mac_sha, kea_dh_anon_export},
337     {SSL_DH_ANON_DES_CBC_SHA,       cipher_des,    mac_sha, kea_dh_anon},
338     {SSL_DH_ANON_3DES_CBC_SHA,      cipher_3des,   mac_sha, kea_dh_anon},
339 #endif
340
341
342 /* New TLS cipher suites */
343     {TLS_RSA_WITH_AES_128_CBC_SHA,      cipher_aes_128, mac_sha, kea_rsa},
344     {TLS_RSA_WITH_AES_128_CBC_SHA256,   cipher_aes_128, hmac_sha256, kea_rsa},
345     {TLS_DHE_DSS_WITH_AES_128_CBC_SHA,  cipher_aes_128, mac_sha, kea_dhe_dss},
346     {TLS_DHE_RSA_WITH_AES_128_CBC_SHA,  cipher_aes_128, mac_sha, kea_dhe_rsa},
347     {TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_dhe_rsa},
348     {TLS_RSA_WITH_AES_256_CBC_SHA,      cipher_aes_256, mac_sha, kea_rsa},
349     {TLS_RSA_WITH_AES_256_CBC_SHA256,   cipher_aes_256, hmac_sha256, kea_rsa},
350     {TLS_DHE_DSS_WITH_AES_256_CBC_SHA,  cipher_aes_256, mac_sha, kea_dhe_dss},
351     {TLS_DHE_RSA_WITH_AES_256_CBC_SHA,  cipher_aes_256, mac_sha, kea_dhe_rsa},
352     {TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, cipher_aes_256, hmac_sha256, kea_dhe_rsa},
353 #if 0
354     {TLS_DH_DSS_WITH_AES_128_CBC_SHA,   cipher_aes_128, mac_sha, kea_dh_dss},
355     {TLS_DH_RSA_WITH_AES_128_CBC_SHA,   cipher_aes_128, mac_sha, kea_dh_rsa},
356     {TLS_DH_ANON_WITH_AES_128_CBC_SHA,  cipher_aes_128, mac_sha, kea_dh_anon},
357     {TLS_DH_DSS_WITH_AES_256_CBC_SHA,   cipher_aes_256, mac_sha, kea_dh_dss},
358     {TLS_DH_RSA_WITH_AES_256_CBC_SHA,   cipher_aes_256, mac_sha, kea_dh_rsa},
359     {TLS_DH_ANON_WITH_AES_256_CBC_SHA,  cipher_aes_256, mac_sha, kea_dh_anon},
360 #endif
361
362     {TLS_RSA_WITH_SEED_CBC_SHA,     cipher_seed,   mac_sha, kea_rsa},
363
364     {TLS_RSA_WITH_CAMELLIA_128_CBC_SHA, cipher_camellia_128, mac_sha, kea_rsa},
365     {TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA,
366      cipher_camellia_128, mac_sha, kea_dhe_dss},
367     {TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA,
368      cipher_camellia_128, mac_sha, kea_dhe_rsa},
369     {TLS_RSA_WITH_CAMELLIA_256_CBC_SHA, cipher_camellia_256, mac_sha, kea_rsa},
370     {TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA,
371      cipher_camellia_256, mac_sha, kea_dhe_dss},
372     {TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA,
373      cipher_camellia_256, mac_sha, kea_dhe_rsa},
374
375     {TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA,
376                                     cipher_des,    mac_sha,kea_rsa_export_1024},
377     {TLS_RSA_EXPORT1024_WITH_RC4_56_SHA,
378                                     cipher_rc4_56, mac_sha,kea_rsa_export_1024},
379
380     {SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_rsa_fips},
381     {SSL_RSA_FIPS_WITH_DES_CBC_SHA, cipher_des,    mac_sha, kea_rsa_fips},
382
383     {TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_dhe_rsa},
384     {TLS_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_rsa},
385     {TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_ecdhe_rsa},
386     {TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_ecdhe_ecdsa},
387
388 #ifdef NSS_ENABLE_ECC
389     {TLS_ECDH_ECDSA_WITH_NULL_SHA,        cipher_null, mac_sha, kea_ecdh_ecdsa},
390     {TLS_ECDH_ECDSA_WITH_RC4_128_SHA,      cipher_rc4, mac_sha, kea_ecdh_ecdsa},
391     {TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdh_ecdsa},
392     {TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdh_ecdsa},
393     {TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdh_ecdsa},
394
395     {TLS_ECDHE_ECDSA_WITH_NULL_SHA,        cipher_null, mac_sha, kea_ecdhe_ecdsa},
396     {TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,      cipher_rc4, mac_sha, kea_ecdhe_ecdsa},
397     {TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdhe_ecdsa},
398     {TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdhe_ecdsa},
399     {TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_ecdhe_ecdsa},
400     {TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdhe_ecdsa},
401
402     {TLS_ECDH_RSA_WITH_NULL_SHA,         cipher_null,    mac_sha, kea_ecdh_rsa},
403     {TLS_ECDH_RSA_WITH_RC4_128_SHA,      cipher_rc4,     mac_sha, kea_ecdh_rsa},
404     {TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des,    mac_sha, kea_ecdh_rsa},
405     {TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,  cipher_aes_128, mac_sha, kea_ecdh_rsa},
406     {TLS_ECDH_RSA_WITH_AES_256_CBC_SHA,  cipher_aes_256, mac_sha, kea_ecdh_rsa},
407
408     {TLS_ECDHE_RSA_WITH_NULL_SHA,         cipher_null,    mac_sha, kea_ecdhe_rsa},
409     {TLS_ECDHE_RSA_WITH_RC4_128_SHA,      cipher_rc4,     mac_sha, kea_ecdhe_rsa},
410     {TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des,    mac_sha, kea_ecdhe_rsa},
411     {TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,  cipher_aes_128, mac_sha, kea_ecdhe_rsa},
412     {TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_ecdhe_rsa},
413     {TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,  cipher_aes_256, mac_sha, kea_ecdhe_rsa},
414
415 #if 0
416     {TLS_ECDH_anon_WITH_NULL_SHA,         cipher_null,    mac_sha, kea_ecdh_anon},
417     {TLS_ECDH_anon_WITH_RC4_128_SHA,      cipher_rc4,     mac_sha, kea_ecdh_anon},
418     {TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA, cipher_3des,    mac_sha, kea_ecdh_anon},
419     {TLS_ECDH_anon_WITH_AES_128_CBC_SHA,  cipher_aes_128, mac_sha, kea_ecdh_anon},
420     {TLS_ECDH_anon_WITH_AES_256_CBC_SHA,  cipher_aes_256, mac_sha, kea_ecdh_anon},
421 #endif
422 #endif /* NSS_ENABLE_ECC */
423 };
424
425 static const CK_MECHANISM_TYPE kea_alg_defs[] = {
426     0x80000000L,
427     CKM_RSA_PKCS,
428     CKM_DH_PKCS_DERIVE,
429     CKM_KEA_KEY_DERIVE,
430     CKM_ECDH1_DERIVE
431 };
432
433 typedef struct SSLCipher2MechStr {
434     SSLCipherAlgorithm  calg;
435     CK_MECHANISM_TYPE   cmech;
436 } SSLCipher2Mech;
437
438 /* indexed by type SSLCipherAlgorithm */
439 static const SSLCipher2Mech alg2Mech[] = {
440     /* calg,          cmech  */
441     { calg_null     , (CK_MECHANISM_TYPE)0x80000000L    },
442     { calg_rc4      , CKM_RC4                           },
443     { calg_rc2      , CKM_RC2_CBC                       },
444     { calg_des      , CKM_DES_CBC                       },
445     { calg_3des     , CKM_DES3_CBC                      },
446     { calg_idea     , CKM_IDEA_CBC                      },
447     { calg_fortezza , CKM_SKIPJACK_CBC64                },
448     { calg_aes      , CKM_AES_CBC                       },
449     { calg_camellia , CKM_CAMELLIA_CBC                  },
450     { calg_seed     , CKM_SEED_CBC                      },
451     { calg_aes_gcm  , CKM_AES_GCM                       },
452 /*  { calg_init     , (CK_MECHANISM_TYPE)0x7fffffffL    }  */
453 };
454
455 #define mmech_invalid  (CK_MECHANISM_TYPE)0x80000000L
456 #define mmech_md5      CKM_SSL3_MD5_MAC
457 #define mmech_sha      CKM_SSL3_SHA1_MAC
458 #define mmech_md5_hmac CKM_MD5_HMAC
459 #define mmech_sha_hmac CKM_SHA_1_HMAC
460 #define mmech_sha256_hmac CKM_SHA256_HMAC
461
462 static const ssl3MACDef mac_defs[] = { /* indexed by SSL3MACAlgorithm */
463     /* pad_size is only used for SSL 3.0 MAC. See RFC 6101 Sec. 5.2.3.1. */
464     /* mac      mmech       pad_size  mac_size                       */
465     { mac_null, mmech_invalid,    0,  0          },
466     { mac_md5,  mmech_md5,       48,  MD5_LENGTH },
467     { mac_sha,  mmech_sha,       40,  SHA1_LENGTH},
468     {hmac_md5,  mmech_md5_hmac,   0,  MD5_LENGTH },
469     {hmac_sha,  mmech_sha_hmac,   0,  SHA1_LENGTH},
470     {hmac_sha256, mmech_sha256_hmac, 0, SHA256_LENGTH},
471     { mac_aead, mmech_invalid,    0,  0          },
472 };
473
474 /* indexed by SSL3BulkCipher */
475 const char * const ssl3_cipherName[] = {
476     "NULL",
477     "RC4",
478     "RC4-40",
479     "RC4-56",
480     "RC2-CBC",
481     "RC2-CBC-40",
482     "DES-CBC",
483     "3DES-EDE-CBC",
484     "DES-CBC-40",
485     "IDEA-CBC",
486     "AES-128",
487     "AES-256",
488     "Camellia-128",
489     "Camellia-256",
490     "SEED-CBC",
491     "AES-128-GCM",
492     "missing"
493 };
494
495 #ifdef NSS_ENABLE_ECC
496 /* The ECCWrappedKeyInfo structure defines how various pieces of 
497  * information are laid out within wrappedSymmetricWrappingkey 
498  * for ECDH key exchange. Since wrappedSymmetricWrappingkey is 
499  * a 512-byte buffer (see sslimpl.h), the variable length field 
500  * in ECCWrappedKeyInfo can be at most (512 - 8) = 504 bytes.
501  *
502  * XXX For now, NSS only supports named elliptic curves of size 571 bits 
503  * or smaller. The public value will fit within 145 bytes and EC params
504  * will fit within 12 bytes. We'll need to revisit this when NSS
505  * supports arbitrary curves.
506  */
507 #define MAX_EC_WRAPPED_KEY_BUFLEN  504
508
509 typedef struct ECCWrappedKeyInfoStr {
510     PRUint16 size;            /* EC public key size in bits */
511     PRUint16 encodedParamLen; /* length (in bytes) of DER encoded EC params */
512     PRUint16 pubValueLen;     /* length (in bytes) of EC public value */
513     PRUint16 wrappedKeyLen;   /* length (in bytes) of the wrapped key */
514     PRUint8 var[MAX_EC_WRAPPED_KEY_BUFLEN]; /* this buffer contains the */
515     /* EC public-key params, the EC public value and the wrapped key  */
516 } ECCWrappedKeyInfo;
517 #endif /* NSS_ENABLE_ECC */
518
519 #if defined(TRACE)
520
521 static char *
522 ssl3_DecodeHandshakeType(int msgType)
523 {
524     char * rv;
525     static char line[40];
526
527     switch(msgType) {
528     case hello_request:         rv = "hello_request (0)";               break;
529     case client_hello:          rv = "client_hello  (1)";               break;
530     case server_hello:          rv = "server_hello  (2)";               break;
531     case hello_verify_request:  rv = "hello_verify_request (3)";        break;
532     case certificate:           rv = "certificate  (11)";               break;
533     case server_key_exchange:   rv = "server_key_exchange (12)";        break;
534     case certificate_request:   rv = "certificate_request (13)";        break;
535     case server_hello_done:     rv = "server_hello_done   (14)";        break;
536     case certificate_verify:    rv = "certificate_verify  (15)";        break;
537     case client_key_exchange:   rv = "client_key_exchange (16)";        break;
538     case finished:              rv = "finished     (20)";               break;
539     default:
540         sprintf(line, "*UNKNOWN* handshake type! (%d)", msgType);
541         rv = line;
542     }
543     return rv;
544 }
545
546 static char *
547 ssl3_DecodeContentType(int msgType)
548 {
549     char * rv;
550     static char line[40];
551
552     switch(msgType) {
553     case content_change_cipher_spec:
554                                 rv = "change_cipher_spec (20)";         break;
555     case content_alert:         rv = "alert      (21)";                 break;
556     case content_handshake:     rv = "handshake  (22)";                 break;
557     case content_application_data:
558                                 rv = "application_data (23)";           break;
559     default:
560         sprintf(line, "*UNKNOWN* record type! (%d)", msgType);
561         rv = line;
562     }
563     return rv;
564 }
565
566 #endif
567
568 SSL3Statistics * 
569 SSL_GetStatistics(void)
570 {
571     return &ssl3stats;
572 }
573
574 typedef struct tooLongStr {
575 #if defined(IS_LITTLE_ENDIAN)
576     PRInt32 low;
577     PRInt32 high;
578 #else
579     PRInt32 high;
580     PRInt32 low;
581 #endif
582 } tooLong;
583
584 void SSL_AtomicIncrementLong(long * x)
585 {
586     if ((sizeof *x) == sizeof(PRInt32)) {
587         PR_ATOMIC_INCREMENT((PRInt32 *)x);
588     } else {
589         tooLong * tl = (tooLong *)x;
590         if (PR_ATOMIC_INCREMENT(&tl->low) == 0)
591             PR_ATOMIC_INCREMENT(&tl->high);
592     }
593 }
594
595 static PRBool
596 ssl3_CipherSuiteAllowedForVersionRange(
597     ssl3CipherSuite cipherSuite,
598     const SSLVersionRange *vrange)
599 {
600     switch (cipherSuite) {
601     /* See RFC 4346 A.5. Export cipher suites must not be used in TLS 1.1 or
602      * later. This set of cipher suites is similar to, but different from, the
603      * set of cipher suites considered exportable by SSL_IsExportCipherSuite.
604      */
605     case SSL_RSA_EXPORT_WITH_RC4_40_MD5:
606     case SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5:
607     /*   SSL_RSA_EXPORT_WITH_DES40_CBC_SHA:      never implemented
608      *   SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA:   never implemented
609      *   SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA:   never implemented
610      *   SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA:  never implemented
611      *   SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA:  never implemented
612      *   SSL_DH_ANON_EXPORT_WITH_RC4_40_MD5:     never implemented
613      *   SSL_DH_ANON_EXPORT_WITH_DES40_CBC_SHA:  never implemented
614      */
615         return vrange->min <= SSL_LIBRARY_VERSION_TLS_1_0;
616     case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256:
617     case TLS_RSA_WITH_AES_256_CBC_SHA256:
618     case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
619     case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
620     case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
621     case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
622     case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256:
623     case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
624     case TLS_RSA_WITH_AES_128_CBC_SHA256:
625     case TLS_RSA_WITH_AES_128_GCM_SHA256:
626     case TLS_RSA_WITH_NULL_SHA256:
627         return vrange->max >= SSL_LIBRARY_VERSION_TLS_1_2;
628     default:
629         return PR_TRUE;
630     }
631 }
632
633 /* return pointer to ssl3CipherSuiteDef for suite, or NULL */
634 /* XXX This does a linear search.  A binary search would be better. */
635 static const ssl3CipherSuiteDef *
636 ssl_LookupCipherSuiteDef(ssl3CipherSuite suite)
637 {
638     int cipher_suite_def_len =
639         sizeof(cipher_suite_defs) / sizeof(cipher_suite_defs[0]);
640     int i;
641
642     for (i = 0; i < cipher_suite_def_len; i++) {
643         if (cipher_suite_defs[i].cipher_suite == suite)
644             return &cipher_suite_defs[i];
645     }
646     PORT_Assert(PR_FALSE);  /* We should never get here. */
647     PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE);
648     return NULL;
649 }
650
651 /* Find the cipher configuration struct associate with suite */
652 /* XXX This does a linear search.  A binary search would be better. */
653 static ssl3CipherSuiteCfg *
654 ssl_LookupCipherSuiteCfg(ssl3CipherSuite suite, ssl3CipherSuiteCfg *suites)
655 {
656     int i;
657
658     for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
659         if (suites[i].cipher_suite == suite)
660             return &suites[i];
661     }
662     /* return NULL and let the caller handle it.  */
663     PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE);
664     return NULL;
665 }
666
667
668 /* Initialize the suite->isPresent value for config_match
669  * Returns count of enabled ciphers supported by extant tokens,
670  * regardless of policy or user preference.
671  * If this returns zero, the user cannot do SSL v3.
672  */
673 int
674 ssl3_config_match_init(sslSocket *ss)
675 {
676     ssl3CipherSuiteCfg *      suite;
677     const ssl3CipherSuiteDef *cipher_def;
678     SSLCipherAlgorithm        cipher_alg;
679     CK_MECHANISM_TYPE         cipher_mech;
680     SSL3KEAType               exchKeyType;
681     int                       i;
682     int                       numPresent                = 0;
683     int                       numEnabled                = 0;
684     PRBool                    isServer;
685     sslServerCerts           *svrAuth;
686
687     PORT_Assert(ss);
688     if (!ss) {
689         PORT_SetError(SEC_ERROR_INVALID_ARGS);
690         return 0;
691     }
692     if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
693         return 0;
694     }
695     isServer = (PRBool)(ss->sec.isServer != 0);
696
697     for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
698         suite = &ss->cipherSuites[i];
699         if (suite->enabled) {
700             ++numEnabled;
701             /* We need the cipher defs to see if we have a token that can handle
702              * this cipher.  It isn't part of the static definition.
703              */
704             cipher_def = ssl_LookupCipherSuiteDef(suite->cipher_suite);
705             if (!cipher_def) {
706                 suite->isPresent = PR_FALSE;
707                 continue;
708             }
709             cipher_alg = bulk_cipher_defs[cipher_def->bulk_cipher_alg].calg;
710             PORT_Assert(  alg2Mech[cipher_alg].calg == cipher_alg);
711             cipher_mech = alg2Mech[cipher_alg].cmech;
712             exchKeyType =
713                     kea_defs[cipher_def->key_exchange_alg].exchKeyType;
714 #ifndef NSS_ENABLE_ECC
715             svrAuth = ss->serverCerts + exchKeyType;
716 #else
717             /* XXX SSLKEAType isn't really a good choice for 
718              * indexing certificates. It doesn't work for
719              * (EC)DHE-* ciphers. Here we use a hack to ensure
720              * that the server uses an RSA cert for (EC)DHE-RSA.
721              */
722             switch (cipher_def->key_exchange_alg) {
723             case kea_ecdhe_rsa:
724 #if NSS_SERVER_DHE_IMPLEMENTED
725             /* XXX NSS does not yet implement the server side of _DHE_
726              * cipher suites.  Correcting the computation for svrAuth,
727              * as the case below does, causes NSS SSL servers to begin to
728              * negotiate cipher suites they do not implement.  So, until
729              * server side _DHE_ is implemented, keep this disabled.
730              */
731             case kea_dhe_rsa:
732 #endif
733                 svrAuth = ss->serverCerts + kt_rsa;
734                 break;
735             case kea_ecdh_ecdsa:
736             case kea_ecdh_rsa:
737                 /* 
738                  * XXX We ought to have different indices for 
739                  * ECDSA- and RSA-signed EC certificates so
740                  * we could support both key exchange mechanisms
741                  * simultaneously. For now, both of them use
742                  * whatever is in the certificate slot for kt_ecdh
743                  */
744             default:
745                 svrAuth = ss->serverCerts + exchKeyType;
746                 break;
747             }
748 #endif /* NSS_ENABLE_ECC */
749
750             /* Mark the suites that are backed by real tokens, certs and keys */
751             suite->isPresent = (PRBool)
752                 (((exchKeyType == kt_null) ||
753                    ((!isServer || (svrAuth->serverKeyPair &&
754                                    svrAuth->SERVERKEY &&
755                                    svrAuth->serverCertChain)) &&
756                     PK11_TokenExists(kea_alg_defs[exchKeyType]))) &&
757                 ((cipher_alg == calg_null) || PK11_TokenExists(cipher_mech)));
758             if (suite->isPresent)
759                 ++numPresent;
760         }
761     }
762     PORT_Assert(numPresent > 0 || numEnabled == 0);
763     if (numPresent <= 0) {
764         PORT_SetError(SSL_ERROR_NO_CIPHERS_SUPPORTED);
765     }
766     return numPresent;
767 }
768
769
770 /* return PR_TRUE if suite matches policy, enabled state and is applicable to
771  * the given version range. */
772 /* It would be a REALLY BAD THING (tm) if we ever permitted the use
773 ** of a cipher that was NOT_ALLOWED.  So, if this is ever called with
774 ** policy == SSL_NOT_ALLOWED, report no match.
775 */
776 /* adjust suite enabled to the availability of a token that can do the
777  * cipher suite. */
778 static PRBool
779 config_match(ssl3CipherSuiteCfg *suite, int policy, PRBool enabled,
780              const SSLVersionRange *vrange)
781 {
782     PORT_Assert(policy != SSL_NOT_ALLOWED && enabled != PR_FALSE);
783     if (policy == SSL_NOT_ALLOWED || !enabled)
784         return PR_FALSE;
785     return (PRBool)(suite->enabled &&
786                     suite->isPresent &&
787                     suite->policy != SSL_NOT_ALLOWED &&
788                     suite->policy <= policy &&
789                     ssl3_CipherSuiteAllowedForVersionRange(
790                         suite->cipher_suite, vrange));
791 }
792
793 /* return number of cipher suites that match policy, enabled state and are
794  * applicable for the configured protocol version range. */
795 /* called from ssl3_SendClientHello and ssl3_ConstructV2CipherSpecsHack */
796 static int
797 count_cipher_suites(sslSocket *ss, int policy, PRBool enabled)
798 {
799     int i, count = 0;
800
801     if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
802         return 0;
803     }
804     for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
805         if (config_match(&ss->cipherSuites[i], policy, enabled, &ss->vrange))
806             count++;
807     }
808     if (count <= 0) {
809         PORT_SetError(SSL_ERROR_SSL_DISABLED);
810     }
811     return count;
812 }
813
814 /*
815  * Null compression, mac and encryption functions
816  */
817
818 static SECStatus
819 Null_Cipher(void *ctx, unsigned char *output, int *outputLen, int maxOutputLen,
820             const unsigned char *input, int inputLen)
821 {
822     if (inputLen > maxOutputLen) {
823         *outputLen = 0;  /* Match PK11_CipherOp in setting outputLen */
824         PORT_SetError(SEC_ERROR_OUTPUT_LEN);
825         return SECFailure;
826     }
827     *outputLen = inputLen;
828     if (input != output)
829         PORT_Memcpy(output, input, inputLen);
830     return SECSuccess;
831 }
832
833 /*
834  * SSL3 Utility functions
835  */
836
837 /* allowLargerPeerVersion controls whether the function will select the
838  * highest enabled SSL version or fail when peerVersion is greater than the
839  * highest enabled version.
840  *
841  * If allowLargerPeerVersion is true, peerVersion is the peer's highest
842  * enabled version rather than the peer's selected version.
843  */
844 SECStatus
845 ssl3_NegotiateVersion(sslSocket *ss, SSL3ProtocolVersion peerVersion,
846                       PRBool allowLargerPeerVersion)
847 {
848     if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
849         PORT_SetError(SSL_ERROR_SSL_DISABLED);
850         return SECFailure;
851     }
852
853     if (peerVersion < ss->vrange.min ||
854         (peerVersion > ss->vrange.max && !allowLargerPeerVersion)) {
855         PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
856         return SECFailure;
857     }
858
859     ss->version = PR_MIN(peerVersion, ss->vrange.max);
860     PORT_Assert(ssl3_VersionIsSupported(ss->protocolVariant, ss->version));
861
862     return SECSuccess;
863 }
864
865 static SECStatus
866 ssl3_GetNewRandom(SSL3Random *random)
867 {
868     PRUint32 gmt = ssl_Time();
869     SECStatus rv;
870
871     random->rand[0] = (unsigned char)(gmt >> 24);
872     random->rand[1] = (unsigned char)(gmt >> 16);
873     random->rand[2] = (unsigned char)(gmt >>  8);
874     random->rand[3] = (unsigned char)(gmt);
875
876     /* first 4 bytes are reserverd for time */
877     rv = PK11_GenerateRandom(&random->rand[4], SSL3_RANDOM_LENGTH - 4);
878     if (rv != SECSuccess) {
879         ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
880     }
881     return rv;
882 }
883
884 /* Called by ssl3_SendServerKeyExchange and ssl3_SendCertificateVerify */
885 SECStatus
886 ssl3_SignHashes(SSL3Hashes *hash, SECKEYPrivateKey *key, SECItem *buf, 
887                 PRBool isTLS)
888 {
889     SECStatus rv                = SECFailure;
890     PRBool    doDerEncode       = PR_FALSE;
891     int       signatureLen;
892     SECItem   hashItem;
893
894     buf->data    = NULL;
895
896     switch (key->keyType) {
897     case rsaKey:
898         hashItem.data = hash->u.raw;
899         hashItem.len = hash->len;
900         break;
901     case dsaKey:
902         doDerEncode = isTLS;
903         /* SEC_OID_UNKNOWN is used to specify the MD5/SHA1 concatenated hash.
904          * In that case, we use just the SHA1 part. */
905         if (hash->hashAlg == SEC_OID_UNKNOWN) {
906             hashItem.data = hash->u.s.sha;
907             hashItem.len = sizeof(hash->u.s.sha);
908         } else {
909             hashItem.data = hash->u.raw;
910             hashItem.len = hash->len;
911         }
912         break;
913 #ifdef NSS_ENABLE_ECC
914     case ecKey:
915         doDerEncode = PR_TRUE;
916         /* SEC_OID_UNKNOWN is used to specify the MD5/SHA1 concatenated hash.
917          * In that case, we use just the SHA1 part. */
918         if (hash->hashAlg == SEC_OID_UNKNOWN) {
919             hashItem.data = hash->u.s.sha;
920             hashItem.len = sizeof(hash->u.s.sha);
921         } else {
922             hashItem.data = hash->u.raw;
923             hashItem.len = hash->len;
924         }
925         break;
926 #endif /* NSS_ENABLE_ECC */
927     default:
928         PORT_SetError(SEC_ERROR_INVALID_KEY);
929         goto done;
930     }
931     PRINT_BUF(60, (NULL, "hash(es) to be signed", hashItem.data, hashItem.len));
932
933     if (hash->hashAlg == SEC_OID_UNKNOWN) {
934         signatureLen = PK11_SignatureLen(key);
935         if (signatureLen <= 0) {
936             PORT_SetError(SEC_ERROR_INVALID_KEY);
937             goto done;
938         }
939
940         buf->len  = (unsigned)signatureLen;
941         buf->data = (unsigned char *)PORT_Alloc(signatureLen);
942         if (!buf->data)
943             goto done;  /* error code was set. */
944
945         rv = PK11_Sign(key, buf, &hashItem);
946     } else {
947         rv = SGN_Digest(key, hash->hashAlg, buf, &hashItem);
948     }
949     if (rv != SECSuccess) {
950         ssl_MapLowLevelError(SSL_ERROR_SIGN_HASHES_FAILURE);
951     } else if (doDerEncode) {
952         SECItem   derSig        = {siBuffer, NULL, 0};
953
954         /* This also works for an ECDSA signature */
955         rv = DSAU_EncodeDerSigWithLen(&derSig, buf, buf->len);
956         if (rv == SECSuccess) {
957             PORT_Free(buf->data);       /* discard unencoded signature. */
958             *buf = derSig;              /* give caller encoded signature. */
959         } else if (derSig.data) {
960             PORT_Free(derSig.data);
961         }
962     }
963
964     PRINT_BUF(60, (NULL, "signed hashes", (unsigned char*)buf->data, buf->len));
965 done:
966     if (rv != SECSuccess && buf->data) {
967         PORT_Free(buf->data);
968         buf->data = NULL;
969     }
970     return rv;
971 }
972
973 /* Called from ssl3_HandleServerKeyExchange, ssl3_HandleCertificateVerify */
974 SECStatus
975 ssl3_VerifySignedHashes(SSL3Hashes *hash, CERTCertificate *cert, 
976                         SECItem *buf, PRBool isTLS, void *pwArg)
977 {
978     SECKEYPublicKey * key;
979     SECItem *         signature = NULL;
980     SECStatus         rv;
981     SECItem           hashItem;
982     SECOidTag         encAlg;
983     SECOidTag         hashAlg;
984
985
986     PRINT_BUF(60, (NULL, "check signed hashes",
987                   buf->data, buf->len));
988
989     key = CERT_ExtractPublicKey(cert);
990     if (key == NULL) {
991         ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
992         return SECFailure;
993     }
994
995     hashAlg = hash->hashAlg;
996     switch (key->keyType) {
997     case rsaKey:
998         encAlg = SEC_OID_PKCS1_RSA_ENCRYPTION;
999         hashItem.data = hash->u.raw;
1000         hashItem.len = hash->len;
1001         break;
1002     case dsaKey:
1003         encAlg = SEC_OID_ANSIX9_DSA_SIGNATURE;
1004         /* SEC_OID_UNKNOWN is used to specify the MD5/SHA1 concatenated hash.
1005          * In that case, we use just the SHA1 part. */
1006         if (hash->hashAlg == SEC_OID_UNKNOWN) {
1007             hashItem.data = hash->u.s.sha;
1008             hashItem.len = sizeof(hash->u.s.sha);
1009         } else {
1010             hashItem.data = hash->u.raw;
1011             hashItem.len = hash->len;
1012         }
1013         /* Allow DER encoded DSA signatures in SSL 3.0 */
1014         if (isTLS || buf->len != SECKEY_SignatureLen(key)) {
1015             signature = DSAU_DecodeDerSig(buf);
1016             if (!signature) {
1017                 PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
1018                 return SECFailure;
1019             }
1020             buf = signature;
1021         }
1022         break;
1023
1024 #ifdef NSS_ENABLE_ECC
1025     case ecKey:
1026         encAlg = SEC_OID_ANSIX962_EC_PUBLIC_KEY;
1027         /* SEC_OID_UNKNOWN is used to specify the MD5/SHA1 concatenated hash.
1028          * In that case, we use just the SHA1 part.
1029          * ECDSA signatures always encode the integers r and s using ASN.1
1030          * (unlike DSA where ASN.1 encoding is used with TLS but not with
1031          * SSL3). So we can use VFY_VerifyDigestDirect for ECDSA.
1032          */
1033         if (hash->hashAlg == SEC_OID_UNKNOWN) {
1034             hashAlg = SEC_OID_SHA1;
1035             hashItem.data = hash->u.s.sha;
1036             hashItem.len = sizeof(hash->u.s.sha);
1037         } else {
1038             hashItem.data = hash->u.raw;
1039             hashItem.len = hash->len;
1040         }
1041         break;
1042 #endif /* NSS_ENABLE_ECC */
1043
1044     default:
1045         SECKEY_DestroyPublicKey(key);
1046         PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
1047         return SECFailure;
1048     }
1049
1050     PRINT_BUF(60, (NULL, "hash(es) to be verified",
1051                   hashItem.data, hashItem.len));
1052
1053     if (hashAlg == SEC_OID_UNKNOWN || key->keyType == dsaKey) {
1054         /* VFY_VerifyDigestDirect requires DSA signatures to be DER-encoded.
1055          * DSA signatures are DER-encoded in TLS but not in SSL3 and the code
1056          * above always removes the DER encoding of DSA signatures when
1057          * present. Thus DSA signatures are always verified with PK11_Verify.
1058          */
1059         rv = PK11_Verify(key, buf, &hashItem, pwArg);
1060     } else {
1061         rv = VFY_VerifyDigestDirect(&hashItem, key, buf, encAlg, hashAlg,
1062                                     pwArg);
1063     }
1064     SECKEY_DestroyPublicKey(key);
1065     if (signature) {
1066         SECITEM_FreeItem(signature, PR_TRUE);
1067     }
1068     if (rv != SECSuccess) {
1069         ssl_MapLowLevelError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
1070     }
1071     return rv;
1072 }
1073
1074
1075 /* Caller must set hiLevel error code. */
1076 /* Called from ssl3_ComputeExportRSAKeyHash
1077  *             ssl3_ComputeDHKeyHash
1078  * which are called from ssl3_HandleServerKeyExchange. 
1079  *
1080  * hashAlg: either the OID for a hash algorithm or SEC_OID_UNKNOWN to specify
1081  * the pre-1.2, MD5/SHA1 combination hash.
1082  */
1083 SECStatus
1084 ssl3_ComputeCommonKeyHash(SECOidTag hashAlg,
1085                           PRUint8 * hashBuf, unsigned int bufLen,
1086                           SSL3Hashes *hashes, PRBool bypassPKCS11)
1087 {
1088     SECStatus     rv            = SECSuccess;
1089
1090 #ifndef NO_PKCS11_BYPASS
1091     if (bypassPKCS11) {
1092         if (hashAlg == SEC_OID_UNKNOWN) {
1093             MD5_HashBuf (hashes->u.s.md5, hashBuf, bufLen);
1094             SHA1_HashBuf(hashes->u.s.sha, hashBuf, bufLen);
1095             hashes->len = MD5_LENGTH + SHA1_LENGTH;
1096         } else if (hashAlg == SEC_OID_SHA1) {
1097             SHA1_HashBuf(hashes->u.raw, hashBuf, bufLen);
1098             hashes->len = SHA1_LENGTH;
1099         } else if (hashAlg == SEC_OID_SHA256) {
1100             SHA256_HashBuf(hashes->u.raw, hashBuf, bufLen);
1101             hashes->len = SHA256_LENGTH;
1102         } else if (hashAlg == SEC_OID_SHA384) {
1103             SHA384_HashBuf(hashes->u.raw, hashBuf, bufLen);
1104             hashes->len = SHA384_LENGTH;
1105         } else if (hashAlg == SEC_OID_SHA512) {
1106             SHA512_HashBuf(hashes->u.raw, hashBuf, bufLen);
1107             hashes->len = SHA512_LENGTH;
1108         } else {
1109             PORT_SetError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
1110             return SECFailure;
1111         }
1112     } else 
1113 #endif
1114     {
1115         if (hashAlg == SEC_OID_UNKNOWN) {
1116             rv = PK11_HashBuf(SEC_OID_MD5, hashes->u.s.md5, hashBuf, bufLen);
1117             if (rv != SECSuccess) {
1118                 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
1119                 rv = SECFailure;
1120                 goto done;
1121             }
1122
1123             rv = PK11_HashBuf(SEC_OID_SHA1, hashes->u.s.sha, hashBuf, bufLen);
1124             if (rv != SECSuccess) {
1125                 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
1126                 rv = SECFailure;
1127             }
1128             hashes->len = MD5_LENGTH + SHA1_LENGTH;
1129         } else {
1130             hashes->len = HASH_ResultLenByOidTag(hashAlg);
1131             if (hashes->len > sizeof(hashes->u.raw)) {
1132                 ssl_MapLowLevelError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
1133                 rv = SECFailure;
1134                 goto done;
1135             }
1136             rv = PK11_HashBuf(hashAlg, hashes->u.raw, hashBuf, bufLen);
1137             if (rv != SECSuccess) {
1138                 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
1139                 rv = SECFailure;
1140             }
1141         }
1142     }
1143     hashes->hashAlg = hashAlg;
1144
1145 done:
1146     return rv;
1147 }
1148
1149 /* Caller must set hiLevel error code. 
1150 ** Called from ssl3_SendServerKeyExchange and 
1151 **             ssl3_HandleServerKeyExchange.
1152 */
1153 static SECStatus
1154 ssl3_ComputeExportRSAKeyHash(SECOidTag hashAlg,
1155                              SECItem modulus, SECItem publicExponent,
1156                              SSL3Random *client_rand, SSL3Random *server_rand,
1157                              SSL3Hashes *hashes, PRBool bypassPKCS11)
1158 {
1159     PRUint8     * hashBuf;
1160     PRUint8     * pBuf;
1161     SECStatus     rv            = SECSuccess;
1162     unsigned int  bufLen;
1163     PRUint8       buf[2*SSL3_RANDOM_LENGTH + 2 + 4096/8 + 2 + 4096/8];
1164
1165     bufLen = 2*SSL3_RANDOM_LENGTH + 2 + modulus.len + 2 + publicExponent.len;
1166     if (bufLen <= sizeof buf) {
1167         hashBuf = buf;
1168     } else {
1169         hashBuf = PORT_Alloc(bufLen);
1170         if (!hashBuf) {
1171             return SECFailure;
1172         }
1173     }
1174
1175     memcpy(hashBuf, client_rand, SSL3_RANDOM_LENGTH); 
1176         pBuf = hashBuf + SSL3_RANDOM_LENGTH;
1177     memcpy(pBuf, server_rand, SSL3_RANDOM_LENGTH);
1178         pBuf += SSL3_RANDOM_LENGTH;
1179     pBuf[0]  = (PRUint8)(modulus.len >> 8);
1180     pBuf[1]  = (PRUint8)(modulus.len);
1181         pBuf += 2;
1182     memcpy(pBuf, modulus.data, modulus.len);
1183         pBuf += modulus.len;
1184     pBuf[0] = (PRUint8)(publicExponent.len >> 8);
1185     pBuf[1] = (PRUint8)(publicExponent.len);
1186         pBuf += 2;
1187     memcpy(pBuf, publicExponent.data, publicExponent.len);
1188         pBuf += publicExponent.len;
1189     PORT_Assert((unsigned int)(pBuf - hashBuf) == bufLen);
1190
1191     rv = ssl3_ComputeCommonKeyHash(hashAlg, hashBuf, bufLen, hashes,
1192                                    bypassPKCS11);
1193
1194     PRINT_BUF(95, (NULL, "RSAkey hash: ", hashBuf, bufLen));
1195     if (hashAlg == SEC_OID_UNKNOWN) {
1196         PRINT_BUF(95, (NULL, "RSAkey hash: MD5 result",
1197                   hashes->u.s.md5, MD5_LENGTH));
1198         PRINT_BUF(95, (NULL, "RSAkey hash: SHA1 result",
1199                   hashes->u.s.sha, SHA1_LENGTH));
1200     } else {
1201         PRINT_BUF(95, (NULL, "RSAkey hash: result",
1202                   hashes->u.raw, hashes->len));
1203     }
1204
1205     if (hashBuf != buf && hashBuf != NULL)
1206         PORT_Free(hashBuf);
1207     return rv;
1208 }
1209
1210 /* Caller must set hiLevel error code. */
1211 /* Called from ssl3_HandleServerKeyExchange. */
1212 static SECStatus
1213 ssl3_ComputeDHKeyHash(SECOidTag hashAlg,
1214                       SECItem dh_p, SECItem dh_g, SECItem dh_Ys,
1215                       SSL3Random *client_rand, SSL3Random *server_rand,
1216                       SSL3Hashes *hashes, PRBool bypassPKCS11)
1217 {
1218     PRUint8     * hashBuf;
1219     PRUint8     * pBuf;
1220     SECStatus     rv            = SECSuccess;
1221     unsigned int  bufLen;
1222     PRUint8       buf[2*SSL3_RANDOM_LENGTH + 2 + 4096/8 + 2 + 4096/8];
1223
1224     bufLen = 2*SSL3_RANDOM_LENGTH + 2 + dh_p.len + 2 + dh_g.len + 2 + dh_Ys.len;
1225     if (bufLen <= sizeof buf) {
1226         hashBuf = buf;
1227     } else {
1228         hashBuf = PORT_Alloc(bufLen);
1229         if (!hashBuf) {
1230             return SECFailure;
1231         }
1232     }
1233
1234     memcpy(hashBuf, client_rand, SSL3_RANDOM_LENGTH); 
1235         pBuf = hashBuf + SSL3_RANDOM_LENGTH;
1236     memcpy(pBuf, server_rand, SSL3_RANDOM_LENGTH);
1237         pBuf += SSL3_RANDOM_LENGTH;
1238     pBuf[0]  = (PRUint8)(dh_p.len >> 8);
1239     pBuf[1]  = (PRUint8)(dh_p.len);
1240         pBuf += 2;
1241     memcpy(pBuf, dh_p.data, dh_p.len);
1242         pBuf += dh_p.len;
1243     pBuf[0] = (PRUint8)(dh_g.len >> 8);
1244     pBuf[1] = (PRUint8)(dh_g.len);
1245         pBuf += 2;
1246     memcpy(pBuf, dh_g.data, dh_g.len);
1247         pBuf += dh_g.len;
1248     pBuf[0] = (PRUint8)(dh_Ys.len >> 8);
1249     pBuf[1] = (PRUint8)(dh_Ys.len);
1250         pBuf += 2;
1251     memcpy(pBuf, dh_Ys.data, dh_Ys.len);
1252         pBuf += dh_Ys.len;
1253     PORT_Assert((unsigned int)(pBuf - hashBuf) == bufLen);
1254
1255     rv = ssl3_ComputeCommonKeyHash(hashAlg, hashBuf, bufLen, hashes,
1256                                    bypassPKCS11);
1257
1258     PRINT_BUF(95, (NULL, "DHkey hash: ", hashBuf, bufLen));
1259     if (hashAlg == SEC_OID_UNKNOWN) {
1260         PRINT_BUF(95, (NULL, "DHkey hash: MD5 result",
1261                   hashes->u.s.md5, MD5_LENGTH));
1262         PRINT_BUF(95, (NULL, "DHkey hash: SHA1 result",
1263                   hashes->u.s.sha, SHA1_LENGTH));
1264     } else {
1265         PRINT_BUF(95, (NULL, "DHkey hash: result",
1266                   hashes->u.raw, hashes->len));
1267     }
1268
1269     if (hashBuf != buf && hashBuf != NULL)
1270         PORT_Free(hashBuf);
1271     return rv;
1272 }
1273
1274 static void
1275 ssl3_BumpSequenceNumber(SSL3SequenceNumber *num)
1276 {
1277     num->low++;
1278     if (num->low == 0)
1279         num->high++;
1280 }
1281
1282 /* Called twice, only from ssl3_DestroyCipherSpec (immediately below). */
1283 static void
1284 ssl3_CleanupKeyMaterial(ssl3KeyMaterial *mat)
1285 {
1286     if (mat->write_key != NULL) {
1287         PK11_FreeSymKey(mat->write_key);
1288         mat->write_key = NULL;
1289     }
1290     if (mat->write_mac_key != NULL) {
1291         PK11_FreeSymKey(mat->write_mac_key);
1292         mat->write_mac_key = NULL;
1293     }
1294     if (mat->write_mac_context != NULL) {
1295         PK11_DestroyContext(mat->write_mac_context, PR_TRUE);
1296         mat->write_mac_context = NULL;
1297     }
1298 }
1299
1300 /* Called from ssl3_SendChangeCipherSpecs() and 
1301 **             ssl3_HandleChangeCipherSpecs()
1302 **             ssl3_DestroySSL3Info
1303 ** Caller must hold SpecWriteLock.
1304 */
1305 void
1306 ssl3_DestroyCipherSpec(ssl3CipherSpec *spec, PRBool freeSrvName)
1307 {
1308     PRBool freeit = (PRBool)(!spec->bypassCiphers);
1309 /*  PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); Don't have ss! */
1310     if (spec->destroy) {
1311         spec->destroy(spec->encodeContext, freeit);
1312         spec->destroy(spec->decodeContext, freeit);
1313         spec->encodeContext = NULL; /* paranoia */
1314         spec->decodeContext = NULL;
1315     }
1316     if (spec->destroyCompressContext && spec->compressContext) {
1317         spec->destroyCompressContext(spec->compressContext, 1);
1318         spec->compressContext = NULL;
1319     }
1320     if (spec->destroyDecompressContext && spec->decompressContext) {
1321         spec->destroyDecompressContext(spec->decompressContext, 1);
1322         spec->decompressContext = NULL;
1323     }
1324     if (freeSrvName && spec->srvVirtName.data) {
1325         SECITEM_FreeItem(&spec->srvVirtName, PR_FALSE);
1326     }
1327     if (spec->master_secret != NULL) {
1328         PK11_FreeSymKey(spec->master_secret);
1329         spec->master_secret = NULL;
1330     }
1331     spec->msItem.data = NULL;
1332     spec->msItem.len  = 0;
1333     ssl3_CleanupKeyMaterial(&spec->client);
1334     ssl3_CleanupKeyMaterial(&spec->server);
1335     spec->bypassCiphers = PR_FALSE;
1336     spec->destroy=NULL;
1337     spec->destroyCompressContext = NULL;
1338     spec->destroyDecompressContext = NULL;
1339 }
1340
1341 /* Fill in the pending cipher spec with info from the selected ciphersuite.
1342 ** This is as much initialization as we can do without having key material.
1343 ** Called from ssl3_HandleServerHello(), ssl3_SendServerHello()
1344 ** Caller must hold the ssl3 handshake lock.
1345 ** Acquires & releases SpecWriteLock.
1346 */
1347 static SECStatus
1348 ssl3_SetupPendingCipherSpec(sslSocket *ss)
1349 {
1350     ssl3CipherSpec *          pwSpec;
1351     ssl3CipherSpec *          cwSpec;
1352     ssl3CipherSuite           suite     = ss->ssl3.hs.cipher_suite;
1353     SSL3MACAlgorithm          mac;
1354     SSL3BulkCipher            cipher;
1355     SSL3KeyExchangeAlgorithm  kea;
1356     const ssl3CipherSuiteDef *suite_def;
1357     PRBool                    isTLS;
1358
1359     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
1360
1361     ssl_GetSpecWriteLock(ss);  /*******************************/
1362
1363     pwSpec = ss->ssl3.pwSpec;
1364     PORT_Assert(pwSpec == ss->ssl3.prSpec);
1365
1366     /* This hack provides maximal interoperability with SSL 3 servers. */
1367     cwSpec = ss->ssl3.cwSpec;
1368     if (cwSpec->mac_def->mac == mac_null) {
1369         /* SSL records are not being MACed. */
1370         cwSpec->version = ss->version;
1371     }
1372
1373     pwSpec->version  = ss->version;
1374     isTLS  = (PRBool)(pwSpec->version > SSL_LIBRARY_VERSION_3_0);
1375
1376     SSL_TRC(3, ("%d: SSL3[%d]: Set XXX Pending Cipher Suite to 0x%04x",
1377                 SSL_GETPID(), ss->fd, suite));
1378
1379     suite_def = ssl_LookupCipherSuiteDef(suite);
1380     if (suite_def == NULL) {
1381         ssl_ReleaseSpecWriteLock(ss);
1382         return SECFailure;      /* error code set by ssl_LookupCipherSuiteDef */
1383     }
1384
1385     if (IS_DTLS(ss)) {
1386         /* Double-check that we did not pick an RC4 suite */
1387         PORT_Assert((suite_def->bulk_cipher_alg != cipher_rc4) &&
1388                     (suite_def->bulk_cipher_alg != cipher_rc4_40) &&
1389                     (suite_def->bulk_cipher_alg != cipher_rc4_56));
1390     }
1391
1392     cipher = suite_def->bulk_cipher_alg;
1393     kea    = suite_def->key_exchange_alg;
1394     mac    = suite_def->mac_alg;
1395     if (mac <= ssl_mac_sha && mac != ssl_mac_null && isTLS)
1396         mac += 2;
1397
1398     ss->ssl3.hs.suite_def = suite_def;
1399     ss->ssl3.hs.kea_def   = &kea_defs[kea];
1400     PORT_Assert(ss->ssl3.hs.kea_def->kea == kea);
1401
1402     pwSpec->cipher_def   = &bulk_cipher_defs[cipher];
1403     PORT_Assert(pwSpec->cipher_def->cipher == cipher);
1404
1405     pwSpec->mac_def = &mac_defs[mac];
1406     PORT_Assert(pwSpec->mac_def->mac == mac);
1407
1408     ss->sec.keyBits       = pwSpec->cipher_def->key_size        * BPB;
1409     ss->sec.secretKeyBits = pwSpec->cipher_def->secret_key_size * BPB;
1410     ss->sec.cipherType    = cipher;
1411
1412     pwSpec->encodeContext = NULL;
1413     pwSpec->decodeContext = NULL;
1414
1415     pwSpec->mac_size = pwSpec->mac_def->mac_size;
1416
1417     pwSpec->compression_method = ss->ssl3.hs.compression;
1418     pwSpec->compressContext = NULL;
1419     pwSpec->decompressContext = NULL;
1420
1421     ssl_ReleaseSpecWriteLock(ss);  /*******************************/
1422     return SECSuccess;
1423 }
1424
1425 #ifdef NSS_ENABLE_ZLIB
1426 #define SSL3_DEFLATE_CONTEXT_SIZE sizeof(z_stream)
1427
1428 static SECStatus
1429 ssl3_MapZlibError(int zlib_error)
1430 {
1431     switch (zlib_error) {
1432     case Z_OK:
1433         return SECSuccess;
1434     default:
1435         return SECFailure;
1436     }
1437 }
1438
1439 static SECStatus
1440 ssl3_DeflateInit(void *void_context)
1441 {
1442     z_stream *context = void_context;
1443     context->zalloc = NULL;
1444     context->zfree = NULL;
1445     context->opaque = NULL;
1446
1447     return ssl3_MapZlibError(deflateInit(context, Z_DEFAULT_COMPRESSION));
1448 }
1449
1450 static SECStatus
1451 ssl3_InflateInit(void *void_context)
1452 {
1453     z_stream *context = void_context;
1454     context->zalloc = NULL;
1455     context->zfree = NULL;
1456     context->opaque = NULL;
1457     context->next_in = NULL;
1458     context->avail_in = 0;
1459
1460     return ssl3_MapZlibError(inflateInit(context));
1461 }
1462
1463 static SECStatus
1464 ssl3_DeflateCompress(void *void_context, unsigned char *out, int *out_len,
1465                      int maxout, const unsigned char *in, int inlen)
1466 {
1467     z_stream *context = void_context;
1468
1469     if (!inlen) {
1470         *out_len = 0;
1471         return SECSuccess;
1472     }
1473
1474     context->next_in = (unsigned char*) in;
1475     context->avail_in = inlen;
1476     context->next_out = out;
1477     context->avail_out = maxout;
1478     if (deflate(context, Z_SYNC_FLUSH) != Z_OK) {
1479         return SECFailure;
1480     }
1481     if (context->avail_out == 0) {
1482         /* We ran out of space! */
1483         SSL_TRC(3, ("%d: SSL3[%d] Ran out of buffer while compressing",
1484                     SSL_GETPID()));
1485         return SECFailure;
1486     }
1487
1488     *out_len = maxout - context->avail_out;
1489     return SECSuccess;
1490 }
1491
1492 static SECStatus
1493 ssl3_DeflateDecompress(void *void_context, unsigned char *out, int *out_len,
1494                        int maxout, const unsigned char *in, int inlen)
1495 {
1496     z_stream *context = void_context;
1497
1498     if (!inlen) {
1499         *out_len = 0;
1500         return SECSuccess;
1501     }
1502
1503     context->next_in = (unsigned char*) in;
1504     context->avail_in = inlen;
1505     context->next_out = out;
1506     context->avail_out = maxout;
1507     if (inflate(context, Z_SYNC_FLUSH) != Z_OK) {
1508         PORT_SetError(SSL_ERROR_DECOMPRESSION_FAILURE);
1509         return SECFailure;
1510     }
1511
1512     *out_len = maxout - context->avail_out;
1513     return SECSuccess;
1514 }
1515
1516 static SECStatus
1517 ssl3_DestroyCompressContext(void *void_context, PRBool unused)
1518 {
1519     deflateEnd(void_context);
1520     PORT_Free(void_context);
1521     return SECSuccess;
1522 }
1523
1524 static SECStatus
1525 ssl3_DestroyDecompressContext(void *void_context, PRBool unused)
1526 {
1527     inflateEnd(void_context);
1528     PORT_Free(void_context);
1529     return SECSuccess;
1530 }
1531
1532 #endif /* NSS_ENABLE_ZLIB */
1533
1534 /* Initialize the compression functions and contexts for the given
1535  * CipherSpec.  */
1536 static SECStatus
1537 ssl3_InitCompressionContext(ssl3CipherSpec *pwSpec)
1538 {
1539     /* Setup the compression functions */
1540     switch (pwSpec->compression_method) {
1541     case ssl_compression_null:
1542         pwSpec->compressor = NULL;
1543         pwSpec->decompressor = NULL;
1544         pwSpec->compressContext = NULL;
1545         pwSpec->decompressContext = NULL;
1546         pwSpec->destroyCompressContext = NULL;
1547         pwSpec->destroyDecompressContext = NULL;
1548         break;
1549 #ifdef NSS_ENABLE_ZLIB
1550     case ssl_compression_deflate:
1551         pwSpec->compressor = ssl3_DeflateCompress;
1552         pwSpec->decompressor = ssl3_DeflateDecompress;
1553         pwSpec->compressContext = PORT_Alloc(SSL3_DEFLATE_CONTEXT_SIZE);
1554         pwSpec->decompressContext = PORT_Alloc(SSL3_DEFLATE_CONTEXT_SIZE);
1555         pwSpec->destroyCompressContext = ssl3_DestroyCompressContext;
1556         pwSpec->destroyDecompressContext = ssl3_DestroyDecompressContext;
1557         ssl3_DeflateInit(pwSpec->compressContext);
1558         ssl3_InflateInit(pwSpec->decompressContext);
1559         break;
1560 #endif /* NSS_ENABLE_ZLIB */
1561     default:
1562         PORT_Assert(0);
1563         PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1564         return SECFailure;
1565     }
1566
1567     return SECSuccess;
1568 }
1569
1570 #ifndef NO_PKCS11_BYPASS
1571 /* Initialize encryption contexts for pending spec.
1572  * MAC contexts are set up when computing the mac, not here.
1573  * Master Secret already is derived in spec->msItem
1574  * Caller holds Spec write lock.
1575  */
1576 static SECStatus
1577 ssl3_InitPendingContextsBypass(sslSocket *ss)
1578 {
1579       ssl3CipherSpec  *  pwSpec;
1580       const ssl3BulkCipherDef *cipher_def;
1581       void *             serverContext = NULL;
1582       void *             clientContext = NULL;
1583       BLapiInitContextFunc initFn = (BLapiInitContextFunc)NULL;
1584       int                mode     = 0;
1585       unsigned int       optArg1  = 0;
1586       unsigned int       optArg2  = 0;
1587       PRBool             server_encrypts = ss->sec.isServer;
1588       SSLCipherAlgorithm calg;
1589       SECStatus          rv;
1590
1591     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
1592     PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
1593     PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
1594
1595     pwSpec        = ss->ssl3.pwSpec;
1596     cipher_def    = pwSpec->cipher_def;
1597
1598     calg = cipher_def->calg;
1599
1600     if (calg == calg_aes_gcm) {
1601         pwSpec->encode = NULL;
1602         pwSpec->decode = NULL;
1603         pwSpec->destroy = NULL;
1604         pwSpec->encodeContext = NULL;
1605         pwSpec->decodeContext = NULL;
1606         pwSpec->aead = ssl3_AESGCMBypass;
1607         ssl3_InitCompressionContext(pwSpec);
1608         return SECSuccess;
1609     }
1610
1611     serverContext = pwSpec->server.cipher_context;
1612     clientContext = pwSpec->client.cipher_context;
1613
1614     switch (calg) {
1615     case ssl_calg_null:
1616         pwSpec->encode  = Null_Cipher;
1617         pwSpec->decode  = Null_Cipher;
1618         pwSpec->destroy = NULL;
1619         goto success;
1620
1621     case ssl_calg_rc4:
1622         initFn = (BLapiInitContextFunc)RC4_InitContext;
1623         pwSpec->encode  = (SSLCipher) RC4_Encrypt;
1624         pwSpec->decode  = (SSLCipher) RC4_Decrypt;
1625         pwSpec->destroy = (SSLDestroy) RC4_DestroyContext;
1626         break;
1627     case ssl_calg_rc2:
1628         initFn = (BLapiInitContextFunc)RC2_InitContext;
1629         mode = NSS_RC2_CBC;
1630         optArg1 = cipher_def->key_size;
1631         pwSpec->encode  = (SSLCipher) RC2_Encrypt;
1632         pwSpec->decode  = (SSLCipher) RC2_Decrypt;
1633         pwSpec->destroy = (SSLDestroy) RC2_DestroyContext;
1634         break;
1635     case ssl_calg_des:
1636         initFn = (BLapiInitContextFunc)DES_InitContext;
1637         mode = NSS_DES_CBC;
1638         optArg1 = server_encrypts;
1639         pwSpec->encode  = (SSLCipher) DES_Encrypt;
1640         pwSpec->decode  = (SSLCipher) DES_Decrypt;
1641         pwSpec->destroy = (SSLDestroy) DES_DestroyContext;
1642         break;
1643     case ssl_calg_3des:
1644         initFn = (BLapiInitContextFunc)DES_InitContext;
1645         mode = NSS_DES_EDE3_CBC;
1646         optArg1 = server_encrypts;
1647         pwSpec->encode  = (SSLCipher) DES_Encrypt;
1648         pwSpec->decode  = (SSLCipher) DES_Decrypt;
1649         pwSpec->destroy = (SSLDestroy) DES_DestroyContext;
1650         break;
1651     case ssl_calg_aes:
1652         initFn = (BLapiInitContextFunc)AES_InitContext;
1653         mode = NSS_AES_CBC;
1654         optArg1 = server_encrypts;
1655         optArg2 = AES_BLOCK_SIZE;
1656         pwSpec->encode  = (SSLCipher) AES_Encrypt;
1657         pwSpec->decode  = (SSLCipher) AES_Decrypt;
1658         pwSpec->destroy = (SSLDestroy) AES_DestroyContext;
1659         break;
1660
1661     case ssl_calg_camellia:
1662         initFn = (BLapiInitContextFunc)Camellia_InitContext;
1663         mode = NSS_CAMELLIA_CBC;
1664         optArg1 = server_encrypts;
1665         optArg2 = CAMELLIA_BLOCK_SIZE;
1666         pwSpec->encode  = (SSLCipher) Camellia_Encrypt;
1667         pwSpec->decode  = (SSLCipher) Camellia_Decrypt;
1668         pwSpec->destroy = (SSLDestroy) Camellia_DestroyContext;
1669         break;
1670
1671     case ssl_calg_seed:
1672         initFn = (BLapiInitContextFunc)SEED_InitContext;
1673         mode = NSS_SEED_CBC;
1674         optArg1 = server_encrypts;
1675         optArg2 = SEED_BLOCK_SIZE;
1676         pwSpec->encode  = (SSLCipher) SEED_Encrypt;
1677         pwSpec->decode  = (SSLCipher) SEED_Decrypt;
1678         pwSpec->destroy = (SSLDestroy) SEED_DestroyContext;
1679         break;
1680
1681     case ssl_calg_idea:
1682     case ssl_calg_fortezza :
1683     default:
1684         PORT_Assert(0);
1685         PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1686         goto bail_out;
1687     }
1688     rv = (*initFn)(serverContext,
1689                    pwSpec->server.write_key_item.data,
1690                    pwSpec->server.write_key_item.len,
1691                    pwSpec->server.write_iv_item.data,
1692                    mode, optArg1, optArg2);
1693     if (rv != SECSuccess) {
1694         PORT_Assert(0);
1695         PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1696         goto bail_out;
1697     }
1698
1699     switch (calg) {
1700     case ssl_calg_des:
1701     case ssl_calg_3des:
1702     case ssl_calg_aes:
1703     case ssl_calg_camellia:
1704     case ssl_calg_seed:
1705         /* For block ciphers, if the server is encrypting, then the client
1706         * is decrypting, and vice versa.
1707         */
1708         optArg1 = !optArg1;
1709         break;
1710     /* kill warnings. */
1711     case ssl_calg_null:
1712     case ssl_calg_rc4:
1713     case ssl_calg_rc2:
1714     case ssl_calg_idea:
1715     case ssl_calg_fortezza:
1716         break;
1717     }
1718
1719     rv = (*initFn)(clientContext,
1720                    pwSpec->client.write_key_item.data,
1721                    pwSpec->client.write_key_item.len,
1722                    pwSpec->client.write_iv_item.data,
1723                    mode, optArg1, optArg2);
1724     if (rv != SECSuccess) {
1725         PORT_Assert(0);
1726         PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1727         goto bail_out;
1728     }
1729
1730     pwSpec->encodeContext = (ss->sec.isServer) ? serverContext : clientContext;
1731     pwSpec->decodeContext = (ss->sec.isServer) ? clientContext : serverContext;
1732
1733     ssl3_InitCompressionContext(pwSpec);
1734
1735 success:
1736     return SECSuccess;
1737
1738 bail_out:
1739     return SECFailure;
1740 }
1741 #endif
1742
1743 /* This function should probably be moved to pk11wrap and be named 
1744  * PK11_ParamFromIVAndEffectiveKeyBits
1745  */
1746 static SECItem *
1747 ssl3_ParamFromIV(CK_MECHANISM_TYPE mtype, SECItem *iv, CK_ULONG ulEffectiveBits)
1748 {
1749     SECItem * param = PK11_ParamFromIV(mtype, iv);
1750     if (param && param->data  && param->len >= sizeof(CK_RC2_PARAMS)) {
1751         switch (mtype) {
1752         case CKM_RC2_KEY_GEN:
1753         case CKM_RC2_ECB:
1754         case CKM_RC2_CBC:
1755         case CKM_RC2_MAC:
1756         case CKM_RC2_MAC_GENERAL:
1757         case CKM_RC2_CBC_PAD:
1758             *(CK_RC2_PARAMS *)param->data = ulEffectiveBits;
1759         default: break;
1760         }
1761     }
1762     return param;
1763 }
1764
1765 /* ssl3_BuildRecordPseudoHeader writes the SSL/TLS pseudo-header (the data
1766  * which is included in the MAC or AEAD additional data) to |out| and returns
1767  * its length. See https://tools.ietf.org/html/rfc5246#section-6.2.3.3 for the
1768  * definition of the AEAD additional data.
1769  *
1770  * TLS pseudo-header includes the record's version field, SSL's doesn't. Which
1771  * pseudo-header defintiion to use should be decided based on the version of
1772  * the protocol that was negotiated when the cipher spec became current, NOT
1773  * based on the version value in the record itself, and the decision is passed
1774  * to this function as the |includesVersion| argument. But, the |version|
1775  * argument should be the record's version value.
1776  */
1777 static unsigned int
1778 ssl3_BuildRecordPseudoHeader(unsigned char *out,
1779                              SSL3SequenceNumber seq_num,
1780                              SSL3ContentType type,
1781                              PRBool includesVersion,
1782                              SSL3ProtocolVersion version,
1783                              PRBool isDTLS,
1784                              int length)
1785 {
1786     out[0] = (unsigned char)(seq_num.high >> 24);
1787     out[1] = (unsigned char)(seq_num.high >> 16);
1788     out[2] = (unsigned char)(seq_num.high >>  8);
1789     out[3] = (unsigned char)(seq_num.high >>  0);
1790     out[4] = (unsigned char)(seq_num.low  >> 24);
1791     out[5] = (unsigned char)(seq_num.low  >> 16);
1792     out[6] = (unsigned char)(seq_num.low  >>  8);
1793     out[7] = (unsigned char)(seq_num.low  >>  0);
1794     out[8] = type;
1795
1796     /* SSL3 MAC doesn't include the record's version field. */
1797     if (!includesVersion) {
1798         out[9]  = MSB(length);
1799         out[10] = LSB(length);
1800         return 11;
1801     }
1802
1803     /* TLS MAC and AEAD additional data include version. */
1804     if (isDTLS) {
1805         SSL3ProtocolVersion dtls_version;
1806
1807         dtls_version = dtls_TLSVersionToDTLSVersion(version);
1808         out[9]  = MSB(dtls_version);
1809         out[10] = LSB(dtls_version);
1810     } else {
1811         out[9]  = MSB(version);
1812         out[10] = LSB(version);
1813     }
1814     out[11] = MSB(length);
1815     out[12] = LSB(length);
1816     return 13;
1817 }
1818
1819 static SECStatus
1820 ssl3_AESGCM(ssl3KeyMaterial *keys,
1821             PRBool doDecrypt,
1822             unsigned char *out,
1823             int *outlen,
1824             int maxout,
1825             const unsigned char *in,
1826             int inlen,
1827             const unsigned char *additionalData,
1828             int additionalDataLen)
1829 {
1830     SECItem            param;
1831     SECStatus          rv = SECFailure;
1832     unsigned char      nonce[12];
1833     unsigned int       uOutLen;
1834     CK_GCM_PARAMS      gcmParams;
1835
1836     static const int   tagSize = 16;
1837     static const int   explicitNonceLen = 8;
1838
1839     /* See https://tools.ietf.org/html/rfc5288#section-3 for details of how the
1840      * nonce is formed. */
1841     memcpy(nonce, keys->write_iv, 4);
1842     if (doDecrypt) {
1843         memcpy(nonce + 4, in, explicitNonceLen);
1844         in += explicitNonceLen;
1845         inlen -= explicitNonceLen;
1846         *outlen = 0;
1847     } else {
1848         if (maxout < explicitNonceLen) {
1849             PORT_SetError(SEC_ERROR_INPUT_LEN);
1850             return SECFailure;
1851         }
1852         /* Use the 64-bit sequence number as the explicit nonce. */
1853         memcpy(nonce + 4, additionalData, explicitNonceLen);
1854         memcpy(out, additionalData, explicitNonceLen);
1855         out += explicitNonceLen;
1856         maxout -= explicitNonceLen;
1857         *outlen = explicitNonceLen;
1858     }
1859
1860     param.type = siBuffer;
1861     param.data = (unsigned char *) &gcmParams;
1862     param.len = sizeof(gcmParams);
1863     gcmParams.pIv = nonce;
1864     gcmParams.ulIvLen = sizeof(nonce);
1865     gcmParams.pAAD = (unsigned char *)additionalData;  /* const cast */
1866     gcmParams.ulAADLen = additionalDataLen;
1867     gcmParams.ulTagBits = tagSize * 8;
1868
1869     if (doDecrypt) {
1870         rv = PK11_Decrypt(keys->write_key, CKM_AES_GCM, &param, out, &uOutLen,
1871                           maxout, in, inlen);
1872     } else {
1873         rv = PK11_Encrypt(keys->write_key, CKM_AES_GCM, &param, out, &uOutLen,
1874                           maxout, in, inlen);
1875     }
1876     *outlen += (int) uOutLen;
1877
1878     return rv;
1879 }
1880
1881 #ifndef NO_PKCS11_BYPASS
1882 static SECStatus
1883 ssl3_AESGCMBypass(ssl3KeyMaterial *keys,
1884                   PRBool doDecrypt,
1885                   unsigned char *out,
1886                   int *outlen,
1887                   int maxout,
1888                   const unsigned char *in,
1889                   int inlen,
1890                   const unsigned char *additionalData,
1891                   int additionalDataLen)
1892 {
1893     SECStatus          rv = SECFailure;
1894     unsigned char      nonce[12];
1895     unsigned int       uOutLen;
1896     AESContext        *cx;
1897     CK_GCM_PARAMS      gcmParams;
1898
1899     static const int   tagSize = 16;
1900     static const int   explicitNonceLen = 8;
1901
1902     /* See https://tools.ietf.org/html/rfc5288#section-3 for details of how the
1903      * nonce is formed. */
1904     PORT_Assert(keys->write_iv_item.len == 4);
1905     if (keys->write_iv_item.len != 4) {
1906         PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1907         return SECFailure;
1908     }
1909     memcpy(nonce, keys->write_iv_item.data, 4);
1910     if (doDecrypt) {
1911         memcpy(nonce + 4, in, explicitNonceLen);
1912         in += explicitNonceLen;
1913         inlen -= explicitNonceLen;
1914         *outlen = 0;
1915     } else {
1916         if (maxout < explicitNonceLen) {
1917             PORT_SetError(SEC_ERROR_INPUT_LEN);
1918             return SECFailure;
1919         }
1920         /* Use the 64-bit sequence number as the explicit nonce. */
1921         memcpy(nonce + 4, additionalData, explicitNonceLen);
1922         memcpy(out, additionalData, explicitNonceLen);
1923         out += explicitNonceLen;
1924         maxout -= explicitNonceLen;
1925         *outlen = explicitNonceLen;
1926     }
1927
1928     gcmParams.pIv = nonce;
1929     gcmParams.ulIvLen = sizeof(nonce);
1930     gcmParams.pAAD = (unsigned char *)additionalData;  /* const cast */
1931     gcmParams.ulAADLen = additionalDataLen;
1932     gcmParams.ulTagBits = tagSize * 8;
1933
1934     cx = (AESContext *)keys->cipher_context;
1935     rv = AES_InitContext(cx, keys->write_key_item.data,
1936                          keys->write_key_item.len,
1937                          (unsigned char *)&gcmParams, NSS_AES_GCM, !doDecrypt,
1938                          AES_BLOCK_SIZE);
1939     if (rv != SECSuccess) {
1940         return rv;
1941     }
1942     if (doDecrypt) {
1943         rv = AES_Decrypt(cx, out, &uOutLen, maxout, in, inlen);
1944     } else {
1945         rv = AES_Encrypt(cx, out, &uOutLen, maxout, in, inlen);
1946     }
1947     AES_DestroyContext(cx, PR_FALSE);
1948     *outlen += (int) uOutLen;
1949
1950     return rv;
1951 }
1952 #endif
1953
1954 /* Initialize encryption and MAC contexts for pending spec.
1955  * Master Secret already is derived.
1956  * Caller holds Spec write lock.
1957  */
1958 static SECStatus
1959 ssl3_InitPendingContextsPKCS11(sslSocket *ss)
1960 {
1961       ssl3CipherSpec  *  pwSpec;
1962       const ssl3BulkCipherDef *cipher_def;
1963       PK11Context *      serverContext = NULL;
1964       PK11Context *      clientContext = NULL;
1965       SECItem *          param;
1966       CK_MECHANISM_TYPE  mechanism;
1967       CK_MECHANISM_TYPE  mac_mech;
1968       CK_ULONG           macLength;
1969       CK_ULONG           effKeyBits;
1970       SECItem            iv;
1971       SECItem            mac_param;
1972       SSLCipherAlgorithm calg;
1973
1974     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
1975     PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
1976     PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
1977
1978     pwSpec        = ss->ssl3.pwSpec;
1979     cipher_def    = pwSpec->cipher_def;
1980     macLength     = pwSpec->mac_size;
1981     calg          = cipher_def->calg;
1982     PORT_Assert(alg2Mech[calg].calg == calg);
1983
1984     pwSpec->client.write_mac_context = NULL;
1985     pwSpec->server.write_mac_context = NULL;
1986
1987     if (calg == calg_aes_gcm) {
1988         pwSpec->encode = NULL;
1989         pwSpec->decode = NULL;
1990         pwSpec->destroy = NULL;
1991         pwSpec->encodeContext = NULL;
1992         pwSpec->decodeContext = NULL;
1993         pwSpec->aead = ssl3_AESGCM;
1994         return SECSuccess;
1995     }
1996
1997     /* 
1998     ** Now setup the MAC contexts, 
1999     **   crypto contexts are setup below.
2000     */
2001
2002     mac_mech       = pwSpec->mac_def->mmech;
2003     mac_param.data = (unsigned char *)&macLength;
2004     mac_param.len  = sizeof(macLength);
2005     mac_param.type = 0;
2006
2007     pwSpec->client.write_mac_context = PK11_CreateContextBySymKey(
2008             mac_mech, CKA_SIGN, pwSpec->client.write_mac_key, &mac_param);
2009     if (pwSpec->client.write_mac_context == NULL)  {
2010         ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
2011         goto fail;
2012     }
2013     pwSpec->server.write_mac_context = PK11_CreateContextBySymKey(
2014             mac_mech, CKA_SIGN, pwSpec->server.write_mac_key, &mac_param);
2015     if (pwSpec->server.write_mac_context == NULL) {
2016         ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
2017         goto fail;
2018     }
2019
2020     /* 
2021     ** Now setup the crypto contexts.
2022     */
2023
2024     if (calg == calg_null) {
2025         pwSpec->encode  = Null_Cipher;
2026         pwSpec->decode  = Null_Cipher;
2027         pwSpec->destroy = NULL;
2028         return SECSuccess;
2029     }
2030     mechanism = alg2Mech[calg].cmech;
2031     effKeyBits = cipher_def->key_size * BPB;
2032
2033     /*
2034      * build the server context
2035      */
2036     iv.data = pwSpec->server.write_iv;
2037     iv.len  = cipher_def->iv_size;
2038     param = ssl3_ParamFromIV(mechanism, &iv, effKeyBits);
2039     if (param == NULL) {
2040         ssl_MapLowLevelError(SSL_ERROR_IV_PARAM_FAILURE);
2041         goto fail;
2042     }
2043     serverContext = PK11_CreateContextBySymKey(mechanism,
2044                                 (ss->sec.isServer ? CKA_ENCRYPT : CKA_DECRYPT),
2045                                 pwSpec->server.write_key, param);
2046     iv.data = PK11_IVFromParam(mechanism, param, (int *)&iv.len);
2047     if (iv.data)
2048         PORT_Memcpy(pwSpec->server.write_iv, iv.data, iv.len);
2049     SECITEM_FreeItem(param, PR_TRUE);
2050     if (serverContext == NULL) {
2051         ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
2052         goto fail;
2053     }
2054
2055     /*
2056      * build the client context
2057      */
2058     iv.data = pwSpec->client.write_iv;
2059     iv.len  = cipher_def->iv_size;
2060
2061     param = ssl3_ParamFromIV(mechanism, &iv, effKeyBits);
2062     if (param == NULL) {
2063         ssl_MapLowLevelError(SSL_ERROR_IV_PARAM_FAILURE);
2064         goto fail;
2065     }
2066     clientContext = PK11_CreateContextBySymKey(mechanism,
2067                                 (ss->sec.isServer ? CKA_DECRYPT : CKA_ENCRYPT),
2068                                 pwSpec->client.write_key, param);
2069     iv.data = PK11_IVFromParam(mechanism, param, (int *)&iv.len);
2070     if (iv.data)
2071         PORT_Memcpy(pwSpec->client.write_iv, iv.data, iv.len);
2072     SECITEM_FreeItem(param,PR_TRUE);
2073     if (clientContext == NULL) {
2074         ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
2075         goto fail;
2076     }
2077     pwSpec->encode  = (SSLCipher) PK11_CipherOp;
2078     pwSpec->decode  = (SSLCipher) PK11_CipherOp;
2079     pwSpec->destroy = (SSLDestroy) PK11_DestroyContext;
2080
2081     pwSpec->encodeContext = (ss->sec.isServer) ? serverContext : clientContext;
2082     pwSpec->decodeContext = (ss->sec.isServer) ? clientContext : serverContext;
2083
2084     serverContext = NULL;
2085     clientContext = NULL;
2086
2087     ssl3_InitCompressionContext(pwSpec);
2088
2089     return SECSuccess;
2090
2091 fail:
2092     if (serverContext != NULL) PK11_DestroyContext(serverContext, PR_TRUE);
2093     if (clientContext != NULL) PK11_DestroyContext(clientContext, PR_TRUE);
2094     if (pwSpec->client.write_mac_context != NULL) {
2095         PK11_DestroyContext(pwSpec->client.write_mac_context,PR_TRUE);
2096         pwSpec->client.write_mac_context = NULL;
2097     }
2098     if (pwSpec->server.write_mac_context != NULL) {
2099         PK11_DestroyContext(pwSpec->server.write_mac_context,PR_TRUE);
2100         pwSpec->server.write_mac_context = NULL;
2101     }
2102
2103     return SECFailure;
2104 }
2105
2106 /* Complete the initialization of all keys, ciphers, MACs and their contexts
2107  * for the pending Cipher Spec.
2108  * Called from: ssl3_SendClientKeyExchange      (for Full handshake)
2109  *              ssl3_HandleRSAClientKeyExchange (for Full handshake)
2110  *              ssl3_HandleServerHello          (for session restart)
2111  *              ssl3_HandleClientHello          (for session restart)
2112  * Sets error code, but caller probably should override to disambiguate.
2113  * NULL pms means re-use old master_secret.
2114  *
2115  * This code is common to the bypass and PKCS11 execution paths.
2116  * For the bypass case,  pms is NULL.
2117  */
2118 SECStatus
2119 ssl3_InitPendingCipherSpec(sslSocket *ss, PK11SymKey *pms)
2120 {
2121     ssl3CipherSpec  *  pwSpec;
2122     ssl3CipherSpec  *  cwSpec;
2123     SECStatus          rv;
2124
2125     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
2126
2127     ssl_GetSpecWriteLock(ss);   /**************************************/
2128
2129     PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
2130
2131     pwSpec        = ss->ssl3.pwSpec;
2132     cwSpec        = ss->ssl3.cwSpec;
2133
2134     if (pms || (!pwSpec->msItem.len && !pwSpec->master_secret)) {
2135         rv = ssl3_DeriveMasterSecret(ss, pms);
2136         if (rv != SECSuccess) {
2137             goto done;  /* err code set by ssl3_DeriveMasterSecret */
2138         }
2139     }
2140 #ifndef NO_PKCS11_BYPASS
2141     if (ss->opt.bypassPKCS11 && pwSpec->msItem.len && pwSpec->msItem.data) {
2142         /* Double Bypass succeeded in extracting the master_secret */
2143         const ssl3KEADef * kea_def = ss->ssl3.hs.kea_def;
2144         PRBool             isTLS   = (PRBool)(kea_def->tls_keygen ||
2145                                 (pwSpec->version > SSL_LIBRARY_VERSION_3_0));
2146         pwSpec->bypassCiphers = PR_TRUE;
2147         rv = ssl3_KeyAndMacDeriveBypass( pwSpec, 
2148                              (const unsigned char *)&ss->ssl3.hs.client_random,
2149                              (const unsigned char *)&ss->ssl3.hs.server_random,
2150                              isTLS, 
2151                              (PRBool)(kea_def->is_limited));
2152         if (rv == SECSuccess) {
2153             rv = ssl3_InitPendingContextsBypass(ss);
2154         }
2155     } else
2156 #endif
2157     if (pwSpec->master_secret) {
2158         rv = ssl3_DeriveConnectionKeysPKCS11(ss);
2159         if (rv == SECSuccess) {
2160             rv = ssl3_InitPendingContextsPKCS11(ss);
2161         }
2162     } else {
2163         PORT_Assert(pwSpec->master_secret);
2164         PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2165         rv = SECFailure;
2166     }
2167     if (rv != SECSuccess) {
2168         goto done;
2169     }
2170
2171     /* Generic behaviors -- common to all crypto methods */
2172     if (!IS_DTLS(ss)) {
2173         pwSpec->read_seq_num.high = pwSpec->write_seq_num.high = 0;
2174     } else {
2175         if (cwSpec->epoch == PR_UINT16_MAX) {
2176             /* The problem here is that we have rehandshaked too many
2177              * times (you are not allowed to wrap the epoch). The
2178              * spec says you should be discarding the connection
2179              * and start over, so not much we can do here. */
2180             PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2181             rv = SECFailure;
2182             goto done;
2183         }
2184         /* The sequence number has the high 16 bits as the epoch. */
2185         pwSpec->epoch = cwSpec->epoch + 1;
2186         pwSpec->read_seq_num.high = pwSpec->write_seq_num.high =
2187             pwSpec->epoch << 16;
2188
2189         dtls_InitRecvdRecords(&pwSpec->recvdRecords);
2190     }
2191     pwSpec->read_seq_num.low = pwSpec->write_seq_num.low = 0;
2192
2193 done:
2194     ssl_ReleaseSpecWriteLock(ss);       /******************************/
2195     if (rv != SECSuccess)
2196         ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
2197     return rv;
2198 }
2199
2200 /*
2201  * 60 bytes is 3 times the maximum length MAC size that is supported.
2202  */
2203 static const unsigned char mac_pad_1 [60] = {
2204     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
2205     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
2206     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
2207     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
2208     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
2209     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
2210     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
2211     0x36, 0x36, 0x36, 0x36
2212 };
2213 static const unsigned char mac_pad_2 [60] = {
2214     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
2215     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
2216     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
2217     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
2218     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
2219     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
2220     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
2221     0x5c, 0x5c, 0x5c, 0x5c
2222 };
2223
2224 /* Called from: ssl3_SendRecord()
2225 ** Caller must already hold the SpecReadLock. (wish we could assert that!)
2226 */
2227 static SECStatus
2228 ssl3_ComputeRecordMAC(
2229     ssl3CipherSpec *   spec,
2230     PRBool             useServerMacKey,
2231     const unsigned char *header,
2232     unsigned int       headerLen,
2233     const SSL3Opaque * input,
2234     int                inputLength,
2235     unsigned char *    outbuf,
2236     unsigned int *     outLength)
2237 {
2238     const ssl3MACDef * mac_def;
2239     SECStatus          rv;
2240
2241     PRINT_BUF(95, (NULL, "frag hash1: header", header, headerLen));
2242     PRINT_BUF(95, (NULL, "frag hash1: input", input, inputLength));
2243
2244     mac_def = spec->mac_def;
2245     if (mac_def->mac == mac_null) {
2246         *outLength = 0;
2247         return SECSuccess;
2248     }
2249 #ifndef NO_PKCS11_BYPASS
2250     if (spec->bypassCiphers) {
2251         /* bypass version */
2252         const SECHashObject *hashObj = NULL;
2253         unsigned int       pad_bytes = 0;
2254         PRUint64           write_mac_context[MAX_MAC_CONTEXT_LLONGS];
2255
2256         switch (mac_def->mac) {
2257         case ssl_mac_null:
2258             *outLength = 0;
2259             return SECSuccess;
2260         case ssl_mac_md5:
2261             pad_bytes = 48;
2262             hashObj = HASH_GetRawHashObject(HASH_AlgMD5);
2263             break;
2264         case ssl_mac_sha:
2265             pad_bytes = 40;
2266             hashObj = HASH_GetRawHashObject(HASH_AlgSHA1);
2267             break;
2268         case ssl_hmac_md5: /* used with TLS */
2269             hashObj = HASH_GetRawHashObject(HASH_AlgMD5);
2270             break;
2271         case ssl_hmac_sha: /* used with TLS */
2272             hashObj = HASH_GetRawHashObject(HASH_AlgSHA1);
2273             break;
2274         case ssl_hmac_sha256: /* used with TLS */
2275             hashObj = HASH_GetRawHashObject(HASH_AlgSHA256);
2276             break;
2277         default:
2278             break;
2279         }
2280         if (!hashObj) {
2281             PORT_Assert(0);
2282             PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2283             return SECFailure;
2284         }
2285
2286         if (spec->version <= SSL_LIBRARY_VERSION_3_0) {
2287             unsigned int tempLen;
2288             unsigned char temp[MAX_MAC_LENGTH];
2289
2290             /* compute "inner" part of SSL3 MAC */
2291             hashObj->begin(write_mac_context);
2292             if (useServerMacKey)
2293                 hashObj->update(write_mac_context, 
2294                                 spec->server.write_mac_key_item.data,
2295                                 spec->server.write_mac_key_item.len);
2296             else
2297                 hashObj->update(write_mac_context, 
2298                                 spec->client.write_mac_key_item.data,
2299                                 spec->client.write_mac_key_item.len);
2300             hashObj->update(write_mac_context, mac_pad_1, pad_bytes);
2301             hashObj->update(write_mac_context, header, headerLen);
2302             hashObj->update(write_mac_context, input, inputLength);
2303             hashObj->end(write_mac_context,    temp, &tempLen, sizeof temp);
2304
2305             /* compute "outer" part of SSL3 MAC */
2306             hashObj->begin(write_mac_context);
2307             if (useServerMacKey)
2308                 hashObj->update(write_mac_context, 
2309                                 spec->server.write_mac_key_item.data,
2310                                 spec->server.write_mac_key_item.len);
2311             else
2312                 hashObj->update(write_mac_context, 
2313                                 spec->client.write_mac_key_item.data,
2314                                 spec->client.write_mac_key_item.len);
2315             hashObj->update(write_mac_context, mac_pad_2, pad_bytes);
2316             hashObj->update(write_mac_context, temp, tempLen);
2317             hashObj->end(write_mac_context, outbuf, outLength, spec->mac_size);
2318             rv = SECSuccess;
2319         } else { /* is TLS */
2320 #define cx ((HMACContext *)write_mac_context)
2321             if (useServerMacKey) {
2322                 rv = HMAC_Init(cx, hashObj, 
2323                                spec->server.write_mac_key_item.data,
2324                                spec->server.write_mac_key_item.len, PR_FALSE);
2325             } else {
2326                 rv = HMAC_Init(cx, hashObj, 
2327                                spec->client.write_mac_key_item.data,
2328                                spec->client.write_mac_key_item.len, PR_FALSE);
2329             }
2330             if (rv == SECSuccess) {
2331                 HMAC_Begin(cx);
2332                 HMAC_Update(cx, header, headerLen);
2333                 HMAC_Update(cx, input, inputLength);
2334                 rv = HMAC_Finish(cx, outbuf, outLength, spec->mac_size);
2335                 HMAC_Destroy(cx, PR_FALSE);
2336             }
2337 #undef cx
2338         }
2339     } else
2340 #endif
2341     {
2342         PK11Context *mac_context = 
2343             (useServerMacKey ? spec->server.write_mac_context
2344                              : spec->client.write_mac_context);
2345         rv  = PK11_DigestBegin(mac_context);
2346         rv |= PK11_DigestOp(mac_context, header, headerLen);
2347         rv |= PK11_DigestOp(mac_context, input, inputLength);
2348         rv |= PK11_DigestFinal(mac_context, outbuf, outLength, spec->mac_size);
2349     }
2350
2351     PORT_Assert(rv != SECSuccess || *outLength == (unsigned)spec->mac_size);
2352
2353     PRINT_BUF(95, (NULL, "frag hash2: result", outbuf, *outLength));
2354
2355     if (rv != SECSuccess) {
2356         rv = SECFailure;
2357         ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
2358     }
2359     return rv;
2360 }
2361
2362 /* Called from: ssl3_HandleRecord()
2363  * Caller must already hold the SpecReadLock. (wish we could assert that!)
2364  *
2365  * On entry:
2366  *   originalLen >= inputLen >= MAC size
2367 */
2368 static SECStatus
2369 ssl3_ComputeRecordMACConstantTime(
2370     ssl3CipherSpec *   spec,
2371     PRBool             useServerMacKey,
2372     const unsigned char *header,
2373     unsigned int       headerLen,
2374     const SSL3Opaque * input,
2375     int                inputLen,
2376     int                originalLen,
2377     unsigned char *    outbuf,
2378     unsigned int *     outLen)
2379 {
2380     CK_MECHANISM_TYPE            macType;
2381     CK_NSS_MAC_CONSTANT_TIME_PARAMS params;
2382     SECItem                      param, inputItem, outputItem;
2383     SECStatus                    rv;
2384     PK11SymKey *                 key;
2385
2386     PORT_Assert(inputLen >= spec->mac_size);
2387     PORT_Assert(originalLen >= inputLen);
2388
2389     if (spec->bypassCiphers) {
2390         /* This function doesn't support PKCS#11 bypass. We fallback on the
2391          * non-constant time version. */
2392         goto fallback;
2393     }
2394
2395     if (spec->mac_def->mac == mac_null) {
2396         *outLen = 0;
2397         return SECSuccess;
2398     }
2399
2400     macType = CKM_NSS_HMAC_CONSTANT_TIME;
2401     if (spec->version <= SSL_LIBRARY_VERSION_3_0) {
2402         macType = CKM_NSS_SSL3_MAC_CONSTANT_TIME;
2403     }
2404
2405     params.macAlg = spec->mac_def->mmech;
2406     params.ulBodyTotalLen = originalLen;
2407     params.pHeader = (unsigned char *) header;  /* const cast */
2408     params.ulHeaderLen = headerLen;
2409
2410     param.data = (unsigned char*) &params;
2411     param.len = sizeof(params);
2412     param.type = 0;
2413
2414     inputItem.data = (unsigned char *) input;
2415     inputItem.len = inputLen;
2416     inputItem.type = 0;
2417
2418     outputItem.data = outbuf;
2419     outputItem.len = *outLen;
2420     outputItem.type = 0;
2421
2422     key = spec->server.write_mac_key;
2423     if (!useServerMacKey) {
2424         key = spec->client.write_mac_key;
2425     }
2426
2427     rv = PK11_SignWithSymKey(key, macType, &param, &outputItem, &inputItem);
2428     if (rv != SECSuccess) {
2429         if (PORT_GetError() == SEC_ERROR_INVALID_ALGORITHM) {
2430             goto fallback;
2431         }
2432
2433         *outLen = 0;
2434         rv = SECFailure;
2435         ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
2436         return rv;
2437     }
2438
2439     PORT_Assert(outputItem.len == (unsigned)spec->mac_size);
2440     *outLen = outputItem.len;
2441
2442     return rv;
2443
2444 fallback:
2445     /* ssl3_ComputeRecordMAC expects the MAC to have been removed from the
2446      * length already. */
2447     inputLen -= spec->mac_size;
2448     return ssl3_ComputeRecordMAC(spec, useServerMacKey, header, headerLen,
2449                                  input, inputLen, outbuf, outLen);
2450 }
2451
2452 static PRBool
2453 ssl3_ClientAuthTokenPresent(sslSessionID *sid) {
2454     PK11SlotInfo *slot = NULL;
2455     PRBool isPresent = PR_TRUE;
2456
2457     /* we only care if we are doing client auth */
2458     if (!sid || !sid->u.ssl3.clAuthValid) {
2459         return PR_TRUE;
2460     }
2461
2462     /* get the slot */
2463     slot = SECMOD_LookupSlot(sid->u.ssl3.clAuthModuleID,
2464                              sid->u.ssl3.clAuthSlotID);
2465     if (slot == NULL ||
2466         !PK11_IsPresent(slot) ||
2467         sid->u.ssl3.clAuthSeries     != PK11_GetSlotSeries(slot) ||
2468         sid->u.ssl3.clAuthSlotID     != PK11_GetSlotID(slot)     ||
2469         sid->u.ssl3.clAuthModuleID   != PK11_GetModuleID(slot)   ||
2470         (PK11_NeedLogin(slot) && !PK11_IsLoggedIn(slot, NULL))) {
2471         isPresent = PR_FALSE;
2472     } 
2473     if (slot) {
2474         PK11_FreeSlot(slot);
2475     }
2476     return isPresent;
2477 }
2478
2479 /* Caller must hold the spec read lock. */
2480 SECStatus
2481 ssl3_CompressMACEncryptRecord(ssl3CipherSpec *   cwSpec,
2482                               PRBool             isServer,
2483                               PRBool             isDTLS,
2484                               PRBool             capRecordVersion,
2485                               SSL3ContentType    type,
2486                               const SSL3Opaque * pIn,
2487                               PRUint32           contentLen,
2488                               sslBuffer *        wrBuf)
2489 {
2490     const ssl3BulkCipherDef * cipher_def;
2491     SECStatus                 rv;
2492     PRUint32                  macLen = 0;
2493     PRUint32                  fragLen;
2494     PRUint32  p1Len, p2Len, oddLen = 0;
2495     PRUint16                  headerLen;
2496     int                       ivLen = 0;
2497     int                       cipherBytes = 0;
2498     unsigned char             pseudoHeader[13];
2499     unsigned int              pseudoHeaderLen;
2500
2501     cipher_def = cwSpec->cipher_def;
2502     headerLen = isDTLS ? DTLS_RECORD_HEADER_LENGTH : SSL3_RECORD_HEADER_LENGTH;
2503
2504     if (cipher_def->type == type_block &&
2505         cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
2506         /* Prepend the per-record explicit IV using technique 2b from
2507          * RFC 4346 section 6.2.3.2: The IV is a cryptographically
2508          * strong random number XORed with the CBC residue from the previous
2509          * record.
2510          */
2511         ivLen = cipher_def->iv_size;
2512         if (ivLen > wrBuf->space - headerLen) {
2513             PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2514             return SECFailure;
2515         }
2516         rv = PK11_GenerateRandom(wrBuf->buf + headerLen, ivLen);
2517         if (rv != SECSuccess) {
2518             ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
2519             return rv;
2520         }
2521         rv = cwSpec->encode( cwSpec->encodeContext, 
2522             wrBuf->buf + headerLen,
2523             &cipherBytes,                       /* output and actual outLen */
2524             ivLen,                              /* max outlen */
2525             wrBuf->buf + headerLen,
2526             ivLen);                             /* input and inputLen*/
2527         if (rv != SECSuccess || cipherBytes != ivLen) {
2528             PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
2529             return SECFailure;
2530         }
2531     }
2532
2533     if (cwSpec->compressor) {
2534         int outlen;
2535         rv = cwSpec->compressor(
2536             cwSpec->compressContext,
2537             wrBuf->buf + headerLen + ivLen, &outlen,
2538             wrBuf->space - headerLen - ivLen, pIn, contentLen);
2539         if (rv != SECSuccess)
2540             return rv;
2541         pIn = wrBuf->buf + headerLen + ivLen;
2542         contentLen = outlen;
2543     }
2544
2545     pseudoHeaderLen = ssl3_BuildRecordPseudoHeader(
2546         pseudoHeader, cwSpec->write_seq_num, type,
2547         cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_0, cwSpec->version,
2548         isDTLS, contentLen);
2549     PORT_Assert(pseudoHeaderLen <= sizeof(pseudoHeader));
2550     if (cipher_def->type == type_aead) {
2551         const int nonceLen = cipher_def->explicit_nonce_size;
2552         const int tagLen = cipher_def->tag_size;
2553
2554         if (headerLen + nonceLen + contentLen + tagLen > wrBuf->space) {
2555             PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2556             return SECFailure;
2557         }
2558
2559         cipherBytes = contentLen;
2560         rv = cwSpec->aead(
2561                 isServer ? &cwSpec->server : &cwSpec->client,
2562                 PR_FALSE,                                   /* do encrypt */
2563                 wrBuf->buf + headerLen,                     /* output  */
2564                 &cipherBytes,                               /* out len */
2565                 wrBuf->space - headerLen,                   /* max out */
2566                 pIn, contentLen,                            /* input   */
2567                 pseudoHeader, pseudoHeaderLen);
2568         if (rv != SECSuccess) {
2569             PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
2570             return SECFailure;
2571         }
2572     } else {
2573         /*
2574          * Add the MAC
2575          */
2576         rv = ssl3_ComputeRecordMAC(cwSpec, isServer,
2577             pseudoHeader, pseudoHeaderLen, pIn, contentLen,
2578             wrBuf->buf + headerLen + ivLen + contentLen, &macLen);
2579         if (rv != SECSuccess) {
2580             ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
2581             return SECFailure;
2582         }
2583         p1Len   = contentLen;
2584         p2Len   = macLen;
2585         fragLen = contentLen + macLen;  /* needs to be encrypted */
2586         PORT_Assert(fragLen <= MAX_FRAGMENT_LENGTH + 1024);
2587
2588         /*
2589          * Pad the text (if we're doing a block cipher)
2590          * then Encrypt it
2591          */
2592         if (cipher_def->type == type_block) {
2593             unsigned char * pBuf;
2594             int             padding_length;
2595             int             i;
2596
2597             oddLen = contentLen % cipher_def->block_size;
2598             /* Assume blockSize is a power of two */
2599             padding_length = cipher_def->block_size - 1 -
2600                             ((fragLen) & (cipher_def->block_size - 1));
2601             fragLen += padding_length + 1;
2602             PORT_Assert((fragLen % cipher_def->block_size) == 0);
2603
2604             /* Pad according to TLS rules (also acceptable to SSL3). */
2605             pBuf = &wrBuf->buf[headerLen + ivLen + fragLen - 1];
2606             for (i = padding_length + 1; i > 0; --i) {
2607                 *pBuf-- = padding_length;
2608             }
2609             /* now, if contentLen is not a multiple of block size, fix it */
2610             p2Len = fragLen - p1Len;
2611         }
2612         if (p1Len < 256) {
2613             oddLen = p1Len;
2614             p1Len = 0;
2615         } else {
2616             p1Len -= oddLen;
2617         }
2618         if (oddLen) {
2619             p2Len += oddLen;
2620             PORT_Assert( (cipher_def->block_size < 2) || \
2621                          (p2Len % cipher_def->block_size) == 0);
2622             memmove(wrBuf->buf + headerLen + ivLen + p1Len, pIn + p1Len,
2623                     oddLen);
2624         }
2625         if (p1Len > 0) {
2626             int cipherBytesPart1 = -1;
2627             rv = cwSpec->encode( cwSpec->encodeContext, 
2628                 wrBuf->buf + headerLen + ivLen,         /* output */
2629                 &cipherBytesPart1,                      /* actual outlen */
2630                 p1Len,                                  /* max outlen */
2631                 pIn, p1Len);                      /* input, and inputlen */
2632             PORT_Assert(rv == SECSuccess && cipherBytesPart1 == (int) p1Len);
2633             if (rv != SECSuccess || cipherBytesPart1 != (int) p1Len) {
2634                 PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
2635                 return SECFailure;
2636             }
2637             cipherBytes += cipherBytesPart1;
2638         }
2639         if (p2Len > 0) {
2640             int cipherBytesPart2 = -1;
2641             rv = cwSpec->encode( cwSpec->encodeContext, 
2642                 wrBuf->buf + headerLen + ivLen + p1Len,
2643                 &cipherBytesPart2,          /* output and actual outLen */
2644                 p2Len,                             /* max outlen */
2645                 wrBuf->buf + headerLen + ivLen + p1Len,
2646                 p2Len);                            /* input and inputLen*/
2647             PORT_Assert(rv == SECSuccess && cipherBytesPart2 == (int) p2Len);
2648             if (rv != SECSuccess || cipherBytesPart2 != (int) p2Len) {
2649                 PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
2650                 return SECFailure;
2651             }
2652             cipherBytes += cipherBytesPart2;
2653         }
2654     }
2655
2656     PORT_Assert(cipherBytes <= MAX_FRAGMENT_LENGTH + 1024);
2657
2658     wrBuf->len    = cipherBytes + headerLen;
2659     wrBuf->buf[0] = type;
2660     if (isDTLS) {
2661         SSL3ProtocolVersion version;
2662
2663         version = dtls_TLSVersionToDTLSVersion(cwSpec->version);
2664         wrBuf->buf[1] = MSB(version);
2665         wrBuf->buf[2] = LSB(version);
2666         wrBuf->buf[3] = (unsigned char)(cwSpec->write_seq_num.high >> 24);
2667         wrBuf->buf[4] = (unsigned char)(cwSpec->write_seq_num.high >> 16);
2668         wrBuf->buf[5] = (unsigned char)(cwSpec->write_seq_num.high >>  8);
2669         wrBuf->buf[6] = (unsigned char)(cwSpec->write_seq_num.high >>  0);
2670         wrBuf->buf[7] = (unsigned char)(cwSpec->write_seq_num.low  >> 24);
2671         wrBuf->buf[8] = (unsigned char)(cwSpec->write_seq_num.low  >> 16);
2672         wrBuf->buf[9] = (unsigned char)(cwSpec->write_seq_num.low  >>  8);
2673         wrBuf->buf[10] = (unsigned char)(cwSpec->write_seq_num.low >>  0);
2674         wrBuf->buf[11] = MSB(cipherBytes);
2675         wrBuf->buf[12] = LSB(cipherBytes);
2676     } else {
2677         SSL3ProtocolVersion version = cwSpec->version;
2678
2679         if (capRecordVersion) {
2680             version = PR_MIN(SSL_LIBRARY_VERSION_TLS_1_0, version);
2681         }
2682         wrBuf->buf[1] = MSB(version);
2683         wrBuf->buf[2] = LSB(version);
2684         wrBuf->buf[3] = MSB(cipherBytes);
2685         wrBuf->buf[4] = LSB(cipherBytes);
2686     }
2687
2688     ssl3_BumpSequenceNumber(&cwSpec->write_seq_num);
2689
2690     return SECSuccess;
2691 }
2692
2693 /* Process the plain text before sending it.
2694  * Returns the number of bytes of plaintext that were successfully sent
2695  *      plus the number of bytes of plaintext that were copied into the
2696  *      output (write) buffer.
2697  * Returns SECFailure on a hard IO error, memory error, or crypto error.
2698  * Does NOT return SECWouldBlock.
2699  *
2700  * Notes on the use of the private ssl flags:
2701  * (no private SSL flags)
2702  *    Attempt to make and send SSL records for all plaintext
2703  *    If non-blocking and a send gets WOULD_BLOCK,
2704  *    or if the pending (ciphertext) buffer is not empty,
2705  *    then buffer remaining bytes of ciphertext into pending buf,
2706  *    and continue to do that for all succssive records until all
2707  *    bytes are used.
2708  * ssl_SEND_FLAG_FORCE_INTO_BUFFER
2709  *    As above, except this suppresses all write attempts, and forces
2710  *    all ciphertext into the pending ciphertext buffer.
2711  * ssl_SEND_FLAG_USE_EPOCH (for DTLS)
2712  *    Forces the use of the provided epoch
2713  * ssl_SEND_FLAG_CAP_RECORD_VERSION
2714  *    Caps the record layer version number of TLS ClientHello to { 3, 1 }
2715  *    (TLS 1.0). Some TLS 1.0 servers (which seem to use F5 BIG-IP) ignore 
2716  *    ClientHello.client_version and use the record layer version number
2717  *    (TLSPlaintext.version) instead when negotiating protocol versions. In
2718  *    addition, if the record layer version number of ClientHello is { 3, 2 }
2719  *    (TLS 1.1) or higher, these servers reset the TCP connections. Set this
2720  *    flag to work around such servers.
2721  */
2722 PRInt32
2723 ssl3_SendRecord(   sslSocket *        ss,
2724                    DTLSEpoch          epoch, /* DTLS only */
2725                    SSL3ContentType    type,
2726                    const SSL3Opaque * pIn,   /* input buffer */
2727                    PRInt32            nIn,   /* bytes of input */
2728                    PRInt32            flags)
2729 {
2730     sslBuffer      *          wrBuf       = &ss->sec.writeBuf;
2731     SECStatus                 rv;
2732     PRInt32                   totalSent   = 0;
2733     PRBool                    capRecordVersion;
2734
2735     SSL_TRC(3, ("%d: SSL3[%d] SendRecord type: %s nIn=%d",
2736                 SSL_GETPID(), ss->fd, ssl3_DecodeContentType(type),
2737                 nIn));
2738     PRINT_BUF(3, (ss, "Send record (plain text)", pIn, nIn));
2739
2740     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
2741
2742     capRecordVersion = ((flags & ssl_SEND_FLAG_CAP_RECORD_VERSION) != 0);
2743
2744     if (capRecordVersion) {
2745         /* ssl_SEND_FLAG_CAP_RECORD_VERSION can only be used with the
2746          * TLS initial ClientHello. */
2747         PORT_Assert(!IS_DTLS(ss));
2748         PORT_Assert(!ss->firstHsDone);
2749         PORT_Assert(type == content_handshake);
2750         PORT_Assert(ss->ssl3.hs.ws == wait_server_hello);
2751     }
2752
2753     if (ss->ssl3.initialized == PR_FALSE) {
2754         /* This can happen on a server if the very first incoming record
2755         ** looks like a defective ssl3 record (e.g. too long), and we're
2756         ** trying to send an alert.
2757         */
2758         PR_ASSERT(type == content_alert);
2759         rv = ssl3_InitState(ss);
2760         if (rv != SECSuccess) {
2761             return SECFailure;  /* ssl3_InitState has set the error code. */
2762         }
2763     }
2764
2765     /* check for Token Presence */
2766     if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) {
2767         PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
2768         return SECFailure;
2769     }
2770
2771     while (nIn > 0) {
2772         PRUint32  contentLen = PR_MIN(nIn, MAX_FRAGMENT_LENGTH);
2773         unsigned int spaceNeeded;
2774         unsigned int numRecords;
2775
2776         ssl_GetSpecReadLock(ss);    /********************************/
2777
2778         if (nIn > 1 && ss->opt.cbcRandomIV &&
2779             ss->ssl3.cwSpec->version < SSL_LIBRARY_VERSION_TLS_1_1 &&
2780             type == content_application_data &&
2781             ss->ssl3.cwSpec->cipher_def->type == type_block /* CBC mode */) {
2782             /* We will split the first byte of the record into its own record,
2783              * as explained in the documentation for SSL_CBC_RANDOM_IV in ssl.h
2784              */
2785             numRecords = 2;
2786         } else {
2787             numRecords = 1;
2788         }
2789
2790         spaceNeeded = contentLen + (numRecords * SSL3_BUFFER_FUDGE);
2791         if (ss->ssl3.cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1 &&
2792             ss->ssl3.cwSpec->cipher_def->type == type_block) {
2793             spaceNeeded += ss->ssl3.cwSpec->cipher_def->iv_size;
2794         }
2795         if (spaceNeeded > wrBuf->space) {
2796             rv = sslBuffer_Grow(wrBuf, spaceNeeded);
2797             if (rv != SECSuccess) {
2798                 SSL_DBG(("%d: SSL3[%d]: SendRecord, tried to get %d bytes",
2799                          SSL_GETPID(), ss->fd, spaceNeeded));
2800                 goto spec_locked_loser; /* sslBuffer_Grow set error code. */
2801             }
2802         }
2803
2804         if (numRecords == 2) {
2805             sslBuffer secondRecord;
2806
2807             rv = ssl3_CompressMACEncryptRecord(ss->ssl3.cwSpec,
2808                                                ss->sec.isServer, IS_DTLS(ss),
2809                                                capRecordVersion, type, pIn,
2810                                                1, wrBuf);
2811             if (rv != SECSuccess)
2812                 goto spec_locked_loser;
2813
2814             PRINT_BUF(50, (ss, "send (encrypted) record data [1/2]:",
2815                            wrBuf->buf, wrBuf->len));
2816
2817             secondRecord.buf = wrBuf->buf + wrBuf->len;
2818             secondRecord.len = 0;
2819             secondRecord.space = wrBuf->space - wrBuf->len;
2820
2821             rv = ssl3_CompressMACEncryptRecord(ss->ssl3.cwSpec,
2822                                                ss->sec.isServer, IS_DTLS(ss),
2823                                                capRecordVersion, type,
2824                                                pIn + 1, contentLen - 1,
2825                                                &secondRecord);
2826             if (rv == SECSuccess) {
2827                 PRINT_BUF(50, (ss, "send (encrypted) record data [2/2]:",
2828                                secondRecord.buf, secondRecord.len));
2829                 wrBuf->len += secondRecord.len;
2830             }
2831         } else {
2832             if (!IS_DTLS(ss)) {
2833                 rv = ssl3_CompressMACEncryptRecord(ss->ssl3.cwSpec,
2834                                                    ss->sec.isServer,
2835                                                    IS_DTLS(ss),
2836                                                    capRecordVersion,
2837                                                    type, pIn,
2838                                                    contentLen, wrBuf);
2839             } else {
2840                 rv = dtls_CompressMACEncryptRecord(ss, epoch,
2841                                                    !!(flags & ssl_SEND_FLAG_USE_EPOCH),
2842                                                    type, pIn,
2843                                                    contentLen, wrBuf);
2844             }
2845
2846             if (rv == SECSuccess) {
2847                 PRINT_BUF(50, (ss, "send (encrypted) record data:",
2848                                wrBuf->buf, wrBuf->len));
2849             }
2850         }
2851
2852 spec_locked_loser:
2853         ssl_ReleaseSpecReadLock(ss); /************************************/
2854
2855         if (rv != SECSuccess)
2856             return SECFailure;
2857
2858         pIn += contentLen;
2859         nIn -= contentLen;
2860         PORT_Assert( nIn >= 0 );
2861
2862         /* If there's still some previously saved ciphertext,
2863          * or the caller doesn't want us to send the data yet,
2864          * then add all our new ciphertext to the amount previously saved.
2865          */
2866         if ((ss->pendingBuf.len > 0) ||
2867             (flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) {
2868
2869             rv = ssl_SaveWriteData(ss, wrBuf->buf, wrBuf->len);
2870             if (rv != SECSuccess) {
2871                 /* presumably a memory error, SEC_ERROR_NO_MEMORY */
2872                 return SECFailure;
2873             }
2874             wrBuf->len = 0;     /* All cipher text is saved away. */
2875
2876             if (!(flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) {
2877                 PRInt32   sent;
2878                 ss->handshakeBegun = 1;
2879                 sent = ssl_SendSavedWriteData(ss);
2880                 if (sent < 0 && PR_GetError() != PR_WOULD_BLOCK_ERROR) {
2881                     ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE);
2882                     return SECFailure;
2883                 }
2884                 if (ss->pendingBuf.len) {
2885                     flags |= ssl_SEND_FLAG_FORCE_INTO_BUFFER;
2886                 }
2887             }
2888         } else if (wrBuf->len > 0) {
2889             PRInt32   sent;
2890             ss->handshakeBegun = 1;
2891             sent = ssl_DefSend(ss, wrBuf->buf, wrBuf->len,
2892                                flags & ~ssl_SEND_FLAG_MASK);
2893             if (sent < 0) {
2894                 if (PR_GetError() != PR_WOULD_BLOCK_ERROR) {
2895                     ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE);
2896                     return SECFailure;
2897                 }
2898                 /* we got PR_WOULD_BLOCK_ERROR, which means none was sent. */
2899                 sent = 0;
2900             }
2901             wrBuf->len -= sent;
2902             if (wrBuf->len) {
2903                 if (IS_DTLS(ss)) {
2904                     /* DTLS just says no in this case. No buffering */
2905                     PR_SetError(PR_WOULD_BLOCK_ERROR, 0);
2906                     return SECFailure;
2907                 }
2908                 /* now take all the remaining unsent new ciphertext and 
2909                  * append it to the buffer of previously unsent ciphertext.
2910                  */
2911                 rv = ssl_SaveWriteData(ss, wrBuf->buf + sent, wrBuf->len);
2912                 if (rv != SECSuccess) {
2913                     /* presumably a memory error, SEC_ERROR_NO_MEMORY */
2914                     return SECFailure;
2915                 }
2916             }
2917         }
2918         totalSent += contentLen;
2919     }
2920     return totalSent;
2921 }
2922
2923 #define SSL3_PENDING_HIGH_WATER 1024
2924
2925 /* Attempt to send the content of "in" in an SSL application_data record.
2926  * Returns "len" or SECFailure,   never SECWouldBlock, nor SECSuccess.
2927  */
2928 int
2929 ssl3_SendApplicationData(sslSocket *ss, const unsigned char *in,
2930                          PRInt32 len, PRInt32 flags)
2931 {
2932     PRInt32   totalSent = 0;
2933     PRInt32   discarded = 0;
2934
2935     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
2936     /* These flags for internal use only */
2937     PORT_Assert(!(flags & (ssl_SEND_FLAG_USE_EPOCH |
2938                            ssl_SEND_FLAG_NO_RETRANSMIT)));
2939     if (len < 0 || !in) {
2940         PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
2941         return SECFailure;
2942     }
2943
2944     if (ss->pendingBuf.len > SSL3_PENDING_HIGH_WATER &&
2945         !ssl_SocketIsBlocking(ss)) {
2946         PORT_Assert(!ssl_SocketIsBlocking(ss));
2947         PORT_SetError(PR_WOULD_BLOCK_ERROR);
2948         return SECFailure;
2949     }
2950
2951     if (ss->appDataBuffered && len) {
2952         PORT_Assert (in[0] == (unsigned char)(ss->appDataBuffered));
2953         if (in[0] != (unsigned char)(ss->appDataBuffered)) {
2954             PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
2955             return SECFailure;
2956         }
2957         in++;
2958         len--;
2959         discarded = 1;
2960     }
2961     while (len > totalSent) {
2962         PRInt32   sent, toSend;
2963
2964         if (totalSent > 0) {
2965             /*
2966              * The thread yield is intended to give the reader thread a
2967              * chance to get some cycles while the writer thread is in
2968              * the middle of a large application data write.  (See
2969              * Bugzilla bug 127740, comment #1.)
2970              */
2971             ssl_ReleaseXmitBufLock(ss);
2972             PR_Sleep(PR_INTERVAL_NO_WAIT);      /* PR_Yield(); */
2973             ssl_GetXmitBufLock(ss);
2974         }
2975         toSend = PR_MIN(len - totalSent, MAX_FRAGMENT_LENGTH);
2976         /*
2977          * Note that the 0 epoch is OK because flags will never require 
2978          * its use, as guaranteed by the PORT_Assert above.
2979          */
2980         sent = ssl3_SendRecord(ss, 0, content_application_data,
2981                                in + totalSent, toSend, flags);
2982         if (sent < 0) {
2983             if (totalSent > 0 && PR_GetError() == PR_WOULD_BLOCK_ERROR) {
2984                 PORT_Assert(ss->lastWriteBlocked);
2985                 break;
2986             }
2987             return SECFailure; /* error code set by ssl3_SendRecord */
2988         }
2989         totalSent += sent;
2990         if (ss->pendingBuf.len) {
2991             /* must be a non-blocking socket */
2992             PORT_Assert(!ssl_SocketIsBlocking(ss));
2993             PORT_Assert(ss->lastWriteBlocked);
2994             break;      
2995         }
2996     }
2997     if (ss->pendingBuf.len) {
2998         /* Must be non-blocking. */
2999         PORT_Assert(!ssl_SocketIsBlocking(ss));
3000         if (totalSent > 0) {
3001             ss->appDataBuffered = 0x100 | in[totalSent - 1];
3002         }
3003
3004         totalSent = totalSent + discarded - 1;
3005         if (totalSent <= 0) {
3006             PORT_SetError(PR_WOULD_BLOCK_ERROR);
3007             totalSent = SECFailure;
3008         }
3009         return totalSent;
3010     } 
3011     ss->appDataBuffered = 0;
3012     return totalSent + discarded;
3013 }
3014
3015 /* Attempt to send buffered handshake messages.
3016  * This function returns SECSuccess or SECFailure, never SECWouldBlock.
3017  * Always set sendBuf.len to 0, even when returning SECFailure.
3018  *
3019  * Depending on whether we are doing DTLS or not, this either calls
3020  *
3021  * - ssl3_FlushHandshakeMessages if non-DTLS
3022  * - dtls_FlushHandshakeMessages if DTLS
3023  *
3024  * Called from SSL3_SendAlert(), ssl3_SendChangeCipherSpecs(),
3025  *             ssl3_AppendHandshake(), ssl3_SendClientHello(),
3026  *             ssl3_SendHelloRequest(), ssl3_SendServerHelloDone(),
3027  *             ssl3_SendFinished(),
3028  */
3029 static SECStatus
3030 ssl3_FlushHandshake(sslSocket *ss, PRInt32 flags)
3031 {
3032     if (IS_DTLS(ss)) {
3033         return dtls_FlushHandshakeMessages(ss, flags);
3034     } else {
3035         return ssl3_FlushHandshakeMessages(ss, flags);
3036     }
3037 }
3038
3039 /* Attempt to send the content of sendBuf buffer in an SSL handshake record.
3040  * This function returns SECSuccess or SECFailure, never SECWouldBlock.
3041  * Always set sendBuf.len to 0, even when returning SECFailure.
3042  *
3043  * Called from ssl3_FlushHandshake
3044  */
3045 static SECStatus
3046 ssl3_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags)
3047 {
3048     static const PRInt32 allowedFlags = ssl_SEND_FLAG_FORCE_INTO_BUFFER |
3049                                         ssl_SEND_FLAG_CAP_RECORD_VERSION;
3050     PRInt32 rv = SECSuccess;
3051
3052     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3053     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
3054
3055     if (!ss->sec.ci.sendBuf.buf || !ss->sec.ci.sendBuf.len)
3056         return rv;
3057
3058     /* only these flags are allowed */
3059     PORT_Assert(!(flags & ~allowedFlags));
3060     if ((flags & ~allowedFlags) != 0) {
3061         PORT_SetError(SEC_ERROR_INVALID_ARGS);
3062         rv = SECFailure;
3063     } else {
3064         rv = ssl3_SendRecord(ss, 0, content_handshake, ss->sec.ci.sendBuf.buf,
3065                              ss->sec.ci.sendBuf.len, flags);
3066     }
3067     if (rv < 0) { 
3068         int err = PORT_GetError();
3069         PORT_Assert(err != PR_WOULD_BLOCK_ERROR);
3070         if (err == PR_WOULD_BLOCK_ERROR) {
3071             PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
3072         }
3073     } else if (rv < ss->sec.ci.sendBuf.len) {
3074         /* short write should never happen */
3075         PORT_Assert(rv >= ss->sec.ci.sendBuf.len);
3076         PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
3077         rv = SECFailure;
3078     } else {
3079         rv = SECSuccess;
3080     }
3081
3082     /* Whether we succeeded or failed, toss the old handshake data. */
3083     ss->sec.ci.sendBuf.len = 0;
3084     return rv;
3085 }
3086
3087 /*
3088  * Called from ssl3_HandleAlert and from ssl3_HandleCertificate when
3089  * the remote client sends a negative response to our certificate request.
3090  * Returns SECFailure if the application has required client auth.
3091  *         SECSuccess otherwise.
3092  */
3093 static SECStatus
3094 ssl3_HandleNoCertificate(sslSocket *ss)
3095 {
3096     if (ss->sec.peerCert != NULL) {
3097         if (ss->sec.peerKey != NULL) {
3098             SECKEY_DestroyPublicKey(ss->sec.peerKey);
3099             ss->sec.peerKey = NULL;
3100         }
3101         CERT_DestroyCertificate(ss->sec.peerCert);
3102         ss->sec.peerCert = NULL;
3103     }
3104     ssl3_CleanupPeerCerts(ss);
3105
3106     /* If the server has required client-auth blindly but doesn't
3107      * actually look at the certificate it won't know that no
3108      * certificate was presented so we shutdown the socket to ensure
3109      * an error.  We only do this if we haven't already completed the
3110      * first handshake because if we're redoing the handshake we 
3111      * know the server is paying attention to the certificate.
3112      */
3113     if ((ss->opt.requireCertificate == SSL_REQUIRE_ALWAYS) ||
3114         (!ss->firstHsDone && 
3115          (ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE))) {
3116         PRFileDesc * lower;
3117
3118         if (ss->sec.uncache)
3119             ss->sec.uncache(ss->sec.ci.sid);
3120         SSL3_SendAlert(ss, alert_fatal, bad_certificate);
3121
3122         lower = ss->fd->lower;
3123 #ifdef _WIN32
3124         lower->methods->shutdown(lower, PR_SHUTDOWN_SEND);
3125 #else
3126         lower->methods->shutdown(lower, PR_SHUTDOWN_BOTH);
3127 #endif
3128         PORT_SetError(SSL_ERROR_NO_CERTIFICATE);
3129         return SECFailure;
3130     }
3131     return SECSuccess;
3132 }
3133
3134 /************************************************************************
3135  * Alerts
3136  */
3137
3138 /*
3139 ** Acquires both handshake and XmitBuf locks.
3140 ** Called from: ssl3_IllegalParameter   <-
3141 **              ssl3_HandshakeFailure   <-
3142 **              ssl3_HandleAlert        <- ssl3_HandleRecord.
3143 **              ssl3_HandleChangeCipherSpecs <- ssl3_HandleRecord
3144 **              ssl3_ConsumeHandshakeVariable <-
3145 **              ssl3_HandleHelloRequest <-
3146 **              ssl3_HandleServerHello  <-
3147 **              ssl3_HandleServerKeyExchange <-
3148 **              ssl3_HandleCertificateRequest <-
3149 **              ssl3_HandleServerHelloDone <-
3150 **              ssl3_HandleClientHello  <-
3151 **              ssl3_HandleV2ClientHello <-
3152 **              ssl3_HandleCertificateVerify <-
3153 **              ssl3_HandleClientKeyExchange <-
3154 **              ssl3_HandleCertificate  <-
3155 **              ssl3_HandleFinished     <-
3156 **              ssl3_HandleHandshakeMessage <-
3157 **              ssl3_HandleRecord       <-
3158 **
3159 */
3160 SECStatus
3161 SSL3_SendAlert(sslSocket *ss, SSL3AlertLevel level, SSL3AlertDescription desc)
3162 {
3163     PRUint8     bytes[2];
3164     SECStatus   rv;
3165
3166     SSL_TRC(3, ("%d: SSL3[%d]: send alert record, level=%d desc=%d",
3167                 SSL_GETPID(), ss->fd, level, desc));
3168
3169     bytes[0] = level;
3170     bytes[1] = desc;
3171
3172     ssl_GetSSL3HandshakeLock(ss);
3173     if (level == alert_fatal) {
3174         if (!ss->opt.noCache && ss->sec.ci.sid && ss->sec.uncache) {
3175             ss->sec.uncache(ss->sec.ci.sid);
3176         }
3177     }
3178     ssl_GetXmitBufLock(ss);
3179     rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
3180     if (rv == SECSuccess) {
3181         PRInt32 sent;
3182         sent = ssl3_SendRecord(ss, 0, content_alert, bytes, 2, 
3183                                desc == no_certificate 
3184                                ? ssl_SEND_FLAG_FORCE_INTO_BUFFER : 0);
3185         rv = (sent >= 0) ? SECSuccess : (SECStatus)sent;
3186     }
3187     ssl_ReleaseXmitBufLock(ss);
3188     ssl_ReleaseSSL3HandshakeLock(ss);
3189     return rv;  /* error set by ssl3_FlushHandshake or ssl3_SendRecord */
3190 }
3191
3192 /*
3193  * Send illegal_parameter alert.  Set generic error number.
3194  */
3195 static SECStatus
3196 ssl3_IllegalParameter(sslSocket *ss)
3197 {
3198     (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
3199     PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
3200                                    : SSL_ERROR_BAD_SERVER );
3201     return SECFailure;
3202 }
3203
3204 /*
3205  * Send handshake_Failure alert.  Set generic error number.
3206  */
3207 static SECStatus
3208 ssl3_HandshakeFailure(sslSocket *ss)
3209 {
3210     (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure);
3211     PORT_SetError( ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
3212                                     : SSL_ERROR_BAD_SERVER );
3213     return SECFailure;
3214 }
3215
3216 static void
3217 ssl3_SendAlertForCertError(sslSocket * ss, PRErrorCode errCode)
3218 {
3219     SSL3AlertDescription desc   = bad_certificate;
3220     PRBool isTLS = ss->version >= SSL_LIBRARY_VERSION_3_1_TLS;
3221
3222     switch (errCode) {
3223     case SEC_ERROR_LIBRARY_FAILURE:     desc = unsupported_certificate; break;
3224     case SEC_ERROR_EXPIRED_CERTIFICATE: desc = certificate_expired;     break;
3225     case SEC_ERROR_REVOKED_CERTIFICATE: desc = certificate_revoked;     break;
3226     case SEC_ERROR_INADEQUATE_KEY_USAGE:
3227     case SEC_ERROR_INADEQUATE_CERT_TYPE:
3228                                         desc = certificate_unknown;     break;
3229     case SEC_ERROR_UNTRUSTED_CERT:
3230                     desc = isTLS ? access_denied : certificate_unknown; break;
3231     case SEC_ERROR_UNKNOWN_ISSUER:      
3232     case SEC_ERROR_UNTRUSTED_ISSUER:    
3233                     desc = isTLS ? unknown_ca : certificate_unknown; break;
3234     case SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE:
3235                     desc = isTLS ? unknown_ca : certificate_expired; break;
3236
3237     case SEC_ERROR_CERT_NOT_IN_NAME_SPACE:
3238     case SEC_ERROR_PATH_LEN_CONSTRAINT_INVALID:
3239     case SEC_ERROR_CA_CERT_INVALID:
3240     case SEC_ERROR_BAD_SIGNATURE:
3241     default:                            desc = bad_certificate;     break;
3242     }
3243     SSL_DBG(("%d: SSL3[%d]: peer certificate is no good: error=%d",
3244              SSL_GETPID(), ss->fd, errCode));
3245
3246     (void) SSL3_SendAlert(ss, alert_fatal, desc);
3247 }
3248
3249
3250 /*
3251  * Send decode_error alert.  Set generic error number.
3252  */
3253 SECStatus
3254 ssl3_DecodeError(sslSocket *ss)
3255 {
3256     (void)SSL3_SendAlert(ss, alert_fatal, 
3257                   ss->version > SSL_LIBRARY_VERSION_3_0 ? decode_error 
3258                                                         : illegal_parameter);
3259     PORT_SetError( ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
3260                                     : SSL_ERROR_BAD_SERVER );
3261     return SECFailure;
3262 }
3263
3264 /* Called from ssl3_HandleRecord.
3265 ** Caller must hold both RecvBuf and Handshake locks.
3266 */
3267 static SECStatus
3268 ssl3_HandleAlert(sslSocket *ss, sslBuffer *buf)
3269 {
3270     SSL3AlertLevel       level;
3271     SSL3AlertDescription desc;
3272     int                  error;
3273
3274     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
3275     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
3276
3277     SSL_TRC(3, ("%d: SSL3[%d]: handle alert record", SSL_GETPID(), ss->fd));
3278
3279     if (buf->len != 2) {
3280         (void)ssl3_DecodeError(ss);
3281         PORT_SetError(SSL_ERROR_RX_MALFORMED_ALERT);
3282         return SECFailure;
3283     }
3284     level = (SSL3AlertLevel)buf->buf[0];
3285     desc  = (SSL3AlertDescription)buf->buf[1];
3286     buf->len = 0;
3287     SSL_TRC(5, ("%d: SSL3[%d] received alert, level = %d, description = %d",
3288         SSL_GETPID(), ss->fd, level, desc));
3289
3290     switch (desc) {
3291     case close_notify:          ss->recvdCloseNotify = 1;
3292                                 error = SSL_ERROR_CLOSE_NOTIFY_ALERT;     break;
3293     case unexpected_message:    error = SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT;
3294                                                                           break;
3295     case bad_record_mac:        error = SSL_ERROR_BAD_MAC_ALERT;          break;
3296     case decryption_failed_RESERVED:
3297                                 error = SSL_ERROR_DECRYPTION_FAILED_ALERT; 
3298                                                                           break;
3299     case record_overflow:       error = SSL_ERROR_RECORD_OVERFLOW_ALERT;  break;
3300     case decompression_failure: error = SSL_ERROR_DECOMPRESSION_FAILURE_ALERT;
3301                                                                           break;
3302     case handshake_failure:     error = SSL_ERROR_HANDSHAKE_FAILURE_ALERT;
3303                                                                           break;
3304     case no_certificate:        error = SSL_ERROR_NO_CERTIFICATE;         break;
3305     case bad_certificate:       error = SSL_ERROR_BAD_CERT_ALERT;         break;
3306     case unsupported_certificate:error = SSL_ERROR_UNSUPPORTED_CERT_ALERT;break;
3307     case certificate_revoked:   error = SSL_ERROR_REVOKED_CERT_ALERT;     break;
3308     case certificate_expired:   error = SSL_ERROR_EXPIRED_CERT_ALERT;     break;
3309     case certificate_unknown:   error = SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT;
3310                                                                           break;
3311     case illegal_parameter:     error = SSL_ERROR_ILLEGAL_PARAMETER_ALERT;break;
3312
3313     /* All alerts below are TLS only. */
3314     case unknown_ca:            error = SSL_ERROR_UNKNOWN_CA_ALERT;       break;
3315     case access_denied:         error = SSL_ERROR_ACCESS_DENIED_ALERT;    break;
3316     case decode_error:          error = SSL_ERROR_DECODE_ERROR_ALERT;     break;
3317     case decrypt_error:         error = SSL_ERROR_DECRYPT_ERROR_ALERT;    break;
3318     case export_restriction:    error = SSL_ERROR_EXPORT_RESTRICTION_ALERT; 
3319                                                                           break;
3320     case protocol_version:      error = SSL_ERROR_PROTOCOL_VERSION_ALERT; break;
3321     case insufficient_security: error = SSL_ERROR_INSUFFICIENT_SECURITY_ALERT; 
3322                                                                           break;
3323     case internal_error:        error = SSL_ERROR_INTERNAL_ERROR_ALERT;   break;
3324     case user_canceled:         error = SSL_ERROR_USER_CANCELED_ALERT;    break;
3325     case no_renegotiation:      error = SSL_ERROR_NO_RENEGOTIATION_ALERT; break;
3326
3327     /* Alerts for TLS client hello extensions */
3328     case unsupported_extension: 
3329                         error = SSL_ERROR_UNSUPPORTED_EXTENSION_ALERT;    break;
3330     case certificate_unobtainable: 
3331                         error = SSL_ERROR_CERTIFICATE_UNOBTAINABLE_ALERT; break;
3332     case unrecognized_name: 
3333                         error = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;        break;
3334     case bad_certificate_status_response: 
3335                         error = SSL_ERROR_BAD_CERT_STATUS_RESPONSE_ALERT; break;
3336     case bad_certificate_hash_value: 
3337                         error = SSL_ERROR_BAD_CERT_HASH_VALUE_ALERT;      break;
3338     default:            error = SSL_ERROR_RX_UNKNOWN_ALERT;               break;
3339     }
3340     if (level == alert_fatal) {
3341         if (!ss->opt.noCache) {
3342             if (ss->sec.uncache)
3343                 ss->sec.uncache(ss->sec.ci.sid);
3344         }
3345         if ((ss->ssl3.hs.ws == wait_server_hello) &&
3346             (desc == handshake_failure)) {
3347             /* XXX This is a hack.  We're assuming that any handshake failure
3348              * XXX on the client hello is a failure to match ciphers.
3349              */
3350             error = SSL_ERROR_NO_CYPHER_OVERLAP;
3351         }
3352         PORT_SetError(error);
3353         return SECFailure;
3354     }
3355     if ((desc == no_certificate) && (ss->ssl3.hs.ws == wait_client_cert)) {
3356         /* I'm a server. I've requested a client cert. He hasn't got one. */
3357         SECStatus rv;
3358
3359         PORT_Assert(ss->sec.isServer);
3360         ss->ssl3.hs.ws = wait_client_key;
3361         rv = ssl3_HandleNoCertificate(ss);
3362         return rv;
3363     }
3364     return SECSuccess;
3365 }
3366
3367 /*
3368  * Change Cipher Specs
3369  * Called from ssl3_HandleServerHelloDone,
3370  *             ssl3_HandleClientHello,
3371  * and         ssl3_HandleFinished
3372  *
3373  * Acquires and releases spec write lock, to protect switching the current
3374  * and pending write spec pointers.
3375  */
3376
3377 static SECStatus
3378 ssl3_SendChangeCipherSpecs(sslSocket *ss)
3379 {
3380     PRUint8           change = change_cipher_spec_choice;
3381     ssl3CipherSpec *  pwSpec;
3382     SECStatus         rv;
3383     PRInt32           sent;
3384
3385     SSL_TRC(3, ("%d: SSL3[%d]: send change_cipher_spec record",
3386                 SSL_GETPID(), ss->fd));
3387
3388     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
3389     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3390
3391     rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
3392     if (rv != SECSuccess) {
3393         return rv;      /* error code set by ssl3_FlushHandshake */
3394     }
3395     if (!IS_DTLS(ss)) {
3396         sent = ssl3_SendRecord(ss, 0, content_change_cipher_spec, &change, 1,
3397                                ssl_SEND_FLAG_FORCE_INTO_BUFFER);
3398         if (sent < 0) {
3399             return (SECStatus)sent;     /* error code set by ssl3_SendRecord */
3400         }
3401     } else {
3402         rv = dtls_QueueMessage(ss, content_change_cipher_spec, &change, 1);
3403         if (rv != SECSuccess) {
3404             return rv;
3405         }
3406     }
3407
3408     /* swap the pending and current write specs. */
3409     ssl_GetSpecWriteLock(ss);   /**************************************/
3410     pwSpec                     = ss->ssl3.pwSpec;
3411
3412     ss->ssl3.pwSpec = ss->ssl3.cwSpec;
3413     ss->ssl3.cwSpec = pwSpec;
3414
3415     SSL_TRC(3, ("%d: SSL3[%d] Set Current Write Cipher Suite to Pending",
3416                 SSL_GETPID(), ss->fd ));
3417
3418     /* We need to free up the contexts, keys and certs ! */
3419     /* If we are really through with the old cipher spec
3420      * (Both the read and write sides have changed) destroy it.
3421      */
3422     if (ss->ssl3.prSpec == ss->ssl3.pwSpec) {
3423         if (!IS_DTLS(ss)) {
3424             ssl3_DestroyCipherSpec(ss->ssl3.pwSpec, PR_FALSE/*freeSrvName*/);
3425         } else {
3426             /* With DTLS, we need to set a holddown timer in case the final
3427              * message got lost */
3428             ss->ssl3.hs.rtTimeoutMs = DTLS_FINISHED_TIMER_MS;
3429             dtls_StartTimer(ss, dtls_FinishedTimerCb);
3430         }
3431     }
3432     ssl_ReleaseSpecWriteLock(ss); /**************************************/
3433
3434     return SECSuccess;
3435 }
3436
3437 /* Called from ssl3_HandleRecord.
3438 ** Caller must hold both RecvBuf and Handshake locks.
3439  *
3440  * Acquires and releases spec write lock, to protect switching the current
3441  * and pending write spec pointers.
3442 */
3443 static SECStatus
3444 ssl3_HandleChangeCipherSpecs(sslSocket *ss, sslBuffer *buf)
3445 {
3446     ssl3CipherSpec *           prSpec;
3447     SSL3WaitState              ws      = ss->ssl3.hs.ws;
3448     SSL3ChangeCipherSpecChoice change;
3449
3450     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
3451     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
3452
3453     SSL_TRC(3, ("%d: SSL3[%d]: handle change_cipher_spec record",
3454                 SSL_GETPID(), ss->fd));
3455
3456     if (ws != wait_change_cipher) {
3457         (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
3458         PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER);
3459         return SECFailure;
3460     }
3461
3462     if(buf->len != 1) {
3463         (void)ssl3_DecodeError(ss);
3464         PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER);
3465         return SECFailure;
3466     }
3467     change = (SSL3ChangeCipherSpecChoice)buf->buf[0];
3468     if (change != change_cipher_spec_choice) {
3469         /* illegal_parameter is correct here for both SSL3 and TLS. */
3470         (void)ssl3_IllegalParameter(ss);
3471         PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER);
3472         return SECFailure;
3473     }
3474     buf->len = 0;
3475
3476     /* Swap the pending and current read specs. */
3477     ssl_GetSpecWriteLock(ss);   /*************************************/
3478     prSpec                    = ss->ssl3.prSpec;
3479
3480     ss->ssl3.prSpec  = ss->ssl3.crSpec;
3481     ss->ssl3.crSpec  = prSpec;
3482     ss->ssl3.hs.ws   = wait_finished;
3483
3484     SSL_TRC(3, ("%d: SSL3[%d] Set Current Read Cipher Suite to Pending",
3485                 SSL_GETPID(), ss->fd ));
3486
3487     /* If we are really through with the old cipher prSpec
3488      * (Both the read and write sides have changed) destroy it.
3489      */
3490     if (ss->ssl3.prSpec == ss->ssl3.pwSpec) {
3491         ssl3_DestroyCipherSpec(ss->ssl3.prSpec, PR_FALSE/*freeSrvName*/);
3492     }
3493     ssl_ReleaseSpecWriteLock(ss);   /*************************************/
3494     return SECSuccess;
3495 }
3496
3497 /* This method uses PKCS11 to derive the MS from the PMS, where PMS 
3498 ** is a PKCS11 symkey. This is used in all cases except the 
3499 ** "triple bypass" with RSA key exchange.
3500 ** Called from ssl3_InitPendingCipherSpec.   prSpec is pwSpec.
3501 */
3502 static SECStatus
3503 ssl3_DeriveMasterSecret(sslSocket *ss, PK11SymKey *pms)
3504 {
3505     ssl3CipherSpec *  pwSpec = ss->ssl3.pwSpec;
3506     const ssl3KEADef *kea_def= ss->ssl3.hs.kea_def;
3507     unsigned char *   cr     = (unsigned char *)&ss->ssl3.hs.client_random;
3508     unsigned char *   sr     = (unsigned char *)&ss->ssl3.hs.server_random;
3509     PRBool            isTLS  = (PRBool)(kea_def->tls_keygen ||
3510                                 (pwSpec->version > SSL_LIBRARY_VERSION_3_0));
3511     PRBool            isTLS12=
3512             (PRBool)(isTLS && pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
3513     /* 
3514      * Whenever isDH is true, we need to use CKM_TLS_MASTER_KEY_DERIVE_DH
3515      * which, unlike CKM_TLS_MASTER_KEY_DERIVE, converts arbitrary size
3516      * data into a 48-byte value. 
3517      */
3518     PRBool    isDH = (PRBool) ((ss->ssl3.hs.kea_def->exchKeyType == kt_dh) ||
3519                                (ss->ssl3.hs.kea_def->exchKeyType == kt_ecdh));
3520     SECStatus         rv = SECFailure;
3521     CK_MECHANISM_TYPE master_derive;
3522     CK_MECHANISM_TYPE key_derive;
3523     SECItem           params;
3524     CK_FLAGS          keyFlags;
3525     CK_VERSION        pms_version;
3526     CK_SSL3_MASTER_KEY_DERIVE_PARAMS master_params;
3527
3528     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3529     PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
3530     PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
3531     if (isTLS12) {
3532         if(isDH) master_derive = CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256;
3533         else master_derive = CKM_NSS_TLS_MASTER_KEY_DERIVE_SHA256;
3534         key_derive    = CKM_NSS_TLS_KEY_AND_MAC_DERIVE_SHA256;
3535         keyFlags      = CKF_SIGN | CKF_VERIFY;
3536     } else if (isTLS) {
3537         if(isDH) master_derive = CKM_TLS_MASTER_KEY_DERIVE_DH;
3538         else master_derive = CKM_TLS_MASTER_KEY_DERIVE;
3539         key_derive    = CKM_TLS_KEY_AND_MAC_DERIVE;
3540         keyFlags      = CKF_SIGN | CKF_VERIFY;
3541     } else {
3542         if (isDH) master_derive = CKM_SSL3_MASTER_KEY_DERIVE_DH;
3543         else master_derive = CKM_SSL3_MASTER_KEY_DERIVE;
3544         key_derive    = CKM_SSL3_KEY_AND_MAC_DERIVE;
3545         keyFlags      = 0;
3546     }
3547
3548     if (pms || !pwSpec->master_secret) {
3549         if (isDH) {
3550             master_params.pVersion                     = NULL;
3551         } else {
3552             master_params.pVersion                     = &pms_version;
3553         }
3554         master_params.RandomInfo.pClientRandom     = cr;
3555         master_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH;
3556         master_params.RandomInfo.pServerRandom     = sr;
3557         master_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH;
3558
3559         params.data = (unsigned char *) &master_params;
3560         params.len  = sizeof master_params;
3561     }
3562
3563     if (pms != NULL) {
3564 #if defined(TRACE)
3565         if (ssl_trace >= 100) {
3566             SECStatus extractRV = PK11_ExtractKeyValue(pms);
3567             if (extractRV == SECSuccess) {
3568                 SECItem * keyData = PK11_GetKeyData(pms);
3569                 if (keyData && keyData->data && keyData->len) {
3570                     ssl_PrintBuf(ss, "Pre-Master Secret", 
3571                                  keyData->data, keyData->len);
3572                 }
3573             }
3574         }
3575 #endif
3576         pwSpec->master_secret = PK11_DeriveWithFlags(pms, master_derive, 
3577                                 &params, key_derive, CKA_DERIVE, 0, keyFlags);
3578         if (!isDH && pwSpec->master_secret && ss->opt.detectRollBack) {
3579             SSL3ProtocolVersion client_version;
3580             client_version = pms_version.major << 8 | pms_version.minor;
3581
3582             if (IS_DTLS(ss)) {
3583                 client_version = dtls_DTLSVersionToTLSVersion(client_version);
3584             }
3585
3586             if (client_version != ss->clientHelloVersion) {
3587                 /* Destroy it.  Version roll-back detected. */
3588                 PK11_FreeSymKey(pwSpec->master_secret);
3589                 pwSpec->master_secret = NULL;
3590             }
3591         }
3592         if (pwSpec->master_secret == NULL) {
3593             /* Generate a faux master secret in the same slot as the old one. */
3594             PK11SlotInfo * slot = PK11_GetSlotFromKey((PK11SymKey *)pms);
3595             PK11SymKey *   fpms = ssl3_GenerateRSAPMS(ss, pwSpec, slot);
3596
3597             PK11_FreeSlot(slot);
3598             if (fpms != NULL) {
3599                 pwSpec->master_secret = PK11_DeriveWithFlags(fpms, 
3600                                         master_derive, &params, key_derive, 
3601                                         CKA_DERIVE, 0, keyFlags);
3602                 PK11_FreeSymKey(fpms);
3603             }
3604         }
3605     }
3606     if (pwSpec->master_secret == NULL) {
3607         /* Generate a faux master secret from the internal slot. */
3608         PK11SlotInfo *  slot = PK11_GetInternalSlot();
3609         PK11SymKey *    fpms = ssl3_GenerateRSAPMS(ss, pwSpec, slot);
3610
3611         PK11_FreeSlot(slot);
3612         if (fpms != NULL) {
3613             pwSpec->master_secret = PK11_DeriveWithFlags(fpms, 
3614                                         master_derive, &params, key_derive, 
3615                                         CKA_DERIVE, 0, keyFlags);
3616             if (pwSpec->master_secret == NULL) {
3617                 pwSpec->master_secret = fpms; /* use the fpms as the master. */
3618                 fpms = NULL;
3619             }
3620         }
3621         if (fpms) {
3622             PK11_FreeSymKey(fpms);
3623         }
3624     }
3625     if (pwSpec->master_secret == NULL) {
3626         ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3627         return rv;
3628     }
3629 #ifndef NO_PKCS11_BYPASS
3630     if (ss->opt.bypassPKCS11) {
3631         SECItem * keydata;
3632         /* In hope of doing a "double bypass", 
3633          * need to extract the master secret's value from the key object 
3634          * and store it raw in the sslSocket struct.
3635          */
3636         rv = PK11_ExtractKeyValue(pwSpec->master_secret);
3637         if (rv != SECSuccess) {
3638             return rv;
3639         } 
3640         /* This returns the address of the secItem inside the key struct,
3641          * not a copy or a reference.  So, there's no need to free it.
3642          */
3643         keydata = PK11_GetKeyData(pwSpec->master_secret);
3644         if (keydata && keydata->len <= sizeof pwSpec->raw_master_secret) {
3645             memcpy(pwSpec->raw_master_secret, keydata->data, keydata->len);
3646             pwSpec->msItem.data = pwSpec->raw_master_secret;
3647             pwSpec->msItem.len  = keydata->len;
3648         } else {
3649             PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
3650             return SECFailure;
3651         }
3652     }
3653 #endif
3654     return SECSuccess;
3655 }
3656
3657
3658 /* 
3659  * Derive encryption and MAC Keys (and IVs) from master secret
3660  * Sets a useful error code when returning SECFailure.
3661  *
3662  * Called only from ssl3_InitPendingCipherSpec(),
3663  * which in turn is called from
3664  *              sendRSAClientKeyExchange        (for Full handshake)
3665  *              sendDHClientKeyExchange         (for Full handshake)
3666  *              ssl3_HandleClientKeyExchange    (for Full handshake)
3667  *              ssl3_HandleServerHello          (for session restart)
3668  *              ssl3_HandleClientHello          (for session restart)
3669  * Caller MUST hold the specWriteLock, and SSL3HandshakeLock.
3670  * ssl3_InitPendingCipherSpec does that.
3671  *
3672  */
3673 static SECStatus
3674 ssl3_DeriveConnectionKeysPKCS11(sslSocket *ss)
3675 {
3676     ssl3CipherSpec *         pwSpec     = ss->ssl3.pwSpec;
3677     const ssl3KEADef *       kea_def    = ss->ssl3.hs.kea_def;
3678     unsigned char *   cr     = (unsigned char *)&ss->ssl3.hs.client_random;
3679     unsigned char *   sr     = (unsigned char *)&ss->ssl3.hs.server_random;
3680     PRBool            isTLS  = (PRBool)(kea_def->tls_keygen ||
3681                                 (pwSpec->version > SSL_LIBRARY_VERSION_3_0));
3682     PRBool            isTLS12=
3683             (PRBool)(isTLS && pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
3684     /* following variables used in PKCS11 path */
3685     const ssl3BulkCipherDef *cipher_def = pwSpec->cipher_def;
3686     PK11SlotInfo *         slot   = NULL;
3687     PK11SymKey *           symKey = NULL;
3688     void *                 pwArg  = ss->pkcs11PinArg;
3689     int                    keySize;
3690     CK_SSL3_KEY_MAT_PARAMS key_material_params;
3691     CK_SSL3_KEY_MAT_OUT    returnedKeys;
3692     CK_MECHANISM_TYPE      key_derive;
3693     CK_MECHANISM_TYPE      bulk_mechanism;
3694     SSLCipherAlgorithm     calg;
3695     SECItem                params;
3696     PRBool         skipKeysAndIVs = (PRBool)(cipher_def->calg == calg_null);
3697
3698     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3699     PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
3700     PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
3701
3702     if (!pwSpec->master_secret) {
3703         PORT_SetError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3704         return SECFailure;
3705     }
3706     /*
3707      * generate the key material
3708      */
3709     key_material_params.ulMacSizeInBits = pwSpec->mac_size           * BPB;
3710     key_material_params.ulKeySizeInBits = cipher_def->secret_key_size* BPB;
3711     key_material_params.ulIVSizeInBits  = cipher_def->iv_size        * BPB;
3712     if (cipher_def->type == type_block &&
3713         pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
3714         /* Block ciphers in >= TLS 1.1 use a per-record, explicit IV. */
3715         key_material_params.ulIVSizeInBits = 0;
3716         memset(pwSpec->client.write_iv, 0, cipher_def->iv_size);
3717         memset(pwSpec->server.write_iv, 0, cipher_def->iv_size);
3718     }
3719
3720     key_material_params.bIsExport = (CK_BBOOL)(kea_def->is_limited);
3721
3722     key_material_params.RandomInfo.pClientRandom     = cr;
3723     key_material_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH;
3724     key_material_params.RandomInfo.pServerRandom     = sr;
3725     key_material_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH;
3726     key_material_params.pReturnedKeyMaterial         = &returnedKeys;
3727
3728     returnedKeys.pIVClient = pwSpec->client.write_iv;
3729     returnedKeys.pIVServer = pwSpec->server.write_iv;
3730     keySize                = cipher_def->key_size;
3731
3732     if (skipKeysAndIVs) {
3733         keySize                             = 0;
3734         key_material_params.ulKeySizeInBits = 0;
3735         key_material_params.ulIVSizeInBits  = 0;
3736         returnedKeys.pIVClient              = NULL;
3737         returnedKeys.pIVServer              = NULL;
3738     }
3739
3740     calg = cipher_def->calg;
3741     PORT_Assert(     alg2Mech[calg].calg == calg);
3742     bulk_mechanism = alg2Mech[calg].cmech;
3743
3744     params.data    = (unsigned char *)&key_material_params;
3745     params.len     = sizeof(key_material_params);
3746
3747     if (isTLS12) {
3748         key_derive    = CKM_NSS_TLS_KEY_AND_MAC_DERIVE_SHA256;
3749     } else if (isTLS) {
3750         key_derive    = CKM_TLS_KEY_AND_MAC_DERIVE;
3751     } else {
3752         key_derive    = CKM_SSL3_KEY_AND_MAC_DERIVE;
3753     }
3754
3755     /* CKM_SSL3_KEY_AND_MAC_DERIVE is defined to set ENCRYPT, DECRYPT, and
3756      * DERIVE by DEFAULT */
3757     symKey = PK11_Derive(pwSpec->master_secret, key_derive, &params,
3758                          bulk_mechanism, CKA_ENCRYPT, keySize);
3759     if (!symKey) {
3760         ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3761         return SECFailure;
3762     }
3763     /* we really should use the actual mac'ing mechanism here, but we
3764      * don't because these types are used to map keytype anyway and both
3765      * mac's map to the same keytype.
3766      */
3767     slot  = PK11_GetSlotFromKey(symKey);
3768
3769     PK11_FreeSlot(slot); /* slot is held until the key is freed */
3770     pwSpec->client.write_mac_key =
3771         PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive,
3772             CKM_SSL3_SHA1_MAC, returnedKeys.hClientMacSecret, PR_TRUE, pwArg);
3773     if (pwSpec->client.write_mac_key == NULL ) {
3774         goto loser;     /* loser sets err */
3775     }
3776     pwSpec->server.write_mac_key =
3777         PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive,
3778             CKM_SSL3_SHA1_MAC, returnedKeys.hServerMacSecret, PR_TRUE, pwArg);
3779     if (pwSpec->server.write_mac_key == NULL ) {
3780         goto loser;     /* loser sets err */
3781     }
3782     if (!skipKeysAndIVs) {
3783         pwSpec->client.write_key =
3784                 PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive,
3785                      bulk_mechanism, returnedKeys.hClientKey, PR_TRUE, pwArg);
3786         if (pwSpec->client.write_key == NULL ) {
3787             goto loser; /* loser sets err */
3788         }
3789         pwSpec->server.write_key =
3790                 PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive,
3791                      bulk_mechanism, returnedKeys.hServerKey, PR_TRUE, pwArg);
3792         if (pwSpec->server.write_key == NULL ) {
3793             goto loser; /* loser sets err */
3794         }
3795     }
3796     PK11_FreeSymKey(symKey);
3797     return SECSuccess;
3798
3799
3800 loser:
3801     if (symKey) PK11_FreeSymKey(symKey);
3802     ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3803     return SECFailure;
3804 }
3805
3806 /* ssl3_InitHandshakeHashes creates handshake hash contexts and hashes in
3807  * buffered messages in ss->ssl3.hs.messages. */
3808 static SECStatus
3809 ssl3_InitHandshakeHashes(sslSocket *ss)
3810 {
3811     SSL_TRC(30,("%d: SSL3[%d]: start handshake hashes", SSL_GETPID(), ss->fd));
3812
3813     PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_unknown);
3814 #ifndef NO_PKCS11_BYPASS
3815     if (ss->opt.bypassPKCS11) {
3816         PORT_Assert(!ss->ssl3.hs.sha_obj && !ss->ssl3.hs.sha_clone);
3817         if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
3818             /* If we ever support ciphersuites where the PRF hash isn't SHA-256
3819              * then this will need to be updated. */
3820             ss->ssl3.hs.sha_obj = HASH_GetRawHashObject(HASH_AlgSHA256);
3821             if (!ss->ssl3.hs.sha_obj) {
3822                 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
3823                 return SECFailure;
3824             }
3825             ss->ssl3.hs.sha_clone = (void (*)(void *, void *))SHA256_Clone;
3826             ss->ssl3.hs.hashType = handshake_hash_single;
3827             ss->ssl3.hs.sha_obj->begin(ss->ssl3.hs.sha_cx);
3828         } else {
3829             ss->ssl3.hs.hashType = handshake_hash_combo;
3830             MD5_Begin((MD5Context *)ss->ssl3.hs.md5_cx);
3831             SHA1_Begin((SHA1Context *)ss->ssl3.hs.sha_cx);
3832         }
3833     } else
3834 #endif
3835     {
3836         PORT_Assert(!ss->ssl3.hs.md5 && !ss->ssl3.hs.sha);
3837         /*
3838          * note: We should probably lookup an SSL3 slot for these
3839          * handshake hashes in hopes that we wind up with the same slots
3840          * that the master secret will wind up in ...
3841          */
3842         if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
3843             /* If we ever support ciphersuites where the PRF hash isn't SHA-256
3844              * then this will need to be updated. */
3845             ss->ssl3.hs.sha = PK11_CreateDigestContext(SEC_OID_SHA256);
3846             if (ss->ssl3.hs.sha == NULL) {
3847                 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3848                 return SECFailure;
3849             }
3850             ss->ssl3.hs.hashType = handshake_hash_single;
3851
3852             if (PK11_DigestBegin(ss->ssl3.hs.sha) != SECSuccess) {
3853                 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
3854                 return SECFailure;
3855             }
3856         } else {
3857             /* Both ss->ssl3.hs.md5 and ss->ssl3.hs.sha should be NULL or
3858              * created successfully. */
3859             ss->ssl3.hs.md5 = PK11_CreateDigestContext(SEC_OID_MD5);
3860             if (ss->ssl3.hs.md5 == NULL) {
3861                 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
3862                 return SECFailure;
3863             }
3864             ss->ssl3.hs.sha = PK11_CreateDigestContext(SEC_OID_SHA1);
3865             if (ss->ssl3.hs.sha == NULL) {
3866                 PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE);
3867                 ss->ssl3.hs.md5 = NULL;
3868                 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3869                 return SECFailure;
3870             }
3871             ss->ssl3.hs.hashType = handshake_hash_combo;
3872
3873             if (PK11_DigestBegin(ss->ssl3.hs.md5) != SECSuccess) {
3874                 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
3875                 return SECFailure;
3876             }
3877             if (PK11_DigestBegin(ss->ssl3.hs.sha) != SECSuccess) {
3878                 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3879                 return SECFailure;
3880             }
3881         }
3882     }
3883
3884     if (ss->ssl3.hs.messages.len > 0) {
3885         if (ssl3_UpdateHandshakeHashes(ss, ss->ssl3.hs.messages.buf,
3886                                        ss->ssl3.hs.messages.len) !=
3887             SECSuccess) {
3888             return SECFailure;
3889         }
3890         PORT_Free(ss->ssl3.hs.messages.buf);
3891         ss->ssl3.hs.messages.buf = NULL;
3892         ss->ssl3.hs.messages.len = 0;
3893         ss->ssl3.hs.messages.space = 0;
3894     }
3895
3896     return SECSuccess;
3897 }
3898
3899 static SECStatus 
3900 ssl3_RestartHandshakeHashes(sslSocket *ss)
3901 {
3902     SECStatus rv = SECSuccess;
3903
3904     SSL_TRC(30,("%d: SSL3[%d]: reset handshake hashes",
3905             SSL_GETPID(), ss->fd ));
3906     ss->ssl3.hs.hashType = handshake_hash_unknown;
3907     ss->ssl3.hs.messages.len = 0;
3908 #ifndef NO_PKCS11_BYPASS
3909     ss->ssl3.hs.sha_obj = NULL;
3910     ss->ssl3.hs.sha_clone = NULL;
3911 #endif
3912     if (ss->ssl3.hs.md5) {
3913         PK11_DestroyContext(ss->ssl3.hs.md5,PR_TRUE);
3914         ss->ssl3.hs.md5 = NULL;
3915     }
3916     if (ss->ssl3.hs.sha) {
3917         PK11_DestroyContext(ss->ssl3.hs.sha,PR_TRUE);
3918         ss->ssl3.hs.sha = NULL;
3919     }
3920     return rv;
3921 }
3922
3923 /*
3924  * Handshake messages
3925  */
3926 /* Called from  ssl3_InitHandshakeHashes()
3927 **              ssl3_AppendHandshake()
3928 **              ssl3_StartHandshakeHash()
3929 **              ssl3_HandleV2ClientHello()
3930 **              ssl3_HandleHandshakeMessage()
3931 ** Caller must hold the ssl3Handshake lock.
3932 */
3933 static SECStatus
3934 ssl3_UpdateHandshakeHashes(sslSocket *ss, const unsigned char *b,
3935                            unsigned int l)
3936 {
3937     SECStatus  rv = SECSuccess;
3938
3939     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
3940
3941     /* We need to buffer the handshake messages until we have established
3942      * which handshake hash function to use. */
3943     if (ss->ssl3.hs.hashType == handshake_hash_unknown) {
3944         return sslBuffer_Append(&ss->ssl3.hs.messages, b, l);
3945     }
3946
3947     PRINT_BUF(90, (NULL, "handshake hash input:", b, l));
3948
3949 #ifndef NO_PKCS11_BYPASS
3950     if (ss->opt.bypassPKCS11) {
3951         if (ss->ssl3.hs.hashType == handshake_hash_single) {
3952             ss->ssl3.hs.sha_obj->update(ss->ssl3.hs.sha_cx, b, l);
3953         } else {
3954             MD5_Update((MD5Context *)ss->ssl3.hs.md5_cx, b, l);
3955             SHA1_Update((SHA1Context *)ss->ssl3.hs.sha_cx, b, l);
3956         }
3957         return rv;
3958     }
3959 #endif
3960     if (ss->ssl3.hs.hashType == handshake_hash_single) {
3961         rv = PK11_DigestOp(ss->ssl3.hs.sha, b, l);
3962         if (rv != SECSuccess) {
3963             ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
3964             return rv;
3965         }
3966     } else {
3967         rv = PK11_DigestOp(ss->ssl3.hs.md5, b, l);
3968         if (rv != SECSuccess) {
3969             ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
3970             return rv;
3971         }
3972         rv = PK11_DigestOp(ss->ssl3.hs.sha, b, l);
3973         if (rv != SECSuccess) {
3974             ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3975             return rv;
3976         }
3977     }
3978     return rv;
3979 }
3980
3981 /**************************************************************************
3982  * Append Handshake functions.
3983  * All these functions set appropriate error codes.
3984  * Most rely on ssl3_AppendHandshake to set the error code.
3985  **************************************************************************/
3986 SECStatus
3987 ssl3_AppendHandshake(sslSocket *ss, const void *void_src, PRInt32 bytes)
3988 {
3989     unsigned char *  src  = (unsigned char *)void_src;
3990     int              room = ss->sec.ci.sendBuf.space - ss->sec.ci.sendBuf.len;
3991     SECStatus        rv;
3992
3993     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); /* protects sendBuf. */
3994
3995     if (!bytes)
3996         return SECSuccess;
3997     if (ss->sec.ci.sendBuf.space < MAX_SEND_BUF_LENGTH && room < bytes) {
3998         rv = sslBuffer_Grow(&ss->sec.ci.sendBuf, PR_MAX(MIN_SEND_BUF_LENGTH,
3999                  PR_MIN(MAX_SEND_BUF_LENGTH, ss->sec.ci.sendBuf.len + bytes)));
4000         if (rv != SECSuccess)
4001             return rv;  /* sslBuffer_Grow has set a memory error code. */
4002         room = ss->sec.ci.sendBuf.space - ss->sec.ci.sendBuf.len;
4003     }
4004
4005     PRINT_BUF(60, (ss, "Append to Handshake", (unsigned char*)void_src, bytes));
4006     rv = ssl3_UpdateHandshakeHashes(ss, src, bytes);
4007     if (rv != SECSuccess)
4008         return rv;      /* error code set by ssl3_UpdateHandshakeHashes */
4009
4010     while (bytes > room) {
4011         if (room > 0)
4012             PORT_Memcpy(ss->sec.ci.sendBuf.buf + ss->sec.ci.sendBuf.len, src, 
4013                         room);
4014         ss->sec.ci.sendBuf.len += room;
4015         rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
4016         if (rv != SECSuccess) {
4017             return rv;  /* error code set by ssl3_FlushHandshake */
4018         }
4019         bytes -= room;
4020         src += room;
4021         room = ss->sec.ci.sendBuf.space;
4022         PORT_Assert(ss->sec.ci.sendBuf.len == 0);
4023     }
4024     PORT_Memcpy(ss->sec.ci.sendBuf.buf + ss->sec.ci.sendBuf.len, src, bytes);
4025     ss->sec.ci.sendBuf.len += bytes;
4026     return SECSuccess;
4027 }
4028
4029 SECStatus
4030 ssl3_AppendHandshakeNumber(sslSocket *ss, PRInt32 num, PRInt32 lenSize)
4031 {
4032     SECStatus rv;
4033     PRUint8   b[4];
4034     PRUint8 * p = b;
4035
4036     switch (lenSize) {
4037       case 4:
4038         *p++ = (num >> 24) & 0xff;
4039       case 3:
4040         *p++ = (num >> 16) & 0xff;
4041       case 2:
4042         *p++ = (num >> 8) & 0xff;
4043       case 1:
4044         *p = num & 0xff;
4045     }
4046     SSL_TRC(60, ("%d: number:", SSL_GETPID()));
4047     rv = ssl3_AppendHandshake(ss, &b[0], lenSize);
4048     return rv;  /* error code set by AppendHandshake, if applicable. */
4049 }
4050
4051 SECStatus
4052 ssl3_AppendHandshakeVariable(
4053     sslSocket *ss, const SSL3Opaque *src, PRInt32 bytes, PRInt32 lenSize)
4054 {
4055     SECStatus rv;
4056
4057     PORT_Assert((bytes < (1<<8) && lenSize == 1) ||
4058               (bytes < (1L<<16) && lenSize == 2) ||
4059               (bytes < (1L<<24) && lenSize == 3));
4060
4061     SSL_TRC(60,("%d: append variable:", SSL_GETPID()));
4062     rv = ssl3_AppendHandshakeNumber(ss, bytes, lenSize);
4063     if (rv != SECSuccess) {
4064         return rv;      /* error code set by AppendHandshake, if applicable. */
4065     }
4066     SSL_TRC(60, ("data:"));
4067     rv = ssl3_AppendHandshake(ss, src, bytes);
4068     return rv;  /* error code set by AppendHandshake, if applicable. */
4069 }
4070
4071 SECStatus
4072 ssl3_AppendHandshakeHeader(sslSocket *ss, SSL3HandshakeType t, PRUint32 length)
4073 {
4074     SECStatus rv;
4075
4076     /* If we already have a message in place, we need to enqueue it.
4077      * This empties the buffer. This is a convenient place to call
4078      * dtls_StageHandshakeMessage to mark the message boundary.
4079      */
4080     if (IS_DTLS(ss)) {
4081         rv = dtls_StageHandshakeMessage(ss);
4082         if (rv != SECSuccess) {
4083             return rv;
4084         }
4085     }
4086
4087     SSL_TRC(30,("%d: SSL3[%d]: append handshake header: type %s",
4088         SSL_GETPID(), ss->fd, ssl3_DecodeHandshakeType(t)));
4089
4090     rv = ssl3_AppendHandshakeNumber(ss, t, 1);
4091     if (rv != SECSuccess) {
4092         return rv;      /* error code set by AppendHandshake, if applicable. */
4093     }
4094     rv = ssl3_AppendHandshakeNumber(ss, length, 3);
4095     if (rv != SECSuccess) {
4096         return rv;      /* error code set by AppendHandshake, if applicable. */
4097     }
4098
4099     if (IS_DTLS(ss)) {
4100         /* Note that we make an unfragmented message here. We fragment in the
4101          * transmission code, if necessary */
4102         rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.sendMessageSeq, 2);
4103         if (rv != SECSuccess) {
4104             return rv;  /* error code set by AppendHandshake, if applicable. */
4105         }
4106         ss->ssl3.hs.sendMessageSeq++;
4107
4108         /* 0 is the fragment offset, because it's not fragmented yet */
4109         rv = ssl3_AppendHandshakeNumber(ss, 0, 3);
4110         if (rv != SECSuccess) {
4111             return rv;  /* error code set by AppendHandshake, if applicable. */
4112         }
4113
4114         /* Fragment length -- set to the packet length because not fragmented */
4115         rv = ssl3_AppendHandshakeNumber(ss, length, 3);
4116         if (rv != SECSuccess) {
4117             return rv;  /* error code set by AppendHandshake, if applicable. */
4118         }
4119     }
4120
4121     return rv;          /* error code set by AppendHandshake, if applicable. */
4122 }
4123
4124 /* ssl3_AppendSignatureAndHashAlgorithm appends the serialisation of
4125  * |sigAndHash| to the current handshake message. */
4126 SECStatus
4127 ssl3_AppendSignatureAndHashAlgorithm(
4128         sslSocket *ss, const SSL3SignatureAndHashAlgorithm* sigAndHash)
4129 {
4130     unsigned char serialized[2];
4131
4132     serialized[0] = ssl3_OIDToTLSHashAlgorithm(sigAndHash->hashAlg);
4133     if (serialized[0] == 0) {
4134         PORT_SetError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
4135         return SECFailure;
4136     }
4137
4138     serialized[1] = sigAndHash->sigAlg;
4139
4140     return ssl3_AppendHandshake(ss, serialized, sizeof(serialized));
4141 }
4142
4143 /**************************************************************************
4144  * Consume Handshake functions.
4145  *
4146  * All data used in these functions is protected by two locks,
4147  * the RecvBufLock and the SSL3HandshakeLock
4148  **************************************************************************/
4149
4150 /* Read up the next "bytes" number of bytes from the (decrypted) input
4151  * stream "b" (which is *length bytes long). Copy them into buffer "v".
4152  * Reduces *length by bytes.  Advances *b by bytes.
4153  *
4154  * If this function returns SECFailure, it has already sent an alert,
4155  * and has set a generic error code.  The caller should probably
4156  * override the generic error code by setting another.
4157  */
4158 SECStatus
4159 ssl3_ConsumeHandshake(sslSocket *ss, void *v, PRInt32 bytes, SSL3Opaque **b,
4160                       PRUint32 *length)
4161 {
4162     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
4163     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
4164
4165     if ((PRUint32)bytes > *length) {
4166         return ssl3_DecodeError(ss);
4167     }
4168     PORT_Memcpy(v, *b, bytes);
4169     PRINT_BUF(60, (ss, "consume bytes:", *b, bytes));
4170     *b      += bytes;
4171     *length -= bytes;
4172     return SECSuccess;
4173 }
4174
4175 /* Read up the next "bytes" number of bytes from the (decrypted) input
4176  * stream "b" (which is *length bytes long), and interpret them as an
4177  * integer in network byte order.  Returns the received value.
4178  * Reduces *length by bytes.  Advances *b by bytes.
4179  *
4180  * Returns SECFailure (-1) on failure.
4181  * This value is indistinguishable from the equivalent received value.
4182  * Only positive numbers are to be received this way.
4183  * Thus, the largest value that may be sent this way is 0x7fffffff.
4184  * On error, an alert has been sent, and a generic error code has been set.
4185  */
4186 PRInt32
4187 ssl3_ConsumeHandshakeNumber(sslSocket *ss, PRInt32 bytes, SSL3Opaque **b,
4188                             PRUint32 *length)
4189 {
4190     PRUint8  *buf = *b;
4191     int       i;
4192     PRInt32   num = 0;
4193
4194     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
4195     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
4196     PORT_Assert( bytes <= sizeof num);
4197
4198     if ((PRUint32)bytes > *length) {
4199         return ssl3_DecodeError(ss);
4200     }
4201     PRINT_BUF(60, (ss, "consume bytes:", *b, bytes));
4202
4203     for (i = 0; i < bytes; i++)
4204         num = (num << 8) + buf[i];
4205     *b      += bytes;
4206     *length -= bytes;
4207     return num;
4208 }
4209
4210 /* Read in two values from the incoming decrypted byte stream "b", which is
4211  * *length bytes long.  The first value is a number whose size is "bytes"
4212  * bytes long.  The second value is a byte-string whose size is the value
4213  * of the first number received.  The latter byte-string, and its length,
4214  * is returned in the SECItem i.
4215  *
4216  * Returns SECFailure (-1) on failure.
4217  * On error, an alert has been sent, and a generic error code has been set.
4218  *
4219  * RADICAL CHANGE for NSS 3.11.  All callers of this function make copies 
4220  * of the data returned in the SECItem *i, so making a copy of it here
4221  * is simply wasteful.  So, This function now just sets SECItem *i to 
4222  * point to the values in the buffer **b.
4223  */
4224 SECStatus
4225 ssl3_ConsumeHandshakeVariable(sslSocket *ss, SECItem *i, PRInt32 bytes,
4226                               SSL3Opaque **b, PRUint32 *length)
4227 {
4228     PRInt32   count;
4229
4230     PORT_Assert(bytes <= 3);
4231     i->len  = 0;
4232     i->data = NULL;
4233     count = ssl3_ConsumeHandshakeNumber(ss, bytes, b, length);
4234     if (count < 0) {            /* Can't test for SECSuccess here. */
4235         return SECFailure;
4236     }
4237     if (count > 0) {
4238         if ((PRUint32)count > *length) {
4239             return ssl3_DecodeError(ss);
4240         }
4241         i->data = *b;
4242         i->len  = count;
4243         *b      += count;
4244         *length -= count;
4245     }
4246     return SECSuccess;
4247 }
4248
4249 /* tlsHashOIDMap contains the mapping between TLS hash identifiers and the
4250  * SECOidTag used internally by NSS. */
4251 static const struct {
4252     int tlsHash;
4253     SECOidTag oid;
4254 } tlsHashOIDMap[] = {
4255     { tls_hash_md5, SEC_OID_MD5 },
4256     { tls_hash_sha1, SEC_OID_SHA1 },
4257     { tls_hash_sha224, SEC_OID_SHA224 },
4258     { tls_hash_sha256, SEC_OID_SHA256 },
4259     { tls_hash_sha384, SEC_OID_SHA384 },
4260     { tls_hash_sha512, SEC_OID_SHA512 }
4261 };
4262
4263 /* ssl3_TLSHashAlgorithmToOID converts a TLS hash identifier into an OID value.
4264  * If the hash is not recognised, SEC_OID_UNKNOWN is returned.
4265  *
4266  * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
4267 SECOidTag
4268 ssl3_TLSHashAlgorithmToOID(int hashFunc)
4269 {
4270     unsigned int i;
4271
4272     for (i = 0; i < PR_ARRAY_SIZE(tlsHashOIDMap); i++) {
4273         if (hashFunc == tlsHashOIDMap[i].tlsHash) {
4274             return tlsHashOIDMap[i].oid;
4275         }
4276     }
4277     return SEC_OID_UNKNOWN;
4278 }
4279
4280 /* ssl3_OIDToTLSHashAlgorithm converts an OID to a TLS hash algorithm
4281  * identifier. If the hash is not recognised, zero is returned.
4282  *
4283  * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
4284 static int
4285 ssl3_OIDToTLSHashAlgorithm(SECOidTag oid)
4286 {
4287     unsigned int i;
4288
4289     for (i = 0; i < PR_ARRAY_SIZE(tlsHashOIDMap); i++) {
4290         if (oid == tlsHashOIDMap[i].oid) {
4291             return tlsHashOIDMap[i].tlsHash;
4292         }
4293     }
4294     return 0;
4295 }
4296
4297 /* ssl3_TLSSignatureAlgorithmForKeyType returns the TLS 1.2 signature algorithm
4298  * identifier for a given KeyType. */
4299 static SECStatus
4300 ssl3_TLSSignatureAlgorithmForKeyType(KeyType keyType,
4301                                      TLSSignatureAlgorithm *out)
4302 {
4303     switch (keyType) {
4304     case rsaKey:
4305         *out = tls_sig_rsa;
4306         return SECSuccess;
4307     case dsaKey:
4308         *out = tls_sig_dsa;
4309         return SECSuccess;
4310     case ecKey:
4311         *out = tls_sig_ecdsa;
4312         return SECSuccess;
4313     default:
4314         PORT_SetError(SEC_ERROR_INVALID_KEY);
4315         return SECFailure;
4316     }
4317 }
4318
4319 /* ssl3_TLSSignatureAlgorithmForCertificate returns the TLS 1.2 signature
4320  * algorithm identifier for the given certificate. */
4321 static SECStatus
4322 ssl3_TLSSignatureAlgorithmForCertificate(CERTCertificate *cert,
4323                                          TLSSignatureAlgorithm *out)
4324 {
4325     SECKEYPublicKey *key;
4326     KeyType keyType;
4327
4328     key = CERT_ExtractPublicKey(cert);
4329     if (key == NULL) {
4330         ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
4331         return SECFailure;
4332     }
4333
4334     keyType = key->keyType;
4335     SECKEY_DestroyPublicKey(key);
4336     return ssl3_TLSSignatureAlgorithmForKeyType(keyType, out);
4337 }
4338
4339 /* ssl3_CheckSignatureAndHashAlgorithmConsistency checks that the signature
4340  * algorithm identifier in |sigAndHash| is consistent with the public key in
4341  * |cert|. If so, SECSuccess is returned. Otherwise, PORT_SetError is called
4342  * and SECFailure is returned. */
4343 SECStatus
4344 ssl3_CheckSignatureAndHashAlgorithmConsistency(
4345         const SSL3SignatureAndHashAlgorithm *sigAndHash, CERTCertificate* cert)
4346 {
4347     SECStatus rv;
4348     TLSSignatureAlgorithm sigAlg;
4349
4350     rv = ssl3_TLSSignatureAlgorithmForCertificate(cert, &sigAlg);
4351     if (rv != SECSuccess) {
4352         return rv;
4353     }
4354     if (sigAlg != sigAndHash->sigAlg) {
4355         PORT_SetError(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM);
4356         return SECFailure;
4357     }
4358     return SECSuccess;
4359 }
4360
4361 /* ssl3_ConsumeSignatureAndHashAlgorithm reads a SignatureAndHashAlgorithm
4362  * structure from |b| and puts the resulting value into |out|. |b| and |length|
4363  * are updated accordingly.
4364  *
4365  * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
4366 SECStatus
4367 ssl3_ConsumeSignatureAndHashAlgorithm(sslSocket *ss,
4368                                       SSL3Opaque **b,
4369                                       PRUint32 *length,
4370                                       SSL3SignatureAndHashAlgorithm *out)
4371 {
4372     unsigned char bytes[2];
4373     SECStatus rv;
4374
4375     rv = ssl3_ConsumeHandshake(ss, bytes, sizeof(bytes), b, length);
4376     if (rv != SECSuccess) {
4377         return rv;
4378     }
4379
4380     out->hashAlg = ssl3_TLSHashAlgorithmToOID(bytes[0]);
4381     if (out->hashAlg == SEC_OID_UNKNOWN) {
4382         PORT_SetError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
4383         return SECFailure;
4384     }
4385
4386     out->sigAlg = bytes[1];
4387     return SECSuccess;
4388 }
4389
4390 /**************************************************************************
4391  * end of Consume Handshake functions.
4392  **************************************************************************/
4393
4394 /* Extract the hashes of handshake messages to this point.
4395  * Called from ssl3_SendCertificateVerify
4396  *             ssl3_SendFinished
4397  *             ssl3_HandleHandshakeMessage
4398  *
4399  * Caller must hold the SSL3HandshakeLock.
4400  * Caller must hold a read or write lock on the Spec R/W lock.
4401  *      (There is presently no way to assert on a Read lock.)
4402  */
4403 static SECStatus
4404 ssl3_ComputeHandshakeHashes(sslSocket *     ss,
4405                             ssl3CipherSpec *spec,   /* uses ->master_secret */
4406                             SSL3Hashes *    hashes, /* output goes here. */
4407                             PRUint32        sender)
4408 {
4409     SECStatus     rv        = SECSuccess;
4410     PRBool        isTLS     = (PRBool)(spec->version > SSL_LIBRARY_VERSION_3_0);
4411     unsigned int  outLength;
4412     SSL3Opaque    md5_inner[MAX_MAC_LENGTH];
4413     SSL3Opaque    sha_inner[MAX_MAC_LENGTH];
4414
4415     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
4416     hashes->hashAlg = SEC_OID_UNKNOWN;
4417
4418 #ifndef NO_PKCS11_BYPASS
4419     if (ss->opt.bypassPKCS11 &&
4420         ss->ssl3.hs.hashType == handshake_hash_single) {
4421         /* compute them without PKCS11 */
4422         PRUint64      sha_cx[MAX_MAC_CONTEXT_LLONGS];
4423
4424         if (!spec->msItem.data) {
4425             PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
4426             return SECFailure;
4427         }
4428
4429         ss->ssl3.hs.sha_clone(sha_cx, ss->ssl3.hs.sha_cx);
4430         ss->ssl3.hs.sha_obj->end(sha_cx, hashes->u.raw, &hashes->len,
4431                                  sizeof(hashes->u.raw));
4432
4433         PRINT_BUF(60, (NULL, "SHA-256: result", hashes->u.raw, hashes->len));
4434
4435         /* If we ever support ciphersuites where the PRF hash isn't SHA-256
4436          * then this will need to be updated. */
4437         hashes->hashAlg = SEC_OID_SHA256;
4438         rv = SECSuccess;
4439     } else if (ss->opt.bypassPKCS11) {
4440         /* compute them without PKCS11 */
4441         PRUint64      md5_cx[MAX_MAC_CONTEXT_LLONGS];
4442         PRUint64      sha_cx[MAX_MAC_CONTEXT_LLONGS];
4443
4444 #define md5cx ((MD5Context *)md5_cx)
4445 #define shacx ((SHA1Context *)sha_cx)
4446
4447         if (!spec->msItem.data) {
4448             PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
4449             return SECFailure;
4450         }
4451
4452         MD5_Clone (md5cx,  (MD5Context *)ss->ssl3.hs.md5_cx);
4453         SHA1_Clone(shacx, (SHA1Context *)ss->ssl3.hs.sha_cx);
4454
4455         if (!isTLS) {
4456             /* compute hashes for SSL3. */
4457             unsigned char s[4];
4458
4459             s[0] = (unsigned char)(sender >> 24);
4460             s[1] = (unsigned char)(sender >> 16);
4461             s[2] = (unsigned char)(sender >> 8);
4462             s[3] = (unsigned char)sender;
4463
4464             if (sender != 0) {
4465                 MD5_Update(md5cx, s, 4);
4466                 PRINT_BUF(95, (NULL, "MD5 inner: sender", s, 4));
4467             }
4468
4469             PRINT_BUF(95, (NULL, "MD5 inner: MAC Pad 1", mac_pad_1, 
4470                             mac_defs[mac_md5].pad_size));
4471
4472             MD5_Update(md5cx, spec->msItem.data, spec->msItem.len);
4473             MD5_Update(md5cx, mac_pad_1, mac_defs[mac_md5].pad_size);
4474             MD5_End(md5cx, md5_inner, &outLength, MD5_LENGTH);
4475
4476             PRINT_BUF(95, (NULL, "MD5 inner: result", md5_inner, outLength));
4477
4478             if (sender != 0) {
4479                 SHA1_Update(shacx, s, 4);
4480                 PRINT_BUF(95, (NULL, "SHA inner: sender", s, 4));
4481             }
4482
4483             PRINT_BUF(95, (NULL, "SHA inner: MAC Pad 1", mac_pad_1, 
4484                             mac_defs[mac_sha].pad_size));
4485
4486             SHA1_Update(shacx, spec->msItem.data, spec->msItem.len);
4487             SHA1_Update(shacx, mac_pad_1, mac_defs[mac_sha].pad_size);
4488             SHA1_End(shacx, sha_inner, &outLength, SHA1_LENGTH);
4489
4490             PRINT_BUF(95, (NULL, "SHA inner: result", sha_inner, outLength));
4491             PRINT_BUF(95, (NULL, "MD5 outer: MAC Pad 2", mac_pad_2, 
4492                             mac_defs[mac_md5].pad_size));
4493             PRINT_BUF(95, (NULL, "MD5 outer: MD5 inner", md5_inner, MD5_LENGTH));
4494
4495             MD5_Begin(md5cx);
4496             MD5_Update(md5cx, spec->msItem.data, spec->msItem.len);
4497             MD5_Update(md5cx, mac_pad_2, mac_defs[mac_md5].pad_size);
4498             MD5_Update(md5cx, md5_inner, MD5_LENGTH);
4499         }
4500         MD5_End(md5cx, hashes->u.s.md5, &outLength, MD5_LENGTH);
4501
4502         PRINT_BUF(60, (NULL, "MD5 outer: result", hashes->u.s.md5, MD5_LENGTH));
4503
4504         if (!isTLS) {
4505             PRINT_BUF(95, (NULL, "SHA outer: MAC Pad 2", mac_pad_2, 
4506                             mac_defs[mac_sha].pad_size));
4507             PRINT_BUF(95, (NULL, "SHA outer: SHA inner", sha_inner, SHA1_LENGTH));
4508
4509             SHA1_Begin(shacx);
4510             SHA1_Update(shacx, spec->msItem.data, spec->msItem.len);
4511             SHA1_Update(shacx, mac_pad_2, mac_defs[mac_sha].pad_size);
4512             SHA1_Update(shacx, sha_inner, SHA1_LENGTH);
4513         }
4514         SHA1_End(shacx, hashes->u.s.sha, &outLength, SHA1_LENGTH);
4515
4516         PRINT_BUF(60, (NULL, "SHA outer: result", hashes->u.s.sha, SHA1_LENGTH));
4517
4518         hashes->len = MD5_LENGTH + SHA1_LENGTH;
4519         rv = SECSuccess;
4520 #undef md5cx
4521 #undef shacx
4522     } else 
4523 #endif
4524     if (ss->ssl3.hs.hashType == handshake_hash_single) {
4525         /* compute hashes with PKCS11 */
4526         PK11Context *h;
4527         unsigned int  stateLen;
4528         unsigned char stackBuf[1024];
4529         unsigned char *stateBuf = NULL;
4530
4531         if (!spec->master_secret) {
4532             PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
4533             return SECFailure;
4534         }
4535
4536         h = ss->ssl3.hs.sha;
4537         stateBuf = PK11_SaveContextAlloc(h, stackBuf,
4538                                          sizeof(stackBuf), &stateLen);
4539         if (stateBuf == NULL) {
4540             ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4541             goto tls12_loser;
4542         }
4543         rv |= PK11_DigestFinal(h, hashes->u.raw, &hashes->len,
4544                                sizeof(hashes->u.raw));
4545         if (rv != SECSuccess) {
4546             ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4547             rv = SECFailure;
4548             goto tls12_loser;
4549         }
4550         /* If we ever support ciphersuites where the PRF hash isn't SHA-256
4551          * then this will need to be updated. */
4552         hashes->hashAlg = SEC_OID_SHA256;
4553         rv = SECSuccess;
4554
4555 tls12_loser:
4556         if (stateBuf) {
4557             if (PK11_RestoreContext(h, stateBuf, stateLen) != SECSuccess) {
4558                 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4559                 rv = SECFailure;
4560             }
4561             if (stateBuf != stackBuf) {
4562                 PORT_ZFree(stateBuf, stateLen);
4563             }
4564         }
4565     } else {
4566         /* compute hashes with PKCS11 */
4567         PK11Context * md5;
4568         PK11Context * sha       = NULL;
4569         unsigned char *md5StateBuf = NULL;
4570         unsigned char *shaStateBuf = NULL;
4571         unsigned int  md5StateLen, shaStateLen;
4572         unsigned char md5StackBuf[256];
4573         unsigned char shaStackBuf[512];
4574
4575         if (!spec->master_secret) {
4576             PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
4577             return SECFailure;
4578         }
4579
4580         md5StateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.md5, md5StackBuf,
4581                                             sizeof md5StackBuf, &md5StateLen);
4582         if (md5StateBuf == NULL) {
4583             ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4584             goto loser;
4585         }
4586         md5 = ss->ssl3.hs.md5;
4587
4588         shaStateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.sha, shaStackBuf,
4589                                             sizeof shaStackBuf, &shaStateLen);
4590         if (shaStateBuf == NULL) {
4591             ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4592             goto loser;
4593         }
4594         sha = ss->ssl3.hs.sha;
4595
4596         if (!isTLS) {
4597             /* compute hashes for SSL3. */
4598             unsigned char s[4];
4599
4600             s[0] = (unsigned char)(sender >> 24);
4601             s[1] = (unsigned char)(sender >> 16);
4602             s[2] = (unsigned char)(sender >> 8);
4603             s[3] = (unsigned char)sender;
4604
4605             if (sender != 0) {
4606                 rv |= PK11_DigestOp(md5, s, 4);
4607                 PRINT_BUF(95, (NULL, "MD5 inner: sender", s, 4));
4608             }
4609
4610             PRINT_BUF(95, (NULL, "MD5 inner: MAC Pad 1", mac_pad_1, 
4611                           mac_defs[mac_md5].pad_size));
4612
4613             rv |= PK11_DigestKey(md5,spec->master_secret);
4614             rv |= PK11_DigestOp(md5, mac_pad_1, mac_defs[mac_md5].pad_size);
4615             rv |= PK11_DigestFinal(md5, md5_inner, &outLength, MD5_LENGTH);
4616             PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH);
4617             if (rv != SECSuccess) {
4618                 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4619                 rv = SECFailure;
4620                 goto loser;
4621             }
4622
4623             PRINT_BUF(95, (NULL, "MD5 inner: result", md5_inner, outLength));
4624
4625             if (sender != 0) {
4626                 rv |= PK11_DigestOp(sha, s, 4);
4627                 PRINT_BUF(95, (NULL, "SHA inner: sender", s, 4));
4628             }
4629
4630             PRINT_BUF(95, (NULL, "SHA inner: MAC Pad 1", mac_pad_1, 
4631                           mac_defs[mac_sha].pad_size));
4632
4633             rv |= PK11_DigestKey(sha, spec->master_secret);
4634             rv |= PK11_DigestOp(sha, mac_pad_1, mac_defs[mac_sha].pad_size);
4635             rv |= PK11_DigestFinal(sha, sha_inner, &outLength, SHA1_LENGTH);
4636             PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH);
4637             if (rv != SECSuccess) {
4638                 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4639                 rv = SECFailure;
4640                 goto loser;
4641             }
4642
4643             PRINT_BUF(95, (NULL, "SHA inner: result", sha_inner, outLength));
4644
4645             PRINT_BUF(95, (NULL, "MD5 outer: MAC Pad 2", mac_pad_2, 
4646                           mac_defs[mac_md5].pad_size));
4647             PRINT_BUF(95, (NULL, "MD5 outer: MD5 inner", md5_inner, MD5_LENGTH));
4648
4649             rv |= PK11_DigestBegin(md5);
4650             rv |= PK11_DigestKey(md5, spec->master_secret);
4651             rv |= PK11_DigestOp(md5, mac_pad_2, mac_defs[mac_md5].pad_size);
4652             rv |= PK11_DigestOp(md5, md5_inner, MD5_LENGTH);
4653         }
4654         rv |= PK11_DigestFinal(md5, hashes->u.s.md5, &outLength, MD5_LENGTH);
4655         PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH);
4656         if (rv != SECSuccess) {
4657             ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4658             rv = SECFailure;
4659             goto loser;
4660         }
4661
4662         PRINT_BUF(60, (NULL, "MD5 outer: result", hashes->u.s.md5, MD5_LENGTH));
4663
4664         if (!isTLS) {
4665             PRINT_BUF(95, (NULL, "SHA outer: MAC Pad 2", mac_pad_2, 
4666                           mac_defs[mac_sha].pad_size));
4667             PRINT_BUF(95, (NULL, "SHA outer: SHA inner", sha_inner, SHA1_LENGTH));
4668
4669             rv |= PK11_DigestBegin(sha);
4670             rv |= PK11_DigestKey(sha,spec->master_secret);
4671             rv |= PK11_DigestOp(sha, mac_pad_2, mac_defs[mac_sha].pad_size);
4672             rv |= PK11_DigestOp(sha, sha_inner, SHA1_LENGTH);
4673         }
4674         rv |= PK11_DigestFinal(sha, hashes->u.s.sha, &outLength, SHA1_LENGTH);
4675         PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH);
4676         if (rv != SECSuccess) {
4677             ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4678             rv = SECFailure;
4679             goto loser;
4680         }
4681
4682         PRINT_BUF(60, (NULL, "SHA outer: result", hashes->u.s.sha, SHA1_LENGTH));
4683
4684         hashes->len = MD5_LENGTH + SHA1_LENGTH;
4685         rv = SECSuccess;
4686
4687     loser:
4688         if (md5StateBuf) {
4689             if (PK11_RestoreContext(ss->ssl3.hs.md5, md5StateBuf, md5StateLen)
4690                  != SECSuccess) 
4691             {
4692                 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4693                 rv = SECFailure;
4694             }
4695             if (md5StateBuf != md5StackBuf) {
4696                 PORT_ZFree(md5StateBuf, md5StateLen);
4697             }
4698         }
4699         if (shaStateBuf) {
4700             if (PK11_RestoreContext(ss->ssl3.hs.sha, shaStateBuf, shaStateLen)
4701                  != SECSuccess) 
4702             {
4703                 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4704                 rv = SECFailure;
4705             }
4706             if (shaStateBuf != shaStackBuf) {
4707                 PORT_ZFree(shaStateBuf, shaStateLen);
4708             }
4709         }
4710     }
4711     return rv;
4712 }
4713
4714 /*
4715  * SSL 2 based implementations pass in the initial outbound buffer
4716  * so that the handshake hash can contain the included information.
4717  *
4718  * Called from ssl2_BeginClientHandshake() in sslcon.c
4719  */
4720 SECStatus
4721 ssl3_StartHandshakeHash(sslSocket *ss, unsigned char * buf, int length)
4722 {
4723     SECStatus rv;
4724
4725     ssl_GetSSL3HandshakeLock(ss);  /**************************************/
4726
4727     rv = ssl3_InitState(ss);
4728     if (rv != SECSuccess) {
4729         goto done;              /* ssl3_InitState has set the error code. */
4730     }
4731     rv = ssl3_RestartHandshakeHashes(ss);
4732     if (rv != SECSuccess) {
4733         goto done;
4734     }
4735
4736     PORT_Memset(&ss->ssl3.hs.client_random, 0, SSL3_RANDOM_LENGTH);
4737     PORT_Memcpy(
4738         &ss->ssl3.hs.client_random.rand[SSL3_RANDOM_LENGTH - SSL_CHALLENGE_BYTES],
4739         &ss->sec.ci.clientChallenge,
4740         SSL_CHALLENGE_BYTES);
4741
4742     rv = ssl3_UpdateHandshakeHashes(ss, buf, length);
4743     /* if it failed, ssl3_UpdateHandshakeHashes has set the error code. */
4744
4745 done:
4746     ssl_ReleaseSSL3HandshakeLock(ss);  /**************************************/
4747     return rv;
4748 }
4749
4750 /**************************************************************************
4751  * end of Handshake Hash functions.
4752  * Begin Send and Handle functions for handshakes.
4753  **************************************************************************/
4754
4755 /* Called from ssl3_HandleHelloRequest(),
4756  *             ssl3_RedoHandshake()
4757  *             ssl2_BeginClientHandshake (when resuming ssl3 session)
4758  *             dtls_HandleHelloVerifyRequest(with resending=PR_TRUE)
4759  */
4760 SECStatus
4761 ssl3_SendClientHello(sslSocket *ss, PRBool resending)
4762 {
4763     sslSessionID *   sid;
4764     ssl3CipherSpec * cwSpec;
4765     SECStatus        rv;
4766     int              i;
4767     int              length;
4768     int              num_suites;
4769     int              actual_count = 0;
4770     PRBool           isTLS = PR_FALSE;
4771     PRBool           requestingResume = PR_FALSE;
4772     PRInt32          total_exten_len = 0;
4773     unsigned         numCompressionMethods;
4774     PRInt32          flags;
4775
4776     SSL_TRC(3, ("%d: SSL3[%d]: send client_hello handshake", SSL_GETPID(),
4777                 ss->fd));
4778
4779     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
4780     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
4781
4782     rv = ssl3_InitState(ss);
4783     if (rv != SECSuccess) {
4784         return rv;              /* ssl3_InitState has set the error code. */
4785     }
4786     ss->ssl3.hs.sendingSCSV = PR_FALSE; /* Must be reset every handshake */
4787     PORT_Assert(IS_DTLS(ss) || !resending);
4788
4789     /* We might be starting a session renegotiation in which case we should
4790      * clear previous state.
4791      */
4792     PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData));
4793
4794     rv = ssl3_RestartHandshakeHashes(ss);
4795     if (rv != SECSuccess) {
4796         return rv;
4797     }
4798
4799     /*
4800      * During a renegotiation, ss->clientHelloVersion will be used again to
4801      * work around a Windows SChannel bug. Ensure that it is still enabled.
4802      */
4803     if (ss->firstHsDone) {
4804         if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
4805             PORT_SetError(SSL_ERROR_SSL_DISABLED);
4806             return SECFailure;
4807         }
4808
4809         if (ss->clientHelloVersion < ss->vrange.min ||
4810             ss->clientHelloVersion > ss->vrange.max) {
4811             PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
4812             return SECFailure;
4813         }
4814     }
4815
4816     /* We ignore ss->sec.ci.sid here, and use ssl_Lookup because Lookup
4817      * handles expired entries and other details.
4818      * XXX If we've been called from ssl2_BeginClientHandshake, then
4819      * this lookup is duplicative and wasteful.
4820      */
4821     sid = (ss->opt.noCache) ? NULL
4822             : ssl_LookupSID(&ss->sec.ci.peer, ss->sec.ci.port, ss->peerID, ss->url);
4823
4824     /* We can't resume based on a different token. If the sid exists,
4825      * make sure the token that holds the master secret still exists ...
4826      * If we previously did client-auth, make sure that the token that holds
4827      * the private key still exists, is logged in, hasn't been removed, etc.
4828      */
4829     if (sid) {
4830         PRBool sidOK = PR_TRUE;
4831         if (sid->u.ssl3.keys.msIsWrapped) {
4832             /* Session key was wrapped, which means it was using PKCS11, */
4833             PK11SlotInfo *slot = NULL;
4834             if (sid->u.ssl3.masterValid && !ss->opt.bypassPKCS11) {
4835                 slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID,
4836                                          sid->u.ssl3.masterSlotID);
4837             }
4838             if (slot == NULL) {
4839                sidOK = PR_FALSE;
4840             } else {
4841                 PK11SymKey *wrapKey = NULL;
4842                 if (!PK11_IsPresent(slot) ||
4843                     ((wrapKey = PK11_GetWrapKey(slot, 
4844                                                 sid->u.ssl3.masterWrapIndex,
4845                                                 sid->u.ssl3.masterWrapMech,
4846                                                 sid->u.ssl3.masterWrapSeries,
4847                                                 ss->pkcs11PinArg)) == NULL) ) {
4848                     sidOK = PR_FALSE;
4849                 }
4850                 if (wrapKey) PK11_FreeSymKey(wrapKey);
4851                 PK11_FreeSlot(slot);
4852                 slot = NULL;
4853             }
4854         }
4855         /* If we previously did client-auth, make sure that the token that
4856         ** holds the private key still exists, is logged in, hasn't been
4857         ** removed, etc.
4858         */
4859         if (sidOK && !ssl3_ClientAuthTokenPresent(sid)) {
4860             sidOK = PR_FALSE;
4861         }
4862
4863         /* TLS 1.0 (RFC 2246) Appendix E says:
4864          *   Whenever a client already knows the highest protocol known to
4865          *   a server (for example, when resuming a session), it should
4866          *   initiate the connection in that native protocol.
4867          * So we pass sid->version to ssl3_NegotiateVersion() here, except
4868          * when renegotiating.
4869          *
4870          * Windows SChannel compares the client_version inside the RSA
4871          * EncryptedPreMasterSecret of a renegotiation with the
4872          * client_version of the initial ClientHello rather than the
4873          * ClientHello in the renegotiation. To work around this bug, we
4874          * continue to use the client_version used in the initial
4875          * ClientHello when renegotiating.
4876          */
4877         if (sidOK) {
4878             if (ss->firstHsDone) {
4879                 /*
4880                  * The client_version of the initial ClientHello is still
4881                  * available in ss->clientHelloVersion. Ensure that
4882                  * sid->version is bounded within
4883                  * [ss->vrange.min, ss->clientHelloVersion], otherwise we
4884                  * can't use sid.
4885                  */
4886                 if (sid->version >= ss->vrange.min &&
4887                     sid->version <= ss->clientHelloVersion) {
4888                     ss->version = ss->clientHelloVersion;
4889                 } else {
4890                     sidOK = PR_FALSE;
4891                 }
4892             } else {
4893                 if (ssl3_NegotiateVersion(ss, sid->version,
4894                                           PR_FALSE) != SECSuccess) {
4895                     sidOK = PR_FALSE;
4896                 }
4897             }
4898         }
4899
4900         if (!sidOK) {
4901             SSL_AtomicIncrementLong(& ssl3stats.sch_sid_cache_not_ok );
4902             if (ss->sec.uncache)
4903                 (*ss->sec.uncache)(sid);
4904             ssl_FreeSID(sid);
4905             sid = NULL;
4906         }
4907     }
4908
4909     if (sid) {
4910         requestingResume = PR_TRUE;
4911         SSL_AtomicIncrementLong(& ssl3stats.sch_sid_cache_hits );
4912
4913         /* Are we attempting a stateless session resume? */
4914         if (sid->version > SSL_LIBRARY_VERSION_3_0 &&
4915             sid->u.ssl3.sessionTicket.ticket.data)
4916             SSL_AtomicIncrementLong(& ssl3stats.sch_sid_stateless_resumes );
4917
4918         PRINT_BUF(4, (ss, "client, found session-id:", sid->u.ssl3.sessionID,
4919                       sid->u.ssl3.sessionIDLength));
4920
4921         ss->ssl3.policy = sid->u.ssl3.policy;
4922     } else {
4923         SSL_AtomicIncrementLong(& ssl3stats.sch_sid_cache_misses );
4924
4925         /*
4926          * Windows SChannel compares the client_version inside the RSA
4927          * EncryptedPreMasterSecret of a renegotiation with the
4928          * client_version of the initial ClientHello rather than the
4929          * ClientHello in the renegotiation. To work around this bug, we
4930          * continue to use the client_version used in the initial
4931          * ClientHello when renegotiating.
4932          */
4933         if (ss->firstHsDone) {
4934             ss->version = ss->clientHelloVersion;
4935         } else {
4936             rv = ssl3_NegotiateVersion(ss, SSL_LIBRARY_VERSION_MAX_SUPPORTED,
4937                                        PR_TRUE);
4938             if (rv != SECSuccess)
4939                 return rv;      /* error code was set */
4940         }
4941
4942         sid = ssl3_NewSessionID(ss, PR_FALSE);
4943         if (!sid) {
4944             return SECFailure;  /* memory error is set */
4945         }
4946     }
4947
4948     isTLS = (ss->version > SSL_LIBRARY_VERSION_3_0);
4949     ssl_GetSpecWriteLock(ss);
4950     cwSpec = ss->ssl3.cwSpec;
4951     if (cwSpec->mac_def->mac == mac_null) {
4952         /* SSL records are not being MACed. */
4953         cwSpec->version = ss->version;
4954     }
4955     ssl_ReleaseSpecWriteLock(ss);
4956
4957     if (ss->sec.ci.sid != NULL) {
4958         ssl_FreeSID(ss->sec.ci.sid);    /* decrement ref count, free if zero */
4959     }
4960     ss->sec.ci.sid = sid;
4961
4962     ss->sec.send = ssl3_SendApplicationData;
4963
4964     /* shouldn't get here if SSL3 is disabled, but ... */
4965     if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
4966         PR_NOT_REACHED("No versions of SSL 3.0 or later are enabled");
4967         PORT_SetError(SSL_ERROR_SSL_DISABLED);
4968         return SECFailure;
4969     }
4970
4971     /* how many suites does our PKCS11 support (regardless of policy)? */
4972     num_suites = ssl3_config_match_init(ss);
4973     if (!num_suites)
4974         return SECFailure;      /* ssl3_config_match_init has set error code. */
4975
4976     /* HACK for SCSV in SSL 3.0.  On initial handshake, prepend SCSV,
4977      * only if we're willing to complete an SSL 3.0 handshake.
4978      */
4979     if (!ss->firstHsDone && ss->vrange.min == SSL_LIBRARY_VERSION_3_0) {
4980         /* Must set this before calling Hello Extension Senders, 
4981          * to suppress sending of empty RI extension.
4982          */
4983         ss->ssl3.hs.sendingSCSV = PR_TRUE;
4984     }
4985
4986     if (isTLS || (ss->firstHsDone && ss->peerRequestedProtection)) {
4987         PRUint32 maxBytes = 65535; /* 2^16 - 1 */
4988         PRInt32  extLen;
4989
4990         extLen = ssl3_CallHelloExtensionSenders(ss, PR_FALSE, maxBytes, NULL);
4991         if (extLen < 0) {
4992             return SECFailure;
4993         }
4994         maxBytes        -= extLen;
4995         total_exten_len += extLen;
4996
4997         if (total_exten_len > 0)
4998             total_exten_len += 2;
4999     }
5000
5001 #if defined(NSS_ENABLE_ECC)
5002     if (!total_exten_len || !isTLS) {
5003         /* not sending the elliptic_curves and ec_point_formats extensions */
5004         ssl3_DisableECCSuites(ss, NULL); /* disable all ECC suites */
5005     }
5006 #endif
5007
5008     if (IS_DTLS(ss)) {
5009         ssl3_DisableNonDTLSSuites(ss);
5010     }
5011
5012     /* how many suites are permitted by policy and user preference? */
5013     num_suites = count_cipher_suites(ss, ss->ssl3.policy, PR_TRUE);
5014     if (!num_suites)
5015         return SECFailure;      /* count_cipher_suites has set error code. */
5016     if (ss->ssl3.hs.sendingSCSV) {
5017         ++num_suites;   /* make room for SCSV */
5018     }
5019
5020     /* count compression methods */
5021     numCompressionMethods = 0;
5022     for (i = 0; i < compressionMethodsCount; i++) {
5023         if (compressionEnabled(ss, compressions[i]))
5024             numCompressionMethods++;
5025     }
5026
5027     length = sizeof(SSL3ProtocolVersion) + SSL3_RANDOM_LENGTH +
5028         1 + ((sid == NULL) ? 0 : sid->u.ssl3.sessionIDLength) +
5029         2 + num_suites*sizeof(ssl3CipherSuite) +
5030         1 + numCompressionMethods + total_exten_len;
5031     if (IS_DTLS(ss)) {
5032         length += 1 + ss->ssl3.hs.cookieLen;
5033     }
5034
5035     rv = ssl3_AppendHandshakeHeader(ss, client_hello, length);
5036     if (rv != SECSuccess) {
5037         return rv;      /* err set by ssl3_AppendHandshake* */
5038     }
5039
5040     if (ss->firstHsDone) {
5041         /* The client hello version must stay unchanged to work around
5042          * the Windows SChannel bug described above. */
5043         PORT_Assert(ss->version == ss->clientHelloVersion);
5044     }
5045     ss->clientHelloVersion = ss->version;
5046     if (IS_DTLS(ss)) {
5047         PRUint16 version;
5048
5049         version = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion);
5050         rv = ssl3_AppendHandshakeNumber(ss, version, 2);
5051     } else {
5052         rv = ssl3_AppendHandshakeNumber(ss, ss->clientHelloVersion, 2);
5053     }
5054     if (rv != SECSuccess) {
5055         return rv;      /* err set by ssl3_AppendHandshake* */
5056     }
5057
5058     if (!resending) { /* Don't re-generate if we are in DTLS re-sending mode */
5059         rv = ssl3_GetNewRandom(&ss->ssl3.hs.client_random);
5060         if (rv != SECSuccess) {
5061             return rv;  /* err set by GetNewRandom. */
5062         }
5063     }
5064     rv = ssl3_AppendHandshake(ss, &ss->ssl3.hs.client_random,
5065                               SSL3_RANDOM_LENGTH);
5066     if (rv != SECSuccess) {
5067         return rv;      /* err set by ssl3_AppendHandshake* */
5068     }
5069
5070     if (sid)
5071         rv = ssl3_AppendHandshakeVariable(
5072             ss, sid->u.ssl3.sessionID, sid->u.ssl3.sessionIDLength, 1);
5073     else
5074         rv = ssl3_AppendHandshakeVariable(ss, NULL, 0, 1);
5075     if (rv != SECSuccess) {
5076         return rv;      /* err set by ssl3_AppendHandshake* */
5077     }
5078
5079     if (IS_DTLS(ss)) {
5080         rv = ssl3_AppendHandshakeVariable(
5081             ss, ss->ssl3.hs.cookie, ss->ssl3.hs.cookieLen, 1);
5082         if (rv != SECSuccess) {
5083             return rv;  /* err set by ssl3_AppendHandshake* */
5084         }
5085     }
5086
5087     rv = ssl3_AppendHandshakeNumber(ss, num_suites*sizeof(ssl3CipherSuite), 2);
5088     if (rv != SECSuccess) {
5089         return rv;      /* err set by ssl3_AppendHandshake* */
5090     }
5091
5092     if (ss->ssl3.hs.sendingSCSV) {
5093         /* Add the actual SCSV */
5094         rv = ssl3_AppendHandshakeNumber(ss, TLS_EMPTY_RENEGOTIATION_INFO_SCSV,
5095                                         sizeof(ssl3CipherSuite));
5096         if (rv != SECSuccess) {
5097             return rv;  /* err set by ssl3_AppendHandshake* */
5098         }
5099         actual_count++;
5100     }
5101     for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
5102         ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i];
5103         if (config_match(suite, ss->ssl3.policy, PR_TRUE, &ss->vrange)) {
5104             actual_count++;
5105             if (actual_count > num_suites) {
5106                 /* set error card removal/insertion error */
5107                 PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
5108                 return SECFailure;
5109             }
5110             rv = ssl3_AppendHandshakeNumber(ss, suite->cipher_suite,
5111                                             sizeof(ssl3CipherSuite));
5112             if (rv != SECSuccess) {
5113                 return rv;      /* err set by ssl3_AppendHandshake* */
5114             }
5115         }
5116     }
5117
5118     /* if cards were removed or inserted between count_cipher_suites and
5119      * generating our list, detect the error here rather than send it off to
5120      * the server.. */
5121     if (actual_count != num_suites) {
5122         /* Card removal/insertion error */
5123         PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
5124         return SECFailure;
5125     }
5126
5127     rv = ssl3_AppendHandshakeNumber(ss, numCompressionMethods, 1);
5128     if (rv != SECSuccess) {
5129         return rv;      /* err set by ssl3_AppendHandshake* */
5130     }
5131     for (i = 0; i < compressionMethodsCount; i++) {
5132         if (!compressionEnabled(ss, compressions[i]))
5133             continue;
5134         rv = ssl3_AppendHandshakeNumber(ss, compressions[i], 1);
5135         if (rv != SECSuccess) {
5136             return rv;  /* err set by ssl3_AppendHandshake* */
5137         }
5138     }
5139
5140     if (total_exten_len) {
5141         PRUint32 maxBytes = total_exten_len - 2;
5142         PRInt32  extLen;
5143
5144         rv = ssl3_AppendHandshakeNumber(ss, maxBytes, 2);
5145         if (rv != SECSuccess) {
5146             return rv;  /* err set by AppendHandshake. */
5147         }
5148
5149         extLen = ssl3_CallHelloExtensionSenders(ss, PR_TRUE, maxBytes, NULL);
5150         if (extLen < 0) {
5151             return SECFailure;
5152         }
5153         maxBytes -= extLen;
5154         PORT_Assert(!maxBytes);
5155     } 
5156     if (ss->ssl3.hs.sendingSCSV) {
5157         /* Since we sent the SCSV, pretend we sent empty RI extension. */
5158         TLSExtensionData *xtnData = &ss->xtnData;
5159         xtnData->advertised[xtnData->numAdvertised++] = 
5160             ssl_renegotiation_info_xtn;
5161     }
5162
5163     flags = 0;
5164     if (!ss->firstHsDone && !requestingResume && !IS_DTLS(ss)) {
5165         flags |= ssl_SEND_FLAG_CAP_RECORD_VERSION;
5166     }
5167     rv = ssl3_FlushHandshake(ss, flags);
5168     if (rv != SECSuccess) {
5169         return rv;      /* error code set by ssl3_FlushHandshake */
5170     }
5171
5172     ss->ssl3.hs.ws = wait_server_hello;
5173     return rv;
5174 }
5175
5176
5177 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
5178  * ssl3 Hello Request.
5179  * Caller must hold Handshake and RecvBuf locks.
5180  */
5181 static SECStatus
5182 ssl3_HandleHelloRequest(sslSocket *ss)
5183 {
5184     sslSessionID *sid = ss->sec.ci.sid;
5185     SECStatus     rv;
5186
5187     SSL_TRC(3, ("%d: SSL3[%d]: handle hello_request handshake",
5188                 SSL_GETPID(), ss->fd));
5189
5190     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
5191     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
5192
5193     if (ss->ssl3.hs.ws == wait_server_hello)
5194         return SECSuccess;
5195     if (ss->ssl3.hs.ws != idle_handshake || ss->sec.isServer) {
5196         (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
5197         PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST);
5198         return SECFailure;
5199     }
5200     if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) {
5201         ssl_GetXmitBufLock(ss);
5202         rv = SSL3_SendAlert(ss, alert_warning, no_renegotiation);
5203         ssl_ReleaseXmitBufLock(ss);
5204         PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED);
5205         return SECFailure;
5206     }
5207
5208     if (sid) {
5209         if (ss->sec.uncache)
5210             ss->sec.uncache(sid);
5211         ssl_FreeSID(sid);
5212         ss->sec.ci.sid = NULL;
5213     }
5214
5215     if (IS_DTLS(ss)) {
5216         dtls_RehandshakeCleanup(ss);
5217     }
5218
5219     ssl_GetXmitBufLock(ss);
5220     rv = ssl3_SendClientHello(ss, PR_FALSE);
5221     ssl_ReleaseXmitBufLock(ss);
5222
5223     return rv;
5224 }
5225
5226 #define UNKNOWN_WRAP_MECHANISM 0x7fffffff
5227
5228 static const CK_MECHANISM_TYPE wrapMechanismList[SSL_NUM_WRAP_MECHS] = {
5229     CKM_DES3_ECB,
5230     CKM_CAST5_ECB,
5231     CKM_DES_ECB,
5232     CKM_KEY_WRAP_LYNKS,
5233     CKM_IDEA_ECB,
5234     CKM_CAST3_ECB,
5235     CKM_CAST_ECB,
5236     CKM_RC5_ECB,
5237     CKM_RC2_ECB,
5238     CKM_CDMF_ECB,
5239     CKM_SKIPJACK_WRAP,
5240     CKM_SKIPJACK_CBC64,
5241     CKM_AES_ECB,
5242     CKM_CAMELLIA_ECB,
5243     CKM_SEED_ECB,
5244     UNKNOWN_WRAP_MECHANISM
5245 };
5246
5247 static int
5248 ssl_FindIndexByWrapMechanism(CK_MECHANISM_TYPE mech)
5249 {
5250     const CK_MECHANISM_TYPE *pMech = wrapMechanismList;
5251
5252     while (mech != *pMech && *pMech != UNKNOWN_WRAP_MECHANISM) {
5253         ++pMech;
5254     }
5255     return (*pMech == UNKNOWN_WRAP_MECHANISM) ? -1
5256                                               : (pMech - wrapMechanismList);
5257 }
5258
5259 static PK11SymKey *
5260 ssl_UnwrapSymWrappingKey(
5261         SSLWrappedSymWrappingKey *pWswk,
5262         SECKEYPrivateKey *        svrPrivKey,
5263         SSL3KEAType               exchKeyType,
5264         CK_MECHANISM_TYPE         masterWrapMech,
5265         void *                    pwArg)
5266 {
5267     PK11SymKey *             unwrappedWrappingKey  = NULL;
5268     SECItem                  wrappedKey;
5269 #ifdef NSS_ENABLE_ECC
5270     PK11SymKey *             Ks;
5271     SECKEYPublicKey          pubWrapKey;
5272     ECCWrappedKeyInfo        *ecWrapped;
5273 #endif /* NSS_ENABLE_ECC */
5274
5275     /* found the wrapping key on disk. */
5276     PORT_Assert(pWswk->symWrapMechanism == masterWrapMech);
5277     PORT_Assert(pWswk->exchKeyType      == exchKeyType);
5278     if (pWswk->symWrapMechanism != masterWrapMech ||
5279         pWswk->exchKeyType      != exchKeyType) {
5280         goto loser;
5281     }
5282     wrappedKey.type = siBuffer;
5283     wrappedKey.data = pWswk->wrappedSymmetricWrappingkey;
5284     wrappedKey.len  = pWswk->wrappedSymKeyLen;
5285     PORT_Assert(wrappedKey.len <= sizeof pWswk->wrappedSymmetricWrappingkey);
5286
5287     switch (exchKeyType) {
5288
5289     case kt_rsa:
5290         unwrappedWrappingKey =
5291             PK11_PubUnwrapSymKey(svrPrivKey, &wrappedKey,
5292                                  masterWrapMech, CKA_UNWRAP, 0);
5293         break;
5294
5295 #ifdef NSS_ENABLE_ECC
5296     case kt_ecdh:
5297         /* 
5298          * For kt_ecdh, we first create an EC public key based on
5299          * data stored with the wrappedSymmetricWrappingkey. Next,
5300          * we do an ECDH computation involving this public key and
5301          * the SSL server's (long-term) EC private key. The resulting
5302          * shared secret is treated the same way as Fortezza's Ks, i.e.,
5303          * it is used to recover the symmetric wrapping key.
5304          *
5305          * The data in wrappedSymmetricWrappingkey is laid out as defined
5306          * in the ECCWrappedKeyInfo structure.
5307          */
5308         ecWrapped = (ECCWrappedKeyInfo *) pWswk->wrappedSymmetricWrappingkey;
5309
5310         PORT_Assert(ecWrapped->encodedParamLen + ecWrapped->pubValueLen + 
5311             ecWrapped->wrappedKeyLen <= MAX_EC_WRAPPED_KEY_BUFLEN);
5312
5313         if (ecWrapped->encodedParamLen + ecWrapped->pubValueLen + 
5314             ecWrapped->wrappedKeyLen > MAX_EC_WRAPPED_KEY_BUFLEN) {
5315             PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
5316             goto loser;
5317         }
5318
5319         pubWrapKey.keyType = ecKey;
5320         pubWrapKey.u.ec.size = ecWrapped->size;
5321         pubWrapKey.u.ec.DEREncodedParams.len = ecWrapped->encodedParamLen;
5322         pubWrapKey.u.ec.DEREncodedParams.data = ecWrapped->var;
5323         pubWrapKey.u.ec.publicValue.len = ecWrapped->pubValueLen;
5324         pubWrapKey.u.ec.publicValue.data = ecWrapped->var + 
5325             ecWrapped->encodedParamLen;
5326
5327         wrappedKey.len  = ecWrapped->wrappedKeyLen;
5328         wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen + 
5329             ecWrapped->pubValueLen;
5330         
5331         /* Derive Ks using ECDH */
5332         Ks = PK11_PubDeriveWithKDF(svrPrivKey, &pubWrapKey, PR_FALSE, NULL,
5333                                    NULL, CKM_ECDH1_DERIVE, masterWrapMech, 
5334                                    CKA_DERIVE, 0, CKD_NULL, NULL, NULL);
5335         if (Ks == NULL) {
5336             goto loser;
5337         }
5338
5339         /*  Use Ks to unwrap the wrapping key */
5340         unwrappedWrappingKey = PK11_UnwrapSymKey(Ks, masterWrapMech, NULL, 
5341                                                  &wrappedKey, masterWrapMech, 
5342                                                  CKA_UNWRAP, 0);
5343         PK11_FreeSymKey(Ks);
5344         
5345         break;
5346 #endif
5347
5348     default:
5349         /* Assert? */
5350         SET_ERROR_CODE
5351         goto loser;
5352     }
5353 loser:
5354     return unwrappedWrappingKey;
5355 }
5356
5357 /* Each process sharing the server session ID cache has its own array of
5358  * SymKey pointers for the symmetric wrapping keys that are used to wrap
5359  * the master secrets.  There is one key for each KEA type.  These Symkeys
5360  * correspond to the wrapped SymKeys kept in the server session cache.
5361  */
5362
5363 typedef struct {
5364     PK11SymKey *      symWrapKey[kt_kea_size];
5365 } ssl3SymWrapKey;
5366
5367 static PZLock *          symWrapKeysLock = NULL;
5368 static ssl3SymWrapKey    symWrapKeys[SSL_NUM_WRAP_MECHS];
5369
5370 SECStatus ssl_FreeSymWrapKeysLock(void)
5371 {
5372     if (symWrapKeysLock) {
5373         PZ_DestroyLock(symWrapKeysLock);
5374         symWrapKeysLock = NULL;
5375         return SECSuccess;
5376     }
5377     PORT_SetError(SEC_ERROR_NOT_INITIALIZED);
5378     return SECFailure;
5379 }
5380
5381 SECStatus
5382 SSL3_ShutdownServerCache(void)
5383 {
5384     int             i, j;
5385
5386     if (!symWrapKeysLock)
5387         return SECSuccess;      /* lock was never initialized */
5388     PZ_Lock(symWrapKeysLock);
5389     /* get rid of all symWrapKeys */
5390     for (i = 0; i < SSL_NUM_WRAP_MECHS; ++i) {
5391         for (j = 0; j < kt_kea_size; ++j) {
5392             PK11SymKey **   pSymWrapKey;
5393             pSymWrapKey = &symWrapKeys[i].symWrapKey[j];
5394             if (*pSymWrapKey) {
5395                 PK11_FreeSymKey(*pSymWrapKey);
5396                 *pSymWrapKey = NULL;
5397             }
5398         }
5399     }
5400
5401     PZ_Unlock(symWrapKeysLock);
5402     ssl_FreeSessionCacheLocks();
5403     return SECSuccess;
5404 }
5405
5406 SECStatus ssl_InitSymWrapKeysLock(void)
5407 {
5408     symWrapKeysLock = PZ_NewLock(nssILockOther);
5409     return symWrapKeysLock ? SECSuccess : SECFailure;
5410 }
5411
5412 /* Try to get wrapping key for mechanism from in-memory array.
5413  * If that fails, look for one on disk.
5414  * If that fails, generate a new one, put the new one on disk,
5415  * Put the new key in the in-memory array.
5416  */
5417 static PK11SymKey *
5418 getWrappingKey( sslSocket *       ss,
5419                 PK11SlotInfo *    masterSecretSlot,
5420                 SSL3KEAType       exchKeyType,
5421                 CK_MECHANISM_TYPE masterWrapMech,
5422                 void *            pwArg)
5423 {
5424     SECKEYPrivateKey *       svrPrivKey;
5425     SECKEYPublicKey *        svrPubKey             = NULL;
5426     PK11SymKey *             unwrappedWrappingKey  = NULL;
5427     PK11SymKey **            pSymWrapKey;
5428     CK_MECHANISM_TYPE        asymWrapMechanism = CKM_INVALID_MECHANISM;
5429     int                      length;
5430     int                      symWrapMechIndex;
5431     SECStatus                rv;
5432     SECItem                  wrappedKey;
5433     SSLWrappedSymWrappingKey wswk;
5434 #ifdef NSS_ENABLE_ECC
5435     PK11SymKey *      Ks = NULL;
5436     SECKEYPublicKey   *pubWrapKey = NULL;
5437     SECKEYPrivateKey  *privWrapKey = NULL;
5438     ECCWrappedKeyInfo *ecWrapped;
5439 #endif /* NSS_ENABLE_ECC */
5440
5441     svrPrivKey  = ss->serverCerts[exchKeyType].SERVERKEY;
5442     PORT_Assert(svrPrivKey != NULL);
5443     if (!svrPrivKey) {
5444         return NULL;    /* why are we here?!? */
5445     }
5446
5447     symWrapMechIndex = ssl_FindIndexByWrapMechanism(masterWrapMech);
5448     PORT_Assert(symWrapMechIndex >= 0);
5449     if (symWrapMechIndex < 0)
5450         return NULL;    /* invalid masterWrapMech. */
5451
5452     pSymWrapKey = &symWrapKeys[symWrapMechIndex].symWrapKey[exchKeyType];
5453
5454     ssl_InitSessionCacheLocks(PR_TRUE);
5455
5456     PZ_Lock(symWrapKeysLock);
5457
5458     unwrappedWrappingKey = *pSymWrapKey;
5459     if (unwrappedWrappingKey != NULL) {
5460         if (PK11_VerifyKeyOK(unwrappedWrappingKey)) {
5461             unwrappedWrappingKey = PK11_ReferenceSymKey(unwrappedWrappingKey);
5462             goto done;
5463         }
5464         /* slot series has changed, so this key is no good any more. */
5465         PK11_FreeSymKey(unwrappedWrappingKey);
5466         *pSymWrapKey = unwrappedWrappingKey = NULL;
5467     }
5468
5469     /* Try to get wrapped SymWrapping key out of the (disk) cache. */
5470     /* Following call fills in wswk on success. */
5471     if (ssl_GetWrappingKey(symWrapMechIndex, exchKeyType, &wswk)) {
5472         /* found the wrapped sym wrapping key on disk. */
5473         unwrappedWrappingKey =
5474             ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, exchKeyType,
5475                                      masterWrapMech, pwArg);
5476         if (unwrappedWrappingKey) {
5477             goto install;
5478         }
5479     }
5480
5481     if (!masterSecretSlot)      /* caller doesn't want to create a new one. */
5482         goto loser;
5483
5484     length = PK11_GetBestKeyLength(masterSecretSlot, masterWrapMech);
5485     /* Zero length means fixed key length algorithm, or error.
5486      * It's ambiguous.
5487      */
5488     unwrappedWrappingKey = PK11_KeyGen(masterSecretSlot, masterWrapMech, NULL,
5489                                        length, pwArg);
5490     if (!unwrappedWrappingKey) {
5491         goto loser;
5492     }
5493
5494     /* Prepare the buffer to receive the wrappedWrappingKey,
5495      * the symmetric wrapping key wrapped using the server's pub key.
5496      */
5497     PORT_Memset(&wswk, 0, sizeof wswk); /* eliminate UMRs. */
5498
5499     if (ss->serverCerts[exchKeyType].serverKeyPair) {
5500         svrPubKey = ss->serverCerts[exchKeyType].serverKeyPair->pubKey;
5501     }
5502     if (svrPubKey == NULL) {
5503         PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
5504         goto loser;
5505     }
5506     wrappedKey.type = siBuffer;
5507     wrappedKey.len  = SECKEY_PublicKeyStrength(svrPubKey);
5508     wrappedKey.data = wswk.wrappedSymmetricWrappingkey;
5509
5510     PORT_Assert(wrappedKey.len <= sizeof wswk.wrappedSymmetricWrappingkey);
5511     if (wrappedKey.len > sizeof wswk.wrappedSymmetricWrappingkey)
5512         goto loser;
5513
5514     /* wrap symmetric wrapping key in server's public key. */
5515     switch (exchKeyType) {
5516     case kt_rsa:
5517         asymWrapMechanism = CKM_RSA_PKCS;
5518         rv = PK11_PubWrapSymKey(asymWrapMechanism, svrPubKey,
5519                                 unwrappedWrappingKey, &wrappedKey);
5520         break;
5521
5522 #ifdef NSS_ENABLE_ECC
5523     case kt_ecdh:
5524         /*
5525          * We generate an ephemeral EC key pair. Perform an ECDH
5526          * computation involving this ephemeral EC public key and
5527          * the SSL server's (long-term) EC private key. The resulting
5528          * shared secret is treated in the same way as Fortezza's Ks, 
5529          * i.e., it is used to wrap the wrapping key. To facilitate
5530          * unwrapping in ssl_UnwrapWrappingKey, we also store all
5531          * relevant info about the ephemeral EC public key in
5532          * wswk.wrappedSymmetricWrappingkey and lay it out as 
5533          * described in the ECCWrappedKeyInfo structure.
5534          */
5535         PORT_Assert(svrPubKey->keyType == ecKey);
5536         if (svrPubKey->keyType != ecKey) {
5537             /* something is wrong in sslsecur.c if this isn't an ecKey */
5538             PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
5539             rv = SECFailure;
5540             goto ec_cleanup;
5541         }
5542
5543         privWrapKey = SECKEY_CreateECPrivateKey(
5544             &svrPubKey->u.ec.DEREncodedParams, &pubWrapKey, NULL);
5545         if ((privWrapKey == NULL) || (pubWrapKey == NULL)) {
5546             rv = SECFailure;
5547             goto ec_cleanup;
5548         }
5549         
5550         /* Set the key size in bits */
5551         if (pubWrapKey->u.ec.size == 0) {
5552             pubWrapKey->u.ec.size = SECKEY_PublicKeyStrengthInBits(svrPubKey);
5553         }
5554
5555         PORT_Assert(pubWrapKey->u.ec.DEREncodedParams.len + 
5556             pubWrapKey->u.ec.publicValue.len < MAX_EC_WRAPPED_KEY_BUFLEN);
5557         if (pubWrapKey->u.ec.DEREncodedParams.len + 
5558             pubWrapKey->u.ec.publicValue.len >= MAX_EC_WRAPPED_KEY_BUFLEN) {
5559             PORT_SetError(SEC_ERROR_INVALID_KEY);
5560             rv = SECFailure;
5561             goto ec_cleanup;
5562         }
5563
5564         /* Derive Ks using ECDH */
5565         Ks = PK11_PubDeriveWithKDF(svrPrivKey, pubWrapKey, PR_FALSE, NULL,
5566                                    NULL, CKM_ECDH1_DERIVE, masterWrapMech, 
5567                                    CKA_DERIVE, 0, CKD_NULL, NULL, NULL);
5568         if (Ks == NULL) {
5569             rv = SECFailure;
5570             goto ec_cleanup;
5571         }
5572
5573         ecWrapped = (ECCWrappedKeyInfo *) (wswk.wrappedSymmetricWrappingkey);
5574         ecWrapped->size = pubWrapKey->u.ec.size;
5575         ecWrapped->encodedParamLen = pubWrapKey->u.ec.DEREncodedParams.len;
5576         PORT_Memcpy(ecWrapped->var, pubWrapKey->u.ec.DEREncodedParams.data, 
5577             pubWrapKey->u.ec.DEREncodedParams.len);
5578
5579         ecWrapped->pubValueLen = pubWrapKey->u.ec.publicValue.len;
5580         PORT_Memcpy(ecWrapped->var + ecWrapped->encodedParamLen, 
5581                     pubWrapKey->u.ec.publicValue.data, 
5582                     pubWrapKey->u.ec.publicValue.len);
5583
5584         wrappedKey.len = MAX_EC_WRAPPED_KEY_BUFLEN - 
5585             (ecWrapped->encodedParamLen + ecWrapped->pubValueLen);
5586         wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen +
5587             ecWrapped->pubValueLen;
5588
5589         /* wrap symmetricWrapping key with the local Ks */
5590         rv = PK11_WrapSymKey(masterWrapMech, NULL, Ks,
5591                              unwrappedWrappingKey, &wrappedKey);
5592
5593         if (rv != SECSuccess) {
5594             goto ec_cleanup;
5595         }
5596
5597         /* Write down the length of wrapped key in the buffer
5598          * wswk.wrappedSymmetricWrappingkey at the appropriate offset
5599          */
5600         ecWrapped->wrappedKeyLen = wrappedKey.len;
5601
5602 ec_cleanup:
5603         if (privWrapKey) SECKEY_DestroyPrivateKey(privWrapKey);
5604         if (pubWrapKey) SECKEY_DestroyPublicKey(pubWrapKey);
5605         if (Ks) PK11_FreeSymKey(Ks);
5606         asymWrapMechanism = masterWrapMech;
5607         break;
5608 #endif /* NSS_ENABLE_ECC */
5609
5610     default:
5611         rv = SECFailure;
5612         break;
5613     }
5614
5615     if (rv != SECSuccess) {
5616         ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
5617         goto loser;
5618     }
5619
5620     PORT_Assert(asymWrapMechanism != CKM_INVALID_MECHANISM);
5621
5622     wswk.symWrapMechanism  = masterWrapMech;
5623     wswk.symWrapMechIndex  = symWrapMechIndex;
5624     wswk.asymWrapMechanism = asymWrapMechanism;
5625     wswk.exchKeyType       = exchKeyType;
5626     wswk.wrappedSymKeyLen  = wrappedKey.len;
5627
5628     /* put it on disk. */
5629     /* If the wrapping key for this KEA type has already been set, 
5630      * then abandon the value we just computed and 
5631      * use the one we got from the disk.
5632      */
5633     if (ssl_SetWrappingKey(&wswk)) {
5634         /* somebody beat us to it.  The original contents of our wswk
5635          * has been replaced with the content on disk.  Now, discard
5636          * the key we just created and unwrap this new one.
5637          */
5638         PK11_FreeSymKey(unwrappedWrappingKey);
5639
5640         unwrappedWrappingKey =
5641             ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, exchKeyType,
5642                                      masterWrapMech, pwArg);
5643     }
5644
5645 install:
5646     if (unwrappedWrappingKey) {
5647         *pSymWrapKey = PK11_ReferenceSymKey(unwrappedWrappingKey);
5648     }
5649
5650 loser:
5651 done:
5652     PZ_Unlock(symWrapKeysLock);
5653     return unwrappedWrappingKey;
5654 }
5655
5656 /* hexEncode hex encodes |length| bytes from |in| and writes it as |length*2|
5657  * bytes to |out|. */
5658 static void
5659 hexEncode(char *out, const unsigned char *in, unsigned int length)
5660 {
5661     static const char hextable[] = "0123456789abcdef";
5662     unsigned int i;
5663
5664     for (i = 0; i < length; i++) {
5665         *(out++) = hextable[in[i] >> 4];
5666         *(out++) = hextable[in[i] & 15];
5667     }
5668 }
5669
5670 /* Called from ssl3_SendClientKeyExchange(). */
5671 /* Presently, this always uses PKCS11.  There is no bypass for this. */
5672 static SECStatus
5673 sendRSAClientKeyExchange(sslSocket * ss, SECKEYPublicKey * svrPubKey)
5674 {
5675     PK11SymKey *        pms             = NULL;
5676     SECStatus           rv              = SECFailure;
5677     SECItem             enc_pms         = {siBuffer, NULL, 0};
5678     PRBool              isTLS;
5679
5680     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
5681     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
5682
5683     /* Generate the pre-master secret ...  */
5684     ssl_GetSpecWriteLock(ss);
5685     isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
5686
5687     pms = ssl3_GenerateRSAPMS(ss, ss->ssl3.pwSpec, NULL);
5688     ssl_ReleaseSpecWriteLock(ss);
5689     if (pms == NULL) {
5690         ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
5691         goto loser;
5692     }
5693
5694     /* Get the wrapped (encrypted) pre-master secret, enc_pms */
5695     enc_pms.len  = SECKEY_PublicKeyStrength(svrPubKey);
5696     enc_pms.data = (unsigned char*)PORT_Alloc(enc_pms.len);
5697     if (enc_pms.data == NULL) {
5698         goto loser;     /* err set by PORT_Alloc */
5699     }
5700
5701     /* wrap pre-master secret in server's public key. */
5702     rv = PK11_PubWrapSymKey(CKM_RSA_PKCS, svrPubKey, pms, &enc_pms);
5703     if (rv != SECSuccess) {
5704         ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
5705         goto loser;
5706     }
5707
5708     if (ssl_keylog_iob) {
5709         SECStatus extractRV = PK11_ExtractKeyValue(pms);
5710         if (extractRV == SECSuccess) {
5711             SECItem * keyData = PK11_GetKeyData(pms);
5712             if (keyData && keyData->data && keyData->len) {
5713 #ifdef TRACE
5714                 if (ssl_trace >= 100) {
5715                     ssl_PrintBuf(ss, "Pre-Master Secret",
5716                                  keyData->data, keyData->len);
5717                 }
5718 #endif
5719                 if (ssl_keylog_iob && enc_pms.len >= 8 && keyData->len == 48) {
5720                     /* https://developer.mozilla.org/en/NSS_Key_Log_Format */
5721
5722                     /* There could be multiple, concurrent writers to the
5723                      * keylog, so we have to do everything in a single call to
5724                      * fwrite. */
5725                     char buf[4 + 8*2 + 1 + 48*2 + 1];
5726
5727                     strcpy(buf, "RSA ");
5728                     hexEncode(buf + 4, enc_pms.data, 8);
5729                     buf[20] = ' ';
5730                     hexEncode(buf + 21, keyData->data, 48);
5731                     buf[sizeof(buf) - 1] = '\n';
5732
5733                     fwrite(buf, sizeof(buf), 1, ssl_keylog_iob);
5734                     fflush(ssl_keylog_iob);
5735                 }
5736             }
5737         }
5738     }
5739
5740     rv = ssl3_InitPendingCipherSpec(ss,  pms);
5741     PK11_FreeSymKey(pms); pms = NULL;
5742
5743     if (rv != SECSuccess) {
5744         ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
5745         goto loser;
5746     }
5747
5748     rv = ssl3_AppendHandshakeHeader(ss, client_key_exchange, 
5749                                     isTLS ? enc_pms.len + 2 : enc_pms.len);
5750     if (rv != SECSuccess) {
5751         goto loser;     /* err set by ssl3_AppendHandshake* */
5752     }
5753     if (isTLS) {
5754         rv = ssl3_AppendHandshakeVariable(ss, enc_pms.data, enc_pms.len, 2);
5755     } else {
5756         rv = ssl3_AppendHandshake(ss, enc_pms.data, enc_pms.len);
5757     }
5758     if (rv != SECSuccess) {
5759         goto loser;     /* err set by ssl3_AppendHandshake* */
5760     }
5761
5762     rv = SECSuccess;
5763
5764 loser:
5765     if (enc_pms.data != NULL) {
5766         PORT_Free(enc_pms.data);
5767     }
5768     if (pms != NULL) {
5769         PK11_FreeSymKey(pms);
5770     }
5771     return rv;
5772 }
5773
5774 /* Called from ssl3_SendClientKeyExchange(). */
5775 /* Presently, this always uses PKCS11.  There is no bypass for this. */
5776 static SECStatus
5777 sendDHClientKeyExchange(sslSocket * ss, SECKEYPublicKey * svrPubKey)
5778 {
5779     PK11SymKey *        pms             = NULL;
5780     SECStatus           rv              = SECFailure;
5781     PRBool              isTLS;
5782     CK_MECHANISM_TYPE   target;
5783
5784     SECKEYDHParams      dhParam;                /* DH parameters */
5785     SECKEYPublicKey     *pubKey = NULL;         /* Ephemeral DH key */
5786     SECKEYPrivateKey    *privKey = NULL;        /* Ephemeral DH key */
5787
5788     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
5789     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
5790
5791     isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
5792
5793     /* Copy DH parameters from server key */
5794
5795     if (svrPubKey->keyType != dhKey) {
5796         PORT_SetError(SEC_ERROR_BAD_KEY);
5797         goto loser;
5798     }
5799     dhParam.prime.data = svrPubKey->u.dh.prime.data;
5800     dhParam.prime.len = svrPubKey->u.dh.prime.len;
5801     dhParam.base.data = svrPubKey->u.dh.base.data;
5802     dhParam.base.len = svrPubKey->u.dh.base.len;
5803
5804     /* Generate ephemeral DH keypair */
5805     privKey = SECKEY_CreateDHPrivateKey(&dhParam, &pubKey, NULL);
5806     if (!privKey || !pubKey) {
5807             ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL);
5808             rv = SECFailure;
5809             goto loser;
5810     }
5811     PRINT_BUF(50, (ss, "DH public value:",
5812                                         pubKey->u.dh.publicValue.data,
5813                                         pubKey->u.dh.publicValue.len));
5814
5815     if (isTLS) target = CKM_TLS_MASTER_KEY_DERIVE_DH;
5816     else target = CKM_SSL3_MASTER_KEY_DERIVE_DH;
5817
5818     /* Determine the PMS */
5819
5820     pms = PK11_PubDerive(privKey, svrPubKey, PR_FALSE, NULL, NULL,
5821                             CKM_DH_PKCS_DERIVE, target, CKA_DERIVE, 0, NULL);
5822
5823     if (pms == NULL) {
5824         ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
5825         goto loser;
5826     }
5827
5828     SECKEY_DestroyPrivateKey(privKey);
5829     privKey = NULL;
5830
5831     rv = ssl3_InitPendingCipherSpec(ss,  pms);
5832     PK11_FreeSymKey(pms); pms = NULL;
5833
5834     if (rv != SECSuccess) {
5835         ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
5836         goto loser;
5837     }
5838
5839     rv = ssl3_AppendHandshakeHeader(ss, client_key_exchange, 
5840                                         pubKey->u.dh.publicValue.len + 2);
5841     if (rv != SECSuccess) {
5842         goto loser;     /* err set by ssl3_AppendHandshake* */
5843     }
5844     rv = ssl3_AppendHandshakeVariable(ss, 
5845                                         pubKey->u.dh.publicValue.data,
5846                                         pubKey->u.dh.publicValue.len, 2);
5847     SECKEY_DestroyPublicKey(pubKey);
5848     pubKey = NULL;
5849
5850     if (rv != SECSuccess) {
5851         goto loser;     /* err set by ssl3_AppendHandshake* */
5852     }
5853
5854     rv = SECSuccess;
5855
5856
5857 loser:
5858
5859     if(pms) PK11_FreeSymKey(pms);
5860     if(privKey) SECKEY_DestroyPrivateKey(privKey);
5861     if(pubKey) SECKEY_DestroyPublicKey(pubKey);
5862     return rv;
5863 }
5864
5865
5866
5867
5868
5869 /* Called from ssl3_HandleServerHelloDone(). */
5870 static SECStatus
5871 ssl3_SendClientKeyExchange(sslSocket *ss)
5872 {
5873     SECKEYPublicKey *   serverKey       = NULL;
5874     SECStatus           rv              = SECFailure;
5875     PRBool              isTLS;
5876
5877     SSL_TRC(3, ("%d: SSL3[%d]: send client_key_exchange handshake",
5878                 SSL_GETPID(), ss->fd));
5879
5880     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
5881     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
5882
5883     if (ss->sec.peerKey == NULL) {
5884         serverKey = CERT_ExtractPublicKey(ss->sec.peerCert);
5885         if (serverKey == NULL) {
5886             ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
5887             return SECFailure;
5888         }
5889     } else {
5890         serverKey = ss->sec.peerKey;
5891         ss->sec.peerKey = NULL; /* we're done with it now */
5892     }
5893
5894     isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
5895     /* enforce limits on kea key sizes. */
5896     if (ss->ssl3.hs.kea_def->is_limited) {
5897         int keyLen = SECKEY_PublicKeyStrength(serverKey);       /* bytes */
5898
5899         if (keyLen * BPB > ss->ssl3.hs.kea_def->key_size_limit) {
5900             if (isTLS)
5901                 (void)SSL3_SendAlert(ss, alert_fatal, export_restriction);
5902             else
5903                 (void)ssl3_HandshakeFailure(ss);
5904             PORT_SetError(SSL_ERROR_PUB_KEY_SIZE_LIMIT_EXCEEDED);
5905             goto loser;
5906         }
5907     }
5908
5909     ss->sec.keaType    = ss->ssl3.hs.kea_def->exchKeyType;
5910     ss->sec.keaKeyBits = SECKEY_PublicKeyStrengthInBits(serverKey);
5911
5912     switch (ss->ssl3.hs.kea_def->exchKeyType) {
5913     case kt_rsa:
5914         rv = sendRSAClientKeyExchange(ss, serverKey);
5915         break;
5916
5917     case kt_dh:
5918         rv = sendDHClientKeyExchange(ss, serverKey);
5919         break;
5920
5921 #ifdef NSS_ENABLE_ECC
5922     case kt_ecdh:
5923         rv = ssl3_SendECDHClientKeyExchange(ss, serverKey);
5924         break;
5925 #endif /* NSS_ENABLE_ECC */
5926
5927     default:
5928         /* got an unknown or unsupported Key Exchange Algorithm.  */
5929         SEND_ALERT
5930         PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
5931         break;
5932     }
5933
5934     SSL_TRC(3, ("%d: SSL3[%d]: DONE sending client_key_exchange",
5935                 SSL_GETPID(), ss->fd));
5936
5937 loser:
5938     if (serverKey) 
5939         SECKEY_DestroyPublicKey(serverKey);
5940     return rv;  /* err code already set. */
5941 }
5942
5943 /* Called from ssl3_HandleServerHelloDone(). */
5944 static SECStatus
5945 ssl3_SendCertificateVerify(sslSocket *ss)
5946 {
5947     SECStatus     rv            = SECFailure;
5948     PRBool        isTLS;
5949     PRBool        isTLS12;
5950     SECItem       buf           = {siBuffer, NULL, 0};
5951     SSL3Hashes    hashes;
5952     KeyType       keyType;
5953     unsigned int  len;
5954     SSL3SignatureAndHashAlgorithm sigAndHash;
5955
5956     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
5957     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
5958
5959     SSL_TRC(3, ("%d: SSL3[%d]: send certificate_verify handshake",
5960                 SSL_GETPID(), ss->fd));
5961
5962     ssl_GetSpecReadLock(ss);
5963     rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.pwSpec, &hashes, 0);
5964     ssl_ReleaseSpecReadLock(ss);
5965     if (rv != SECSuccess) {
5966         goto done;      /* err code was set by ssl3_ComputeHandshakeHashes */
5967     }
5968
5969     isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
5970     isTLS12 = (PRBool)(ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
5971     keyType = ss->ssl3.clientPrivateKey->keyType;
5972     rv = ssl3_SignHashes(&hashes, ss->ssl3.clientPrivateKey, &buf, isTLS);
5973     if (rv == SECSuccess) {
5974         PK11SlotInfo * slot;
5975         sslSessionID * sid   = ss->sec.ci.sid;
5976
5977         /* Remember the info about the slot that did the signing.
5978         ** Later, when doing an SSL restart handshake, verify this.
5979         ** These calls are mere accessors, and can't fail.
5980         */
5981         slot = PK11_GetSlotFromPrivateKey(ss->ssl3.clientPrivateKey);
5982         sid->u.ssl3.clAuthSeries     = PK11_GetSlotSeries(slot);
5983         sid->u.ssl3.clAuthSlotID     = PK11_GetSlotID(slot);
5984         sid->u.ssl3.clAuthModuleID   = PK11_GetModuleID(slot);
5985         sid->u.ssl3.clAuthValid      = PR_TRUE;
5986         PK11_FreeSlot(slot);
5987     }
5988     SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
5989     ss->ssl3.clientPrivateKey = NULL;
5990     if (rv != SECSuccess) {
5991         goto done;      /* err code was set by ssl3_SignHashes */
5992     }
5993
5994     len = buf.len + 2 + (isTLS12 ? 2 : 0);
5995
5996     rv = ssl3_AppendHandshakeHeader(ss, certificate_verify, len);
5997     if (rv != SECSuccess) {
5998         goto done;      /* error code set by AppendHandshake */
5999     }
6000     if (isTLS12) {
6001         rv = ssl3_TLSSignatureAlgorithmForKeyType(keyType,
6002                                                   &sigAndHash.sigAlg);
6003         if (rv != SECSuccess) {
6004             goto done;
6005         }
6006         /* We always sign using the handshake hash function. It's possible that
6007          * a server could support SHA-256 as the handshake hash but not as a
6008          * signature hash. In that case we wouldn't be able to do client
6009          * certificates with it. The alternative is to buffer all handshake
6010          * messages. */
6011         sigAndHash.hashAlg = hashes.hashAlg;
6012
6013         rv = ssl3_AppendSignatureAndHashAlgorithm(ss, &sigAndHash);
6014         if (rv != SECSuccess) {
6015             goto done;  /* err set by AppendHandshake. */
6016         }
6017     }
6018     rv = ssl3_AppendHandshakeVariable(ss, buf.data, buf.len, 2);
6019     if (rv != SECSuccess) {
6020         goto done;      /* error code set by AppendHandshake */
6021     }
6022
6023 done:
6024     if (buf.data)
6025         PORT_Free(buf.data);
6026     return rv;
6027 }
6028
6029 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
6030  * ssl3 ServerHello message.
6031  * Caller must hold Handshake and RecvBuf locks.
6032  */
6033 static SECStatus
6034 ssl3_HandleServerHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
6035 {
6036     sslSessionID *sid           = ss->sec.ci.sid;
6037     PRInt32       temp;         /* allow for consume number failure */
6038     PRBool        suite_found   = PR_FALSE;
6039     int           i;
6040     int           errCode       = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
6041     SECStatus     rv;
6042     SECItem       sidBytes      = {siBuffer, NULL, 0};
6043     PRBool        sid_match;
6044     PRBool        isTLS         = PR_FALSE;
6045     SSL3AlertDescription desc   = illegal_parameter;
6046     SSL3ProtocolVersion version;
6047
6048     SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello handshake",
6049         SSL_GETPID(), ss->fd));
6050     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
6051     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
6052     PORT_Assert( ss->ssl3.initialized );
6053
6054     if (ss->ssl3.hs.ws != wait_server_hello) {
6055         errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO;
6056         desc    = unexpected_message;
6057         goto alert_loser;
6058     }
6059
6060     /* clean up anything left from previous handshake. */
6061     if (ss->ssl3.clientCertChain != NULL) {
6062        CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
6063        ss->ssl3.clientCertChain = NULL;
6064     }
6065     if (ss->ssl3.clientCertificate != NULL) {
6066        CERT_DestroyCertificate(ss->ssl3.clientCertificate);
6067        ss->ssl3.clientCertificate = NULL;
6068     }
6069     if (ss->ssl3.clientPrivateKey != NULL) {
6070        SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
6071        ss->ssl3.clientPrivateKey = NULL;
6072     }
6073
6074     temp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
6075     if (temp < 0) {
6076         goto loser;     /* alert has been sent */
6077     }
6078     version = (SSL3ProtocolVersion)temp;
6079
6080     if (IS_DTLS(ss)) {
6081         /* RFC 4347 required that you verify that the server versions
6082          * match (Section 4.2.1) in the HelloVerifyRequest and the
6083          * ServerHello.
6084          *
6085          * RFC 6347 suggests (SHOULD) that servers always use 1.0
6086          * in HelloVerifyRequest and allows the versions not to match,
6087          * especially when 1.2 is being negotiated.
6088          *
6089          * Therefore we do not check for matching here.
6090          */
6091         version = dtls_DTLSVersionToTLSVersion(version);
6092         if (version == 0) {  /* Insane version number */
6093             goto alert_loser;
6094         }
6095     }
6096
6097     rv = ssl3_NegotiateVersion(ss, version, PR_FALSE);
6098     if (rv != SECSuccess) {
6099         desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version 
6100                                                    : handshake_failure;
6101         errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
6102         goto alert_loser;
6103     }
6104     isTLS = (ss->version > SSL_LIBRARY_VERSION_3_0);
6105
6106     rv = ssl3_InitHandshakeHashes(ss);
6107     if (rv != SECSuccess) {
6108         desc = internal_error;
6109         errCode = PORT_GetError();
6110         goto alert_loser;
6111     }
6112
6113     rv = ssl3_ConsumeHandshake(
6114         ss, &ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH, &b, &length);
6115     if (rv != SECSuccess) {
6116         goto loser;     /* alert has been sent */
6117     }
6118
6119     rv = ssl3_ConsumeHandshakeVariable(ss, &sidBytes, 1, &b, &length);
6120     if (rv != SECSuccess) {
6121         goto loser;     /* alert has been sent */
6122     }
6123     if (sidBytes.len > SSL3_SESSIONID_BYTES) {
6124         if (isTLS)
6125             desc = decode_error;
6126         goto alert_loser;       /* malformed. */
6127     }
6128
6129     /* find selected cipher suite in our list. */
6130     temp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
6131     if (temp < 0) {
6132         goto loser;     /* alert has been sent */
6133     }
6134     ssl3_config_match_init(ss);
6135     for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
6136         ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i];
6137         if (temp == suite->cipher_suite) {
6138             SSLVersionRange vrange = {ss->version, ss->version};
6139             if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange)) {
6140                 /* config_match already checks whether the cipher suite is
6141                  * acceptable for the version, but the check is repeated here
6142                  * in order to give a more precise error code. */
6143                 if (!ssl3_CipherSuiteAllowedForVersionRange(temp, &vrange)) {
6144                     desc    = handshake_failure;
6145                     errCode = SSL_ERROR_CIPHER_DISALLOWED_FOR_VERSION;
6146                     goto alert_loser;
6147                 }
6148
6149                 break;  /* failure */
6150             }
6151         
6152             suite_found = PR_TRUE;
6153             break;      /* success */
6154         }
6155     }
6156     if (!suite_found) {
6157         desc    = handshake_failure;
6158         errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
6159         goto alert_loser;
6160     }
6161     ss->ssl3.hs.cipher_suite = (ssl3CipherSuite)temp;
6162     ss->ssl3.hs.suite_def    = ssl_LookupCipherSuiteDef((ssl3CipherSuite)temp);
6163     PORT_Assert(ss->ssl3.hs.suite_def);
6164     if (!ss->ssl3.hs.suite_def) {
6165         PORT_SetError(errCode = SEC_ERROR_LIBRARY_FAILURE);
6166         goto loser;     /* we don't send alerts for our screw-ups. */
6167     }
6168
6169     /* find selected compression method in our list. */
6170     temp = ssl3_ConsumeHandshakeNumber(ss, 1, &b, &length);
6171     if (temp < 0) {
6172         goto loser;     /* alert has been sent */
6173     }
6174     suite_found = PR_FALSE;
6175     for (i = 0; i < compressionMethodsCount; i++) {
6176         if (temp == compressions[i]) {
6177             if (!compressionEnabled(ss, compressions[i])) {
6178                 break;  /* failure */
6179             }
6180             suite_found = PR_TRUE;
6181             break;      /* success */
6182         }
6183     }
6184     if (!suite_found) {
6185         desc    = handshake_failure;
6186         errCode = SSL_ERROR_NO_COMPRESSION_OVERLAP;
6187         goto alert_loser;
6188     }
6189     ss->ssl3.hs.compression = (SSLCompressionMethod)temp;
6190
6191     /* Note that if !isTLS and the extra stuff is not extensions, we
6192      * do NOT goto alert_loser.
6193      * There are some old SSL 3.0 implementations that do send stuff
6194      * after the end of the server hello, and we deliberately ignore
6195      * such stuff in the interest of maximal interoperability (being
6196      * "generous in what you accept").
6197      * Update: Starting in NSS 3.12.6, we handle the renegotiation_info
6198      * extension in SSL 3.0.
6199      */
6200     if (length != 0) {
6201         SECItem extensions;
6202         rv = ssl3_ConsumeHandshakeVariable(ss, &extensions, 2, &b, &length);
6203         if (rv != SECSuccess || length != 0) {
6204             if (isTLS)
6205                 goto alert_loser;
6206         } else {
6207             rv = ssl3_HandleHelloExtensions(ss, &extensions.data,
6208                                             &extensions.len);
6209             if (rv != SECSuccess)
6210                 goto alert_loser;
6211         }
6212     }
6213     if ((ss->opt.requireSafeNegotiation || 
6214          (ss->firstHsDone && (ss->peerRequestedProtection ||
6215          ss->opt.enableRenegotiation == SSL_RENEGOTIATE_REQUIRES_XTN))) &&
6216         !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
6217         desc = handshake_failure;
6218         errCode = ss->firstHsDone ? SSL_ERROR_RENEGOTIATION_NOT_ALLOWED
6219                                   : SSL_ERROR_UNSAFE_NEGOTIATION;
6220         goto alert_loser;
6221     }
6222
6223     /* Any errors after this point are not "malformed" errors. */
6224     desc    = handshake_failure;
6225
6226     /* we need to call ssl3_SetupPendingCipherSpec here so we can check the
6227      * key exchange algorithm. */
6228     rv = ssl3_SetupPendingCipherSpec(ss);
6229     if (rv != SECSuccess) {
6230         goto alert_loser;       /* error code is set. */
6231     }
6232
6233     /* We may or may not have sent a session id, we may get one back or
6234      * not and if so it may match the one we sent.
6235      * Attempt to restore the master secret to see if this is so...
6236      * Don't consider failure to find a matching SID an error.
6237      */
6238     sid_match = (PRBool)(sidBytes.len > 0 &&
6239         sidBytes.len == sid->u.ssl3.sessionIDLength &&
6240         !PORT_Memcmp(sid->u.ssl3.sessionID, sidBytes.data, sidBytes.len));
6241
6242     if (sid_match &&
6243         sid->version == ss->version &&
6244         sid->u.ssl3.cipherSuite == ss->ssl3.hs.cipher_suite) do {
6245         ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec;
6246
6247         SECItem       wrappedMS;   /* wrapped master secret. */
6248
6249         ss->sec.authAlgorithm = sid->authAlgorithm;
6250         ss->sec.authKeyBits   = sid->authKeyBits;
6251         ss->sec.keaType       = sid->keaType;
6252         ss->sec.keaKeyBits    = sid->keaKeyBits;
6253
6254         /* 3 cases here:
6255          * a) key is wrapped (implies using PKCS11)
6256          * b) key is unwrapped, but we're still using PKCS11
6257          * c) key is unwrapped, and we're bypassing PKCS11.
6258          */
6259         if (sid->u.ssl3.keys.msIsWrapped) {
6260             PK11SlotInfo *slot;
6261             PK11SymKey *  wrapKey;     /* wrapping key */
6262             CK_FLAGS      keyFlags      = 0;
6263
6264 #ifndef NO_PKCS11_BYPASS
6265             if (ss->opt.bypassPKCS11) {
6266                 /* we cannot restart a non-bypass session in a 
6267                 ** bypass socket.
6268                 */
6269                 break;  
6270             }
6271 #endif
6272             /* unwrap master secret with PKCS11 */
6273             slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID,
6274                                      sid->u.ssl3.masterSlotID);
6275             if (slot == NULL) {
6276                 break;          /* not considered an error. */
6277             }
6278             if (!PK11_IsPresent(slot)) {
6279                 PK11_FreeSlot(slot);
6280                 break;          /* not considered an error. */
6281             }
6282             wrapKey = PK11_GetWrapKey(slot, sid->u.ssl3.masterWrapIndex,
6283                                       sid->u.ssl3.masterWrapMech,
6284                                       sid->u.ssl3.masterWrapSeries,
6285                                       ss->pkcs11PinArg);
6286             PK11_FreeSlot(slot);
6287             if (wrapKey == NULL) {
6288                 break;          /* not considered an error. */
6289             }
6290
6291             if (ss->version > SSL_LIBRARY_VERSION_3_0) {        /* isTLS */
6292                 keyFlags = CKF_SIGN | CKF_VERIFY;
6293             }
6294
6295             wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
6296             wrappedMS.len  = sid->u.ssl3.keys.wrapped_master_secret_len;
6297             pwSpec->master_secret =
6298                 PK11_UnwrapSymKeyWithFlags(wrapKey, sid->u.ssl3.masterWrapMech, 
6299                             NULL, &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE,
6300                             CKA_DERIVE, sizeof(SSL3MasterSecret), keyFlags);
6301             errCode = PORT_GetError();
6302             PK11_FreeSymKey(wrapKey);
6303             if (pwSpec->master_secret == NULL) {
6304                 break;  /* errorCode set just after call to UnwrapSymKey. */
6305             }
6306 #ifndef NO_PKCS11_BYPASS
6307         } else if (ss->opt.bypassPKCS11) {
6308             /* MS is not wrapped */
6309             wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
6310             wrappedMS.len  = sid->u.ssl3.keys.wrapped_master_secret_len;
6311             memcpy(pwSpec->raw_master_secret, wrappedMS.data, wrappedMS.len);
6312             pwSpec->msItem.data = pwSpec->raw_master_secret;
6313             pwSpec->msItem.len  = wrappedMS.len;
6314 #endif
6315         } else {
6316             /* We CAN restart a bypass session in a non-bypass socket. */
6317             /* need to import the raw master secret to session object */
6318             PK11SlotInfo *slot = PK11_GetInternalSlot();
6319             wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
6320             wrappedMS.len  = sid->u.ssl3.keys.wrapped_master_secret_len;
6321             pwSpec->master_secret =  
6322                 PK11_ImportSymKey(slot, CKM_SSL3_MASTER_KEY_DERIVE, 
6323                                   PK11_OriginUnwrap, CKA_ENCRYPT, 
6324                                   &wrappedMS, NULL);
6325             PK11_FreeSlot(slot);
6326             if (pwSpec->master_secret == NULL) {
6327                 break; 
6328             }
6329         }
6330
6331         /* Got a Match */
6332         SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_cache_hits );
6333
6334         /* If we sent a session ticket, then this is a stateless resume. */
6335         if (sid->version > SSL_LIBRARY_VERSION_3_0 &&
6336             sid->u.ssl3.sessionTicket.ticket.data != NULL)
6337             SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_stateless_resumes );
6338
6339         if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn))
6340             ss->ssl3.hs.ws = wait_new_session_ticket;
6341         else
6342             ss->ssl3.hs.ws = wait_change_cipher;
6343
6344         ss->ssl3.hs.isResuming = PR_TRUE;
6345
6346         /* copy the peer cert from the SID */
6347         if (sid->peerCert != NULL) {
6348             ss->sec.peerCert = CERT_DupCertificate(sid->peerCert);
6349         }
6350
6351         /* NULL value for PMS signifies re-use of the old MS */
6352         rv = ssl3_InitPendingCipherSpec(ss,  NULL);
6353         if (rv != SECSuccess) {
6354             goto alert_loser;   /* err code was set */
6355         }
6356         return SECSuccess;
6357     } while (0);
6358
6359     if (sid_match)
6360         SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_cache_not_ok );
6361     else
6362         SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_cache_misses );
6363
6364     /* throw the old one away */
6365     sid->u.ssl3.keys.resumable = PR_FALSE;
6366     if (ss->sec.uncache)
6367         (*ss->sec.uncache)(sid);
6368     ssl_FreeSID(sid);
6369
6370     /* get a new sid */
6371     ss->sec.ci.sid = sid = ssl3_NewSessionID(ss, PR_FALSE);
6372     if (sid == NULL) {
6373         goto alert_loser;       /* memory error is set. */
6374     }
6375
6376     sid->version = ss->version;
6377     sid->u.ssl3.sessionIDLength = sidBytes.len;
6378     PORT_Memcpy(sid->u.ssl3.sessionID, sidBytes.data, sidBytes.len);
6379
6380     ss->ssl3.hs.isResuming = PR_FALSE;
6381     ss->ssl3.hs.ws         = wait_server_cert;
6382     return SECSuccess;
6383
6384 alert_loser:
6385     (void)SSL3_SendAlert(ss, alert_fatal, desc);
6386
6387 loser:
6388     errCode = ssl_MapLowLevelError(errCode);
6389     return SECFailure;
6390 }
6391
6392 /* ssl3_BigIntGreaterThanOne returns true iff |mpint|, taken as an unsigned,
6393  * big-endian integer is > 1 */
6394 static PRBool
6395 ssl3_BigIntGreaterThanOne(const SECItem* mpint) {
6396     unsigned char firstNonZeroByte = 0;
6397     unsigned int i;
6398
6399     for (i = 0; i < mpint->len; i++) {
6400         if (mpint->data[i]) {
6401             firstNonZeroByte = mpint->data[i];
6402             break;
6403         }
6404     }
6405
6406     if (firstNonZeroByte == 0)
6407         return PR_FALSE;
6408     if (firstNonZeroByte > 1)
6409         return PR_TRUE;
6410
6411     /* firstNonZeroByte == 1, therefore mpint > 1 iff the first non-zero byte
6412      * is followed by another byte. */
6413     return (i < mpint->len - 1);
6414 }
6415
6416 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
6417  * ssl3 ServerKeyExchange message.
6418  * Caller must hold Handshake and RecvBuf locks.
6419  */
6420 static SECStatus
6421 ssl3_HandleServerKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
6422 {
6423     PLArenaPool *    arena     = NULL;
6424     SECKEYPublicKey *peerKey   = NULL;
6425     PRBool           isTLS, isTLS12;
6426     SECStatus        rv;
6427     int              errCode   = SSL_ERROR_RX_MALFORMED_SERVER_KEY_EXCH;
6428     SSL3AlertDescription desc  = illegal_parameter;
6429     SSL3Hashes       hashes;
6430     SECItem          signature = {siBuffer, NULL, 0};
6431     SSL3SignatureAndHashAlgorithm sigAndHash;
6432
6433     sigAndHash.hashAlg = SEC_OID_UNKNOWN;
6434
6435     SSL_TRC(3, ("%d: SSL3[%d]: handle server_key_exchange handshake",
6436                 SSL_GETPID(), ss->fd));
6437     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
6438     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
6439
6440     if (ss->ssl3.hs.ws != wait_server_key &&
6441         ss->ssl3.hs.ws != wait_server_cert) {
6442         errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH;
6443         desc    = unexpected_message;
6444         goto alert_loser;
6445     }
6446     if (ss->sec.peerCert == NULL) {
6447         errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH;
6448         desc    = unexpected_message;
6449         goto alert_loser;
6450     }
6451
6452     isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
6453     isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
6454
6455     switch (ss->ssl3.hs.kea_def->exchKeyType) {
6456
6457     case kt_rsa: {
6458         SECItem          modulus   = {siBuffer, NULL, 0};
6459         SECItem          exponent  = {siBuffer, NULL, 0};
6460
6461         rv = ssl3_ConsumeHandshakeVariable(ss, &modulus, 2, &b, &length);
6462         if (rv != SECSuccess) {
6463             goto loser;         /* malformed. */
6464         }
6465         rv = ssl3_ConsumeHandshakeVariable(ss, &exponent, 2, &b, &length);
6466         if (rv != SECSuccess) {
6467             goto loser;         /* malformed. */
6468         }
6469         if (isTLS12) {
6470             rv = ssl3_ConsumeSignatureAndHashAlgorithm(ss, &b, &length,
6471                                                        &sigAndHash);
6472             if (rv != SECSuccess) {
6473                 goto loser;     /* malformed or unsupported. */
6474             }
6475             rv = ssl3_CheckSignatureAndHashAlgorithmConsistency(
6476                     &sigAndHash, ss->sec.peerCert);
6477             if (rv != SECSuccess) {
6478                 goto loser;
6479             }
6480         }
6481         rv = ssl3_ConsumeHandshakeVariable(ss, &signature, 2, &b, &length);
6482         if (rv != SECSuccess) {
6483             goto loser;         /* malformed. */
6484         }
6485         if (length != 0) {
6486             if (isTLS)
6487                 desc = decode_error;
6488             goto alert_loser;           /* malformed. */
6489         }
6490
6491         /* failures after this point are not malformed handshakes. */
6492         /* TLS: send decrypt_error if signature failed. */
6493         desc = isTLS ? decrypt_error : handshake_failure;
6494
6495         /*
6496          *  check to make sure the hash is signed by right guy
6497          */
6498         rv = ssl3_ComputeExportRSAKeyHash(sigAndHash.hashAlg, modulus, exponent,
6499                                           &ss->ssl3.hs.client_random,
6500                                           &ss->ssl3.hs.server_random, 
6501                                           &hashes, ss->opt.bypassPKCS11);
6502         if (rv != SECSuccess) {
6503             errCode =
6504                 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
6505             goto alert_loser;
6506         }
6507         rv = ssl3_VerifySignedHashes(&hashes, ss->sec.peerCert, &signature,
6508                                     isTLS, ss->pkcs11PinArg);
6509         if (rv != SECSuccess)  {
6510             errCode =
6511                 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
6512             goto alert_loser;
6513         }
6514
6515         /*
6516          * we really need to build a new key here because we can no longer
6517          * ignore calling SECKEY_DestroyPublicKey. Using the key may allocate
6518          * pkcs11 slots and ID's.
6519          */
6520         arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
6521         if (arena == NULL) {
6522             goto no_memory;
6523         }
6524
6525         peerKey = PORT_ArenaZNew(arena, SECKEYPublicKey);
6526         if (peerKey == NULL) {
6527             PORT_FreeArena(arena, PR_FALSE);
6528             goto no_memory;
6529         }
6530
6531         peerKey->arena              = arena;
6532         peerKey->keyType            = rsaKey;
6533         peerKey->pkcs11Slot         = NULL;
6534         peerKey->pkcs11ID           = CK_INVALID_HANDLE;
6535         if (SECITEM_CopyItem(arena, &peerKey->u.rsa.modulus,        &modulus) ||
6536             SECITEM_CopyItem(arena, &peerKey->u.rsa.publicExponent, &exponent))
6537         {
6538             PORT_FreeArena(arena, PR_FALSE);
6539             goto no_memory;
6540         }
6541         ss->sec.peerKey = peerKey;
6542         ss->ssl3.hs.ws = wait_cert_request;
6543         return SECSuccess;
6544     }
6545
6546     case kt_dh: {
6547         SECItem          dh_p      = {siBuffer, NULL, 0};
6548         SECItem          dh_g      = {siBuffer, NULL, 0};
6549         SECItem          dh_Ys     = {siBuffer, NULL, 0};
6550
6551         rv = ssl3_ConsumeHandshakeVariable(ss, &dh_p, 2, &b, &length);
6552         if (rv != SECSuccess) {
6553             goto loser;         /* malformed. */
6554         }
6555         if (dh_p.len < 512/8) {
6556             errCode = SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY;
6557             goto alert_loser;
6558         }
6559         rv = ssl3_ConsumeHandshakeVariable(ss, &dh_g, 2, &b, &length);
6560         if (rv != SECSuccess) {
6561             goto loser;         /* malformed. */
6562         }
6563         if (dh_g.len > dh_p.len || !ssl3_BigIntGreaterThanOne(&dh_g))
6564             goto alert_loser;
6565         rv = ssl3_ConsumeHandshakeVariable(ss, &dh_Ys, 2, &b, &length);
6566         if (rv != SECSuccess) {
6567             goto loser;         /* malformed. */
6568         }
6569         if (dh_Ys.len > dh_p.len || !ssl3_BigIntGreaterThanOne(&dh_Ys))
6570             goto alert_loser;
6571         if (isTLS12) {
6572             rv = ssl3_ConsumeSignatureAndHashAlgorithm(ss, &b, &length,
6573                                                        &sigAndHash);
6574             if (rv != SECSuccess) {
6575                 goto loser;     /* malformed or unsupported. */
6576             }
6577             rv = ssl3_CheckSignatureAndHashAlgorithmConsistency(
6578                     &sigAndHash, ss->sec.peerCert);
6579             if (rv != SECSuccess) {
6580                 goto loser;
6581             }
6582         }
6583         rv = ssl3_ConsumeHandshakeVariable(ss, &signature, 2, &b, &length);
6584         if (rv != SECSuccess) {
6585             goto loser;         /* malformed. */
6586         }
6587         if (length != 0) {
6588             if (isTLS)
6589                 desc = decode_error;
6590             goto alert_loser;           /* malformed. */
6591         }
6592
6593         PRINT_BUF(60, (NULL, "Server DH p", dh_p.data, dh_p.len));
6594         PRINT_BUF(60, (NULL, "Server DH g", dh_g.data, dh_g.len));
6595         PRINT_BUF(60, (NULL, "Server DH Ys", dh_Ys.data, dh_Ys.len));
6596
6597         /* failures after this point are not malformed handshakes. */
6598         /* TLS: send decrypt_error if signature failed. */
6599         desc = isTLS ? decrypt_error : handshake_failure;
6600
6601         /*
6602          *  check to make sure the hash is signed by right guy
6603          */
6604         rv = ssl3_ComputeDHKeyHash(sigAndHash.hashAlg, dh_p, dh_g, dh_Ys,
6605                                           &ss->ssl3.hs.client_random,
6606                                           &ss->ssl3.hs.server_random, 
6607                                           &hashes, ss->opt.bypassPKCS11);
6608         if (rv != SECSuccess) {
6609             errCode =
6610                 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
6611             goto alert_loser;
6612         }
6613         rv = ssl3_VerifySignedHashes(&hashes, ss->sec.peerCert, &signature,
6614                                     isTLS, ss->pkcs11PinArg);
6615         if (rv != SECSuccess)  {
6616             errCode =
6617                 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
6618             goto alert_loser;
6619         }
6620
6621         /*
6622          * we really need to build a new key here because we can no longer
6623          * ignore calling SECKEY_DestroyPublicKey. Using the key may allocate
6624          * pkcs11 slots and ID's.
6625          */
6626         arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
6627         if (arena == NULL) {
6628             goto no_memory;
6629         }
6630
6631         ss->sec.peerKey = peerKey = PORT_ArenaZNew(arena, SECKEYPublicKey);
6632         if (peerKey == NULL) {
6633             goto no_memory;
6634         }
6635
6636         peerKey->arena              = arena;
6637         peerKey->keyType            = dhKey;
6638         peerKey->pkcs11Slot         = NULL;
6639         peerKey->pkcs11ID           = CK_INVALID_HANDLE;
6640
6641         if (SECITEM_CopyItem(arena, &peerKey->u.dh.prime,        &dh_p) ||
6642             SECITEM_CopyItem(arena, &peerKey->u.dh.base,         &dh_g) ||
6643             SECITEM_CopyItem(arena, &peerKey->u.dh.publicValue,  &dh_Ys))
6644         {
6645             PORT_FreeArena(arena, PR_FALSE);
6646             goto no_memory;
6647         }
6648         ss->sec.peerKey = peerKey;
6649         ss->ssl3.hs.ws = wait_cert_request;
6650         return SECSuccess;
6651     }
6652
6653 #ifdef NSS_ENABLE_ECC
6654     case kt_ecdh:
6655         rv = ssl3_HandleECDHServerKeyExchange(ss, b, length);
6656         return rv;
6657 #endif /* NSS_ENABLE_ECC */
6658
6659     default:
6660         desc    = handshake_failure;
6661         errCode = SEC_ERROR_UNSUPPORTED_KEYALG;
6662         break;          /* goto alert_loser; */
6663     }
6664
6665 alert_loser:
6666     (void)SSL3_SendAlert(ss, alert_fatal, desc);
6667 loser:
6668     PORT_SetError( errCode );
6669     return SECFailure;
6670
6671 no_memory:      /* no-memory error has already been set. */
6672     ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
6673     return SECFailure;
6674 }
6675
6676
6677 typedef struct dnameNode {
6678     struct dnameNode *next;
6679     SECItem           name;
6680 } dnameNode;
6681
6682 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
6683  * ssl3 Certificate Request message.
6684  * Caller must hold Handshake and RecvBuf locks.
6685  */
6686 static SECStatus
6687 ssl3_HandleCertificateRequest(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
6688 {
6689     PLArenaPool *        arena       = NULL;
6690     dnameNode *          node;
6691     PRInt32              remaining;
6692     PRBool               isTLS       = PR_FALSE;
6693     PRBool               isTLS12     = PR_FALSE;
6694     int                  i;
6695     int                  errCode     = SSL_ERROR_RX_MALFORMED_CERT_REQUEST;
6696     int                  nnames      = 0;
6697     SECStatus            rv;
6698     SSL3AlertDescription desc        = illegal_parameter;
6699     SECItem              cert_types  = {siBuffer, NULL, 0};
6700     SECItem              algorithms  = {siBuffer, NULL, 0};
6701     CERTDistNames        ca_list;
6702
6703     SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_request handshake",
6704                 SSL_GETPID(), ss->fd));
6705     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
6706     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
6707
6708     if (ss->ssl3.hs.ws != wait_cert_request &&
6709         ss->ssl3.hs.ws != wait_server_key) {
6710         desc    = unexpected_message;
6711         errCode = SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST;
6712         goto alert_loser;
6713     }
6714
6715     PORT_Assert(ss->ssl3.clientCertChain == NULL);
6716     PORT_Assert(ss->ssl3.clientCertificate == NULL);
6717     PORT_Assert(ss->ssl3.clientPrivateKey == NULL);
6718
6719     isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
6720     isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
6721     rv = ssl3_ConsumeHandshakeVariable(ss, &cert_types, 1, &b, &length);
6722     if (rv != SECSuccess)
6723         goto loser;             /* malformed, alert has been sent */
6724
6725     if (isTLS12) {
6726         rv = ssl3_ConsumeHandshakeVariable(ss, &algorithms, 2, &b, &length);
6727         if (rv != SECSuccess)
6728             goto loser;         /* malformed, alert has been sent */
6729         /* An empty or odd-length value is invalid.
6730          *    SignatureAndHashAlgorithm
6731          *      supported_signature_algorithms<2..2^16-2>;
6732          */
6733         if (algorithms.len == 0 || (algorithms.len & 1) != 0)
6734             goto alert_loser;
6735     }
6736
6737     arena = ca_list.arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
6738     if (arena == NULL)
6739         goto no_mem;
6740
6741     remaining = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
6742     if (remaining < 0)
6743         goto loser;             /* malformed, alert has been sent */
6744
6745     if ((PRUint32)remaining > length)
6746         goto alert_loser;
6747
6748     ca_list.head = node = PORT_ArenaZNew(arena, dnameNode);
6749     if (node == NULL)
6750         goto no_mem;
6751
6752     while (remaining > 0) {
6753         PRInt32 len;
6754
6755         if (remaining < 2)
6756             goto alert_loser;   /* malformed */
6757
6758         node->name.len = len = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
6759         if (len <= 0)
6760             goto loser;         /* malformed, alert has been sent */
6761
6762         remaining -= 2;
6763         if (remaining < len)
6764             goto alert_loser;   /* malformed */
6765
6766         node->name.data = b;
6767         b         += len;
6768         length    -= len;
6769         remaining -= len;
6770         nnames++;
6771         if (remaining <= 0)
6772             break;              /* success */
6773
6774         node->next = PORT_ArenaZNew(arena, dnameNode);
6775         node = node->next;
6776         if (node == NULL)
6777             goto no_mem;
6778     }
6779
6780     ca_list.nnames = nnames;
6781     ca_list.names  = PORT_ArenaNewArray(arena, SECItem, nnames);
6782     if (nnames > 0 && ca_list.names == NULL)
6783         goto no_mem;
6784
6785     for(i = 0, node = (dnameNode*)ca_list.head;
6786         i < nnames;
6787         i++, node = node->next) {
6788         ca_list.names[i] = node->name;
6789     }
6790
6791     if (length != 0)
6792         goto alert_loser;       /* malformed */
6793
6794     desc = no_certificate;
6795     ss->ssl3.hs.ws = wait_hello_done;
6796
6797     if (ss->getClientAuthData != NULL) {
6798         /* XXX Should pass cert_types and algorithms in this call!! */
6799         rv = (SECStatus)(*ss->getClientAuthData)(ss->getClientAuthDataArg,
6800                                                  ss->fd, &ca_list,
6801                                                  &ss->ssl3.clientCertificate,
6802                                                  &ss->ssl3.clientPrivateKey);
6803     } else {
6804         rv = SECFailure; /* force it to send a no_certificate alert */
6805     }
6806     switch (rv) {
6807     case SECWouldBlock: /* getClientAuthData has put up a dialog box. */
6808         ssl3_SetAlwaysBlock(ss);
6809         break;  /* not an error */
6810
6811     case SECSuccess:
6812         /* check what the callback function returned */
6813         if ((!ss->ssl3.clientCertificate) || (!ss->ssl3.clientPrivateKey)) {
6814             /* we are missing either the key or cert */
6815             if (ss->ssl3.clientCertificate) {
6816                 /* got a cert, but no key - free it */
6817                 CERT_DestroyCertificate(ss->ssl3.clientCertificate);
6818                 ss->ssl3.clientCertificate = NULL;
6819             }
6820             if (ss->ssl3.clientPrivateKey) {
6821                 /* got a key, but no cert - free it */
6822                 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
6823                 ss->ssl3.clientPrivateKey = NULL;
6824             }
6825             goto send_no_certificate;
6826         }
6827         /* Setting ssl3.clientCertChain non-NULL will cause
6828          * ssl3_HandleServerHelloDone to call SendCertificate.
6829          */
6830         ss->ssl3.clientCertChain = CERT_CertChainFromCert(
6831                                         ss->ssl3.clientCertificate,
6832                                         certUsageSSLClient, PR_FALSE);
6833         if (ss->ssl3.clientCertChain == NULL) {
6834             if (ss->ssl3.clientCertificate != NULL) {
6835                 CERT_DestroyCertificate(ss->ssl3.clientCertificate);
6836                 ss->ssl3.clientCertificate = NULL;
6837             }
6838             if (ss->ssl3.clientPrivateKey != NULL) {
6839                 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
6840                 ss->ssl3.clientPrivateKey = NULL;
6841             }
6842             goto send_no_certificate;
6843         }
6844         break;  /* not an error */
6845
6846     case SECFailure:
6847     default:
6848 send_no_certificate:
6849         if (isTLS) {
6850             ss->ssl3.sendEmptyCert = PR_TRUE;
6851         } else {
6852             (void)SSL3_SendAlert(ss, alert_warning, no_certificate);
6853         }
6854         rv = SECSuccess;
6855         break;
6856     }
6857     goto done;
6858
6859 no_mem:
6860     rv = SECFailure;
6861     PORT_SetError(SEC_ERROR_NO_MEMORY);
6862     goto done;
6863
6864 alert_loser:
6865     if (isTLS && desc == illegal_parameter)
6866         desc = decode_error;
6867     (void)SSL3_SendAlert(ss, alert_fatal, desc);
6868 loser:
6869     PORT_SetError(errCode);
6870     rv = SECFailure;
6871 done:
6872     if (arena != NULL)
6873         PORT_FreeArena(arena, PR_FALSE);
6874     return rv;
6875 }
6876
6877 PRBool
6878 ssl3_CanFalseStart(sslSocket *ss) {
6879     PRBool rv;
6880
6881     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
6882
6883     /* XXX: does not take into account whether we are waiting for
6884      * SSL_AuthCertificateComplete or SSL_RestartHandshakeAfterCertReq. If/when
6885      * that is done, this function could return different results each time it
6886      * would be called.
6887      */
6888
6889     ssl_GetSpecReadLock(ss);
6890     rv = ss->opt.enableFalseStart &&
6891          !ss->sec.isServer &&
6892          !ss->ssl3.hs.isResuming &&
6893          ss->ssl3.cwSpec &&
6894
6895          /* An attacker can control the selected ciphersuite so we only wish to
6896           * do False Start in the case that the selected ciphersuite is
6897           * sufficiently strong that the attack can gain no advantage.
6898           * Therefore we require an 80-bit cipher and a forward-secret key
6899           * exchange. */
6900          ss->ssl3.cwSpec->cipher_def->secret_key_size >= 10 &&
6901         (ss->ssl3.hs.kea_def->kea == kea_dhe_dss ||
6902          ss->ssl3.hs.kea_def->kea == kea_dhe_rsa ||
6903          ss->ssl3.hs.kea_def->kea == kea_ecdhe_ecdsa ||
6904          ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa);
6905     ssl_ReleaseSpecReadLock(ss);
6906     return rv;
6907 }
6908
6909 static SECStatus ssl3_SendClientSecondRound(sslSocket *ss);
6910
6911 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
6912  * ssl3 Server Hello Done message.
6913  * Caller must hold Handshake and RecvBuf locks.
6914  */
6915 static SECStatus
6916 ssl3_HandleServerHelloDone(sslSocket *ss)
6917 {
6918     SECStatus     rv;
6919     SSL3WaitState ws          = ss->ssl3.hs.ws;
6920
6921     SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello_done handshake",
6922                 SSL_GETPID(), ss->fd));
6923     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
6924     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
6925
6926     if (ws != wait_hello_done  &&
6927         ws != wait_server_cert &&
6928         ws != wait_server_key  &&
6929         ws != wait_cert_request) {
6930         SSL3_SendAlert(ss, alert_fatal, unexpected_message);
6931         PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE);
6932         return SECFailure;
6933     }
6934
6935     rv = ssl3_SendClientSecondRound(ss);
6936
6937     return rv;
6938 }
6939
6940 /* Called from ssl3_HandleServerHelloDone and ssl3_AuthCertificateComplete.
6941  *
6942  * Caller must hold Handshake and RecvBuf locks.
6943  */
6944 static SECStatus
6945 ssl3_SendClientSecondRound(sslSocket *ss)
6946 {
6947     SECStatus rv;
6948     PRBool sendClientCert;
6949
6950     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
6951     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
6952
6953     sendClientCert = !ss->ssl3.sendEmptyCert &&
6954                      ss->ssl3.clientCertChain  != NULL &&
6955                      ss->ssl3.clientPrivateKey != NULL;
6956
6957     /* We must wait for the server's certificate to be authenticated before
6958      * sending the client certificate in order to disclosing the client
6959      * certificate to an attacker that does not have a valid cert for the
6960      * domain we are connecting to.
6961      *
6962      * XXX: We should do the same for the NPN extension, but for that we
6963      * need an option to give the application the ability to leak the NPN
6964      * information to get better performance.
6965      *
6966      * During the initial handshake on a connection, we never send/receive
6967      * application data until we have authenticated the server's certificate;
6968      * i.e. we have fully authenticated the handshake before using the cipher
6969      * specs agreed upon for that handshake. During a renegotiation, we may
6970      * continue sending and receiving application data during the handshake
6971      * interleaved with the handshake records. If we were to send the client's
6972      * second round for a renegotiation before the server's certificate was
6973      * authenticated, then the application data sent/received after this point
6974      * would be using cipher spec that hadn't been authenticated. By waiting
6975      * until the server's certificate has been authenticated during
6976      * renegotiations, we ensure that renegotiations have the same property
6977      * as initial handshakes; i.e. we have fully authenticated the handshake
6978      * before using the cipher specs agreed upon for that handshake for
6979      * application data.
6980      */
6981     if (ss->ssl3.hs.restartTarget) {
6982         PR_NOT_REACHED("unexpected ss->ssl3.hs.restartTarget");
6983         PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
6984         return SECFailure;
6985     }
6986     if (ss->ssl3.hs.authCertificatePending &&
6987         (sendClientCert || ss->ssl3.sendEmptyCert || ss->firstHsDone)) {
6988         ss->ssl3.hs.restartTarget = ssl3_SendClientSecondRound;
6989         return SECWouldBlock;
6990     }
6991
6992     ssl_GetXmitBufLock(ss);             /*******************************/
6993
6994     if (ss->ssl3.sendEmptyCert) {
6995         ss->ssl3.sendEmptyCert = PR_FALSE;
6996         rv = ssl3_SendEmptyCertificate(ss);
6997         /* Don't send verify */
6998         if (rv != SECSuccess) {
6999             goto loser; /* error code is set. */
7000         }
7001     } else if (sendClientCert) {
7002         rv = ssl3_SendCertificate(ss);
7003         if (rv != SECSuccess) {
7004             goto loser; /* error code is set. */
7005         }
7006     }
7007
7008     rv = ssl3_SendClientKeyExchange(ss);
7009     if (rv != SECSuccess) {
7010         goto loser;     /* err is set. */
7011     }
7012
7013     if (sendClientCert) {
7014         rv = ssl3_SendCertificateVerify(ss);
7015         if (rv != SECSuccess) {
7016             goto loser; /* err is set. */
7017         }
7018     }
7019
7020     rv = ssl3_SendChangeCipherSpecs(ss);
7021     if (rv != SECSuccess) {
7022         goto loser;     /* err code was set. */
7023     }
7024
7025     /* XXX: If the server's certificate hasn't been authenticated by this
7026      * point, then we may be leaking this NPN message to an attacker.
7027      */
7028     if (!ss->firstHsDone) {
7029         rv = ssl3_SendNextProto(ss);
7030         if (rv != SECSuccess) {
7031             goto loser; /* err code was set. */
7032         }
7033     }
7034
7035     rv = ssl3_SendFinished(ss, 0);
7036     if (rv != SECSuccess) {
7037         goto loser;     /* err code was set. */
7038     }
7039
7040     ssl_ReleaseXmitBufLock(ss);         /*******************************/
7041
7042     if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn))
7043         ss->ssl3.hs.ws = wait_new_session_ticket;
7044     else
7045         ss->ssl3.hs.ws = wait_change_cipher;
7046
7047     /* Do the handshake callback for sslv3 here, if we can false start. */
7048     if (ss->handshakeCallback != NULL && ssl3_CanFalseStart(ss)) {
7049         (ss->handshakeCallback)(ss->fd, ss->handshakeCallbackData);
7050     }
7051
7052     return SECSuccess;
7053
7054 loser:
7055     ssl_ReleaseXmitBufLock(ss);
7056     return rv;
7057 }
7058
7059 /*
7060  * Routines used by servers
7061  */
7062 static SECStatus
7063 ssl3_SendHelloRequest(sslSocket *ss)
7064 {
7065     SECStatus rv;
7066
7067     SSL_TRC(3, ("%d: SSL3[%d]: send hello_request handshake", SSL_GETPID(),
7068                 ss->fd));
7069
7070     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
7071     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
7072
7073     rv = ssl3_AppendHandshakeHeader(ss, hello_request, 0);
7074     if (rv != SECSuccess) {
7075         return rv;      /* err set by AppendHandshake */
7076     }
7077     rv = ssl3_FlushHandshake(ss, 0);
7078     if (rv != SECSuccess) {
7079         return rv;      /* error code set by ssl3_FlushHandshake */
7080     }
7081     ss->ssl3.hs.ws = wait_client_hello;
7082     return SECSuccess;
7083 }
7084
7085 /*
7086  * Called from:
7087  *      ssl3_HandleClientHello()
7088  */
7089 static SECComparison
7090 ssl3_ServerNameCompare(const SECItem *name1, const SECItem *name2)
7091 {
7092     if (!name1 != !name2) {
7093         return SECLessThan;
7094     }
7095     if (!name1) {
7096         return SECEqual;
7097     }
7098     if (name1->type != name2->type) {
7099         return SECLessThan;
7100     }
7101     return SECITEM_CompareItem(name1, name2);
7102 }
7103
7104 /* Sets memory error when returning NULL.
7105  * Called from:
7106  *      ssl3_SendClientHello()
7107  *      ssl3_HandleServerHello()
7108  *      ssl3_HandleClientHello()
7109  *      ssl3_HandleV2ClientHello()
7110  */
7111 sslSessionID *
7112 ssl3_NewSessionID(sslSocket *ss, PRBool is_server)
7113 {
7114     sslSessionID *sid;
7115
7116     sid = PORT_ZNew(sslSessionID);
7117     if (sid == NULL)
7118         return sid;
7119
7120     if (is_server) {
7121         const SECItem *  srvName;
7122         SECStatus        rv = SECSuccess;
7123
7124         ssl_GetSpecReadLock(ss);        /********************************/
7125         srvName = &ss->ssl3.prSpec->srvVirtName;
7126         if (srvName->len && srvName->data) {
7127             rv = SECITEM_CopyItem(NULL, &sid->u.ssl3.srvName, srvName);
7128         }
7129         ssl_ReleaseSpecReadLock(ss); /************************************/
7130         if (rv != SECSuccess) {
7131             PORT_Free(sid);
7132             return NULL;
7133         }
7134     }
7135     sid->peerID         = (ss->peerID == NULL) ? NULL : PORT_Strdup(ss->peerID);
7136     sid->urlSvrName     = (ss->url    == NULL) ? NULL : PORT_Strdup(ss->url);
7137     sid->addr           = ss->sec.ci.peer;
7138     sid->port           = ss->sec.ci.port;
7139     sid->references     = 1;
7140     sid->cached         = never_cached;
7141     sid->version        = ss->version;
7142
7143     sid->u.ssl3.keys.resumable = PR_TRUE;
7144     sid->u.ssl3.policy         = SSL_ALLOWED;
7145     sid->u.ssl3.clientWriteKey = NULL;
7146     sid->u.ssl3.serverWriteKey = NULL;
7147
7148     if (is_server) {
7149         SECStatus rv;
7150         int       pid = SSL_GETPID();
7151
7152         sid->u.ssl3.sessionIDLength = SSL3_SESSIONID_BYTES;
7153         sid->u.ssl3.sessionID[0]    = (pid >> 8) & 0xff;
7154         sid->u.ssl3.sessionID[1]    =  pid       & 0xff;
7155         rv = PK11_GenerateRandom(sid->u.ssl3.sessionID + 2,
7156                                  SSL3_SESSIONID_BYTES -2);
7157         if (rv != SECSuccess) {
7158             ssl_FreeSID(sid);
7159             ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
7160             return NULL;
7161         }
7162     }
7163     return sid;
7164 }
7165
7166 /* Called from:  ssl3_HandleClientHello, ssl3_HandleV2ClientHello */
7167 static SECStatus
7168 ssl3_SendServerHelloSequence(sslSocket *ss)
7169 {
7170     const ssl3KEADef *kea_def;
7171     SECStatus         rv;
7172
7173     SSL_TRC(3, ("%d: SSL3[%d]: begin send server_hello sequence",
7174                 SSL_GETPID(), ss->fd));
7175
7176     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
7177     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
7178
7179     rv = ssl3_SendServerHello(ss);
7180     if (rv != SECSuccess) {
7181         return rv;      /* err code is set. */
7182     }
7183     rv = ssl3_SendCertificate(ss);
7184     if (rv != SECSuccess) {
7185         return rv;      /* error code is set. */
7186     }
7187     rv = ssl3_SendCertificateStatus(ss);
7188     if (rv != SECSuccess) {
7189         return rv;      /* error code is set. */
7190     }
7191     /* We have to do this after the call to ssl3_SendServerHello,
7192      * because kea_def is set up by ssl3_SendServerHello().
7193      */
7194     kea_def = ss->ssl3.hs.kea_def;
7195     ss->ssl3.hs.usedStepDownKey = PR_FALSE;
7196
7197     if (kea_def->is_limited && kea_def->exchKeyType == kt_rsa) {
7198         /* see if we can legally use the key in the cert. */
7199         int keyLen;  /* bytes */
7200
7201         keyLen = PK11_GetPrivateModulusLen(
7202                             ss->serverCerts[kea_def->exchKeyType].SERVERKEY);
7203
7204         if (keyLen > 0 &&
7205             keyLen * BPB <= kea_def->key_size_limit ) {
7206             /* XXX AND cert is not signing only!! */
7207             /* just fall through and use it. */
7208         } else if (ss->stepDownKeyPair != NULL) {
7209             ss->ssl3.hs.usedStepDownKey = PR_TRUE;
7210             rv = ssl3_SendServerKeyExchange(ss);
7211             if (rv != SECSuccess) {
7212                 return rv;      /* err code was set. */
7213             }
7214         } else {
7215 #ifndef HACKED_EXPORT_SERVER
7216             PORT_SetError(SSL_ERROR_PUB_KEY_SIZE_LIMIT_EXCEEDED);
7217             return rv;
7218 #endif
7219         }
7220 #ifdef NSS_ENABLE_ECC
7221     } else if ((kea_def->kea == kea_ecdhe_rsa) ||
7222                (kea_def->kea == kea_ecdhe_ecdsa)) {
7223         rv = ssl3_SendServerKeyExchange(ss);
7224         if (rv != SECSuccess) {
7225             return rv;  /* err code was set. */
7226         }
7227 #endif /* NSS_ENABLE_ECC */
7228     }
7229
7230     if (ss->opt.requestCertificate) {
7231         rv = ssl3_SendCertificateRequest(ss);
7232         if (rv != SECSuccess) {
7233             return rv;          /* err code is set. */
7234         }
7235     }
7236     rv = ssl3_SendServerHelloDone(ss);
7237     if (rv != SECSuccess) {
7238         return rv;              /* err code is set. */
7239     }
7240
7241     ss->ssl3.hs.ws = (ss->opt.requestCertificate) ? wait_client_cert
7242                                                : wait_client_key;
7243     return SECSuccess;
7244 }
7245
7246 /* An empty TLS Renegotiation Info (RI) extension */
7247 static const PRUint8 emptyRIext[5] = {0xff, 0x01, 0x00, 0x01, 0x00};
7248
7249 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
7250  * ssl3 Client Hello message.
7251  * Caller must hold Handshake and RecvBuf locks.
7252  */
7253 static SECStatus
7254 ssl3_HandleClientHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
7255 {
7256     sslSessionID *      sid      = NULL;
7257     PRInt32             tmp;
7258     unsigned int        i;
7259     int                 j;
7260     SECStatus           rv;
7261     int                 errCode  = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
7262     SSL3AlertDescription desc    = illegal_parameter;
7263     SSL3AlertLevel      level    = alert_fatal;
7264     SSL3ProtocolVersion version;
7265     SECItem             sidBytes = {siBuffer, NULL, 0};
7266     SECItem             cookieBytes = {siBuffer, NULL, 0};
7267     SECItem             suites   = {siBuffer, NULL, 0};
7268     SECItem             comps    = {siBuffer, NULL, 0};
7269     PRBool              haveSpecWriteLock = PR_FALSE;
7270     PRBool              haveXmitBufLock   = PR_FALSE;
7271
7272     SSL_TRC(3, ("%d: SSL3[%d]: handle client_hello handshake",
7273         SSL_GETPID(), ss->fd));
7274
7275     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
7276     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
7277     PORT_Assert( ss->ssl3.initialized );
7278
7279     /* Get peer name of client */
7280     rv = ssl_GetPeerInfo(ss);
7281     if (rv != SECSuccess) {
7282         return rv;              /* error code is set. */
7283     }
7284
7285     /* Clearing the handshake pointers so that ssl_Do1stHandshake won't
7286      * call ssl2_HandleMessage.
7287      *
7288      * The issue here is that TLS ordinarily starts out in
7289      * ssl2_HandleV3HandshakeRecord() because of the backward-compatibility
7290      * code paths. That function zeroes these next pointers. But with DTLS,
7291      * we don't even try to do the v2 ClientHello so we skip that function
7292      * and need to reset these values here.
7293      */
7294     if (IS_DTLS(ss)) {
7295         ss->nextHandshake     = 0;
7296         ss->securityHandshake = 0;
7297     }
7298
7299     /* We might be starting session renegotiation in which case we should
7300      * clear previous state.
7301      */
7302     PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData));
7303     ss->statelessResume = PR_FALSE;
7304
7305     if ((ss->ssl3.hs.ws != wait_client_hello) &&
7306         (ss->ssl3.hs.ws != idle_handshake)) {
7307         desc    = unexpected_message;
7308         errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO;
7309         goto alert_loser;
7310     }
7311     if (ss->ssl3.hs.ws == idle_handshake  &&
7312         ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) {
7313         desc    = no_renegotiation;
7314         level   = alert_warning;
7315         errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED;
7316         goto alert_loser;
7317     }
7318
7319     if (IS_DTLS(ss)) {
7320         dtls_RehandshakeCleanup(ss);
7321     }
7322
7323     tmp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
7324     if (tmp < 0)
7325         goto loser;             /* malformed, alert already sent */
7326
7327     /* Translate the version */
7328     if (IS_DTLS(ss)) {
7329         ss->clientHelloVersion = version =
7330             dtls_DTLSVersionToTLSVersion((SSL3ProtocolVersion)tmp);
7331     } else {
7332         ss->clientHelloVersion = version = (SSL3ProtocolVersion)tmp;
7333     }
7334
7335     rv = ssl3_NegotiateVersion(ss, version, PR_TRUE);
7336     if (rv != SECSuccess) {
7337         desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version 
7338                                                    : handshake_failure;
7339         errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
7340         goto alert_loser;
7341     }
7342
7343     rv = ssl3_InitHandshakeHashes(ss);
7344     if (rv != SECSuccess) {
7345         desc = internal_error;
7346         errCode = PORT_GetError();
7347         goto alert_loser;
7348     }
7349
7350     /* grab the client random data. */
7351     rv = ssl3_ConsumeHandshake(
7352         ss, &ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH, &b, &length);
7353     if (rv != SECSuccess) {
7354         goto loser;             /* malformed */
7355     }
7356
7357     /* grab the client's SID, if present. */
7358     rv = ssl3_ConsumeHandshakeVariable(ss, &sidBytes, 1, &b, &length);
7359     if (rv != SECSuccess) {
7360         goto loser;             /* malformed */
7361     }
7362
7363     /* grab the client's cookie, if present. */
7364     if (IS_DTLS(ss)) {
7365         rv = ssl3_ConsumeHandshakeVariable(ss, &cookieBytes, 1, &b, &length);
7366         if (rv != SECSuccess) {
7367             goto loser;         /* malformed */
7368         }
7369     }
7370
7371     /* grab the list of cipher suites. */
7372     rv = ssl3_ConsumeHandshakeVariable(ss, &suites, 2, &b, &length);
7373     if (rv != SECSuccess) {
7374         goto loser;             /* malformed */
7375     }
7376
7377     /* grab the list of compression methods. */
7378     rv = ssl3_ConsumeHandshakeVariable(ss, &comps, 1, &b, &length);
7379     if (rv != SECSuccess) {
7380         goto loser;             /* malformed */
7381     }
7382
7383     desc = handshake_failure;
7384
7385     /* Handle TLS hello extensions for SSL3 & TLS. We do not know if
7386      * we are restarting a previous session until extensions have been
7387      * parsed, since we might have received a SessionTicket extension.
7388      * Note: we allow extensions even when negotiating SSL3 for the sake
7389      * of interoperability (and backwards compatibility).
7390      */
7391
7392     if (length) {
7393         /* Get length of hello extensions */
7394         PRInt32 extension_length;
7395         extension_length = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
7396         if (extension_length < 0) {
7397             goto loser;                         /* alert already sent */
7398         }
7399         if (extension_length != length) {
7400             ssl3_DecodeError(ss);               /* send alert */
7401             goto loser;
7402         }
7403         rv = ssl3_HandleHelloExtensions(ss, &b, &length);
7404         if (rv != SECSuccess) {
7405             goto loser;         /* malformed */
7406         }
7407     }
7408     if (!ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
7409         /* If we didn't receive an RI extension, look for the SCSV,
7410          * and if found, treat it just like an empty RI extension
7411          * by processing a local copy of an empty RI extension.
7412          */
7413         for (i = 0; i + 1 < suites.len; i += 2) {
7414             PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1];
7415             if (suite_i == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) {
7416                 SSL3Opaque * b2 = (SSL3Opaque *)emptyRIext;
7417                 PRUint32     L2 = sizeof emptyRIext;
7418                 (void)ssl3_HandleHelloExtensions(ss, &b2, &L2);
7419                 break;
7420             }
7421         }
7422     }
7423     if (ss->firstHsDone &&
7424         (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_REQUIRES_XTN ||
7425         ss->opt.enableRenegotiation == SSL_RENEGOTIATE_TRANSITIONAL) && 
7426         !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
7427         desc    = no_renegotiation;
7428         level   = alert_warning;
7429         errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED;
7430         goto alert_loser;
7431     }
7432     if ((ss->opt.requireSafeNegotiation || 
7433          (ss->firstHsDone && ss->peerRequestedProtection)) &&
7434         !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
7435         desc = handshake_failure;
7436         errCode = SSL_ERROR_UNSAFE_NEGOTIATION;
7437         goto alert_loser;
7438     }
7439
7440     /* We do stateful resumes only if either of the following
7441      * conditions are satisfied: (1) the client does not support the
7442      * session ticket extension, or (2) the client support the session
7443      * ticket extension, but sent an empty ticket.
7444      */
7445     if (!ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) ||
7446         ss->xtnData.emptySessionTicket) {
7447         if (sidBytes.len > 0 && !ss->opt.noCache) {
7448             SSL_TRC(7, ("%d: SSL3[%d]: server, lookup client session-id for 0x%08x%08x%08x%08x",
7449                         SSL_GETPID(), ss->fd, ss->sec.ci.peer.pr_s6_addr32[0],
7450                         ss->sec.ci.peer.pr_s6_addr32[1], 
7451                         ss->sec.ci.peer.pr_s6_addr32[2],
7452                         ss->sec.ci.peer.pr_s6_addr32[3]));
7453             if (ssl_sid_lookup) {
7454                 sid = (*ssl_sid_lookup)(&ss->sec.ci.peer, sidBytes.data, 
7455                                         sidBytes.len, ss->dbHandle);
7456             } else {
7457                 errCode = SSL_ERROR_SERVER_CACHE_NOT_CONFIGURED;
7458                 goto loser;
7459             }
7460         }
7461     } else if (ss->statelessResume) {
7462         /* Fill in the client's session ID if doing a stateless resume.
7463          * (When doing stateless resumes, server echos client's SessionID.)
7464          */
7465         sid = ss->sec.ci.sid;
7466         PORT_Assert(sid != NULL);  /* Should have already been filled in.*/
7467
7468         if (sidBytes.len > 0 && sidBytes.len <= SSL3_SESSIONID_BYTES) {
7469             sid->u.ssl3.sessionIDLength = sidBytes.len;
7470             PORT_Memcpy(sid->u.ssl3.sessionID, sidBytes.data,
7471                 sidBytes.len);
7472             sid->u.ssl3.sessionIDLength = sidBytes.len;
7473         } else {
7474             sid->u.ssl3.sessionIDLength = 0;
7475         }
7476         ss->sec.ci.sid = NULL;
7477     }
7478
7479     /* We only send a session ticket extension if the client supports
7480      * the extension and we are unable to do either a stateful or
7481      * stateless resume.
7482      *
7483      * TODO: send a session ticket if performing a stateful
7484      * resumption.  (As per RFC4507, a server may issue a session
7485      * ticket while doing a (stateless or stateful) session resume,
7486      * but OpenSSL-0.9.8g does not accept session tickets while
7487      * resuming.)
7488      */
7489     if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) && sid == NULL) {
7490         ssl3_RegisterServerHelloExtensionSender(ss,
7491             ssl_session_ticket_xtn, ssl3_SendSessionTicketXtn);
7492     }
7493
7494     if (sid != NULL) {
7495         /* We've found a session cache entry for this client.
7496          * Now, if we're going to require a client-auth cert,
7497          * and we don't already have this client's cert in the session cache,
7498          * and this is the first handshake on this connection (not a redo),
7499          * then drop this old cache entry and start a new session.
7500          */
7501         if ((sid->peerCert == NULL) && ss->opt.requestCertificate &&
7502             ((ss->opt.requireCertificate == SSL_REQUIRE_ALWAYS) ||
7503              (ss->opt.requireCertificate == SSL_REQUIRE_NO_ERROR) ||
7504              ((ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE) 
7505               && !ss->firstHsDone))) {
7506
7507             SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_not_ok );
7508             if (ss->sec.uncache)
7509                 ss->sec.uncache(sid);
7510             ssl_FreeSID(sid);
7511             sid = NULL;
7512         }
7513     }
7514
7515 #ifdef NSS_ENABLE_ECC
7516     /* Disable any ECC cipher suites for which we have no cert. */
7517     ssl3_FilterECCipherSuitesByServerCerts(ss);
7518 #endif
7519
7520     if (IS_DTLS(ss)) {
7521         ssl3_DisableNonDTLSSuites(ss);
7522     }
7523
7524 #ifdef PARANOID
7525     /* Look for a matching cipher suite. */
7526     j = ssl3_config_match_init(ss);
7527     if (j <= 0) {               /* no ciphers are working/supported by PK11 */
7528         errCode = PORT_GetError();      /* error code is already set. */
7529         goto alert_loser;
7530     }
7531 #endif
7532
7533     /* If we already have a session for this client, be sure to pick the
7534     ** same cipher suite and compression method we picked before.
7535     ** This is not a loop, despite appearances.
7536     */
7537     if (sid) do {
7538         ssl3CipherSuiteCfg *suite;
7539 #ifdef PARANOID
7540         SSLVersionRange vrange = {ss->version, ss->version};
7541 #endif
7542
7543         /* Check that the cached compression method is still enabled. */
7544         if (!compressionEnabled(ss, sid->u.ssl3.compression))
7545             break;
7546
7547         /* Check that the cached compression method is in the client's list */
7548         for (i = 0; i < comps.len; i++) {
7549             if (comps.data[i] == sid->u.ssl3.compression)
7550                 break;
7551         }
7552         if (i == comps.len)
7553             break;
7554
7555         suite = ss->cipherSuites;
7556         /* Find the entry for the cipher suite used in the cached session. */
7557         for (j = ssl_V3_SUITES_IMPLEMENTED; j > 0; --j, ++suite) {
7558             if (suite->cipher_suite == sid->u.ssl3.cipherSuite)
7559                 break;
7560         }
7561         PORT_Assert(j > 0);
7562         if (j <= 0)
7563             break;
7564 #ifdef PARANOID
7565         /* Double check that the cached cipher suite is still enabled,
7566          * implemented, and allowed by policy.  Might have been disabled.
7567          * The product policy won't change during the process lifetime.  
7568          * Implemented ("isPresent") shouldn't change for servers.
7569          */
7570         if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange))
7571             break;
7572 #else
7573         if (!suite->enabled)
7574             break;
7575 #endif
7576         /* Double check that the cached cipher suite is in the client's list */
7577         for (i = 0; i + 1 < suites.len; i += 2) {
7578             PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1];
7579             if (suite_i == suite->cipher_suite) {
7580                 ss->ssl3.hs.cipher_suite = suite->cipher_suite;
7581                 ss->ssl3.hs.suite_def =
7582                     ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite);
7583
7584                 /* Use the cached compression method. */
7585                 ss->ssl3.hs.compression = sid->u.ssl3.compression;
7586                 goto compression_found;
7587             }
7588         }
7589     } while (0);
7590
7591     /* START A NEW SESSION */
7592
7593 #ifndef PARANOID
7594     /* Look for a matching cipher suite. */
7595     j = ssl3_config_match_init(ss);
7596     if (j <= 0) {               /* no ciphers are working/supported by PK11 */
7597         errCode = PORT_GetError();      /* error code is already set. */
7598         goto alert_loser;
7599     }
7600 #endif
7601
7602     /* Select a cipher suite.
7603     **
7604     ** NOTE: This suite selection algorithm should be the same as the one in
7605     ** ssl3_HandleV2ClientHello().
7606     **
7607     ** If TLS 1.0 is enabled, we could handle the case where the client
7608     ** offered TLS 1.1 but offered only export cipher suites by choosing TLS
7609     ** 1.0 and selecting one of those export cipher suites. However, a secure
7610     ** TLS 1.1 client should not have export cipher suites enabled at all,
7611     ** and a TLS 1.1 client should definitely not be offering *only* export
7612     ** cipher suites. Therefore, we refuse to negotiate export cipher suites
7613     ** with any client that indicates support for TLS 1.1 or higher when we
7614     ** (the server) have TLS 1.1 support enabled.
7615     */
7616     for (j = 0; j < ssl_V3_SUITES_IMPLEMENTED; j++) {
7617         ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j];
7618         SSLVersionRange vrange = {ss->version, ss->version};
7619         if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange)) {
7620             continue;
7621         }
7622         for (i = 0; i + 1 < suites.len; i += 2) {
7623             PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1];
7624             if (suite_i == suite->cipher_suite) {
7625                 ss->ssl3.hs.cipher_suite = suite->cipher_suite;
7626                 ss->ssl3.hs.suite_def =
7627                     ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite);
7628                 goto suite_found;
7629             }
7630         }
7631     }
7632     errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
7633     goto alert_loser;
7634
7635 suite_found:
7636     /* Select a compression algorithm. */
7637     for (i = 0; i < comps.len; i++) {
7638         if (!compressionEnabled(ss, comps.data[i]))
7639             continue;
7640         for (j = 0; j < compressionMethodsCount; j++) {
7641             if (comps.data[i] == compressions[j]) {
7642                 ss->ssl3.hs.compression = 
7643                                         (SSLCompressionMethod)compressions[j];
7644                 goto compression_found;
7645             }
7646         }
7647     }
7648     errCode = SSL_ERROR_NO_COMPRESSION_OVERLAP;
7649                                 /* null compression must be supported */
7650     goto alert_loser;
7651
7652 compression_found:
7653     suites.data = NULL;
7654     comps.data = NULL;
7655
7656     ss->sec.send = ssl3_SendApplicationData;
7657
7658     /* If there are any failures while processing the old sid,
7659      * we don't consider them to be errors.  Instead, We just behave
7660      * as if the client had sent us no sid to begin with, and make a new one.
7661      */
7662     if (sid != NULL) do {
7663         ssl3CipherSpec *pwSpec;
7664         SECItem         wrappedMS;      /* wrapped key */
7665
7666         if (sid->version != ss->version  ||
7667             sid->u.ssl3.cipherSuite != ss->ssl3.hs.cipher_suite ||
7668             sid->u.ssl3.compression != ss->ssl3.hs.compression) {
7669             break;      /* not an error */
7670         }
7671
7672         if (ss->sec.ci.sid) {
7673             if (ss->sec.uncache)
7674                 ss->sec.uncache(ss->sec.ci.sid);
7675             PORT_Assert(ss->sec.ci.sid != sid);  /* should be impossible, but ... */
7676             if (ss->sec.ci.sid != sid) {
7677                 ssl_FreeSID(ss->sec.ci.sid);
7678             }
7679             ss->sec.ci.sid = NULL;
7680         }
7681         /* we need to resurrect the master secret.... */
7682
7683         ssl_GetSpecWriteLock(ss);  haveSpecWriteLock = PR_TRUE;
7684         pwSpec = ss->ssl3.pwSpec;
7685         if (sid->u.ssl3.keys.msIsWrapped) {
7686             PK11SymKey *    wrapKey;    /* wrapping key */
7687             CK_FLAGS        keyFlags      = 0;
7688 #ifndef NO_PKCS11_BYPASS
7689             if (ss->opt.bypassPKCS11) {
7690                 /* we cannot restart a non-bypass session in a 
7691                 ** bypass socket.
7692                 */
7693                 break;  
7694             }
7695 #endif
7696
7697             wrapKey = getWrappingKey(ss, NULL, sid->u.ssl3.exchKeyType,
7698                                      sid->u.ssl3.masterWrapMech, 
7699                                      ss->pkcs11PinArg);
7700             if (!wrapKey) {
7701                 /* we have a SID cache entry, but no wrapping key for it??? */
7702                 break;
7703             }
7704
7705             if (ss->version > SSL_LIBRARY_VERSION_3_0) {        /* isTLS */
7706                 keyFlags = CKF_SIGN | CKF_VERIFY;
7707             }
7708
7709             wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
7710             wrappedMS.len  = sid->u.ssl3.keys.wrapped_master_secret_len;
7711
7712             /* unwrap the master secret. */
7713             pwSpec->master_secret =
7714                 PK11_UnwrapSymKeyWithFlags(wrapKey, sid->u.ssl3.masterWrapMech, 
7715                             NULL, &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE,
7716                             CKA_DERIVE, sizeof(SSL3MasterSecret), keyFlags);
7717             PK11_FreeSymKey(wrapKey);
7718             if (pwSpec->master_secret == NULL) {
7719                 break;  /* not an error */
7720             }
7721 #ifndef NO_PKCS11_BYPASS
7722         } else if (ss->opt.bypassPKCS11) {
7723             wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
7724             wrappedMS.len  = sid->u.ssl3.keys.wrapped_master_secret_len;
7725             memcpy(pwSpec->raw_master_secret, wrappedMS.data, wrappedMS.len);
7726             pwSpec->msItem.data = pwSpec->raw_master_secret;
7727             pwSpec->msItem.len  = wrappedMS.len;
7728 #endif
7729         } else {
7730             /* We CAN restart a bypass session in a non-bypass socket. */
7731             /* need to import the raw master secret to session object */
7732             PK11SlotInfo * slot;
7733             wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
7734             wrappedMS.len  = sid->u.ssl3.keys.wrapped_master_secret_len;
7735             slot = PK11_GetInternalSlot();
7736             pwSpec->master_secret =  
7737                 PK11_ImportSymKey(slot, CKM_SSL3_MASTER_KEY_DERIVE, 
7738                                   PK11_OriginUnwrap, CKA_ENCRYPT, &wrappedMS, 
7739                                   NULL);
7740             PK11_FreeSlot(slot);
7741             if (pwSpec->master_secret == NULL) {
7742                 break;  /* not an error */
7743             }
7744         }
7745         ss->sec.ci.sid = sid;
7746         if (sid->peerCert != NULL) {
7747             ss->sec.peerCert = CERT_DupCertificate(sid->peerCert);
7748         }
7749
7750         /*
7751          * Old SID passed all tests, so resume this old session.
7752          *
7753          * XXX make sure compression still matches
7754          */
7755         SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_hits );
7756         if (ss->statelessResume)
7757             SSL_AtomicIncrementLong(& ssl3stats.hch_sid_stateless_resumes );
7758         ss->ssl3.hs.isResuming = PR_TRUE;
7759
7760         ss->sec.authAlgorithm = sid->authAlgorithm;
7761         ss->sec.authKeyBits   = sid->authKeyBits;
7762         ss->sec.keaType       = sid->keaType;
7763         ss->sec.keaKeyBits    = sid->keaKeyBits;
7764
7765         /* server sids don't remember the server cert we previously sent,
7766         ** but they do remember the kea type we originally used, so we
7767         ** can locate it again, provided that the current ssl socket
7768         ** has had its server certs configured the same as the previous one.
7769         */
7770         ss->sec.localCert     = 
7771                 CERT_DupCertificate(ss->serverCerts[sid->keaType].serverCert);
7772
7773         /* Copy cached name in to pending spec */
7774         if (sid != NULL &&
7775             sid->version > SSL_LIBRARY_VERSION_3_0 &&
7776             sid->u.ssl3.srvName.len && sid->u.ssl3.srvName.data) {
7777             /* Set server name from sid */
7778             SECItem *sidName = &sid->u.ssl3.srvName;
7779             SECItem *pwsName = &ss->ssl3.pwSpec->srvVirtName;
7780             if (pwsName->data) {
7781                 SECITEM_FreeItem(pwsName, PR_FALSE);
7782             }
7783             rv = SECITEM_CopyItem(NULL, pwsName, sidName);
7784             if (rv != SECSuccess) {
7785                 errCode = PORT_GetError();
7786                 desc = internal_error;
7787                 goto alert_loser;
7788             }
7789         }
7790
7791         /* Clean up sni name array */
7792         if (ssl3_ExtensionNegotiated(ss, ssl_server_name_xtn) &&
7793             ss->xtnData.sniNameArr) {
7794             PORT_Free(ss->xtnData.sniNameArr);
7795             ss->xtnData.sniNameArr = NULL;
7796             ss->xtnData.sniNameArrSize = 0;
7797         }
7798
7799         ssl_GetXmitBufLock(ss); haveXmitBufLock = PR_TRUE;
7800
7801         rv = ssl3_SendServerHello(ss);
7802         if (rv != SECSuccess) {
7803             errCode = PORT_GetError();
7804             goto loser;
7805         }
7806
7807         if (haveSpecWriteLock) {
7808             ssl_ReleaseSpecWriteLock(ss);
7809             haveSpecWriteLock = PR_FALSE;
7810         }
7811
7812         /* NULL value for PMS signifies re-use of the old MS */
7813         rv = ssl3_InitPendingCipherSpec(ss,  NULL);
7814         if (rv != SECSuccess) {
7815             errCode = PORT_GetError();
7816             goto loser;
7817         }
7818
7819         rv = ssl3_SendChangeCipherSpecs(ss);
7820         if (rv != SECSuccess) {
7821             errCode = PORT_GetError();
7822             goto loser;
7823         }
7824         rv = ssl3_SendFinished(ss, 0);
7825         ss->ssl3.hs.ws = wait_change_cipher;
7826         if (rv != SECSuccess) {
7827             errCode = PORT_GetError();
7828             goto loser;
7829         }
7830
7831         if (haveXmitBufLock) {
7832             ssl_ReleaseXmitBufLock(ss);
7833             haveXmitBufLock = PR_FALSE;
7834         }
7835
7836         return SECSuccess;
7837     } while (0);
7838
7839     if (haveSpecWriteLock) {
7840         ssl_ReleaseSpecWriteLock(ss);
7841         haveSpecWriteLock = PR_FALSE;
7842     }
7843
7844     if (sid) {  /* we had a sid, but it's no longer valid, free it */
7845         SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_not_ok );
7846         if (ss->sec.uncache)
7847             ss->sec.uncache(sid);
7848         ssl_FreeSID(sid);
7849         sid = NULL;
7850     }
7851     SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_misses );
7852
7853     if (ssl3_ExtensionNegotiated(ss, ssl_server_name_xtn)) {
7854         int ret = 0;
7855         if (ss->sniSocketConfig) do { /* not a loop */
7856             ret = SSL_SNI_SEND_ALERT;
7857             /* If extension is negotiated, the len of names should > 0. */
7858             if (ss->xtnData.sniNameArrSize) {
7859                 /* Calling client callback to reconfigure the socket. */
7860                 ret = (SECStatus)(*ss->sniSocketConfig)(ss->fd,
7861                                          ss->xtnData.sniNameArr,
7862                                       ss->xtnData.sniNameArrSize,
7863                                           ss->sniSocketConfigArg);
7864             }
7865             if (ret <= SSL_SNI_SEND_ALERT) {
7866                 /* Application does not know the name or was not able to
7867                  * properly reconfigure the socket. */
7868                 errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
7869                 desc = unrecognized_name;
7870                 break;
7871             } else if (ret == SSL_SNI_CURRENT_CONFIG_IS_USED) {
7872                 SECStatus       rv = SECSuccess;
7873                 SECItem *       cwsName, *pwsName;
7874
7875                 ssl_GetSpecWriteLock(ss);  /*******************************/
7876                 pwsName = &ss->ssl3.pwSpec->srvVirtName;
7877                 cwsName = &ss->ssl3.cwSpec->srvVirtName;
7878 #ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS
7879                 /* not allow name change on the 2d HS */
7880                 if (ss->firstHsDone) {
7881                     if (ssl3_ServerNameCompare(pwsName, cwsName)) {
7882                         ssl_ReleaseSpecWriteLock(ss);  /******************/
7883                         errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
7884                         desc = handshake_failure;
7885                         ret = SSL_SNI_SEND_ALERT;
7886                         break;
7887                     }
7888                 }
7889 #endif
7890                 if (pwsName->data) {
7891                     SECITEM_FreeItem(pwsName, PR_FALSE);
7892                 }
7893                 if (cwsName->data) {
7894                     rv = SECITEM_CopyItem(NULL, pwsName, cwsName);
7895                 }
7896                 ssl_ReleaseSpecWriteLock(ss);  /**************************/
7897                 if (rv != SECSuccess) {
7898                     errCode = SSL_ERROR_INTERNAL_ERROR_ALERT;
7899                     desc = internal_error;
7900                     ret = SSL_SNI_SEND_ALERT;
7901                     break;
7902                 }
7903             } else if (ret < ss->xtnData.sniNameArrSize) {
7904                 /* Application has configured new socket info. Lets check it
7905                  * and save the name. */
7906                 SECStatus       rv;
7907                 SECItem *       name = &ss->xtnData.sniNameArr[ret];
7908                 int             configedCiphers;
7909                 SECItem *       pwsName;
7910
7911                 /* get rid of the old name and save the newly picked. */
7912                 /* This code is protected by ssl3HandshakeLock. */
7913                 ssl_GetSpecWriteLock(ss);  /*******************************/
7914 #ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS
7915                 /* not allow name change on the 2d HS */
7916                 if (ss->firstHsDone) {
7917                     SECItem *cwsName = &ss->ssl3.cwSpec->srvVirtName;
7918                     if (ssl3_ServerNameCompare(name, cwsName)) {
7919                         ssl_ReleaseSpecWriteLock(ss);  /******************/
7920                         errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
7921                         desc = handshake_failure;
7922                         ret = SSL_SNI_SEND_ALERT;
7923                         break;
7924                     }
7925                 }
7926 #endif
7927                 pwsName = &ss->ssl3.pwSpec->srvVirtName;
7928                 if (pwsName->data) {
7929                     SECITEM_FreeItem(pwsName, PR_FALSE);
7930                 }
7931                 rv = SECITEM_CopyItem(NULL, pwsName, name);
7932                 ssl_ReleaseSpecWriteLock(ss);  /***************************/
7933                 if (rv != SECSuccess) {
7934                     errCode = SSL_ERROR_INTERNAL_ERROR_ALERT;
7935                     desc = internal_error;
7936                     ret = SSL_SNI_SEND_ALERT;
7937                     break;
7938                 }
7939                 configedCiphers = ssl3_config_match_init(ss);
7940                 if (configedCiphers <= 0) {
7941                     /* no ciphers are working/supported */
7942                     errCode = PORT_GetError();
7943                     desc = handshake_failure;
7944                     ret = SSL_SNI_SEND_ALERT;
7945                     break;
7946                 }
7947                 /* Need to tell the client that application has picked
7948                  * the name from the offered list and reconfigured the socket.
7949                  */
7950                 ssl3_RegisterServerHelloExtensionSender(ss, ssl_server_name_xtn,
7951                                                         ssl3_SendServerNameXtn);
7952             } else {
7953                 /* Callback returned index outside of the boundary. */
7954                 PORT_Assert(ret < ss->xtnData.sniNameArrSize);
7955                 errCode = SSL_ERROR_INTERNAL_ERROR_ALERT;
7956                 desc = internal_error;
7957                 ret = SSL_SNI_SEND_ALERT;
7958                 break;
7959             }
7960         } while (0);
7961         /* Free sniNameArr. The data that each SECItem in the array
7962          * points into is the data from the input buffer "b". It will
7963          * not be available outside the scope of this or it's child
7964          * functions.*/
7965         if (ss->xtnData.sniNameArr) {
7966             PORT_Free(ss->xtnData.sniNameArr);
7967             ss->xtnData.sniNameArr = NULL;
7968             ss->xtnData.sniNameArrSize = 0;
7969         }
7970         if (ret <= SSL_SNI_SEND_ALERT) {
7971             /* desc and errCode should be set. */
7972             goto alert_loser;
7973         }
7974     }
7975 #ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS
7976     else if (ss->firstHsDone) {
7977         /* Check that we don't have the name is current spec
7978          * if this extension was not negotiated on the 2d hs. */
7979         PRBool passed = PR_TRUE;
7980         ssl_GetSpecReadLock(ss);  /*******************************/
7981         if (ss->ssl3.cwSpec->srvVirtName.data) {
7982             passed = PR_FALSE;
7983         }
7984         ssl_ReleaseSpecReadLock(ss);  /***************************/
7985         if (!passed) {
7986             errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
7987             desc = handshake_failure;
7988             goto alert_loser;
7989         }
7990     }
7991 #endif
7992
7993     sid = ssl3_NewSessionID(ss, PR_TRUE);
7994     if (sid == NULL) {
7995         errCode = PORT_GetError();
7996         goto loser;     /* memory error is set. */
7997     }
7998     ss->sec.ci.sid = sid;
7999
8000     ss->ssl3.hs.isResuming = PR_FALSE;
8001     ssl_GetXmitBufLock(ss);
8002     rv = ssl3_SendServerHelloSequence(ss);
8003     ssl_ReleaseXmitBufLock(ss);
8004     if (rv != SECSuccess) {
8005         errCode = PORT_GetError();
8006         goto loser;
8007     }
8008
8009     if (haveXmitBufLock) {
8010         ssl_ReleaseXmitBufLock(ss);
8011         haveXmitBufLock = PR_FALSE;
8012     }
8013
8014     return SECSuccess;
8015
8016 alert_loser:
8017     if (haveSpecWriteLock) {
8018         ssl_ReleaseSpecWriteLock(ss);
8019         haveSpecWriteLock = PR_FALSE;
8020     }
8021     (void)SSL3_SendAlert(ss, level, desc);
8022     /* FALLTHRU */
8023 loser:
8024     if (haveSpecWriteLock) {
8025         ssl_ReleaseSpecWriteLock(ss);
8026         haveSpecWriteLock = PR_FALSE;
8027     }
8028
8029     if (haveXmitBufLock) {
8030         ssl_ReleaseXmitBufLock(ss);
8031         haveXmitBufLock = PR_FALSE;
8032     }
8033
8034     PORT_SetError(errCode);
8035     return SECFailure;
8036 }
8037
8038 /*
8039  * ssl3_HandleV2ClientHello is used when a V2 formatted hello comes
8040  * in asking to use the V3 handshake.
8041  * Called from ssl2_HandleClientHelloMessage() in sslcon.c
8042  */
8043 SECStatus
8044 ssl3_HandleV2ClientHello(sslSocket *ss, unsigned char *buffer, int length)
8045 {
8046     sslSessionID *      sid             = NULL;
8047     unsigned char *     suites;
8048     unsigned char *     random;
8049     SSL3ProtocolVersion version;
8050     SECStatus           rv;
8051     int                 i;
8052     int                 j;
8053     int                 sid_length;
8054     int                 suite_length;
8055     int                 rand_length;
8056     int                 errCode  = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
8057     SSL3AlertDescription desc    = handshake_failure;
8058
8059     SSL_TRC(3, ("%d: SSL3[%d]: handle v2 client_hello", SSL_GETPID(), ss->fd));
8060
8061     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
8062
8063     ssl_GetSSL3HandshakeLock(ss);
8064
8065     PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData));
8066
8067     rv = ssl3_InitState(ss);
8068     if (rv != SECSuccess) {
8069         ssl_ReleaseSSL3HandshakeLock(ss);
8070         return rv;              /* ssl3_InitState has set the error code. */
8071     }
8072     rv = ssl3_RestartHandshakeHashes(ss);
8073     if (rv != SECSuccess) {
8074         ssl_ReleaseSSL3HandshakeLock(ss);
8075         return rv;
8076     }
8077
8078     if (ss->ssl3.hs.ws != wait_client_hello) {
8079         desc    = unexpected_message;
8080         errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO;
8081         goto loser;     /* alert_loser */
8082     }
8083
8084     version      = (buffer[1] << 8) | buffer[2];
8085     suite_length = (buffer[3] << 8) | buffer[4];
8086     sid_length   = (buffer[5] << 8) | buffer[6];
8087     rand_length  = (buffer[7] << 8) | buffer[8];
8088     ss->clientHelloVersion = version;
8089
8090     rv = ssl3_NegotiateVersion(ss, version, PR_TRUE);
8091     if (rv != SECSuccess) {
8092         /* send back which ever alert client will understand. */
8093         desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version : handshake_failure;
8094         errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
8095         goto alert_loser;
8096     }
8097
8098     rv = ssl3_InitHandshakeHashes(ss);
8099     if (rv != SECSuccess) {
8100         desc = internal_error;
8101         errCode = PORT_GetError();
8102         goto alert_loser;
8103     }
8104
8105     /* if we get a non-zero SID, just ignore it. */
8106     if (length !=
8107         SSL_HL_CLIENT_HELLO_HBYTES + suite_length + sid_length + rand_length) {
8108         SSL_DBG(("%d: SSL3[%d]: bad v2 client hello message, len=%d should=%d",
8109                  SSL_GETPID(), ss->fd, length,
8110                  SSL_HL_CLIENT_HELLO_HBYTES + suite_length + sid_length +
8111                  rand_length));
8112         goto loser;     /* malformed */ /* alert_loser */
8113     }
8114
8115     suites = buffer + SSL_HL_CLIENT_HELLO_HBYTES;
8116     random = suites + suite_length + sid_length;
8117
8118     if (rand_length < SSL_MIN_CHALLENGE_BYTES ||
8119         rand_length > SSL_MAX_CHALLENGE_BYTES) {
8120         goto loser;     /* malformed */ /* alert_loser */
8121     }
8122
8123     PORT_Assert(SSL_MAX_CHALLENGE_BYTES == SSL3_RANDOM_LENGTH);
8124
8125     PORT_Memset(&ss->ssl3.hs.client_random, 0, SSL3_RANDOM_LENGTH);
8126     PORT_Memcpy(
8127         &ss->ssl3.hs.client_random.rand[SSL3_RANDOM_LENGTH - rand_length],
8128         random, rand_length);
8129
8130     PRINT_BUF(60, (ss, "client random:", &ss->ssl3.hs.client_random.rand[0],
8131                    SSL3_RANDOM_LENGTH));
8132 #ifdef NSS_ENABLE_ECC
8133     /* Disable any ECC cipher suites for which we have no cert. */
8134     ssl3_FilterECCipherSuitesByServerCerts(ss);
8135 #endif
8136     i = ssl3_config_match_init(ss);
8137     if (i <= 0) {
8138         errCode = PORT_GetError();      /* error code is already set. */
8139         goto alert_loser;
8140     }
8141
8142     /* Select a cipher suite.
8143     **
8144     ** NOTE: This suite selection algorithm should be the same as the one in
8145     ** ssl3_HandleClientHello().
8146     **
8147     ** See the comments about export cipher suites in ssl3_HandleClientHello().
8148     */
8149     for (j = 0; j < ssl_V3_SUITES_IMPLEMENTED; j++) {
8150         ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j];
8151         SSLVersionRange vrange = {ss->version, ss->version};
8152         if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange)) {
8153             continue;
8154         }
8155         for (i = 0; i+2 < suite_length; i += 3) {
8156             PRUint32 suite_i = (suites[i] << 16)|(suites[i+1] << 8)|suites[i+2];
8157             if (suite_i == suite->cipher_suite) {
8158                 ss->ssl3.hs.cipher_suite = suite->cipher_suite;
8159                 ss->ssl3.hs.suite_def =
8160                     ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite);
8161                 goto suite_found;
8162             }
8163         }
8164     }
8165     errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
8166     goto alert_loser;
8167
8168 suite_found:
8169
8170     /* Look for the SCSV, and if found, treat it just like an empty RI 
8171      * extension by processing a local copy of an empty RI extension.
8172      */
8173     for (i = 0; i+2 < suite_length; i += 3) {
8174         PRUint32 suite_i = (suites[i] << 16) | (suites[i+1] << 8) | suites[i+2];
8175         if (suite_i == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) {
8176             SSL3Opaque * b2 = (SSL3Opaque *)emptyRIext;
8177             PRUint32     L2 = sizeof emptyRIext;
8178             (void)ssl3_HandleHelloExtensions(ss, &b2, &L2);
8179             break;
8180         }
8181     }
8182
8183     if (ss->opt.requireSafeNegotiation &&
8184         !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
8185         desc = handshake_failure;
8186         errCode = SSL_ERROR_UNSAFE_NEGOTIATION;
8187         goto alert_loser;
8188     }
8189
8190     ss->ssl3.hs.compression = ssl_compression_null;
8191     ss->sec.send            = ssl3_SendApplicationData;
8192
8193     /* we don't even search for a cache hit here.  It's just a miss. */
8194     SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_misses );
8195     sid = ssl3_NewSessionID(ss, PR_TRUE);
8196     if (sid == NULL) {
8197         errCode = PORT_GetError();
8198         goto loser;     /* memory error is set. */
8199     }
8200     ss->sec.ci.sid = sid;
8201     /* do not worry about memory leak of sid since it now belongs to ci */
8202
8203     /* We have to update the handshake hashes before we can send stuff */
8204     rv = ssl3_UpdateHandshakeHashes(ss, buffer, length);
8205     if (rv != SECSuccess) {
8206         errCode = PORT_GetError();
8207         goto loser;
8208     }
8209
8210     ssl_GetXmitBufLock(ss);
8211     rv = ssl3_SendServerHelloSequence(ss);
8212     ssl_ReleaseXmitBufLock(ss);
8213     if (rv != SECSuccess) {
8214         errCode = PORT_GetError();
8215         goto loser;
8216     }
8217
8218     /* XXX_1    The call stack to here is:
8219      * ssl_Do1stHandshake -> ssl2_HandleClientHelloMessage -> here.
8220      * ssl2_HandleClientHelloMessage returns whatever we return here.
8221      * ssl_Do1stHandshake will continue looping if it gets back either
8222      *          SECSuccess or SECWouldBlock.
8223      * SECSuccess is preferable here.  See XXX_1 in sslgathr.c.
8224      */
8225     ssl_ReleaseSSL3HandshakeLock(ss);
8226     return SECSuccess;
8227
8228 alert_loser:
8229     SSL3_SendAlert(ss, alert_fatal, desc);
8230 loser:
8231     ssl_ReleaseSSL3HandshakeLock(ss);
8232     PORT_SetError(errCode);
8233     return SECFailure;
8234 }
8235
8236 /* The negotiated version number has been already placed in ss->version.
8237 **
8238 ** Called from:  ssl3_HandleClientHello                     (resuming session),
8239 **      ssl3_SendServerHelloSequence <- ssl3_HandleClientHello   (new session),
8240 **      ssl3_SendServerHelloSequence <- ssl3_HandleV2ClientHello (new session)
8241 */
8242 static SECStatus
8243 ssl3_SendServerHello(sslSocket *ss)
8244 {
8245     sslSessionID *sid;
8246     SECStatus     rv;
8247     PRUint32      maxBytes = 65535;
8248     PRUint32      length;
8249     PRInt32       extensions_len = 0;
8250     SSL3ProtocolVersion version;
8251
8252     SSL_TRC(3, ("%d: SSL3[%d]: send server_hello handshake", SSL_GETPID(),
8253                 ss->fd));
8254
8255     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
8256     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
8257
8258     if (!IS_DTLS(ss)) {
8259         PORT_Assert(MSB(ss->version) == MSB(SSL_LIBRARY_VERSION_3_0));
8260
8261         if (MSB(ss->version) != MSB(SSL_LIBRARY_VERSION_3_0)) {
8262             PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
8263             return SECFailure;
8264         }
8265     } else {
8266         PORT_Assert(MSB(ss->version) == MSB(SSL_LIBRARY_VERSION_DTLS_1_0));
8267
8268         if (MSB(ss->version) != MSB(SSL_LIBRARY_VERSION_DTLS_1_0)) {
8269             PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
8270             return SECFailure;
8271         }
8272     }
8273
8274     sid = ss->sec.ci.sid;
8275
8276     extensions_len = ssl3_CallHelloExtensionSenders(ss, PR_FALSE, maxBytes,
8277                                                &ss->xtnData.serverSenders[0]);
8278     if (extensions_len > 0)
8279         extensions_len += 2; /* Add sizeof total extension length */
8280
8281     length = sizeof(SSL3ProtocolVersion) + SSL3_RANDOM_LENGTH + 1 +
8282              ((sid == NULL) ? 0: sid->u.ssl3.sessionIDLength) +
8283              sizeof(ssl3CipherSuite) + 1 + extensions_len;
8284     rv = ssl3_AppendHandshakeHeader(ss, server_hello, length);
8285     if (rv != SECSuccess) {
8286         return rv;      /* err set by AppendHandshake. */
8287     }
8288
8289     if (IS_DTLS(ss)) {
8290         version = dtls_TLSVersionToDTLSVersion(ss->version);
8291     } else {
8292         version = ss->version;
8293     }
8294
8295     rv = ssl3_AppendHandshakeNumber(ss, version, 2);
8296     if (rv != SECSuccess) {
8297         return rv;      /* err set by AppendHandshake. */
8298     }
8299     rv = ssl3_GetNewRandom(&ss->ssl3.hs.server_random);
8300     if (rv != SECSuccess) {
8301         ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
8302         return rv;
8303     }
8304     rv = ssl3_AppendHandshake(
8305         ss, &ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH);
8306     if (rv != SECSuccess) {
8307         return rv;      /* err set by AppendHandshake. */
8308     }
8309
8310     if (sid)
8311         rv = ssl3_AppendHandshakeVariable(
8312             ss, sid->u.ssl3.sessionID, sid->u.ssl3.sessionIDLength, 1);
8313     else
8314         rv = ssl3_AppendHandshakeVariable(ss, NULL, 0, 1);
8315     if (rv != SECSuccess) {
8316         return rv;      /* err set by AppendHandshake. */
8317     }
8318
8319     rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.cipher_suite, 2);
8320     if (rv != SECSuccess) {
8321         return rv;      /* err set by AppendHandshake. */
8322     }
8323     rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.compression, 1);
8324     if (rv != SECSuccess) {
8325         return rv;      /* err set by AppendHandshake. */
8326     }
8327     if (extensions_len) {
8328         PRInt32 sent_len;
8329
8330         extensions_len -= 2;
8331         rv = ssl3_AppendHandshakeNumber(ss, extensions_len, 2);
8332         if (rv != SECSuccess) 
8333             return rv;  /* err set by ssl3_SetupPendingCipherSpec */
8334         sent_len = ssl3_CallHelloExtensionSenders(ss, PR_TRUE, extensions_len,
8335                                            &ss->xtnData.serverSenders[0]);
8336         PORT_Assert(sent_len == extensions_len);
8337         if (sent_len != extensions_len) {
8338             if (sent_len >= 0)
8339                 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
8340             return SECFailure;
8341         }
8342     }
8343     rv = ssl3_SetupPendingCipherSpec(ss);
8344     if (rv != SECSuccess) {
8345         return rv;      /* err set by ssl3_SetupPendingCipherSpec */
8346     }
8347
8348     return SECSuccess;
8349 }
8350
8351 /* ssl3_PickSignatureHashAlgorithm selects a hash algorithm to use when signing
8352  * elements of the handshake. (The negotiated cipher suite determines the
8353  * signature algorithm.) Prior to TLS 1.2, the MD5/SHA1 combination is always
8354  * used. With TLS 1.2, a client may advertise its support for signature and
8355  * hash combinations. */
8356 static SECStatus
8357 ssl3_PickSignatureHashAlgorithm(sslSocket *ss,
8358                                 SSL3SignatureAndHashAlgorithm* out)
8359 {
8360     TLSSignatureAlgorithm sigAlg;
8361     unsigned int i, j;
8362     /* hashPreference expresses our preferences for hash algorithms, most
8363      * preferable first. */
8364     static const PRUint8 hashPreference[] = {
8365         tls_hash_sha256,
8366         tls_hash_sha384,
8367         tls_hash_sha512,
8368         tls_hash_sha1,
8369     };
8370
8371     switch (ss->ssl3.hs.kea_def->kea) {
8372     case kea_rsa:
8373     case kea_rsa_export:
8374     case kea_rsa_export_1024:
8375     case kea_dh_rsa:
8376     case kea_dh_rsa_export:
8377     case kea_dhe_rsa:
8378     case kea_dhe_rsa_export:
8379     case kea_rsa_fips:
8380     case kea_ecdh_rsa:
8381     case kea_ecdhe_rsa:
8382         sigAlg = tls_sig_rsa;
8383         break;
8384     case kea_dh_dss:
8385     case kea_dh_dss_export:
8386     case kea_dhe_dss:
8387     case kea_dhe_dss_export:
8388         sigAlg = tls_sig_dsa;
8389         break;
8390     case kea_ecdh_ecdsa:
8391     case kea_ecdhe_ecdsa:
8392         sigAlg = tls_sig_ecdsa;
8393         break;
8394     default:
8395         PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
8396         return SECFailure;
8397     }
8398     out->sigAlg = sigAlg;
8399
8400     if (ss->version <= SSL_LIBRARY_VERSION_TLS_1_1) {
8401         /* SEC_OID_UNKNOWN means the MD5/SHA1 combo hash used in TLS 1.1 and
8402          * prior. */
8403         out->hashAlg = SEC_OID_UNKNOWN;
8404         return SECSuccess;
8405     }
8406
8407     if (ss->ssl3.hs.numClientSigAndHash == 0) {
8408         /* If the client didn't provide any signature_algorithms extension then
8409          * we can assume that they support SHA-1:
8410          * https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
8411         out->hashAlg = SEC_OID_SHA1;
8412         return SECSuccess;
8413     }
8414
8415     for (i = 0; i < PR_ARRAY_SIZE(hashPreference); i++) {
8416         for (j = 0; j < ss->ssl3.hs.numClientSigAndHash; j++) {
8417             const SSL3SignatureAndHashAlgorithm* sh =
8418                 &ss->ssl3.hs.clientSigAndHash[j];
8419             if (sh->sigAlg == sigAlg && sh->hashAlg == hashPreference[i]) {
8420                 out->hashAlg = sh->hashAlg;
8421                 return SECSuccess;
8422             }
8423         }
8424     }
8425
8426     PORT_SetError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
8427     return SECFailure;
8428 }
8429
8430
8431 static SECStatus
8432 ssl3_SendServerKeyExchange(sslSocket *ss)
8433 {
8434     const ssl3KEADef * kea_def     = ss->ssl3.hs.kea_def;
8435     SECStatus          rv          = SECFailure;
8436     int                length;
8437     PRBool             isTLS;
8438     SECItem            signed_hash = {siBuffer, NULL, 0};
8439     SSL3Hashes         hashes;
8440     SECKEYPublicKey *  sdPub;   /* public key for step-down */
8441     SSL3SignatureAndHashAlgorithm sigAndHash;
8442
8443     SSL_TRC(3, ("%d: SSL3[%d]: send server_key_exchange handshake",
8444                 SSL_GETPID(), ss->fd));
8445
8446     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
8447     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
8448
8449     if (ssl3_PickSignatureHashAlgorithm(ss, &sigAndHash) != SECSuccess) {
8450         return SECFailure;
8451     }
8452
8453     switch (kea_def->exchKeyType) {
8454     case kt_rsa:
8455         /* Perform SSL Step-Down here. */
8456         sdPub = ss->stepDownKeyPair->pubKey;
8457         PORT_Assert(sdPub != NULL);
8458         if (!sdPub) {
8459             PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
8460             return SECFailure;
8461         }
8462         rv = ssl3_ComputeExportRSAKeyHash(sigAndHash.hashAlg,
8463                                           sdPub->u.rsa.modulus,
8464                                           sdPub->u.rsa.publicExponent,
8465                                           &ss->ssl3.hs.client_random,
8466                                           &ss->ssl3.hs.server_random,
8467                                           &hashes, ss->opt.bypassPKCS11);
8468         if (rv != SECSuccess) {
8469             ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
8470             return rv;
8471         }
8472
8473         isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
8474         rv = ssl3_SignHashes(&hashes, ss->serverCerts[kt_rsa].SERVERKEY, 
8475                              &signed_hash, isTLS);
8476         if (rv != SECSuccess) {
8477             goto loser;         /* ssl3_SignHashes has set err. */
8478         }
8479         if (signed_hash.data == NULL) {
8480             /* how can this happen and rv == SECSuccess ?? */
8481             PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
8482             goto loser;
8483         }
8484         length = 2 + sdPub->u.rsa.modulus.len +
8485                  2 + sdPub->u.rsa.publicExponent.len +
8486                  2 + signed_hash.len;
8487
8488         rv = ssl3_AppendHandshakeHeader(ss, server_key_exchange, length);
8489         if (rv != SECSuccess) {
8490             goto loser;         /* err set by AppendHandshake. */
8491         }
8492
8493         rv = ssl3_AppendHandshakeVariable(ss, sdPub->u.rsa.modulus.data,
8494                                           sdPub->u.rsa.modulus.len, 2);
8495         if (rv != SECSuccess) {
8496             goto loser;         /* err set by AppendHandshake. */
8497         }
8498
8499         rv = ssl3_AppendHandshakeVariable(
8500                                 ss, sdPub->u.rsa.publicExponent.data,
8501                                 sdPub->u.rsa.publicExponent.len, 2);
8502         if (rv != SECSuccess) {
8503             goto loser;         /* err set by AppendHandshake. */
8504         }
8505
8506         if (ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
8507             rv = ssl3_AppendSignatureAndHashAlgorithm(ss, &sigAndHash);
8508             if (rv != SECSuccess) {
8509                 goto loser;     /* err set by AppendHandshake. */
8510             }
8511         }
8512
8513         rv = ssl3_AppendHandshakeVariable(ss, signed_hash.data,
8514                                           signed_hash.len, 2);
8515         if (rv != SECSuccess) {
8516             goto loser;         /* err set by AppendHandshake. */
8517         }
8518         PORT_Free(signed_hash.data);
8519         return SECSuccess;
8520
8521 #ifdef NSS_ENABLE_ECC
8522     case kt_ecdh: {
8523         rv = ssl3_SendECDHServerKeyExchange(ss, &sigAndHash);
8524         return rv;
8525     }
8526 #endif /* NSS_ENABLE_ECC */
8527
8528     case kt_dh:
8529     case kt_null:
8530     default:
8531         PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
8532         break;
8533     }
8534 loser:
8535     if (signed_hash.data != NULL) 
8536         PORT_Free(signed_hash.data);
8537     return SECFailure;
8538 }
8539
8540
8541 static SECStatus
8542 ssl3_SendCertificateRequest(sslSocket *ss)
8543 {
8544     PRBool         isTLS12;
8545     SECItem *      name;
8546     CERTDistNames *ca_list;
8547     const PRUint8 *certTypes;
8548     const PRUint8 *sigAlgs;
8549     SECItem *      names        = NULL;
8550     SECStatus      rv;
8551     int            length;
8552     int            i;
8553     int            calen        = 0;
8554     int            nnames       = 0;
8555     int            certTypesLength;
8556     int            sigAlgsLength;
8557
8558     SSL_TRC(3, ("%d: SSL3[%d]: send certificate_request handshake",
8559                 SSL_GETPID(), ss->fd));
8560
8561     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
8562     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
8563
8564     isTLS12 = (PRBool)(ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
8565
8566     /* ssl3.ca_list is initialized to NULL, and never changed. */
8567     ca_list = ss->ssl3.ca_list;
8568     if (!ca_list) {
8569         ca_list = ssl3_server_ca_list;
8570     }
8571
8572     if (ca_list != NULL) {
8573         names = ca_list->names;
8574         nnames = ca_list->nnames;
8575     }
8576
8577     for (i = 0, name = names; i < nnames; i++, name++) {
8578         calen += 2 + name->len;
8579     }
8580
8581     certTypes       = certificate_types;
8582     certTypesLength = sizeof certificate_types;
8583     sigAlgs         = supported_signature_algorithms;
8584     sigAlgsLength   = sizeof supported_signature_algorithms;
8585
8586     length = 1 + certTypesLength + 2 + calen;
8587     if (isTLS12) {
8588         length += 2 + sigAlgsLength;
8589     }
8590
8591     rv = ssl3_AppendHandshakeHeader(ss, certificate_request, length);
8592     if (rv != SECSuccess) {
8593         return rv;              /* err set by AppendHandshake. */
8594     }
8595     rv = ssl3_AppendHandshakeVariable(ss, certTypes, certTypesLength, 1);
8596     if (rv != SECSuccess) {
8597         return rv;              /* err set by AppendHandshake. */
8598     }
8599     if (isTLS12) {
8600         rv = ssl3_AppendHandshakeVariable(ss, sigAlgs, sigAlgsLength, 2);
8601         if (rv != SECSuccess) {
8602             return rv;          /* err set by AppendHandshake. */
8603         }
8604     }
8605     rv = ssl3_AppendHandshakeNumber(ss, calen, 2);
8606     if (rv != SECSuccess) {
8607         return rv;              /* err set by AppendHandshake. */
8608     }
8609     for (i = 0, name = names; i < nnames; i++, name++) {
8610         rv = ssl3_AppendHandshakeVariable(ss, name->data, name->len, 2);
8611         if (rv != SECSuccess) {
8612             return rv;          /* err set by AppendHandshake. */
8613         }
8614     }
8615
8616     return SECSuccess;
8617 }
8618
8619 static SECStatus
8620 ssl3_SendServerHelloDone(sslSocket *ss)
8621 {
8622     SECStatus rv;
8623
8624     SSL_TRC(3, ("%d: SSL3[%d]: send server_hello_done handshake",
8625                 SSL_GETPID(), ss->fd));
8626
8627     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
8628     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
8629
8630     rv = ssl3_AppendHandshakeHeader(ss, server_hello_done, 0);
8631     if (rv != SECSuccess) {
8632         return rv;              /* err set by AppendHandshake. */
8633     }
8634     rv = ssl3_FlushHandshake(ss, 0);
8635     if (rv != SECSuccess) {
8636         return rv;      /* error code set by ssl3_FlushHandshake */
8637     }
8638     return SECSuccess;
8639 }
8640
8641 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
8642  * ssl3 Certificate Verify message
8643  * Caller must hold Handshake and RecvBuf locks.
8644  */
8645 static SECStatus
8646 ssl3_HandleCertificateVerify(sslSocket *ss, SSL3Opaque *b, PRUint32 length,
8647                              SSL3Hashes *hashes)
8648 {
8649     SECItem              signed_hash = {siBuffer, NULL, 0};
8650     SECStatus            rv;
8651     int                  errCode     = SSL_ERROR_RX_MALFORMED_CERT_VERIFY;
8652     SSL3AlertDescription desc        = handshake_failure;
8653     PRBool               isTLS, isTLS12;
8654     SSL3SignatureAndHashAlgorithm sigAndHash;
8655
8656     SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_verify handshake",
8657                 SSL_GETPID(), ss->fd));
8658     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
8659     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
8660
8661     isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
8662     isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
8663
8664     if (ss->ssl3.hs.ws != wait_cert_verify || ss->sec.peerCert == NULL) {
8665         desc    = unexpected_message;
8666         errCode = SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY;
8667         goto alert_loser;
8668     }
8669
8670     if (isTLS12) {
8671         rv = ssl3_ConsumeSignatureAndHashAlgorithm(ss, &b, &length,
8672                                                    &sigAndHash);
8673         if (rv != SECSuccess) {
8674             goto loser; /* malformed or unsupported. */
8675         }
8676         rv = ssl3_CheckSignatureAndHashAlgorithmConsistency(
8677                 &sigAndHash, ss->sec.peerCert);
8678         if (rv != SECSuccess) {
8679             errCode = PORT_GetError();
8680             desc = decrypt_error;
8681             goto alert_loser;
8682         }
8683
8684         /* We only support CertificateVerify messages that use the handshake
8685          * hash. */
8686         if (sigAndHash.hashAlg != hashes->hashAlg) {
8687             errCode = SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM;
8688             desc = decrypt_error;
8689             goto alert_loser;
8690         }
8691     }
8692
8693     rv = ssl3_ConsumeHandshakeVariable(ss, &signed_hash, 2, &b, &length);
8694     if (rv != SECSuccess) {
8695         goto loser;             /* malformed. */
8696     }
8697
8698     /* XXX verify that the key & kea match */
8699     rv = ssl3_VerifySignedHashes(hashes, ss->sec.peerCert, &signed_hash,
8700                                  isTLS, ss->pkcs11PinArg);
8701     if (rv != SECSuccess) {
8702         errCode = PORT_GetError();
8703         desc = isTLS ? decrypt_error : handshake_failure;
8704         goto alert_loser;
8705     }
8706
8707     signed_hash.data = NULL;
8708
8709     if (length != 0) {
8710         desc    = isTLS ? decode_error : illegal_parameter;
8711         goto alert_loser;       /* malformed */
8712     }
8713     ss->ssl3.hs.ws = wait_change_cipher;
8714     return SECSuccess;
8715
8716 alert_loser:
8717     SSL3_SendAlert(ss, alert_fatal, desc);
8718 loser:
8719     PORT_SetError(errCode);
8720     return SECFailure;
8721 }
8722
8723
8724 /* find a slot that is able to generate a PMS and wrap it with RSA.
8725  * Then generate and return the PMS.
8726  * If the serverKeySlot parameter is non-null, this function will use
8727  * that slot to do the job, otherwise it will find a slot.
8728  *
8729  * Called from  ssl3_DeriveConnectionKeysPKCS11()  (above)
8730  *              sendRSAClientKeyExchange()         (above)
8731  *              ssl3_HandleRSAClientKeyExchange()  (below)
8732  * Caller must hold the SpecWriteLock, the SSL3HandshakeLock
8733  */
8734 static PK11SymKey *
8735 ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec,
8736                     PK11SlotInfo * serverKeySlot)
8737 {
8738     PK11SymKey *      pms               = NULL;
8739     PK11SlotInfo *    slot              = serverKeySlot;
8740     void *            pwArg             = ss->pkcs11PinArg;
8741     SECItem           param;
8742     CK_VERSION        version;
8743     CK_MECHANISM_TYPE mechanism_array[3];
8744
8745     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
8746
8747     if (slot == NULL) {
8748         SSLCipherAlgorithm calg;
8749         /* The specReadLock would suffice here, but we cannot assert on
8750         ** read locks.  Also, all the callers who call with a non-null
8751         ** slot already hold the SpecWriteLock.
8752         */
8753         PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
8754         PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
8755
8756         calg = spec->cipher_def->calg;
8757         PORT_Assert(alg2Mech[calg].calg == calg);
8758
8759         /* First get an appropriate slot.  */
8760         mechanism_array[0] = CKM_SSL3_PRE_MASTER_KEY_GEN;
8761         mechanism_array[1] = CKM_RSA_PKCS;
8762         mechanism_array[2] = alg2Mech[calg].cmech;
8763
8764         slot = PK11_GetBestSlotMultiple(mechanism_array, 3, pwArg);
8765         if (slot == NULL) {
8766            /* can't find a slot with all three, find a slot with the minimum */
8767             slot = PK11_GetBestSlotMultiple(mechanism_array, 2, pwArg);
8768             if (slot == NULL) {
8769                 PORT_SetError(SSL_ERROR_TOKEN_SLOT_NOT_FOUND);
8770                 return pms;     /* which is NULL */
8771             }
8772         }
8773     }
8774
8775     /* Generate the pre-master secret ...  */
8776     if (IS_DTLS(ss)) {
8777         SSL3ProtocolVersion temp;
8778
8779         temp = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion);
8780         version.major = MSB(temp);
8781         version.minor = LSB(temp);
8782     } else {
8783         version.major = MSB(ss->clientHelloVersion);
8784         version.minor = LSB(ss->clientHelloVersion);
8785     }
8786
8787     param.data = (unsigned char *)&version;
8788     param.len  = sizeof version;
8789
8790     pms = PK11_KeyGen(slot, CKM_SSL3_PRE_MASTER_KEY_GEN, &param, 0, pwArg);
8791     if (!serverKeySlot)
8792         PK11_FreeSlot(slot);
8793     if (pms == NULL) {
8794         ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
8795     }
8796     return pms;
8797 }
8798
8799 /* Note: The Bleichenbacher attack on PKCS#1 necessitates that we NEVER
8800  * return any indication of failure of the Client Key Exchange message,
8801  * where that failure is caused by the content of the client's message.
8802  * This function must not return SECFailure for any reason that is directly
8803  * or indirectly caused by the content of the client's encrypted PMS.
8804  * We must not send an alert and also not drop the connection.
8805  * Instead, we generate a random PMS.  This will cause a failure
8806  * in the processing the finished message, which is exactly where
8807  * the failure must occur.
8808  *
8809  * Called from ssl3_HandleClientKeyExchange
8810  */
8811 static SECStatus
8812 ssl3_HandleRSAClientKeyExchange(sslSocket *ss,
8813                                 SSL3Opaque *b,
8814                                 PRUint32 length,
8815                                 SECKEYPrivateKey *serverKey)
8816 {
8817     PK11SymKey *      pms;
8818 #ifndef NO_PKCS11_BYPASS
8819     unsigned char *   cr     = (unsigned char *)&ss->ssl3.hs.client_random;
8820     unsigned char *   sr     = (unsigned char *)&ss->ssl3.hs.server_random;
8821     ssl3CipherSpec *  pwSpec = ss->ssl3.pwSpec;
8822     unsigned int      outLen = 0;
8823 #endif
8824     PRBool            isTLS  = PR_FALSE;
8825     SECStatus         rv;
8826     SECItem           enc_pms;
8827     unsigned char     rsaPmsBuf[SSL3_RSA_PMS_LENGTH];
8828     SECItem           pmsItem = {siBuffer, NULL, 0};
8829
8830     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
8831     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
8832     PORT_Assert( ss->ssl3.prSpec == ss->ssl3.pwSpec );
8833
8834     enc_pms.data = b;
8835     enc_pms.len  = length;
8836     pmsItem.data = rsaPmsBuf;
8837     pmsItem.len  = sizeof rsaPmsBuf;
8838
8839     if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */
8840         PRInt32 kLen;
8841         kLen = ssl3_ConsumeHandshakeNumber(ss, 2, &enc_pms.data, &enc_pms.len);
8842         if (kLen < 0) {
8843             PORT_SetError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
8844             return SECFailure;
8845         }
8846         if ((unsigned)kLen < enc_pms.len) {
8847             enc_pms.len = kLen;
8848         }
8849         isTLS = PR_TRUE;
8850     } else {
8851         isTLS = (PRBool)(ss->ssl3.hs.kea_def->tls_keygen != 0);
8852     }
8853
8854 #ifndef NO_PKCS11_BYPASS
8855     if (ss->opt.bypassPKCS11) {
8856         /* TRIPLE BYPASS, get PMS directly from RSA decryption.
8857          * Use PK11_PrivDecryptPKCS1 to decrypt the PMS to a buffer, 
8858          * then, check for version rollback attack, then 
8859          * do the equivalent of ssl3_DeriveMasterSecret, placing the MS in 
8860          * pwSpec->msItem.  Finally call ssl3_InitPendingCipherSpec with 
8861          * ss and NULL, so that it will use the MS we've already derived here. 
8862          */
8863
8864         rv = PK11_PrivDecryptPKCS1(serverKey, rsaPmsBuf, &outLen, 
8865                                    sizeof rsaPmsBuf, enc_pms.data, enc_pms.len);
8866         if (rv != SECSuccess) {
8867             /* triple bypass failed.  Let's try for a double bypass. */
8868             goto double_bypass;
8869         } else if (ss->opt.detectRollBack) {
8870             SSL3ProtocolVersion client_version = 
8871                                          (rsaPmsBuf[0] << 8) | rsaPmsBuf[1];
8872
8873             if (IS_DTLS(ss)) {
8874                 client_version = dtls_DTLSVersionToTLSVersion(client_version);
8875             }
8876
8877             if (client_version != ss->clientHelloVersion) {
8878                 /* Version roll-back detected. ensure failure.  */
8879                 rv = PK11_GenerateRandom(rsaPmsBuf, sizeof rsaPmsBuf);
8880             }
8881         }
8882         /* have PMS, build MS without PKCS11 */
8883         rv = ssl3_MasterKeyDeriveBypass(pwSpec, cr, sr, &pmsItem, isTLS, 
8884                                         PR_TRUE);
8885         if (rv != SECSuccess) {
8886             pwSpec->msItem.data = pwSpec->raw_master_secret;
8887             pwSpec->msItem.len  = SSL3_MASTER_SECRET_LENGTH;
8888             PK11_GenerateRandom(pwSpec->msItem.data, pwSpec->msItem.len);
8889         }
8890         rv = ssl3_InitPendingCipherSpec(ss,  NULL);
8891     } else 
8892 #endif
8893     {
8894 #ifndef NO_PKCS11_BYPASS
8895 double_bypass:
8896 #endif
8897         /*
8898          * unwrap pms out of the incoming buffer
8899          * Note: CKM_SSL3_MASTER_KEY_DERIVE is NOT the mechanism used to do 
8900          *      the unwrap.  Rather, it is the mechanism with which the 
8901          *      unwrapped pms will be used.
8902          */
8903         pms = PK11_PubUnwrapSymKey(serverKey, &enc_pms,
8904                                    CKM_SSL3_MASTER_KEY_DERIVE, CKA_DERIVE, 0);
8905         if (pms != NULL) {
8906             PRINT_BUF(60, (ss, "decrypted premaster secret:",
8907                            PK11_GetKeyData(pms)->data,
8908                            PK11_GetKeyData(pms)->len));
8909         } else {
8910             /* unwrap failed. Generate a bogus PMS and carry on. */
8911             PK11SlotInfo *  slot   = PK11_GetSlotFromPrivateKey(serverKey);
8912
8913             ssl_GetSpecWriteLock(ss);
8914             pms = ssl3_GenerateRSAPMS(ss, ss->ssl3.prSpec, slot);
8915             ssl_ReleaseSpecWriteLock(ss);
8916             PK11_FreeSlot(slot);
8917         }
8918
8919         if (pms == NULL) {
8920             /* last gasp.  */
8921             ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
8922             return SECFailure;
8923         }
8924
8925         /* This step will derive the MS from the PMS, among other things. */
8926         rv = ssl3_InitPendingCipherSpec(ss,  pms);
8927         PK11_FreeSymKey(pms);
8928     }
8929
8930     if (rv != SECSuccess) {
8931         SEND_ALERT
8932         return SECFailure; /* error code set by ssl3_InitPendingCipherSpec */
8933     }
8934     return SECSuccess;
8935 }
8936
8937
8938 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
8939  * ssl3 ClientKeyExchange message from the remote client
8940  * Caller must hold Handshake and RecvBuf locks.
8941  */
8942 static SECStatus
8943 ssl3_HandleClientKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
8944 {
8945     SECKEYPrivateKey *serverKey         = NULL;
8946     SECStatus         rv;
8947     const ssl3KEADef *kea_def;
8948     ssl3KeyPair     *serverKeyPair      = NULL;
8949 #ifdef NSS_ENABLE_ECC
8950     SECKEYPublicKey *serverPubKey       = NULL;
8951 #endif /* NSS_ENABLE_ECC */
8952
8953     SSL_TRC(3, ("%d: SSL3[%d]: handle client_key_exchange handshake",
8954                 SSL_GETPID(), ss->fd));
8955
8956     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
8957     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
8958
8959     if (ss->ssl3.hs.ws != wait_client_key) {
8960         SSL3_SendAlert(ss, alert_fatal, unexpected_message);
8961         PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH);
8962         return SECFailure;
8963     }
8964
8965     kea_def   = ss->ssl3.hs.kea_def;
8966
8967     if (ss->ssl3.hs.usedStepDownKey) {
8968          PORT_Assert(kea_def->is_limited /* XXX OR cert is signing only */
8969                  && kea_def->exchKeyType == kt_rsa 
8970                  && ss->stepDownKeyPair != NULL);
8971          if (!kea_def->is_limited  ||
8972               kea_def->exchKeyType != kt_rsa ||
8973               ss->stepDownKeyPair == NULL) {
8974                 /* shouldn't happen, don't use step down if it does */
8975                 goto skip;
8976          }
8977         serverKeyPair = ss->stepDownKeyPair;
8978         ss->sec.keaKeyBits = EXPORT_RSA_KEY_LENGTH * BPB;
8979     } else 
8980 skip:
8981 #ifdef NSS_ENABLE_ECC
8982     /* XXX Using SSLKEAType to index server certifiates
8983      * does not work for (EC)DHE ciphers. Until we have
8984      * an indexing mechanism general enough for all key
8985      * exchange algorithms, we'll need to deal with each
8986      * one seprately.
8987      */
8988     if ((kea_def->kea == kea_ecdhe_rsa) ||
8989                (kea_def->kea == kea_ecdhe_ecdsa)) {
8990         if (ss->ephemeralECDHKeyPair != NULL) {
8991            serverKeyPair = ss->ephemeralECDHKeyPair;
8992            if (serverKeyPair->pubKey) {
8993                 ss->sec.keaKeyBits = 
8994                     SECKEY_PublicKeyStrengthInBits(serverKeyPair->pubKey);
8995            }
8996         }
8997     } else 
8998 #endif
8999     {
9000         sslServerCerts * sc = ss->serverCerts + kea_def->exchKeyType;
9001         serverKeyPair = sc->serverKeyPair;
9002         ss->sec.keaKeyBits = sc->serverKeyBits;
9003     }
9004
9005     if (serverKeyPair) {
9006         serverKey = serverKeyPair->privKey;
9007     }
9008
9009     if (serverKey == NULL) {
9010         SEND_ALERT
9011         PORT_SetError(SSL_ERROR_NO_SERVER_KEY_FOR_ALG);
9012         return SECFailure;
9013     }
9014
9015     ss->sec.keaType    = kea_def->exchKeyType;
9016
9017     switch (kea_def->exchKeyType) {
9018     case kt_rsa:
9019         rv = ssl3_HandleRSAClientKeyExchange(ss, b, length, serverKey);
9020         if (rv != SECSuccess) {
9021             SEND_ALERT
9022             return SECFailure;  /* error code set */
9023         }
9024         break;
9025
9026
9027 #ifdef NSS_ENABLE_ECC
9028     case kt_ecdh:
9029         /* XXX We really ought to be able to store multiple
9030          * EC certs (a requirement if we wish to support both
9031          * ECDH-RSA and ECDH-ECDSA key exchanges concurrently).
9032          * When we make that change, we'll need an index other
9033          * than kt_ecdh to pick the right EC certificate.
9034          */
9035         if (serverKeyPair) {
9036             serverPubKey = serverKeyPair->pubKey;
9037         }
9038         if (serverPubKey == NULL) {
9039             /* XXX Is this the right error code? */
9040             PORT_SetError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
9041             return SECFailure;
9042         }
9043         rv = ssl3_HandleECDHClientKeyExchange(ss, b, length, 
9044                                               serverPubKey, serverKey);
9045         if (rv != SECSuccess) {
9046             return SECFailure;  /* error code set */
9047         }
9048         break;
9049 #endif /* NSS_ENABLE_ECC */
9050
9051     default:
9052         (void) ssl3_HandshakeFailure(ss);
9053         PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
9054         return SECFailure;
9055     }
9056     ss->ssl3.hs.ws = ss->sec.peerCert ? wait_cert_verify : wait_change_cipher;
9057     return SECSuccess;
9058
9059 }
9060
9061 /* This is TLS's equivalent of sending a no_certificate alert. */
9062 static SECStatus
9063 ssl3_SendEmptyCertificate(sslSocket *ss)
9064 {
9065     SECStatus            rv;
9066
9067     rv = ssl3_AppendHandshakeHeader(ss, certificate, 3);
9068     if (rv == SECSuccess) {
9069         rv = ssl3_AppendHandshakeNumber(ss, 0, 3);
9070     }
9071     return rv;  /* error, if any, set by functions called above. */
9072 }
9073
9074 SECStatus
9075 ssl3_HandleNewSessionTicket(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
9076 {
9077     SECStatus         rv;
9078     NewSessionTicket  session_ticket;
9079
9080     SSL_TRC(3, ("%d: SSL3[%d]: handle session_ticket handshake",
9081                 SSL_GETPID(), ss->fd));
9082
9083     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
9084     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
9085
9086     if (ss->ssl3.hs.ws != wait_new_session_ticket) {
9087         SSL3_SendAlert(ss, alert_fatal, unexpected_message);
9088         PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET);
9089         return SECFailure;
9090     }
9091
9092     session_ticket.received_timestamp = ssl_Time();
9093     if (length < 4) {
9094         (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
9095         PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
9096         return SECFailure;
9097     }
9098     session_ticket.ticket_lifetime_hint =
9099         (PRUint32)ssl3_ConsumeHandshakeNumber(ss, 4, &b, &length);
9100
9101     rv = ssl3_ConsumeHandshakeVariable(ss, &session_ticket.ticket, 2,
9102         &b, &length);
9103     if (length != 0 || rv != SECSuccess) {
9104         (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
9105         PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
9106         return SECFailure;  /* malformed */
9107     }
9108
9109     rv = ssl3_SetSIDSessionTicket(ss->sec.ci.sid, &session_ticket);
9110     if (rv != SECSuccess) {
9111         (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure);
9112         PORT_SetError(SSL_ERROR_INTERNAL_ERROR_ALERT);
9113         return SECFailure;
9114     }
9115     ss->ssl3.hs.ws = wait_change_cipher;
9116     return SECSuccess;
9117 }
9118
9119 #ifdef NISCC_TEST
9120 static PRInt32 connNum = 0;
9121
9122 static SECStatus 
9123 get_fake_cert(SECItem *pCertItem, int *pIndex)
9124 {
9125     PRFileDesc *cf;
9126     char *      testdir;
9127     char *      startat;
9128     char *      stopat;
9129     const char *extension;
9130     int         fileNum;
9131     PRInt32     numBytes   = 0;
9132     PRStatus    prStatus;
9133     PRFileInfo  info;
9134     char        cfn[100];
9135
9136     pCertItem->data = 0;
9137     if ((testdir = PR_GetEnv("NISCC_TEST")) == NULL) {
9138         return SECSuccess;
9139     }
9140     *pIndex   = (NULL != strstr(testdir, "root"));
9141     extension = (strstr(testdir, "simple") ? "" : ".der");
9142     fileNum     = PR_ATOMIC_INCREMENT(&connNum) - 1;
9143     if ((startat = PR_GetEnv("START_AT")) != NULL) {
9144         fileNum += atoi(startat);
9145     }
9146     if ((stopat = PR_GetEnv("STOP_AT")) != NULL && 
9147         fileNum >= atoi(stopat)) {
9148         *pIndex = -1;
9149         return SECSuccess;
9150     }
9151     sprintf(cfn, "%s/%08d%s", testdir, fileNum, extension);
9152     cf = PR_Open(cfn, PR_RDONLY, 0);
9153     if (!cf) {
9154         goto loser;
9155     }
9156     prStatus = PR_GetOpenFileInfo(cf, &info);
9157     if (prStatus != PR_SUCCESS) {
9158         PR_Close(cf);
9159         goto loser;
9160     }
9161     pCertItem = SECITEM_AllocItem(NULL, pCertItem, info.size);
9162     if (pCertItem) {
9163         numBytes = PR_Read(cf, pCertItem->data, info.size);
9164     }
9165     PR_Close(cf);
9166     if (numBytes != info.size) {
9167         SECITEM_FreeItem(pCertItem, PR_FALSE);
9168         PORT_SetError(SEC_ERROR_IO);
9169         goto loser;
9170     }
9171     fprintf(stderr, "using %s\n", cfn);
9172     return SECSuccess;
9173
9174 loser:
9175     fprintf(stderr, "failed to use %s\n", cfn);
9176     *pIndex = -1;
9177     return SECFailure;
9178 }
9179 #endif
9180
9181 /*
9182  * Used by both client and server.
9183  * Called from HandleServerHelloDone and from SendServerHelloSequence.
9184  */
9185 static SECStatus
9186 ssl3_SendCertificate(sslSocket *ss)
9187 {
9188     SECStatus            rv;
9189     CERTCertificateList *certChain;
9190     int                  len            = 0;
9191     int                  i;
9192     SSL3KEAType          certIndex;
9193 #ifdef NISCC_TEST
9194     SECItem              fakeCert;
9195     int                  ndex           = -1;
9196 #endif
9197
9198     SSL_TRC(3, ("%d: SSL3[%d]: send certificate handshake",
9199                 SSL_GETPID(), ss->fd));
9200
9201     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
9202     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
9203
9204     if (ss->sec.localCert)
9205         CERT_DestroyCertificate(ss->sec.localCert);
9206     if (ss->sec.isServer) {
9207         sslServerCerts * sc = NULL;
9208
9209         /* XXX SSLKEAType isn't really a good choice for 
9210          * indexing certificates (it breaks when we deal
9211          * with (EC)DHE-* cipher suites. This hack ensures
9212          * the RSA cert is picked for (EC)DHE-RSA.
9213          * Revisit this when we add server side support
9214          * for ECDHE-ECDSA or client-side authentication
9215          * using EC certificates.
9216          */
9217         if ((ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) ||
9218             (ss->ssl3.hs.kea_def->kea == kea_dhe_rsa)) {
9219             certIndex = kt_rsa;
9220         } else {
9221             certIndex = ss->ssl3.hs.kea_def->exchKeyType;
9222         }
9223         sc                    = ss->serverCerts + certIndex;
9224         certChain             = sc->serverCertChain;
9225         ss->sec.authKeyBits   = sc->serverKeyBits;
9226         ss->sec.authAlgorithm = ss->ssl3.hs.kea_def->signKeyType;
9227         ss->sec.localCert     = CERT_DupCertificate(sc->serverCert);
9228     } else {
9229         certChain          = ss->ssl3.clientCertChain;
9230         ss->sec.localCert = CERT_DupCertificate(ss->ssl3.clientCertificate);
9231     }
9232
9233 #ifdef NISCC_TEST
9234     rv = get_fake_cert(&fakeCert, &ndex);
9235 #endif
9236
9237     if (certChain) {
9238         for (i = 0; i < certChain->len; i++) {
9239 #ifdef NISCC_TEST
9240             if (fakeCert.len > 0 && i == ndex) {
9241                 len += fakeCert.len + 3;
9242             } else {
9243                 len += certChain->certs[i].len + 3;
9244             }
9245 #else
9246             len += certChain->certs[i].len + 3;
9247 #endif
9248         }
9249     }
9250
9251     rv = ssl3_AppendHandshakeHeader(ss, certificate, len + 3);
9252     if (rv != SECSuccess) {
9253         return rv;              /* err set by AppendHandshake. */
9254     }
9255     rv = ssl3_AppendHandshakeNumber(ss, len, 3);
9256     if (rv != SECSuccess) {
9257         return rv;              /* err set by AppendHandshake. */
9258     }
9259     if (certChain) {
9260         for (i = 0; i < certChain->len; i++) {
9261 #ifdef NISCC_TEST
9262             if (fakeCert.len > 0 && i == ndex) {
9263                 rv = ssl3_AppendHandshakeVariable(ss, fakeCert.data,
9264                                                   fakeCert.len, 3);
9265                 SECITEM_FreeItem(&fakeCert, PR_FALSE);
9266             } else {
9267                 rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data,
9268                                                   certChain->certs[i].len, 3);
9269             }
9270 #else
9271             rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data,
9272                                               certChain->certs[i].len, 3);
9273 #endif
9274             if (rv != SECSuccess) {
9275                 return rv;              /* err set by AppendHandshake. */
9276             }
9277         }
9278     }
9279
9280     return SECSuccess;
9281 }
9282
9283 /*
9284  * Used by server only.
9285  * single-stapling, send only a single cert status
9286  */
9287 static SECStatus
9288 ssl3_SendCertificateStatus(sslSocket *ss)
9289 {
9290     SECStatus rv;
9291     int len = 0;
9292     SECItemArray *statusToSend = NULL;
9293     SSL3KEAType certIndex;
9294
9295     SSL_TRC(3, ("%d: SSL3[%d]: send certificate status handshake",
9296                 SSL_GETPID(), ss->fd));
9297
9298     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
9299     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
9300     PORT_Assert( ss->sec.isServer);
9301
9302     if (!ssl3_ExtensionNegotiated(ss, ssl_cert_status_xtn))
9303         return SECSuccess;
9304
9305     /* Use certStatus based on the cert being used. */
9306     if ((ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) ||
9307         (ss->ssl3.hs.kea_def->kea == kea_dhe_rsa)) {
9308         certIndex = kt_rsa;
9309     } else {
9310         certIndex = ss->ssl3.hs.kea_def->exchKeyType;
9311     }
9312     if (ss->certStatusArray[certIndex] && ss->certStatusArray[certIndex]->len) {
9313         statusToSend = ss->certStatusArray[certIndex];
9314     }
9315     if (!statusToSend)
9316         return SECSuccess;
9317
9318     /* Use the array's first item only (single stapling) */
9319     len = 1 + statusToSend->items[0].len + 3;
9320
9321     rv = ssl3_AppendHandshakeHeader(ss, certificate_status, len);
9322     if (rv != SECSuccess) {
9323         return rv;              /* err set by AppendHandshake. */
9324     }
9325     rv = ssl3_AppendHandshakeNumber(ss, 1 /*ocsp*/, 1);
9326     if (rv != SECSuccess)
9327         return rv;              /* err set by AppendHandshake. */
9328
9329     rv = ssl3_AppendHandshakeVariable(ss,
9330                                       statusToSend->items[0].data,
9331                                       statusToSend->items[0].len,
9332                                       3);
9333     if (rv != SECSuccess)
9334         return rv;              /* err set by AppendHandshake. */
9335
9336     return SECSuccess;
9337 }
9338
9339 /* This is used to delete the CA certificates in the peer certificate chain
9340  * from the cert database after they've been validated.
9341  */
9342 static void
9343 ssl3_CleanupPeerCerts(sslSocket *ss)
9344 {
9345     PLArenaPool * arena = ss->ssl3.peerCertArena;
9346     ssl3CertNode *certs = (ssl3CertNode *)ss->ssl3.peerCertChain;
9347
9348     for (; certs; certs = certs->next) {
9349         CERT_DestroyCertificate(certs->cert);
9350     }
9351     if (arena) PORT_FreeArena(arena, PR_FALSE);
9352     ss->ssl3.peerCertArena = NULL;
9353     ss->ssl3.peerCertChain = NULL;
9354 }
9355
9356 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
9357  * ssl3 CertificateStatus message.
9358  * Caller must hold Handshake and RecvBuf locks.
9359  * This is always called before ssl3_HandleCertificate, even if the Certificate
9360  * message is sent first.
9361  */
9362 static SECStatus
9363 ssl3_HandleCertificateStatus(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
9364 {
9365     PRInt32 status, len;
9366
9367     if (ss->ssl3.hs.ws != wait_certificate_status) {
9368         (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
9369         PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_STATUS);
9370         return SECFailure;
9371     }
9372
9373     PORT_Assert(!ss->sec.isServer);
9374
9375     /* Consume the CertificateStatusType enum */
9376     status = ssl3_ConsumeHandshakeNumber(ss, 1, &b, &length);
9377     if (status != 1 /* ocsp */) {
9378        goto format_loser;
9379     }
9380
9381     len = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length);
9382     if (len != length) {
9383        goto format_loser;
9384     }
9385
9386 #define MAX_CERTSTATUS_LEN 0x1ffff   /* 128k - 1 */
9387     if (length > MAX_CERTSTATUS_LEN)
9388        goto format_loser;
9389 #undef MAX_CERTSTATUS_LEN
9390
9391     /* Array size 1, because we currently implement single-stapling only */
9392     SECITEM_AllocArray(NULL, &ss->sec.ci.sid->peerCertStatus, 1);
9393     if (!ss->sec.ci.sid->peerCertStatus.items)
9394        return SECFailure;
9395
9396     ss->sec.ci.sid->peerCertStatus.items[0].data = PORT_Alloc(length);
9397
9398     if (!ss->sec.ci.sid->peerCertStatus.items[0].data) {
9399         SECITEM_FreeArray(&ss->sec.ci.sid->peerCertStatus, PR_FALSE);
9400         return SECFailure;
9401     }
9402
9403     PORT_Memcpy(ss->sec.ci.sid->peerCertStatus.items[0].data, b, length);
9404     ss->sec.ci.sid->peerCertStatus.items[0].len = length;
9405     ss->sec.ci.sid->peerCertStatus.items[0].type = siBuffer;
9406
9407     return ssl3_AuthCertificate(ss);
9408
9409 format_loser:
9410     return ssl3_DecodeError(ss);
9411 }
9412
9413 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
9414  * ssl3 Certificate message.
9415  * Caller must hold Handshake and RecvBuf locks.
9416  */
9417 static SECStatus
9418 ssl3_HandleCertificate(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
9419 {
9420     ssl3CertNode *   c;
9421     ssl3CertNode *   lastCert   = NULL;
9422     PRInt32          remaining  = 0;
9423     PRInt32          size;
9424     SECStatus        rv;
9425     PRBool           isServer   = (PRBool)(!!ss->sec.isServer);
9426     PRBool           isTLS;
9427     SSL3AlertDescription desc;
9428     int              errCode    = SSL_ERROR_RX_MALFORMED_CERTIFICATE;
9429     SECItem          certItem;
9430
9431     SSL_TRC(3, ("%d: SSL3[%d]: handle certificate handshake",
9432                 SSL_GETPID(), ss->fd));
9433     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
9434     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
9435
9436     if ((ss->ssl3.hs.ws != wait_server_cert) &&
9437         (ss->ssl3.hs.ws != wait_client_cert)) {
9438         desc    = unexpected_message;
9439         errCode = SSL_ERROR_RX_UNEXPECTED_CERTIFICATE;
9440         goto alert_loser;
9441     }
9442
9443     if (ss->sec.peerCert != NULL) {
9444         if (ss->sec.peerKey) {
9445             SECKEY_DestroyPublicKey(ss->sec.peerKey);
9446             ss->sec.peerKey = NULL;
9447         }
9448         CERT_DestroyCertificate(ss->sec.peerCert);
9449         ss->sec.peerCert = NULL;
9450     }
9451
9452     ssl3_CleanupPeerCerts(ss);
9453     isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
9454
9455     /* It is reported that some TLS client sends a Certificate message
9456     ** with a zero-length message body.  We'll treat that case like a
9457     ** normal no_certificates message to maximize interoperability.
9458     */
9459     if (length) {
9460         remaining = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length);
9461         if (remaining < 0)
9462             goto loser; /* fatal alert already sent by ConsumeHandshake. */
9463         if ((PRUint32)remaining > length)
9464             goto decode_loser;
9465     }
9466
9467     if (!remaining) {
9468         if (!(isTLS && isServer)) {
9469             desc = bad_certificate;
9470             goto alert_loser;
9471         }
9472         /* This is TLS's version of a no_certificate alert. */
9473         /* I'm a server. I've requested a client cert. He hasn't got one. */
9474         rv = ssl3_HandleNoCertificate(ss);
9475         if (rv != SECSuccess) {
9476             errCode = PORT_GetError();
9477             goto loser;
9478         }
9479        ss->ssl3.hs.ws = wait_client_key;
9480        return SECSuccess;
9481     }
9482
9483     ss->ssl3.peerCertArena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
9484     if (ss->ssl3.peerCertArena == NULL) {
9485         goto loser;     /* don't send alerts on memory errors */
9486     }
9487
9488     /* First get the peer cert. */
9489     remaining -= 3;
9490     if (remaining < 0)
9491         goto decode_loser;
9492
9493     size = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length);
9494     if (size <= 0)
9495         goto loser;     /* fatal alert already sent by ConsumeHandshake. */
9496
9497     if (remaining < size)
9498         goto decode_loser;
9499
9500     certItem.data = b;
9501     certItem.len = size;
9502     b      += size;
9503     length -= size;
9504     remaining -= size;
9505
9506     ss->sec.peerCert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL,
9507                                             PR_FALSE, PR_TRUE);
9508     if (ss->sec.peerCert == NULL) {
9509         /* We should report an alert if the cert was bad, but not if the
9510          * problem was just some local problem, like memory error.
9511          */
9512         goto ambiguous_err;
9513     }
9514
9515     /* Now get all of the CA certs. */
9516     while (remaining > 0) {
9517         remaining -= 3;
9518         if (remaining < 0)
9519             goto decode_loser;
9520
9521         size = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length);
9522         if (size <= 0)
9523             goto loser; /* fatal alert already sent by ConsumeHandshake. */
9524
9525         if (remaining < size)
9526             goto decode_loser;
9527
9528         certItem.data = b;
9529         certItem.len = size;
9530         b      += size;
9531         length -= size;
9532         remaining -= size;
9533
9534         c = PORT_ArenaNew(ss->ssl3.peerCertArena, ssl3CertNode);
9535         if (c == NULL) {
9536             goto loser; /* don't send alerts on memory errors */
9537         }
9538
9539         c->cert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL,
9540                                           PR_FALSE, PR_TRUE);
9541         if (c->cert == NULL) {
9542             goto ambiguous_err;
9543         }
9544
9545         c->next = NULL;
9546         if (lastCert) {
9547             lastCert->next = c;
9548         } else {
9549             ss->ssl3.peerCertChain = c;
9550         }
9551         lastCert = c;
9552     }
9553
9554     if (remaining != 0)
9555         goto decode_loser;
9556
9557     SECKEY_UpdateCertPQG(ss->sec.peerCert);
9558
9559     if (!isServer && ssl3_ExtensionNegotiated(ss, ssl_cert_status_xtn)) {
9560        ss->ssl3.hs.ws = wait_certificate_status;
9561        rv = SECSuccess;
9562     } else {
9563        rv = ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */
9564     }
9565
9566     return rv;
9567
9568 ambiguous_err:
9569     errCode = PORT_GetError();
9570     switch (errCode) {
9571     case PR_OUT_OF_MEMORY_ERROR:
9572     case SEC_ERROR_BAD_DATABASE:
9573     case SEC_ERROR_NO_MEMORY:
9574        if (isTLS) {
9575            desc = internal_error;
9576            goto alert_loser;
9577        }
9578        goto loser;
9579     }
9580     ssl3_SendAlertForCertError(ss, errCode);
9581     goto loser;
9582
9583 decode_loser:
9584     desc = isTLS ? decode_error : bad_certificate;
9585
9586 alert_loser:
9587     (void)SSL3_SendAlert(ss, alert_fatal, desc);
9588
9589 loser:
9590     (void)ssl_MapLowLevelError(errCode);
9591     return SECFailure;
9592 }
9593
9594 static SECStatus
9595 ssl3_AuthCertificate(sslSocket *ss)
9596 {
9597     SECStatus        rv;
9598     PRBool           isServer   = (PRBool)(!!ss->sec.isServer);
9599     int              errCode;
9600
9601     ss->ssl3.hs.authCertificatePending = PR_FALSE;
9602
9603     /*
9604      * Ask caller-supplied callback function to validate cert chain.
9605      */
9606     rv = (SECStatus)(*ss->authCertificate)(ss->authCertificateArg, ss->fd,
9607                                            PR_TRUE, isServer);
9608     if (rv) {
9609         errCode = PORT_GetError();
9610         if (rv != SECWouldBlock) {
9611             if (ss->handleBadCert) {
9612                 rv = (*ss->handleBadCert)(ss->badCertArg, ss->fd);
9613             }
9614         }
9615
9616         if (rv == SECWouldBlock) {
9617             if (ss->sec.isServer) {
9618                 errCode = SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS;
9619                 rv = SECFailure;
9620                 goto loser;
9621             }
9622
9623             ss->ssl3.hs.authCertificatePending = PR_TRUE;
9624             rv = SECSuccess;
9625
9626             /* XXX: Async cert validation and False Start don't work together
9627              * safely yet; if we leave False Start enabled, we may end up false
9628              * starting (sending application data) before we
9629              * SSL_AuthCertificateComplete has been called.
9630              */
9631             ss->opt.enableFalseStart = PR_FALSE;
9632         }
9633
9634         if (rv != SECSuccess) {
9635             ssl3_SendAlertForCertError(ss, errCode);
9636             goto loser;
9637         }
9638     }
9639
9640     ss->sec.ci.sid->peerCert = CERT_DupCertificate(ss->sec.peerCert);
9641
9642     if (!ss->sec.isServer) {
9643         CERTCertificate *cert = ss->sec.peerCert;
9644
9645         /* set the server authentication and key exchange types and sizes
9646         ** from the value in the cert.  If the key exchange key is different,
9647         ** it will get fixed when we handle the server key exchange message.
9648         */
9649         SECKEYPublicKey * pubKey  = CERT_ExtractPublicKey(cert);
9650         ss->sec.authAlgorithm = ss->ssl3.hs.kea_def->signKeyType;
9651         ss->sec.keaType       = ss->ssl3.hs.kea_def->exchKeyType;
9652         if (pubKey) {
9653             ss->sec.keaKeyBits = ss->sec.authKeyBits =
9654                 SECKEY_PublicKeyStrengthInBits(pubKey);
9655 #ifdef NSS_ENABLE_ECC
9656             if (ss->sec.keaType == kt_ecdh) {
9657                 /* Get authKeyBits from signing key.
9658                  * XXX The code below uses a quick approximation of
9659                  * key size based on cert->signatureWrap.signature.data
9660                  * (which contains the DER encoded signature). The field
9661                  * cert->signatureWrap.signature.len contains the
9662                  * length of the encoded signature in bits.
9663                  */
9664                 if (ss->ssl3.hs.kea_def->kea == kea_ecdh_ecdsa) {
9665                     ss->sec.authKeyBits = 
9666                         cert->signatureWrap.signature.data[3]*8;
9667                     if (cert->signatureWrap.signature.data[4] == 0x00)
9668                             ss->sec.authKeyBits -= 8;
9669                     /* 
9670                      * XXX: if cert is not signed by ecdsa we should
9671                      * destroy pubKey and goto bad_cert
9672                      */
9673                 } else if (ss->ssl3.hs.kea_def->kea == kea_ecdh_rsa) {
9674                     ss->sec.authKeyBits = cert->signatureWrap.signature.len;
9675                     /* 
9676                      * XXX: if cert is not signed by rsa we should
9677                      * destroy pubKey and goto bad_cert
9678                      */
9679                 }
9680             }
9681 #endif /* NSS_ENABLE_ECC */
9682             SECKEY_DestroyPublicKey(pubKey); 
9683             pubKey = NULL;
9684         }
9685
9686         ss->ssl3.hs.ws = wait_cert_request; /* disallow server_key_exchange */
9687         if (ss->ssl3.hs.kea_def->is_limited ||
9688             /* XXX OR server cert is signing only. */
9689 #ifdef NSS_ENABLE_ECC
9690             ss->ssl3.hs.kea_def->kea == kea_ecdhe_ecdsa ||
9691             ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa ||
9692 #endif /* NSS_ENABLE_ECC */
9693             ss->ssl3.hs.kea_def->exchKeyType == kt_dh) {
9694             ss->ssl3.hs.ws = wait_server_key; /* allow server_key_exchange */
9695         }
9696     } else {
9697         ss->ssl3.hs.ws = wait_client_key;
9698     }
9699
9700     PORT_Assert(rv == SECSuccess);
9701     if (rv != SECSuccess) {
9702         errCode = SEC_ERROR_LIBRARY_FAILURE;
9703         rv = SECFailure;
9704         goto loser;
9705     }
9706
9707     return rv;
9708
9709 loser:
9710     (void)ssl_MapLowLevelError(errCode);
9711     return SECFailure;
9712 }
9713
9714 static SECStatus ssl3_FinishHandshake(sslSocket *ss);
9715
9716 static SECStatus
9717 ssl3_AlwaysFail(sslSocket * ss)
9718 {
9719     PORT_SetError(PR_INVALID_STATE_ERROR);
9720     return SECFailure;
9721 }
9722
9723 /* Caller must hold 1stHandshakeLock.
9724 */
9725 SECStatus
9726 ssl3_AuthCertificateComplete(sslSocket *ss, PRErrorCode error)
9727 {
9728     SECStatus rv;
9729
9730     PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss));
9731
9732     if (ss->sec.isServer) {
9733         PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS);
9734         return SECFailure;
9735     }
9736
9737     ssl_GetRecvBufLock(ss);
9738     ssl_GetSSL3HandshakeLock(ss);
9739
9740     if (!ss->ssl3.hs.authCertificatePending) {
9741         PORT_SetError(PR_INVALID_STATE_ERROR);
9742         rv = SECFailure;
9743         goto done;
9744     }
9745
9746     ss->ssl3.hs.authCertificatePending = PR_FALSE;
9747
9748     if (error != 0) {
9749         ss->ssl3.hs.restartTarget = ssl3_AlwaysFail;
9750         ssl3_SendAlertForCertError(ss, error);
9751         rv = SECSuccess;
9752     } else if (ss->ssl3.hs.restartTarget != NULL) {
9753         sslRestartTarget target = ss->ssl3.hs.restartTarget;
9754         ss->ssl3.hs.restartTarget = NULL;
9755         rv = target(ss);
9756         /* Even if we blocked here, we have accomplished enough to claim
9757          * success. Any remaining work will be taken care of by subsequent
9758          * calls to SSL_ForceHandshake/PR_Send/PR_Read/etc. 
9759          */
9760         if (rv == SECWouldBlock) {
9761             rv = SECSuccess;
9762         }
9763     } else {
9764         rv = SECSuccess;
9765     }
9766
9767 done:
9768     ssl_ReleaseSSL3HandshakeLock(ss);
9769     ssl_ReleaseRecvBufLock(ss);
9770
9771     return rv;
9772 }
9773
9774 static SECStatus
9775 ssl3_ComputeTLSFinished(ssl3CipherSpec *spec,
9776                         PRBool          isServer,
9777                 const   SSL3Hashes   *  hashes,
9778                         TLSFinished  *  tlsFinished)
9779 {
9780     const char * label;
9781     unsigned int len;
9782     SECStatus    rv;
9783
9784     label = isServer ? "server finished" : "client finished";
9785     len   = 15;
9786
9787     rv = ssl3_TLSPRFWithMasterSecret(spec, label, len, hashes->u.raw,
9788         hashes->len, tlsFinished->verify_data,
9789         sizeof tlsFinished->verify_data);
9790
9791     return rv;
9792 }
9793
9794 /* The calling function must acquire and release the appropriate
9795  * lock (e.g., ssl_GetSpecReadLock / ssl_ReleaseSpecReadLock for
9796  * ss->ssl3.crSpec).
9797  */
9798 SECStatus
9799 ssl3_TLSPRFWithMasterSecret(ssl3CipherSpec *spec, const char *label,
9800     unsigned int labelLen, const unsigned char *val, unsigned int valLen,
9801     unsigned char *out, unsigned int outLen)
9802 {
9803     SECStatus rv = SECSuccess;
9804
9805     if (spec->master_secret && !spec->bypassCiphers) {
9806         SECItem param = {siBuffer, NULL, 0};
9807         CK_MECHANISM_TYPE mech = CKM_TLS_PRF_GENERAL;
9808         PK11Context *prf_context;
9809         unsigned int retLen;
9810
9811         if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
9812             mech = CKM_NSS_TLS_PRF_GENERAL_SHA256;
9813         }
9814         prf_context = PK11_CreateContextBySymKey(mech, CKA_SIGN,
9815                                                  spec->master_secret, &param);
9816         if (!prf_context)
9817             return SECFailure;
9818
9819         rv  = PK11_DigestBegin(prf_context);
9820         rv |= PK11_DigestOp(prf_context, (unsigned char *) label, labelLen);
9821         rv |= PK11_DigestOp(prf_context, val, valLen);
9822         rv |= PK11_DigestFinal(prf_context, out, &retLen, outLen);
9823         PORT_Assert(rv != SECSuccess || retLen == outLen);
9824
9825         PK11_DestroyContext(prf_context, PR_TRUE);
9826     } else {
9827         /* bypass PKCS11 */
9828 #ifdef NO_PKCS11_BYPASS
9829         PORT_Assert(spec->master_secret);
9830         PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
9831         rv = SECFailure;
9832 #else
9833         SECItem inData  = { siBuffer, };
9834         SECItem outData = { siBuffer, };
9835         PRBool isFIPS   = PR_FALSE;
9836
9837         inData.data  = (unsigned char *) val;
9838         inData.len   = valLen;
9839         outData.data = out;
9840         outData.len  = outLen;
9841         if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
9842             rv = TLS_P_hash(HASH_AlgSHA256, &spec->msItem, label, &inData,
9843                             &outData, isFIPS);
9844         } else {
9845             rv = TLS_PRF(&spec->msItem, label, &inData, &outData, isFIPS);
9846         }
9847         PORT_Assert(rv != SECSuccess || outData.len == outLen);
9848 #endif
9849     }
9850     return rv;
9851 }
9852
9853 /* called from ssl3_HandleServerHelloDone
9854  */
9855 static SECStatus
9856 ssl3_SendNextProto(sslSocket *ss)
9857 {
9858     SECStatus rv;
9859     int padding_len;
9860     static const unsigned char padding[32] = {0};
9861
9862     if (ss->ssl3.nextProto.len == 0)
9863         return SECSuccess;
9864
9865     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
9866     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
9867
9868     padding_len = 32 - ((ss->ssl3.nextProto.len + 2) % 32);
9869
9870     rv = ssl3_AppendHandshakeHeader(ss, next_proto, ss->ssl3.nextProto.len +
9871                                                     2 + padding_len);
9872     if (rv != SECSuccess) {
9873         return rv;      /* error code set by AppendHandshakeHeader */
9874     }
9875     rv = ssl3_AppendHandshakeVariable(ss, ss->ssl3.nextProto.data,
9876                                       ss->ssl3.nextProto.len, 1);
9877     if (rv != SECSuccess) {
9878         return rv;      /* error code set by AppendHandshake */
9879     }
9880     rv = ssl3_AppendHandshakeVariable(ss, padding, padding_len, 1);
9881     if (rv != SECSuccess) {
9882         return rv;      /* error code set by AppendHandshake */
9883     }
9884     return rv;
9885 }
9886
9887 /* called from ssl3_SendFinished
9888  *
9889  * This function is simply a debugging aid and therefore does not return a
9890  * SECStatus. */
9891 static void
9892 ssl3_RecordKeyLog(sslSocket *ss)
9893 {
9894     SECStatus rv;
9895     SECItem *keyData;
9896     char buf[14 /* "CLIENT_RANDOM " */ +
9897              SSL3_RANDOM_LENGTH*2 /* client_random */ +
9898              1 /* " " */ +
9899              48*2 /* master secret */ +
9900              1 /* new line */];
9901     unsigned int j;
9902
9903     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
9904
9905     if (!ssl_keylog_iob)
9906         return;
9907
9908     rv = PK11_ExtractKeyValue(ss->ssl3.cwSpec->master_secret);
9909     if (rv != SECSuccess)
9910         return;
9911
9912     ssl_GetSpecReadLock(ss);
9913
9914     /* keyData does not need to be freed. */
9915     keyData = PK11_GetKeyData(ss->ssl3.cwSpec->master_secret);
9916     if (!keyData || !keyData->data || keyData->len != 48) {
9917         ssl_ReleaseSpecReadLock(ss);
9918         return;
9919     }
9920
9921     /* https://developer.mozilla.org/en/NSS_Key_Log_Format */
9922
9923     /* There could be multiple, concurrent writers to the
9924      * keylog, so we have to do everything in a single call to
9925      * fwrite. */
9926
9927     memcpy(buf, "CLIENT_RANDOM ", 14);
9928     j = 14;
9929     hexEncode(buf + j, ss->ssl3.hs.client_random.rand, SSL3_RANDOM_LENGTH);
9930     j += SSL3_RANDOM_LENGTH*2;
9931     buf[j++] = ' ';
9932     hexEncode(buf + j, keyData->data, 48);
9933     j += 48*2;
9934     buf[j++] = '\n';
9935
9936     PORT_Assert(j == sizeof(buf));
9937
9938     ssl_ReleaseSpecReadLock(ss);
9939
9940     if (fwrite(buf, sizeof(buf), 1, ssl_keylog_iob) != 1)
9941         return;
9942     fflush(ssl_keylog_iob);
9943     return;
9944 }
9945
9946 /* called from ssl3_HandleServerHelloDone
9947  *             ssl3_HandleClientHello
9948  *             ssl3_HandleFinished
9949  */
9950 static SECStatus
9951 ssl3_SendFinished(sslSocket *ss, PRInt32 flags)
9952 {
9953     ssl3CipherSpec *cwSpec;
9954     PRBool          isTLS;
9955     PRBool          isServer = ss->sec.isServer;
9956     SECStatus       rv;
9957     SSL3Sender      sender = isServer ? sender_server : sender_client;
9958     SSL3Hashes      hashes;
9959     TLSFinished     tlsFinished;
9960
9961     SSL_TRC(3, ("%d: SSL3[%d]: send finished handshake", SSL_GETPID(), ss->fd));
9962
9963     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
9964     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
9965
9966     ssl_GetSpecReadLock(ss);
9967     cwSpec = ss->ssl3.cwSpec;
9968     isTLS = (PRBool)(cwSpec->version > SSL_LIBRARY_VERSION_3_0);
9969     rv = ssl3_ComputeHandshakeHashes(ss, cwSpec, &hashes, sender);
9970     if (isTLS && rv == SECSuccess) {
9971         rv = ssl3_ComputeTLSFinished(cwSpec, isServer, &hashes, &tlsFinished);
9972     }
9973     ssl_ReleaseSpecReadLock(ss);
9974     if (rv != SECSuccess) {
9975         goto fail;      /* err code was set by ssl3_ComputeHandshakeHashes */
9976     }
9977
9978     if (isTLS) {
9979         if (isServer)
9980             ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished;
9981         else
9982             ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished;
9983         ss->ssl3.hs.finishedBytes = sizeof tlsFinished;
9984         rv = ssl3_AppendHandshakeHeader(ss, finished, sizeof tlsFinished);
9985         if (rv != SECSuccess) 
9986             goto fail;          /* err set by AppendHandshake. */
9987         rv = ssl3_AppendHandshake(ss, &tlsFinished, sizeof tlsFinished);
9988         if (rv != SECSuccess) 
9989             goto fail;          /* err set by AppendHandshake. */
9990     } else {
9991         if (isServer)
9992             ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes.u.s;
9993         else
9994             ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes.u.s;
9995         PORT_Assert(hashes.len == sizeof hashes.u.s);
9996         ss->ssl3.hs.finishedBytes = sizeof hashes.u.s;
9997         rv = ssl3_AppendHandshakeHeader(ss, finished, sizeof hashes.u.s);
9998         if (rv != SECSuccess) 
9999             goto fail;          /* err set by AppendHandshake. */
10000         rv = ssl3_AppendHandshake(ss, &hashes.u.s, sizeof hashes.u.s);
10001         if (rv != SECSuccess) 
10002             goto fail;          /* err set by AppendHandshake. */
10003     }
10004     rv = ssl3_FlushHandshake(ss, flags);
10005     if (rv != SECSuccess) {
10006         goto fail;      /* error code set by ssl3_FlushHandshake */
10007     }
10008
10009     ssl3_RecordKeyLog(ss);
10010
10011     return SECSuccess;
10012
10013 fail:
10014     return rv;
10015 }
10016
10017 /* wrap the master secret, and put it into the SID.
10018  * Caller holds the Spec read lock.
10019  */
10020 SECStatus
10021 ssl3_CacheWrappedMasterSecret(sslSocket *ss, sslSessionID *sid,
10022     ssl3CipherSpec *spec, SSL3KEAType effectiveExchKeyType)
10023 {
10024     PK11SymKey *      wrappingKey  = NULL;
10025     PK11SlotInfo *    symKeySlot;
10026     void *            pwArg        = ss->pkcs11PinArg;
10027     SECStatus         rv           = SECFailure;
10028     PRBool            isServer     = ss->sec.isServer;
10029     CK_MECHANISM_TYPE mechanism    = CKM_INVALID_MECHANISM;
10030     symKeySlot = PK11_GetSlotFromKey(spec->master_secret);
10031     if (!isServer) {
10032         int  wrapKeyIndex;
10033         int  incarnation;
10034
10035         /* these next few functions are mere accessors and don't fail. */
10036         sid->u.ssl3.masterWrapIndex  = wrapKeyIndex =
10037                                        PK11_GetCurrentWrapIndex(symKeySlot);
10038         PORT_Assert(wrapKeyIndex == 0); /* array has only one entry! */
10039
10040         sid->u.ssl3.masterWrapSeries = incarnation =
10041                                        PK11_GetSlotSeries(symKeySlot);
10042         sid->u.ssl3.masterSlotID   = PK11_GetSlotID(symKeySlot);
10043         sid->u.ssl3.masterModuleID = PK11_GetModuleID(symKeySlot);
10044         sid->u.ssl3.masterValid    = PR_TRUE;
10045         /* Get the default wrapping key, for wrapping the master secret before
10046          * placing it in the SID cache entry. */
10047         wrappingKey = PK11_GetWrapKey(symKeySlot, wrapKeyIndex,
10048                                       CKM_INVALID_MECHANISM, incarnation,
10049                                       pwArg);
10050         if (wrappingKey) {
10051             mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */
10052         } else {
10053             int keyLength;
10054             /* if the wrappingKey doesn't exist, attempt to create it.
10055              * Note: we intentionally ignore errors here.  If we cannot
10056              * generate a wrapping key, it is not fatal to this SSL connection,
10057              * but we will not be able to restart this session.
10058              */
10059             mechanism = PK11_GetBestWrapMechanism(symKeySlot);
10060             keyLength = PK11_GetBestKeyLength(symKeySlot, mechanism);
10061             /* Zero length means fixed key length algorithm, or error.
10062              * It's ambiguous.
10063              */
10064             wrappingKey = PK11_KeyGen(symKeySlot, mechanism, NULL,
10065                                       keyLength, pwArg);
10066             if (wrappingKey) {
10067                 PK11_SetWrapKey(symKeySlot, wrapKeyIndex, wrappingKey);
10068             }
10069         }
10070     } else {
10071         /* server socket using session cache. */
10072         mechanism = PK11_GetBestWrapMechanism(symKeySlot);
10073         if (mechanism != CKM_INVALID_MECHANISM) {
10074             wrappingKey =
10075                 getWrappingKey(ss, symKeySlot, effectiveExchKeyType,
10076                                mechanism, pwArg);
10077             if (wrappingKey) {
10078                 mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */
10079             }
10080         }
10081     }
10082
10083     sid->u.ssl3.masterWrapMech = mechanism;
10084     PK11_FreeSlot(symKeySlot);
10085
10086     if (wrappingKey) {
10087         SECItem wmsItem;
10088
10089         wmsItem.data = sid->u.ssl3.keys.wrapped_master_secret;
10090         wmsItem.len  = sizeof sid->u.ssl3.keys.wrapped_master_secret;
10091         rv = PK11_WrapSymKey(mechanism, NULL, wrappingKey,
10092                              spec->master_secret, &wmsItem);
10093         /* rv is examined below. */
10094         sid->u.ssl3.keys.wrapped_master_secret_len = wmsItem.len;
10095         PK11_FreeSymKey(wrappingKey);
10096     }
10097     return rv;
10098 }
10099
10100 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
10101  * ssl3 Finished message from the peer.
10102  * Caller must hold Handshake and RecvBuf locks.
10103  */
10104 static SECStatus
10105 ssl3_HandleFinished(sslSocket *ss, SSL3Opaque *b, PRUint32 length,
10106                     const SSL3Hashes *hashes)
10107 {
10108     sslSessionID *    sid          = ss->sec.ci.sid;
10109     SECStatus         rv           = SECSuccess;
10110     PRBool            isServer     = ss->sec.isServer;
10111     PRBool            isTLS;
10112     SSL3KEAType       effectiveExchKeyType;
10113
10114     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
10115     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
10116
10117     SSL_TRC(3, ("%d: SSL3[%d]: handle finished handshake",
10118         SSL_GETPID(), ss->fd));
10119
10120     if (ss->ssl3.hs.ws != wait_finished) {
10121         SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10122         PORT_SetError(SSL_ERROR_RX_UNEXPECTED_FINISHED);
10123         return SECFailure;
10124     }
10125
10126     isTLS = (PRBool)(ss->ssl3.crSpec->version > SSL_LIBRARY_VERSION_3_0);
10127     if (isTLS) {
10128         TLSFinished tlsFinished;
10129
10130         if (length != sizeof tlsFinished) {
10131             (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
10132             PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED);
10133             return SECFailure;
10134         }
10135         rv = ssl3_ComputeTLSFinished(ss->ssl3.crSpec, !isServer, 
10136                                      hashes, &tlsFinished);
10137         if (!isServer)
10138             ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished;
10139         else
10140             ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished;
10141         ss->ssl3.hs.finishedBytes = sizeof tlsFinished;
10142         if (rv != SECSuccess ||
10143             0 != NSS_SecureMemcmp(&tlsFinished, b, length)) {
10144             (void)SSL3_SendAlert(ss, alert_fatal, decrypt_error);
10145             PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
10146             return SECFailure;
10147         }
10148     } else {
10149         if (length != sizeof(SSL3Finished)) {
10150             (void)ssl3_IllegalParameter(ss);
10151             PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED);
10152             return SECFailure;
10153         }
10154
10155         if (!isServer)
10156             ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes->u.s;
10157         else
10158             ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes->u.s;
10159         PORT_Assert(hashes->len == sizeof hashes->u.s);
10160         ss->ssl3.hs.finishedBytes = sizeof hashes->u.s;
10161         if (0 != NSS_SecureMemcmp(&hashes->u.s, b, length)) {
10162             (void)ssl3_HandshakeFailure(ss);
10163             PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
10164             return SECFailure;
10165         }
10166     }
10167
10168     ssl_GetXmitBufLock(ss);     /*************************************/
10169
10170     if ((isServer && !ss->ssl3.hs.isResuming) ||
10171         (!isServer && ss->ssl3.hs.isResuming)) {
10172         PRInt32 flags = 0;
10173
10174         /* Send a NewSessionTicket message if the client sent us
10175          * either an empty session ticket, or one that did not verify.
10176          * (Note that if either of these conditions was met, then the
10177          * server has sent a SessionTicket extension in the
10178          * ServerHello message.)
10179          */
10180         if (isServer && !ss->ssl3.hs.isResuming &&
10181             ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn)) {
10182             rv = ssl3_SendNewSessionTicket(ss);
10183             if (rv != SECSuccess) {
10184                 goto xmit_loser;
10185             }
10186         }
10187
10188         rv = ssl3_SendChangeCipherSpecs(ss);
10189         if (rv != SECSuccess) {
10190             goto xmit_loser;    /* err is set. */
10191         }
10192         /* If this thread is in SSL_SecureSend (trying to write some data) 
10193         ** then set the ssl_SEND_FLAG_FORCE_INTO_BUFFER flag, so that the 
10194         ** last two handshake messages (change cipher spec and finished) 
10195         ** will be sent in the same send/write call as the application data.
10196         */
10197         if (ss->writerThread == PR_GetCurrentThread()) {
10198             flags = ssl_SEND_FLAG_FORCE_INTO_BUFFER;
10199         }
10200
10201         if (!isServer && !ss->firstHsDone) {
10202             rv = ssl3_SendNextProto(ss);
10203             if (rv != SECSuccess) {
10204                 goto xmit_loser; /* err code was set. */
10205             }
10206         }
10207
10208         if (IS_DTLS(ss)) {
10209             flags |= ssl_SEND_FLAG_NO_RETRANSMIT;
10210         }
10211
10212         rv = ssl3_SendFinished(ss, flags);
10213         if (rv != SECSuccess) {
10214             goto xmit_loser;    /* err is set. */
10215         }
10216     }
10217
10218 xmit_loser:
10219     ssl_ReleaseXmitBufLock(ss); /*************************************/
10220     if (rv != SECSuccess) {
10221         return rv;
10222     }
10223
10224     ss->gs.writeOffset = 0;
10225     ss->gs.readOffset  = 0;
10226
10227     if (ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) {
10228         effectiveExchKeyType = kt_rsa;
10229     } else {
10230         effectiveExchKeyType = ss->ssl3.hs.kea_def->exchKeyType;
10231     }
10232
10233     if (sid->cached == never_cached && !ss->opt.noCache && ss->sec.cache) {
10234         /* fill in the sid */
10235         sid->u.ssl3.cipherSuite = ss->ssl3.hs.cipher_suite;
10236         sid->u.ssl3.compression = ss->ssl3.hs.compression;
10237         sid->u.ssl3.policy      = ss->ssl3.policy;
10238 #ifdef NSS_ENABLE_ECC
10239         sid->u.ssl3.negotiatedECCurves = ss->ssl3.hs.negotiatedECCurves;
10240 #endif
10241         sid->u.ssl3.exchKeyType = effectiveExchKeyType;
10242         sid->version            = ss->version;
10243         sid->authAlgorithm      = ss->sec.authAlgorithm;
10244         sid->authKeyBits        = ss->sec.authKeyBits;
10245         sid->keaType            = ss->sec.keaType;
10246         sid->keaKeyBits         = ss->sec.keaKeyBits;
10247         sid->lastAccessTime     = sid->creationTime = ssl_Time();
10248         sid->expirationTime     = sid->creationTime + ssl3_sid_timeout;
10249         sid->localCert          = CERT_DupCertificate(ss->sec.localCert);
10250
10251         ssl_GetSpecReadLock(ss);        /*************************************/
10252
10253         /* Copy the master secret (wrapped or unwrapped) into the sid */
10254         if (ss->ssl3.crSpec->msItem.len && ss->ssl3.crSpec->msItem.data) {
10255             sid->u.ssl3.keys.wrapped_master_secret_len = 
10256                             ss->ssl3.crSpec->msItem.len;
10257             memcpy(sid->u.ssl3.keys.wrapped_master_secret, 
10258                    ss->ssl3.crSpec->msItem.data, ss->ssl3.crSpec->msItem.len);
10259             sid->u.ssl3.masterValid    = PR_TRUE;
10260             sid->u.ssl3.keys.msIsWrapped = PR_FALSE;
10261             rv = SECSuccess;
10262         } else {
10263             rv = ssl3_CacheWrappedMasterSecret(ss, ss->sec.ci.sid,
10264                                                ss->ssl3.crSpec,
10265                                                effectiveExchKeyType);
10266             sid->u.ssl3.keys.msIsWrapped = PR_TRUE;
10267         }
10268         ssl_ReleaseSpecReadLock(ss);  /*************************************/
10269
10270         /* If the wrap failed, we don't cache the sid.
10271          * The connection continues normally however.
10272          */
10273         ss->ssl3.hs.cacheSID = rv == SECSuccess;
10274     }
10275
10276     if (ss->ssl3.hs.authCertificatePending) {
10277         if (ss->ssl3.hs.restartTarget) {
10278             PR_NOT_REACHED("ssl3_HandleFinished: unexpected restartTarget");
10279             PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
10280             return SECFailure;
10281         }
10282
10283         ss->ssl3.hs.restartTarget = ssl3_FinishHandshake;
10284         return SECWouldBlock;
10285     }
10286
10287     rv = ssl3_FinishHandshake(ss);
10288     return rv;
10289 }
10290
10291 SECStatus
10292 ssl3_FinishHandshake(sslSocket * ss)
10293 {
10294     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
10295     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
10296     PORT_Assert( ss->ssl3.hs.restartTarget == NULL );
10297
10298     /* The first handshake is now completed. */
10299     ss->handshake           = NULL;
10300     ss->firstHsDone         = PR_TRUE;
10301
10302     if (ss->ssl3.hs.cacheSID) {
10303         (*ss->sec.cache)(ss->sec.ci.sid);
10304         ss->ssl3.hs.cacheSID = PR_FALSE;
10305     }
10306
10307     ss->ssl3.hs.ws = idle_handshake;
10308
10309     /* Do the handshake callback for sslv3 here, if we cannot false start. */
10310     if (ss->handshakeCallback != NULL && !ssl3_CanFalseStart(ss)) {
10311         (ss->handshakeCallback)(ss->fd, ss->handshakeCallbackData);
10312     }
10313
10314     return SECSuccess;
10315 }
10316
10317 /* Called from ssl3_HandleHandshake() when it has gathered a complete ssl3
10318  * hanshake message.
10319  * Caller must hold Handshake and RecvBuf locks.
10320  */
10321 SECStatus
10322 ssl3_HandleHandshakeMessage(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
10323 {
10324     SECStatus         rv        = SECSuccess;
10325     SSL3HandshakeType type      = ss->ssl3.hs.msg_type;
10326     SSL3Hashes        hashes;   /* computed hashes are put here. */
10327     PRUint8           hdr[4];
10328     PRUint8           dtlsData[8];
10329
10330     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
10331     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
10332     /*
10333      * We have to compute the hashes before we update them with the
10334      * current message.
10335      */
10336     ssl_GetSpecReadLock(ss);    /************************************/
10337     if((type == finished) || (type == certificate_verify)) {
10338         SSL3Sender      sender = (SSL3Sender)0;
10339         ssl3CipherSpec *rSpec  = ss->ssl3.prSpec;
10340
10341         if (type == finished) {
10342             sender = ss->sec.isServer ? sender_client : sender_server;
10343             rSpec  = ss->ssl3.crSpec;
10344         }
10345         rv = ssl3_ComputeHandshakeHashes(ss, rSpec, &hashes, sender);
10346     }
10347     ssl_ReleaseSpecReadLock(ss); /************************************/
10348     if (rv != SECSuccess) {
10349         return rv;      /* error code was set by ssl3_ComputeHandshakeHashes*/
10350     }
10351     SSL_TRC(30,("%d: SSL3[%d]: handle handshake message: %s", SSL_GETPID(),
10352                 ss->fd, ssl3_DecodeHandshakeType(ss->ssl3.hs.msg_type)));
10353
10354     hdr[0] = (PRUint8)ss->ssl3.hs.msg_type;
10355     hdr[1] = (PRUint8)(length >> 16);
10356     hdr[2] = (PRUint8)(length >>  8);
10357     hdr[3] = (PRUint8)(length      );
10358
10359     /* Start new handshake hashes when we start a new handshake */
10360     if (ss->ssl3.hs.msg_type == client_hello) {
10361         rv = ssl3_RestartHandshakeHashes(ss);
10362         if (rv != SECSuccess) {
10363             return rv;
10364         }
10365     }
10366     /* We should not include hello_request and hello_verify_request messages
10367      * in the handshake hashes */
10368     if ((ss->ssl3.hs.msg_type != hello_request) &&
10369         (ss->ssl3.hs.msg_type != hello_verify_request)) {
10370         rv = ssl3_UpdateHandshakeHashes(ss, (unsigned char*) hdr, 4);
10371         if (rv != SECSuccess) return rv;        /* err code already set. */
10372
10373         /* Extra data to simulate a complete DTLS handshake fragment */
10374         if (IS_DTLS(ss)) {
10375             /* Sequence number */
10376             dtlsData[0] = MSB(ss->ssl3.hs.recvMessageSeq);
10377             dtlsData[1] = LSB(ss->ssl3.hs.recvMessageSeq);
10378
10379             /* Fragment offset */
10380             dtlsData[2] = 0;
10381             dtlsData[3] = 0;
10382             dtlsData[4] = 0;
10383
10384             /* Fragment length */
10385             dtlsData[5] = (PRUint8)(length >> 16);
10386             dtlsData[6] = (PRUint8)(length >>  8);
10387             dtlsData[7] = (PRUint8)(length      );
10388
10389             rv = ssl3_UpdateHandshakeHashes(ss, (unsigned char*) dtlsData,
10390                                             sizeof(dtlsData));
10391             if (rv != SECSuccess) return rv;    /* err code already set. */
10392         }
10393
10394         /* The message body */
10395         rv = ssl3_UpdateHandshakeHashes(ss, b, length);
10396         if (rv != SECSuccess) return rv;        /* err code already set. */
10397     }
10398
10399     PORT_SetError(0);   /* each message starts with no error. */
10400
10401     if (ss->ssl3.hs.ws == wait_certificate_status &&
10402         ss->ssl3.hs.msg_type != certificate_status) {
10403         /* If we negotiated the certificate_status extension then we deferred
10404          * certificate validation until we get the CertificateStatus messsage.
10405          * But the CertificateStatus message is optional. If the server did
10406          * not send it then we need to validate the certificate now. If the
10407          * server does send the CertificateStatus message then we will
10408          * authenticate the certificate in ssl3_HandleCertificateStatus.
10409          */
10410         rv = ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */
10411         PORT_Assert(rv != SECWouldBlock);
10412         if (rv != SECSuccess) {
10413             return rv;
10414         }
10415     }
10416
10417     switch (ss->ssl3.hs.msg_type) {
10418     case hello_request:
10419         if (length != 0) {
10420             (void)ssl3_DecodeError(ss);
10421             PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_REQUEST);
10422             return SECFailure;
10423         }
10424         if (ss->sec.isServer) {
10425             (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10426             PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST);
10427             return SECFailure;
10428         }
10429         rv = ssl3_HandleHelloRequest(ss);
10430         break;
10431     case client_hello:
10432         if (!ss->sec.isServer) {
10433             (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10434             PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO);
10435             return SECFailure;
10436         }
10437         rv = ssl3_HandleClientHello(ss, b, length);
10438         break;
10439     case server_hello:
10440         if (ss->sec.isServer) {
10441             (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10442             PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO);
10443             return SECFailure;
10444         }
10445         rv = ssl3_HandleServerHello(ss, b, length);
10446         break;
10447     case hello_verify_request:
10448         if (!IS_DTLS(ss) || ss->sec.isServer) {
10449             (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10450             PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_VERIFY_REQUEST);
10451             return SECFailure;
10452         }
10453         rv = dtls_HandleHelloVerifyRequest(ss, b, length);
10454         break;
10455     case certificate:
10456         rv = ssl3_HandleCertificate(ss, b, length);
10457         break;
10458     case certificate_status:
10459         rv = ssl3_HandleCertificateStatus(ss, b, length);
10460         break;
10461     case server_key_exchange:
10462         if (ss->sec.isServer) {
10463             (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10464             PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH);
10465             return SECFailure;
10466         }
10467         rv = ssl3_HandleServerKeyExchange(ss, b, length);
10468         break;
10469     case certificate_request:
10470         if (ss->sec.isServer) {
10471             (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10472             PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST);
10473             return SECFailure;
10474         }
10475         rv = ssl3_HandleCertificateRequest(ss, b, length);
10476         break;
10477     case server_hello_done:
10478         if (length != 0) {
10479             (void)ssl3_DecodeError(ss);
10480             PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_DONE);
10481             return SECFailure;
10482         }
10483         if (ss->sec.isServer) {
10484             (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10485             PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE);
10486             return SECFailure;
10487         }
10488         rv = ssl3_HandleServerHelloDone(ss);
10489         break;
10490     case certificate_verify:
10491         if (!ss->sec.isServer) {
10492             (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10493             PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY);
10494             return SECFailure;
10495         }
10496         rv = ssl3_HandleCertificateVerify(ss, b, length, &hashes);
10497         break;
10498     case client_key_exchange:
10499         if (!ss->sec.isServer) {
10500             (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10501             PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH);
10502             return SECFailure;
10503         }
10504         rv = ssl3_HandleClientKeyExchange(ss, b, length);
10505         break;
10506     case new_session_ticket:
10507         if (ss->sec.isServer) {
10508             (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10509             PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET);
10510             return SECFailure;
10511         }
10512         rv = ssl3_HandleNewSessionTicket(ss, b, length);
10513         break;
10514     case finished:
10515         rv = ssl3_HandleFinished(ss, b, length, &hashes);
10516         break;
10517     default:
10518         (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10519         PORT_SetError(SSL_ERROR_RX_UNKNOWN_HANDSHAKE);
10520         rv = SECFailure;
10521     }
10522
10523     if (IS_DTLS(ss) && (rv != SECFailure)) {
10524         /* Increment the expected sequence number */
10525         ss->ssl3.hs.recvMessageSeq++;
10526     }
10527
10528     return rv;
10529 }
10530
10531 /* Called only from ssl3_HandleRecord, for each (deciphered) ssl3 record.
10532  * origBuf is the decrypted ssl record content.
10533  * Caller must hold the handshake and RecvBuf locks.
10534  */
10535 static SECStatus
10536 ssl3_HandleHandshake(sslSocket *ss, sslBuffer *origBuf)
10537 {
10538     /*
10539      * There may be a partial handshake message already in the handshake
10540      * state. The incoming buffer may contain another portion, or a
10541      * complete message or several messages followed by another portion.
10542      *
10543      * Each message is made contiguous before being passed to the actual
10544      * message parser.
10545      */
10546     sslBuffer *buf = &ss->ssl3.hs.msgState; /* do not lose the original buffer pointer */
10547     SECStatus rv;
10548
10549     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
10550     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
10551
10552     if (buf->buf == NULL) {
10553         *buf = *origBuf;
10554     }
10555     while (buf->len > 0) {
10556         if (ss->ssl3.hs.header_bytes < 4) {
10557             PRUint8 t;
10558             t = *(buf->buf++);
10559             buf->len--;
10560             if (ss->ssl3.hs.header_bytes++ == 0)
10561                 ss->ssl3.hs.msg_type = (SSL3HandshakeType)t;
10562             else
10563                 ss->ssl3.hs.msg_len = (ss->ssl3.hs.msg_len << 8) + t;
10564             if (ss->ssl3.hs.header_bytes < 4)
10565                 continue;
10566
10567 #define MAX_HANDSHAKE_MSG_LEN 0x1ffff   /* 128k - 1 */
10568             if (ss->ssl3.hs.msg_len > MAX_HANDSHAKE_MSG_LEN) {
10569                 (void)ssl3_DecodeError(ss);
10570                 PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
10571                 return SECFailure;
10572             }
10573 #undef MAX_HANDSHAKE_MSG_LEN
10574
10575             /* If msg_len is zero, be sure we fall through, 
10576             ** even if buf->len is zero. 
10577             */
10578             if (ss->ssl3.hs.msg_len > 0) 
10579                 continue;
10580         }
10581
10582         /*
10583          * Header has been gathered and there is at least one byte of new
10584          * data available for this message. If it can be done right out
10585          * of the original buffer, then use it from there.
10586          */
10587         if (ss->ssl3.hs.msg_body.len == 0 && buf->len >= ss->ssl3.hs.msg_len) {
10588             /* handle it from input buffer */
10589             rv = ssl3_HandleHandshakeMessage(ss, buf->buf, ss->ssl3.hs.msg_len);
10590             if (rv == SECFailure) {
10591                 /* This test wants to fall through on either
10592                  * SECSuccess or SECWouldBlock.
10593                  * ssl3_HandleHandshakeMessage MUST set the error code.
10594                  */
10595                 return rv;
10596             }
10597             buf->buf += ss->ssl3.hs.msg_len;
10598             buf->len -= ss->ssl3.hs.msg_len;
10599             ss->ssl3.hs.msg_len = 0;
10600             ss->ssl3.hs.header_bytes = 0;
10601             if (rv != SECSuccess) { /* return if SECWouldBlock. */
10602                 return rv;
10603             }
10604         } else {
10605             /* must be copied to msg_body and dealt with from there */
10606             unsigned int bytes;
10607
10608             PORT_Assert(ss->ssl3.hs.msg_body.len < ss->ssl3.hs.msg_len);
10609             bytes = PR_MIN(buf->len, ss->ssl3.hs.msg_len - ss->ssl3.hs.msg_body.len);
10610
10611             /* Grow the buffer if needed */
10612             rv = sslBuffer_Grow(&ss->ssl3.hs.msg_body, ss->ssl3.hs.msg_len);
10613             if (rv != SECSuccess) {
10614                 /* sslBuffer_Grow has set a memory error code. */
10615                 return SECFailure;
10616             }
10617
10618             PORT_Memcpy(ss->ssl3.hs.msg_body.buf + ss->ssl3.hs.msg_body.len,
10619                         buf->buf, bytes);
10620             ss->ssl3.hs.msg_body.len += bytes;
10621             buf->buf += bytes;
10622             buf->len -= bytes;
10623
10624             PORT_Assert(ss->ssl3.hs.msg_body.len <= ss->ssl3.hs.msg_len);
10625
10626             /* if we have a whole message, do it */
10627             if (ss->ssl3.hs.msg_body.len == ss->ssl3.hs.msg_len) {
10628                 rv = ssl3_HandleHandshakeMessage(
10629                     ss, ss->ssl3.hs.msg_body.buf, ss->ssl3.hs.msg_len);
10630                 if (rv == SECFailure) {
10631                     /* This test wants to fall through on either
10632                      * SECSuccess or SECWouldBlock.
10633                      * ssl3_HandleHandshakeMessage MUST set error code.
10634                      */
10635                     return rv;
10636                 }
10637                 ss->ssl3.hs.msg_body.len = 0;
10638                 ss->ssl3.hs.msg_len = 0;
10639                 ss->ssl3.hs.header_bytes = 0;
10640                 if (rv != SECSuccess) { /* return if SECWouldBlock. */
10641                     return rv;
10642                 }
10643             } else {
10644                 PORT_Assert(buf->len == 0);
10645                 break;
10646             }
10647         }
10648     }   /* end loop */
10649
10650     origBuf->len = 0;   /* So ssl3_GatherAppDataRecord will keep looping. */
10651     buf->buf = NULL;    /* not a leak. */
10652     return SECSuccess;
10653 }
10654
10655 /* These macros return the given value with the MSB copied to all the other
10656  * bits. They use the fact that arithmetic shift shifts-in the sign bit.
10657  * However, this is not ensured by the C standard so you may need to replace
10658  * them with something else for odd compilers. */
10659 #define DUPLICATE_MSB_TO_ALL(x) ( (unsigned)( (int)(x) >> (sizeof(int)*8-1) ) )
10660 #define DUPLICATE_MSB_TO_ALL_8(x) ((unsigned char)(DUPLICATE_MSB_TO_ALL(x)))
10661
10662 /* SECStatusToMask returns, in constant time, a mask value of all ones if
10663  * rv == SECSuccess.  Otherwise it returns zero. */
10664 static unsigned int
10665 SECStatusToMask(SECStatus rv)
10666 {
10667     unsigned int good;
10668     /* rv ^ SECSuccess is zero iff rv == SECSuccess. Subtracting one results
10669      * in the MSB being set to one iff it was zero before. */
10670     good = rv ^ SECSuccess;
10671     good--;
10672     return DUPLICATE_MSB_TO_ALL(good);
10673 }
10674
10675 /* ssl_ConstantTimeGE returns 0xff if a>=b and 0x00 otherwise. */
10676 static unsigned char
10677 ssl_ConstantTimeGE(unsigned int a, unsigned int b)
10678 {
10679     a -= b;
10680     return DUPLICATE_MSB_TO_ALL(~a);
10681 }
10682
10683 /* ssl_ConstantTimeEQ8 returns 0xff if a==b and 0x00 otherwise. */
10684 static unsigned char
10685 ssl_ConstantTimeEQ8(unsigned char a, unsigned char b)
10686 {
10687     unsigned int c = a ^ b;
10688     c--;
10689     return DUPLICATE_MSB_TO_ALL_8(c);
10690 }
10691
10692 static SECStatus
10693 ssl_RemoveSSLv3CBCPadding(sslBuffer *plaintext,
10694                           unsigned int blockSize,
10695                           unsigned int macSize)
10696 {
10697     unsigned int paddingLength, good, t;
10698     const unsigned int overhead = 1 /* padding length byte */ + macSize;
10699
10700     /* These lengths are all public so we can test them in non-constant
10701      * time. */
10702     if (overhead > plaintext->len) {
10703         return SECFailure;
10704     }
10705
10706     paddingLength = plaintext->buf[plaintext->len-1];
10707     /* SSLv3 padding bytes are random and cannot be checked. */
10708     t = plaintext->len;
10709     t -= paddingLength+overhead;
10710     /* If len >= paddingLength+overhead then the MSB of t is zero. */
10711     good = DUPLICATE_MSB_TO_ALL(~t);
10712     /* SSLv3 requires that the padding is minimal. */
10713     t = blockSize - (paddingLength+1);
10714     good &= DUPLICATE_MSB_TO_ALL(~t);
10715     plaintext->len -= good & (paddingLength+1);
10716     return (good & SECSuccess) | (~good & SECFailure);
10717 }
10718
10719 static SECStatus
10720 ssl_RemoveTLSCBCPadding(sslBuffer *plaintext, unsigned int macSize)
10721 {
10722     unsigned int paddingLength, good, t, toCheck, i;
10723     const unsigned int overhead = 1 /* padding length byte */ + macSize;
10724
10725     /* These lengths are all public so we can test them in non-constant
10726      * time. */
10727     if (overhead > plaintext->len) {
10728         return SECFailure;
10729     }
10730
10731     paddingLength = plaintext->buf[plaintext->len-1];
10732     t = plaintext->len;
10733     t -= paddingLength+overhead;
10734     /* If len >= paddingLength+overhead then the MSB of t is zero. */
10735     good = DUPLICATE_MSB_TO_ALL(~t);
10736
10737     /* The padding consists of a length byte at the end of the record and then
10738      * that many bytes of padding, all with the same value as the length byte.
10739      * Thus, with the length byte included, there are paddingLength+1 bytes of
10740      * padding.
10741      *
10742      * We can't check just |paddingLength+1| bytes because that leaks
10743      * decrypted information. Therefore we always have to check the maximum
10744      * amount of padding possible. (Again, the length of the record is
10745      * public information so we can use it.) */
10746     toCheck = 255; /* maximum amount of padding. */
10747     if (toCheck > plaintext->len-1) {
10748         toCheck = plaintext->len-1;
10749     }
10750
10751     for (i = 0; i < toCheck; i++) {
10752         unsigned int t = paddingLength - i;
10753         /* If i <= paddingLength then the MSB of t is zero and mask is
10754          * 0xff.  Otherwise, mask is 0. */
10755         unsigned char mask = DUPLICATE_MSB_TO_ALL(~t);
10756         unsigned char b = plaintext->buf[plaintext->len-1-i];
10757         /* The final |paddingLength+1| bytes should all have the value
10758          * |paddingLength|. Therefore the XOR should be zero. */
10759         good &= ~(mask&(paddingLength ^ b));
10760     }
10761
10762     /* If any of the final |paddingLength+1| bytes had the wrong value,
10763      * one or more of the lower eight bits of |good| will be cleared. We
10764      * AND the bottom 8 bits together and duplicate the result to all the
10765      * bits. */
10766     good &= good >> 4;
10767     good &= good >> 2;
10768     good &= good >> 1;
10769     good <<= sizeof(good)*8-1;
10770     good = DUPLICATE_MSB_TO_ALL(good);
10771
10772     plaintext->len -= good & (paddingLength+1);
10773     return (good & SECSuccess) | (~good & SECFailure);
10774 }
10775
10776 /* On entry:
10777  *   originalLength >= macSize
10778  *   macSize <= MAX_MAC_LENGTH
10779  *   plaintext->len >= macSize
10780  */
10781 static void
10782 ssl_CBCExtractMAC(sslBuffer *plaintext,
10783                   unsigned int originalLength,
10784                   SSL3Opaque* out,
10785                   unsigned int macSize)
10786 {
10787     unsigned char rotatedMac[MAX_MAC_LENGTH];
10788     /* macEnd is the index of |plaintext->buf| just after the end of the
10789      * MAC. */
10790     unsigned macEnd = plaintext->len;
10791     unsigned macStart = macEnd - macSize;
10792     /* scanStart contains the number of bytes that we can ignore because
10793      * the MAC's position can only vary by 255 bytes. */
10794     unsigned scanStart = 0;
10795     unsigned i, j, divSpoiler;
10796     unsigned char rotateOffset;
10797
10798     if (originalLength > macSize + 255 + 1)
10799         scanStart = originalLength - (macSize + 255 + 1);
10800
10801     /* divSpoiler contains a multiple of macSize that is used to cause the
10802      * modulo operation to be constant time. Without this, the time varies
10803      * based on the amount of padding when running on Intel chips at least.
10804      *
10805      * The aim of right-shifting macSize is so that the compiler doesn't
10806      * figure out that it can remove divSpoiler as that would require it
10807      * to prove that macSize is always even, which I hope is beyond it. */
10808     divSpoiler = macSize >> 1;
10809     divSpoiler <<= (sizeof(divSpoiler)-1)*8;
10810     rotateOffset = (divSpoiler + macStart - scanStart) % macSize;
10811
10812     memset(rotatedMac, 0, macSize);
10813     for (i = scanStart; i < originalLength;) {
10814         for (j = 0; j < macSize && i < originalLength; i++, j++) {
10815             unsigned char macStarted = ssl_ConstantTimeGE(i, macStart);
10816             unsigned char macEnded = ssl_ConstantTimeGE(i, macEnd);
10817             unsigned char b = 0;
10818             b = plaintext->buf[i];
10819             rotatedMac[j] |= b & macStarted & ~macEnded;
10820         }
10821     }
10822
10823     /* Now rotate the MAC. If we knew that the MAC fit into a CPU cache line
10824      * we could line-align |rotatedMac| and rotate in place. */
10825     memset(out, 0, macSize);
10826     for (i = 0; i < macSize; i++) {
10827         unsigned char offset =
10828             (divSpoiler + macSize - rotateOffset + i) % macSize;
10829         for (j = 0; j < macSize; j++) {
10830             out[j] |= rotatedMac[i] & ssl_ConstantTimeEQ8(j, offset);
10831         }
10832     }
10833 }
10834
10835 /* if cText is non-null, then decipher, check MAC, and decompress the
10836  * SSL record from cText->buf (typically gs->inbuf)
10837  * into databuf (typically gs->buf), and any previous contents of databuf
10838  * is lost.  Then handle databuf according to its SSL record type,
10839  * unless it's an application record.
10840  *
10841  * If cText is NULL, then the ciphertext has previously been deciphered and
10842  * checked, and is already sitting in databuf.  It is processed as an SSL
10843  * Handshake message.
10844  *
10845  * DOES NOT process the decrypted/decompressed application data.
10846  * On return, databuf contains the decrypted/decompressed record.
10847  *
10848  * Called from ssl3_GatherCompleteHandshake
10849  *             ssl3_RestartHandshakeAfterCertReq
10850  *
10851  * Caller must hold the RecvBufLock.
10852  *
10853  * This function aquires and releases the SSL3Handshake Lock, holding the
10854  * lock around any calls to functions that handle records other than
10855  * Application Data records.
10856  */
10857 SECStatus
10858 ssl3_HandleRecord(sslSocket *ss, SSL3Ciphertext *cText, sslBuffer *databuf)
10859 {
10860     const ssl3BulkCipherDef *cipher_def;
10861     ssl3CipherSpec *     crSpec;
10862     SECStatus            rv;
10863     unsigned int         hashBytes = MAX_MAC_LENGTH + 1;
10864     PRBool               isTLS;
10865     SSL3ContentType      rType;
10866     SSL3Opaque           hash[MAX_MAC_LENGTH];
10867     SSL3Opaque           givenHashBuf[MAX_MAC_LENGTH];
10868     SSL3Opaque          *givenHash;
10869     sslBuffer           *plaintext;
10870     sslBuffer            temp_buf;
10871     PRUint64             dtls_seq_num;
10872     unsigned int         ivLen = 0;
10873     unsigned int         originalLen = 0;
10874     unsigned int         good;
10875     unsigned int         minLength;
10876     unsigned char        header[13];
10877     unsigned int         headerLen;
10878
10879     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
10880
10881     if (!ss->ssl3.initialized) {
10882         ssl_GetSSL3HandshakeLock(ss);
10883         rv = ssl3_InitState(ss);
10884         ssl_ReleaseSSL3HandshakeLock(ss);
10885         if (rv != SECSuccess) {
10886             return rv;          /* ssl3_InitState has set the error code. */
10887         }
10888     }
10889
10890     /* check for Token Presence */
10891     if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) {
10892         PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
10893         return SECFailure;
10894     }
10895
10896     /* cText is NULL when we're called from ssl3_RestartHandshakeAfterXXX().
10897      * This implies that databuf holds a previously deciphered SSL Handshake
10898      * message.
10899      */
10900     if (cText == NULL) {
10901         SSL_DBG(("%d: SSL3[%d]: HandleRecord, resuming handshake",
10902                  SSL_GETPID(), ss->fd));
10903         rType = content_handshake;
10904         goto process_it;
10905     }
10906
10907     ssl_GetSpecReadLock(ss); /******************************************/
10908
10909     crSpec = ss->ssl3.crSpec;
10910     cipher_def = crSpec->cipher_def;
10911
10912     /* 
10913      * DTLS relevance checks:
10914      * Note that this code currently ignores all out-of-epoch packets,
10915      * which means we lose some in the case of rehandshake +
10916      * loss/reordering. Since DTLS is explicitly unreliable, this
10917      * seems like a good tradeoff for implementation effort and is
10918      * consistent with the guidance of RFC 6347 Sections 4.1 and 4.2.4.1
10919      */
10920     if (IS_DTLS(ss)) {
10921         DTLSEpoch epoch = (cText->seq_num.high >> 16) & 0xffff;
10922         
10923         if (crSpec->epoch != epoch) {
10924             ssl_ReleaseSpecReadLock(ss);
10925             SSL_DBG(("%d: SSL3[%d]: HandleRecord, received packet "
10926                      "from irrelevant epoch %d", SSL_GETPID(), ss->fd, epoch));
10927             /* Silently drop the packet */
10928             databuf->len = 0; /* Needed to ensure data not left around */
10929             return SECSuccess;
10930         }
10931
10932         dtls_seq_num = (((PRUint64)(cText->seq_num.high & 0xffff)) << 32) |
10933                         ((PRUint64)cText->seq_num.low);
10934
10935         if (dtls_RecordGetRecvd(&crSpec->recvdRecords, dtls_seq_num) != 0) {
10936             ssl_ReleaseSpecReadLock(ss);
10937             SSL_DBG(("%d: SSL3[%d]: HandleRecord, rejecting "
10938                      "potentially replayed packet", SSL_GETPID(), ss->fd));
10939             /* Silently drop the packet */
10940             databuf->len = 0; /* Needed to ensure data not left around */
10941             return SECSuccess;
10942         }
10943     }
10944
10945     good = ~0U;
10946     minLength = crSpec->mac_size;
10947     if (cipher_def->type == type_block) {
10948         /* CBC records have a padding length byte at the end. */
10949         minLength++;
10950         if (crSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
10951             /* With >= TLS 1.1, CBC records have an explicit IV. */
10952             minLength += cipher_def->iv_size;
10953         }
10954     } else if (cipher_def->type == type_aead) {
10955         minLength = cipher_def->explicit_nonce_size + cipher_def->tag_size;
10956     }
10957
10958     /* We can perform this test in variable time because the record's total
10959      * length and the ciphersuite are both public knowledge. */
10960     if (cText->buf->len < minLength) {
10961         goto decrypt_loser;
10962     }
10963
10964     if (cipher_def->type == type_block &&
10965         crSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
10966         /* Consume the per-record explicit IV. RFC 4346 Section 6.2.3.2 states
10967          * "The receiver decrypts the entire GenericBlockCipher structure and
10968          * then discards the first cipher block corresponding to the IV
10969          * component." Instead, we decrypt the first cipher block and then
10970          * discard it before decrypting the rest.
10971          */
10972         SSL3Opaque iv[MAX_IV_LENGTH];
10973         int decoded;
10974
10975         ivLen = cipher_def->iv_size;
10976         if (ivLen < 8 || ivLen > sizeof(iv)) {
10977             ssl_ReleaseSpecReadLock(ss);
10978             PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
10979             return SECFailure;
10980         }
10981
10982         PRINT_BUF(80, (ss, "IV (ciphertext):", cText->buf->buf, ivLen));
10983
10984         /* The decryption result is garbage, but since we just throw away
10985          * the block it doesn't matter.  The decryption of the next block
10986          * depends only on the ciphertext of the IV block.
10987          */
10988         rv = crSpec->decode(crSpec->decodeContext, iv, &decoded,
10989                             sizeof(iv), cText->buf->buf, ivLen);
10990
10991         good &= SECStatusToMask(rv);
10992     }
10993
10994     /* If we will be decompressing the buffer we need to decrypt somewhere
10995      * other than into databuf */
10996     if (crSpec->decompressor) {
10997         temp_buf.buf = NULL;
10998         temp_buf.space = 0;
10999         plaintext = &temp_buf;
11000     } else {
11001         plaintext = databuf;
11002     }
11003
11004     plaintext->len = 0; /* filled in by decode call below. */
11005     if (plaintext->space < MAX_FRAGMENT_LENGTH) {
11006         rv = sslBuffer_Grow(plaintext, MAX_FRAGMENT_LENGTH + 2048);
11007         if (rv != SECSuccess) {
11008             ssl_ReleaseSpecReadLock(ss);
11009             SSL_DBG(("%d: SSL3[%d]: HandleRecord, tried to get %d bytes",
11010                      SSL_GETPID(), ss->fd, MAX_FRAGMENT_LENGTH + 2048));
11011             /* sslBuffer_Grow has set a memory error code. */
11012             /* Perhaps we should send an alert. (but we have no memory!) */
11013             return SECFailure;
11014         }
11015     }
11016
11017     PRINT_BUF(80, (ss, "ciphertext:", cText->buf->buf + ivLen,
11018                                       cText->buf->len - ivLen));
11019
11020     isTLS = (PRBool)(crSpec->version > SSL_LIBRARY_VERSION_3_0);
11021
11022     if (isTLS && cText->buf->len - ivLen > (MAX_FRAGMENT_LENGTH + 2048)) {
11023         ssl_ReleaseSpecReadLock(ss);
11024         SSL3_SendAlert(ss, alert_fatal, record_overflow);
11025         PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
11026         return SECFailure;
11027     }
11028
11029     rType = cText->type;
11030     if (cipher_def->type == type_aead) {
11031         /* XXX For many AEAD ciphers, the plaintext is shorter than the
11032          * ciphertext by a fixed byte count, but it is not true in general.
11033          * Each AEAD cipher should provide a function that returns the
11034          * plaintext length for a given ciphertext. */
11035         unsigned int decryptedLen =
11036             cText->buf->len - cipher_def->explicit_nonce_size -
11037             cipher_def->tag_size;
11038         headerLen = ssl3_BuildRecordPseudoHeader(
11039             header, IS_DTLS(ss) ? cText->seq_num : crSpec->read_seq_num,
11040             rType, isTLS, cText->version, IS_DTLS(ss), decryptedLen);
11041         PORT_Assert(headerLen <= sizeof(header));
11042         rv = crSpec->aead(
11043                 ss->sec.isServer ? &crSpec->client : &crSpec->server,
11044                 PR_TRUE,                          /* do decrypt */
11045                 plaintext->buf,                   /* out */
11046                 (int*) &plaintext->len,           /* outlen */
11047                 plaintext->space,                 /* maxout */
11048                 cText->buf->buf,                  /* in */
11049                 cText->buf->len,                  /* inlen */
11050                 header, headerLen);
11051         if (rv != SECSuccess) {
11052             good = 0;
11053         }
11054     } else {
11055         if (cipher_def->type == type_block &&
11056             ((cText->buf->len - ivLen) % cipher_def->block_size) != 0) {
11057             goto decrypt_loser;
11058         }
11059
11060         /* decrypt from cText buf to plaintext. */
11061         rv = crSpec->decode(
11062             crSpec->decodeContext, plaintext->buf, (int *)&plaintext->len,
11063             plaintext->space, cText->buf->buf + ivLen, cText->buf->len - ivLen);
11064         if (rv != SECSuccess) {
11065             goto decrypt_loser;
11066         }
11067
11068         PRINT_BUF(80, (ss, "cleartext:", plaintext->buf, plaintext->len));
11069
11070         originalLen = plaintext->len;
11071
11072         /* If it's a block cipher, check and strip the padding. */
11073         if (cipher_def->type == type_block) {
11074             const unsigned int blockSize = cipher_def->block_size;
11075             const unsigned int macSize = crSpec->mac_size;
11076
11077             if (!isTLS) {
11078                 good &= SECStatusToMask(ssl_RemoveSSLv3CBCPadding(
11079                             plaintext, blockSize, macSize));
11080             } else {
11081                 good &= SECStatusToMask(ssl_RemoveTLSCBCPadding(
11082                             plaintext, macSize));
11083             }
11084         }
11085
11086         /* compute the MAC */
11087         headerLen = ssl3_BuildRecordPseudoHeader(
11088             header, IS_DTLS(ss) ? cText->seq_num : crSpec->read_seq_num,
11089             rType, isTLS, cText->version, IS_DTLS(ss),
11090             plaintext->len - crSpec->mac_size);
11091         PORT_Assert(headerLen <= sizeof(header));
11092         if (cipher_def->type == type_block) {
11093             rv = ssl3_ComputeRecordMACConstantTime(
11094                 crSpec, (PRBool)(!ss->sec.isServer), header, headerLen,
11095                 plaintext->buf, plaintext->len, originalLen,
11096                 hash, &hashBytes);
11097
11098             ssl_CBCExtractMAC(plaintext, originalLen, givenHashBuf,
11099                               crSpec->mac_size);
11100             givenHash = givenHashBuf;
11101
11102             /* plaintext->len will always have enough space to remove the MAC
11103              * because in ssl_Remove{SSLv3|TLS}CBCPadding we only adjust
11104              * plaintext->len if the result has enough space for the MAC and we
11105              * tested the unadjusted size against minLength, above. */
11106             plaintext->len -= crSpec->mac_size;
11107         } else {
11108             /* This is safe because we checked the minLength above. */
11109             plaintext->len -= crSpec->mac_size;
11110
11111             rv = ssl3_ComputeRecordMAC(
11112                 crSpec, (PRBool)(!ss->sec.isServer), header, headerLen,
11113                 plaintext->buf, plaintext->len, hash, &hashBytes);
11114
11115             /* We can read the MAC directly from the record because its location
11116              * is public when a stream cipher is used. */
11117             givenHash = plaintext->buf + plaintext->len;
11118         }
11119
11120         good &= SECStatusToMask(rv);
11121
11122         if (hashBytes != (unsigned)crSpec->mac_size ||
11123             NSS_SecureMemcmp(givenHash, hash, crSpec->mac_size) != 0) {
11124             /* We're allowed to leak whether or not the MAC check was correct */
11125             good = 0;
11126         }
11127     }
11128
11129     if (good == 0) {
11130 decrypt_loser:
11131         /* must not hold spec lock when calling SSL3_SendAlert. */
11132         ssl_ReleaseSpecReadLock(ss);
11133
11134         SSL_DBG(("%d: SSL3[%d]: decryption failed", SSL_GETPID(), ss->fd));
11135
11136         if (!IS_DTLS(ss)) {
11137             SSL3_SendAlert(ss, alert_fatal, bad_record_mac);
11138             /* always log mac error, in case attacker can read server logs. */
11139             PORT_SetError(SSL_ERROR_BAD_MAC_READ);
11140             return SECFailure;
11141         } else {
11142             /* Silently drop the packet */
11143             databuf->len = 0; /* Needed to ensure data not left around */
11144             return SECSuccess;
11145         }
11146     }
11147
11148     if (!IS_DTLS(ss)) {
11149         ssl3_BumpSequenceNumber(&crSpec->read_seq_num);
11150     } else {
11151         dtls_RecordSetRecvd(&crSpec->recvdRecords, dtls_seq_num);
11152     }
11153
11154     ssl_ReleaseSpecReadLock(ss); /*****************************************/
11155
11156     /*
11157      * The decrypted data is now in plaintext.
11158      */
11159
11160     /* possibly decompress the record. If we aren't using compression then
11161      * plaintext == databuf and so the uncompressed data is already in
11162      * databuf. */
11163     if (crSpec->decompressor) {
11164         if (databuf->space < plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION) {
11165             rv = sslBuffer_Grow(
11166                 databuf, plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION);
11167             if (rv != SECSuccess) {
11168                 SSL_DBG(("%d: SSL3[%d]: HandleRecord, tried to get %d bytes",
11169                          SSL_GETPID(), ss->fd,
11170                          plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION));
11171                 /* sslBuffer_Grow has set a memory error code. */
11172                 /* Perhaps we should send an alert. (but we have no memory!) */
11173                 PORT_Free(plaintext->buf);
11174                 return SECFailure;
11175             }
11176         }
11177
11178         rv = crSpec->decompressor(crSpec->decompressContext,
11179                                   databuf->buf,
11180                                   (int*) &databuf->len,
11181                                   databuf->space,
11182                                   plaintext->buf,
11183                                   plaintext->len);
11184
11185         if (rv != SECSuccess) {
11186             int err = ssl_MapLowLevelError(SSL_ERROR_DECOMPRESSION_FAILURE);
11187             SSL3_SendAlert(ss, alert_fatal,
11188                            isTLS ? decompression_failure : bad_record_mac);
11189
11190             /* There appears to be a bug with (at least) Apache + OpenSSL where
11191              * resumed SSLv3 connections don't actually use compression. See
11192              * comments 93-95 of
11193              * https://bugzilla.mozilla.org/show_bug.cgi?id=275744
11194              *
11195              * So, if we get a decompression error, and the record appears to
11196              * be already uncompressed, then we return a more specific error
11197              * code to hopefully save somebody some debugging time in the
11198              * future.
11199              */
11200             if (plaintext->len >= 4) {
11201                 unsigned int len = ((unsigned int) plaintext->buf[1] << 16) |
11202                                    ((unsigned int) plaintext->buf[2] << 8) |
11203                                    (unsigned int) plaintext->buf[3];
11204                 if (len == plaintext->len - 4) {
11205                     /* This appears to be uncompressed already */
11206                     err = SSL_ERROR_RX_UNEXPECTED_UNCOMPRESSED_RECORD;
11207                 }
11208             }
11209
11210             PORT_Free(plaintext->buf);
11211             PORT_SetError(err);
11212             return SECFailure;
11213         }
11214
11215         PORT_Free(plaintext->buf);
11216     }
11217
11218     /*
11219     ** Having completed the decompression, check the length again. 
11220     */
11221     if (isTLS && databuf->len > (MAX_FRAGMENT_LENGTH + 1024)) {
11222         SSL3_SendAlert(ss, alert_fatal, record_overflow);
11223         PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
11224         return SECFailure;
11225     }
11226
11227     /* Application data records are processed by the caller of this
11228     ** function, not by this function.
11229     */
11230     if (rType == content_application_data) {
11231         if (ss->firstHsDone)
11232             return SECSuccess;
11233         (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
11234         PORT_SetError(SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA);
11235         return SECFailure;
11236     }
11237
11238     /* It's a record that must be handled by ssl itself, not the application.
11239     */
11240 process_it:
11241     /* XXX  Get the xmit lock here.  Odds are very high that we'll be xmiting
11242      * data ang getting the xmit lock here prevents deadlocks.
11243      */
11244     ssl_GetSSL3HandshakeLock(ss);
11245
11246     /* All the functions called in this switch MUST set error code if
11247     ** they return SECFailure or SECWouldBlock.
11248     */
11249     switch (rType) {
11250     case content_change_cipher_spec:
11251         rv = ssl3_HandleChangeCipherSpecs(ss, databuf);
11252         break;
11253     case content_alert:
11254         rv = ssl3_HandleAlert(ss, databuf);
11255         break;
11256     case content_handshake:
11257         if (!IS_DTLS(ss)) {
11258             rv = ssl3_HandleHandshake(ss, databuf);
11259         } else {
11260             rv = dtls_HandleHandshake(ss, databuf);
11261         }
11262         break;
11263     /*
11264     case content_application_data is handled before this switch
11265     */
11266     default:
11267         SSL_DBG(("%d: SSL3[%d]: bogus content type=%d",
11268                  SSL_GETPID(), ss->fd, cText->type));
11269         /* XXX Send an alert ???  */
11270         PORT_SetError(SSL_ERROR_RX_UNKNOWN_RECORD_TYPE);
11271         rv = SECFailure;
11272         break;
11273     }
11274
11275     ssl_ReleaseSSL3HandshakeLock(ss);
11276     return rv;
11277
11278 }
11279
11280 /*
11281  * Initialization functions
11282  */
11283
11284 /* Called from ssl3_InitState, immediately below. */
11285 /* Caller must hold the SpecWriteLock. */
11286 static void
11287 ssl3_InitCipherSpec(sslSocket *ss, ssl3CipherSpec *spec)
11288 {
11289     spec->cipher_def               = &bulk_cipher_defs[cipher_null];
11290     PORT_Assert(spec->cipher_def->cipher == cipher_null);
11291     spec->mac_def                  = &mac_defs[mac_null];
11292     PORT_Assert(spec->mac_def->mac == mac_null);
11293     spec->encode                   = Null_Cipher;
11294     spec->decode                   = Null_Cipher;
11295     spec->destroy                  = NULL;
11296     spec->compressor               = NULL;
11297     spec->decompressor             = NULL;
11298     spec->destroyCompressContext   = NULL;
11299     spec->destroyDecompressContext = NULL;
11300     spec->mac_size                 = 0;
11301     spec->master_secret            = NULL;
11302     spec->bypassCiphers            = PR_FALSE;
11303
11304     spec->msItem.data              = NULL;
11305     spec->msItem.len               = 0;
11306
11307     spec->client.write_key         = NULL;
11308     spec->client.write_mac_key     = NULL;
11309     spec->client.write_mac_context = NULL;
11310
11311     spec->server.write_key         = NULL;
11312     spec->server.write_mac_key     = NULL;
11313     spec->server.write_mac_context = NULL;
11314
11315     spec->write_seq_num.high       = 0;
11316     spec->write_seq_num.low        = 0;
11317
11318     spec->read_seq_num.high        = 0;
11319     spec->read_seq_num.low         = 0;
11320
11321     spec->epoch                    = 0;
11322     dtls_InitRecvdRecords(&spec->recvdRecords);
11323
11324     spec->version                  = ss->vrange.max;
11325 }
11326
11327 /* Called from: ssl3_SendRecord
11328 **              ssl3_StartHandshakeHash() <- ssl2_BeginClientHandshake()
11329 **              ssl3_SendClientHello()
11330 **              ssl3_HandleV2ClientHello()
11331 **              ssl3_HandleRecord()
11332 **
11333 ** This function should perhaps acquire and release the SpecWriteLock.
11334 **
11335 **
11336 */
11337 static SECStatus
11338 ssl3_InitState(sslSocket *ss)
11339 {
11340     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
11341
11342     if (ss->ssl3.initialized)
11343         return SECSuccess;      /* Function should be idempotent */
11344
11345     ss->ssl3.policy = SSL_ALLOWED;
11346
11347     ssl_GetSpecWriteLock(ss);
11348     ss->ssl3.crSpec = ss->ssl3.cwSpec = &ss->ssl3.specs[0];
11349     ss->ssl3.prSpec = ss->ssl3.pwSpec = &ss->ssl3.specs[1];
11350     ss->ssl3.hs.sendingSCSV = PR_FALSE;
11351     ssl3_InitCipherSpec(ss, ss->ssl3.crSpec);
11352     ssl3_InitCipherSpec(ss, ss->ssl3.prSpec);
11353
11354     ss->ssl3.hs.ws = (ss->sec.isServer) ? wait_client_hello : wait_server_hello;
11355 #ifdef NSS_ENABLE_ECC
11356     ss->ssl3.hs.negotiatedECCurves = ssl3_GetSupportedECCurveMask(ss);
11357 #endif
11358     ssl_ReleaseSpecWriteLock(ss);
11359
11360     PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData));
11361
11362     if (IS_DTLS(ss)) {
11363         ss->ssl3.hs.sendMessageSeq = 0;
11364         ss->ssl3.hs.recvMessageSeq = 0;
11365         ss->ssl3.hs.rtTimeoutMs = INITIAL_DTLS_TIMEOUT_MS;
11366         ss->ssl3.hs.rtRetries = 0;
11367         ss->ssl3.hs.recvdHighWater = -1;
11368         PR_INIT_CLIST(&ss->ssl3.hs.lastMessageFlight);
11369         dtls_SetMTU(ss, 0); /* Set the MTU to the highest plateau */
11370     }
11371
11372     PORT_Assert(!ss->ssl3.hs.messages.buf && !ss->ssl3.hs.messages.space);
11373     ss->ssl3.hs.messages.buf = NULL;
11374     ss->ssl3.hs.messages.space = 0;
11375
11376     ss->ssl3.initialized = PR_TRUE;
11377     return SECSuccess;
11378 }
11379
11380 /* Returns a reference counted object that contains a key pair.
11381  * Or NULL on failure.  Initial ref count is 1.
11382  * Uses the keys in the pair as input.
11383  */
11384 ssl3KeyPair *
11385 ssl3_NewKeyPair( SECKEYPrivateKey * privKey, SECKEYPublicKey * pubKey)
11386 {
11387     ssl3KeyPair * pair;
11388
11389     if (!privKey || !pubKey) {
11390         PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
11391         return NULL;
11392     }
11393     pair = PORT_ZNew(ssl3KeyPair);
11394     if (!pair)
11395         return NULL;                    /* error code is set. */
11396     pair->refCount = 1;
11397     pair->privKey  = privKey;
11398     pair->pubKey   = pubKey;
11399     return pair;                        /* success */
11400 }
11401
11402 ssl3KeyPair *
11403 ssl3_GetKeyPairRef(ssl3KeyPair * keyPair)
11404 {
11405     PR_ATOMIC_INCREMENT(&keyPair->refCount);
11406     return keyPair;
11407 }
11408
11409 void
11410 ssl3_FreeKeyPair(ssl3KeyPair * keyPair)
11411 {
11412     PRInt32 newCount =  PR_ATOMIC_DECREMENT(&keyPair->refCount);
11413     if (!newCount) {
11414         if (keyPair->privKey)
11415             SECKEY_DestroyPrivateKey(keyPair->privKey);
11416         if (keyPair->pubKey)
11417             SECKEY_DestroyPublicKey( keyPair->pubKey);
11418         PORT_Free(keyPair);
11419     }
11420 }
11421
11422
11423
11424 /*
11425  * Creates the public and private RSA keys for SSL Step down.
11426  * Called from SSL_ConfigSecureServer in sslsecur.c
11427  */
11428 SECStatus
11429 ssl3_CreateRSAStepDownKeys(sslSocket *ss)
11430 {
11431     SECStatus             rv     = SECSuccess;
11432     SECKEYPrivateKey *    privKey;              /* RSA step down key */
11433     SECKEYPublicKey *     pubKey;               /* RSA step down key */
11434
11435     if (ss->stepDownKeyPair)
11436         ssl3_FreeKeyPair(ss->stepDownKeyPair);
11437     ss->stepDownKeyPair = NULL;
11438 #ifndef HACKED_EXPORT_SERVER
11439     /* Sigh, should have a get key strength call for private keys */
11440     if (PK11_GetPrivateModulusLen(ss->serverCerts[kt_rsa].SERVERKEY) >
11441                                                      EXPORT_RSA_KEY_LENGTH) {
11442         /* need to ask for the key size in bits */
11443         privKey = SECKEY_CreateRSAPrivateKey(EXPORT_RSA_KEY_LENGTH * BPB,
11444                                              &pubKey, NULL);
11445         if (!privKey || !pubKey ||
11446             !(ss->stepDownKeyPair = ssl3_NewKeyPair(privKey, pubKey))) {
11447             ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL);
11448             rv = SECFailure;
11449         }
11450     }
11451 #endif
11452     return rv;
11453 }
11454
11455
11456 /* record the export policy for this cipher suite */
11457 SECStatus
11458 ssl3_SetPolicy(ssl3CipherSuite which, int policy)
11459 {
11460     ssl3CipherSuiteCfg *suite;
11461
11462     suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
11463     if (suite == NULL) {
11464         return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
11465     }
11466     suite->policy = policy;
11467
11468     return SECSuccess;
11469 }
11470
11471 SECStatus
11472 ssl3_GetPolicy(ssl3CipherSuite which, PRInt32 *oPolicy)
11473 {
11474     ssl3CipherSuiteCfg *suite;
11475     PRInt32             policy;
11476     SECStatus           rv;
11477
11478     suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
11479     if (suite) {
11480         policy = suite->policy;
11481         rv     = SECSuccess;
11482     } else {
11483         policy = SSL_NOT_ALLOWED;
11484         rv     = SECFailure;    /* err code was set by Lookup. */
11485     }
11486     *oPolicy = policy;
11487     return rv;
11488 }
11489
11490 /* record the user preference for this suite */
11491 SECStatus
11492 ssl3_CipherPrefSetDefault(ssl3CipherSuite which, PRBool enabled)
11493 {
11494     ssl3CipherSuiteCfg *suite;
11495
11496     suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
11497     if (suite == NULL) {
11498         return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
11499     }
11500     suite->enabled = enabled;
11501     return SECSuccess;
11502 }
11503
11504 /* return the user preference for this suite */
11505 SECStatus
11506 ssl3_CipherPrefGetDefault(ssl3CipherSuite which, PRBool *enabled)
11507 {
11508     ssl3CipherSuiteCfg *suite;
11509     PRBool              pref;
11510     SECStatus           rv;
11511
11512     suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
11513     if (suite) {
11514         pref   = suite->enabled;
11515         rv     = SECSuccess;
11516     } else {
11517         pref   = SSL_NOT_ALLOWED;
11518         rv     = SECFailure;    /* err code was set by Lookup. */
11519     }
11520     *enabled = pref;
11521     return rv;
11522 }
11523
11524 SECStatus
11525 ssl3_CipherPrefSet(sslSocket *ss, ssl3CipherSuite which, PRBool enabled)
11526 {
11527     ssl3CipherSuiteCfg *suite;
11528
11529     suite = ssl_LookupCipherSuiteCfg(which, ss->cipherSuites);
11530     if (suite == NULL) {
11531         return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
11532     }
11533     suite->enabled = enabled;
11534     return SECSuccess;
11535 }
11536
11537 SECStatus
11538 ssl3_CipherPrefGet(sslSocket *ss, ssl3CipherSuite which, PRBool *enabled)
11539 {
11540     ssl3CipherSuiteCfg *suite;
11541     PRBool              pref;
11542     SECStatus           rv;
11543
11544     suite = ssl_LookupCipherSuiteCfg(which, ss->cipherSuites);
11545     if (suite) {
11546         pref   = suite->enabled;
11547         rv     = SECSuccess;
11548     } else {
11549         pref   = SSL_NOT_ALLOWED;
11550         rv     = SECFailure;    /* err code was set by Lookup. */
11551     }
11552     *enabled = pref;
11553     return rv;
11554 }
11555
11556 /* copy global default policy into socket. */
11557 void
11558 ssl3_InitSocketPolicy(sslSocket *ss)
11559 {
11560     PORT_Memcpy(ss->cipherSuites, cipherSuites, sizeof cipherSuites);
11561 }
11562
11563 /* ssl3_config_match_init must have already been called by
11564  * the caller of this function.
11565  */
11566 SECStatus
11567 ssl3_ConstructV2CipherSpecsHack(sslSocket *ss, unsigned char *cs, int *size)
11568 {
11569     int i, count = 0;
11570
11571     PORT_Assert(ss != 0);
11572     if (!ss) {
11573         PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
11574         return SECFailure;
11575     }
11576     if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
11577         *size = 0;
11578         return SECSuccess;
11579     }
11580     if (cs == NULL) {
11581         *size = count_cipher_suites(ss, SSL_ALLOWED, PR_TRUE);
11582         return SECSuccess;
11583     }
11584
11585     /* ssl3_config_match_init was called by the caller of this function. */
11586     for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
11587         ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i];
11588         if (config_match(suite, SSL_ALLOWED, PR_TRUE, &ss->vrange)) {
11589             if (cs != NULL) {
11590                 *cs++ = 0x00;
11591                 *cs++ = (suite->cipher_suite >> 8) & 0xFF;
11592                 *cs++ =  suite->cipher_suite       & 0xFF;
11593             }
11594             count++;
11595         }
11596     }
11597     *size = count;
11598     return SECSuccess;
11599 }
11600
11601 /*
11602 ** If ssl3 socket has completed the first handshake, and is in idle state, 
11603 ** then start a new handshake.
11604 ** If flushCache is true, the SID cache will be flushed first, forcing a
11605 ** "Full" handshake (not a session restart handshake), to be done.
11606 **
11607 ** called from SSL_RedoHandshake(), which already holds the handshake locks.
11608 */
11609 SECStatus
11610 ssl3_RedoHandshake(sslSocket *ss, PRBool flushCache)
11611 {
11612     sslSessionID *   sid = ss->sec.ci.sid;
11613     SECStatus        rv;
11614
11615     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
11616
11617     if (!ss->firstHsDone ||
11618         ((ss->version >= SSL_LIBRARY_VERSION_3_0) &&
11619          ss->ssl3.initialized && 
11620          (ss->ssl3.hs.ws != idle_handshake))) {
11621         PORT_SetError(SSL_ERROR_HANDSHAKE_NOT_COMPLETED);
11622         return SECFailure;
11623     }
11624
11625     if (IS_DTLS(ss)) {
11626         dtls_RehandshakeCleanup(ss);
11627     }
11628
11629     if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) {
11630         PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED);
11631         return SECFailure;
11632     }
11633     if (sid && flushCache) {
11634         if (ss->sec.uncache)
11635             ss->sec.uncache(sid); /* remove it from whichever cache it's in. */
11636         ssl_FreeSID(sid);       /* dec ref count and free if zero. */
11637         ss->sec.ci.sid = NULL;
11638     }
11639
11640     ssl_GetXmitBufLock(ss);     /**************************************/
11641
11642     /* start off a new handshake. */
11643     rv = (ss->sec.isServer) ? ssl3_SendHelloRequest(ss)
11644                             : ssl3_SendClientHello(ss, PR_FALSE);
11645
11646     ssl_ReleaseXmitBufLock(ss); /**************************************/
11647     return rv;
11648 }
11649
11650 /* Called from ssl_DestroySocketContents() in sslsock.c */
11651 void
11652 ssl3_DestroySSL3Info(sslSocket *ss)
11653 {
11654
11655     if (ss->ssl3.clientCertificate != NULL)
11656         CERT_DestroyCertificate(ss->ssl3.clientCertificate);
11657
11658     if (ss->ssl3.clientPrivateKey != NULL)
11659         SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
11660
11661     if (ss->ssl3.peerCertArena != NULL)
11662         ssl3_CleanupPeerCerts(ss);
11663
11664     if (ss->ssl3.clientCertChain != NULL) {
11665        CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
11666        ss->ssl3.clientCertChain = NULL;
11667     }
11668
11669     /* clean up handshake */
11670 #ifndef NO_PKCS11_BYPASS
11671     if (ss->opt.bypassPKCS11) {
11672         if (ss->ssl3.hs.hashType == handshake_hash_combo) {
11673             SHA1_DestroyContext((SHA1Context *)ss->ssl3.hs.sha_cx, PR_FALSE);
11674             MD5_DestroyContext((MD5Context *)ss->ssl3.hs.md5_cx, PR_FALSE);
11675         } else if (ss->ssl3.hs.hashType == handshake_hash_single) {
11676             ss->ssl3.hs.sha_obj->destroy(ss->ssl3.hs.sha_cx, PR_FALSE);
11677         }
11678     } 
11679 #endif
11680     if (ss->ssl3.hs.md5) {
11681         PK11_DestroyContext(ss->ssl3.hs.md5,PR_TRUE);
11682     }
11683     if (ss->ssl3.hs.sha) {
11684         PK11_DestroyContext(ss->ssl3.hs.sha,PR_TRUE);
11685     }
11686     if (ss->ssl3.hs.clientSigAndHash) {
11687         PORT_Free(ss->ssl3.hs.clientSigAndHash);
11688     }
11689     if (ss->ssl3.hs.messages.buf) {
11690         PORT_Free(ss->ssl3.hs.messages.buf);
11691         ss->ssl3.hs.messages.buf = NULL;
11692         ss->ssl3.hs.messages.len = 0;
11693         ss->ssl3.hs.messages.space = 0;
11694     }
11695
11696     /* free the SSL3Buffer (msg_body) */
11697     PORT_Free(ss->ssl3.hs.msg_body.buf);
11698
11699     /* free up the CipherSpecs */
11700     ssl3_DestroyCipherSpec(&ss->ssl3.specs[0], PR_TRUE/*freeSrvName*/);
11701     ssl3_DestroyCipherSpec(&ss->ssl3.specs[1], PR_TRUE/*freeSrvName*/);
11702
11703     /* Destroy the DTLS data */
11704     if (IS_DTLS(ss)) {
11705         dtls_FreeHandshakeMessages(&ss->ssl3.hs.lastMessageFlight);
11706         if (ss->ssl3.hs.recvdFragments.buf) {
11707             PORT_Free(ss->ssl3.hs.recvdFragments.buf);
11708         }
11709     }
11710
11711     ss->ssl3.initialized = PR_FALSE;
11712
11713     SECITEM_FreeItem(&ss->ssl3.nextProto, PR_FALSE);
11714 }
11715
11716 /* End of ssl3con.c */