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