security/nss/lib/ssl/ssl3con.c

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

mercurial