• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * SSL3 Protocol
3  *
4  * ***** BEGIN LICENSE BLOCK *****
5  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
6  *
7  * The contents of this file are subject to the Mozilla Public License Version
8  * 1.1 (the "License"); you may not use this file except in compliance with
9  * the License. You may obtain a copy of the License at
10  * http://www.mozilla.org/MPL/
11  *
12  * Software distributed under the License is distributed on an "AS IS" basis,
13  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
14  * for the specific language governing rights and limitations under the
15  * License.
16  *
17  * The Original Code is the Netscape security libraries.
18  *
19  * The Initial Developer of the Original Code is
20  * Netscape Communications Corporation.
21  * Portions created by the Initial Developer are Copyright (C) 1994-2000
22  * the Initial Developer. All Rights Reserved.
23  *
24  * Contributor(s):
25  *   Dr Stephen Henson <stephen.henson@gemplus.com>
26  *   Dr Vipul Gupta <vipul.gupta@sun.com> and
27  *   Douglas Stebila <douglas@stebila.ca>, Sun Microsystems Laboratories
28  *
29  * Alternatively, the contents of this file may be used under the terms of
30  * either the GNU General Public License Version 2 or later (the "GPL"), or
31  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
32  * in which case the provisions of the GPL or the LGPL are applicable instead
33  * of those above. If you wish to allow use of your version of this file only
34  * under the terms of either the GPL or the LGPL, and not to allow others to
35  * use your version of this file under the terms of the MPL, indicate your
36  * decision by deleting the provisions above and replace them with the notice
37  * and other provisions required by the GPL or the LGPL. If you do not delete
38  * the provisions above, a recipient may use your version of this file under
39  * the terms of any one of the MPL, the GPL or the LGPL.
40  *
41  * ***** END LICENSE BLOCK ***** */
42 /* $Id: ssl3con.c,v 1.126 2009/12/01 17:59:46 wtc%google.com Exp $ */
43 
44 #include "cert.h"
45 #include "ssl.h"
46 #include "cryptohi.h"	/* for DSAU_ stuff */
47 #include "keyhi.h"
48 #include "secder.h"
49 #include "secitem.h"
50 
51 #include "sslimpl.h"
52 #include "sslproto.h"
53 #include "sslerr.h"
54 #include "prtime.h"
55 #include "prinrval.h"
56 #include "prerror.h"
57 #include "pratom.h"
58 #include "prthread.h"
59 
60 #include "pk11func.h"
61 #include "secmod.h"
62 #include "blapi.h"
63 
64 #include <stdio.h>
65 #ifdef NSS_ENABLE_ZLIB
66 #include "zlib.h"
67 #endif
68 
69 #ifndef PK11_SETATTRS
70 #define PK11_SETATTRS(x,id,v,l) (x)->type = (id); \
71 		(x)->pValue=(v); (x)->ulValueLen = (l);
72 #endif
73 
74 static void      ssl3_CleanupPeerCerts(sslSocket *ss);
75 static PK11SymKey *ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec,
76                                        PK11SlotInfo * serverKeySlot);
77 static SECStatus ssl3_DeriveMasterSecret(sslSocket *ss, PK11SymKey *pms);
78 static SECStatus ssl3_DeriveConnectionKeysPKCS11(sslSocket *ss);
79 static SECStatus ssl3_HandshakeFailure(      sslSocket *ss);
80 static SECStatus ssl3_InitState(             sslSocket *ss);
81 static SECStatus ssl3_SendCertificate(       sslSocket *ss);
82 static SECStatus ssl3_SendEmptyCertificate(  sslSocket *ss);
83 static SECStatus ssl3_SendCertificateRequest(sslSocket *ss);
84 static SECStatus ssl3_SendNextProto(         sslSocket *ss);
85 static SECStatus ssl3_SendFinished(          sslSocket *ss, PRInt32 flags);
86 static SECStatus ssl3_SendServerHello(       sslSocket *ss);
87 static SECStatus ssl3_SendServerHelloDone(   sslSocket *ss);
88 static SECStatus ssl3_SendServerKeyExchange( sslSocket *ss);
89 static SECStatus ssl3_NewHandshakeHashes(    sslSocket *ss);
90 static SECStatus ssl3_UpdateHandshakeHashes( sslSocket *ss, unsigned char *b,
91                                              unsigned int l);
92 
93 static SECStatus Null_Cipher(void *ctx, unsigned char *output, int *outputLen,
94 			     int maxOutputLen, const unsigned char *input,
95 			     int inputLen);
96 
97 #define MAX_SEND_BUF_LENGTH 32000 /* watch for 16-bit integer overflow */
98 #define MIN_SEND_BUF_LENGTH  4000
99 
100 #define MAX_CIPHER_SUITES 20
101 
102 /* This list of SSL3 cipher suites is sorted in descending order of
103  * precedence (desirability).  It only includes cipher suites we implement.
104  * This table is modified by SSL3_SetPolicy(). The ordering of cipher suites
105  * in this table must match the ordering in SSL_ImplementedCiphers (sslenum.c)
106  */
107 static ssl3CipherSuiteCfg cipherSuites[ssl_V3_SUITES_IMPLEMENTED] = {
108    /*      cipher_suite                         policy      enabled is_present*/
109 #ifdef NSS_ENABLE_ECC
110  { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,   SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
111  { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,     SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
112 #endif /* NSS_ENABLE_ECC */
113  { TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA,  SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
114  { TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA,  SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
115  { TLS_DHE_RSA_WITH_AES_256_CBC_SHA, 	   SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
116  { TLS_DHE_DSS_WITH_AES_256_CBC_SHA, 	   SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
117 #ifdef NSS_ENABLE_ECC
118  { TLS_ECDH_RSA_WITH_AES_256_CBC_SHA,      SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
119  { TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA,    SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
120 #endif /* NSS_ENABLE_ECC */
121  { TLS_RSA_WITH_CAMELLIA_256_CBC_SHA,  	   SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
122  { TLS_RSA_WITH_AES_256_CBC_SHA,     	   SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
123 
124 #ifdef NSS_ENABLE_ECC
125  { TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,       SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
126  { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,   SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
127  { TLS_ECDHE_RSA_WITH_RC4_128_SHA,         SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
128  { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,     SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
129 #endif /* NSS_ENABLE_ECC */
130  { TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA,  SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
131  { TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA,  SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
132  { TLS_DHE_DSS_WITH_RC4_128_SHA,           SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
133  { TLS_DHE_RSA_WITH_AES_128_CBC_SHA,       SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
134  { TLS_DHE_DSS_WITH_AES_128_CBC_SHA, 	   SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
135 #ifdef NSS_ENABLE_ECC
136  { TLS_ECDH_RSA_WITH_RC4_128_SHA,          SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
137  { TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,      SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
138  { TLS_ECDH_ECDSA_WITH_RC4_128_SHA,        SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
139  { TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,    SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
140 #endif /* NSS_ENABLE_ECC */
141  { TLS_RSA_WITH_SEED_CBC_SHA,              SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
142  { TLS_RSA_WITH_CAMELLIA_128_CBC_SHA,  	   SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
143  { SSL_RSA_WITH_RC4_128_MD5,               SSL_NOT_ALLOWED, PR_TRUE, PR_FALSE},
144  { SSL_RSA_WITH_RC4_128_SHA,               SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
145  { TLS_RSA_WITH_AES_128_CBC_SHA,     	   SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
146 
147 #ifdef NSS_ENABLE_ECC
148  { TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA,  SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
149  { TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,    SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
150 #endif /* NSS_ENABLE_ECC */
151  { SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA,      SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
152  { SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA,      SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
153 #ifdef NSS_ENABLE_ECC
154  { TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA,     SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
155  { TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA,   SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
156 #endif /* NSS_ENABLE_ECC */
157  { SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA,     SSL_NOT_ALLOWED, PR_TRUE, PR_FALSE},
158  { SSL_RSA_WITH_3DES_EDE_CBC_SHA,          SSL_NOT_ALLOWED, PR_TRUE, PR_FALSE},
159 
160 
161  { SSL_DHE_RSA_WITH_DES_CBC_SHA,           SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
162  { SSL_DHE_DSS_WITH_DES_CBC_SHA,           SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
163  { SSL_RSA_FIPS_WITH_DES_CBC_SHA,          SSL_NOT_ALLOWED, PR_TRUE, PR_FALSE},
164  { SSL_RSA_WITH_DES_CBC_SHA,               SSL_NOT_ALLOWED, PR_TRUE, PR_FALSE},
165  { TLS_RSA_EXPORT1024_WITH_RC4_56_SHA,     SSL_NOT_ALLOWED, PR_TRUE, PR_FALSE},
166  { TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA,    SSL_NOT_ALLOWED, PR_TRUE, PR_FALSE},
167 
168  { SSL_RSA_EXPORT_WITH_RC4_40_MD5,         SSL_NOT_ALLOWED, PR_TRUE, PR_FALSE},
169  { SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5,     SSL_NOT_ALLOWED, PR_TRUE, PR_FALSE},
170 
171 #ifdef NSS_ENABLE_ECC
172  { TLS_ECDHE_ECDSA_WITH_NULL_SHA,          SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
173  { TLS_ECDHE_RSA_WITH_NULL_SHA,            SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
174  { TLS_ECDH_RSA_WITH_NULL_SHA,             SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
175  { TLS_ECDH_ECDSA_WITH_NULL_SHA,           SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
176 #endif /* NSS_ENABLE_ECC */
177  { SSL_RSA_WITH_NULL_SHA,                  SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
178  { SSL_RSA_WITH_NULL_MD5,                  SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
179 
180 };
181 
182 /* This list of SSL3 compression methods is sorted in descending order of
183  * precedence (desirability).  It only includes compression methods we
184  * implement.
185  */
186 static const /*SSLCompressionMethod*/ uint8 compressions [] = {
187 #ifdef NSS_ENABLE_ZLIB
188     ssl_compression_deflate,
189 #endif
190     ssl_compression_null
191 };
192 
193 static const int compressionMethodsCount =
194     sizeof(compressions) / sizeof(compressions[0]);
195 
196 /* compressionEnabled returns true iff the compression algorithm is enabled
197  * for the given SSL socket. */
198 static PRBool
compressionEnabled(sslSocket * ss,SSLCompressionMethod compression)199 compressionEnabled(sslSocket *ss, SSLCompressionMethod compression)
200 {
201     switch (compression) {
202     case ssl_compression_null:
203 	return PR_TRUE;  /* Always enabled */
204 #ifdef NSS_ENABLE_ZLIB
205     case ssl_compression_deflate:
206 	return ss->opt.enableDeflate;
207 #endif
208     default:
209 	return PR_FALSE;
210     }
211 }
212 
213 static const /*SSL3ClientCertificateType */ uint8 certificate_types [] = {
214     ct_RSA_sign,
215     ct_DSS_sign,
216 #ifdef NSS_ENABLE_ECC
217     ct_ECDSA_sign,
218 #endif /* NSS_ENABLE_ECC */
219 };
220 
221 #ifdef NSS_ENABLE_ZLIB
222 /*
223  * The DEFLATE algorithm can result in an expansion of 0.1% + 12 bytes. For a
224  * maximum TLS record payload of 2**14 bytes, that's 29 bytes.
225  */
226 #define SSL3_COMPRESSION_MAX_EXPANSION 29
227 #else  /* !NSS_ENABLE_ZLIB */
228 #define SSL3_COMPRESSION_MAX_EXPANSION 0
229 #endif
230 
231 /*
232  * make sure there is room in the write buffer for padding and
233  * other compression and cryptographic expansions.
234  */
235 #define SSL3_BUFFER_FUDGE     100 + SSL3_COMPRESSION_MAX_EXPANSION
236 
237 #define EXPORT_RSA_KEY_LENGTH 64	/* bytes */
238 
239 
240 /* This is a hack to make sure we don't do double handshakes for US policy */
241 PRBool ssl3_global_policy_some_restricted = PR_FALSE;
242 
243 /* This global item is used only in servers.  It is is initialized by
244 ** SSL_ConfigSecureServer(), and is used in ssl3_SendCertificateRequest().
245 */
246 CERTDistNames *ssl3_server_ca_list = NULL;
247 static SSL3Statistics ssl3stats;
248 
249 /* indexed by SSL3BulkCipher */
250 static const ssl3BulkCipherDef bulk_cipher_defs[] = {
251     /* cipher          calg        keySz secretSz  type  ivSz BlkSz keygen */
252     {cipher_null,      calg_null,      0,  0, type_stream,  0, 0, kg_null},
253     {cipher_rc4,       calg_rc4,      16, 16, type_stream,  0, 0, kg_strong},
254     {cipher_rc4_40,    calg_rc4,      16,  5, type_stream,  0, 0, kg_export},
255     {cipher_rc4_56,    calg_rc4,      16,  7, type_stream,  0, 0, kg_export},
256     {cipher_rc2,       calg_rc2,      16, 16, type_block,   8, 8, kg_strong},
257     {cipher_rc2_40,    calg_rc2,      16,  5, type_block,   8, 8, kg_export},
258     {cipher_des,       calg_des,       8,  8, type_block,   8, 8, kg_strong},
259     {cipher_3des,      calg_3des,     24, 24, type_block,   8, 8, kg_strong},
260     {cipher_des40,     calg_des,       8,  5, type_block,   8, 8, kg_export},
261     {cipher_idea,      calg_idea,     16, 16, type_block,   8, 8, kg_strong},
262     {cipher_aes_128,   calg_aes,      16, 16, type_block,  16,16, kg_strong},
263     {cipher_aes_256,   calg_aes,      32, 32, type_block,  16,16, kg_strong},
264     {cipher_camellia_128, calg_camellia,16, 16, type_block,  16,16, kg_strong},
265     {cipher_camellia_256, calg_camellia,32, 32, type_block,  16,16, kg_strong},
266     {cipher_seed,      calg_seed,     16, 16, type_block,  16,16, kg_strong},
267     {cipher_missing,   calg_null,      0,  0, type_stream,  0, 0, kg_null},
268 };
269 
270 static const ssl3KEADef kea_defs[] =
271 { /* indexed by SSL3KeyExchangeAlgorithm */
272     /* kea              exchKeyType signKeyType is_limited limit  tls_keygen */
273     {kea_null,           kt_null,     sign_null, PR_FALSE,   0, PR_FALSE},
274     {kea_rsa,            kt_rsa,      sign_rsa,  PR_FALSE,   0, PR_FALSE},
275     {kea_rsa_export,     kt_rsa,      sign_rsa,  PR_TRUE,  512, PR_FALSE},
276     {kea_rsa_export_1024,kt_rsa,      sign_rsa,  PR_TRUE, 1024, PR_FALSE},
277     {kea_dh_dss,         kt_dh,       sign_dsa,  PR_FALSE,   0, PR_FALSE},
278     {kea_dh_dss_export,  kt_dh,       sign_dsa,  PR_TRUE,  512, PR_FALSE},
279     {kea_dh_rsa,         kt_dh,       sign_rsa,  PR_FALSE,   0, PR_FALSE},
280     {kea_dh_rsa_export,  kt_dh,       sign_rsa,  PR_TRUE,  512, PR_FALSE},
281     {kea_dhe_dss,        kt_dh,       sign_dsa,  PR_FALSE,   0, PR_FALSE},
282     {kea_dhe_dss_export, kt_dh,       sign_dsa,  PR_TRUE,  512, PR_FALSE},
283     {kea_dhe_rsa,        kt_dh,       sign_rsa,  PR_FALSE,   0, PR_FALSE},
284     {kea_dhe_rsa_export, kt_dh,       sign_rsa,  PR_TRUE,  512, PR_FALSE},
285     {kea_dh_anon,        kt_dh,       sign_null, PR_FALSE,   0, PR_FALSE},
286     {kea_dh_anon_export, kt_dh,       sign_null, PR_TRUE,  512, PR_FALSE},
287     {kea_rsa_fips,       kt_rsa,      sign_rsa,  PR_FALSE,   0, PR_TRUE },
288 #ifdef NSS_ENABLE_ECC
289     {kea_ecdh_ecdsa,     kt_ecdh,     sign_ecdsa,  PR_FALSE, 0, PR_FALSE},
290     {kea_ecdhe_ecdsa,    kt_ecdh,     sign_ecdsa,  PR_FALSE,   0, PR_FALSE},
291     {kea_ecdh_rsa,       kt_ecdh,     sign_rsa,  PR_FALSE,   0, PR_FALSE},
292     {kea_ecdhe_rsa,      kt_ecdh,     sign_rsa,  PR_FALSE,   0, PR_FALSE},
293     {kea_ecdh_anon,      kt_ecdh,     sign_null,  PR_FALSE,   0, PR_FALSE},
294 #endif /* NSS_ENABLE_ECC */
295 };
296 
297 /* must use ssl_LookupCipherSuiteDef to access */
298 static const ssl3CipherSuiteDef cipher_suite_defs[] =
299 {
300 /*  cipher_suite                    bulk_cipher_alg mac_alg key_exchange_alg */
301 
302     {SSL_NULL_WITH_NULL_NULL,       cipher_null,   mac_null, kea_null},
303     {SSL_RSA_WITH_NULL_MD5,         cipher_null,   mac_md5, kea_rsa},
304     {SSL_RSA_WITH_NULL_SHA,         cipher_null,   mac_sha, kea_rsa},
305     {SSL_RSA_EXPORT_WITH_RC4_40_MD5,cipher_rc4_40, mac_md5, kea_rsa_export},
306     {SSL_RSA_WITH_RC4_128_MD5,      cipher_rc4,    mac_md5, kea_rsa},
307     {SSL_RSA_WITH_RC4_128_SHA,      cipher_rc4,    mac_sha, kea_rsa},
308     {SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5,
309                                     cipher_rc2_40, mac_md5, kea_rsa_export},
310 #if 0 /* not implemented */
311     {SSL_RSA_WITH_IDEA_CBC_SHA,     cipher_idea,   mac_sha, kea_rsa},
312     {SSL_RSA_EXPORT_WITH_DES40_CBC_SHA,
313                                     cipher_des40,  mac_sha, kea_rsa_export},
314 #endif
315     {SSL_RSA_WITH_DES_CBC_SHA,      cipher_des,    mac_sha, kea_rsa},
316     {SSL_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des,   mac_sha, kea_rsa},
317     {SSL_DHE_DSS_WITH_DES_CBC_SHA,  cipher_des,    mac_sha, kea_dhe_dss},
318     {SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA,
319                                     cipher_3des,   mac_sha, kea_dhe_dss},
320     {TLS_DHE_DSS_WITH_RC4_128_SHA,  cipher_rc4,    mac_sha, kea_dhe_dss},
321 #if 0 /* not implemented */
322     {SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA,
323                                     cipher_des40,  mac_sha, kea_dh_dss_export},
324     {SSL_DH_DSS_DES_CBC_SHA,        cipher_des,    mac_sha, kea_dh_dss},
325     {SSL_DH_DSS_3DES_CBC_SHA,       cipher_3des,   mac_sha, kea_dh_dss},
326     {SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA,
327                                     cipher_des40,  mac_sha, kea_dh_rsa_export},
328     {SSL_DH_RSA_DES_CBC_SHA,        cipher_des,    mac_sha, kea_dh_rsa},
329     {SSL_DH_RSA_3DES_CBC_SHA,       cipher_3des,   mac_sha, kea_dh_rsa},
330     {SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA,
331                                     cipher_des40,  mac_sha, kea_dh_dss_export},
332     {SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA,
333                                     cipher_des40,  mac_sha, kea_dh_rsa_export},
334 #endif
335     {SSL_DHE_RSA_WITH_DES_CBC_SHA,  cipher_des,    mac_sha, kea_dhe_rsa},
336     {SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA,
337                                     cipher_3des,   mac_sha, kea_dhe_rsa},
338 #if 0
339     {SSL_DH_ANON_EXPORT_RC4_40_MD5, cipher_rc4_40, mac_md5, kea_dh_anon_export},
340     {SSL_DH_ANON_EXPORT_RC4_40_MD5, cipher_rc4,    mac_md5, kea_dh_anon_export},
341     {SSL_DH_ANON_EXPORT_WITH_DES40_CBC_SHA,
342                                     cipher_des40,  mac_sha, kea_dh_anon_export},
343     {SSL_DH_ANON_DES_CBC_SHA,       cipher_des,    mac_sha, kea_dh_anon},
344     {SSL_DH_ANON_3DES_CBC_SHA,      cipher_3des,   mac_sha, kea_dh_anon},
345 #endif
346 
347 
348 /* New TLS cipher suites */
349     {TLS_RSA_WITH_AES_128_CBC_SHA,     	cipher_aes_128, mac_sha, kea_rsa},
350     {TLS_DHE_DSS_WITH_AES_128_CBC_SHA, 	cipher_aes_128, mac_sha, kea_dhe_dss},
351     {TLS_DHE_RSA_WITH_AES_128_CBC_SHA, 	cipher_aes_128, mac_sha, kea_dhe_rsa},
352     {TLS_RSA_WITH_AES_256_CBC_SHA,     	cipher_aes_256, mac_sha, kea_rsa},
353     {TLS_DHE_DSS_WITH_AES_256_CBC_SHA, 	cipher_aes_256, mac_sha, kea_dhe_dss},
354     {TLS_DHE_RSA_WITH_AES_256_CBC_SHA, 	cipher_aes_256, mac_sha, kea_dhe_rsa},
355 #if 0
356     {TLS_DH_DSS_WITH_AES_128_CBC_SHA,  	cipher_aes_128, mac_sha, kea_dh_dss},
357     {TLS_DH_RSA_WITH_AES_128_CBC_SHA,  	cipher_aes_128, mac_sha, kea_dh_rsa},
358     {TLS_DH_ANON_WITH_AES_128_CBC_SHA, 	cipher_aes_128, mac_sha, kea_dh_anon},
359     {TLS_DH_DSS_WITH_AES_256_CBC_SHA,  	cipher_aes_256, mac_sha, kea_dh_dss},
360     {TLS_DH_RSA_WITH_AES_256_CBC_SHA,  	cipher_aes_256, mac_sha, kea_dh_rsa},
361     {TLS_DH_ANON_WITH_AES_256_CBC_SHA, 	cipher_aes_256, mac_sha, kea_dh_anon},
362 #endif
363 
364     {TLS_RSA_WITH_SEED_CBC_SHA,	    cipher_seed,   mac_sha, kea_rsa},
365 
366     {TLS_RSA_WITH_CAMELLIA_128_CBC_SHA, cipher_camellia_128, mac_sha, kea_rsa},
367     {TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA,
368      cipher_camellia_128, mac_sha, kea_dhe_dss},
369     {TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA,
370      cipher_camellia_128, mac_sha, kea_dhe_rsa},
371     {TLS_RSA_WITH_CAMELLIA_256_CBC_SHA,	cipher_camellia_256, mac_sha, kea_rsa},
372     {TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA,
373      cipher_camellia_256, mac_sha, kea_dhe_dss},
374     {TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA,
375      cipher_camellia_256, mac_sha, kea_dhe_rsa},
376 
377     {TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA,
378                                     cipher_des,    mac_sha,kea_rsa_export_1024},
379     {TLS_RSA_EXPORT1024_WITH_RC4_56_SHA,
380                                     cipher_rc4_56, mac_sha,kea_rsa_export_1024},
381 
382     {SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_rsa_fips},
383     {SSL_RSA_FIPS_WITH_DES_CBC_SHA, cipher_des,    mac_sha, kea_rsa_fips},
384 
385 #ifdef NSS_ENABLE_ECC
386     {TLS_ECDH_ECDSA_WITH_NULL_SHA,        cipher_null, mac_sha, kea_ecdh_ecdsa},
387     {TLS_ECDH_ECDSA_WITH_RC4_128_SHA,      cipher_rc4, mac_sha, kea_ecdh_ecdsa},
388     {TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdh_ecdsa},
389     {TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdh_ecdsa},
390     {TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdh_ecdsa},
391 
392     {TLS_ECDHE_ECDSA_WITH_NULL_SHA,        cipher_null, mac_sha, kea_ecdhe_ecdsa},
393     {TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,      cipher_rc4, mac_sha, kea_ecdhe_ecdsa},
394     {TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdhe_ecdsa},
395     {TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdhe_ecdsa},
396     {TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdhe_ecdsa},
397 
398     {TLS_ECDH_RSA_WITH_NULL_SHA,         cipher_null,    mac_sha, kea_ecdh_rsa},
399     {TLS_ECDH_RSA_WITH_RC4_128_SHA,      cipher_rc4,     mac_sha, kea_ecdh_rsa},
400     {TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des,    mac_sha, kea_ecdh_rsa},
401     {TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,  cipher_aes_128, mac_sha, kea_ecdh_rsa},
402     {TLS_ECDH_RSA_WITH_AES_256_CBC_SHA,  cipher_aes_256, mac_sha, kea_ecdh_rsa},
403 
404     {TLS_ECDHE_RSA_WITH_NULL_SHA,         cipher_null,    mac_sha, kea_ecdhe_rsa},
405     {TLS_ECDHE_RSA_WITH_RC4_128_SHA,      cipher_rc4,     mac_sha, kea_ecdhe_rsa},
406     {TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des,    mac_sha, kea_ecdhe_rsa},
407     {TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,  cipher_aes_128, mac_sha, kea_ecdhe_rsa},
408     {TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,  cipher_aes_256, mac_sha, kea_ecdhe_rsa},
409 
410 #if 0
411     {TLS_ECDH_anon_WITH_NULL_SHA,         cipher_null,    mac_sha, kea_ecdh_anon},
412     {TLS_ECDH_anon_WITH_RC4_128_SHA,      cipher_rc4,     mac_sha, kea_ecdh_anon},
413     {TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA, cipher_3des,    mac_sha, kea_ecdh_anon},
414     {TLS_ECDH_anon_WITH_AES_128_CBC_SHA,  cipher_aes_128, mac_sha, kea_ecdh_anon},
415     {TLS_ECDH_anon_WITH_AES_256_CBC_SHA,  cipher_aes_256, mac_sha, kea_ecdh_anon},
416 #endif
417 #endif /* NSS_ENABLE_ECC */
418 };
419 
420 static const CK_MECHANISM_TYPE kea_alg_defs[] = {
421     0x80000000L,
422     CKM_RSA_PKCS,
423     CKM_DH_PKCS_DERIVE,
424     CKM_KEA_KEY_DERIVE,
425     CKM_ECDH1_DERIVE
426 };
427 
428 typedef struct SSLCipher2MechStr {
429     SSLCipherAlgorithm  calg;
430     CK_MECHANISM_TYPE   cmech;
431 } SSLCipher2Mech;
432 
433 /* indexed by type SSLCipherAlgorithm */
434 static const SSLCipher2Mech alg2Mech[] = {
435     /* calg,          cmech  */
436     { calg_null     , (CK_MECHANISM_TYPE)0x80000000L	},
437     { calg_rc4      , CKM_RC4				},
438     { calg_rc2      , CKM_RC2_CBC			},
439     { calg_des      , CKM_DES_CBC			},
440     { calg_3des     , CKM_DES3_CBC			},
441     { calg_idea     , CKM_IDEA_CBC			},
442     { calg_fortezza , CKM_SKIPJACK_CBC64                },
443     { calg_aes      , CKM_AES_CBC			},
444     { calg_camellia , CKM_CAMELLIA_CBC			},
445     { calg_seed     , CKM_SEED_CBC			},
446 /*  { calg_init     , (CK_MECHANISM_TYPE)0x7fffffffL    }  */
447 };
448 
449 #define mmech_null     (CK_MECHANISM_TYPE)0x80000000L
450 #define mmech_md5      CKM_SSL3_MD5_MAC
451 #define mmech_sha      CKM_SSL3_SHA1_MAC
452 #define mmech_md5_hmac CKM_MD5_HMAC
453 #define mmech_sha_hmac CKM_SHA_1_HMAC
454 
455 static const ssl3MACDef mac_defs[] = { /* indexed by SSL3MACAlgorithm */
456     /* mac      mmech       pad_size  mac_size                       */
457     { mac_null, mmech_null,       0,  0          },
458     { mac_md5,  mmech_md5,       48,  MD5_LENGTH },
459     { mac_sha,  mmech_sha,       40,  SHA1_LENGTH},
460     {hmac_md5,  mmech_md5_hmac,  48,  MD5_LENGTH },
461     {hmac_sha,  mmech_sha_hmac,  40,  SHA1_LENGTH},
462 };
463 
464 /* indexed by SSL3BulkCipher */
465 const char * const ssl3_cipherName[] = {
466     "NULL",
467     "RC4",
468     "RC4-40",
469     "RC4-56",
470     "RC2-CBC",
471     "RC2-CBC-40",
472     "DES-CBC",
473     "3DES-EDE-CBC",
474     "DES-CBC-40",
475     "IDEA-CBC",
476     "AES-128",
477     "AES-256",
478     "Camellia-128",
479     "Camellia-256",
480     "SEED-CBC",
481     "missing"
482 };
483 
484 #ifdef NSS_ENABLE_ECC
485 /* The ECCWrappedKeyInfo structure defines how various pieces of
486  * information are laid out within wrappedSymmetricWrappingkey
487  * for ECDH key exchange. Since wrappedSymmetricWrappingkey is
488  * a 512-byte buffer (see sslimpl.h), the variable length field
489  * in ECCWrappedKeyInfo can be at most (512 - 8) = 504 bytes.
490  *
491  * XXX For now, NSS only supports named elliptic curves of size 571 bits
492  * or smaller. The public value will fit within 145 bytes and EC params
493  * will fit within 12 bytes. We'll need to revisit this when NSS
494  * supports arbitrary curves.
495  */
496 #define MAX_EC_WRAPPED_KEY_BUFLEN  504
497 
498 typedef struct ECCWrappedKeyInfoStr {
499     PRUint16 size;            /* EC public key size in bits */
500     PRUint16 encodedParamLen; /* length (in bytes) of DER encoded EC params */
501     PRUint16 pubValueLen;     /* length (in bytes) of EC public value */
502     PRUint16 wrappedKeyLen;   /* length (in bytes) of the wrapped key */
503     PRUint8 var[MAX_EC_WRAPPED_KEY_BUFLEN]; /* this buffer contains the */
504     /* EC public-key params, the EC public value and the wrapped key  */
505 } ECCWrappedKeyInfo;
506 #endif /* NSS_ENABLE_ECC */
507 
508 #if defined(TRACE)
509 
510 static char *
ssl3_DecodeHandshakeType(int msgType)511 ssl3_DecodeHandshakeType(int msgType)
512 {
513     char * rv;
514     static char line[40];
515 
516     switch(msgType) {
517     case hello_request:	        rv = "hello_request (0)";               break;
518     case client_hello:	        rv = "client_hello  (1)";               break;
519     case server_hello:	        rv = "server_hello  (2)";               break;
520     case certificate:	        rv = "certificate  (11)";               break;
521     case server_key_exchange:	rv = "server_key_exchange (12)";        break;
522     case certificate_request:	rv = "certificate_request (13)";        break;
523     case server_hello_done:	rv = "server_hello_done   (14)";        break;
524     case certificate_verify:	rv = "certificate_verify  (15)";        break;
525     case client_key_exchange:	rv = "client_key_exchange (16)";        break;
526     case finished:	        rv = "finished     (20)";               break;
527     default:
528         sprintf(line, "*UNKNOWN* handshake type! (%d)", msgType);
529 	rv = line;
530     }
531     return rv;
532 }
533 
534 static char *
ssl3_DecodeContentType(int msgType)535 ssl3_DecodeContentType(int msgType)
536 {
537     char * rv;
538     static char line[40];
539 
540     switch(msgType) {
541     case content_change_cipher_spec:
542                                 rv = "change_cipher_spec (20)";         break;
543     case content_alert:	        rv = "alert      (21)";                 break;
544     case content_handshake:	rv = "handshake  (22)";                 break;
545     case content_application_data:
546                                 rv = "application_data (23)";           break;
547     default:
548         sprintf(line, "*UNKNOWN* record type! (%d)", msgType);
549 	rv = line;
550     }
551     return rv;
552 }
553 
554 #endif
555 
556 SSL3Statistics *
SSL_GetStatistics(void)557 SSL_GetStatistics(void)
558 {
559     return &ssl3stats;
560 }
561 
562 typedef struct tooLongStr {
563 #if defined(IS_LITTLE_ENDIAN)
564     PRInt32 low;
565     PRInt32 high;
566 #else
567     PRInt32 high;
568     PRInt32 low;
569 #endif
570 } tooLong;
571 
SSL_AtomicIncrementLong(long * x)572 void SSL_AtomicIncrementLong(long * x)
573 {
574     if ((sizeof *x) == sizeof(PRInt32)) {
575         PR_AtomicIncrement((PRInt32 *)x);
576     } else {
577     	tooLong * tl = (tooLong *)x;
578 	if (PR_AtomicIncrement(&tl->low) == 0)
579 	    PR_AtomicIncrement(&tl->high);
580     }
581 }
582 
583 /* return pointer to ssl3CipherSuiteDef for suite, or NULL */
584 /* XXX This does a linear search.  A binary search would be better. */
585 static const ssl3CipherSuiteDef *
ssl_LookupCipherSuiteDef(ssl3CipherSuite suite)586 ssl_LookupCipherSuiteDef(ssl3CipherSuite suite)
587 {
588     int cipher_suite_def_len =
589 	sizeof(cipher_suite_defs) / sizeof(cipher_suite_defs[0]);
590     int i;
591 
592     for (i = 0; i < cipher_suite_def_len; i++) {
593 	if (cipher_suite_defs[i].cipher_suite == suite)
594 	    return &cipher_suite_defs[i];
595     }
596     PORT_Assert(PR_FALSE);  /* We should never get here. */
597     PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE);
598     return NULL;
599 }
600 
601 /* Find the cipher configuration struct associate with suite */
602 /* XXX This does a linear search.  A binary search would be better. */
603 static ssl3CipherSuiteCfg *
ssl_LookupCipherSuiteCfg(ssl3CipherSuite suite,ssl3CipherSuiteCfg * suites)604 ssl_LookupCipherSuiteCfg(ssl3CipherSuite suite, ssl3CipherSuiteCfg *suites)
605 {
606     int i;
607 
608     for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
609 	if (suites[i].cipher_suite == suite)
610 	    return &suites[i];
611     }
612     /* return NULL and let the caller handle it.  */
613     PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE);
614     return NULL;
615 }
616 
617 
618 /* Initialize the suite->isPresent value for config_match
619  * Returns count of enabled ciphers supported by extant tokens,
620  * regardless of policy or user preference.
621  * If this returns zero, the user cannot do SSL v3.
622  */
623 int
ssl3_config_match_init(sslSocket * ss)624 ssl3_config_match_init(sslSocket *ss)
625 {
626     ssl3CipherSuiteCfg *      suite;
627     const ssl3CipherSuiteDef *cipher_def;
628     SSLCipherAlgorithm        cipher_alg;
629     CK_MECHANISM_TYPE         cipher_mech;
630     SSL3KEAType               exchKeyType;
631     int                       i;
632     int                       numPresent		= 0;
633     int                       numEnabled		= 0;
634     PRBool                    isServer;
635     sslServerCerts           *svrAuth;
636 
637     PORT_Assert(ss);
638     if (!ss) {
639     	PORT_SetError(SEC_ERROR_INVALID_ARGS);
640 	return 0;
641     }
642     if (!ss->opt.enableSSL3 && !ss->opt.enableTLS) {
643     	return 0;
644     }
645     isServer = (PRBool)(ss->sec.isServer != 0);
646 
647     for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
648 	suite = &ss->cipherSuites[i];
649 	if (suite->enabled) {
650 	    ++numEnabled;
651 	    /* We need the cipher defs to see if we have a token that can handle
652 	     * this cipher.  It isn't part of the static definition.
653 	     */
654 	    cipher_def = ssl_LookupCipherSuiteDef(suite->cipher_suite);
655 	    if (!cipher_def) {
656 	    	suite->isPresent = PR_FALSE;
657 		continue;
658 	    }
659 	    cipher_alg=bulk_cipher_defs[cipher_def->bulk_cipher_alg ].calg;
660 	    PORT_Assert(  alg2Mech[cipher_alg].calg == cipher_alg);
661 	    cipher_mech = alg2Mech[cipher_alg].cmech;
662 	    exchKeyType =
663 	    	    kea_defs[cipher_def->key_exchange_alg].exchKeyType;
664 #ifndef NSS_ENABLE_ECC
665 	    svrAuth = ss->serverCerts + exchKeyType;
666 #else
667 	    /* XXX SSLKEAType isn't really a good choice for
668 	     * indexing certificates. It doesn't work for
669 	     * (EC)DHE-* ciphers. Here we use a hack to ensure
670 	     * that the server uses an RSA cert for (EC)DHE-RSA.
671 	     */
672 	    switch (cipher_def->key_exchange_alg) {
673 	    case kea_ecdhe_rsa:
674 #if NSS_SERVER_DHE_IMPLEMENTED
675 	    /* XXX NSS does not yet implement the server side of _DHE_
676 	     * cipher suites.  Correcting the computation for svrAuth,
677 	     * as the case below does, causes NSS SSL servers to begin to
678 	     * negotiate cipher suites they do not implement.  So, until
679 	     * server side _DHE_ is implemented, keep this disabled.
680 	     */
681 	    case kea_dhe_rsa:
682 #endif
683 		svrAuth = ss->serverCerts + kt_rsa;
684 		break;
685 	    case kea_ecdh_ecdsa:
686 	    case kea_ecdh_rsa:
687 	        /*
688 		 * XXX We ought to have different indices for
689 		 * ECDSA- and RSA-signed EC certificates so
690 		 * we could support both key exchange mechanisms
691 		 * simultaneously. For now, both of them use
692 		 * whatever is in the certificate slot for kt_ecdh
693 		 */
694 	    default:
695 		svrAuth = ss->serverCerts + exchKeyType;
696 		break;
697 	    }
698 #endif /* NSS_ENABLE_ECC */
699 
700 	    /* Mark the suites that are backed by real tokens, certs and keys */
701 	    suite->isPresent = (PRBool)
702 		(((exchKeyType == kt_null) ||
703 		   ((!isServer || (svrAuth->serverKeyPair &&
704 		                   svrAuth->SERVERKEY &&
705 				   svrAuth->serverCertChain)) &&
706 		    PK11_TokenExists(kea_alg_defs[exchKeyType]))) &&
707 		((cipher_alg == calg_null) || PK11_TokenExists(cipher_mech)));
708 	    if (suite->isPresent)
709 	    	++numPresent;
710 	}
711     }
712     PORT_Assert(numPresent > 0 || numEnabled == 0);
713     if (numPresent <= 0) {
714 	PORT_SetError(SSL_ERROR_NO_CIPHERS_SUPPORTED);
715     }
716     return numPresent;
717 }
718 
719 
720 /* return PR_TRUE if suite matches policy and enabled state */
721 /* It would be a REALLY BAD THING (tm) if we ever permitted the use
722 ** of a cipher that was NOT_ALLOWED.  So, if this is ever called with
723 ** policy == SSL_NOT_ALLOWED, report no match.
724 */
725 /* adjust suite enabled to the availability of a token that can do the
726  * cipher suite. */
727 static PRBool
config_match(ssl3CipherSuiteCfg * suite,int policy,PRBool enabled)728 config_match(ssl3CipherSuiteCfg *suite, int policy, PRBool enabled)
729 {
730     PORT_Assert(policy != SSL_NOT_ALLOWED && enabled != PR_FALSE);
731     if (policy == SSL_NOT_ALLOWED || !enabled)
732     	return PR_FALSE;
733     return (PRBool)(suite->enabled &&
734                     suite->isPresent &&
735 	            suite->policy != SSL_NOT_ALLOWED &&
736 		    suite->policy <= policy);
737 }
738 
739 /* return number of cipher suites that match policy and enabled state */
740 /* called from ssl3_SendClientHello and ssl3_ConstructV2CipherSpecsHack */
741 static int
count_cipher_suites(sslSocket * ss,int policy,PRBool enabled)742 count_cipher_suites(sslSocket *ss, int policy, PRBool enabled)
743 {
744     int i, count = 0;
745 
746     if (!ss->opt.enableSSL3 && !ss->opt.enableTLS) {
747     	return 0;
748     }
749     for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
750 	if (config_match(&ss->cipherSuites[i], policy, enabled))
751 	    count++;
752     }
753     if (count <= 0) {
754 	PORT_SetError(SSL_ERROR_SSL_DISABLED);
755     }
756     return count;
757 }
758 
759 static PRBool
anyRestrictedEnabled(sslSocket * ss)760 anyRestrictedEnabled(sslSocket *ss)
761 {
762     int i;
763 
764     if (!ss->opt.enableSSL3 && !ss->opt.enableTLS) {
765     	return PR_FALSE;
766     }
767     for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
768 	ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i];
769 	if (suite->policy == SSL_RESTRICTED &&
770 	    suite->enabled &&
771 	    suite->isPresent)
772 	    return PR_TRUE;
773     }
774     return PR_FALSE;
775 }
776 
777 /*
778  * Null compression, mac and encryption functions
779  */
780 
781 static SECStatus
Null_Cipher(void * ctx,unsigned char * output,int * outputLen,int maxOutputLen,const unsigned char * input,int inputLen)782 Null_Cipher(void *ctx, unsigned char *output, int *outputLen, int maxOutputLen,
783 	    const unsigned char *input, int inputLen)
784 {
785     *outputLen = inputLen;
786     if (input != output)
787 	PORT_Memcpy(output, input, inputLen);
788     return SECSuccess;
789 }
790 
791 /*
792  * SSL3 Utility functions
793  */
794 
795 SECStatus
ssl3_NegotiateVersion(sslSocket * ss,SSL3ProtocolVersion peerVersion)796 ssl3_NegotiateVersion(sslSocket *ss, SSL3ProtocolVersion peerVersion)
797 {
798     SSL3ProtocolVersion version;
799     SSL3ProtocolVersion maxVersion;
800 
801     if (ss->opt.enableTLS) {
802 	maxVersion = SSL_LIBRARY_VERSION_3_1_TLS;
803     } else if (ss->opt.enableSSL3) {
804 	maxVersion = SSL_LIBRARY_VERSION_3_0;
805     } else {
806     	/* what are we doing here? */
807 	PORT_Assert(ss->opt.enableSSL3 || ss->opt.enableTLS);
808 	PORT_SetError(SSL_ERROR_SSL_DISABLED);
809 	return SECFailure;
810     }
811 
812     ss->version = version = PR_MIN(maxVersion, peerVersion);
813 
814     if ((version == SSL_LIBRARY_VERSION_3_1_TLS && ss->opt.enableTLS) ||
815     	(version == SSL_LIBRARY_VERSION_3_0     && ss->opt.enableSSL3)) {
816 	return SECSuccess;
817     }
818 
819     PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
820     return SECFailure;
821 
822 }
823 
824 static SECStatus
ssl3_GetNewRandom(SSL3Random * random)825 ssl3_GetNewRandom(SSL3Random *random)
826 {
827     PRUint32 gmt = ssl_Time();
828     SECStatus rv;
829 
830     random->rand[0] = (unsigned char)(gmt >> 24);
831     random->rand[1] = (unsigned char)(gmt >> 16);
832     random->rand[2] = (unsigned char)(gmt >>  8);
833     random->rand[3] = (unsigned char)(gmt);
834 
835     /* first 4 bytes are reserverd for time */
836     rv = PK11_GenerateRandom(&random->rand[4], SSL3_RANDOM_LENGTH - 4);
837     if (rv != SECSuccess) {
838 	ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
839     }
840     return rv;
841 }
842 
843 /* Called by ssl3_SendServerKeyExchange and ssl3_SendCertificateVerify */
844 SECStatus
ssl3_SignHashes(SSL3Hashes * hash,SECKEYPrivateKey * key,SECItem * buf,PRBool isTLS)845 ssl3_SignHashes(SSL3Hashes *hash, SECKEYPrivateKey *key, SECItem *buf,
846                 PRBool isTLS)
847 {
848     SECStatus rv		= SECFailure;
849     PRBool    doDerEncode       = PR_FALSE;
850     int       signatureLen;
851     SECItem   hashItem;
852 
853     buf->data    = NULL;
854     signatureLen = PK11_SignatureLen(key);
855     if (signatureLen <= 0) {
856 	PORT_SetError(SEC_ERROR_INVALID_KEY);
857         goto done;
858     }
859 
860     buf->len  = (unsigned)signatureLen;
861     buf->data = (unsigned char *)PORT_Alloc(signatureLen);
862     if (!buf->data)
863         goto done;	/* error code was set. */
864 
865     switch (key->keyType) {
866     case rsaKey:
867     	hashItem.data = hash->md5;
868     	hashItem.len = sizeof(SSL3Hashes);
869 	break;
870     case dsaKey:
871 	doDerEncode = isTLS;
872 	hashItem.data = hash->sha;
873 	hashItem.len = sizeof(hash->sha);
874 	break;
875 #ifdef NSS_ENABLE_ECC
876     case ecKey:
877 	doDerEncode = PR_TRUE;
878 	hashItem.data = hash->sha;
879 	hashItem.len = sizeof(hash->sha);
880 	break;
881 #endif /* NSS_ENABLE_ECC */
882     default:
883 	PORT_SetError(SEC_ERROR_INVALID_KEY);
884 	goto done;
885     }
886     PRINT_BUF(60, (NULL, "hash(es) to be signed", hashItem.data, hashItem.len));
887 
888     rv = PK11_Sign(key, buf, &hashItem);
889     if (rv != SECSuccess) {
890 	ssl_MapLowLevelError(SSL_ERROR_SIGN_HASHES_FAILURE);
891     } else if (doDerEncode) {
892 	SECItem   derSig	= {siBuffer, NULL, 0};
893 
894 	/* This also works for an ECDSA signature */
895 	rv = DSAU_EncodeDerSigWithLen(&derSig, buf, buf->len);
896 	if (rv == SECSuccess) {
897 	    PORT_Free(buf->data);	/* discard unencoded signature. */
898 	    *buf = derSig;		/* give caller encoded signature. */
899 	} else if (derSig.data) {
900 	    PORT_Free(derSig.data);
901 	}
902     }
903 
904     PRINT_BUF(60, (NULL, "signed hashes", (unsigned char*)buf->data, buf->len));
905 done:
906     if (rv != SECSuccess && buf->data) {
907 	PORT_Free(buf->data);
908 	buf->data = NULL;
909     }
910     return rv;
911 }
912 
913 /* Called from ssl3_HandleServerKeyExchange, ssl3_HandleCertificateVerify */
914 SECStatus
ssl3_VerifySignedHashes(SSL3Hashes * hash,CERTCertificate * cert,SECItem * buf,PRBool isTLS,void * pwArg)915 ssl3_VerifySignedHashes(SSL3Hashes *hash, CERTCertificate *cert,
916                         SECItem *buf, PRBool isTLS, void *pwArg)
917 {
918     SECKEYPublicKey * key;
919     SECItem *         signature	= NULL;
920     SECStatus         rv;
921     SECItem           hashItem;
922 #ifdef NSS_ENABLE_ECC
923     unsigned int      len;
924 #endif /* NSS_ENABLE_ECC */
925 
926 
927     PRINT_BUF(60, (NULL, "check signed hashes",
928                   buf->data, buf->len));
929 
930     key = CERT_ExtractPublicKey(cert);
931     if (key == NULL) {
932 	/* CERT_ExtractPublicKey doesn't set error code */
933 	PORT_SetError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
934     	return SECFailure;
935     }
936 
937     switch (key->keyType) {
938     case rsaKey:
939     	hashItem.data = hash->md5;
940     	hashItem.len = sizeof(SSL3Hashes);
941 	break;
942     case dsaKey:
943 	hashItem.data = hash->sha;
944 	hashItem.len = sizeof(hash->sha);
945 	/* Allow DER encoded DSA signatures in SSL 3.0 */
946 	if (isTLS || buf->len != DSA_SIGNATURE_LEN) {
947 	    signature = DSAU_DecodeDerSig(buf);
948 	    if (!signature) {
949 	    	PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
950 		return SECFailure;
951 	    }
952 	    buf = signature;
953 	}
954 	break;
955 
956 #ifdef NSS_ENABLE_ECC
957     case ecKey:
958 	hashItem.data = hash->sha;
959 	hashItem.len = sizeof(hash->sha);
960 	/*
961 	 * ECDSA signatures always encode the integers r and s
962 	 * using ASN (unlike DSA where ASN encoding is used
963 	 * with TLS but not with SSL3)
964 	 */
965 	len = SECKEY_SignatureLen(key);
966 	if (len == 0) {
967 	    SECKEY_DestroyPublicKey(key);
968 	    PORT_SetError(SEC_ERROR_UNSUPPORTED_ELLIPTIC_CURVE);
969 	    return SECFailure;
970 	}
971 	signature = DSAU_DecodeDerSigToLen(buf, len);
972 	if (!signature) {
973 	    PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
974 	    return SECFailure;
975 	}
976 	buf = signature;
977 	break;
978 #endif /* NSS_ENABLE_ECC */
979 
980     default:
981     	SECKEY_DestroyPublicKey(key);
982 	PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
983 	return SECFailure;
984     }
985 
986     PRINT_BUF(60, (NULL, "hash(es) to be verified",
987                   hashItem.data, hashItem.len));
988 
989     rv = PK11_Verify(key, buf, &hashItem, pwArg);
990     SECKEY_DestroyPublicKey(key);
991     if (signature) {
992     	SECITEM_FreeItem(signature, PR_TRUE);
993     }
994     if (rv != SECSuccess) {
995 	ssl_MapLowLevelError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
996     }
997     return rv;
998 }
999 
1000 
1001 /* Caller must set hiLevel error code. */
1002 /* Called from ssl3_ComputeExportRSAKeyHash
1003  *             ssl3_ComputeDHKeyHash
1004  * which are called from ssl3_HandleServerKeyExchange.
1005  */
1006 SECStatus
ssl3_ComputeCommonKeyHash(PRUint8 * hashBuf,unsigned int bufLen,SSL3Hashes * hashes,PRBool bypassPKCS11)1007 ssl3_ComputeCommonKeyHash(PRUint8 * hashBuf, unsigned int bufLen,
1008 			     SSL3Hashes *hashes, PRBool bypassPKCS11)
1009 {
1010     SECStatus     rv 		= SECSuccess;
1011 
1012     if (bypassPKCS11) {
1013 	MD5_HashBuf (hashes->md5, hashBuf, bufLen);
1014 	SHA1_HashBuf(hashes->sha, hashBuf, bufLen);
1015     } else {
1016 	rv = PK11_HashBuf(SEC_OID_MD5, hashes->md5, hashBuf, bufLen);
1017 	if (rv != SECSuccess) {
1018 	    ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
1019 	    rv = SECFailure;
1020 	    goto done;
1021 	}
1022 
1023 	rv = PK11_HashBuf(SEC_OID_SHA1, hashes->sha, hashBuf, bufLen);
1024 	if (rv != SECSuccess) {
1025 	    ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
1026 	    rv = SECFailure;
1027 	}
1028     }
1029 done:
1030     return rv;
1031 }
1032 
1033 /* Caller must set hiLevel error code.
1034 ** Called from ssl3_SendServerKeyExchange and
1035 **             ssl3_HandleServerKeyExchange.
1036 */
1037 static SECStatus
ssl3_ComputeExportRSAKeyHash(SECItem modulus,SECItem publicExponent,SSL3Random * client_rand,SSL3Random * server_rand,SSL3Hashes * hashes,PRBool bypassPKCS11)1038 ssl3_ComputeExportRSAKeyHash(SECItem modulus, SECItem publicExponent,
1039 			     SSL3Random *client_rand, SSL3Random *server_rand,
1040 			     SSL3Hashes *hashes, PRBool bypassPKCS11)
1041 {
1042     PRUint8     * hashBuf;
1043     PRUint8     * pBuf;
1044     SECStatus     rv 		= SECSuccess;
1045     unsigned int  bufLen;
1046     PRUint8       buf[2*SSL3_RANDOM_LENGTH + 2 + 4096/8 + 2 + 4096/8];
1047 
1048     bufLen = 2*SSL3_RANDOM_LENGTH + 2 + modulus.len + 2 + publicExponent.len;
1049     if (bufLen <= sizeof buf) {
1050     	hashBuf = buf;
1051     } else {
1052     	hashBuf = PORT_Alloc(bufLen);
1053 	if (!hashBuf) {
1054 	    return SECFailure;
1055 	}
1056     }
1057 
1058     memcpy(hashBuf, client_rand, SSL3_RANDOM_LENGTH);
1059     	pBuf = hashBuf + SSL3_RANDOM_LENGTH;
1060     memcpy(pBuf, server_rand, SSL3_RANDOM_LENGTH);
1061     	pBuf += SSL3_RANDOM_LENGTH;
1062     pBuf[0]  = (PRUint8)(modulus.len >> 8);
1063     pBuf[1]  = (PRUint8)(modulus.len);
1064     	pBuf += 2;
1065     memcpy(pBuf, modulus.data, modulus.len);
1066     	pBuf += modulus.len;
1067     pBuf[0] = (PRUint8)(publicExponent.len >> 8);
1068     pBuf[1] = (PRUint8)(publicExponent.len);
1069     	pBuf += 2;
1070     memcpy(pBuf, publicExponent.data, publicExponent.len);
1071     	pBuf += publicExponent.len;
1072     PORT_Assert((unsigned int)(pBuf - hashBuf) == bufLen);
1073 
1074     rv = ssl3_ComputeCommonKeyHash(hashBuf, bufLen, hashes, bypassPKCS11);
1075 
1076     PRINT_BUF(95, (NULL, "RSAkey hash: ", hashBuf, bufLen));
1077     PRINT_BUF(95, (NULL, "RSAkey hash: MD5 result", hashes->md5, MD5_LENGTH));
1078     PRINT_BUF(95, (NULL, "RSAkey hash: SHA1 result", hashes->sha, SHA1_LENGTH));
1079 
1080     if (hashBuf != buf && hashBuf != NULL)
1081     	PORT_Free(hashBuf);
1082     return rv;
1083 }
1084 
1085 /* Caller must set hiLevel error code. */
1086 /* Called from ssl3_HandleServerKeyExchange. */
1087 static SECStatus
ssl3_ComputeDHKeyHash(SECItem dh_p,SECItem dh_g,SECItem dh_Ys,SSL3Random * client_rand,SSL3Random * server_rand,SSL3Hashes * hashes,PRBool bypassPKCS11)1088 ssl3_ComputeDHKeyHash(SECItem dh_p, SECItem dh_g, SECItem dh_Ys,
1089 			     SSL3Random *client_rand, SSL3Random *server_rand,
1090 			     SSL3Hashes *hashes, PRBool bypassPKCS11)
1091 {
1092     PRUint8     * hashBuf;
1093     PRUint8     * pBuf;
1094     SECStatus     rv 		= SECSuccess;
1095     unsigned int  bufLen;
1096     PRUint8       buf[2*SSL3_RANDOM_LENGTH + 2 + 4096/8 + 2 + 4096/8];
1097 
1098     bufLen = 2*SSL3_RANDOM_LENGTH + 2 + dh_p.len + 2 + dh_g.len + 2 + dh_Ys.len;
1099     if (bufLen <= sizeof buf) {
1100     	hashBuf = buf;
1101     } else {
1102     	hashBuf = PORT_Alloc(bufLen);
1103 	if (!hashBuf) {
1104 	    return SECFailure;
1105 	}
1106     }
1107 
1108     memcpy(hashBuf, client_rand, SSL3_RANDOM_LENGTH);
1109     	pBuf = hashBuf + SSL3_RANDOM_LENGTH;
1110     memcpy(pBuf, server_rand, SSL3_RANDOM_LENGTH);
1111     	pBuf += SSL3_RANDOM_LENGTH;
1112     pBuf[0]  = (PRUint8)(dh_p.len >> 8);
1113     pBuf[1]  = (PRUint8)(dh_p.len);
1114     	pBuf += 2;
1115     memcpy(pBuf, dh_p.data, dh_p.len);
1116     	pBuf += dh_p.len;
1117     pBuf[0] = (PRUint8)(dh_g.len >> 8);
1118     pBuf[1] = (PRUint8)(dh_g.len);
1119     	pBuf += 2;
1120     memcpy(pBuf, dh_g.data, dh_g.len);
1121     	pBuf += dh_g.len;
1122     pBuf[0] = (PRUint8)(dh_Ys.len >> 8);
1123     pBuf[1] = (PRUint8)(dh_Ys.len);
1124     	pBuf += 2;
1125     memcpy(pBuf, dh_Ys.data, dh_Ys.len);
1126     	pBuf += dh_Ys.len;
1127     PORT_Assert((unsigned int)(pBuf - hashBuf) == bufLen);
1128 
1129     rv = ssl3_ComputeCommonKeyHash(hashBuf, bufLen, hashes, bypassPKCS11);
1130 
1131     PRINT_BUF(95, (NULL, "DHkey hash: ", hashBuf, bufLen));
1132     PRINT_BUF(95, (NULL, "DHkey hash: MD5 result", hashes->md5, MD5_LENGTH));
1133     PRINT_BUF(95, (NULL, "DHkey hash: SHA1 result", hashes->sha, SHA1_LENGTH));
1134 
1135     if (hashBuf != buf && hashBuf != NULL)
1136     	PORT_Free(hashBuf);
1137     return rv;
1138 }
1139 
1140 static void
ssl3_BumpSequenceNumber(SSL3SequenceNumber * num)1141 ssl3_BumpSequenceNumber(SSL3SequenceNumber *num)
1142 {
1143     num->low++;
1144     if (num->low == 0)
1145 	num->high++;
1146 }
1147 
1148 /* Called twice, only from ssl3_DestroyCipherSpec (immediately below). */
1149 static void
ssl3_CleanupKeyMaterial(ssl3KeyMaterial * mat)1150 ssl3_CleanupKeyMaterial(ssl3KeyMaterial *mat)
1151 {
1152     if (mat->write_key != NULL) {
1153 	PK11_FreeSymKey(mat->write_key);
1154 	mat->write_key = NULL;
1155     }
1156     if (mat->write_mac_key != NULL) {
1157 	PK11_FreeSymKey(mat->write_mac_key);
1158 	mat->write_mac_key = NULL;
1159     }
1160     if (mat->write_mac_context != NULL) {
1161 	PK11_DestroyContext(mat->write_mac_context, PR_TRUE);
1162 	mat->write_mac_context = NULL;
1163     }
1164 }
1165 
1166 /* Called from ssl3_SendChangeCipherSpecs() and
1167 **	       ssl3_HandleChangeCipherSpecs()
1168 **             ssl3_DestroySSL3Info
1169 ** Caller must hold SpecWriteLock.
1170 */
1171 static void
ssl3_DestroyCipherSpec(ssl3CipherSpec * spec)1172 ssl3_DestroyCipherSpec(ssl3CipherSpec *spec)
1173 {
1174     PRBool freeit = (PRBool)(!spec->bypassCiphers);
1175 /*  PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); Don't have ss! */
1176     if (spec->destroy) {
1177 	spec->destroy(spec->encodeContext, freeit);
1178 	spec->destroy(spec->decodeContext, freeit);
1179 	spec->encodeContext = NULL; /* paranoia */
1180 	spec->decodeContext = NULL;
1181     }
1182     if (spec->destroyCompressContext && spec->compressContext) {
1183 	spec->destroyCompressContext(spec->compressContext, 1);
1184 	spec->compressContext = NULL;
1185     }
1186     if (spec->destroyDecompressContext && spec->decompressContext) {
1187 	spec->destroyDecompressContext(spec->decompressContext, 1);
1188 	spec->decompressContext = NULL;
1189     }
1190     if (spec->master_secret != NULL) {
1191 	PK11_FreeSymKey(spec->master_secret);
1192 	spec->master_secret = NULL;
1193     }
1194     spec->msItem.data = NULL;
1195     spec->msItem.len  = 0;
1196     ssl3_CleanupKeyMaterial(&spec->client);
1197     ssl3_CleanupKeyMaterial(&spec->server);
1198     spec->bypassCiphers = PR_FALSE;
1199     spec->destroy=NULL;
1200     spec->destroyCompressContext = NULL;
1201     spec->destroyDecompressContext = NULL;
1202 }
1203 
1204 /* Fill in the pending cipher spec with info from the selected ciphersuite.
1205 ** This is as much initialization as we can do without having key material.
1206 ** Called from ssl3_HandleServerHello(), ssl3_SendServerHello()
1207 ** Caller must hold the ssl3 handshake lock.
1208 ** Acquires & releases SpecWriteLock.
1209 */
1210 static SECStatus
ssl3_SetupPendingCipherSpec(sslSocket * ss)1211 ssl3_SetupPendingCipherSpec(sslSocket *ss)
1212 {
1213     ssl3CipherSpec *          pwSpec;
1214     ssl3CipherSpec *          cwSpec;
1215     ssl3CipherSuite           suite     = ss->ssl3.hs.cipher_suite;
1216     SSL3MACAlgorithm          mac;
1217     SSL3BulkCipher            cipher;
1218     SSL3KeyExchangeAlgorithm  kea;
1219     const ssl3CipherSuiteDef *suite_def;
1220     PRBool                    isTLS;
1221 
1222     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
1223 
1224     ssl_GetSpecWriteLock(ss);  /*******************************/
1225 
1226     pwSpec = ss->ssl3.pwSpec;
1227     PORT_Assert(pwSpec == ss->ssl3.prSpec);
1228 
1229     /* This hack provides maximal interoperability with SSL 3 servers. */
1230     cwSpec = ss->ssl3.cwSpec;
1231     if (cwSpec->mac_def->mac == mac_null) {
1232 	/* SSL records are not being MACed. */
1233 	cwSpec->version = ss->version;
1234     }
1235 
1236     pwSpec->version  = ss->version;
1237     isTLS  = (PRBool)(pwSpec->version > SSL_LIBRARY_VERSION_3_0);
1238 
1239     SSL_TRC(3, ("%d: SSL3[%d]: Set XXX Pending Cipher Suite to 0x%04x",
1240 		SSL_GETPID(), ss->fd, suite));
1241 
1242     suite_def = ssl_LookupCipherSuiteDef(suite);
1243     if (suite_def == NULL) {
1244 	ssl_ReleaseSpecWriteLock(ss);
1245 	return SECFailure;	/* error code set by ssl_LookupCipherSuiteDef */
1246     }
1247 
1248 
1249     cipher = suite_def->bulk_cipher_alg;
1250     kea    = suite_def->key_exchange_alg;
1251     mac    = suite_def->mac_alg;
1252     if (isTLS)
1253 	mac += 2;
1254 
1255     ss->ssl3.hs.suite_def = suite_def;
1256     ss->ssl3.hs.kea_def   = &kea_defs[kea];
1257     PORT_Assert(ss->ssl3.hs.kea_def->kea == kea);
1258 
1259     pwSpec->cipher_def   = &bulk_cipher_defs[cipher];
1260     PORT_Assert(pwSpec->cipher_def->cipher == cipher);
1261 
1262     pwSpec->mac_def = &mac_defs[mac];
1263     PORT_Assert(pwSpec->mac_def->mac == mac);
1264 
1265     ss->sec.keyBits       = pwSpec->cipher_def->key_size        * BPB;
1266     ss->sec.secretKeyBits = pwSpec->cipher_def->secret_key_size * BPB;
1267     ss->sec.cipherType    = cipher;
1268 
1269     pwSpec->encodeContext = NULL;
1270     pwSpec->decodeContext = NULL;
1271 
1272     pwSpec->mac_size = pwSpec->mac_def->mac_size;
1273 
1274     pwSpec->compression_method = ss->ssl3.hs.compression;
1275     pwSpec->compressContext = NULL;
1276     pwSpec->decompressContext = NULL;
1277 
1278     ssl_ReleaseSpecWriteLock(ss);  /*******************************/
1279     return SECSuccess;
1280 }
1281 
1282 #ifdef NSS_ENABLE_ZLIB
1283 #define SSL3_DEFLATE_CONTEXT_SIZE sizeof(z_stream)
1284 
1285 static SECStatus
ssl3_MapZlibError(int zlib_error)1286 ssl3_MapZlibError(int zlib_error)
1287 {
1288     switch (zlib_error) {
1289     case Z_OK:
1290         return SECSuccess;
1291     default:
1292         return SECFailure;
1293     }
1294 }
1295 
1296 static SECStatus
ssl3_DeflateInit(void * void_context)1297 ssl3_DeflateInit(void *void_context)
1298 {
1299     z_stream *context = void_context;
1300     context->zalloc = NULL;
1301     context->zfree = NULL;
1302     context->opaque = NULL;
1303 
1304     return ssl3_MapZlibError(deflateInit(context, Z_DEFAULT_COMPRESSION));
1305 }
1306 
1307 static SECStatus
ssl3_InflateInit(void * void_context)1308 ssl3_InflateInit(void *void_context)
1309 {
1310     z_stream *context = void_context;
1311     context->zalloc = NULL;
1312     context->zfree = NULL;
1313     context->opaque = NULL;
1314     context->next_in = NULL;
1315     context->avail_in = 0;
1316 
1317     return ssl3_MapZlibError(inflateInit(context));
1318 }
1319 
1320 static SECStatus
ssl3_DeflateCompress(void * void_context,unsigned char * out,int * out_len,int maxout,const unsigned char * in,int inlen)1321 ssl3_DeflateCompress(void *void_context, unsigned char *out, int *out_len,
1322                      int maxout, const unsigned char *in, int inlen)
1323 {
1324     z_stream *context = void_context;
1325 
1326     if (!inlen) {
1327         *out_len = 0;
1328         return SECSuccess;
1329     }
1330 
1331     context->next_in = (unsigned char*) in;
1332     context->avail_in = inlen;
1333     context->next_out = out;
1334     context->avail_out = maxout;
1335     if (deflate(context, Z_SYNC_FLUSH) != Z_OK) {
1336         return SECFailure;
1337     }
1338     if (context->avail_out == 0) {
1339         /* We ran out of space! */
1340         SSL_TRC(3, ("%d: SSL3[%d] Ran out of buffer while compressing",
1341                     SSL_GETPID()));
1342         return SECFailure;
1343     }
1344 
1345     *out_len = maxout - context->avail_out;
1346     return SECSuccess;
1347 }
1348 
1349 static SECStatus
ssl3_DeflateDecompress(void * void_context,unsigned char * out,int * out_len,int maxout,const unsigned char * in,int inlen)1350 ssl3_DeflateDecompress(void *void_context, unsigned char *out, int *out_len,
1351                        int maxout, const unsigned char *in, int inlen)
1352 {
1353     z_stream *context = void_context;
1354 
1355     if (!inlen) {
1356         *out_len = 0;
1357         return SECSuccess;
1358     }
1359 
1360     context->next_in = (unsigned char*) in;
1361     context->avail_in = inlen;
1362     context->next_out = out;
1363     context->avail_out = maxout;
1364     if (inflate(context, Z_SYNC_FLUSH) != Z_OK) {
1365         PORT_SetError(SSL_ERROR_DECOMPRESSION_FAILURE);
1366         return SECFailure;
1367     }
1368 
1369     *out_len = maxout - context->avail_out;
1370     return SECSuccess;
1371 }
1372 
1373 static SECStatus
ssl3_DestroyCompressContext(void * void_context,PRBool unused)1374 ssl3_DestroyCompressContext(void *void_context, PRBool unused)
1375 {
1376     deflateEnd(void_context);
1377     PORT_Free(void_context);
1378     return SECSuccess;
1379 }
1380 
1381 static SECStatus
ssl3_DestroyDecompressContext(void * void_context,PRBool unused)1382 ssl3_DestroyDecompressContext(void *void_context, PRBool unused)
1383 {
1384     inflateEnd(void_context);
1385     PORT_Free(void_context);
1386     return SECSuccess;
1387 }
1388 
1389 #endif /* NSS_ENABLE_ZLIB */
1390 
1391 /* Initialize the compression functions and contexts for the given
1392  * CipherSpec.  */
1393 static SECStatus
ssl3_InitCompressionContext(ssl3CipherSpec * pwSpec)1394 ssl3_InitCompressionContext(ssl3CipherSpec *pwSpec)
1395 {
1396     /* Setup the compression functions */
1397     switch (pwSpec->compression_method) {
1398     case ssl_compression_null:
1399 	pwSpec->compressor = NULL;
1400 	pwSpec->decompressor = NULL;
1401 	pwSpec->compressContext = NULL;
1402 	pwSpec->decompressContext = NULL;
1403 	pwSpec->destroyCompressContext = NULL;
1404 	pwSpec->destroyDecompressContext = NULL;
1405 	break;
1406 #ifdef NSS_ENABLE_ZLIB
1407     case ssl_compression_deflate:
1408 	pwSpec->compressor = ssl3_DeflateCompress;
1409 	pwSpec->decompressor = ssl3_DeflateDecompress;
1410 	pwSpec->compressContext = PORT_Alloc(SSL3_DEFLATE_CONTEXT_SIZE);
1411 	pwSpec->decompressContext = PORT_Alloc(SSL3_DEFLATE_CONTEXT_SIZE);
1412 	pwSpec->destroyCompressContext = ssl3_DestroyCompressContext;
1413 	pwSpec->destroyDecompressContext = ssl3_DestroyDecompressContext;
1414 	ssl3_DeflateInit(pwSpec->compressContext);
1415 	ssl3_InflateInit(pwSpec->decompressContext);
1416 	break;
1417 #endif /* NSS_ENABLE_ZLIB */
1418     default:
1419 	PORT_Assert(0);
1420 	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1421 	return SECFailure;
1422     }
1423 
1424     return SECSuccess;
1425 }
1426 
1427 /* Initialize encryption and MAC contexts for pending spec.
1428  * Master Secret already is derived in spec->msItem
1429  * Caller holds Spec write lock.
1430  */
1431 static SECStatus
ssl3_InitPendingContextsBypass(sslSocket * ss)1432 ssl3_InitPendingContextsBypass(sslSocket *ss)
1433 {
1434       ssl3CipherSpec  *  pwSpec;
1435 const ssl3BulkCipherDef *cipher_def;
1436       void *             serverContext = NULL;
1437       void *             clientContext = NULL;
1438       BLapiInitContextFunc initFn = (BLapiInitContextFunc)NULL;
1439       int                mode     = 0;
1440       unsigned int       optArg1  = 0;
1441       unsigned int       optArg2  = 0;
1442       PRBool             server_encrypts = ss->sec.isServer;
1443       CK_ULONG           macLength;
1444       SSLCipherAlgorithm calg;
1445       SSLCompressionMethod compression_method;
1446       SECStatus          rv;
1447 
1448     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
1449 
1450     PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
1451 
1452     pwSpec        = ss->ssl3.pwSpec;
1453     cipher_def    = pwSpec->cipher_def;
1454     macLength     = pwSpec->mac_size;
1455 
1456     /* MAC setup is done when computing the mac, not here.
1457      * Now setup the crypto contexts.
1458      */
1459 
1460     calg = cipher_def->calg;
1461     compression_method = pwSpec->compression_method;
1462 
1463     serverContext = pwSpec->server.cipher_context;
1464     clientContext = pwSpec->client.cipher_context;
1465 
1466     switch (calg) {
1467     case ssl_calg_null:
1468 	pwSpec->encode  = Null_Cipher;
1469 	pwSpec->decode  = Null_Cipher;
1470         pwSpec->destroy = NULL;
1471 	goto success;
1472 
1473     case ssl_calg_rc4:
1474       	initFn = (BLapiInitContextFunc)RC4_InitContext;
1475 	pwSpec->encode  = (SSLCipher) RC4_Encrypt;
1476 	pwSpec->decode  = (SSLCipher) RC4_Decrypt;
1477 	pwSpec->destroy = (SSLDestroy) RC4_DestroyContext;
1478 	break;
1479     case ssl_calg_rc2:
1480       	initFn = (BLapiInitContextFunc)RC2_InitContext;
1481 	mode = NSS_RC2_CBC;
1482 	optArg1 = cipher_def->key_size;
1483 	pwSpec->encode  = (SSLCipher) RC2_Encrypt;
1484 	pwSpec->decode  = (SSLCipher) RC2_Decrypt;
1485 	pwSpec->destroy = (SSLDestroy) RC2_DestroyContext;
1486 	break;
1487     case ssl_calg_des:
1488       	initFn = (BLapiInitContextFunc)DES_InitContext;
1489 	mode = NSS_DES_CBC;
1490 	optArg1 = server_encrypts;
1491 	pwSpec->encode  = (SSLCipher) DES_Encrypt;
1492 	pwSpec->decode  = (SSLCipher) DES_Decrypt;
1493 	pwSpec->destroy = (SSLDestroy) DES_DestroyContext;
1494 	break;
1495     case ssl_calg_3des:
1496       	initFn = (BLapiInitContextFunc)DES_InitContext;
1497 	mode = NSS_DES_EDE3_CBC;
1498 	optArg1 = server_encrypts;
1499 	pwSpec->encode  = (SSLCipher) DES_Encrypt;
1500 	pwSpec->decode  = (SSLCipher) DES_Decrypt;
1501 	pwSpec->destroy = (SSLDestroy) DES_DestroyContext;
1502 	break;
1503     case ssl_calg_aes:
1504       	initFn = (BLapiInitContextFunc)AES_InitContext;
1505 	mode = NSS_AES_CBC;
1506 	optArg1 = server_encrypts;
1507 	optArg2 = AES_BLOCK_SIZE;
1508 	pwSpec->encode  = (SSLCipher) AES_Encrypt;
1509 	pwSpec->decode  = (SSLCipher) AES_Decrypt;
1510 	pwSpec->destroy = (SSLDestroy) AES_DestroyContext;
1511 	break;
1512 
1513     case ssl_calg_camellia:
1514       	initFn = (BLapiInitContextFunc)Camellia_InitContext;
1515 	mode = NSS_CAMELLIA_CBC;
1516 	optArg1 = server_encrypts;
1517 	optArg2 = CAMELLIA_BLOCK_SIZE;
1518 	pwSpec->encode  = (SSLCipher) Camellia_Encrypt;
1519 	pwSpec->decode  = (SSLCipher) Camellia_Decrypt;
1520 	pwSpec->destroy = (SSLDestroy) Camellia_DestroyContext;
1521 	break;
1522 
1523     case ssl_calg_seed:
1524       	initFn = (BLapiInitContextFunc)SEED_InitContext;
1525 	mode = NSS_SEED_CBC;
1526 	optArg1 = server_encrypts;
1527 	optArg2 = SEED_BLOCK_SIZE;
1528 	pwSpec->encode  = (SSLCipher) SEED_Encrypt;
1529 	pwSpec->decode  = (SSLCipher) SEED_Decrypt;
1530 	pwSpec->destroy = (SSLDestroy) SEED_DestroyContext;
1531 	break;
1532 
1533     case ssl_calg_idea:
1534     case ssl_calg_fortezza :
1535     default:
1536 	PORT_Assert(0);
1537 	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1538 	goto bail_out;
1539     }
1540     rv = (*initFn)(serverContext,
1541 		   pwSpec->server.write_key_item.data,
1542 		   pwSpec->server.write_key_item.len,
1543 		   pwSpec->server.write_iv_item.data,
1544 		   mode, optArg1, optArg2);
1545     if (rv != SECSuccess) {
1546 	PORT_Assert(0);
1547 	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1548 	goto bail_out;
1549     }
1550 
1551     switch (calg) {
1552     case ssl_calg_des:
1553     case ssl_calg_3des:
1554     case ssl_calg_aes:
1555     case ssl_calg_camellia:
1556     case ssl_calg_seed:
1557 	/* For block ciphers, if the server is encrypting, then the client
1558 	* is decrypting, and vice versa.
1559 	*/
1560         optArg1 = !optArg1;
1561     }
1562 
1563     rv = (*initFn)(clientContext,
1564 		   pwSpec->client.write_key_item.data,
1565 		   pwSpec->client.write_key_item.len,
1566 		   pwSpec->client.write_iv_item.data,
1567 		   mode, optArg1, optArg2);
1568     if (rv != SECSuccess) {
1569 	PORT_Assert(0);
1570 	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1571 	goto bail_out;
1572     }
1573 
1574     pwSpec->encodeContext = (ss->sec.isServer) ? serverContext : clientContext;
1575     pwSpec->decodeContext = (ss->sec.isServer) ? clientContext : serverContext;
1576 
1577     ssl3_InitCompressionContext(pwSpec);
1578 
1579 success:
1580     return SECSuccess;
1581 
1582 bail_out:
1583     return SECFailure;
1584 }
1585 
1586 /* This function should probably be moved to pk11wrap and be named
1587  * PK11_ParamFromIVAndEffectiveKeyBits
1588  */
1589 static SECItem *
ssl3_ParamFromIV(CK_MECHANISM_TYPE mtype,SECItem * iv,CK_ULONG ulEffectiveBits)1590 ssl3_ParamFromIV(CK_MECHANISM_TYPE mtype, SECItem *iv, CK_ULONG ulEffectiveBits)
1591 {
1592     SECItem * param = PK11_ParamFromIV(mtype, iv);
1593     if (param && param->data  && param->len >= sizeof(CK_RC2_PARAMS)) {
1594 	switch (mtype) {
1595 	case CKM_RC2_KEY_GEN:
1596 	case CKM_RC2_ECB:
1597 	case CKM_RC2_CBC:
1598 	case CKM_RC2_MAC:
1599 	case CKM_RC2_MAC_GENERAL:
1600 	case CKM_RC2_CBC_PAD:
1601 	    *(CK_RC2_PARAMS *)param->data = ulEffectiveBits;
1602 	default: break;
1603 	}
1604     }
1605     return param;
1606 }
1607 
1608 /* Initialize encryption and MAC contexts for pending spec.
1609  * Master Secret already is derived.
1610  * Caller holds Spec write lock.
1611  */
1612 static SECStatus
ssl3_InitPendingContextsPKCS11(sslSocket * ss)1613 ssl3_InitPendingContextsPKCS11(sslSocket *ss)
1614 {
1615       ssl3CipherSpec  *  pwSpec;
1616 const ssl3BulkCipherDef *cipher_def;
1617       PK11Context *      serverContext = NULL;
1618       PK11Context *      clientContext = NULL;
1619       SECItem *          param;
1620       CK_MECHANISM_TYPE  mechanism;
1621       CK_MECHANISM_TYPE  mac_mech;
1622       CK_ULONG           macLength;
1623       CK_ULONG           effKeyBits;
1624       SECItem            iv;
1625       SECItem            mac_param;
1626       SSLCipherAlgorithm calg;
1627 
1628     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
1629 
1630     PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
1631 
1632     pwSpec        = ss->ssl3.pwSpec;
1633     cipher_def    = pwSpec->cipher_def;
1634     macLength     = pwSpec->mac_size;
1635 
1636     /*
1637     ** Now setup the MAC contexts,
1638     **   crypto contexts are setup below.
1639     */
1640 
1641     pwSpec->client.write_mac_context = NULL;
1642     pwSpec->server.write_mac_context = NULL;
1643     mac_mech       = pwSpec->mac_def->mmech;
1644     mac_param.data = (unsigned char *)&macLength;
1645     mac_param.len  = sizeof(macLength);
1646     mac_param.type = 0;
1647 
1648     pwSpec->client.write_mac_context = PK11_CreateContextBySymKey(
1649 	    mac_mech, CKA_SIGN, pwSpec->client.write_mac_key, &mac_param);
1650     if (pwSpec->client.write_mac_context == NULL)  {
1651 	ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
1652 	goto fail;
1653     }
1654     pwSpec->server.write_mac_context = PK11_CreateContextBySymKey(
1655 	    mac_mech, CKA_SIGN, pwSpec->server.write_mac_key, &mac_param);
1656     if (pwSpec->server.write_mac_context == NULL) {
1657 	ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
1658 	goto fail;
1659     }
1660 
1661     /*
1662     ** Now setup the crypto contexts.
1663     */
1664 
1665     calg = cipher_def->calg;
1666     PORT_Assert(alg2Mech[calg].calg == calg);
1667 
1668     if (calg == calg_null) {
1669 	pwSpec->encode  = Null_Cipher;
1670 	pwSpec->decode  = Null_Cipher;
1671 	pwSpec->destroy = NULL;
1672 	return SECSuccess;
1673     }
1674     mechanism = alg2Mech[calg].cmech;
1675     effKeyBits = cipher_def->key_size * BPB;
1676 
1677     /*
1678      * build the server context
1679      */
1680     iv.data = pwSpec->server.write_iv;
1681     iv.len  = cipher_def->iv_size;
1682     param = ssl3_ParamFromIV(mechanism, &iv, effKeyBits);
1683     if (param == NULL) {
1684 	ssl_MapLowLevelError(SSL_ERROR_IV_PARAM_FAILURE);
1685     	goto fail;
1686     }
1687     serverContext = PK11_CreateContextBySymKey(mechanism,
1688 				(ss->sec.isServer ? CKA_ENCRYPT : CKA_DECRYPT),
1689 				pwSpec->server.write_key, param);
1690     iv.data = PK11_IVFromParam(mechanism, param, (int *)&iv.len);
1691     if (iv.data)
1692     	PORT_Memcpy(pwSpec->server.write_iv, iv.data, iv.len);
1693     SECITEM_FreeItem(param, PR_TRUE);
1694     if (serverContext == NULL) {
1695 	ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
1696     	goto fail;
1697     }
1698 
1699     /*
1700      * build the client context
1701      */
1702     iv.data = pwSpec->client.write_iv;
1703     iv.len  = cipher_def->iv_size;
1704 
1705     param = ssl3_ParamFromIV(mechanism, &iv, effKeyBits);
1706     if (param == NULL) {
1707 	ssl_MapLowLevelError(SSL_ERROR_IV_PARAM_FAILURE);
1708     	goto fail;
1709     }
1710     clientContext = PK11_CreateContextBySymKey(mechanism,
1711 				(ss->sec.isServer ? CKA_DECRYPT : CKA_ENCRYPT),
1712 				pwSpec->client.write_key, param);
1713     iv.data = PK11_IVFromParam(mechanism, param, (int *)&iv.len);
1714     if (iv.data)
1715     	PORT_Memcpy(pwSpec->client.write_iv, iv.data, iv.len);
1716     SECITEM_FreeItem(param,PR_TRUE);
1717     if (clientContext == NULL) {
1718 	ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
1719     	goto fail;
1720     }
1721     pwSpec->encode  = (SSLCipher) PK11_CipherOp;
1722     pwSpec->decode  = (SSLCipher) PK11_CipherOp;
1723     pwSpec->destroy = (SSLDestroy) PK11_DestroyContext;
1724 
1725     pwSpec->encodeContext = (ss->sec.isServer) ? serverContext : clientContext;
1726     pwSpec->decodeContext = (ss->sec.isServer) ? clientContext : serverContext;
1727 
1728     serverContext = NULL;
1729     clientContext = NULL;
1730 
1731     ssl3_InitCompressionContext(pwSpec);
1732 
1733     return SECSuccess;
1734 
1735 fail:
1736     if (serverContext != NULL) PK11_DestroyContext(serverContext, PR_TRUE);
1737     if (clientContext != NULL) PK11_DestroyContext(clientContext, PR_TRUE);
1738     if (pwSpec->client.write_mac_context != NULL) {
1739     	PK11_DestroyContext(pwSpec->client.write_mac_context,PR_TRUE);
1740 	pwSpec->client.write_mac_context = NULL;
1741     }
1742     if (pwSpec->server.write_mac_context != NULL) {
1743     	PK11_DestroyContext(pwSpec->server.write_mac_context,PR_TRUE);
1744 	pwSpec->server.write_mac_context = NULL;
1745     }
1746 
1747     return SECFailure;
1748 }
1749 
1750 /* Complete the initialization of all keys, ciphers, MACs and their contexts
1751  * for the pending Cipher Spec.
1752  * Called from: ssl3_SendClientKeyExchange 	(for Full handshake)
1753  *              ssl3_HandleRSAClientKeyExchange	(for Full handshake)
1754  *              ssl3_HandleServerHello		(for session restart)
1755  *              ssl3_HandleClientHello		(for session restart)
1756  * Sets error code, but caller probably should override to disambiguate.
1757  * NULL pms means re-use old master_secret.
1758  *
1759  * This code is common to the bypass and PKCS11 execution paths.
1760  * For the bypass case,  pms is NULL.
1761  */
1762 SECStatus
ssl3_InitPendingCipherSpec(sslSocket * ss,PK11SymKey * pms)1763 ssl3_InitPendingCipherSpec(sslSocket *ss, PK11SymKey *pms)
1764 {
1765     ssl3CipherSpec  *  pwSpec;
1766     SECStatus          rv;
1767 
1768     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
1769 
1770     ssl_GetSpecWriteLock(ss);	/**************************************/
1771 
1772     PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
1773 
1774     pwSpec        = ss->ssl3.pwSpec;
1775 
1776     if (pms || (!pwSpec->msItem.len && !pwSpec->master_secret)) {
1777 	rv = ssl3_DeriveMasterSecret(ss, pms);
1778 	if (rv != SECSuccess) {
1779 	    goto done;  /* err code set by ssl3_DeriveMasterSecret */
1780 	}
1781     }
1782     if (ss->opt.bypassPKCS11 && pwSpec->msItem.len && pwSpec->msItem.data) {
1783 	/* Double Bypass succeeded in extracting the master_secret */
1784 	const ssl3KEADef * kea_def = ss->ssl3.hs.kea_def;
1785 	PRBool             isTLS   = (PRBool)(kea_def->tls_keygen ||
1786                                 (pwSpec->version > SSL_LIBRARY_VERSION_3_0));
1787 	pwSpec->bypassCiphers = PR_TRUE;
1788 	rv = ssl3_KeyAndMacDeriveBypass( pwSpec,
1789 			     (const unsigned char *)&ss->ssl3.hs.client_random,
1790 			     (const unsigned char *)&ss->ssl3.hs.server_random,
1791 			     isTLS,
1792 			     (PRBool)(kea_def->is_limited));
1793 	if (rv == SECSuccess) {
1794 	    rv = ssl3_InitPendingContextsBypass(ss);
1795 	}
1796     } else if (pwSpec->master_secret) {
1797 	rv = ssl3_DeriveConnectionKeysPKCS11(ss);
1798 	if (rv == SECSuccess) {
1799 	    rv = ssl3_InitPendingContextsPKCS11(ss);
1800 	}
1801     } else {
1802 	PORT_Assert(pwSpec->master_secret);
1803 	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1804 	rv = SECFailure;
1805     }
1806 
1807 done:
1808     ssl_ReleaseSpecWriteLock(ss);	/******************************/
1809     if (rv != SECSuccess)
1810 	ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
1811     return rv;
1812 }
1813 
1814 /*
1815  * 60 bytes is 3 times the maximum length MAC size that is supported.
1816  */
1817 static const unsigned char mac_pad_1 [60] = {
1818     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1819     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1820     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1821     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1822     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1823     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1824     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1825     0x36, 0x36, 0x36, 0x36
1826 };
1827 static const unsigned char mac_pad_2 [60] = {
1828     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1829     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1830     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1831     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1832     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1833     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1834     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1835     0x5c, 0x5c, 0x5c, 0x5c
1836 };
1837 
1838 /* Called from: ssl3_SendRecord()
1839 **		ssl3_HandleRecord()
1840 ** Caller must already hold the SpecReadLock. (wish we could assert that!)
1841 */
1842 static SECStatus
ssl3_ComputeRecordMAC(ssl3CipherSpec * spec,PRBool useServerMacKey,SSL3ContentType type,SSL3ProtocolVersion version,SSL3SequenceNumber seq_num,const SSL3Opaque * input,int inputLength,unsigned char * outbuf,unsigned int * outLength)1843 ssl3_ComputeRecordMAC(
1844     ssl3CipherSpec *   spec,
1845     PRBool             useServerMacKey,
1846     SSL3ContentType    type,
1847     SSL3ProtocolVersion version,
1848     SSL3SequenceNumber seq_num,
1849     const SSL3Opaque * input,
1850     int                inputLength,
1851     unsigned char *    outbuf,
1852     unsigned int *     outLength)
1853 {
1854     const ssl3MACDef * mac_def;
1855     SECStatus          rv;
1856     PRBool             isTLS;
1857     unsigned int       tempLen;
1858     unsigned char      temp[MAX_MAC_LENGTH];
1859 
1860     temp[0] = (unsigned char)(seq_num.high >> 24);
1861     temp[1] = (unsigned char)(seq_num.high >> 16);
1862     temp[2] = (unsigned char)(seq_num.high >>  8);
1863     temp[3] = (unsigned char)(seq_num.high >>  0);
1864     temp[4] = (unsigned char)(seq_num.low  >> 24);
1865     temp[5] = (unsigned char)(seq_num.low  >> 16);
1866     temp[6] = (unsigned char)(seq_num.low  >>  8);
1867     temp[7] = (unsigned char)(seq_num.low  >>  0);
1868     temp[8] = type;
1869 
1870     /* TLS MAC includes the record's version field, SSL's doesn't.
1871     ** We decide which MAC defintiion to use based on the version of
1872     ** the protocol that was negotiated when the spec became current,
1873     ** NOT based on the version value in the record itself.
1874     ** But, we use the record'v version value in the computation.
1875     */
1876     if (spec->version <= SSL_LIBRARY_VERSION_3_0) {
1877 	temp[9]  = MSB(inputLength);
1878 	temp[10] = LSB(inputLength);
1879 	tempLen  = 11;
1880 	isTLS    = PR_FALSE;
1881     } else {
1882     	/* New TLS hash includes version. */
1883 	temp[9]  = MSB(version);
1884 	temp[10] = LSB(version);
1885 	temp[11] = MSB(inputLength);
1886 	temp[12] = LSB(inputLength);
1887 	tempLen  = 13;
1888 	isTLS    = PR_TRUE;
1889     }
1890 
1891     PRINT_BUF(95, (NULL, "frag hash1: temp", temp, tempLen));
1892     PRINT_BUF(95, (NULL, "frag hash1: input", input, inputLength));
1893 
1894     mac_def = spec->mac_def;
1895     if (mac_def->mac == mac_null) {
1896 	*outLength = 0;
1897 	return SECSuccess;
1898     }
1899     if (! spec->bypassCiphers) {
1900 	PK11Context *mac_context =
1901 	    (useServerMacKey ? spec->server.write_mac_context
1902 	                     : spec->client.write_mac_context);
1903 	rv  = PK11_DigestBegin(mac_context);
1904 	rv |= PK11_DigestOp(mac_context, temp, tempLen);
1905 	rv |= PK11_DigestOp(mac_context, input, inputLength);
1906 	rv |= PK11_DigestFinal(mac_context, outbuf, outLength, spec->mac_size);
1907     } else {
1908 	/* bypass version */
1909 	const SECHashObject *hashObj = NULL;
1910 	unsigned int       pad_bytes = 0;
1911 	PRUint64           write_mac_context[MAX_MAC_CONTEXT_LLONGS];
1912 
1913 	switch (mac_def->mac) {
1914 	case ssl_mac_null:
1915 	    *outLength = 0;
1916 	    return SECSuccess;
1917 	case ssl_mac_md5:
1918 	    pad_bytes = 48;
1919 	    hashObj = HASH_GetRawHashObject(HASH_AlgMD5);
1920 	    break;
1921 	case ssl_mac_sha:
1922 	    pad_bytes = 40;
1923 	    hashObj = HASH_GetRawHashObject(HASH_AlgSHA1);
1924 	    break;
1925 	case ssl_hmac_md5: /* used with TLS */
1926 	    hashObj = HASH_GetRawHashObject(HASH_AlgMD5);
1927 	    break;
1928 	case ssl_hmac_sha: /* used with TLS */
1929 	    hashObj = HASH_GetRawHashObject(HASH_AlgSHA1);
1930 	    break;
1931 	default:
1932 	    break;
1933 	}
1934 	if (!hashObj) {
1935 	    PORT_Assert(0);
1936 	    PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1937 	    return SECFailure;
1938 	}
1939 
1940 	if (!isTLS) {
1941 	    /* compute "inner" part of SSL3 MAC */
1942 	    hashObj->begin(write_mac_context);
1943 	    if (useServerMacKey)
1944 		hashObj->update(write_mac_context,
1945 				spec->server.write_mac_key_item.data,
1946 				spec->server.write_mac_key_item.len);
1947 	    else
1948 		hashObj->update(write_mac_context,
1949 				spec->client.write_mac_key_item.data,
1950 				spec->client.write_mac_key_item.len);
1951 	    hashObj->update(write_mac_context, mac_pad_1, pad_bytes);
1952 	    hashObj->update(write_mac_context, temp,  tempLen);
1953 	    hashObj->update(write_mac_context, input, inputLength);
1954 	    hashObj->end(write_mac_context,    temp, &tempLen, sizeof temp);
1955 
1956 	    /* compute "outer" part of SSL3 MAC */
1957 	    hashObj->begin(write_mac_context);
1958 	    if (useServerMacKey)
1959 		hashObj->update(write_mac_context,
1960 				spec->server.write_mac_key_item.data,
1961 				spec->server.write_mac_key_item.len);
1962 	    else
1963 		hashObj->update(write_mac_context,
1964 				spec->client.write_mac_key_item.data,
1965 				spec->client.write_mac_key_item.len);
1966 	    hashObj->update(write_mac_context, mac_pad_2, pad_bytes);
1967 	    hashObj->update(write_mac_context, temp, tempLen);
1968 	    hashObj->end(write_mac_context, outbuf, outLength, spec->mac_size);
1969 	    rv = SECSuccess;
1970 	} else { /* is TLS */
1971 #define cx ((HMACContext *)write_mac_context)
1972 	    if (useServerMacKey) {
1973 		rv = HMAC_Init(cx, hashObj,
1974 			       spec->server.write_mac_key_item.data,
1975 			       spec->server.write_mac_key_item.len, PR_FALSE);
1976 	    } else {
1977 		rv = HMAC_Init(cx, hashObj,
1978 			       spec->client.write_mac_key_item.data,
1979 			       spec->client.write_mac_key_item.len, PR_FALSE);
1980 	    }
1981 	    if (rv == SECSuccess) {
1982 		HMAC_Begin(cx);
1983 		HMAC_Update(cx, temp, tempLen);
1984 		HMAC_Update(cx, input, inputLength);
1985 		rv = HMAC_Finish(cx, outbuf, outLength, spec->mac_size);
1986 		HMAC_Destroy(cx, PR_FALSE);
1987 	    }
1988 #undef cx
1989 	}
1990     }
1991 
1992     PORT_Assert(rv != SECSuccess || *outLength == (unsigned)spec->mac_size);
1993 
1994     PRINT_BUF(95, (NULL, "frag hash2: result", outbuf, *outLength));
1995 
1996     if (rv != SECSuccess) {
1997     	rv = SECFailure;
1998 	ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
1999     }
2000     return rv;
2001 }
2002 
2003 static PRBool
ssl3_ClientAuthTokenPresent(sslSessionID * sid)2004 ssl3_ClientAuthTokenPresent(sslSessionID *sid) {
2005     PK11SlotInfo *slot = NULL;
2006     PRBool isPresent = PR_TRUE;
2007 
2008     /* we only care if we are doing client auth */
2009     if (!sid || !sid->u.ssl3.clAuthValid) {
2010 	return PR_TRUE;
2011     }
2012 
2013     /* get the slot */
2014     slot = SECMOD_LookupSlot(sid->u.ssl3.clAuthModuleID,
2015 	                     sid->u.ssl3.clAuthSlotID);
2016     if (slot == NULL ||
2017 	!PK11_IsPresent(slot) ||
2018 	sid->u.ssl3.clAuthSeries     != PK11_GetSlotSeries(slot) ||
2019 	sid->u.ssl3.clAuthSlotID     != PK11_GetSlotID(slot)     ||
2020 	sid->u.ssl3.clAuthModuleID   != PK11_GetModuleID(slot)   ||
2021 	(PK11_NeedLogin(slot) && !PK11_IsLoggedIn(slot, NULL))) {
2022 	isPresent = PR_FALSE;
2023     }
2024     if (slot) {
2025 	PK11_FreeSlot(slot);
2026     }
2027     return isPresent;
2028 }
2029 
2030 static SECStatus
ssl3_CompressMACEncryptRecord(sslSocket * ss,SSL3ContentType type,const SSL3Opaque * pIn,PRUint32 contentLen)2031 ssl3_CompressMACEncryptRecord(sslSocket *        ss,
2032                               SSL3ContentType    type,
2033 		              const SSL3Opaque * pIn,
2034 		              PRUint32           contentLen)
2035 {
2036     ssl3CipherSpec *          cwSpec;
2037     const ssl3BulkCipherDef * cipher_def;
2038     sslBuffer      *          wrBuf 	  = &ss->sec.writeBuf;
2039     SECStatus                 rv;
2040     PRUint32                  macLen      = 0;
2041     PRUint32                  fragLen;
2042     PRUint32  p1Len, p2Len, oddLen = 0;
2043     PRInt32   cipherBytes =  0;
2044 
2045     ssl_GetSpecReadLock(ss);	/********************************/
2046 
2047     cwSpec = ss->ssl3.cwSpec;
2048     cipher_def = cwSpec->cipher_def;
2049 
2050     if (cwSpec->compressor) {
2051 	int outlen;
2052 	rv = cwSpec->compressor(
2053 	    cwSpec->compressContext, wrBuf->buf + SSL3_RECORD_HEADER_LENGTH,
2054 	    &outlen, wrBuf->space - SSL3_RECORD_HEADER_LENGTH, pIn, contentLen);
2055 	if (rv != SECSuccess)
2056 	    return rv;
2057 	pIn = wrBuf->buf + SSL3_RECORD_HEADER_LENGTH;
2058 	contentLen = outlen;
2059     }
2060 
2061     /*
2062      * Add the MAC
2063      */
2064     rv = ssl3_ComputeRecordMAC( cwSpec, (PRBool)(ss->sec.isServer),
2065 	type, cwSpec->version, cwSpec->write_seq_num, pIn, contentLen,
2066 	wrBuf->buf + contentLen + SSL3_RECORD_HEADER_LENGTH, &macLen);
2067     if (rv != SECSuccess) {
2068 	ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
2069 	goto spec_locked_loser;
2070     }
2071     p1Len   = contentLen;
2072     p2Len   = macLen;
2073     fragLen = contentLen + macLen;	/* needs to be encrypted */
2074     PORT_Assert(fragLen <= MAX_FRAGMENT_LENGTH + 1024);
2075 
2076     /*
2077      * Pad the text (if we're doing a block cipher)
2078      * then Encrypt it
2079      */
2080     if (cipher_def->type == type_block) {
2081 	unsigned char * pBuf;
2082 	int             padding_length;
2083 	int             i;
2084 
2085 	oddLen = contentLen % cipher_def->block_size;
2086 	/* Assume blockSize is a power of two */
2087 	padding_length = cipher_def->block_size - 1 -
2088 			((fragLen) & (cipher_def->block_size - 1));
2089 	fragLen += padding_length + 1;
2090 	PORT_Assert((fragLen % cipher_def->block_size) == 0);
2091 
2092 	/* Pad according to TLS rules (also acceptable to SSL3). */
2093 	pBuf = &wrBuf->buf[fragLen + SSL3_RECORD_HEADER_LENGTH - 1];
2094 	for (i = padding_length + 1; i > 0; --i) {
2095 	    *pBuf-- = padding_length;
2096 	}
2097 	/* now, if contentLen is not a multiple of block size, fix it */
2098 	p2Len = fragLen - p1Len;
2099     }
2100     if (p1Len < 256) {
2101 	oddLen = p1Len;
2102 	p1Len = 0;
2103     } else {
2104 	p1Len -= oddLen;
2105     }
2106     if (oddLen) {
2107 	p2Len += oddLen;
2108 	PORT_Assert( (cipher_def->block_size < 2) || \
2109 		     (p2Len % cipher_def->block_size) == 0);
2110 	memmove(wrBuf->buf + SSL3_RECORD_HEADER_LENGTH + p1Len,
2111 	        pIn + p1Len, oddLen);
2112     }
2113     if (p1Len > 0) {
2114 	rv = cwSpec->encode( cwSpec->encodeContext,
2115 	    wrBuf->buf + SSL3_RECORD_HEADER_LENGTH, /* output */
2116 	    &cipherBytes,                           /* actual outlen */
2117 	    p1Len,                                  /* max outlen */
2118 	    pIn, p1Len);                      /* input, and inputlen */
2119 	PORT_Assert(rv == SECSuccess && cipherBytes == p1Len);
2120 	if (rv != SECSuccess || cipherBytes != p1Len) {
2121 	    PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
2122 	    goto spec_locked_loser;
2123 	}
2124     }
2125     if (p2Len > 0) {
2126 	PRInt32 cipherBytesPart2 = -1;
2127 	rv = cwSpec->encode( cwSpec->encodeContext,
2128 	    wrBuf->buf + SSL3_RECORD_HEADER_LENGTH + p1Len,
2129 	    &cipherBytesPart2,          /* output and actual outLen */
2130 	    p2Len,                             /* max outlen */
2131 	    wrBuf->buf + SSL3_RECORD_HEADER_LENGTH + p1Len,
2132 	    p2Len);                            /* input and inputLen*/
2133 	PORT_Assert(rv == SECSuccess && cipherBytesPart2 == p2Len);
2134 	if (rv != SECSuccess || cipherBytesPart2 != p2Len) {
2135 	    PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
2136 	    goto spec_locked_loser;
2137 	}
2138 	cipherBytes += cipherBytesPart2;
2139     }
2140     PORT_Assert(cipherBytes <= MAX_FRAGMENT_LENGTH + 1024);
2141 
2142     ssl3_BumpSequenceNumber(&cwSpec->write_seq_num);
2143 
2144     wrBuf->len    = cipherBytes + SSL3_RECORD_HEADER_LENGTH;
2145     wrBuf->buf[0] = type;
2146     wrBuf->buf[1] = MSB(cwSpec->version);
2147     wrBuf->buf[2] = LSB(cwSpec->version);
2148     wrBuf->buf[3] = MSB(cipherBytes);
2149     wrBuf->buf[4] = LSB(cipherBytes);
2150 
2151     ssl_ReleaseSpecReadLock(ss); /************************************/
2152 
2153     return SECSuccess;
2154 
2155 spec_locked_loser:
2156     ssl_ReleaseSpecReadLock(ss);
2157     return SECFailure;
2158 }
2159 
2160 /* Process the plain text before sending it.
2161  * Returns the number of bytes of plaintext that were successfully sent
2162  * 	plus the number of bytes of plaintext that were copied into the
2163  *	output (write) buffer.
2164  * Returns SECFailure on a hard IO error, memory error, or crypto error.
2165  * Does NOT return SECWouldBlock.
2166  *
2167  * Notes on the use of the private ssl flags:
2168  * (no private SSL flags)
2169  *    Attempt to make and send SSL records for all plaintext
2170  *    If non-blocking and a send gets WOULD_BLOCK,
2171  *    or if the pending (ciphertext) buffer is not empty,
2172  *    then buffer remaining bytes of ciphertext into pending buf,
2173  *    and continue to do that for all succssive records until all
2174  *    bytes are used.
2175  * ssl_SEND_FLAG_FORCE_INTO_BUFFER
2176  *    As above, except this suppresses all write attempts, and forces
2177  *    all ciphertext into the pending ciphertext buffer.
2178  *
2179  */
2180 static PRInt32
ssl3_SendRecord(sslSocket * ss,SSL3ContentType type,const SSL3Opaque * pIn,PRInt32 nIn,PRInt32 flags)2181 ssl3_SendRecord(   sslSocket *        ss,
2182                    SSL3ContentType    type,
2183 		   const SSL3Opaque * pIn,   /* input buffer */
2184 		   PRInt32            nIn,   /* bytes of input */
2185 		   PRInt32            flags)
2186 {
2187     sslBuffer      *          wrBuf 	  = &ss->sec.writeBuf;
2188     SECStatus                 rv;
2189     PRInt32                   totalSent   = 0;
2190 
2191     SSL_TRC(3, ("%d: SSL3[%d] SendRecord type: %s nIn=%d",
2192 		SSL_GETPID(), ss->fd, ssl3_DecodeContentType(type),
2193 		nIn));
2194     PRINT_BUF(3, (ss, "Send record (plain text)", pIn, nIn));
2195 
2196     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
2197 
2198     if (ss->ssl3.initialized == PR_FALSE) {
2199 	/* This can happen on a server if the very first incoming record
2200 	** looks like a defective ssl3 record (e.g. too long), and we're
2201 	** trying to send an alert.
2202 	*/
2203 	PR_ASSERT(type == content_alert);
2204 	rv = ssl3_InitState(ss);
2205 	if (rv != SECSuccess) {
2206 	    return SECFailure;	/* ssl3_InitState has set the error code. */
2207     	}
2208     }
2209 
2210     /* check for Token Presence */
2211     if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) {
2212 	PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
2213 	return SECFailure;
2214     }
2215 
2216     while (nIn > 0) {
2217 	PRUint32  contentLen = PR_MIN(nIn, MAX_FRAGMENT_LENGTH);
2218 
2219 	if (wrBuf->space < contentLen + SSL3_BUFFER_FUDGE) {
2220 	    PRInt32 newSpace = PR_MAX(wrBuf->space * 2, contentLen);
2221 	    newSpace = PR_MIN(newSpace, MAX_FRAGMENT_LENGTH);
2222 	    newSpace += SSL3_BUFFER_FUDGE;
2223 	    rv = sslBuffer_Grow(wrBuf, newSpace);
2224 	    if (rv != SECSuccess) {
2225 		SSL_DBG(("%d: SSL3[%d]: SendRecord, tried to get %d bytes",
2226 			 SSL_GETPID(), ss->fd, newSpace));
2227 		return SECFailure; /* sslBuffer_Grow set a memory error code. */
2228 	    }
2229 	}
2230 
2231 	rv = ssl3_CompressMACEncryptRecord( ss, type, pIn, contentLen);
2232 	if (rv != SECSuccess)
2233 	    return SECFailure;
2234 
2235 	pIn += contentLen;
2236 	nIn -= contentLen;
2237 	PORT_Assert( nIn >= 0 );
2238 
2239 	PRINT_BUF(50, (ss, "send (encrypted) record data:", wrBuf->buf, wrBuf->len));
2240 
2241 	/* If there's still some previously saved ciphertext,
2242 	 * or the caller doesn't want us to send the data yet,
2243 	 * then add all our new ciphertext to the amount previously saved.
2244 	 */
2245 	if ((ss->pendingBuf.len > 0) ||
2246 	    (flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) {
2247 
2248 	    rv = ssl_SaveWriteData(ss, wrBuf->buf, wrBuf->len);
2249 	    if (rv != SECSuccess) {
2250 		/* presumably a memory error, SEC_ERROR_NO_MEMORY */
2251 		return SECFailure;
2252 	    }
2253 	    wrBuf->len = 0;	/* All cipher text is saved away. */
2254 
2255 	    if (!(flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) {
2256 		PRInt32   sent;
2257 		ss->handshakeBegun = 1;
2258 		sent = ssl_SendSavedWriteData(ss);
2259 		if (sent < 0 && PR_GetError() != PR_WOULD_BLOCK_ERROR) {
2260 		    ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE);
2261 		    return SECFailure;
2262 		}
2263 		if (ss->pendingBuf.len) {
2264 		    flags |= ssl_SEND_FLAG_FORCE_INTO_BUFFER;
2265 		}
2266 	    }
2267 	} else if (wrBuf->len > 0) {
2268 	    PRInt32   sent;
2269 	    ss->handshakeBegun = 1;
2270 	    sent = ssl_DefSend(ss, wrBuf->buf, wrBuf->len,
2271 			       flags & ~ssl_SEND_FLAG_MASK);
2272 	    if (sent < 0) {
2273 		if (PR_GetError() != PR_WOULD_BLOCK_ERROR) {
2274 		    ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE);
2275 		    return SECFailure;
2276 		}
2277 		/* we got PR_WOULD_BLOCK_ERROR, which means none was sent. */
2278 		sent = 0;
2279 	    }
2280 	    wrBuf->len -= sent;
2281 	    if (wrBuf->len) {
2282 		/* now take all the remaining unsent new ciphertext and
2283 		 * append it to the buffer of previously unsent ciphertext.
2284 		 */
2285 		rv = ssl_SaveWriteData(ss, wrBuf->buf + sent, wrBuf->len);
2286 		if (rv != SECSuccess) {
2287 		    /* presumably a memory error, SEC_ERROR_NO_MEMORY */
2288 		    return SECFailure;
2289 		}
2290 	    }
2291 	}
2292 	totalSent += contentLen;
2293     }
2294     return totalSent;
2295 }
2296 
2297 #define SSL3_PENDING_HIGH_WATER 1024
2298 
2299 /* Attempt to send the content of "in" in an SSL application_data record.
2300  * Returns "len" or SECFailure,   never SECWouldBlock, nor SECSuccess.
2301  */
2302 int
ssl3_SendApplicationData(sslSocket * ss,const unsigned char * in,PRInt32 len,PRInt32 flags)2303 ssl3_SendApplicationData(sslSocket *ss, const unsigned char *in,
2304 			 PRInt32 len, PRInt32 flags)
2305 {
2306     PRInt32   totalSent	= 0;
2307     PRInt32   discarded = 0;
2308 
2309     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
2310     if (len < 0 || !in) {
2311 	PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
2312 	return SECFailure;
2313     }
2314 
2315     if (ss->pendingBuf.len > SSL3_PENDING_HIGH_WATER &&
2316         !ssl_SocketIsBlocking(ss)) {
2317 	PORT_Assert(!ssl_SocketIsBlocking(ss));
2318 	PORT_SetError(PR_WOULD_BLOCK_ERROR);
2319 	return SECFailure;
2320     }
2321 
2322     if (ss->appDataBuffered && len) {
2323 	PORT_Assert (in[0] == (unsigned char)(ss->appDataBuffered));
2324 	if (in[0] != (unsigned char)(ss->appDataBuffered)) {
2325 	    PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
2326 	    return SECFailure;
2327 	}
2328     	in++;
2329 	len--;
2330 	discarded = 1;
2331     }
2332     while (len > totalSent) {
2333 	PRInt32   sent, toSend;
2334 
2335 	if (totalSent > 0) {
2336 	    /*
2337 	     * The thread yield is intended to give the reader thread a
2338 	     * chance to get some cycles while the writer thread is in
2339 	     * the middle of a large application data write.  (See
2340 	     * Bugzilla bug 127740, comment #1.)
2341 	     */
2342 	    ssl_ReleaseXmitBufLock(ss);
2343 	    PR_Sleep(PR_INTERVAL_NO_WAIT);	/* PR_Yield(); */
2344 	    ssl_GetXmitBufLock(ss);
2345 	}
2346 	toSend = PR_MIN(len - totalSent, MAX_FRAGMENT_LENGTH);
2347 	sent = ssl3_SendRecord(ss, content_application_data,
2348 	                       in + totalSent, toSend, flags);
2349 	if (sent < 0) {
2350 	    if (totalSent > 0 && PR_GetError() == PR_WOULD_BLOCK_ERROR) {
2351 		PORT_Assert(ss->lastWriteBlocked);
2352 	    	break;
2353 	    }
2354 	    return SECFailure; /* error code set by ssl3_SendRecord */
2355 	}
2356 	totalSent += sent;
2357 	if (ss->pendingBuf.len) {
2358 	    /* must be a non-blocking socket */
2359 	    PORT_Assert(!ssl_SocketIsBlocking(ss));
2360 	    PORT_Assert(ss->lastWriteBlocked);
2361 	    break;
2362 	}
2363     }
2364     if (ss->pendingBuf.len) {
2365 	/* Must be non-blocking. */
2366 	PORT_Assert(!ssl_SocketIsBlocking(ss));
2367 	if (totalSent > 0) {
2368 	    ss->appDataBuffered = 0x100 | in[totalSent - 1];
2369 	}
2370 
2371 	totalSent = totalSent + discarded - 1;
2372 	if (totalSent <= 0) {
2373 	    PORT_SetError(PR_WOULD_BLOCK_ERROR);
2374 	    totalSent = SECFailure;
2375 	}
2376 	return totalSent;
2377     }
2378     ss->appDataBuffered = 0;
2379     return totalSent + discarded;
2380 }
2381 
2382 /* Attempt to send the content of sendBuf buffer in an SSL handshake record.
2383  * This function returns SECSuccess or SECFailure, never SECWouldBlock.
2384  * Always set sendBuf.len to 0, even when returning SECFailure.
2385  *
2386  * Called from SSL3_SendAlert(), ssl3_SendChangeCipherSpecs(),
2387  *             ssl3_AppendHandshake(), ssl3_SendClientHello(),
2388  *             ssl3_SendHelloRequest(), ssl3_SendServerHelloDone(),
2389  *             ssl3_SendFinished(),
2390  */
2391 static SECStatus
ssl3_FlushHandshake(sslSocket * ss,PRInt32 flags)2392 ssl3_FlushHandshake(sslSocket *ss, PRInt32 flags)
2393 {
2394     PRInt32 rv = SECSuccess;
2395 
2396     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
2397     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
2398 
2399     if (!ss->sec.ci.sendBuf.buf || !ss->sec.ci.sendBuf.len)
2400 	return rv;
2401 
2402     /* only this flag is allowed */
2403     PORT_Assert(!(flags & ~ssl_SEND_FLAG_FORCE_INTO_BUFFER));
2404     if ((flags & ~ssl_SEND_FLAG_FORCE_INTO_BUFFER) != 0) {
2405 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
2406 	rv = SECFailure;
2407     } else {
2408 	rv = ssl3_SendRecord(ss, content_handshake, ss->sec.ci.sendBuf.buf,
2409 			     ss->sec.ci.sendBuf.len, flags);
2410     }
2411     if (rv < 0) {
2412     	int err = PORT_GetError();
2413 	PORT_Assert(err != PR_WOULD_BLOCK_ERROR);
2414 	if (err == PR_WOULD_BLOCK_ERROR) {
2415 	    PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2416 	}
2417     } else if (rv < ss->sec.ci.sendBuf.len) {
2418     	/* short write should never happen */
2419 	PORT_Assert(rv >= ss->sec.ci.sendBuf.len);
2420 	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2421 	rv = SECFailure;
2422     } else {
2423 	rv = SECSuccess;
2424     }
2425 
2426     /* Whether we succeeded or failed, toss the old handshake data. */
2427     ss->sec.ci.sendBuf.len = 0;
2428     return rv;
2429 }
2430 
2431 /*
2432  * Called from ssl3_HandleAlert and from ssl3_HandleCertificate when
2433  * the remote client sends a negative response to our certificate request.
2434  * Returns SECFailure if the application has required client auth.
2435  *         SECSuccess otherwise.
2436  */
2437 static SECStatus
ssl3_HandleNoCertificate(sslSocket * ss)2438 ssl3_HandleNoCertificate(sslSocket *ss)
2439 {
2440     if (ss->sec.peerCert != NULL) {
2441 	if (ss->sec.peerKey != NULL) {
2442 	    SECKEY_DestroyPublicKey(ss->sec.peerKey);
2443 	    ss->sec.peerKey = NULL;
2444 	}
2445 	CERT_DestroyCertificate(ss->sec.peerCert);
2446 	ss->sec.peerCert = NULL;
2447     }
2448     ssl3_CleanupPeerCerts(ss);
2449 
2450     /* If the server has required client-auth blindly but doesn't
2451      * actually look at the certificate it won't know that no
2452      * certificate was presented so we shutdown the socket to ensure
2453      * an error.  We only do this if we haven't already completed the
2454      * first handshake because if we're redoing the handshake we
2455      * know the server is paying attention to the certificate.
2456      */
2457     if ((ss->opt.requireCertificate == SSL_REQUIRE_ALWAYS) ||
2458 	(!ss->firstHsDone &&
2459 	 (ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE))) {
2460 	PRFileDesc * lower;
2461 
2462 	ss->sec.uncache(ss->sec.ci.sid);
2463 	SSL3_SendAlert(ss, alert_fatal, bad_certificate);
2464 
2465 	lower = ss->fd->lower;
2466 #ifdef _WIN32
2467 	lower->methods->shutdown(lower, PR_SHUTDOWN_SEND);
2468 #else
2469 	lower->methods->shutdown(lower, PR_SHUTDOWN_BOTH);
2470 #endif
2471 	PORT_SetError(SSL_ERROR_NO_CERTIFICATE);
2472 	return SECFailure;
2473     }
2474     return SECSuccess;
2475 }
2476 
2477 /************************************************************************
2478  * Alerts
2479  */
2480 
2481 /*
2482 ** Acquires both handshake and XmitBuf locks.
2483 ** Called from: ssl3_IllegalParameter	<-
2484 **              ssl3_HandshakeFailure	<-
2485 **              ssl3_HandleAlert	<- ssl3_HandleRecord.
2486 **              ssl3_HandleChangeCipherSpecs <- ssl3_HandleRecord
2487 **              ssl3_ConsumeHandshakeVariable <-
2488 **              ssl3_HandleHelloRequest	<-
2489 **              ssl3_HandleServerHello	<-
2490 **              ssl3_HandleServerKeyExchange <-
2491 **              ssl3_HandleCertificateRequest <-
2492 **              ssl3_HandleServerHelloDone <-
2493 **              ssl3_HandleClientHello	<-
2494 **              ssl3_HandleV2ClientHello <-
2495 **              ssl3_HandleCertificateVerify <-
2496 **              ssl3_HandleClientKeyExchange <-
2497 **              ssl3_HandleCertificate	<-
2498 **              ssl3_HandleFinished	<-
2499 **              ssl3_HandleHandshakeMessage <-
2500 **              ssl3_HandleRecord	<-
2501 **
2502 */
2503 SECStatus
SSL3_SendAlert(sslSocket * ss,SSL3AlertLevel level,SSL3AlertDescription desc)2504 SSL3_SendAlert(sslSocket *ss, SSL3AlertLevel level, SSL3AlertDescription desc)
2505 {
2506     uint8 	bytes[2];
2507     SECStatus	rv;
2508 
2509     SSL_TRC(3, ("%d: SSL3[%d]: send alert record, level=%d desc=%d",
2510 		SSL_GETPID(), ss->fd, level, desc));
2511 
2512     bytes[0] = level;
2513     bytes[1] = desc;
2514 
2515     ssl_GetSSL3HandshakeLock(ss);
2516     if (level == alert_fatal) {
2517 	if (ss->sec.ci.sid) {
2518 	    ss->sec.uncache(ss->sec.ci.sid);
2519 	}
2520     }
2521     ssl_GetXmitBufLock(ss);
2522     rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
2523     if (rv == SECSuccess) {
2524 	PRInt32 sent;
2525 	sent = ssl3_SendRecord(ss, content_alert, bytes, 2,
2526 			       desc == no_certificate
2527 			       ? ssl_SEND_FLAG_FORCE_INTO_BUFFER : 0);
2528 	rv = (sent >= 0) ? SECSuccess : (SECStatus)sent;
2529     }
2530     ssl_ReleaseXmitBufLock(ss);
2531     ssl_ReleaseSSL3HandshakeLock(ss);
2532     return rv;	/* error set by ssl3_FlushHandshake or ssl3_SendRecord */
2533 }
2534 
2535 /*
2536  * Send illegal_parameter alert.  Set generic error number.
2537  */
2538 static SECStatus
ssl3_IllegalParameter(sslSocket * ss)2539 ssl3_IllegalParameter(sslSocket *ss)
2540 {
2541     PRBool isTLS;
2542 
2543     isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
2544     (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
2545     PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
2546                                    : SSL_ERROR_BAD_SERVER );
2547     return SECFailure;
2548 }
2549 
2550 /*
2551  * Send handshake_Failure alert.  Set generic error number.
2552  */
2553 static SECStatus
ssl3_HandshakeFailure(sslSocket * ss)2554 ssl3_HandshakeFailure(sslSocket *ss)
2555 {
2556     (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure);
2557     PORT_SetError( ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
2558                                     : SSL_ERROR_BAD_SERVER );
2559     return SECFailure;
2560 }
2561 
2562 /*
2563  * Send handshake_Failure alert.  Set generic error number.
2564  */
2565 static SECStatus
ssl3_DecodeError(sslSocket * ss)2566 ssl3_DecodeError(sslSocket *ss)
2567 {
2568     (void)SSL3_SendAlert(ss, alert_fatal,
2569 		  ss->version > SSL_LIBRARY_VERSION_3_0 ? decode_error
2570 							: illegal_parameter);
2571     PORT_SetError( ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
2572                                     : SSL_ERROR_BAD_SERVER );
2573     return SECFailure;
2574 }
2575 
2576 /* Called from ssl3_HandleRecord.
2577 ** Caller must hold both RecvBuf and Handshake locks.
2578 */
2579 static SECStatus
ssl3_HandleAlert(sslSocket * ss,sslBuffer * buf)2580 ssl3_HandleAlert(sslSocket *ss, sslBuffer *buf)
2581 {
2582     SSL3AlertLevel       level;
2583     SSL3AlertDescription desc;
2584     int                  error;
2585 
2586     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
2587     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
2588 
2589     SSL_TRC(3, ("%d: SSL3[%d]: handle alert record", SSL_GETPID(), ss->fd));
2590 
2591     if (buf->len != 2) {
2592 	(void)ssl3_DecodeError(ss);
2593 	PORT_SetError(SSL_ERROR_RX_MALFORMED_ALERT);
2594 	return SECFailure;
2595     }
2596     level = (SSL3AlertLevel)buf->buf[0];
2597     desc  = (SSL3AlertDescription)buf->buf[1];
2598     buf->len = 0;
2599     SSL_TRC(5, ("%d: SSL3[%d] received alert, level = %d, description = %d",
2600         SSL_GETPID(), ss->fd, level, desc));
2601 
2602     switch (desc) {
2603     case close_notify:		ss->recvdCloseNotify = 1;
2604 		        	error = SSL_ERROR_CLOSE_NOTIFY_ALERT;     break;
2605     case unexpected_message: 	error = SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT;
2606 									  break;
2607     case bad_record_mac: 	error = SSL_ERROR_BAD_MAC_ALERT; 	  break;
2608     case decryption_failed: 	error = SSL_ERROR_DECRYPTION_FAILED_ALERT;
2609     									  break;
2610     case record_overflow: 	error = SSL_ERROR_RECORD_OVERFLOW_ALERT;  break;
2611     case decompression_failure: error = SSL_ERROR_DECOMPRESSION_FAILURE_ALERT;
2612 									  break;
2613     case handshake_failure: 	error = SSL_ERROR_HANDSHAKE_FAILURE_ALERT;
2614 			        					  break;
2615     case no_certificate: 	error = SSL_ERROR_NO_CERTIFICATE;	  break;
2616     case bad_certificate: 	error = SSL_ERROR_BAD_CERT_ALERT; 	  break;
2617     case unsupported_certificate:error = SSL_ERROR_UNSUPPORTED_CERT_ALERT;break;
2618     case certificate_revoked: 	error = SSL_ERROR_REVOKED_CERT_ALERT; 	  break;
2619     case certificate_expired: 	error = SSL_ERROR_EXPIRED_CERT_ALERT; 	  break;
2620     case certificate_unknown: 	error = SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT;
2621 			        					  break;
2622     case illegal_parameter: 	error = SSL_ERROR_ILLEGAL_PARAMETER_ALERT;break;
2623 
2624     /* All alerts below are TLS only. */
2625     case unknown_ca: 		error = SSL_ERROR_UNKNOWN_CA_ALERT;       break;
2626     case access_denied: 	error = SSL_ERROR_ACCESS_DENIED_ALERT;    break;
2627     case decode_error: 		error = SSL_ERROR_DECODE_ERROR_ALERT;     break;
2628     case decrypt_error: 	error = SSL_ERROR_DECRYPT_ERROR_ALERT;    break;
2629     case export_restriction: 	error = SSL_ERROR_EXPORT_RESTRICTION_ALERT;
2630     									  break;
2631     case protocol_version: 	error = SSL_ERROR_PROTOCOL_VERSION_ALERT; break;
2632     case insufficient_security: error = SSL_ERROR_INSUFFICIENT_SECURITY_ALERT;
2633     									  break;
2634     case internal_error: 	error = SSL_ERROR_INTERNAL_ERROR_ALERT;   break;
2635     case user_canceled: 	error = SSL_ERROR_USER_CANCELED_ALERT;    break;
2636     case no_renegotiation: 	error = SSL_ERROR_NO_RENEGOTIATION_ALERT; break;
2637 
2638     /* Alerts for TLS client hello extensions */
2639     case unsupported_extension:
2640 			error = SSL_ERROR_UNSUPPORTED_EXTENSION_ALERT;    break;
2641     case certificate_unobtainable:
2642 			error = SSL_ERROR_CERTIFICATE_UNOBTAINABLE_ALERT; break;
2643     case unrecognized_name:
2644 			error = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;        break;
2645     case bad_certificate_status_response:
2646 			error = SSL_ERROR_BAD_CERT_STATUS_RESPONSE_ALERT; break;
2647     case bad_certificate_hash_value:
2648 			error = SSL_ERROR_BAD_CERT_HASH_VALUE_ALERT;      break;
2649     default: 		error = SSL_ERROR_RX_UNKNOWN_ALERT;               break;
2650     }
2651     if (level == alert_fatal) {
2652 	ss->sec.uncache(ss->sec.ci.sid);
2653 	if ((ss->ssl3.hs.ws == wait_server_hello) &&
2654 	    (desc == handshake_failure)) {
2655 	    /* XXX This is a hack.  We're assuming that any handshake failure
2656 	     * XXX on the client hello is a failure to match ciphers.
2657 	     */
2658 	    error = SSL_ERROR_NO_CYPHER_OVERLAP;
2659 	}
2660 	PORT_SetError(error);
2661 	return SECFailure;
2662     }
2663     if ((desc == no_certificate) && (ss->ssl3.hs.ws == wait_client_cert)) {
2664     	/* I'm a server. I've requested a client cert. He hasn't got one. */
2665 	SECStatus rv;
2666 
2667 	PORT_Assert(ss->sec.isServer);
2668 	ss->ssl3.hs.ws = wait_client_key;
2669 	rv = ssl3_HandleNoCertificate(ss);
2670 	return rv;
2671     }
2672     return SECSuccess;
2673 }
2674 
2675 /*
2676  * Change Cipher Specs
2677  * Called from ssl3_HandleServerHelloDone,
2678  *             ssl3_HandleClientHello,
2679  * and         ssl3_HandleFinished
2680  *
2681  * Acquires and releases spec write lock, to protect switching the current
2682  * and pending write spec pointers.
2683  */
2684 
2685 static SECStatus
ssl3_SendChangeCipherSpecs(sslSocket * ss)2686 ssl3_SendChangeCipherSpecs(sslSocket *ss)
2687 {
2688     uint8             change = change_cipher_spec_choice;
2689     ssl3CipherSpec *  pwSpec;
2690     SECStatus         rv;
2691     PRInt32           sent;
2692 
2693     SSL_TRC(3, ("%d: SSL3[%d]: send change_cipher_spec record",
2694 		SSL_GETPID(), ss->fd));
2695 
2696     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
2697     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
2698 
2699     rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
2700     if (rv != SECSuccess) {
2701 	return rv;	/* error code set by ssl3_FlushHandshake */
2702     }
2703     sent = ssl3_SendRecord(ss, content_change_cipher_spec, &change, 1,
2704                               ssl_SEND_FLAG_FORCE_INTO_BUFFER);
2705     if (sent < 0) {
2706 	return (SECStatus)sent;	/* error code set by ssl3_SendRecord */
2707     }
2708 
2709     /* swap the pending and current write specs. */
2710     ssl_GetSpecWriteLock(ss);	/**************************************/
2711     pwSpec                     = ss->ssl3.pwSpec;
2712     pwSpec->write_seq_num.high = 0;
2713     pwSpec->write_seq_num.low  = 0;
2714 
2715     ss->ssl3.pwSpec = ss->ssl3.cwSpec;
2716     ss->ssl3.cwSpec = pwSpec;
2717 
2718     SSL_TRC(3, ("%d: SSL3[%d] Set Current Write Cipher Suite to Pending",
2719 		SSL_GETPID(), ss->fd ));
2720 
2721     /* We need to free up the contexts, keys and certs ! */
2722     /* If we are really through with the old cipher spec
2723      * (Both the read and write sides have changed) destroy it.
2724      */
2725     if (ss->ssl3.prSpec == ss->ssl3.pwSpec) {
2726     	ssl3_DestroyCipherSpec(ss->ssl3.pwSpec);
2727     }
2728     ssl_ReleaseSpecWriteLock(ss); /**************************************/
2729 
2730     return SECSuccess;
2731 }
2732 
2733 /* Called from ssl3_HandleRecord.
2734 ** Caller must hold both RecvBuf and Handshake locks.
2735  *
2736  * Acquires and releases spec write lock, to protect switching the current
2737  * and pending write spec pointers.
2738 */
2739 static SECStatus
ssl3_HandleChangeCipherSpecs(sslSocket * ss,sslBuffer * buf)2740 ssl3_HandleChangeCipherSpecs(sslSocket *ss, sslBuffer *buf)
2741 {
2742     ssl3CipherSpec *           prSpec;
2743     SSL3WaitState              ws      = ss->ssl3.hs.ws;
2744     SSL3ChangeCipherSpecChoice change;
2745 
2746     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
2747     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
2748 
2749     SSL_TRC(3, ("%d: SSL3[%d]: handle change_cipher_spec record",
2750 		SSL_GETPID(), ss->fd));
2751 
2752     if (ws != wait_change_cipher) {
2753 	(void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
2754 	PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER);
2755 	return SECFailure;
2756     }
2757 
2758     if(buf->len != 1) {
2759 	(void)ssl3_DecodeError(ss);
2760 	PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER);
2761 	return SECFailure;
2762     }
2763     change = (SSL3ChangeCipherSpecChoice)buf->buf[0];
2764     if (change != change_cipher_spec_choice) {
2765 	/* illegal_parameter is correct here for both SSL3 and TLS. */
2766 	(void)ssl3_IllegalParameter(ss);
2767 	PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER);
2768 	return SECFailure;
2769     }
2770     buf->len = 0;
2771 
2772     /* Swap the pending and current read specs. */
2773     ssl_GetSpecWriteLock(ss);   /*************************************/
2774     prSpec                    = ss->ssl3.prSpec;
2775     prSpec->read_seq_num.high = prSpec->read_seq_num.low = 0;
2776 
2777     ss->ssl3.prSpec  = ss->ssl3.crSpec;
2778     ss->ssl3.crSpec  = prSpec;
2779     ss->ssl3.hs.ws   = wait_finished;
2780 
2781     SSL_TRC(3, ("%d: SSL3[%d] Set Current Read Cipher Suite to Pending",
2782 		SSL_GETPID(), ss->fd ));
2783 
2784     /* If we are really through with the old cipher prSpec
2785      * (Both the read and write sides have changed) destroy it.
2786      */
2787     if (ss->ssl3.prSpec == ss->ssl3.pwSpec) {
2788     	ssl3_DestroyCipherSpec(ss->ssl3.prSpec);
2789     }
2790     ssl_ReleaseSpecWriteLock(ss);   /*************************************/
2791     return SECSuccess;
2792 }
2793 
2794 /* This method uses PKCS11 to derive the MS from the PMS, where PMS
2795 ** is a PKCS11 symkey. This is used in all cases except the
2796 ** "triple bypass" with RSA key exchange.
2797 ** Called from ssl3_InitPendingCipherSpec.   prSpec is pwSpec.
2798 */
2799 static SECStatus
ssl3_DeriveMasterSecret(sslSocket * ss,PK11SymKey * pms)2800 ssl3_DeriveMasterSecret(sslSocket *ss, PK11SymKey *pms)
2801 {
2802     ssl3CipherSpec *  pwSpec = ss->ssl3.pwSpec;
2803     const ssl3KEADef *kea_def= ss->ssl3.hs.kea_def;
2804     unsigned char *   cr     = (unsigned char *)&ss->ssl3.hs.client_random;
2805     unsigned char *   sr     = (unsigned char *)&ss->ssl3.hs.server_random;
2806     PRBool            isTLS  = (PRBool)(kea_def->tls_keygen ||
2807                                 (pwSpec->version > SSL_LIBRARY_VERSION_3_0));
2808     /*
2809      * Whenever isDH is true, we need to use CKM_TLS_MASTER_KEY_DERIVE_DH
2810      * which, unlike CKM_TLS_MASTER_KEY_DERIVE, converts arbitrary size
2811      * data into a 48-byte value.
2812      */
2813     PRBool    isDH = (PRBool) ((ss->ssl3.hs.kea_def->exchKeyType == kt_dh) ||
2814 	                       (ss->ssl3.hs.kea_def->exchKeyType == kt_ecdh));
2815     SECStatus         rv = SECFailure;
2816     CK_MECHANISM_TYPE master_derive;
2817     CK_MECHANISM_TYPE key_derive;
2818     SECItem           params;
2819     CK_FLAGS          keyFlags;
2820     CK_VERSION        pms_version;
2821     CK_SSL3_MASTER_KEY_DERIVE_PARAMS master_params;
2822 
2823     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
2824     PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
2825     PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
2826     if (isTLS) {
2827 	if(isDH) master_derive = CKM_TLS_MASTER_KEY_DERIVE_DH;
2828 	else master_derive = CKM_TLS_MASTER_KEY_DERIVE;
2829 	key_derive    = CKM_TLS_KEY_AND_MAC_DERIVE;
2830 	keyFlags      = CKF_SIGN | CKF_VERIFY;
2831     } else {
2832 	if (isDH) master_derive = CKM_SSL3_MASTER_KEY_DERIVE_DH;
2833 	else master_derive = CKM_SSL3_MASTER_KEY_DERIVE;
2834 	key_derive    = CKM_SSL3_KEY_AND_MAC_DERIVE;
2835 	keyFlags      = 0;
2836     }
2837 
2838     if (pms || !pwSpec->master_secret) {
2839 	master_params.pVersion                     = &pms_version;
2840 	master_params.RandomInfo.pClientRandom     = cr;
2841 	master_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH;
2842 	master_params.RandomInfo.pServerRandom     = sr;
2843 	master_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH;
2844 
2845 	params.data = (unsigned char *) &master_params;
2846 	params.len  = sizeof master_params;
2847     }
2848 
2849     if (pms != NULL) {
2850 #if defined(TRACE)
2851 	if (ssl_trace >= 100) {
2852 	    SECStatus extractRV = PK11_ExtractKeyValue(pms);
2853 	    if (extractRV == SECSuccess) {
2854 		SECItem * keyData = PK11_GetKeyData(pms);
2855 		if (keyData && keyData->data && keyData->len) {
2856 		    ssl_PrintBuf(ss, "Pre-Master Secret",
2857 				 keyData->data, keyData->len);
2858 		}
2859 	    }
2860 	}
2861 #endif
2862 	pwSpec->master_secret = PK11_DeriveWithFlags(pms, master_derive,
2863 				&params, key_derive, CKA_DERIVE, 0, keyFlags);
2864 	if (!isDH && pwSpec->master_secret && ss->opt.detectRollBack) {
2865 	    SSL3ProtocolVersion client_version;
2866 	    client_version = pms_version.major << 8 | pms_version.minor;
2867 	    if (client_version != ss->clientHelloVersion) {
2868 		/* Destroy it.  Version roll-back detected. */
2869 		PK11_FreeSymKey(pwSpec->master_secret);
2870 	    	pwSpec->master_secret = NULL;
2871 	    }
2872 	}
2873 	if (pwSpec->master_secret == NULL) {
2874 	    /* Generate a faux master secret in the same slot as the old one. */
2875 	    PK11SlotInfo * slot = PK11_GetSlotFromKey((PK11SymKey *)pms);
2876 	    PK11SymKey *   fpms = ssl3_GenerateRSAPMS(ss, pwSpec, slot);
2877 
2878 	    PK11_FreeSlot(slot);
2879 	    if (fpms != NULL) {
2880 		pwSpec->master_secret = PK11_DeriveWithFlags(fpms,
2881 					master_derive, &params, key_derive,
2882 					CKA_DERIVE, 0, keyFlags);
2883 		PK11_FreeSymKey(fpms);
2884 	    }
2885 	}
2886     }
2887     if (pwSpec->master_secret == NULL) {
2888 	/* Generate a faux master secret from the internal slot. */
2889 	PK11SlotInfo *  slot = PK11_GetInternalSlot();
2890 	PK11SymKey *    fpms = ssl3_GenerateRSAPMS(ss, pwSpec, slot);
2891 
2892 	PK11_FreeSlot(slot);
2893 	if (fpms != NULL) {
2894 	    pwSpec->master_secret = PK11_DeriveWithFlags(fpms,
2895 					master_derive, &params, key_derive,
2896 					CKA_DERIVE, 0, keyFlags);
2897 	    if (pwSpec->master_secret == NULL) {
2898 	    	pwSpec->master_secret = fpms; /* use the fpms as the master. */
2899 		fpms = NULL;
2900 	    }
2901 	}
2902 	if (fpms) {
2903 	    PK11_FreeSymKey(fpms);
2904     	}
2905     }
2906     if (pwSpec->master_secret == NULL) {
2907 	ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
2908 	return rv;
2909     }
2910     if (ss->opt.bypassPKCS11) {
2911 	SECItem * keydata;
2912 	/* In hope of doing a "double bypass",
2913 	 * need to extract the master secret's value from the key object
2914 	 * and store it raw in the sslSocket struct.
2915 	 */
2916 	rv = PK11_ExtractKeyValue(pwSpec->master_secret);
2917 	if (rv != SECSuccess) {
2918 #if defined(NSS_SURVIVE_DOUBLE_BYPASS_FAILURE)
2919 	    /* The double bypass failed.
2920 	     * Attempt to revert to an all PKCS#11, non-bypass method.
2921 	     * Do we need any unacquired locks here?
2922 	     */
2923 	    ss->opt.bypassPKCS11 = 0;
2924 	    rv = ssl3_NewHandshakeHashes(ss);
2925 	    if (rv == SECSuccess) {
2926 		rv = ssl3_UpdateHandshakeHashes(ss, ss->ssl3.hs.messages.buf,
2927 		                                    ss->ssl3.hs.messages.len);
2928 	    }
2929 #endif
2930 	    return rv;
2931 	}
2932 	/* This returns the address of the secItem inside the key struct,
2933 	 * not a copy or a reference.  So, there's no need to free it.
2934 	 */
2935 	keydata = PK11_GetKeyData(pwSpec->master_secret);
2936 	if (keydata && keydata->len <= sizeof pwSpec->raw_master_secret) {
2937 	    memcpy(pwSpec->raw_master_secret, keydata->data, keydata->len);
2938 	    pwSpec->msItem.data = pwSpec->raw_master_secret;
2939 	    pwSpec->msItem.len  = keydata->len;
2940 	} else {
2941 	    PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2942 	    return SECFailure;
2943 	}
2944     }
2945     return SECSuccess;
2946 }
2947 
2948 
2949 /*
2950  * Derive encryption and MAC Keys (and IVs) from master secret
2951  * Sets a useful error code when returning SECFailure.
2952  *
2953  * Called only from ssl3_InitPendingCipherSpec(),
2954  * which in turn is called from
2955  *              sendRSAClientKeyExchange        (for Full handshake)
2956  *              sendDHClientKeyExchange         (for Full handshake)
2957  *              ssl3_HandleClientKeyExchange    (for Full handshake)
2958  *              ssl3_HandleServerHello          (for session restart)
2959  *              ssl3_HandleClientHello          (for session restart)
2960  * Caller MUST hold the specWriteLock, and SSL3HandshakeLock.
2961  * ssl3_InitPendingCipherSpec does that.
2962  *
2963  */
2964 static SECStatus
ssl3_DeriveConnectionKeysPKCS11(sslSocket * ss)2965 ssl3_DeriveConnectionKeysPKCS11(sslSocket *ss)
2966 {
2967     ssl3CipherSpec *         pwSpec     = ss->ssl3.pwSpec;
2968     const ssl3KEADef *       kea_def    = ss->ssl3.hs.kea_def;
2969     unsigned char *   cr     = (unsigned char *)&ss->ssl3.hs.client_random;
2970     unsigned char *   sr     = (unsigned char *)&ss->ssl3.hs.server_random;
2971     PRBool            isTLS  = (PRBool)(kea_def->tls_keygen ||
2972                                 (pwSpec->version > SSL_LIBRARY_VERSION_3_0));
2973     /* following variables used in PKCS11 path */
2974     const ssl3BulkCipherDef *cipher_def = pwSpec->cipher_def;
2975     PK11SlotInfo *         slot   = NULL;
2976     PK11SymKey *           symKey = NULL;
2977     void *                 pwArg  = ss->pkcs11PinArg;
2978     int                    keySize;
2979     CK_SSL3_KEY_MAT_PARAMS key_material_params;
2980     CK_SSL3_KEY_MAT_OUT    returnedKeys;
2981     CK_MECHANISM_TYPE      key_derive;
2982     CK_MECHANISM_TYPE      bulk_mechanism;
2983     SSLCipherAlgorithm     calg;
2984     SECItem                params;
2985     PRBool         skipKeysAndIVs = (PRBool)(cipher_def->calg == calg_null);
2986 
2987     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
2988     PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
2989     PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
2990 
2991     if (!pwSpec->master_secret) {
2992 	PORT_SetError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
2993 	return SECFailure;
2994     }
2995     /*
2996      * generate the key material
2997      */
2998     key_material_params.ulMacSizeInBits = pwSpec->mac_size           * BPB;
2999     key_material_params.ulKeySizeInBits = cipher_def->secret_key_size* BPB;
3000     key_material_params.ulIVSizeInBits  = cipher_def->iv_size        * BPB;
3001 
3002     key_material_params.bIsExport = (CK_BBOOL)(kea_def->is_limited);
3003     /* was:	(CK_BBOOL)(cipher_def->keygen_mode != kg_strong); */
3004 
3005     key_material_params.RandomInfo.pClientRandom     = cr;
3006     key_material_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH;
3007     key_material_params.RandomInfo.pServerRandom     = sr;
3008     key_material_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH;
3009     key_material_params.pReturnedKeyMaterial         = &returnedKeys;
3010 
3011     returnedKeys.pIVClient = pwSpec->client.write_iv;
3012     returnedKeys.pIVServer = pwSpec->server.write_iv;
3013     keySize                = cipher_def->key_size;
3014 
3015     if (skipKeysAndIVs) {
3016 	keySize                             = 0;
3017         key_material_params.ulKeySizeInBits = 0;
3018         key_material_params.ulIVSizeInBits  = 0;
3019     	returnedKeys.pIVClient              = NULL;
3020     	returnedKeys.pIVServer              = NULL;
3021     }
3022 
3023     calg = cipher_def->calg;
3024     PORT_Assert(     alg2Mech[calg].calg == calg);
3025     bulk_mechanism = alg2Mech[calg].cmech;
3026 
3027     params.data    = (unsigned char *)&key_material_params;
3028     params.len     = sizeof(key_material_params);
3029 
3030     if (isTLS) {
3031 	key_derive    = CKM_TLS_KEY_AND_MAC_DERIVE;
3032     } else {
3033 	key_derive    = CKM_SSL3_KEY_AND_MAC_DERIVE;
3034     }
3035 
3036     /* CKM_SSL3_KEY_AND_MAC_DERIVE is defined to set ENCRYPT, DECRYPT, and
3037      * DERIVE by DEFAULT */
3038     symKey = PK11_Derive(pwSpec->master_secret, key_derive, &params,
3039                          bulk_mechanism, CKA_ENCRYPT, keySize);
3040     if (!symKey) {
3041 	ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3042 	return SECFailure;
3043     }
3044     /* we really should use the actual mac'ing mechanism here, but we
3045      * don't because these types are used to map keytype anyway and both
3046      * mac's map to the same keytype.
3047      */
3048     slot  = PK11_GetSlotFromKey(symKey);
3049 
3050     PK11_FreeSlot(slot); /* slot is held until the key is freed */
3051     pwSpec->client.write_mac_key =
3052     	PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive,
3053 	    CKM_SSL3_SHA1_MAC, returnedKeys.hClientMacSecret, PR_TRUE, pwArg);
3054     if (pwSpec->client.write_mac_key == NULL ) {
3055 	goto loser;	/* loser sets err */
3056     }
3057     pwSpec->server.write_mac_key =
3058     	PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive,
3059 	    CKM_SSL3_SHA1_MAC, returnedKeys.hServerMacSecret, PR_TRUE, pwArg);
3060     if (pwSpec->server.write_mac_key == NULL ) {
3061 	goto loser;	/* loser sets err */
3062     }
3063     if (!skipKeysAndIVs) {
3064 	pwSpec->client.write_key =
3065 		PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive,
3066 		     bulk_mechanism, returnedKeys.hClientKey, PR_TRUE, pwArg);
3067 	if (pwSpec->client.write_key == NULL ) {
3068 	    goto loser;	/* loser sets err */
3069 	}
3070 	pwSpec->server.write_key =
3071 		PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive,
3072 		     bulk_mechanism, returnedKeys.hServerKey, PR_TRUE, pwArg);
3073 	if (pwSpec->server.write_key == NULL ) {
3074 	    goto loser;	/* loser sets err */
3075 	}
3076     }
3077     PK11_FreeSymKey(symKey);
3078     return SECSuccess;
3079 
3080 
3081 loser:
3082     if (symKey) PK11_FreeSymKey(symKey);
3083     ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3084     return SECFailure;
3085 }
3086 
3087 static SECStatus
ssl3_RestartHandshakeHashes(sslSocket * ss)3088 ssl3_RestartHandshakeHashes(sslSocket *ss)
3089 {
3090     SECStatus rv = SECSuccess;
3091 
3092     if (ss->opt.bypassPKCS11) {
3093 	ss->ssl3.hs.messages.len = 0;
3094 	MD5_Begin((MD5Context *)ss->ssl3.hs.md5_cx);
3095 	SHA1_Begin((SHA1Context *)ss->ssl3.hs.sha_cx);
3096     } else {
3097 	rv = PK11_DigestBegin(ss->ssl3.hs.md5);
3098 	if (rv != SECSuccess) {
3099 	    ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
3100 	    return rv;
3101 	}
3102 	rv = PK11_DigestBegin(ss->ssl3.hs.sha);
3103 	if (rv != SECSuccess) {
3104 	    ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3105 	    return rv;
3106 	}
3107     }
3108     return rv;
3109 }
3110 
3111 static SECStatus
ssl3_NewHandshakeHashes(sslSocket * ss)3112 ssl3_NewHandshakeHashes(sslSocket *ss)
3113 {
3114     PK11Context *md5  = NULL;
3115     PK11Context *sha  = NULL;
3116 
3117     /*
3118      * note: We should probably lookup an SSL3 slot for these
3119      * handshake hashes in hopes that we wind up with the same slots
3120      * that the master secret will wind up in ...
3121      */
3122     SSL_TRC(30,("%d: SSL3[%d]: start handshake hashes", SSL_GETPID(), ss->fd));
3123     if (ss->opt.bypassPKCS11) {
3124 	PORT_Assert(!ss->ssl3.hs.messages.buf && !ss->ssl3.hs.messages.space);
3125 	ss->ssl3.hs.messages.buf = NULL;
3126 	ss->ssl3.hs.messages.space = 0;
3127     } else {
3128 	ss->ssl3.hs.md5 = md5 = PK11_CreateDigestContext(SEC_OID_MD5);
3129 	ss->ssl3.hs.sha = sha = PK11_CreateDigestContext(SEC_OID_SHA1);
3130 	if (md5 == NULL) {
3131 	    ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
3132 	    goto loser;
3133 	}
3134 	if (sha == NULL) {
3135 	    ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3136 	    goto loser;
3137 	}
3138     }
3139     if (SECSuccess == ssl3_RestartHandshakeHashes(ss)) {
3140 	return SECSuccess;
3141     }
3142 
3143 loser:
3144     if (md5 != NULL) {
3145     	PK11_DestroyContext(md5, PR_TRUE);
3146 	ss->ssl3.hs.md5 = NULL;
3147     }
3148     if (sha != NULL) {
3149     	PK11_DestroyContext(sha, PR_TRUE);
3150 	ss->ssl3.hs.sha = NULL;
3151     }
3152     return SECFailure;
3153 
3154 }
3155 
3156 /*
3157  * Handshake messages
3158  */
3159 /* Called from	ssl3_AppendHandshake()
3160 **		ssl3_StartHandshakeHash()
3161 **		ssl3_HandleV2ClientHello()
3162 **		ssl3_HandleHandshakeMessage()
3163 ** Caller must hold the ssl3Handshake lock.
3164 */
3165 static SECStatus
ssl3_UpdateHandshakeHashes(sslSocket * ss,unsigned char * b,unsigned int l)3166 ssl3_UpdateHandshakeHashes(sslSocket *ss, unsigned char *b, unsigned int l)
3167 {
3168     SECStatus  rv = SECSuccess;
3169 
3170     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
3171 
3172     PRINT_BUF(90, (NULL, "MD5 & SHA handshake hash input:", b, l));
3173 
3174     if (ss->opt.bypassPKCS11) {
3175 	MD5_Update((MD5Context *)ss->ssl3.hs.md5_cx, b, l);
3176 	SHA1_Update((SHA1Context *)ss->ssl3.hs.sha_cx, b, l);
3177 #if defined(NSS_SURVIVE_DOUBLE_BYPASS_FAILURE)
3178 	rv = sslBuffer_Append(&ss->ssl3.hs.messages, b, l);
3179 #endif
3180 	return rv;
3181     }
3182     rv = PK11_DigestOp(ss->ssl3.hs.md5, b, l);
3183     if (rv != SECSuccess) {
3184 	ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
3185 	return rv;
3186     }
3187     rv = PK11_DigestOp(ss->ssl3.hs.sha, b, l);
3188     if (rv != SECSuccess) {
3189 	ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3190 	return rv;
3191     }
3192     return rv;
3193 }
3194 
3195 /**************************************************************************
3196  * Append Handshake functions.
3197  * All these functions set appropriate error codes.
3198  * Most rely on ssl3_AppendHandshake to set the error code.
3199  **************************************************************************/
3200 SECStatus
ssl3_AppendHandshake(sslSocket * ss,const void * void_src,PRInt32 bytes)3201 ssl3_AppendHandshake(sslSocket *ss, const void *void_src, PRInt32 bytes)
3202 {
3203     unsigned char *  src  = (unsigned char *)void_src;
3204     int              room = ss->sec.ci.sendBuf.space - ss->sec.ci.sendBuf.len;
3205     SECStatus        rv;
3206 
3207     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); /* protects sendBuf. */
3208 
3209     if (ss->sec.ci.sendBuf.space < MAX_SEND_BUF_LENGTH && room < bytes) {
3210 	rv = sslBuffer_Grow(&ss->sec.ci.sendBuf, PR_MAX(MIN_SEND_BUF_LENGTH,
3211 		 PR_MIN(MAX_SEND_BUF_LENGTH, ss->sec.ci.sendBuf.len + bytes)));
3212 	if (rv != SECSuccess)
3213 	    return rv;	/* sslBuffer_Grow has set a memory error code. */
3214 	room = ss->sec.ci.sendBuf.space - ss->sec.ci.sendBuf.len;
3215     }
3216 
3217     PRINT_BUF(60, (ss, "Append to Handshake", (unsigned char*)void_src, bytes));
3218     rv = ssl3_UpdateHandshakeHashes(ss, src, bytes);
3219     if (rv != SECSuccess)
3220 	return rv;	/* error code set by ssl3_UpdateHandshakeHashes */
3221 
3222     while (bytes > room) {
3223 	if (room > 0)
3224 	    PORT_Memcpy(ss->sec.ci.sendBuf.buf + ss->sec.ci.sendBuf.len, src,
3225 	                room);
3226 	ss->sec.ci.sendBuf.len += room;
3227 	rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
3228 	if (rv != SECSuccess) {
3229 	    return rv;	/* error code set by ssl3_FlushHandshake */
3230 	}
3231 	bytes -= room;
3232 	src += room;
3233 	room = ss->sec.ci.sendBuf.space;
3234 	PORT_Assert(ss->sec.ci.sendBuf.len == 0);
3235     }
3236     PORT_Memcpy(ss->sec.ci.sendBuf.buf + ss->sec.ci.sendBuf.len, src, bytes);
3237     ss->sec.ci.sendBuf.len += bytes;
3238     return SECSuccess;
3239 }
3240 
3241 SECStatus
ssl3_AppendHandshakeNumber(sslSocket * ss,PRInt32 num,PRInt32 lenSize)3242 ssl3_AppendHandshakeNumber(sslSocket *ss, PRInt32 num, PRInt32 lenSize)
3243 {
3244     SECStatus rv;
3245     uint8     b[4];
3246     uint8 *   p = b;
3247 
3248     switch (lenSize) {
3249       case 4:
3250 	*p++ = (num >> 24) & 0xff;
3251       case 3:
3252 	*p++ = (num >> 16) & 0xff;
3253       case 2:
3254 	*p++ = (num >> 8) & 0xff;
3255       case 1:
3256 	*p = num & 0xff;
3257     }
3258     SSL_TRC(60, ("%d: number:", SSL_GETPID()));
3259     rv = ssl3_AppendHandshake(ss, &b[0], lenSize);
3260     return rv;	/* error code set by AppendHandshake, if applicable. */
3261 }
3262 
3263 SECStatus
ssl3_AppendHandshakeVariable(sslSocket * ss,const SSL3Opaque * src,PRInt32 bytes,PRInt32 lenSize)3264 ssl3_AppendHandshakeVariable(
3265     sslSocket *ss, const SSL3Opaque *src, PRInt32 bytes, PRInt32 lenSize)
3266 {
3267     SECStatus rv;
3268 
3269     PORT_Assert((bytes < (1<<8) && lenSize == 1) ||
3270 	      (bytes < (1L<<16) && lenSize == 2) ||
3271 	      (bytes < (1L<<24) && lenSize == 3));
3272 
3273     SSL_TRC(60,("%d: append variable:", SSL_GETPID()));
3274     rv = ssl3_AppendHandshakeNumber(ss, bytes, lenSize);
3275     if (rv != SECSuccess) {
3276 	return rv;	/* error code set by AppendHandshake, if applicable. */
3277     }
3278     SSL_TRC(60, ("data:"));
3279     rv = ssl3_AppendHandshake(ss, src, bytes);
3280     return rv;	/* error code set by AppendHandshake, if applicable. */
3281 }
3282 
3283 SECStatus
ssl3_AppendHandshakeHeader(sslSocket * ss,SSL3HandshakeType t,PRUint32 length)3284 ssl3_AppendHandshakeHeader(sslSocket *ss, SSL3HandshakeType t, PRUint32 length)
3285 {
3286     SECStatus rv;
3287 
3288     SSL_TRC(30,("%d: SSL3[%d]: append handshake header: type %s",
3289     	SSL_GETPID(), ss->fd, ssl3_DecodeHandshakeType(t)));
3290     PRINT_BUF(60, (ss, "MD5 handshake hash:",
3291     	          (unsigned char*)ss->ssl3.hs.md5_cx, MD5_LENGTH));
3292     PRINT_BUF(95, (ss, "SHA handshake hash:",
3293     	          (unsigned char*)ss->ssl3.hs.sha_cx, SHA1_LENGTH));
3294 
3295     rv = ssl3_AppendHandshakeNumber(ss, t, 1);
3296     if (rv != SECSuccess) {
3297     	return rv;	/* error code set by AppendHandshake, if applicable. */
3298     }
3299     rv = ssl3_AppendHandshakeNumber(ss, length, 3);
3300     return rv;		/* error code set by AppendHandshake, if applicable. */
3301 }
3302 
3303 /**************************************************************************
3304  * Consume Handshake functions.
3305  *
3306  * All data used in these functions is protected by two locks,
3307  * the RecvBufLock and the SSL3HandshakeLock
3308  **************************************************************************/
3309 
3310 /* Read up the next "bytes" number of bytes from the (decrypted) input
3311  * stream "b" (which is *length bytes long). Copy them into buffer "v".
3312  * Reduces *length by bytes.  Advances *b by bytes.
3313  *
3314  * If this function returns SECFailure, it has already sent an alert,
3315  * and has set a generic error code.  The caller should probably
3316  * override the generic error code by setting another.
3317  */
3318 SECStatus
ssl3_ConsumeHandshake(sslSocket * ss,void * v,PRInt32 bytes,SSL3Opaque ** b,PRUint32 * length)3319 ssl3_ConsumeHandshake(sslSocket *ss, void *v, PRInt32 bytes, SSL3Opaque **b,
3320 		      PRUint32 *length)
3321 {
3322     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
3323     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
3324 
3325     if ((PRUint32)bytes > *length) {
3326 	return ssl3_DecodeError(ss);
3327     }
3328     PORT_Memcpy(v, *b, bytes);
3329     PRINT_BUF(60, (ss, "consume bytes:", *b, bytes));
3330     *b      += bytes;
3331     *length -= bytes;
3332     return SECSuccess;
3333 }
3334 
3335 /* Read up the next "bytes" number of bytes from the (decrypted) input
3336  * stream "b" (which is *length bytes long), and interpret them as an
3337  * integer in network byte order.  Returns the received value.
3338  * Reduces *length by bytes.  Advances *b by bytes.
3339  *
3340  * Returns SECFailure (-1) on failure.
3341  * This value is indistinguishable from the equivalent received value.
3342  * Only positive numbers are to be received this way.
3343  * Thus, the largest value that may be sent this way is 0x7fffffff.
3344  * On error, an alert has been sent, and a generic error code has been set.
3345  */
3346 PRInt32
ssl3_ConsumeHandshakeNumber(sslSocket * ss,PRInt32 bytes,SSL3Opaque ** b,PRUint32 * length)3347 ssl3_ConsumeHandshakeNumber(sslSocket *ss, PRInt32 bytes, SSL3Opaque **b,
3348 			    PRUint32 *length)
3349 {
3350     uint8     *buf = *b;
3351     int       i;
3352     PRInt32   num = 0;
3353 
3354     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
3355     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
3356     PORT_Assert( bytes <= sizeof num);
3357 
3358     if ((PRUint32)bytes > *length) {
3359 	return ssl3_DecodeError(ss);
3360     }
3361     PRINT_BUF(60, (ss, "consume bytes:", *b, bytes));
3362 
3363     for (i = 0; i < bytes; i++)
3364 	num = (num << 8) + buf[i];
3365     *b      += bytes;
3366     *length -= bytes;
3367     return num;
3368 }
3369 
3370 /* Read in two values from the incoming decrypted byte stream "b", which is
3371  * *length bytes long.  The first value is a number whose size is "bytes"
3372  * bytes long.  The second value is a byte-string whose size is the value
3373  * of the first number received.  The latter byte-string, and its length,
3374  * is returned in the SECItem i.
3375  *
3376  * Returns SECFailure (-1) on failure.
3377  * On error, an alert has been sent, and a generic error code has been set.
3378  *
3379  * RADICAL CHANGE for NSS 3.11.  All callers of this function make copies
3380  * of the data returned in the SECItem *i, so making a copy of it here
3381  * is simply wasteful.  So, This function now just sets SECItem *i to
3382  * point to the values in the buffer **b.
3383  */
3384 SECStatus
ssl3_ConsumeHandshakeVariable(sslSocket * ss,SECItem * i,PRInt32 bytes,SSL3Opaque ** b,PRUint32 * length)3385 ssl3_ConsumeHandshakeVariable(sslSocket *ss, SECItem *i, PRInt32 bytes,
3386 			      SSL3Opaque **b, PRUint32 *length)
3387 {
3388     PRInt32   count;
3389 
3390     PORT_Assert(bytes <= 3);
3391     i->len  = 0;
3392     i->data = NULL;
3393     count = ssl3_ConsumeHandshakeNumber(ss, bytes, b, length);
3394     if (count < 0) { 		/* Can't test for SECSuccess here. */
3395     	return SECFailure;
3396     }
3397     if (count > 0) {
3398 	if ((PRUint32)count > *length) {
3399 	    return ssl3_DecodeError(ss);
3400 	}
3401 	i->data = *b;
3402 	i->len  = count;
3403 	*b      += count;
3404 	*length -= count;
3405     }
3406     return SECSuccess;
3407 }
3408 
3409 /**************************************************************************
3410  * end of Consume Handshake functions.
3411  **************************************************************************/
3412 
3413 /* Extract the hashes of handshake messages to this point.
3414  * Called from ssl3_SendCertificateVerify
3415  *             ssl3_SendFinished
3416  *             ssl3_HandleHandshakeMessage
3417  *
3418  * Caller must hold the SSL3HandshakeLock.
3419  * Caller must hold a read or write lock on the Spec R/W lock.
3420  *	(There is presently no way to assert on a Read lock.)
3421  */
3422 static SECStatus
ssl3_ComputeHandshakeHashes(sslSocket * ss,ssl3CipherSpec * spec,SSL3Hashes * hashes,PRUint32 sender)3423 ssl3_ComputeHandshakeHashes(sslSocket *     ss,
3424                             ssl3CipherSpec *spec,   /* uses ->master_secret */
3425 			    SSL3Hashes *    hashes, /* output goes here. */
3426 			    PRUint32        sender)
3427 {
3428     SECStatus     rv        = SECSuccess;
3429     PRBool        isTLS     = (PRBool)(spec->version > SSL_LIBRARY_VERSION_3_0);
3430     unsigned int  outLength;
3431     SSL3Opaque    md5_inner[MAX_MAC_LENGTH];
3432     SSL3Opaque    sha_inner[MAX_MAC_LENGTH];
3433 
3434     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
3435 
3436     if (ss->opt.bypassPKCS11) {
3437 	/* compute them without PKCS11 */
3438 	PRUint64      md5_cx[MAX_MAC_CONTEXT_LLONGS];
3439 	PRUint64      sha_cx[MAX_MAC_CONTEXT_LLONGS];
3440 
3441 #define md5cx ((MD5Context *)md5_cx)
3442 #define shacx ((SHA1Context *)sha_cx)
3443 
3444 	if (!spec->msItem.data) {
3445 	    PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
3446 	    return SECFailure;
3447 	}
3448 
3449 	MD5_Clone (md5cx,  (MD5Context *)ss->ssl3.hs.md5_cx);
3450 	SHA1_Clone(shacx, (SHA1Context *)ss->ssl3.hs.sha_cx);
3451 
3452 	if (!isTLS) {
3453 	    /* compute hashes for SSL3. */
3454 	    unsigned char s[4];
3455 
3456 	    s[0] = (unsigned char)(sender >> 24);
3457 	    s[1] = (unsigned char)(sender >> 16);
3458 	    s[2] = (unsigned char)(sender >> 8);
3459 	    s[3] = (unsigned char)sender;
3460 
3461 	    if (sender != 0) {
3462 		MD5_Update(md5cx, s, 4);
3463 		PRINT_BUF(95, (NULL, "MD5 inner: sender", s, 4));
3464 	    }
3465 
3466 	    PRINT_BUF(95, (NULL, "MD5 inner: MAC Pad 1", mac_pad_1,
3467 			    mac_defs[mac_md5].pad_size));
3468 
3469 	    MD5_Update(md5cx, spec->msItem.data, spec->msItem.len);
3470 	    MD5_Update(md5cx, mac_pad_1, mac_defs[mac_md5].pad_size);
3471 	    MD5_End(md5cx, md5_inner, &outLength, MD5_LENGTH);
3472 
3473 	    PRINT_BUF(95, (NULL, "MD5 inner: result", md5_inner, outLength));
3474 
3475 	    if (sender != 0) {
3476 		SHA1_Update(shacx, s, 4);
3477 		PRINT_BUF(95, (NULL, "SHA inner: sender", s, 4));
3478 	    }
3479 
3480 	    PRINT_BUF(95, (NULL, "SHA inner: MAC Pad 1", mac_pad_1,
3481 			    mac_defs[mac_sha].pad_size));
3482 
3483 	    SHA1_Update(shacx, spec->msItem.data, spec->msItem.len);
3484 	    SHA1_Update(shacx, mac_pad_1, mac_defs[mac_sha].pad_size);
3485 	    SHA1_End(shacx, sha_inner, &outLength, SHA1_LENGTH);
3486 
3487 	    PRINT_BUF(95, (NULL, "SHA inner: result", sha_inner, outLength));
3488 	    PRINT_BUF(95, (NULL, "MD5 outer: MAC Pad 2", mac_pad_2,
3489 			    mac_defs[mac_md5].pad_size));
3490 	    PRINT_BUF(95, (NULL, "MD5 outer: MD5 inner", md5_inner, MD5_LENGTH));
3491 
3492 	    MD5_Begin(md5cx);
3493 	    MD5_Update(md5cx, spec->msItem.data, spec->msItem.len);
3494 	    MD5_Update(md5cx, mac_pad_2, mac_defs[mac_md5].pad_size);
3495 	    MD5_Update(md5cx, md5_inner, MD5_LENGTH);
3496 	}
3497 	MD5_End(md5cx, hashes->md5, &outLength, MD5_LENGTH);
3498 
3499 	PRINT_BUF(60, (NULL, "MD5 outer: result", hashes->md5, MD5_LENGTH));
3500 
3501 	if (!isTLS) {
3502 	    PRINT_BUF(95, (NULL, "SHA outer: MAC Pad 2", mac_pad_2,
3503 			    mac_defs[mac_sha].pad_size));
3504 	    PRINT_BUF(95, (NULL, "SHA outer: SHA inner", sha_inner, SHA1_LENGTH));
3505 
3506 	    SHA1_Begin(shacx);
3507 	    SHA1_Update(shacx, spec->msItem.data, spec->msItem.len);
3508 	    SHA1_Update(shacx, mac_pad_2, mac_defs[mac_sha].pad_size);
3509 	    SHA1_Update(shacx, sha_inner, SHA1_LENGTH);
3510 	}
3511 	SHA1_End(shacx, hashes->sha, &outLength, SHA1_LENGTH);
3512 
3513 	PRINT_BUF(60, (NULL, "SHA outer: result", hashes->sha, SHA1_LENGTH));
3514 
3515 	rv = SECSuccess;
3516 #undef md5cx
3517 #undef shacx
3518     } else {
3519 	/* compute hases with PKCS11 */
3520 	PK11Context * md5;
3521 	PK11Context * sha       = NULL;
3522 	unsigned char *md5StateBuf = NULL;
3523 	unsigned char *shaStateBuf = NULL;
3524 	unsigned int  md5StateLen, shaStateLen;
3525 	unsigned char md5StackBuf[256];
3526 	unsigned char shaStackBuf[512];
3527 
3528 	if (!spec->master_secret) {
3529 	    PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
3530 	    return SECFailure;
3531 	}
3532 
3533 	md5StateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.md5, md5StackBuf,
3534 					    sizeof md5StackBuf, &md5StateLen);
3535 	if (md5StateBuf == NULL) {
3536 	    ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
3537 	    goto loser;
3538 	}
3539 	md5 = ss->ssl3.hs.md5;
3540 
3541 	shaStateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.sha, shaStackBuf,
3542 					    sizeof shaStackBuf, &shaStateLen);
3543 	if (shaStateBuf == NULL) {
3544 	    ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3545 	    goto loser;
3546 	}
3547 	sha = ss->ssl3.hs.sha;
3548 
3549 	if (!isTLS) {
3550 	    /* compute hashes for SSL3. */
3551 	    unsigned char s[4];
3552 
3553 	    s[0] = (unsigned char)(sender >> 24);
3554 	    s[1] = (unsigned char)(sender >> 16);
3555 	    s[2] = (unsigned char)(sender >> 8);
3556 	    s[3] = (unsigned char)sender;
3557 
3558 	    if (sender != 0) {
3559 		rv |= PK11_DigestOp(md5, s, 4);
3560 		PRINT_BUF(95, (NULL, "MD5 inner: sender", s, 4));
3561 	    }
3562 
3563 	    PRINT_BUF(95, (NULL, "MD5 inner: MAC Pad 1", mac_pad_1,
3564 			  mac_defs[mac_md5].pad_size));
3565 
3566 	    rv |= PK11_DigestKey(md5,spec->master_secret);
3567 	    rv |= PK11_DigestOp(md5, mac_pad_1, mac_defs[mac_md5].pad_size);
3568 	    rv |= PK11_DigestFinal(md5, md5_inner, &outLength, MD5_LENGTH);
3569 	    PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH);
3570 	    if (rv != SECSuccess) {
3571 		ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
3572 		rv = SECFailure;
3573 		goto loser;
3574 	    }
3575 
3576 	    PRINT_BUF(95, (NULL, "MD5 inner: result", md5_inner, outLength));
3577 
3578 	    if (sender != 0) {
3579 		rv |= PK11_DigestOp(sha, s, 4);
3580 		PRINT_BUF(95, (NULL, "SHA inner: sender", s, 4));
3581 	    }
3582 
3583 	    PRINT_BUF(95, (NULL, "SHA inner: MAC Pad 1", mac_pad_1,
3584 			  mac_defs[mac_sha].pad_size));
3585 
3586 	    rv |= PK11_DigestKey(sha, spec->master_secret);
3587 	    rv |= PK11_DigestOp(sha, mac_pad_1, mac_defs[mac_sha].pad_size);
3588 	    rv |= PK11_DigestFinal(sha, sha_inner, &outLength, SHA1_LENGTH);
3589 	    PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH);
3590 	    if (rv != SECSuccess) {
3591 		ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3592 		rv = SECFailure;
3593 		goto loser;
3594 	    }
3595 
3596 	    PRINT_BUF(95, (NULL, "SHA inner: result", sha_inner, outLength));
3597 
3598 	    PRINT_BUF(95, (NULL, "MD5 outer: MAC Pad 2", mac_pad_2,
3599 			  mac_defs[mac_md5].pad_size));
3600 	    PRINT_BUF(95, (NULL, "MD5 outer: MD5 inner", md5_inner, MD5_LENGTH));
3601 
3602 	    rv |= PK11_DigestBegin(md5);
3603 	    rv |= PK11_DigestKey(md5, spec->master_secret);
3604 	    rv |= PK11_DigestOp(md5, mac_pad_2, mac_defs[mac_md5].pad_size);
3605 	    rv |= PK11_DigestOp(md5, md5_inner, MD5_LENGTH);
3606 	}
3607 	rv |= PK11_DigestFinal(md5, hashes->md5, &outLength, MD5_LENGTH);
3608 	PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH);
3609 	if (rv != SECSuccess) {
3610 	    ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
3611 	    rv = SECFailure;
3612 	    goto loser;
3613 	}
3614 
3615 	PRINT_BUF(60, (NULL, "MD5 outer: result", hashes->md5, MD5_LENGTH));
3616 
3617 	if (!isTLS) {
3618 	    PRINT_BUF(95, (NULL, "SHA outer: MAC Pad 2", mac_pad_2,
3619 			  mac_defs[mac_sha].pad_size));
3620 	    PRINT_BUF(95, (NULL, "SHA outer: SHA inner", sha_inner, SHA1_LENGTH));
3621 
3622 	    rv |= PK11_DigestBegin(sha);
3623 	    rv |= PK11_DigestKey(sha,spec->master_secret);
3624 	    rv |= PK11_DigestOp(sha, mac_pad_2, mac_defs[mac_sha].pad_size);
3625 	    rv |= PK11_DigestOp(sha, sha_inner, SHA1_LENGTH);
3626 	}
3627 	rv |= PK11_DigestFinal(sha, hashes->sha, &outLength, SHA1_LENGTH);
3628 	PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH);
3629 	if (rv != SECSuccess) {
3630 	    ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3631 	    rv = SECFailure;
3632 	    goto loser;
3633 	}
3634 
3635 	PRINT_BUF(60, (NULL, "SHA outer: result", hashes->sha, SHA1_LENGTH));
3636 
3637 	rv = SECSuccess;
3638 
3639     loser:
3640 	if (md5StateBuf) {
3641 	    if (PK11_RestoreContext(ss->ssl3.hs.md5, md5StateBuf, md5StateLen)
3642 		 != SECSuccess)
3643 	    {
3644 		ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
3645 		rv = SECFailure;
3646 	    }
3647 	    if (md5StateBuf != md5StackBuf) {
3648 		PORT_ZFree(md5StateBuf, md5StateLen);
3649 	    }
3650 	}
3651 	if (shaStateBuf) {
3652 	    if (PK11_RestoreContext(ss->ssl3.hs.sha, shaStateBuf, shaStateLen)
3653 		 != SECSuccess)
3654 	    {
3655 		ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3656 		rv = SECFailure;
3657 	    }
3658 	    if (shaStateBuf != shaStackBuf) {
3659 		PORT_ZFree(shaStateBuf, shaStateLen);
3660 	    }
3661 	}
3662     }
3663     return rv;
3664 }
3665 
3666 /*
3667  * SSL 2 based implementations pass in the initial outbound buffer
3668  * so that the handshake hash can contain the included information.
3669  *
3670  * Called from ssl2_BeginClientHandshake() in sslcon.c
3671  */
3672 SECStatus
ssl3_StartHandshakeHash(sslSocket * ss,unsigned char * buf,int length)3673 ssl3_StartHandshakeHash(sslSocket *ss, unsigned char * buf, int length)
3674 {
3675     SECStatus rv;
3676 
3677     ssl_GetSSL3HandshakeLock(ss);  /**************************************/
3678 
3679     rv = ssl3_InitState(ss);
3680     if (rv != SECSuccess) {
3681 	goto done;		/* ssl3_InitState has set the error code. */
3682     }
3683 
3684     PORT_Memset(&ss->ssl3.hs.client_random, 0, SSL3_RANDOM_LENGTH);
3685     PORT_Memcpy(
3686 	&ss->ssl3.hs.client_random.rand[SSL3_RANDOM_LENGTH - SSL_CHALLENGE_BYTES],
3687 	&ss->sec.ci.clientChallenge,
3688 	SSL_CHALLENGE_BYTES);
3689 
3690     rv = ssl3_UpdateHandshakeHashes(ss, buf, length);
3691     /* if it failed, ssl3_UpdateHandshakeHashes has set the error code. */
3692 
3693 done:
3694     ssl_ReleaseSSL3HandshakeLock(ss);  /**************************************/
3695     return rv;
3696 }
3697 
3698 /**************************************************************************
3699  * end of Handshake Hash functions.
3700  * Begin Send and Handle functions for handshakes.
3701  **************************************************************************/
3702 
3703 /* Called from ssl3_HandleHelloRequest(),
3704  *             ssl3_HandleFinished() (for step-up)
3705  *             ssl3_RedoHandshake()
3706  *             ssl2_BeginClientHandshake (when resuming ssl3 session)
3707  */
3708 SECStatus
ssl3_SendClientHello(sslSocket * ss)3709 ssl3_SendClientHello(sslSocket *ss)
3710 {
3711     sslSessionID *   sid;
3712     ssl3CipherSpec * cwSpec;
3713     SECStatus        rv;
3714     int              i;
3715     int              length;
3716     int              num_suites;
3717     int              actual_count = 0;
3718     PRInt32          total_exten_len = 0;
3719     unsigned         numCompressionMethods;
3720 
3721     SSL_TRC(3, ("%d: SSL3[%d]: send client_hello handshake", SSL_GETPID(),
3722 		ss->fd));
3723 
3724     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
3725     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
3726 
3727     rv = ssl3_InitState(ss);
3728     if (rv != SECSuccess) {
3729 	return rv;		/* ssl3_InitState has set the error code. */
3730     }
3731 
3732     /* We might be starting a session renegotiation in which case we should
3733      * clear previous state.
3734      */
3735     PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData));
3736 
3737     SSL_TRC(30,("%d: SSL3[%d]: reset handshake hashes",
3738 	    SSL_GETPID(), ss->fd ));
3739     rv = ssl3_RestartHandshakeHashes(ss);
3740     if (rv != SECSuccess) {
3741 	return rv;
3742     }
3743 
3744     /* We ignore ss->sec.ci.sid here, and use ssl_Lookup because Lookup
3745      * handles expired entries and other details.
3746      * XXX If we've been called from ssl2_BeginClientHandshake, then
3747      * this lookup is duplicative and wasteful.
3748      */
3749     sid = (ss->opt.noCache) ? NULL
3750 	    : ssl_LookupSID(&ss->sec.ci.peer, ss->sec.ci.port, ss->peerID, ss->url);
3751 
3752     /* We can't resume based on a different token. If the sid exists,
3753      * make sure the token that holds the master secret still exists ...
3754      * If we previously did client-auth, make sure that the token that holds
3755      * the private key still exists, is logged in, hasn't been removed, etc.
3756      */
3757     if (sid) {
3758 	PRBool sidOK = PR_TRUE;
3759 	if (sid->u.ssl3.keys.msIsWrapped) {
3760 	    /* Session key was wrapped, which means it was using PKCS11, */
3761 	    PK11SlotInfo *slot = NULL;
3762 	    if (sid->u.ssl3.masterValid && !ss->opt.bypassPKCS11) {
3763 		slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID,
3764 					 sid->u.ssl3.masterSlotID);
3765 	    }
3766 	    if (slot == NULL) {
3767 	       sidOK = PR_FALSE;
3768 	    } else {
3769 		PK11SymKey *wrapKey = NULL;
3770 		if (!PK11_IsPresent(slot) ||
3771 		    ((wrapKey = PK11_GetWrapKey(slot,
3772 						sid->u.ssl3.masterWrapIndex,
3773 						sid->u.ssl3.masterWrapMech,
3774 						sid->u.ssl3.masterWrapSeries,
3775 						ss->pkcs11PinArg)) == NULL) ) {
3776 		    sidOK = PR_FALSE;
3777 		}
3778 		if (wrapKey) PK11_FreeSymKey(wrapKey);
3779 		PK11_FreeSlot(slot);
3780 		slot = NULL;
3781 	    }
3782 	}
3783 	/* If we previously did client-auth, make sure that the token that
3784 	** holds the private key still exists, is logged in, hasn't been
3785 	** removed, etc.
3786 	*/
3787 	if (sidOK && !ssl3_ClientAuthTokenPresent(sid)) {
3788 	    sidOK = PR_FALSE;
3789 	}
3790 
3791 	if (!sidOK) {
3792 	    SSL_AtomicIncrementLong(& ssl3stats.sch_sid_cache_not_ok );
3793 	    (*ss->sec.uncache)(sid);
3794 	    ssl_FreeSID(sid);
3795 	    sid = NULL;
3796 	}
3797     }
3798 
3799     if (sid) {
3800 	SSL_AtomicIncrementLong(& ssl3stats.sch_sid_cache_hits );
3801 
3802 	/* Are we attempting a stateless session resume? */
3803 	if (sid->version > SSL_LIBRARY_VERSION_3_0 &&
3804 	    sid->u.ssl3.sessionTicket.ticket.data)
3805 	    SSL_AtomicIncrementLong(& ssl3stats.sch_sid_stateless_resumes );
3806 
3807 	rv = ssl3_NegotiateVersion(ss, sid->version);
3808 	if (rv != SECSuccess)
3809 	    return rv;	/* error code was set */
3810 
3811 	PRINT_BUF(4, (ss, "client, found session-id:", sid->u.ssl3.sessionID,
3812 		      sid->u.ssl3.sessionIDLength));
3813 
3814 	ss->ssl3.policy = sid->u.ssl3.policy;
3815     } else {
3816 	SSL_AtomicIncrementLong(& ssl3stats.sch_sid_cache_misses );
3817 
3818 	rv = ssl3_NegotiateVersion(ss, SSL_LIBRARY_VERSION_3_1_TLS);
3819 	if (rv != SECSuccess)
3820 	    return rv;	/* error code was set */
3821 
3822 	sid = ssl3_NewSessionID(ss, PR_FALSE);
3823 	if (!sid) {
3824 	    return SECFailure;	/* memory error is set */
3825         }
3826     }
3827 
3828     ssl_GetSpecWriteLock(ss);
3829     cwSpec = ss->ssl3.cwSpec;
3830     if (cwSpec->mac_def->mac == mac_null) {
3831 	/* SSL records are not being MACed. */
3832 	cwSpec->version = ss->version;
3833     }
3834     ssl_ReleaseSpecWriteLock(ss);
3835 
3836     if (ss->sec.ci.sid != NULL) {
3837 	ssl_FreeSID(ss->sec.ci.sid);	/* decrement ref count, free if zero */
3838     }
3839     ss->sec.ci.sid = sid;
3840 
3841     ss->sec.send = ssl3_SendApplicationData;
3842 
3843     /* shouldn't get here if SSL3 is disabled, but ... */
3844     PORT_Assert(ss->opt.enableSSL3 || ss->opt.enableTLS);
3845     if (!ss->opt.enableSSL3 && !ss->opt.enableTLS) {
3846 	PORT_SetError(SSL_ERROR_SSL_DISABLED);
3847     	return SECFailure;
3848     }
3849 
3850     /* how many suites does our PKCS11 support (regardless of policy)? */
3851     num_suites = ssl3_config_match_init(ss);
3852     if (!num_suites)
3853     	return SECFailure;	/* ssl3_config_match_init has set error code. */
3854 
3855     if (ss->opt.enableTLS && ss->version > SSL_LIBRARY_VERSION_3_0) {
3856 	PRUint32 maxBytes = 65535; /* 2^16 - 1 */
3857 	PRInt32  extLen;
3858 
3859 	extLen = ssl3_CallHelloExtensionSenders(ss, PR_FALSE, maxBytes, NULL);
3860 	if (extLen < 0) {
3861 	    return SECFailure;
3862 	}
3863 	maxBytes        -= extLen;
3864 	total_exten_len += extLen;
3865 
3866 	if (total_exten_len > 0)
3867 	    total_exten_len += 2;
3868     }
3869 #if defined(NSS_ENABLE_ECC) && !defined(NSS_ECC_MORE_THAN_SUITE_B)
3870     else { /* SSL3 only */
3871     	ssl3_DisableECCSuites(ss, NULL); /* disable all ECC suites */
3872     }
3873 #endif
3874 
3875     /* how many suites are permitted by policy and user preference? */
3876     num_suites = count_cipher_suites(ss, ss->ssl3.policy, PR_TRUE);
3877     if (!num_suites)
3878     	return SECFailure;	/* count_cipher_suites has set error code. */
3879 
3880     /* count compression methods */
3881     numCompressionMethods = 0;
3882     for (i = 0; i < compressionMethodsCount; i++) {
3883 	if (compressionEnabled(ss, compressions[i]))
3884 	    numCompressionMethods++;
3885     }
3886 
3887     length = sizeof(SSL3ProtocolVersion) + SSL3_RANDOM_LENGTH +
3888 	1 + ((sid == NULL) ? 0 : sid->u.ssl3.sessionIDLength) +
3889 	2 + num_suites*sizeof(ssl3CipherSuite) +
3890 	1 + numCompressionMethods + total_exten_len;
3891 
3892     rv = ssl3_AppendHandshakeHeader(ss, client_hello, length);
3893     if (rv != SECSuccess) {
3894 	return rv;	/* err set by ssl3_AppendHandshake* */
3895     }
3896 
3897     ss->clientHelloVersion = ss->version;
3898     rv = ssl3_AppendHandshakeNumber(ss, ss->clientHelloVersion, 2);
3899     if (rv != SECSuccess) {
3900 	return rv;	/* err set by ssl3_AppendHandshake* */
3901     }
3902     rv = ssl3_GetNewRandom(&ss->ssl3.hs.client_random);
3903     if (rv != SECSuccess) {
3904 	return rv;	/* err set by GetNewRandom. */
3905     }
3906     rv = ssl3_AppendHandshake(ss, &ss->ssl3.hs.client_random,
3907                               SSL3_RANDOM_LENGTH);
3908     if (rv != SECSuccess) {
3909 	return rv;	/* err set by ssl3_AppendHandshake* */
3910     }
3911 
3912     if (sid)
3913 	rv = ssl3_AppendHandshakeVariable(
3914 	    ss, sid->u.ssl3.sessionID, sid->u.ssl3.sessionIDLength, 1);
3915     else
3916 	rv = ssl3_AppendHandshakeVariable(ss, NULL, 0, 1);
3917     if (rv != SECSuccess) {
3918 	return rv;	/* err set by ssl3_AppendHandshake* */
3919     }
3920 
3921     rv = ssl3_AppendHandshakeNumber(ss, num_suites*sizeof(ssl3CipherSuite), 2);
3922     if (rv != SECSuccess) {
3923 	return rv;	/* err set by ssl3_AppendHandshake* */
3924     }
3925 
3926 
3927     for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
3928 	ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i];
3929 	if (config_match(suite, ss->ssl3.policy, PR_TRUE)) {
3930 	    actual_count++;
3931 	    if (actual_count > num_suites) {
3932 		/* set error card removal/insertion error */
3933 		PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
3934 		return SECFailure;
3935 	    }
3936 	    rv = ssl3_AppendHandshakeNumber(ss, suite->cipher_suite,
3937 					    sizeof(ssl3CipherSuite));
3938 	    if (rv != SECSuccess) {
3939 		return rv;	/* err set by ssl3_AppendHandshake* */
3940 	    }
3941 	}
3942     }
3943 
3944     /* if cards were removed or inserted between count_cipher_suites and
3945      * generating our list, detect the error here rather than send it off to
3946      * the server.. */
3947     if (actual_count != num_suites) {
3948 	/* Card removal/insertion error */
3949 	PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
3950 	return SECFailure;
3951     }
3952 
3953     rv = ssl3_AppendHandshakeNumber(ss, numCompressionMethods, 1);
3954     if (rv != SECSuccess) {
3955 	return rv;	/* err set by ssl3_AppendHandshake* */
3956     }
3957     for (i = 0; i < compressionMethodsCount; i++) {
3958 	if (!compressionEnabled(ss, compressions[i]))
3959 	    continue;
3960 	rv = ssl3_AppendHandshakeNumber(ss, compressions[i], 1);
3961 	if (rv != SECSuccess) {
3962 	    return rv;	/* err set by ssl3_AppendHandshake* */
3963 	}
3964     }
3965 
3966     if (total_exten_len) {
3967 	PRUint32 maxBytes = total_exten_len - 2;
3968 	PRInt32  extLen;
3969 
3970 	rv = ssl3_AppendHandshakeNumber(ss, maxBytes, 2);
3971 	if (rv != SECSuccess) {
3972 	    return rv;	/* err set by AppendHandshake. */
3973 	}
3974 
3975 	extLen = ssl3_CallHelloExtensionSenders(ss, PR_TRUE, maxBytes, NULL);
3976 	if (extLen < 0) {
3977 	    return SECFailure;
3978 	}
3979 	maxBytes -= extLen;
3980 	PORT_Assert(!maxBytes);
3981     }
3982 
3983 
3984     rv = ssl3_FlushHandshake(ss, 0);
3985     if (rv != SECSuccess) {
3986 	return rv;	/* error code set by ssl3_FlushHandshake */
3987     }
3988 
3989     ss->ssl3.hs.ws = wait_server_hello;
3990     return rv;
3991 }
3992 
3993 
3994 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
3995  * ssl3 Hello Request.
3996  * Caller must hold Handshake and RecvBuf locks.
3997  */
3998 static SECStatus
ssl3_HandleHelloRequest(sslSocket * ss)3999 ssl3_HandleHelloRequest(sslSocket *ss)
4000 {
4001     sslSessionID *sid = ss->sec.ci.sid;
4002     SECStatus     rv;
4003 
4004     SSL_TRC(3, ("%d: SSL3[%d]: handle hello_request handshake",
4005 		SSL_GETPID(), ss->fd));
4006 
4007     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
4008     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
4009 
4010     if (ss->ssl3.hs.ws == wait_server_hello)
4011 	return SECSuccess;
4012     if (ss->ssl3.hs.ws != idle_handshake || ss->sec.isServer) {
4013 	(void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
4014 	PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST);
4015 	return SECFailure;
4016     }
4017     if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) {
4018 	ssl_GetXmitBufLock(ss);
4019 	rv = SSL3_SendAlert(ss, alert_warning, no_renegotiation);
4020 	ssl_ReleaseXmitBufLock(ss);
4021 	PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED);
4022 	return SECFailure;
4023     }
4024 
4025     if (sid) {
4026 	ss->sec.uncache(sid);
4027 	ssl_FreeSID(sid);
4028 	ss->sec.ci.sid = NULL;
4029     }
4030 
4031     ssl_GetXmitBufLock(ss);
4032     rv = ssl3_SendClientHello(ss);
4033     ssl_ReleaseXmitBufLock(ss);
4034 
4035     return rv;
4036 }
4037 
4038 #define UNKNOWN_WRAP_MECHANISM 0x7fffffff
4039 
4040 static const CK_MECHANISM_TYPE wrapMechanismList[SSL_NUM_WRAP_MECHS] = {
4041     CKM_DES3_ECB,
4042     CKM_CAST5_ECB,
4043     CKM_DES_ECB,
4044     CKM_KEY_WRAP_LYNKS,
4045     CKM_IDEA_ECB,
4046     CKM_CAST3_ECB,
4047     CKM_CAST_ECB,
4048     CKM_RC5_ECB,
4049     CKM_RC2_ECB,
4050     CKM_CDMF_ECB,
4051     CKM_SKIPJACK_WRAP,
4052     CKM_SKIPJACK_CBC64,
4053     CKM_AES_ECB,
4054     CKM_CAMELLIA_ECB,
4055     CKM_SEED_ECB,
4056     UNKNOWN_WRAP_MECHANISM
4057 };
4058 
4059 static int
ssl_FindIndexByWrapMechanism(CK_MECHANISM_TYPE mech)4060 ssl_FindIndexByWrapMechanism(CK_MECHANISM_TYPE mech)
4061 {
4062     const CK_MECHANISM_TYPE *pMech = wrapMechanismList;
4063 
4064     while (mech != *pMech && *pMech != UNKNOWN_WRAP_MECHANISM) {
4065     	++pMech;
4066     }
4067     return (*pMech == UNKNOWN_WRAP_MECHANISM) ? -1
4068                                               : (pMech - wrapMechanismList);
4069 }
4070 
4071 static PK11SymKey *
ssl_UnwrapSymWrappingKey(SSLWrappedSymWrappingKey * pWswk,SECKEYPrivateKey * svrPrivKey,SSL3KEAType exchKeyType,CK_MECHANISM_TYPE masterWrapMech,void * pwArg)4072 ssl_UnwrapSymWrappingKey(
4073 	SSLWrappedSymWrappingKey *pWswk,
4074 	SECKEYPrivateKey *        svrPrivKey,
4075 	SSL3KEAType               exchKeyType,
4076 	CK_MECHANISM_TYPE         masterWrapMech,
4077 	void *                    pwArg)
4078 {
4079     PK11SymKey *             unwrappedWrappingKey  = NULL;
4080     SECItem                  wrappedKey;
4081 #ifdef NSS_ENABLE_ECC
4082     PK11SymKey *             Ks;
4083     SECKEYPublicKey          pubWrapKey;
4084     ECCWrappedKeyInfo        *ecWrapped;
4085 #endif /* NSS_ENABLE_ECC */
4086 
4087     /* found the wrapping key on disk. */
4088     PORT_Assert(pWswk->symWrapMechanism == masterWrapMech);
4089     PORT_Assert(pWswk->exchKeyType      == exchKeyType);
4090     if (pWswk->symWrapMechanism != masterWrapMech ||
4091 	pWswk->exchKeyType      != exchKeyType) {
4092 	goto loser;
4093     }
4094     wrappedKey.type = siBuffer;
4095     wrappedKey.data = pWswk->wrappedSymmetricWrappingkey;
4096     wrappedKey.len  = pWswk->wrappedSymKeyLen;
4097     PORT_Assert(wrappedKey.len <= sizeof pWswk->wrappedSymmetricWrappingkey);
4098 
4099     switch (exchKeyType) {
4100 
4101     case kt_rsa:
4102 	unwrappedWrappingKey =
4103 	    PK11_PubUnwrapSymKey(svrPrivKey, &wrappedKey,
4104 				 masterWrapMech, CKA_UNWRAP, 0);
4105 	break;
4106 
4107 #ifdef NSS_ENABLE_ECC
4108     case kt_ecdh:
4109         /*
4110          * For kt_ecdh, we first create an EC public key based on
4111          * data stored with the wrappedSymmetricWrappingkey. Next,
4112          * we do an ECDH computation involving this public key and
4113          * the SSL server's (long-term) EC private key. The resulting
4114          * shared secret is treated the same way as Fortezza's Ks, i.e.,
4115          * it is used to recover the symmetric wrapping key.
4116          *
4117          * The data in wrappedSymmetricWrappingkey is laid out as defined
4118          * in the ECCWrappedKeyInfo structure.
4119          */
4120         ecWrapped = (ECCWrappedKeyInfo *) pWswk->wrappedSymmetricWrappingkey;
4121 
4122         PORT_Assert(ecWrapped->encodedParamLen + ecWrapped->pubValueLen +
4123             ecWrapped->wrappedKeyLen <= MAX_EC_WRAPPED_KEY_BUFLEN);
4124 
4125         if (ecWrapped->encodedParamLen + ecWrapped->pubValueLen +
4126             ecWrapped->wrappedKeyLen > MAX_EC_WRAPPED_KEY_BUFLEN) {
4127             PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
4128             goto loser;
4129         }
4130 
4131         pubWrapKey.keyType = ecKey;
4132         pubWrapKey.u.ec.size = ecWrapped->size;
4133         pubWrapKey.u.ec.DEREncodedParams.len = ecWrapped->encodedParamLen;
4134         pubWrapKey.u.ec.DEREncodedParams.data = ecWrapped->var;
4135         pubWrapKey.u.ec.publicValue.len = ecWrapped->pubValueLen;
4136         pubWrapKey.u.ec.publicValue.data = ecWrapped->var +
4137             ecWrapped->encodedParamLen;
4138 
4139         wrappedKey.len  = ecWrapped->wrappedKeyLen;
4140         wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen +
4141             ecWrapped->pubValueLen;
4142 
4143         /* Derive Ks using ECDH */
4144         Ks = PK11_PubDeriveWithKDF(svrPrivKey, &pubWrapKey, PR_FALSE, NULL,
4145 				   NULL, CKM_ECDH1_DERIVE, masterWrapMech,
4146 				   CKA_DERIVE, 0, CKD_NULL, NULL, NULL);
4147         if (Ks == NULL) {
4148             goto loser;
4149         }
4150 
4151         /*  Use Ks to unwrap the wrapping key */
4152         unwrappedWrappingKey = PK11_UnwrapSymKey(Ks, masterWrapMech, NULL,
4153 						 &wrappedKey, masterWrapMech,
4154 						 CKA_UNWRAP, 0);
4155         PK11_FreeSymKey(Ks);
4156 
4157         break;
4158 #endif
4159 
4160     default:
4161 	/* Assert? */
4162 	SET_ERROR_CODE
4163 	goto loser;
4164     }
4165 loser:
4166     return unwrappedWrappingKey;
4167 }
4168 
4169 /* Each process sharing the server session ID cache has its own array of
4170  * SymKey pointers for the symmetric wrapping keys that are used to wrap
4171  * the master secrets.  There is one key for each KEA type.  These Symkeys
4172  * correspond to the wrapped SymKeys kept in the server session cache.
4173  */
4174 
4175 typedef struct {
4176     PK11SymKey *      symWrapKey[kt_kea_size];
4177 } ssl3SymWrapKey;
4178 
4179 static PZLock *          symWrapKeysLock = NULL;
4180 static ssl3SymWrapKey    symWrapKeys[SSL_NUM_WRAP_MECHS];
4181 
ssl_FreeSymWrapKeysLock(void)4182 SECStatus ssl_FreeSymWrapKeysLock(void)
4183 {
4184     if (symWrapKeysLock) {
4185         PZ_DestroyLock(symWrapKeysLock);
4186         symWrapKeysLock = NULL;
4187         return SECSuccess;
4188     }
4189     PORT_SetError(SEC_ERROR_NOT_INITIALIZED);
4190     return SECFailure;
4191 }
4192 
4193 SECStatus
SSL3_ShutdownServerCache(void)4194 SSL3_ShutdownServerCache(void)
4195 {
4196     int             i, j;
4197 
4198     if (!symWrapKeysLock)
4199     	return SECSuccess;	/* lock was never initialized */
4200     PZ_Lock(symWrapKeysLock);
4201     /* get rid of all symWrapKeys */
4202     for (i = 0; i < SSL_NUM_WRAP_MECHS; ++i) {
4203     	for (j = 0; j < kt_kea_size; ++j) {
4204 	    PK11SymKey **   pSymWrapKey;
4205 	    pSymWrapKey = &symWrapKeys[i].symWrapKey[j];
4206 	    if (*pSymWrapKey) {
4207 		PK11_FreeSymKey(*pSymWrapKey);
4208 	    	*pSymWrapKey = NULL;
4209 	    }
4210 	}
4211     }
4212 
4213     PZ_Unlock(symWrapKeysLock);
4214     ssl_FreeSessionCacheLocks();
4215     return SECSuccess;
4216 }
4217 
ssl_InitSymWrapKeysLock(void)4218 SECStatus ssl_InitSymWrapKeysLock(void)
4219 {
4220     symWrapKeysLock = PZ_NewLock(nssILockOther);
4221     return symWrapKeysLock ? SECSuccess : SECFailure;
4222 }
4223 
4224 /* Try to get wrapping key for mechanism from in-memory array.
4225  * If that fails, look for one on disk.
4226  * If that fails, generate a new one, put the new one on disk,
4227  * Put the new key in the in-memory array.
4228  */
4229 static PK11SymKey *
getWrappingKey(sslSocket * ss,PK11SlotInfo * masterSecretSlot,SSL3KEAType exchKeyType,CK_MECHANISM_TYPE masterWrapMech,void * pwArg)4230 getWrappingKey( sslSocket *       ss,
4231 		PK11SlotInfo *    masterSecretSlot,
4232 		SSL3KEAType       exchKeyType,
4233                 CK_MECHANISM_TYPE masterWrapMech,
4234 	        void *            pwArg)
4235 {
4236     SECKEYPrivateKey *       svrPrivKey;
4237     SECKEYPublicKey *        svrPubKey             = NULL;
4238     PK11SymKey *             unwrappedWrappingKey  = NULL;
4239     PK11SymKey **            pSymWrapKey;
4240     CK_MECHANISM_TYPE        asymWrapMechanism = CKM_INVALID_MECHANISM;
4241     int                      length;
4242     int                      symWrapMechIndex;
4243     SECStatus                rv;
4244     SECItem                  wrappedKey;
4245     SSLWrappedSymWrappingKey wswk;
4246 
4247     svrPrivKey  = ss->serverCerts[exchKeyType].SERVERKEY;
4248     PORT_Assert(svrPrivKey != NULL);
4249     if (!svrPrivKey) {
4250     	return NULL;	/* why are we here?!? */
4251     }
4252 
4253     symWrapMechIndex = ssl_FindIndexByWrapMechanism(masterWrapMech);
4254     PORT_Assert(symWrapMechIndex >= 0);
4255     if (symWrapMechIndex < 0)
4256     	return NULL;	/* invalid masterWrapMech. */
4257 
4258     pSymWrapKey = &symWrapKeys[symWrapMechIndex].symWrapKey[exchKeyType];
4259 
4260     ssl_InitSessionCacheLocks(PR_TRUE);
4261 
4262     PZ_Lock(symWrapKeysLock);
4263 
4264     unwrappedWrappingKey = *pSymWrapKey;
4265     if (unwrappedWrappingKey != NULL) {
4266 	if (PK11_VerifyKeyOK(unwrappedWrappingKey)) {
4267 	    unwrappedWrappingKey = PK11_ReferenceSymKey(unwrappedWrappingKey);
4268 	    goto done;
4269 	}
4270 	/* slot series has changed, so this key is no good any more. */
4271 	PK11_FreeSymKey(unwrappedWrappingKey);
4272 	*pSymWrapKey = unwrappedWrappingKey = NULL;
4273     }
4274 
4275     /* Try to get wrapped SymWrapping key out of the (disk) cache. */
4276     /* Following call fills in wswk on success. */
4277     if (ssl_GetWrappingKey(symWrapMechIndex, exchKeyType, &wswk)) {
4278     	/* found the wrapped sym wrapping key on disk. */
4279 	unwrappedWrappingKey =
4280 	    ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, exchKeyType,
4281                                      masterWrapMech, pwArg);
4282 	if (unwrappedWrappingKey) {
4283 	    goto install;
4284 	}
4285     }
4286 
4287     if (!masterSecretSlot) 	/* caller doesn't want to create a new one. */
4288     	goto loser;
4289 
4290     length = PK11_GetBestKeyLength(masterSecretSlot, masterWrapMech);
4291     /* Zero length means fixed key length algorithm, or error.
4292      * It's ambiguous.
4293      */
4294     unwrappedWrappingKey = PK11_KeyGen(masterSecretSlot, masterWrapMech, NULL,
4295                                        length, pwArg);
4296     if (!unwrappedWrappingKey) {
4297     	goto loser;
4298     }
4299 
4300     /* Prepare the buffer to receive the wrappedWrappingKey,
4301      * the symmetric wrapping key wrapped using the server's pub key.
4302      */
4303     PORT_Memset(&wswk, 0, sizeof wswk);	/* eliminate UMRs. */
4304 
4305     if (ss->serverCerts[exchKeyType].serverKeyPair) {
4306 	svrPubKey = ss->serverCerts[exchKeyType].serverKeyPair->pubKey;
4307     }
4308     if (svrPubKey == NULL) {
4309 	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
4310 	goto loser;
4311     }
4312     wrappedKey.type = siBuffer;
4313     wrappedKey.len  = SECKEY_PublicKeyStrength(svrPubKey);
4314     wrappedKey.data = wswk.wrappedSymmetricWrappingkey;
4315 
4316     PORT_Assert(wrappedKey.len <= sizeof wswk.wrappedSymmetricWrappingkey);
4317     if (wrappedKey.len > sizeof wswk.wrappedSymmetricWrappingkey)
4318     	goto loser;
4319 
4320     /* wrap symmetric wrapping key in server's public key. */
4321     switch (exchKeyType) {
4322 #ifdef NSS_ENABLE_ECC
4323     PK11SymKey *      Ks = NULL;
4324     SECKEYPublicKey   *pubWrapKey = NULL;
4325     SECKEYPrivateKey  *privWrapKey = NULL;
4326     ECCWrappedKeyInfo *ecWrapped;
4327 #endif /* NSS_ENABLE_ECC */
4328 
4329     case kt_rsa:
4330 	asymWrapMechanism = CKM_RSA_PKCS;
4331 	rv = PK11_PubWrapSymKey(asymWrapMechanism, svrPubKey,
4332 	                        unwrappedWrappingKey, &wrappedKey);
4333 	break;
4334 
4335 #ifdef NSS_ENABLE_ECC
4336     case kt_ecdh:
4337 	/*
4338 	 * We generate an ephemeral EC key pair. Perform an ECDH
4339 	 * computation involving this ephemeral EC public key and
4340 	 * the SSL server's (long-term) EC private key. The resulting
4341 	 * shared secret is treated in the same way as Fortezza's Ks,
4342 	 * i.e., it is used to wrap the wrapping key. To facilitate
4343 	 * unwrapping in ssl_UnwrapWrappingKey, we also store all
4344 	 * relevant info about the ephemeral EC public key in
4345 	 * wswk.wrappedSymmetricWrappingkey and lay it out as
4346 	 * described in the ECCWrappedKeyInfo structure.
4347 	 */
4348 	PORT_Assert(svrPubKey->keyType == ecKey);
4349 	if (svrPubKey->keyType != ecKey) {
4350 	    /* something is wrong in sslsecur.c if this isn't an ecKey */
4351 	    PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
4352 	    rv = SECFailure;
4353 	    goto ec_cleanup;
4354 	}
4355 
4356 	privWrapKey = SECKEY_CreateECPrivateKey(
4357 	    &svrPubKey->u.ec.DEREncodedParams, &pubWrapKey, NULL);
4358 	if ((privWrapKey == NULL) || (pubWrapKey == NULL)) {
4359 	    rv = SECFailure;
4360 	    goto ec_cleanup;
4361 	}
4362 
4363 	/* Set the key size in bits */
4364 	if (pubWrapKey->u.ec.size == 0) {
4365 	    pubWrapKey->u.ec.size = SECKEY_PublicKeyStrengthInBits(svrPubKey);
4366 	}
4367 
4368 	PORT_Assert(pubWrapKey->u.ec.DEREncodedParams.len +
4369 	    pubWrapKey->u.ec.publicValue.len < MAX_EC_WRAPPED_KEY_BUFLEN);
4370 	if (pubWrapKey->u.ec.DEREncodedParams.len +
4371 	    pubWrapKey->u.ec.publicValue.len >= MAX_EC_WRAPPED_KEY_BUFLEN) {
4372 	    PORT_SetError(SEC_ERROR_INVALID_KEY);
4373 	    rv = SECFailure;
4374 	    goto ec_cleanup;
4375 	}
4376 
4377 	/* Derive Ks using ECDH */
4378 	Ks = PK11_PubDeriveWithKDF(svrPrivKey, pubWrapKey, PR_FALSE, NULL,
4379 				   NULL, CKM_ECDH1_DERIVE, masterWrapMech,
4380 				   CKA_DERIVE, 0, CKD_NULL, NULL, NULL);
4381 	if (Ks == NULL) {
4382 	    rv = SECFailure;
4383 	    goto ec_cleanup;
4384 	}
4385 
4386 	ecWrapped = (ECCWrappedKeyInfo *) (wswk.wrappedSymmetricWrappingkey);
4387 	ecWrapped->size = pubWrapKey->u.ec.size;
4388 	ecWrapped->encodedParamLen = pubWrapKey->u.ec.DEREncodedParams.len;
4389 	PORT_Memcpy(ecWrapped->var, pubWrapKey->u.ec.DEREncodedParams.data,
4390 	    pubWrapKey->u.ec.DEREncodedParams.len);
4391 
4392 	ecWrapped->pubValueLen = pubWrapKey->u.ec.publicValue.len;
4393 	PORT_Memcpy(ecWrapped->var + ecWrapped->encodedParamLen,
4394 		    pubWrapKey->u.ec.publicValue.data,
4395 		    pubWrapKey->u.ec.publicValue.len);
4396 
4397 	wrappedKey.len = MAX_EC_WRAPPED_KEY_BUFLEN -
4398 	    (ecWrapped->encodedParamLen + ecWrapped->pubValueLen);
4399 	wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen +
4400 	    ecWrapped->pubValueLen;
4401 
4402 	/* wrap symmetricWrapping key with the local Ks */
4403 	rv = PK11_WrapSymKey(masterWrapMech, NULL, Ks,
4404 			     unwrappedWrappingKey, &wrappedKey);
4405 
4406 	if (rv != SECSuccess) {
4407 	    goto ec_cleanup;
4408 	}
4409 
4410 	/* Write down the length of wrapped key in the buffer
4411 	 * wswk.wrappedSymmetricWrappingkey at the appropriate offset
4412 	 */
4413 	ecWrapped->wrappedKeyLen = wrappedKey.len;
4414 
4415 ec_cleanup:
4416 	if (privWrapKey) SECKEY_DestroyPrivateKey(privWrapKey);
4417 	if (pubWrapKey) SECKEY_DestroyPublicKey(pubWrapKey);
4418 	if (Ks) PK11_FreeSymKey(Ks);
4419 	asymWrapMechanism = masterWrapMech;
4420 	break;
4421 #endif /* NSS_ENABLE_ECC */
4422 
4423     default:
4424 	rv = SECFailure;
4425 	break;
4426     }
4427 
4428     if (rv != SECSuccess) {
4429 	ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
4430 	goto loser;
4431     }
4432 
4433     PORT_Assert(asymWrapMechanism != CKM_INVALID_MECHANISM);
4434 
4435     wswk.symWrapMechanism  = masterWrapMech;
4436     wswk.symWrapMechIndex  = symWrapMechIndex;
4437     wswk.asymWrapMechanism = asymWrapMechanism;
4438     wswk.exchKeyType       = exchKeyType;
4439     wswk.wrappedSymKeyLen  = wrappedKey.len;
4440 
4441     /* put it on disk. */
4442     /* If the wrapping key for this KEA type has already been set,
4443      * then abandon the value we just computed and
4444      * use the one we got from the disk.
4445      */
4446     if (ssl_SetWrappingKey(&wswk)) {
4447     	/* somebody beat us to it.  The original contents of our wswk
4448 	 * has been replaced with the content on disk.  Now, discard
4449 	 * the key we just created and unwrap this new one.
4450 	 */
4451     	PK11_FreeSymKey(unwrappedWrappingKey);
4452 
4453 	unwrappedWrappingKey =
4454 	    ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, exchKeyType,
4455                                      masterWrapMech, pwArg);
4456     }
4457 
4458 install:
4459     if (unwrappedWrappingKey) {
4460 	*pSymWrapKey = PK11_ReferenceSymKey(unwrappedWrappingKey);
4461     }
4462 
4463 loser:
4464 done:
4465     PZ_Unlock(symWrapKeysLock);
4466     return unwrappedWrappingKey;
4467 }
4468 
4469 
4470 /* Called from ssl3_SendClientKeyExchange(). */
4471 /* Presently, this always uses PKCS11.  There is no bypass for this. */
4472 static SECStatus
sendRSAClientKeyExchange(sslSocket * ss,SECKEYPublicKey * svrPubKey)4473 sendRSAClientKeyExchange(sslSocket * ss, SECKEYPublicKey * svrPubKey)
4474 {
4475     PK11SymKey *	pms 		= NULL;
4476     SECStatus           rv    		= SECFailure;
4477     SECItem 		enc_pms 	= {siBuffer, NULL, 0};
4478     PRBool              isTLS;
4479 
4480     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
4481     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
4482 
4483     /* Generate the pre-master secret ...  */
4484     ssl_GetSpecWriteLock(ss);
4485     isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
4486 
4487     pms = ssl3_GenerateRSAPMS(ss, ss->ssl3.pwSpec, NULL);
4488     ssl_ReleaseSpecWriteLock(ss);
4489     if (pms == NULL) {
4490 	ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
4491 	goto loser;
4492     }
4493 
4494 #if defined(TRACE)
4495     if (ssl_trace >= 100) {
4496 	SECStatus extractRV = PK11_ExtractKeyValue(pms);
4497 	if (extractRV == SECSuccess) {
4498 	    SECItem * keyData = PK11_GetKeyData(pms);
4499 	    if (keyData && keyData->data && keyData->len) {
4500 		ssl_PrintBuf(ss, "Pre-Master Secret",
4501 			     keyData->data, keyData->len);
4502 	    }
4503     	}
4504     }
4505 #endif
4506 
4507     /* Get the wrapped (encrypted) pre-master secret, enc_pms */
4508     enc_pms.len  = SECKEY_PublicKeyStrength(svrPubKey);
4509     enc_pms.data = (unsigned char*)PORT_Alloc(enc_pms.len);
4510     if (enc_pms.data == NULL) {
4511 	goto loser;	/* err set by PORT_Alloc */
4512     }
4513 
4514     /* wrap pre-master secret in server's public key. */
4515     rv = PK11_PubWrapSymKey(CKM_RSA_PKCS, svrPubKey, pms, &enc_pms);
4516     if (rv != SECSuccess) {
4517 	ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
4518 	goto loser;
4519     }
4520 
4521     rv = ssl3_InitPendingCipherSpec(ss,  pms);
4522     PK11_FreeSymKey(pms); pms = NULL;
4523 
4524     if (rv != SECSuccess) {
4525 	ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
4526 	goto loser;
4527     }
4528 
4529     rv = ssl3_AppendHandshakeHeader(ss, client_key_exchange,
4530 				    isTLS ? enc_pms.len + 2 : enc_pms.len);
4531     if (rv != SECSuccess) {
4532 	goto loser;	/* err set by ssl3_AppendHandshake* */
4533     }
4534     if (isTLS) {
4535     	rv = ssl3_AppendHandshakeVariable(ss, enc_pms.data, enc_pms.len, 2);
4536     } else {
4537 	rv = ssl3_AppendHandshake(ss, enc_pms.data, enc_pms.len);
4538     }
4539     if (rv != SECSuccess) {
4540 	goto loser;	/* err set by ssl3_AppendHandshake* */
4541     }
4542 
4543     rv = SECSuccess;
4544 
4545 loser:
4546     if (enc_pms.data != NULL) {
4547 	PORT_Free(enc_pms.data);
4548     }
4549     if (pms != NULL) {
4550     	PK11_FreeSymKey(pms);
4551     }
4552     return rv;
4553 }
4554 
4555 /* Called from ssl3_SendClientKeyExchange(). */
4556 /* Presently, this always uses PKCS11.  There is no bypass for this. */
4557 static SECStatus
sendDHClientKeyExchange(sslSocket * ss,SECKEYPublicKey * svrPubKey)4558 sendDHClientKeyExchange(sslSocket * ss, SECKEYPublicKey * svrPubKey)
4559 {
4560     PK11SymKey *	pms 		= NULL;
4561     SECStatus           rv    		= SECFailure;
4562     PRBool              isTLS;
4563     CK_MECHANISM_TYPE	target;
4564 
4565     SECKEYDHParams	dhParam;		/* DH parameters */
4566     SECKEYPublicKey	*pubKey = NULL;		/* Ephemeral DH key */
4567     SECKEYPrivateKey	*privKey = NULL;	/* Ephemeral DH key */
4568 
4569     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
4570     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
4571 
4572     isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
4573 
4574     /* Copy DH parameters from server key */
4575 
4576     if (svrPubKey->keyType != dhKey) {
4577 	PORT_SetError(SEC_ERROR_BAD_KEY);
4578 	goto loser;
4579     }
4580     dhParam.prime.data = svrPubKey->u.dh.prime.data;
4581     dhParam.prime.len = svrPubKey->u.dh.prime.len;
4582     dhParam.base.data = svrPubKey->u.dh.base.data;
4583     dhParam.base.len = svrPubKey->u.dh.base.len;
4584 
4585     /* Generate ephemeral DH keypair */
4586     privKey = SECKEY_CreateDHPrivateKey(&dhParam, &pubKey, NULL);
4587     if (!privKey || !pubKey) {
4588 	    ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL);
4589 	    rv = SECFailure;
4590 	    goto loser;
4591     }
4592     PRINT_BUF(50, (ss, "DH public value:",
4593 					pubKey->u.dh.publicValue.data,
4594 					pubKey->u.dh.publicValue.len));
4595 
4596     if (isTLS) target = CKM_TLS_MASTER_KEY_DERIVE_DH;
4597     else target = CKM_SSL3_MASTER_KEY_DERIVE_DH;
4598 
4599     /* Determine the PMS */
4600 
4601     pms = PK11_PubDerive(privKey, svrPubKey, PR_FALSE, NULL, NULL,
4602 			    CKM_DH_PKCS_DERIVE, target, CKA_DERIVE, 0, NULL);
4603 
4604     if (pms == NULL) {
4605 	ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
4606 	goto loser;
4607     }
4608 
4609     SECKEY_DestroyPrivateKey(privKey);
4610     privKey = NULL;
4611 
4612     rv = ssl3_InitPendingCipherSpec(ss,  pms);
4613     PK11_FreeSymKey(pms); pms = NULL;
4614 
4615     if (rv != SECSuccess) {
4616 	ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
4617 	goto loser;
4618     }
4619 
4620     rv = ssl3_AppendHandshakeHeader(ss, client_key_exchange,
4621 					pubKey->u.dh.publicValue.len + 2);
4622     if (rv != SECSuccess) {
4623 	goto loser;	/* err set by ssl3_AppendHandshake* */
4624     }
4625     rv = ssl3_AppendHandshakeVariable(ss,
4626 					pubKey->u.dh.publicValue.data,
4627 					pubKey->u.dh.publicValue.len, 2);
4628     SECKEY_DestroyPublicKey(pubKey);
4629     pubKey = NULL;
4630 
4631     if (rv != SECSuccess) {
4632 	goto loser;	/* err set by ssl3_AppendHandshake* */
4633     }
4634 
4635     rv = SECSuccess;
4636 
4637 
4638 loser:
4639 
4640     if(pms) PK11_FreeSymKey(pms);
4641     if(privKey) SECKEY_DestroyPrivateKey(privKey);
4642     if(pubKey) SECKEY_DestroyPublicKey(pubKey);
4643     return rv;
4644 }
4645 
4646 
4647 
4648 
4649 
4650 /* Called from ssl3_HandleServerHelloDone(). */
4651 static SECStatus
ssl3_SendClientKeyExchange(sslSocket * ss)4652 ssl3_SendClientKeyExchange(sslSocket *ss)
4653 {
4654     SECKEYPublicKey *	serverKey 	= NULL;
4655     SECStatus 		rv 		= SECFailure;
4656     PRBool              isTLS;
4657 
4658     SSL_TRC(3, ("%d: SSL3[%d]: send client_key_exchange handshake",
4659 		SSL_GETPID(), ss->fd));
4660 
4661     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
4662     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
4663 
4664     if (ss->sec.peerKey == NULL) {
4665 	serverKey = CERT_ExtractPublicKey(ss->sec.peerCert);
4666 	if (serverKey == NULL) {
4667 	    PORT_SetError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
4668 	    return SECFailure;
4669 	}
4670     } else {
4671 	serverKey = ss->sec.peerKey;
4672 	ss->sec.peerKey = NULL; /* we're done with it now */
4673     }
4674 
4675     isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
4676     /* enforce limits on kea key sizes. */
4677     if (ss->ssl3.hs.kea_def->is_limited) {
4678 	int keyLen = SECKEY_PublicKeyStrength(serverKey);	/* bytes */
4679 
4680 	if (keyLen * BPB > ss->ssl3.hs.kea_def->key_size_limit) {
4681 	    if (isTLS)
4682 		(void)SSL3_SendAlert(ss, alert_fatal, export_restriction);
4683 	    else
4684 		(void)ssl3_HandshakeFailure(ss);
4685 	    PORT_SetError(SSL_ERROR_PUB_KEY_SIZE_LIMIT_EXCEEDED);
4686 	    goto loser;
4687 	}
4688     }
4689 
4690     ss->sec.keaType    = ss->ssl3.hs.kea_def->exchKeyType;
4691     ss->sec.keaKeyBits = SECKEY_PublicKeyStrengthInBits(serverKey);
4692 
4693     switch (ss->ssl3.hs.kea_def->exchKeyType) {
4694     case kt_rsa:
4695 	rv = sendRSAClientKeyExchange(ss, serverKey);
4696 	break;
4697 
4698     case kt_dh:
4699 	rv = sendDHClientKeyExchange(ss, serverKey);
4700 	break;
4701 
4702 #ifdef NSS_ENABLE_ECC
4703     case kt_ecdh:
4704 	rv = ssl3_SendECDHClientKeyExchange(ss, serverKey);
4705 	break;
4706 #endif /* NSS_ENABLE_ECC */
4707 
4708     default:
4709 	/* got an unknown or unsupported Key Exchange Algorithm.  */
4710 	SEND_ALERT
4711 	PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
4712 	break;
4713     }
4714 
4715     SSL_TRC(3, ("%d: SSL3[%d]: DONE sending client_key_exchange",
4716 		SSL_GETPID(), ss->fd));
4717 
4718 loser:
4719     if (serverKey)
4720     	SECKEY_DestroyPublicKey(serverKey);
4721     return rv;	/* err code already set. */
4722 }
4723 
4724 /* Called from ssl3_HandleServerHelloDone(). */
4725 static SECStatus
ssl3_SendCertificateVerify(sslSocket * ss)4726 ssl3_SendCertificateVerify(sslSocket *ss)
4727 {
4728     SECStatus     rv		= SECFailure;
4729     PRBool        isTLS;
4730     SECItem       buf           = {siBuffer, NULL, 0};
4731     SSL3Hashes    hashes;
4732 
4733     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
4734     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
4735 
4736     SSL_TRC(3, ("%d: SSL3[%d]: send certificate_verify handshake",
4737 		SSL_GETPID(), ss->fd));
4738 
4739     ssl_GetSpecReadLock(ss);
4740     rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.pwSpec, &hashes, 0);
4741     ssl_ReleaseSpecReadLock(ss);
4742     if (rv != SECSuccess) {
4743 	goto done;	/* err code was set by ssl3_ComputeHandshakeHashes */
4744     }
4745 
4746     isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
4747     rv = ssl3_SignHashes(&hashes, ss->ssl3.clientPrivateKey, &buf, isTLS);
4748     if (rv == SECSuccess) {
4749 	PK11SlotInfo * slot;
4750 	sslSessionID * sid   = ss->sec.ci.sid;
4751 
4752     	/* Remember the info about the slot that did the signing.
4753 	** Later, when doing an SSL restart handshake, verify this.
4754 	** These calls are mere accessors, and can't fail.
4755 	*/
4756 	slot = PK11_GetSlotFromPrivateKey(ss->ssl3.clientPrivateKey);
4757 	sid->u.ssl3.clAuthSeries     = PK11_GetSlotSeries(slot);
4758 	sid->u.ssl3.clAuthSlotID     = PK11_GetSlotID(slot);
4759 	sid->u.ssl3.clAuthModuleID   = PK11_GetModuleID(slot);
4760 	sid->u.ssl3.clAuthValid      = PR_TRUE;
4761 	PK11_FreeSlot(slot);
4762     }
4763     /* If we're doing RSA key exchange, we're all done with the private key
4764      * here.  Diffie-Hellman key exchanges need the client's
4765      * private key for the key exchange.
4766      */
4767     if (ss->ssl3.hs.kea_def->exchKeyType == kt_rsa) {
4768 	SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
4769 	ss->ssl3.clientPrivateKey = NULL;
4770     }
4771     if (rv != SECSuccess) {
4772 	goto done;	/* err code was set by ssl3_SignHashes */
4773     }
4774 
4775     rv = ssl3_AppendHandshakeHeader(ss, certificate_verify, buf.len + 2);
4776     if (rv != SECSuccess) {
4777 	goto done;	/* error code set by AppendHandshake */
4778     }
4779     rv = ssl3_AppendHandshakeVariable(ss, buf.data, buf.len, 2);
4780     if (rv != SECSuccess) {
4781 	goto done;	/* error code set by AppendHandshake */
4782     }
4783 
4784 done:
4785     if (buf.data)
4786 	PORT_Free(buf.data);
4787     return rv;
4788 }
4789 
4790 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
4791  * ssl3 ServerHello message.
4792  * Caller must hold Handshake and RecvBuf locks.
4793  */
4794 static SECStatus
ssl3_HandleServerHello(sslSocket * ss,SSL3Opaque * b,PRUint32 length)4795 ssl3_HandleServerHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
4796 {
4797     sslSessionID *sid		= ss->sec.ci.sid;
4798     PRInt32       temp;		/* allow for consume number failure */
4799     PRBool        suite_found   = PR_FALSE;
4800     int           i;
4801     int           errCode	= SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
4802     SECStatus     rv;
4803     SECItem       sidBytes 	= {siBuffer, NULL, 0};
4804     PRBool        sid_match;
4805     PRBool        isTLS		= PR_FALSE;
4806     SSL3AlertDescription desc   = illegal_parameter;
4807     SSL3ProtocolVersion version;
4808 
4809     SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello handshake",
4810     	SSL_GETPID(), ss->fd));
4811     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
4812     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
4813 
4814     rv = ssl3_InitState(ss);
4815     if (rv != SECSuccess) {
4816 	errCode = PORT_GetError(); /* ssl3_InitState has set the error code. */
4817 	goto alert_loser;
4818     }
4819     if (ss->ssl3.hs.ws != wait_server_hello) {
4820         errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO;
4821 	desc    = unexpected_message;
4822 	goto alert_loser;
4823     }
4824 
4825     temp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
4826     if (temp < 0) {
4827     	goto loser; 	/* alert has been sent */
4828     }
4829     version = (SSL3ProtocolVersion)temp;
4830 
4831     /* this is appropriate since the negotiation is complete, and we only
4832     ** know SSL 3.x.
4833     */
4834     if (MSB(version) != MSB(SSL_LIBRARY_VERSION_3_0)) {
4835     	desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version
4836 						   : handshake_failure;
4837 	goto alert_loser;
4838     }
4839 
4840     rv = ssl3_NegotiateVersion(ss, version);
4841     if (rv != SECSuccess) {
4842     	desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version
4843 						   : handshake_failure;
4844 	errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
4845 	goto alert_loser;
4846     }
4847     isTLS = (ss->version > SSL_LIBRARY_VERSION_3_0);
4848 
4849     rv = ssl3_ConsumeHandshake(
4850 	ss, &ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH, &b, &length);
4851     if (rv != SECSuccess) {
4852     	goto loser; 	/* alert has been sent */
4853     }
4854 
4855     rv = ssl3_ConsumeHandshakeVariable(ss, &sidBytes, 1, &b, &length);
4856     if (rv != SECSuccess) {
4857     	goto loser; 	/* alert has been sent */
4858     }
4859     if (sidBytes.len > SSL3_SESSIONID_BYTES) {
4860 	if (isTLS)
4861 	    desc = decode_error;
4862 	goto alert_loser;	/* malformed. */
4863     }
4864 
4865     /* find selected cipher suite in our list. */
4866     temp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
4867     if (temp < 0) {
4868     	goto loser; 	/* alert has been sent */
4869     }
4870     ssl3_config_match_init(ss);
4871     for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
4872 	ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i];
4873 	if ((temp == suite->cipher_suite) &&
4874 	    (config_match(suite, ss->ssl3.policy, PR_TRUE))) {
4875 	    suite_found = PR_TRUE;
4876 	    break;	/* success */
4877 	}
4878     }
4879     if (!suite_found) {
4880     	desc    = handshake_failure;
4881 	errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
4882 	goto alert_loser;
4883     }
4884     ss->ssl3.hs.cipher_suite = (ssl3CipherSuite)temp;
4885     ss->ssl3.hs.suite_def    = ssl_LookupCipherSuiteDef((ssl3CipherSuite)temp);
4886     PORT_Assert(ss->ssl3.hs.suite_def);
4887     if (!ss->ssl3.hs.suite_def) {
4888     	PORT_SetError(errCode = SEC_ERROR_LIBRARY_FAILURE);
4889 	goto loser;	/* we don't send alerts for our screw-ups. */
4890     }
4891 
4892     /* find selected compression method in our list. */
4893     temp = ssl3_ConsumeHandshakeNumber(ss, 1, &b, &length);
4894     if (temp < 0) {
4895     	goto loser; 	/* alert has been sent */
4896     }
4897     suite_found = PR_FALSE;
4898     for (i = 0; i < compressionMethodsCount; i++) {
4899 	if (temp == compressions[i] &&
4900 	    compressionEnabled(ss, compressions[i]))  {
4901 	    suite_found = PR_TRUE;
4902 	    break;	/* success */
4903     	}
4904     }
4905     if (!suite_found) {
4906     	desc    = handshake_failure;
4907 	errCode = SSL_ERROR_NO_COMPRESSION_OVERLAP;
4908 	goto alert_loser;
4909     }
4910     ss->ssl3.hs.compression = (SSLCompressionMethod)temp;
4911 
4912     /* Note that if !isTLS && length != 0, we do NOT goto alert_loser.
4913      * There are some old SSL 3.0 implementations that do send stuff
4914      * after the end of the server hello, and we deliberately ignore
4915      * such stuff in the interest of maximal interoperability (being
4916      * "generous in what you accept").
4917      */
4918     if (isTLS && length != 0) {
4919 	SECItem extensions;
4920 	rv = ssl3_ConsumeHandshakeVariable(ss, &extensions, 2, &b, &length);
4921 	if (rv != SECSuccess || length != 0)
4922 	    goto alert_loser;
4923 	rv = ssl3_HandleHelloExtensions(ss, &extensions.data, &extensions.len);
4924 	if (rv != SECSuccess)
4925 	    goto alert_loser;
4926     }
4927 
4928     /* Any errors after this point are not "malformed" errors. */
4929     desc    = handshake_failure;
4930 
4931     /* we need to call ssl3_SetupPendingCipherSpec here so we can check the
4932      * key exchange algorithm. */
4933     rv = ssl3_SetupPendingCipherSpec(ss);
4934     if (rv != SECSuccess) {
4935 	goto alert_loser;	/* error code is set. */
4936     }
4937 
4938     /* We may or may not have sent a session id, we may get one back or
4939      * not and if so it may match the one we sent.
4940      * Attempt to restore the master secret to see if this is so...
4941      * Don't consider failure to find a matching SID an error.
4942      */
4943     sid_match = (PRBool)(sidBytes.len > 0 &&
4944 	sidBytes.len == sid->u.ssl3.sessionIDLength &&
4945 	!PORT_Memcmp(sid->u.ssl3.sessionID, sidBytes.data, sidBytes.len));
4946 
4947     if (sid_match &&
4948 	sid->version == ss->version &&
4949 	sid->u.ssl3.cipherSuite == ss->ssl3.hs.cipher_suite) do {
4950 	ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec;
4951 
4952 	SECItem       wrappedMS;   /* wrapped master secret. */
4953 
4954 	ss->sec.authAlgorithm = sid->authAlgorithm;
4955 	ss->sec.authKeyBits   = sid->authKeyBits;
4956 	ss->sec.keaType       = sid->keaType;
4957 	ss->sec.keaKeyBits    = sid->keaKeyBits;
4958 
4959 	/* 3 cases here:
4960 	 * a) key is wrapped (implies using PKCS11)
4961 	 * b) key is unwrapped, but we're still using PKCS11
4962 	 * c) key is unwrapped, and we're bypassing PKCS11.
4963 	 */
4964 	if (sid->u.ssl3.keys.msIsWrapped) {
4965 	    PK11SlotInfo *slot;
4966 	    PK11SymKey *  wrapKey;     /* wrapping key */
4967 	    CK_FLAGS      keyFlags      = 0;
4968 
4969 	    if (ss->opt.bypassPKCS11) {
4970 		/* we cannot restart a non-bypass session in a
4971 		** bypass socket.
4972 		*/
4973 		break;
4974 	    }
4975 	    /* unwrap master secret with PKCS11 */
4976 	    slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID,
4977 				     sid->u.ssl3.masterSlotID);
4978 	    if (slot == NULL) {
4979 		break;		/* not considered an error. */
4980 	    }
4981 	    if (!PK11_IsPresent(slot)) {
4982 		PK11_FreeSlot(slot);
4983 		break;		/* not considered an error. */
4984 	    }
4985 	    wrapKey = PK11_GetWrapKey(slot, sid->u.ssl3.masterWrapIndex,
4986 				      sid->u.ssl3.masterWrapMech,
4987 				      sid->u.ssl3.masterWrapSeries,
4988 				      ss->pkcs11PinArg);
4989 	    PK11_FreeSlot(slot);
4990 	    if (wrapKey == NULL) {
4991 		break;		/* not considered an error. */
4992 	    }
4993 
4994 	    if (ss->version > SSL_LIBRARY_VERSION_3_0) {	/* isTLS */
4995 		keyFlags = CKF_SIGN | CKF_VERIFY;
4996 	    }
4997 
4998 	    wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
4999 	    wrappedMS.len  = sid->u.ssl3.keys.wrapped_master_secret_len;
5000 	    pwSpec->master_secret =
5001 		PK11_UnwrapSymKeyWithFlags(wrapKey, sid->u.ssl3.masterWrapMech,
5002 			    NULL, &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE,
5003 			    CKA_DERIVE, sizeof(SSL3MasterSecret), keyFlags);
5004 	    errCode = PORT_GetError();
5005 	    PK11_FreeSymKey(wrapKey);
5006 	    if (pwSpec->master_secret == NULL) {
5007 		break;	/* errorCode set just after call to UnwrapSymKey. */
5008 	    }
5009 	} else if (ss->opt.bypassPKCS11) {
5010 	    /* MS is not wrapped */
5011 	    wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
5012 	    wrappedMS.len  = sid->u.ssl3.keys.wrapped_master_secret_len;
5013 	    memcpy(pwSpec->raw_master_secret, wrappedMS.data, wrappedMS.len);
5014 	    pwSpec->msItem.data = pwSpec->raw_master_secret;
5015 	    pwSpec->msItem.len  = wrappedMS.len;
5016 	} else {
5017 	    /* We CAN restart a bypass session in a non-bypass socket. */
5018 	    /* need to import the raw master secret to session object */
5019 	    PK11SlotInfo *slot = PK11_GetInternalSlot();
5020 	    wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
5021 	    wrappedMS.len  = sid->u.ssl3.keys.wrapped_master_secret_len;
5022 	    pwSpec->master_secret =
5023 		PK11_ImportSymKey(slot, CKM_SSL3_MASTER_KEY_DERIVE,
5024 				  PK11_OriginUnwrap, CKA_ENCRYPT,
5025 				  &wrappedMS, NULL);
5026 	    PK11_FreeSlot(slot);
5027 	    if (pwSpec->master_secret == NULL) {
5028 		break;
5029 	    }
5030 	}
5031 
5032 	/* Got a Match */
5033 	SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_cache_hits );
5034 
5035 	/* If we sent a session ticket, then this is a stateless resume. */
5036 	if (sid->version > SSL_LIBRARY_VERSION_3_0 &&
5037 	    sid->u.ssl3.sessionTicket.ticket.data != NULL)
5038 	    SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_stateless_resumes );
5039 
5040 	if (ssl3_ExtensionNegotiated(ss, session_ticket_xtn))
5041 	    ss->ssl3.hs.ws = wait_new_session_ticket;
5042 	else
5043 	    ss->ssl3.hs.ws = wait_change_cipher;
5044 
5045 	ss->ssl3.hs.isResuming = PR_TRUE;
5046 
5047 	/* copy the peer cert from the SID */
5048 	if (sid->peerCert != NULL) {
5049 	    ss->sec.peerCert = CERT_DupCertificate(sid->peerCert);
5050 	}
5051 
5052 
5053 	/* NULL value for PMS signifies re-use of the old MS */
5054 	rv = ssl3_InitPendingCipherSpec(ss,  NULL);
5055 	if (rv != SECSuccess) {
5056 	    goto alert_loser;	/* err code was set */
5057 	}
5058 	return SECSuccess;
5059     } while (0);
5060 
5061     if (sid_match)
5062 	SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_cache_not_ok );
5063     else
5064 	SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_cache_misses );
5065 
5066     /* throw the old one away */
5067     sid->u.ssl3.keys.resumable = PR_FALSE;
5068     (*ss->sec.uncache)(sid);
5069     ssl_FreeSID(sid);
5070 
5071     /* get a new sid */
5072     ss->sec.ci.sid = sid = ssl3_NewSessionID(ss, PR_FALSE);
5073     if (sid == NULL) {
5074 	goto alert_loser;	/* memory error is set. */
5075     }
5076 
5077     sid->version = ss->version;
5078     sid->u.ssl3.sessionIDLength = sidBytes.len;
5079     PORT_Memcpy(sid->u.ssl3.sessionID, sidBytes.data, sidBytes.len);
5080 
5081     ss->ssl3.hs.isResuming = PR_FALSE;
5082     ss->ssl3.hs.ws         = wait_server_cert;
5083     return SECSuccess;
5084 
5085 alert_loser:
5086     (void)SSL3_SendAlert(ss, alert_fatal, desc);
5087 
5088 loser:
5089     errCode = ssl_MapLowLevelError(errCode);
5090     return SECFailure;
5091 }
5092 
5093 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
5094  * ssl3 ServerKeyExchange message.
5095  * Caller must hold Handshake and RecvBuf locks.
5096  */
5097 static SECStatus
ssl3_HandleServerKeyExchange(sslSocket * ss,SSL3Opaque * b,PRUint32 length)5098 ssl3_HandleServerKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
5099 {
5100     PRArenaPool *    arena     = NULL;
5101     SECKEYPublicKey *peerKey   = NULL;
5102     PRBool           isTLS;
5103     SECStatus        rv;
5104     int              errCode   = SSL_ERROR_RX_MALFORMED_SERVER_KEY_EXCH;
5105     SSL3AlertDescription desc  = illegal_parameter;
5106     SSL3Hashes       hashes;
5107     SECItem          signature = {siBuffer, NULL, 0};
5108 
5109     SSL_TRC(3, ("%d: SSL3[%d]: handle server_key_exchange handshake",
5110 		SSL_GETPID(), ss->fd));
5111     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
5112     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
5113 
5114     if (ss->ssl3.hs.ws != wait_server_key &&
5115 	ss->ssl3.hs.ws != wait_server_cert) {
5116 	errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH;
5117 	desc    = unexpected_message;
5118 	goto alert_loser;
5119     }
5120     if (ss->sec.peerCert == NULL) {
5121 	errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH;
5122 	desc    = unexpected_message;
5123 	goto alert_loser;
5124     }
5125 
5126     isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
5127 
5128     switch (ss->ssl3.hs.kea_def->exchKeyType) {
5129 
5130     case kt_rsa: {
5131 	SECItem          modulus   = {siBuffer, NULL, 0};
5132 	SECItem          exponent  = {siBuffer, NULL, 0};
5133 
5134     	rv = ssl3_ConsumeHandshakeVariable(ss, &modulus, 2, &b, &length);
5135     	if (rv != SECSuccess) {
5136 	    goto loser;		/* malformed. */
5137 	}
5138     	rv = ssl3_ConsumeHandshakeVariable(ss, &exponent, 2, &b, &length);
5139     	if (rv != SECSuccess) {
5140 	    goto loser;		/* malformed. */
5141 	}
5142     	rv = ssl3_ConsumeHandshakeVariable(ss, &signature, 2, &b, &length);
5143     	if (rv != SECSuccess) {
5144 	    goto loser;		/* malformed. */
5145 	}
5146     	if (length != 0) {
5147 	    if (isTLS)
5148 		desc = decode_error;
5149 	    goto alert_loser;		/* malformed. */
5150 	}
5151 
5152 	/* failures after this point are not malformed handshakes. */
5153 	/* TLS: send decrypt_error if signature failed. */
5154     	desc = isTLS ? decrypt_error : handshake_failure;
5155 
5156     	/*
5157      	 *  check to make sure the hash is signed by right guy
5158      	 */
5159     	rv = ssl3_ComputeExportRSAKeyHash(modulus, exponent,
5160 					  &ss->ssl3.hs.client_random,
5161 					  &ss->ssl3.hs.server_random,
5162 					  &hashes, ss->opt.bypassPKCS11);
5163         if (rv != SECSuccess) {
5164 	    errCode =
5165 	    	ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
5166 	    goto alert_loser;
5167 	}
5168         rv = ssl3_VerifySignedHashes(&hashes, ss->sec.peerCert, &signature,
5169 				    isTLS, ss->pkcs11PinArg);
5170 	if (rv != SECSuccess)  {
5171 	    errCode =
5172 	    	ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
5173 	    goto alert_loser;
5174 	}
5175 
5176 	/*
5177 	 * we really need to build a new key here because we can no longer
5178 	 * ignore calling SECKEY_DestroyPublicKey. Using the key may allocate
5179 	 * pkcs11 slots and ID's.
5180 	 */
5181     	arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
5182 	if (arena == NULL) {
5183 	    goto no_memory;
5184 	}
5185 
5186     	peerKey = PORT_ArenaZNew(arena, SECKEYPublicKey);
5187     	if (peerKey == NULL) {
5188             PORT_FreeArena(arena, PR_FALSE);
5189 	    goto no_memory;
5190 	}
5191 
5192 	peerKey->arena              = arena;
5193 	peerKey->keyType            = rsaKey;
5194 	peerKey->pkcs11Slot         = NULL;
5195 	peerKey->pkcs11ID           = CK_INVALID_HANDLE;
5196 	if (SECITEM_CopyItem(arena, &peerKey->u.rsa.modulus,        &modulus) ||
5197 	    SECITEM_CopyItem(arena, &peerKey->u.rsa.publicExponent, &exponent))
5198 	{
5199             PORT_FreeArena(arena, PR_FALSE);
5200 	    goto no_memory;
5201         }
5202     	ss->sec.peerKey = peerKey;
5203     	ss->ssl3.hs.ws = wait_cert_request;
5204     	return SECSuccess;
5205     }
5206 
5207     case kt_dh: {
5208 	SECItem          dh_p      = {siBuffer, NULL, 0};
5209 	SECItem          dh_g      = {siBuffer, NULL, 0};
5210 	SECItem          dh_Ys     = {siBuffer, NULL, 0};
5211 
5212     	rv = ssl3_ConsumeHandshakeVariable(ss, &dh_p, 2, &b, &length);
5213     	if (rv != SECSuccess) {
5214 	    goto loser;		/* malformed. */
5215 	}
5216     	rv = ssl3_ConsumeHandshakeVariable(ss, &dh_g, 2, &b, &length);
5217     	if (rv != SECSuccess) {
5218 	    goto loser;		/* malformed. */
5219 	}
5220     	rv = ssl3_ConsumeHandshakeVariable(ss, &dh_Ys, 2, &b, &length);
5221     	if (rv != SECSuccess) {
5222 	    goto loser;		/* malformed. */
5223 	}
5224     	rv = ssl3_ConsumeHandshakeVariable(ss, &signature, 2, &b, &length);
5225     	if (rv != SECSuccess) {
5226 	    goto loser;		/* malformed. */
5227 	}
5228     	if (length != 0) {
5229 	    if (isTLS)
5230 		desc = decode_error;
5231 	    goto alert_loser;		/* malformed. */
5232 	}
5233 
5234 	PRINT_BUF(60, (NULL, "Server DH p", dh_p.data, dh_p.len));
5235 	PRINT_BUF(60, (NULL, "Server DH g", dh_g.data, dh_g.len));
5236 	PRINT_BUF(60, (NULL, "Server DH Ys", dh_Ys.data, dh_Ys.len));
5237 
5238 	/* failures after this point are not malformed handshakes. */
5239 	/* TLS: send decrypt_error if signature failed. */
5240     	desc = isTLS ? decrypt_error : handshake_failure;
5241 
5242     	/*
5243      	 *  check to make sure the hash is signed by right guy
5244      	 */
5245     	rv = ssl3_ComputeDHKeyHash(dh_p, dh_g, dh_Ys,
5246 					  &ss->ssl3.hs.client_random,
5247 					  &ss->ssl3.hs.server_random,
5248 					  &hashes, ss->opt.bypassPKCS11);
5249         if (rv != SECSuccess) {
5250 	    errCode =
5251 	    	ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
5252 	    goto alert_loser;
5253 	}
5254         rv = ssl3_VerifySignedHashes(&hashes, ss->sec.peerCert, &signature,
5255 				    isTLS, ss->pkcs11PinArg);
5256 	if (rv != SECSuccess)  {
5257 	    errCode =
5258 	    	ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
5259 	    goto alert_loser;
5260 	}
5261 
5262 	/*
5263 	 * we really need to build a new key here because we can no longer
5264 	 * ignore calling SECKEY_DestroyPublicKey. Using the key may allocate
5265 	 * pkcs11 slots and ID's.
5266 	 */
5267     	arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
5268 	if (arena == NULL) {
5269 	    goto no_memory;
5270 	}
5271 
5272     	ss->sec.peerKey = peerKey = PORT_ArenaZNew(arena, SECKEYPublicKey);
5273     	if (peerKey == NULL) {
5274 	    goto no_memory;
5275 	}
5276 
5277 	peerKey->arena              = arena;
5278 	peerKey->keyType            = dhKey;
5279 	peerKey->pkcs11Slot         = NULL;
5280 	peerKey->pkcs11ID           = CK_INVALID_HANDLE;
5281 
5282 	if (SECITEM_CopyItem(arena, &peerKey->u.dh.prime,        &dh_p) ||
5283 	    SECITEM_CopyItem(arena, &peerKey->u.dh.base,         &dh_g) ||
5284 	    SECITEM_CopyItem(arena, &peerKey->u.dh.publicValue,  &dh_Ys))
5285 	{
5286             PORT_FreeArena(arena, PR_FALSE);
5287 	    goto no_memory;
5288         }
5289     	ss->sec.peerKey = peerKey;
5290     	ss->ssl3.hs.ws = wait_cert_request;
5291     	return SECSuccess;
5292     }
5293 
5294 #ifdef NSS_ENABLE_ECC
5295     case kt_ecdh:
5296 	rv = ssl3_HandleECDHServerKeyExchange(ss, b, length);
5297 	return rv;
5298 #endif /* NSS_ENABLE_ECC */
5299 
5300     default:
5301     	desc    = handshake_failure;
5302 	errCode = SEC_ERROR_UNSUPPORTED_KEYALG;
5303 	break;		/* goto alert_loser; */
5304     }
5305 
5306 alert_loser:
5307     (void)SSL3_SendAlert(ss, alert_fatal, desc);
5308 loser:
5309     PORT_SetError( errCode );
5310     return SECFailure;
5311 
5312 no_memory:	/* no-memory error has already been set. */
5313     ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
5314     return SECFailure;
5315 }
5316 
5317 
5318 typedef struct dnameNode {
5319     struct dnameNode *next;
5320     SECItem           name;
5321 } dnameNode;
5322 
5323 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
5324  * ssl3 Certificate Request message.
5325  * Caller must hold Handshake and RecvBuf locks.
5326  */
5327 static SECStatus
ssl3_HandleCertificateRequest(sslSocket * ss,SSL3Opaque * b,PRUint32 length)5328 ssl3_HandleCertificateRequest(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
5329 {
5330     PRArenaPool *        arena       = NULL;
5331     dnameNode *          node;
5332     PRInt32              remaining;
5333     PRBool               isTLS       = PR_FALSE;
5334     int                  i;
5335     int                  errCode     = SSL_ERROR_RX_MALFORMED_CERT_REQUEST;
5336     int                  nnames      = 0;
5337     SECStatus            rv;
5338     SSL3AlertDescription desc        = illegal_parameter;
5339     SECItem              cert_types  = {siBuffer, NULL, 0};
5340     CERTDistNames        ca_list;
5341 
5342     SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_request handshake",
5343 		SSL_GETPID(), ss->fd));
5344     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
5345     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
5346 
5347     if (ss->ssl3.hs.ws != wait_cert_request &&
5348     	ss->ssl3.hs.ws != wait_server_key) {
5349 	desc    = unexpected_message;
5350 	errCode = SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST;
5351 	goto alert_loser;
5352     }
5353 
5354     /* clean up anything left from previous handshake. */
5355     if (ss->ssl3.clientCertChain != NULL) {
5356        CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
5357        ss->ssl3.clientCertChain = NULL;
5358     }
5359     if (ss->ssl3.clientCertificate != NULL) {
5360        CERT_DestroyCertificate(ss->ssl3.clientCertificate);
5361        ss->ssl3.clientCertificate = NULL;
5362     }
5363     if (ss->ssl3.clientPrivateKey != NULL) {
5364        SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
5365        ss->ssl3.clientPrivateKey = NULL;
5366     }
5367 
5368     isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
5369     rv = ssl3_ConsumeHandshakeVariable(ss, &cert_types, 1, &b, &length);
5370     if (rv != SECSuccess)
5371     	goto loser;		/* malformed, alert has been sent */
5372 
5373     arena = ca_list.arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
5374     if (arena == NULL)
5375     	goto no_mem;
5376 
5377     remaining = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
5378     if (remaining < 0)
5379     	goto loser;	 	/* malformed, alert has been sent */
5380 
5381     if ((PRUint32)remaining > length)
5382 	goto alert_loser;
5383 
5384     ca_list.head = node = PORT_ArenaZNew(arena, dnameNode);
5385     if (node == NULL)
5386     	goto no_mem;
5387 
5388     while (remaining > 0) {
5389 	PRInt32 len;
5390 
5391 	if (remaining < 2)
5392 	    goto alert_loser;	/* malformed */
5393 
5394 	node->name.len = len = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
5395 	if (len <= 0)
5396 	    goto loser;		/* malformed, alert has been sent */
5397 
5398 	remaining -= 2;
5399 	if (remaining < len)
5400 	    goto alert_loser;	/* malformed */
5401 
5402 	node->name.data = b;
5403 	b         += len;
5404 	length    -= len;
5405 	remaining -= len;
5406 	nnames++;
5407 	if (remaining <= 0)
5408 	    break;		/* success */
5409 
5410 	node->next = PORT_ArenaZNew(arena, dnameNode);
5411 	node = node->next;
5412 	if (node == NULL)
5413 	    goto no_mem;
5414     }
5415 
5416     ca_list.nnames = nnames;
5417     ca_list.names  = PORT_ArenaNewArray(arena, SECItem, nnames);
5418     if (nnames > 0 && ca_list.names == NULL)
5419         goto no_mem;
5420 
5421     for(i = 0, node = (dnameNode*)ca_list.head;
5422 	i < nnames;
5423 	i++, node = node->next) {
5424 	ca_list.names[i] = node->name;
5425     }
5426 
5427     if (length != 0)
5428         goto alert_loser;   	/* malformed */
5429 
5430     desc = no_certificate;
5431     ss->ssl3.hs.ws = wait_hello_done;
5432 
5433     if (ss->getClientAuthData == NULL) {
5434 	rv = SECFailure; /* force it to send a no_certificate alert */
5435     } else {
5436 	/* XXX Should pass cert_types in this call!! */
5437 	rv = (SECStatus)(*ss->getClientAuthData)(ss->getClientAuthDataArg,
5438 						 ss->fd, &ca_list,
5439 						 &ss->ssl3.clientCertificate,
5440 						 &ss->ssl3.clientPrivateKey);
5441     }
5442     switch (rv) {
5443     case SECWouldBlock:	/* getClientAuthData has put up a dialog box. */
5444 	ssl_SetAlwaysBlock(ss);
5445 	break;	/* not an error */
5446 
5447     case SECSuccess:
5448         /* check what the callback function returned */
5449         if ((!ss->ssl3.clientCertificate) || (!ss->ssl3.clientPrivateKey)) {
5450             /* we are missing either the key or cert */
5451             if (ss->ssl3.clientCertificate) {
5452                 /* got a cert, but no key - free it */
5453                 CERT_DestroyCertificate(ss->ssl3.clientCertificate);
5454                 ss->ssl3.clientCertificate = NULL;
5455             }
5456             if (ss->ssl3.clientPrivateKey) {
5457                 /* got a key, but no cert - free it */
5458                 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
5459                 ss->ssl3.clientPrivateKey = NULL;
5460             }
5461             goto send_no_certificate;
5462         }
5463 	/* Setting ssl3.clientCertChain non-NULL will cause
5464 	 * ssl3_HandleServerHelloDone to call SendCertificate.
5465 	 */
5466 	ss->ssl3.clientCertChain = CERT_CertChainFromCert(
5467 					ss->ssl3.clientCertificate,
5468 					certUsageSSLClient, PR_FALSE);
5469 	if (ss->ssl3.clientCertChain == NULL) {
5470 	    if (ss->ssl3.clientCertificate != NULL) {
5471 		CERT_DestroyCertificate(ss->ssl3.clientCertificate);
5472 		ss->ssl3.clientCertificate = NULL;
5473 	    }
5474 	    if (ss->ssl3.clientPrivateKey != NULL) {
5475 		SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
5476 		ss->ssl3.clientPrivateKey = NULL;
5477 	    }
5478 	    goto send_no_certificate;
5479 	}
5480 	break;	/* not an error */
5481 
5482     case SECFailure:
5483     default:
5484 send_no_certificate:
5485 	if (isTLS) {
5486 	    ss->ssl3.sendEmptyCert = PR_TRUE;
5487 	} else {
5488 	    (void)SSL3_SendAlert(ss, alert_warning, no_certificate);
5489 	}
5490 	rv = SECSuccess;
5491 	break;
5492     }
5493     goto done;
5494 
5495 no_mem:
5496     rv = SECFailure;
5497     PORT_SetError(SEC_ERROR_NO_MEMORY);
5498     goto done;
5499 
5500 alert_loser:
5501     if (isTLS && desc == illegal_parameter)
5502     	desc = decode_error;
5503     (void)SSL3_SendAlert(ss, alert_fatal, desc);
5504 loser:
5505     PORT_SetError(errCode);
5506     rv = SECFailure;
5507 done:
5508     if (arena != NULL)
5509     	PORT_FreeArena(arena, PR_FALSE);
5510     return rv;
5511 }
5512 
5513 /*
5514  * attempt to restart the handshake after asynchronously handling
5515  * a request for the client's certificate.
5516  *
5517  * inputs:
5518  *	cert	Client cert chosen by application.
5519  *		Note: ssl takes this reference, and does not bump the
5520  *		reference count.  The caller should drop its reference
5521  *		without calling CERT_DestroyCert after calling this function.
5522  *
5523  *	key	Private key associated with cert.  This function makes a
5524  *		copy of the private key, so the caller remains responsible
5525  *		for destroying its copy after this function returns.
5526  *
5527  *	certChain  DER-encoded certs, client cert and its signers.
5528  *		Note: ssl takes this reference, and does not copy the chain.
5529  *		The caller should drop its reference without destroying the
5530  *		chain.  SSL will free the chain when it is done with it.
5531  *
5532  * Return value: XXX
5533  *
5534  * XXX This code only works on the initial handshake on a connection, XXX
5535  *     It does not work on a subsequent handshake (redo).
5536  *
5537  * Caller holds 1stHandshakeLock.
5538  */
5539 SECStatus
ssl3_RestartHandshakeAfterCertReq(sslSocket * ss,CERTCertificate * cert,SECKEYPrivateKey * key,CERTCertificateList * certChain)5540 ssl3_RestartHandshakeAfterCertReq(sslSocket *         ss,
5541 				CERTCertificate *    cert,
5542 				SECKEYPrivateKey *   key,
5543 				CERTCertificateList *certChain)
5544 {
5545     SECStatus        rv          = SECSuccess;
5546 
5547     if (MSB(ss->version) == MSB(SSL_LIBRARY_VERSION_3_0)) {
5548 	/* XXX This code only works on the initial handshake on a connection,
5549 	** XXX It does not work on a subsequent handshake (redo).
5550 	*/
5551 	if (ss->handshake != 0) {
5552 	    ss->handshake               = ssl_GatherRecord1stHandshake;
5553 	    ss->ssl3.clientCertificate = cert;
5554 	    ss->ssl3.clientCertChain   = certChain;
5555 	    if (key == NULL) {
5556 		(void)SSL3_SendAlert(ss, alert_warning, no_certificate);
5557 		ss->ssl3.clientPrivateKey = NULL;
5558 	    } else {
5559 		ss->ssl3.clientPrivateKey = SECKEY_CopyPrivateKey(key);
5560 	    }
5561 	    ssl_GetRecvBufLock(ss);
5562 	    if (ss->ssl3.hs.msgState.buf != NULL) {
5563 		rv = ssl3_HandleRecord(ss, NULL, &ss->gs.buf);
5564 	    }
5565 	    ssl_ReleaseRecvBufLock(ss);
5566 	}
5567     }
5568     return rv;
5569 }
5570 
5571 
5572 
5573 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
5574  * ssl3 Server Hello Done message.
5575  * Caller must hold Handshake and RecvBuf locks.
5576  */
5577 static SECStatus
ssl3_HandleServerHelloDone(sslSocket * ss)5578 ssl3_HandleServerHelloDone(sslSocket *ss)
5579 {
5580     SECStatus     rv;
5581     SSL3WaitState ws          = ss->ssl3.hs.ws;
5582     PRBool        send_verify = PR_FALSE;
5583 
5584     SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello_done handshake",
5585 		SSL_GETPID(), ss->fd));
5586     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
5587     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
5588 
5589     if (ws != wait_hello_done  &&
5590         ws != wait_server_cert &&
5591 	ws != wait_server_key  &&
5592 	ws != wait_cert_request) {
5593 	SSL3_SendAlert(ss, alert_fatal, unexpected_message);
5594 	PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE);
5595 	return SECFailure;
5596     }
5597 
5598     ssl_GetXmitBufLock(ss);		/*******************************/
5599 
5600     if (ss->ssl3.sendEmptyCert) {
5601 	ss->ssl3.sendEmptyCert = PR_FALSE;
5602 	rv = ssl3_SendEmptyCertificate(ss);
5603 	/* Don't send verify */
5604 	if (rv != SECSuccess) {
5605 	    goto loser;	/* error code is set. */
5606     	}
5607     } else
5608     if (ss->ssl3.clientCertChain  != NULL &&
5609 	ss->ssl3.clientPrivateKey != NULL) {
5610 	send_verify = PR_TRUE;
5611 	rv = ssl3_SendCertificate(ss);
5612 	if (rv != SECSuccess) {
5613 	    goto loser;	/* error code is set. */
5614     	}
5615     }
5616 
5617     rv = ssl3_SendClientKeyExchange(ss);
5618     if (rv != SECSuccess) {
5619     	goto loser;	/* err is set. */
5620     }
5621 
5622     if (send_verify) {
5623 	rv = ssl3_SendCertificateVerify(ss);
5624 	if (rv != SECSuccess) {
5625 	    goto loser;	/* err is set. */
5626         }
5627     }
5628     rv = ssl3_SendChangeCipherSpecs(ss);
5629     if (rv != SECSuccess) {
5630 	goto loser;	/* err code was set. */
5631     }
5632 
5633     rv = ssl3_SendNextProto(ss);
5634     if (rv != SECSuccess) {
5635 	goto loser;	/* err code was set. */
5636     }
5637 
5638     rv = ssl3_SendFinished(ss, 0);
5639     if (rv != SECSuccess) {
5640 	goto loser;	/* err code was set. */
5641     }
5642 
5643     ssl_ReleaseXmitBufLock(ss);		/*******************************/
5644 
5645     if (ssl3_ExtensionNegotiated(ss, session_ticket_xtn))
5646 	ss->ssl3.hs.ws = wait_new_session_ticket;
5647     else
5648 	ss->ssl3.hs.ws = wait_change_cipher;
5649     return SECSuccess;
5650 
5651 loser:
5652     ssl_ReleaseXmitBufLock(ss);
5653     return rv;
5654 }
5655 
5656 /*
5657  * Routines used by servers
5658  */
5659 static SECStatus
ssl3_SendHelloRequest(sslSocket * ss)5660 ssl3_SendHelloRequest(sslSocket *ss)
5661 {
5662     SECStatus rv;
5663 
5664     SSL_TRC(3, ("%d: SSL3[%d]: send hello_request handshake", SSL_GETPID(),
5665 		ss->fd));
5666 
5667     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
5668     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
5669 
5670     rv = ssl3_AppendHandshakeHeader(ss, hello_request, 0);
5671     if (rv != SECSuccess) {
5672 	return rv;	/* err set by AppendHandshake */
5673     }
5674     rv = ssl3_FlushHandshake(ss, 0);
5675     if (rv != SECSuccess) {
5676 	return rv;	/* error code set by ssl3_FlushHandshake */
5677     }
5678     ss->ssl3.hs.ws = wait_client_hello;
5679     return SECSuccess;
5680 }
5681 
5682 /* Sets memory error when returning NULL.
5683  * Called from:
5684  *	ssl3_SendClientHello()
5685  *	ssl3_HandleServerHello()
5686  *	ssl3_HandleClientHello()
5687  *	ssl3_HandleV2ClientHello()
5688  */
5689 sslSessionID *
ssl3_NewSessionID(sslSocket * ss,PRBool is_server)5690 ssl3_NewSessionID(sslSocket *ss, PRBool is_server)
5691 {
5692     sslSessionID *sid;
5693 
5694     sid = PORT_ZNew(sslSessionID);
5695     if (sid == NULL)
5696     	return sid;
5697 
5698     sid->peerID		= (ss->peerID == NULL) ? NULL : PORT_Strdup(ss->peerID);
5699     sid->urlSvrName	= (ss->url    == NULL) ? NULL : PORT_Strdup(ss->url);
5700     sid->addr           = ss->sec.ci.peer;
5701     sid->port           = ss->sec.ci.port;
5702     sid->references     = 1;
5703     sid->cached         = never_cached;
5704     sid->version        = ss->version;
5705 
5706     sid->u.ssl3.keys.resumable = PR_TRUE;
5707     sid->u.ssl3.policy         = SSL_ALLOWED;
5708     sid->u.ssl3.clientWriteKey = NULL;
5709     sid->u.ssl3.serverWriteKey = NULL;
5710 
5711     if (is_server) {
5712 	SECStatus rv;
5713 	int       pid = SSL_GETPID();
5714 
5715 	sid->u.ssl3.sessionIDLength = SSL3_SESSIONID_BYTES;
5716 	sid->u.ssl3.sessionID[0]    = (pid >> 8) & 0xff;
5717 	sid->u.ssl3.sessionID[1]    =  pid       & 0xff;
5718 	rv = PK11_GenerateRandom(sid->u.ssl3.sessionID + 2,
5719 	                         SSL3_SESSIONID_BYTES -2);
5720 	if (rv != SECSuccess) {
5721 	    ssl_FreeSID(sid);
5722 	    ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
5723 	    return NULL;
5724     	}
5725     }
5726     return sid;
5727 }
5728 
5729 /* Called from:  ssl3_HandleClientHello, ssl3_HandleV2ClientHello */
5730 static SECStatus
ssl3_SendServerHelloSequence(sslSocket * ss)5731 ssl3_SendServerHelloSequence(sslSocket *ss)
5732 {
5733     const ssl3KEADef *kea_def;
5734     SECStatus         rv;
5735 
5736     SSL_TRC(3, ("%d: SSL3[%d]: begin send server_hello sequence",
5737 		SSL_GETPID(), ss->fd));
5738 
5739     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
5740     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
5741 
5742     rv = ssl3_SendServerHello(ss);
5743     if (rv != SECSuccess) {
5744 	return rv;	/* err code is set. */
5745     }
5746     rv = ssl3_SendCertificate(ss);
5747     if (rv != SECSuccess) {
5748 	return rv;	/* error code is set. */
5749     }
5750     /* We have to do this after the call to ssl3_SendServerHello,
5751      * because kea_def is set up by ssl3_SendServerHello().
5752      */
5753     kea_def = ss->ssl3.hs.kea_def;
5754     ss->ssl3.hs.usedStepDownKey = PR_FALSE;
5755 
5756     if (kea_def->is_limited && kea_def->exchKeyType == kt_rsa) {
5757 	/* see if we can legally use the key in the cert. */
5758 	int keyLen;  /* bytes */
5759 
5760 	keyLen = PK11_GetPrivateModulusLen(
5761 			    ss->serverCerts[kea_def->exchKeyType].SERVERKEY);
5762 
5763 	if (keyLen > 0 &&
5764 	    keyLen * BPB <= kea_def->key_size_limit ) {
5765 	    /* XXX AND cert is not signing only!! */
5766 	    /* just fall through and use it. */
5767 	} else if (ss->stepDownKeyPair != NULL) {
5768 	    ss->ssl3.hs.usedStepDownKey = PR_TRUE;
5769 	    rv = ssl3_SendServerKeyExchange(ss);
5770 	    if (rv != SECSuccess) {
5771 		return rv;	/* err code was set. */
5772 	    }
5773 	} else {
5774 #ifndef HACKED_EXPORT_SERVER
5775 	    PORT_SetError(SSL_ERROR_PUB_KEY_SIZE_LIMIT_EXCEEDED);
5776 	    return rv;
5777 #endif
5778 	}
5779 #ifdef NSS_ENABLE_ECC
5780     } else if ((kea_def->kea == kea_ecdhe_rsa) ||
5781 	       (kea_def->kea == kea_ecdhe_ecdsa)) {
5782 	rv = ssl3_SendServerKeyExchange(ss);
5783 	if (rv != SECSuccess) {
5784 	    return rv;	/* err code was set. */
5785 	}
5786 #endif /* NSS_ENABLE_ECC */
5787     }
5788 
5789     if (ss->opt.requestCertificate) {
5790 	rv = ssl3_SendCertificateRequest(ss);
5791 	if (rv != SECSuccess) {
5792 	    return rv;		/* err code is set. */
5793 	}
5794     }
5795     rv = ssl3_SendServerHelloDone(ss);
5796     if (rv != SECSuccess) {
5797 	return rv;		/* err code is set. */
5798     }
5799 
5800     ss->ssl3.hs.ws = (ss->opt.requestCertificate) ? wait_client_cert
5801                                                : wait_client_key;
5802     return SECSuccess;
5803 }
5804 
5805 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
5806  * ssl3 Client Hello message.
5807  * Caller must hold Handshake and RecvBuf locks.
5808  */
5809 static SECStatus
ssl3_HandleClientHello(sslSocket * ss,SSL3Opaque * b,PRUint32 length)5810 ssl3_HandleClientHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
5811 {
5812     sslSessionID *      sid      = NULL;
5813     PRInt32		tmp;
5814     unsigned int        i;
5815     int                 j;
5816     SECStatus           rv;
5817     int                 errCode  = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
5818     SSL3AlertDescription desc    = illegal_parameter;
5819     SSL3AlertLevel      level    = alert_fatal;
5820     SSL3ProtocolVersion version;
5821     SECItem             sidBytes = {siBuffer, NULL, 0};
5822     SECItem             suites   = {siBuffer, NULL, 0};
5823     SECItem             comps    = {siBuffer, NULL, 0};
5824     PRBool              haveSpecWriteLock = PR_FALSE;
5825     PRBool              haveXmitBufLock   = PR_FALSE;
5826 
5827     SSL_TRC(3, ("%d: SSL3[%d]: handle client_hello handshake",
5828     	SSL_GETPID(), ss->fd));
5829 
5830     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
5831     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
5832 
5833     /* Get peer name of client */
5834     rv = ssl_GetPeerInfo(ss);
5835     if (rv != SECSuccess) {
5836 	return rv;		/* error code is set. */
5837     }
5838 
5839     /* We might be starting session renegotiation in which case we should
5840      * clear previous state.
5841      */
5842     PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData));
5843     ss->statelessResume = PR_FALSE;
5844 
5845     rv = ssl3_InitState(ss);
5846     if (rv != SECSuccess) {
5847 	return rv;		/* ssl3_InitState has set the error code. */
5848     }
5849 
5850     if ((ss->ssl3.hs.ws != wait_client_hello) &&
5851 	(ss->ssl3.hs.ws != idle_handshake)) {
5852 	desc    = unexpected_message;
5853 	errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO;
5854 	goto alert_loser;
5855     }
5856     if (ss->ssl3.hs.ws == idle_handshake  &&
5857     	ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) {
5858 	desc    = no_renegotiation;
5859 	level   = alert_warning;
5860 	errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED;
5861 	goto alert_loser;
5862     }
5863 
5864     tmp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
5865     if (tmp < 0)
5866 	goto loser;		/* malformed, alert already sent */
5867     ss->clientHelloVersion = version = (SSL3ProtocolVersion)tmp;
5868     rv = ssl3_NegotiateVersion(ss, version);
5869     if (rv != SECSuccess) {
5870     	desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version
5871 	                                           : handshake_failure;
5872 	errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
5873 	goto alert_loser;
5874     }
5875 
5876     /* grab the client random data. */
5877     rv = ssl3_ConsumeHandshake(
5878 	ss, &ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH, &b, &length);
5879     if (rv != SECSuccess) {
5880 	goto loser;		/* malformed */
5881     }
5882 
5883     /* grab the client's SID, if present. */
5884     rv = ssl3_ConsumeHandshakeVariable(ss, &sidBytes, 1, &b, &length);
5885     if (rv != SECSuccess) {
5886 	goto loser;		/* malformed */
5887     }
5888 
5889     /* grab the list of cipher suites. */
5890     rv = ssl3_ConsumeHandshakeVariable(ss, &suites, 2, &b, &length);
5891     if (rv != SECSuccess) {
5892 	goto loser;		/* malformed */
5893     }
5894 
5895     /* grab the list of compression methods. */
5896     rv = ssl3_ConsumeHandshakeVariable(ss, &comps, 1, &b, &length);
5897     if (rv != SECSuccess) {
5898 	goto loser;		/* malformed */
5899     }
5900 
5901     desc = handshake_failure;
5902 
5903     /* Handle TLS hello extensions for SSL3 & TLS. We do not know if
5904      * we are restarting a previous session until extensions have been
5905      * parsed, since we might have received a SessionTicket extension.
5906      * Note: we allow extensions even when negotiating SSL3 for the sake
5907      * of interoperability (and backwards compatibility).
5908      */
5909 
5910     if (length) {
5911 	/* Get length of hello extensions */
5912 	PRInt32 extension_length;
5913 	extension_length = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
5914 	if (extension_length < 0) {
5915 	    goto loser;				/* alert already sent */
5916 	}
5917 	if (extension_length != length) {
5918 	    ssl3_DecodeError(ss);		/* send alert */
5919 	    goto loser;
5920 	}
5921 	rv = ssl3_HandleHelloExtensions(ss, &b, &length);
5922 	if (rv != SECSuccess) {
5923 	    goto loser;		/* malformed */
5924 	}
5925     }
5926 
5927     /* We do stateful resumes only if either of the following
5928      * conditions are satisfied: (1) the client does not support the
5929      * session ticket extension, or (2) the client support the session
5930      * ticket extension, but sent an empty ticket.
5931      */
5932     if (!ssl3_ExtensionNegotiated(ss, session_ticket_xtn) ||
5933 	ss->xtnData.emptySessionTicket) {
5934 	if (sidBytes.len > 0 && !ss->opt.noCache) {
5935 	    SSL_TRC(7, ("%d: SSL3[%d]: server, lookup client session-id for 0x%08x%08x%08x%08x",
5936 			SSL_GETPID(), ss->fd, ss->sec.ci.peer.pr_s6_addr32[0],
5937 			ss->sec.ci.peer.pr_s6_addr32[1],
5938 			ss->sec.ci.peer.pr_s6_addr32[2],
5939 			ss->sec.ci.peer.pr_s6_addr32[3]));
5940 	    if (ssl_sid_lookup) {
5941 		sid = (*ssl_sid_lookup)(&ss->sec.ci.peer, sidBytes.data,
5942 					sidBytes.len, ss->dbHandle);
5943 	    } else {
5944 		errCode = SSL_ERROR_SERVER_CACHE_NOT_CONFIGURED;
5945 		goto loser;
5946 	    }
5947 	}
5948     } else if (ss->statelessResume) {
5949 	/* Fill in the client's session ID if doing a stateless resume.
5950 	 * (When doing stateless resumes, server echos client's SessionID.)
5951 	 */
5952 	sid = ss->sec.ci.sid;
5953 	PORT_Assert(sid != NULL);  /* Should have already been filled in.*/
5954 
5955 	if (sidBytes.len > 0 && sidBytes.len <= SSL3_SESSIONID_BYTES) {
5956 	    sid->u.ssl3.sessionIDLength = sidBytes.len;
5957 	    PORT_Memcpy(sid->u.ssl3.sessionID, sidBytes.data,
5958 		sidBytes.len);
5959 	    sid->u.ssl3.sessionIDLength = sidBytes.len;
5960 	} else {
5961 	    sid->u.ssl3.sessionIDLength = 0;
5962 	}
5963 	ss->sec.ci.sid = NULL;
5964     }
5965 
5966     /* We only send a session ticket extension if the client supports
5967      * the extension and we are unable to do either a stateful or
5968      * stateless resume.
5969      *
5970      * TODO: send a session ticket if performing a stateful
5971      * resumption.  (As per RFC4507, a server may issue a session
5972      * ticket while doing a (stateless or stateful) session resume,
5973      * but OpenSSL-0.9.8g does not accept session tickets while
5974      * resuming.)
5975      */
5976     if (ssl3_ExtensionNegotiated(ss, session_ticket_xtn) && sid == NULL) {
5977 	ssl3_RegisterServerHelloExtensionSender(ss,
5978 	    session_ticket_xtn, ssl3_SendSessionTicketXtn);
5979     }
5980 
5981     if (sid != NULL) {
5982 	/* We've found a session cache entry for this client.
5983 	 * Now, if we're going to require a client-auth cert,
5984 	 * and we don't already have this client's cert in the session cache,
5985 	 * and this is the first handshake on this connection (not a redo),
5986 	 * then drop this old cache entry and start a new session.
5987 	 */
5988 	if ((sid->peerCert == NULL) && ss->opt.requestCertificate &&
5989 	    ((ss->opt.requireCertificate == SSL_REQUIRE_ALWAYS) ||
5990 	     (ss->opt.requireCertificate == SSL_REQUIRE_NO_ERROR) ||
5991 	     ((ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE)
5992 	      && !ss->firstHsDone))) {
5993 
5994 	    SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_not_ok );
5995 	    ss->sec.uncache(sid);
5996 	    ssl_FreeSID(sid);
5997 	    sid = NULL;
5998 	}
5999     }
6000 
6001 #ifdef NSS_ENABLE_ECC
6002     /* Disable any ECC cipher suites for which we have no cert. */
6003     ssl3_FilterECCipherSuitesByServerCerts(ss);
6004 #endif
6005 
6006 #ifdef PARANOID
6007     /* Look for a matching cipher suite. */
6008     j = ssl3_config_match_init(ss);
6009     if (j <= 0) {		/* no ciphers are working/supported by PK11 */
6010     	errCode = PORT_GetError();	/* error code is already set. */
6011 	goto alert_loser;
6012     }
6013 #endif
6014 
6015     /* If we already have a session for this client, be sure to pick the
6016     ** same cipher suite and compression method we picked before.
6017     ** This is not a loop, despite appearances.
6018     */
6019     if (sid) do {
6020 	ssl3CipherSuiteCfg *suite;
6021 
6022 	/* Check that the cached compression method is still enabled. */
6023 	if (!compressionEnabled(ss, sid->u.ssl3.compression))
6024 	    break;
6025 
6026 	/* Check that the cached compression method is in the client's list */
6027 	for (i = 0; i < comps.len; i++) {
6028 	    if (comps.data[i] == sid->u.ssl3.compression)
6029 		break;
6030 	}
6031 	if (i == comps.len)
6032 	    break;
6033 
6034 	suite = ss->cipherSuites;
6035 	/* Find the entry for the cipher suite used in the cached session. */
6036 	for (j = ssl_V3_SUITES_IMPLEMENTED; j > 0; --j, ++suite) {
6037 	    if (suite->cipher_suite == sid->u.ssl3.cipherSuite)
6038 		break;
6039 	}
6040 	PORT_Assert(j > 0);
6041 	if (j <= 0)
6042 	    break;
6043 #ifdef PARANOID
6044 	/* Double check that the cached cipher suite is still enabled,
6045 	 * implemented, and allowed by policy.  Might have been disabled.
6046 	 * The product policy won't change during the process lifetime.
6047 	 * Implemented ("isPresent") shouldn't change for servers.
6048 	 */
6049 	if (!config_match(suite, ss->ssl3.policy, PR_TRUE))
6050 	    break;
6051 #else
6052 	if (!suite->enabled)
6053 	    break;
6054 #endif
6055 	/* Double check that the cached cipher suite is in the client's list */
6056 	for (i = 0; i < suites.len; i += 2) {
6057 	    if ((suites.data[i]     == MSB(suite->cipher_suite)) &&
6058 	        (suites.data[i + 1] == LSB(suite->cipher_suite))) {
6059 
6060 		ss->ssl3.hs.cipher_suite = suite->cipher_suite;
6061 		ss->ssl3.hs.suite_def =
6062 		    ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite);
6063 
6064 		/* Use the cached compression method. */
6065 		ss->ssl3.hs.compression = sid->u.ssl3.compression;
6066 		goto compression_found;
6067 	    }
6068 	}
6069     } while (0);
6070 
6071     /* START A NEW SESSION */
6072 
6073 #ifndef PARANOID
6074     /* Look for a matching cipher suite. */
6075     j = ssl3_config_match_init(ss);
6076     if (j <= 0) {		/* no ciphers are working/supported by PK11 */
6077     	errCode = PORT_GetError();	/* error code is already set. */
6078 	goto alert_loser;
6079     }
6080 #endif
6081 
6082     /* Select a cipher suite.
6083     ** NOTE: This suite selection algorithm should be the same as the one in
6084     ** ssl3_HandleV2ClientHello().
6085     */
6086     for (j = 0; j < ssl_V3_SUITES_IMPLEMENTED; j++) {
6087 	ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j];
6088 	if (!config_match(suite, ss->ssl3.policy, PR_TRUE))
6089 	    continue;
6090 	for (i = 0; i < suites.len; i += 2) {
6091 	    if ((suites.data[i]     == MSB(suite->cipher_suite)) &&
6092 	        (suites.data[i + 1] == LSB(suite->cipher_suite))) {
6093 
6094 		ss->ssl3.hs.cipher_suite = suite->cipher_suite;
6095 		ss->ssl3.hs.suite_def =
6096 		    ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite);
6097 		goto suite_found;
6098 	    }
6099 	}
6100     }
6101     errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
6102     goto alert_loser;
6103 
6104 suite_found:
6105     /* Look for a matching compression algorithm. */
6106     for (i = 0; i < comps.len; i++) {
6107 	for (j = 0; j < compressionMethodsCount; j++) {
6108 	    if (comps.data[i] == compressions[j] &&
6109 		compressionEnabled(ss, compressions[j])) {
6110 		ss->ssl3.hs.compression =
6111 					(SSLCompressionMethod)compressions[j];
6112 		goto compression_found;
6113 	    }
6114 	}
6115     }
6116     errCode = SSL_ERROR_NO_COMPRESSION_OVERLAP;
6117     				/* null compression must be supported */
6118     goto alert_loser;
6119 
6120 compression_found:
6121     suites.data = NULL;
6122     comps.data = NULL;
6123 
6124     ss->sec.send = ssl3_SendApplicationData;
6125 
6126     /* If there are any failures while processing the old sid,
6127      * we don't consider them to be errors.  Instead, We just behave
6128      * as if the client had sent us no sid to begin with, and make a new one.
6129      */
6130     if (sid != NULL) do {
6131 	ssl3CipherSpec *pwSpec;
6132 	SECItem         wrappedMS;  	/* wrapped key */
6133 
6134 	if (sid->version != ss->version  ||
6135 	    sid->u.ssl3.cipherSuite != ss->ssl3.hs.cipher_suite) {
6136 	    break;	/* not an error */
6137 	}
6138 
6139 	if (ss->sec.ci.sid) {
6140 	    ss->sec.uncache(ss->sec.ci.sid);
6141 	    PORT_Assert(ss->sec.ci.sid != sid);  /* should be impossible, but ... */
6142 	    if (ss->sec.ci.sid != sid) {
6143 		ssl_FreeSID(ss->sec.ci.sid);
6144 	    }
6145 	    ss->sec.ci.sid = NULL;
6146 	}
6147 	/* we need to resurrect the master secret.... */
6148 
6149 	ssl_GetSpecWriteLock(ss);  haveSpecWriteLock = PR_TRUE;
6150 	pwSpec = ss->ssl3.pwSpec;
6151 	if (sid->u.ssl3.keys.msIsWrapped) {
6152 	    PK11SymKey *    wrapKey; 	/* wrapping key */
6153 	    CK_FLAGS        keyFlags      = 0;
6154 	    if (ss->opt.bypassPKCS11) {
6155 		/* we cannot restart a non-bypass session in a
6156 		** bypass socket.
6157 		*/
6158 		break;
6159 	    }
6160 
6161 	    wrapKey = getWrappingKey(ss, NULL, sid->u.ssl3.exchKeyType,
6162 				     sid->u.ssl3.masterWrapMech,
6163 				     ss->pkcs11PinArg);
6164 	    if (!wrapKey) {
6165 		/* we have a SID cache entry, but no wrapping key for it??? */
6166 		break;
6167 	    }
6168 
6169 	    if (ss->version > SSL_LIBRARY_VERSION_3_0) {	/* isTLS */
6170 		keyFlags = CKF_SIGN | CKF_VERIFY;
6171 	    }
6172 
6173 	    wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
6174 	    wrappedMS.len  = sid->u.ssl3.keys.wrapped_master_secret_len;
6175 
6176 	    /* unwrap the master secret. */
6177 	    pwSpec->master_secret =
6178 		PK11_UnwrapSymKeyWithFlags(wrapKey, sid->u.ssl3.masterWrapMech,
6179 			    NULL, &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE,
6180 			    CKA_DERIVE, sizeof(SSL3MasterSecret), keyFlags);
6181 	    PK11_FreeSymKey(wrapKey);
6182 	    if (pwSpec->master_secret == NULL) {
6183 		break;	/* not an error */
6184 	    }
6185 	} else if (ss->opt.bypassPKCS11) {
6186 	    wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
6187 	    wrappedMS.len  = sid->u.ssl3.keys.wrapped_master_secret_len;
6188 	    memcpy(pwSpec->raw_master_secret, wrappedMS.data, wrappedMS.len);
6189 	    pwSpec->msItem.data = pwSpec->raw_master_secret;
6190 	    pwSpec->msItem.len  = wrappedMS.len;
6191 	} else {
6192 	    /* We CAN restart a bypass session in a non-bypass socket. */
6193 	    /* need to import the raw master secret to session object */
6194 	    PK11SlotInfo * slot;
6195 	    wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
6196 	    wrappedMS.len  = sid->u.ssl3.keys.wrapped_master_secret_len;
6197 	    slot = PK11_GetInternalSlot();
6198 	    pwSpec->master_secret =
6199 		PK11_ImportSymKey(slot, CKM_SSL3_MASTER_KEY_DERIVE,
6200 				  PK11_OriginUnwrap, CKA_ENCRYPT, &wrappedMS,
6201 				  NULL);
6202 	    PK11_FreeSlot(slot);
6203 	    if (pwSpec->master_secret == NULL) {
6204 		break;	/* not an error */
6205 	    }
6206 	}
6207 	ss->sec.ci.sid = sid;
6208 	if (sid->peerCert != NULL) {
6209 	    ss->sec.peerCert = CERT_DupCertificate(sid->peerCert);
6210 	}
6211 
6212 	/*
6213 	 * Old SID passed all tests, so resume this old session.
6214 	 *
6215 	 * XXX make sure compression still matches
6216 	 */
6217 	SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_hits );
6218 	if (ss->statelessResume)
6219 	    SSL_AtomicIncrementLong(& ssl3stats.hch_sid_stateless_resumes );
6220 	ss->ssl3.hs.isResuming = PR_TRUE;
6221 
6222         ss->sec.authAlgorithm = sid->authAlgorithm;
6223 	ss->sec.authKeyBits   = sid->authKeyBits;
6224 	ss->sec.keaType       = sid->keaType;
6225 	ss->sec.keaKeyBits    = sid->keaKeyBits;
6226 
6227 	/* server sids don't remember the server cert we previously sent,
6228 	** but they do remember the kea type we originally used, so we
6229 	** can locate it again, provided that the current ssl socket
6230 	** has had its server certs configured the same as the previous one.
6231 	*/
6232 	ss->sec.localCert     =
6233 		CERT_DupCertificate(ss->serverCerts[sid->keaType].serverCert);
6234 
6235 	ssl_GetXmitBufLock(ss); haveXmitBufLock = PR_TRUE;
6236 
6237 	rv = ssl3_SendServerHello(ss);
6238 	if (rv != SECSuccess) {
6239 	    errCode = PORT_GetError();
6240 	    goto loser;
6241 	}
6242 
6243 	if (haveSpecWriteLock) {
6244 	    ssl_ReleaseSpecWriteLock(ss);
6245 	    haveSpecWriteLock = PR_FALSE;
6246 	}
6247 
6248 	/* NULL value for PMS signifies re-use of the old MS */
6249 	rv = ssl3_InitPendingCipherSpec(ss,  NULL);
6250 	if (rv != SECSuccess) {
6251 	    errCode = PORT_GetError();
6252 	    goto loser;
6253 	}
6254 
6255 	rv = ssl3_SendChangeCipherSpecs(ss);
6256 	if (rv != SECSuccess) {
6257 	    errCode = PORT_GetError();
6258 	    goto loser;
6259 	}
6260 	rv = ssl3_SendFinished(ss, 0);
6261 	ss->ssl3.hs.ws = wait_change_cipher;
6262 	if (rv != SECSuccess) {
6263 	    errCode = PORT_GetError();
6264 	    goto loser;
6265 	}
6266 
6267 	if (haveXmitBufLock) {
6268 	    ssl_ReleaseXmitBufLock(ss);
6269 	    haveXmitBufLock = PR_FALSE;
6270 	}
6271 
6272         return SECSuccess;
6273     } while (0);
6274 
6275     if (haveSpecWriteLock) {
6276 	ssl_ReleaseSpecWriteLock(ss);
6277 	haveSpecWriteLock = PR_FALSE;
6278     }
6279 
6280     if (sid) { 	/* we had a sid, but it's no longer valid, free it */
6281 	SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_not_ok );
6282 	ss->sec.uncache(sid);
6283 	ssl_FreeSID(sid);
6284 	sid = NULL;
6285     }
6286     SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_misses );
6287 
6288     sid = ssl3_NewSessionID(ss, PR_TRUE);
6289     if (sid == NULL) {
6290 	errCode = PORT_GetError();
6291 	goto loser;	/* memory error is set. */
6292     }
6293     ss->sec.ci.sid = sid;
6294 
6295     ss->ssl3.hs.isResuming = PR_FALSE;
6296     ssl_GetXmitBufLock(ss);
6297     rv = ssl3_SendServerHelloSequence(ss);
6298     ssl_ReleaseXmitBufLock(ss);
6299     if (rv != SECSuccess) {
6300 	errCode = PORT_GetError();
6301 	goto loser;
6302     }
6303 
6304     if (haveXmitBufLock) {
6305 	ssl_ReleaseXmitBufLock(ss);
6306 	haveXmitBufLock = PR_FALSE;
6307     }
6308 
6309     return SECSuccess;
6310 
6311 alert_loser:
6312     if (haveSpecWriteLock) {
6313 	ssl_ReleaseSpecWriteLock(ss);
6314 	haveSpecWriteLock = PR_FALSE;
6315     }
6316     (void)SSL3_SendAlert(ss, level, desc);
6317     /* FALLTHRU */
6318 loser:
6319     if (haveSpecWriteLock) {
6320 	ssl_ReleaseSpecWriteLock(ss);
6321 	haveSpecWriteLock = PR_FALSE;
6322     }
6323 
6324     if (haveXmitBufLock) {
6325 	ssl_ReleaseXmitBufLock(ss);
6326 	haveXmitBufLock = PR_FALSE;
6327     }
6328 
6329     PORT_SetError(errCode);
6330     return SECFailure;
6331 }
6332 
6333 /*
6334  * ssl3_HandleV2ClientHello is used when a V2 formatted hello comes
6335  * in asking to use the V3 handshake.
6336  * Called from ssl2_HandleClientHelloMessage() in sslcon.c
6337  */
6338 SECStatus
ssl3_HandleV2ClientHello(sslSocket * ss,unsigned char * buffer,int length)6339 ssl3_HandleV2ClientHello(sslSocket *ss, unsigned char *buffer, int length)
6340 {
6341     sslSessionID *      sid 		= NULL;
6342     unsigned char *     suites;
6343     unsigned char *     random;
6344     SSL3ProtocolVersion version;
6345     SECStatus           rv;
6346     int                 i;
6347     int                 j;
6348     int                 sid_length;
6349     int                 suite_length;
6350     int                 rand_length;
6351     int                 errCode  = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
6352     SSL3AlertDescription desc    = handshake_failure;
6353 
6354     SSL_TRC(3, ("%d: SSL3[%d]: handle v2 client_hello", SSL_GETPID(), ss->fd));
6355 
6356     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
6357 
6358     ssl_GetSSL3HandshakeLock(ss);
6359 
6360     PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData));
6361 
6362     rv = ssl3_InitState(ss);
6363     if (rv != SECSuccess) {
6364 	ssl_ReleaseSSL3HandshakeLock(ss);
6365 	return rv;		/* ssl3_InitState has set the error code. */
6366     }
6367 
6368     if (ss->ssl3.hs.ws != wait_client_hello) {
6369 	desc    = unexpected_message;
6370 	errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO;
6371 	goto loser;	/* alert_loser */
6372     }
6373 
6374     version      = (buffer[1] << 8) | buffer[2];
6375     suite_length = (buffer[3] << 8) | buffer[4];
6376     sid_length   = (buffer[5] << 8) | buffer[6];
6377     rand_length  = (buffer[7] << 8) | buffer[8];
6378     ss->clientHelloVersion = version;
6379 
6380     rv = ssl3_NegotiateVersion(ss, version);
6381     if (rv != SECSuccess) {
6382 	/* send back which ever alert client will understand. */
6383     	desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version : handshake_failure;
6384 	errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
6385 	goto alert_loser;
6386     }
6387 
6388     /* if we get a non-zero SID, just ignore it. */
6389     if (length !=
6390         SSL_HL_CLIENT_HELLO_HBYTES + suite_length + sid_length + rand_length) {
6391 	SSL_DBG(("%d: SSL3[%d]: bad v2 client hello message, len=%d should=%d",
6392 		 SSL_GETPID(), ss->fd, length,
6393 		 SSL_HL_CLIENT_HELLO_HBYTES + suite_length + sid_length +
6394 		 rand_length));
6395 	goto loser;	/* malformed */	/* alert_loser */
6396     }
6397 
6398     suites = buffer + SSL_HL_CLIENT_HELLO_HBYTES;
6399     random = suites + suite_length + sid_length;
6400 
6401     if (rand_length < SSL_MIN_CHALLENGE_BYTES ||
6402 	rand_length > SSL_MAX_CHALLENGE_BYTES) {
6403 	goto loser;	/* malformed */	/* alert_loser */
6404     }
6405 
6406     PORT_Assert(SSL_MAX_CHALLENGE_BYTES == SSL3_RANDOM_LENGTH);
6407 
6408     PORT_Memset(&ss->ssl3.hs.client_random, 0, SSL3_RANDOM_LENGTH);
6409     PORT_Memcpy(
6410 	&ss->ssl3.hs.client_random.rand[SSL3_RANDOM_LENGTH - rand_length],
6411 	random, rand_length);
6412 
6413     PRINT_BUF(60, (ss, "client random:", &ss->ssl3.hs.client_random.rand[0],
6414 		   SSL3_RANDOM_LENGTH));
6415 #ifdef NSS_ENABLE_ECC
6416     /* Disable any ECC cipher suites for which we have no cert. */
6417     ssl3_FilterECCipherSuitesByServerCerts(ss);
6418 #endif
6419     i = ssl3_config_match_init(ss);
6420     if (i <= 0) {
6421     	errCode = PORT_GetError();	/* error code is already set. */
6422 	goto alert_loser;
6423     }
6424 
6425     /* Select a cipher suite.
6426     ** NOTE: This suite selection algorithm should be the same as the one in
6427     ** ssl3_HandleClientHello().
6428     */
6429     for (j = 0; j < ssl_V3_SUITES_IMPLEMENTED; j++) {
6430 	ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j];
6431 	if (!config_match(suite, ss->ssl3.policy, PR_TRUE))
6432 	    continue;
6433 	for (i = 0; i < suite_length; i += 3) {
6434 	    if ((suites[i]   == 0) &&
6435 		(suites[i+1] == MSB(suite->cipher_suite)) &&
6436 		(suites[i+2] == LSB(suite->cipher_suite))) {
6437 
6438 		ss->ssl3.hs.cipher_suite = suite->cipher_suite;
6439 		ss->ssl3.hs.suite_def =
6440 		    ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite);
6441 		goto suite_found;
6442 	    }
6443 	}
6444     }
6445     errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
6446     goto alert_loser;
6447 
6448 suite_found:
6449 
6450     ss->ssl3.hs.compression = ssl_compression_null;
6451     ss->sec.send            = ssl3_SendApplicationData;
6452 
6453     /* we don't even search for a cache hit here.  It's just a miss. */
6454     SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_misses );
6455     sid = ssl3_NewSessionID(ss, PR_TRUE);
6456     if (sid == NULL) {
6457     	errCode = PORT_GetError();
6458 	goto loser;	/* memory error is set. */
6459     }
6460     ss->sec.ci.sid = sid;
6461     /* do not worry about memory leak of sid since it now belongs to ci */
6462 
6463     /* We have to update the handshake hashes before we can send stuff */
6464     rv = ssl3_UpdateHandshakeHashes(ss, buffer, length);
6465     if (rv != SECSuccess) {
6466     	errCode = PORT_GetError();
6467 	goto loser;
6468     }
6469 
6470     ssl_GetXmitBufLock(ss);
6471     rv = ssl3_SendServerHelloSequence(ss);
6472     ssl_ReleaseXmitBufLock(ss);
6473     if (rv != SECSuccess) {
6474     	errCode = PORT_GetError();
6475 	goto loser;
6476     }
6477 
6478     /* XXX_1 	The call stack to here is:
6479      * ssl_Do1stHandshake -> ssl2_HandleClientHelloMessage -> here.
6480      * ssl2_HandleClientHelloMessage returns whatever we return here.
6481      * ssl_Do1stHandshake will continue looping if it gets back either
6482      *		SECSuccess or SECWouldBlock.
6483      * SECSuccess is preferable here.  See XXX_1 in sslgathr.c.
6484      */
6485     ssl_ReleaseSSL3HandshakeLock(ss);
6486     return SECSuccess;
6487 
6488 alert_loser:
6489     SSL3_SendAlert(ss, alert_fatal, desc);
6490 loser:
6491     ssl_ReleaseSSL3HandshakeLock(ss);
6492     PORT_SetError(errCode);
6493     return SECFailure;
6494 }
6495 
6496 /* The negotiated version number has been already placed in ss->version.
6497 **
6498 ** Called from:  ssl3_HandleClientHello                     (resuming session),
6499 ** 	ssl3_SendServerHelloSequence <- ssl3_HandleClientHello   (new session),
6500 ** 	ssl3_SendServerHelloSequence <- ssl3_HandleV2ClientHello (new session)
6501 */
6502 static SECStatus
ssl3_SendServerHello(sslSocket * ss)6503 ssl3_SendServerHello(sslSocket *ss)
6504 {
6505     sslSessionID *sid;
6506     SECStatus     rv;
6507     PRUint32      maxBytes = 65535;
6508     PRUint32      length;
6509     PRInt32       extensions_len = 0;
6510 
6511     SSL_TRC(3, ("%d: SSL3[%d]: send server_hello handshake", SSL_GETPID(),
6512 		ss->fd));
6513 
6514     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
6515     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
6516     PORT_Assert( MSB(ss->version) == MSB(SSL_LIBRARY_VERSION_3_0));
6517 
6518     if (MSB(ss->version) != MSB(SSL_LIBRARY_VERSION_3_0)) {
6519 	PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
6520 	return SECFailure;
6521     }
6522 
6523     sid = ss->sec.ci.sid;
6524 
6525     extensions_len = ssl3_CallHelloExtensionSenders(ss, PR_FALSE, maxBytes,
6526 					       &ss->xtnData.serverSenders[0]);
6527     if (extensions_len > 0)
6528     	extensions_len += 2; /* Add sizeof total extension length */
6529 
6530     length = sizeof(SSL3ProtocolVersion) + SSL3_RANDOM_LENGTH + 1 +
6531              ((sid == NULL) ? 0: sid->u.ssl3.sessionIDLength) +
6532 	     sizeof(ssl3CipherSuite) + 1 + extensions_len;
6533     rv = ssl3_AppendHandshakeHeader(ss, server_hello, length);
6534     if (rv != SECSuccess) {
6535 	return rv;	/* err set by AppendHandshake. */
6536     }
6537 
6538     rv = ssl3_AppendHandshakeNumber(ss, ss->version, 2);
6539     if (rv != SECSuccess) {
6540 	return rv;	/* err set by AppendHandshake. */
6541     }
6542     rv = ssl3_GetNewRandom(&ss->ssl3.hs.server_random);
6543     if (rv != SECSuccess) {
6544 	ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
6545 	return rv;
6546     }
6547     rv = ssl3_AppendHandshake(
6548 	ss, &ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH);
6549     if (rv != SECSuccess) {
6550 	return rv;	/* err set by AppendHandshake. */
6551     }
6552 
6553     if (sid)
6554 	rv = ssl3_AppendHandshakeVariable(
6555 	    ss, sid->u.ssl3.sessionID, sid->u.ssl3.sessionIDLength, 1);
6556     else
6557 	rv = ssl3_AppendHandshakeVariable(ss, NULL, 0, 1);
6558     if (rv != SECSuccess) {
6559 	return rv;	/* err set by AppendHandshake. */
6560     }
6561 
6562     rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.cipher_suite, 2);
6563     if (rv != SECSuccess) {
6564 	return rv;	/* err set by AppendHandshake. */
6565     }
6566     rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.compression, 1);
6567     if (rv != SECSuccess) {
6568 	return rv;	/* err set by AppendHandshake. */
6569     }
6570     if (extensions_len) {
6571 	PRInt32 sent_len;
6572 
6573     	extensions_len -= 2;
6574 	rv = ssl3_AppendHandshakeNumber(ss, extensions_len, 2);
6575 	if (rv != SECSuccess)
6576 	    return rv;	/* err set by ssl3_SetupPendingCipherSpec */
6577 	sent_len = ssl3_CallHelloExtensionSenders(ss, PR_TRUE, extensions_len,
6578 					   &ss->xtnData.serverSenders[0]);
6579         PORT_Assert(sent_len == extensions_len);
6580 	if (sent_len != extensions_len) {
6581 	    if (sent_len >= 0)
6582 	    	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
6583 	    return SECFailure;
6584 	}
6585     }
6586     rv = ssl3_SetupPendingCipherSpec(ss);
6587     if (rv != SECSuccess) {
6588 	return rv;	/* err set by ssl3_SetupPendingCipherSpec */
6589     }
6590 
6591     return SECSuccess;
6592 }
6593 
6594 
6595 static SECStatus
ssl3_SendServerKeyExchange(sslSocket * ss)6596 ssl3_SendServerKeyExchange(sslSocket *ss)
6597 {
6598 const ssl3KEADef *     kea_def     = ss->ssl3.hs.kea_def;
6599     SECStatus          rv          = SECFailure;
6600     int                length;
6601     PRBool             isTLS;
6602     SECItem            signed_hash = {siBuffer, NULL, 0};
6603     SSL3Hashes         hashes;
6604     SECKEYPublicKey *  sdPub;	/* public key for step-down */
6605 
6606     SSL_TRC(3, ("%d: SSL3[%d]: send server_key_exchange handshake",
6607 		SSL_GETPID(), ss->fd));
6608 
6609     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
6610     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
6611 
6612     switch (kea_def->exchKeyType) {
6613     case kt_rsa:
6614 	/* Perform SSL Step-Down here. */
6615 	sdPub = ss->stepDownKeyPair->pubKey;
6616 	PORT_Assert(sdPub != NULL);
6617 	if (!sdPub) {
6618 	    PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
6619 	    return SECFailure;
6620 	}
6621     	rv = ssl3_ComputeExportRSAKeyHash(sdPub->u.rsa.modulus,
6622 					  sdPub->u.rsa.publicExponent,
6623 	                                  &ss->ssl3.hs.client_random,
6624 	                                  &ss->ssl3.hs.server_random,
6625 					  &hashes, ss->opt.bypassPKCS11);
6626         if (rv != SECSuccess) {
6627 	    ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
6628 	    return rv;
6629 	}
6630 
6631 	isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
6632 	rv = ssl3_SignHashes(&hashes, ss->serverCerts[kt_rsa].SERVERKEY,
6633 	                     &signed_hash, isTLS);
6634         if (rv != SECSuccess) {
6635 	    goto loser;		/* ssl3_SignHashes has set err. */
6636 	}
6637 	if (signed_hash.data == NULL) {
6638 	    /* how can this happen and rv == SECSuccess ?? */
6639 	    PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
6640 	    goto loser;
6641 	}
6642 	length = 2 + sdPub->u.rsa.modulus.len +
6643 	         2 + sdPub->u.rsa.publicExponent.len +
6644 	         2 + signed_hash.len;
6645 
6646 	rv = ssl3_AppendHandshakeHeader(ss, server_key_exchange, length);
6647 	if (rv != SECSuccess) {
6648 	    goto loser; 	/* err set by AppendHandshake. */
6649 	}
6650 
6651 	rv = ssl3_AppendHandshakeVariable(ss, sdPub->u.rsa.modulus.data,
6652 					  sdPub->u.rsa.modulus.len, 2);
6653 	if (rv != SECSuccess) {
6654 	    goto loser; 	/* err set by AppendHandshake. */
6655 	}
6656 
6657 	rv = ssl3_AppendHandshakeVariable(
6658 				ss, sdPub->u.rsa.publicExponent.data,
6659 				sdPub->u.rsa.publicExponent.len, 2);
6660 	if (rv != SECSuccess) {
6661 	    goto loser; 	/* err set by AppendHandshake. */
6662 	}
6663 
6664 	rv = ssl3_AppendHandshakeVariable(ss, signed_hash.data,
6665 	                                  signed_hash.len, 2);
6666 	if (rv != SECSuccess) {
6667 	    goto loser; 	/* err set by AppendHandshake. */
6668 	}
6669 	PORT_Free(signed_hash.data);
6670 	return SECSuccess;
6671 
6672 #ifdef NSS_ENABLE_ECC
6673     case kt_ecdh: {
6674 	rv = ssl3_SendECDHServerKeyExchange(ss);
6675 	return rv;
6676     }
6677 #endif /* NSS_ENABLE_ECC */
6678 
6679     case kt_dh:
6680     case kt_null:
6681     default:
6682 	PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
6683 	break;
6684     }
6685 loser:
6686     if (signed_hash.data != NULL)
6687     	PORT_Free(signed_hash.data);
6688     return SECFailure;
6689 }
6690 
6691 
6692 static SECStatus
ssl3_SendCertificateRequest(sslSocket * ss)6693 ssl3_SendCertificateRequest(sslSocket *ss)
6694 {
6695     SECItem *      name;
6696     CERTDistNames *ca_list;
6697 const uint8 *      certTypes;
6698     SECItem *      names	= NULL;
6699     SECStatus      rv;
6700     int            length;
6701     int            i;
6702     int            calen	= 0;
6703     int            nnames	= 0;
6704     int            certTypesLength;
6705 
6706     SSL_TRC(3, ("%d: SSL3[%d]: send certificate_request handshake",
6707 		SSL_GETPID(), ss->fd));
6708 
6709     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
6710     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
6711 
6712     /* ssl3.ca_list is initialized to NULL, and never changed. */
6713     ca_list = ss->ssl3.ca_list;
6714     if (!ca_list) {
6715 	ca_list = ssl3_server_ca_list;
6716     }
6717 
6718     if (ca_list != NULL) {
6719 	names = ca_list->names;
6720 	nnames = ca_list->nnames;
6721     }
6722 
6723     if (!nnames) {
6724 	PORT_SetError(SSL_ERROR_NO_TRUSTED_SSL_CLIENT_CA);
6725 	return SECFailure;
6726     }
6727 
6728     for (i = 0, name = names; i < nnames; i++, name++) {
6729 	calen += 2 + name->len;
6730     }
6731 
6732     certTypes       = certificate_types;
6733     certTypesLength = sizeof certificate_types;
6734 
6735     length = 1 + certTypesLength + 2 + calen;
6736 
6737     rv = ssl3_AppendHandshakeHeader(ss, certificate_request, length);
6738     if (rv != SECSuccess) {
6739 	return rv; 		/* err set by AppendHandshake. */
6740     }
6741     rv = ssl3_AppendHandshakeVariable(ss, certTypes, certTypesLength, 1);
6742     if (rv != SECSuccess) {
6743 	return rv; 		/* err set by AppendHandshake. */
6744     }
6745     rv = ssl3_AppendHandshakeNumber(ss, calen, 2);
6746     if (rv != SECSuccess) {
6747 	return rv; 		/* err set by AppendHandshake. */
6748     }
6749     for (i = 0, name = names; i < nnames; i++, name++) {
6750 	rv = ssl3_AppendHandshakeVariable(ss, name->data, name->len, 2);
6751 	if (rv != SECSuccess) {
6752 	    return rv; 		/* err set by AppendHandshake. */
6753 	}
6754     }
6755 
6756     return SECSuccess;
6757 }
6758 
6759 static SECStatus
ssl3_SendServerHelloDone(sslSocket * ss)6760 ssl3_SendServerHelloDone(sslSocket *ss)
6761 {
6762     SECStatus rv;
6763 
6764     SSL_TRC(3, ("%d: SSL3[%d]: send server_hello_done handshake",
6765 		SSL_GETPID(), ss->fd));
6766 
6767     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
6768     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
6769 
6770     rv = ssl3_AppendHandshakeHeader(ss, server_hello_done, 0);
6771     if (rv != SECSuccess) {
6772 	return rv; 		/* err set by AppendHandshake. */
6773     }
6774     rv = ssl3_FlushHandshake(ss, 0);
6775     if (rv != SECSuccess) {
6776 	return rv;	/* error code set by ssl3_FlushHandshake */
6777     }
6778     return SECSuccess;
6779 }
6780 
6781 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
6782  * ssl3 Certificate Verify message
6783  * Caller must hold Handshake and RecvBuf locks.
6784  */
6785 static SECStatus
ssl3_HandleCertificateVerify(sslSocket * ss,SSL3Opaque * b,PRUint32 length,SSL3Hashes * hashes)6786 ssl3_HandleCertificateVerify(sslSocket *ss, SSL3Opaque *b, PRUint32 length,
6787 			     SSL3Hashes *hashes)
6788 {
6789     SECItem              signed_hash = {siBuffer, NULL, 0};
6790     SECStatus            rv;
6791     int                  errCode     = SSL_ERROR_RX_MALFORMED_CERT_VERIFY;
6792     SSL3AlertDescription desc        = handshake_failure;
6793     PRBool               isTLS;
6794 
6795     SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_verify handshake",
6796 		SSL_GETPID(), ss->fd));
6797     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
6798     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
6799 
6800     if (ss->ssl3.hs.ws != wait_cert_verify || ss->sec.peerCert == NULL) {
6801 	desc    = unexpected_message;
6802 	errCode = SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY;
6803 	goto alert_loser;
6804     }
6805 
6806     rv = ssl3_ConsumeHandshakeVariable(ss, &signed_hash, 2, &b, &length);
6807     if (rv != SECSuccess) {
6808 	goto loser;		/* malformed. */
6809     }
6810 
6811     isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
6812 
6813     /* XXX verify that the key & kea match */
6814     rv = ssl3_VerifySignedHashes(hashes, ss->sec.peerCert, &signed_hash,
6815 				 isTLS, ss->pkcs11PinArg);
6816     if (rv != SECSuccess) {
6817     	errCode = PORT_GetError();
6818 	desc = isTLS ? decrypt_error : handshake_failure;
6819 	goto alert_loser;
6820     }
6821 
6822     signed_hash.data = NULL;
6823 
6824     if (length != 0) {
6825 	desc    = isTLS ? decode_error : illegal_parameter;
6826 	goto alert_loser;	/* malformed */
6827     }
6828     ss->ssl3.hs.ws = wait_change_cipher;
6829     return SECSuccess;
6830 
6831 alert_loser:
6832     SSL3_SendAlert(ss, alert_fatal, desc);
6833 loser:
6834     PORT_SetError(errCode);
6835     return SECFailure;
6836 }
6837 
6838 
6839 /* find a slot that is able to generate a PMS and wrap it with RSA.
6840  * Then generate and return the PMS.
6841  * If the serverKeySlot parameter is non-null, this function will use
6842  * that slot to do the job, otherwise it will find a slot.
6843  *
6844  * Called from  ssl3_DeriveConnectionKeysPKCS11()  (above)
6845  *		sendRSAClientKeyExchange()         (above)
6846  *		ssl3_HandleRSAClientKeyExchange()  (below)
6847  * Caller must hold the SpecWriteLock, the SSL3HandshakeLock
6848  */
6849 static PK11SymKey *
ssl3_GenerateRSAPMS(sslSocket * ss,ssl3CipherSpec * spec,PK11SlotInfo * serverKeySlot)6850 ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec,
6851                     PK11SlotInfo * serverKeySlot)
6852 {
6853     PK11SymKey *      pms		= NULL;
6854     PK11SlotInfo *    slot		= serverKeySlot;
6855     void *	      pwArg 		= ss->pkcs11PinArg;
6856     SECItem           param;
6857     CK_VERSION 	      version;
6858     CK_MECHANISM_TYPE mechanism_array[3];
6859 
6860     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
6861 
6862     if (slot == NULL) {
6863 	SSLCipherAlgorithm calg;
6864 	/* The specReadLock would suffice here, but we cannot assert on
6865 	** read locks.  Also, all the callers who call with a non-null
6866 	** slot already hold the SpecWriteLock.
6867 	*/
6868 	PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
6869 	PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
6870 
6871         calg = spec->cipher_def->calg;
6872 	PORT_Assert(alg2Mech[calg].calg == calg);
6873 
6874 	/* First get an appropriate slot.  */
6875 	mechanism_array[0] = CKM_SSL3_PRE_MASTER_KEY_GEN;
6876 	mechanism_array[1] = CKM_RSA_PKCS;
6877 	mechanism_array[2] = alg2Mech[calg].cmech;
6878 
6879 	slot = PK11_GetBestSlotMultiple(mechanism_array, 3, pwArg);
6880 	if (slot == NULL) {
6881 	   /* can't find a slot with all three, find a slot with the minimum */
6882 	    slot = PK11_GetBestSlotMultiple(mechanism_array, 2, pwArg);
6883 	    if (slot == NULL) {
6884 		PORT_SetError(SSL_ERROR_TOKEN_SLOT_NOT_FOUND);
6885 		return pms;	/* which is NULL */
6886 	    }
6887 	}
6888     }
6889 
6890     /* Generate the pre-master secret ...  */
6891     version.major = MSB(ss->clientHelloVersion);
6892     version.minor = LSB(ss->clientHelloVersion);
6893 
6894     param.data = (unsigned char *)&version;
6895     param.len  = sizeof version;
6896 
6897     pms = PK11_KeyGen(slot, CKM_SSL3_PRE_MASTER_KEY_GEN, &param, 0, pwArg);
6898     if (!serverKeySlot)
6899 	PK11_FreeSlot(slot);
6900     if (pms == NULL) {
6901 	ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
6902     }
6903     return pms;
6904 }
6905 
6906 /* Note: The Bleichenbacher attack on PKCS#1 necessitates that we NEVER
6907  * return any indication of failure of the Client Key Exchange message,
6908  * where that failure is caused by the content of the client's message.
6909  * This function must not return SECFailure for any reason that is directly
6910  * or indirectly caused by the content of the client's encrypted PMS.
6911  * We must not send an alert and also not drop the connection.
6912  * Instead, we generate a random PMS.  This will cause a failure
6913  * in the processing the finished message, which is exactly where
6914  * the failure must occur.
6915  *
6916  * Called from ssl3_HandleClientKeyExchange
6917  */
6918 static SECStatus
ssl3_HandleRSAClientKeyExchange(sslSocket * ss,SSL3Opaque * b,PRUint32 length,SECKEYPrivateKey * serverKey)6919 ssl3_HandleRSAClientKeyExchange(sslSocket *ss,
6920                                 SSL3Opaque *b,
6921 				PRUint32 length,
6922 				SECKEYPrivateKey *serverKey)
6923 {
6924     PK11SymKey *      pms;
6925     unsigned char *   cr     = (unsigned char *)&ss->ssl3.hs.client_random;
6926     unsigned char *   sr     = (unsigned char *)&ss->ssl3.hs.server_random;
6927     ssl3CipherSpec *  pwSpec = ss->ssl3.pwSpec;
6928     unsigned int      outLen = 0;
6929     PRBool            isTLS  = PR_FALSE;
6930     SECStatus         rv;
6931     SECItem           enc_pms;
6932     unsigned char     rsaPmsBuf[SSL3_RSA_PMS_LENGTH];
6933     SECItem           pmsItem = {siBuffer, NULL, 0};
6934 
6935     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
6936     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
6937 
6938     enc_pms.data = b;
6939     enc_pms.len  = length;
6940     pmsItem.data = rsaPmsBuf;
6941     pmsItem.len  = sizeof rsaPmsBuf;
6942 
6943     if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */
6944 	PRInt32 kLen;
6945 	kLen = ssl3_ConsumeHandshakeNumber(ss, 2, &enc_pms.data, &enc_pms.len);
6946 	if (kLen < 0) {
6947 	    PORT_SetError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
6948 	    return SECFailure;
6949 	}
6950 	if ((unsigned)kLen < enc_pms.len) {
6951 	    enc_pms.len = kLen;
6952 	}
6953 	isTLS = PR_TRUE;
6954     } else {
6955 	isTLS = (PRBool)(ss->ssl3.hs.kea_def->tls_keygen != 0);
6956     }
6957 
6958     if (ss->opt.bypassPKCS11) {
6959 	/* TRIPLE BYPASS, get PMS directly from RSA decryption.
6960 	 * Use PK11_PrivDecryptPKCS1 to decrypt the PMS to a buffer,
6961 	 * then, check for version rollback attack, then
6962 	 * do the equivalent of ssl3_DeriveMasterSecret, placing the MS in
6963 	 * pwSpec->msItem.  Finally call ssl3_InitPendingCipherSpec with
6964 	 * ss and NULL, so that it will use the MS we've already derived here.
6965 	 */
6966 
6967 	rv = PK11_PrivDecryptPKCS1(serverKey, rsaPmsBuf, &outLen,
6968 				   sizeof rsaPmsBuf, enc_pms.data, enc_pms.len);
6969 	if (rv != SECSuccess) {
6970 	    /* triple bypass failed.  Let's try for a double bypass. */
6971 	    goto double_bypass;
6972 	} else if (ss->opt.detectRollBack) {
6973 	    SSL3ProtocolVersion client_version =
6974 					 (rsaPmsBuf[0] << 8) | rsaPmsBuf[1];
6975 	    if (client_version != ss->clientHelloVersion) {
6976 		/* Version roll-back detected. ensure failure.  */
6977 		rv = PK11_GenerateRandom(rsaPmsBuf, sizeof rsaPmsBuf);
6978 	    }
6979 	}
6980 	/* have PMS, build MS without PKCS11 */
6981 	rv = ssl3_MasterKeyDeriveBypass(pwSpec, cr, sr, &pmsItem, isTLS,
6982 					PR_TRUE);
6983 	if (rv != SECSuccess) {
6984 	    pwSpec->msItem.data = pwSpec->raw_master_secret;
6985 	    pwSpec->msItem.len  = SSL3_MASTER_SECRET_LENGTH;
6986 	    PK11_GenerateRandom(pwSpec->msItem.data, pwSpec->msItem.len);
6987 	}
6988 	rv = ssl3_InitPendingCipherSpec(ss,  NULL);
6989     } else {
6990 double_bypass:
6991 	/*
6992 	 * unwrap pms out of the incoming buffer
6993 	 * Note: CKM_SSL3_MASTER_KEY_DERIVE is NOT the mechanism used to do
6994 	 *	the unwrap.  Rather, it is the mechanism with which the
6995 	 *      unwrapped pms will be used.
6996 	 */
6997 	pms = PK11_PubUnwrapSymKey(serverKey, &enc_pms,
6998 				   CKM_SSL3_MASTER_KEY_DERIVE, CKA_DERIVE, 0);
6999 	if (pms != NULL) {
7000 	    PRINT_BUF(60, (ss, "decrypted premaster secret:",
7001 			   PK11_GetKeyData(pms)->data,
7002 			   PK11_GetKeyData(pms)->len));
7003 	} else {
7004 	    /* unwrap failed. Generate a bogus PMS and carry on. */
7005 	    PK11SlotInfo *  slot   = PK11_GetSlotFromPrivateKey(serverKey);
7006 
7007 	    ssl_GetSpecWriteLock(ss);
7008 	    pms = ssl3_GenerateRSAPMS(ss, ss->ssl3.prSpec, slot);
7009 	    ssl_ReleaseSpecWriteLock(ss);
7010 	    PK11_FreeSlot(slot);
7011 	}
7012 
7013 	if (pms == NULL) {
7014 	    /* last gasp.  */
7015 	    ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
7016 	    return SECFailure;
7017 	}
7018 
7019 	/* This step will derive the MS from the PMS, among other things. */
7020 	rv = ssl3_InitPendingCipherSpec(ss,  pms);
7021 	PK11_FreeSymKey(pms);
7022     }
7023 
7024     if (rv != SECSuccess) {
7025 	SEND_ALERT
7026 	return SECFailure; /* error code set by ssl3_InitPendingCipherSpec */
7027     }
7028     return SECSuccess;
7029 }
7030 
7031 
7032 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
7033  * ssl3 ClientKeyExchange message from the remote client
7034  * Caller must hold Handshake and RecvBuf locks.
7035  */
7036 static SECStatus
ssl3_HandleClientKeyExchange(sslSocket * ss,SSL3Opaque * b,PRUint32 length)7037 ssl3_HandleClientKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
7038 {
7039     SECKEYPrivateKey *serverKey         = NULL;
7040     SECStatus         rv;
7041 const ssl3KEADef *    kea_def;
7042     ssl3KeyPair     *serverKeyPair      = NULL;
7043 #ifdef NSS_ENABLE_ECC
7044     SECKEYPublicKey *serverPubKey       = NULL;
7045 #endif /* NSS_ENABLE_ECC */
7046 
7047     SSL_TRC(3, ("%d: SSL3[%d]: handle client_key_exchange handshake",
7048 		SSL_GETPID(), ss->fd));
7049 
7050     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
7051     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
7052 
7053     if (ss->ssl3.hs.ws != wait_client_key) {
7054 	SSL3_SendAlert(ss, alert_fatal, unexpected_message);
7055     	PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH);
7056 	return SECFailure;
7057     }
7058 
7059     kea_def   = ss->ssl3.hs.kea_def;
7060 
7061     if (ss->ssl3.hs.usedStepDownKey) {
7062 	 PORT_Assert(kea_def->is_limited /* XXX OR cert is signing only */
7063 		 && kea_def->exchKeyType == kt_rsa
7064 		 && ss->stepDownKeyPair != NULL);
7065 	 if (!kea_def->is_limited  ||
7066 	      kea_def->exchKeyType != kt_rsa ||
7067 	      ss->stepDownKeyPair == NULL) {
7068 	 	/* shouldn't happen, don't use step down if it does */
7069 		goto skip;
7070 	 }
7071     	serverKeyPair = ss->stepDownKeyPair;
7072 	ss->sec.keaKeyBits = EXPORT_RSA_KEY_LENGTH * BPB;
7073     } else
7074 skip:
7075 #ifdef NSS_ENABLE_ECC
7076     /* XXX Using SSLKEAType to index server certifiates
7077      * does not work for (EC)DHE ciphers. Until we have
7078      * an indexing mechanism general enough for all key
7079      * exchange algorithms, we'll need to deal with each
7080      * one seprately.
7081      */
7082     if ((kea_def->kea == kea_ecdhe_rsa) ||
7083                (kea_def->kea == kea_ecdhe_ecdsa)) {
7084 	if (ss->ephemeralECDHKeyPair != NULL) {
7085 	   serverKeyPair = ss->ephemeralECDHKeyPair;
7086 	   if (serverKeyPair->pubKey) {
7087 		ss->sec.keaKeyBits =
7088 		    SECKEY_PublicKeyStrengthInBits(serverKeyPair->pubKey);
7089 	   }
7090 	}
7091     } else
7092 #endif
7093     {
7094 	sslServerCerts * sc = ss->serverCerts + kea_def->exchKeyType;
7095 	serverKeyPair = sc->serverKeyPair;
7096 	ss->sec.keaKeyBits = sc->serverKeyBits;
7097     }
7098 
7099     if (serverKeyPair) {
7100 	serverKey = serverKeyPair->privKey;
7101     }
7102 
7103     if (serverKey == NULL) {
7104     	SEND_ALERT
7105 	PORT_SetError(SSL_ERROR_NO_SERVER_KEY_FOR_ALG);
7106 	return SECFailure;
7107     }
7108 
7109     ss->sec.keaType    = kea_def->exchKeyType;
7110 
7111     switch (kea_def->exchKeyType) {
7112     case kt_rsa:
7113 	rv = ssl3_HandleRSAClientKeyExchange(ss, b, length, serverKey);
7114 	if (rv != SECSuccess) {
7115 	    SEND_ALERT
7116 	    return SECFailure;	/* error code set */
7117 	}
7118 	break;
7119 
7120 
7121 #ifdef NSS_ENABLE_ECC
7122     case kt_ecdh:
7123 	/* XXX We really ought to be able to store multiple
7124 	 * EC certs (a requirement if we wish to support both
7125 	 * ECDH-RSA and ECDH-ECDSA key exchanges concurrently).
7126 	 * When we make that change, we'll need an index other
7127 	 * than kt_ecdh to pick the right EC certificate.
7128 	 */
7129 	if (serverKeyPair) {
7130 	    serverPubKey = serverKeyPair->pubKey;
7131         }
7132 	if (serverPubKey == NULL) {
7133 	    /* XXX Is this the right error code? */
7134 	    PORT_SetError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
7135 	    return SECFailure;
7136 	}
7137 	rv = ssl3_HandleECDHClientKeyExchange(ss, b, length,
7138 					      serverPubKey, serverKey);
7139 	if (rv != SECSuccess) {
7140 	    return SECFailure;	/* error code set */
7141 	}
7142 	break;
7143 #endif /* NSS_ENABLE_ECC */
7144 
7145     default:
7146 	(void) ssl3_HandshakeFailure(ss);
7147 	PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
7148 	return SECFailure;
7149     }
7150     ss->ssl3.hs.ws = ss->sec.peerCert ? wait_cert_verify : wait_change_cipher;
7151     return SECSuccess;
7152 
7153 }
7154 
7155 /* This is TLS's equivalent of sending a no_certificate alert. */
7156 static SECStatus
ssl3_SendEmptyCertificate(sslSocket * ss)7157 ssl3_SendEmptyCertificate(sslSocket *ss)
7158 {
7159     SECStatus            rv;
7160 
7161     rv = ssl3_AppendHandshakeHeader(ss, certificate, 3);
7162     if (rv == SECSuccess) {
7163 	rv = ssl3_AppendHandshakeNumber(ss, 0, 3);
7164     }
7165     return rv;	/* error, if any, set by functions called above. */
7166 }
7167 
7168 SECStatus
ssl3_HandleNewSessionTicket(sslSocket * ss,SSL3Opaque * b,PRUint32 length)7169 ssl3_HandleNewSessionTicket(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
7170 {
7171     SECStatus         rv;
7172     NewSessionTicket  session_ticket;
7173 
7174     SSL_TRC(3, ("%d: SSL3[%d]: handle session_ticket handshake",
7175 		SSL_GETPID(), ss->fd));
7176 
7177     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
7178     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
7179 
7180     if (ss->ssl3.hs.ws != wait_new_session_ticket) {
7181 	SSL3_SendAlert(ss, alert_fatal, unexpected_message);
7182 	PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET);
7183 	return SECFailure;
7184     }
7185 
7186     session_ticket.received_timestamp = ssl_Time();
7187     if (length < 4) {
7188 	(void)SSL3_SendAlert(ss, alert_fatal, decode_error);
7189 	PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
7190 	return SECFailure;
7191     }
7192     session_ticket.ticket_lifetime_hint =
7193 	(PRUint32)ssl3_ConsumeHandshakeNumber(ss, 4, &b, &length);
7194 
7195     rv = ssl3_ConsumeHandshakeVariable(ss, &session_ticket.ticket, 2,
7196 	&b, &length);
7197     if (length != 0 || rv != SECSuccess) {
7198 	(void)SSL3_SendAlert(ss, alert_fatal, decode_error);
7199 	PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
7200 	return SECFailure;  /* malformed */
7201     }
7202 
7203     rv = ssl3_SetSIDSessionTicket(ss->sec.ci.sid, &session_ticket);
7204     if (rv != SECSuccess) {
7205 	(void)SSL3_SendAlert(ss, alert_fatal, handshake_failure);
7206 	PORT_SetError(SSL_ERROR_INTERNAL_ERROR_ALERT);
7207 	return SECFailure;
7208     }
7209     ss->ssl3.hs.ws = wait_change_cipher;
7210     return SECSuccess;
7211 }
7212 
7213 #ifdef NISCC_TEST
7214 static PRInt32 connNum = 0;
7215 
7216 static SECStatus
get_fake_cert(SECItem * pCertItem,int * pIndex)7217 get_fake_cert(SECItem *pCertItem, int *pIndex)
7218 {
7219     PRFileDesc *cf;
7220     char *      testdir;
7221     char *      startat;
7222     char *      stopat;
7223     const char *extension;
7224     int         fileNum;
7225     PRInt32     numBytes   = 0;
7226     PRStatus    prStatus;
7227     PRFileInfo  info;
7228     char        cfn[100];
7229 
7230     pCertItem->data = 0;
7231     if ((testdir = PR_GetEnv("NISCC_TEST")) == NULL) {
7232 	return SECSuccess;
7233     }
7234     *pIndex   = (NULL != strstr(testdir, "root"));
7235     extension = (strstr(testdir, "simple") ? "" : ".der");
7236     fileNum     = PR_AtomicIncrement(&connNum) - 1;
7237     if ((startat = PR_GetEnv("START_AT")) != NULL) {
7238 	fileNum += atoi(startat);
7239     }
7240     if ((stopat = PR_GetEnv("STOP_AT")) != NULL &&
7241 	fileNum >= atoi(stopat)) {
7242 	*pIndex = -1;
7243 	return SECSuccess;
7244     }
7245     sprintf(cfn, "%s/%08d%s", testdir, fileNum, extension);
7246     cf = PR_Open(cfn, PR_RDONLY, 0);
7247     if (!cf) {
7248 	goto loser;
7249     }
7250     prStatus = PR_GetOpenFileInfo(cf, &info);
7251     if (prStatus != PR_SUCCESS) {
7252 	PR_Close(cf);
7253 	goto loser;
7254     }
7255     pCertItem = SECITEM_AllocItem(NULL, pCertItem, info.size);
7256     if (pCertItem) {
7257 	numBytes = PR_Read(cf, pCertItem->data, info.size);
7258     }
7259     PR_Close(cf);
7260     if (numBytes != info.size) {
7261 	SECITEM_FreeItem(pCertItem, PR_FALSE);
7262 	PORT_SetError(SEC_ERROR_IO);
7263 	goto loser;
7264     }
7265     fprintf(stderr, "using %s\n", cfn);
7266     return SECSuccess;
7267 
7268 loser:
7269     fprintf(stderr, "failed to use %s\n", cfn);
7270     *pIndex = -1;
7271     return SECFailure;
7272 }
7273 #endif
7274 
7275 /*
7276  * Used by both client and server.
7277  * Called from HandleServerHelloDone and from SendServerHelloSequence.
7278  */
7279 static SECStatus
ssl3_SendCertificate(sslSocket * ss)7280 ssl3_SendCertificate(sslSocket *ss)
7281 {
7282     SECStatus            rv;
7283     CERTCertificateList *certChain;
7284     int                  len 		= 0;
7285     int                  i;
7286     SSL3KEAType          certIndex;
7287 #ifdef NISCC_TEST
7288     SECItem              fakeCert;
7289     int                  ndex           = -1;
7290 #endif
7291 
7292     SSL_TRC(3, ("%d: SSL3[%d]: send certificate handshake",
7293 		SSL_GETPID(), ss->fd));
7294 
7295     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
7296     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
7297 
7298     if (ss->sec.localCert)
7299     	CERT_DestroyCertificate(ss->sec.localCert);
7300     if (ss->sec.isServer) {
7301 	sslServerCerts * sc = NULL;
7302 
7303 	/* XXX SSLKEAType isn't really a good choice for
7304 	 * indexing certificates (it breaks when we deal
7305 	 * with (EC)DHE-* cipher suites. This hack ensures
7306 	 * the RSA cert is picked for (EC)DHE-RSA.
7307 	 * Revisit this when we add server side support
7308 	 * for ECDHE-ECDSA or client-side authentication
7309 	 * using EC certificates.
7310 	 */
7311 	if ((ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) ||
7312 	    (ss->ssl3.hs.kea_def->kea == kea_dhe_rsa)) {
7313 	    certIndex = kt_rsa;
7314 	} else {
7315 	    certIndex = ss->ssl3.hs.kea_def->exchKeyType;
7316 	}
7317 	sc                    = ss->serverCerts + certIndex;
7318 	certChain             = sc->serverCertChain;
7319 	ss->sec.authKeyBits   = sc->serverKeyBits;
7320 	ss->sec.authAlgorithm = ss->ssl3.hs.kea_def->signKeyType;
7321 	ss->sec.localCert     = CERT_DupCertificate(sc->serverCert);
7322     } else {
7323 	certChain          = ss->ssl3.clientCertChain;
7324 	ss->sec.localCert = CERT_DupCertificate(ss->ssl3.clientCertificate);
7325     }
7326 
7327 #ifdef NISCC_TEST
7328     rv = get_fake_cert(&fakeCert, &ndex);
7329 #endif
7330 
7331     if (certChain) {
7332 	for (i = 0; i < certChain->len; i++) {
7333 #ifdef NISCC_TEST
7334 	    if (fakeCert.len > 0 && i == ndex) {
7335 		len += fakeCert.len + 3;
7336 	    } else {
7337 		len += certChain->certs[i].len + 3;
7338 	    }
7339 #else
7340 	    len += certChain->certs[i].len + 3;
7341 #endif
7342 	}
7343     }
7344 
7345     rv = ssl3_AppendHandshakeHeader(ss, certificate, len + 3);
7346     if (rv != SECSuccess) {
7347 	return rv; 		/* err set by AppendHandshake. */
7348     }
7349     rv = ssl3_AppendHandshakeNumber(ss, len, 3);
7350     if (rv != SECSuccess) {
7351 	return rv; 		/* err set by AppendHandshake. */
7352     }
7353     if (certChain) {
7354         for (i = 0; i < certChain->len; i++) {
7355 #ifdef NISCC_TEST
7356             if (fakeCert.len > 0 && i == ndex) {
7357                 rv = ssl3_AppendHandshakeVariable(ss, fakeCert.data,
7358                                                   fakeCert.len, 3);
7359                 SECITEM_FreeItem(&fakeCert, PR_FALSE);
7360             } else {
7361                 rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data,
7362                                                   certChain->certs[i].len, 3);
7363             }
7364 #else
7365             rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data,
7366                                               certChain->certs[i].len, 3);
7367 #endif
7368             if (rv != SECSuccess) {
7369                 return rv; 		/* err set by AppendHandshake. */
7370             }
7371         }
7372     }
7373 
7374     return SECSuccess;
7375 }
7376 
7377 /* This is used to delete the CA certificates in the peer certificate chain
7378  * from the cert database after they've been validated.
7379  */
7380 static void
ssl3_CleanupPeerCerts(sslSocket * ss)7381 ssl3_CleanupPeerCerts(sslSocket *ss)
7382 {
7383     PRArenaPool * arena = ss->ssl3.peerCertArena;
7384     ssl3CertNode *certs = (ssl3CertNode *)ss->ssl3.peerCertChain;
7385 
7386     for (; certs; certs = certs->next) {
7387 	CERT_DestroyCertificate(certs->cert);
7388     }
7389     if (arena) PORT_FreeArena(arena, PR_FALSE);
7390     ss->ssl3.peerCertArena = NULL;
7391     ss->ssl3.peerCertChain = NULL;
7392 }
7393 
7394 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
7395  * ssl3 Certificate message.
7396  * Caller must hold Handshake and RecvBuf locks.
7397  */
7398 static SECStatus
ssl3_HandleCertificate(sslSocket * ss,SSL3Opaque * b,PRUint32 length)7399 ssl3_HandleCertificate(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
7400 {
7401     ssl3CertNode *   c;
7402     ssl3CertNode *   certs 	= NULL;
7403     PRArenaPool *    arena 	= NULL;
7404     CERTCertificate *cert;
7405     PRInt32          remaining  = 0;
7406     PRInt32          size;
7407     SECStatus        rv;
7408     PRBool           isServer	= (PRBool)(!!ss->sec.isServer);
7409     PRBool           trusted 	= PR_FALSE;
7410     PRBool           isTLS;
7411     SSL3AlertDescription desc	= bad_certificate;
7412     int              errCode    = SSL_ERROR_RX_MALFORMED_CERTIFICATE;
7413     SECItem          certItem;
7414 
7415     SSL_TRC(3, ("%d: SSL3[%d]: handle certificate handshake",
7416 		SSL_GETPID(), ss->fd));
7417     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
7418     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
7419 
7420     if ((ss->ssl3.hs.ws != wait_server_cert) &&
7421 	(ss->ssl3.hs.ws != wait_client_cert)) {
7422 	desc    = unexpected_message;
7423 	errCode = SSL_ERROR_RX_UNEXPECTED_CERTIFICATE;
7424 	goto alert_loser;
7425     }
7426 
7427     if (ss->sec.peerCert != NULL) {
7428 	if (ss->sec.peerKey) {
7429 	    SECKEY_DestroyPublicKey(ss->sec.peerKey);
7430 	    ss->sec.peerKey = NULL;
7431 	}
7432 	CERT_DestroyCertificate(ss->sec.peerCert);
7433 	ss->sec.peerCert = NULL;
7434     }
7435 
7436     ssl3_CleanupPeerCerts(ss);
7437     isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
7438 
7439     /* It is reported that some TLS client sends a Certificate message
7440     ** with a zero-length message body.  We'll treat that case like a
7441     ** normal no_certificates message to maximize interoperability.
7442     */
7443     if (length) {
7444 	remaining = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length);
7445 	if (remaining < 0)
7446 	    goto loser;	/* fatal alert already sent by ConsumeHandshake. */
7447 	if ((PRUint32)remaining > length)
7448 	    goto decode_loser;
7449     }
7450 
7451     if (!remaining) {
7452 	if (!(isTLS && isServer))
7453 	    goto alert_loser;
7454     	/* This is TLS's version of a no_certificate alert. */
7455     	/* I'm a server. I've requested a client cert. He hasn't got one. */
7456 	rv = ssl3_HandleNoCertificate(ss);
7457 	if (rv != SECSuccess) {
7458 	    errCode = PORT_GetError();
7459 	    goto loser;
7460 	}
7461 	goto cert_block;
7462     }
7463 
7464     ss->ssl3.peerCertArena = arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
7465     if ( arena == NULL ) {
7466 	goto loser;	/* don't send alerts on memory errors */
7467     }
7468 
7469     /* First get the peer cert. */
7470     remaining -= 3;
7471     if (remaining < 0)
7472 	goto decode_loser;
7473 
7474     size = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length);
7475     if (size <= 0)
7476 	goto loser;	/* fatal alert already sent by ConsumeHandshake. */
7477 
7478     if (remaining < size)
7479 	goto decode_loser;
7480 
7481     certItem.data = b;
7482     certItem.len = size;
7483     b      += size;
7484     length -= size;
7485     remaining -= size;
7486 
7487     ss->sec.peerCert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL,
7488                                             PR_FALSE, PR_TRUE);
7489     if (ss->sec.peerCert == NULL) {
7490 	/* We should report an alert if the cert was bad, but not if the
7491 	 * problem was just some local problem, like memory error.
7492 	 */
7493 	goto ambiguous_err;
7494     }
7495 
7496     /* Now get all of the CA certs. */
7497     while (remaining > 0) {
7498 	remaining -= 3;
7499 	if (remaining < 0)
7500 	    goto decode_loser;
7501 
7502 	size = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length);
7503 	if (size <= 0)
7504 	    goto loser;	/* fatal alert already sent by ConsumeHandshake. */
7505 
7506 	if (remaining < size)
7507 	    goto decode_loser;
7508 
7509 	certItem.data = b;
7510 	certItem.len = size;
7511 	b      += size;
7512 	length -= size;
7513 	remaining -= size;
7514 
7515 	c = PORT_ArenaNew(arena, ssl3CertNode);
7516 	if (c == NULL) {
7517 	    goto loser;	/* don't send alerts on memory errors */
7518 	}
7519 
7520 	c->cert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL,
7521 	                                  PR_FALSE, PR_TRUE);
7522 	if (c->cert == NULL) {
7523 	    goto ambiguous_err;
7524 	}
7525 
7526 	if (c->cert->trust)
7527 	    trusted = PR_TRUE;
7528 
7529 	c->next = certs;
7530 	certs = c;
7531     }
7532 
7533     if (remaining != 0)
7534         goto decode_loser;
7535 
7536     SECKEY_UpdateCertPQG(ss->sec.peerCert);
7537 
7538     /*
7539      * Ask caller-supplied callback function to validate cert chain.
7540      */
7541     rv = (SECStatus)(*ss->authCertificate)(ss->authCertificateArg, ss->fd,
7542 					   PR_TRUE, isServer);
7543     if (rv) {
7544 	errCode = PORT_GetError();
7545 	if (!ss->handleBadCert) {
7546 	    goto bad_cert;
7547 	}
7548 	rv = (SECStatus)(*ss->handleBadCert)(ss->badCertArg, ss->fd);
7549 	if ( rv ) {
7550 	    if ( rv == SECWouldBlock ) {
7551 		/* someone will handle this connection asynchronously*/
7552 		SSL_DBG(("%d: SSL3[%d]: go to async cert handler",
7553 			 SSL_GETPID(), ss->fd));
7554 		ss->ssl3.peerCertChain = certs;
7555 		certs               = NULL;
7556 		ssl_SetAlwaysBlock(ss);
7557 		goto cert_block;
7558 	    }
7559 	    /* cert is bad */
7560 	    goto bad_cert;
7561 	}
7562 	/* cert is good */
7563     }
7564 
7565     /* start SSL Step Up, if appropriate */
7566     cert = ss->sec.peerCert;
7567     if (!isServer &&
7568     	ssl3_global_policy_some_restricted &&
7569         ss->ssl3.policy == SSL_ALLOWED &&
7570 	anyRestrictedEnabled(ss) &&
7571 	SECSuccess == CERT_VerifyCertNow(cert->dbhandle, cert,
7572 	                                 PR_FALSE, /* checkSig */
7573 				         certUsageSSLServerWithStepUp,
7574 /*XXX*/				         ss->authCertificateArg) ) {
7575 	ss->ssl3.policy         = SSL_RESTRICTED;
7576 	ss->ssl3.hs.rehandshake = PR_TRUE;
7577     }
7578 
7579     ss->sec.ci.sid->peerCert = CERT_DupCertificate(ss->sec.peerCert);
7580 
7581     if (!ss->sec.isServer) {
7582 	/* set the server authentication and key exchange types and sizes
7583 	** from the value in the cert.  If the key exchange key is different,
7584 	** it will get fixed when we handle the server key exchange message.
7585 	*/
7586 	SECKEYPublicKey * pubKey  = CERT_ExtractPublicKey(cert);
7587 	ss->sec.authAlgorithm = ss->ssl3.hs.kea_def->signKeyType;
7588 	ss->sec.keaType       = ss->ssl3.hs.kea_def->exchKeyType;
7589 	if (pubKey) {
7590 	    ss->sec.keaKeyBits = ss->sec.authKeyBits =
7591 		SECKEY_PublicKeyStrengthInBits(pubKey);
7592 #ifdef NSS_ENABLE_ECC
7593 	    if (ss->sec.keaType == kt_ecdh) {
7594 		/* Get authKeyBits from signing key.
7595 		 * XXX The code below uses a quick approximation of
7596 		 * key size based on cert->signatureWrap.signature.data
7597 		 * (which contains the DER encoded signature). The field
7598 		 * cert->signatureWrap.signature.len contains the
7599 		 * length of the encoded signature in bits.
7600 		 */
7601 		if (ss->ssl3.hs.kea_def->kea == kea_ecdh_ecdsa) {
7602 		    ss->sec.authKeyBits =
7603 			cert->signatureWrap.signature.data[3]*8;
7604 		    if (cert->signatureWrap.signature.data[4] == 0x00)
7605 			    ss->sec.authKeyBits -= 8;
7606 		    /*
7607 		     * XXX: if cert is not signed by ecdsa we should
7608 		     * destroy pubKey and goto bad_cert
7609 		     */
7610 		} else if (ss->ssl3.hs.kea_def->kea == kea_ecdh_rsa) {
7611 		    ss->sec.authKeyBits = cert->signatureWrap.signature.len;
7612 		    /*
7613 		     * XXX: if cert is not signed by rsa we should
7614 		     * destroy pubKey and goto bad_cert
7615 		     */
7616 		}
7617 	    }
7618 #endif /* NSS_ENABLE_ECC */
7619 	    SECKEY_DestroyPublicKey(pubKey);
7620 	    pubKey = NULL;
7621     	}
7622     }
7623 
7624     ss->ssl3.peerCertChain = certs;  certs = NULL;  arena = NULL;
7625 
7626 cert_block:
7627     if (ss->sec.isServer) {
7628 	ss->ssl3.hs.ws = wait_client_key;
7629     } else {
7630 	ss->ssl3.hs.ws = wait_cert_request; /* disallow server_key_exchange */
7631 	if (ss->ssl3.hs.kea_def->is_limited ||
7632 	    /* XXX OR server cert is signing only. */
7633 #ifdef NSS_ENABLE_ECC
7634 	    ss->ssl3.hs.kea_def->kea == kea_ecdhe_ecdsa ||
7635 	    ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa ||
7636 #endif /* NSS_ENABLE_ECC */
7637 	    ss->ssl3.hs.kea_def->exchKeyType == kt_dh) {
7638 	    ss->ssl3.hs.ws = wait_server_key; /* allow server_key_exchange */
7639 	}
7640     }
7641 
7642     /* rv must normally be equal to SECSuccess here.  If we called
7643      * handleBadCert, it can also be SECWouldBlock.
7644      */
7645     return rv;
7646 
7647 ambiguous_err:
7648     errCode = PORT_GetError();
7649     switch (errCode) {
7650     case PR_OUT_OF_MEMORY_ERROR:
7651     case SEC_ERROR_BAD_DATABASE:
7652     case SEC_ERROR_NO_MEMORY:
7653 	if (isTLS) {
7654 	    desc = internal_error;
7655 	    goto alert_loser;
7656 	}
7657 	goto loser;
7658     }
7659     /* fall through to bad_cert. */
7660 
7661 bad_cert:	/* caller has set errCode. */
7662     switch (errCode) {
7663     case SEC_ERROR_LIBRARY_FAILURE:     desc = unsupported_certificate; break;
7664     case SEC_ERROR_EXPIRED_CERTIFICATE: desc = certificate_expired;     break;
7665     case SEC_ERROR_REVOKED_CERTIFICATE: desc = certificate_revoked;     break;
7666     case SEC_ERROR_INADEQUATE_KEY_USAGE:
7667     case SEC_ERROR_INADEQUATE_CERT_TYPE:
7668 		                        desc = certificate_unknown;     break;
7669     case SEC_ERROR_UNTRUSTED_CERT:
7670 		    desc = isTLS ? access_denied : certificate_unknown; break;
7671     case SEC_ERROR_UNKNOWN_ISSUER:
7672     case SEC_ERROR_UNTRUSTED_ISSUER:
7673 		    desc = isTLS ? unknown_ca : certificate_unknown; break;
7674     case SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE:
7675 		    desc = isTLS ? unknown_ca : certificate_expired; break;
7676 
7677     case SEC_ERROR_CERT_NOT_IN_NAME_SPACE:
7678     case SEC_ERROR_PATH_LEN_CONSTRAINT_INVALID:
7679     case SEC_ERROR_CA_CERT_INVALID:
7680     case SEC_ERROR_BAD_SIGNATURE:
7681     default:                            desc = bad_certificate;     break;
7682     }
7683     SSL_DBG(("%d: SSL3[%d]: peer certificate is no good: error=%d",
7684 	     SSL_GETPID(), ss->fd, errCode));
7685 
7686     goto alert_loser;
7687 
7688 decode_loser:
7689     desc = isTLS ? decode_error : bad_certificate;
7690 
7691 alert_loser:
7692     (void)SSL3_SendAlert(ss, alert_fatal, desc);
7693 
7694 loser:
7695     ss->ssl3.peerCertChain = certs;  certs = NULL;  arena = NULL;
7696     ssl3_CleanupPeerCerts(ss);
7697 
7698     if (ss->sec.peerCert != NULL) {
7699 	CERT_DestroyCertificate(ss->sec.peerCert);
7700 	ss->sec.peerCert = NULL;
7701     }
7702     (void)ssl_MapLowLevelError(errCode);
7703     return SECFailure;
7704 }
7705 
7706 
7707 /* restart an SSL connection that we stopped to run certificate dialogs
7708 ** XXX	Need to document here how an application marks a cert to show that
7709 **	the application has accepted it (overridden CERT_VerifyCert).
7710  *
7711  * XXX This code only works on the initial handshake on a connection, XXX
7712  *     It does not work on a subsequent handshake (redo).
7713  *
7714  * Return value: XXX
7715  *
7716  * Caller holds 1stHandshakeLock.
7717 */
7718 int
ssl3_RestartHandshakeAfterServerCert(sslSocket * ss)7719 ssl3_RestartHandshakeAfterServerCert(sslSocket *ss)
7720 {
7721     CERTCertificate * cert;
7722     int               rv	= SECSuccess;
7723 
7724     if (MSB(ss->version) != MSB(SSL_LIBRARY_VERSION_3_0)) {
7725 	SET_ERROR_CODE
7726     	return SECFailure;
7727     }
7728     if (!ss->ssl3.initialized) {
7729 	SET_ERROR_CODE
7730     	return SECFailure;
7731     }
7732 
7733     cert = ss->sec.peerCert;
7734 
7735     /* Permit step up if user decided to accept the cert */
7736     if (!ss->sec.isServer &&
7737     	ssl3_global_policy_some_restricted &&
7738         ss->ssl3.policy == SSL_ALLOWED &&
7739 	anyRestrictedEnabled(ss) &&
7740 	(SECSuccess == CERT_VerifyCertNow(cert->dbhandle, cert,
7741 	                                  PR_FALSE, /* checksig */
7742 				          certUsageSSLServerWithStepUp,
7743 /*XXX*/				          ss->authCertificateArg) )) {
7744 	ss->ssl3.policy         = SSL_RESTRICTED;
7745 	ss->ssl3.hs.rehandshake = PR_TRUE;
7746     }
7747 
7748     if (ss->handshake != NULL) {
7749 	ss->handshake = ssl_GatherRecord1stHandshake;
7750 	ss->sec.ci.sid->peerCert = CERT_DupCertificate(ss->sec.peerCert);
7751 
7752 	ssl_GetRecvBufLock(ss);
7753 	if (ss->ssl3.hs.msgState.buf != NULL) {
7754 	    rv = ssl3_HandleRecord(ss, NULL, &ss->gs.buf);
7755 	}
7756 	ssl_ReleaseRecvBufLock(ss);
7757     }
7758 
7759     return rv;
7760 }
7761 
7762 static SECStatus
ssl3_ComputeTLSFinished(ssl3CipherSpec * spec,PRBool isServer,const SSL3Finished * hashes,TLSFinished * tlsFinished)7763 ssl3_ComputeTLSFinished(ssl3CipherSpec *spec,
7764 			PRBool          isServer,
7765                 const   SSL3Finished *  hashes,
7766                         TLSFinished  *  tlsFinished)
7767 {
7768     const char * label;
7769     unsigned int len;
7770     SECStatus    rv;
7771 
7772     label = isServer ? "server finished" : "client finished";
7773     len   = 15;
7774 
7775     if (spec->master_secret && !spec->bypassCiphers) {
7776 	SECItem      param       = {siBuffer, NULL, 0};
7777 	PK11Context *prf_context =
7778 	    PK11_CreateContextBySymKey(CKM_TLS_PRF_GENERAL, CKA_SIGN,
7779 				       spec->master_secret, &param);
7780 	if (!prf_context)
7781 	    return SECFailure;
7782 
7783 	rv  = PK11_DigestBegin(prf_context);
7784 	rv |= PK11_DigestOp(prf_context, (const unsigned char *) label, len);
7785 	rv |= PK11_DigestOp(prf_context, hashes->md5, sizeof *hashes);
7786 	rv |= PK11_DigestFinal(prf_context, tlsFinished->verify_data,
7787 			       &len, sizeof tlsFinished->verify_data);
7788 	PORT_Assert(rv != SECSuccess || len == sizeof *tlsFinished);
7789 
7790 	PK11_DestroyContext(prf_context, PR_TRUE);
7791     } else {
7792 	/* bypass PKCS11 */
7793 	SECItem inData  = { siBuffer, };
7794 	SECItem outData = { siBuffer, };
7795 	PRBool isFIPS   = PR_FALSE;
7796 
7797 	inData.data  = (unsigned char *)hashes->md5;
7798 	inData.len   = sizeof hashes[0];
7799 	outData.data = tlsFinished->verify_data;
7800 	outData.len  = sizeof tlsFinished->verify_data;
7801 	rv = TLS_PRF(&spec->msItem, label, &inData, &outData, isFIPS);
7802 	PORT_Assert(rv != SECSuccess || \
7803 		    outData.len == sizeof tlsFinished->verify_data);
7804     }
7805     return rv;
7806 }
7807 
7808 /* called from ssl3_HandleServerHelloDone
7809  */
7810 static SECStatus
ssl3_SendNextProto(sslSocket * ss)7811 ssl3_SendNextProto(sslSocket *ss)
7812 {
7813     SECStatus rv;
7814     int padding_len;
7815     static const unsigned char padding[32] = {0};
7816 
7817     if (ss->ssl3.nextProtoState == SSL_NEXT_PROTO_NO_SUPPORT)
7818 	return SECSuccess;
7819 
7820     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
7821     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
7822 
7823     padding_len = 32 - ((ss->ssl3.nextProto.len + 2) % 32);
7824 
7825     rv = ssl3_AppendHandshakeHeader(ss, next_proto, ss->ssl3.nextProto.len +
7826 						    2 + padding_len);
7827     if (rv != SECSuccess) {
7828 	return rv;	/* error code set by AppendHandshakeHeader */
7829     }
7830     rv = ssl3_AppendHandshakeVariable(ss, ss->ssl3.nextProto.data,
7831 				      ss->ssl3.nextProto.len, 1);
7832     if (rv != SECSuccess) {
7833 	return rv;	/* error code set by AppendHandshake */
7834     }
7835     rv = ssl3_AppendHandshakeVariable(ss, padding, padding_len, 1);
7836     if (rv != SECSuccess) {
7837 	return rv;	/* error code set by AppendHandshake */
7838     }
7839     return rv;
7840 }
7841 
7842 /* called from ssl3_HandleServerHelloDone
7843  *             ssl3_HandleClientHello
7844  *             ssl3_HandleFinished
7845  */
7846 static SECStatus
ssl3_SendFinished(sslSocket * ss,PRInt32 flags)7847 ssl3_SendFinished(sslSocket *ss, PRInt32 flags)
7848 {
7849     ssl3CipherSpec *cwSpec;
7850     PRBool          isTLS;
7851     PRBool          isServer = ss->sec.isServer;
7852     SECStatus       rv;
7853     SSL3Sender      sender = isServer ? sender_server : sender_client;
7854     SSL3Finished    hashes;
7855     TLSFinished     tlsFinished;
7856 
7857     SSL_TRC(3, ("%d: SSL3[%d]: send finished handshake", SSL_GETPID(), ss->fd));
7858 
7859     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
7860     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
7861 
7862     ssl_GetSpecReadLock(ss);
7863     cwSpec = ss->ssl3.cwSpec;
7864     isTLS = (PRBool)(cwSpec->version > SSL_LIBRARY_VERSION_3_0);
7865     rv = ssl3_ComputeHandshakeHashes(ss, cwSpec, &hashes, sender);
7866     if (isTLS && rv == SECSuccess) {
7867 	rv = ssl3_ComputeTLSFinished(cwSpec, isServer, &hashes, &tlsFinished);
7868     }
7869     ssl_ReleaseSpecReadLock(ss);
7870     if (rv != SECSuccess) {
7871 	goto fail;	/* err code was set by ssl3_ComputeHandshakeHashes */
7872     }
7873 
7874     if (isTLS) {
7875 	rv = ssl3_AppendHandshakeHeader(ss, finished, sizeof tlsFinished);
7876 	if (rv != SECSuccess)
7877 	    goto fail; 		/* err set by AppendHandshake. */
7878 	rv = ssl3_AppendHandshake(ss, &tlsFinished, sizeof tlsFinished);
7879 	if (rv != SECSuccess)
7880 	    goto fail; 		/* err set by AppendHandshake. */
7881     } else {
7882 	rv = ssl3_AppendHandshakeHeader(ss, finished, sizeof hashes);
7883 	if (rv != SECSuccess)
7884 	    goto fail; 		/* err set by AppendHandshake. */
7885 	rv = ssl3_AppendHandshake(ss, &hashes, sizeof hashes);
7886 	if (rv != SECSuccess)
7887 	    goto fail; 		/* err set by AppendHandshake. */
7888     }
7889     rv = ssl3_FlushHandshake(ss, flags);
7890     if (rv != SECSuccess) {
7891 	goto fail;	/* error code set by ssl3_FlushHandshake */
7892     }
7893     return SECSuccess;
7894 
7895 fail:
7896     return rv;
7897 }
7898 
7899 /* wrap the master secret, and put it into the SID.
7900  * Caller holds the Spec read lock.
7901  */
7902 SECStatus
ssl3_CacheWrappedMasterSecret(sslSocket * ss,sslSessionID * sid,ssl3CipherSpec * spec,SSL3KEAType effectiveExchKeyType)7903 ssl3_CacheWrappedMasterSecret(sslSocket *ss, sslSessionID *sid,
7904     ssl3CipherSpec *spec, SSL3KEAType effectiveExchKeyType)
7905 {
7906     PK11SymKey *      wrappingKey  = NULL;
7907     PK11SlotInfo *    symKeySlot;
7908     void *            pwArg        = ss->pkcs11PinArg;
7909     SECStatus         rv           = SECFailure;
7910     PRBool            isServer     = ss->sec.isServer;
7911     CK_MECHANISM_TYPE mechanism    = CKM_INVALID_MECHANISM;
7912     symKeySlot = PK11_GetSlotFromKey(spec->master_secret);
7913     if (!isServer) {
7914 	int  wrapKeyIndex;
7915 	int  incarnation;
7916 
7917 	/* these next few functions are mere accessors and don't fail. */
7918 	sid->u.ssl3.masterWrapIndex  = wrapKeyIndex =
7919 				       PK11_GetCurrentWrapIndex(symKeySlot);
7920 	PORT_Assert(wrapKeyIndex == 0);	/* array has only one entry! */
7921 
7922 	sid->u.ssl3.masterWrapSeries = incarnation =
7923 				       PK11_GetSlotSeries(symKeySlot);
7924 	sid->u.ssl3.masterSlotID   = PK11_GetSlotID(symKeySlot);
7925 	sid->u.ssl3.masterModuleID = PK11_GetModuleID(symKeySlot);
7926 	sid->u.ssl3.masterValid    = PR_TRUE;
7927 	/* Get the default wrapping key, for wrapping the master secret before
7928 	 * placing it in the SID cache entry. */
7929 	wrappingKey = PK11_GetWrapKey(symKeySlot, wrapKeyIndex,
7930 				      CKM_INVALID_MECHANISM, incarnation,
7931 				      pwArg);
7932 	if (wrappingKey) {
7933 	    mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */
7934 	} else {
7935 	    int keyLength;
7936 	    /* if the wrappingKey doesn't exist, attempt to create it.
7937 	     * Note: we intentionally ignore errors here.  If we cannot
7938 	     * generate a wrapping key, it is not fatal to this SSL connection,
7939 	     * but we will not be able to restart this session.
7940 	     */
7941 	    mechanism = PK11_GetBestWrapMechanism(symKeySlot);
7942 	    keyLength = PK11_GetBestKeyLength(symKeySlot, mechanism);
7943 	    /* Zero length means fixed key length algorithm, or error.
7944 	     * It's ambiguous.
7945 	     */
7946 	    wrappingKey = PK11_KeyGen(symKeySlot, mechanism, NULL,
7947 				      keyLength, pwArg);
7948 	    if (wrappingKey) {
7949 		PK11_SetWrapKey(symKeySlot, wrapKeyIndex, wrappingKey);
7950 	    }
7951 	}
7952     } else {
7953 	/* server socket using session cache. */
7954 	mechanism = PK11_GetBestWrapMechanism(symKeySlot);
7955 	if (mechanism != CKM_INVALID_MECHANISM) {
7956 	    wrappingKey =
7957 		getWrappingKey(ss, symKeySlot, effectiveExchKeyType,
7958 			       mechanism, pwArg);
7959 	    if (wrappingKey) {
7960 		mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */
7961 	    }
7962 	}
7963     }
7964 
7965     sid->u.ssl3.masterWrapMech = mechanism;
7966     PK11_FreeSlot(symKeySlot);
7967 
7968     if (wrappingKey) {
7969 	SECItem wmsItem;
7970 
7971 	wmsItem.data = sid->u.ssl3.keys.wrapped_master_secret;
7972 	wmsItem.len  = sizeof sid->u.ssl3.keys.wrapped_master_secret;
7973 	rv = PK11_WrapSymKey(mechanism, NULL, wrappingKey,
7974 			     spec->master_secret, &wmsItem);
7975 	/* rv is examined below. */
7976 	sid->u.ssl3.keys.wrapped_master_secret_len = wmsItem.len;
7977 	PK11_FreeSymKey(wrappingKey);
7978     }
7979     return rv;
7980 }
7981 
7982 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
7983  * ssl3 Finished message from the peer.
7984  * Caller must hold Handshake and RecvBuf locks.
7985  */
7986 static SECStatus
ssl3_HandleFinished(sslSocket * ss,SSL3Opaque * b,PRUint32 length,const SSL3Hashes * hashes)7987 ssl3_HandleFinished(sslSocket *ss, SSL3Opaque *b, PRUint32 length,
7988 		    const SSL3Hashes *hashes)
7989 {
7990     sslSessionID *    sid	   = ss->sec.ci.sid;
7991     SECStatus         rv           = SECSuccess;
7992     PRBool            isServer     = ss->sec.isServer;
7993     PRBool            isTLS;
7994     PRBool            doStepUp;
7995     SSL3KEAType       effectiveExchKeyType;
7996 
7997     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
7998     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
7999 
8000     SSL_TRC(3, ("%d: SSL3[%d]: handle finished handshake",
8001     	SSL_GETPID(), ss->fd));
8002 
8003     if (ss->ssl3.hs.ws != wait_finished) {
8004 	SSL3_SendAlert(ss, alert_fatal, unexpected_message);
8005     	PORT_SetError(SSL_ERROR_RX_UNEXPECTED_FINISHED);
8006 	return SECFailure;
8007     }
8008 
8009     isTLS = (PRBool)(ss->ssl3.crSpec->version > SSL_LIBRARY_VERSION_3_0);
8010     if (isTLS) {
8011 	TLSFinished tlsFinished;
8012 
8013 	if (length != sizeof tlsFinished) {
8014 	    (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
8015 	    PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED);
8016 	    return SECFailure;
8017 	}
8018 	rv = ssl3_ComputeTLSFinished(ss->ssl3.crSpec, !isServer,
8019 	                             hashes, &tlsFinished);
8020 	if (rv != SECSuccess ||
8021 	    0 != NSS_SecureMemcmp(&tlsFinished, b, length)) {
8022 	    (void)SSL3_SendAlert(ss, alert_fatal, decrypt_error);
8023 	    PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
8024 	    return SECFailure;
8025 	}
8026     } else {
8027 	if (length != sizeof(SSL3Hashes)) {
8028 	    (void)ssl3_IllegalParameter(ss);
8029 	    PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED);
8030 	    return SECFailure;
8031 	}
8032 
8033 	if (0 != NSS_SecureMemcmp(hashes, b, length)) {
8034 	    (void)ssl3_HandshakeFailure(ss);
8035 	    PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
8036 	    return SECFailure;
8037 	}
8038     }
8039 
8040     doStepUp = (PRBool)(!isServer && ss->ssl3.hs.rehandshake);
8041 
8042     ssl_GetXmitBufLock(ss);	/*************************************/
8043 
8044     if ((isServer && !ss->ssl3.hs.isResuming) ||
8045 	(!isServer && ss->ssl3.hs.isResuming)) {
8046 	PRInt32 flags = 0;
8047 
8048 	/* Send a NewSessionTicket message if the client sent us
8049 	 * either an empty session ticket, or one that did not verify.
8050 	 * (Note that if either of these conditions was met, then the
8051 	 * server has sent a SessionTicket extension in the
8052 	 * ServerHello message.)
8053 	 */
8054 	if (isServer && !ss->ssl3.hs.isResuming &&
8055 	    ssl3_ExtensionNegotiated(ss, session_ticket_xtn)) {
8056 	    rv = ssl3_SendNewSessionTicket(ss);
8057 	    if (rv != SECSuccess) {
8058 		goto xmit_loser;
8059 	    }
8060 	}
8061 
8062 	rv = ssl3_SendChangeCipherSpecs(ss);
8063 	if (rv != SECSuccess) {
8064 	    goto xmit_loser;	/* err is set. */
8065 	}
8066 	/* If this thread is in SSL_SecureSend (trying to write some data)
8067 	** or if it is going to step up,
8068 	** then set the ssl_SEND_FLAG_FORCE_INTO_BUFFER flag, so that the
8069 	** last two handshake messages (change cipher spec and finished)
8070 	** will be sent in the same send/write call as the application data.
8071 	*/
8072 	if (doStepUp || ss->writerThread == PR_GetCurrentThread()) {
8073 	    flags = ssl_SEND_FLAG_FORCE_INTO_BUFFER;
8074 	}
8075 	rv = ssl3_SendFinished(ss, flags);
8076 	if (rv != SECSuccess) {
8077 	    goto xmit_loser;	/* err is set. */
8078 	}
8079     }
8080 
8081     /* Optimization: don't cache this connection if we're going to step up. */
8082     if (doStepUp) {
8083 	ssl_FreeSID(sid);
8084 	ss->sec.ci.sid     = sid = NULL;
8085 	ss->ssl3.hs.rehandshake = PR_FALSE;
8086 	rv = ssl3_SendClientHello(ss);
8087 xmit_loser:
8088 	ssl_ReleaseXmitBufLock(ss);
8089 	return rv;	/* err code is set if appropriate. */
8090     }
8091 
8092     ssl_ReleaseXmitBufLock(ss);	/*************************************/
8093 
8094     /* The first handshake is now completed. */
8095     ss->handshake           = NULL;
8096     ss->firstHsDone         = PR_TRUE;
8097     ss->gs.writeOffset = 0;
8098     ss->gs.readOffset  = 0;
8099 
8100     if (ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) {
8101 	effectiveExchKeyType = kt_rsa;
8102     } else {
8103 	effectiveExchKeyType = ss->ssl3.hs.kea_def->exchKeyType;
8104     }
8105 
8106     if (sid->cached == never_cached && !ss->opt.noCache && ss->sec.cache) {
8107 	/* fill in the sid */
8108 	sid->u.ssl3.cipherSuite = ss->ssl3.hs.cipher_suite;
8109 	sid->u.ssl3.compression = ss->ssl3.hs.compression;
8110 	sid->u.ssl3.policy      = ss->ssl3.policy;
8111 #ifdef NSS_ENABLE_ECC
8112 	sid->u.ssl3.negotiatedECCurves = ss->ssl3.hs.negotiatedECCurves;
8113 #endif
8114 	sid->u.ssl3.exchKeyType = effectiveExchKeyType;
8115 	sid->version            = ss->version;
8116 	sid->authAlgorithm      = ss->sec.authAlgorithm;
8117 	sid->authKeyBits        = ss->sec.authKeyBits;
8118 	sid->keaType            = ss->sec.keaType;
8119 	sid->keaKeyBits         = ss->sec.keaKeyBits;
8120 	sid->lastAccessTime     = sid->creationTime = ssl_Time();
8121 	sid->expirationTime     = sid->creationTime + ssl3_sid_timeout;
8122 	sid->localCert          = CERT_DupCertificate(ss->sec.localCert);
8123 
8124 	ssl_GetSpecReadLock(ss);	/*************************************/
8125 
8126 	/* Copy the master secret (wrapped or unwrapped) into the sid */
8127 	if (ss->ssl3.crSpec->msItem.len && ss->ssl3.crSpec->msItem.data) {
8128 	    sid->u.ssl3.keys.wrapped_master_secret_len =
8129 			    ss->ssl3.crSpec->msItem.len;
8130 	    memcpy(sid->u.ssl3.keys.wrapped_master_secret,
8131 		   ss->ssl3.crSpec->msItem.data, ss->ssl3.crSpec->msItem.len);
8132 	    sid->u.ssl3.masterValid    = PR_TRUE;
8133 	    sid->u.ssl3.keys.msIsWrapped = PR_FALSE;
8134 	    rv = SECSuccess;
8135 	} else {
8136 	    rv = ssl3_CacheWrappedMasterSecret(ss, ss->sec.ci.sid,
8137 					       ss->ssl3.crSpec,
8138 					       effectiveExchKeyType);
8139 	    sid->u.ssl3.keys.msIsWrapped = PR_TRUE;
8140 	}
8141 	ssl_ReleaseSpecReadLock(ss);  /*************************************/
8142 
8143 	/* If the wrap failed, we don't cache the sid.
8144 	 * The connection continues normally however.
8145 	 */
8146 	if (rv == SECSuccess) {
8147 	    (*ss->sec.cache)(sid);
8148 	}
8149     }
8150     ss->ssl3.hs.ws = idle_handshake;
8151 
8152     /* Do the handshake callback for sslv3 here. */
8153     if (ss->handshakeCallback != NULL) {
8154 	(ss->handshakeCallback)(ss->fd, ss->handshakeCallbackData);
8155     }
8156 
8157     return SECSuccess;
8158 }
8159 
8160 /* Called from ssl3_HandleHandshake() when it has gathered a complete ssl3
8161  * hanshake message.
8162  * Caller must hold Handshake and RecvBuf locks.
8163  */
8164 static SECStatus
ssl3_HandleHandshakeMessage(sslSocket * ss,SSL3Opaque * b,PRUint32 length)8165 ssl3_HandleHandshakeMessage(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
8166 {
8167     SECStatus         rv 	= SECSuccess;
8168     SSL3HandshakeType type 	= ss->ssl3.hs.msg_type;
8169     SSL3Hashes        hashes;	/* computed hashes are put here. */
8170     PRUint8           hdr[4];
8171 
8172     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
8173     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
8174     /*
8175      * We have to compute the hashes before we update them with the
8176      * current message.
8177      */
8178     ssl_GetSpecReadLock(ss);	/************************************/
8179     if((type == finished) || (type == certificate_verify)) {
8180 	SSL3Sender      sender = (SSL3Sender)0;
8181 	ssl3CipherSpec *rSpec  = ss->ssl3.prSpec;
8182 
8183 	if (type == finished) {
8184 	    sender = ss->sec.isServer ? sender_client : sender_server;
8185 	    rSpec  = ss->ssl3.crSpec;
8186 	}
8187 	rv = ssl3_ComputeHandshakeHashes(ss, rSpec, &hashes, sender);
8188     }
8189     ssl_ReleaseSpecReadLock(ss); /************************************/
8190     if (rv != SECSuccess) {
8191 	return rv;	/* error code was set by ssl3_ComputeHandshakeHashes*/
8192     }
8193     SSL_TRC(30,("%d: SSL3[%d]: handle handshake message: %s", SSL_GETPID(),
8194 		ss->fd, ssl3_DecodeHandshakeType(ss->ssl3.hs.msg_type)));
8195     PRINT_BUF(60, (ss, "MD5 handshake hash:",
8196     	      (unsigned char*)ss->ssl3.hs.md5_cx, MD5_LENGTH));
8197     PRINT_BUF(95, (ss, "SHA handshake hash:",
8198     	      (unsigned char*)ss->ssl3.hs.sha_cx, SHA1_LENGTH));
8199 
8200     hdr[0] = (PRUint8)ss->ssl3.hs.msg_type;
8201     hdr[1] = (PRUint8)(length >> 16);
8202     hdr[2] = (PRUint8)(length >>  8);
8203     hdr[3] = (PRUint8)(length      );
8204 
8205     /* Start new handshake hashes when we start a new handshake */
8206     if (ss->ssl3.hs.msg_type == client_hello) {
8207 	SSL_TRC(30,("%d: SSL3[%d]: reset handshake hashes",
8208 		SSL_GETPID(), ss->fd ));
8209 	rv = ssl3_RestartHandshakeHashes(ss);
8210 	if (rv != SECSuccess) {
8211 	    return rv;
8212 	}
8213     }
8214     /* We should not include hello_request messages in the handshake hashes */
8215     if (ss->ssl3.hs.msg_type != hello_request) {
8216 	rv = ssl3_UpdateHandshakeHashes(ss, (unsigned char*) hdr, 4);
8217 	if (rv != SECSuccess) return rv;	/* err code already set. */
8218 	rv = ssl3_UpdateHandshakeHashes(ss, b, length);
8219 	if (rv != SECSuccess) return rv;	/* err code already set. */
8220     }
8221 
8222     PORT_SetError(0);	/* each message starts with no error. */
8223     switch (ss->ssl3.hs.msg_type) {
8224     case hello_request:
8225 	if (length != 0) {
8226 	    (void)ssl3_DecodeError(ss);
8227 	    PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_REQUEST);
8228 	    return SECFailure;
8229 	}
8230 	if (ss->sec.isServer) {
8231 	    (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
8232 	    PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST);
8233 	    return SECFailure;
8234 	}
8235 	rv = ssl3_HandleHelloRequest(ss);
8236 	break;
8237     case client_hello:
8238 	if (!ss->sec.isServer) {
8239 	    (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
8240 	    PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO);
8241 	    return SECFailure;
8242 	}
8243 	rv = ssl3_HandleClientHello(ss, b, length);
8244 	break;
8245     case server_hello:
8246 	if (ss->sec.isServer) {
8247 	    (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
8248 	    PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO);
8249 	    return SECFailure;
8250 	}
8251 	rv = ssl3_HandleServerHello(ss, b, length);
8252 	break;
8253     case certificate:
8254 	rv = ssl3_HandleCertificate(ss, b, length);
8255 	break;
8256     case server_key_exchange:
8257 	if (ss->sec.isServer) {
8258 	    (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
8259 	    PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH);
8260 	    return SECFailure;
8261 	}
8262 	rv = ssl3_HandleServerKeyExchange(ss, b, length);
8263 	break;
8264     case certificate_request:
8265 	if (ss->sec.isServer) {
8266 	    (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
8267 	    PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST);
8268 	    return SECFailure;
8269 	}
8270 	rv = ssl3_HandleCertificateRequest(ss, b, length);
8271 	break;
8272     case server_hello_done:
8273 	if (length != 0) {
8274 	    (void)ssl3_DecodeError(ss);
8275 	    PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_DONE);
8276 	    return SECFailure;
8277 	}
8278 	if (ss->sec.isServer) {
8279 	    (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
8280 	    PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE);
8281 	    return SECFailure;
8282 	}
8283 	rv = ssl3_HandleServerHelloDone(ss);
8284 	break;
8285     case certificate_verify:
8286 	if (!ss->sec.isServer) {
8287 	    (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
8288 	    PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY);
8289 	    return SECFailure;
8290 	}
8291 	rv = ssl3_HandleCertificateVerify(ss, b, length, &hashes);
8292 	break;
8293     case client_key_exchange:
8294 	if (!ss->sec.isServer) {
8295 	    (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
8296 	    PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH);
8297 	    return SECFailure;
8298 	}
8299 	rv = ssl3_HandleClientKeyExchange(ss, b, length);
8300 	break;
8301     case new_session_ticket:
8302 	if (ss->sec.isServer) {
8303 	    (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
8304 	    PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET);
8305 	    return SECFailure;
8306 	}
8307 	rv = ssl3_HandleNewSessionTicket(ss, b, length);
8308 	break;
8309     case finished:
8310         rv = ssl3_HandleFinished(ss, b, length, &hashes);
8311 	break;
8312     default:
8313 	(void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
8314 	PORT_SetError(SSL_ERROR_RX_UNKNOWN_HANDSHAKE);
8315 	rv = SECFailure;
8316     }
8317     return rv;
8318 }
8319 
8320 /* Called only from ssl3_HandleRecord, for each (deciphered) ssl3 record.
8321  * origBuf is the decrypted ssl record content.
8322  * Caller must hold the handshake and RecvBuf locks.
8323  */
8324 static SECStatus
ssl3_HandleHandshake(sslSocket * ss,sslBuffer * origBuf)8325 ssl3_HandleHandshake(sslSocket *ss, sslBuffer *origBuf)
8326 {
8327     /*
8328      * There may be a partial handshake message already in the handshake
8329      * state. The incoming buffer may contain another portion, or a
8330      * complete message or several messages followed by another portion.
8331      *
8332      * Each message is made contiguous before being passed to the actual
8333      * message parser.
8334      */
8335     sslBuffer *buf = &ss->ssl3.hs.msgState; /* do not lose the original buffer pointer */
8336     SECStatus rv;
8337 
8338     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
8339     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
8340 
8341     if (buf->buf == NULL) {
8342 	*buf = *origBuf;
8343     }
8344     while (buf->len > 0) {
8345 	if (ss->ssl3.hs.header_bytes < 4) {
8346 	    uint8 t;
8347 	    t = *(buf->buf++);
8348 	    buf->len--;
8349 	    if (ss->ssl3.hs.header_bytes++ == 0)
8350 		ss->ssl3.hs.msg_type = (SSL3HandshakeType)t;
8351 	    else
8352 		ss->ssl3.hs.msg_len = (ss->ssl3.hs.msg_len << 8) + t;
8353 	    if (ss->ssl3.hs.header_bytes < 4)
8354 	    	continue;
8355 
8356 #define MAX_HANDSHAKE_MSG_LEN 0x1ffff	/* 128k - 1 */
8357 	    if (ss->ssl3.hs.msg_len > MAX_HANDSHAKE_MSG_LEN) {
8358 		(void)ssl3_DecodeError(ss);
8359 		PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
8360 		return SECFailure;
8361 	    }
8362 #undef MAX_HANDSHAKE_MSG_LEN
8363 
8364 	    /* If msg_len is zero, be sure we fall through,
8365 	    ** even if buf->len is zero.
8366 	    */
8367 	    if (ss->ssl3.hs.msg_len > 0)
8368 	    	continue;
8369 	}
8370 
8371 	/*
8372 	 * Header has been gathered and there is at least one byte of new
8373 	 * data available for this message. If it can be done right out
8374 	 * of the original buffer, then use it from there.
8375 	 */
8376 	if (ss->ssl3.hs.msg_body.len == 0 && buf->len >= ss->ssl3.hs.msg_len) {
8377 	    /* handle it from input buffer */
8378 	    rv = ssl3_HandleHandshakeMessage(ss, buf->buf, ss->ssl3.hs.msg_len);
8379 	    if (rv == SECFailure) {
8380 		/* This test wants to fall through on either
8381 		 * SECSuccess or SECWouldBlock.
8382 		 * ssl3_HandleHandshakeMessage MUST set the error code.
8383 		 */
8384 		return rv;
8385 	    }
8386 	    buf->buf += ss->ssl3.hs.msg_len;
8387 	    buf->len -= ss->ssl3.hs.msg_len;
8388 	    ss->ssl3.hs.msg_len = 0;
8389 	    ss->ssl3.hs.header_bytes = 0;
8390 	    if (rv != SECSuccess) { /* return if SECWouldBlock. */
8391 		return rv;
8392 	    }
8393 	} else {
8394 	    /* must be copied to msg_body and dealt with from there */
8395 	    unsigned int bytes;
8396 
8397 	    PORT_Assert(ss->ssl3.hs.msg_body.len <= ss->ssl3.hs.msg_len);
8398 	    bytes = PR_MIN(buf->len, ss->ssl3.hs.msg_len - ss->ssl3.hs.msg_body.len);
8399 
8400 	    /* Grow the buffer if needed */
8401 	    rv = sslBuffer_Grow(&ss->ssl3.hs.msg_body, ss->ssl3.hs.msg_len);
8402 	    if (rv != SECSuccess) {
8403 		/* sslBuffer_Grow has set a memory error code. */
8404 		return SECFailure;
8405 	    }
8406 
8407 	    PORT_Memcpy(ss->ssl3.hs.msg_body.buf + ss->ssl3.hs.msg_body.len,
8408 		        buf->buf, bytes);
8409 	    ss->ssl3.hs.msg_body.len += bytes;
8410 	    buf->buf += bytes;
8411 	    buf->len -= bytes;
8412 
8413 	    PORT_Assert(ss->ssl3.hs.msg_body.len <= ss->ssl3.hs.msg_len);
8414 
8415 	    /* if we have a whole message, do it */
8416 	    if (ss->ssl3.hs.msg_body.len == ss->ssl3.hs.msg_len) {
8417 		rv = ssl3_HandleHandshakeMessage(
8418 		    ss, ss->ssl3.hs.msg_body.buf, ss->ssl3.hs.msg_len);
8419 		/*
8420 		 * XXX This appears to be wrong.  This error handling
8421 		 * should clean up after a SECWouldBlock return, like the
8422 		 * error handling used 40 lines before/above this one,
8423 		 */
8424 		if (rv != SECSuccess) {
8425 		    /* ssl3_HandleHandshakeMessage MUST set error code. */
8426 		    return rv;
8427 		}
8428 		ss->ssl3.hs.msg_body.len = 0;
8429 		ss->ssl3.hs.msg_len      = 0;
8430 		ss->ssl3.hs.header_bytes = 0;
8431 	    } else {
8432 		PORT_Assert(buf->len == 0);
8433 		break;
8434 	    }
8435 	}
8436     }	/* end loop */
8437 
8438     origBuf->len = 0;	/* So ssl3_GatherAppDataRecord will keep looping. */
8439     buf->buf = NULL;	/* not a leak. */
8440     return SECSuccess;
8441 }
8442 
8443 /* if cText is non-null, then decipher, check MAC, and decompress the
8444  * SSL record from cText->buf (typically gs->inbuf)
8445  * into databuf (typically gs->buf), and any previous contents of databuf
8446  * is lost.  Then handle databuf according to its SSL record type,
8447  * unless it's an application record.
8448  *
8449  * If cText is NULL, then the ciphertext has previously been deciphered and
8450  * checked, and is already sitting in databuf.  It is processed as an SSL
8451  * Handshake message.
8452  *
8453  * DOES NOT process the decrypted/decompressed application data.
8454  * On return, databuf contains the decrypted/decompressed record.
8455  *
8456  * Called from ssl3_GatherCompleteHandshake
8457  *             ssl3_RestartHandshakeAfterCertReq
8458  *             ssl3_RestartHandshakeAfterServerCert
8459  *
8460  * Caller must hold the RecvBufLock.
8461  *
8462  * This function aquires and releases the SSL3Handshake Lock, holding the
8463  * lock around any calls to functions that handle records other than
8464  * Application Data records.
8465  */
8466 SECStatus
ssl3_HandleRecord(sslSocket * ss,SSL3Ciphertext * cText,sslBuffer * databuf)8467 ssl3_HandleRecord(sslSocket *ss, SSL3Ciphertext *cText, sslBuffer *databuf)
8468 {
8469 const ssl3BulkCipherDef *cipher_def;
8470     ssl3CipherSpec *     crSpec;
8471     SECStatus            rv;
8472     unsigned int         hashBytes		= MAX_MAC_LENGTH + 1;
8473     unsigned int         padding_length;
8474     PRBool               isTLS;
8475     PRBool               padIsBad               = PR_FALSE;
8476     SSL3ContentType      rType;
8477     SSL3Opaque           hash[MAX_MAC_LENGTH];
8478     sslBuffer           *plaintext;
8479     sslBuffer            temp_buf;
8480 
8481     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
8482 
8483     if (!ss->ssl3.initialized) {
8484 	ssl_GetSSL3HandshakeLock(ss);
8485 	rv = ssl3_InitState(ss);
8486 	ssl_ReleaseSSL3HandshakeLock(ss);
8487 	if (rv != SECSuccess) {
8488 	    return rv;		/* ssl3_InitState has set the error code. */
8489     	}
8490     }
8491 
8492     /* check for Token Presence */
8493     if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) {
8494 	PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
8495 	return SECFailure;
8496     }
8497 
8498     /* cText is NULL when we're called from ssl3_RestartHandshakeAfterXXX().
8499      * This implies that databuf holds a previously deciphered SSL Handshake
8500      * message.
8501      */
8502     if (cText == NULL) {
8503 	SSL_DBG(("%d: SSL3[%d]: HandleRecord, resuming handshake",
8504 		 SSL_GETPID(), ss->fd));
8505 	rType = content_handshake;
8506 	goto process_it;
8507     }
8508 
8509     ssl_GetSpecReadLock(ss); /******************************************/
8510 
8511     crSpec = ss->ssl3.crSpec;
8512 
8513     /* If we will be decompressing the buffer we need to decrypt somewhere
8514      * other than into databuf */
8515     if (crSpec->decompressor) {
8516 	temp_buf.buf = NULL;
8517 	temp_buf.space = 0;
8518 	plaintext = &temp_buf;
8519     } else {
8520 	plaintext = databuf;
8521     }
8522 
8523     plaintext->len = 0; /* filled in by decode call below. */
8524     if (plaintext->space < MAX_FRAGMENT_LENGTH) {
8525 	rv = sslBuffer_Grow(plaintext, MAX_FRAGMENT_LENGTH + 2048);
8526 	if (rv != SECSuccess) {
8527 	    ssl_ReleaseSpecReadLock(ss);
8528 	    SSL_DBG(("%d: SSL3[%d]: HandleRecord, tried to get %d bytes",
8529 		     SSL_GETPID(), ss->fd, MAX_FRAGMENT_LENGTH + 2048));
8530 	    /* sslBuffer_Grow has set a memory error code. */
8531 	    /* Perhaps we should send an alert. (but we have no memory!) */
8532 	    return SECFailure;
8533 	}
8534     }
8535 
8536     PRINT_BUF(80, (ss, "ciphertext:", cText->buf->buf, cText->buf->len));
8537 
8538     cipher_def = crSpec->cipher_def;
8539     isTLS = (PRBool)(crSpec->version > SSL_LIBRARY_VERSION_3_0);
8540 
8541     if (isTLS && cText->buf->len > (MAX_FRAGMENT_LENGTH + 2048)) {
8542 	ssl_ReleaseSpecReadLock(ss);
8543 	SSL3_SendAlert(ss, alert_fatal, record_overflow);
8544 	PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
8545 	return SECFailure;
8546     }
8547 
8548     /* decrypt from cText buf to plaintext. */
8549     rv = crSpec->decode(
8550 	crSpec->decodeContext, plaintext->buf, (int *)&plaintext->len,
8551 	plaintext->space, cText->buf->buf, cText->buf->len);
8552 
8553     PRINT_BUF(80, (ss, "cleartext:", plaintext->buf, plaintext->len));
8554     if (rv != SECSuccess) {
8555 	int err = ssl_MapLowLevelError(SSL_ERROR_DECRYPTION_FAILURE);
8556 	ssl_ReleaseSpecReadLock(ss);
8557 	SSL3_SendAlert(ss, alert_fatal,
8558 	               isTLS ? decryption_failed : bad_record_mac);
8559 	PORT_SetError(err);
8560 	return SECFailure;
8561     }
8562 
8563     /* If it's a block cipher, check and strip the padding. */
8564     if (cipher_def->type == type_block) {
8565 	padding_length = *(plaintext->buf + plaintext->len - 1);
8566 	/* TLS permits padding to exceed the block size, up to 255 bytes. */
8567 	if (padding_length + 1 + crSpec->mac_size > plaintext->len)
8568 	    padIsBad = PR_TRUE;
8569 	/* if TLS, check value of first padding byte. */
8570 	else if (padding_length && isTLS &&
8571 	         padding_length != *(plaintext->buf +
8572 	                             plaintext->len - (padding_length + 1)))
8573 	    padIsBad = PR_TRUE;
8574 	else
8575 	    plaintext->len -= padding_length + 1;
8576     }
8577 
8578     /* Remove the MAC. */
8579     if (plaintext->len >= crSpec->mac_size)
8580 	plaintext->len -= crSpec->mac_size;
8581     else
8582     	padIsBad = PR_TRUE;	/* really macIsBad */
8583 
8584     /* compute the MAC */
8585     rType = cText->type;
8586     rv = ssl3_ComputeRecordMAC( crSpec, (PRBool)(!ss->sec.isServer),
8587 	rType, cText->version, crSpec->read_seq_num,
8588 	plaintext->buf, plaintext->len, hash, &hashBytes);
8589     if (rv != SECSuccess) {
8590 	int err = ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
8591 	ssl_ReleaseSpecReadLock(ss);
8592 	SSL3_SendAlert(ss, alert_fatal, bad_record_mac);
8593 	PORT_SetError(err);
8594 	return rv;
8595     }
8596 
8597     /* Check the MAC */
8598     if (hashBytes != (unsigned)crSpec->mac_size || padIsBad ||
8599 	NSS_SecureMemcmp(plaintext->buf + plaintext->len, hash,
8600 	                 crSpec->mac_size) != 0) {
8601 	/* must not hold spec lock when calling SSL3_SendAlert. */
8602 	ssl_ReleaseSpecReadLock(ss);
8603 	SSL3_SendAlert(ss, alert_fatal, bad_record_mac);
8604 	/* always log mac error, in case attacker can read server logs. */
8605 	PORT_SetError(SSL_ERROR_BAD_MAC_READ);
8606 
8607 	SSL_DBG(("%d: SSL3[%d]: mac check failed", SSL_GETPID(), ss->fd));
8608 
8609 	return SECFailure;
8610     }
8611 
8612 
8613 
8614     ssl3_BumpSequenceNumber(&crSpec->read_seq_num);
8615 
8616     ssl_ReleaseSpecReadLock(ss); /*****************************************/
8617 
8618     /*
8619      * The decrypted data is now in plaintext.
8620      */
8621 
8622     /* possibly decompress the record. If we aren't using compression then
8623      * plaintext == databuf and so the uncompressed data is already in
8624      * databuf. */
8625     if (crSpec->decompressor) {
8626 	if (databuf->space < plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION) {
8627 	    rv = sslBuffer_Grow(
8628 	        databuf, plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION);
8629 	    if (rv != SECSuccess) {
8630 		SSL_DBG(("%d: SSL3[%d]: HandleRecord, tried to get %d bytes",
8631 			 SSL_GETPID(), ss->fd,
8632 			 plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION));
8633 		/* sslBuffer_Grow has set a memory error code. */
8634 		/* Perhaps we should send an alert. (but we have no memory!) */
8635 		PORT_Free(plaintext->buf);
8636 		return SECFailure;
8637 	    }
8638 	}
8639 
8640 	rv = crSpec->decompressor(crSpec->decompressContext,
8641 				  databuf->buf,
8642 				  (int*) &databuf->len,
8643 				  databuf->space,
8644 				  plaintext->buf,
8645 				  plaintext->len);
8646 	if (rv != SECSuccess) {
8647 	    int err = ssl_MapLowLevelError(SSL_ERROR_DECOMPRESSION_FAILURE);
8648 	    PORT_Free(plaintext->buf);
8649 	    SSL3_SendAlert(ss, alert_fatal,
8650 			   isTLS ? decompression_failure : bad_record_mac);
8651 	    PORT_SetError(err);
8652 	    return SECFailure;
8653 	}
8654 
8655 	PORT_Free(plaintext->buf);
8656     }
8657 
8658     /*
8659     ** Having completed the decompression, check the length again.
8660     */
8661     if (isTLS && databuf->len > (MAX_FRAGMENT_LENGTH + 1024)) {
8662 	SSL3_SendAlert(ss, alert_fatal, record_overflow);
8663 	PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
8664 	return SECFailure;
8665     }
8666 
8667     /* Application data records are processed by the caller of this
8668     ** function, not by this function.
8669     */
8670     if (rType == content_application_data) {
8671     	return SECSuccess;
8672     }
8673 
8674     /* It's a record that must be handled by ssl itself, not the application.
8675     */
8676 process_it:
8677     /* XXX  Get the xmit lock here.  Odds are very high that we'll be xmiting
8678      * data ang getting the xmit lock here prevents deadlocks.
8679      */
8680     ssl_GetSSL3HandshakeLock(ss);
8681 
8682     /* All the functions called in this switch MUST set error code if
8683     ** they return SECFailure or SECWouldBlock.
8684     */
8685     switch (rType) {
8686     case content_change_cipher_spec:
8687 	rv = ssl3_HandleChangeCipherSpecs(ss, databuf);
8688 	break;
8689     case content_alert:
8690 	rv = ssl3_HandleAlert(ss, databuf);
8691 	break;
8692     case content_handshake:
8693 	rv = ssl3_HandleHandshake(ss, databuf);
8694 	break;
8695     /*
8696     case content_application_data is handled before this switch
8697     */
8698     default:
8699 	SSL_DBG(("%d: SSL3[%d]: bogus content type=%d",
8700 		 SSL_GETPID(), ss->fd, cText->type));
8701 	/* XXX Send an alert ???  */
8702 	PORT_SetError(SSL_ERROR_RX_UNKNOWN_RECORD_TYPE);
8703 	rv = SECFailure;
8704 	break;
8705     }
8706 
8707     ssl_ReleaseSSL3HandshakeLock(ss);
8708     return rv;
8709 
8710 }
8711 
8712 /*
8713  * Initialization functions
8714  */
8715 
8716 /* Called from ssl3_InitState, immediately below. */
8717 /* Caller must hold the SpecWriteLock. */
8718 static void
ssl3_InitCipherSpec(sslSocket * ss,ssl3CipherSpec * spec)8719 ssl3_InitCipherSpec(sslSocket *ss, ssl3CipherSpec *spec)
8720 {
8721     spec->cipher_def               = &bulk_cipher_defs[cipher_null];
8722     PORT_Assert(spec->cipher_def->cipher == cipher_null);
8723     spec->mac_def                  = &mac_defs[mac_null];
8724     PORT_Assert(spec->mac_def->mac == mac_null);
8725     spec->encode                   = Null_Cipher;
8726     spec->decode                   = Null_Cipher;
8727     spec->destroy                  = NULL;
8728     spec->compressor               = NULL;
8729     spec->decompressor             = NULL;
8730     spec->destroyCompressContext   = NULL;
8731     spec->destroyDecompressContext = NULL;
8732     spec->mac_size                 = 0;
8733     spec->master_secret            = NULL;
8734     spec->bypassCiphers            = PR_FALSE;
8735 
8736     spec->msItem.data              = NULL;
8737     spec->msItem.len               = 0;
8738 
8739     spec->client.write_key         = NULL;
8740     spec->client.write_mac_key     = NULL;
8741     spec->client.write_mac_context = NULL;
8742 
8743     spec->server.write_key         = NULL;
8744     spec->server.write_mac_key     = NULL;
8745     spec->server.write_mac_context = NULL;
8746 
8747     spec->write_seq_num.high       = 0;
8748     spec->write_seq_num.low        = 0;
8749 
8750     spec->read_seq_num.high        = 0;
8751     spec->read_seq_num.low         = 0;
8752 
8753     spec->version                  = ss->opt.enableTLS
8754                                           ? SSL_LIBRARY_VERSION_3_1_TLS
8755                                           : SSL_LIBRARY_VERSION_3_0;
8756 }
8757 
8758 /* Called from:	ssl3_SendRecord
8759 **		ssl3_StartHandshakeHash() <- ssl2_BeginClientHandshake()
8760 **		ssl3_SendClientHello()
8761 **		ssl3_HandleServerHello()
8762 **		ssl3_HandleClientHello()
8763 **		ssl3_HandleV2ClientHello()
8764 **		ssl3_HandleRecord()
8765 **
8766 ** This function should perhaps acquire and release the SpecWriteLock.
8767 **
8768 **
8769 */
8770 static SECStatus
ssl3_InitState(sslSocket * ss)8771 ssl3_InitState(sslSocket *ss)
8772 {
8773     SECStatus    rv;
8774     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
8775 
8776     if (ss->ssl3.initialized)
8777     	return SECSuccess;	/* Function should be idempotent */
8778 
8779     ss->ssl3.policy = SSL_ALLOWED;
8780 
8781     ssl_GetSpecWriteLock(ss);
8782     ss->ssl3.crSpec = ss->ssl3.cwSpec = &ss->ssl3.specs[0];
8783     ss->ssl3.prSpec = ss->ssl3.pwSpec = &ss->ssl3.specs[1];
8784     ss->ssl3.hs.rehandshake = PR_FALSE;
8785     ssl3_InitCipherSpec(ss, ss->ssl3.crSpec);
8786     ssl3_InitCipherSpec(ss, ss->ssl3.prSpec);
8787 
8788     ss->ssl3.hs.ws = (ss->sec.isServer) ? wait_client_hello : wait_server_hello;
8789 #ifdef NSS_ENABLE_ECC
8790     ss->ssl3.hs.negotiatedECCurves = SSL3_SUPPORTED_CURVES_MASK;
8791 #endif
8792     ssl_ReleaseSpecWriteLock(ss);
8793 
8794     PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData));
8795 
8796     rv = ssl3_NewHandshakeHashes(ss);
8797     if (rv == SECSuccess) {
8798 	ss->ssl3.initialized = PR_TRUE;
8799     }
8800 
8801     return rv;
8802 }
8803 
8804 /* Returns a reference counted object that contains a key pair.
8805  * Or NULL on failure.  Initial ref count is 1.
8806  * Uses the keys in the pair as input.
8807  */
8808 ssl3KeyPair *
ssl3_NewKeyPair(SECKEYPrivateKey * privKey,SECKEYPublicKey * pubKey)8809 ssl3_NewKeyPair( SECKEYPrivateKey * privKey, SECKEYPublicKey * pubKey)
8810 {
8811     ssl3KeyPair * pair;
8812 
8813     if (!privKey || !pubKey) {
8814 	PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
8815     	return NULL;
8816     }
8817     pair = PORT_ZNew(ssl3KeyPair);
8818     if (!pair)
8819     	return NULL;			/* error code is set. */
8820     pair->refCount = 1;
8821     pair->privKey  = privKey;
8822     pair->pubKey   = pubKey;
8823     return pair;			/* success */
8824 }
8825 
8826 ssl3KeyPair *
ssl3_GetKeyPairRef(ssl3KeyPair * keyPair)8827 ssl3_GetKeyPairRef(ssl3KeyPair * keyPair)
8828 {
8829     PR_AtomicIncrement(&keyPair->refCount);
8830     return keyPair;
8831 }
8832 
8833 void
ssl3_FreeKeyPair(ssl3KeyPair * keyPair)8834 ssl3_FreeKeyPair(ssl3KeyPair * keyPair)
8835 {
8836     PRInt32 newCount =  PR_AtomicDecrement(&keyPair->refCount);
8837     if (!newCount) {
8838 	if (keyPair->privKey)
8839 	    SECKEY_DestroyPrivateKey(keyPair->privKey);
8840 	if (keyPair->pubKey)
8841 	    SECKEY_DestroyPublicKey( keyPair->pubKey);
8842     	PORT_Free(keyPair);
8843     }
8844 }
8845 
8846 
8847 
8848 /*
8849  * Creates the public and private RSA keys for SSL Step down.
8850  * Called from SSL_ConfigSecureServer in sslsecur.c
8851  */
8852 SECStatus
ssl3_CreateRSAStepDownKeys(sslSocket * ss)8853 ssl3_CreateRSAStepDownKeys(sslSocket *ss)
8854 {
8855     SECStatus             rv  	 = SECSuccess;
8856     SECKEYPrivateKey *    privKey;		/* RSA step down key */
8857     SECKEYPublicKey *     pubKey;		/* RSA step down key */
8858 
8859     if (ss->stepDownKeyPair)
8860 	ssl3_FreeKeyPair(ss->stepDownKeyPair);
8861     ss->stepDownKeyPair = NULL;
8862 #ifndef HACKED_EXPORT_SERVER
8863     /* Sigh, should have a get key strength call for private keys */
8864     if (PK11_GetPrivateModulusLen(ss->serverCerts[kt_rsa].SERVERKEY) >
8865                                                      EXPORT_RSA_KEY_LENGTH) {
8866 	/* need to ask for the key size in bits */
8867 	privKey = SECKEY_CreateRSAPrivateKey(EXPORT_RSA_KEY_LENGTH * BPB,
8868 					     &pubKey, NULL);
8869     	if (!privKey || !pubKey ||
8870 	    !(ss->stepDownKeyPair = ssl3_NewKeyPair(privKey, pubKey))) {
8871 	    ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL);
8872 	    rv = SECFailure;
8873 	}
8874     }
8875 #endif
8876     return rv;
8877 }
8878 
8879 
8880 /* record the export policy for this cipher suite */
8881 SECStatus
ssl3_SetPolicy(ssl3CipherSuite which,int policy)8882 ssl3_SetPolicy(ssl3CipherSuite which, int policy)
8883 {
8884     ssl3CipherSuiteCfg *suite;
8885 
8886     suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
8887     if (suite == NULL) {
8888 	return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
8889     }
8890     suite->policy = policy;
8891 
8892     if (policy == SSL_RESTRICTED) {
8893 	ssl3_global_policy_some_restricted = PR_TRUE;
8894     }
8895 
8896     return SECSuccess;
8897 }
8898 
8899 SECStatus
ssl3_GetPolicy(ssl3CipherSuite which,PRInt32 * oPolicy)8900 ssl3_GetPolicy(ssl3CipherSuite which, PRInt32 *oPolicy)
8901 {
8902     ssl3CipherSuiteCfg *suite;
8903     PRInt32             policy;
8904     SECStatus           rv;
8905 
8906     suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
8907     if (suite) {
8908     	policy = suite->policy;
8909 	rv     = SECSuccess;
8910     } else {
8911     	policy = SSL_NOT_ALLOWED;
8912 	rv     = SECFailure;	/* err code was set by Lookup. */
8913     }
8914     *oPolicy = policy;
8915     return rv;
8916 }
8917 
8918 /* record the user preference for this suite */
8919 SECStatus
ssl3_CipherPrefSetDefault(ssl3CipherSuite which,PRBool enabled)8920 ssl3_CipherPrefSetDefault(ssl3CipherSuite which, PRBool enabled)
8921 {
8922     ssl3CipherSuiteCfg *suite;
8923 
8924     suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
8925     if (suite == NULL) {
8926 	return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
8927     }
8928     suite->enabled = enabled;
8929     return SECSuccess;
8930 }
8931 
8932 /* return the user preference for this suite */
8933 SECStatus
ssl3_CipherPrefGetDefault(ssl3CipherSuite which,PRBool * enabled)8934 ssl3_CipherPrefGetDefault(ssl3CipherSuite which, PRBool *enabled)
8935 {
8936     ssl3CipherSuiteCfg *suite;
8937     PRBool              pref;
8938     SECStatus           rv;
8939 
8940     suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
8941     if (suite) {
8942     	pref   = suite->enabled;
8943 	rv     = SECSuccess;
8944     } else {
8945     	pref   = SSL_NOT_ALLOWED;
8946 	rv     = SECFailure;	/* err code was set by Lookup. */
8947     }
8948     *enabled = pref;
8949     return rv;
8950 }
8951 
8952 SECStatus
ssl3_CipherPrefSet(sslSocket * ss,ssl3CipherSuite which,PRBool enabled)8953 ssl3_CipherPrefSet(sslSocket *ss, ssl3CipherSuite which, PRBool enabled)
8954 {
8955     ssl3CipherSuiteCfg *suite;
8956 
8957     suite = ssl_LookupCipherSuiteCfg(which, ss->cipherSuites);
8958     if (suite == NULL) {
8959 	return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
8960     }
8961     suite->enabled = enabled;
8962     return SECSuccess;
8963 }
8964 
8965 SECStatus
ssl3_CipherPrefGet(sslSocket * ss,ssl3CipherSuite which,PRBool * enabled)8966 ssl3_CipherPrefGet(sslSocket *ss, ssl3CipherSuite which, PRBool *enabled)
8967 {
8968     ssl3CipherSuiteCfg *suite;
8969     PRBool              pref;
8970     SECStatus           rv;
8971 
8972     suite = ssl_LookupCipherSuiteCfg(which, ss->cipherSuites);
8973     if (suite) {
8974     	pref   = suite->enabled;
8975 	rv     = SECSuccess;
8976     } else {
8977     	pref   = SSL_NOT_ALLOWED;
8978 	rv     = SECFailure;	/* err code was set by Lookup. */
8979     }
8980     *enabled = pref;
8981     return rv;
8982 }
8983 
8984 /* copy global default policy into socket. */
8985 void
ssl3_InitSocketPolicy(sslSocket * ss)8986 ssl3_InitSocketPolicy(sslSocket *ss)
8987 {
8988     PORT_Memcpy(ss->cipherSuites, cipherSuites, sizeof cipherSuites);
8989 }
8990 
8991 /* ssl3_config_match_init must have already been called by
8992  * the caller of this function.
8993  */
8994 SECStatus
ssl3_ConstructV2CipherSpecsHack(sslSocket * ss,unsigned char * cs,int * size)8995 ssl3_ConstructV2CipherSpecsHack(sslSocket *ss, unsigned char *cs, int *size)
8996 {
8997     int i, count = 0;
8998 
8999     PORT_Assert(ss != 0);
9000     if (!ss) {
9001 	PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
9002 	return SECFailure;
9003     }
9004     if (!ss->opt.enableSSL3 && !ss->opt.enableTLS) {
9005     	*size = 0;
9006 	return SECSuccess;
9007     }
9008     if (cs == NULL) {
9009 	*size = count_cipher_suites(ss, SSL_ALLOWED, PR_TRUE);
9010 	return SECSuccess;
9011     }
9012 
9013     /* ssl3_config_match_init was called by the caller of this function. */
9014     for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
9015 	ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i];
9016 	if (config_match(suite, SSL_ALLOWED, PR_TRUE)) {
9017 	    if (cs != NULL) {
9018 		*cs++ = 0x00;
9019 		*cs++ = (suite->cipher_suite >> 8) & 0xFF;
9020 		*cs++ =  suite->cipher_suite       & 0xFF;
9021 	    }
9022 	    count++;
9023 	}
9024     }
9025     *size = count;
9026     return SECSuccess;
9027 }
9028 
9029 /*
9030 ** If ssl3 socket has completed the first handshake, and is in idle state,
9031 ** then start a new handshake.
9032 ** If flushCache is true, the SID cache will be flushed first, forcing a
9033 ** "Full" handshake (not a session restart handshake), to be done.
9034 **
9035 ** called from SSL_RedoHandshake(), which already holds the handshake locks.
9036 */
9037 SECStatus
ssl3_RedoHandshake(sslSocket * ss,PRBool flushCache)9038 ssl3_RedoHandshake(sslSocket *ss, PRBool flushCache)
9039 {
9040     sslSessionID *   sid = ss->sec.ci.sid;
9041     SECStatus        rv;
9042 
9043     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
9044 
9045     if (!ss->firstHsDone ||
9046         ((ss->version >= SSL_LIBRARY_VERSION_3_0) &&
9047 	 ss->ssl3.initialized &&
9048 	 (ss->ssl3.hs.ws != idle_handshake))) {
9049 	PORT_SetError(SSL_ERROR_HANDSHAKE_NOT_COMPLETED);
9050 	return SECFailure;
9051     }
9052     if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) {
9053 	PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED);
9054 	return SECFailure;
9055     }
9056     if (sid && flushCache) {
9057 	ss->sec.uncache(sid);	/* remove it from whichever cache it's in. */
9058 	ssl_FreeSID(sid);	/* dec ref count and free if zero. */
9059 	ss->sec.ci.sid = NULL;
9060     }
9061 
9062     ssl_GetXmitBufLock(ss);	/**************************************/
9063 
9064     /* start off a new handshake. */
9065     rv = (ss->sec.isServer) ? ssl3_SendHelloRequest(ss)
9066                             : ssl3_SendClientHello(ss);
9067 
9068     ssl_ReleaseXmitBufLock(ss);	/**************************************/
9069     return rv;
9070 }
9071 
9072 /* Called from ssl_DestroySocketContents() in sslsock.c */
9073 void
ssl3_DestroySSL3Info(sslSocket * ss)9074 ssl3_DestroySSL3Info(sslSocket *ss)
9075 {
9076 
9077     if (ss->ssl3.clientCertificate != NULL)
9078 	CERT_DestroyCertificate(ss->ssl3.clientCertificate);
9079 
9080     if (ss->ssl3.clientPrivateKey != NULL)
9081 	SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
9082 
9083     if (ss->ssl3.peerCertArena != NULL)
9084 	ssl3_CleanupPeerCerts(ss);
9085 
9086     if (ss->ssl3.clientCertChain != NULL) {
9087        CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
9088        ss->ssl3.clientCertChain = NULL;
9089     }
9090 
9091     /* clean up handshake */
9092     if (ss->opt.bypassPKCS11) {
9093 	SHA1_DestroyContext((SHA1Context *)ss->ssl3.hs.sha_cx, PR_FALSE);
9094 	MD5_DestroyContext((MD5Context *)ss->ssl3.hs.md5_cx, PR_FALSE);
9095     }
9096     if (ss->ssl3.hs.md5) {
9097 	PK11_DestroyContext(ss->ssl3.hs.md5,PR_TRUE);
9098     }
9099     if (ss->ssl3.hs.sha) {
9100 	PK11_DestroyContext(ss->ssl3.hs.sha,PR_TRUE);
9101     }
9102     if (ss->ssl3.hs.messages.buf) {
9103     	PORT_Free(ss->ssl3.hs.messages.buf);
9104 	ss->ssl3.hs.messages.buf = NULL;
9105 	ss->ssl3.hs.messages.len = 0;
9106 	ss->ssl3.hs.messages.space = 0;
9107     }
9108 
9109     /* free the SSL3Buffer (msg_body) */
9110     PORT_Free(ss->ssl3.hs.msg_body.buf);
9111 
9112     /* free up the CipherSpecs */
9113     ssl3_DestroyCipherSpec(&ss->ssl3.specs[0]);
9114     ssl3_DestroyCipherSpec(&ss->ssl3.specs[1]);
9115 
9116     ss->ssl3.initialized = PR_FALSE;
9117 
9118     if (ss->ssl3.nextProto.data) {
9119 	PORT_Free(ss->ssl3.nextProto.data);
9120 	ss->ssl3.nextProto.data = NULL;
9121     }
9122 }
9123 
9124 /* End of ssl3con.c */
9125