Upstream version 8.37.180.0
[platform/framework/web/crosswalk.git] / src / net / third_party / nss / 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 /* This is a bodge to allow this code to be compiled against older NSS headers
35  * that don't contain the TLS 1.2 changes. */
36 #ifndef CKM_NSS_TLS_PRF_GENERAL_SHA256
37 #define CKM_NSS_TLS_PRF_GENERAL_SHA256          (CKM_NSS + 21)
38 #define CKM_NSS_TLS_MASTER_KEY_DERIVE_SHA256    (CKM_NSS + 22)
39 #define CKM_NSS_TLS_KEY_AND_MAC_DERIVE_SHA256   (CKM_NSS + 23)
40 #define CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256 (CKM_NSS + 24)
41 #endif
42
43 /* This is a bodge to allow this code to be compiled against older NSS
44  * headers. */
45 #ifndef CKM_NSS_CHACHA20_POLY1305
46 #define CKM_NSS_CHACHA20_POLY1305               (CKM_NSS + 26)
47
48 typedef struct CK_NSS_AEAD_PARAMS {
49     CK_BYTE_PTR  pIv;  /* This is the nonce. */
50     CK_ULONG     ulIvLen;
51     CK_BYTE_PTR  pAAD;
52     CK_ULONG     ulAADLen;
53     CK_ULONG     ulTagLen;
54 } CK_NSS_AEAD_PARAMS;
55
56 #endif
57
58 #include <stdio.h>
59 #ifdef NSS_ENABLE_ZLIB
60 #include "zlib.h"
61 #endif
62 #ifdef LINUX
63 #include <dlfcn.h>
64 #endif
65
66 #ifndef PK11_SETATTRS
67 #define PK11_SETATTRS(x,id,v,l) (x)->type = (id); \
68                 (x)->pValue=(v); (x)->ulValueLen = (l);
69 #endif
70
71 static SECStatus ssl3_AuthCertificate(sslSocket *ss);
72 static void      ssl3_CleanupPeerCerts(sslSocket *ss);
73 static void      ssl3_CopyPeerCertsFromSID(sslSocket *ss, sslSessionID *sid);
74 static PK11SymKey *ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec,
75                                        PK11SlotInfo * serverKeySlot);
76 static SECStatus ssl3_DeriveMasterSecret(sslSocket *ss, PK11SymKey *pms);
77 static SECStatus ssl3_DeriveConnectionKeysPKCS11(sslSocket *ss);
78 static SECStatus ssl3_HandshakeFailure(      sslSocket *ss);
79 static SECStatus ssl3_InitState(             sslSocket *ss);
80 static SECStatus ssl3_SendCertificate(       sslSocket *ss);
81 static SECStatus ssl3_SendCertificateStatus( sslSocket *ss);
82 static SECStatus ssl3_SendEmptyCertificate(  sslSocket *ss);
83 static SECStatus ssl3_SendCertificateRequest(sslSocket *ss);
84 static SECStatus ssl3_SendNextProto(         sslSocket *ss);
85 static SECStatus ssl3_SendEncryptedExtensions(sslSocket *ss);
86 static SECStatus ssl3_SendFinished(          sslSocket *ss, PRInt32 flags);
87 static SECStatus ssl3_SendServerHello(       sslSocket *ss);
88 static SECStatus ssl3_SendServerHelloDone(   sslSocket *ss);
89 static SECStatus ssl3_SendServerKeyExchange( sslSocket *ss);
90 static SECStatus ssl3_UpdateHandshakeHashes( sslSocket *ss,
91                                              const unsigned char *b,
92                                              unsigned int l);
93 static SECStatus ssl3_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags);
94 static int       ssl3_OIDToTLSHashAlgorithm(SECOidTag oid);
95
96 static SECStatus Null_Cipher(void *ctx, unsigned char *output, int *outputLen,
97                              int maxOutputLen, const unsigned char *input,
98                              int inputLen);
99 #ifndef NO_PKCS11_BYPASS
100 static SECStatus ssl3_AESGCMBypass(ssl3KeyMaterial *keys, PRBool doDecrypt,
101                                    unsigned char *out, int *outlen, int maxout,
102                                    const unsigned char *in, int inlen,
103                                    const unsigned char *additionalData,
104                                    int additionalDataLen);
105 #endif
106
107 #define MAX_SEND_BUF_LENGTH 32000 /* watch for 16-bit integer overflow */
108 #define MIN_SEND_BUF_LENGTH  4000
109
110 /* This list of SSL3 cipher suites is sorted in descending order of
111  * precedence (desirability).  It only includes cipher suites we implement.
112  * This table is modified by SSL3_SetPolicy(). The ordering of cipher suites
113  * in this table must match the ordering in SSL_ImplementedCiphers (sslenum.c)
114  *
115  * Important: See bug 946147 before enabling, reordering, or adding any cipher
116  * suites to this list.
117  */
118 static ssl3CipherSuiteCfg cipherSuites[ssl_V3_SUITES_IMPLEMENTED] = {
119    /*      cipher_suite                     policy       enabled   isPresent */
120
121 #ifdef NSS_ENABLE_ECC
122  { TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,  SSL_ALLOWED, PR_FALSE, PR_FALSE},
123  { TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,    SSL_ALLOWED, PR_FALSE, PR_FALSE},
124  { TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE},
125  { TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,   SSL_ALLOWED, PR_FALSE, PR_FALSE},
126    /* TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA is out of order to work around
127     * bug 946147.
128     */
129  { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,    SSL_ALLOWED, PR_FALSE, PR_FALSE},
130  { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,    SSL_ALLOWED, PR_FALSE, PR_FALSE},
131  { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,      SSL_ALLOWED, PR_FALSE, PR_FALSE},
132  { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE},
133  { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,   SSL_ALLOWED, PR_FALSE, PR_FALSE},
134  { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,      SSL_ALLOWED, PR_FALSE, PR_FALSE},
135  { TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA,   SSL_ALLOWED, PR_FALSE, PR_FALSE},
136  { TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,     SSL_ALLOWED, PR_FALSE, PR_FALSE},
137  { TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,        SSL_ALLOWED, PR_FALSE, PR_FALSE},
138  { TLS_ECDHE_RSA_WITH_RC4_128_SHA,          SSL_ALLOWED, PR_FALSE, PR_FALSE},
139 #endif /* NSS_ENABLE_ECC */
140
141  { TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,     SSL_ALLOWED, PR_TRUE,  PR_FALSE},
142  { TLS_DHE_RSA_WITH_AES_128_CBC_SHA,        SSL_ALLOWED, PR_TRUE,  PR_FALSE},
143  { TLS_DHE_DSS_WITH_AES_128_CBC_SHA,        SSL_ALLOWED, PR_TRUE,  PR_FALSE},
144  { TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,     SSL_ALLOWED, PR_TRUE,  PR_FALSE},
145  { TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA,   SSL_ALLOWED, PR_FALSE, PR_FALSE},
146  { TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA,   SSL_ALLOWED, PR_FALSE, PR_FALSE},
147  { TLS_DHE_RSA_WITH_AES_256_CBC_SHA,        SSL_ALLOWED, PR_TRUE,  PR_FALSE},
148  { TLS_DHE_DSS_WITH_AES_256_CBC_SHA,        SSL_ALLOWED, PR_TRUE,  PR_FALSE},
149  { TLS_DHE_RSA_WITH_AES_256_CBC_SHA256,     SSL_ALLOWED, PR_TRUE,  PR_FALSE},
150  { TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA,   SSL_ALLOWED, PR_FALSE, PR_FALSE},
151  { TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA,   SSL_ALLOWED, PR_FALSE, PR_FALSE},
152  { SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA,       SSL_ALLOWED, PR_TRUE,  PR_FALSE},
153  { SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA,       SSL_ALLOWED, PR_TRUE,  PR_FALSE},
154  { TLS_DHE_DSS_WITH_RC4_128_SHA,            SSL_ALLOWED, PR_FALSE, PR_FALSE},
155
156 #ifdef NSS_ENABLE_ECC
157  { TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,     SSL_ALLOWED, PR_FALSE, PR_FALSE},
158  { TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,       SSL_ALLOWED, PR_FALSE, PR_FALSE},
159  { TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA,     SSL_ALLOWED, PR_FALSE, PR_FALSE},
160  { TLS_ECDH_RSA_WITH_AES_256_CBC_SHA,       SSL_ALLOWED, PR_FALSE, PR_FALSE},
161  { TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA,    SSL_ALLOWED, PR_FALSE, PR_FALSE},
162  { TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA,      SSL_ALLOWED, PR_FALSE, PR_FALSE},
163  { TLS_ECDH_ECDSA_WITH_RC4_128_SHA,         SSL_ALLOWED, PR_FALSE, PR_FALSE},
164  { TLS_ECDH_RSA_WITH_RC4_128_SHA,           SSL_ALLOWED, PR_FALSE, PR_FALSE},
165 #endif /* NSS_ENABLE_ECC */
166
167  /* RSA */
168  { TLS_RSA_WITH_AES_128_GCM_SHA256,         SSL_ALLOWED, PR_TRUE,  PR_FALSE},
169  { TLS_RSA_WITH_AES_128_CBC_SHA,            SSL_ALLOWED, PR_TRUE,  PR_FALSE},
170  { TLS_RSA_WITH_AES_128_CBC_SHA256,         SSL_ALLOWED, PR_TRUE,  PR_FALSE},
171  { TLS_RSA_WITH_CAMELLIA_128_CBC_SHA,       SSL_ALLOWED, PR_FALSE, PR_FALSE},
172  { TLS_RSA_WITH_AES_256_CBC_SHA,            SSL_ALLOWED, PR_TRUE,  PR_FALSE},
173  { TLS_RSA_WITH_AES_256_CBC_SHA256,         SSL_ALLOWED, PR_TRUE,  PR_FALSE},
174  { TLS_RSA_WITH_CAMELLIA_256_CBC_SHA,       SSL_ALLOWED, PR_FALSE, PR_FALSE},
175  { TLS_RSA_WITH_SEED_CBC_SHA,               SSL_ALLOWED, PR_FALSE, PR_FALSE},
176  { SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA,      SSL_ALLOWED, PR_FALSE, PR_FALSE},
177  { SSL_RSA_WITH_3DES_EDE_CBC_SHA,           SSL_ALLOWED, PR_TRUE,  PR_FALSE},
178  { SSL_RSA_WITH_RC4_128_SHA,                SSL_ALLOWED, PR_TRUE,  PR_FALSE},
179  { SSL_RSA_WITH_RC4_128_MD5,                SSL_ALLOWED, PR_TRUE,  PR_FALSE},
180
181  /* 56-bit DES "domestic" cipher suites */
182  { SSL_DHE_RSA_WITH_DES_CBC_SHA,            SSL_ALLOWED, PR_FALSE, PR_FALSE},
183  { SSL_DHE_DSS_WITH_DES_CBC_SHA,            SSL_ALLOWED, PR_FALSE, PR_FALSE},
184  { SSL_RSA_FIPS_WITH_DES_CBC_SHA,           SSL_ALLOWED, PR_FALSE, PR_FALSE},
185  { SSL_RSA_WITH_DES_CBC_SHA,                SSL_ALLOWED, PR_FALSE, PR_FALSE},
186
187  /* export ciphersuites with 1024-bit public key exchange keys */
188  { TLS_RSA_EXPORT1024_WITH_RC4_56_SHA,      SSL_ALLOWED, PR_FALSE, PR_FALSE},
189  { TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA,     SSL_ALLOWED, PR_FALSE, PR_FALSE},
190
191  /* export ciphersuites with 512-bit public key exchange keys */
192  { SSL_RSA_EXPORT_WITH_RC4_40_MD5,          SSL_ALLOWED, PR_FALSE, PR_FALSE},
193  { SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5,      SSL_ALLOWED, PR_FALSE, PR_FALSE},
194
195  /* ciphersuites with no encryption */
196 #ifdef NSS_ENABLE_ECC
197  { TLS_ECDHE_ECDSA_WITH_NULL_SHA,           SSL_ALLOWED, PR_FALSE, PR_FALSE},
198  { TLS_ECDHE_RSA_WITH_NULL_SHA,             SSL_ALLOWED, PR_FALSE, PR_FALSE},
199  { TLS_ECDH_RSA_WITH_NULL_SHA,              SSL_ALLOWED, PR_FALSE, PR_FALSE},
200  { TLS_ECDH_ECDSA_WITH_NULL_SHA,            SSL_ALLOWED, PR_FALSE, PR_FALSE},
201 #endif /* NSS_ENABLE_ECC */
202  { SSL_RSA_WITH_NULL_SHA,                   SSL_ALLOWED, PR_FALSE, PR_FALSE},
203  { TLS_RSA_WITH_NULL_SHA256,                SSL_ALLOWED, PR_FALSE, PR_FALSE},
204  { SSL_RSA_WITH_NULL_MD5,                   SSL_ALLOWED, PR_FALSE, PR_FALSE},
205 };
206
207 /* Verify that SSL_ImplementedCiphers and cipherSuites are in consistent order.
208  */
209 #ifdef DEBUG
210 void ssl3_CheckCipherSuiteOrderConsistency()
211 {
212     unsigned int i;
213
214     /* Note that SSL_ImplementedCiphers has more elements than cipherSuites
215      * because it SSL_ImplementedCiphers includes SSL 2.0 cipher suites.
216      */
217     PORT_Assert(SSL_NumImplementedCiphers >= PR_ARRAY_SIZE(cipherSuites));
218
219     for (i = 0; i < PR_ARRAY_SIZE(cipherSuites); ++i) {
220         PORT_Assert(SSL_ImplementedCiphers[i] == cipherSuites[i].cipher_suite);
221     }
222 }
223 #endif
224
225 /* This list of SSL3 compression methods is sorted in descending order of
226  * precedence (desirability).  It only includes compression methods we
227  * implement.
228  */
229 static const /*SSLCompressionMethod*/ PRUint8 compressions [] = {
230 #ifdef NSS_ENABLE_ZLIB
231     ssl_compression_deflate,
232 #endif
233     ssl_compression_null
234 };
235
236 static const int compressionMethodsCount =
237     sizeof(compressions) / sizeof(compressions[0]);
238
239 /* compressionEnabled returns true iff the compression algorithm is enabled
240  * for the given SSL socket. */
241 static PRBool
242 compressionEnabled(sslSocket *ss, SSLCompressionMethod compression)
243 {
244     switch (compression) {
245     case ssl_compression_null:
246         return PR_TRUE;  /* Always enabled */
247 #ifdef NSS_ENABLE_ZLIB
248     case ssl_compression_deflate:
249         return ss->opt.enableDeflate;
250 #endif
251     default:
252         return PR_FALSE;
253     }
254 }
255
256 static const /*SSL3ClientCertificateType */ PRUint8 certificate_types [] = {
257     ct_RSA_sign,
258 #ifdef NSS_ENABLE_ECC
259     ct_ECDSA_sign,
260 #endif /* NSS_ENABLE_ECC */
261     ct_DSS_sign,
262 };
263
264 /* This block is the contents of the supported_signature_algorithms field of
265  * our TLS 1.2 CertificateRequest message, in wire format. See
266  * https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1
267  *
268  * This block contains only sha256 entries because we only support TLS 1.2
269  * CertificateVerify messages that use the handshake hash. */
270 static const PRUint8 supported_signature_algorithms[] = {
271     tls_hash_sha256, tls_sig_rsa,
272 #ifdef NSS_ENABLE_ECC
273     tls_hash_sha256, tls_sig_ecdsa,
274 #endif
275     tls_hash_sha256, tls_sig_dsa,
276 };
277
278 #define EXPORT_RSA_KEY_LENGTH 64        /* bytes */
279
280
281 /* This global item is used only in servers.  It is is initialized by
282 ** SSL_ConfigSecureServer(), and is used in ssl3_SendCertificateRequest().
283 */
284 CERTDistNames *ssl3_server_ca_list = NULL;
285 static SSL3Statistics ssl3stats;
286
287 /* indexed by SSL3BulkCipher */
288 static const ssl3BulkCipherDef bulk_cipher_defs[] = {
289     /*                                       |--------- Lengths --------| */
290     /* cipher             calg               k  s  type         i  b  t  n */
291     /*                                       e  e               v  l  a  o */
292     /*                                       y  c               |  o  g  n */
293     /*                                       |  r               |  c  |  c */
294     /*                                       |  e               |  k  |  e */
295     /*                                       |  t               |  |  |  | */
296     {cipher_null,         calg_null,         0, 0, type_stream, 0, 0, 0, 0},
297     {cipher_rc4,          calg_rc4,         16,16, type_stream, 0, 0, 0, 0},
298     {cipher_rc4_40,       calg_rc4,         16, 5, type_stream, 0, 0, 0, 0},
299     {cipher_rc4_56,       calg_rc4,         16, 7, type_stream, 0, 0, 0, 0},
300     {cipher_rc2,          calg_rc2,         16,16, type_block,  8, 8, 0, 0},
301     {cipher_rc2_40,       calg_rc2,         16, 5, type_block,  8, 8, 0, 0},
302     {cipher_des,          calg_des,          8, 8, type_block,  8, 8, 0, 0},
303     {cipher_3des,         calg_3des,        24,24, type_block,  8, 8, 0, 0},
304     {cipher_des40,        calg_des,          8, 5, type_block,  8, 8, 0, 0},
305     {cipher_idea,         calg_idea,        16,16, type_block,  8, 8, 0, 0},
306     {cipher_aes_128,      calg_aes,         16,16, type_block, 16,16, 0, 0},
307     {cipher_aes_256,      calg_aes,         32,32, type_block, 16,16, 0, 0},
308     {cipher_camellia_128, calg_camellia,    16,16, type_block, 16,16, 0, 0},
309     {cipher_camellia_256, calg_camellia,    32,32, type_block, 16,16, 0, 0},
310     {cipher_seed,         calg_seed,        16,16, type_block, 16,16, 0, 0},
311     {cipher_aes_128_gcm,  calg_aes_gcm,     16,16, type_aead,   4, 0,16, 8},
312     {cipher_chacha20,     calg_chacha20,    32,32, type_aead,   0, 0,16, 0},
313     {cipher_missing,      calg_null,         0, 0, type_stream, 0, 0, 0, 0},
314 };
315
316 static const ssl3KEADef kea_defs[] = 
317 { /* indexed by SSL3KeyExchangeAlgorithm */
318     /* kea              exchKeyType signKeyType is_limited limit  tls_keygen */
319     {kea_null,           kt_null,     sign_null, PR_FALSE,   0, PR_FALSE},
320     {kea_rsa,            kt_rsa,      sign_rsa,  PR_FALSE,   0, PR_FALSE},
321     {kea_rsa_export,     kt_rsa,      sign_rsa,  PR_TRUE,  512, PR_FALSE},
322     {kea_rsa_export_1024,kt_rsa,      sign_rsa,  PR_TRUE, 1024, PR_FALSE},
323     {kea_dh_dss,         kt_dh,       sign_dsa,  PR_FALSE,   0, PR_FALSE},
324     {kea_dh_dss_export,  kt_dh,       sign_dsa,  PR_TRUE,  512, PR_FALSE},
325     {kea_dh_rsa,         kt_dh,       sign_rsa,  PR_FALSE,   0, PR_FALSE},
326     {kea_dh_rsa_export,  kt_dh,       sign_rsa,  PR_TRUE,  512, PR_FALSE},
327     {kea_dhe_dss,        kt_dh,       sign_dsa,  PR_FALSE,   0, PR_FALSE},
328     {kea_dhe_dss_export, kt_dh,       sign_dsa,  PR_TRUE,  512, PR_FALSE},
329     {kea_dhe_rsa,        kt_dh,       sign_rsa,  PR_FALSE,   0, PR_FALSE},
330     {kea_dhe_rsa_export, kt_dh,       sign_rsa,  PR_TRUE,  512, PR_FALSE},
331     {kea_dh_anon,        kt_dh,       sign_null, PR_FALSE,   0, PR_FALSE},
332     {kea_dh_anon_export, kt_dh,       sign_null, PR_TRUE,  512, PR_FALSE},
333     {kea_rsa_fips,       kt_rsa,      sign_rsa,  PR_FALSE,   0, PR_TRUE },
334 #ifdef NSS_ENABLE_ECC
335     {kea_ecdh_ecdsa,     kt_ecdh,     sign_ecdsa,  PR_FALSE, 0, PR_FALSE},
336     {kea_ecdhe_ecdsa,    kt_ecdh,     sign_ecdsa,  PR_FALSE,   0, PR_FALSE},
337     {kea_ecdh_rsa,       kt_ecdh,     sign_rsa,  PR_FALSE,   0, PR_FALSE},
338     {kea_ecdhe_rsa,      kt_ecdh,     sign_rsa,  PR_FALSE,   0, PR_FALSE},
339     {kea_ecdh_anon,      kt_ecdh,     sign_null,  PR_FALSE,   0, PR_FALSE},
340 #endif /* NSS_ENABLE_ECC */
341 };
342
343 /* must use ssl_LookupCipherSuiteDef to access */
344 static const ssl3CipherSuiteDef cipher_suite_defs[] = 
345 {
346 /*  cipher_suite                    bulk_cipher_alg mac_alg key_exchange_alg */
347
348     {SSL_NULL_WITH_NULL_NULL,       cipher_null,   mac_null, kea_null},
349     {SSL_RSA_WITH_NULL_MD5,         cipher_null,   mac_md5, kea_rsa},
350     {SSL_RSA_WITH_NULL_SHA,         cipher_null,   mac_sha, kea_rsa},
351     {TLS_RSA_WITH_NULL_SHA256,      cipher_null,   hmac_sha256, kea_rsa},
352     {SSL_RSA_EXPORT_WITH_RC4_40_MD5,cipher_rc4_40, mac_md5, kea_rsa_export},
353     {SSL_RSA_WITH_RC4_128_MD5,      cipher_rc4,    mac_md5, kea_rsa},
354     {SSL_RSA_WITH_RC4_128_SHA,      cipher_rc4,    mac_sha, kea_rsa},
355     {SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5,
356                                     cipher_rc2_40, mac_md5, kea_rsa_export},
357 #if 0 /* not implemented */
358     {SSL_RSA_WITH_IDEA_CBC_SHA,     cipher_idea,   mac_sha, kea_rsa},
359     {SSL_RSA_EXPORT_WITH_DES40_CBC_SHA,
360                                     cipher_des40,  mac_sha, kea_rsa_export},
361 #endif
362     {SSL_RSA_WITH_DES_CBC_SHA,      cipher_des,    mac_sha, kea_rsa},
363     {SSL_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des,   mac_sha, kea_rsa},
364     {SSL_DHE_DSS_WITH_DES_CBC_SHA,  cipher_des,    mac_sha, kea_dhe_dss},
365     {SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA,
366                                     cipher_3des,   mac_sha, kea_dhe_dss},
367     {TLS_DHE_DSS_WITH_RC4_128_SHA,  cipher_rc4,    mac_sha, kea_dhe_dss},
368 #if 0 /* not implemented */
369     {SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA,
370                                     cipher_des40,  mac_sha, kea_dh_dss_export},
371     {SSL_DH_DSS_DES_CBC_SHA,        cipher_des,    mac_sha, kea_dh_dss},
372     {SSL_DH_DSS_3DES_CBC_SHA,       cipher_3des,   mac_sha, kea_dh_dss},
373     {SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA,
374                                     cipher_des40,  mac_sha, kea_dh_rsa_export},
375     {SSL_DH_RSA_DES_CBC_SHA,        cipher_des,    mac_sha, kea_dh_rsa},
376     {SSL_DH_RSA_3DES_CBC_SHA,       cipher_3des,   mac_sha, kea_dh_rsa},
377     {SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA,
378                                     cipher_des40,  mac_sha, kea_dh_dss_export},
379     {SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA,
380                                     cipher_des40,  mac_sha, kea_dh_rsa_export},
381 #endif
382     {SSL_DHE_RSA_WITH_DES_CBC_SHA,  cipher_des,    mac_sha, kea_dhe_rsa},
383     {SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA,
384                                     cipher_3des,   mac_sha, kea_dhe_rsa},
385 #if 0
386     {SSL_DH_ANON_EXPORT_RC4_40_MD5, cipher_rc4_40, mac_md5, kea_dh_anon_export},
387     {SSL_DH_ANON_EXPORT_WITH_DES40_CBC_SHA,
388                                     cipher_des40,  mac_sha, kea_dh_anon_export},
389     {SSL_DH_ANON_DES_CBC_SHA,       cipher_des,    mac_sha, kea_dh_anon},
390     {SSL_DH_ANON_3DES_CBC_SHA,      cipher_3des,   mac_sha, kea_dh_anon},
391 #endif
392
393
394 /* New TLS cipher suites */
395     {TLS_RSA_WITH_AES_128_CBC_SHA,      cipher_aes_128, mac_sha, kea_rsa},
396     {TLS_RSA_WITH_AES_128_CBC_SHA256,   cipher_aes_128, hmac_sha256, kea_rsa},
397     {TLS_DHE_DSS_WITH_AES_128_CBC_SHA,  cipher_aes_128, mac_sha, kea_dhe_dss},
398     {TLS_DHE_RSA_WITH_AES_128_CBC_SHA,  cipher_aes_128, mac_sha, kea_dhe_rsa},
399     {TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_dhe_rsa},
400     {TLS_RSA_WITH_AES_256_CBC_SHA,      cipher_aes_256, mac_sha, kea_rsa},
401     {TLS_RSA_WITH_AES_256_CBC_SHA256,   cipher_aes_256, hmac_sha256, kea_rsa},
402     {TLS_DHE_DSS_WITH_AES_256_CBC_SHA,  cipher_aes_256, mac_sha, kea_dhe_dss},
403     {TLS_DHE_RSA_WITH_AES_256_CBC_SHA,  cipher_aes_256, mac_sha, kea_dhe_rsa},
404     {TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, cipher_aes_256, hmac_sha256, kea_dhe_rsa},
405 #if 0
406     {TLS_DH_DSS_WITH_AES_128_CBC_SHA,   cipher_aes_128, mac_sha, kea_dh_dss},
407     {TLS_DH_RSA_WITH_AES_128_CBC_SHA,   cipher_aes_128, mac_sha, kea_dh_rsa},
408     {TLS_DH_ANON_WITH_AES_128_CBC_SHA,  cipher_aes_128, mac_sha, kea_dh_anon},
409     {TLS_DH_DSS_WITH_AES_256_CBC_SHA,   cipher_aes_256, mac_sha, kea_dh_dss},
410     {TLS_DH_RSA_WITH_AES_256_CBC_SHA,   cipher_aes_256, mac_sha, kea_dh_rsa},
411     {TLS_DH_ANON_WITH_AES_256_CBC_SHA,  cipher_aes_256, mac_sha, kea_dh_anon},
412 #endif
413
414     {TLS_RSA_WITH_SEED_CBC_SHA,     cipher_seed,   mac_sha, kea_rsa},
415
416     {TLS_RSA_WITH_CAMELLIA_128_CBC_SHA, cipher_camellia_128, mac_sha, kea_rsa},
417     {TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA,
418      cipher_camellia_128, mac_sha, kea_dhe_dss},
419     {TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA,
420      cipher_camellia_128, mac_sha, kea_dhe_rsa},
421     {TLS_RSA_WITH_CAMELLIA_256_CBC_SHA, cipher_camellia_256, mac_sha, kea_rsa},
422     {TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA,
423      cipher_camellia_256, mac_sha, kea_dhe_dss},
424     {TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA,
425      cipher_camellia_256, mac_sha, kea_dhe_rsa},
426
427     {TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA,
428                                     cipher_des,    mac_sha,kea_rsa_export_1024},
429     {TLS_RSA_EXPORT1024_WITH_RC4_56_SHA,
430                                     cipher_rc4_56, mac_sha,kea_rsa_export_1024},
431
432     {SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_rsa_fips},
433     {SSL_RSA_FIPS_WITH_DES_CBC_SHA, cipher_des,    mac_sha, kea_rsa_fips},
434
435     {TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_dhe_rsa},
436     {TLS_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_rsa},
437     {TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_ecdhe_rsa},
438     {TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_ecdhe_ecdsa},
439     {TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, cipher_chacha20, mac_aead, kea_ecdhe_rsa},
440     {TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, cipher_chacha20, mac_aead, kea_ecdhe_ecdsa},
441
442 #ifdef NSS_ENABLE_ECC
443     {TLS_ECDH_ECDSA_WITH_NULL_SHA,        cipher_null, mac_sha, kea_ecdh_ecdsa},
444     {TLS_ECDH_ECDSA_WITH_RC4_128_SHA,      cipher_rc4, mac_sha, kea_ecdh_ecdsa},
445     {TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdh_ecdsa},
446     {TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdh_ecdsa},
447     {TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdh_ecdsa},
448
449     {TLS_ECDHE_ECDSA_WITH_NULL_SHA,        cipher_null, mac_sha, kea_ecdhe_ecdsa},
450     {TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,      cipher_rc4, mac_sha, kea_ecdhe_ecdsa},
451     {TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdhe_ecdsa},
452     {TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdhe_ecdsa},
453     {TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_ecdhe_ecdsa},
454     {TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdhe_ecdsa},
455
456     {TLS_ECDH_RSA_WITH_NULL_SHA,         cipher_null,    mac_sha, kea_ecdh_rsa},
457     {TLS_ECDH_RSA_WITH_RC4_128_SHA,      cipher_rc4,     mac_sha, kea_ecdh_rsa},
458     {TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des,    mac_sha, kea_ecdh_rsa},
459     {TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,  cipher_aes_128, mac_sha, kea_ecdh_rsa},
460     {TLS_ECDH_RSA_WITH_AES_256_CBC_SHA,  cipher_aes_256, mac_sha, kea_ecdh_rsa},
461
462     {TLS_ECDHE_RSA_WITH_NULL_SHA,         cipher_null,    mac_sha, kea_ecdhe_rsa},
463     {TLS_ECDHE_RSA_WITH_RC4_128_SHA,      cipher_rc4,     mac_sha, kea_ecdhe_rsa},
464     {TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des,    mac_sha, kea_ecdhe_rsa},
465     {TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,  cipher_aes_128, mac_sha, kea_ecdhe_rsa},
466     {TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_ecdhe_rsa},
467     {TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,  cipher_aes_256, mac_sha, kea_ecdhe_rsa},
468
469 #if 0
470     {TLS_ECDH_anon_WITH_NULL_SHA,         cipher_null,    mac_sha, kea_ecdh_anon},
471     {TLS_ECDH_anon_WITH_RC4_128_SHA,      cipher_rc4,     mac_sha, kea_ecdh_anon},
472     {TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA, cipher_3des,    mac_sha, kea_ecdh_anon},
473     {TLS_ECDH_anon_WITH_AES_128_CBC_SHA,  cipher_aes_128, mac_sha, kea_ecdh_anon},
474     {TLS_ECDH_anon_WITH_AES_256_CBC_SHA,  cipher_aes_256, mac_sha, kea_ecdh_anon},
475 #endif
476 #endif /* NSS_ENABLE_ECC */
477 };
478
479 static const CK_MECHANISM_TYPE kea_alg_defs[] = {
480     0x80000000L,
481     CKM_RSA_PKCS,
482     CKM_DH_PKCS_DERIVE,
483     CKM_KEA_KEY_DERIVE,
484     CKM_ECDH1_DERIVE
485 };
486
487 typedef struct SSLCipher2MechStr {
488     SSLCipherAlgorithm  calg;
489     CK_MECHANISM_TYPE   cmech;
490 } SSLCipher2Mech;
491
492 /* indexed by type SSLCipherAlgorithm */
493 static const SSLCipher2Mech alg2Mech[] = {
494     /* calg,          cmech  */
495     { calg_null     , (CK_MECHANISM_TYPE)0x80000000L    },
496     { calg_rc4      , CKM_RC4                           },
497     { calg_rc2      , CKM_RC2_CBC                       },
498     { calg_des      , CKM_DES_CBC                       },
499     { calg_3des     , CKM_DES3_CBC                      },
500     { calg_idea     , CKM_IDEA_CBC                      },
501     { calg_fortezza , CKM_SKIPJACK_CBC64                },
502     { calg_aes      , CKM_AES_CBC                       },
503     { calg_camellia , CKM_CAMELLIA_CBC                  },
504     { calg_seed     , CKM_SEED_CBC                      },
505     { calg_aes_gcm  , CKM_AES_GCM                       },
506     { calg_chacha20 , CKM_NSS_CHACHA20_POLY1305         },
507 /*  { calg_init     , (CK_MECHANISM_TYPE)0x7fffffffL    }  */
508 };
509
510 #define mmech_invalid  (CK_MECHANISM_TYPE)0x80000000L
511 #define mmech_md5      CKM_SSL3_MD5_MAC
512 #define mmech_sha      CKM_SSL3_SHA1_MAC
513 #define mmech_md5_hmac CKM_MD5_HMAC
514 #define mmech_sha_hmac CKM_SHA_1_HMAC
515 #define mmech_sha256_hmac CKM_SHA256_HMAC
516
517 static const ssl3MACDef mac_defs[] = { /* indexed by SSL3MACAlgorithm */
518     /* pad_size is only used for SSL 3.0 MAC. See RFC 6101 Sec. 5.2.3.1. */
519     /* mac      mmech       pad_size  mac_size                       */
520     { mac_null, mmech_invalid,    0,  0          },
521     { mac_md5,  mmech_md5,       48,  MD5_LENGTH },
522     { mac_sha,  mmech_sha,       40,  SHA1_LENGTH},
523     {hmac_md5,  mmech_md5_hmac,   0,  MD5_LENGTH },
524     {hmac_sha,  mmech_sha_hmac,   0,  SHA1_LENGTH},
525     {hmac_sha256, mmech_sha256_hmac, 0, SHA256_LENGTH},
526     { mac_aead, mmech_invalid,    0,  0          },
527 };
528
529 /* indexed by SSL3BulkCipher */
530 const char * const ssl3_cipherName[] = {
531     "NULL",
532     "RC4",
533     "RC4-40",
534     "RC4-56",
535     "RC2-CBC",
536     "RC2-CBC-40",
537     "DES-CBC",
538     "3DES-EDE-CBC",
539     "DES-CBC-40",
540     "IDEA-CBC",
541     "AES-128",
542     "AES-256",
543     "Camellia-128",
544     "Camellia-256",
545     "SEED-CBC",
546     "AES-128-GCM",
547     "missing"
548 };
549
550 #ifdef NSS_ENABLE_ECC
551 /* The ECCWrappedKeyInfo structure defines how various pieces of 
552  * information are laid out within wrappedSymmetricWrappingkey 
553  * for ECDH key exchange. Since wrappedSymmetricWrappingkey is 
554  * a 512-byte buffer (see sslimpl.h), the variable length field 
555  * in ECCWrappedKeyInfo can be at most (512 - 8) = 504 bytes.
556  *
557  * XXX For now, NSS only supports named elliptic curves of size 571 bits 
558  * or smaller. The public value will fit within 145 bytes and EC params
559  * will fit within 12 bytes. We'll need to revisit this when NSS
560  * supports arbitrary curves.
561  */
562 #define MAX_EC_WRAPPED_KEY_BUFLEN  504
563
564 typedef struct ECCWrappedKeyInfoStr {
565     PRUint16 size;            /* EC public key size in bits */
566     PRUint16 encodedParamLen; /* length (in bytes) of DER encoded EC params */
567     PRUint16 pubValueLen;     /* length (in bytes) of EC public value */
568     PRUint16 wrappedKeyLen;   /* length (in bytes) of the wrapped key */
569     PRUint8 var[MAX_EC_WRAPPED_KEY_BUFLEN]; /* this buffer contains the */
570     /* EC public-key params, the EC public value and the wrapped key  */
571 } ECCWrappedKeyInfo;
572 #endif /* NSS_ENABLE_ECC */
573
574 #if defined(TRACE)
575
576 static char *
577 ssl3_DecodeHandshakeType(int msgType)
578 {
579     char * rv;
580     static char line[40];
581
582     switch(msgType) {
583     case hello_request:         rv = "hello_request (0)";               break;
584     case client_hello:          rv = "client_hello  (1)";               break;
585     case server_hello:          rv = "server_hello  (2)";               break;
586     case hello_verify_request:  rv = "hello_verify_request (3)";        break;
587     case certificate:           rv = "certificate  (11)";               break;
588     case server_key_exchange:   rv = "server_key_exchange (12)";        break;
589     case certificate_request:   rv = "certificate_request (13)";        break;
590     case server_hello_done:     rv = "server_hello_done   (14)";        break;
591     case certificate_verify:    rv = "certificate_verify  (15)";        break;
592     case client_key_exchange:   rv = "client_key_exchange (16)";        break;
593     case finished:              rv = "finished     (20)";               break;
594     default:
595         sprintf(line, "*UNKNOWN* handshake type! (%d)", msgType);
596         rv = line;
597     }
598     return rv;
599 }
600
601 static char *
602 ssl3_DecodeContentType(int msgType)
603 {
604     char * rv;
605     static char line[40];
606
607     switch(msgType) {
608     case content_change_cipher_spec:
609                                 rv = "change_cipher_spec (20)";         break;
610     case content_alert:         rv = "alert      (21)";                 break;
611     case content_handshake:     rv = "handshake  (22)";                 break;
612     case content_application_data:
613                                 rv = "application_data (23)";           break;
614     default:
615         sprintf(line, "*UNKNOWN* record type! (%d)", msgType);
616         rv = line;
617     }
618     return rv;
619 }
620
621 #endif
622
623 SSL3Statistics * 
624 SSL_GetStatistics(void)
625 {
626     return &ssl3stats;
627 }
628
629 typedef struct tooLongStr {
630 #if defined(IS_LITTLE_ENDIAN)
631     PRInt32 low;
632     PRInt32 high;
633 #else
634     PRInt32 high;
635     PRInt32 low;
636 #endif
637 } tooLong;
638
639 void SSL_AtomicIncrementLong(long * x)
640 {
641     if ((sizeof *x) == sizeof(PRInt32)) {
642         PR_ATOMIC_INCREMENT((PRInt32 *)x);
643     } else {
644         tooLong * tl = (tooLong *)x;
645         if (PR_ATOMIC_INCREMENT(&tl->low) == 0)
646             PR_ATOMIC_INCREMENT(&tl->high);
647     }
648 }
649
650 static PRBool
651 ssl3_CipherSuiteAllowedForVersionRange(
652     ssl3CipherSuite cipherSuite,
653     const SSLVersionRange *vrange)
654 {
655     switch (cipherSuite) {
656     /* See RFC 4346 A.5. Export cipher suites must not be used in TLS 1.1 or
657      * later. This set of cipher suites is similar to, but different from, the
658      * set of cipher suites considered exportable by SSL_IsExportCipherSuite.
659      */
660     case SSL_RSA_EXPORT_WITH_RC4_40_MD5:
661     case SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5:
662     /*   SSL_RSA_EXPORT_WITH_DES40_CBC_SHA:      never implemented
663      *   SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA:   never implemented
664      *   SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA:   never implemented
665      *   SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA:  never implemented
666      *   SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA:  never implemented
667      *   SSL_DH_ANON_EXPORT_WITH_RC4_40_MD5:     never implemented
668      *   SSL_DH_ANON_EXPORT_WITH_DES40_CBC_SHA:  never implemented
669      */
670         return vrange->min <= SSL_LIBRARY_VERSION_TLS_1_0;
671     case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305:
672     case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305:
673     case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256:
674     case TLS_RSA_WITH_AES_256_CBC_SHA256:
675     case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
676     case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
677     case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
678     case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
679     case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256:
680     case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
681     case TLS_RSA_WITH_AES_128_CBC_SHA256:
682     case TLS_RSA_WITH_AES_128_GCM_SHA256:
683     case TLS_RSA_WITH_NULL_SHA256:
684         return vrange->max >= SSL_LIBRARY_VERSION_TLS_1_2;
685     default:
686         return PR_TRUE;
687     }
688 }
689
690 /* return pointer to ssl3CipherSuiteDef for suite, or NULL */
691 /* XXX This does a linear search.  A binary search would be better. */
692 static const ssl3CipherSuiteDef *
693 ssl_LookupCipherSuiteDef(ssl3CipherSuite suite)
694 {
695     int cipher_suite_def_len =
696         sizeof(cipher_suite_defs) / sizeof(cipher_suite_defs[0]);
697     int i;
698
699     for (i = 0; i < cipher_suite_def_len; i++) {
700         if (cipher_suite_defs[i].cipher_suite == suite)
701             return &cipher_suite_defs[i];
702     }
703     PORT_Assert(PR_FALSE);  /* We should never get here. */
704     PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE);
705     return NULL;
706 }
707
708 /* Find the cipher configuration struct associate with suite */
709 /* XXX This does a linear search.  A binary search would be better. */
710 static ssl3CipherSuiteCfg *
711 ssl_LookupCipherSuiteCfg(ssl3CipherSuite suite, ssl3CipherSuiteCfg *suites)
712 {
713     int i;
714
715     for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
716         if (suites[i].cipher_suite == suite)
717             return &suites[i];
718     }
719     /* return NULL and let the caller handle it.  */
720     PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE);
721     return NULL;
722 }
723
724
725 /* Initialize the suite->isPresent value for config_match
726  * Returns count of enabled ciphers supported by extant tokens,
727  * regardless of policy or user preference.
728  * If this returns zero, the user cannot do SSL v3.
729  */
730 int
731 ssl3_config_match_init(sslSocket *ss)
732 {
733     ssl3CipherSuiteCfg *      suite;
734     const ssl3CipherSuiteDef *cipher_def;
735     SSLCipherAlgorithm        cipher_alg;
736     CK_MECHANISM_TYPE         cipher_mech;
737     SSL3KEAType               exchKeyType;
738     int                       i;
739     int                       numPresent                = 0;
740     int                       numEnabled                = 0;
741     PRBool                    isServer;
742     sslServerCerts           *svrAuth;
743
744     PORT_Assert(ss);
745     if (!ss) {
746         PORT_SetError(SEC_ERROR_INVALID_ARGS);
747         return 0;
748     }
749     if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
750         return 0;
751     }
752     isServer = (PRBool)(ss->sec.isServer != 0);
753
754     for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
755         suite = &ss->cipherSuites[i];
756         if (suite->enabled) {
757             ++numEnabled;
758             /* We need the cipher defs to see if we have a token that can handle
759              * this cipher.  It isn't part of the static definition.
760              */
761             cipher_def = ssl_LookupCipherSuiteDef(suite->cipher_suite);
762             if (!cipher_def) {
763                 suite->isPresent = PR_FALSE;
764                 continue;
765             }
766             cipher_alg = bulk_cipher_defs[cipher_def->bulk_cipher_alg].calg;
767             PORT_Assert(  alg2Mech[cipher_alg].calg == cipher_alg);
768             cipher_mech = alg2Mech[cipher_alg].cmech;
769             exchKeyType =
770                     kea_defs[cipher_def->key_exchange_alg].exchKeyType;
771 #ifndef NSS_ENABLE_ECC
772             svrAuth = ss->serverCerts + exchKeyType;
773 #else
774             /* XXX SSLKEAType isn't really a good choice for 
775              * indexing certificates. It doesn't work for
776              * (EC)DHE-* ciphers. Here we use a hack to ensure
777              * that the server uses an RSA cert for (EC)DHE-RSA.
778              */
779             switch (cipher_def->key_exchange_alg) {
780             case kea_ecdhe_rsa:
781 #if NSS_SERVER_DHE_IMPLEMENTED
782             /* XXX NSS does not yet implement the server side of _DHE_
783              * cipher suites.  Correcting the computation for svrAuth,
784              * as the case below does, causes NSS SSL servers to begin to
785              * negotiate cipher suites they do not implement.  So, until
786              * server side _DHE_ is implemented, keep this disabled.
787              */
788             case kea_dhe_rsa:
789 #endif
790                 svrAuth = ss->serverCerts + kt_rsa;
791                 break;
792             case kea_ecdh_ecdsa:
793             case kea_ecdh_rsa:
794                 /* 
795                  * XXX We ought to have different indices for 
796                  * ECDSA- and RSA-signed EC certificates so
797                  * we could support both key exchange mechanisms
798                  * simultaneously. For now, both of them use
799                  * whatever is in the certificate slot for kt_ecdh
800                  */
801             default:
802                 svrAuth = ss->serverCerts + exchKeyType;
803                 break;
804             }
805 #endif /* NSS_ENABLE_ECC */
806
807             /* Mark the suites that are backed by real tokens, certs and keys */
808             suite->isPresent = (PRBool)
809                 (((exchKeyType == kt_null) ||
810                    ((!isServer || (svrAuth->serverKeyPair &&
811                                    svrAuth->SERVERKEY &&
812                                    svrAuth->serverCertChain)) &&
813                     PK11_TokenExists(kea_alg_defs[exchKeyType]))) &&
814                 ((cipher_alg == calg_null) || PK11_TokenExists(cipher_mech)));
815             if (suite->isPresent)
816                 ++numPresent;
817         }
818     }
819     PORT_Assert(numPresent > 0 || numEnabled == 0);
820     if (numPresent <= 0) {
821         PORT_SetError(SSL_ERROR_NO_CIPHERS_SUPPORTED);
822     }
823     return numPresent;
824 }
825
826
827 /* return PR_TRUE if suite matches policy, enabled state and is applicable to
828  * the given version range. */
829 /* It would be a REALLY BAD THING (tm) if we ever permitted the use
830 ** of a cipher that was NOT_ALLOWED.  So, if this is ever called with
831 ** policy == SSL_NOT_ALLOWED, report no match.
832 */
833 /* adjust suite enabled to the availability of a token that can do the
834  * cipher suite. */
835 static PRBool
836 config_match(ssl3CipherSuiteCfg *suite, int policy, PRBool enabled,
837              const SSLVersionRange *vrange)
838 {
839     PORT_Assert(policy != SSL_NOT_ALLOWED && enabled != PR_FALSE);
840     if (policy == SSL_NOT_ALLOWED || !enabled)
841         return PR_FALSE;
842     return (PRBool)(suite->enabled &&
843                     suite->isPresent &&
844                     suite->policy != SSL_NOT_ALLOWED &&
845                     suite->policy <= policy &&
846                     ssl3_CipherSuiteAllowedForVersionRange(
847                         suite->cipher_suite, vrange));
848 }
849
850 /* return number of cipher suites that match policy, enabled state and are
851  * applicable for the configured protocol version range. */
852 /* called from ssl3_SendClientHello and ssl3_ConstructV2CipherSpecsHack */
853 static int
854 count_cipher_suites(sslSocket *ss, int policy, PRBool enabled)
855 {
856     int i, count = 0;
857
858     if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
859         return 0;
860     }
861     for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
862         if (config_match(&ss->cipherSuites[i], policy, enabled, &ss->vrange))
863             count++;
864     }
865     if (count <= 0) {
866         PORT_SetError(SSL_ERROR_SSL_DISABLED);
867     }
868     return count;
869 }
870
871 /*
872  * Null compression, mac and encryption functions
873  */
874
875 static SECStatus
876 Null_Cipher(void *ctx, unsigned char *output, int *outputLen, int maxOutputLen,
877             const unsigned char *input, int inputLen)
878 {
879     if (inputLen > maxOutputLen) {
880         *outputLen = 0;  /* Match PK11_CipherOp in setting outputLen */
881         PORT_SetError(SEC_ERROR_OUTPUT_LEN);
882         return SECFailure;
883     }
884     *outputLen = inputLen;
885     if (input != output)
886         PORT_Memcpy(output, input, inputLen);
887     return SECSuccess;
888 }
889
890 /*
891  * SSL3 Utility functions
892  */
893
894 /* allowLargerPeerVersion controls whether the function will select the
895  * highest enabled SSL version or fail when peerVersion is greater than the
896  * highest enabled version.
897  *
898  * If allowLargerPeerVersion is true, peerVersion is the peer's highest
899  * enabled version rather than the peer's selected version.
900  */
901 SECStatus
902 ssl3_NegotiateVersion(sslSocket *ss, SSL3ProtocolVersion peerVersion,
903                       PRBool allowLargerPeerVersion)
904 {
905     if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
906         PORT_SetError(SSL_ERROR_SSL_DISABLED);
907         return SECFailure;
908     }
909
910     if (peerVersion < ss->vrange.min ||
911         (peerVersion > ss->vrange.max && !allowLargerPeerVersion)) {
912         PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
913         return SECFailure;
914     }
915
916     ss->version = PR_MIN(peerVersion, ss->vrange.max);
917     PORT_Assert(ssl3_VersionIsSupported(ss->protocolVariant, ss->version));
918
919     return SECSuccess;
920 }
921
922 static SECStatus
923 ssl3_GetNewRandom(SSL3Random *random)
924 {
925     SECStatus rv;
926
927     /* first 4 bytes are reserverd for time */
928     rv = PK11_GenerateRandom(random->rand, SSL3_RANDOM_LENGTH);
929     if (rv != SECSuccess) {
930         ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
931     }
932     return rv;
933 }
934
935 /* Called by ssl3_SendServerKeyExchange and ssl3_SendCertificateVerify */
936 SECStatus
937 ssl3_SignHashes(SSL3Hashes *hash, SECKEYPrivateKey *key, SECItem *buf, 
938                 PRBool isTLS)
939 {
940     SECStatus rv                = SECFailure;
941     PRBool    doDerEncode       = PR_FALSE;
942     int       signatureLen;
943     SECItem   hashItem;
944
945     buf->data    = NULL;
946
947     switch (key->keyType) {
948     case rsaKey:
949         hashItem.data = hash->u.raw;
950         hashItem.len = hash->len;
951         break;
952     case dsaKey:
953         doDerEncode = isTLS;
954         /* SEC_OID_UNKNOWN is used to specify the MD5/SHA1 concatenated hash.
955          * In that case, we use just the SHA1 part. */
956         if (hash->hashAlg == SEC_OID_UNKNOWN) {
957             hashItem.data = hash->u.s.sha;
958             hashItem.len = sizeof(hash->u.s.sha);
959         } else {
960             hashItem.data = hash->u.raw;
961             hashItem.len = hash->len;
962         }
963         break;
964 #ifdef NSS_ENABLE_ECC
965     case ecKey:
966         doDerEncode = PR_TRUE;
967         /* SEC_OID_UNKNOWN is used to specify the MD5/SHA1 concatenated hash.
968          * In that case, we use just the SHA1 part. */
969         if (hash->hashAlg == SEC_OID_UNKNOWN) {
970             hashItem.data = hash->u.s.sha;
971             hashItem.len = sizeof(hash->u.s.sha);
972         } else {
973             hashItem.data = hash->u.raw;
974             hashItem.len = hash->len;
975         }
976         break;
977 #endif /* NSS_ENABLE_ECC */
978     default:
979         PORT_SetError(SEC_ERROR_INVALID_KEY);
980         goto done;
981     }
982     PRINT_BUF(60, (NULL, "hash(es) to be signed", hashItem.data, hashItem.len));
983
984     if (hash->hashAlg == SEC_OID_UNKNOWN) {
985         signatureLen = PK11_SignatureLen(key);
986         if (signatureLen <= 0) {
987             PORT_SetError(SEC_ERROR_INVALID_KEY);
988             goto done;
989         }
990
991         buf->len  = (unsigned)signatureLen;
992         buf->data = (unsigned char *)PORT_Alloc(signatureLen);
993         if (!buf->data)
994             goto done;  /* error code was set. */
995
996         rv = PK11_Sign(key, buf, &hashItem);
997     } else {
998         rv = SGN_Digest(key, hash->hashAlg, buf, &hashItem);
999     }
1000     if (rv != SECSuccess) {
1001         ssl_MapLowLevelError(SSL_ERROR_SIGN_HASHES_FAILURE);
1002     } else if (doDerEncode) {
1003         SECItem   derSig        = {siBuffer, NULL, 0};
1004
1005         /* This also works for an ECDSA signature */
1006         rv = DSAU_EncodeDerSigWithLen(&derSig, buf, buf->len);
1007         if (rv == SECSuccess) {
1008             PORT_Free(buf->data);       /* discard unencoded signature. */
1009             *buf = derSig;              /* give caller encoded signature. */
1010         } else if (derSig.data) {
1011             PORT_Free(derSig.data);
1012         }
1013     }
1014
1015     PRINT_BUF(60, (NULL, "signed hashes", (unsigned char*)buf->data, buf->len));
1016 done:
1017     if (rv != SECSuccess && buf->data) {
1018         PORT_Free(buf->data);
1019         buf->data = NULL;
1020     }
1021     return rv;
1022 }
1023
1024 /* Called from ssl3_HandleServerKeyExchange, ssl3_HandleCertificateVerify */
1025 SECStatus
1026 ssl3_VerifySignedHashes(SSL3Hashes *hash, CERTCertificate *cert, 
1027                         SECItem *buf, PRBool isTLS, void *pwArg)
1028 {
1029     SECKEYPublicKey * key;
1030     SECItem *         signature = NULL;
1031     SECStatus         rv;
1032     SECItem           hashItem;
1033     SECOidTag         encAlg;
1034     SECOidTag         hashAlg;
1035
1036
1037     PRINT_BUF(60, (NULL, "check signed hashes",
1038                   buf->data, buf->len));
1039
1040     key = CERT_ExtractPublicKey(cert);
1041     if (key == NULL) {
1042         ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
1043         return SECFailure;
1044     }
1045
1046     hashAlg = hash->hashAlg;
1047     switch (key->keyType) {
1048     case rsaKey:
1049         encAlg = SEC_OID_PKCS1_RSA_ENCRYPTION;
1050         hashItem.data = hash->u.raw;
1051         hashItem.len = hash->len;
1052         break;
1053     case dsaKey:
1054         encAlg = SEC_OID_ANSIX9_DSA_SIGNATURE;
1055         /* SEC_OID_UNKNOWN is used to specify the MD5/SHA1 concatenated hash.
1056          * In that case, we use just the SHA1 part. */
1057         if (hash->hashAlg == SEC_OID_UNKNOWN) {
1058             hashItem.data = hash->u.s.sha;
1059             hashItem.len = sizeof(hash->u.s.sha);
1060         } else {
1061             hashItem.data = hash->u.raw;
1062             hashItem.len = hash->len;
1063         }
1064         /* Allow DER encoded DSA signatures in SSL 3.0 */
1065         if (isTLS || buf->len != SECKEY_SignatureLen(key)) {
1066             signature = DSAU_DecodeDerSigToLen(buf, SECKEY_SignatureLen(key));
1067             if (!signature) {
1068                 PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
1069                 return SECFailure;
1070             }
1071             buf = signature;
1072         }
1073         break;
1074
1075 #ifdef NSS_ENABLE_ECC
1076     case ecKey:
1077         encAlg = SEC_OID_ANSIX962_EC_PUBLIC_KEY;
1078         /* SEC_OID_UNKNOWN is used to specify the MD5/SHA1 concatenated hash.
1079          * In that case, we use just the SHA1 part.
1080          * ECDSA signatures always encode the integers r and s using ASN.1
1081          * (unlike DSA where ASN.1 encoding is used with TLS but not with
1082          * SSL3). So we can use VFY_VerifyDigestDirect for ECDSA.
1083          */
1084         if (hash->hashAlg == SEC_OID_UNKNOWN) {
1085             hashAlg = SEC_OID_SHA1;
1086             hashItem.data = hash->u.s.sha;
1087             hashItem.len = sizeof(hash->u.s.sha);
1088         } else {
1089             hashItem.data = hash->u.raw;
1090             hashItem.len = hash->len;
1091         }
1092         break;
1093 #endif /* NSS_ENABLE_ECC */
1094
1095     default:
1096         SECKEY_DestroyPublicKey(key);
1097         PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
1098         return SECFailure;
1099     }
1100
1101     PRINT_BUF(60, (NULL, "hash(es) to be verified",
1102                   hashItem.data, hashItem.len));
1103
1104     if (hashAlg == SEC_OID_UNKNOWN || key->keyType == dsaKey) {
1105         /* VFY_VerifyDigestDirect requires DSA signatures to be DER-encoded.
1106          * DSA signatures are DER-encoded in TLS but not in SSL3 and the code
1107          * above always removes the DER encoding of DSA signatures when
1108          * present. Thus DSA signatures are always verified with PK11_Verify.
1109          */
1110         rv = PK11_Verify(key, buf, &hashItem, pwArg);
1111     } else {
1112         rv = VFY_VerifyDigestDirect(&hashItem, key, buf, encAlg, hashAlg,
1113                                     pwArg);
1114     }
1115     SECKEY_DestroyPublicKey(key);
1116     if (signature) {
1117         SECITEM_FreeItem(signature, PR_TRUE);
1118     }
1119     if (rv != SECSuccess) {
1120         ssl_MapLowLevelError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
1121     }
1122     return rv;
1123 }
1124
1125
1126 /* Caller must set hiLevel error code. */
1127 /* Called from ssl3_ComputeExportRSAKeyHash
1128  *             ssl3_ComputeDHKeyHash
1129  * which are called from ssl3_HandleServerKeyExchange. 
1130  *
1131  * hashAlg: either the OID for a hash algorithm or SEC_OID_UNKNOWN to specify
1132  * the pre-1.2, MD5/SHA1 combination hash.
1133  */
1134 SECStatus
1135 ssl3_ComputeCommonKeyHash(SECOidTag hashAlg,
1136                           PRUint8 * hashBuf, unsigned int bufLen,
1137                           SSL3Hashes *hashes, PRBool bypassPKCS11)
1138 {
1139     SECStatus     rv            = SECSuccess;
1140
1141 #ifndef NO_PKCS11_BYPASS
1142     if (bypassPKCS11) {
1143         if (hashAlg == SEC_OID_UNKNOWN) {
1144             MD5_HashBuf (hashes->u.s.md5, hashBuf, bufLen);
1145             SHA1_HashBuf(hashes->u.s.sha, hashBuf, bufLen);
1146             hashes->len = MD5_LENGTH + SHA1_LENGTH;
1147         } else if (hashAlg == SEC_OID_SHA1) {
1148             SHA1_HashBuf(hashes->u.raw, hashBuf, bufLen);
1149             hashes->len = SHA1_LENGTH;
1150         } else if (hashAlg == SEC_OID_SHA256) {
1151             SHA256_HashBuf(hashes->u.raw, hashBuf, bufLen);
1152             hashes->len = SHA256_LENGTH;
1153         } else if (hashAlg == SEC_OID_SHA384) {
1154             SHA384_HashBuf(hashes->u.raw, hashBuf, bufLen);
1155             hashes->len = SHA384_LENGTH;
1156         } else if (hashAlg == SEC_OID_SHA512) {
1157             SHA512_HashBuf(hashes->u.raw, hashBuf, bufLen);
1158             hashes->len = SHA512_LENGTH;
1159         } else {
1160             PORT_SetError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
1161             return SECFailure;
1162         }
1163     } else 
1164 #endif
1165     {
1166         if (hashAlg == SEC_OID_UNKNOWN) {
1167             rv = PK11_HashBuf(SEC_OID_MD5, hashes->u.s.md5, hashBuf, bufLen);
1168             if (rv != SECSuccess) {
1169                 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
1170                 rv = SECFailure;
1171                 goto done;
1172             }
1173
1174             rv = PK11_HashBuf(SEC_OID_SHA1, hashes->u.s.sha, hashBuf, bufLen);
1175             if (rv != SECSuccess) {
1176                 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
1177                 rv = SECFailure;
1178             }
1179             hashes->len = MD5_LENGTH + SHA1_LENGTH;
1180         } else {
1181             hashes->len = HASH_ResultLenByOidTag(hashAlg);
1182             if (hashes->len > sizeof(hashes->u.raw)) {
1183                 ssl_MapLowLevelError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
1184                 rv = SECFailure;
1185                 goto done;
1186             }
1187             rv = PK11_HashBuf(hashAlg, hashes->u.raw, hashBuf, bufLen);
1188             if (rv != SECSuccess) {
1189                 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
1190                 rv = SECFailure;
1191             }
1192         }
1193     }
1194     hashes->hashAlg = hashAlg;
1195
1196 done:
1197     return rv;
1198 }
1199
1200 /* Caller must set hiLevel error code. 
1201 ** Called from ssl3_SendServerKeyExchange and 
1202 **             ssl3_HandleServerKeyExchange.
1203 */
1204 static SECStatus
1205 ssl3_ComputeExportRSAKeyHash(SECOidTag hashAlg,
1206                              SECItem modulus, SECItem publicExponent,
1207                              SSL3Random *client_rand, SSL3Random *server_rand,
1208                              SSL3Hashes *hashes, PRBool bypassPKCS11)
1209 {
1210     PRUint8     * hashBuf;
1211     PRUint8     * pBuf;
1212     SECStatus     rv            = SECSuccess;
1213     unsigned int  bufLen;
1214     PRUint8       buf[2*SSL3_RANDOM_LENGTH + 2 + 4096/8 + 2 + 4096/8];
1215
1216     bufLen = 2*SSL3_RANDOM_LENGTH + 2 + modulus.len + 2 + publicExponent.len;
1217     if (bufLen <= sizeof buf) {
1218         hashBuf = buf;
1219     } else {
1220         hashBuf = PORT_Alloc(bufLen);
1221         if (!hashBuf) {
1222             return SECFailure;
1223         }
1224     }
1225
1226     memcpy(hashBuf, client_rand, SSL3_RANDOM_LENGTH); 
1227         pBuf = hashBuf + SSL3_RANDOM_LENGTH;
1228     memcpy(pBuf, server_rand, SSL3_RANDOM_LENGTH);
1229         pBuf += SSL3_RANDOM_LENGTH;
1230     pBuf[0]  = (PRUint8)(modulus.len >> 8);
1231     pBuf[1]  = (PRUint8)(modulus.len);
1232         pBuf += 2;
1233     memcpy(pBuf, modulus.data, modulus.len);
1234         pBuf += modulus.len;
1235     pBuf[0] = (PRUint8)(publicExponent.len >> 8);
1236     pBuf[1] = (PRUint8)(publicExponent.len);
1237         pBuf += 2;
1238     memcpy(pBuf, publicExponent.data, publicExponent.len);
1239         pBuf += publicExponent.len;
1240     PORT_Assert((unsigned int)(pBuf - hashBuf) == bufLen);
1241
1242     rv = ssl3_ComputeCommonKeyHash(hashAlg, hashBuf, bufLen, hashes,
1243                                    bypassPKCS11);
1244
1245     PRINT_BUF(95, (NULL, "RSAkey hash: ", hashBuf, bufLen));
1246     if (hashAlg == SEC_OID_UNKNOWN) {
1247         PRINT_BUF(95, (NULL, "RSAkey hash: MD5 result",
1248                   hashes->u.s.md5, MD5_LENGTH));
1249         PRINT_BUF(95, (NULL, "RSAkey hash: SHA1 result",
1250                   hashes->u.s.sha, SHA1_LENGTH));
1251     } else {
1252         PRINT_BUF(95, (NULL, "RSAkey hash: result",
1253                   hashes->u.raw, hashes->len));
1254     }
1255
1256     if (hashBuf != buf && hashBuf != NULL)
1257         PORT_Free(hashBuf);
1258     return rv;
1259 }
1260
1261 /* Caller must set hiLevel error code. */
1262 /* Called from ssl3_HandleServerKeyExchange. */
1263 static SECStatus
1264 ssl3_ComputeDHKeyHash(SECOidTag hashAlg,
1265                       SECItem dh_p, SECItem dh_g, SECItem dh_Ys,
1266                       SSL3Random *client_rand, SSL3Random *server_rand,
1267                       SSL3Hashes *hashes, PRBool bypassPKCS11)
1268 {
1269     PRUint8     * hashBuf;
1270     PRUint8     * pBuf;
1271     SECStatus     rv            = SECSuccess;
1272     unsigned int  bufLen;
1273     PRUint8       buf[2*SSL3_RANDOM_LENGTH + 2 + 4096/8 + 2 + 4096/8];
1274
1275     bufLen = 2*SSL3_RANDOM_LENGTH + 2 + dh_p.len + 2 + dh_g.len + 2 + dh_Ys.len;
1276     if (bufLen <= sizeof buf) {
1277         hashBuf = buf;
1278     } else {
1279         hashBuf = PORT_Alloc(bufLen);
1280         if (!hashBuf) {
1281             return SECFailure;
1282         }
1283     }
1284
1285     memcpy(hashBuf, client_rand, SSL3_RANDOM_LENGTH); 
1286         pBuf = hashBuf + SSL3_RANDOM_LENGTH;
1287     memcpy(pBuf, server_rand, SSL3_RANDOM_LENGTH);
1288         pBuf += SSL3_RANDOM_LENGTH;
1289     pBuf[0]  = (PRUint8)(dh_p.len >> 8);
1290     pBuf[1]  = (PRUint8)(dh_p.len);
1291         pBuf += 2;
1292     memcpy(pBuf, dh_p.data, dh_p.len);
1293         pBuf += dh_p.len;
1294     pBuf[0] = (PRUint8)(dh_g.len >> 8);
1295     pBuf[1] = (PRUint8)(dh_g.len);
1296         pBuf += 2;
1297     memcpy(pBuf, dh_g.data, dh_g.len);
1298         pBuf += dh_g.len;
1299     pBuf[0] = (PRUint8)(dh_Ys.len >> 8);
1300     pBuf[1] = (PRUint8)(dh_Ys.len);
1301         pBuf += 2;
1302     memcpy(pBuf, dh_Ys.data, dh_Ys.len);
1303         pBuf += dh_Ys.len;
1304     PORT_Assert((unsigned int)(pBuf - hashBuf) == bufLen);
1305
1306     rv = ssl3_ComputeCommonKeyHash(hashAlg, hashBuf, bufLen, hashes,
1307                                    bypassPKCS11);
1308
1309     PRINT_BUF(95, (NULL, "DHkey hash: ", hashBuf, bufLen));
1310     if (hashAlg == SEC_OID_UNKNOWN) {
1311         PRINT_BUF(95, (NULL, "DHkey hash: MD5 result",
1312                   hashes->u.s.md5, MD5_LENGTH));
1313         PRINT_BUF(95, (NULL, "DHkey hash: SHA1 result",
1314                   hashes->u.s.sha, SHA1_LENGTH));
1315     } else {
1316         PRINT_BUF(95, (NULL, "DHkey hash: result",
1317                   hashes->u.raw, hashes->len));
1318     }
1319
1320     if (hashBuf != buf && hashBuf != NULL)
1321         PORT_Free(hashBuf);
1322     return rv;
1323 }
1324
1325 static void
1326 ssl3_BumpSequenceNumber(SSL3SequenceNumber *num)
1327 {
1328     num->low++;
1329     if (num->low == 0)
1330         num->high++;
1331 }
1332
1333 /* Called twice, only from ssl3_DestroyCipherSpec (immediately below). */
1334 static void
1335 ssl3_CleanupKeyMaterial(ssl3KeyMaterial *mat)
1336 {
1337     if (mat->write_key != NULL) {
1338         PK11_FreeSymKey(mat->write_key);
1339         mat->write_key = NULL;
1340     }
1341     if (mat->write_mac_key != NULL) {
1342         PK11_FreeSymKey(mat->write_mac_key);
1343         mat->write_mac_key = NULL;
1344     }
1345     if (mat->write_mac_context != NULL) {
1346         PK11_DestroyContext(mat->write_mac_context, PR_TRUE);
1347         mat->write_mac_context = NULL;
1348     }
1349 }
1350
1351 /* Called from ssl3_SendChangeCipherSpecs() and 
1352 **             ssl3_HandleChangeCipherSpecs()
1353 **             ssl3_DestroySSL3Info
1354 ** Caller must hold SpecWriteLock.
1355 */
1356 void
1357 ssl3_DestroyCipherSpec(ssl3CipherSpec *spec, PRBool freeSrvName)
1358 {
1359     PRBool freeit = (PRBool)(!spec->bypassCiphers);
1360 /*  PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); Don't have ss! */
1361     if (spec->destroy) {
1362         spec->destroy(spec->encodeContext, freeit);
1363         spec->destroy(spec->decodeContext, freeit);
1364         spec->encodeContext = NULL; /* paranoia */
1365         spec->decodeContext = NULL;
1366     }
1367     if (spec->destroyCompressContext && spec->compressContext) {
1368         spec->destroyCompressContext(spec->compressContext, 1);
1369         spec->compressContext = NULL;
1370     }
1371     if (spec->destroyDecompressContext && spec->decompressContext) {
1372         spec->destroyDecompressContext(spec->decompressContext, 1);
1373         spec->decompressContext = NULL;
1374     }
1375     if (freeSrvName && spec->srvVirtName.data) {
1376         SECITEM_FreeItem(&spec->srvVirtName, PR_FALSE);
1377     }
1378     if (spec->master_secret != NULL) {
1379         PK11_FreeSymKey(spec->master_secret);
1380         spec->master_secret = NULL;
1381     }
1382     spec->msItem.data = NULL;
1383     spec->msItem.len  = 0;
1384     ssl3_CleanupKeyMaterial(&spec->client);
1385     ssl3_CleanupKeyMaterial(&spec->server);
1386     spec->bypassCiphers = PR_FALSE;
1387     spec->destroy=NULL;
1388     spec->destroyCompressContext = NULL;
1389     spec->destroyDecompressContext = NULL;
1390 }
1391
1392 /* Fill in the pending cipher spec with info from the selected ciphersuite.
1393 ** This is as much initialization as we can do without having key material.
1394 ** Called from ssl3_HandleServerHello(), ssl3_SendServerHello()
1395 ** Caller must hold the ssl3 handshake lock.
1396 ** Acquires & releases SpecWriteLock.
1397 */
1398 static SECStatus
1399 ssl3_SetupPendingCipherSpec(sslSocket *ss)
1400 {
1401     ssl3CipherSpec *          pwSpec;
1402     ssl3CipherSpec *          cwSpec;
1403     ssl3CipherSuite           suite     = ss->ssl3.hs.cipher_suite;
1404     SSL3MACAlgorithm          mac;
1405     SSL3BulkCipher            cipher;
1406     SSL3KeyExchangeAlgorithm  kea;
1407     const ssl3CipherSuiteDef *suite_def;
1408     PRBool                    isTLS;
1409
1410     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
1411
1412     ssl_GetSpecWriteLock(ss);  /*******************************/
1413
1414     pwSpec = ss->ssl3.pwSpec;
1415     PORT_Assert(pwSpec == ss->ssl3.prSpec);
1416
1417     /* This hack provides maximal interoperability with SSL 3 servers. */
1418     cwSpec = ss->ssl3.cwSpec;
1419     if (cwSpec->mac_def->mac == mac_null) {
1420         /* SSL records are not being MACed. */
1421         cwSpec->version = ss->version;
1422     }
1423
1424     pwSpec->version  = ss->version;
1425     isTLS  = (PRBool)(pwSpec->version > SSL_LIBRARY_VERSION_3_0);
1426
1427     SSL_TRC(3, ("%d: SSL3[%d]: Set XXX Pending Cipher Suite to 0x%04x",
1428                 SSL_GETPID(), ss->fd, suite));
1429
1430     suite_def = ssl_LookupCipherSuiteDef(suite);
1431     if (suite_def == NULL) {
1432         ssl_ReleaseSpecWriteLock(ss);
1433         return SECFailure;      /* error code set by ssl_LookupCipherSuiteDef */
1434     }
1435
1436     if (IS_DTLS(ss)) {
1437         /* Double-check that we did not pick an RC4 suite */
1438         PORT_Assert((suite_def->bulk_cipher_alg != cipher_rc4) &&
1439                     (suite_def->bulk_cipher_alg != cipher_rc4_40) &&
1440                     (suite_def->bulk_cipher_alg != cipher_rc4_56));
1441     }
1442
1443     cipher = suite_def->bulk_cipher_alg;
1444     kea    = suite_def->key_exchange_alg;
1445     mac    = suite_def->mac_alg;
1446     if (mac <= ssl_mac_sha && mac != ssl_mac_null && isTLS)
1447         mac += 2;
1448
1449     ss->ssl3.hs.suite_def = suite_def;
1450     ss->ssl3.hs.kea_def   = &kea_defs[kea];
1451     PORT_Assert(ss->ssl3.hs.kea_def->kea == kea);
1452
1453     pwSpec->cipher_def   = &bulk_cipher_defs[cipher];
1454     PORT_Assert(pwSpec->cipher_def->cipher == cipher);
1455
1456     pwSpec->mac_def = &mac_defs[mac];
1457     PORT_Assert(pwSpec->mac_def->mac == mac);
1458
1459     ss->sec.keyBits       = pwSpec->cipher_def->key_size        * BPB;
1460     ss->sec.secretKeyBits = pwSpec->cipher_def->secret_key_size * BPB;
1461     ss->sec.cipherType    = cipher;
1462
1463     pwSpec->encodeContext = NULL;
1464     pwSpec->decodeContext = NULL;
1465
1466     pwSpec->mac_size = pwSpec->mac_def->mac_size;
1467
1468     pwSpec->compression_method = ss->ssl3.hs.compression;
1469     pwSpec->compressContext = NULL;
1470     pwSpec->decompressContext = NULL;
1471
1472     ssl_ReleaseSpecWriteLock(ss);  /*******************************/
1473     return SECSuccess;
1474 }
1475
1476 #ifdef NSS_ENABLE_ZLIB
1477 #define SSL3_DEFLATE_CONTEXT_SIZE sizeof(z_stream)
1478
1479 static SECStatus
1480 ssl3_MapZlibError(int zlib_error)
1481 {
1482     switch (zlib_error) {
1483     case Z_OK:
1484         return SECSuccess;
1485     default:
1486         return SECFailure;
1487     }
1488 }
1489
1490 static SECStatus
1491 ssl3_DeflateInit(void *void_context)
1492 {
1493     z_stream *context = void_context;
1494     context->zalloc = NULL;
1495     context->zfree = NULL;
1496     context->opaque = NULL;
1497
1498     return ssl3_MapZlibError(deflateInit(context, Z_DEFAULT_COMPRESSION));
1499 }
1500
1501 static SECStatus
1502 ssl3_InflateInit(void *void_context)
1503 {
1504     z_stream *context = void_context;
1505     context->zalloc = NULL;
1506     context->zfree = NULL;
1507     context->opaque = NULL;
1508     context->next_in = NULL;
1509     context->avail_in = 0;
1510
1511     return ssl3_MapZlibError(inflateInit(context));
1512 }
1513
1514 static SECStatus
1515 ssl3_DeflateCompress(void *void_context, unsigned char *out, int *out_len,
1516                      int maxout, const unsigned char *in, int inlen)
1517 {
1518     z_stream *context = void_context;
1519
1520     if (!inlen) {
1521         *out_len = 0;
1522         return SECSuccess;
1523     }
1524
1525     context->next_in = (unsigned char*) in;
1526     context->avail_in = inlen;
1527     context->next_out = out;
1528     context->avail_out = maxout;
1529     if (deflate(context, Z_SYNC_FLUSH) != Z_OK) {
1530         return SECFailure;
1531     }
1532     if (context->avail_out == 0) {
1533         /* We ran out of space! */
1534         SSL_TRC(3, ("%d: SSL3[%d] Ran out of buffer while compressing",
1535                     SSL_GETPID()));
1536         return SECFailure;
1537     }
1538
1539     *out_len = maxout - context->avail_out;
1540     return SECSuccess;
1541 }
1542
1543 static SECStatus
1544 ssl3_DeflateDecompress(void *void_context, unsigned char *out, int *out_len,
1545                        int maxout, const unsigned char *in, int inlen)
1546 {
1547     z_stream *context = void_context;
1548
1549     if (!inlen) {
1550         *out_len = 0;
1551         return SECSuccess;
1552     }
1553
1554     context->next_in = (unsigned char*) in;
1555     context->avail_in = inlen;
1556     context->next_out = out;
1557     context->avail_out = maxout;
1558     if (inflate(context, Z_SYNC_FLUSH) != Z_OK) {
1559         PORT_SetError(SSL_ERROR_DECOMPRESSION_FAILURE);
1560         return SECFailure;
1561     }
1562
1563     *out_len = maxout - context->avail_out;
1564     return SECSuccess;
1565 }
1566
1567 static SECStatus
1568 ssl3_DestroyCompressContext(void *void_context, PRBool unused)
1569 {
1570     deflateEnd(void_context);
1571     PORT_Free(void_context);
1572     return SECSuccess;
1573 }
1574
1575 static SECStatus
1576 ssl3_DestroyDecompressContext(void *void_context, PRBool unused)
1577 {
1578     inflateEnd(void_context);
1579     PORT_Free(void_context);
1580     return SECSuccess;
1581 }
1582
1583 #endif /* NSS_ENABLE_ZLIB */
1584
1585 /* Initialize the compression functions and contexts for the given
1586  * CipherSpec.  */
1587 static SECStatus
1588 ssl3_InitCompressionContext(ssl3CipherSpec *pwSpec)
1589 {
1590     /* Setup the compression functions */
1591     switch (pwSpec->compression_method) {
1592     case ssl_compression_null:
1593         pwSpec->compressor = NULL;
1594         pwSpec->decompressor = NULL;
1595         pwSpec->compressContext = NULL;
1596         pwSpec->decompressContext = NULL;
1597         pwSpec->destroyCompressContext = NULL;
1598         pwSpec->destroyDecompressContext = NULL;
1599         break;
1600 #ifdef NSS_ENABLE_ZLIB
1601     case ssl_compression_deflate:
1602         pwSpec->compressor = ssl3_DeflateCompress;
1603         pwSpec->decompressor = ssl3_DeflateDecompress;
1604         pwSpec->compressContext = PORT_Alloc(SSL3_DEFLATE_CONTEXT_SIZE);
1605         pwSpec->decompressContext = PORT_Alloc(SSL3_DEFLATE_CONTEXT_SIZE);
1606         pwSpec->destroyCompressContext = ssl3_DestroyCompressContext;
1607         pwSpec->destroyDecompressContext = ssl3_DestroyDecompressContext;
1608         ssl3_DeflateInit(pwSpec->compressContext);
1609         ssl3_InflateInit(pwSpec->decompressContext);
1610         break;
1611 #endif /* NSS_ENABLE_ZLIB */
1612     default:
1613         PORT_Assert(0);
1614         PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1615         return SECFailure;
1616     }
1617
1618     return SECSuccess;
1619 }
1620
1621 #ifndef NO_PKCS11_BYPASS
1622 /* Initialize encryption contexts for pending spec.
1623  * MAC contexts are set up when computing the mac, not here.
1624  * Master Secret already is derived in spec->msItem
1625  * Caller holds Spec write lock.
1626  */
1627 static SECStatus
1628 ssl3_InitPendingContextsBypass(sslSocket *ss)
1629 {
1630       ssl3CipherSpec  *  pwSpec;
1631       const ssl3BulkCipherDef *cipher_def;
1632       void *             serverContext = NULL;
1633       void *             clientContext = NULL;
1634       BLapiInitContextFunc initFn = (BLapiInitContextFunc)NULL;
1635       int                mode     = 0;
1636       unsigned int       optArg1  = 0;
1637       unsigned int       optArg2  = 0;
1638       PRBool             server_encrypts = ss->sec.isServer;
1639       SSLCipherAlgorithm calg;
1640       SECStatus          rv;
1641
1642     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
1643     PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
1644     PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
1645
1646     pwSpec        = ss->ssl3.pwSpec;
1647     cipher_def    = pwSpec->cipher_def;
1648
1649     calg = cipher_def->calg;
1650
1651     if (calg == ssl_calg_aes_gcm) {
1652         pwSpec->encode = NULL;
1653         pwSpec->decode = NULL;
1654         pwSpec->destroy = NULL;
1655         pwSpec->encodeContext = NULL;
1656         pwSpec->decodeContext = NULL;
1657         pwSpec->aead = ssl3_AESGCMBypass;
1658         ssl3_InitCompressionContext(pwSpec);
1659         return SECSuccess;
1660     }
1661
1662     serverContext = pwSpec->server.cipher_context;
1663     clientContext = pwSpec->client.cipher_context;
1664
1665     switch (calg) {
1666     case ssl_calg_null:
1667         pwSpec->encode  = Null_Cipher;
1668         pwSpec->decode  = Null_Cipher;
1669         pwSpec->destroy = NULL;
1670         goto success;
1671
1672     case ssl_calg_rc4:
1673         initFn = (BLapiInitContextFunc)RC4_InitContext;
1674         pwSpec->encode  = (SSLCipher) RC4_Encrypt;
1675         pwSpec->decode  = (SSLCipher) RC4_Decrypt;
1676         pwSpec->destroy = (SSLDestroy) RC4_DestroyContext;
1677         break;
1678     case ssl_calg_rc2:
1679         initFn = (BLapiInitContextFunc)RC2_InitContext;
1680         mode = NSS_RC2_CBC;
1681         optArg1 = cipher_def->key_size;
1682         pwSpec->encode  = (SSLCipher) RC2_Encrypt;
1683         pwSpec->decode  = (SSLCipher) RC2_Decrypt;
1684         pwSpec->destroy = (SSLDestroy) RC2_DestroyContext;
1685         break;
1686     case ssl_calg_des:
1687         initFn = (BLapiInitContextFunc)DES_InitContext;
1688         mode = NSS_DES_CBC;
1689         optArg1 = server_encrypts;
1690         pwSpec->encode  = (SSLCipher) DES_Encrypt;
1691         pwSpec->decode  = (SSLCipher) DES_Decrypt;
1692         pwSpec->destroy = (SSLDestroy) DES_DestroyContext;
1693         break;
1694     case ssl_calg_3des:
1695         initFn = (BLapiInitContextFunc)DES_InitContext;
1696         mode = NSS_DES_EDE3_CBC;
1697         optArg1 = server_encrypts;
1698         pwSpec->encode  = (SSLCipher) DES_Encrypt;
1699         pwSpec->decode  = (SSLCipher) DES_Decrypt;
1700         pwSpec->destroy = (SSLDestroy) DES_DestroyContext;
1701         break;
1702     case ssl_calg_aes:
1703         initFn = (BLapiInitContextFunc)AES_InitContext;
1704         mode = NSS_AES_CBC;
1705         optArg1 = server_encrypts;
1706         optArg2 = AES_BLOCK_SIZE;
1707         pwSpec->encode  = (SSLCipher) AES_Encrypt;
1708         pwSpec->decode  = (SSLCipher) AES_Decrypt;
1709         pwSpec->destroy = (SSLDestroy) AES_DestroyContext;
1710         break;
1711
1712     case ssl_calg_camellia:
1713         initFn = (BLapiInitContextFunc)Camellia_InitContext;
1714         mode = NSS_CAMELLIA_CBC;
1715         optArg1 = server_encrypts;
1716         optArg2 = CAMELLIA_BLOCK_SIZE;
1717         pwSpec->encode  = (SSLCipher) Camellia_Encrypt;
1718         pwSpec->decode  = (SSLCipher) Camellia_Decrypt;
1719         pwSpec->destroy = (SSLDestroy) Camellia_DestroyContext;
1720         break;
1721
1722     case ssl_calg_seed:
1723         initFn = (BLapiInitContextFunc)SEED_InitContext;
1724         mode = NSS_SEED_CBC;
1725         optArg1 = server_encrypts;
1726         optArg2 = SEED_BLOCK_SIZE;
1727         pwSpec->encode  = (SSLCipher) SEED_Encrypt;
1728         pwSpec->decode  = (SSLCipher) SEED_Decrypt;
1729         pwSpec->destroy = (SSLDestroy) SEED_DestroyContext;
1730         break;
1731
1732     case ssl_calg_idea:
1733     case ssl_calg_fortezza :
1734     default:
1735         PORT_Assert(0);
1736         PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1737         goto bail_out;
1738     }
1739     rv = (*initFn)(serverContext,
1740                    pwSpec->server.write_key_item.data,
1741                    pwSpec->server.write_key_item.len,
1742                    pwSpec->server.write_iv_item.data,
1743                    mode, optArg1, optArg2);
1744     if (rv != SECSuccess) {
1745         PORT_Assert(0);
1746         PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1747         goto bail_out;
1748     }
1749
1750     switch (calg) {
1751     case ssl_calg_des:
1752     case ssl_calg_3des:
1753     case ssl_calg_aes:
1754     case ssl_calg_camellia:
1755     case ssl_calg_seed:
1756         /* For block ciphers, if the server is encrypting, then the client
1757         * is decrypting, and vice versa.
1758         */
1759         optArg1 = !optArg1;
1760         break;
1761     /* kill warnings. */
1762     case ssl_calg_null:
1763     case ssl_calg_rc4:
1764     case ssl_calg_rc2:
1765     case ssl_calg_idea:
1766     case ssl_calg_fortezza:
1767     case ssl_calg_aes_gcm:
1768         break;
1769     }
1770
1771     rv = (*initFn)(clientContext,
1772                    pwSpec->client.write_key_item.data,
1773                    pwSpec->client.write_key_item.len,
1774                    pwSpec->client.write_iv_item.data,
1775                    mode, optArg1, optArg2);
1776     if (rv != SECSuccess) {
1777         PORT_Assert(0);
1778         PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1779         goto bail_out;
1780     }
1781
1782     pwSpec->encodeContext = (ss->sec.isServer) ? serverContext : clientContext;
1783     pwSpec->decodeContext = (ss->sec.isServer) ? clientContext : serverContext;
1784
1785     ssl3_InitCompressionContext(pwSpec);
1786
1787 success:
1788     return SECSuccess;
1789
1790 bail_out:
1791     return SECFailure;
1792 }
1793 #endif
1794
1795 /* This function should probably be moved to pk11wrap and be named 
1796  * PK11_ParamFromIVAndEffectiveKeyBits
1797  */
1798 static SECItem *
1799 ssl3_ParamFromIV(CK_MECHANISM_TYPE mtype, SECItem *iv, CK_ULONG ulEffectiveBits)
1800 {
1801     SECItem * param = PK11_ParamFromIV(mtype, iv);
1802     if (param && param->data  && param->len >= sizeof(CK_RC2_PARAMS)) {
1803         switch (mtype) {
1804         case CKM_RC2_KEY_GEN:
1805         case CKM_RC2_ECB:
1806         case CKM_RC2_CBC:
1807         case CKM_RC2_MAC:
1808         case CKM_RC2_MAC_GENERAL:
1809         case CKM_RC2_CBC_PAD:
1810             *(CK_RC2_PARAMS *)param->data = ulEffectiveBits;
1811         default: break;
1812         }
1813     }
1814     return param;
1815 }
1816
1817 /* ssl3_BuildRecordPseudoHeader writes the SSL/TLS pseudo-header (the data
1818  * which is included in the MAC or AEAD additional data) to |out| and returns
1819  * its length. See https://tools.ietf.org/html/rfc5246#section-6.2.3.3 for the
1820  * definition of the AEAD additional data.
1821  *
1822  * TLS pseudo-header includes the record's version field, SSL's doesn't. Which
1823  * pseudo-header defintiion to use should be decided based on the version of
1824  * the protocol that was negotiated when the cipher spec became current, NOT
1825  * based on the version value in the record itself, and the decision is passed
1826  * to this function as the |includesVersion| argument. But, the |version|
1827  * argument should be the record's version value.
1828  */
1829 static unsigned int
1830 ssl3_BuildRecordPseudoHeader(unsigned char *out,
1831                              SSL3SequenceNumber seq_num,
1832                              SSL3ContentType type,
1833                              PRBool includesVersion,
1834                              SSL3ProtocolVersion version,
1835                              PRBool isDTLS,
1836                              int length)
1837 {
1838     out[0] = (unsigned char)(seq_num.high >> 24);
1839     out[1] = (unsigned char)(seq_num.high >> 16);
1840     out[2] = (unsigned char)(seq_num.high >>  8);
1841     out[3] = (unsigned char)(seq_num.high >>  0);
1842     out[4] = (unsigned char)(seq_num.low  >> 24);
1843     out[5] = (unsigned char)(seq_num.low  >> 16);
1844     out[6] = (unsigned char)(seq_num.low  >>  8);
1845     out[7] = (unsigned char)(seq_num.low  >>  0);
1846     out[8] = type;
1847
1848     /* SSL3 MAC doesn't include the record's version field. */
1849     if (!includesVersion) {
1850         out[9]  = MSB(length);
1851         out[10] = LSB(length);
1852         return 11;
1853     }
1854
1855     /* TLS MAC and AEAD additional data include version. */
1856     if (isDTLS) {
1857         SSL3ProtocolVersion dtls_version;
1858
1859         dtls_version = dtls_TLSVersionToDTLSVersion(version);
1860         out[9]  = MSB(dtls_version);
1861         out[10] = LSB(dtls_version);
1862     } else {
1863         out[9]  = MSB(version);
1864         out[10] = LSB(version);
1865     }
1866     out[11] = MSB(length);
1867     out[12] = LSB(length);
1868     return 13;
1869 }
1870
1871 typedef SECStatus (*PK11CryptFcn)(
1872     PK11SymKey *symKey, CK_MECHANISM_TYPE mechanism, SECItem *param,
1873     unsigned char *out, unsigned int *outLen, unsigned int maxLen,
1874     const unsigned char *in, unsigned int inLen);
1875
1876 static PK11CryptFcn pk11_encrypt = NULL;
1877 static PK11CryptFcn pk11_decrypt = NULL;
1878
1879 static PRCallOnceType resolvePK11CryptOnce;
1880
1881 static PRStatus
1882 ssl3_ResolvePK11CryptFunctions(void)
1883 {
1884 #ifdef LINUX
1885     /* On Linux we use the system NSS libraries. Look up the PK11_Encrypt and
1886      * PK11_Decrypt functions at run time. */
1887     void *handle = dlopen(NULL, RTLD_LAZY);
1888     if (!handle) {
1889         PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1890         return PR_FAILURE;
1891     }
1892     pk11_encrypt = (PK11CryptFcn)dlsym(handle, "PK11_Encrypt");
1893     pk11_decrypt = (PK11CryptFcn)dlsym(handle, "PK11_Decrypt");
1894     dlclose(handle);
1895     return PR_SUCCESS;
1896 #else
1897     /* On other platforms we use our own copy of NSS. PK11_Encrypt and
1898      * PK11_Decrypt are known to be available. */
1899     pk11_encrypt = PK11_Encrypt;
1900     pk11_decrypt = PK11_Decrypt;
1901     return PR_SUCCESS;
1902 #endif
1903 }
1904
1905 /* 
1906  * In NSS 3.15, PK11_Encrypt and PK11_Decrypt were added to provide access
1907  * to the AES GCM implementation in the NSS softoken. So the presence of
1908  * these two functions implies the NSS version supports AES GCM.
1909  */
1910 static PRBool
1911 ssl3_HasGCMSupport(void)
1912 {
1913     (void)PR_CallOnce(&resolvePK11CryptOnce, ssl3_ResolvePK11CryptFunctions);
1914     return pk11_encrypt != NULL;
1915 }
1916
1917 /* On this socket, disable the GCM cipher suites */
1918 SECStatus
1919 ssl3_DisableGCMSuites(sslSocket * ss)
1920 {
1921     unsigned int i;
1922
1923     for (i = 0; i < PR_ARRAY_SIZE(cipher_suite_defs); i++) {
1924         const ssl3CipherSuiteDef *cipher_def = &cipher_suite_defs[i];
1925         if (cipher_def->bulk_cipher_alg == cipher_aes_128_gcm) {
1926             SECStatus rv = ssl3_CipherPrefSet(ss, cipher_def->cipher_suite,
1927                                               PR_FALSE);
1928             PORT_Assert(rv == SECSuccess); /* else is coding error */
1929         }
1930     }
1931     return SECSuccess;
1932 }
1933
1934 static SECStatus
1935 ssl3_AESGCM(ssl3KeyMaterial *keys,
1936             PRBool doDecrypt,
1937             unsigned char *out,
1938             int *outlen,
1939             int maxout,
1940             const unsigned char *in,
1941             int inlen,
1942             const unsigned char *additionalData,
1943             int additionalDataLen)
1944 {
1945     SECItem            param;
1946     SECStatus          rv = SECFailure;
1947     unsigned char      nonce[12];
1948     unsigned int       uOutLen;
1949     CK_GCM_PARAMS      gcmParams;
1950
1951     static const int   tagSize = 16;
1952     static const int   explicitNonceLen = 8;
1953
1954     /* See https://tools.ietf.org/html/rfc5288#section-3 for details of how the
1955      * nonce is formed. */
1956     memcpy(nonce, keys->write_iv, 4);
1957     if (doDecrypt) {
1958         memcpy(nonce + 4, in, explicitNonceLen);
1959         in += explicitNonceLen;
1960         inlen -= explicitNonceLen;
1961         *outlen = 0;
1962     } else {
1963         if (maxout < explicitNonceLen) {
1964             PORT_SetError(SEC_ERROR_INPUT_LEN);
1965             return SECFailure;
1966         }
1967         /* Use the 64-bit sequence number as the explicit nonce. */
1968         memcpy(nonce + 4, additionalData, explicitNonceLen);
1969         memcpy(out, additionalData, explicitNonceLen);
1970         out += explicitNonceLen;
1971         maxout -= explicitNonceLen;
1972         *outlen = explicitNonceLen;
1973     }
1974
1975     param.type = siBuffer;
1976     param.data = (unsigned char *) &gcmParams;
1977     param.len = sizeof(gcmParams);
1978     gcmParams.pIv = nonce;
1979     gcmParams.ulIvLen = sizeof(nonce);
1980     gcmParams.pAAD = (unsigned char *)additionalData;  /* const cast */
1981     gcmParams.ulAADLen = additionalDataLen;
1982     gcmParams.ulTagBits = tagSize * 8;
1983
1984     if (doDecrypt) {
1985         rv = pk11_decrypt(keys->write_key, CKM_AES_GCM, &param, out, &uOutLen,
1986                           maxout, in, inlen);
1987     } else {
1988         rv = pk11_encrypt(keys->write_key, CKM_AES_GCM, &param, out, &uOutLen,
1989                           maxout, in, inlen);
1990     }
1991     *outlen += (int) uOutLen;
1992
1993     return rv;
1994 }
1995
1996 #ifndef NO_PKCS11_BYPASS
1997 static SECStatus
1998 ssl3_AESGCMBypass(ssl3KeyMaterial *keys,
1999                   PRBool doDecrypt,
2000                   unsigned char *out,
2001                   int *outlen,
2002                   int maxout,
2003                   const unsigned char *in,
2004                   int inlen,
2005                   const unsigned char *additionalData,
2006                   int additionalDataLen)
2007 {
2008     SECStatus          rv = SECFailure;
2009     unsigned char      nonce[12];
2010     unsigned int       uOutLen;
2011     AESContext        *cx;
2012     CK_GCM_PARAMS      gcmParams;
2013
2014     static const int   tagSize = 16;
2015     static const int   explicitNonceLen = 8;
2016
2017     /* See https://tools.ietf.org/html/rfc5288#section-3 for details of how the
2018      * nonce is formed. */
2019     PORT_Assert(keys->write_iv_item.len == 4);
2020     if (keys->write_iv_item.len != 4) {
2021         PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2022         return SECFailure;
2023     }
2024     memcpy(nonce, keys->write_iv_item.data, 4);
2025     if (doDecrypt) {
2026         memcpy(nonce + 4, in, explicitNonceLen);
2027         in += explicitNonceLen;
2028         inlen -= explicitNonceLen;
2029         *outlen = 0;
2030     } else {
2031         if (maxout < explicitNonceLen) {
2032             PORT_SetError(SEC_ERROR_INPUT_LEN);
2033             return SECFailure;
2034         }
2035         /* Use the 64-bit sequence number as the explicit nonce. */
2036         memcpy(nonce + 4, additionalData, explicitNonceLen);
2037         memcpy(out, additionalData, explicitNonceLen);
2038         out += explicitNonceLen;
2039         maxout -= explicitNonceLen;
2040         *outlen = explicitNonceLen;
2041     }
2042
2043     gcmParams.pIv = nonce;
2044     gcmParams.ulIvLen = sizeof(nonce);
2045     gcmParams.pAAD = (unsigned char *)additionalData;  /* const cast */
2046     gcmParams.ulAADLen = additionalDataLen;
2047     gcmParams.ulTagBits = tagSize * 8;
2048
2049     cx = (AESContext *)keys->cipher_context;
2050     rv = AES_InitContext(cx, keys->write_key_item.data,
2051                          keys->write_key_item.len,
2052                          (unsigned char *)&gcmParams, NSS_AES_GCM, !doDecrypt,
2053                          AES_BLOCK_SIZE);
2054     if (rv != SECSuccess) {
2055         return rv;
2056     }
2057     if (doDecrypt) {
2058         rv = AES_Decrypt(cx, out, &uOutLen, maxout, in, inlen);
2059     } else {
2060         rv = AES_Encrypt(cx, out, &uOutLen, maxout, in, inlen);
2061     }
2062     AES_DestroyContext(cx, PR_FALSE);
2063     *outlen += (int) uOutLen;
2064
2065     return rv;
2066 }
2067 #endif
2068
2069 static SECStatus
2070 ssl3_ChaCha20Poly1305(
2071         ssl3KeyMaterial *keys,
2072         PRBool doDecrypt,
2073         unsigned char *out,
2074         int *outlen,
2075         int maxout,
2076         const unsigned char *in,
2077         int inlen,
2078         const unsigned char *additionalData,
2079         int additionalDataLen)
2080 {
2081     SECItem            param;
2082     SECStatus          rv = SECFailure;
2083     unsigned int       uOutLen;
2084     CK_NSS_AEAD_PARAMS aeadParams;
2085     static const int   tagSize = 16;
2086
2087     param.type = siBuffer;
2088     param.len = sizeof(aeadParams);
2089     param.data = (unsigned char *) &aeadParams;
2090     memset(&aeadParams, 0, sizeof(aeadParams));
2091     aeadParams.pIv = (unsigned char *) additionalData;
2092     aeadParams.ulIvLen = 8;
2093     aeadParams.pAAD = (unsigned char *) additionalData;
2094     aeadParams.ulAADLen = additionalDataLen;
2095     aeadParams.ulTagLen = tagSize;
2096
2097     if (doDecrypt) {
2098         rv = pk11_decrypt(keys->write_key, CKM_NSS_CHACHA20_POLY1305, &param,
2099                           out, &uOutLen, maxout, in, inlen);
2100     } else {
2101         rv = pk11_encrypt(keys->write_key, CKM_NSS_CHACHA20_POLY1305, &param,
2102                           out, &uOutLen, maxout, in, inlen);
2103     }
2104     *outlen = (int) uOutLen;
2105
2106     return rv;
2107 }
2108
2109 /* Initialize encryption and MAC contexts for pending spec.
2110  * Master Secret already is derived.
2111  * Caller holds Spec write lock.
2112  */
2113 static SECStatus
2114 ssl3_InitPendingContextsPKCS11(sslSocket *ss)
2115 {
2116       ssl3CipherSpec  *  pwSpec;
2117       const ssl3BulkCipherDef *cipher_def;
2118       PK11Context *      serverContext = NULL;
2119       PK11Context *      clientContext = NULL;
2120       SECItem *          param;
2121       CK_MECHANISM_TYPE  mechanism;
2122       CK_MECHANISM_TYPE  mac_mech;
2123       CK_ULONG           macLength;
2124       CK_ULONG           effKeyBits;
2125       SECItem            iv;
2126       SECItem            mac_param;
2127       SSLCipherAlgorithm calg;
2128
2129     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
2130     PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
2131     PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
2132
2133     pwSpec        = ss->ssl3.pwSpec;
2134     cipher_def    = pwSpec->cipher_def;
2135     macLength     = pwSpec->mac_size;
2136     calg          = cipher_def->calg;
2137     PORT_Assert(alg2Mech[calg].calg == calg);
2138
2139     pwSpec->client.write_mac_context = NULL;
2140     pwSpec->server.write_mac_context = NULL;
2141
2142     if (calg == calg_aes_gcm || calg == calg_chacha20) {
2143         pwSpec->encode = NULL;
2144         pwSpec->decode = NULL;
2145         pwSpec->destroy = NULL;
2146         pwSpec->encodeContext = NULL;
2147         pwSpec->decodeContext = NULL;
2148         if (calg == calg_aes_gcm) {
2149             pwSpec->aead = ssl3_AESGCM;
2150         } else {
2151             pwSpec->aead = ssl3_ChaCha20Poly1305;
2152         }
2153         return SECSuccess;
2154     }
2155
2156     /* 
2157     ** Now setup the MAC contexts, 
2158     **   crypto contexts are setup below.
2159     */
2160
2161     mac_mech       = pwSpec->mac_def->mmech;
2162     mac_param.data = (unsigned char *)&macLength;
2163     mac_param.len  = sizeof(macLength);
2164     mac_param.type = 0;
2165
2166     pwSpec->client.write_mac_context = PK11_CreateContextBySymKey(
2167             mac_mech, CKA_SIGN, pwSpec->client.write_mac_key, &mac_param);
2168     if (pwSpec->client.write_mac_context == NULL)  {
2169         ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
2170         goto fail;
2171     }
2172     pwSpec->server.write_mac_context = PK11_CreateContextBySymKey(
2173             mac_mech, CKA_SIGN, pwSpec->server.write_mac_key, &mac_param);
2174     if (pwSpec->server.write_mac_context == NULL) {
2175         ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
2176         goto fail;
2177     }
2178
2179     /* 
2180     ** Now setup the crypto contexts.
2181     */
2182
2183     if (calg == calg_null) {
2184         pwSpec->encode  = Null_Cipher;
2185         pwSpec->decode  = Null_Cipher;
2186         pwSpec->destroy = NULL;
2187         return SECSuccess;
2188     }
2189     mechanism = alg2Mech[calg].cmech;
2190     effKeyBits = cipher_def->key_size * BPB;
2191
2192     /*
2193      * build the server context
2194      */
2195     iv.data = pwSpec->server.write_iv;
2196     iv.len  = cipher_def->iv_size;
2197     param = ssl3_ParamFromIV(mechanism, &iv, effKeyBits);
2198     if (param == NULL) {
2199         ssl_MapLowLevelError(SSL_ERROR_IV_PARAM_FAILURE);
2200         goto fail;
2201     }
2202     serverContext = PK11_CreateContextBySymKey(mechanism,
2203                                 (ss->sec.isServer ? CKA_ENCRYPT : CKA_DECRYPT),
2204                                 pwSpec->server.write_key, param);
2205     iv.data = PK11_IVFromParam(mechanism, param, (int *)&iv.len);
2206     if (iv.data)
2207         PORT_Memcpy(pwSpec->server.write_iv, iv.data, iv.len);
2208     SECITEM_FreeItem(param, PR_TRUE);
2209     if (serverContext == NULL) {
2210         ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
2211         goto fail;
2212     }
2213
2214     /*
2215      * build the client context
2216      */
2217     iv.data = pwSpec->client.write_iv;
2218     iv.len  = cipher_def->iv_size;
2219
2220     param = ssl3_ParamFromIV(mechanism, &iv, effKeyBits);
2221     if (param == NULL) {
2222         ssl_MapLowLevelError(SSL_ERROR_IV_PARAM_FAILURE);
2223         goto fail;
2224     }
2225     clientContext = PK11_CreateContextBySymKey(mechanism,
2226                                 (ss->sec.isServer ? CKA_DECRYPT : CKA_ENCRYPT),
2227                                 pwSpec->client.write_key, param);
2228     iv.data = PK11_IVFromParam(mechanism, param, (int *)&iv.len);
2229     if (iv.data)
2230         PORT_Memcpy(pwSpec->client.write_iv, iv.data, iv.len);
2231     SECITEM_FreeItem(param,PR_TRUE);
2232     if (clientContext == NULL) {
2233         ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
2234         goto fail;
2235     }
2236     pwSpec->encode  = (SSLCipher) PK11_CipherOp;
2237     pwSpec->decode  = (SSLCipher) PK11_CipherOp;
2238     pwSpec->destroy = (SSLDestroy) PK11_DestroyContext;
2239
2240     pwSpec->encodeContext = (ss->sec.isServer) ? serverContext : clientContext;
2241     pwSpec->decodeContext = (ss->sec.isServer) ? clientContext : serverContext;
2242
2243     serverContext = NULL;
2244     clientContext = NULL;
2245
2246     ssl3_InitCompressionContext(pwSpec);
2247
2248     return SECSuccess;
2249
2250 fail:
2251     if (serverContext != NULL) PK11_DestroyContext(serverContext, PR_TRUE);
2252     if (clientContext != NULL) PK11_DestroyContext(clientContext, PR_TRUE);
2253     if (pwSpec->client.write_mac_context != NULL) {
2254         PK11_DestroyContext(pwSpec->client.write_mac_context,PR_TRUE);
2255         pwSpec->client.write_mac_context = NULL;
2256     }
2257     if (pwSpec->server.write_mac_context != NULL) {
2258         PK11_DestroyContext(pwSpec->server.write_mac_context,PR_TRUE);
2259         pwSpec->server.write_mac_context = NULL;
2260     }
2261
2262     return SECFailure;
2263 }
2264
2265 /* Complete the initialization of all keys, ciphers, MACs and their contexts
2266  * for the pending Cipher Spec.
2267  * Called from: ssl3_SendClientKeyExchange      (for Full handshake)
2268  *              ssl3_HandleRSAClientKeyExchange (for Full handshake)
2269  *              ssl3_HandleServerHello          (for session restart)
2270  *              ssl3_HandleClientHello          (for session restart)
2271  * Sets error code, but caller probably should override to disambiguate.
2272  * NULL pms means re-use old master_secret.
2273  *
2274  * This code is common to the bypass and PKCS11 execution paths.
2275  * For the bypass case,  pms is NULL.
2276  */
2277 SECStatus
2278 ssl3_InitPendingCipherSpec(sslSocket *ss, PK11SymKey *pms)
2279 {
2280     ssl3CipherSpec  *  pwSpec;
2281     ssl3CipherSpec  *  cwSpec;
2282     SECStatus          rv;
2283
2284     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
2285
2286     ssl_GetSpecWriteLock(ss);   /**************************************/
2287
2288     PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
2289
2290     pwSpec        = ss->ssl3.pwSpec;
2291     cwSpec        = ss->ssl3.cwSpec;
2292
2293     if (pms || (!pwSpec->msItem.len && !pwSpec->master_secret)) {
2294         rv = ssl3_DeriveMasterSecret(ss, pms);
2295         if (rv != SECSuccess) {
2296             goto done;  /* err code set by ssl3_DeriveMasterSecret */
2297         }
2298     }
2299 #ifndef NO_PKCS11_BYPASS
2300     if (ss->opt.bypassPKCS11 && pwSpec->msItem.len && pwSpec->msItem.data) {
2301         /* Double Bypass succeeded in extracting the master_secret */
2302         const ssl3KEADef * kea_def = ss->ssl3.hs.kea_def;
2303         PRBool             isTLS   = (PRBool)(kea_def->tls_keygen ||
2304                                 (pwSpec->version > SSL_LIBRARY_VERSION_3_0));
2305         pwSpec->bypassCiphers = PR_TRUE;
2306         rv = ssl3_KeyAndMacDeriveBypass( pwSpec, 
2307                              (const unsigned char *)&ss->ssl3.hs.client_random,
2308                              (const unsigned char *)&ss->ssl3.hs.server_random,
2309                              isTLS, 
2310                              (PRBool)(kea_def->is_limited));
2311         if (rv == SECSuccess) {
2312             rv = ssl3_InitPendingContextsBypass(ss);
2313         }
2314     } else
2315 #endif
2316     if (pwSpec->master_secret) {
2317         rv = ssl3_DeriveConnectionKeysPKCS11(ss);
2318         if (rv == SECSuccess) {
2319             rv = ssl3_InitPendingContextsPKCS11(ss);
2320         }
2321     } else {
2322         PORT_Assert(pwSpec->master_secret);
2323         PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2324         rv = SECFailure;
2325     }
2326     if (rv != SECSuccess) {
2327         goto done;
2328     }
2329
2330     /* Generic behaviors -- common to all crypto methods */
2331     if (!IS_DTLS(ss)) {
2332         pwSpec->read_seq_num.high = pwSpec->write_seq_num.high = 0;
2333     } else {
2334         if (cwSpec->epoch == PR_UINT16_MAX) {
2335             /* The problem here is that we have rehandshaked too many
2336              * times (you are not allowed to wrap the epoch). The
2337              * spec says you should be discarding the connection
2338              * and start over, so not much we can do here. */
2339             PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2340             rv = SECFailure;
2341             goto done;
2342         }
2343         /* The sequence number has the high 16 bits as the epoch. */
2344         pwSpec->epoch = cwSpec->epoch + 1;
2345         pwSpec->read_seq_num.high = pwSpec->write_seq_num.high =
2346             pwSpec->epoch << 16;
2347
2348         dtls_InitRecvdRecords(&pwSpec->recvdRecords);
2349     }
2350     pwSpec->read_seq_num.low = pwSpec->write_seq_num.low = 0;
2351
2352 done:
2353     ssl_ReleaseSpecWriteLock(ss);       /******************************/
2354     if (rv != SECSuccess)
2355         ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
2356     return rv;
2357 }
2358
2359 /*
2360  * 60 bytes is 3 times the maximum length MAC size that is supported.
2361  */
2362 static const unsigned char mac_pad_1 [60] = {
2363     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
2364     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
2365     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
2366     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
2367     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
2368     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
2369     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
2370     0x36, 0x36, 0x36, 0x36
2371 };
2372 static const unsigned char mac_pad_2 [60] = {
2373     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
2374     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
2375     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
2376     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
2377     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
2378     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
2379     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
2380     0x5c, 0x5c, 0x5c, 0x5c
2381 };
2382
2383 /* Called from: ssl3_SendRecord()
2384 ** Caller must already hold the SpecReadLock. (wish we could assert that!)
2385 */
2386 static SECStatus
2387 ssl3_ComputeRecordMAC(
2388     ssl3CipherSpec *   spec,
2389     PRBool             useServerMacKey,
2390     const unsigned char *header,
2391     unsigned int       headerLen,
2392     const SSL3Opaque * input,
2393     int                inputLength,
2394     unsigned char *    outbuf,
2395     unsigned int *     outLength)
2396 {
2397     const ssl3MACDef * mac_def;
2398     SECStatus          rv;
2399
2400     PRINT_BUF(95, (NULL, "frag hash1: header", header, headerLen));
2401     PRINT_BUF(95, (NULL, "frag hash1: input", input, inputLength));
2402
2403     mac_def = spec->mac_def;
2404     if (mac_def->mac == mac_null) {
2405         *outLength = 0;
2406         return SECSuccess;
2407     }
2408 #ifndef NO_PKCS11_BYPASS
2409     if (spec->bypassCiphers) {
2410         /* bypass version */
2411         const SECHashObject *hashObj = NULL;
2412         unsigned int       pad_bytes = 0;
2413         PRUint64           write_mac_context[MAX_MAC_CONTEXT_LLONGS];
2414
2415         switch (mac_def->mac) {
2416         case ssl_mac_null:
2417             *outLength = 0;
2418             return SECSuccess;
2419         case ssl_mac_md5:
2420             pad_bytes = 48;
2421             hashObj = HASH_GetRawHashObject(HASH_AlgMD5);
2422             break;
2423         case ssl_mac_sha:
2424             pad_bytes = 40;
2425             hashObj = HASH_GetRawHashObject(HASH_AlgSHA1);
2426             break;
2427         case ssl_hmac_md5: /* used with TLS */
2428             hashObj = HASH_GetRawHashObject(HASH_AlgMD5);
2429             break;
2430         case ssl_hmac_sha: /* used with TLS */
2431             hashObj = HASH_GetRawHashObject(HASH_AlgSHA1);
2432             break;
2433         case ssl_hmac_sha256: /* used with TLS */
2434             hashObj = HASH_GetRawHashObject(HASH_AlgSHA256);
2435             break;
2436         default:
2437             break;
2438         }
2439         if (!hashObj) {
2440             PORT_Assert(0);
2441             PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2442             return SECFailure;
2443         }
2444
2445         if (spec->version <= SSL_LIBRARY_VERSION_3_0) {
2446             unsigned int tempLen;
2447             unsigned char temp[MAX_MAC_LENGTH];
2448
2449             /* compute "inner" part of SSL3 MAC */
2450             hashObj->begin(write_mac_context);
2451             if (useServerMacKey)
2452                 hashObj->update(write_mac_context, 
2453                                 spec->server.write_mac_key_item.data,
2454                                 spec->server.write_mac_key_item.len);
2455             else
2456                 hashObj->update(write_mac_context, 
2457                                 spec->client.write_mac_key_item.data,
2458                                 spec->client.write_mac_key_item.len);
2459             hashObj->update(write_mac_context, mac_pad_1, pad_bytes);
2460             hashObj->update(write_mac_context, header, headerLen);
2461             hashObj->update(write_mac_context, input, inputLength);
2462             hashObj->end(write_mac_context,    temp, &tempLen, sizeof temp);
2463
2464             /* compute "outer" part of SSL3 MAC */
2465             hashObj->begin(write_mac_context);
2466             if (useServerMacKey)
2467                 hashObj->update(write_mac_context, 
2468                                 spec->server.write_mac_key_item.data,
2469                                 spec->server.write_mac_key_item.len);
2470             else
2471                 hashObj->update(write_mac_context, 
2472                                 spec->client.write_mac_key_item.data,
2473                                 spec->client.write_mac_key_item.len);
2474             hashObj->update(write_mac_context, mac_pad_2, pad_bytes);
2475             hashObj->update(write_mac_context, temp, tempLen);
2476             hashObj->end(write_mac_context, outbuf, outLength, spec->mac_size);
2477             rv = SECSuccess;
2478         } else { /* is TLS */
2479 #define cx ((HMACContext *)write_mac_context)
2480             if (useServerMacKey) {
2481                 rv = HMAC_Init(cx, hashObj, 
2482                                spec->server.write_mac_key_item.data,
2483                                spec->server.write_mac_key_item.len, PR_FALSE);
2484             } else {
2485                 rv = HMAC_Init(cx, hashObj, 
2486                                spec->client.write_mac_key_item.data,
2487                                spec->client.write_mac_key_item.len, PR_FALSE);
2488             }
2489             if (rv == SECSuccess) {
2490                 HMAC_Begin(cx);
2491                 HMAC_Update(cx, header, headerLen);
2492                 HMAC_Update(cx, input, inputLength);
2493                 rv = HMAC_Finish(cx, outbuf, outLength, spec->mac_size);
2494                 HMAC_Destroy(cx, PR_FALSE);
2495             }
2496 #undef cx
2497         }
2498     } else
2499 #endif
2500     {
2501         PK11Context *mac_context = 
2502             (useServerMacKey ? spec->server.write_mac_context
2503                              : spec->client.write_mac_context);
2504         rv  = PK11_DigestBegin(mac_context);
2505         rv |= PK11_DigestOp(mac_context, header, headerLen);
2506         rv |= PK11_DigestOp(mac_context, input, inputLength);
2507         rv |= PK11_DigestFinal(mac_context, outbuf, outLength, spec->mac_size);
2508     }
2509
2510     PORT_Assert(rv != SECSuccess || *outLength == (unsigned)spec->mac_size);
2511
2512     PRINT_BUF(95, (NULL, "frag hash2: result", outbuf, *outLength));
2513
2514     if (rv != SECSuccess) {
2515         rv = SECFailure;
2516         ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
2517     }
2518     return rv;
2519 }
2520
2521 /* Called from: ssl3_HandleRecord()
2522  * Caller must already hold the SpecReadLock. (wish we could assert that!)
2523  *
2524  * On entry:
2525  *   originalLen >= inputLen >= MAC size
2526 */
2527 static SECStatus
2528 ssl3_ComputeRecordMACConstantTime(
2529     ssl3CipherSpec *   spec,
2530     PRBool             useServerMacKey,
2531     const unsigned char *header,
2532     unsigned int       headerLen,
2533     const SSL3Opaque * input,
2534     int                inputLen,
2535     int                originalLen,
2536     unsigned char *    outbuf,
2537     unsigned int *     outLen)
2538 {
2539     CK_MECHANISM_TYPE            macType;
2540     CK_NSS_MAC_CONSTANT_TIME_PARAMS params;
2541     SECItem                      param, inputItem, outputItem;
2542     SECStatus                    rv;
2543     PK11SymKey *                 key;
2544
2545     PORT_Assert(inputLen >= spec->mac_size);
2546     PORT_Assert(originalLen >= inputLen);
2547
2548     if (spec->bypassCiphers) {
2549         /* This function doesn't support PKCS#11 bypass. We fallback on the
2550          * non-constant time version. */
2551         goto fallback;
2552     }
2553
2554     if (spec->mac_def->mac == mac_null) {
2555         *outLen = 0;
2556         return SECSuccess;
2557     }
2558
2559     macType = CKM_NSS_HMAC_CONSTANT_TIME;
2560     if (spec->version <= SSL_LIBRARY_VERSION_3_0) {
2561         macType = CKM_NSS_SSL3_MAC_CONSTANT_TIME;
2562     }
2563
2564     params.macAlg = spec->mac_def->mmech;
2565     params.ulBodyTotalLen = originalLen;
2566     params.pHeader = (unsigned char *) header;  /* const cast */
2567     params.ulHeaderLen = headerLen;
2568
2569     param.data = (unsigned char*) &params;
2570     param.len = sizeof(params);
2571     param.type = 0;
2572
2573     inputItem.data = (unsigned char *) input;
2574     inputItem.len = inputLen;
2575     inputItem.type = 0;
2576
2577     outputItem.data = outbuf;
2578     outputItem.len = *outLen;
2579     outputItem.type = 0;
2580
2581     key = spec->server.write_mac_key;
2582     if (!useServerMacKey) {
2583         key = spec->client.write_mac_key;
2584     }
2585
2586     rv = PK11_SignWithSymKey(key, macType, &param, &outputItem, &inputItem);
2587     if (rv != SECSuccess) {
2588         if (PORT_GetError() == SEC_ERROR_INVALID_ALGORITHM) {
2589             goto fallback;
2590         }
2591
2592         *outLen = 0;
2593         rv = SECFailure;
2594         ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
2595         return rv;
2596     }
2597
2598     PORT_Assert(outputItem.len == (unsigned)spec->mac_size);
2599     *outLen = outputItem.len;
2600
2601     return rv;
2602
2603 fallback:
2604     /* ssl3_ComputeRecordMAC expects the MAC to have been removed from the
2605      * length already. */
2606     inputLen -= spec->mac_size;
2607     return ssl3_ComputeRecordMAC(spec, useServerMacKey, header, headerLen,
2608                                  input, inputLen, outbuf, outLen);
2609 }
2610
2611 static PRBool
2612 ssl3_ClientAuthTokenPresent(sslSessionID *sid) {
2613     PK11SlotInfo *slot = NULL;
2614     PRBool isPresent = PR_TRUE;
2615
2616     /* we only care if we are doing client auth */
2617     /* If NSS_PLATFORM_CLIENT_AUTH is defined and a platformClientKey is being
2618      * used, u.ssl3.clAuthValid will be false and this function will always
2619      * return PR_TRUE. */
2620     if (!sid || !sid->u.ssl3.clAuthValid) {
2621         return PR_TRUE;
2622     }
2623
2624     /* get the slot */
2625     slot = SECMOD_LookupSlot(sid->u.ssl3.clAuthModuleID,
2626                              sid->u.ssl3.clAuthSlotID);
2627     if (slot == NULL ||
2628         !PK11_IsPresent(slot) ||
2629         sid->u.ssl3.clAuthSeries     != PK11_GetSlotSeries(slot) ||
2630         sid->u.ssl3.clAuthSlotID     != PK11_GetSlotID(slot)     ||
2631         sid->u.ssl3.clAuthModuleID   != PK11_GetModuleID(slot)   ||
2632         (PK11_NeedLogin(slot) && !PK11_IsLoggedIn(slot, NULL))) {
2633         isPresent = PR_FALSE;
2634     } 
2635     if (slot) {
2636         PK11_FreeSlot(slot);
2637     }
2638     return isPresent;
2639 }
2640
2641 /* Caller must hold the spec read lock. */
2642 SECStatus
2643 ssl3_CompressMACEncryptRecord(ssl3CipherSpec *   cwSpec,
2644                               PRBool             isServer,
2645                               PRBool             isDTLS,
2646                               PRBool             capRecordVersion,
2647                               SSL3ContentType    type,
2648                               const SSL3Opaque * pIn,
2649                               PRUint32           contentLen,
2650                               sslBuffer *        wrBuf)
2651 {
2652     const ssl3BulkCipherDef * cipher_def;
2653     SECStatus                 rv;
2654     PRUint32                  macLen = 0;
2655     PRUint32                  fragLen;
2656     PRUint32  p1Len, p2Len, oddLen = 0;
2657     PRUint16                  headerLen;
2658     int                       ivLen = 0;
2659     int                       cipherBytes = 0;
2660     unsigned char             pseudoHeader[13];
2661     unsigned int              pseudoHeaderLen;
2662
2663     cipher_def = cwSpec->cipher_def;
2664     headerLen = isDTLS ? DTLS_RECORD_HEADER_LENGTH : SSL3_RECORD_HEADER_LENGTH;
2665
2666     if (cipher_def->type == type_block &&
2667         cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
2668         /* Prepend the per-record explicit IV using technique 2b from
2669          * RFC 4346 section 6.2.3.2: The IV is a cryptographically
2670          * strong random number XORed with the CBC residue from the previous
2671          * record.
2672          */
2673         ivLen = cipher_def->iv_size;
2674         if (ivLen > wrBuf->space - headerLen) {
2675             PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2676             return SECFailure;
2677         }
2678         rv = PK11_GenerateRandom(wrBuf->buf + headerLen, ivLen);
2679         if (rv != SECSuccess) {
2680             ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
2681             return rv;
2682         }
2683         rv = cwSpec->encode( cwSpec->encodeContext, 
2684             wrBuf->buf + headerLen,
2685             &cipherBytes,                       /* output and actual outLen */
2686             ivLen,                              /* max outlen */
2687             wrBuf->buf + headerLen,
2688             ivLen);                             /* input and inputLen*/
2689         if (rv != SECSuccess || cipherBytes != ivLen) {
2690             PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
2691             return SECFailure;
2692         }
2693     }
2694
2695     if (cwSpec->compressor) {
2696         int outlen;
2697         rv = cwSpec->compressor(
2698             cwSpec->compressContext,
2699             wrBuf->buf + headerLen + ivLen, &outlen,
2700             wrBuf->space - headerLen - ivLen, pIn, contentLen);
2701         if (rv != SECSuccess)
2702             return rv;
2703         pIn = wrBuf->buf + headerLen + ivLen;
2704         contentLen = outlen;
2705     }
2706
2707     pseudoHeaderLen = ssl3_BuildRecordPseudoHeader(
2708         pseudoHeader, cwSpec->write_seq_num, type,
2709         cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_0, cwSpec->version,
2710         isDTLS, contentLen);
2711     PORT_Assert(pseudoHeaderLen <= sizeof(pseudoHeader));
2712     if (cipher_def->type == type_aead) {
2713         const int nonceLen = cipher_def->explicit_nonce_size;
2714         const int tagLen = cipher_def->tag_size;
2715
2716         if (headerLen + nonceLen + contentLen + tagLen > wrBuf->space) {
2717             PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2718             return SECFailure;
2719         }
2720
2721         cipherBytes = contentLen;
2722         rv = cwSpec->aead(
2723                 isServer ? &cwSpec->server : &cwSpec->client,
2724                 PR_FALSE,                                   /* do encrypt */
2725                 wrBuf->buf + headerLen,                     /* output  */
2726                 &cipherBytes,                               /* out len */
2727                 wrBuf->space - headerLen,                   /* max out */
2728                 pIn, contentLen,                            /* input   */
2729                 pseudoHeader, pseudoHeaderLen);
2730         if (rv != SECSuccess) {
2731             PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
2732             return SECFailure;
2733         }
2734     } else {
2735         /*
2736          * Add the MAC
2737          */
2738         rv = ssl3_ComputeRecordMAC(cwSpec, isServer,
2739             pseudoHeader, pseudoHeaderLen, pIn, contentLen,
2740             wrBuf->buf + headerLen + ivLen + contentLen, &macLen);
2741         if (rv != SECSuccess) {
2742             ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
2743             return SECFailure;
2744         }
2745         p1Len   = contentLen;
2746         p2Len   = macLen;
2747         fragLen = contentLen + macLen;  /* needs to be encrypted */
2748         PORT_Assert(fragLen <= MAX_FRAGMENT_LENGTH + 1024);
2749
2750         /*
2751          * Pad the text (if we're doing a block cipher)
2752          * then Encrypt it
2753          */
2754         if (cipher_def->type == type_block) {
2755             unsigned char * pBuf;
2756             int             padding_length;
2757             int             i;
2758
2759             oddLen = contentLen % cipher_def->block_size;
2760             /* Assume blockSize is a power of two */
2761             padding_length = cipher_def->block_size - 1 -
2762                             ((fragLen) & (cipher_def->block_size - 1));
2763             fragLen += padding_length + 1;
2764             PORT_Assert((fragLen % cipher_def->block_size) == 0);
2765
2766             /* Pad according to TLS rules (also acceptable to SSL3). */
2767             pBuf = &wrBuf->buf[headerLen + ivLen + fragLen - 1];
2768             for (i = padding_length + 1; i > 0; --i) {
2769                 *pBuf-- = padding_length;
2770             }
2771             /* now, if contentLen is not a multiple of block size, fix it */
2772             p2Len = fragLen - p1Len;
2773         }
2774         if (p1Len < 256) {
2775             oddLen = p1Len;
2776             p1Len = 0;
2777         } else {
2778             p1Len -= oddLen;
2779         }
2780         if (oddLen) {
2781             p2Len += oddLen;
2782             PORT_Assert( (cipher_def->block_size < 2) || \
2783                          (p2Len % cipher_def->block_size) == 0);
2784             memmove(wrBuf->buf + headerLen + ivLen + p1Len, pIn + p1Len,
2785                     oddLen);
2786         }
2787         if (p1Len > 0) {
2788             int cipherBytesPart1 = -1;
2789             rv = cwSpec->encode( cwSpec->encodeContext, 
2790                 wrBuf->buf + headerLen + ivLen,         /* output */
2791                 &cipherBytesPart1,                      /* actual outlen */
2792                 p1Len,                                  /* max outlen */
2793                 pIn, p1Len);                      /* input, and inputlen */
2794             PORT_Assert(rv == SECSuccess && cipherBytesPart1 == (int) p1Len);
2795             if (rv != SECSuccess || cipherBytesPart1 != (int) p1Len) {
2796                 PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
2797                 return SECFailure;
2798             }
2799             cipherBytes += cipherBytesPart1;
2800         }
2801         if (p2Len > 0) {
2802             int cipherBytesPart2 = -1;
2803             rv = cwSpec->encode( cwSpec->encodeContext, 
2804                 wrBuf->buf + headerLen + ivLen + p1Len,
2805                 &cipherBytesPart2,          /* output and actual outLen */
2806                 p2Len,                             /* max outlen */
2807                 wrBuf->buf + headerLen + ivLen + p1Len,
2808                 p2Len);                            /* input and inputLen*/
2809             PORT_Assert(rv == SECSuccess && cipherBytesPart2 == (int) p2Len);
2810             if (rv != SECSuccess || cipherBytesPart2 != (int) p2Len) {
2811                 PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
2812                 return SECFailure;
2813             }
2814             cipherBytes += cipherBytesPart2;
2815         }
2816     }
2817
2818     PORT_Assert(cipherBytes <= MAX_FRAGMENT_LENGTH + 1024);
2819
2820     wrBuf->len    = cipherBytes + headerLen;
2821     wrBuf->buf[0] = type;
2822     if (isDTLS) {
2823         SSL3ProtocolVersion version;
2824
2825         version = dtls_TLSVersionToDTLSVersion(cwSpec->version);
2826         wrBuf->buf[1] = MSB(version);
2827         wrBuf->buf[2] = LSB(version);
2828         wrBuf->buf[3] = (unsigned char)(cwSpec->write_seq_num.high >> 24);
2829         wrBuf->buf[4] = (unsigned char)(cwSpec->write_seq_num.high >> 16);
2830         wrBuf->buf[5] = (unsigned char)(cwSpec->write_seq_num.high >>  8);
2831         wrBuf->buf[6] = (unsigned char)(cwSpec->write_seq_num.high >>  0);
2832         wrBuf->buf[7] = (unsigned char)(cwSpec->write_seq_num.low  >> 24);
2833         wrBuf->buf[8] = (unsigned char)(cwSpec->write_seq_num.low  >> 16);
2834         wrBuf->buf[9] = (unsigned char)(cwSpec->write_seq_num.low  >>  8);
2835         wrBuf->buf[10] = (unsigned char)(cwSpec->write_seq_num.low >>  0);
2836         wrBuf->buf[11] = MSB(cipherBytes);
2837         wrBuf->buf[12] = LSB(cipherBytes);
2838     } else {
2839         SSL3ProtocolVersion version = cwSpec->version;
2840
2841         if (capRecordVersion) {
2842             version = PR_MIN(SSL_LIBRARY_VERSION_TLS_1_0, version);
2843         }
2844         wrBuf->buf[1] = MSB(version);
2845         wrBuf->buf[2] = LSB(version);
2846         wrBuf->buf[3] = MSB(cipherBytes);
2847         wrBuf->buf[4] = LSB(cipherBytes);
2848     }
2849
2850     ssl3_BumpSequenceNumber(&cwSpec->write_seq_num);
2851
2852     return SECSuccess;
2853 }
2854
2855 /* Process the plain text before sending it.
2856  * Returns the number of bytes of plaintext that were successfully sent
2857  *      plus the number of bytes of plaintext that were copied into the
2858  *      output (write) buffer.
2859  * Returns SECFailure on a hard IO error, memory error, or crypto error.
2860  * Does NOT return SECWouldBlock.
2861  *
2862  * Notes on the use of the private ssl flags:
2863  * (no private SSL flags)
2864  *    Attempt to make and send SSL records for all plaintext
2865  *    If non-blocking and a send gets WOULD_BLOCK,
2866  *    or if the pending (ciphertext) buffer is not empty,
2867  *    then buffer remaining bytes of ciphertext into pending buf,
2868  *    and continue to do that for all succssive records until all
2869  *    bytes are used.
2870  * ssl_SEND_FLAG_FORCE_INTO_BUFFER
2871  *    As above, except this suppresses all write attempts, and forces
2872  *    all ciphertext into the pending ciphertext buffer.
2873  * ssl_SEND_FLAG_USE_EPOCH (for DTLS)
2874  *    Forces the use of the provided epoch
2875  * ssl_SEND_FLAG_CAP_RECORD_VERSION
2876  *    Caps the record layer version number of TLS ClientHello to { 3, 1 }
2877  *    (TLS 1.0). Some TLS 1.0 servers (which seem to use F5 BIG-IP) ignore
2878  *    ClientHello.client_version and use the record layer version number
2879  *    (TLSPlaintext.version) instead when negotiating protocol versions. In
2880  *    addition, if the record layer version number of ClientHello is { 3, 2 }
2881  *    (TLS 1.1) or higher, these servers reset the TCP connections. Lastly,
2882  *    some F5 BIG-IP servers hang if a record containing a ClientHello has a
2883  *    version greater than { 3, 1 } and a length greater than 255. Set this
2884  *    flag to work around such servers.
2885  */
2886 PRInt32
2887 ssl3_SendRecord(   sslSocket *        ss,
2888                    DTLSEpoch          epoch, /* DTLS only */
2889                    SSL3ContentType    type,
2890                    const SSL3Opaque * pIn,   /* input buffer */
2891                    PRInt32            nIn,   /* bytes of input */
2892                    PRInt32            flags)
2893 {
2894     sslBuffer      *          wrBuf       = &ss->sec.writeBuf;
2895     SECStatus                 rv;
2896     PRInt32                   totalSent   = 0;
2897     PRBool                    capRecordVersion;
2898
2899     SSL_TRC(3, ("%d: SSL3[%d] SendRecord type: %s nIn=%d",
2900                 SSL_GETPID(), ss->fd, ssl3_DecodeContentType(type),
2901                 nIn));
2902     PRINT_BUF(50, (ss, "Send record (plain text)", pIn, nIn));
2903
2904     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
2905
2906     capRecordVersion = ((flags & ssl_SEND_FLAG_CAP_RECORD_VERSION) != 0);
2907
2908     if (capRecordVersion) {
2909         /* ssl_SEND_FLAG_CAP_RECORD_VERSION can only be used with the
2910          * TLS initial ClientHello. */
2911         PORT_Assert(!IS_DTLS(ss));
2912         PORT_Assert(!ss->firstHsDone);
2913         PORT_Assert(type == content_handshake);
2914         PORT_Assert(ss->ssl3.hs.ws == wait_server_hello);
2915     }
2916
2917     if (ss->ssl3.initialized == PR_FALSE) {
2918         /* This can happen on a server if the very first incoming record
2919         ** looks like a defective ssl3 record (e.g. too long), and we're
2920         ** trying to send an alert.
2921         */
2922         PR_ASSERT(type == content_alert);
2923         rv = ssl3_InitState(ss);
2924         if (rv != SECSuccess) {
2925             return SECFailure;  /* ssl3_InitState has set the error code. */
2926         }
2927     }
2928
2929     /* check for Token Presence */
2930     if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) {
2931         PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
2932         return SECFailure;
2933     }
2934
2935     while (nIn > 0) {
2936         PRUint32  contentLen = PR_MIN(nIn, MAX_FRAGMENT_LENGTH);
2937         unsigned int spaceNeeded;
2938         unsigned int numRecords;
2939
2940         ssl_GetSpecReadLock(ss);    /********************************/
2941
2942         if (nIn > 1 && ss->opt.cbcRandomIV &&
2943             ss->ssl3.cwSpec->version < SSL_LIBRARY_VERSION_TLS_1_1 &&
2944             type == content_application_data &&
2945             ss->ssl3.cwSpec->cipher_def->type == type_block /* CBC mode */) {
2946             /* We will split the first byte of the record into its own record,
2947              * as explained in the documentation for SSL_CBC_RANDOM_IV in ssl.h
2948              */
2949             numRecords = 2;
2950         } else {
2951             numRecords = 1;
2952         }
2953
2954         spaceNeeded = contentLen + (numRecords * SSL3_BUFFER_FUDGE);
2955         if (ss->ssl3.cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1 &&
2956             ss->ssl3.cwSpec->cipher_def->type == type_block) {
2957             spaceNeeded += ss->ssl3.cwSpec->cipher_def->iv_size;
2958         }
2959         if (spaceNeeded > wrBuf->space) {
2960             rv = sslBuffer_Grow(wrBuf, spaceNeeded);
2961             if (rv != SECSuccess) {
2962                 SSL_DBG(("%d: SSL3[%d]: SendRecord, tried to get %d bytes",
2963                          SSL_GETPID(), ss->fd, spaceNeeded));
2964                 goto spec_locked_loser; /* sslBuffer_Grow set error code. */
2965             }
2966         }
2967
2968         if (numRecords == 2) {
2969             sslBuffer secondRecord;
2970
2971             rv = ssl3_CompressMACEncryptRecord(ss->ssl3.cwSpec,
2972                                                ss->sec.isServer, IS_DTLS(ss),
2973                                                capRecordVersion, type, pIn,
2974                                                1, wrBuf);
2975             if (rv != SECSuccess)
2976                 goto spec_locked_loser;
2977
2978             PRINT_BUF(50, (ss, "send (encrypted) record data [1/2]:",
2979                            wrBuf->buf, wrBuf->len));
2980
2981             secondRecord.buf = wrBuf->buf + wrBuf->len;
2982             secondRecord.len = 0;
2983             secondRecord.space = wrBuf->space - wrBuf->len;
2984
2985             rv = ssl3_CompressMACEncryptRecord(ss->ssl3.cwSpec,
2986                                                ss->sec.isServer, IS_DTLS(ss),
2987                                                capRecordVersion, type,
2988                                                pIn + 1, contentLen - 1,
2989                                                &secondRecord);
2990             if (rv == SECSuccess) {
2991                 PRINT_BUF(50, (ss, "send (encrypted) record data [2/2]:",
2992                                secondRecord.buf, secondRecord.len));
2993                 wrBuf->len += secondRecord.len;
2994             }
2995         } else {
2996             if (!IS_DTLS(ss)) {
2997                 rv = ssl3_CompressMACEncryptRecord(ss->ssl3.cwSpec,
2998                                                    ss->sec.isServer,
2999                                                    IS_DTLS(ss),
3000                                                    capRecordVersion,
3001                                                    type, pIn,
3002                                                    contentLen, wrBuf);
3003             } else {
3004                 rv = dtls_CompressMACEncryptRecord(ss, epoch,
3005                                                    !!(flags & ssl_SEND_FLAG_USE_EPOCH),
3006                                                    type, pIn,
3007                                                    contentLen, wrBuf);
3008             }
3009
3010             if (rv == SECSuccess) {
3011                 PRINT_BUF(50, (ss, "send (encrypted) record data:",
3012                                wrBuf->buf, wrBuf->len));
3013             }
3014         }
3015
3016 spec_locked_loser:
3017         ssl_ReleaseSpecReadLock(ss); /************************************/
3018
3019         if (rv != SECSuccess)
3020             return SECFailure;
3021
3022         pIn += contentLen;
3023         nIn -= contentLen;
3024         PORT_Assert( nIn >= 0 );
3025
3026         /* If there's still some previously saved ciphertext,
3027          * or the caller doesn't want us to send the data yet,
3028          * then add all our new ciphertext to the amount previously saved.
3029          */
3030         if ((ss->pendingBuf.len > 0) ||
3031             (flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) {
3032
3033             rv = ssl_SaveWriteData(ss, wrBuf->buf, wrBuf->len);
3034             if (rv != SECSuccess) {
3035                 /* presumably a memory error, SEC_ERROR_NO_MEMORY */
3036                 return SECFailure;
3037             }
3038             wrBuf->len = 0;     /* All cipher text is saved away. */
3039
3040             if (!(flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) {
3041                 PRInt32   sent;
3042                 ss->handshakeBegun = 1;
3043                 sent = ssl_SendSavedWriteData(ss);
3044                 if (sent < 0 && PR_GetError() != PR_WOULD_BLOCK_ERROR) {
3045                     ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE);
3046                     return SECFailure;
3047                 }
3048                 if (ss->pendingBuf.len) {
3049                     flags |= ssl_SEND_FLAG_FORCE_INTO_BUFFER;
3050                 }
3051             }
3052         } else if (wrBuf->len > 0) {
3053             PRInt32   sent;
3054             ss->handshakeBegun = 1;
3055             sent = ssl_DefSend(ss, wrBuf->buf, wrBuf->len,
3056                                flags & ~ssl_SEND_FLAG_MASK);
3057             if (sent < 0) {
3058                 if (PR_GetError() != PR_WOULD_BLOCK_ERROR) {
3059                     ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE);
3060                     return SECFailure;
3061                 }
3062                 /* we got PR_WOULD_BLOCK_ERROR, which means none was sent. */
3063                 sent = 0;
3064             }
3065             wrBuf->len -= sent;
3066             if (wrBuf->len) {
3067                 if (IS_DTLS(ss)) {
3068                     /* DTLS just says no in this case. No buffering */
3069                     PR_SetError(PR_WOULD_BLOCK_ERROR, 0);
3070                     return SECFailure;
3071                 }
3072                 /* now take all the remaining unsent new ciphertext and 
3073                  * append it to the buffer of previously unsent ciphertext.
3074                  */
3075                 rv = ssl_SaveWriteData(ss, wrBuf->buf + sent, wrBuf->len);
3076                 if (rv != SECSuccess) {
3077                     /* presumably a memory error, SEC_ERROR_NO_MEMORY */
3078                     return SECFailure;
3079                 }
3080             }
3081         }
3082         totalSent += contentLen;
3083     }
3084     return totalSent;
3085 }
3086
3087 #define SSL3_PENDING_HIGH_WATER 1024
3088
3089 /* Attempt to send the content of "in" in an SSL application_data record.
3090  * Returns "len" or SECFailure,   never SECWouldBlock, nor SECSuccess.
3091  */
3092 int
3093 ssl3_SendApplicationData(sslSocket *ss, const unsigned char *in,
3094                          PRInt32 len, PRInt32 flags)
3095 {
3096     PRInt32   totalSent = 0;
3097     PRInt32   discarded = 0;
3098
3099     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
3100     /* These flags for internal use only */
3101     PORT_Assert(!(flags & (ssl_SEND_FLAG_USE_EPOCH |
3102                            ssl_SEND_FLAG_NO_RETRANSMIT)));
3103     if (len < 0 || !in) {
3104         PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
3105         return SECFailure;
3106     }
3107
3108     if (ss->pendingBuf.len > SSL3_PENDING_HIGH_WATER &&
3109         !ssl_SocketIsBlocking(ss)) {
3110         PORT_Assert(!ssl_SocketIsBlocking(ss));
3111         PORT_SetError(PR_WOULD_BLOCK_ERROR);
3112         return SECFailure;
3113     }
3114
3115     if (ss->appDataBuffered && len) {
3116         PORT_Assert (in[0] == (unsigned char)(ss->appDataBuffered));
3117         if (in[0] != (unsigned char)(ss->appDataBuffered)) {
3118             PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
3119             return SECFailure;
3120         }
3121         in++;
3122         len--;
3123         discarded = 1;
3124     }
3125     while (len > totalSent) {
3126         PRInt32   sent, toSend;
3127
3128         if (totalSent > 0) {
3129             /*
3130              * The thread yield is intended to give the reader thread a
3131              * chance to get some cycles while the writer thread is in
3132              * the middle of a large application data write.  (See
3133              * Bugzilla bug 127740, comment #1.)
3134              */
3135             ssl_ReleaseXmitBufLock(ss);
3136             PR_Sleep(PR_INTERVAL_NO_WAIT);      /* PR_Yield(); */
3137             ssl_GetXmitBufLock(ss);
3138         }
3139         toSend = PR_MIN(len - totalSent, MAX_FRAGMENT_LENGTH);
3140         /*
3141          * Note that the 0 epoch is OK because flags will never require 
3142          * its use, as guaranteed by the PORT_Assert above.
3143          */
3144         sent = ssl3_SendRecord(ss, 0, content_application_data,
3145                                in + totalSent, toSend, flags);
3146         if (sent < 0) {
3147             if (totalSent > 0 && PR_GetError() == PR_WOULD_BLOCK_ERROR) {
3148                 PORT_Assert(ss->lastWriteBlocked);
3149                 break;
3150             }
3151             return SECFailure; /* error code set by ssl3_SendRecord */
3152         }
3153         totalSent += sent;
3154         if (ss->pendingBuf.len) {
3155             /* must be a non-blocking socket */
3156             PORT_Assert(!ssl_SocketIsBlocking(ss));
3157             PORT_Assert(ss->lastWriteBlocked);
3158             break;      
3159         }
3160     }
3161     if (ss->pendingBuf.len) {
3162         /* Must be non-blocking. */
3163         PORT_Assert(!ssl_SocketIsBlocking(ss));
3164         if (totalSent > 0) {
3165             ss->appDataBuffered = 0x100 | in[totalSent - 1];
3166         }
3167
3168         totalSent = totalSent + discarded - 1;
3169         if (totalSent <= 0) {
3170             PORT_SetError(PR_WOULD_BLOCK_ERROR);
3171             totalSent = SECFailure;
3172         }
3173         return totalSent;
3174     } 
3175     ss->appDataBuffered = 0;
3176     return totalSent + discarded;
3177 }
3178
3179 /* Attempt to send buffered handshake messages.
3180  * This function returns SECSuccess or SECFailure, never SECWouldBlock.
3181  * Always set sendBuf.len to 0, even when returning SECFailure.
3182  *
3183  * Depending on whether we are doing DTLS or not, this either calls
3184  *
3185  * - ssl3_FlushHandshakeMessages if non-DTLS
3186  * - dtls_FlushHandshakeMessages if DTLS
3187  *
3188  * Called from SSL3_SendAlert(), ssl3_SendChangeCipherSpecs(),
3189  *             ssl3_AppendHandshake(), ssl3_SendClientHello(),
3190  *             ssl3_SendHelloRequest(), ssl3_SendServerHelloDone(),
3191  *             ssl3_SendFinished(),
3192  */
3193 static SECStatus
3194 ssl3_FlushHandshake(sslSocket *ss, PRInt32 flags)
3195 {
3196     if (IS_DTLS(ss)) {
3197         return dtls_FlushHandshakeMessages(ss, flags);
3198     } else {
3199         return ssl3_FlushHandshakeMessages(ss, flags);
3200     }
3201 }
3202
3203 /* Attempt to send the content of sendBuf buffer in an SSL handshake record.
3204  * This function returns SECSuccess or SECFailure, never SECWouldBlock.
3205  * Always set sendBuf.len to 0, even when returning SECFailure.
3206  *
3207  * Called from ssl3_FlushHandshake
3208  */
3209 static SECStatus
3210 ssl3_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags)
3211 {
3212     static const PRInt32 allowedFlags = ssl_SEND_FLAG_FORCE_INTO_BUFFER |
3213                                         ssl_SEND_FLAG_CAP_RECORD_VERSION;
3214     PRInt32 rv = SECSuccess;
3215
3216     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3217     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
3218
3219     if (!ss->sec.ci.sendBuf.buf || !ss->sec.ci.sendBuf.len)
3220         return rv;
3221
3222     /* only these flags are allowed */
3223     PORT_Assert(!(flags & ~allowedFlags));
3224     if ((flags & ~allowedFlags) != 0) {
3225         PORT_SetError(SEC_ERROR_INVALID_ARGS);
3226         rv = SECFailure;
3227     } else {
3228         rv = ssl3_SendRecord(ss, 0, content_handshake, ss->sec.ci.sendBuf.buf,
3229                              ss->sec.ci.sendBuf.len, flags);
3230     }
3231     if (rv < 0) { 
3232         int err = PORT_GetError();
3233         PORT_Assert(err != PR_WOULD_BLOCK_ERROR);
3234         if (err == PR_WOULD_BLOCK_ERROR) {
3235             PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
3236         }
3237     } else if (rv < ss->sec.ci.sendBuf.len) {
3238         /* short write should never happen */
3239         PORT_Assert(rv >= ss->sec.ci.sendBuf.len);
3240         PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
3241         rv = SECFailure;
3242     } else {
3243         rv = SECSuccess;
3244     }
3245
3246     /* Whether we succeeded or failed, toss the old handshake data. */
3247     ss->sec.ci.sendBuf.len = 0;
3248     return rv;
3249 }
3250
3251 /*
3252  * Called from ssl3_HandleAlert and from ssl3_HandleCertificate when
3253  * the remote client sends a negative response to our certificate request.
3254  * Returns SECFailure if the application has required client auth.
3255  *         SECSuccess otherwise.
3256  */
3257 static SECStatus
3258 ssl3_HandleNoCertificate(sslSocket *ss)
3259 {
3260     if (ss->sec.peerCert != NULL) {
3261         if (ss->sec.peerKey != NULL) {
3262             SECKEY_DestroyPublicKey(ss->sec.peerKey);
3263             ss->sec.peerKey = NULL;
3264         }
3265         CERT_DestroyCertificate(ss->sec.peerCert);
3266         ss->sec.peerCert = NULL;
3267     }
3268     ssl3_CleanupPeerCerts(ss);
3269
3270     /* If the server has required client-auth blindly but doesn't
3271      * actually look at the certificate it won't know that no
3272      * certificate was presented so we shutdown the socket to ensure
3273      * an error.  We only do this if we haven't already completed the
3274      * first handshake because if we're redoing the handshake we 
3275      * know the server is paying attention to the certificate.
3276      */
3277     if ((ss->opt.requireCertificate == SSL_REQUIRE_ALWAYS) ||
3278         (!ss->firstHsDone && 
3279          (ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE))) {
3280         PRFileDesc * lower;
3281
3282         if (ss->sec.uncache)
3283             ss->sec.uncache(ss->sec.ci.sid);
3284         SSL3_SendAlert(ss, alert_fatal, bad_certificate);
3285
3286         lower = ss->fd->lower;
3287 #ifdef _WIN32
3288         lower->methods->shutdown(lower, PR_SHUTDOWN_SEND);
3289 #else
3290         lower->methods->shutdown(lower, PR_SHUTDOWN_BOTH);
3291 #endif
3292         PORT_SetError(SSL_ERROR_NO_CERTIFICATE);
3293         return SECFailure;
3294     }
3295     return SECSuccess;
3296 }
3297
3298 /************************************************************************
3299  * Alerts
3300  */
3301
3302 /*
3303 ** Acquires both handshake and XmitBuf locks.
3304 ** Called from: ssl3_IllegalParameter   <-
3305 **              ssl3_HandshakeFailure   <-
3306 **              ssl3_HandleAlert        <- ssl3_HandleRecord.
3307 **              ssl3_HandleChangeCipherSpecs <- ssl3_HandleRecord
3308 **              ssl3_ConsumeHandshakeVariable <-
3309 **              ssl3_HandleHelloRequest <-
3310 **              ssl3_HandleServerHello  <-
3311 **              ssl3_HandleServerKeyExchange <-
3312 **              ssl3_HandleCertificateRequest <-
3313 **              ssl3_HandleServerHelloDone <-
3314 **              ssl3_HandleClientHello  <-
3315 **              ssl3_HandleV2ClientHello <-
3316 **              ssl3_HandleCertificateVerify <-
3317 **              ssl3_HandleClientKeyExchange <-
3318 **              ssl3_HandleCertificate  <-
3319 **              ssl3_HandleFinished     <-
3320 **              ssl3_HandleHandshakeMessage <-
3321 **              ssl3_HandleRecord       <-
3322 **
3323 */
3324 SECStatus
3325 SSL3_SendAlert(sslSocket *ss, SSL3AlertLevel level, SSL3AlertDescription desc)
3326 {
3327     PRUint8     bytes[2];
3328     SECStatus   rv;
3329
3330     SSL_TRC(3, ("%d: SSL3[%d]: send alert record, level=%d desc=%d",
3331                 SSL_GETPID(), ss->fd, level, desc));
3332
3333     bytes[0] = level;
3334     bytes[1] = desc;
3335
3336     ssl_GetSSL3HandshakeLock(ss);
3337     if (level == alert_fatal) {
3338         if (!ss->opt.noCache && ss->sec.ci.sid && ss->sec.uncache) {
3339             ss->sec.uncache(ss->sec.ci.sid);
3340         }
3341     }
3342     ssl_GetXmitBufLock(ss);
3343     rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
3344     if (rv == SECSuccess) {
3345         PRInt32 sent;
3346         sent = ssl3_SendRecord(ss, 0, content_alert, bytes, 2, 
3347                                desc == no_certificate 
3348                                ? ssl_SEND_FLAG_FORCE_INTO_BUFFER : 0);
3349         rv = (sent >= 0) ? SECSuccess : (SECStatus)sent;
3350     }
3351     ssl_ReleaseXmitBufLock(ss);
3352     ssl_ReleaseSSL3HandshakeLock(ss);
3353     return rv;  /* error set by ssl3_FlushHandshake or ssl3_SendRecord */
3354 }
3355
3356 /*
3357  * Send illegal_parameter alert.  Set generic error number.
3358  */
3359 static SECStatus
3360 ssl3_IllegalParameter(sslSocket *ss)
3361 {
3362     (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
3363     PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
3364                                    : SSL_ERROR_BAD_SERVER );
3365     return SECFailure;
3366 }
3367
3368 /*
3369  * Send handshake_Failure alert.  Set generic error number.
3370  */
3371 static SECStatus
3372 ssl3_HandshakeFailure(sslSocket *ss)
3373 {
3374     (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure);
3375     PORT_SetError( ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
3376                                     : SSL_ERROR_BAD_SERVER );
3377     return SECFailure;
3378 }
3379
3380 static void
3381 ssl3_SendAlertForCertError(sslSocket * ss, PRErrorCode errCode)
3382 {
3383     SSL3AlertDescription desc   = bad_certificate;
3384     PRBool isTLS = ss->version >= SSL_LIBRARY_VERSION_3_1_TLS;
3385
3386     switch (errCode) {
3387     case SEC_ERROR_LIBRARY_FAILURE:     desc = unsupported_certificate; break;
3388     case SEC_ERROR_EXPIRED_CERTIFICATE: desc = certificate_expired;     break;
3389     case SEC_ERROR_REVOKED_CERTIFICATE: desc = certificate_revoked;     break;
3390     case SEC_ERROR_INADEQUATE_KEY_USAGE:
3391     case SEC_ERROR_INADEQUATE_CERT_TYPE:
3392                                         desc = certificate_unknown;     break;
3393     case SEC_ERROR_UNTRUSTED_CERT:
3394                     desc = isTLS ? access_denied : certificate_unknown; break;
3395     case SEC_ERROR_UNKNOWN_ISSUER:      
3396     case SEC_ERROR_UNTRUSTED_ISSUER:    
3397                     desc = isTLS ? unknown_ca : certificate_unknown; break;
3398     case SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE:
3399                     desc = isTLS ? unknown_ca : certificate_expired; break;
3400
3401     case SEC_ERROR_CERT_NOT_IN_NAME_SPACE:
3402     case SEC_ERROR_PATH_LEN_CONSTRAINT_INVALID:
3403     case SEC_ERROR_CA_CERT_INVALID:
3404     case SEC_ERROR_BAD_SIGNATURE:
3405     default:                            desc = bad_certificate;     break;
3406     }
3407     SSL_DBG(("%d: SSL3[%d]: peer certificate is no good: error=%d",
3408              SSL_GETPID(), ss->fd, errCode));
3409
3410     (void) SSL3_SendAlert(ss, alert_fatal, desc);
3411 }
3412
3413
3414 /*
3415  * Send decode_error alert.  Set generic error number.
3416  */
3417 SECStatus
3418 ssl3_DecodeError(sslSocket *ss)
3419 {
3420     (void)SSL3_SendAlert(ss, alert_fatal, 
3421                   ss->version > SSL_LIBRARY_VERSION_3_0 ? decode_error 
3422                                                         : illegal_parameter);
3423     PORT_SetError( ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
3424                                     : SSL_ERROR_BAD_SERVER );
3425     return SECFailure;
3426 }
3427
3428 /* Called from ssl3_HandleRecord.
3429 ** Caller must hold both RecvBuf and Handshake locks.
3430 */
3431 static SECStatus
3432 ssl3_HandleAlert(sslSocket *ss, sslBuffer *buf)
3433 {
3434     SSL3AlertLevel       level;
3435     SSL3AlertDescription desc;
3436     int                  error;
3437
3438     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
3439     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
3440
3441     SSL_TRC(3, ("%d: SSL3[%d]: handle alert record", SSL_GETPID(), ss->fd));
3442
3443     if (buf->len != 2) {
3444         (void)ssl3_DecodeError(ss);
3445         PORT_SetError(SSL_ERROR_RX_MALFORMED_ALERT);
3446         return SECFailure;
3447     }
3448     level = (SSL3AlertLevel)buf->buf[0];
3449     desc  = (SSL3AlertDescription)buf->buf[1];
3450     buf->len = 0;
3451     SSL_TRC(5, ("%d: SSL3[%d] received alert, level = %d, description = %d",
3452         SSL_GETPID(), ss->fd, level, desc));
3453
3454     switch (desc) {
3455     case close_notify:          ss->recvdCloseNotify = 1;
3456                                 error = SSL_ERROR_CLOSE_NOTIFY_ALERT;     break;
3457     case unexpected_message:    error = SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT;
3458                                                                           break;
3459     case bad_record_mac:        error = SSL_ERROR_BAD_MAC_ALERT;          break;
3460     case decryption_failed_RESERVED:
3461                                 error = SSL_ERROR_DECRYPTION_FAILED_ALERT; 
3462                                                                           break;
3463     case record_overflow:       error = SSL_ERROR_RECORD_OVERFLOW_ALERT;  break;
3464     case decompression_failure: error = SSL_ERROR_DECOMPRESSION_FAILURE_ALERT;
3465                                                                           break;
3466     case handshake_failure:     error = SSL_ERROR_HANDSHAKE_FAILURE_ALERT;
3467                                                                           break;
3468     case no_certificate:        error = SSL_ERROR_NO_CERTIFICATE;         break;
3469     case bad_certificate:       error = SSL_ERROR_BAD_CERT_ALERT;         break;
3470     case unsupported_certificate:error = SSL_ERROR_UNSUPPORTED_CERT_ALERT;break;
3471     case certificate_revoked:   error = SSL_ERROR_REVOKED_CERT_ALERT;     break;
3472     case certificate_expired:   error = SSL_ERROR_EXPIRED_CERT_ALERT;     break;
3473     case certificate_unknown:   error = SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT;
3474                                                                           break;
3475     case illegal_parameter:     error = SSL_ERROR_ILLEGAL_PARAMETER_ALERT;break;
3476     case inappropriate_fallback:
3477         error = SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT;
3478         break;
3479
3480     /* All alerts below are TLS only. */
3481     case unknown_ca:            error = SSL_ERROR_UNKNOWN_CA_ALERT;       break;
3482     case access_denied:         error = SSL_ERROR_ACCESS_DENIED_ALERT;    break;
3483     case decode_error:          error = SSL_ERROR_DECODE_ERROR_ALERT;     break;
3484     case decrypt_error:         error = SSL_ERROR_DECRYPT_ERROR_ALERT;    break;
3485     case export_restriction:    error = SSL_ERROR_EXPORT_RESTRICTION_ALERT; 
3486                                                                           break;
3487     case protocol_version:      error = SSL_ERROR_PROTOCOL_VERSION_ALERT; break;
3488     case insufficient_security: error = SSL_ERROR_INSUFFICIENT_SECURITY_ALERT; 
3489                                                                           break;
3490     case internal_error:        error = SSL_ERROR_INTERNAL_ERROR_ALERT;   break;
3491     case user_canceled:         error = SSL_ERROR_USER_CANCELED_ALERT;    break;
3492     case no_renegotiation:      error = SSL_ERROR_NO_RENEGOTIATION_ALERT; break;
3493
3494     /* Alerts for TLS client hello extensions */
3495     case unsupported_extension: 
3496                         error = SSL_ERROR_UNSUPPORTED_EXTENSION_ALERT;    break;
3497     case certificate_unobtainable: 
3498                         error = SSL_ERROR_CERTIFICATE_UNOBTAINABLE_ALERT; break;
3499     case unrecognized_name: 
3500                         error = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;        break;
3501     case bad_certificate_status_response: 
3502                         error = SSL_ERROR_BAD_CERT_STATUS_RESPONSE_ALERT; break;
3503     case bad_certificate_hash_value: 
3504                         error = SSL_ERROR_BAD_CERT_HASH_VALUE_ALERT;      break;
3505     default:            error = SSL_ERROR_RX_UNKNOWN_ALERT;               break;
3506     }
3507     if (level == alert_fatal) {
3508         if (!ss->opt.noCache) {
3509             if (ss->sec.uncache)
3510                 ss->sec.uncache(ss->sec.ci.sid);
3511         }
3512         if ((ss->ssl3.hs.ws == wait_server_hello) &&
3513             (desc == handshake_failure)) {
3514             /* XXX This is a hack.  We're assuming that any handshake failure
3515              * XXX on the client hello is a failure to match ciphers.
3516              */
3517             error = SSL_ERROR_NO_CYPHER_OVERLAP;
3518         }
3519         PORT_SetError(error);
3520         return SECFailure;
3521     }
3522     if ((desc == no_certificate) && (ss->ssl3.hs.ws == wait_client_cert)) {
3523         /* I'm a server. I've requested a client cert. He hasn't got one. */
3524         SECStatus rv;
3525
3526         PORT_Assert(ss->sec.isServer);
3527         ss->ssl3.hs.ws = wait_client_key;
3528         rv = ssl3_HandleNoCertificate(ss);
3529         return rv;
3530     }
3531     return SECSuccess;
3532 }
3533
3534 /*
3535  * Change Cipher Specs
3536  * Called from ssl3_HandleServerHelloDone,
3537  *             ssl3_HandleClientHello,
3538  * and         ssl3_HandleFinished
3539  *
3540  * Acquires and releases spec write lock, to protect switching the current
3541  * and pending write spec pointers.
3542  */
3543
3544 static SECStatus
3545 ssl3_SendChangeCipherSpecs(sslSocket *ss)
3546 {
3547     PRUint8           change = change_cipher_spec_choice;
3548     ssl3CipherSpec *  pwSpec;
3549     SECStatus         rv;
3550     PRInt32           sent;
3551
3552     SSL_TRC(3, ("%d: SSL3[%d]: send change_cipher_spec record",
3553                 SSL_GETPID(), ss->fd));
3554
3555     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
3556     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3557
3558     rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
3559     if (rv != SECSuccess) {
3560         return rv;      /* error code set by ssl3_FlushHandshake */
3561     }
3562     if (!IS_DTLS(ss)) {
3563         sent = ssl3_SendRecord(ss, 0, content_change_cipher_spec, &change, 1,
3564                                ssl_SEND_FLAG_FORCE_INTO_BUFFER);
3565         if (sent < 0) {
3566             return (SECStatus)sent;     /* error code set by ssl3_SendRecord */
3567         }
3568     } else {
3569         rv = dtls_QueueMessage(ss, content_change_cipher_spec, &change, 1);
3570         if (rv != SECSuccess) {
3571             return rv;
3572         }
3573     }
3574
3575     /* swap the pending and current write specs. */
3576     ssl_GetSpecWriteLock(ss);   /**************************************/
3577     pwSpec                     = ss->ssl3.pwSpec;
3578
3579     ss->ssl3.pwSpec = ss->ssl3.cwSpec;
3580     ss->ssl3.cwSpec = pwSpec;
3581
3582     SSL_TRC(3, ("%d: SSL3[%d] Set Current Write Cipher Suite to Pending",
3583                 SSL_GETPID(), ss->fd ));
3584
3585     /* We need to free up the contexts, keys and certs ! */
3586     /* If we are really through with the old cipher spec
3587      * (Both the read and write sides have changed) destroy it.
3588      */
3589     if (ss->ssl3.prSpec == ss->ssl3.pwSpec) {
3590         if (!IS_DTLS(ss)) {
3591             ssl3_DestroyCipherSpec(ss->ssl3.pwSpec, PR_FALSE/*freeSrvName*/);
3592         } else {
3593             /* With DTLS, we need to set a holddown timer in case the final
3594              * message got lost */
3595             ss->ssl3.hs.rtTimeoutMs = DTLS_FINISHED_TIMER_MS;
3596             dtls_StartTimer(ss, dtls_FinishedTimerCb);
3597         }
3598     }
3599     ssl_ReleaseSpecWriteLock(ss); /**************************************/
3600
3601     return SECSuccess;
3602 }
3603
3604 /* Called from ssl3_HandleRecord.
3605 ** Caller must hold both RecvBuf and Handshake locks.
3606  *
3607  * Acquires and releases spec write lock, to protect switching the current
3608  * and pending write spec pointers.
3609 */
3610 static SECStatus
3611 ssl3_HandleChangeCipherSpecs(sslSocket *ss, sslBuffer *buf)
3612 {
3613     ssl3CipherSpec *           prSpec;
3614     SSL3WaitState              ws      = ss->ssl3.hs.ws;
3615     SSL3ChangeCipherSpecChoice change;
3616
3617     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
3618     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
3619
3620     SSL_TRC(3, ("%d: SSL3[%d]: handle change_cipher_spec record",
3621                 SSL_GETPID(), ss->fd));
3622
3623     if (ws != wait_change_cipher) {
3624         if (IS_DTLS(ss)) {
3625             /* Ignore this because it's out of order. */
3626             SSL_TRC(3, ("%d: SSL3[%d]: discard out of order "
3627                         "DTLS change_cipher_spec",
3628                         SSL_GETPID(), ss->fd));
3629             buf->len = 0;
3630             return SECSuccess;
3631         }
3632         (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
3633         PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER);
3634         return SECFailure;
3635     }
3636
3637     if(buf->len != 1) {
3638         (void)ssl3_DecodeError(ss);
3639         PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER);
3640         return SECFailure;
3641     }
3642     change = (SSL3ChangeCipherSpecChoice)buf->buf[0];
3643     if (change != change_cipher_spec_choice) {
3644         /* illegal_parameter is correct here for both SSL3 and TLS. */
3645         (void)ssl3_IllegalParameter(ss);
3646         PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER);
3647         return SECFailure;
3648     }
3649     buf->len = 0;
3650
3651     /* Swap the pending and current read specs. */
3652     ssl_GetSpecWriteLock(ss);   /*************************************/
3653     prSpec                    = ss->ssl3.prSpec;
3654
3655     ss->ssl3.prSpec  = ss->ssl3.crSpec;
3656     ss->ssl3.crSpec  = prSpec;
3657     ss->ssl3.hs.ws   = wait_finished;
3658
3659     SSL_TRC(3, ("%d: SSL3[%d] Set Current Read Cipher Suite to Pending",
3660                 SSL_GETPID(), ss->fd ));
3661
3662     /* If we are really through with the old cipher prSpec
3663      * (Both the read and write sides have changed) destroy it.
3664      */
3665     if (ss->ssl3.prSpec == ss->ssl3.pwSpec) {
3666         ssl3_DestroyCipherSpec(ss->ssl3.prSpec, PR_FALSE/*freeSrvName*/);
3667     }
3668     ssl_ReleaseSpecWriteLock(ss);   /*************************************/
3669     return SECSuccess;
3670 }
3671
3672 /* This method uses PKCS11 to derive the MS from the PMS, where PMS 
3673 ** is a PKCS11 symkey. This is used in all cases except the 
3674 ** "triple bypass" with RSA key exchange.
3675 ** Called from ssl3_InitPendingCipherSpec.   prSpec is pwSpec.
3676 */
3677 static SECStatus
3678 ssl3_DeriveMasterSecret(sslSocket *ss, PK11SymKey *pms)
3679 {
3680     ssl3CipherSpec *  pwSpec = ss->ssl3.pwSpec;
3681     const ssl3KEADef *kea_def= ss->ssl3.hs.kea_def;
3682     unsigned char *   cr     = (unsigned char *)&ss->ssl3.hs.client_random;
3683     unsigned char *   sr     = (unsigned char *)&ss->ssl3.hs.server_random;
3684     PRBool            isTLS  = (PRBool)(kea_def->tls_keygen ||
3685                                 (pwSpec->version > SSL_LIBRARY_VERSION_3_0));
3686     PRBool            isTLS12=
3687             (PRBool)(isTLS && pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
3688     /* 
3689      * Whenever isDH is true, we need to use CKM_TLS_MASTER_KEY_DERIVE_DH
3690      * which, unlike CKM_TLS_MASTER_KEY_DERIVE, converts arbitrary size
3691      * data into a 48-byte value. 
3692      */
3693     PRBool    isDH = (PRBool) ((ss->ssl3.hs.kea_def->exchKeyType == kt_dh) ||
3694                                (ss->ssl3.hs.kea_def->exchKeyType == kt_ecdh));
3695     SECStatus         rv = SECFailure;
3696     CK_MECHANISM_TYPE master_derive;
3697     CK_MECHANISM_TYPE key_derive;
3698     SECItem           params;
3699     CK_FLAGS          keyFlags;
3700     CK_VERSION        pms_version;
3701     CK_SSL3_MASTER_KEY_DERIVE_PARAMS master_params;
3702
3703     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3704     PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
3705     PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
3706     if (isTLS12) {
3707         if(isDH) master_derive = CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256;
3708         else master_derive = CKM_NSS_TLS_MASTER_KEY_DERIVE_SHA256;
3709         key_derive    = CKM_NSS_TLS_KEY_AND_MAC_DERIVE_SHA256;
3710         keyFlags      = CKF_SIGN | CKF_VERIFY;
3711     } else if (isTLS) {
3712         if(isDH) master_derive = CKM_TLS_MASTER_KEY_DERIVE_DH;
3713         else master_derive = CKM_TLS_MASTER_KEY_DERIVE;
3714         key_derive    = CKM_TLS_KEY_AND_MAC_DERIVE;
3715         keyFlags      = CKF_SIGN | CKF_VERIFY;
3716     } else {
3717         if (isDH) master_derive = CKM_SSL3_MASTER_KEY_DERIVE_DH;
3718         else master_derive = CKM_SSL3_MASTER_KEY_DERIVE;
3719         key_derive    = CKM_SSL3_KEY_AND_MAC_DERIVE;
3720         keyFlags      = 0;
3721     }
3722
3723     if (pms || !pwSpec->master_secret) {
3724         if (isDH) {
3725             master_params.pVersion                     = NULL;
3726         } else {
3727             master_params.pVersion                     = &pms_version;
3728         }
3729         master_params.RandomInfo.pClientRandom     = cr;
3730         master_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH;
3731         master_params.RandomInfo.pServerRandom     = sr;
3732         master_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH;
3733
3734         params.data = (unsigned char *) &master_params;
3735         params.len  = sizeof master_params;
3736     }
3737
3738     if (pms != NULL) {
3739 #if defined(TRACE)
3740         if (ssl_trace >= 100) {
3741             SECStatus extractRV = PK11_ExtractKeyValue(pms);
3742             if (extractRV == SECSuccess) {
3743                 SECItem * keyData = PK11_GetKeyData(pms);
3744                 if (keyData && keyData->data && keyData->len) {
3745                     ssl_PrintBuf(ss, "Pre-Master Secret", 
3746                                  keyData->data, keyData->len);
3747                 }
3748             }
3749         }
3750 #endif
3751         pwSpec->master_secret = PK11_DeriveWithFlags(pms, master_derive, 
3752                                 &params, key_derive, CKA_DERIVE, 0, keyFlags);
3753         if (!isDH && pwSpec->master_secret && ss->opt.detectRollBack) {
3754             SSL3ProtocolVersion client_version;
3755             client_version = pms_version.major << 8 | pms_version.minor;
3756
3757             if (IS_DTLS(ss)) {
3758                 client_version = dtls_DTLSVersionToTLSVersion(client_version);
3759             }
3760
3761             if (client_version != ss->clientHelloVersion) {
3762                 /* Destroy it.  Version roll-back detected. */
3763                 PK11_FreeSymKey(pwSpec->master_secret);
3764                 pwSpec->master_secret = NULL;
3765             }
3766         }
3767         if (pwSpec->master_secret == NULL) {
3768             /* Generate a faux master secret in the same slot as the old one. */
3769             PK11SlotInfo * slot = PK11_GetSlotFromKey((PK11SymKey *)pms);
3770             PK11SymKey *   fpms = ssl3_GenerateRSAPMS(ss, pwSpec, slot);
3771
3772             PK11_FreeSlot(slot);
3773             if (fpms != NULL) {
3774                 pwSpec->master_secret = PK11_DeriveWithFlags(fpms, 
3775                                         master_derive, &params, key_derive, 
3776                                         CKA_DERIVE, 0, keyFlags);
3777                 PK11_FreeSymKey(fpms);
3778             }
3779         }
3780     }
3781     if (pwSpec->master_secret == NULL) {
3782         /* Generate a faux master secret from the internal slot. */
3783         PK11SlotInfo *  slot = PK11_GetInternalSlot();
3784         PK11SymKey *    fpms = ssl3_GenerateRSAPMS(ss, pwSpec, slot);
3785
3786         PK11_FreeSlot(slot);
3787         if (fpms != NULL) {
3788             pwSpec->master_secret = PK11_DeriveWithFlags(fpms, 
3789                                         master_derive, &params, key_derive, 
3790                                         CKA_DERIVE, 0, keyFlags);
3791             if (pwSpec->master_secret == NULL) {
3792                 pwSpec->master_secret = fpms; /* use the fpms as the master. */
3793                 fpms = NULL;
3794             }
3795         }
3796         if (fpms) {
3797             PK11_FreeSymKey(fpms);
3798         }
3799     }
3800     if (pwSpec->master_secret == NULL) {
3801         ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3802         return rv;
3803     }
3804 #ifndef NO_PKCS11_BYPASS
3805     if (ss->opt.bypassPKCS11) {
3806         SECItem * keydata;
3807         /* In hope of doing a "double bypass", 
3808          * need to extract the master secret's value from the key object 
3809          * and store it raw in the sslSocket struct.
3810          */
3811         rv = PK11_ExtractKeyValue(pwSpec->master_secret);
3812         if (rv != SECSuccess) {
3813             return rv;
3814         } 
3815         /* This returns the address of the secItem inside the key struct,
3816          * not a copy or a reference.  So, there's no need to free it.
3817          */
3818         keydata = PK11_GetKeyData(pwSpec->master_secret);
3819         if (keydata && keydata->len <= sizeof pwSpec->raw_master_secret) {
3820             memcpy(pwSpec->raw_master_secret, keydata->data, keydata->len);
3821             pwSpec->msItem.data = pwSpec->raw_master_secret;
3822             pwSpec->msItem.len  = keydata->len;
3823         } else {
3824             PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
3825             return SECFailure;
3826         }
3827     }
3828 #endif
3829     return SECSuccess;
3830 }
3831
3832
3833 /* 
3834  * Derive encryption and MAC Keys (and IVs) from master secret
3835  * Sets a useful error code when returning SECFailure.
3836  *
3837  * Called only from ssl3_InitPendingCipherSpec(),
3838  * which in turn is called from
3839  *              sendRSAClientKeyExchange        (for Full handshake)
3840  *              sendDHClientKeyExchange         (for Full handshake)
3841  *              ssl3_HandleClientKeyExchange    (for Full handshake)
3842  *              ssl3_HandleServerHello          (for session restart)
3843  *              ssl3_HandleClientHello          (for session restart)
3844  * Caller MUST hold the specWriteLock, and SSL3HandshakeLock.
3845  * ssl3_InitPendingCipherSpec does that.
3846  *
3847  */
3848 static SECStatus
3849 ssl3_DeriveConnectionKeysPKCS11(sslSocket *ss)
3850 {
3851     ssl3CipherSpec *         pwSpec     = ss->ssl3.pwSpec;
3852     const ssl3KEADef *       kea_def    = ss->ssl3.hs.kea_def;
3853     unsigned char *   cr     = (unsigned char *)&ss->ssl3.hs.client_random;
3854     unsigned char *   sr     = (unsigned char *)&ss->ssl3.hs.server_random;
3855     PRBool            isTLS  = (PRBool)(kea_def->tls_keygen ||
3856                                 (pwSpec->version > SSL_LIBRARY_VERSION_3_0));
3857     PRBool            isTLS12=
3858             (PRBool)(isTLS && pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
3859     /* following variables used in PKCS11 path */
3860     const ssl3BulkCipherDef *cipher_def = pwSpec->cipher_def;
3861     PK11SlotInfo *         slot   = NULL;
3862     PK11SymKey *           symKey = NULL;
3863     void *                 pwArg  = ss->pkcs11PinArg;
3864     int                    keySize;
3865     CK_SSL3_KEY_MAT_PARAMS key_material_params;
3866     CK_SSL3_KEY_MAT_OUT    returnedKeys;
3867     CK_MECHANISM_TYPE      key_derive;
3868     CK_MECHANISM_TYPE      bulk_mechanism;
3869     SSLCipherAlgorithm     calg;
3870     SECItem                params;
3871     PRBool         skipKeysAndIVs = (PRBool)(cipher_def->calg == calg_null);
3872
3873     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3874     PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
3875     PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
3876
3877     if (!pwSpec->master_secret) {
3878         PORT_SetError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3879         return SECFailure;
3880     }
3881     /*
3882      * generate the key material
3883      */
3884     key_material_params.ulMacSizeInBits = pwSpec->mac_size           * BPB;
3885     key_material_params.ulKeySizeInBits = cipher_def->secret_key_size* BPB;
3886     key_material_params.ulIVSizeInBits  = cipher_def->iv_size        * BPB;
3887     if (cipher_def->type == type_block &&
3888         pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
3889         /* Block ciphers in >= TLS 1.1 use a per-record, explicit IV. */
3890         key_material_params.ulIVSizeInBits = 0;
3891         memset(pwSpec->client.write_iv, 0, cipher_def->iv_size);
3892         memset(pwSpec->server.write_iv, 0, cipher_def->iv_size);
3893     }
3894
3895     key_material_params.bIsExport = (CK_BBOOL)(kea_def->is_limited);
3896
3897     key_material_params.RandomInfo.pClientRandom     = cr;
3898     key_material_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH;
3899     key_material_params.RandomInfo.pServerRandom     = sr;
3900     key_material_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH;
3901     key_material_params.pReturnedKeyMaterial         = &returnedKeys;
3902
3903     returnedKeys.pIVClient = pwSpec->client.write_iv;
3904     returnedKeys.pIVServer = pwSpec->server.write_iv;
3905     keySize                = cipher_def->key_size;
3906
3907     if (skipKeysAndIVs) {
3908         keySize                             = 0;
3909         key_material_params.ulKeySizeInBits = 0;
3910         key_material_params.ulIVSizeInBits  = 0;
3911         returnedKeys.pIVClient              = NULL;
3912         returnedKeys.pIVServer              = NULL;
3913     }
3914
3915     calg = cipher_def->calg;
3916     PORT_Assert(     alg2Mech[calg].calg == calg);
3917     bulk_mechanism = alg2Mech[calg].cmech;
3918
3919     params.data    = (unsigned char *)&key_material_params;
3920     params.len     = sizeof(key_material_params);
3921
3922     if (isTLS12) {
3923         key_derive    = CKM_NSS_TLS_KEY_AND_MAC_DERIVE_SHA256;
3924     } else if (isTLS) {
3925         key_derive    = CKM_TLS_KEY_AND_MAC_DERIVE;
3926     } else {
3927         key_derive    = CKM_SSL3_KEY_AND_MAC_DERIVE;
3928     }
3929
3930     /* CKM_SSL3_KEY_AND_MAC_DERIVE is defined to set ENCRYPT, DECRYPT, and
3931      * DERIVE by DEFAULT */
3932     symKey = PK11_Derive(pwSpec->master_secret, key_derive, &params,
3933                          bulk_mechanism, CKA_ENCRYPT, keySize);
3934     if (!symKey) {
3935         ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3936         return SECFailure;
3937     }
3938     /* we really should use the actual mac'ing mechanism here, but we
3939      * don't because these types are used to map keytype anyway and both
3940      * mac's map to the same keytype.
3941      */
3942     slot  = PK11_GetSlotFromKey(symKey);
3943
3944     PK11_FreeSlot(slot); /* slot is held until the key is freed */
3945     pwSpec->client.write_mac_key =
3946         PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive,
3947             CKM_SSL3_SHA1_MAC, returnedKeys.hClientMacSecret, PR_TRUE, pwArg);
3948     if (pwSpec->client.write_mac_key == NULL ) {
3949         goto loser;     /* loser sets err */
3950     }
3951     pwSpec->server.write_mac_key =
3952         PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive,
3953             CKM_SSL3_SHA1_MAC, returnedKeys.hServerMacSecret, PR_TRUE, pwArg);
3954     if (pwSpec->server.write_mac_key == NULL ) {
3955         goto loser;     /* loser sets err */
3956     }
3957     if (!skipKeysAndIVs) {
3958         pwSpec->client.write_key =
3959                 PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive,
3960                      bulk_mechanism, returnedKeys.hClientKey, PR_TRUE, pwArg);
3961         if (pwSpec->client.write_key == NULL ) {
3962             goto loser; /* loser sets err */
3963         }
3964         pwSpec->server.write_key =
3965                 PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive,
3966                      bulk_mechanism, returnedKeys.hServerKey, PR_TRUE, pwArg);
3967         if (pwSpec->server.write_key == NULL ) {
3968             goto loser; /* loser sets err */
3969         }
3970     }
3971     PK11_FreeSymKey(symKey);
3972     return SECSuccess;
3973
3974
3975 loser:
3976     if (symKey) PK11_FreeSymKey(symKey);
3977     ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3978     return SECFailure;
3979 }
3980
3981 /* ssl3_InitHandshakeHashes creates handshake hash contexts and hashes in
3982  * buffered messages in ss->ssl3.hs.messages. */
3983 static SECStatus
3984 ssl3_InitHandshakeHashes(sslSocket *ss)
3985 {
3986     SSL_TRC(30,("%d: SSL3[%d]: start handshake hashes", SSL_GETPID(), ss->fd));
3987
3988     PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_unknown);
3989 #ifndef NO_PKCS11_BYPASS
3990     if (ss->opt.bypassPKCS11) {
3991         PORT_Assert(!ss->ssl3.hs.sha_obj && !ss->ssl3.hs.sha_clone);
3992         if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
3993             /* If we ever support ciphersuites where the PRF hash isn't SHA-256
3994              * then this will need to be updated. */
3995             ss->ssl3.hs.sha_obj = HASH_GetRawHashObject(HASH_AlgSHA256);
3996             if (!ss->ssl3.hs.sha_obj) {
3997                 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
3998                 return SECFailure;
3999             }
4000             ss->ssl3.hs.sha_clone = (void (*)(void *, void *))SHA256_Clone;
4001             ss->ssl3.hs.hashType = handshake_hash_single;
4002             ss->ssl3.hs.sha_obj->begin(ss->ssl3.hs.sha_cx);
4003         } else {
4004             ss->ssl3.hs.hashType = handshake_hash_combo;
4005             MD5_Begin((MD5Context *)ss->ssl3.hs.md5_cx);
4006             SHA1_Begin((SHA1Context *)ss->ssl3.hs.sha_cx);
4007         }
4008     } else
4009 #endif
4010     {
4011         PORT_Assert(!ss->ssl3.hs.md5 && !ss->ssl3.hs.sha);
4012         /*
4013          * note: We should probably lookup an SSL3 slot for these
4014          * handshake hashes in hopes that we wind up with the same slots
4015          * that the master secret will wind up in ...
4016          */
4017         if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
4018             /* If we ever support ciphersuites where the PRF hash isn't SHA-256
4019              * then this will need to be updated. */
4020             ss->ssl3.hs.sha = PK11_CreateDigestContext(SEC_OID_SHA256);
4021             if (ss->ssl3.hs.sha == NULL) {
4022                 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4023                 return SECFailure;
4024             }
4025             ss->ssl3.hs.hashType = handshake_hash_single;
4026
4027             if (PK11_DigestBegin(ss->ssl3.hs.sha) != SECSuccess) {
4028                 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4029                 return SECFailure;
4030             }
4031
4032             /* Create a backup SHA-1 hash for a potential client auth
4033              * signature.
4034              *
4035              * In TLS 1.2, ssl3_ComputeHandshakeHashes always uses the
4036              * handshake hash function (SHA-256). If the server or the client
4037              * does not support SHA-256 as a signature hash, we can either
4038              * maintain a backup SHA-1 handshake hash or buffer all handshake
4039              * messages.
4040              */
4041             if (!ss->sec.isServer) {
4042                 ss->ssl3.hs.backupHash = PK11_CreateDigestContext(SEC_OID_SHA1);
4043                 if (ss->ssl3.hs.backupHash == NULL) {
4044                     ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4045                     return SECFailure;
4046                 }
4047
4048                 if (PK11_DigestBegin(ss->ssl3.hs.backupHash) != SECSuccess) {
4049                     ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4050                     return SECFailure;
4051                 }
4052             }
4053         } else {
4054             /* Both ss->ssl3.hs.md5 and ss->ssl3.hs.sha should be NULL or
4055              * created successfully. */
4056             ss->ssl3.hs.md5 = PK11_CreateDigestContext(SEC_OID_MD5);
4057             if (ss->ssl3.hs.md5 == NULL) {
4058                 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4059                 return SECFailure;
4060             }
4061             ss->ssl3.hs.sha = PK11_CreateDigestContext(SEC_OID_SHA1);
4062             if (ss->ssl3.hs.sha == NULL) {
4063                 PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE);
4064                 ss->ssl3.hs.md5 = NULL;
4065                 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4066                 return SECFailure;
4067             }
4068             ss->ssl3.hs.hashType = handshake_hash_combo;
4069
4070             if (PK11_DigestBegin(ss->ssl3.hs.md5) != SECSuccess) {
4071                 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4072                 return SECFailure;
4073             }
4074             if (PK11_DigestBegin(ss->ssl3.hs.sha) != SECSuccess) {
4075                 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4076                 return SECFailure;
4077             }
4078         }
4079     }
4080
4081     if (ss->ssl3.hs.messages.len > 0) {
4082         if (ssl3_UpdateHandshakeHashes(ss, ss->ssl3.hs.messages.buf,
4083                                        ss->ssl3.hs.messages.len) !=
4084             SECSuccess) {
4085             return SECFailure;
4086         }
4087         PORT_Free(ss->ssl3.hs.messages.buf);
4088         ss->ssl3.hs.messages.buf = NULL;
4089         ss->ssl3.hs.messages.len = 0;
4090         ss->ssl3.hs.messages.space = 0;
4091     }
4092
4093     return SECSuccess;
4094 }
4095
4096 static SECStatus 
4097 ssl3_RestartHandshakeHashes(sslSocket *ss)
4098 {
4099     SECStatus rv = SECSuccess;
4100
4101     SSL_TRC(30,("%d: SSL3[%d]: reset handshake hashes",
4102             SSL_GETPID(), ss->fd ));
4103     ss->ssl3.hs.hashType = handshake_hash_unknown;
4104     ss->ssl3.hs.messages.len = 0;
4105 #ifndef NO_PKCS11_BYPASS
4106     ss->ssl3.hs.sha_obj = NULL;
4107     ss->ssl3.hs.sha_clone = NULL;
4108 #endif
4109     if (ss->ssl3.hs.md5) {
4110         PK11_DestroyContext(ss->ssl3.hs.md5,PR_TRUE);
4111         ss->ssl3.hs.md5 = NULL;
4112     }
4113     if (ss->ssl3.hs.sha) {
4114         PK11_DestroyContext(ss->ssl3.hs.sha,PR_TRUE);
4115         ss->ssl3.hs.sha = NULL;
4116     }
4117     return rv;
4118 }
4119
4120 /*
4121  * Handshake messages
4122  */
4123 /* Called from  ssl3_InitHandshakeHashes()
4124 **              ssl3_AppendHandshake()
4125 **              ssl3_StartHandshakeHash()
4126 **              ssl3_HandleV2ClientHello()
4127 **              ssl3_HandleHandshakeMessage()
4128 ** Caller must hold the ssl3Handshake lock.
4129 */
4130 static SECStatus
4131 ssl3_UpdateHandshakeHashes(sslSocket *ss, const unsigned char *b,
4132                            unsigned int l)
4133 {
4134     SECStatus  rv = SECSuccess;
4135
4136     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
4137
4138     /* We need to buffer the handshake messages until we have established
4139      * which handshake hash function to use. */
4140     if (ss->ssl3.hs.hashType == handshake_hash_unknown) {
4141         return sslBuffer_Append(&ss->ssl3.hs.messages, b, l);
4142     }
4143
4144     PRINT_BUF(90, (NULL, "handshake hash input:", b, l));
4145
4146 #ifndef NO_PKCS11_BYPASS
4147     if (ss->opt.bypassPKCS11) {
4148         if (ss->ssl3.hs.hashType == handshake_hash_single) {
4149             ss->ssl3.hs.sha_obj->update(ss->ssl3.hs.sha_cx, b, l);
4150         } else {
4151             MD5_Update((MD5Context *)ss->ssl3.hs.md5_cx, b, l);
4152             SHA1_Update((SHA1Context *)ss->ssl3.hs.sha_cx, b, l);
4153         }
4154         return rv;
4155     }
4156 #endif
4157     if (ss->ssl3.hs.hashType == handshake_hash_single) {
4158         rv = PK11_DigestOp(ss->ssl3.hs.sha, b, l);
4159         if (rv != SECSuccess) {
4160             ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4161             return rv;
4162         }
4163         if (ss->ssl3.hs.backupHash) {
4164             rv = PK11_DigestOp(ss->ssl3.hs.backupHash, b, l);
4165             if (rv != SECSuccess) {
4166                 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4167                 return rv;
4168             }
4169         }
4170     } else {
4171         rv = PK11_DigestOp(ss->ssl3.hs.md5, b, l);
4172         if (rv != SECSuccess) {
4173             ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4174             return rv;
4175         }
4176         rv = PK11_DigestOp(ss->ssl3.hs.sha, b, l);
4177         if (rv != SECSuccess) {
4178             ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4179             return rv;
4180         }
4181     }
4182     return rv;
4183 }
4184
4185 /**************************************************************************
4186  * Append Handshake functions.
4187  * All these functions set appropriate error codes.
4188  * Most rely on ssl3_AppendHandshake to set the error code.
4189  **************************************************************************/
4190 SECStatus
4191 ssl3_AppendHandshake(sslSocket *ss, const void *void_src, PRInt32 bytes)
4192 {
4193     unsigned char *  src  = (unsigned char *)void_src;
4194     int              room = ss->sec.ci.sendBuf.space - ss->sec.ci.sendBuf.len;
4195     SECStatus        rv;
4196
4197     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); /* protects sendBuf. */
4198
4199     if (!bytes)
4200         return SECSuccess;
4201     if (ss->sec.ci.sendBuf.space < MAX_SEND_BUF_LENGTH && room < bytes) {
4202         rv = sslBuffer_Grow(&ss->sec.ci.sendBuf, PR_MAX(MIN_SEND_BUF_LENGTH,
4203                  PR_MIN(MAX_SEND_BUF_LENGTH, ss->sec.ci.sendBuf.len + bytes)));
4204         if (rv != SECSuccess)
4205             return rv;  /* sslBuffer_Grow has set a memory error code. */
4206         room = ss->sec.ci.sendBuf.space - ss->sec.ci.sendBuf.len;
4207     }
4208
4209     PRINT_BUF(60, (ss, "Append to Handshake", (unsigned char*)void_src, bytes));
4210     rv = ssl3_UpdateHandshakeHashes(ss, src, bytes);
4211     if (rv != SECSuccess)
4212         return rv;      /* error code set by ssl3_UpdateHandshakeHashes */
4213
4214     while (bytes > room) {
4215         if (room > 0)
4216             PORT_Memcpy(ss->sec.ci.sendBuf.buf + ss->sec.ci.sendBuf.len, src, 
4217                         room);
4218         ss->sec.ci.sendBuf.len += room;
4219         rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
4220         if (rv != SECSuccess) {
4221             return rv;  /* error code set by ssl3_FlushHandshake */
4222         }
4223         bytes -= room;
4224         src += room;
4225         room = ss->sec.ci.sendBuf.space;
4226         PORT_Assert(ss->sec.ci.sendBuf.len == 0);
4227     }
4228     PORT_Memcpy(ss->sec.ci.sendBuf.buf + ss->sec.ci.sendBuf.len, src, bytes);
4229     ss->sec.ci.sendBuf.len += bytes;
4230     return SECSuccess;
4231 }
4232
4233 SECStatus
4234 ssl3_AppendHandshakeNumber(sslSocket *ss, PRInt32 num, PRInt32 lenSize)
4235 {
4236     SECStatus rv;
4237     PRUint8   b[4];
4238     PRUint8 * p = b;
4239
4240     switch (lenSize) {
4241       case 4:
4242         *p++ = (num >> 24) & 0xff;
4243       case 3:
4244         *p++ = (num >> 16) & 0xff;
4245       case 2:
4246         *p++ = (num >> 8) & 0xff;
4247       case 1:
4248         *p = num & 0xff;
4249     }
4250     SSL_TRC(60, ("%d: number:", SSL_GETPID()));
4251     rv = ssl3_AppendHandshake(ss, &b[0], lenSize);
4252     return rv;  /* error code set by AppendHandshake, if applicable. */
4253 }
4254
4255 SECStatus
4256 ssl3_AppendHandshakeVariable(
4257     sslSocket *ss, const SSL3Opaque *src, PRInt32 bytes, PRInt32 lenSize)
4258 {
4259     SECStatus rv;
4260
4261     PORT_Assert((bytes < (1<<8) && lenSize == 1) ||
4262               (bytes < (1L<<16) && lenSize == 2) ||
4263               (bytes < (1L<<24) && lenSize == 3));
4264
4265     SSL_TRC(60,("%d: append variable:", SSL_GETPID()));
4266     rv = ssl3_AppendHandshakeNumber(ss, bytes, lenSize);
4267     if (rv != SECSuccess) {
4268         return rv;      /* error code set by AppendHandshake, if applicable. */
4269     }
4270     SSL_TRC(60, ("data:"));
4271     rv = ssl3_AppendHandshake(ss, src, bytes);
4272     return rv;  /* error code set by AppendHandshake, if applicable. */
4273 }
4274
4275 SECStatus
4276 ssl3_AppendHandshakeHeader(sslSocket *ss, SSL3HandshakeType t, PRUint32 length)
4277 {
4278     SECStatus rv;
4279
4280     /* If we already have a message in place, we need to enqueue it.
4281      * This empties the buffer. This is a convenient place to call
4282      * dtls_StageHandshakeMessage to mark the message boundary.
4283      */
4284     if (IS_DTLS(ss)) {
4285         rv = dtls_StageHandshakeMessage(ss);
4286         if (rv != SECSuccess) {
4287             return rv;
4288         }
4289     }
4290
4291     SSL_TRC(30,("%d: SSL3[%d]: append handshake header: type %s",
4292         SSL_GETPID(), ss->fd, ssl3_DecodeHandshakeType(t)));
4293
4294     rv = ssl3_AppendHandshakeNumber(ss, t, 1);
4295     if (rv != SECSuccess) {
4296         return rv;      /* error code set by AppendHandshake, if applicable. */
4297     }
4298     rv = ssl3_AppendHandshakeNumber(ss, length, 3);
4299     if (rv != SECSuccess) {
4300         return rv;      /* error code set by AppendHandshake, if applicable. */
4301     }
4302
4303     if (IS_DTLS(ss)) {
4304         /* Note that we make an unfragmented message here. We fragment in the
4305          * transmission code, if necessary */
4306         rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.sendMessageSeq, 2);
4307         if (rv != SECSuccess) {
4308             return rv;  /* error code set by AppendHandshake, if applicable. */
4309         }
4310         ss->ssl3.hs.sendMessageSeq++;
4311
4312         /* 0 is the fragment offset, because it's not fragmented yet */
4313         rv = ssl3_AppendHandshakeNumber(ss, 0, 3);
4314         if (rv != SECSuccess) {
4315             return rv;  /* error code set by AppendHandshake, if applicable. */
4316         }
4317
4318         /* Fragment length -- set to the packet length because not fragmented */
4319         rv = ssl3_AppendHandshakeNumber(ss, length, 3);
4320         if (rv != SECSuccess) {
4321             return rv;  /* error code set by AppendHandshake, if applicable. */
4322         }
4323     }
4324
4325     return rv;          /* error code set by AppendHandshake, if applicable. */
4326 }
4327
4328 /* ssl3_AppendSignatureAndHashAlgorithm appends the serialisation of
4329  * |sigAndHash| to the current handshake message. */
4330 SECStatus
4331 ssl3_AppendSignatureAndHashAlgorithm(
4332         sslSocket *ss, const SSL3SignatureAndHashAlgorithm* sigAndHash)
4333 {
4334     unsigned char serialized[2];
4335
4336     serialized[0] = ssl3_OIDToTLSHashAlgorithm(sigAndHash->hashAlg);
4337     if (serialized[0] == 0) {
4338         PORT_SetError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
4339         return SECFailure;
4340     }
4341
4342     serialized[1] = sigAndHash->sigAlg;
4343
4344     return ssl3_AppendHandshake(ss, serialized, sizeof(serialized));
4345 }
4346
4347 /**************************************************************************
4348  * Consume Handshake functions.
4349  *
4350  * All data used in these functions is protected by two locks,
4351  * the RecvBufLock and the SSL3HandshakeLock
4352  **************************************************************************/
4353
4354 /* Read up the next "bytes" number of bytes from the (decrypted) input
4355  * stream "b" (which is *length bytes long). Copy them into buffer "v".
4356  * Reduces *length by bytes.  Advances *b by bytes.
4357  *
4358  * If this function returns SECFailure, it has already sent an alert,
4359  * and has set a generic error code.  The caller should probably
4360  * override the generic error code by setting another.
4361  */
4362 SECStatus
4363 ssl3_ConsumeHandshake(sslSocket *ss, void *v, PRInt32 bytes, SSL3Opaque **b,
4364                       PRUint32 *length)
4365 {
4366     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
4367     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
4368
4369     if ((PRUint32)bytes > *length) {
4370         return ssl3_DecodeError(ss);
4371     }
4372     PORT_Memcpy(v, *b, bytes);
4373     PRINT_BUF(60, (ss, "consume bytes:", *b, bytes));
4374     *b      += bytes;
4375     *length -= bytes;
4376     return SECSuccess;
4377 }
4378
4379 /* Read up the next "bytes" number of bytes from the (decrypted) input
4380  * stream "b" (which is *length bytes long), and interpret them as an
4381  * integer in network byte order.  Returns the received value.
4382  * Reduces *length by bytes.  Advances *b by bytes.
4383  *
4384  * Returns SECFailure (-1) on failure.
4385  * This value is indistinguishable from the equivalent received value.
4386  * Only positive numbers are to be received this way.
4387  * Thus, the largest value that may be sent this way is 0x7fffffff.
4388  * On error, an alert has been sent, and a generic error code has been set.
4389  */
4390 PRInt32
4391 ssl3_ConsumeHandshakeNumber(sslSocket *ss, PRInt32 bytes, SSL3Opaque **b,
4392                             PRUint32 *length)
4393 {
4394     PRUint8  *buf = *b;
4395     int       i;
4396     PRInt32   num = 0;
4397
4398     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
4399     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
4400     PORT_Assert( bytes <= sizeof num);
4401
4402     if ((PRUint32)bytes > *length) {
4403         return ssl3_DecodeError(ss);
4404     }
4405     PRINT_BUF(60, (ss, "consume bytes:", *b, bytes));
4406
4407     for (i = 0; i < bytes; i++)
4408         num = (num << 8) + buf[i];
4409     *b      += bytes;
4410     *length -= bytes;
4411     return num;
4412 }
4413
4414 /* Read in two values from the incoming decrypted byte stream "b", which is
4415  * *length bytes long.  The first value is a number whose size is "bytes"
4416  * bytes long.  The second value is a byte-string whose size is the value
4417  * of the first number received.  The latter byte-string, and its length,
4418  * is returned in the SECItem i.
4419  *
4420  * Returns SECFailure (-1) on failure.
4421  * On error, an alert has been sent, and a generic error code has been set.
4422  *
4423  * RADICAL CHANGE for NSS 3.11.  All callers of this function make copies 
4424  * of the data returned in the SECItem *i, so making a copy of it here
4425  * is simply wasteful.  So, This function now just sets SECItem *i to 
4426  * point to the values in the buffer **b.
4427  */
4428 SECStatus
4429 ssl3_ConsumeHandshakeVariable(sslSocket *ss, SECItem *i, PRInt32 bytes,
4430                               SSL3Opaque **b, PRUint32 *length)
4431 {
4432     PRInt32   count;
4433
4434     PORT_Assert(bytes <= 3);
4435     i->len  = 0;
4436     i->data = NULL;
4437     count = ssl3_ConsumeHandshakeNumber(ss, bytes, b, length);
4438     if (count < 0) {            /* Can't test for SECSuccess here. */
4439         return SECFailure;
4440     }
4441     if (count > 0) {
4442         if ((PRUint32)count > *length) {
4443             return ssl3_DecodeError(ss);
4444         }
4445         i->data = *b;
4446         i->len  = count;
4447         *b      += count;
4448         *length -= count;
4449     }
4450     return SECSuccess;
4451 }
4452
4453 /* tlsHashOIDMap contains the mapping between TLS hash identifiers and the
4454  * SECOidTag used internally by NSS. */
4455 static const struct {
4456     int tlsHash;
4457     SECOidTag oid;
4458 } tlsHashOIDMap[] = {
4459     { tls_hash_md5, SEC_OID_MD5 },
4460     { tls_hash_sha1, SEC_OID_SHA1 },
4461     { tls_hash_sha224, SEC_OID_SHA224 },
4462     { tls_hash_sha256, SEC_OID_SHA256 },
4463     { tls_hash_sha384, SEC_OID_SHA384 },
4464     { tls_hash_sha512, SEC_OID_SHA512 }
4465 };
4466
4467 /* ssl3_TLSHashAlgorithmToOID converts a TLS hash identifier into an OID value.
4468  * If the hash is not recognised, SEC_OID_UNKNOWN is returned.
4469  *
4470  * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
4471 SECOidTag
4472 ssl3_TLSHashAlgorithmToOID(int hashFunc)
4473 {
4474     unsigned int i;
4475
4476     for (i = 0; i < PR_ARRAY_SIZE(tlsHashOIDMap); i++) {
4477         if (hashFunc == tlsHashOIDMap[i].tlsHash) {
4478             return tlsHashOIDMap[i].oid;
4479         }
4480     }
4481     return SEC_OID_UNKNOWN;
4482 }
4483
4484 /* ssl3_OIDToTLSHashAlgorithm converts an OID to a TLS hash algorithm
4485  * identifier. If the hash is not recognised, zero is returned.
4486  *
4487  * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
4488 static int
4489 ssl3_OIDToTLSHashAlgorithm(SECOidTag oid)
4490 {
4491     unsigned int i;
4492
4493     for (i = 0; i < PR_ARRAY_SIZE(tlsHashOIDMap); i++) {
4494         if (oid == tlsHashOIDMap[i].oid) {
4495             return tlsHashOIDMap[i].tlsHash;
4496         }
4497     }
4498     return 0;
4499 }
4500
4501 /* ssl3_TLSSignatureAlgorithmForKeyType returns the TLS 1.2 signature algorithm
4502  * identifier for a given KeyType. */
4503 static SECStatus
4504 ssl3_TLSSignatureAlgorithmForKeyType(KeyType keyType,
4505                                      TLSSignatureAlgorithm *out)
4506 {
4507     switch (keyType) {
4508     case rsaKey:
4509         *out = tls_sig_rsa;
4510         return SECSuccess;
4511     case dsaKey:
4512         *out = tls_sig_dsa;
4513         return SECSuccess;
4514     case ecKey:
4515         *out = tls_sig_ecdsa;
4516         return SECSuccess;
4517     default:
4518         PORT_SetError(SEC_ERROR_INVALID_KEY);
4519         return SECFailure;
4520     }
4521 }
4522
4523 /* ssl3_TLSSignatureAlgorithmForCertificate returns the TLS 1.2 signature
4524  * algorithm identifier for the given certificate. */
4525 static SECStatus
4526 ssl3_TLSSignatureAlgorithmForCertificate(CERTCertificate *cert,
4527                                          TLSSignatureAlgorithm *out)
4528 {
4529     SECKEYPublicKey *key;
4530     KeyType keyType;
4531
4532     key = CERT_ExtractPublicKey(cert);
4533     if (key == NULL) {
4534         ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
4535         return SECFailure;
4536     }
4537
4538     keyType = key->keyType;
4539     SECKEY_DestroyPublicKey(key);
4540     return ssl3_TLSSignatureAlgorithmForKeyType(keyType, out);
4541 }
4542
4543 /* ssl3_CheckSignatureAndHashAlgorithmConsistency checks that the signature
4544  * algorithm identifier in |sigAndHash| is consistent with the public key in
4545  * |cert|. If so, SECSuccess is returned. Otherwise, PORT_SetError is called
4546  * and SECFailure is returned. */
4547 SECStatus
4548 ssl3_CheckSignatureAndHashAlgorithmConsistency(
4549         const SSL3SignatureAndHashAlgorithm *sigAndHash, CERTCertificate* cert)
4550 {
4551     SECStatus rv;
4552     TLSSignatureAlgorithm sigAlg;
4553
4554     rv = ssl3_TLSSignatureAlgorithmForCertificate(cert, &sigAlg);
4555     if (rv != SECSuccess) {
4556         return rv;
4557     }
4558     if (sigAlg != sigAndHash->sigAlg) {
4559         PORT_SetError(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM);
4560         return SECFailure;
4561     }
4562     return SECSuccess;
4563 }
4564
4565 /* ssl3_ConsumeSignatureAndHashAlgorithm reads a SignatureAndHashAlgorithm
4566  * structure from |b| and puts the resulting value into |out|. |b| and |length|
4567  * are updated accordingly.
4568  *
4569  * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
4570 SECStatus
4571 ssl3_ConsumeSignatureAndHashAlgorithm(sslSocket *ss,
4572                                       SSL3Opaque **b,
4573                                       PRUint32 *length,
4574                                       SSL3SignatureAndHashAlgorithm *out)
4575 {
4576     unsigned char bytes[2];
4577     SECStatus rv;
4578
4579     rv = ssl3_ConsumeHandshake(ss, bytes, sizeof(bytes), b, length);
4580     if (rv != SECSuccess) {
4581         return rv;
4582     }
4583
4584     out->hashAlg = ssl3_TLSHashAlgorithmToOID(bytes[0]);
4585     if (out->hashAlg == SEC_OID_UNKNOWN) {
4586         PORT_SetError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
4587         return SECFailure;
4588     }
4589
4590     out->sigAlg = bytes[1];
4591     return SECSuccess;
4592 }
4593
4594 /**************************************************************************
4595  * end of Consume Handshake functions.
4596  **************************************************************************/
4597
4598 /* Extract the hashes of handshake messages to this point.
4599  * Called from ssl3_SendCertificateVerify
4600  *             ssl3_SendFinished
4601  *             ssl3_HandleHandshakeMessage
4602  *
4603  * Caller must hold the SSL3HandshakeLock.
4604  * Caller must hold a read or write lock on the Spec R/W lock.
4605  *      (There is presently no way to assert on a Read lock.)
4606  */
4607 static SECStatus
4608 ssl3_ComputeHandshakeHashes(sslSocket *     ss,
4609                             ssl3CipherSpec *spec,   /* uses ->master_secret */
4610                             SSL3Hashes *    hashes, /* output goes here. */
4611                             PRUint32        sender)
4612 {
4613     SECStatus     rv        = SECSuccess;
4614     PRBool        isTLS     = (PRBool)(spec->version > SSL_LIBRARY_VERSION_3_0);
4615     unsigned int  outLength;
4616     SSL3Opaque    md5_inner[MAX_MAC_LENGTH];
4617     SSL3Opaque    sha_inner[MAX_MAC_LENGTH];
4618
4619     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
4620     hashes->hashAlg = SEC_OID_UNKNOWN;
4621
4622 #ifndef NO_PKCS11_BYPASS
4623     if (ss->opt.bypassPKCS11 &&
4624         ss->ssl3.hs.hashType == handshake_hash_single) {
4625         /* compute them without PKCS11 */
4626         PRUint64      sha_cx[MAX_MAC_CONTEXT_LLONGS];
4627
4628         if (!spec->msItem.data) {
4629             PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
4630             return SECFailure;
4631         }
4632
4633         ss->ssl3.hs.sha_clone(sha_cx, ss->ssl3.hs.sha_cx);
4634         ss->ssl3.hs.sha_obj->end(sha_cx, hashes->u.raw, &hashes->len,
4635                                  sizeof(hashes->u.raw));
4636
4637         PRINT_BUF(60, (NULL, "SHA-256: result", hashes->u.raw, hashes->len));
4638
4639         /* If we ever support ciphersuites where the PRF hash isn't SHA-256
4640          * then this will need to be updated. */
4641         hashes->hashAlg = SEC_OID_SHA256;
4642         rv = SECSuccess;
4643     } else if (ss->opt.bypassPKCS11) {
4644         /* compute them without PKCS11 */
4645         PRUint64      md5_cx[MAX_MAC_CONTEXT_LLONGS];
4646         PRUint64      sha_cx[MAX_MAC_CONTEXT_LLONGS];
4647
4648 #define md5cx ((MD5Context *)md5_cx)
4649 #define shacx ((SHA1Context *)sha_cx)
4650
4651         if (!spec->msItem.data) {
4652             PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
4653             return SECFailure;
4654         }
4655
4656         MD5_Clone (md5cx,  (MD5Context *)ss->ssl3.hs.md5_cx);
4657         SHA1_Clone(shacx, (SHA1Context *)ss->ssl3.hs.sha_cx);
4658
4659         if (!isTLS) {
4660             /* compute hashes for SSL3. */
4661             unsigned char s[4];
4662
4663             s[0] = (unsigned char)(sender >> 24);
4664             s[1] = (unsigned char)(sender >> 16);
4665             s[2] = (unsigned char)(sender >> 8);
4666             s[3] = (unsigned char)sender;
4667
4668             if (sender != 0) {
4669                 MD5_Update(md5cx, s, 4);
4670                 PRINT_BUF(95, (NULL, "MD5 inner: sender", s, 4));
4671             }
4672
4673             PRINT_BUF(95, (NULL, "MD5 inner: MAC Pad 1", mac_pad_1, 
4674                             mac_defs[mac_md5].pad_size));
4675
4676             MD5_Update(md5cx, spec->msItem.data, spec->msItem.len);
4677             MD5_Update(md5cx, mac_pad_1, mac_defs[mac_md5].pad_size);
4678             MD5_End(md5cx, md5_inner, &outLength, MD5_LENGTH);
4679
4680             PRINT_BUF(95, (NULL, "MD5 inner: result", md5_inner, outLength));
4681
4682             if (sender != 0) {
4683                 SHA1_Update(shacx, s, 4);
4684                 PRINT_BUF(95, (NULL, "SHA inner: sender", s, 4));
4685             }
4686
4687             PRINT_BUF(95, (NULL, "SHA inner: MAC Pad 1", mac_pad_1, 
4688                             mac_defs[mac_sha].pad_size));
4689
4690             SHA1_Update(shacx, spec->msItem.data, spec->msItem.len);
4691             SHA1_Update(shacx, mac_pad_1, mac_defs[mac_sha].pad_size);
4692             SHA1_End(shacx, sha_inner, &outLength, SHA1_LENGTH);
4693
4694             PRINT_BUF(95, (NULL, "SHA inner: result", sha_inner, outLength));
4695             PRINT_BUF(95, (NULL, "MD5 outer: MAC Pad 2", mac_pad_2, 
4696                             mac_defs[mac_md5].pad_size));
4697             PRINT_BUF(95, (NULL, "MD5 outer: MD5 inner", md5_inner, MD5_LENGTH));
4698
4699             MD5_Begin(md5cx);
4700             MD5_Update(md5cx, spec->msItem.data, spec->msItem.len);
4701             MD5_Update(md5cx, mac_pad_2, mac_defs[mac_md5].pad_size);
4702             MD5_Update(md5cx, md5_inner, MD5_LENGTH);
4703         }
4704         MD5_End(md5cx, hashes->u.s.md5, &outLength, MD5_LENGTH);
4705
4706         PRINT_BUF(60, (NULL, "MD5 outer: result", hashes->u.s.md5, MD5_LENGTH));
4707
4708         if (!isTLS) {
4709             PRINT_BUF(95, (NULL, "SHA outer: MAC Pad 2", mac_pad_2, 
4710                             mac_defs[mac_sha].pad_size));
4711             PRINT_BUF(95, (NULL, "SHA outer: SHA inner", sha_inner, SHA1_LENGTH));
4712
4713             SHA1_Begin(shacx);
4714             SHA1_Update(shacx, spec->msItem.data, spec->msItem.len);
4715             SHA1_Update(shacx, mac_pad_2, mac_defs[mac_sha].pad_size);
4716             SHA1_Update(shacx, sha_inner, SHA1_LENGTH);
4717         }
4718         SHA1_End(shacx, hashes->u.s.sha, &outLength, SHA1_LENGTH);
4719
4720         PRINT_BUF(60, (NULL, "SHA outer: result", hashes->u.s.sha, SHA1_LENGTH));
4721
4722         hashes->len = MD5_LENGTH + SHA1_LENGTH;
4723         rv = SECSuccess;
4724 #undef md5cx
4725 #undef shacx
4726     } else 
4727 #endif
4728     if (ss->ssl3.hs.hashType == handshake_hash_single) {
4729         /* compute hashes with PKCS11 */
4730         PK11Context *h;
4731         unsigned int  stateLen;
4732         unsigned char stackBuf[1024];
4733         unsigned char *stateBuf = NULL;
4734
4735         if (!spec->master_secret) {
4736             PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
4737             return SECFailure;
4738         }
4739
4740         h = ss->ssl3.hs.sha;
4741         stateBuf = PK11_SaveContextAlloc(h, stackBuf,
4742                                          sizeof(stackBuf), &stateLen);
4743         if (stateBuf == NULL) {
4744             ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4745             goto tls12_loser;
4746         }
4747         rv |= PK11_DigestFinal(h, hashes->u.raw, &hashes->len,
4748                                sizeof(hashes->u.raw));
4749         if (rv != SECSuccess) {
4750             ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4751             rv = SECFailure;
4752             goto tls12_loser;
4753         }
4754         /* If we ever support ciphersuites where the PRF hash isn't SHA-256
4755          * then this will need to be updated. */
4756         hashes->hashAlg = SEC_OID_SHA256;
4757         rv = SECSuccess;
4758
4759 tls12_loser:
4760         if (stateBuf) {
4761             if (PK11_RestoreContext(h, stateBuf, stateLen) != SECSuccess) {
4762                 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4763                 rv = SECFailure;
4764             }
4765             if (stateBuf != stackBuf) {
4766                 PORT_ZFree(stateBuf, stateLen);
4767             }
4768         }
4769     } else {
4770         /* compute hashes with PKCS11 */
4771         PK11Context * md5;
4772         PK11Context * sha       = NULL;
4773         unsigned char *md5StateBuf = NULL;
4774         unsigned char *shaStateBuf = NULL;
4775         unsigned int  md5StateLen, shaStateLen;
4776         unsigned char md5StackBuf[256];
4777         unsigned char shaStackBuf[512];
4778
4779         if (!spec->master_secret) {
4780             PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
4781             return SECFailure;
4782         }
4783
4784         md5StateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.md5, md5StackBuf,
4785                                             sizeof md5StackBuf, &md5StateLen);
4786         if (md5StateBuf == NULL) {
4787             ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4788             goto loser;
4789         }
4790         md5 = ss->ssl3.hs.md5;
4791
4792         shaStateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.sha, shaStackBuf,
4793                                             sizeof shaStackBuf, &shaStateLen);
4794         if (shaStateBuf == NULL) {
4795             ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4796             goto loser;
4797         }
4798         sha = ss->ssl3.hs.sha;
4799
4800         if (!isTLS) {
4801             /* compute hashes for SSL3. */
4802             unsigned char s[4];
4803
4804             s[0] = (unsigned char)(sender >> 24);
4805             s[1] = (unsigned char)(sender >> 16);
4806             s[2] = (unsigned char)(sender >> 8);
4807             s[3] = (unsigned char)sender;
4808
4809             if (sender != 0) {
4810                 rv |= PK11_DigestOp(md5, s, 4);
4811                 PRINT_BUF(95, (NULL, "MD5 inner: sender", s, 4));
4812             }
4813
4814             PRINT_BUF(95, (NULL, "MD5 inner: MAC Pad 1", mac_pad_1, 
4815                           mac_defs[mac_md5].pad_size));
4816
4817             rv |= PK11_DigestKey(md5,spec->master_secret);
4818             rv |= PK11_DigestOp(md5, mac_pad_1, mac_defs[mac_md5].pad_size);
4819             rv |= PK11_DigestFinal(md5, md5_inner, &outLength, MD5_LENGTH);
4820             PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH);
4821             if (rv != SECSuccess) {
4822                 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4823                 rv = SECFailure;
4824                 goto loser;
4825             }
4826
4827             PRINT_BUF(95, (NULL, "MD5 inner: result", md5_inner, outLength));
4828
4829             if (sender != 0) {
4830                 rv |= PK11_DigestOp(sha, s, 4);
4831                 PRINT_BUF(95, (NULL, "SHA inner: sender", s, 4));
4832             }
4833
4834             PRINT_BUF(95, (NULL, "SHA inner: MAC Pad 1", mac_pad_1, 
4835                           mac_defs[mac_sha].pad_size));
4836
4837             rv |= PK11_DigestKey(sha, spec->master_secret);
4838             rv |= PK11_DigestOp(sha, mac_pad_1, mac_defs[mac_sha].pad_size);
4839             rv |= PK11_DigestFinal(sha, sha_inner, &outLength, SHA1_LENGTH);
4840             PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH);
4841             if (rv != SECSuccess) {
4842                 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4843                 rv = SECFailure;
4844                 goto loser;
4845             }
4846
4847             PRINT_BUF(95, (NULL, "SHA inner: result", sha_inner, outLength));
4848
4849             PRINT_BUF(95, (NULL, "MD5 outer: MAC Pad 2", mac_pad_2, 
4850                           mac_defs[mac_md5].pad_size));
4851             PRINT_BUF(95, (NULL, "MD5 outer: MD5 inner", md5_inner, MD5_LENGTH));
4852
4853             rv |= PK11_DigestBegin(md5);
4854             rv |= PK11_DigestKey(md5, spec->master_secret);
4855             rv |= PK11_DigestOp(md5, mac_pad_2, mac_defs[mac_md5].pad_size);
4856             rv |= PK11_DigestOp(md5, md5_inner, MD5_LENGTH);
4857         }
4858         rv |= PK11_DigestFinal(md5, hashes->u.s.md5, &outLength, MD5_LENGTH);
4859         PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH);
4860         if (rv != SECSuccess) {
4861             ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4862             rv = SECFailure;
4863             goto loser;
4864         }
4865
4866         PRINT_BUF(60, (NULL, "MD5 outer: result", hashes->u.s.md5, MD5_LENGTH));
4867
4868         if (!isTLS) {
4869             PRINT_BUF(95, (NULL, "SHA outer: MAC Pad 2", mac_pad_2, 
4870                           mac_defs[mac_sha].pad_size));
4871             PRINT_BUF(95, (NULL, "SHA outer: SHA inner", sha_inner, SHA1_LENGTH));
4872
4873             rv |= PK11_DigestBegin(sha);
4874             rv |= PK11_DigestKey(sha,spec->master_secret);
4875             rv |= PK11_DigestOp(sha, mac_pad_2, mac_defs[mac_sha].pad_size);
4876             rv |= PK11_DigestOp(sha, sha_inner, SHA1_LENGTH);
4877         }
4878         rv |= PK11_DigestFinal(sha, hashes->u.s.sha, &outLength, SHA1_LENGTH);
4879         PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH);
4880         if (rv != SECSuccess) {
4881             ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4882             rv = SECFailure;
4883             goto loser;
4884         }
4885
4886         PRINT_BUF(60, (NULL, "SHA outer: result", hashes->u.s.sha, SHA1_LENGTH));
4887
4888         hashes->len = MD5_LENGTH + SHA1_LENGTH;
4889         rv = SECSuccess;
4890
4891     loser:
4892         if (md5StateBuf) {
4893             if (PK11_RestoreContext(ss->ssl3.hs.md5, md5StateBuf, md5StateLen)
4894                  != SECSuccess) 
4895             {
4896                 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4897                 rv = SECFailure;
4898             }
4899             if (md5StateBuf != md5StackBuf) {
4900                 PORT_ZFree(md5StateBuf, md5StateLen);
4901             }
4902         }
4903         if (shaStateBuf) {
4904             if (PK11_RestoreContext(ss->ssl3.hs.sha, shaStateBuf, shaStateLen)
4905                  != SECSuccess) 
4906             {
4907                 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4908                 rv = SECFailure;
4909             }
4910             if (shaStateBuf != shaStackBuf) {
4911                 PORT_ZFree(shaStateBuf, shaStateLen);
4912             }
4913         }
4914     }
4915     return rv;
4916 }
4917
4918 static SECStatus
4919 ssl3_ComputeBackupHandshakeHashes(sslSocket * ss,
4920                                   SSL3Hashes * hashes) /* output goes here. */
4921 {
4922     SECStatus rv = SECSuccess;
4923
4924     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
4925     PORT_Assert( !ss->sec.isServer );
4926     PORT_Assert( ss->ssl3.hs.hashType == handshake_hash_single );
4927
4928     rv = PK11_DigestFinal(ss->ssl3.hs.backupHash, hashes->u.raw, &hashes->len,
4929                           sizeof(hashes->u.raw));
4930     if (rv != SECSuccess) {
4931         ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4932         rv = SECFailure;
4933         goto loser;
4934     }
4935     hashes->hashAlg = SEC_OID_SHA1;
4936
4937 loser:
4938     PK11_DestroyContext(ss->ssl3.hs.backupHash, PR_TRUE);
4939     ss->ssl3.hs.backupHash = NULL;
4940     return rv;
4941 }
4942
4943 /*
4944  * SSL 2 based implementations pass in the initial outbound buffer
4945  * so that the handshake hash can contain the included information.
4946  *
4947  * Called from ssl2_BeginClientHandshake() in sslcon.c
4948  */
4949 SECStatus
4950 ssl3_StartHandshakeHash(sslSocket *ss, unsigned char * buf, int length)
4951 {
4952     SECStatus rv;
4953
4954     ssl_GetSSL3HandshakeLock(ss);  /**************************************/
4955
4956     rv = ssl3_InitState(ss);
4957     if (rv != SECSuccess) {
4958         goto done;              /* ssl3_InitState has set the error code. */
4959     }
4960     rv = ssl3_RestartHandshakeHashes(ss);
4961     if (rv != SECSuccess) {
4962         goto done;
4963     }
4964
4965     PORT_Memset(&ss->ssl3.hs.client_random, 0, SSL3_RANDOM_LENGTH);
4966     PORT_Memcpy(
4967         &ss->ssl3.hs.client_random.rand[SSL3_RANDOM_LENGTH - SSL_CHALLENGE_BYTES],
4968         &ss->sec.ci.clientChallenge,
4969         SSL_CHALLENGE_BYTES);
4970
4971     rv = ssl3_UpdateHandshakeHashes(ss, buf, length);
4972     /* if it failed, ssl3_UpdateHandshakeHashes has set the error code. */
4973
4974 done:
4975     ssl_ReleaseSSL3HandshakeLock(ss);  /**************************************/
4976     return rv;
4977 }
4978
4979 /**************************************************************************
4980  * end of Handshake Hash functions.
4981  * Begin Send and Handle functions for handshakes.
4982  **************************************************************************/
4983
4984 /* Called from ssl3_HandleHelloRequest(),
4985  *             ssl3_RedoHandshake()
4986  *             ssl2_BeginClientHandshake (when resuming ssl3 session)
4987  *             dtls_HandleHelloVerifyRequest(with resending=PR_TRUE)
4988  */
4989 SECStatus
4990 ssl3_SendClientHello(sslSocket *ss, PRBool resending)
4991 {
4992     sslSessionID *   sid;
4993     ssl3CipherSpec * cwSpec;
4994     SECStatus        rv;
4995     int              i;
4996     int              length;
4997     int              num_suites;
4998     int              actual_count = 0;
4999     PRBool           isTLS = PR_FALSE;
5000     PRBool           requestingResume = PR_FALSE, fallbackSCSV = PR_FALSE;
5001     PRInt32          total_exten_len = 0;
5002     unsigned         paddingExtensionLen;
5003     unsigned         numCompressionMethods;
5004     PRInt32          flags;
5005
5006     SSL_TRC(3, ("%d: SSL3[%d]: send client_hello handshake", SSL_GETPID(),
5007                 ss->fd));
5008
5009     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
5010     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
5011
5012     rv = ssl3_InitState(ss);
5013     if (rv != SECSuccess) {
5014         return rv;              /* ssl3_InitState has set the error code. */
5015     }
5016     ss->ssl3.hs.sendingSCSV = PR_FALSE; /* Must be reset every handshake */
5017     PORT_Assert(IS_DTLS(ss) || !resending);
5018
5019     SECITEM_FreeItem(&ss->ssl3.hs.newSessionTicket.ticket, PR_FALSE);
5020     ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE;
5021
5022     /* We might be starting a session renegotiation in which case we should
5023      * clear previous state.
5024      */
5025     PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData));
5026
5027     rv = ssl3_RestartHandshakeHashes(ss);
5028     if (rv != SECSuccess) {
5029         return rv;
5030     }
5031
5032     /*
5033      * During a renegotiation, ss->clientHelloVersion will be used again to
5034      * work around a Windows SChannel bug. Ensure that it is still enabled.
5035      */
5036     if (ss->firstHsDone) {
5037         if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
5038             PORT_SetError(SSL_ERROR_SSL_DISABLED);
5039             return SECFailure;
5040         }
5041
5042         if (ss->clientHelloVersion < ss->vrange.min ||
5043             ss->clientHelloVersion > ss->vrange.max) {
5044             PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
5045             return SECFailure;
5046         }
5047     }
5048
5049     /* We ignore ss->sec.ci.sid here, and use ssl_Lookup because Lookup
5050      * handles expired entries and other details.
5051      * XXX If we've been called from ssl2_BeginClientHandshake, then
5052      * this lookup is duplicative and wasteful.
5053      */
5054     sid = (ss->opt.noCache) ? NULL
5055             : ssl_LookupSID(&ss->sec.ci.peer, ss->sec.ci.port, ss->peerID, ss->url);
5056
5057     /* We can't resume based on a different token. If the sid exists,
5058      * make sure the token that holds the master secret still exists ...
5059      * If we previously did client-auth, make sure that the token that holds
5060      * the private key still exists, is logged in, hasn't been removed, etc.
5061      */
5062     if (sid) {
5063         PRBool sidOK = PR_TRUE;
5064         if (sid->u.ssl3.keys.msIsWrapped) {
5065             /* Session key was wrapped, which means it was using PKCS11, */
5066             PK11SlotInfo *slot = NULL;
5067             if (sid->u.ssl3.masterValid && !ss->opt.bypassPKCS11) {
5068                 slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID,
5069                                          sid->u.ssl3.masterSlotID);
5070             }
5071             if (slot == NULL) {
5072                sidOK = PR_FALSE;
5073             } else {
5074                 PK11SymKey *wrapKey = NULL;
5075                 if (!PK11_IsPresent(slot) ||
5076                     ((wrapKey = PK11_GetWrapKey(slot, 
5077                                                 sid->u.ssl3.masterWrapIndex,
5078                                                 sid->u.ssl3.masterWrapMech,
5079                                                 sid->u.ssl3.masterWrapSeries,
5080                                                 ss->pkcs11PinArg)) == NULL) ) {
5081                     sidOK = PR_FALSE;
5082                 }
5083                 if (wrapKey) PK11_FreeSymKey(wrapKey);
5084                 PK11_FreeSlot(slot);
5085                 slot = NULL;
5086             }
5087         }
5088         /* If we previously did client-auth, make sure that the token that
5089         ** holds the private key still exists, is logged in, hasn't been
5090         ** removed, etc.
5091         */
5092         if (sidOK && !ssl3_ClientAuthTokenPresent(sid)) {
5093             sidOK = PR_FALSE;
5094         }
5095
5096         /* TLS 1.0 (RFC 2246) Appendix E says:
5097          *   Whenever a client already knows the highest protocol known to
5098          *   a server (for example, when resuming a session), it should
5099          *   initiate the connection in that native protocol.
5100          * So we pass sid->version to ssl3_NegotiateVersion() here, except
5101          * when renegotiating.
5102          *
5103          * Windows SChannel compares the client_version inside the RSA
5104          * EncryptedPreMasterSecret of a renegotiation with the
5105          * client_version of the initial ClientHello rather than the
5106          * ClientHello in the renegotiation. To work around this bug, we
5107          * continue to use the client_version used in the initial
5108          * ClientHello when renegotiating.
5109          */
5110         if (sidOK) {
5111             if (ss->firstHsDone) {
5112                 /*
5113                  * The client_version of the initial ClientHello is still
5114                  * available in ss->clientHelloVersion. Ensure that
5115                  * sid->version is bounded within
5116                  * [ss->vrange.min, ss->clientHelloVersion], otherwise we
5117                  * can't use sid.
5118                  */
5119                 if (sid->version >= ss->vrange.min &&
5120                     sid->version <= ss->clientHelloVersion) {
5121                     ss->version = ss->clientHelloVersion;
5122                 } else {
5123                     sidOK = PR_FALSE;
5124                 }
5125             } else {
5126                 if (ssl3_NegotiateVersion(ss, sid->version,
5127                                           PR_FALSE) != SECSuccess) {
5128                     sidOK = PR_FALSE;
5129                 }
5130             }
5131         }
5132
5133         if (!sidOK) {
5134             SSL_AtomicIncrementLong(& ssl3stats.sch_sid_cache_not_ok );
5135             if (ss->sec.uncache)
5136                 (*ss->sec.uncache)(sid);
5137             ssl_FreeSID(sid);
5138             sid = NULL;
5139         }
5140     }
5141
5142     if (sid) {
5143         requestingResume = PR_TRUE;
5144         SSL_AtomicIncrementLong(& ssl3stats.sch_sid_cache_hits );
5145
5146         PRINT_BUF(4, (ss, "client, found session-id:", sid->u.ssl3.sessionID,
5147                       sid->u.ssl3.sessionIDLength));
5148
5149         ss->ssl3.policy = sid->u.ssl3.policy;
5150     } else {
5151         SSL_AtomicIncrementLong(& ssl3stats.sch_sid_cache_misses );
5152
5153         /*
5154          * Windows SChannel compares the client_version inside the RSA
5155          * EncryptedPreMasterSecret of a renegotiation with the
5156          * client_version of the initial ClientHello rather than the
5157          * ClientHello in the renegotiation. To work around this bug, we
5158          * continue to use the client_version used in the initial
5159          * ClientHello when renegotiating.
5160          */
5161         if (ss->firstHsDone) {
5162             ss->version = ss->clientHelloVersion;
5163         } else {
5164             rv = ssl3_NegotiateVersion(ss, SSL_LIBRARY_VERSION_MAX_SUPPORTED,
5165                                        PR_TRUE);
5166             if (rv != SECSuccess)
5167                 return rv;      /* error code was set */
5168         }
5169
5170         sid = ssl3_NewSessionID(ss, PR_FALSE);
5171         if (!sid) {
5172             return SECFailure;  /* memory error is set */
5173         }
5174     }
5175
5176     isTLS = (ss->version > SSL_LIBRARY_VERSION_3_0);
5177     ssl_GetSpecWriteLock(ss);
5178     cwSpec = ss->ssl3.cwSpec;
5179     if (cwSpec->mac_def->mac == mac_null) {
5180         /* SSL records are not being MACed. */
5181         cwSpec->version = ss->version;
5182     }
5183     ssl_ReleaseSpecWriteLock(ss);
5184
5185     if (ss->sec.ci.sid != NULL) {
5186         ssl_FreeSID(ss->sec.ci.sid);    /* decrement ref count, free if zero */
5187     }
5188     ss->sec.ci.sid = sid;
5189
5190     ss->sec.send = ssl3_SendApplicationData;
5191
5192     /* shouldn't get here if SSL3 is disabled, but ... */
5193     if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
5194         PR_NOT_REACHED("No versions of SSL 3.0 or later are enabled");
5195         PORT_SetError(SSL_ERROR_SSL_DISABLED);
5196         return SECFailure;
5197     }
5198
5199     /* how many suites does our PKCS11 support (regardless of policy)? */
5200     num_suites = ssl3_config_match_init(ss);
5201     if (!num_suites)
5202         return SECFailure;      /* ssl3_config_match_init has set error code. */
5203
5204     /* HACK for SCSV in SSL 3.0.  On initial handshake, prepend SCSV,
5205      * only if TLS is disabled.
5206      */
5207     if (!ss->firstHsDone && !isTLS) {
5208         /* Must set this before calling Hello Extension Senders, 
5209          * to suppress sending of empty RI extension.
5210          */
5211         ss->ssl3.hs.sendingSCSV = PR_TRUE;
5212     }
5213
5214     /* When we attempt session resumption (only), we must lock the sid to
5215      * prevent races with other resumption connections that receive a
5216      * NewSessionTicket that will cause the ticket in the sid to be replaced.
5217      * Once we've copied the session ticket into our ClientHello message, it
5218      * is OK for the ticket to change, so we just need to make sure we hold
5219      * the lock across the calls to ssl3_CallHelloExtensionSenders.
5220      */
5221     if (sid->u.ssl3.lock) {
5222         NSSRWLock_LockRead(sid->u.ssl3.lock);
5223     }
5224
5225     if (isTLS || (ss->firstHsDone && ss->peerRequestedProtection)) {
5226         PRUint32 maxBytes = 65535; /* 2^16 - 1 */
5227         PRInt32  extLen;
5228
5229         extLen = ssl3_CallHelloExtensionSenders(ss, PR_FALSE, maxBytes, NULL);
5230         if (extLen < 0) {
5231             if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); }
5232             return SECFailure;
5233         }
5234         maxBytes        -= extLen;
5235         total_exten_len += extLen;
5236
5237         if (total_exten_len > 0)
5238             total_exten_len += 2;
5239     }
5240
5241 #if defined(NSS_ENABLE_ECC)
5242     if (!total_exten_len || !isTLS) {
5243         /* not sending the elliptic_curves and ec_point_formats extensions */
5244         ssl3_DisableECCSuites(ss, NULL); /* disable all ECC suites */
5245     }
5246 #endif
5247
5248     if (IS_DTLS(ss)) {
5249         ssl3_DisableNonDTLSSuites(ss);
5250     }
5251
5252     if (!ssl3_HasGCMSupport()) {
5253         ssl3_DisableGCMSuites(ss);
5254     }
5255
5256     /* how many suites are permitted by policy and user preference? */
5257     num_suites = count_cipher_suites(ss, ss->ssl3.policy, PR_TRUE);
5258     if (!num_suites) {
5259         if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); }
5260         return SECFailure;      /* count_cipher_suites has set error code. */
5261     }
5262
5263     fallbackSCSV = ss->opt.enableFallbackSCSV && (!requestingResume ||
5264                                                   ss->version < sid->version);
5265     /* make room for SCSV */
5266     if (ss->ssl3.hs.sendingSCSV) {
5267         ++num_suites;
5268     }
5269     if (fallbackSCSV) {
5270         ++num_suites;
5271     }
5272
5273     /* count compression methods */
5274     numCompressionMethods = 0;
5275     for (i = 0; i < compressionMethodsCount; i++) {
5276         if (compressionEnabled(ss, compressions[i]))
5277             numCompressionMethods++;
5278     }
5279
5280     length = sizeof(SSL3ProtocolVersion) + SSL3_RANDOM_LENGTH +
5281         1 + ((sid == NULL) ? 0 : sid->u.ssl3.sessionIDLength) +
5282         2 + num_suites*sizeof(ssl3CipherSuite) +
5283         1 + numCompressionMethods + total_exten_len;
5284     if (IS_DTLS(ss)) {
5285         length += 1 + ss->ssl3.hs.cookieLen;
5286     }
5287
5288     /* A padding extension may be included to ensure that the record containing
5289      * the ClientHello doesn't have a length between 256 and 511 bytes
5290      * (inclusive). Initial, ClientHello records with such lengths trigger bugs
5291      * in F5 devices.
5292      *
5293      * This is not done for DTLS nor for renegotiation. */
5294     if (!IS_DTLS(ss) && isTLS && !ss->firstHsDone) {
5295         paddingExtensionLen = ssl3_CalculatePaddingExtensionLength(length);
5296         total_exten_len += paddingExtensionLen;
5297         length += paddingExtensionLen;
5298     } else {
5299         paddingExtensionLen = 0;
5300     }
5301
5302     rv = ssl3_AppendHandshakeHeader(ss, client_hello, length);
5303     if (rv != SECSuccess) {
5304         if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); }
5305         return rv;      /* err set by ssl3_AppendHandshake* */
5306     }
5307
5308     if (ss->firstHsDone) {
5309         /* The client hello version must stay unchanged to work around
5310          * the Windows SChannel bug described above. */
5311         PORT_Assert(ss->version == ss->clientHelloVersion);
5312     }
5313     ss->clientHelloVersion = ss->version;
5314     if (IS_DTLS(ss)) {
5315         PRUint16 version;
5316
5317         version = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion);
5318         rv = ssl3_AppendHandshakeNumber(ss, version, 2);
5319     } else {
5320         rv = ssl3_AppendHandshakeNumber(ss, ss->clientHelloVersion, 2);
5321     }
5322     if (rv != SECSuccess) {
5323         if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); }
5324         return rv;      /* err set by ssl3_AppendHandshake* */
5325     }
5326
5327     if (!resending) { /* Don't re-generate if we are in DTLS re-sending mode */
5328         rv = ssl3_GetNewRandom(&ss->ssl3.hs.client_random);
5329         if (rv != SECSuccess) {
5330             if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); }
5331             return rv;  /* err set by GetNewRandom. */
5332         }
5333     }
5334     rv = ssl3_AppendHandshake(ss, &ss->ssl3.hs.client_random,
5335                               SSL3_RANDOM_LENGTH);
5336     if (rv != SECSuccess) {
5337         if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); }
5338         return rv;      /* err set by ssl3_AppendHandshake* */
5339     }
5340
5341     if (sid)
5342         rv = ssl3_AppendHandshakeVariable(
5343             ss, sid->u.ssl3.sessionID, sid->u.ssl3.sessionIDLength, 1);
5344     else
5345         rv = ssl3_AppendHandshakeVariable(ss, NULL, 0, 1);
5346     if (rv != SECSuccess) {
5347         if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); }
5348         return rv;      /* err set by ssl3_AppendHandshake* */
5349     }
5350
5351     if (IS_DTLS(ss)) {
5352         rv = ssl3_AppendHandshakeVariable(
5353             ss, ss->ssl3.hs.cookie, ss->ssl3.hs.cookieLen, 1);
5354         if (rv != SECSuccess) {
5355             if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); }
5356             return rv;  /* err set by ssl3_AppendHandshake* */
5357         }
5358     }
5359
5360     rv = ssl3_AppendHandshakeNumber(ss, num_suites*sizeof(ssl3CipherSuite), 2);
5361     if (rv != SECSuccess) {
5362         if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); }
5363         return rv;      /* err set by ssl3_AppendHandshake* */
5364     }
5365
5366     if (ss->ssl3.hs.sendingSCSV) {
5367         /* Add the actual SCSV */
5368         rv = ssl3_AppendHandshakeNumber(ss, TLS_EMPTY_RENEGOTIATION_INFO_SCSV,
5369                                         sizeof(ssl3CipherSuite));
5370         if (rv != SECSuccess) {
5371             if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); }
5372             return rv;  /* err set by ssl3_AppendHandshake* */
5373         }
5374         actual_count++;
5375     }
5376     if (fallbackSCSV) {
5377         rv = ssl3_AppendHandshakeNumber(ss, TLS_FALLBACK_SCSV,
5378                                         sizeof(ssl3CipherSuite));
5379         if (rv != SECSuccess) {
5380             if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); }
5381             return rv;  /* err set by ssl3_AppendHandshake* */
5382         }
5383         actual_count++;
5384     }
5385     for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
5386         ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i];
5387         if (config_match(suite, ss->ssl3.policy, PR_TRUE, &ss->vrange)) {
5388             actual_count++;
5389             if (actual_count > num_suites) {
5390                 if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); }
5391                 /* set error card removal/insertion error */
5392                 PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
5393                 return SECFailure;
5394             }
5395             rv = ssl3_AppendHandshakeNumber(ss, suite->cipher_suite,
5396                                             sizeof(ssl3CipherSuite));
5397             if (rv != SECSuccess) {
5398                 if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); }
5399                 return rv;      /* err set by ssl3_AppendHandshake* */
5400             }
5401         }
5402     }
5403
5404     /* if cards were removed or inserted between count_cipher_suites and
5405      * generating our list, detect the error here rather than send it off to
5406      * the server.. */
5407     if (actual_count != num_suites) {
5408         /* Card removal/insertion error */
5409         if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); }
5410         PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
5411         return SECFailure;
5412     }
5413
5414     rv = ssl3_AppendHandshakeNumber(ss, numCompressionMethods, 1);
5415     if (rv != SECSuccess) {
5416         if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); }
5417         return rv;      /* err set by ssl3_AppendHandshake* */
5418     }
5419     for (i = 0; i < compressionMethodsCount; i++) {
5420         if (!compressionEnabled(ss, compressions[i]))
5421             continue;
5422         rv = ssl3_AppendHandshakeNumber(ss, compressions[i], 1);
5423         if (rv != SECSuccess) {
5424             if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); }
5425             return rv;  /* err set by ssl3_AppendHandshake* */
5426         }
5427     }
5428
5429     if (total_exten_len) {
5430         PRUint32 maxBytes = total_exten_len - 2;
5431         PRInt32  extLen;
5432
5433         rv = ssl3_AppendHandshakeNumber(ss, maxBytes, 2);
5434         if (rv != SECSuccess) {
5435             if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); }
5436             return rv;  /* err set by AppendHandshake. */
5437         }
5438
5439         extLen = ssl3_CallHelloExtensionSenders(ss, PR_TRUE, maxBytes, NULL);
5440         if (extLen < 0) {
5441             if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); }
5442             return SECFailure;
5443         }
5444         maxBytes -= extLen;
5445
5446         extLen = ssl3_AppendPaddingExtension(ss, paddingExtensionLen, maxBytes);
5447         if (extLen < 0) {
5448             if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); }
5449             return SECFailure;
5450         }
5451         maxBytes -= extLen;
5452
5453         PORT_Assert(!maxBytes);
5454     } 
5455
5456     if (sid->u.ssl3.lock) {
5457         NSSRWLock_UnlockRead(sid->u.ssl3.lock);
5458     }
5459
5460     if (ss->xtnData.sentSessionTicketInClientHello) {
5461         SSL_AtomicIncrementLong(&ssl3stats.sch_sid_stateless_resumes);
5462     }
5463
5464     if (ss->ssl3.hs.sendingSCSV) {
5465         /* Since we sent the SCSV, pretend we sent empty RI extension. */
5466         TLSExtensionData *xtnData = &ss->xtnData;
5467         xtnData->advertised[xtnData->numAdvertised++] = 
5468             ssl_renegotiation_info_xtn;
5469     }
5470
5471     flags = 0;
5472     if (!ss->firstHsDone && !IS_DTLS(ss)) {
5473         flags |= ssl_SEND_FLAG_CAP_RECORD_VERSION;
5474     }
5475     rv = ssl3_FlushHandshake(ss, flags);
5476     if (rv != SECSuccess) {
5477         return rv;      /* error code set by ssl3_FlushHandshake */
5478     }
5479
5480     ss->ssl3.hs.ws = wait_server_hello;
5481     return rv;
5482 }
5483
5484
5485 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
5486  * ssl3 Hello Request.
5487  * Caller must hold Handshake and RecvBuf locks.
5488  */
5489 static SECStatus
5490 ssl3_HandleHelloRequest(sslSocket *ss)
5491 {
5492     sslSessionID *sid = ss->sec.ci.sid;
5493     SECStatus     rv;
5494
5495     SSL_TRC(3, ("%d: SSL3[%d]: handle hello_request handshake",
5496                 SSL_GETPID(), ss->fd));
5497
5498     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
5499     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
5500
5501     if (ss->ssl3.hs.ws == wait_server_hello)
5502         return SECSuccess;
5503     if (ss->ssl3.hs.ws != idle_handshake || ss->sec.isServer) {
5504         (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
5505         PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST);
5506         return SECFailure;
5507     }
5508     if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) {
5509         ssl_GetXmitBufLock(ss);
5510         rv = SSL3_SendAlert(ss, alert_warning, no_renegotiation);
5511         ssl_ReleaseXmitBufLock(ss);
5512         PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED);
5513         return SECFailure;
5514     }
5515
5516     if (sid) {
5517         if (ss->sec.uncache)
5518             ss->sec.uncache(sid);
5519         ssl_FreeSID(sid);
5520         ss->sec.ci.sid = NULL;
5521     }
5522
5523     if (IS_DTLS(ss)) {
5524         dtls_RehandshakeCleanup(ss);
5525     }
5526
5527     ssl_GetXmitBufLock(ss);
5528     rv = ssl3_SendClientHello(ss, PR_FALSE);
5529     ssl_ReleaseXmitBufLock(ss);
5530
5531     return rv;
5532 }
5533
5534 #define UNKNOWN_WRAP_MECHANISM 0x7fffffff
5535
5536 static const CK_MECHANISM_TYPE wrapMechanismList[SSL_NUM_WRAP_MECHS] = {
5537     CKM_DES3_ECB,
5538     CKM_CAST5_ECB,
5539     CKM_DES_ECB,
5540     CKM_KEY_WRAP_LYNKS,
5541     CKM_IDEA_ECB,
5542     CKM_CAST3_ECB,
5543     CKM_CAST_ECB,
5544     CKM_RC5_ECB,
5545     CKM_RC2_ECB,
5546     CKM_CDMF_ECB,
5547     CKM_SKIPJACK_WRAP,
5548     CKM_SKIPJACK_CBC64,
5549     CKM_AES_ECB,
5550     CKM_CAMELLIA_ECB,
5551     CKM_SEED_ECB,
5552     UNKNOWN_WRAP_MECHANISM
5553 };
5554
5555 static int
5556 ssl_FindIndexByWrapMechanism(CK_MECHANISM_TYPE mech)
5557 {
5558     const CK_MECHANISM_TYPE *pMech = wrapMechanismList;
5559
5560     while (mech != *pMech && *pMech != UNKNOWN_WRAP_MECHANISM) {
5561         ++pMech;
5562     }
5563     return (*pMech == UNKNOWN_WRAP_MECHANISM) ? -1
5564                                               : (pMech - wrapMechanismList);
5565 }
5566
5567 static PK11SymKey *
5568 ssl_UnwrapSymWrappingKey(
5569         SSLWrappedSymWrappingKey *pWswk,
5570         SECKEYPrivateKey *        svrPrivKey,
5571         SSL3KEAType               exchKeyType,
5572         CK_MECHANISM_TYPE         masterWrapMech,
5573         void *                    pwArg)
5574 {
5575     PK11SymKey *             unwrappedWrappingKey  = NULL;
5576     SECItem                  wrappedKey;
5577 #ifdef NSS_ENABLE_ECC
5578     PK11SymKey *             Ks;
5579     SECKEYPublicKey          pubWrapKey;
5580     ECCWrappedKeyInfo        *ecWrapped;
5581 #endif /* NSS_ENABLE_ECC */
5582
5583     /* found the wrapping key on disk. */
5584     PORT_Assert(pWswk->symWrapMechanism == masterWrapMech);
5585     PORT_Assert(pWswk->exchKeyType      == exchKeyType);
5586     if (pWswk->symWrapMechanism != masterWrapMech ||
5587         pWswk->exchKeyType      != exchKeyType) {
5588         goto loser;
5589     }
5590     wrappedKey.type = siBuffer;
5591     wrappedKey.data = pWswk->wrappedSymmetricWrappingkey;
5592     wrappedKey.len  = pWswk->wrappedSymKeyLen;
5593     PORT_Assert(wrappedKey.len <= sizeof pWswk->wrappedSymmetricWrappingkey);
5594
5595     switch (exchKeyType) {
5596
5597     case kt_rsa:
5598         unwrappedWrappingKey =
5599             PK11_PubUnwrapSymKey(svrPrivKey, &wrappedKey,
5600                                  masterWrapMech, CKA_UNWRAP, 0);
5601         break;
5602
5603 #ifdef NSS_ENABLE_ECC
5604     case kt_ecdh:
5605         /* 
5606          * For kt_ecdh, we first create an EC public key based on
5607          * data stored with the wrappedSymmetricWrappingkey. Next,
5608          * we do an ECDH computation involving this public key and
5609          * the SSL server's (long-term) EC private key. The resulting
5610          * shared secret is treated the same way as Fortezza's Ks, i.e.,
5611          * it is used to recover the symmetric wrapping key.
5612          *
5613          * The data in wrappedSymmetricWrappingkey is laid out as defined
5614          * in the ECCWrappedKeyInfo structure.
5615          */
5616         ecWrapped = (ECCWrappedKeyInfo *) pWswk->wrappedSymmetricWrappingkey;
5617
5618         PORT_Assert(ecWrapped->encodedParamLen + ecWrapped->pubValueLen + 
5619             ecWrapped->wrappedKeyLen <= MAX_EC_WRAPPED_KEY_BUFLEN);
5620
5621         if (ecWrapped->encodedParamLen + ecWrapped->pubValueLen + 
5622             ecWrapped->wrappedKeyLen > MAX_EC_WRAPPED_KEY_BUFLEN) {
5623             PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
5624             goto loser;
5625         }
5626
5627         pubWrapKey.keyType = ecKey;
5628         pubWrapKey.u.ec.size = ecWrapped->size;
5629         pubWrapKey.u.ec.DEREncodedParams.len = ecWrapped->encodedParamLen;
5630         pubWrapKey.u.ec.DEREncodedParams.data = ecWrapped->var;
5631         pubWrapKey.u.ec.publicValue.len = ecWrapped->pubValueLen;
5632         pubWrapKey.u.ec.publicValue.data = ecWrapped->var + 
5633             ecWrapped->encodedParamLen;
5634
5635         wrappedKey.len  = ecWrapped->wrappedKeyLen;
5636         wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen + 
5637             ecWrapped->pubValueLen;
5638         
5639         /* Derive Ks using ECDH */
5640         Ks = PK11_PubDeriveWithKDF(svrPrivKey, &pubWrapKey, PR_FALSE, NULL,
5641                                    NULL, CKM_ECDH1_DERIVE, masterWrapMech, 
5642                                    CKA_DERIVE, 0, CKD_NULL, NULL, NULL);
5643         if (Ks == NULL) {
5644             goto loser;
5645         }
5646
5647         /*  Use Ks to unwrap the wrapping key */
5648         unwrappedWrappingKey = PK11_UnwrapSymKey(Ks, masterWrapMech, NULL, 
5649                                                  &wrappedKey, masterWrapMech, 
5650                                                  CKA_UNWRAP, 0);
5651         PK11_FreeSymKey(Ks);
5652         
5653         break;
5654 #endif
5655
5656     default:
5657         /* Assert? */
5658         SET_ERROR_CODE
5659         goto loser;
5660     }
5661 loser:
5662     return unwrappedWrappingKey;
5663 }
5664
5665 /* Each process sharing the server session ID cache has its own array of
5666  * SymKey pointers for the symmetric wrapping keys that are used to wrap
5667  * the master secrets.  There is one key for each KEA type.  These Symkeys
5668  * correspond to the wrapped SymKeys kept in the server session cache.
5669  */
5670
5671 typedef struct {
5672     PK11SymKey *      symWrapKey[kt_kea_size];
5673 } ssl3SymWrapKey;
5674
5675 static PZLock *          symWrapKeysLock = NULL;
5676 static ssl3SymWrapKey    symWrapKeys[SSL_NUM_WRAP_MECHS];
5677
5678 SECStatus ssl_FreeSymWrapKeysLock(void)
5679 {
5680     if (symWrapKeysLock) {
5681         PZ_DestroyLock(symWrapKeysLock);
5682         symWrapKeysLock = NULL;
5683         return SECSuccess;
5684     }
5685     PORT_SetError(SEC_ERROR_NOT_INITIALIZED);
5686     return SECFailure;
5687 }
5688
5689 SECStatus
5690 SSL3_ShutdownServerCache(void)
5691 {
5692     int             i, j;
5693
5694     if (!symWrapKeysLock)
5695         return SECSuccess;      /* lock was never initialized */
5696     PZ_Lock(symWrapKeysLock);
5697     /* get rid of all symWrapKeys */
5698     for (i = 0; i < SSL_NUM_WRAP_MECHS; ++i) {
5699         for (j = 0; j < kt_kea_size; ++j) {
5700             PK11SymKey **   pSymWrapKey;
5701             pSymWrapKey = &symWrapKeys[i].symWrapKey[j];
5702             if (*pSymWrapKey) {
5703                 PK11_FreeSymKey(*pSymWrapKey);
5704                 *pSymWrapKey = NULL;
5705             }
5706         }
5707     }
5708
5709     PZ_Unlock(symWrapKeysLock);
5710     return SECSuccess;
5711 }
5712
5713 SECStatus ssl_InitSymWrapKeysLock(void)
5714 {
5715     symWrapKeysLock = PZ_NewLock(nssILockOther);
5716     return symWrapKeysLock ? SECSuccess : SECFailure;
5717 }
5718
5719 /* Try to get wrapping key for mechanism from in-memory array.
5720  * If that fails, look for one on disk.
5721  * If that fails, generate a new one, put the new one on disk,
5722  * Put the new key in the in-memory array.
5723  */
5724 static PK11SymKey *
5725 getWrappingKey( sslSocket *       ss,
5726                 PK11SlotInfo *    masterSecretSlot,
5727                 SSL3KEAType       exchKeyType,
5728                 CK_MECHANISM_TYPE masterWrapMech,
5729                 void *            pwArg)
5730 {
5731     SECKEYPrivateKey *       svrPrivKey;
5732     SECKEYPublicKey *        svrPubKey             = NULL;
5733     PK11SymKey *             unwrappedWrappingKey  = NULL;
5734     PK11SymKey **            pSymWrapKey;
5735     CK_MECHANISM_TYPE        asymWrapMechanism = CKM_INVALID_MECHANISM;
5736     int                      length;
5737     int                      symWrapMechIndex;
5738     SECStatus                rv;
5739     SECItem                  wrappedKey;
5740     SSLWrappedSymWrappingKey wswk;
5741 #ifdef NSS_ENABLE_ECC
5742     PK11SymKey *      Ks = NULL;
5743     SECKEYPublicKey   *pubWrapKey = NULL;
5744     SECKEYPrivateKey  *privWrapKey = NULL;
5745     ECCWrappedKeyInfo *ecWrapped;
5746 #endif /* NSS_ENABLE_ECC */
5747
5748     svrPrivKey  = ss->serverCerts[exchKeyType].SERVERKEY;
5749     PORT_Assert(svrPrivKey != NULL);
5750     if (!svrPrivKey) {
5751         return NULL;    /* why are we here?!? */
5752     }
5753
5754     symWrapMechIndex = ssl_FindIndexByWrapMechanism(masterWrapMech);
5755     PORT_Assert(symWrapMechIndex >= 0);
5756     if (symWrapMechIndex < 0)
5757         return NULL;    /* invalid masterWrapMech. */
5758
5759     pSymWrapKey = &symWrapKeys[symWrapMechIndex].symWrapKey[exchKeyType];
5760
5761     ssl_InitSessionCacheLocks();
5762
5763     PZ_Lock(symWrapKeysLock);
5764
5765     unwrappedWrappingKey = *pSymWrapKey;
5766     if (unwrappedWrappingKey != NULL) {
5767         if (PK11_VerifyKeyOK(unwrappedWrappingKey)) {
5768             unwrappedWrappingKey = PK11_ReferenceSymKey(unwrappedWrappingKey);
5769             goto done;
5770         }
5771         /* slot series has changed, so this key is no good any more. */
5772         PK11_FreeSymKey(unwrappedWrappingKey);
5773         *pSymWrapKey = unwrappedWrappingKey = NULL;
5774     }
5775
5776     /* Try to get wrapped SymWrapping key out of the (disk) cache. */
5777     /* Following call fills in wswk on success. */
5778     if (ssl_GetWrappingKey(symWrapMechIndex, exchKeyType, &wswk)) {
5779         /* found the wrapped sym wrapping key on disk. */
5780         unwrappedWrappingKey =
5781             ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, exchKeyType,
5782                                      masterWrapMech, pwArg);
5783         if (unwrappedWrappingKey) {
5784             goto install;
5785         }
5786     }
5787
5788     if (!masterSecretSlot)      /* caller doesn't want to create a new one. */
5789         goto loser;
5790
5791     length = PK11_GetBestKeyLength(masterSecretSlot, masterWrapMech);
5792     /* Zero length means fixed key length algorithm, or error.
5793      * It's ambiguous.
5794      */
5795     unwrappedWrappingKey = PK11_KeyGen(masterSecretSlot, masterWrapMech, NULL,
5796                                        length, pwArg);
5797     if (!unwrappedWrappingKey) {
5798         goto loser;
5799     }
5800
5801     /* Prepare the buffer to receive the wrappedWrappingKey,
5802      * the symmetric wrapping key wrapped using the server's pub key.
5803      */
5804     PORT_Memset(&wswk, 0, sizeof wswk); /* eliminate UMRs. */
5805
5806     if (ss->serverCerts[exchKeyType].serverKeyPair) {
5807         svrPubKey = ss->serverCerts[exchKeyType].serverKeyPair->pubKey;
5808     }
5809     if (svrPubKey == NULL) {
5810         PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
5811         goto loser;
5812     }
5813     wrappedKey.type = siBuffer;
5814     wrappedKey.len  = SECKEY_PublicKeyStrength(svrPubKey);
5815     wrappedKey.data = wswk.wrappedSymmetricWrappingkey;
5816
5817     PORT_Assert(wrappedKey.len <= sizeof wswk.wrappedSymmetricWrappingkey);
5818     if (wrappedKey.len > sizeof wswk.wrappedSymmetricWrappingkey)
5819         goto loser;
5820
5821     /* wrap symmetric wrapping key in server's public key. */
5822     switch (exchKeyType) {
5823     case kt_rsa:
5824         asymWrapMechanism = CKM_RSA_PKCS;
5825         rv = PK11_PubWrapSymKey(asymWrapMechanism, svrPubKey,
5826                                 unwrappedWrappingKey, &wrappedKey);
5827         break;
5828
5829 #ifdef NSS_ENABLE_ECC
5830     case kt_ecdh:
5831         /*
5832          * We generate an ephemeral EC key pair. Perform an ECDH
5833          * computation involving this ephemeral EC public key and
5834          * the SSL server's (long-term) EC private key. The resulting
5835          * shared secret is treated in the same way as Fortezza's Ks, 
5836          * i.e., it is used to wrap the wrapping key. To facilitate
5837          * unwrapping in ssl_UnwrapWrappingKey, we also store all
5838          * relevant info about the ephemeral EC public key in
5839          * wswk.wrappedSymmetricWrappingkey and lay it out as 
5840          * described in the ECCWrappedKeyInfo structure.
5841          */
5842         PORT_Assert(svrPubKey->keyType == ecKey);
5843         if (svrPubKey->keyType != ecKey) {
5844             /* something is wrong in sslsecur.c if this isn't an ecKey */
5845             PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
5846             rv = SECFailure;
5847             goto ec_cleanup;
5848         }
5849
5850         privWrapKey = SECKEY_CreateECPrivateKey(
5851             &svrPubKey->u.ec.DEREncodedParams, &pubWrapKey, NULL);
5852         if ((privWrapKey == NULL) || (pubWrapKey == NULL)) {
5853             rv = SECFailure;
5854             goto ec_cleanup;
5855         }
5856         
5857         /* Set the key size in bits */
5858         if (pubWrapKey->u.ec.size == 0) {
5859             pubWrapKey->u.ec.size = SECKEY_PublicKeyStrengthInBits(svrPubKey);
5860         }
5861
5862         PORT_Assert(pubWrapKey->u.ec.DEREncodedParams.len + 
5863             pubWrapKey->u.ec.publicValue.len < MAX_EC_WRAPPED_KEY_BUFLEN);
5864         if (pubWrapKey->u.ec.DEREncodedParams.len + 
5865             pubWrapKey->u.ec.publicValue.len >= MAX_EC_WRAPPED_KEY_BUFLEN) {
5866             PORT_SetError(SEC_ERROR_INVALID_KEY);
5867             rv = SECFailure;
5868             goto ec_cleanup;
5869         }
5870
5871         /* Derive Ks using ECDH */
5872         Ks = PK11_PubDeriveWithKDF(svrPrivKey, pubWrapKey, PR_FALSE, NULL,
5873                                    NULL, CKM_ECDH1_DERIVE, masterWrapMech, 
5874                                    CKA_DERIVE, 0, CKD_NULL, NULL, NULL);
5875         if (Ks == NULL) {
5876             rv = SECFailure;
5877             goto ec_cleanup;
5878         }
5879
5880         ecWrapped = (ECCWrappedKeyInfo *) (wswk.wrappedSymmetricWrappingkey);
5881         ecWrapped->size = pubWrapKey->u.ec.size;
5882         ecWrapped->encodedParamLen = pubWrapKey->u.ec.DEREncodedParams.len;
5883         PORT_Memcpy(ecWrapped->var, pubWrapKey->u.ec.DEREncodedParams.data, 
5884             pubWrapKey->u.ec.DEREncodedParams.len);
5885
5886         ecWrapped->pubValueLen = pubWrapKey->u.ec.publicValue.len;
5887         PORT_Memcpy(ecWrapped->var + ecWrapped->encodedParamLen, 
5888                     pubWrapKey->u.ec.publicValue.data, 
5889                     pubWrapKey->u.ec.publicValue.len);
5890
5891         wrappedKey.len = MAX_EC_WRAPPED_KEY_BUFLEN - 
5892             (ecWrapped->encodedParamLen + ecWrapped->pubValueLen);
5893         wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen +
5894             ecWrapped->pubValueLen;
5895
5896         /* wrap symmetricWrapping key with the local Ks */
5897         rv = PK11_WrapSymKey(masterWrapMech, NULL, Ks,
5898                              unwrappedWrappingKey, &wrappedKey);
5899
5900         if (rv != SECSuccess) {
5901             goto ec_cleanup;
5902         }
5903
5904         /* Write down the length of wrapped key in the buffer
5905          * wswk.wrappedSymmetricWrappingkey at the appropriate offset
5906          */
5907         ecWrapped->wrappedKeyLen = wrappedKey.len;
5908
5909 ec_cleanup:
5910         if (privWrapKey) SECKEY_DestroyPrivateKey(privWrapKey);
5911         if (pubWrapKey) SECKEY_DestroyPublicKey(pubWrapKey);
5912         if (Ks) PK11_FreeSymKey(Ks);
5913         asymWrapMechanism = masterWrapMech;
5914         break;
5915 #endif /* NSS_ENABLE_ECC */
5916
5917     default:
5918         rv = SECFailure;
5919         break;
5920     }
5921
5922     if (rv != SECSuccess) {
5923         ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
5924         goto loser;
5925     }
5926
5927     PORT_Assert(asymWrapMechanism != CKM_INVALID_MECHANISM);
5928
5929     wswk.symWrapMechanism  = masterWrapMech;
5930     wswk.symWrapMechIndex  = symWrapMechIndex;
5931     wswk.asymWrapMechanism = asymWrapMechanism;
5932     wswk.exchKeyType       = exchKeyType;
5933     wswk.wrappedSymKeyLen  = wrappedKey.len;
5934
5935     /* put it on disk. */
5936     /* If the wrapping key for this KEA type has already been set, 
5937      * then abandon the value we just computed and 
5938      * use the one we got from the disk.
5939      */
5940     if (ssl_SetWrappingKey(&wswk)) {
5941         /* somebody beat us to it.  The original contents of our wswk
5942          * has been replaced with the content on disk.  Now, discard
5943          * the key we just created and unwrap this new one.
5944          */
5945         PK11_FreeSymKey(unwrappedWrappingKey);
5946
5947         unwrappedWrappingKey =
5948             ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, exchKeyType,
5949                                      masterWrapMech, pwArg);
5950     }
5951
5952 install:
5953     if (unwrappedWrappingKey) {
5954         *pSymWrapKey = PK11_ReferenceSymKey(unwrappedWrappingKey);
5955     }
5956
5957 loser:
5958 done:
5959     PZ_Unlock(symWrapKeysLock);
5960     return unwrappedWrappingKey;
5961 }
5962
5963 /* hexEncode hex encodes |length| bytes from |in| and writes it as |length*2|
5964  * bytes to |out|. */
5965 static void
5966 hexEncode(char *out, const unsigned char *in, unsigned int length)
5967 {
5968     static const char hextable[] = "0123456789abcdef";
5969     unsigned int i;
5970
5971     for (i = 0; i < length; i++) {
5972         *(out++) = hextable[in[i] >> 4];
5973         *(out++) = hextable[in[i] & 15];
5974     }
5975 }
5976
5977 /* Called from ssl3_SendClientKeyExchange(). */
5978 /* Presently, this always uses PKCS11.  There is no bypass for this. */
5979 static SECStatus
5980 sendRSAClientKeyExchange(sslSocket * ss, SECKEYPublicKey * svrPubKey)
5981 {
5982     PK11SymKey *        pms             = NULL;
5983     SECStatus           rv              = SECFailure;
5984     SECItem             enc_pms         = {siBuffer, NULL, 0};
5985     PRBool              isTLS;
5986
5987     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
5988     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
5989
5990     /* Generate the pre-master secret ...  */
5991     ssl_GetSpecWriteLock(ss);
5992     isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
5993
5994     pms = ssl3_GenerateRSAPMS(ss, ss->ssl3.pwSpec, NULL);
5995     ssl_ReleaseSpecWriteLock(ss);
5996     if (pms == NULL) {
5997         ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
5998         goto loser;
5999     }
6000
6001     /* Get the wrapped (encrypted) pre-master secret, enc_pms */
6002     enc_pms.len  = SECKEY_PublicKeyStrength(svrPubKey);
6003     enc_pms.data = (unsigned char*)PORT_Alloc(enc_pms.len);
6004     if (enc_pms.data == NULL) {
6005         goto loser;     /* err set by PORT_Alloc */
6006     }
6007
6008     /* wrap pre-master secret in server's public key. */
6009     rv = PK11_PubWrapSymKey(CKM_RSA_PKCS, svrPubKey, pms, &enc_pms);
6010     if (rv != SECSuccess) {
6011         ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
6012         goto loser;
6013     }
6014
6015     if (ssl_keylog_iob) {
6016         SECStatus extractRV = PK11_ExtractKeyValue(pms);
6017         if (extractRV == SECSuccess) {
6018             SECItem * keyData = PK11_GetKeyData(pms);
6019             if (keyData && keyData->data && keyData->len) {
6020 #ifdef TRACE
6021                 if (ssl_trace >= 100) {
6022                     ssl_PrintBuf(ss, "Pre-Master Secret",
6023                                  keyData->data, keyData->len);
6024                 }
6025 #endif
6026                 if (ssl_keylog_iob && enc_pms.len >= 8 && keyData->len == 48) {
6027                     /* https://developer.mozilla.org/en/NSS_Key_Log_Format */
6028
6029                     /* There could be multiple, concurrent writers to the
6030                      * keylog, so we have to do everything in a single call to
6031                      * fwrite. */
6032                     char buf[4 + 8*2 + 1 + 48*2 + 1];
6033
6034                     strcpy(buf, "RSA ");
6035                     hexEncode(buf + 4, enc_pms.data, 8);
6036                     buf[20] = ' ';
6037                     hexEncode(buf + 21, keyData->data, 48);
6038                     buf[sizeof(buf) - 1] = '\n';
6039
6040                     fwrite(buf, sizeof(buf), 1, ssl_keylog_iob);
6041                     fflush(ssl_keylog_iob);
6042                 }
6043             }
6044         }
6045     }
6046
6047     rv = ssl3_InitPendingCipherSpec(ss,  pms);
6048     PK11_FreeSymKey(pms); pms = NULL;
6049
6050     if (rv != SECSuccess) {
6051         ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
6052         goto loser;
6053     }
6054
6055     rv = ssl3_AppendHandshakeHeader(ss, client_key_exchange, 
6056                                     isTLS ? enc_pms.len + 2 : enc_pms.len);
6057     if (rv != SECSuccess) {
6058         goto loser;     /* err set by ssl3_AppendHandshake* */
6059     }
6060     if (isTLS) {
6061         rv = ssl3_AppendHandshakeVariable(ss, enc_pms.data, enc_pms.len, 2);
6062     } else {
6063         rv = ssl3_AppendHandshake(ss, enc_pms.data, enc_pms.len);
6064     }
6065     if (rv != SECSuccess) {
6066         goto loser;     /* err set by ssl3_AppendHandshake* */
6067     }
6068
6069     rv = SECSuccess;
6070
6071 loser:
6072     if (enc_pms.data != NULL) {
6073         PORT_Free(enc_pms.data);
6074     }
6075     if (pms != NULL) {
6076         PK11_FreeSymKey(pms);
6077     }
6078     return rv;
6079 }
6080
6081 /* Called from ssl3_SendClientKeyExchange(). */
6082 /* Presently, this always uses PKCS11.  There is no bypass for this. */
6083 static SECStatus
6084 sendDHClientKeyExchange(sslSocket * ss, SECKEYPublicKey * svrPubKey)
6085 {
6086     PK11SymKey *        pms             = NULL;
6087     SECStatus           rv              = SECFailure;
6088     PRBool              isTLS;
6089     CK_MECHANISM_TYPE   target;
6090
6091     SECKEYDHParams      dhParam;                /* DH parameters */
6092     SECKEYPublicKey     *pubKey = NULL;         /* Ephemeral DH key */
6093     SECKEYPrivateKey    *privKey = NULL;        /* Ephemeral DH key */
6094
6095     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
6096     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
6097
6098     isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
6099
6100     /* Copy DH parameters from server key */
6101
6102     if (svrPubKey->keyType != dhKey) {
6103         PORT_SetError(SEC_ERROR_BAD_KEY);
6104         goto loser;
6105     }
6106     dhParam.prime.data = svrPubKey->u.dh.prime.data;
6107     dhParam.prime.len = svrPubKey->u.dh.prime.len;
6108     dhParam.base.data = svrPubKey->u.dh.base.data;
6109     dhParam.base.len = svrPubKey->u.dh.base.len;
6110
6111     /* Generate ephemeral DH keypair */
6112     privKey = SECKEY_CreateDHPrivateKey(&dhParam, &pubKey, NULL);
6113     if (!privKey || !pubKey) {
6114             ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL);
6115             rv = SECFailure;
6116             goto loser;
6117     }
6118     PRINT_BUF(50, (ss, "DH public value:",
6119                                         pubKey->u.dh.publicValue.data,
6120                                         pubKey->u.dh.publicValue.len));
6121
6122     if (isTLS) target = CKM_TLS_MASTER_KEY_DERIVE_DH;
6123     else target = CKM_SSL3_MASTER_KEY_DERIVE_DH;
6124
6125     /* Determine the PMS */
6126
6127     pms = PK11_PubDerive(privKey, svrPubKey, PR_FALSE, NULL, NULL,
6128                             CKM_DH_PKCS_DERIVE, target, CKA_DERIVE, 0, NULL);
6129
6130     if (pms == NULL) {
6131         ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
6132         goto loser;
6133     }
6134
6135     SECKEY_DestroyPrivateKey(privKey);
6136     privKey = NULL;
6137
6138     rv = ssl3_InitPendingCipherSpec(ss,  pms);
6139     PK11_FreeSymKey(pms); pms = NULL;
6140
6141     if (rv != SECSuccess) {
6142         ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
6143         goto loser;
6144     }
6145
6146     rv = ssl3_AppendHandshakeHeader(ss, client_key_exchange, 
6147                                         pubKey->u.dh.publicValue.len + 2);
6148     if (rv != SECSuccess) {
6149         goto loser;     /* err set by ssl3_AppendHandshake* */
6150     }
6151     rv = ssl3_AppendHandshakeVariable(ss, 
6152                                         pubKey->u.dh.publicValue.data,
6153                                         pubKey->u.dh.publicValue.len, 2);
6154     SECKEY_DestroyPublicKey(pubKey);
6155     pubKey = NULL;
6156
6157     if (rv != SECSuccess) {
6158         goto loser;     /* err set by ssl3_AppendHandshake* */
6159     }
6160
6161     rv = SECSuccess;
6162
6163
6164 loser:
6165
6166     if(pms) PK11_FreeSymKey(pms);
6167     if(privKey) SECKEY_DestroyPrivateKey(privKey);
6168     if(pubKey) SECKEY_DestroyPublicKey(pubKey);
6169     return rv;
6170 }
6171
6172
6173
6174
6175
6176 /* Called from ssl3_HandleServerHelloDone(). */
6177 static SECStatus
6178 ssl3_SendClientKeyExchange(sslSocket *ss)
6179 {
6180     SECKEYPublicKey *   serverKey       = NULL;
6181     SECStatus           rv              = SECFailure;
6182     PRBool              isTLS;
6183
6184     SSL_TRC(3, ("%d: SSL3[%d]: send client_key_exchange handshake",
6185                 SSL_GETPID(), ss->fd));
6186
6187     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
6188     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
6189
6190     if (ss->sec.peerKey == NULL) {
6191         serverKey = CERT_ExtractPublicKey(ss->sec.peerCert);
6192         if (serverKey == NULL) {
6193             ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
6194             return SECFailure;
6195         }
6196     } else {
6197         serverKey = ss->sec.peerKey;
6198         ss->sec.peerKey = NULL; /* we're done with it now */
6199     }
6200
6201     isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
6202     /* enforce limits on kea key sizes. */
6203     if (ss->ssl3.hs.kea_def->is_limited) {
6204         int keyLen = SECKEY_PublicKeyStrength(serverKey);       /* bytes */
6205
6206         if (keyLen * BPB > ss->ssl3.hs.kea_def->key_size_limit) {
6207             if (isTLS)
6208                 (void)SSL3_SendAlert(ss, alert_fatal, export_restriction);
6209             else
6210                 (void)ssl3_HandshakeFailure(ss);
6211             PORT_SetError(SSL_ERROR_PUB_KEY_SIZE_LIMIT_EXCEEDED);
6212             goto loser;
6213         }
6214     }
6215
6216     ss->sec.keaType    = ss->ssl3.hs.kea_def->exchKeyType;
6217     ss->sec.keaKeyBits = SECKEY_PublicKeyStrengthInBits(serverKey);
6218
6219     switch (ss->ssl3.hs.kea_def->exchKeyType) {
6220     case kt_rsa:
6221         rv = sendRSAClientKeyExchange(ss, serverKey);
6222         break;
6223
6224     case kt_dh:
6225         rv = sendDHClientKeyExchange(ss, serverKey);
6226         break;
6227
6228 #ifdef NSS_ENABLE_ECC
6229     case kt_ecdh:
6230         rv = ssl3_SendECDHClientKeyExchange(ss, serverKey);
6231         break;
6232 #endif /* NSS_ENABLE_ECC */
6233
6234     default:
6235         /* got an unknown or unsupported Key Exchange Algorithm.  */
6236         SEND_ALERT
6237         PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
6238         break;
6239     }
6240
6241     SSL_TRC(3, ("%d: SSL3[%d]: DONE sending client_key_exchange",
6242                 SSL_GETPID(), ss->fd));
6243
6244 loser:
6245     if (serverKey) 
6246         SECKEY_DestroyPublicKey(serverKey);
6247     return rv;  /* err code already set. */
6248 }
6249
6250 /* Called from ssl3_HandleServerHelloDone(). */
6251 static SECStatus
6252 ssl3_SendCertificateVerify(sslSocket *ss)
6253 {
6254     SECStatus     rv            = SECFailure;
6255     PRBool        isTLS;
6256     PRBool        isTLS12;
6257     SECItem       buf           = {siBuffer, NULL, 0};
6258     SSL3Hashes    hashes;
6259     KeyType       keyType;
6260     unsigned int  len;
6261     SSL3SignatureAndHashAlgorithm sigAndHash;
6262
6263     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
6264     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
6265
6266     SSL_TRC(3, ("%d: SSL3[%d]: send certificate_verify handshake",
6267                 SSL_GETPID(), ss->fd));
6268
6269     ssl_GetSpecReadLock(ss);
6270     if (ss->ssl3.hs.hashType == handshake_hash_single &&
6271         ss->ssl3.hs.backupHash) {
6272         rv = ssl3_ComputeBackupHandshakeHashes(ss, &hashes);
6273         PORT_Assert(!ss->ssl3.hs.backupHash);
6274     } else {
6275         rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.pwSpec, &hashes, 0);
6276     }
6277     ssl_ReleaseSpecReadLock(ss);
6278     if (rv != SECSuccess) {
6279         goto done;      /* err code was set by ssl3_ComputeHandshakeHashes */
6280     }
6281
6282     isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
6283     isTLS12 = (PRBool)(ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
6284     if (ss->ssl3.platformClientKey) {
6285 #ifdef NSS_PLATFORM_CLIENT_AUTH
6286         keyType = CERT_GetCertKeyType(
6287             &ss->ssl3.clientCertificate->subjectPublicKeyInfo);
6288         rv = ssl3_PlatformSignHashes(
6289             &hashes, ss->ssl3.platformClientKey, &buf, isTLS, keyType);
6290         ssl_FreePlatformKey(ss->ssl3.platformClientKey);
6291         ss->ssl3.platformClientKey = (PlatformKey)NULL;
6292 #endif /* NSS_PLATFORM_CLIENT_AUTH */
6293     } else {
6294         keyType = ss->ssl3.clientPrivateKey->keyType;
6295         rv = ssl3_SignHashes(&hashes, ss->ssl3.clientPrivateKey, &buf, isTLS);
6296         if (rv == SECSuccess) {
6297             PK11SlotInfo * slot;
6298             sslSessionID * sid   = ss->sec.ci.sid;
6299
6300             /* Remember the info about the slot that did the signing.
6301             ** Later, when doing an SSL restart handshake, verify this.
6302             ** These calls are mere accessors, and can't fail.
6303             */
6304             slot = PK11_GetSlotFromPrivateKey(ss->ssl3.clientPrivateKey);
6305             sid->u.ssl3.clAuthSeries     = PK11_GetSlotSeries(slot);
6306             sid->u.ssl3.clAuthSlotID     = PK11_GetSlotID(slot);
6307             sid->u.ssl3.clAuthModuleID   = PK11_GetModuleID(slot);
6308             sid->u.ssl3.clAuthValid      = PR_TRUE;
6309             PK11_FreeSlot(slot);
6310         }
6311         SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
6312         ss->ssl3.clientPrivateKey = NULL;
6313     }
6314     if (rv != SECSuccess) {
6315         goto done;      /* err code was set by ssl3_SignHashes */
6316     }
6317
6318     len = buf.len + 2 + (isTLS12 ? 2 : 0);
6319
6320     rv = ssl3_AppendHandshakeHeader(ss, certificate_verify, len);
6321     if (rv != SECSuccess) {
6322         goto done;      /* error code set by AppendHandshake */
6323     }
6324     if (isTLS12) {
6325         rv = ssl3_TLSSignatureAlgorithmForKeyType(keyType,
6326                                                   &sigAndHash.sigAlg);
6327         if (rv != SECSuccess) {
6328             goto done;
6329         }
6330         sigAndHash.hashAlg = hashes.hashAlg;
6331
6332         rv = ssl3_AppendSignatureAndHashAlgorithm(ss, &sigAndHash);
6333         if (rv != SECSuccess) {
6334             goto done;  /* err set by AppendHandshake. */
6335         }
6336     }
6337     rv = ssl3_AppendHandshakeVariable(ss, buf.data, buf.len, 2);
6338     if (rv != SECSuccess) {
6339         goto done;      /* error code set by AppendHandshake */
6340     }
6341
6342 done:
6343     if (buf.data)
6344         PORT_Free(buf.data);
6345     return rv;
6346 }
6347
6348 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
6349  * ssl3 ServerHello message.
6350  * Caller must hold Handshake and RecvBuf locks.
6351  */
6352 static SECStatus
6353 ssl3_HandleServerHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
6354 {
6355     sslSessionID *sid           = ss->sec.ci.sid;
6356     PRInt32       temp;         /* allow for consume number failure */
6357     PRBool        suite_found   = PR_FALSE;
6358     int           i;
6359     int           errCode       = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
6360     SECStatus     rv;
6361     SECItem       sidBytes      = {siBuffer, NULL, 0};
6362     PRBool        sid_match;
6363     PRBool        isTLS         = PR_FALSE;
6364     SSL3AlertDescription desc   = illegal_parameter;
6365     SSL3ProtocolVersion version;
6366
6367     SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello handshake",
6368         SSL_GETPID(), ss->fd));
6369     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
6370     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
6371     PORT_Assert( ss->ssl3.initialized );
6372
6373     if (ss->ssl3.hs.ws != wait_server_hello) {
6374         errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO;
6375         desc    = unexpected_message;
6376         goto alert_loser;
6377     }
6378
6379     /* clean up anything left from previous handshake. */
6380     if (ss->ssl3.clientCertChain != NULL) {
6381        CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
6382        ss->ssl3.clientCertChain = NULL;
6383     }
6384     if (ss->ssl3.clientCertificate != NULL) {
6385        CERT_DestroyCertificate(ss->ssl3.clientCertificate);
6386        ss->ssl3.clientCertificate = NULL;
6387     }
6388     if (ss->ssl3.clientPrivateKey != NULL) {
6389        SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
6390        ss->ssl3.clientPrivateKey = NULL;
6391     }
6392 #ifdef NSS_PLATFORM_CLIENT_AUTH
6393     if (ss->ssl3.platformClientKey) {
6394        ssl_FreePlatformKey(ss->ssl3.platformClientKey);
6395        ss->ssl3.platformClientKey = (PlatformKey)NULL;
6396     }
6397 #endif  /* NSS_PLATFORM_CLIENT_AUTH */
6398
6399     if (ss->ssl3.channelID != NULL) {
6400         SECKEY_DestroyPrivateKey(ss->ssl3.channelID);
6401         ss->ssl3.channelID = NULL;
6402     }
6403     if (ss->ssl3.channelIDPub != NULL) {
6404         SECKEY_DestroyPublicKey(ss->ssl3.channelIDPub);
6405         ss->ssl3.channelIDPub = NULL;
6406     }
6407
6408     temp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
6409     if (temp < 0) {
6410         goto loser;     /* alert has been sent */
6411     }
6412     version = (SSL3ProtocolVersion)temp;
6413
6414     if (IS_DTLS(ss)) {
6415         /* RFC 4347 required that you verify that the server versions
6416          * match (Section 4.2.1) in the HelloVerifyRequest and the
6417          * ServerHello.
6418          *
6419          * RFC 6347 suggests (SHOULD) that servers always use 1.0
6420          * in HelloVerifyRequest and allows the versions not to match,
6421          * especially when 1.2 is being negotiated.
6422          *
6423          * Therefore we do not check for matching here.
6424          */
6425         version = dtls_DTLSVersionToTLSVersion(version);
6426         if (version == 0) {  /* Insane version number */
6427             goto alert_loser;
6428         }
6429     }
6430
6431     rv = ssl3_NegotiateVersion(ss, version, PR_FALSE);
6432     if (rv != SECSuccess) {
6433         desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version 
6434                                                    : handshake_failure;
6435         errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
6436         goto alert_loser;
6437     }
6438     isTLS = (ss->version > SSL_LIBRARY_VERSION_3_0);
6439
6440     rv = ssl3_InitHandshakeHashes(ss);
6441     if (rv != SECSuccess) {
6442         desc = internal_error;
6443         errCode = PORT_GetError();
6444         goto alert_loser;
6445     }
6446
6447     rv = ssl3_ConsumeHandshake(
6448         ss, &ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH, &b, &length);
6449     if (rv != SECSuccess) {
6450         goto loser;     /* alert has been sent */
6451     }
6452
6453     rv = ssl3_ConsumeHandshakeVariable(ss, &sidBytes, 1, &b, &length);
6454     if (rv != SECSuccess) {
6455         goto loser;     /* alert has been sent */
6456     }
6457     if (sidBytes.len > SSL3_SESSIONID_BYTES) {
6458         if (isTLS)
6459             desc = decode_error;
6460         goto alert_loser;       /* malformed. */
6461     }
6462
6463     /* find selected cipher suite in our list. */
6464     temp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
6465     if (temp < 0) {
6466         goto loser;     /* alert has been sent */
6467     }
6468     ssl3_config_match_init(ss);
6469     for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
6470         ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i];
6471         if (temp == suite->cipher_suite) {
6472             SSLVersionRange vrange = {ss->version, ss->version};
6473             if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange)) {
6474                 /* config_match already checks whether the cipher suite is
6475                  * acceptable for the version, but the check is repeated here
6476                  * in order to give a more precise error code. */
6477                 if (!ssl3_CipherSuiteAllowedForVersionRange(temp, &vrange)) {
6478                     desc    = handshake_failure;
6479                     errCode = SSL_ERROR_CIPHER_DISALLOWED_FOR_VERSION;
6480                     goto alert_loser;
6481                 }
6482
6483                 break;  /* failure */
6484             }
6485         
6486             suite_found = PR_TRUE;
6487             break;      /* success */
6488         }
6489     }
6490     if (!suite_found) {
6491         desc    = handshake_failure;
6492         errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
6493         goto alert_loser;
6494     }
6495     ss->ssl3.hs.cipher_suite = (ssl3CipherSuite)temp;
6496     ss->ssl3.hs.suite_def    = ssl_LookupCipherSuiteDef((ssl3CipherSuite)temp);
6497     PORT_Assert(ss->ssl3.hs.suite_def);
6498     if (!ss->ssl3.hs.suite_def) {
6499         PORT_SetError(errCode = SEC_ERROR_LIBRARY_FAILURE);
6500         goto loser;     /* we don't send alerts for our screw-ups. */
6501     }
6502
6503     /* find selected compression method in our list. */
6504     temp = ssl3_ConsumeHandshakeNumber(ss, 1, &b, &length);
6505     if (temp < 0) {
6506         goto loser;     /* alert has been sent */
6507     }
6508     suite_found = PR_FALSE;
6509     for (i = 0; i < compressionMethodsCount; i++) {
6510         if (temp == compressions[i]) {
6511             if (!compressionEnabled(ss, compressions[i])) {
6512                 break;  /* failure */
6513             }
6514             suite_found = PR_TRUE;
6515             break;      /* success */
6516         }
6517     }
6518     if (!suite_found) {
6519         desc    = handshake_failure;
6520         errCode = SSL_ERROR_NO_COMPRESSION_OVERLAP;
6521         goto alert_loser;
6522     }
6523     ss->ssl3.hs.compression = (SSLCompressionMethod)temp;
6524
6525     /* Note that if !isTLS and the extra stuff is not extensions, we
6526      * do NOT goto alert_loser.
6527      * There are some old SSL 3.0 implementations that do send stuff
6528      * after the end of the server hello, and we deliberately ignore
6529      * such stuff in the interest of maximal interoperability (being
6530      * "generous in what you accept").
6531      * Update: Starting in NSS 3.12.6, we handle the renegotiation_info
6532      * extension in SSL 3.0.
6533      */
6534     if (length != 0) {
6535         SECItem extensions;
6536         rv = ssl3_ConsumeHandshakeVariable(ss, &extensions, 2, &b, &length);
6537         if (rv != SECSuccess || length != 0) {
6538             if (isTLS)
6539                 goto alert_loser;
6540         } else {
6541             rv = ssl3_HandleHelloExtensions(ss, &extensions.data,
6542                                             &extensions.len);
6543             if (rv != SECSuccess)
6544                 goto alert_loser;
6545         }
6546     }
6547     if ((ss->opt.requireSafeNegotiation || 
6548          (ss->firstHsDone && (ss->peerRequestedProtection ||
6549          ss->opt.enableRenegotiation == SSL_RENEGOTIATE_REQUIRES_XTN))) &&
6550         !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
6551         desc = handshake_failure;
6552         errCode = ss->firstHsDone ? SSL_ERROR_RENEGOTIATION_NOT_ALLOWED
6553                                   : SSL_ERROR_UNSAFE_NEGOTIATION;
6554         goto alert_loser;
6555     }
6556
6557     /* Any errors after this point are not "malformed" errors. */
6558     desc    = handshake_failure;
6559
6560     /* we need to call ssl3_SetupPendingCipherSpec here so we can check the
6561      * key exchange algorithm. */
6562     rv = ssl3_SetupPendingCipherSpec(ss);
6563     if (rv != SECSuccess) {
6564         goto alert_loser;       /* error code is set. */
6565     }
6566
6567     /* We may or may not have sent a session id, we may get one back or
6568      * not and if so it may match the one we sent.
6569      * Attempt to restore the master secret to see if this is so...
6570      * Don't consider failure to find a matching SID an error.
6571      */
6572     sid_match = (PRBool)(sidBytes.len > 0 &&
6573         sidBytes.len == sid->u.ssl3.sessionIDLength &&
6574         !PORT_Memcmp(sid->u.ssl3.sessionID, sidBytes.data, sidBytes.len));
6575
6576     if (sid_match &&
6577         sid->version == ss->version &&
6578         sid->u.ssl3.cipherSuite == ss->ssl3.hs.cipher_suite) do {
6579         ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec;
6580
6581         SECItem       wrappedMS;   /* wrapped master secret. */
6582
6583         ss->sec.authAlgorithm = sid->authAlgorithm;
6584         ss->sec.authKeyBits   = sid->authKeyBits;
6585         ss->sec.keaType       = sid->keaType;
6586         ss->sec.keaKeyBits    = sid->keaKeyBits;
6587
6588         /* 3 cases here:
6589          * a) key is wrapped (implies using PKCS11)
6590          * b) key is unwrapped, but we're still using PKCS11
6591          * c) key is unwrapped, and we're bypassing PKCS11.
6592          */
6593         if (sid->u.ssl3.keys.msIsWrapped) {
6594             PK11SlotInfo *slot;
6595             PK11SymKey *  wrapKey;     /* wrapping key */
6596             CK_FLAGS      keyFlags      = 0;
6597
6598 #ifndef NO_PKCS11_BYPASS
6599             if (ss->opt.bypassPKCS11) {
6600                 /* we cannot restart a non-bypass session in a 
6601                 ** bypass socket.
6602                 */
6603                 break;  
6604             }
6605 #endif
6606             /* unwrap master secret with PKCS11 */
6607             slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID,
6608                                      sid->u.ssl3.masterSlotID);
6609             if (slot == NULL) {
6610                 break;          /* not considered an error. */
6611             }
6612             if (!PK11_IsPresent(slot)) {
6613                 PK11_FreeSlot(slot);
6614                 break;          /* not considered an error. */
6615             }
6616             wrapKey = PK11_GetWrapKey(slot, sid->u.ssl3.masterWrapIndex,
6617                                       sid->u.ssl3.masterWrapMech,
6618                                       sid->u.ssl3.masterWrapSeries,
6619                                       ss->pkcs11PinArg);
6620             PK11_FreeSlot(slot);
6621             if (wrapKey == NULL) {
6622                 break;          /* not considered an error. */
6623             }
6624
6625             if (ss->version > SSL_LIBRARY_VERSION_3_0) {        /* isTLS */
6626                 keyFlags = CKF_SIGN | CKF_VERIFY;
6627             }
6628
6629             wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
6630             wrappedMS.len  = sid->u.ssl3.keys.wrapped_master_secret_len;
6631             pwSpec->master_secret =
6632                 PK11_UnwrapSymKeyWithFlags(wrapKey, sid->u.ssl3.masterWrapMech, 
6633                             NULL, &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE,
6634                             CKA_DERIVE, sizeof(SSL3MasterSecret), keyFlags);
6635             errCode = PORT_GetError();
6636             PK11_FreeSymKey(wrapKey);
6637             if (pwSpec->master_secret == NULL) {
6638                 break;  /* errorCode set just after call to UnwrapSymKey. */
6639             }
6640 #ifndef NO_PKCS11_BYPASS
6641         } else if (ss->opt.bypassPKCS11) {
6642             /* MS is not wrapped */
6643             wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
6644             wrappedMS.len  = sid->u.ssl3.keys.wrapped_master_secret_len;
6645             memcpy(pwSpec->raw_master_secret, wrappedMS.data, wrappedMS.len);
6646             pwSpec->msItem.data = pwSpec->raw_master_secret;
6647             pwSpec->msItem.len  = wrappedMS.len;
6648 #endif
6649         } else {
6650             /* We CAN restart a bypass session in a non-bypass socket. */
6651             /* need to import the raw master secret to session object */
6652             PK11SlotInfo *slot = PK11_GetInternalSlot();
6653             wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
6654             wrappedMS.len  = sid->u.ssl3.keys.wrapped_master_secret_len;
6655             pwSpec->master_secret =  
6656                 PK11_ImportSymKey(slot, CKM_SSL3_MASTER_KEY_DERIVE, 
6657                                   PK11_OriginUnwrap, CKA_ENCRYPT, 
6658                                   &wrappedMS, NULL);
6659             PK11_FreeSlot(slot);
6660             if (pwSpec->master_secret == NULL) {
6661                 break; 
6662             }
6663         }
6664
6665         /* Got a Match */
6666         SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_cache_hits );
6667
6668         /* If we sent a session ticket, then this is a stateless resume. */
6669         if (ss->xtnData.sentSessionTicketInClientHello)
6670             SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_stateless_resumes );
6671
6672         if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn))
6673             ss->ssl3.hs.ws = wait_new_session_ticket;
6674         else
6675             ss->ssl3.hs.ws = wait_change_cipher;
6676
6677         ss->ssl3.hs.isResuming = PR_TRUE;
6678
6679         /* copy the peer cert from the SID */
6680         if (sid->peerCert != NULL) {
6681             ss->sec.peerCert = CERT_DupCertificate(sid->peerCert);
6682             ssl3_CopyPeerCertsFromSID(ss, sid);
6683         }
6684
6685         /* NULL value for PMS signifies re-use of the old MS */
6686         rv = ssl3_InitPendingCipherSpec(ss,  NULL);
6687         if (rv != SECSuccess) {
6688             goto alert_loser;   /* err code was set */
6689         }
6690         goto winner;
6691     } while (0);
6692
6693     if (sid_match)
6694         SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_cache_not_ok );
6695     else
6696         SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_cache_misses );
6697
6698     /* throw the old one away */
6699     sid->u.ssl3.keys.resumable = PR_FALSE;
6700     if (ss->sec.uncache)
6701         (*ss->sec.uncache)(sid);
6702     ssl_FreeSID(sid);
6703
6704     /* get a new sid */
6705     ss->sec.ci.sid = sid = ssl3_NewSessionID(ss, PR_FALSE);
6706     if (sid == NULL) {
6707         goto alert_loser;       /* memory error is set. */
6708     }
6709
6710     sid->version = ss->version;
6711     sid->u.ssl3.sessionIDLength = sidBytes.len;
6712     PORT_Memcpy(sid->u.ssl3.sessionID, sidBytes.data, sidBytes.len);
6713
6714     /* Copy Signed Certificate Timestamps, if any. */
6715     if (ss->xtnData.signedCertTimestamps.data) {
6716         rv = SECITEM_CopyItem(NULL, &sid->u.ssl3.signedCertTimestamps,
6717                               &ss->xtnData.signedCertTimestamps);
6718         if (rv != SECSuccess)
6719             goto loser;
6720     }
6721
6722     ss->ssl3.hs.isResuming = PR_FALSE;
6723     ss->ssl3.hs.ws         = wait_server_cert;
6724
6725 winner:
6726     /* Clean up the temporary pointer to the handshake buffer. */
6727     ss->xtnData.signedCertTimestamps.data = NULL;
6728     ss->xtnData.signedCertTimestamps.len = 0;
6729
6730     /* If we will need a ChannelID key then we make the callback now. This
6731      * allows the handshake to be restarted cleanly if the callback returns
6732      * SECWouldBlock. */
6733     if (ssl3_ExtensionNegotiated(ss, ssl_channel_id_xtn)) {
6734         rv = ss->getChannelID(ss->getChannelIDArg, ss->fd,
6735                               &ss->ssl3.channelIDPub, &ss->ssl3.channelID);
6736         if (rv == SECWouldBlock) {
6737             ssl3_SetAlwaysBlock(ss);
6738             return rv;
6739         }
6740         if (rv != SECSuccess ||
6741             ss->ssl3.channelIDPub == NULL ||
6742             ss->ssl3.channelID == NULL) {
6743             PORT_SetError(SSL_ERROR_GET_CHANNEL_ID_FAILED);
6744             desc = internal_error;
6745             goto alert_loser;
6746         }
6747     }
6748
6749     return SECSuccess;
6750
6751 alert_loser:
6752     (void)SSL3_SendAlert(ss, alert_fatal, desc);
6753
6754 loser:
6755     /* Clean up the temporary pointer to the handshake buffer. */
6756     ss->xtnData.signedCertTimestamps.data = NULL;
6757     ss->xtnData.signedCertTimestamps.len = 0;
6758     errCode = ssl_MapLowLevelError(errCode);
6759     return SECFailure;
6760 }
6761
6762 /* ssl3_BigIntGreaterThanOne returns true iff |mpint|, taken as an unsigned,
6763  * big-endian integer is > 1 */
6764 static PRBool
6765 ssl3_BigIntGreaterThanOne(const SECItem* mpint) {
6766     unsigned char firstNonZeroByte = 0;
6767     unsigned int i;
6768
6769     for (i = 0; i < mpint->len; i++) {
6770         if (mpint->data[i]) {
6771             firstNonZeroByte = mpint->data[i];
6772             break;
6773         }
6774     }
6775
6776     if (firstNonZeroByte == 0)
6777         return PR_FALSE;
6778     if (firstNonZeroByte > 1)
6779         return PR_TRUE;
6780
6781     /* firstNonZeroByte == 1, therefore mpint > 1 iff the first non-zero byte
6782      * is followed by another byte. */
6783     return (i < mpint->len - 1);
6784 }
6785
6786 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
6787  * ssl3 ServerKeyExchange message.
6788  * Caller must hold Handshake and RecvBuf locks.
6789  */
6790 static SECStatus
6791 ssl3_HandleServerKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
6792 {
6793     PLArenaPool *    arena     = NULL;
6794     SECKEYPublicKey *peerKey   = NULL;
6795     PRBool           isTLS, isTLS12;
6796     SECStatus        rv;
6797     int              errCode   = SSL_ERROR_RX_MALFORMED_SERVER_KEY_EXCH;
6798     SSL3AlertDescription desc  = illegal_parameter;
6799     SSL3Hashes       hashes;
6800     SECItem          signature = {siBuffer, NULL, 0};
6801     SSL3SignatureAndHashAlgorithm sigAndHash;
6802
6803     sigAndHash.hashAlg = SEC_OID_UNKNOWN;
6804
6805     SSL_TRC(3, ("%d: SSL3[%d]: handle server_key_exchange handshake",
6806                 SSL_GETPID(), ss->fd));
6807     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
6808     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
6809
6810     if (ss->ssl3.hs.ws != wait_server_key &&
6811         ss->ssl3.hs.ws != wait_server_cert) {
6812         errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH;
6813         desc    = unexpected_message;
6814         goto alert_loser;
6815     }
6816     if (ss->sec.peerCert == NULL) {
6817         errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH;
6818         desc    = unexpected_message;
6819         goto alert_loser;
6820     }
6821
6822     isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
6823     isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
6824
6825     switch (ss->ssl3.hs.kea_def->exchKeyType) {
6826
6827     case kt_rsa: {
6828         SECItem          modulus   = {siBuffer, NULL, 0};
6829         SECItem          exponent  = {siBuffer, NULL, 0};
6830
6831         rv = ssl3_ConsumeHandshakeVariable(ss, &modulus, 2, &b, &length);
6832         if (rv != SECSuccess) {
6833             goto loser;         /* malformed. */
6834         }
6835         rv = ssl3_ConsumeHandshakeVariable(ss, &exponent, 2, &b, &length);
6836         if (rv != SECSuccess) {
6837             goto loser;         /* malformed. */
6838         }
6839         if (isTLS12) {
6840             rv = ssl3_ConsumeSignatureAndHashAlgorithm(ss, &b, &length,
6841                                                        &sigAndHash);
6842             if (rv != SECSuccess) {
6843                 goto loser;     /* malformed or unsupported. */
6844             }
6845             rv = ssl3_CheckSignatureAndHashAlgorithmConsistency(
6846                     &sigAndHash, ss->sec.peerCert);
6847             if (rv != SECSuccess) {
6848                 goto loser;
6849             }
6850         }
6851         rv = ssl3_ConsumeHandshakeVariable(ss, &signature, 2, &b, &length);
6852         if (rv != SECSuccess) {
6853             goto loser;         /* malformed. */
6854         }
6855         if (length != 0) {
6856             if (isTLS)
6857                 desc = decode_error;
6858             goto alert_loser;           /* malformed. */
6859         }
6860
6861         /* failures after this point are not malformed handshakes. */
6862         /* TLS: send decrypt_error if signature failed. */
6863         desc = isTLS ? decrypt_error : handshake_failure;
6864
6865         /*
6866          *  check to make sure the hash is signed by right guy
6867          */
6868         rv = ssl3_ComputeExportRSAKeyHash(sigAndHash.hashAlg, modulus, exponent,
6869                                           &ss->ssl3.hs.client_random,
6870                                           &ss->ssl3.hs.server_random, 
6871                                           &hashes, ss->opt.bypassPKCS11);
6872         if (rv != SECSuccess) {
6873             errCode =
6874                 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
6875             goto alert_loser;
6876         }
6877         rv = ssl3_VerifySignedHashes(&hashes, ss->sec.peerCert, &signature,
6878                                     isTLS, ss->pkcs11PinArg);
6879         if (rv != SECSuccess)  {
6880             errCode =
6881                 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
6882             goto alert_loser;
6883         }
6884
6885         /*
6886          * we really need to build a new key here because we can no longer
6887          * ignore calling SECKEY_DestroyPublicKey. Using the key may allocate
6888          * pkcs11 slots and ID's.
6889          */
6890         arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
6891         if (arena == NULL) {
6892             goto no_memory;
6893         }
6894
6895         peerKey = PORT_ArenaZNew(arena, SECKEYPublicKey);
6896         if (peerKey == NULL) {
6897             PORT_FreeArena(arena, PR_FALSE);
6898             goto no_memory;
6899         }
6900
6901         peerKey->arena              = arena;
6902         peerKey->keyType            = rsaKey;
6903         peerKey->pkcs11Slot         = NULL;
6904         peerKey->pkcs11ID           = CK_INVALID_HANDLE;
6905         if (SECITEM_CopyItem(arena, &peerKey->u.rsa.modulus,        &modulus) ||
6906             SECITEM_CopyItem(arena, &peerKey->u.rsa.publicExponent, &exponent))
6907         {
6908             PORT_FreeArena(arena, PR_FALSE);
6909             goto no_memory;
6910         }
6911         ss->sec.peerKey = peerKey;
6912         ss->ssl3.hs.ws = wait_cert_request;
6913         return SECSuccess;
6914     }
6915
6916     case kt_dh: {
6917         SECItem          dh_p      = {siBuffer, NULL, 0};
6918         SECItem          dh_g      = {siBuffer, NULL, 0};
6919         SECItem          dh_Ys     = {siBuffer, NULL, 0};
6920
6921         rv = ssl3_ConsumeHandshakeVariable(ss, &dh_p, 2, &b, &length);
6922         if (rv != SECSuccess) {
6923             goto loser;         /* malformed. */
6924         }
6925         if (dh_p.len < 512/8) {
6926             errCode = SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY;
6927             goto alert_loser;
6928         }
6929         rv = ssl3_ConsumeHandshakeVariable(ss, &dh_g, 2, &b, &length);
6930         if (rv != SECSuccess) {
6931             goto loser;         /* malformed. */
6932         }
6933         if (dh_g.len > dh_p.len || !ssl3_BigIntGreaterThanOne(&dh_g))
6934             goto alert_loser;
6935         rv = ssl3_ConsumeHandshakeVariable(ss, &dh_Ys, 2, &b, &length);
6936         if (rv != SECSuccess) {
6937             goto loser;         /* malformed. */
6938         }
6939         if (dh_Ys.len > dh_p.len || !ssl3_BigIntGreaterThanOne(&dh_Ys))
6940             goto alert_loser;
6941         if (isTLS12) {
6942             rv = ssl3_ConsumeSignatureAndHashAlgorithm(ss, &b, &length,
6943                                                        &sigAndHash);
6944             if (rv != SECSuccess) {
6945                 goto loser;     /* malformed or unsupported. */
6946             }
6947             rv = ssl3_CheckSignatureAndHashAlgorithmConsistency(
6948                     &sigAndHash, ss->sec.peerCert);
6949             if (rv != SECSuccess) {
6950                 goto loser;
6951             }
6952         }
6953         rv = ssl3_ConsumeHandshakeVariable(ss, &signature, 2, &b, &length);
6954         if (rv != SECSuccess) {
6955             goto loser;         /* malformed. */
6956         }
6957         if (length != 0) {
6958             if (isTLS)
6959                 desc = decode_error;
6960             goto alert_loser;           /* malformed. */
6961         }
6962
6963         PRINT_BUF(60, (NULL, "Server DH p", dh_p.data, dh_p.len));
6964         PRINT_BUF(60, (NULL, "Server DH g", dh_g.data, dh_g.len));
6965         PRINT_BUF(60, (NULL, "Server DH Ys", dh_Ys.data, dh_Ys.len));
6966
6967         /* failures after this point are not malformed handshakes. */
6968         /* TLS: send decrypt_error if signature failed. */
6969         desc = isTLS ? decrypt_error : handshake_failure;
6970
6971         /*
6972          *  check to make sure the hash is signed by right guy
6973          */
6974         rv = ssl3_ComputeDHKeyHash(sigAndHash.hashAlg, dh_p, dh_g, dh_Ys,
6975                                           &ss->ssl3.hs.client_random,
6976                                           &ss->ssl3.hs.server_random, 
6977                                           &hashes, ss->opt.bypassPKCS11);
6978         if (rv != SECSuccess) {
6979             errCode =
6980                 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
6981             goto alert_loser;
6982         }
6983         rv = ssl3_VerifySignedHashes(&hashes, ss->sec.peerCert, &signature,
6984                                     isTLS, ss->pkcs11PinArg);
6985         if (rv != SECSuccess)  {
6986             errCode =
6987                 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
6988             goto alert_loser;
6989         }
6990
6991         /*
6992          * we really need to build a new key here because we can no longer
6993          * ignore calling SECKEY_DestroyPublicKey. Using the key may allocate
6994          * pkcs11 slots and ID's.
6995          */
6996         arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
6997         if (arena == NULL) {
6998             goto no_memory;
6999         }
7000
7001         ss->sec.peerKey = peerKey = PORT_ArenaZNew(arena, SECKEYPublicKey);
7002         if (peerKey == NULL) {
7003             goto no_memory;
7004         }
7005
7006         peerKey->arena              = arena;
7007         peerKey->keyType            = dhKey;
7008         peerKey->pkcs11Slot         = NULL;
7009         peerKey->pkcs11ID           = CK_INVALID_HANDLE;
7010
7011         if (SECITEM_CopyItem(arena, &peerKey->u.dh.prime,        &dh_p) ||
7012             SECITEM_CopyItem(arena, &peerKey->u.dh.base,         &dh_g) ||
7013             SECITEM_CopyItem(arena, &peerKey->u.dh.publicValue,  &dh_Ys))
7014         {
7015             PORT_FreeArena(arena, PR_FALSE);
7016             goto no_memory;
7017         }
7018         ss->sec.peerKey = peerKey;
7019         ss->ssl3.hs.ws = wait_cert_request;
7020         return SECSuccess;
7021     }
7022
7023 #ifdef NSS_ENABLE_ECC
7024     case kt_ecdh:
7025         rv = ssl3_HandleECDHServerKeyExchange(ss, b, length);
7026         return rv;
7027 #endif /* NSS_ENABLE_ECC */
7028
7029     default:
7030         desc    = handshake_failure;
7031         errCode = SEC_ERROR_UNSUPPORTED_KEYALG;
7032         break;          /* goto alert_loser; */
7033     }
7034
7035 alert_loser:
7036     (void)SSL3_SendAlert(ss, alert_fatal, desc);
7037 loser:
7038     PORT_SetError( errCode );
7039     return SECFailure;
7040
7041 no_memory:      /* no-memory error has already been set. */
7042     ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
7043     return SECFailure;
7044 }
7045
7046
7047 /*
7048  * Returns the TLS signature algorithm for the client authentication key and
7049  * whether it is an RSA or DSA key that may be able to sign only SHA-1 hashes.
7050  */
7051 static SECStatus
7052 ssl3_ExtractClientKeyInfo(sslSocket *ss,
7053                           TLSSignatureAlgorithm *sigAlg,
7054                           PRBool *preferSha1)
7055 {
7056     SECStatus rv = SECSuccess;
7057     SECKEYPublicKey *pubk;
7058
7059     pubk = CERT_ExtractPublicKey(ss->ssl3.clientCertificate);
7060     if (pubk == NULL) {
7061         rv = SECFailure;
7062         goto done;
7063     }
7064
7065     rv = ssl3_TLSSignatureAlgorithmForKeyType(pubk->keyType, sigAlg);
7066     if (rv != SECSuccess) {
7067         goto done;
7068     }
7069
7070 #if defined(NSS_PLATFORM_CLIENT_AUTH) && defined(_WIN32)
7071     /* If the key is in CAPI, assume conservatively that the CAPI service
7072      * provider may be unable to sign SHA-256 hashes.
7073      */
7074     if (ss->ssl3.platformClientKey->dwKeySpec != CERT_NCRYPT_KEY_SPEC) {
7075         /* CAPI only supports RSA and DSA signatures, so we don't need to
7076          * check the key type. */
7077         *preferSha1 = PR_TRUE;
7078         goto done;
7079     }
7080 #endif  /* NSS_PLATFORM_CLIENT_AUTH && _WIN32 */
7081
7082     /* If the key is a 1024-bit RSA or DSA key, assume conservatively that
7083      * it may be unable to sign SHA-256 hashes. This is the case for older
7084      * Estonian ID cards that have 1024-bit RSA keys. In FIPS 186-2 and
7085      * older, DSA key size is at most 1024 bits and the hash function must
7086      * be SHA-1.
7087      */
7088     if (pubk->keyType == rsaKey || pubk->keyType == dsaKey) {
7089         *preferSha1 = SECKEY_PublicKeyStrength(pubk) <= 128;
7090     } else {
7091         *preferSha1 = PR_FALSE;
7092     }
7093
7094 done:
7095     if (pubk)
7096         SECKEY_DestroyPublicKey(pubk);
7097     return rv;
7098 }
7099
7100 /* Destroys the backup handshake hash context if we don't need it. Note that
7101  * this function selects the hash algorithm for client authentication
7102  * signatures; ssl3_SendCertificateVerify uses the presence of the backup hash
7103  * to determine whether to use SHA-1 or SHA-256. */
7104 static void
7105 ssl3_DestroyBackupHandshakeHashIfNotNeeded(sslSocket *ss,
7106                                            const SECItem *algorithms)
7107 {
7108     SECStatus rv;
7109     TLSSignatureAlgorithm sigAlg;
7110     PRBool preferSha1;
7111     PRBool supportsSha1 = PR_FALSE;
7112     PRBool supportsSha256 = PR_FALSE;
7113     PRBool needBackupHash = PR_FALSE;
7114     unsigned int i;
7115
7116 #ifndef NO_PKCS11_BYPASS
7117     /* Backup handshake hash is not supported in PKCS #11 bypass mode. */
7118     if (ss->opt.bypassPKCS11) {
7119         PORT_Assert(!ss->ssl3.hs.backupHash);
7120         return;
7121     }
7122 #endif
7123     PORT_Assert(ss->ssl3.hs.backupHash);
7124
7125     /* Determine the key's signature algorithm and whether it prefers SHA-1. */
7126     rv = ssl3_ExtractClientKeyInfo(ss, &sigAlg, &preferSha1);
7127     if (rv != SECSuccess) {
7128         goto done;
7129     }
7130
7131     /* Determine the server's hash support for that signature algorithm. */
7132     for (i = 0; i < algorithms->len; i += 2) {
7133         if (algorithms->data[i+1] == sigAlg) {
7134             if (algorithms->data[i] == tls_hash_sha1) {
7135                 supportsSha1 = PR_TRUE;
7136             } else if (algorithms->data[i] == tls_hash_sha256) {
7137                 supportsSha256 = PR_TRUE;
7138             }
7139         }
7140     }
7141
7142     /* If either the server does not support SHA-256 or the client key prefers
7143      * SHA-1, leave the backup hash. */
7144     if (supportsSha1 && (preferSha1 || !supportsSha256)) {
7145         needBackupHash = PR_TRUE;
7146     }
7147
7148 done:
7149     if (!needBackupHash) {
7150         PK11_DestroyContext(ss->ssl3.hs.backupHash, PR_TRUE);
7151         ss->ssl3.hs.backupHash = NULL;
7152     }
7153 }
7154
7155 typedef struct dnameNode {
7156     struct dnameNode *next;
7157     SECItem           name;
7158 } dnameNode;
7159
7160 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
7161  * ssl3 Certificate Request message.
7162  * Caller must hold Handshake and RecvBuf locks.
7163  */
7164 static SECStatus
7165 ssl3_HandleCertificateRequest(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
7166 {
7167     PLArenaPool *        arena       = NULL;
7168     dnameNode *          node;
7169     PRInt32              remaining;
7170     PRBool               isTLS       = PR_FALSE;
7171     PRBool               isTLS12     = PR_FALSE;
7172     int                  i;
7173     int                  errCode     = SSL_ERROR_RX_MALFORMED_CERT_REQUEST;
7174     int                  nnames      = 0;
7175     SECStatus            rv;
7176     SSL3AlertDescription desc        = illegal_parameter;
7177     SECItem              cert_types  = {siBuffer, NULL, 0};
7178     SECItem              algorithms  = {siBuffer, NULL, 0};
7179     CERTDistNames        ca_list;
7180 #ifdef NSS_PLATFORM_CLIENT_AUTH
7181     CERTCertList *       platform_cert_list = NULL;
7182     CERTCertListNode *   certNode = NULL;
7183 #endif  /* NSS_PLATFORM_CLIENT_AUTH */
7184
7185     SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_request handshake",
7186                 SSL_GETPID(), ss->fd));
7187     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
7188     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
7189
7190     if (ss->ssl3.hs.ws != wait_cert_request &&
7191         ss->ssl3.hs.ws != wait_server_key) {
7192         desc    = unexpected_message;
7193         errCode = SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST;
7194         goto alert_loser;
7195     }
7196
7197     PORT_Assert(ss->ssl3.clientCertChain == NULL);
7198     PORT_Assert(ss->ssl3.clientCertificate == NULL);
7199     PORT_Assert(ss->ssl3.clientPrivateKey == NULL);
7200     PORT_Assert(ss->ssl3.platformClientKey == (PlatformKey)NULL);
7201
7202     isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
7203     isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
7204     rv = ssl3_ConsumeHandshakeVariable(ss, &cert_types, 1, &b, &length);
7205     if (rv != SECSuccess)
7206         goto loser;             /* malformed, alert has been sent */
7207
7208     PORT_Assert(!ss->requestedCertTypes);
7209     ss->requestedCertTypes = &cert_types;
7210
7211     if (isTLS12) {
7212         rv = ssl3_ConsumeHandshakeVariable(ss, &algorithms, 2, &b, &length);
7213         if (rv != SECSuccess)
7214             goto loser;         /* malformed, alert has been sent */
7215         /* An empty or odd-length value is invalid.
7216          *    SignatureAndHashAlgorithm
7217          *      supported_signature_algorithms<2..2^16-2>;
7218          */
7219         if (algorithms.len == 0 || (algorithms.len & 1) != 0)
7220             goto alert_loser;
7221     }
7222
7223     arena = ca_list.arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
7224     if (arena == NULL)
7225         goto no_mem;
7226
7227     remaining = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
7228     if (remaining < 0)
7229         goto loser;             /* malformed, alert has been sent */
7230
7231     if ((PRUint32)remaining > length)
7232         goto alert_loser;
7233
7234     ca_list.head = node = PORT_ArenaZNew(arena, dnameNode);
7235     if (node == NULL)
7236         goto no_mem;
7237
7238     while (remaining > 0) {
7239         PRInt32 len;
7240
7241         if (remaining < 2)
7242             goto alert_loser;   /* malformed */
7243
7244         node->name.len = len = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
7245         if (len <= 0)
7246             goto loser;         /* malformed, alert has been sent */
7247
7248         remaining -= 2;
7249         if (remaining < len)
7250             goto alert_loser;   /* malformed */
7251
7252         node->name.data = b;
7253         b         += len;
7254         length    -= len;
7255         remaining -= len;
7256         nnames++;
7257         if (remaining <= 0)
7258             break;              /* success */
7259
7260         node->next = PORT_ArenaZNew(arena, dnameNode);
7261         node = node->next;
7262         if (node == NULL)
7263             goto no_mem;
7264     }
7265
7266     ca_list.nnames = nnames;
7267     ca_list.names  = PORT_ArenaNewArray(arena, SECItem, nnames);
7268     if (nnames > 0 && ca_list.names == NULL)
7269         goto no_mem;
7270
7271     for(i = 0, node = (dnameNode*)ca_list.head;
7272         i < nnames;
7273         i++, node = node->next) {
7274         ca_list.names[i] = node->name;
7275     }
7276
7277     if (length != 0)
7278         goto alert_loser;       /* malformed */
7279
7280     desc = no_certificate;
7281     ss->ssl3.hs.ws = wait_hello_done;
7282
7283 #ifdef NSS_PLATFORM_CLIENT_AUTH
7284     if (ss->getPlatformClientAuthData != NULL) {
7285         /* XXX Should pass cert_types and algorithms in this call!! */
7286         rv = (SECStatus)(*ss->getPlatformClientAuthData)(
7287                                         ss->getPlatformClientAuthDataArg,
7288                                         ss->fd, &ca_list,
7289                                         &platform_cert_list,
7290                                         (void**)&ss->ssl3.platformClientKey,
7291                                         &ss->ssl3.clientCertificate,
7292                                         &ss->ssl3.clientPrivateKey);
7293     } else
7294 #endif
7295     if (ss->getClientAuthData != NULL) {
7296         /* XXX Should pass cert_types and algorithms in this call!! */
7297         rv = (SECStatus)(*ss->getClientAuthData)(ss->getClientAuthDataArg,
7298                                                  ss->fd, &ca_list,
7299                                                  &ss->ssl3.clientCertificate,
7300                                                  &ss->ssl3.clientPrivateKey);
7301     } else {
7302         rv = SECFailure; /* force it to send a no_certificate alert */
7303     }
7304
7305     switch (rv) {
7306     case SECWouldBlock: /* getClientAuthData has put up a dialog box. */
7307         ssl3_SetAlwaysBlock(ss);
7308         break;  /* not an error */
7309
7310     case SECSuccess:
7311 #ifdef NSS_PLATFORM_CLIENT_AUTH
7312         if (!platform_cert_list || CERT_LIST_EMPTY(platform_cert_list) ||
7313             !ss->ssl3.platformClientKey) {
7314             if (platform_cert_list) {
7315                 CERT_DestroyCertList(platform_cert_list);
7316                 platform_cert_list = NULL;
7317             }
7318             if (ss->ssl3.platformClientKey) {
7319                 ssl_FreePlatformKey(ss->ssl3.platformClientKey);
7320                 ss->ssl3.platformClientKey = (PlatformKey)NULL;
7321             }
7322             /* Fall through to NSS client auth check */
7323         } else {
7324             certNode = CERT_LIST_HEAD(platform_cert_list);
7325             ss->ssl3.clientCertificate = CERT_DupCertificate(certNode->cert);
7326
7327             /* Setting ssl3.clientCertChain non-NULL will cause
7328              * ssl3_HandleServerHelloDone to call SendCertificate.
7329              * Note: clientCertChain should include the EE cert as
7330              * clientCertificate is ignored during the actual sending
7331              */
7332             ss->ssl3.clientCertChain =
7333                     hack_NewCertificateListFromCertList(platform_cert_list);
7334             CERT_DestroyCertList(platform_cert_list);
7335             platform_cert_list = NULL;
7336             if (ss->ssl3.clientCertChain == NULL) {
7337                 if (ss->ssl3.clientCertificate != NULL) {
7338                     CERT_DestroyCertificate(ss->ssl3.clientCertificate);
7339                     ss->ssl3.clientCertificate = NULL;
7340                 }
7341                 if (ss->ssl3.platformClientKey) {
7342                     ssl_FreePlatformKey(ss->ssl3.platformClientKey);
7343                     ss->ssl3.platformClientKey = (PlatformKey)NULL;
7344                 }
7345                 goto send_no_certificate;
7346             }
7347             if (ss->ssl3.hs.hashType == handshake_hash_single) {
7348                 ssl3_DestroyBackupHandshakeHashIfNotNeeded(ss, &algorithms);
7349             }
7350             break;  /* not an error */
7351         }
7352 #endif   /* NSS_PLATFORM_CLIENT_AUTH */
7353         /* check what the callback function returned */
7354         if ((!ss->ssl3.clientCertificate) || (!ss->ssl3.clientPrivateKey)) {
7355             /* we are missing either the key or cert */
7356             if (ss->ssl3.clientCertificate) {
7357                 /* got a cert, but no key - free it */
7358                 CERT_DestroyCertificate(ss->ssl3.clientCertificate);
7359                 ss->ssl3.clientCertificate = NULL;
7360             }
7361             if (ss->ssl3.clientPrivateKey) {
7362                 /* got a key, but no cert - free it */
7363                 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
7364                 ss->ssl3.clientPrivateKey = NULL;
7365             }
7366             goto send_no_certificate;
7367         }
7368         /* Setting ssl3.clientCertChain non-NULL will cause
7369          * ssl3_HandleServerHelloDone to call SendCertificate.
7370          */
7371         ss->ssl3.clientCertChain = CERT_CertChainFromCert(
7372                                         ss->ssl3.clientCertificate,
7373                                         certUsageSSLClient, PR_FALSE);
7374         if (ss->ssl3.clientCertChain == NULL) {
7375             CERT_DestroyCertificate(ss->ssl3.clientCertificate);
7376             ss->ssl3.clientCertificate = NULL;
7377             SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
7378             ss->ssl3.clientPrivateKey = NULL;
7379             goto send_no_certificate;
7380         }
7381         if (ss->ssl3.hs.hashType == handshake_hash_single) {
7382             ssl3_DestroyBackupHandshakeHashIfNotNeeded(ss, &algorithms);
7383         }
7384         break;  /* not an error */
7385
7386     case SECFailure:
7387     default:
7388 send_no_certificate:
7389         if (isTLS) {
7390             ss->ssl3.sendEmptyCert = PR_TRUE;
7391         } else {
7392             (void)SSL3_SendAlert(ss, alert_warning, no_certificate);
7393         }
7394         rv = SECSuccess;
7395         break;
7396     }
7397     goto done;
7398
7399 no_mem:
7400     rv = SECFailure;
7401     PORT_SetError(SEC_ERROR_NO_MEMORY);
7402     goto done;
7403
7404 alert_loser:
7405     if (isTLS && desc == illegal_parameter)
7406         desc = decode_error;
7407     (void)SSL3_SendAlert(ss, alert_fatal, desc);
7408 loser:
7409     PORT_SetError(errCode);
7410     rv = SECFailure;
7411 done:
7412     ss->requestedCertTypes = NULL;
7413     if (arena != NULL)
7414         PORT_FreeArena(arena, PR_FALSE);
7415 #ifdef NSS_PLATFORM_CLIENT_AUTH
7416     if (platform_cert_list)
7417         CERT_DestroyCertList(platform_cert_list);
7418 #endif
7419     return rv;
7420 }
7421
7422 /*
7423  * attempt to restart the handshake after asynchronously handling
7424  * a request for the client's certificate.
7425  *
7426  * inputs:
7427  *      cert    Client cert chosen by application.
7428  *              Note: ssl takes this reference, and does not bump the
7429  *              reference count.  The caller should drop its reference
7430  *              without calling CERT_DestroyCert after calling this function.
7431  *
7432  *      key     Private key associated with cert.  This function takes
7433  *              ownership of the private key, so the caller should drop its
7434  *              reference without destroying the private key after this
7435  *              function returns.
7436  *
7437  *      certChain  DER-encoded certs, client cert and its signers.
7438  *              Note: ssl takes this reference, and does not copy the chain.
7439  *              The caller should drop its reference without destroying the
7440  *              chain.  SSL will free the chain when it is done with it.
7441  *
7442  * Return value: XXX
7443  *
7444  * XXX This code only works on the initial handshake on a connection, XXX
7445  *     It does not work on a subsequent handshake (redo).
7446  *
7447  * Caller holds 1stHandshakeLock.
7448  */
7449 SECStatus
7450 ssl3_RestartHandshakeAfterCertReq(sslSocket *         ss,
7451                                 CERTCertificate *    cert,
7452                                 SECKEYPrivateKey *   key,
7453                                 CERTCertificateList *certChain)
7454 {
7455     SECStatus        rv          = SECSuccess;
7456
7457     /* XXX This code only works on the initial handshake on a connection,
7458     ** XXX It does not work on a subsequent handshake (redo).
7459     */
7460     if (ss->handshake != 0) {
7461         ss->handshake              = ssl_GatherRecord1stHandshake;
7462         ss->ssl3.clientCertificate = cert;
7463         ss->ssl3.clientPrivateKey  = key;
7464         ss->ssl3.clientCertChain   = certChain;
7465         if (!cert || !key || !certChain) {
7466             /* we are missing the key, cert, or cert chain */
7467             if (ss->ssl3.clientCertificate) {
7468                 CERT_DestroyCertificate(ss->ssl3.clientCertificate);
7469                 ss->ssl3.clientCertificate = NULL;
7470             }
7471             if (ss->ssl3.clientPrivateKey) {
7472                 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
7473                 ss->ssl3.clientPrivateKey = NULL;
7474             }
7475             if (ss->ssl3.clientCertChain != NULL) {
7476                 CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
7477                 ss->ssl3.clientCertChain = NULL;
7478             }
7479             if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0) {
7480                 ss->ssl3.sendEmptyCert = PR_TRUE;
7481             } else {
7482                 (void)SSL3_SendAlert(ss, alert_warning, no_certificate);
7483             }
7484         }
7485     } else {
7486         if (cert) {
7487             CERT_DestroyCertificate(cert);
7488         }
7489         if (key) {
7490             SECKEY_DestroyPrivateKey(key);
7491         }
7492         if (certChain) {
7493             CERT_DestroyCertificateList(certChain);
7494         }
7495         PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
7496         rv = SECFailure;
7497     }
7498     return rv;
7499 }
7500
7501 static SECStatus
7502 ssl3_CheckFalseStart(sslSocket *ss)
7503 {
7504     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
7505     PORT_Assert( !ss->ssl3.hs.authCertificatePending );
7506     PORT_Assert( !ss->ssl3.hs.canFalseStart );
7507
7508     if (!ss->canFalseStartCallback) {
7509         SSL_TRC(3, ("%d: SSL[%d]: no false start callback so no false start",
7510                     SSL_GETPID(), ss->fd));
7511     } else {
7512         PRBool maybeFalseStart;
7513         SECStatus rv;
7514
7515         /* An attacker can control the selected ciphersuite so we only wish to
7516          * do False Start in the case that the selected ciphersuite is
7517          * sufficiently strong that the attack can gain no advantage.
7518          * Therefore we always require an 80-bit cipher. */
7519         ssl_GetSpecReadLock(ss);
7520         maybeFalseStart = ss->ssl3.cwSpec->cipher_def->secret_key_size >= 10;
7521         ssl_ReleaseSpecReadLock(ss);
7522
7523         if (!maybeFalseStart) {
7524             SSL_TRC(3, ("%d: SSL[%d]: no false start due to weak cipher",
7525                         SSL_GETPID(), ss->fd));
7526         } else {
7527             rv = (ss->canFalseStartCallback)(ss->fd,
7528                                              ss->canFalseStartCallbackData,
7529                                              &ss->ssl3.hs.canFalseStart);
7530             if (rv == SECSuccess) {
7531                 SSL_TRC(3, ("%d: SSL[%d]: false start callback returned %s",
7532                             SSL_GETPID(), ss->fd,
7533                             ss->ssl3.hs.canFalseStart ? "TRUE" : "FALSE"));
7534             } else {
7535                 SSL_TRC(3, ("%d: SSL[%d]: false start callback failed (%s)",
7536                             SSL_GETPID(), ss->fd,
7537                             PR_ErrorToName(PR_GetError())));
7538             }
7539             return rv;
7540         }
7541     }
7542
7543     ss->ssl3.hs.canFalseStart = PR_FALSE;
7544     return SECSuccess;
7545 }
7546
7547 PRBool
7548 ssl3_WaitingForStartOfServerSecondRound(sslSocket *ss)
7549 {
7550     PRBool result;
7551
7552     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
7553
7554     switch (ss->ssl3.hs.ws) {
7555     case wait_new_session_ticket:
7556         result = PR_TRUE;
7557         break;
7558     case wait_change_cipher:
7559         result = !ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn);
7560         break;
7561     default:
7562         result = PR_FALSE;
7563         break;
7564     }
7565
7566     return result;
7567 }
7568
7569 static SECStatus ssl3_SendClientSecondRound(sslSocket *ss);
7570
7571 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
7572  * ssl3 Server Hello Done message.
7573  * Caller must hold Handshake and RecvBuf locks.
7574  */
7575 static SECStatus
7576 ssl3_HandleServerHelloDone(sslSocket *ss)
7577 {
7578     SECStatus     rv;
7579     SSL3WaitState ws          = ss->ssl3.hs.ws;
7580
7581     SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello_done handshake",
7582                 SSL_GETPID(), ss->fd));
7583     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
7584     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
7585
7586     if (ws != wait_hello_done  &&
7587         ws != wait_server_cert &&
7588         ws != wait_server_key  &&
7589         ws != wait_cert_request) {
7590         SSL3_SendAlert(ss, alert_fatal, unexpected_message);
7591         PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE);
7592         return SECFailure;
7593     }
7594
7595     rv = ssl3_SendClientSecondRound(ss);
7596
7597     return rv;
7598 }
7599
7600 /* Called from ssl3_HandleServerHelloDone and ssl3_AuthCertificateComplete.
7601  *
7602  * Caller must hold Handshake and RecvBuf locks.
7603  */
7604 static SECStatus
7605 ssl3_SendClientSecondRound(sslSocket *ss)
7606 {
7607     SECStatus rv;
7608     PRBool sendClientCert;
7609
7610     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
7611     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
7612
7613     sendClientCert = !ss->ssl3.sendEmptyCert &&
7614                      ss->ssl3.clientCertChain  != NULL &&
7615                      (ss->ssl3.platformClientKey ||
7616                      ss->ssl3.clientPrivateKey != NULL);
7617
7618     if (!sendClientCert &&
7619         ss->ssl3.hs.hashType == handshake_hash_single &&
7620         ss->ssl3.hs.backupHash) {
7621         /* Don't need the backup handshake hash. */
7622         PK11_DestroyContext(ss->ssl3.hs.backupHash, PR_TRUE);
7623         ss->ssl3.hs.backupHash = NULL;
7624     }
7625
7626     /* We must wait for the server's certificate to be authenticated before
7627      * sending the client certificate in order to disclosing the client
7628      * certificate to an attacker that does not have a valid cert for the
7629      * domain we are connecting to.
7630      *
7631      * XXX: We should do the same for the NPN extension, but for that we
7632      * need an option to give the application the ability to leak the NPN
7633      * information to get better performance.
7634      *
7635      * During the initial handshake on a connection, we never send/receive
7636      * application data until we have authenticated the server's certificate;
7637      * i.e. we have fully authenticated the handshake before using the cipher
7638      * specs agreed upon for that handshake. During a renegotiation, we may
7639      * continue sending and receiving application data during the handshake
7640      * interleaved with the handshake records. If we were to send the client's
7641      * second round for a renegotiation before the server's certificate was
7642      * authenticated, then the application data sent/received after this point
7643      * would be using cipher spec that hadn't been authenticated. By waiting
7644      * until the server's certificate has been authenticated during
7645      * renegotiations, we ensure that renegotiations have the same property
7646      * as initial handshakes; i.e. we have fully authenticated the handshake
7647      * before using the cipher specs agreed upon for that handshake for
7648      * application data.
7649      */
7650     if (ss->ssl3.hs.restartTarget) {
7651         PR_NOT_REACHED("unexpected ss->ssl3.hs.restartTarget");
7652         PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
7653         return SECFailure;
7654     }
7655     if (ss->ssl3.hs.authCertificatePending &&
7656         (sendClientCert || ss->ssl3.sendEmptyCert || ss->firstHsDone)) {
7657         SSL_TRC(3, ("%d: SSL3[%p]: deferring ssl3_SendClientSecondRound because"
7658                     " certificate authentication is still pending.",
7659                     SSL_GETPID(), ss->fd));
7660         ss->ssl3.hs.restartTarget = ssl3_SendClientSecondRound;
7661         return SECWouldBlock;
7662     }
7663
7664     ssl_GetXmitBufLock(ss);             /*******************************/
7665
7666     if (ss->ssl3.sendEmptyCert) {
7667         ss->ssl3.sendEmptyCert = PR_FALSE;
7668         rv = ssl3_SendEmptyCertificate(ss);
7669         /* Don't send verify */
7670         if (rv != SECSuccess) {
7671             goto loser; /* error code is set. */
7672         }
7673     } else if (sendClientCert) {
7674         rv = ssl3_SendCertificate(ss);
7675         if (rv != SECSuccess) {
7676             goto loser; /* error code is set. */
7677         }
7678     }
7679
7680     rv = ssl3_SendClientKeyExchange(ss);
7681     if (rv != SECSuccess) {
7682         goto loser;     /* err is set. */
7683     }
7684
7685     if (sendClientCert) {
7686         rv = ssl3_SendCertificateVerify(ss);
7687         if (rv != SECSuccess) {
7688             goto loser; /* err is set. */
7689         }
7690     }
7691
7692     rv = ssl3_SendChangeCipherSpecs(ss);
7693     if (rv != SECSuccess) {
7694         goto loser;     /* err code was set. */
7695     }
7696
7697     /* This must be done after we've set ss->ssl3.cwSpec in
7698      * ssl3_SendChangeCipherSpecs because SSL_GetChannelInfo uses information
7699      * from cwSpec. This must be done before we call ssl3_CheckFalseStart
7700      * because the false start callback (if any) may need the information from
7701      * the functions that depend on this being set.
7702      */
7703     ss->enoughFirstHsDone = PR_TRUE;
7704
7705     if (!ss->firstHsDone) {
7706         /* XXX: If the server's certificate hasn't been authenticated by this
7707          * point, then we may be leaking this NPN message to an attacker.
7708          */
7709         rv = ssl3_SendNextProto(ss);
7710         if (rv != SECSuccess) {
7711             goto loser; /* err code was set. */
7712         }
7713     }
7714
7715     rv = ssl3_SendEncryptedExtensions(ss);
7716     if (rv != SECSuccess) {
7717         goto loser; /* err code was set. */
7718     }
7719
7720     if (!ss->firstHsDone) {
7721         if (ss->opt.enableFalseStart) {
7722             if (!ss->ssl3.hs.authCertificatePending) {
7723                 /* When we fix bug 589047, we will need to know whether we are
7724                  * false starting before we try to flush the client second
7725                  * round to the network. With that in mind, we purposefully
7726                  * call ssl3_CheckFalseStart before calling ssl3_SendFinished,
7727                  * which includes a call to ssl3_FlushHandshake, so that
7728                  * no application develops a reliance on such flushing being
7729                  * done before its false start callback is called.
7730                  */
7731                 ssl_ReleaseXmitBufLock(ss);
7732                 rv = ssl3_CheckFalseStart(ss);
7733                 ssl_GetXmitBufLock(ss);
7734                 if (rv != SECSuccess) {
7735                     goto loser;
7736                 }
7737             } else {
7738                 /* The certificate authentication and the server's Finished
7739                  * message are racing each other. If the certificate
7740                  * authentication wins, then we will try to false start in
7741                  * ssl3_AuthCertificateComplete.
7742                  */
7743                 SSL_TRC(3, ("%d: SSL3[%p]: deferring false start check because"
7744                             " certificate authentication is still pending.",
7745                             SSL_GETPID(), ss->fd));
7746             }
7747         }
7748     }
7749
7750     rv = ssl3_SendFinished(ss, 0);
7751     if (rv != SECSuccess) {
7752         goto loser;     /* err code was set. */
7753     }
7754
7755     ssl_ReleaseXmitBufLock(ss);         /*******************************/
7756
7757     if (!ss->ssl3.hs.isResuming &&
7758         ssl3_ExtensionNegotiated(ss, ssl_channel_id_xtn)) {
7759         /* If we are negotiating ChannelID on a full handshake then we record
7760          * the handshake hashes in |sid| at this point. They will be needed in
7761          * the event that we resume this session and use ChannelID on the
7762          * resumption handshake. */
7763         SSL3Hashes hashes;
7764         SECItem *originalHandshakeHash =
7765             &ss->sec.ci.sid->u.ssl3.originalHandshakeHash;
7766         PORT_Assert(ss->sec.ci.sid->cached == never_cached);
7767
7768         ssl_GetSpecReadLock(ss);
7769         PORT_Assert(ss->version > SSL_LIBRARY_VERSION_3_0);
7770         rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.cwSpec, &hashes, 0);
7771         ssl_ReleaseSpecReadLock(ss);
7772         if (rv != SECSuccess) {
7773             return rv;
7774         }
7775
7776         PORT_Assert(originalHandshakeHash->len == 0);
7777         originalHandshakeHash->data = PORT_Alloc(hashes.len);
7778         if (!originalHandshakeHash->data)
7779             return SECFailure;
7780         originalHandshakeHash->len = hashes.len;
7781         memcpy(originalHandshakeHash->data, hashes.u.raw, hashes.len);
7782     }
7783
7784     if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn))
7785         ss->ssl3.hs.ws = wait_new_session_ticket;
7786     else
7787         ss->ssl3.hs.ws = wait_change_cipher;
7788
7789     PORT_Assert(ssl3_WaitingForStartOfServerSecondRound(ss));
7790
7791     return SECSuccess;
7792
7793 loser:
7794     ssl_ReleaseXmitBufLock(ss);
7795     return rv;
7796 }
7797
7798 /*
7799  * Routines used by servers
7800  */
7801 static SECStatus
7802 ssl3_SendHelloRequest(sslSocket *ss)
7803 {
7804     SECStatus rv;
7805
7806     SSL_TRC(3, ("%d: SSL3[%d]: send hello_request handshake", SSL_GETPID(),
7807                 ss->fd));
7808
7809     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
7810     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
7811
7812     rv = ssl3_AppendHandshakeHeader(ss, hello_request, 0);
7813     if (rv != SECSuccess) {
7814         return rv;      /* err set by AppendHandshake */
7815     }
7816     rv = ssl3_FlushHandshake(ss, 0);
7817     if (rv != SECSuccess) {
7818         return rv;      /* error code set by ssl3_FlushHandshake */
7819     }
7820     ss->ssl3.hs.ws = wait_client_hello;
7821     return SECSuccess;
7822 }
7823
7824 /*
7825  * Called from:
7826  *      ssl3_HandleClientHello()
7827  */
7828 static SECComparison
7829 ssl3_ServerNameCompare(const SECItem *name1, const SECItem *name2)
7830 {
7831     if (!name1 != !name2) {
7832         return SECLessThan;
7833     }
7834     if (!name1) {
7835         return SECEqual;
7836     }
7837     if (name1->type != name2->type) {
7838         return SECLessThan;
7839     }
7840     return SECITEM_CompareItem(name1, name2);
7841 }
7842
7843 /* Sets memory error when returning NULL.
7844  * Called from:
7845  *      ssl3_SendClientHello()
7846  *      ssl3_HandleServerHello()
7847  *      ssl3_HandleClientHello()
7848  *      ssl3_HandleV2ClientHello()
7849  */
7850 sslSessionID *
7851 ssl3_NewSessionID(sslSocket *ss, PRBool is_server)
7852 {
7853     sslSessionID *sid;
7854
7855     sid = PORT_ZNew(sslSessionID);
7856     if (sid == NULL)
7857         return sid;
7858
7859     if (is_server) {
7860         const SECItem *  srvName;
7861         SECStatus        rv = SECSuccess;
7862
7863         ssl_GetSpecReadLock(ss);        /********************************/
7864         srvName = &ss->ssl3.prSpec->srvVirtName;
7865         if (srvName->len && srvName->data) {
7866             rv = SECITEM_CopyItem(NULL, &sid->u.ssl3.srvName, srvName);
7867         }
7868         ssl_ReleaseSpecReadLock(ss); /************************************/
7869         if (rv != SECSuccess) {
7870             PORT_Free(sid);
7871             return NULL;
7872         }
7873     }
7874     sid->peerID         = (ss->peerID == NULL) ? NULL : PORT_Strdup(ss->peerID);
7875     sid->urlSvrName     = (ss->url    == NULL) ? NULL : PORT_Strdup(ss->url);
7876     sid->addr           = ss->sec.ci.peer;
7877     sid->port           = ss->sec.ci.port;
7878     sid->references     = 1;
7879     sid->cached         = never_cached;
7880     sid->version        = ss->version;
7881
7882     sid->u.ssl3.keys.resumable = PR_TRUE;
7883     sid->u.ssl3.policy         = SSL_ALLOWED;
7884     sid->u.ssl3.clientWriteKey = NULL;
7885     sid->u.ssl3.serverWriteKey = NULL;
7886
7887     if (is_server) {
7888         SECStatus rv;
7889         int       pid = SSL_GETPID();
7890
7891         sid->u.ssl3.sessionIDLength = SSL3_SESSIONID_BYTES;
7892         sid->u.ssl3.sessionID[0]    = (pid >> 8) & 0xff;
7893         sid->u.ssl3.sessionID[1]    =  pid       & 0xff;
7894         rv = PK11_GenerateRandom(sid->u.ssl3.sessionID + 2,
7895                                  SSL3_SESSIONID_BYTES -2);
7896         if (rv != SECSuccess) {
7897             ssl_FreeSID(sid);
7898             ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
7899             return NULL;
7900         }
7901     }
7902     return sid;
7903 }
7904
7905 /* Called from:  ssl3_HandleClientHello, ssl3_HandleV2ClientHello */
7906 static SECStatus
7907 ssl3_SendServerHelloSequence(sslSocket *ss)
7908 {
7909     const ssl3KEADef *kea_def;
7910     SECStatus         rv;
7911
7912     SSL_TRC(3, ("%d: SSL3[%d]: begin send server_hello sequence",
7913                 SSL_GETPID(), ss->fd));
7914
7915     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
7916     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
7917
7918     rv = ssl3_SendServerHello(ss);
7919     if (rv != SECSuccess) {
7920         return rv;      /* err code is set. */
7921     }
7922     rv = ssl3_SendCertificate(ss);
7923     if (rv != SECSuccess) {
7924         return rv;      /* error code is set. */
7925     }
7926     rv = ssl3_SendCertificateStatus(ss);
7927     if (rv != SECSuccess) {
7928         return rv;      /* error code is set. */
7929     }
7930     /* We have to do this after the call to ssl3_SendServerHello,
7931      * because kea_def is set up by ssl3_SendServerHello().
7932      */
7933     kea_def = ss->ssl3.hs.kea_def;
7934     ss->ssl3.hs.usedStepDownKey = PR_FALSE;
7935
7936     if (kea_def->is_limited && kea_def->exchKeyType == kt_rsa) {
7937         /* see if we can legally use the key in the cert. */
7938         int keyLen;  /* bytes */
7939
7940         keyLen = PK11_GetPrivateModulusLen(
7941                             ss->serverCerts[kea_def->exchKeyType].SERVERKEY);
7942
7943         if (keyLen > 0 &&
7944             keyLen * BPB <= kea_def->key_size_limit ) {
7945             /* XXX AND cert is not signing only!! */
7946             /* just fall through and use it. */
7947         } else if (ss->stepDownKeyPair != NULL) {
7948             ss->ssl3.hs.usedStepDownKey = PR_TRUE;
7949             rv = ssl3_SendServerKeyExchange(ss);
7950             if (rv != SECSuccess) {
7951                 return rv;      /* err code was set. */
7952             }
7953         } else {
7954 #ifndef HACKED_EXPORT_SERVER
7955             PORT_SetError(SSL_ERROR_PUB_KEY_SIZE_LIMIT_EXCEEDED);
7956             return rv;
7957 #endif
7958         }
7959 #ifdef NSS_ENABLE_ECC
7960     } else if ((kea_def->kea == kea_ecdhe_rsa) ||
7961                (kea_def->kea == kea_ecdhe_ecdsa)) {
7962         rv = ssl3_SendServerKeyExchange(ss);
7963         if (rv != SECSuccess) {
7964             return rv;  /* err code was set. */
7965         }
7966 #endif /* NSS_ENABLE_ECC */
7967     }
7968
7969     if (ss->opt.requestCertificate) {
7970         rv = ssl3_SendCertificateRequest(ss);
7971         if (rv != SECSuccess) {
7972             return rv;          /* err code is set. */
7973         }
7974     }
7975     rv = ssl3_SendServerHelloDone(ss);
7976     if (rv != SECSuccess) {
7977         return rv;              /* err code is set. */
7978     }
7979
7980     ss->ssl3.hs.ws = (ss->opt.requestCertificate) ? wait_client_cert
7981                                                : wait_client_key;
7982     return SECSuccess;
7983 }
7984
7985 /* An empty TLS Renegotiation Info (RI) extension */
7986 static const PRUint8 emptyRIext[5] = {0xff, 0x01, 0x00, 0x01, 0x00};
7987
7988 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
7989  * ssl3 Client Hello message.
7990  * Caller must hold Handshake and RecvBuf locks.
7991  */
7992 static SECStatus
7993 ssl3_HandleClientHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
7994 {
7995     sslSessionID *      sid      = NULL;
7996     PRInt32             tmp;
7997     unsigned int        i;
7998     int                 j;
7999     SECStatus           rv;
8000     int                 errCode  = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
8001     SSL3AlertDescription desc    = illegal_parameter;
8002     SSL3AlertLevel      level    = alert_fatal;
8003     SSL3ProtocolVersion version;
8004     SECItem             sidBytes = {siBuffer, NULL, 0};
8005     SECItem             cookieBytes = {siBuffer, NULL, 0};
8006     SECItem             suites   = {siBuffer, NULL, 0};
8007     SECItem             comps    = {siBuffer, NULL, 0};
8008     PRBool              haveSpecWriteLock = PR_FALSE;
8009     PRBool              haveXmitBufLock   = PR_FALSE;
8010
8011     SSL_TRC(3, ("%d: SSL3[%d]: handle client_hello handshake",
8012         SSL_GETPID(), ss->fd));
8013
8014     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
8015     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
8016     PORT_Assert( ss->ssl3.initialized );
8017
8018     /* Get peer name of client */
8019     rv = ssl_GetPeerInfo(ss);
8020     if (rv != SECSuccess) {
8021         return rv;              /* error code is set. */
8022     }
8023
8024     /* Clearing the handshake pointers so that ssl_Do1stHandshake won't
8025      * call ssl2_HandleMessage.
8026      *
8027      * The issue here is that TLS ordinarily starts out in
8028      * ssl2_HandleV3HandshakeRecord() because of the backward-compatibility
8029      * code paths. That function zeroes these next pointers. But with DTLS,
8030      * we don't even try to do the v2 ClientHello so we skip that function
8031      * and need to reset these values here.
8032      */
8033     if (IS_DTLS(ss)) {
8034         ss->nextHandshake     = 0;
8035         ss->securityHandshake = 0;
8036     }
8037
8038     /* We might be starting session renegotiation in which case we should
8039      * clear previous state.
8040      */
8041     PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData));
8042     ss->statelessResume = PR_FALSE;
8043
8044     if ((ss->ssl3.hs.ws != wait_client_hello) &&
8045         (ss->ssl3.hs.ws != idle_handshake)) {
8046         desc    = unexpected_message;
8047         errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO;
8048         goto alert_loser;
8049     }
8050     if (ss->ssl3.hs.ws == idle_handshake  &&
8051         ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) {
8052         desc    = no_renegotiation;
8053         level   = alert_warning;
8054         errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED;
8055         goto alert_loser;
8056     }
8057
8058     if (IS_DTLS(ss)) {
8059         dtls_RehandshakeCleanup(ss);
8060     }
8061
8062     tmp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
8063     if (tmp < 0)
8064         goto loser;             /* malformed, alert already sent */
8065
8066     /* Translate the version */
8067     if (IS_DTLS(ss)) {
8068         ss->clientHelloVersion = version =
8069             dtls_DTLSVersionToTLSVersion((SSL3ProtocolVersion)tmp);
8070     } else {
8071         ss->clientHelloVersion = version = (SSL3ProtocolVersion)tmp;
8072     }
8073
8074     rv = ssl3_NegotiateVersion(ss, version, PR_TRUE);
8075     if (rv != SECSuccess) {
8076         desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version 
8077                                                    : handshake_failure;
8078         errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
8079         goto alert_loser;
8080     }
8081
8082     rv = ssl3_InitHandshakeHashes(ss);
8083     if (rv != SECSuccess) {
8084         desc = internal_error;
8085         errCode = PORT_GetError();
8086         goto alert_loser;
8087     }
8088
8089     /* grab the client random data. */
8090     rv = ssl3_ConsumeHandshake(
8091         ss, &ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH, &b, &length);
8092     if (rv != SECSuccess) {
8093         goto loser;             /* malformed */
8094     }
8095
8096     /* grab the client's SID, if present. */
8097     rv = ssl3_ConsumeHandshakeVariable(ss, &sidBytes, 1, &b, &length);
8098     if (rv != SECSuccess) {
8099         goto loser;             /* malformed */
8100     }
8101
8102     /* grab the client's cookie, if present. */
8103     if (IS_DTLS(ss)) {
8104         rv = ssl3_ConsumeHandshakeVariable(ss, &cookieBytes, 1, &b, &length);
8105         if (rv != SECSuccess) {
8106             goto loser;         /* malformed */
8107         }
8108     }
8109
8110     /* grab the list of cipher suites. */
8111     rv = ssl3_ConsumeHandshakeVariable(ss, &suites, 2, &b, &length);
8112     if (rv != SECSuccess) {
8113         goto loser;             /* malformed */
8114     }
8115
8116     /* If the ClientHello version is less than our maximum version, check for a
8117      * TLS_FALLBACK_SCSV and reject the connection if found. */
8118     if (ss->vrange.max > ss->clientHelloVersion) {
8119         for (i = 0; i + 1 < suites.len; i += 2) {
8120             PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1];
8121             if (suite_i != TLS_FALLBACK_SCSV)
8122                 continue;
8123             desc = inappropriate_fallback;
8124             errCode = SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT;
8125             goto alert_loser;
8126         }
8127     }
8128
8129     /* grab the list of compression methods. */
8130     rv = ssl3_ConsumeHandshakeVariable(ss, &comps, 1, &b, &length);
8131     if (rv != SECSuccess) {
8132         goto loser;             /* malformed */
8133     }
8134
8135     desc = handshake_failure;
8136
8137     /* Handle TLS hello extensions for SSL3 & TLS. We do not know if
8138      * we are restarting a previous session until extensions have been
8139      * parsed, since we might have received a SessionTicket extension.
8140      * Note: we allow extensions even when negotiating SSL3 for the sake
8141      * of interoperability (and backwards compatibility).
8142      */
8143
8144     if (length) {
8145         /* Get length of hello extensions */
8146         PRInt32 extension_length;
8147         extension_length = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
8148         if (extension_length < 0) {
8149             goto loser;                         /* alert already sent */
8150         }
8151         if (extension_length != length) {
8152             ssl3_DecodeError(ss);               /* send alert */
8153             goto loser;
8154         }
8155         rv = ssl3_HandleHelloExtensions(ss, &b, &length);
8156         if (rv != SECSuccess) {
8157             goto loser;         /* malformed */
8158         }
8159     }
8160     if (!ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
8161         /* If we didn't receive an RI extension, look for the SCSV,
8162          * and if found, treat it just like an empty RI extension
8163          * by processing a local copy of an empty RI extension.
8164          */
8165         for (i = 0; i + 1 < suites.len; i += 2) {
8166             PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1];
8167             if (suite_i == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) {
8168                 SSL3Opaque * b2 = (SSL3Opaque *)emptyRIext;
8169                 PRUint32     L2 = sizeof emptyRIext;
8170                 (void)ssl3_HandleHelloExtensions(ss, &b2, &L2);
8171                 break;
8172             }
8173         }
8174     }
8175     if (ss->firstHsDone &&
8176         (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_REQUIRES_XTN ||
8177         ss->opt.enableRenegotiation == SSL_RENEGOTIATE_TRANSITIONAL) && 
8178         !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
8179         desc    = no_renegotiation;
8180         level   = alert_warning;
8181         errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED;
8182         goto alert_loser;
8183     }
8184     if ((ss->opt.requireSafeNegotiation || 
8185          (ss->firstHsDone && ss->peerRequestedProtection)) &&
8186         !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
8187         desc = handshake_failure;
8188         errCode = SSL_ERROR_UNSAFE_NEGOTIATION;
8189         goto alert_loser;
8190     }
8191
8192     /* We do stateful resumes only if either of the following
8193      * conditions are satisfied: (1) the client does not support the
8194      * session ticket extension, or (2) the client support the session
8195      * ticket extension, but sent an empty ticket.
8196      */
8197     if (!ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) ||
8198         ss->xtnData.emptySessionTicket) {
8199         if (sidBytes.len > 0 && !ss->opt.noCache) {
8200             SSL_TRC(7, ("%d: SSL3[%d]: server, lookup client session-id for 0x%08x%08x%08x%08x",
8201                         SSL_GETPID(), ss->fd, ss->sec.ci.peer.pr_s6_addr32[0],
8202                         ss->sec.ci.peer.pr_s6_addr32[1], 
8203                         ss->sec.ci.peer.pr_s6_addr32[2],
8204                         ss->sec.ci.peer.pr_s6_addr32[3]));
8205             if (ssl_sid_lookup) {
8206                 sid = (*ssl_sid_lookup)(&ss->sec.ci.peer, sidBytes.data, 
8207                                         sidBytes.len, ss->dbHandle);
8208             } else {
8209                 errCode = SSL_ERROR_SERVER_CACHE_NOT_CONFIGURED;
8210                 goto loser;
8211             }
8212         }
8213     } else if (ss->statelessResume) {
8214         /* Fill in the client's session ID if doing a stateless resume.
8215          * (When doing stateless resumes, server echos client's SessionID.)
8216          */
8217         sid = ss->sec.ci.sid;
8218         PORT_Assert(sid != NULL);  /* Should have already been filled in.*/
8219
8220         if (sidBytes.len > 0 && sidBytes.len <= SSL3_SESSIONID_BYTES) {
8221             sid->u.ssl3.sessionIDLength = sidBytes.len;
8222             PORT_Memcpy(sid->u.ssl3.sessionID, sidBytes.data,
8223                 sidBytes.len);
8224             sid->u.ssl3.sessionIDLength = sidBytes.len;
8225         } else {
8226             sid->u.ssl3.sessionIDLength = 0;
8227         }
8228         ss->sec.ci.sid = NULL;
8229     }
8230
8231     /* We only send a session ticket extension if the client supports
8232      * the extension and we are unable to do either a stateful or
8233      * stateless resume.
8234      *
8235      * TODO: send a session ticket if performing a stateful
8236      * resumption.  (As per RFC4507, a server may issue a session
8237      * ticket while doing a (stateless or stateful) session resume,
8238      * but OpenSSL-0.9.8g does not accept session tickets while
8239      * resuming.)
8240      */
8241     if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) && sid == NULL) {
8242         ssl3_RegisterServerHelloExtensionSender(ss,
8243             ssl_session_ticket_xtn, ssl3_SendSessionTicketXtn);
8244     }
8245
8246     if (sid != NULL) {
8247         /* We've found a session cache entry for this client.
8248          * Now, if we're going to require a client-auth cert,
8249          * and we don't already have this client's cert in the session cache,
8250          * and this is the first handshake on this connection (not a redo),
8251          * then drop this old cache entry and start a new session.
8252          */
8253         if ((sid->peerCert == NULL) && ss->opt.requestCertificate &&
8254             ((ss->opt.requireCertificate == SSL_REQUIRE_ALWAYS) ||
8255              (ss->opt.requireCertificate == SSL_REQUIRE_NO_ERROR) ||
8256              ((ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE) 
8257               && !ss->firstHsDone))) {
8258
8259             SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_not_ok );
8260             if (ss->sec.uncache)
8261                 ss->sec.uncache(sid);
8262             ssl_FreeSID(sid);
8263             sid = NULL;
8264         }
8265     }
8266
8267 #ifdef NSS_ENABLE_ECC
8268     /* Disable any ECC cipher suites for which we have no cert. */
8269     ssl3_FilterECCipherSuitesByServerCerts(ss);
8270 #endif
8271
8272     if (IS_DTLS(ss)) {
8273         ssl3_DisableNonDTLSSuites(ss);
8274     }
8275
8276     if (!ssl3_HasGCMSupport()) {
8277         ssl3_DisableGCMSuites(ss);
8278     }
8279
8280 #ifdef PARANOID
8281     /* Look for a matching cipher suite. */
8282     j = ssl3_config_match_init(ss);
8283     if (j <= 0) {               /* no ciphers are working/supported by PK11 */
8284         errCode = PORT_GetError();      /* error code is already set. */
8285         goto alert_loser;
8286     }
8287 #endif
8288
8289     /* If we already have a session for this client, be sure to pick the
8290     ** same cipher suite and compression method we picked before.
8291     ** This is not a loop, despite appearances.
8292     */
8293     if (sid) do {
8294         ssl3CipherSuiteCfg *suite;
8295 #ifdef PARANOID
8296         SSLVersionRange vrange = {ss->version, ss->version};
8297 #endif
8298
8299         /* Check that the cached compression method is still enabled. */
8300         if (!compressionEnabled(ss, sid->u.ssl3.compression))
8301             break;
8302
8303         /* Check that the cached compression method is in the client's list */
8304         for (i = 0; i < comps.len; i++) {
8305             if (comps.data[i] == sid->u.ssl3.compression)
8306                 break;
8307         }
8308         if (i == comps.len)
8309             break;
8310
8311         suite = ss->cipherSuites;
8312         /* Find the entry for the cipher suite used in the cached session. */
8313         for (j = ssl_V3_SUITES_IMPLEMENTED; j > 0; --j, ++suite) {
8314             if (suite->cipher_suite == sid->u.ssl3.cipherSuite)
8315                 break;
8316         }
8317         PORT_Assert(j > 0);
8318         if (j <= 0)
8319             break;
8320 #ifdef PARANOID
8321         /* Double check that the cached cipher suite is still enabled,
8322          * implemented, and allowed by policy.  Might have been disabled.
8323          * The product policy won't change during the process lifetime.  
8324          * Implemented ("isPresent") shouldn't change for servers.
8325          */
8326         if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange))
8327             break;
8328 #else
8329         if (!suite->enabled)
8330             break;
8331 #endif
8332         /* Double check that the cached cipher suite is in the client's list */
8333         for (i = 0; i + 1 < suites.len; i += 2) {
8334             PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1];
8335             if (suite_i == suite->cipher_suite) {
8336                 ss->ssl3.hs.cipher_suite = suite->cipher_suite;
8337                 ss->ssl3.hs.suite_def =
8338                     ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite);
8339
8340                 /* Use the cached compression method. */
8341                 ss->ssl3.hs.compression = sid->u.ssl3.compression;
8342                 goto compression_found;
8343             }
8344         }
8345     } while (0);
8346
8347     /* START A NEW SESSION */
8348
8349 #ifndef PARANOID
8350     /* Look for a matching cipher suite. */
8351     j = ssl3_config_match_init(ss);
8352     if (j <= 0) {               /* no ciphers are working/supported by PK11 */
8353         errCode = PORT_GetError();      /* error code is already set. */
8354         goto alert_loser;
8355     }
8356 #endif
8357
8358     /* Select a cipher suite.
8359     **
8360     ** NOTE: This suite selection algorithm should be the same as the one in
8361     ** ssl3_HandleV2ClientHello().
8362     **
8363     ** If TLS 1.0 is enabled, we could handle the case where the client
8364     ** offered TLS 1.1 but offered only export cipher suites by choosing TLS
8365     ** 1.0 and selecting one of those export cipher suites. However, a secure
8366     ** TLS 1.1 client should not have export cipher suites enabled at all,
8367     ** and a TLS 1.1 client should definitely not be offering *only* export
8368     ** cipher suites. Therefore, we refuse to negotiate export cipher suites
8369     ** with any client that indicates support for TLS 1.1 or higher when we
8370     ** (the server) have TLS 1.1 support enabled.
8371     */
8372     for (j = 0; j < ssl_V3_SUITES_IMPLEMENTED; j++) {
8373         ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j];
8374         SSLVersionRange vrange = {ss->version, ss->version};
8375         if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange)) {
8376             continue;
8377         }
8378         for (i = 0; i + 1 < suites.len; i += 2) {
8379             PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1];
8380             if (suite_i == suite->cipher_suite) {
8381                 ss->ssl3.hs.cipher_suite = suite->cipher_suite;
8382                 ss->ssl3.hs.suite_def =
8383                     ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite);
8384                 goto suite_found;
8385             }
8386         }
8387     }
8388     errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
8389     goto alert_loser;
8390
8391 suite_found:
8392     /* Select a compression algorithm. */
8393     for (i = 0; i < comps.len; i++) {
8394         if (!compressionEnabled(ss, comps.data[i]))
8395             continue;
8396         for (j = 0; j < compressionMethodsCount; j++) {
8397             if (comps.data[i] == compressions[j]) {
8398                 ss->ssl3.hs.compression = 
8399                                         (SSLCompressionMethod)compressions[j];
8400                 goto compression_found;
8401             }
8402         }
8403     }
8404     errCode = SSL_ERROR_NO_COMPRESSION_OVERLAP;
8405                                 /* null compression must be supported */
8406     goto alert_loser;
8407
8408 compression_found:
8409     suites.data = NULL;
8410     comps.data = NULL;
8411
8412     ss->sec.send = ssl3_SendApplicationData;
8413
8414     /* If there are any failures while processing the old sid,
8415      * we don't consider them to be errors.  Instead, We just behave
8416      * as if the client had sent us no sid to begin with, and make a new one.
8417      */
8418     if (sid != NULL) do {
8419         ssl3CipherSpec *pwSpec;
8420         SECItem         wrappedMS;      /* wrapped key */
8421
8422         if (sid->version != ss->version  ||
8423             sid->u.ssl3.cipherSuite != ss->ssl3.hs.cipher_suite ||
8424             sid->u.ssl3.compression != ss->ssl3.hs.compression) {
8425             break;      /* not an error */
8426         }
8427
8428         if (ss->sec.ci.sid) {
8429             if (ss->sec.uncache)
8430                 ss->sec.uncache(ss->sec.ci.sid);
8431             PORT_Assert(ss->sec.ci.sid != sid);  /* should be impossible, but ... */
8432             if (ss->sec.ci.sid != sid) {
8433                 ssl_FreeSID(ss->sec.ci.sid);
8434             }
8435             ss->sec.ci.sid = NULL;
8436         }
8437         /* we need to resurrect the master secret.... */
8438
8439         ssl_GetSpecWriteLock(ss);  haveSpecWriteLock = PR_TRUE;
8440         pwSpec = ss->ssl3.pwSpec;
8441         if (sid->u.ssl3.keys.msIsWrapped) {
8442             PK11SymKey *    wrapKey;    /* wrapping key */
8443             CK_FLAGS        keyFlags      = 0;
8444 #ifndef NO_PKCS11_BYPASS
8445             if (ss->opt.bypassPKCS11) {
8446                 /* we cannot restart a non-bypass session in a 
8447                 ** bypass socket.
8448                 */
8449                 break;  
8450             }
8451 #endif
8452
8453             wrapKey = getWrappingKey(ss, NULL, sid->u.ssl3.exchKeyType,
8454                                      sid->u.ssl3.masterWrapMech, 
8455                                      ss->pkcs11PinArg);
8456             if (!wrapKey) {
8457                 /* we have a SID cache entry, but no wrapping key for it??? */
8458                 break;
8459             }
8460
8461             if (ss->version > SSL_LIBRARY_VERSION_3_0) {        /* isTLS */
8462                 keyFlags = CKF_SIGN | CKF_VERIFY;
8463             }
8464
8465             wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
8466             wrappedMS.len  = sid->u.ssl3.keys.wrapped_master_secret_len;
8467
8468             /* unwrap the master secret. */
8469             pwSpec->master_secret =
8470                 PK11_UnwrapSymKeyWithFlags(wrapKey, sid->u.ssl3.masterWrapMech, 
8471                             NULL, &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE,
8472                             CKA_DERIVE, sizeof(SSL3MasterSecret), keyFlags);
8473             PK11_FreeSymKey(wrapKey);
8474             if (pwSpec->master_secret == NULL) {
8475                 break;  /* not an error */
8476             }
8477 #ifndef NO_PKCS11_BYPASS
8478         } else if (ss->opt.bypassPKCS11) {
8479             wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
8480             wrappedMS.len  = sid->u.ssl3.keys.wrapped_master_secret_len;
8481             memcpy(pwSpec->raw_master_secret, wrappedMS.data, wrappedMS.len);
8482             pwSpec->msItem.data = pwSpec->raw_master_secret;
8483             pwSpec->msItem.len  = wrappedMS.len;
8484 #endif
8485         } else {
8486             /* We CAN restart a bypass session in a non-bypass socket. */
8487             /* need to import the raw master secret to session object */
8488             PK11SlotInfo * slot;
8489             wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
8490             wrappedMS.len  = sid->u.ssl3.keys.wrapped_master_secret_len;
8491             slot = PK11_GetInternalSlot();
8492             pwSpec->master_secret =  
8493                 PK11_ImportSymKey(slot, CKM_SSL3_MASTER_KEY_DERIVE, 
8494                                   PK11_OriginUnwrap, CKA_ENCRYPT, &wrappedMS, 
8495                                   NULL);
8496             PK11_FreeSlot(slot);
8497             if (pwSpec->master_secret == NULL) {
8498                 break;  /* not an error */
8499             }
8500         }
8501         ss->sec.ci.sid = sid;
8502         if (sid->peerCert != NULL) {
8503             ss->sec.peerCert = CERT_DupCertificate(sid->peerCert);
8504             ssl3_CopyPeerCertsFromSID(ss, sid);
8505         }
8506
8507         /*
8508          * Old SID passed all tests, so resume this old session.
8509          *
8510          * XXX make sure compression still matches
8511          */
8512         SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_hits );
8513         if (ss->statelessResume)
8514             SSL_AtomicIncrementLong(& ssl3stats.hch_sid_stateless_resumes );
8515         ss->ssl3.hs.isResuming = PR_TRUE;
8516
8517         ss->sec.authAlgorithm = sid->authAlgorithm;
8518         ss->sec.authKeyBits   = sid->authKeyBits;
8519         ss->sec.keaType       = sid->keaType;
8520         ss->sec.keaKeyBits    = sid->keaKeyBits;
8521
8522         /* server sids don't remember the server cert we previously sent,
8523         ** but they do remember the kea type we originally used, so we
8524         ** can locate it again, provided that the current ssl socket
8525         ** has had its server certs configured the same as the previous one.
8526         */
8527         ss->sec.localCert     = 
8528                 CERT_DupCertificate(ss->serverCerts[sid->keaType].serverCert);
8529
8530         /* Copy cached name in to pending spec */
8531         if (sid != NULL &&
8532             sid->version > SSL_LIBRARY_VERSION_3_0 &&
8533             sid->u.ssl3.srvName.len && sid->u.ssl3.srvName.data) {
8534             /* Set server name from sid */
8535             SECItem *sidName = &sid->u.ssl3.srvName;
8536             SECItem *pwsName = &ss->ssl3.pwSpec->srvVirtName;
8537             if (pwsName->data) {
8538                 SECITEM_FreeItem(pwsName, PR_FALSE);
8539             }
8540             rv = SECITEM_CopyItem(NULL, pwsName, sidName);
8541             if (rv != SECSuccess) {
8542                 errCode = PORT_GetError();
8543                 desc = internal_error;
8544                 goto alert_loser;
8545             }
8546         }
8547
8548         /* Clean up sni name array */
8549         if (ssl3_ExtensionNegotiated(ss, ssl_server_name_xtn) &&
8550             ss->xtnData.sniNameArr) {
8551             PORT_Free(ss->xtnData.sniNameArr);
8552             ss->xtnData.sniNameArr = NULL;
8553             ss->xtnData.sniNameArrSize = 0;
8554         }
8555
8556         ssl_GetXmitBufLock(ss); haveXmitBufLock = PR_TRUE;
8557
8558         rv = ssl3_SendServerHello(ss);
8559         if (rv != SECSuccess) {
8560             errCode = PORT_GetError();
8561             goto loser;
8562         }
8563
8564         if (haveSpecWriteLock) {
8565             ssl_ReleaseSpecWriteLock(ss);
8566             haveSpecWriteLock = PR_FALSE;
8567         }
8568
8569         /* NULL value for PMS signifies re-use of the old MS */
8570         rv = ssl3_InitPendingCipherSpec(ss,  NULL);
8571         if (rv != SECSuccess) {
8572             errCode = PORT_GetError();
8573             goto loser;
8574         }
8575
8576         rv = ssl3_SendChangeCipherSpecs(ss);
8577         if (rv != SECSuccess) {
8578             errCode = PORT_GetError();
8579             goto loser;
8580         }
8581         rv = ssl3_SendFinished(ss, 0);
8582         ss->ssl3.hs.ws = wait_change_cipher;
8583         if (rv != SECSuccess) {
8584             errCode = PORT_GetError();
8585             goto loser;
8586         }
8587
8588         if (haveXmitBufLock) {
8589             ssl_ReleaseXmitBufLock(ss);
8590             haveXmitBufLock = PR_FALSE;
8591         }
8592
8593         return SECSuccess;
8594     } while (0);
8595
8596     if (haveSpecWriteLock) {
8597         ssl_ReleaseSpecWriteLock(ss);
8598         haveSpecWriteLock = PR_FALSE;
8599     }
8600
8601     if (sid) {  /* we had a sid, but it's no longer valid, free it */
8602         SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_not_ok );
8603         if (ss->sec.uncache)
8604             ss->sec.uncache(sid);
8605         ssl_FreeSID(sid);
8606         sid = NULL;
8607     }
8608     SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_misses );
8609
8610     if (ssl3_ExtensionNegotiated(ss, ssl_server_name_xtn)) {
8611         int ret = 0;
8612         if (ss->sniSocketConfig) do { /* not a loop */
8613             ret = SSL_SNI_SEND_ALERT;
8614             /* If extension is negotiated, the len of names should > 0. */
8615             if (ss->xtnData.sniNameArrSize) {
8616                 /* Calling client callback to reconfigure the socket. */
8617                 ret = (SECStatus)(*ss->sniSocketConfig)(ss->fd,
8618                                          ss->xtnData.sniNameArr,
8619                                       ss->xtnData.sniNameArrSize,
8620                                           ss->sniSocketConfigArg);
8621             }
8622             if (ret <= SSL_SNI_SEND_ALERT) {
8623                 /* Application does not know the name or was not able to
8624                  * properly reconfigure the socket. */
8625                 errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
8626                 desc = unrecognized_name;
8627                 break;
8628             } else if (ret == SSL_SNI_CURRENT_CONFIG_IS_USED) {
8629                 SECStatus       rv = SECSuccess;
8630                 SECItem *       cwsName, *pwsName;
8631
8632                 ssl_GetSpecWriteLock(ss);  /*******************************/
8633                 pwsName = &ss->ssl3.pwSpec->srvVirtName;
8634                 cwsName = &ss->ssl3.cwSpec->srvVirtName;
8635 #ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS
8636                 /* not allow name change on the 2d HS */
8637                 if (ss->firstHsDone) {
8638                     if (ssl3_ServerNameCompare(pwsName, cwsName)) {
8639                         ssl_ReleaseSpecWriteLock(ss);  /******************/
8640                         errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
8641                         desc = handshake_failure;
8642                         ret = SSL_SNI_SEND_ALERT;
8643                         break;
8644                     }
8645                 }
8646 #endif
8647                 if (pwsName->data) {
8648                     SECITEM_FreeItem(pwsName, PR_FALSE);
8649                 }
8650                 if (cwsName->data) {
8651                     rv = SECITEM_CopyItem(NULL, pwsName, cwsName);
8652                 }
8653                 ssl_ReleaseSpecWriteLock(ss);  /**************************/
8654                 if (rv != SECSuccess) {
8655                     errCode = SSL_ERROR_INTERNAL_ERROR_ALERT;
8656                     desc = internal_error;
8657                     ret = SSL_SNI_SEND_ALERT;
8658                     break;
8659                 }
8660             } else if (ret < ss->xtnData.sniNameArrSize) {
8661                 /* Application has configured new socket info. Lets check it
8662                  * and save the name. */
8663                 SECStatus       rv;
8664                 SECItem *       name = &ss->xtnData.sniNameArr[ret];
8665                 int             configedCiphers;
8666                 SECItem *       pwsName;
8667
8668                 /* get rid of the old name and save the newly picked. */
8669                 /* This code is protected by ssl3HandshakeLock. */
8670                 ssl_GetSpecWriteLock(ss);  /*******************************/
8671 #ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS
8672                 /* not allow name change on the 2d HS */
8673                 if (ss->firstHsDone) {
8674                     SECItem *cwsName = &ss->ssl3.cwSpec->srvVirtName;
8675                     if (ssl3_ServerNameCompare(name, cwsName)) {
8676                         ssl_ReleaseSpecWriteLock(ss);  /******************/
8677                         errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
8678                         desc = handshake_failure;
8679                         ret = SSL_SNI_SEND_ALERT;
8680                         break;
8681                     }
8682                 }
8683 #endif
8684                 pwsName = &ss->ssl3.pwSpec->srvVirtName;
8685                 if (pwsName->data) {
8686                     SECITEM_FreeItem(pwsName, PR_FALSE);
8687                 }
8688                 rv = SECITEM_CopyItem(NULL, pwsName, name);
8689                 ssl_ReleaseSpecWriteLock(ss);  /***************************/
8690                 if (rv != SECSuccess) {
8691                     errCode = SSL_ERROR_INTERNAL_ERROR_ALERT;
8692                     desc = internal_error;
8693                     ret = SSL_SNI_SEND_ALERT;
8694                     break;
8695                 }
8696                 configedCiphers = ssl3_config_match_init(ss);
8697                 if (configedCiphers <= 0) {
8698                     /* no ciphers are working/supported */
8699                     errCode = PORT_GetError();
8700                     desc = handshake_failure;
8701                     ret = SSL_SNI_SEND_ALERT;
8702                     break;
8703                 }
8704                 /* Need to tell the client that application has picked
8705                  * the name from the offered list and reconfigured the socket.
8706                  */
8707                 ssl3_RegisterServerHelloExtensionSender(ss, ssl_server_name_xtn,
8708                                                         ssl3_SendServerNameXtn);
8709             } else {
8710                 /* Callback returned index outside of the boundary. */
8711                 PORT_Assert(ret < ss->xtnData.sniNameArrSize);
8712                 errCode = SSL_ERROR_INTERNAL_ERROR_ALERT;
8713                 desc = internal_error;
8714                 ret = SSL_SNI_SEND_ALERT;
8715                 break;
8716             }
8717         } while (0);
8718         /* Free sniNameArr. The data that each SECItem in the array
8719          * points into is the data from the input buffer "b". It will
8720          * not be available outside the scope of this or it's child
8721          * functions.*/
8722         if (ss->xtnData.sniNameArr) {
8723             PORT_Free(ss->xtnData.sniNameArr);
8724             ss->xtnData.sniNameArr = NULL;
8725             ss->xtnData.sniNameArrSize = 0;
8726         }
8727         if (ret <= SSL_SNI_SEND_ALERT) {
8728             /* desc and errCode should be set. */
8729             goto alert_loser;
8730         }
8731     }
8732 #ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS
8733     else if (ss->firstHsDone) {
8734         /* Check that we don't have the name is current spec
8735          * if this extension was not negotiated on the 2d hs. */
8736         PRBool passed = PR_TRUE;
8737         ssl_GetSpecReadLock(ss);  /*******************************/
8738         if (ss->ssl3.cwSpec->srvVirtName.data) {
8739             passed = PR_FALSE;
8740         }
8741         ssl_ReleaseSpecReadLock(ss);  /***************************/
8742         if (!passed) {
8743             errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
8744             desc = handshake_failure;
8745             goto alert_loser;
8746         }
8747     }
8748 #endif
8749
8750     sid = ssl3_NewSessionID(ss, PR_TRUE);
8751     if (sid == NULL) {
8752         errCode = PORT_GetError();
8753         goto loser;     /* memory error is set. */
8754     }
8755     ss->sec.ci.sid = sid;
8756
8757     ss->ssl3.hs.isResuming = PR_FALSE;
8758     ssl_GetXmitBufLock(ss);
8759     rv = ssl3_SendServerHelloSequence(ss);
8760     ssl_ReleaseXmitBufLock(ss);
8761     if (rv != SECSuccess) {
8762         errCode = PORT_GetError();
8763         goto loser;
8764     }
8765
8766     if (haveXmitBufLock) {
8767         ssl_ReleaseXmitBufLock(ss);
8768         haveXmitBufLock = PR_FALSE;
8769     }
8770
8771     return SECSuccess;
8772
8773 alert_loser:
8774     if (haveSpecWriteLock) {
8775         ssl_ReleaseSpecWriteLock(ss);
8776         haveSpecWriteLock = PR_FALSE;
8777     }
8778     (void)SSL3_SendAlert(ss, level, desc);
8779     /* FALLTHRU */
8780 loser:
8781     if (haveSpecWriteLock) {
8782         ssl_ReleaseSpecWriteLock(ss);
8783         haveSpecWriteLock = PR_FALSE;
8784     }
8785
8786     if (haveXmitBufLock) {
8787         ssl_ReleaseXmitBufLock(ss);
8788         haveXmitBufLock = PR_FALSE;
8789     }
8790
8791     PORT_SetError(errCode);
8792     return SECFailure;
8793 }
8794
8795 /*
8796  * ssl3_HandleV2ClientHello is used when a V2 formatted hello comes
8797  * in asking to use the V3 handshake.
8798  * Called from ssl2_HandleClientHelloMessage() in sslcon.c
8799  */
8800 SECStatus
8801 ssl3_HandleV2ClientHello(sslSocket *ss, unsigned char *buffer, int length)
8802 {
8803     sslSessionID *      sid             = NULL;
8804     unsigned char *     suites;
8805     unsigned char *     random;
8806     SSL3ProtocolVersion version;
8807     SECStatus           rv;
8808     int                 i;
8809     int                 j;
8810     int                 sid_length;
8811     int                 suite_length;
8812     int                 rand_length;
8813     int                 errCode  = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
8814     SSL3AlertDescription desc    = handshake_failure;
8815
8816     SSL_TRC(3, ("%d: SSL3[%d]: handle v2 client_hello", SSL_GETPID(), ss->fd));
8817
8818     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
8819
8820     ssl_GetSSL3HandshakeLock(ss);
8821
8822     PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData));
8823
8824     rv = ssl3_InitState(ss);
8825     if (rv != SECSuccess) {
8826         ssl_ReleaseSSL3HandshakeLock(ss);
8827         return rv;              /* ssl3_InitState has set the error code. */
8828     }
8829     rv = ssl3_RestartHandshakeHashes(ss);
8830     if (rv != SECSuccess) {
8831         ssl_ReleaseSSL3HandshakeLock(ss);
8832         return rv;
8833     }
8834
8835     if (ss->ssl3.hs.ws != wait_client_hello) {
8836         desc    = unexpected_message;
8837         errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO;
8838         goto loser;     /* alert_loser */
8839     }
8840
8841     version      = (buffer[1] << 8) | buffer[2];
8842     suite_length = (buffer[3] << 8) | buffer[4];
8843     sid_length   = (buffer[5] << 8) | buffer[6];
8844     rand_length  = (buffer[7] << 8) | buffer[8];
8845     ss->clientHelloVersion = version;
8846
8847     rv = ssl3_NegotiateVersion(ss, version, PR_TRUE);
8848     if (rv != SECSuccess) {
8849         /* send back which ever alert client will understand. */
8850         desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version : handshake_failure;
8851         errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
8852         goto alert_loser;
8853     }
8854
8855     rv = ssl3_InitHandshakeHashes(ss);
8856     if (rv != SECSuccess) {
8857         desc = internal_error;
8858         errCode = PORT_GetError();
8859         goto alert_loser;
8860     }
8861
8862     /* if we get a non-zero SID, just ignore it. */
8863     if (length !=
8864         SSL_HL_CLIENT_HELLO_HBYTES + suite_length + sid_length + rand_length) {
8865         SSL_DBG(("%d: SSL3[%d]: bad v2 client hello message, len=%d should=%d",
8866                  SSL_GETPID(), ss->fd, length,
8867                  SSL_HL_CLIENT_HELLO_HBYTES + suite_length + sid_length +
8868                  rand_length));
8869         goto loser;     /* malformed */ /* alert_loser */
8870     }
8871
8872     suites = buffer + SSL_HL_CLIENT_HELLO_HBYTES;
8873     random = suites + suite_length + sid_length;
8874
8875     if (rand_length < SSL_MIN_CHALLENGE_BYTES ||
8876         rand_length > SSL_MAX_CHALLENGE_BYTES) {
8877         goto loser;     /* malformed */ /* alert_loser */
8878     }
8879
8880     PORT_Assert(SSL_MAX_CHALLENGE_BYTES == SSL3_RANDOM_LENGTH);
8881
8882     PORT_Memset(&ss->ssl3.hs.client_random, 0, SSL3_RANDOM_LENGTH);
8883     PORT_Memcpy(
8884         &ss->ssl3.hs.client_random.rand[SSL3_RANDOM_LENGTH - rand_length],
8885         random, rand_length);
8886
8887     PRINT_BUF(60, (ss, "client random:", &ss->ssl3.hs.client_random.rand[0],
8888                    SSL3_RANDOM_LENGTH));
8889 #ifdef NSS_ENABLE_ECC
8890     /* Disable any ECC cipher suites for which we have no cert. */
8891     ssl3_FilterECCipherSuitesByServerCerts(ss);
8892 #endif
8893     i = ssl3_config_match_init(ss);
8894     if (i <= 0) {
8895         errCode = PORT_GetError();      /* error code is already set. */
8896         goto alert_loser;
8897     }
8898
8899     /* Select a cipher suite.
8900     **
8901     ** NOTE: This suite selection algorithm should be the same as the one in
8902     ** ssl3_HandleClientHello().
8903     **
8904     ** See the comments about export cipher suites in ssl3_HandleClientHello().
8905     */
8906     for (j = 0; j < ssl_V3_SUITES_IMPLEMENTED; j++) {
8907         ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j];
8908         SSLVersionRange vrange = {ss->version, ss->version};
8909         if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange)) {
8910             continue;
8911         }
8912         for (i = 0; i+2 < suite_length; i += 3) {
8913             PRUint32 suite_i = (suites[i] << 16)|(suites[i+1] << 8)|suites[i+2];
8914             if (suite_i == suite->cipher_suite) {
8915                 ss->ssl3.hs.cipher_suite = suite->cipher_suite;
8916                 ss->ssl3.hs.suite_def =
8917                     ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite);
8918                 goto suite_found;
8919             }
8920         }
8921     }
8922     errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
8923     goto alert_loser;
8924
8925 suite_found:
8926
8927     /* Look for the SCSV, and if found, treat it just like an empty RI 
8928      * extension by processing a local copy of an empty RI extension.
8929      */
8930     for (i = 0; i+2 < suite_length; i += 3) {
8931         PRUint32 suite_i = (suites[i] << 16) | (suites[i+1] << 8) | suites[i+2];
8932         if (suite_i == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) {
8933             SSL3Opaque * b2 = (SSL3Opaque *)emptyRIext;
8934             PRUint32     L2 = sizeof emptyRIext;
8935             (void)ssl3_HandleHelloExtensions(ss, &b2, &L2);
8936             break;
8937         }
8938     }
8939
8940     if (ss->opt.requireSafeNegotiation &&
8941         !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
8942         desc = handshake_failure;
8943         errCode = SSL_ERROR_UNSAFE_NEGOTIATION;
8944         goto alert_loser;
8945     }
8946
8947     ss->ssl3.hs.compression = ssl_compression_null;
8948     ss->sec.send            = ssl3_SendApplicationData;
8949
8950     /* we don't even search for a cache hit here.  It's just a miss. */
8951     SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_misses );
8952     sid = ssl3_NewSessionID(ss, PR_TRUE);
8953     if (sid == NULL) {
8954         errCode = PORT_GetError();
8955         goto loser;     /* memory error is set. */
8956     }
8957     ss->sec.ci.sid = sid;
8958     /* do not worry about memory leak of sid since it now belongs to ci */
8959
8960     /* We have to update the handshake hashes before we can send stuff */
8961     rv = ssl3_UpdateHandshakeHashes(ss, buffer, length);
8962     if (rv != SECSuccess) {
8963         errCode = PORT_GetError();
8964         goto loser;
8965     }
8966
8967     ssl_GetXmitBufLock(ss);
8968     rv = ssl3_SendServerHelloSequence(ss);
8969     ssl_ReleaseXmitBufLock(ss);
8970     if (rv != SECSuccess) {
8971         errCode = PORT_GetError();
8972         goto loser;
8973     }
8974
8975     /* XXX_1    The call stack to here is:
8976      * ssl_Do1stHandshake -> ssl2_HandleClientHelloMessage -> here.
8977      * ssl2_HandleClientHelloMessage returns whatever we return here.
8978      * ssl_Do1stHandshake will continue looping if it gets back either
8979      *          SECSuccess or SECWouldBlock.
8980      * SECSuccess is preferable here.  See XXX_1 in sslgathr.c.
8981      */
8982     ssl_ReleaseSSL3HandshakeLock(ss);
8983     return SECSuccess;
8984
8985 alert_loser:
8986     SSL3_SendAlert(ss, alert_fatal, desc);
8987 loser:
8988     ssl_ReleaseSSL3HandshakeLock(ss);
8989     PORT_SetError(errCode);
8990     return SECFailure;
8991 }
8992
8993 /* The negotiated version number has been already placed in ss->version.
8994 **
8995 ** Called from:  ssl3_HandleClientHello                     (resuming session),
8996 **      ssl3_SendServerHelloSequence <- ssl3_HandleClientHello   (new session),
8997 **      ssl3_SendServerHelloSequence <- ssl3_HandleV2ClientHello (new session)
8998 */
8999 static SECStatus
9000 ssl3_SendServerHello(sslSocket *ss)
9001 {
9002     sslSessionID *sid;
9003     SECStatus     rv;
9004     PRUint32      maxBytes = 65535;
9005     PRUint32      length;
9006     PRInt32       extensions_len = 0;
9007     SSL3ProtocolVersion version;
9008
9009     SSL_TRC(3, ("%d: SSL3[%d]: send server_hello handshake", SSL_GETPID(),
9010                 ss->fd));
9011
9012     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
9013     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
9014
9015     if (!IS_DTLS(ss)) {
9016         PORT_Assert(MSB(ss->version) == MSB(SSL_LIBRARY_VERSION_3_0));
9017
9018         if (MSB(ss->version) != MSB(SSL_LIBRARY_VERSION_3_0)) {
9019             PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
9020             return SECFailure;
9021         }
9022     } else {
9023         PORT_Assert(MSB(ss->version) == MSB(SSL_LIBRARY_VERSION_DTLS_1_0));
9024
9025         if (MSB(ss->version) != MSB(SSL_LIBRARY_VERSION_DTLS_1_0)) {
9026             PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
9027             return SECFailure;
9028         }
9029     }
9030
9031     sid = ss->sec.ci.sid;
9032
9033     extensions_len = ssl3_CallHelloExtensionSenders(ss, PR_FALSE, maxBytes,
9034                                                &ss->xtnData.serverSenders[0]);
9035     if (extensions_len > 0)
9036         extensions_len += 2; /* Add sizeof total extension length */
9037
9038     length = sizeof(SSL3ProtocolVersion) + SSL3_RANDOM_LENGTH + 1 +
9039              ((sid == NULL) ? 0: sid->u.ssl3.sessionIDLength) +
9040              sizeof(ssl3CipherSuite) + 1 + extensions_len;
9041     rv = ssl3_AppendHandshakeHeader(ss, server_hello, length);
9042     if (rv != SECSuccess) {
9043         return rv;      /* err set by AppendHandshake. */
9044     }
9045
9046     if (IS_DTLS(ss)) {
9047         version = dtls_TLSVersionToDTLSVersion(ss->version);
9048     } else {
9049         version = ss->version;
9050     }
9051
9052     rv = ssl3_AppendHandshakeNumber(ss, version, 2);
9053     if (rv != SECSuccess) {
9054         return rv;      /* err set by AppendHandshake. */
9055     }
9056     rv = ssl3_GetNewRandom(&ss->ssl3.hs.server_random);
9057     if (rv != SECSuccess) {
9058         ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
9059         return rv;
9060     }
9061     rv = ssl3_AppendHandshake(
9062         ss, &ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH);
9063     if (rv != SECSuccess) {
9064         return rv;      /* err set by AppendHandshake. */
9065     }
9066
9067     if (sid)
9068         rv = ssl3_AppendHandshakeVariable(
9069             ss, sid->u.ssl3.sessionID, sid->u.ssl3.sessionIDLength, 1);
9070     else
9071         rv = ssl3_AppendHandshakeVariable(ss, NULL, 0, 1);
9072     if (rv != SECSuccess) {
9073         return rv;      /* err set by AppendHandshake. */
9074     }
9075
9076     rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.cipher_suite, 2);
9077     if (rv != SECSuccess) {
9078         return rv;      /* err set by AppendHandshake. */
9079     }
9080     rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.compression, 1);
9081     if (rv != SECSuccess) {
9082         return rv;      /* err set by AppendHandshake. */
9083     }
9084     if (extensions_len) {
9085         PRInt32 sent_len;
9086
9087         extensions_len -= 2;
9088         rv = ssl3_AppendHandshakeNumber(ss, extensions_len, 2);
9089         if (rv != SECSuccess) 
9090             return rv;  /* err set by ssl3_SetupPendingCipherSpec */
9091         sent_len = ssl3_CallHelloExtensionSenders(ss, PR_TRUE, extensions_len,
9092                                            &ss->xtnData.serverSenders[0]);
9093         PORT_Assert(sent_len == extensions_len);
9094         if (sent_len != extensions_len) {
9095             if (sent_len >= 0)
9096                 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
9097             return SECFailure;
9098         }
9099     }
9100     rv = ssl3_SetupPendingCipherSpec(ss);
9101     if (rv != SECSuccess) {
9102         return rv;      /* err set by ssl3_SetupPendingCipherSpec */
9103     }
9104
9105     return SECSuccess;
9106 }
9107
9108 /* ssl3_PickSignatureHashAlgorithm selects a hash algorithm to use when signing
9109  * elements of the handshake. (The negotiated cipher suite determines the
9110  * signature algorithm.) Prior to TLS 1.2, the MD5/SHA1 combination is always
9111  * used. With TLS 1.2, a client may advertise its support for signature and
9112  * hash combinations. */
9113 static SECStatus
9114 ssl3_PickSignatureHashAlgorithm(sslSocket *ss,
9115                                 SSL3SignatureAndHashAlgorithm* out)
9116 {
9117     TLSSignatureAlgorithm sigAlg;
9118     unsigned int i, j;
9119     /* hashPreference expresses our preferences for hash algorithms, most
9120      * preferable first. */
9121     static const PRUint8 hashPreference[] = {
9122         tls_hash_sha256,
9123         tls_hash_sha384,
9124         tls_hash_sha512,
9125         tls_hash_sha1,
9126     };
9127
9128     switch (ss->ssl3.hs.kea_def->kea) {
9129     case kea_rsa:
9130     case kea_rsa_export:
9131     case kea_rsa_export_1024:
9132     case kea_dh_rsa:
9133     case kea_dh_rsa_export:
9134     case kea_dhe_rsa:
9135     case kea_dhe_rsa_export:
9136     case kea_rsa_fips:
9137     case kea_ecdh_rsa:
9138     case kea_ecdhe_rsa:
9139         sigAlg = tls_sig_rsa;
9140         break;
9141     case kea_dh_dss:
9142     case kea_dh_dss_export:
9143     case kea_dhe_dss:
9144     case kea_dhe_dss_export:
9145         sigAlg = tls_sig_dsa;
9146         break;
9147     case kea_ecdh_ecdsa:
9148     case kea_ecdhe_ecdsa:
9149         sigAlg = tls_sig_ecdsa;
9150         break;
9151     default:
9152         PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
9153         return SECFailure;
9154     }
9155     out->sigAlg = sigAlg;
9156
9157     if (ss->version <= SSL_LIBRARY_VERSION_TLS_1_1) {
9158         /* SEC_OID_UNKNOWN means the MD5/SHA1 combo hash used in TLS 1.1 and
9159          * prior. */
9160         out->hashAlg = SEC_OID_UNKNOWN;
9161         return SECSuccess;
9162     }
9163
9164     if (ss->ssl3.hs.numClientSigAndHash == 0) {
9165         /* If the client didn't provide any signature_algorithms extension then
9166          * we can assume that they support SHA-1:
9167          * https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
9168         out->hashAlg = SEC_OID_SHA1;
9169         return SECSuccess;
9170     }
9171
9172     for (i = 0; i < PR_ARRAY_SIZE(hashPreference); i++) {
9173         for (j = 0; j < ss->ssl3.hs.numClientSigAndHash; j++) {
9174             const SSL3SignatureAndHashAlgorithm* sh =
9175                 &ss->ssl3.hs.clientSigAndHash[j];
9176             if (sh->sigAlg == sigAlg && sh->hashAlg == hashPreference[i]) {
9177                 out->hashAlg = sh->hashAlg;
9178                 return SECSuccess;
9179             }
9180         }
9181     }
9182
9183     PORT_SetError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
9184     return SECFailure;
9185 }
9186
9187
9188 static SECStatus
9189 ssl3_SendServerKeyExchange(sslSocket *ss)
9190 {
9191     const ssl3KEADef * kea_def     = ss->ssl3.hs.kea_def;
9192     SECStatus          rv          = SECFailure;
9193     int                length;
9194     PRBool             isTLS;
9195     SECItem            signed_hash = {siBuffer, NULL, 0};
9196     SSL3Hashes         hashes;
9197     SECKEYPublicKey *  sdPub;   /* public key for step-down */
9198     SSL3SignatureAndHashAlgorithm sigAndHash;
9199
9200     SSL_TRC(3, ("%d: SSL3[%d]: send server_key_exchange handshake",
9201                 SSL_GETPID(), ss->fd));
9202
9203     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
9204     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
9205
9206     if (ssl3_PickSignatureHashAlgorithm(ss, &sigAndHash) != SECSuccess) {
9207         return SECFailure;
9208     }
9209
9210     switch (kea_def->exchKeyType) {
9211     case kt_rsa:
9212         /* Perform SSL Step-Down here. */
9213         sdPub = ss->stepDownKeyPair->pubKey;
9214         PORT_Assert(sdPub != NULL);
9215         if (!sdPub) {
9216             PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
9217             return SECFailure;
9218         }
9219         rv = ssl3_ComputeExportRSAKeyHash(sigAndHash.hashAlg,
9220                                           sdPub->u.rsa.modulus,
9221                                           sdPub->u.rsa.publicExponent,
9222                                           &ss->ssl3.hs.client_random,
9223                                           &ss->ssl3.hs.server_random,
9224                                           &hashes, ss->opt.bypassPKCS11);
9225         if (rv != SECSuccess) {
9226             ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
9227             return rv;
9228         }
9229
9230         isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
9231         rv = ssl3_SignHashes(&hashes, ss->serverCerts[kt_rsa].SERVERKEY, 
9232                              &signed_hash, isTLS);
9233         if (rv != SECSuccess) {
9234             goto loser;         /* ssl3_SignHashes has set err. */
9235         }
9236         if (signed_hash.data == NULL) {
9237             /* how can this happen and rv == SECSuccess ?? */
9238             PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
9239             goto loser;
9240         }
9241         length = 2 + sdPub->u.rsa.modulus.len +
9242                  2 + sdPub->u.rsa.publicExponent.len +
9243                  2 + signed_hash.len;
9244
9245         rv = ssl3_AppendHandshakeHeader(ss, server_key_exchange, length);
9246         if (rv != SECSuccess) {
9247             goto loser;         /* err set by AppendHandshake. */
9248         }
9249
9250         rv = ssl3_AppendHandshakeVariable(ss, sdPub->u.rsa.modulus.data,
9251                                           sdPub->u.rsa.modulus.len, 2);
9252         if (rv != SECSuccess) {
9253             goto loser;         /* err set by AppendHandshake. */
9254         }
9255
9256         rv = ssl3_AppendHandshakeVariable(
9257                                 ss, sdPub->u.rsa.publicExponent.data,
9258                                 sdPub->u.rsa.publicExponent.len, 2);
9259         if (rv != SECSuccess) {
9260             goto loser;         /* err set by AppendHandshake. */
9261         }
9262
9263         if (ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
9264             rv = ssl3_AppendSignatureAndHashAlgorithm(ss, &sigAndHash);
9265             if (rv != SECSuccess) {
9266                 goto loser;     /* err set by AppendHandshake. */
9267             }
9268         }
9269
9270         rv = ssl3_AppendHandshakeVariable(ss, signed_hash.data,
9271                                           signed_hash.len, 2);
9272         if (rv != SECSuccess) {
9273             goto loser;         /* err set by AppendHandshake. */
9274         }
9275         PORT_Free(signed_hash.data);
9276         return SECSuccess;
9277
9278 #ifdef NSS_ENABLE_ECC
9279     case kt_ecdh: {
9280         rv = ssl3_SendECDHServerKeyExchange(ss, &sigAndHash);
9281         return rv;
9282     }
9283 #endif /* NSS_ENABLE_ECC */
9284
9285     case kt_dh:
9286     case kt_null:
9287     default:
9288         PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
9289         break;
9290     }
9291 loser:
9292     if (signed_hash.data != NULL) 
9293         PORT_Free(signed_hash.data);
9294     return SECFailure;
9295 }
9296
9297
9298 static SECStatus
9299 ssl3_SendCertificateRequest(sslSocket *ss)
9300 {
9301     PRBool         isTLS12;
9302     SECItem *      name;
9303     CERTDistNames *ca_list;
9304     const PRUint8 *certTypes;
9305     const PRUint8 *sigAlgs;
9306     SECItem *      names        = NULL;
9307     SECStatus      rv;
9308     int            length;
9309     int            i;
9310     int            calen        = 0;
9311     int            nnames       = 0;
9312     int            certTypesLength;
9313     int            sigAlgsLength;
9314
9315     SSL_TRC(3, ("%d: SSL3[%d]: send certificate_request handshake",
9316                 SSL_GETPID(), ss->fd));
9317
9318     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
9319     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
9320
9321     isTLS12 = (PRBool)(ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
9322
9323     /* ssl3.ca_list is initialized to NULL, and never changed. */
9324     ca_list = ss->ssl3.ca_list;
9325     if (!ca_list) {
9326         ca_list = ssl3_server_ca_list;
9327     }
9328
9329     if (ca_list != NULL) {
9330         names = ca_list->names;
9331         nnames = ca_list->nnames;
9332     }
9333
9334     for (i = 0, name = names; i < nnames; i++, name++) {
9335         calen += 2 + name->len;
9336     }
9337
9338     certTypes       = certificate_types;
9339     certTypesLength = sizeof certificate_types;
9340     sigAlgs         = supported_signature_algorithms;
9341     sigAlgsLength   = sizeof supported_signature_algorithms;
9342
9343     length = 1 + certTypesLength + 2 + calen;
9344     if (isTLS12) {
9345         length += 2 + sigAlgsLength;
9346     }
9347
9348     rv = ssl3_AppendHandshakeHeader(ss, certificate_request, length);
9349     if (rv != SECSuccess) {
9350         return rv;              /* err set by AppendHandshake. */
9351     }
9352     rv = ssl3_AppendHandshakeVariable(ss, certTypes, certTypesLength, 1);
9353     if (rv != SECSuccess) {
9354         return rv;              /* err set by AppendHandshake. */
9355     }
9356     if (isTLS12) {
9357         rv = ssl3_AppendHandshakeVariable(ss, sigAlgs, sigAlgsLength, 2);
9358         if (rv != SECSuccess) {
9359             return rv;          /* err set by AppendHandshake. */
9360         }
9361     }
9362     rv = ssl3_AppendHandshakeNumber(ss, calen, 2);
9363     if (rv != SECSuccess) {
9364         return rv;              /* err set by AppendHandshake. */
9365     }
9366     for (i = 0, name = names; i < nnames; i++, name++) {
9367         rv = ssl3_AppendHandshakeVariable(ss, name->data, name->len, 2);
9368         if (rv != SECSuccess) {
9369             return rv;          /* err set by AppendHandshake. */
9370         }
9371     }
9372
9373     return SECSuccess;
9374 }
9375
9376 static SECStatus
9377 ssl3_SendServerHelloDone(sslSocket *ss)
9378 {
9379     SECStatus rv;
9380
9381     SSL_TRC(3, ("%d: SSL3[%d]: send server_hello_done handshake",
9382                 SSL_GETPID(), ss->fd));
9383
9384     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
9385     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
9386
9387     rv = ssl3_AppendHandshakeHeader(ss, server_hello_done, 0);
9388     if (rv != SECSuccess) {
9389         return rv;              /* err set by AppendHandshake. */
9390     }
9391     rv = ssl3_FlushHandshake(ss, 0);
9392     if (rv != SECSuccess) {
9393         return rv;      /* error code set by ssl3_FlushHandshake */
9394     }
9395     return SECSuccess;
9396 }
9397
9398 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
9399  * ssl3 Certificate Verify message
9400  * Caller must hold Handshake and RecvBuf locks.
9401  */
9402 static SECStatus
9403 ssl3_HandleCertificateVerify(sslSocket *ss, SSL3Opaque *b, PRUint32 length,
9404                              SSL3Hashes *hashes)
9405 {
9406     SECItem              signed_hash = {siBuffer, NULL, 0};
9407     SECStatus            rv;
9408     int                  errCode     = SSL_ERROR_RX_MALFORMED_CERT_VERIFY;
9409     SSL3AlertDescription desc        = handshake_failure;
9410     PRBool               isTLS, isTLS12;
9411     SSL3SignatureAndHashAlgorithm sigAndHash;
9412
9413     SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_verify handshake",
9414                 SSL_GETPID(), ss->fd));
9415     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
9416     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
9417
9418     isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
9419     isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
9420
9421     if (ss->ssl3.hs.ws != wait_cert_verify || ss->sec.peerCert == NULL) {
9422         desc    = unexpected_message;
9423         errCode = SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY;
9424         goto alert_loser;
9425     }
9426
9427     if (isTLS12) {
9428         rv = ssl3_ConsumeSignatureAndHashAlgorithm(ss, &b, &length,
9429                                                    &sigAndHash);
9430         if (rv != SECSuccess) {
9431             goto loser; /* malformed or unsupported. */
9432         }
9433         rv = ssl3_CheckSignatureAndHashAlgorithmConsistency(
9434                 &sigAndHash, ss->sec.peerCert);
9435         if (rv != SECSuccess) {
9436             errCode = PORT_GetError();
9437             desc = decrypt_error;
9438             goto alert_loser;
9439         }
9440
9441         /* We only support CertificateVerify messages that use the handshake
9442          * hash. */
9443         if (sigAndHash.hashAlg != hashes->hashAlg) {
9444             errCode = SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM;
9445             desc = decrypt_error;
9446             goto alert_loser;
9447         }
9448     }
9449
9450     rv = ssl3_ConsumeHandshakeVariable(ss, &signed_hash, 2, &b, &length);
9451     if (rv != SECSuccess) {
9452         goto loser;             /* malformed. */
9453     }
9454
9455     /* XXX verify that the key & kea match */
9456     rv = ssl3_VerifySignedHashes(hashes, ss->sec.peerCert, &signed_hash,
9457                                  isTLS, ss->pkcs11PinArg);
9458     if (rv != SECSuccess) {
9459         errCode = PORT_GetError();
9460         desc = isTLS ? decrypt_error : handshake_failure;
9461         goto alert_loser;
9462     }
9463
9464     signed_hash.data = NULL;
9465
9466     if (length != 0) {
9467         desc    = isTLS ? decode_error : illegal_parameter;
9468         goto alert_loser;       /* malformed */
9469     }
9470     ss->ssl3.hs.ws = wait_change_cipher;
9471     return SECSuccess;
9472
9473 alert_loser:
9474     SSL3_SendAlert(ss, alert_fatal, desc);
9475 loser:
9476     PORT_SetError(errCode);
9477     return SECFailure;
9478 }
9479
9480
9481 /* find a slot that is able to generate a PMS and wrap it with RSA.
9482  * Then generate and return the PMS.
9483  * If the serverKeySlot parameter is non-null, this function will use
9484  * that slot to do the job, otherwise it will find a slot.
9485  *
9486  * Called from  ssl3_DeriveConnectionKeysPKCS11()  (above)
9487  *              sendRSAClientKeyExchange()         (above)
9488  *              ssl3_HandleRSAClientKeyExchange()  (below)
9489  * Caller must hold the SpecWriteLock, the SSL3HandshakeLock
9490  */
9491 static PK11SymKey *
9492 ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec,
9493                     PK11SlotInfo * serverKeySlot)
9494 {
9495     PK11SymKey *      pms               = NULL;
9496     PK11SlotInfo *    slot              = serverKeySlot;
9497     void *            pwArg             = ss->pkcs11PinArg;
9498     SECItem           param;
9499     CK_VERSION        version;
9500     CK_MECHANISM_TYPE mechanism_array[3];
9501
9502     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
9503
9504     if (slot == NULL) {
9505         SSLCipherAlgorithm calg;
9506         /* The specReadLock would suffice here, but we cannot assert on
9507         ** read locks.  Also, all the callers who call with a non-null
9508         ** slot already hold the SpecWriteLock.
9509         */
9510         PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
9511         PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
9512
9513         calg = spec->cipher_def->calg;
9514         PORT_Assert(alg2Mech[calg].calg == calg);
9515
9516         /* First get an appropriate slot.  */
9517         mechanism_array[0] = CKM_SSL3_PRE_MASTER_KEY_GEN;
9518         mechanism_array[1] = CKM_RSA_PKCS;
9519         mechanism_array[2] = alg2Mech[calg].cmech;
9520
9521         slot = PK11_GetBestSlotMultiple(mechanism_array, 3, pwArg);
9522         if (slot == NULL) {
9523            /* can't find a slot with all three, find a slot with the minimum */
9524             slot = PK11_GetBestSlotMultiple(mechanism_array, 2, pwArg);
9525             if (slot == NULL) {
9526                 PORT_SetError(SSL_ERROR_TOKEN_SLOT_NOT_FOUND);
9527                 return pms;     /* which is NULL */
9528             }
9529         }
9530     }
9531
9532     /* Generate the pre-master secret ...  */
9533     if (IS_DTLS(ss)) {
9534         SSL3ProtocolVersion temp;
9535
9536         temp = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion);
9537         version.major = MSB(temp);
9538         version.minor = LSB(temp);
9539     } else {
9540         version.major = MSB(ss->clientHelloVersion);
9541         version.minor = LSB(ss->clientHelloVersion);
9542     }
9543
9544     param.data = (unsigned char *)&version;
9545     param.len  = sizeof version;
9546
9547     pms = PK11_KeyGen(slot, CKM_SSL3_PRE_MASTER_KEY_GEN, &param, 0, pwArg);
9548     if (!serverKeySlot)
9549         PK11_FreeSlot(slot);
9550     if (pms == NULL) {
9551         ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
9552     }
9553     return pms;
9554 }
9555
9556 /* Note: The Bleichenbacher attack on PKCS#1 necessitates that we NEVER
9557  * return any indication of failure of the Client Key Exchange message,
9558  * where that failure is caused by the content of the client's message.
9559  * This function must not return SECFailure for any reason that is directly
9560  * or indirectly caused by the content of the client's encrypted PMS.
9561  * We must not send an alert and also not drop the connection.
9562  * Instead, we generate a random PMS.  This will cause a failure
9563  * in the processing the finished message, which is exactly where
9564  * the failure must occur.
9565  *
9566  * Called from ssl3_HandleClientKeyExchange
9567  */
9568 static SECStatus
9569 ssl3_HandleRSAClientKeyExchange(sslSocket *ss,
9570                                 SSL3Opaque *b,
9571                                 PRUint32 length,
9572                                 SECKEYPrivateKey *serverKey)
9573 {
9574     PK11SymKey *      pms;
9575 #ifndef NO_PKCS11_BYPASS
9576     unsigned char *   cr     = (unsigned char *)&ss->ssl3.hs.client_random;
9577     unsigned char *   sr     = (unsigned char *)&ss->ssl3.hs.server_random;
9578     ssl3CipherSpec *  pwSpec = ss->ssl3.pwSpec;
9579     unsigned int      outLen = 0;
9580 #endif
9581     PRBool            isTLS  = PR_FALSE;
9582     SECStatus         rv;
9583     SECItem           enc_pms;
9584     unsigned char     rsaPmsBuf[SSL3_RSA_PMS_LENGTH];
9585     SECItem           pmsItem = {siBuffer, NULL, 0};
9586
9587     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
9588     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
9589     PORT_Assert( ss->ssl3.prSpec == ss->ssl3.pwSpec );
9590
9591     enc_pms.data = b;
9592     enc_pms.len  = length;
9593     pmsItem.data = rsaPmsBuf;
9594     pmsItem.len  = sizeof rsaPmsBuf;
9595
9596     if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */
9597         PRInt32 kLen;
9598         kLen = ssl3_ConsumeHandshakeNumber(ss, 2, &enc_pms.data, &enc_pms.len);
9599         if (kLen < 0) {
9600             PORT_SetError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
9601             return SECFailure;
9602         }
9603         if ((unsigned)kLen < enc_pms.len) {
9604             enc_pms.len = kLen;
9605         }
9606         isTLS = PR_TRUE;
9607     } else {
9608         isTLS = (PRBool)(ss->ssl3.hs.kea_def->tls_keygen != 0);
9609     }
9610
9611 #ifndef NO_PKCS11_BYPASS
9612     if (ss->opt.bypassPKCS11) {
9613         /* TRIPLE BYPASS, get PMS directly from RSA decryption.
9614          * Use PK11_PrivDecryptPKCS1 to decrypt the PMS to a buffer, 
9615          * then, check for version rollback attack, then 
9616          * do the equivalent of ssl3_DeriveMasterSecret, placing the MS in 
9617          * pwSpec->msItem.  Finally call ssl3_InitPendingCipherSpec with 
9618          * ss and NULL, so that it will use the MS we've already derived here. 
9619          */
9620
9621         rv = PK11_PrivDecryptPKCS1(serverKey, rsaPmsBuf, &outLen, 
9622                                    sizeof rsaPmsBuf, enc_pms.data, enc_pms.len);
9623         if (rv != SECSuccess) {
9624             /* triple bypass failed.  Let's try for a double bypass. */
9625             goto double_bypass;
9626         } else if (ss->opt.detectRollBack) {
9627             SSL3ProtocolVersion client_version = 
9628                                          (rsaPmsBuf[0] << 8) | rsaPmsBuf[1];
9629
9630             if (IS_DTLS(ss)) {
9631                 client_version = dtls_DTLSVersionToTLSVersion(client_version);
9632             }
9633
9634             if (client_version != ss->clientHelloVersion) {
9635                 /* Version roll-back detected. ensure failure.  */
9636                 rv = PK11_GenerateRandom(rsaPmsBuf, sizeof rsaPmsBuf);
9637             }
9638         }
9639         /* have PMS, build MS without PKCS11 */
9640         rv = ssl3_MasterKeyDeriveBypass(pwSpec, cr, sr, &pmsItem, isTLS, 
9641                                         PR_TRUE);
9642         if (rv != SECSuccess) {
9643             pwSpec->msItem.data = pwSpec->raw_master_secret;
9644             pwSpec->msItem.len  = SSL3_MASTER_SECRET_LENGTH;
9645             PK11_GenerateRandom(pwSpec->msItem.data, pwSpec->msItem.len);
9646         }
9647         rv = ssl3_InitPendingCipherSpec(ss,  NULL);
9648     } else 
9649 #endif
9650     {
9651 #ifndef NO_PKCS11_BYPASS
9652 double_bypass:
9653 #endif
9654         /*
9655          * unwrap pms out of the incoming buffer
9656          * Note: CKM_SSL3_MASTER_KEY_DERIVE is NOT the mechanism used to do 
9657          *      the unwrap.  Rather, it is the mechanism with which the 
9658          *      unwrapped pms will be used.
9659          */
9660         pms = PK11_PubUnwrapSymKey(serverKey, &enc_pms,
9661                                    CKM_SSL3_MASTER_KEY_DERIVE, CKA_DERIVE, 0);
9662         if (pms != NULL) {
9663             PRINT_BUF(60, (ss, "decrypted premaster secret:",
9664                            PK11_GetKeyData(pms)->data,
9665                            PK11_GetKeyData(pms)->len));
9666         } else {
9667             /* unwrap failed. Generate a bogus PMS and carry on. */
9668             PK11SlotInfo *  slot   = PK11_GetSlotFromPrivateKey(serverKey);
9669
9670             ssl_GetSpecWriteLock(ss);
9671             pms = ssl3_GenerateRSAPMS(ss, ss->ssl3.prSpec, slot);
9672             ssl_ReleaseSpecWriteLock(ss);
9673             PK11_FreeSlot(slot);
9674         }
9675
9676         if (pms == NULL) {
9677             /* last gasp.  */
9678             ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
9679             return SECFailure;
9680         }
9681
9682         /* This step will derive the MS from the PMS, among other things. */
9683         rv = ssl3_InitPendingCipherSpec(ss,  pms);
9684         PK11_FreeSymKey(pms);
9685     }
9686
9687     if (rv != SECSuccess) {
9688         SEND_ALERT
9689         return SECFailure; /* error code set by ssl3_InitPendingCipherSpec */
9690     }
9691     return SECSuccess;
9692 }
9693
9694
9695 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
9696  * ssl3 ClientKeyExchange message from the remote client
9697  * Caller must hold Handshake and RecvBuf locks.
9698  */
9699 static SECStatus
9700 ssl3_HandleClientKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
9701 {
9702     SECKEYPrivateKey *serverKey         = NULL;
9703     SECStatus         rv;
9704     const ssl3KEADef *kea_def;
9705     ssl3KeyPair     *serverKeyPair      = NULL;
9706 #ifdef NSS_ENABLE_ECC
9707     SECKEYPublicKey *serverPubKey       = NULL;
9708 #endif /* NSS_ENABLE_ECC */
9709
9710     SSL_TRC(3, ("%d: SSL3[%d]: handle client_key_exchange handshake",
9711                 SSL_GETPID(), ss->fd));
9712
9713     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
9714     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
9715
9716     if (ss->ssl3.hs.ws != wait_client_key) {
9717         SSL3_SendAlert(ss, alert_fatal, unexpected_message);
9718         PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH);
9719         return SECFailure;
9720     }
9721
9722     kea_def   = ss->ssl3.hs.kea_def;
9723
9724     if (ss->ssl3.hs.usedStepDownKey) {
9725          PORT_Assert(kea_def->is_limited /* XXX OR cert is signing only */
9726                  && kea_def->exchKeyType == kt_rsa 
9727                  && ss->stepDownKeyPair != NULL);
9728          if (!kea_def->is_limited  ||
9729               kea_def->exchKeyType != kt_rsa ||
9730               ss->stepDownKeyPair == NULL) {
9731                 /* shouldn't happen, don't use step down if it does */
9732                 goto skip;
9733          }
9734         serverKeyPair = ss->stepDownKeyPair;
9735         ss->sec.keaKeyBits = EXPORT_RSA_KEY_LENGTH * BPB;
9736     } else 
9737 skip:
9738 #ifdef NSS_ENABLE_ECC
9739     /* XXX Using SSLKEAType to index server certifiates
9740      * does not work for (EC)DHE ciphers. Until we have
9741      * an indexing mechanism general enough for all key
9742      * exchange algorithms, we'll need to deal with each
9743      * one seprately.
9744      */
9745     if ((kea_def->kea == kea_ecdhe_rsa) ||
9746                (kea_def->kea == kea_ecdhe_ecdsa)) {
9747         if (ss->ephemeralECDHKeyPair != NULL) {
9748            serverKeyPair = ss->ephemeralECDHKeyPair;
9749            if (serverKeyPair->pubKey) {
9750                 ss->sec.keaKeyBits = 
9751                     SECKEY_PublicKeyStrengthInBits(serverKeyPair->pubKey);
9752            }
9753         }
9754     } else 
9755 #endif
9756     {
9757         sslServerCerts * sc = ss->serverCerts + kea_def->exchKeyType;
9758         serverKeyPair = sc->serverKeyPair;
9759         ss->sec.keaKeyBits = sc->serverKeyBits;
9760     }
9761
9762     if (serverKeyPair) {
9763         serverKey = serverKeyPair->privKey;
9764     }
9765
9766     if (serverKey == NULL) {
9767         SEND_ALERT
9768         PORT_SetError(SSL_ERROR_NO_SERVER_KEY_FOR_ALG);
9769         return SECFailure;
9770     }
9771
9772     ss->sec.keaType    = kea_def->exchKeyType;
9773
9774     switch (kea_def->exchKeyType) {
9775     case kt_rsa:
9776         rv = ssl3_HandleRSAClientKeyExchange(ss, b, length, serverKey);
9777         if (rv != SECSuccess) {
9778             SEND_ALERT
9779             return SECFailure;  /* error code set */
9780         }
9781         break;
9782
9783
9784 #ifdef NSS_ENABLE_ECC
9785     case kt_ecdh:
9786         /* XXX We really ought to be able to store multiple
9787          * EC certs (a requirement if we wish to support both
9788          * ECDH-RSA and ECDH-ECDSA key exchanges concurrently).
9789          * When we make that change, we'll need an index other
9790          * than kt_ecdh to pick the right EC certificate.
9791          */
9792         if (serverKeyPair) {
9793             serverPubKey = serverKeyPair->pubKey;
9794         }
9795         if (serverPubKey == NULL) {
9796             /* XXX Is this the right error code? */
9797             PORT_SetError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
9798             return SECFailure;
9799         }
9800         rv = ssl3_HandleECDHClientKeyExchange(ss, b, length, 
9801                                               serverPubKey, serverKey);
9802         if (rv != SECSuccess) {
9803             return SECFailure;  /* error code set */
9804         }
9805         break;
9806 #endif /* NSS_ENABLE_ECC */
9807
9808     default:
9809         (void) ssl3_HandshakeFailure(ss);
9810         PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
9811         return SECFailure;
9812     }
9813     ss->ssl3.hs.ws = ss->sec.peerCert ? wait_cert_verify : wait_change_cipher;
9814     return SECSuccess;
9815
9816 }
9817
9818 /* This is TLS's equivalent of sending a no_certificate alert. */
9819 static SECStatus
9820 ssl3_SendEmptyCertificate(sslSocket *ss)
9821 {
9822     SECStatus            rv;
9823
9824     rv = ssl3_AppendHandshakeHeader(ss, certificate, 3);
9825     if (rv == SECSuccess) {
9826         rv = ssl3_AppendHandshakeNumber(ss, 0, 3);
9827     }
9828     return rv;  /* error, if any, set by functions called above. */
9829 }
9830
9831 SECStatus
9832 ssl3_HandleNewSessionTicket(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
9833 {
9834     SECStatus rv;
9835     SECItem ticketData;
9836
9837     SSL_TRC(3, ("%d: SSL3[%d]: handle session_ticket handshake",
9838                 SSL_GETPID(), ss->fd));
9839
9840     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
9841     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
9842
9843     PORT_Assert(!ss->ssl3.hs.newSessionTicket.ticket.data);
9844     PORT_Assert(!ss->ssl3.hs.receivedNewSessionTicket);
9845
9846     if (ss->ssl3.hs.ws != wait_new_session_ticket) {
9847         SSL3_SendAlert(ss, alert_fatal, unexpected_message);
9848         PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET);
9849         return SECFailure;
9850     }
9851
9852     /* RFC5077 Section 3.3: "The client MUST NOT treat the ticket as valid
9853      * until it has verified the server's Finished message." See the comment in
9854      * ssl3_FinishHandshake for more details.
9855      */
9856     ss->ssl3.hs.newSessionTicket.received_timestamp = ssl_Time();
9857     if (length < 4) {
9858         (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
9859         PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
9860         return SECFailure;
9861     }
9862     ss->ssl3.hs.newSessionTicket.ticket_lifetime_hint =
9863         (PRUint32)ssl3_ConsumeHandshakeNumber(ss, 4, &b, &length);
9864
9865     rv = ssl3_ConsumeHandshakeVariable(ss, &ticketData, 2, &b, &length);
9866     if (length != 0 || rv != SECSuccess) {
9867         (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
9868         PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
9869         return SECFailure;  /* malformed */
9870     }
9871     rv = SECITEM_CopyItem(NULL, &ss->ssl3.hs.newSessionTicket.ticket,
9872                           &ticketData);
9873     if (rv != SECSuccess) {
9874         return rv;
9875     }
9876     ss->ssl3.hs.receivedNewSessionTicket = PR_TRUE;
9877
9878     ss->ssl3.hs.ws = wait_change_cipher;
9879     return SECSuccess;
9880 }
9881
9882 #ifdef NISCC_TEST
9883 static PRInt32 connNum = 0;
9884
9885 static SECStatus 
9886 get_fake_cert(SECItem *pCertItem, int *pIndex)
9887 {
9888     PRFileDesc *cf;
9889     char *      testdir;
9890     char *      startat;
9891     char *      stopat;
9892     const char *extension;
9893     int         fileNum;
9894     PRInt32     numBytes   = 0;
9895     PRStatus    prStatus;
9896     PRFileInfo  info;
9897     char        cfn[100];
9898
9899     pCertItem->data = 0;
9900     if ((testdir = PR_GetEnv("NISCC_TEST")) == NULL) {
9901         return SECSuccess;
9902     }
9903     *pIndex   = (NULL != strstr(testdir, "root"));
9904     extension = (strstr(testdir, "simple") ? "" : ".der");
9905     fileNum     = PR_ATOMIC_INCREMENT(&connNum) - 1;
9906     if ((startat = PR_GetEnv("START_AT")) != NULL) {
9907         fileNum += atoi(startat);
9908     }
9909     if ((stopat = PR_GetEnv("STOP_AT")) != NULL && 
9910         fileNum >= atoi(stopat)) {
9911         *pIndex = -1;
9912         return SECSuccess;
9913     }
9914     sprintf(cfn, "%s/%08d%s", testdir, fileNum, extension);
9915     cf = PR_Open(cfn, PR_RDONLY, 0);
9916     if (!cf) {
9917         goto loser;
9918     }
9919     prStatus = PR_GetOpenFileInfo(cf, &info);
9920     if (prStatus != PR_SUCCESS) {
9921         PR_Close(cf);
9922         goto loser;
9923     }
9924     pCertItem = SECITEM_AllocItem(NULL, pCertItem, info.size);
9925     if (pCertItem) {
9926         numBytes = PR_Read(cf, pCertItem->data, info.size);
9927     }
9928     PR_Close(cf);
9929     if (numBytes != info.size) {
9930         SECITEM_FreeItem(pCertItem, PR_FALSE);
9931         PORT_SetError(SEC_ERROR_IO);
9932         goto loser;
9933     }
9934     fprintf(stderr, "using %s\n", cfn);
9935     return SECSuccess;
9936
9937 loser:
9938     fprintf(stderr, "failed to use %s\n", cfn);
9939     *pIndex = -1;
9940     return SECFailure;
9941 }
9942 #endif
9943
9944 /*
9945  * Used by both client and server.
9946  * Called from HandleServerHelloDone and from SendServerHelloSequence.
9947  */
9948 static SECStatus
9949 ssl3_SendCertificate(sslSocket *ss)
9950 {
9951     SECStatus            rv;
9952     CERTCertificateList *certChain;
9953     int                  len            = 0;
9954     int                  i;
9955     SSL3KEAType          certIndex;
9956 #ifdef NISCC_TEST
9957     SECItem              fakeCert;
9958     int                  ndex           = -1;
9959 #endif
9960
9961     SSL_TRC(3, ("%d: SSL3[%d]: send certificate handshake",
9962                 SSL_GETPID(), ss->fd));
9963
9964     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
9965     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
9966
9967     if (ss->sec.localCert)
9968         CERT_DestroyCertificate(ss->sec.localCert);
9969     if (ss->sec.isServer) {
9970         sslServerCerts * sc = NULL;
9971
9972         /* XXX SSLKEAType isn't really a good choice for 
9973          * indexing certificates (it breaks when we deal
9974          * with (EC)DHE-* cipher suites. This hack ensures
9975          * the RSA cert is picked for (EC)DHE-RSA.
9976          * Revisit this when we add server side support
9977          * for ECDHE-ECDSA or client-side authentication
9978          * using EC certificates.
9979          */
9980         if ((ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) ||
9981             (ss->ssl3.hs.kea_def->kea == kea_dhe_rsa)) {
9982             certIndex = kt_rsa;
9983         } else {
9984             certIndex = ss->ssl3.hs.kea_def->exchKeyType;
9985         }
9986         sc                    = ss->serverCerts + certIndex;
9987         certChain             = sc->serverCertChain;
9988         ss->sec.authKeyBits   = sc->serverKeyBits;
9989         ss->sec.authAlgorithm = ss->ssl3.hs.kea_def->signKeyType;
9990         ss->sec.localCert     = CERT_DupCertificate(sc->serverCert);
9991     } else {
9992         certChain          = ss->ssl3.clientCertChain;
9993         ss->sec.localCert = CERT_DupCertificate(ss->ssl3.clientCertificate);
9994     }
9995
9996 #ifdef NISCC_TEST
9997     rv = get_fake_cert(&fakeCert, &ndex);
9998 #endif
9999
10000     if (certChain) {
10001         for (i = 0; i < certChain->len; i++) {
10002 #ifdef NISCC_TEST
10003             if (fakeCert.len > 0 && i == ndex) {
10004                 len += fakeCert.len + 3;
10005             } else {
10006                 len += certChain->certs[i].len + 3;
10007             }
10008 #else
10009             len += certChain->certs[i].len + 3;
10010 #endif
10011         }
10012     }
10013
10014     rv = ssl3_AppendHandshakeHeader(ss, certificate, len + 3);
10015     if (rv != SECSuccess) {
10016         return rv;              /* err set by AppendHandshake. */
10017     }
10018     rv = ssl3_AppendHandshakeNumber(ss, len, 3);
10019     if (rv != SECSuccess) {
10020         return rv;              /* err set by AppendHandshake. */
10021     }
10022     if (certChain) {
10023         for (i = 0; i < certChain->len; i++) {
10024 #ifdef NISCC_TEST
10025             if (fakeCert.len > 0 && i == ndex) {
10026                 rv = ssl3_AppendHandshakeVariable(ss, fakeCert.data,
10027                                                   fakeCert.len, 3);
10028                 SECITEM_FreeItem(&fakeCert, PR_FALSE);
10029             } else {
10030                 rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data,
10031                                                   certChain->certs[i].len, 3);
10032             }
10033 #else
10034             rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data,
10035                                               certChain->certs[i].len, 3);
10036 #endif
10037             if (rv != SECSuccess) {
10038                 return rv;              /* err set by AppendHandshake. */
10039             }
10040         }
10041     }
10042
10043     return SECSuccess;
10044 }
10045
10046 /*
10047  * Used by server only.
10048  * single-stapling, send only a single cert status
10049  */
10050 static SECStatus
10051 ssl3_SendCertificateStatus(sslSocket *ss)
10052 {
10053     SECStatus rv;
10054     int len = 0;
10055     SECItemArray *statusToSend = NULL;
10056     SSL3KEAType certIndex;
10057
10058     SSL_TRC(3, ("%d: SSL3[%d]: send certificate status handshake",
10059                 SSL_GETPID(), ss->fd));
10060
10061     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
10062     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10063     PORT_Assert( ss->sec.isServer);
10064
10065     if (!ssl3_ExtensionNegotiated(ss, ssl_cert_status_xtn))
10066         return SECSuccess;
10067
10068     /* Use certStatus based on the cert being used. */
10069     if ((ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) ||
10070         (ss->ssl3.hs.kea_def->kea == kea_dhe_rsa)) {
10071         certIndex = kt_rsa;
10072     } else {
10073         certIndex = ss->ssl3.hs.kea_def->exchKeyType;
10074     }
10075     if (ss->certStatusArray[certIndex] && ss->certStatusArray[certIndex]->len) {
10076         statusToSend = ss->certStatusArray[certIndex];
10077     }
10078     if (!statusToSend)
10079         return SECSuccess;
10080
10081     /* Use the array's first item only (single stapling) */
10082     len = 1 + statusToSend->items[0].len + 3;
10083
10084     rv = ssl3_AppendHandshakeHeader(ss, certificate_status, len);
10085     if (rv != SECSuccess) {
10086         return rv;              /* err set by AppendHandshake. */
10087     }
10088     rv = ssl3_AppendHandshakeNumber(ss, 1 /*ocsp*/, 1);
10089     if (rv != SECSuccess)
10090         return rv;              /* err set by AppendHandshake. */
10091
10092     rv = ssl3_AppendHandshakeVariable(ss,
10093                                       statusToSend->items[0].data,
10094                                       statusToSend->items[0].len,
10095                                       3);
10096     if (rv != SECSuccess)
10097         return rv;              /* err set by AppendHandshake. */
10098
10099     return SECSuccess;
10100 }
10101
10102 /* This is used to delete the CA certificates in the peer certificate chain
10103  * from the cert database after they've been validated.
10104  */
10105 static void
10106 ssl3_CleanupPeerCerts(sslSocket *ss)
10107 {
10108     PLArenaPool * arena = ss->ssl3.peerCertArena;
10109     ssl3CertNode *certs = (ssl3CertNode *)ss->ssl3.peerCertChain;
10110
10111     for (; certs; certs = certs->next) {
10112         CERT_DestroyCertificate(certs->cert);
10113     }
10114     if (arena) PORT_FreeArena(arena, PR_FALSE);
10115     ss->ssl3.peerCertArena = NULL;
10116     ss->ssl3.peerCertChain = NULL;
10117 }
10118
10119 static void
10120 ssl3_CopyPeerCertsFromSID(sslSocket *ss, sslSessionID *sid)
10121 {
10122     PLArenaPool *arena;
10123     ssl3CertNode *lastCert = NULL;
10124     ssl3CertNode *certs = NULL;
10125     int i;
10126
10127     if (!sid->peerCertChain[0])
10128         return;
10129     PORT_Assert(!ss->ssl3.peerCertArena);
10130     PORT_Assert(!ss->ssl3.peerCertChain);
10131     ss->ssl3.peerCertArena = arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
10132     for (i = 0; i < MAX_PEER_CERT_CHAIN_SIZE && sid->peerCertChain[i]; i++) {
10133         ssl3CertNode *c = PORT_ArenaNew(arena, ssl3CertNode);
10134         c->cert = CERT_DupCertificate(sid->peerCertChain[i]);
10135         c->next = NULL;
10136         if (lastCert) {
10137             lastCert->next = c;
10138         } else {
10139             certs = c;
10140         }
10141         lastCert = c;
10142     }
10143     ss->ssl3.peerCertChain = certs;
10144 }
10145
10146 static void
10147 ssl3_CopyPeerCertsToSID(ssl3CertNode *certs, sslSessionID *sid)
10148 {
10149     int i = 0;
10150     ssl3CertNode *c = certs;
10151     for (; i < MAX_PEER_CERT_CHAIN_SIZE && c; i++, c = c->next) {
10152         PORT_Assert(!sid->peerCertChain[i]);
10153         sid->peerCertChain[i] = CERT_DupCertificate(c->cert);
10154     }
10155 }
10156
10157 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
10158  * ssl3 CertificateStatus message.
10159  * Caller must hold Handshake and RecvBuf locks.
10160  * This is always called before ssl3_HandleCertificate, even if the Certificate
10161  * message is sent first.
10162  */
10163 static SECStatus
10164 ssl3_HandleCertificateStatus(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
10165 {
10166     PRInt32 status, len;
10167
10168     if (ss->ssl3.hs.ws != wait_certificate_status) {
10169         (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10170         PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_STATUS);
10171         return SECFailure;
10172     }
10173
10174     PORT_Assert(!ss->sec.isServer);
10175
10176     /* Consume the CertificateStatusType enum */
10177     status = ssl3_ConsumeHandshakeNumber(ss, 1, &b, &length);
10178     if (status != 1 /* ocsp */) {
10179        goto format_loser;
10180     }
10181
10182     len = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length);
10183     if (len != length) {
10184        goto format_loser;
10185     }
10186
10187 #define MAX_CERTSTATUS_LEN 0x1ffff   /* 128k - 1 */
10188     if (length > MAX_CERTSTATUS_LEN)
10189        goto format_loser;
10190 #undef MAX_CERTSTATUS_LEN
10191
10192     /* Array size 1, because we currently implement single-stapling only */
10193     SECITEM_AllocArray(NULL, &ss->sec.ci.sid->peerCertStatus, 1);
10194     if (!ss->sec.ci.sid->peerCertStatus.items)
10195        return SECFailure;
10196
10197     ss->sec.ci.sid->peerCertStatus.items[0].data = PORT_Alloc(length);
10198
10199     if (!ss->sec.ci.sid->peerCertStatus.items[0].data) {
10200         SECITEM_FreeArray(&ss->sec.ci.sid->peerCertStatus, PR_FALSE);
10201         return SECFailure;
10202     }
10203
10204     PORT_Memcpy(ss->sec.ci.sid->peerCertStatus.items[0].data, b, length);
10205     ss->sec.ci.sid->peerCertStatus.items[0].len = length;
10206     ss->sec.ci.sid->peerCertStatus.items[0].type = siBuffer;
10207
10208     return ssl3_AuthCertificate(ss);
10209
10210 format_loser:
10211     return ssl3_DecodeError(ss);
10212 }
10213
10214 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
10215  * ssl3 Certificate message.
10216  * Caller must hold Handshake and RecvBuf locks.
10217  */
10218 static SECStatus
10219 ssl3_HandleCertificate(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
10220 {
10221     ssl3CertNode *   c;
10222     ssl3CertNode *   lastCert   = NULL;
10223     PRInt32          remaining  = 0;
10224     PRInt32          size;
10225     SECStatus        rv;
10226     PRBool           isServer   = (PRBool)(!!ss->sec.isServer);
10227     PRBool           isTLS;
10228     SSL3AlertDescription desc;
10229     int              errCode    = SSL_ERROR_RX_MALFORMED_CERTIFICATE;
10230     SECItem          certItem;
10231
10232     SSL_TRC(3, ("%d: SSL3[%d]: handle certificate handshake",
10233                 SSL_GETPID(), ss->fd));
10234     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
10235     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
10236
10237     if ((ss->ssl3.hs.ws != wait_server_cert) &&
10238         (ss->ssl3.hs.ws != wait_client_cert)) {
10239         desc    = unexpected_message;
10240         errCode = SSL_ERROR_RX_UNEXPECTED_CERTIFICATE;
10241         goto alert_loser;
10242     }
10243
10244     if (ss->sec.peerCert != NULL) {
10245         if (ss->sec.peerKey) {
10246             SECKEY_DestroyPublicKey(ss->sec.peerKey);
10247             ss->sec.peerKey = NULL;
10248         }
10249         CERT_DestroyCertificate(ss->sec.peerCert);
10250         ss->sec.peerCert = NULL;
10251     }
10252
10253     ssl3_CleanupPeerCerts(ss);
10254     isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
10255
10256     /* It is reported that some TLS client sends a Certificate message
10257     ** with a zero-length message body.  We'll treat that case like a
10258     ** normal no_certificates message to maximize interoperability.
10259     */
10260     if (length) {
10261         remaining = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length);
10262         if (remaining < 0)
10263             goto loser; /* fatal alert already sent by ConsumeHandshake. */
10264         if ((PRUint32)remaining > length)
10265             goto decode_loser;
10266     }
10267
10268     if (!remaining) {
10269         if (!(isTLS && isServer)) {
10270             desc = bad_certificate;
10271             goto alert_loser;
10272         }
10273         /* This is TLS's version of a no_certificate alert. */
10274         /* I'm a server. I've requested a client cert. He hasn't got one. */
10275         rv = ssl3_HandleNoCertificate(ss);
10276         if (rv != SECSuccess) {
10277             errCode = PORT_GetError();
10278             goto loser;
10279         }
10280        ss->ssl3.hs.ws = wait_client_key;
10281        return SECSuccess;
10282     }
10283
10284     ss->ssl3.peerCertArena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
10285     if (ss->ssl3.peerCertArena == NULL) {
10286         goto loser;     /* don't send alerts on memory errors */
10287     }
10288
10289     /* First get the peer cert. */
10290     remaining -= 3;
10291     if (remaining < 0)
10292         goto decode_loser;
10293
10294     size = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length);
10295     if (size <= 0)
10296         goto loser;     /* fatal alert already sent by ConsumeHandshake. */
10297
10298     if (remaining < size)
10299         goto decode_loser;
10300
10301     certItem.data = b;
10302     certItem.len = size;
10303     b      += size;
10304     length -= size;
10305     remaining -= size;
10306
10307     ss->sec.peerCert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL,
10308                                             PR_FALSE, PR_TRUE);
10309     if (ss->sec.peerCert == NULL) {
10310         /* We should report an alert if the cert was bad, but not if the
10311          * problem was just some local problem, like memory error.
10312          */
10313         goto ambiguous_err;
10314     }
10315
10316     /* Now get all of the CA certs. */
10317     while (remaining > 0) {
10318         remaining -= 3;
10319         if (remaining < 0)
10320             goto decode_loser;
10321
10322         size = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length);
10323         if (size <= 0)
10324             goto loser; /* fatal alert already sent by ConsumeHandshake. */
10325
10326         if (remaining < size)
10327             goto decode_loser;
10328
10329         certItem.data = b;
10330         certItem.len = size;
10331         b      += size;
10332         length -= size;
10333         remaining -= size;
10334
10335         c = PORT_ArenaNew(ss->ssl3.peerCertArena, ssl3CertNode);
10336         if (c == NULL) {
10337             goto loser; /* don't send alerts on memory errors */
10338         }
10339
10340         c->cert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL,
10341                                           PR_FALSE, PR_TRUE);
10342         if (c->cert == NULL) {
10343             goto ambiguous_err;
10344         }
10345
10346         c->next = NULL;
10347         if (lastCert) {
10348             lastCert->next = c;
10349         } else {
10350             ss->ssl3.peerCertChain = c;
10351         }
10352         lastCert = c;
10353     }
10354
10355     if (remaining != 0)
10356         goto decode_loser;
10357
10358     SECKEY_UpdateCertPQG(ss->sec.peerCert);
10359
10360     if (!isServer && ssl3_ExtensionNegotiated(ss, ssl_cert_status_xtn)) {
10361        ss->ssl3.hs.ws = wait_certificate_status;
10362        rv = SECSuccess;
10363     } else {
10364        rv = ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */
10365     }
10366
10367     return rv;
10368
10369 ambiguous_err:
10370     errCode = PORT_GetError();
10371     switch (errCode) {
10372     case PR_OUT_OF_MEMORY_ERROR:
10373     case SEC_ERROR_BAD_DATABASE:
10374     case SEC_ERROR_NO_MEMORY:
10375        if (isTLS) {
10376            desc = internal_error;
10377            goto alert_loser;
10378        }
10379        goto loser;
10380     }
10381     ssl3_SendAlertForCertError(ss, errCode);
10382     goto loser;
10383
10384 decode_loser:
10385     desc = isTLS ? decode_error : bad_certificate;
10386
10387 alert_loser:
10388     (void)SSL3_SendAlert(ss, alert_fatal, desc);
10389
10390 loser:
10391     (void)ssl_MapLowLevelError(errCode);
10392     return SECFailure;
10393 }
10394
10395 static SECStatus
10396 ssl3_AuthCertificate(sslSocket *ss)
10397 {
10398     SECStatus        rv;
10399     PRBool           isServer   = (PRBool)(!!ss->sec.isServer);
10400     int              errCode;
10401
10402     ss->ssl3.hs.authCertificatePending = PR_FALSE;
10403
10404     /*
10405      * Ask caller-supplied callback function to validate cert chain.
10406      */
10407     rv = (SECStatus)(*ss->authCertificate)(ss->authCertificateArg, ss->fd,
10408                                            PR_TRUE, isServer);
10409     if (rv) {
10410         errCode = PORT_GetError();
10411         if (rv != SECWouldBlock) {
10412             if (ss->handleBadCert) {
10413                 rv = (*ss->handleBadCert)(ss->badCertArg, ss->fd);
10414             }
10415         }
10416
10417         if (rv == SECWouldBlock) {
10418             if (ss->sec.isServer) {
10419                 errCode = SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS;
10420                 rv = SECFailure;
10421                 goto loser;
10422             }
10423
10424             ss->ssl3.hs.authCertificatePending = PR_TRUE;
10425             rv = SECSuccess;
10426         }
10427
10428         if (rv != SECSuccess) {
10429             ssl3_SendAlertForCertError(ss, errCode);
10430             goto loser;
10431         }
10432     }
10433
10434     ss->sec.ci.sid->peerCert = CERT_DupCertificate(ss->sec.peerCert);
10435     ssl3_CopyPeerCertsToSID(ss->ssl3.peerCertChain, ss->sec.ci.sid);
10436
10437     if (!ss->sec.isServer) {
10438         CERTCertificate *cert = ss->sec.peerCert;
10439
10440         /* set the server authentication and key exchange types and sizes
10441         ** from the value in the cert.  If the key exchange key is different,
10442         ** it will get fixed when we handle the server key exchange message.
10443         */
10444         SECKEYPublicKey * pubKey  = CERT_ExtractPublicKey(cert);
10445         ss->sec.authAlgorithm = ss->ssl3.hs.kea_def->signKeyType;
10446         ss->sec.keaType       = ss->ssl3.hs.kea_def->exchKeyType;
10447         if (pubKey) {
10448             ss->sec.keaKeyBits = ss->sec.authKeyBits =
10449                 SECKEY_PublicKeyStrengthInBits(pubKey);
10450 #ifdef NSS_ENABLE_ECC
10451             if (ss->sec.keaType == kt_ecdh) {
10452                 /* Get authKeyBits from signing key.
10453                  * XXX The code below uses a quick approximation of
10454                  * key size based on cert->signatureWrap.signature.data
10455                  * (which contains the DER encoded signature). The field
10456                  * cert->signatureWrap.signature.len contains the
10457                  * length of the encoded signature in bits.
10458                  */
10459                 if (ss->ssl3.hs.kea_def->kea == kea_ecdh_ecdsa) {
10460                     ss->sec.authKeyBits = 
10461                         cert->signatureWrap.signature.data[3]*8;
10462                     if (cert->signatureWrap.signature.data[4] == 0x00)
10463                             ss->sec.authKeyBits -= 8;
10464                     /* 
10465                      * XXX: if cert is not signed by ecdsa we should
10466                      * destroy pubKey and goto bad_cert
10467                      */
10468                 } else if (ss->ssl3.hs.kea_def->kea == kea_ecdh_rsa) {
10469                     ss->sec.authKeyBits = cert->signatureWrap.signature.len;
10470                     /* 
10471                      * XXX: if cert is not signed by rsa we should
10472                      * destroy pubKey and goto bad_cert
10473                      */
10474                 }
10475             }
10476 #endif /* NSS_ENABLE_ECC */
10477             SECKEY_DestroyPublicKey(pubKey); 
10478             pubKey = NULL;
10479         }
10480
10481         ss->ssl3.hs.ws = wait_cert_request; /* disallow server_key_exchange */
10482         if (ss->ssl3.hs.kea_def->is_limited ||
10483             /* XXX OR server cert is signing only. */
10484 #ifdef NSS_ENABLE_ECC
10485             ss->ssl3.hs.kea_def->kea == kea_ecdhe_ecdsa ||
10486             ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa ||
10487 #endif /* NSS_ENABLE_ECC */
10488             ss->ssl3.hs.kea_def->exchKeyType == kt_dh) {
10489             ss->ssl3.hs.ws = wait_server_key; /* allow server_key_exchange */
10490         }
10491     } else {
10492         ss->ssl3.hs.ws = wait_client_key;
10493     }
10494
10495     PORT_Assert(rv == SECSuccess);
10496     if (rv != SECSuccess) {
10497         errCode = SEC_ERROR_LIBRARY_FAILURE;
10498         rv = SECFailure;
10499         goto loser;
10500     }
10501
10502     return rv;
10503
10504 loser:
10505     (void)ssl_MapLowLevelError(errCode);
10506     return SECFailure;
10507 }
10508
10509 static SECStatus ssl3_FinishHandshake(sslSocket *ss);
10510
10511 static SECStatus
10512 ssl3_AlwaysFail(sslSocket * ss)
10513 {
10514     PORT_SetError(PR_INVALID_STATE_ERROR);
10515     return SECFailure;
10516 }
10517
10518 /* Caller must hold 1stHandshakeLock.
10519 */
10520 SECStatus
10521 ssl3_AuthCertificateComplete(sslSocket *ss, PRErrorCode error)
10522 {
10523     SECStatus rv;
10524
10525     PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss));
10526
10527     if (ss->sec.isServer) {
10528         PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS);
10529         return SECFailure;
10530     }
10531
10532     ssl_GetRecvBufLock(ss);
10533     ssl_GetSSL3HandshakeLock(ss);
10534
10535     if (!ss->ssl3.hs.authCertificatePending) {
10536         PORT_SetError(PR_INVALID_STATE_ERROR);
10537         rv = SECFailure;
10538         goto done;
10539     }
10540
10541     ss->ssl3.hs.authCertificatePending = PR_FALSE;
10542
10543     if (error != 0) {
10544         ss->ssl3.hs.restartTarget = ssl3_AlwaysFail;
10545         ssl3_SendAlertForCertError(ss, error);
10546         rv = SECSuccess;
10547     } else if (ss->ssl3.hs.restartTarget != NULL) {
10548         sslRestartTarget target = ss->ssl3.hs.restartTarget;
10549         ss->ssl3.hs.restartTarget = NULL;
10550
10551         if (target == ssl3_FinishHandshake) {
10552             SSL_TRC(3,("%d: SSL3[%p]: certificate authentication lost the race"
10553                        " with peer's finished message", SSL_GETPID(), ss->fd));
10554         }
10555
10556         rv = target(ss);
10557         /* Even if we blocked here, we have accomplished enough to claim
10558          * success. Any remaining work will be taken care of by subsequent
10559          * calls to SSL_ForceHandshake/PR_Send/PR_Read/etc. 
10560          */
10561         if (rv == SECWouldBlock) {
10562             rv = SECSuccess;
10563         }
10564     } else {
10565         SSL_TRC(3, ("%d: SSL3[%p]: certificate authentication won the race with"
10566                     " peer's finished message", SSL_GETPID(), ss->fd));
10567
10568         PORT_Assert(!ss->ssl3.hs.isResuming);
10569         PORT_Assert(ss->ssl3.hs.ws != idle_handshake);
10570
10571         if (ss->opt.enableFalseStart &&
10572             !ss->firstHsDone &&
10573             !ss->ssl3.hs.isResuming &&
10574             ssl3_WaitingForStartOfServerSecondRound(ss)) {
10575             /* ssl3_SendClientSecondRound deferred the false start check because
10576              * certificate authentication was pending, so we do it now if we still
10577              * haven't received any of the server's second round yet.
10578              */
10579             rv = ssl3_CheckFalseStart(ss);
10580         } else {
10581             rv = SECSuccess;
10582         }
10583     }
10584
10585 done:
10586     ssl_ReleaseSSL3HandshakeLock(ss);
10587     ssl_ReleaseRecvBufLock(ss);
10588
10589     return rv;
10590 }
10591
10592 static SECStatus
10593 ssl3_ComputeTLSFinished(ssl3CipherSpec *spec,
10594                         PRBool          isServer,
10595                 const   SSL3Hashes   *  hashes,
10596                         TLSFinished  *  tlsFinished)
10597 {
10598     const char * label;
10599     unsigned int len;
10600     SECStatus    rv;
10601
10602     label = isServer ? "server finished" : "client finished";
10603     len   = 15;
10604
10605     rv = ssl3_TLSPRFWithMasterSecret(spec, label, len, hashes->u.raw,
10606         hashes->len, tlsFinished->verify_data,
10607         sizeof tlsFinished->verify_data);
10608
10609     return rv;
10610 }
10611
10612 /* The calling function must acquire and release the appropriate
10613  * lock (e.g., ssl_GetSpecReadLock / ssl_ReleaseSpecReadLock for
10614  * ss->ssl3.crSpec).
10615  */
10616 SECStatus
10617 ssl3_TLSPRFWithMasterSecret(ssl3CipherSpec *spec, const char *label,
10618     unsigned int labelLen, const unsigned char *val, unsigned int valLen,
10619     unsigned char *out, unsigned int outLen)
10620 {
10621     SECStatus rv = SECSuccess;
10622
10623     if (spec->master_secret && !spec->bypassCiphers) {
10624         SECItem param = {siBuffer, NULL, 0};
10625         CK_MECHANISM_TYPE mech = CKM_TLS_PRF_GENERAL;
10626         PK11Context *prf_context;
10627         unsigned int retLen;
10628
10629         if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
10630             mech = CKM_NSS_TLS_PRF_GENERAL_SHA256;
10631         }
10632         prf_context = PK11_CreateContextBySymKey(mech, CKA_SIGN,
10633                                                  spec->master_secret, &param);
10634         if (!prf_context)
10635             return SECFailure;
10636
10637         rv  = PK11_DigestBegin(prf_context);
10638         rv |= PK11_DigestOp(prf_context, (unsigned char *) label, labelLen);
10639         rv |= PK11_DigestOp(prf_context, val, valLen);
10640         rv |= PK11_DigestFinal(prf_context, out, &retLen, outLen);
10641         PORT_Assert(rv != SECSuccess || retLen == outLen);
10642
10643         PK11_DestroyContext(prf_context, PR_TRUE);
10644     } else {
10645         /* bypass PKCS11 */
10646 #ifdef NO_PKCS11_BYPASS
10647         PORT_Assert(spec->master_secret);
10648         PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
10649         rv = SECFailure;
10650 #else
10651         SECItem inData  = { siBuffer, };
10652         SECItem outData = { siBuffer, };
10653         PRBool isFIPS   = PR_FALSE;
10654
10655         inData.data  = (unsigned char *) val;
10656         inData.len   = valLen;
10657         outData.data = out;
10658         outData.len  = outLen;
10659         if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
10660             rv = TLS_P_hash(HASH_AlgSHA256, &spec->msItem, label, &inData,
10661                             &outData, isFIPS);
10662         } else {
10663             rv = TLS_PRF(&spec->msItem, label, &inData, &outData, isFIPS);
10664         }
10665         PORT_Assert(rv != SECSuccess || outData.len == outLen);
10666 #endif
10667     }
10668     return rv;
10669 }
10670
10671 /* called from ssl3_SendClientSecondRound
10672  *             ssl3_HandleFinished
10673  */
10674 static SECStatus
10675 ssl3_SendNextProto(sslSocket *ss)
10676 {
10677     SECStatus rv;
10678     int padding_len;
10679     static const unsigned char padding[32] = {0};
10680
10681     if (ss->ssl3.nextProto.len == 0 ||
10682         ss->ssl3.nextProtoState == SSL_NEXT_PROTO_SELECTED) {
10683         return SECSuccess;
10684     }
10685
10686     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
10687     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10688
10689     padding_len = 32 - ((ss->ssl3.nextProto.len + 2) % 32);
10690
10691     rv = ssl3_AppendHandshakeHeader(ss, next_proto, ss->ssl3.nextProto.len +
10692                                                     2 + padding_len);
10693     if (rv != SECSuccess) {
10694         return rv;      /* error code set by AppendHandshakeHeader */
10695     }
10696     rv = ssl3_AppendHandshakeVariable(ss, ss->ssl3.nextProto.data,
10697                                       ss->ssl3.nextProto.len, 1);
10698     if (rv != SECSuccess) {
10699         return rv;      /* error code set by AppendHandshake */
10700     }
10701     rv = ssl3_AppendHandshakeVariable(ss, padding, padding_len, 1);
10702     if (rv != SECSuccess) {
10703         return rv;      /* error code set by AppendHandshake */
10704     }
10705     return rv;
10706 }
10707
10708 /* called from ssl3_SendFinished
10709  *
10710  * This function is simply a debugging aid and therefore does not return a
10711  * SECStatus. */
10712 static void
10713 ssl3_RecordKeyLog(sslSocket *ss)
10714 {
10715     SECStatus rv;
10716     SECItem *keyData;
10717     char buf[14 /* "CLIENT_RANDOM " */ +
10718              SSL3_RANDOM_LENGTH*2 /* client_random */ +
10719              1 /* " " */ +
10720              48*2 /* master secret */ +
10721              1 /* new line */];
10722     unsigned int j;
10723
10724     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10725
10726     if (!ssl_keylog_iob)
10727         return;
10728
10729     rv = PK11_ExtractKeyValue(ss->ssl3.cwSpec->master_secret);
10730     if (rv != SECSuccess)
10731         return;
10732
10733     ssl_GetSpecReadLock(ss);
10734
10735     /* keyData does not need to be freed. */
10736     keyData = PK11_GetKeyData(ss->ssl3.cwSpec->master_secret);
10737     if (!keyData || !keyData->data || keyData->len != 48) {
10738         ssl_ReleaseSpecReadLock(ss);
10739         return;
10740     }
10741
10742     /* https://developer.mozilla.org/en/NSS_Key_Log_Format */
10743
10744     /* There could be multiple, concurrent writers to the
10745      * keylog, so we have to do everything in a single call to
10746      * fwrite. */
10747
10748     memcpy(buf, "CLIENT_RANDOM ", 14);
10749     j = 14;
10750     hexEncode(buf + j, ss->ssl3.hs.client_random.rand, SSL3_RANDOM_LENGTH);
10751     j += SSL3_RANDOM_LENGTH*2;
10752     buf[j++] = ' ';
10753     hexEncode(buf + j, keyData->data, 48);
10754     j += 48*2;
10755     buf[j++] = '\n';
10756
10757     PORT_Assert(j == sizeof(buf));
10758
10759     ssl_ReleaseSpecReadLock(ss);
10760
10761     if (fwrite(buf, sizeof(buf), 1, ssl_keylog_iob) != 1)
10762         return;
10763     fflush(ssl_keylog_iob);
10764     return;
10765 }
10766
10767 /* called from ssl3_SendClientSecondRound
10768  *           ssl3_HandleFinished
10769  */
10770 static SECStatus
10771 ssl3_SendEncryptedExtensions(sslSocket *ss)
10772 {
10773     static const char CHANNEL_ID_MAGIC[] = "TLS Channel ID signature";
10774     static const char CHANNEL_ID_RESUMPTION_MAGIC[] = "Resumption";
10775     /* This is the ASN.1 prefix for a P-256 public key. Specifically it's:
10776      * SEQUENCE
10777      *   SEQUENCE
10778      *     OID id-ecPublicKey
10779      *     OID prime256v1
10780      *   BIT STRING, length 66, 0 trailing bits: 0x04
10781      *
10782      * The 0x04 in the BIT STRING is the prefix for an uncompressed, X9.62
10783      * public key. Following that are the two field elements as 32-byte,
10784      * big-endian numbers, as required by the Channel ID. */
10785     static const unsigned char P256_SPKI_PREFIX[] = {
10786         0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86,
10787         0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a,
10788         0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03,
10789         0x42, 0x00, 0x04
10790     };
10791     /* ChannelIDs are always 128 bytes long: 64 bytes of P-256 public key and 64
10792      * bytes of ECDSA signature. */
10793     static const int CHANNEL_ID_PUBLIC_KEY_LENGTH = 64;
10794     static const int CHANNEL_ID_LENGTH = 128;
10795
10796     SECStatus rv = SECFailure;
10797     SECItem *spki = NULL;
10798     SSL3Hashes hashes;
10799     const unsigned char *pub_bytes;
10800     unsigned char signed_data[sizeof(CHANNEL_ID_MAGIC) +
10801                               sizeof(CHANNEL_ID_RESUMPTION_MAGIC) +
10802                               sizeof(SSL3Hashes)*2];
10803     size_t signed_data_len;
10804     unsigned char digest[SHA256_LENGTH];
10805     SECItem digest_item;
10806     unsigned char signature[64];
10807     SECItem signature_item;
10808
10809     PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
10810     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10811
10812     if (ss->ssl3.channelID == NULL)
10813         return SECSuccess;
10814
10815     PORT_Assert(ssl3_ExtensionNegotiated(ss, ssl_channel_id_xtn));
10816
10817     if (SECKEY_GetPrivateKeyType(ss->ssl3.channelID) != ecKey ||
10818         PK11_SignatureLen(ss->ssl3.channelID) != sizeof(signature)) {
10819         PORT_SetError(SSL_ERROR_INVALID_CHANNEL_ID_KEY);
10820         rv = SECFailure;
10821         goto loser;
10822     }
10823
10824     ssl_GetSpecReadLock(ss);
10825     rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.cwSpec, &hashes, 0);
10826     ssl_ReleaseSpecReadLock(ss);
10827
10828     if (rv != SECSuccess)
10829         goto loser;
10830
10831     rv = ssl3_AppendHandshakeHeader(ss, encrypted_extensions,
10832                                     2 + 2 + CHANNEL_ID_LENGTH);
10833     if (rv != SECSuccess)
10834         goto loser;     /* error code set by AppendHandshakeHeader */
10835     rv = ssl3_AppendHandshakeNumber(ss, ssl_channel_id_xtn, 2);
10836     if (rv != SECSuccess)
10837         goto loser;     /* error code set by AppendHandshake */
10838     rv = ssl3_AppendHandshakeNumber(ss, CHANNEL_ID_LENGTH, 2);
10839     if (rv != SECSuccess)
10840         goto loser;     /* error code set by AppendHandshake */
10841
10842     spki = SECKEY_EncodeDERSubjectPublicKeyInfo(ss->ssl3.channelIDPub);
10843
10844     if (spki->len != sizeof(P256_SPKI_PREFIX) + CHANNEL_ID_PUBLIC_KEY_LENGTH ||
10845         memcmp(spki->data, P256_SPKI_PREFIX, sizeof(P256_SPKI_PREFIX)) != 0) {
10846         PORT_SetError(SSL_ERROR_INVALID_CHANNEL_ID_KEY);
10847         rv = SECFailure;
10848         goto loser;
10849     }
10850
10851     pub_bytes = spki->data + sizeof(P256_SPKI_PREFIX);
10852
10853     signed_data_len = 0;
10854     memcpy(signed_data + signed_data_len, CHANNEL_ID_MAGIC,
10855            sizeof(CHANNEL_ID_MAGIC));
10856     signed_data_len += sizeof(CHANNEL_ID_MAGIC);
10857     if (ss->ssl3.hs.isResuming) {
10858         SECItem *originalHandshakeHash =
10859             &ss->sec.ci.sid->u.ssl3.originalHandshakeHash;
10860         PORT_Assert(originalHandshakeHash->len > 0);
10861
10862         memcpy(signed_data + signed_data_len, CHANNEL_ID_RESUMPTION_MAGIC,
10863                sizeof(CHANNEL_ID_RESUMPTION_MAGIC));
10864         signed_data_len += sizeof(CHANNEL_ID_RESUMPTION_MAGIC);
10865         memcpy(signed_data + signed_data_len, originalHandshakeHash->data,
10866                originalHandshakeHash->len);
10867         signed_data_len += originalHandshakeHash->len;
10868     }
10869     memcpy(signed_data + signed_data_len, hashes.u.raw, hashes.len);
10870     signed_data_len += hashes.len;
10871
10872     rv = PK11_HashBuf(SEC_OID_SHA256, digest, signed_data, signed_data_len);
10873     if (rv != SECSuccess)
10874         goto loser;
10875
10876     digest_item.data = digest;
10877     digest_item.len = sizeof(digest);
10878
10879     signature_item.data = signature;
10880     signature_item.len = sizeof(signature);
10881
10882     rv = PK11_Sign(ss->ssl3.channelID, &signature_item, &digest_item);
10883     if (rv != SECSuccess)
10884         goto loser;
10885
10886     rv = ssl3_AppendHandshake(ss, pub_bytes, CHANNEL_ID_PUBLIC_KEY_LENGTH);
10887     if (rv != SECSuccess)
10888         goto loser;
10889     rv = ssl3_AppendHandshake(ss, signature, sizeof(signature));
10890
10891 loser:
10892     if (spki)
10893         SECITEM_FreeItem(spki, PR_TRUE);
10894     if (ss->ssl3.channelID) {
10895         SECKEY_DestroyPrivateKey(ss->ssl3.channelID);
10896         ss->ssl3.channelID = NULL;
10897     }
10898     if (ss->ssl3.channelIDPub) {
10899         SECKEY_DestroyPublicKey(ss->ssl3.channelIDPub);
10900         ss->ssl3.channelIDPub = NULL;
10901     }
10902
10903     return rv;
10904 }
10905
10906 /* ssl3_RestartHandshakeAfterChannelIDReq is called to restart a handshake
10907  * after a ChannelID callback returned SECWouldBlock. At this point we have
10908  * processed the server's ServerHello but not yet any further messages. We will
10909  * always get a message from the server after a ServerHello so either they are
10910  * waiting in the buffer or we'll get network I/O. */
10911 SECStatus
10912 ssl3_RestartHandshakeAfterChannelIDReq(sslSocket *ss,
10913                                        SECKEYPublicKey *channelIDPub,
10914                                        SECKEYPrivateKey *channelID)
10915 {
10916     if (ss->handshake == 0) {
10917         SECKEY_DestroyPublicKey(channelIDPub);
10918         SECKEY_DestroyPrivateKey(channelID);
10919         PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
10920         return SECFailure;
10921     }
10922
10923     if (channelIDPub == NULL ||
10924         channelID == NULL) {
10925         if (channelIDPub)
10926             SECKEY_DestroyPublicKey(channelIDPub);
10927         if (channelID)
10928             SECKEY_DestroyPrivateKey(channelID);
10929         PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
10930         return SECFailure;
10931     }
10932
10933     if (ss->ssl3.channelID)
10934         SECKEY_DestroyPrivateKey(ss->ssl3.channelID);
10935     if (ss->ssl3.channelIDPub)
10936         SECKEY_DestroyPublicKey(ss->ssl3.channelIDPub);
10937
10938     ss->handshake = ssl_GatherRecord1stHandshake;
10939     ss->ssl3.channelID = channelID;
10940     ss->ssl3.channelIDPub = channelIDPub;
10941
10942     return SECSuccess;
10943 }
10944
10945 /* called from ssl3_SendClientSecondRound
10946  *             ssl3_HandleClientHello
10947  *             ssl3_HandleFinished
10948  */
10949 static SECStatus
10950 ssl3_SendFinished(sslSocket *ss, PRInt32 flags)
10951 {
10952     ssl3CipherSpec *cwSpec;
10953     PRBool          isTLS;
10954     PRBool          isServer = ss->sec.isServer;
10955     SECStatus       rv;
10956     SSL3Sender      sender = isServer ? sender_server : sender_client;
10957     SSL3Hashes      hashes;
10958     TLSFinished     tlsFinished;
10959
10960     SSL_TRC(3, ("%d: SSL3[%d]: send finished handshake", SSL_GETPID(), ss->fd));
10961
10962     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
10963     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10964
10965     ssl_GetSpecReadLock(ss);
10966     cwSpec = ss->ssl3.cwSpec;
10967     isTLS = (PRBool)(cwSpec->version > SSL_LIBRARY_VERSION_3_0);
10968     rv = ssl3_ComputeHandshakeHashes(ss, cwSpec, &hashes, sender);
10969     if (isTLS && rv == SECSuccess) {
10970         rv = ssl3_ComputeTLSFinished(cwSpec, isServer, &hashes, &tlsFinished);
10971     }
10972     ssl_ReleaseSpecReadLock(ss);
10973     if (rv != SECSuccess) {
10974         goto fail;      /* err code was set by ssl3_ComputeHandshakeHashes */
10975     }
10976
10977     if (isTLS) {
10978         if (isServer)
10979             ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished;
10980         else
10981             ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished;
10982         ss->ssl3.hs.finishedBytes = sizeof tlsFinished;
10983         rv = ssl3_AppendHandshakeHeader(ss, finished, sizeof tlsFinished);
10984         if (rv != SECSuccess) 
10985             goto fail;          /* err set by AppendHandshake. */
10986         rv = ssl3_AppendHandshake(ss, &tlsFinished, sizeof tlsFinished);
10987         if (rv != SECSuccess) 
10988             goto fail;          /* err set by AppendHandshake. */
10989     } else {
10990         if (isServer)
10991             ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes.u.s;
10992         else
10993             ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes.u.s;
10994         PORT_Assert(hashes.len == sizeof hashes.u.s);
10995         ss->ssl3.hs.finishedBytes = sizeof hashes.u.s;
10996         rv = ssl3_AppendHandshakeHeader(ss, finished, sizeof hashes.u.s);
10997         if (rv != SECSuccess) 
10998             goto fail;          /* err set by AppendHandshake. */
10999         rv = ssl3_AppendHandshake(ss, &hashes.u.s, sizeof hashes.u.s);
11000         if (rv != SECSuccess) 
11001             goto fail;          /* err set by AppendHandshake. */
11002     }
11003     rv = ssl3_FlushHandshake(ss, flags);
11004     if (rv != SECSuccess) {
11005         goto fail;      /* error code set by ssl3_FlushHandshake */
11006     }
11007
11008     ssl3_RecordKeyLog(ss);
11009
11010     return SECSuccess;
11011
11012 fail:
11013     return rv;
11014 }
11015
11016 /* wrap the master secret, and put it into the SID.
11017  * Caller holds the Spec read lock.
11018  */
11019 SECStatus
11020 ssl3_CacheWrappedMasterSecret(sslSocket *ss, sslSessionID *sid,
11021     ssl3CipherSpec *spec, SSL3KEAType effectiveExchKeyType)
11022 {
11023     PK11SymKey *      wrappingKey  = NULL;
11024     PK11SlotInfo *    symKeySlot;
11025     void *            pwArg        = ss->pkcs11PinArg;
11026     SECStatus         rv           = SECFailure;
11027     PRBool            isServer     = ss->sec.isServer;
11028     CK_MECHANISM_TYPE mechanism    = CKM_INVALID_MECHANISM;
11029     symKeySlot = PK11_GetSlotFromKey(spec->master_secret);
11030     if (!isServer) {
11031         int  wrapKeyIndex;
11032         int  incarnation;
11033
11034         /* these next few functions are mere accessors and don't fail. */
11035         sid->u.ssl3.masterWrapIndex  = wrapKeyIndex =
11036                                        PK11_GetCurrentWrapIndex(symKeySlot);
11037         PORT_Assert(wrapKeyIndex == 0); /* array has only one entry! */
11038
11039         sid->u.ssl3.masterWrapSeries = incarnation =
11040                                        PK11_GetSlotSeries(symKeySlot);
11041         sid->u.ssl3.masterSlotID   = PK11_GetSlotID(symKeySlot);
11042         sid->u.ssl3.masterModuleID = PK11_GetModuleID(symKeySlot);
11043         sid->u.ssl3.masterValid    = PR_TRUE;
11044         /* Get the default wrapping key, for wrapping the master secret before
11045          * placing it in the SID cache entry. */
11046         wrappingKey = PK11_GetWrapKey(symKeySlot, wrapKeyIndex,
11047                                       CKM_INVALID_MECHANISM, incarnation,
11048                                       pwArg);
11049         if (wrappingKey) {
11050             mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */
11051         } else {
11052             int keyLength;
11053             /* if the wrappingKey doesn't exist, attempt to create it.
11054              * Note: we intentionally ignore errors here.  If we cannot
11055              * generate a wrapping key, it is not fatal to this SSL connection,
11056              * but we will not be able to restart this session.
11057              */
11058             mechanism = PK11_GetBestWrapMechanism(symKeySlot);
11059             keyLength = PK11_GetBestKeyLength(symKeySlot, mechanism);
11060             /* Zero length means fixed key length algorithm, or error.
11061              * It's ambiguous.
11062              */
11063             wrappingKey = PK11_KeyGen(symKeySlot, mechanism, NULL,
11064                                       keyLength, pwArg);
11065             if (wrappingKey) {
11066                 PK11_SetWrapKey(symKeySlot, wrapKeyIndex, wrappingKey);
11067             }
11068         }
11069     } else {
11070         /* server socket using session cache. */
11071         mechanism = PK11_GetBestWrapMechanism(symKeySlot);
11072         if (mechanism != CKM_INVALID_MECHANISM) {
11073             wrappingKey =
11074                 getWrappingKey(ss, symKeySlot, effectiveExchKeyType,
11075                                mechanism, pwArg);
11076             if (wrappingKey) {
11077                 mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */
11078             }
11079         }
11080     }
11081
11082     sid->u.ssl3.masterWrapMech = mechanism;
11083     PK11_FreeSlot(symKeySlot);
11084
11085     if (wrappingKey) {
11086         SECItem wmsItem;
11087
11088         wmsItem.data = sid->u.ssl3.keys.wrapped_master_secret;
11089         wmsItem.len  = sizeof sid->u.ssl3.keys.wrapped_master_secret;
11090         rv = PK11_WrapSymKey(mechanism, NULL, wrappingKey,
11091                              spec->master_secret, &wmsItem);
11092         /* rv is examined below. */
11093         sid->u.ssl3.keys.wrapped_master_secret_len = wmsItem.len;
11094         PK11_FreeSymKey(wrappingKey);
11095     }
11096     return rv;
11097 }
11098
11099 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
11100  * ssl3 Finished message from the peer.
11101  * Caller must hold Handshake and RecvBuf locks.
11102  */
11103 static SECStatus
11104 ssl3_HandleFinished(sslSocket *ss, SSL3Opaque *b, PRUint32 length,
11105                     const SSL3Hashes *hashes)
11106 {
11107     sslSessionID *    sid          = ss->sec.ci.sid;
11108     SECStatus         rv           = SECSuccess;
11109     PRBool            isServer     = ss->sec.isServer;
11110     PRBool            isTLS;
11111     SSL3KEAType       effectiveExchKeyType;
11112
11113     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
11114     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
11115
11116     SSL_TRC(3, ("%d: SSL3[%d]: handle finished handshake",
11117         SSL_GETPID(), ss->fd));
11118
11119     if (ss->ssl3.hs.ws != wait_finished) {
11120         SSL3_SendAlert(ss, alert_fatal, unexpected_message);
11121         PORT_SetError(SSL_ERROR_RX_UNEXPECTED_FINISHED);
11122         return SECFailure;
11123     }
11124
11125     isTLS = (PRBool)(ss->ssl3.crSpec->version > SSL_LIBRARY_VERSION_3_0);
11126     if (isTLS) {
11127         TLSFinished tlsFinished;
11128
11129         if (length != sizeof tlsFinished) {
11130             (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
11131             PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED);
11132             return SECFailure;
11133         }
11134         rv = ssl3_ComputeTLSFinished(ss->ssl3.crSpec, !isServer, 
11135                                      hashes, &tlsFinished);
11136         if (!isServer)
11137             ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished;
11138         else
11139             ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished;
11140         ss->ssl3.hs.finishedBytes = sizeof tlsFinished;
11141         if (rv != SECSuccess ||
11142             0 != NSS_SecureMemcmp(&tlsFinished, b, length)) {
11143             (void)SSL3_SendAlert(ss, alert_fatal, decrypt_error);
11144             PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
11145             return SECFailure;
11146         }
11147     } else {
11148         if (length != sizeof(SSL3Finished)) {
11149             (void)ssl3_IllegalParameter(ss);
11150             PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED);
11151             return SECFailure;
11152         }
11153
11154         if (!isServer)
11155             ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes->u.s;
11156         else
11157             ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes->u.s;
11158         PORT_Assert(hashes->len == sizeof hashes->u.s);
11159         ss->ssl3.hs.finishedBytes = sizeof hashes->u.s;
11160         if (0 != NSS_SecureMemcmp(&hashes->u.s, b, length)) {
11161             (void)ssl3_HandshakeFailure(ss);
11162             PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
11163             return SECFailure;
11164         }
11165     }
11166
11167     ssl_GetXmitBufLock(ss);     /*************************************/
11168
11169     if ((isServer && !ss->ssl3.hs.isResuming) ||
11170         (!isServer && ss->ssl3.hs.isResuming)) {
11171         PRInt32 flags = 0;
11172
11173         /* Send a NewSessionTicket message if the client sent us
11174          * either an empty session ticket, or one that did not verify.
11175          * (Note that if either of these conditions was met, then the
11176          * server has sent a SessionTicket extension in the
11177          * ServerHello message.)
11178          */
11179         if (isServer && !ss->ssl3.hs.isResuming &&
11180             ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn)) {
11181             /* RFC 5077 Section 3.3: "In the case of a full handshake, the
11182              * server MUST verify the client's Finished message before sending
11183              * the ticket." Presumably, this also means that the client's
11184              * certificate, if any, must be verified beforehand too.
11185              */
11186             rv = ssl3_SendNewSessionTicket(ss);
11187             if (rv != SECSuccess) {
11188                 goto xmit_loser;
11189             }
11190         }
11191
11192         rv = ssl3_SendChangeCipherSpecs(ss);
11193         if (rv != SECSuccess) {
11194             goto xmit_loser;    /* err is set. */
11195         }
11196         /* If this thread is in SSL_SecureSend (trying to write some data) 
11197         ** then set the ssl_SEND_FLAG_FORCE_INTO_BUFFER flag, so that the 
11198         ** last two handshake messages (change cipher spec and finished) 
11199         ** will be sent in the same send/write call as the application data.
11200         */
11201         if (ss->writerThread == PR_GetCurrentThread()) {
11202             flags = ssl_SEND_FLAG_FORCE_INTO_BUFFER;
11203         }
11204
11205         if (!isServer) {
11206             if (!ss->firstHsDone) {
11207                 rv = ssl3_SendNextProto(ss);
11208                 if (rv != SECSuccess) {
11209                     goto xmit_loser; /* err code was set. */
11210                 }
11211             }
11212             rv = ssl3_SendEncryptedExtensions(ss);
11213             if (rv != SECSuccess)
11214                 goto xmit_loser; /* err code was set. */
11215         }
11216
11217         if (IS_DTLS(ss)) {
11218             flags |= ssl_SEND_FLAG_NO_RETRANSMIT;
11219         }
11220
11221         rv = ssl3_SendFinished(ss, flags);
11222         if (rv != SECSuccess) {
11223             goto xmit_loser;    /* err is set. */
11224         }
11225     }
11226
11227 xmit_loser:
11228     ssl_ReleaseXmitBufLock(ss); /*************************************/
11229     if (rv != SECSuccess) {
11230         return rv;
11231     }
11232
11233     if (ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) {
11234         effectiveExchKeyType = kt_rsa;
11235     } else {
11236         effectiveExchKeyType = ss->ssl3.hs.kea_def->exchKeyType;
11237     }
11238
11239     if (sid->cached == never_cached && !ss->opt.noCache && ss->sec.cache) {
11240         /* fill in the sid */
11241         sid->u.ssl3.cipherSuite = ss->ssl3.hs.cipher_suite;
11242         sid->u.ssl3.compression = ss->ssl3.hs.compression;
11243         sid->u.ssl3.policy      = ss->ssl3.policy;
11244 #ifdef NSS_ENABLE_ECC
11245         sid->u.ssl3.negotiatedECCurves = ss->ssl3.hs.negotiatedECCurves;
11246 #endif
11247         sid->u.ssl3.exchKeyType = effectiveExchKeyType;
11248         sid->version            = ss->version;
11249         sid->authAlgorithm      = ss->sec.authAlgorithm;
11250         sid->authKeyBits        = ss->sec.authKeyBits;
11251         sid->keaType            = ss->sec.keaType;
11252         sid->keaKeyBits         = ss->sec.keaKeyBits;
11253         sid->lastAccessTime     = sid->creationTime = ssl_Time();
11254         sid->expirationTime     = sid->creationTime + ssl3_sid_timeout;
11255         sid->localCert          = CERT_DupCertificate(ss->sec.localCert);
11256
11257         ssl_GetSpecReadLock(ss);        /*************************************/
11258
11259         /* Copy the master secret (wrapped or unwrapped) into the sid */
11260         if (ss->ssl3.crSpec->msItem.len && ss->ssl3.crSpec->msItem.data) {
11261             sid->u.ssl3.keys.wrapped_master_secret_len = 
11262                             ss->ssl3.crSpec->msItem.len;
11263             memcpy(sid->u.ssl3.keys.wrapped_master_secret, 
11264                    ss->ssl3.crSpec->msItem.data, ss->ssl3.crSpec->msItem.len);
11265             sid->u.ssl3.masterValid    = PR_TRUE;
11266             sid->u.ssl3.keys.msIsWrapped = PR_FALSE;
11267             rv = SECSuccess;
11268         } else {
11269             rv = ssl3_CacheWrappedMasterSecret(ss, ss->sec.ci.sid,
11270                                                ss->ssl3.crSpec,
11271                                                effectiveExchKeyType);
11272             sid->u.ssl3.keys.msIsWrapped = PR_TRUE;
11273         }
11274         ssl_ReleaseSpecReadLock(ss);  /*************************************/
11275
11276         /* If the wrap failed, we don't cache the sid.
11277          * The connection continues normally however.
11278          */
11279         ss->ssl3.hs.cacheSID = rv == SECSuccess;
11280     }
11281
11282     if (ss->ssl3.hs.authCertificatePending) {
11283         if (ss->ssl3.hs.restartTarget) {
11284             PR_NOT_REACHED("ssl3_HandleFinished: unexpected restartTarget");
11285             PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
11286             return SECFailure;
11287         }
11288
11289         ss->ssl3.hs.restartTarget = ssl3_FinishHandshake;
11290         return SECWouldBlock;
11291     }
11292
11293     rv = ssl3_FinishHandshake(ss);
11294     return rv;
11295 }
11296
11297 /* The return type is SECStatus instead of void because this function needs
11298  * to have type sslRestartTarget.
11299  */
11300 SECStatus
11301 ssl3_FinishHandshake(sslSocket * ss)
11302 {
11303     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
11304     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
11305     PORT_Assert( ss->ssl3.hs.restartTarget == NULL );
11306
11307     /* The first handshake is now completed. */
11308     ss->handshake           = NULL;
11309
11310     /* RFC 5077 Section 3.3: "The client MUST NOT treat the ticket as valid
11311      * until it has verified the server's Finished message." When the server
11312      * sends a NewSessionTicket in a resumption handshake, we must wait until
11313      * the handshake is finished (we have verified the server's Finished
11314      * AND the server's certificate) before we update the ticket in the sid.
11315      *
11316      * This must be done before we call (*ss->sec.cache)(ss->sec.ci.sid)
11317      * because CacheSID requires the session ticket to already be set, and also
11318      * because of the lazy lock creation scheme used by CacheSID and
11319      * ssl3_SetSIDSessionTicket.
11320      */
11321     if (ss->ssl3.hs.receivedNewSessionTicket) {
11322         PORT_Assert(!ss->sec.isServer);
11323         ssl3_SetSIDSessionTicket(ss->sec.ci.sid, &ss->ssl3.hs.newSessionTicket);
11324         /* The sid took over the ticket data */
11325         PORT_Assert(!ss->ssl3.hs.newSessionTicket.ticket.data);
11326         ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE;
11327     }
11328
11329     if (ss->ssl3.hs.cacheSID && ss->sec.isServer) {
11330         PORT_Assert(ss->sec.ci.sid->cached == never_cached);
11331         (*ss->sec.cache)(ss->sec.ci.sid);
11332         ss->ssl3.hs.cacheSID = PR_FALSE;
11333     }
11334
11335     ss->ssl3.hs.canFalseStart = PR_FALSE; /* False Start phase is complete */
11336     ss->ssl3.hs.ws = idle_handshake;
11337
11338     ssl_FinishHandshake(ss);
11339
11340     return SECSuccess;
11341 }
11342
11343 /* Called from ssl3_HandleHandshake() when it has gathered a complete ssl3
11344  * hanshake message.
11345  * Caller must hold Handshake and RecvBuf locks.
11346  */
11347 SECStatus
11348 ssl3_HandleHandshakeMessage(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
11349 {
11350     SECStatus         rv        = SECSuccess;
11351     SSL3HandshakeType type      = ss->ssl3.hs.msg_type;
11352     SSL3Hashes        hashes;   /* computed hashes are put here. */
11353     PRUint8           hdr[4];
11354     PRUint8           dtlsData[8];
11355
11356     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
11357     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
11358     /*
11359      * We have to compute the hashes before we update them with the
11360      * current message.
11361      */
11362     ssl_GetSpecReadLock(ss);    /************************************/
11363     if((type == finished) || (type == certificate_verify)) {
11364         SSL3Sender      sender = (SSL3Sender)0;
11365         ssl3CipherSpec *rSpec  = ss->ssl3.prSpec;
11366
11367         if (type == finished) {
11368             sender = ss->sec.isServer ? sender_client : sender_server;
11369             rSpec  = ss->ssl3.crSpec;
11370         }
11371         rv = ssl3_ComputeHandshakeHashes(ss, rSpec, &hashes, sender);
11372     }
11373     ssl_ReleaseSpecReadLock(ss); /************************************/
11374     if (rv != SECSuccess) {
11375         return rv;      /* error code was set by ssl3_ComputeHandshakeHashes*/
11376     }
11377     SSL_TRC(30,("%d: SSL3[%d]: handle handshake message: %s", SSL_GETPID(),
11378                 ss->fd, ssl3_DecodeHandshakeType(ss->ssl3.hs.msg_type)));
11379
11380     hdr[0] = (PRUint8)ss->ssl3.hs.msg_type;
11381     hdr[1] = (PRUint8)(length >> 16);
11382     hdr[2] = (PRUint8)(length >>  8);
11383     hdr[3] = (PRUint8)(length      );
11384
11385     /* Start new handshake hashes when we start a new handshake */
11386     if (ss->ssl3.hs.msg_type == client_hello) {
11387         rv = ssl3_RestartHandshakeHashes(ss);
11388         if (rv != SECSuccess) {
11389             return rv;
11390         }
11391     }
11392     /* We should not include hello_request and hello_verify_request messages
11393      * in the handshake hashes */
11394     if ((ss->ssl3.hs.msg_type != hello_request) &&
11395         (ss->ssl3.hs.msg_type != hello_verify_request)) {
11396         rv = ssl3_UpdateHandshakeHashes(ss, (unsigned char*) hdr, 4);
11397         if (rv != SECSuccess) return rv;        /* err code already set. */
11398
11399         /* Extra data to simulate a complete DTLS handshake fragment */
11400         if (IS_DTLS(ss)) {
11401             /* Sequence number */
11402             dtlsData[0] = MSB(ss->ssl3.hs.recvMessageSeq);
11403             dtlsData[1] = LSB(ss->ssl3.hs.recvMessageSeq);
11404
11405             /* Fragment offset */
11406             dtlsData[2] = 0;
11407             dtlsData[3] = 0;
11408             dtlsData[4] = 0;
11409
11410             /* Fragment length */
11411             dtlsData[5] = (PRUint8)(length >> 16);
11412             dtlsData[6] = (PRUint8)(length >>  8);
11413             dtlsData[7] = (PRUint8)(length      );
11414
11415             rv = ssl3_UpdateHandshakeHashes(ss, (unsigned char*) dtlsData,
11416                                             sizeof(dtlsData));
11417             if (rv != SECSuccess) return rv;    /* err code already set. */
11418         }
11419
11420         /* The message body */
11421         rv = ssl3_UpdateHandshakeHashes(ss, b, length);
11422         if (rv != SECSuccess) return rv;        /* err code already set. */
11423     }
11424
11425     PORT_SetError(0);   /* each message starts with no error. */
11426
11427     if (ss->ssl3.hs.ws == wait_certificate_status &&
11428         ss->ssl3.hs.msg_type != certificate_status) {
11429         /* If we negotiated the certificate_status extension then we deferred
11430          * certificate validation until we get the CertificateStatus messsage.
11431          * But the CertificateStatus message is optional. If the server did
11432          * not send it then we need to validate the certificate now. If the
11433          * server does send the CertificateStatus message then we will
11434          * authenticate the certificate in ssl3_HandleCertificateStatus.
11435          */
11436         rv = ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */
11437         PORT_Assert(rv != SECWouldBlock);
11438         if (rv != SECSuccess) {
11439             return rv;
11440         }
11441     }
11442
11443     switch (ss->ssl3.hs.msg_type) {
11444     case hello_request:
11445         if (length != 0) {
11446             (void)ssl3_DecodeError(ss);
11447             PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_REQUEST);
11448             return SECFailure;
11449         }
11450         if (ss->sec.isServer) {
11451             (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
11452             PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST);
11453             return SECFailure;
11454         }
11455         rv = ssl3_HandleHelloRequest(ss);
11456         break;
11457     case client_hello:
11458         if (!ss->sec.isServer) {
11459             (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
11460             PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO);
11461             return SECFailure;
11462         }
11463         rv = ssl3_HandleClientHello(ss, b, length);
11464         break;
11465     case server_hello:
11466         if (ss->sec.isServer) {
11467             (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
11468             PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO);
11469             return SECFailure;
11470         }
11471         rv = ssl3_HandleServerHello(ss, b, length);
11472         break;
11473     case hello_verify_request:
11474         if (!IS_DTLS(ss) || ss->sec.isServer) {
11475             (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
11476             PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_VERIFY_REQUEST);
11477             return SECFailure;
11478         }
11479         rv = dtls_HandleHelloVerifyRequest(ss, b, length);
11480         break;
11481     case certificate:
11482         rv = ssl3_HandleCertificate(ss, b, length);
11483         break;
11484     case certificate_status:
11485         rv = ssl3_HandleCertificateStatus(ss, b, length);
11486         break;
11487     case server_key_exchange:
11488         if (ss->sec.isServer) {
11489             (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
11490             PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH);
11491             return SECFailure;
11492         }
11493         rv = ssl3_HandleServerKeyExchange(ss, b, length);
11494         break;
11495     case certificate_request:
11496         if (ss->sec.isServer) {
11497             (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
11498             PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST);
11499             return SECFailure;
11500         }
11501         rv = ssl3_HandleCertificateRequest(ss, b, length);
11502         break;
11503     case server_hello_done:
11504         if (length != 0) {
11505             (void)ssl3_DecodeError(ss);
11506             PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_DONE);
11507             return SECFailure;
11508         }
11509         if (ss->sec.isServer) {
11510             (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
11511             PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE);
11512             return SECFailure;
11513         }
11514         rv = ssl3_HandleServerHelloDone(ss);
11515         break;
11516     case certificate_verify:
11517         if (!ss->sec.isServer) {
11518             (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
11519             PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY);
11520             return SECFailure;
11521         }
11522         rv = ssl3_HandleCertificateVerify(ss, b, length, &hashes);
11523         break;
11524     case client_key_exchange:
11525         if (!ss->sec.isServer) {
11526             (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
11527             PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH);
11528             return SECFailure;
11529         }
11530         rv = ssl3_HandleClientKeyExchange(ss, b, length);
11531         break;
11532     case new_session_ticket:
11533         if (ss->sec.isServer) {
11534             (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
11535             PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET);
11536             return SECFailure;
11537         }
11538         rv = ssl3_HandleNewSessionTicket(ss, b, length);
11539         break;
11540     case finished:
11541         rv = ssl3_HandleFinished(ss, b, length, &hashes);
11542         break;
11543     default:
11544         (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
11545         PORT_SetError(SSL_ERROR_RX_UNKNOWN_HANDSHAKE);
11546         rv = SECFailure;
11547     }
11548
11549     if (IS_DTLS(ss) && (rv != SECFailure)) {
11550         /* Increment the expected sequence number */
11551         ss->ssl3.hs.recvMessageSeq++;
11552     }
11553
11554     return rv;
11555 }
11556
11557 /* Called only from ssl3_HandleRecord, for each (deciphered) ssl3 record.
11558  * origBuf is the decrypted ssl record content.
11559  * Caller must hold the handshake and RecvBuf locks.
11560  */
11561 static SECStatus
11562 ssl3_HandleHandshake(sslSocket *ss, sslBuffer *origBuf)
11563 {
11564     /*
11565      * There may be a partial handshake message already in the handshake
11566      * state. The incoming buffer may contain another portion, or a
11567      * complete message or several messages followed by another portion.
11568      *
11569      * Each message is made contiguous before being passed to the actual
11570      * message parser.
11571      */
11572     sslBuffer *buf = &ss->ssl3.hs.msgState; /* do not lose the original buffer pointer */
11573     SECStatus rv;
11574
11575     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
11576     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
11577
11578     if (buf->buf == NULL) {
11579         *buf = *origBuf;
11580     }
11581     while (buf->len > 0) {
11582         if (ss->ssl3.hs.header_bytes < 4) {
11583             PRUint8 t;
11584             t = *(buf->buf++);
11585             buf->len--;
11586             if (ss->ssl3.hs.header_bytes++ == 0)
11587                 ss->ssl3.hs.msg_type = (SSL3HandshakeType)t;
11588             else
11589                 ss->ssl3.hs.msg_len = (ss->ssl3.hs.msg_len << 8) + t;
11590             if (ss->ssl3.hs.header_bytes < 4)
11591                 continue;
11592
11593 #define MAX_HANDSHAKE_MSG_LEN 0x1ffff   /* 128k - 1 */
11594             if (ss->ssl3.hs.msg_len > MAX_HANDSHAKE_MSG_LEN) {
11595                 (void)ssl3_DecodeError(ss);
11596                 PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
11597                 return SECFailure;
11598             }
11599 #undef MAX_HANDSHAKE_MSG_LEN
11600
11601             /* If msg_len is zero, be sure we fall through, 
11602             ** even if buf->len is zero. 
11603             */
11604             if (ss->ssl3.hs.msg_len > 0) 
11605                 continue;
11606         }
11607
11608         /*
11609          * Header has been gathered and there is at least one byte of new
11610          * data available for this message. If it can be done right out
11611          * of the original buffer, then use it from there.
11612          */
11613         if (ss->ssl3.hs.msg_body.len == 0 && buf->len >= ss->ssl3.hs.msg_len) {
11614             /* handle it from input buffer */
11615             rv = ssl3_HandleHandshakeMessage(ss, buf->buf, ss->ssl3.hs.msg_len);
11616             if (rv == SECFailure) {
11617                 /* This test wants to fall through on either
11618                  * SECSuccess or SECWouldBlock.
11619                  * ssl3_HandleHandshakeMessage MUST set the error code.
11620                  */
11621                 return rv;
11622             }
11623             buf->buf += ss->ssl3.hs.msg_len;
11624             buf->len -= ss->ssl3.hs.msg_len;
11625             ss->ssl3.hs.msg_len = 0;
11626             ss->ssl3.hs.header_bytes = 0;
11627             if (rv != SECSuccess) { /* return if SECWouldBlock. */
11628                 return rv;
11629             }
11630         } else {
11631             /* must be copied to msg_body and dealt with from there */
11632             unsigned int bytes;
11633
11634             PORT_Assert(ss->ssl3.hs.msg_body.len < ss->ssl3.hs.msg_len);
11635             bytes = PR_MIN(buf->len, ss->ssl3.hs.msg_len - ss->ssl3.hs.msg_body.len);
11636
11637             /* Grow the buffer if needed */
11638             rv = sslBuffer_Grow(&ss->ssl3.hs.msg_body, ss->ssl3.hs.msg_len);
11639             if (rv != SECSuccess) {
11640                 /* sslBuffer_Grow has set a memory error code. */
11641                 return SECFailure;
11642             }
11643
11644             PORT_Memcpy(ss->ssl3.hs.msg_body.buf + ss->ssl3.hs.msg_body.len,
11645                         buf->buf, bytes);
11646             ss->ssl3.hs.msg_body.len += bytes;
11647             buf->buf += bytes;
11648             buf->len -= bytes;
11649
11650             PORT_Assert(ss->ssl3.hs.msg_body.len <= ss->ssl3.hs.msg_len);
11651
11652             /* if we have a whole message, do it */
11653             if (ss->ssl3.hs.msg_body.len == ss->ssl3.hs.msg_len) {
11654                 rv = ssl3_HandleHandshakeMessage(
11655                     ss, ss->ssl3.hs.msg_body.buf, ss->ssl3.hs.msg_len);
11656                 if (rv == SECFailure) {
11657                     /* This test wants to fall through on either
11658                      * SECSuccess or SECWouldBlock.
11659                      * ssl3_HandleHandshakeMessage MUST set error code.
11660                      */
11661                     return rv;
11662                 }
11663                 ss->ssl3.hs.msg_body.len = 0;
11664                 ss->ssl3.hs.msg_len = 0;
11665                 ss->ssl3.hs.header_bytes = 0;
11666                 if (rv != SECSuccess) { /* return if SECWouldBlock. */
11667                     return rv;
11668                 }
11669             } else {
11670                 PORT_Assert(buf->len == 0);
11671                 break;
11672             }
11673         }
11674     }   /* end loop */
11675
11676     origBuf->len = 0;   /* So ssl3_GatherAppDataRecord will keep looping. */
11677     buf->buf = NULL;    /* not a leak. */
11678     return SECSuccess;
11679 }
11680
11681 /* These macros return the given value with the MSB copied to all the other
11682  * bits. They use the fact that arithmetic shift shifts-in the sign bit.
11683  * However, this is not ensured by the C standard so you may need to replace
11684  * them with something else for odd compilers. */
11685 #define DUPLICATE_MSB_TO_ALL(x) ( (unsigned)( (int)(x) >> (sizeof(int)*8-1) ) )
11686 #define DUPLICATE_MSB_TO_ALL_8(x) ((unsigned char)(DUPLICATE_MSB_TO_ALL(x)))
11687
11688 /* SECStatusToMask returns, in constant time, a mask value of all ones if
11689  * rv == SECSuccess.  Otherwise it returns zero. */
11690 static unsigned int
11691 SECStatusToMask(SECStatus rv)
11692 {
11693     unsigned int good;
11694     /* rv ^ SECSuccess is zero iff rv == SECSuccess. Subtracting one results
11695      * in the MSB being set to one iff it was zero before. */
11696     good = rv ^ SECSuccess;
11697     good--;
11698     return DUPLICATE_MSB_TO_ALL(good);
11699 }
11700
11701 /* ssl_ConstantTimeGE returns 0xff if a>=b and 0x00 otherwise. */
11702 static unsigned char
11703 ssl_ConstantTimeGE(unsigned int a, unsigned int b)
11704 {
11705     a -= b;
11706     return DUPLICATE_MSB_TO_ALL(~a);
11707 }
11708
11709 /* ssl_ConstantTimeEQ8 returns 0xff if a==b and 0x00 otherwise. */
11710 static unsigned char
11711 ssl_ConstantTimeEQ8(unsigned char a, unsigned char b)
11712 {
11713     unsigned int c = a ^ b;
11714     c--;
11715     return DUPLICATE_MSB_TO_ALL_8(c);
11716 }
11717
11718 static SECStatus
11719 ssl_RemoveSSLv3CBCPadding(sslBuffer *plaintext,
11720                           unsigned int blockSize,
11721                           unsigned int macSize)
11722 {
11723     unsigned int paddingLength, good, t;
11724     const unsigned int overhead = 1 /* padding length byte */ + macSize;
11725
11726     /* These lengths are all public so we can test them in non-constant
11727      * time. */
11728     if (overhead > plaintext->len) {
11729         return SECFailure;
11730     }
11731
11732     paddingLength = plaintext->buf[plaintext->len-1];
11733     /* SSLv3 padding bytes are random and cannot be checked. */
11734     t = plaintext->len;
11735     t -= paddingLength+overhead;
11736     /* If len >= paddingLength+overhead then the MSB of t is zero. */
11737     good = DUPLICATE_MSB_TO_ALL(~t);
11738     /* SSLv3 requires that the padding is minimal. */
11739     t = blockSize - (paddingLength+1);
11740     good &= DUPLICATE_MSB_TO_ALL(~t);
11741     plaintext->len -= good & (paddingLength+1);
11742     return (good & SECSuccess) | (~good & SECFailure);
11743 }
11744
11745 static SECStatus
11746 ssl_RemoveTLSCBCPadding(sslBuffer *plaintext, unsigned int macSize)
11747 {
11748     unsigned int paddingLength, good, t, toCheck, i;
11749     const unsigned int overhead = 1 /* padding length byte */ + macSize;
11750
11751     /* These lengths are all public so we can test them in non-constant
11752      * time. */
11753     if (overhead > plaintext->len) {
11754         return SECFailure;
11755     }
11756
11757     paddingLength = plaintext->buf[plaintext->len-1];
11758     t = plaintext->len;
11759     t -= paddingLength+overhead;
11760     /* If len >= paddingLength+overhead then the MSB of t is zero. */
11761     good = DUPLICATE_MSB_TO_ALL(~t);
11762
11763     /* The padding consists of a length byte at the end of the record and then
11764      * that many bytes of padding, all with the same value as the length byte.
11765      * Thus, with the length byte included, there are paddingLength+1 bytes of
11766      * padding.
11767      *
11768      * We can't check just |paddingLength+1| bytes because that leaks
11769      * decrypted information. Therefore we always have to check the maximum
11770      * amount of padding possible. (Again, the length of the record is
11771      * public information so we can use it.) */
11772     toCheck = 255; /* maximum amount of padding. */
11773     if (toCheck > plaintext->len-1) {
11774         toCheck = plaintext->len-1;
11775     }
11776
11777     for (i = 0; i < toCheck; i++) {
11778         unsigned int t = paddingLength - i;
11779         /* If i <= paddingLength then the MSB of t is zero and mask is
11780          * 0xff.  Otherwise, mask is 0. */
11781         unsigned char mask = DUPLICATE_MSB_TO_ALL(~t);
11782         unsigned char b = plaintext->buf[plaintext->len-1-i];
11783         /* The final |paddingLength+1| bytes should all have the value
11784          * |paddingLength|. Therefore the XOR should be zero. */
11785         good &= ~(mask&(paddingLength ^ b));
11786     }
11787
11788     /* If any of the final |paddingLength+1| bytes had the wrong value,
11789      * one or more of the lower eight bits of |good| will be cleared. We
11790      * AND the bottom 8 bits together and duplicate the result to all the
11791      * bits. */
11792     good &= good >> 4;
11793     good &= good >> 2;
11794     good &= good >> 1;
11795     good <<= sizeof(good)*8-1;
11796     good = DUPLICATE_MSB_TO_ALL(good);
11797
11798     plaintext->len -= good & (paddingLength+1);
11799     return (good & SECSuccess) | (~good & SECFailure);
11800 }
11801
11802 /* On entry:
11803  *   originalLength >= macSize
11804  *   macSize <= MAX_MAC_LENGTH
11805  *   plaintext->len >= macSize
11806  */
11807 static void
11808 ssl_CBCExtractMAC(sslBuffer *plaintext,
11809                   unsigned int originalLength,
11810                   SSL3Opaque* out,
11811                   unsigned int macSize)
11812 {
11813     unsigned char rotatedMac[MAX_MAC_LENGTH];
11814     /* macEnd is the index of |plaintext->buf| just after the end of the
11815      * MAC. */
11816     unsigned macEnd = plaintext->len;
11817     unsigned macStart = macEnd - macSize;
11818     /* scanStart contains the number of bytes that we can ignore because
11819      * the MAC's position can only vary by 255 bytes. */
11820     unsigned scanStart = 0;
11821     unsigned i, j, divSpoiler;
11822     unsigned char rotateOffset;
11823
11824     if (originalLength > macSize + 255 + 1)
11825         scanStart = originalLength - (macSize + 255 + 1);
11826
11827     /* divSpoiler contains a multiple of macSize that is used to cause the
11828      * modulo operation to be constant time. Without this, the time varies
11829      * based on the amount of padding when running on Intel chips at least.
11830      *
11831      * The aim of right-shifting macSize is so that the compiler doesn't
11832      * figure out that it can remove divSpoiler as that would require it
11833      * to prove that macSize is always even, which I hope is beyond it. */
11834     divSpoiler = macSize >> 1;
11835     divSpoiler <<= (sizeof(divSpoiler)-1)*8;
11836     rotateOffset = (divSpoiler + macStart - scanStart) % macSize;
11837
11838     memset(rotatedMac, 0, macSize);
11839     for (i = scanStart; i < originalLength;) {
11840         for (j = 0; j < macSize && i < originalLength; i++, j++) {
11841             unsigned char macStarted = ssl_ConstantTimeGE(i, macStart);
11842             unsigned char macEnded = ssl_ConstantTimeGE(i, macEnd);
11843             unsigned char b = 0;
11844             b = plaintext->buf[i];
11845             rotatedMac[j] |= b & macStarted & ~macEnded;
11846         }
11847     }
11848
11849     /* Now rotate the MAC. If we knew that the MAC fit into a CPU cache line
11850      * we could line-align |rotatedMac| and rotate in place. */
11851     memset(out, 0, macSize);
11852     for (i = 0; i < macSize; i++) {
11853         unsigned char offset =
11854             (divSpoiler + macSize - rotateOffset + i) % macSize;
11855         for (j = 0; j < macSize; j++) {
11856             out[j] |= rotatedMac[i] & ssl_ConstantTimeEQ8(j, offset);
11857         }
11858     }
11859 }
11860
11861 /* if cText is non-null, then decipher, check MAC, and decompress the
11862  * SSL record from cText->buf (typically gs->inbuf)
11863  * into databuf (typically gs->buf), and any previous contents of databuf
11864  * is lost.  Then handle databuf according to its SSL record type,
11865  * unless it's an application record.
11866  *
11867  * If cText is NULL, then the ciphertext has previously been deciphered and
11868  * checked, and is already sitting in databuf.  It is processed as an SSL
11869  * Handshake message.
11870  *
11871  * DOES NOT process the decrypted/decompressed application data.
11872  * On return, databuf contains the decrypted/decompressed record.
11873  *
11874  * Called from ssl3_GatherCompleteHandshake
11875  *             ssl3_RestartHandshakeAfterCertReq
11876  *
11877  * Caller must hold the RecvBufLock.
11878  *
11879  * This function aquires and releases the SSL3Handshake Lock, holding the
11880  * lock around any calls to functions that handle records other than
11881  * Application Data records.
11882  */
11883 SECStatus
11884 ssl3_HandleRecord(sslSocket *ss, SSL3Ciphertext *cText, sslBuffer *databuf)
11885 {
11886     const ssl3BulkCipherDef *cipher_def;
11887     ssl3CipherSpec *     crSpec;
11888     SECStatus            rv;
11889     unsigned int         hashBytes = MAX_MAC_LENGTH + 1;
11890     PRBool               isTLS;
11891     SSL3ContentType      rType;
11892     SSL3Opaque           hash[MAX_MAC_LENGTH];
11893     SSL3Opaque           givenHashBuf[MAX_MAC_LENGTH];
11894     SSL3Opaque          *givenHash;
11895     sslBuffer           *plaintext;
11896     sslBuffer            temp_buf;
11897     PRUint64             dtls_seq_num;
11898     unsigned int         ivLen = 0;
11899     unsigned int         originalLen = 0;
11900     unsigned int         good;
11901     unsigned int         minLength;
11902     unsigned char        header[13];
11903     unsigned int         headerLen;
11904
11905     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
11906
11907     if (!ss->ssl3.initialized) {
11908         ssl_GetSSL3HandshakeLock(ss);
11909         rv = ssl3_InitState(ss);
11910         ssl_ReleaseSSL3HandshakeLock(ss);
11911         if (rv != SECSuccess) {
11912             return rv;          /* ssl3_InitState has set the error code. */
11913         }
11914     }
11915
11916     /* check for Token Presence */
11917     if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) {
11918         PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
11919         return SECFailure;
11920     }
11921
11922     /* cText is NULL when we're called from ssl3_RestartHandshakeAfterXXX().
11923      * This implies that databuf holds a previously deciphered SSL Handshake
11924      * message.
11925      */
11926     if (cText == NULL) {
11927         SSL_DBG(("%d: SSL3[%d]: HandleRecord, resuming handshake",
11928                  SSL_GETPID(), ss->fd));
11929         rType = content_handshake;
11930         goto process_it;
11931     }
11932
11933     ssl_GetSpecReadLock(ss); /******************************************/
11934
11935     crSpec = ss->ssl3.crSpec;
11936     cipher_def = crSpec->cipher_def;
11937
11938     /* 
11939      * DTLS relevance checks:
11940      * Note that this code currently ignores all out-of-epoch packets,
11941      * which means we lose some in the case of rehandshake +
11942      * loss/reordering. Since DTLS is explicitly unreliable, this
11943      * seems like a good tradeoff for implementation effort and is
11944      * consistent with the guidance of RFC 6347 Sections 4.1 and 4.2.4.1
11945      */
11946     if (IS_DTLS(ss)) {
11947         DTLSEpoch epoch = (cText->seq_num.high >> 16) & 0xffff;
11948         
11949         if (crSpec->epoch != epoch) {
11950             ssl_ReleaseSpecReadLock(ss);
11951             SSL_DBG(("%d: SSL3[%d]: HandleRecord, received packet "
11952                      "from irrelevant epoch %d", SSL_GETPID(), ss->fd, epoch));
11953             /* Silently drop the packet */
11954             databuf->len = 0; /* Needed to ensure data not left around */
11955             return SECSuccess;
11956         }
11957
11958         dtls_seq_num = (((PRUint64)(cText->seq_num.high & 0xffff)) << 32) |
11959                         ((PRUint64)cText->seq_num.low);
11960
11961         if (dtls_RecordGetRecvd(&crSpec->recvdRecords, dtls_seq_num) != 0) {
11962             ssl_ReleaseSpecReadLock(ss);
11963             SSL_DBG(("%d: SSL3[%d]: HandleRecord, rejecting "
11964                      "potentially replayed packet", SSL_GETPID(), ss->fd));
11965             /* Silently drop the packet */
11966             databuf->len = 0; /* Needed to ensure data not left around */
11967             return SECSuccess;
11968         }
11969     }
11970
11971     good = ~0U;
11972     minLength = crSpec->mac_size;
11973     if (cipher_def->type == type_block) {
11974         /* CBC records have a padding length byte at the end. */
11975         minLength++;
11976         if (crSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
11977             /* With >= TLS 1.1, CBC records have an explicit IV. */
11978             minLength += cipher_def->iv_size;
11979         }
11980     } else if (cipher_def->type == type_aead) {
11981         minLength = cipher_def->explicit_nonce_size + cipher_def->tag_size;
11982     }
11983
11984     /* We can perform this test in variable time because the record's total
11985      * length and the ciphersuite are both public knowledge. */
11986     if (cText->buf->len < minLength) {
11987         goto decrypt_loser;
11988     }
11989
11990     if (cipher_def->type == type_block &&
11991         crSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
11992         /* Consume the per-record explicit IV. RFC 4346 Section 6.2.3.2 states
11993          * "The receiver decrypts the entire GenericBlockCipher structure and
11994          * then discards the first cipher block corresponding to the IV
11995          * component." Instead, we decrypt the first cipher block and then
11996          * discard it before decrypting the rest.
11997          */
11998         SSL3Opaque iv[MAX_IV_LENGTH];
11999         int decoded;
12000
12001         ivLen = cipher_def->iv_size;
12002         if (ivLen < 8 || ivLen > sizeof(iv)) {
12003             ssl_ReleaseSpecReadLock(ss);
12004             PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
12005             return SECFailure;
12006         }
12007
12008         PRINT_BUF(80, (ss, "IV (ciphertext):", cText->buf->buf, ivLen));
12009
12010         /* The decryption result is garbage, but since we just throw away
12011          * the block it doesn't matter.  The decryption of the next block
12012          * depends only on the ciphertext of the IV block.
12013          */
12014         rv = crSpec->decode(crSpec->decodeContext, iv, &decoded,
12015                             sizeof(iv), cText->buf->buf, ivLen);
12016
12017         good &= SECStatusToMask(rv);
12018     }
12019
12020     /* If we will be decompressing the buffer we need to decrypt somewhere
12021      * other than into databuf */
12022     if (crSpec->decompressor) {
12023         temp_buf.buf = NULL;
12024         temp_buf.space = 0;
12025         plaintext = &temp_buf;
12026     } else {
12027         plaintext = databuf;
12028     }
12029
12030     plaintext->len = 0; /* filled in by decode call below. */
12031     if (plaintext->space < MAX_FRAGMENT_LENGTH) {
12032         rv = sslBuffer_Grow(plaintext, MAX_FRAGMENT_LENGTH + 2048);
12033         if (rv != SECSuccess) {
12034             ssl_ReleaseSpecReadLock(ss);
12035             SSL_DBG(("%d: SSL3[%d]: HandleRecord, tried to get %d bytes",
12036                      SSL_GETPID(), ss->fd, MAX_FRAGMENT_LENGTH + 2048));
12037             /* sslBuffer_Grow has set a memory error code. */
12038             /* Perhaps we should send an alert. (but we have no memory!) */
12039             return SECFailure;
12040         }
12041     }
12042
12043     PRINT_BUF(80, (ss, "ciphertext:", cText->buf->buf + ivLen,
12044                                       cText->buf->len - ivLen));
12045
12046     isTLS = (PRBool)(crSpec->version > SSL_LIBRARY_VERSION_3_0);
12047
12048     if (isTLS && cText->buf->len - ivLen > (MAX_FRAGMENT_LENGTH + 2048)) {
12049         ssl_ReleaseSpecReadLock(ss);
12050         SSL3_SendAlert(ss, alert_fatal, record_overflow);
12051         PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
12052         return SECFailure;
12053     }
12054
12055     rType = cText->type;
12056     if (cipher_def->type == type_aead) {
12057         /* XXX For many AEAD ciphers, the plaintext is shorter than the
12058          * ciphertext by a fixed byte count, but it is not true in general.
12059          * Each AEAD cipher should provide a function that returns the
12060          * plaintext length for a given ciphertext. */
12061         unsigned int decryptedLen =
12062             cText->buf->len - cipher_def->explicit_nonce_size -
12063             cipher_def->tag_size;
12064         headerLen = ssl3_BuildRecordPseudoHeader(
12065             header, IS_DTLS(ss) ? cText->seq_num : crSpec->read_seq_num,
12066             rType, isTLS, cText->version, IS_DTLS(ss), decryptedLen);
12067         PORT_Assert(headerLen <= sizeof(header));
12068         rv = crSpec->aead(
12069                 ss->sec.isServer ? &crSpec->client : &crSpec->server,
12070                 PR_TRUE,                          /* do decrypt */
12071                 plaintext->buf,                   /* out */
12072                 (int*) &plaintext->len,           /* outlen */
12073                 plaintext->space,                 /* maxout */
12074                 cText->buf->buf,                  /* in */
12075                 cText->buf->len,                  /* inlen */
12076                 header, headerLen);
12077         if (rv != SECSuccess) {
12078             good = 0;
12079         }
12080     } else {
12081         if (cipher_def->type == type_block &&
12082             ((cText->buf->len - ivLen) % cipher_def->block_size) != 0) {
12083             goto decrypt_loser;
12084         }
12085
12086         /* decrypt from cText buf to plaintext. */
12087         rv = crSpec->decode(
12088             crSpec->decodeContext, plaintext->buf, (int *)&plaintext->len,
12089             plaintext->space, cText->buf->buf + ivLen, cText->buf->len - ivLen);
12090         if (rv != SECSuccess) {
12091             goto decrypt_loser;
12092         }
12093
12094         PRINT_BUF(80, (ss, "cleartext:", plaintext->buf, plaintext->len));
12095
12096         originalLen = plaintext->len;
12097
12098         /* If it's a block cipher, check and strip the padding. */
12099         if (cipher_def->type == type_block) {
12100             const unsigned int blockSize = cipher_def->block_size;
12101             const unsigned int macSize = crSpec->mac_size;
12102
12103             if (!isTLS) {
12104                 good &= SECStatusToMask(ssl_RemoveSSLv3CBCPadding(
12105                             plaintext, blockSize, macSize));
12106             } else {
12107                 good &= SECStatusToMask(ssl_RemoveTLSCBCPadding(
12108                             plaintext, macSize));
12109             }
12110         }
12111
12112         /* compute the MAC */
12113         headerLen = ssl3_BuildRecordPseudoHeader(
12114             header, IS_DTLS(ss) ? cText->seq_num : crSpec->read_seq_num,
12115             rType, isTLS, cText->version, IS_DTLS(ss),
12116             plaintext->len - crSpec->mac_size);
12117         PORT_Assert(headerLen <= sizeof(header));
12118         if (cipher_def->type == type_block) {
12119             rv = ssl3_ComputeRecordMACConstantTime(
12120                 crSpec, (PRBool)(!ss->sec.isServer), header, headerLen,
12121                 plaintext->buf, plaintext->len, originalLen,
12122                 hash, &hashBytes);
12123
12124             ssl_CBCExtractMAC(plaintext, originalLen, givenHashBuf,
12125                               crSpec->mac_size);
12126             givenHash = givenHashBuf;
12127
12128             /* plaintext->len will always have enough space to remove the MAC
12129              * because in ssl_Remove{SSLv3|TLS}CBCPadding we only adjust
12130              * plaintext->len if the result has enough space for the MAC and we
12131              * tested the unadjusted size against minLength, above. */
12132             plaintext->len -= crSpec->mac_size;
12133         } else {
12134             /* This is safe because we checked the minLength above. */
12135             plaintext->len -= crSpec->mac_size;
12136
12137             rv = ssl3_ComputeRecordMAC(
12138                 crSpec, (PRBool)(!ss->sec.isServer), header, headerLen,
12139                 plaintext->buf, plaintext->len, hash, &hashBytes);
12140
12141             /* We can read the MAC directly from the record because its location
12142              * is public when a stream cipher is used. */
12143             givenHash = plaintext->buf + plaintext->len;
12144         }
12145
12146         good &= SECStatusToMask(rv);
12147
12148         if (hashBytes != (unsigned)crSpec->mac_size ||
12149             NSS_SecureMemcmp(givenHash, hash, crSpec->mac_size) != 0) {
12150             /* We're allowed to leak whether or not the MAC check was correct */
12151             good = 0;
12152         }
12153     }
12154
12155     if (good == 0) {
12156 decrypt_loser:
12157         /* must not hold spec lock when calling SSL3_SendAlert. */
12158         ssl_ReleaseSpecReadLock(ss);
12159
12160         SSL_DBG(("%d: SSL3[%d]: decryption failed", SSL_GETPID(), ss->fd));
12161
12162         if (!IS_DTLS(ss)) {
12163             SSL3_SendAlert(ss, alert_fatal, bad_record_mac);
12164             /* always log mac error, in case attacker can read server logs. */
12165             PORT_SetError(SSL_ERROR_BAD_MAC_READ);
12166             return SECFailure;
12167         } else {
12168             /* Silently drop the packet */
12169             databuf->len = 0; /* Needed to ensure data not left around */
12170             return SECSuccess;
12171         }
12172     }
12173
12174     if (!IS_DTLS(ss)) {
12175         ssl3_BumpSequenceNumber(&crSpec->read_seq_num);
12176     } else {
12177         dtls_RecordSetRecvd(&crSpec->recvdRecords, dtls_seq_num);
12178     }
12179
12180     ssl_ReleaseSpecReadLock(ss); /*****************************************/
12181
12182     /*
12183      * The decrypted data is now in plaintext.
12184      */
12185
12186     /* possibly decompress the record. If we aren't using compression then
12187      * plaintext == databuf and so the uncompressed data is already in
12188      * databuf. */
12189     if (crSpec->decompressor) {
12190         if (databuf->space < plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION) {
12191             rv = sslBuffer_Grow(
12192                 databuf, plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION);
12193             if (rv != SECSuccess) {
12194                 SSL_DBG(("%d: SSL3[%d]: HandleRecord, tried to get %d bytes",
12195                          SSL_GETPID(), ss->fd,
12196                          plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION));
12197                 /* sslBuffer_Grow has set a memory error code. */
12198                 /* Perhaps we should send an alert. (but we have no memory!) */
12199                 PORT_Free(plaintext->buf);
12200                 return SECFailure;
12201             }
12202         }
12203
12204         rv = crSpec->decompressor(crSpec->decompressContext,
12205                                   databuf->buf,
12206                                   (int*) &databuf->len,
12207                                   databuf->space,
12208                                   plaintext->buf,
12209                                   plaintext->len);
12210
12211         if (rv != SECSuccess) {
12212             int err = ssl_MapLowLevelError(SSL_ERROR_DECOMPRESSION_FAILURE);
12213             SSL3_SendAlert(ss, alert_fatal,
12214                            isTLS ? decompression_failure : bad_record_mac);
12215
12216             /* There appears to be a bug with (at least) Apache + OpenSSL where
12217              * resumed SSLv3 connections don't actually use compression. See
12218              * comments 93-95 of
12219              * https://bugzilla.mozilla.org/show_bug.cgi?id=275744
12220              *
12221              * So, if we get a decompression error, and the record appears to
12222              * be already uncompressed, then we return a more specific error
12223              * code to hopefully save somebody some debugging time in the
12224              * future.
12225              */
12226             if (plaintext->len >= 4) {
12227                 unsigned int len = ((unsigned int) plaintext->buf[1] << 16) |
12228                                    ((unsigned int) plaintext->buf[2] << 8) |
12229                                    (unsigned int) plaintext->buf[3];
12230                 if (len == plaintext->len - 4) {
12231                     /* This appears to be uncompressed already */
12232                     err = SSL_ERROR_RX_UNEXPECTED_UNCOMPRESSED_RECORD;
12233                 }
12234             }
12235
12236             PORT_Free(plaintext->buf);
12237             PORT_SetError(err);
12238             return SECFailure;
12239         }
12240
12241         PORT_Free(plaintext->buf);
12242     }
12243
12244     /*
12245     ** Having completed the decompression, check the length again. 
12246     */
12247     if (isTLS && databuf->len > (MAX_FRAGMENT_LENGTH + 1024)) {
12248         SSL3_SendAlert(ss, alert_fatal, record_overflow);
12249         PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
12250         return SECFailure;
12251     }
12252
12253     /* Application data records are processed by the caller of this
12254     ** function, not by this function.
12255     */
12256     if (rType == content_application_data) {
12257         if (ss->firstHsDone)
12258             return SECSuccess;
12259         (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12260         PORT_SetError(SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA);
12261         return SECFailure;
12262     }
12263
12264     /* It's a record that must be handled by ssl itself, not the application.
12265     */
12266 process_it:
12267     /* XXX  Get the xmit lock here.  Odds are very high that we'll be xmiting
12268      * data ang getting the xmit lock here prevents deadlocks.
12269      */
12270     ssl_GetSSL3HandshakeLock(ss);
12271
12272     /* All the functions called in this switch MUST set error code if
12273     ** they return SECFailure or SECWouldBlock.
12274     */
12275     switch (rType) {
12276     case content_change_cipher_spec:
12277         rv = ssl3_HandleChangeCipherSpecs(ss, databuf);
12278         break;
12279     case content_alert:
12280         rv = ssl3_HandleAlert(ss, databuf);
12281         break;
12282     case content_handshake:
12283         if (!IS_DTLS(ss)) {
12284             rv = ssl3_HandleHandshake(ss, databuf);
12285         } else {
12286             rv = dtls_HandleHandshake(ss, databuf);
12287         }
12288         break;
12289     /*
12290     case content_application_data is handled before this switch
12291     */
12292     default:
12293         SSL_DBG(("%d: SSL3[%d]: bogus content type=%d",
12294                  SSL_GETPID(), ss->fd, cText->type));
12295         /* XXX Send an alert ???  */
12296         PORT_SetError(SSL_ERROR_RX_UNKNOWN_RECORD_TYPE);
12297         rv = SECFailure;
12298         break;
12299     }
12300
12301     ssl_ReleaseSSL3HandshakeLock(ss);
12302     return rv;
12303 }
12304
12305 /*
12306  * Initialization functions
12307  */
12308
12309 /* Called from ssl3_InitState, immediately below. */
12310 /* Caller must hold the SpecWriteLock. */
12311 static void
12312 ssl3_InitCipherSpec(sslSocket *ss, ssl3CipherSpec *spec)
12313 {
12314     spec->cipher_def               = &bulk_cipher_defs[cipher_null];
12315     PORT_Assert(spec->cipher_def->cipher == cipher_null);
12316     spec->mac_def                  = &mac_defs[mac_null];
12317     PORT_Assert(spec->mac_def->mac == mac_null);
12318     spec->encode                   = Null_Cipher;
12319     spec->decode                   = Null_Cipher;
12320     spec->destroy                  = NULL;
12321     spec->compressor               = NULL;
12322     spec->decompressor             = NULL;
12323     spec->destroyCompressContext   = NULL;
12324     spec->destroyDecompressContext = NULL;
12325     spec->mac_size                 = 0;
12326     spec->master_secret            = NULL;
12327     spec->bypassCiphers            = PR_FALSE;
12328
12329     spec->msItem.data              = NULL;
12330     spec->msItem.len               = 0;
12331
12332     spec->client.write_key         = NULL;
12333     spec->client.write_mac_key     = NULL;
12334     spec->client.write_mac_context = NULL;
12335
12336     spec->server.write_key         = NULL;
12337     spec->server.write_mac_key     = NULL;
12338     spec->server.write_mac_context = NULL;
12339
12340     spec->write_seq_num.high       = 0;
12341     spec->write_seq_num.low        = 0;
12342
12343     spec->read_seq_num.high        = 0;
12344     spec->read_seq_num.low         = 0;
12345
12346     spec->epoch                    = 0;
12347     dtls_InitRecvdRecords(&spec->recvdRecords);
12348
12349     spec->version                  = ss->vrange.max;
12350 }
12351
12352 /* Called from: ssl3_SendRecord
12353 **              ssl3_StartHandshakeHash() <- ssl2_BeginClientHandshake()
12354 **              ssl3_SendClientHello()
12355 **              ssl3_HandleV2ClientHello()
12356 **              ssl3_HandleRecord()
12357 **
12358 ** This function should perhaps acquire and release the SpecWriteLock.
12359 **
12360 **
12361 */
12362 static SECStatus
12363 ssl3_InitState(sslSocket *ss)
12364 {
12365     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
12366
12367     if (ss->ssl3.initialized)
12368         return SECSuccess;      /* Function should be idempotent */
12369
12370     ss->ssl3.policy = SSL_ALLOWED;
12371
12372     ssl_GetSpecWriteLock(ss);
12373     ss->ssl3.crSpec = ss->ssl3.cwSpec = &ss->ssl3.specs[0];
12374     ss->ssl3.prSpec = ss->ssl3.pwSpec = &ss->ssl3.specs[1];
12375     ss->ssl3.hs.sendingSCSV = PR_FALSE;
12376     ssl3_InitCipherSpec(ss, ss->ssl3.crSpec);
12377     ssl3_InitCipherSpec(ss, ss->ssl3.prSpec);
12378
12379     ss->ssl3.hs.ws = (ss->sec.isServer) ? wait_client_hello : wait_server_hello;
12380 #ifdef NSS_ENABLE_ECC
12381     ss->ssl3.hs.negotiatedECCurves = ssl3_GetSupportedECCurveMask(ss);
12382 #endif
12383     ssl_ReleaseSpecWriteLock(ss);
12384
12385     PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData));
12386
12387     if (IS_DTLS(ss)) {
12388         ss->ssl3.hs.sendMessageSeq = 0;
12389         ss->ssl3.hs.recvMessageSeq = 0;
12390         ss->ssl3.hs.rtTimeoutMs = INITIAL_DTLS_TIMEOUT_MS;
12391         ss->ssl3.hs.rtRetries = 0;
12392         ss->ssl3.hs.recvdHighWater = -1;
12393         PR_INIT_CLIST(&ss->ssl3.hs.lastMessageFlight);
12394         dtls_SetMTU(ss, 0); /* Set the MTU to the highest plateau */
12395     }
12396
12397     PORT_Assert(!ss->ssl3.hs.messages.buf && !ss->ssl3.hs.messages.space);
12398     ss->ssl3.hs.messages.buf = NULL;
12399     ss->ssl3.hs.messages.space = 0;
12400
12401     ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE;
12402     PORT_Memset(&ss->ssl3.hs.newSessionTicket, 0,
12403                 sizeof(ss->ssl3.hs.newSessionTicket));
12404
12405     ss->ssl3.initialized = PR_TRUE;
12406     return SECSuccess;
12407 }
12408
12409 /* Returns a reference counted object that contains a key pair.
12410  * Or NULL on failure.  Initial ref count is 1.
12411  * Uses the keys in the pair as input.
12412  */
12413 ssl3KeyPair *
12414 ssl3_NewKeyPair( SECKEYPrivateKey * privKey, SECKEYPublicKey * pubKey)
12415 {
12416     ssl3KeyPair * pair;
12417
12418     if (!privKey || !pubKey) {
12419         PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
12420         return NULL;
12421     }
12422     pair = PORT_ZNew(ssl3KeyPair);
12423     if (!pair)
12424         return NULL;                    /* error code is set. */
12425     pair->refCount = 1;
12426     pair->privKey  = privKey;
12427     pair->pubKey   = pubKey;
12428     return pair;                        /* success */
12429 }
12430
12431 ssl3KeyPair *
12432 ssl3_GetKeyPairRef(ssl3KeyPair * keyPair)
12433 {
12434     PR_ATOMIC_INCREMENT(&keyPair->refCount);
12435     return keyPair;
12436 }
12437
12438 void
12439 ssl3_FreeKeyPair(ssl3KeyPair * keyPair)
12440 {
12441     PRInt32 newCount =  PR_ATOMIC_DECREMENT(&keyPair->refCount);
12442     if (!newCount) {
12443         if (keyPair->privKey)
12444             SECKEY_DestroyPrivateKey(keyPair->privKey);
12445         if (keyPair->pubKey)
12446             SECKEY_DestroyPublicKey( keyPair->pubKey);
12447         PORT_Free(keyPair);
12448     }
12449 }
12450
12451
12452
12453 /*
12454  * Creates the public and private RSA keys for SSL Step down.
12455  * Called from SSL_ConfigSecureServer in sslsecur.c
12456  */
12457 SECStatus
12458 ssl3_CreateRSAStepDownKeys(sslSocket *ss)
12459 {
12460     SECStatus             rv     = SECSuccess;
12461     SECKEYPrivateKey *    privKey;              /* RSA step down key */
12462     SECKEYPublicKey *     pubKey;               /* RSA step down key */
12463
12464     if (ss->stepDownKeyPair)
12465         ssl3_FreeKeyPair(ss->stepDownKeyPair);
12466     ss->stepDownKeyPair = NULL;
12467 #ifndef HACKED_EXPORT_SERVER
12468     /* Sigh, should have a get key strength call for private keys */
12469     if (PK11_GetPrivateModulusLen(ss->serverCerts[kt_rsa].SERVERKEY) >
12470                                                      EXPORT_RSA_KEY_LENGTH) {
12471         /* need to ask for the key size in bits */
12472         privKey = SECKEY_CreateRSAPrivateKey(EXPORT_RSA_KEY_LENGTH * BPB,
12473                                              &pubKey, NULL);
12474         if (!privKey || !pubKey ||
12475             !(ss->stepDownKeyPair = ssl3_NewKeyPair(privKey, pubKey))) {
12476             ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL);
12477             rv = SECFailure;
12478         }
12479     }
12480 #endif
12481     return rv;
12482 }
12483
12484
12485 /* record the export policy for this cipher suite */
12486 SECStatus
12487 ssl3_SetPolicy(ssl3CipherSuite which, int policy)
12488 {
12489     ssl3CipherSuiteCfg *suite;
12490
12491     suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
12492     if (suite == NULL) {
12493         return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
12494     }
12495     suite->policy = policy;
12496
12497     return SECSuccess;
12498 }
12499
12500 SECStatus
12501 ssl3_GetPolicy(ssl3CipherSuite which, PRInt32 *oPolicy)
12502 {
12503     ssl3CipherSuiteCfg *suite;
12504     PRInt32             policy;
12505     SECStatus           rv;
12506
12507     suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
12508     if (suite) {
12509         policy = suite->policy;
12510         rv     = SECSuccess;
12511     } else {
12512         policy = SSL_NOT_ALLOWED;
12513         rv     = SECFailure;    /* err code was set by Lookup. */
12514     }
12515     *oPolicy = policy;
12516     return rv;
12517 }
12518
12519 /* record the user preference for this suite */
12520 SECStatus
12521 ssl3_CipherPrefSetDefault(ssl3CipherSuite which, PRBool enabled)
12522 {
12523     ssl3CipherSuiteCfg *suite;
12524
12525     suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
12526     if (suite == NULL) {
12527         return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
12528     }
12529     suite->enabled = enabled;
12530     return SECSuccess;
12531 }
12532
12533 /* return the user preference for this suite */
12534 SECStatus
12535 ssl3_CipherPrefGetDefault(ssl3CipherSuite which, PRBool *enabled)
12536 {
12537     ssl3CipherSuiteCfg *suite;
12538     PRBool              pref;
12539     SECStatus           rv;
12540
12541     suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
12542     if (suite) {
12543         pref   = suite->enabled;
12544         rv     = SECSuccess;
12545     } else {
12546         pref   = SSL_NOT_ALLOWED;
12547         rv     = SECFailure;    /* err code was set by Lookup. */
12548     }
12549     *enabled = pref;
12550     return rv;
12551 }
12552
12553 SECStatus
12554 ssl3_CipherPrefSet(sslSocket *ss, ssl3CipherSuite which, PRBool enabled)
12555 {
12556     ssl3CipherSuiteCfg *suite;
12557
12558     suite = ssl_LookupCipherSuiteCfg(which, ss->cipherSuites);
12559     if (suite == NULL) {
12560         return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
12561     }
12562     suite->enabled = enabled;
12563     return SECSuccess;
12564 }
12565
12566 SECStatus
12567 ssl3_CipherPrefGet(sslSocket *ss, ssl3CipherSuite which, PRBool *enabled)
12568 {
12569     ssl3CipherSuiteCfg *suite;
12570     PRBool              pref;
12571     SECStatus           rv;
12572
12573     suite = ssl_LookupCipherSuiteCfg(which, ss->cipherSuites);
12574     if (suite) {
12575         pref   = suite->enabled;
12576         rv     = SECSuccess;
12577     } else {
12578         pref   = SSL_NOT_ALLOWED;
12579         rv     = SECFailure;    /* err code was set by Lookup. */
12580     }
12581     *enabled = pref;
12582     return rv;
12583 }
12584
12585 SECStatus
12586 ssl3_CipherOrderSet(sslSocket *ss, const ssl3CipherSuite *ciphers, unsigned int len)
12587 {
12588     /* |i| iterates over |ciphers| while |done| and |j| iterate over
12589      * |ss->cipherSuites|. */
12590     unsigned int i, done;
12591
12592     for (i = done = 0; i < len; i++) {
12593         PRUint16 id = ciphers[i];
12594         unsigned int existingIndex, j;
12595         PRBool found = PR_FALSE;
12596
12597         for (j = done; j < ssl_V3_SUITES_IMPLEMENTED; j++) {
12598             if (ss->cipherSuites[j].cipher_suite == id) {
12599                 existingIndex = j;
12600                 found = PR_TRUE;
12601                 break;
12602             }
12603         }
12604
12605         if (!found) {
12606             continue;
12607         }
12608
12609         if (existingIndex != done) {
12610             const ssl3CipherSuiteCfg temp = ss->cipherSuites[done];
12611             ss->cipherSuites[done] = ss->cipherSuites[existingIndex];
12612             ss->cipherSuites[existingIndex] = temp;
12613         }
12614         done++;
12615     }
12616
12617     /* Disable all cipher suites that weren't included. */
12618     for (; done < ssl_V3_SUITES_IMPLEMENTED; done++) {
12619         ss->cipherSuites[done].enabled = 0;
12620     }
12621
12622     return SECSuccess;
12623 }
12624
12625 /* copy global default policy into socket. */
12626 void
12627 ssl3_InitSocketPolicy(sslSocket *ss)
12628 {
12629     PORT_Memcpy(ss->cipherSuites, cipherSuites, sizeof cipherSuites);
12630 }
12631
12632 SECStatus
12633 ssl3_GetTLSUniqueChannelBinding(sslSocket *ss,
12634                                 unsigned char *out,
12635                                 unsigned int *outLen,
12636                                 unsigned int outLenMax) {
12637     PRBool       isTLS;
12638     int          index = 0;
12639     unsigned int len;
12640     SECStatus    rv = SECFailure;
12641
12642     *outLen = 0;
12643
12644     ssl_GetSSL3HandshakeLock(ss);
12645
12646     ssl_GetSpecReadLock(ss);
12647     isTLS = (PRBool)(ss->ssl3.cwSpec->version > SSL_LIBRARY_VERSION_3_0);
12648     ssl_ReleaseSpecReadLock(ss);
12649
12650     /* The tls-unique channel binding is the first Finished structure in the
12651      * handshake. In the case of a resumption, that's the server's Finished.
12652      * Otherwise, it's the client's Finished. */
12653     len = ss->ssl3.hs.finishedBytes;
12654
12655     /* Sending or receiving a Finished message will set finishedBytes to a
12656      * non-zero value. */
12657     if (len == 0) {
12658         PORT_SetError(SSL_ERROR_HANDSHAKE_NOT_COMPLETED);
12659         goto loser;
12660     }
12661
12662     /* If we are in the middle of a renegotiation then the channel binding
12663      * value is poorly defined and depends on the direction that it will be
12664      * used on. Therefore we simply return an error in this case. */
12665     if (ss->firstHsDone && ss->ssl3.hs.ws != idle_handshake) {
12666         PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED);
12667         goto loser;
12668     }
12669
12670     /* If resuming, then we want the second Finished value in the array, which
12671      * is the server's */
12672     if (ss->ssl3.hs.isResuming)
12673         index = 1;
12674
12675     *outLen = len;
12676     if (outLenMax < len) {
12677         PORT_SetError(SEC_ERROR_OUTPUT_LEN);
12678         goto loser;
12679     }
12680
12681     if (isTLS) {
12682         memcpy(out, &ss->ssl3.hs.finishedMsgs.tFinished[index], len);
12683     } else {
12684         memcpy(out, &ss->ssl3.hs.finishedMsgs.sFinished[index], len);
12685     }
12686
12687     rv = SECSuccess;
12688
12689 loser:
12690     ssl_ReleaseSSL3HandshakeLock(ss);
12691     return rv;
12692 }
12693
12694 /* ssl3_config_match_init must have already been called by
12695  * the caller of this function.
12696  */
12697 SECStatus
12698 ssl3_ConstructV2CipherSpecsHack(sslSocket *ss, unsigned char *cs, int *size)
12699 {
12700     int i, count = 0;
12701
12702     PORT_Assert(ss != 0);
12703     if (!ss) {
12704         PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
12705         return SECFailure;
12706     }
12707     if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
12708         *size = 0;
12709         return SECSuccess;
12710     }
12711     if (cs == NULL) {
12712         *size = count_cipher_suites(ss, SSL_ALLOWED, PR_TRUE);
12713         return SECSuccess;
12714     }
12715
12716     /* ssl3_config_match_init was called by the caller of this function. */
12717     for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
12718         ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i];
12719         if (config_match(suite, SSL_ALLOWED, PR_TRUE, &ss->vrange)) {
12720             if (cs != NULL) {
12721                 *cs++ = 0x00;
12722                 *cs++ = (suite->cipher_suite >> 8) & 0xFF;
12723                 *cs++ =  suite->cipher_suite       & 0xFF;
12724             }
12725             count++;
12726         }
12727     }
12728     *size = count;
12729     return SECSuccess;
12730 }
12731
12732 /*
12733 ** If ssl3 socket has completed the first handshake, and is in idle state, 
12734 ** then start a new handshake.
12735 ** If flushCache is true, the SID cache will be flushed first, forcing a
12736 ** "Full" handshake (not a session restart handshake), to be done.
12737 **
12738 ** called from SSL_RedoHandshake(), which already holds the handshake locks.
12739 */
12740 SECStatus
12741 ssl3_RedoHandshake(sslSocket *ss, PRBool flushCache)
12742 {
12743     sslSessionID *   sid = ss->sec.ci.sid;
12744     SECStatus        rv;
12745
12746     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
12747
12748     if (!ss->firstHsDone ||
12749         ((ss->version >= SSL_LIBRARY_VERSION_3_0) &&
12750          ss->ssl3.initialized && 
12751          (ss->ssl3.hs.ws != idle_handshake))) {
12752         PORT_SetError(SSL_ERROR_HANDSHAKE_NOT_COMPLETED);
12753         return SECFailure;
12754     }
12755
12756     if (IS_DTLS(ss)) {
12757         dtls_RehandshakeCleanup(ss);
12758     }
12759
12760     if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) {
12761         PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED);
12762         return SECFailure;
12763     }
12764     if (sid && flushCache) {
12765         if (ss->sec.uncache)
12766             ss->sec.uncache(sid); /* remove it from whichever cache it's in. */
12767         ssl_FreeSID(sid);       /* dec ref count and free if zero. */
12768         ss->sec.ci.sid = NULL;
12769     }
12770
12771     ssl_GetXmitBufLock(ss);     /**************************************/
12772
12773     /* start off a new handshake. */
12774     rv = (ss->sec.isServer) ? ssl3_SendHelloRequest(ss)
12775                             : ssl3_SendClientHello(ss, PR_FALSE);
12776
12777     ssl_ReleaseXmitBufLock(ss); /**************************************/
12778     return rv;
12779 }
12780
12781 /* Called from ssl_DestroySocketContents() in sslsock.c */
12782 void
12783 ssl3_DestroySSL3Info(sslSocket *ss)
12784 {
12785
12786     if (ss->ssl3.clientCertificate != NULL)
12787         CERT_DestroyCertificate(ss->ssl3.clientCertificate);
12788
12789     if (ss->ssl3.clientPrivateKey != NULL)
12790         SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
12791 #ifdef NSS_PLATFORM_CLIENT_AUTH
12792     if (ss->ssl3.platformClientKey)
12793         ssl_FreePlatformKey(ss->ssl3.platformClientKey);
12794 #endif /* NSS_PLATFORM_CLIENT_AUTH */
12795
12796     if (ss->ssl3.channelID)
12797         SECKEY_DestroyPrivateKey(ss->ssl3.channelID);
12798     if (ss->ssl3.channelIDPub)
12799         SECKEY_DestroyPublicKey(ss->ssl3.channelIDPub);
12800
12801     if (ss->ssl3.peerCertArena != NULL)
12802         ssl3_CleanupPeerCerts(ss);
12803
12804     if (ss->ssl3.clientCertChain != NULL) {
12805        CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
12806        ss->ssl3.clientCertChain = NULL;
12807     }
12808
12809     /* clean up handshake */
12810 #ifndef NO_PKCS11_BYPASS
12811     if (ss->opt.bypassPKCS11) {
12812         if (ss->ssl3.hs.hashType == handshake_hash_combo) {
12813             SHA1_DestroyContext((SHA1Context *)ss->ssl3.hs.sha_cx, PR_FALSE);
12814             MD5_DestroyContext((MD5Context *)ss->ssl3.hs.md5_cx, PR_FALSE);
12815         } else if (ss->ssl3.hs.hashType == handshake_hash_single) {
12816             ss->ssl3.hs.sha_obj->destroy(ss->ssl3.hs.sha_cx, PR_FALSE);
12817         }
12818     } 
12819 #endif
12820     if (ss->ssl3.hs.md5) {
12821         PK11_DestroyContext(ss->ssl3.hs.md5,PR_TRUE);
12822     }
12823     if (ss->ssl3.hs.sha) {
12824         PK11_DestroyContext(ss->ssl3.hs.sha,PR_TRUE);
12825     }
12826     if (ss->ssl3.hs.clientSigAndHash) {
12827         PORT_Free(ss->ssl3.hs.clientSigAndHash);
12828     }
12829     if (ss->ssl3.hs.messages.buf) {
12830         PORT_Free(ss->ssl3.hs.messages.buf);
12831         ss->ssl3.hs.messages.buf = NULL;
12832         ss->ssl3.hs.messages.len = 0;
12833         ss->ssl3.hs.messages.space = 0;
12834     }
12835
12836     /* free the SSL3Buffer (msg_body) */
12837     PORT_Free(ss->ssl3.hs.msg_body.buf);
12838
12839     SECITEM_FreeItem(&ss->ssl3.hs.newSessionTicket.ticket, PR_FALSE);
12840
12841     /* free up the CipherSpecs */
12842     ssl3_DestroyCipherSpec(&ss->ssl3.specs[0], PR_TRUE/*freeSrvName*/);
12843     ssl3_DestroyCipherSpec(&ss->ssl3.specs[1], PR_TRUE/*freeSrvName*/);
12844
12845     /* Destroy the DTLS data */
12846     if (IS_DTLS(ss)) {
12847         dtls_FreeHandshakeMessages(&ss->ssl3.hs.lastMessageFlight);
12848         if (ss->ssl3.hs.recvdFragments.buf) {
12849             PORT_Free(ss->ssl3.hs.recvdFragments.buf);
12850         }
12851     }
12852
12853     ss->ssl3.initialized = PR_FALSE;
12854
12855     SECITEM_FreeItem(&ss->ssl3.nextProto, PR_FALSE);
12856 }
12857
12858 /* End of ssl3con.c */