Revert "Merged all Chromoting Host code into remoting_core.dll (Windows)."
[chromium-blink-merge.git] / net / third_party / nss / ssl / ssl3con.c
blob506044750c6306ecef59d8bc217f2c048011f68f
1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * SSL3 Protocol
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 /* $Id: ssl3con.c,v 1.192 2012/09/28 05:10:25 wtc%google.com Exp $ */
10 /* TODO(ekr): Implement HelloVerifyRequest on server side. OK for now. */
12 #include "cert.h"
13 #include "ssl.h"
14 #include "cryptohi.h" /* for DSAU_ stuff */
15 #include "keyhi.h"
16 #include "secder.h"
17 #include "secitem.h"
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"
28 #include "pk11func.h"
29 #include "secmod.h"
30 #ifndef NO_PKCS11_BYPASS
31 #include "blapi.h"
32 #endif
34 #include <stdio.h>
35 #ifdef NSS_ENABLE_ZLIB
36 #include "zlib.h"
37 #endif
39 #ifndef PK11_SETATTRS
40 #define PK11_SETATTRS(x,id,v,l) (x)->type = (id); \
41 (x)->pValue=(v); (x)->ulValueLen = (l);
42 #endif
44 static void ssl3_CleanupPeerCerts(sslSocket *ss);
45 static void ssl3_CopyPeerCertsFromSID(sslSocket *ss, sslSessionID *sid);
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_SendEmptyCertificate( sslSocket *ss);
54 static SECStatus ssl3_SendCertificateRequest(sslSocket *ss);
55 static SECStatus ssl3_SendNextProto( sslSocket *ss);
56 static SECStatus ssl3_SendEncryptedExtensions(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_NewHandshakeHashes( sslSocket *ss);
62 static SECStatus ssl3_UpdateHandshakeHashes( sslSocket *ss,
63 const unsigned char *b,
64 unsigned int l);
65 static SECStatus ssl3_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags);
67 static SECStatus Null_Cipher(void *ctx, unsigned char *output, int *outputLen,
68 int maxOutputLen, const unsigned char *input,
69 int inputLen);
71 #define MAX_SEND_BUF_LENGTH 32000 /* watch for 16-bit integer overflow */
72 #define MIN_SEND_BUF_LENGTH 4000
74 /* This list of SSL3 cipher suites is sorted in descending order of
75 * precedence (desirability). It only includes cipher suites we implement.
76 * This table is modified by SSL3_SetPolicy(). The ordering of cipher suites
77 * in this table must match the ordering in SSL_ImplementedCiphers (sslenum.c)
79 static ssl3CipherSuiteCfg cipherSuites[ssl_V3_SUITES_IMPLEMENTED] = {
80 /* cipher_suite policy enabled is_present*/
81 #ifdef NSS_ENABLE_ECC
82 { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
83 { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
84 #endif /* NSS_ENABLE_ECC */
85 { TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
86 { TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
87 { TLS_DHE_RSA_WITH_AES_256_CBC_SHA, SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
88 { TLS_DHE_DSS_WITH_AES_256_CBC_SHA, SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
89 #ifdef NSS_ENABLE_ECC
90 { TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
91 { TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
92 #endif /* NSS_ENABLE_ECC */
93 { TLS_RSA_WITH_CAMELLIA_256_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
94 { TLS_RSA_WITH_AES_256_CBC_SHA, SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
96 #ifdef NSS_ENABLE_ECC
97 { TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
98 { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
99 { TLS_ECDHE_RSA_WITH_RC4_128_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
100 { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
101 #endif /* NSS_ENABLE_ECC */
102 { TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
103 { TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
104 { TLS_DHE_DSS_WITH_RC4_128_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
105 { TLS_DHE_RSA_WITH_AES_128_CBC_SHA, SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
106 { TLS_DHE_DSS_WITH_AES_128_CBC_SHA, SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
107 #ifdef NSS_ENABLE_ECC
108 { TLS_ECDH_RSA_WITH_RC4_128_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
109 { TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
110 { TLS_ECDH_ECDSA_WITH_RC4_128_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
111 { TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
112 #endif /* NSS_ENABLE_ECC */
113 { TLS_RSA_WITH_SEED_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
114 { TLS_RSA_WITH_CAMELLIA_128_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
115 { SSL_RSA_WITH_RC4_128_SHA, SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
116 { SSL_RSA_WITH_RC4_128_MD5, SSL_NOT_ALLOWED, PR_TRUE, PR_FALSE},
117 { TLS_RSA_WITH_AES_128_CBC_SHA, SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
119 #ifdef NSS_ENABLE_ECC
120 { TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
121 { TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
122 #endif /* NSS_ENABLE_ECC */
123 { SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
124 { SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA, SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
125 #ifdef NSS_ENABLE_ECC
126 { TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
127 { TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
128 #endif /* NSS_ENABLE_ECC */
129 { SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
130 { SSL_RSA_WITH_3DES_EDE_CBC_SHA, SSL_NOT_ALLOWED, PR_TRUE, PR_FALSE},
133 { SSL_DHE_RSA_WITH_DES_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
134 { SSL_DHE_DSS_WITH_DES_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
135 { SSL_RSA_FIPS_WITH_DES_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
136 { SSL_RSA_WITH_DES_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
137 { TLS_RSA_EXPORT1024_WITH_RC4_56_SHA, SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
138 { TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
140 { SSL_RSA_EXPORT_WITH_RC4_40_MD5, SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
141 { SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5, SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
143 #ifdef NSS_ENABLE_ECC
144 { TLS_ECDHE_ECDSA_WITH_NULL_SHA, SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
145 { TLS_ECDHE_RSA_WITH_NULL_SHA, SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
146 { TLS_ECDH_RSA_WITH_NULL_SHA, SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
147 { TLS_ECDH_ECDSA_WITH_NULL_SHA, SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
148 #endif /* NSS_ENABLE_ECC */
149 { SSL_RSA_WITH_NULL_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
150 { SSL_RSA_WITH_NULL_MD5, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
154 /* This list of SSL3 compression methods is sorted in descending order of
155 * precedence (desirability). It only includes compression methods we
156 * implement.
158 static const /*SSLCompressionMethod*/ uint8 compressions [] = {
159 #ifdef NSS_ENABLE_ZLIB
160 ssl_compression_deflate,
161 #endif
162 ssl_compression_null
165 static const int compressionMethodsCount =
166 sizeof(compressions) / sizeof(compressions[0]);
168 /* compressionEnabled returns true iff the compression algorithm is enabled
169 * for the given SSL socket. */
170 static PRBool
171 compressionEnabled(sslSocket *ss, SSLCompressionMethod compression)
173 switch (compression) {
174 case ssl_compression_null:
175 return PR_TRUE; /* Always enabled */
176 #ifdef NSS_ENABLE_ZLIB
177 case ssl_compression_deflate:
178 return ss->opt.enableDeflate;
179 #endif
180 default:
181 return PR_FALSE;
185 static const /*SSL3ClientCertificateType */ uint8 certificate_types [] = {
186 ct_RSA_sign,
187 ct_DSS_sign,
188 #ifdef NSS_ENABLE_ECC
189 ct_ECDSA_sign,
190 #endif /* NSS_ENABLE_ECC */
193 #define EXPORT_RSA_KEY_LENGTH 64 /* bytes */
196 /* This global item is used only in servers. It is is initialized by
197 ** SSL_ConfigSecureServer(), and is used in ssl3_SendCertificateRequest().
199 CERTDistNames *ssl3_server_ca_list = NULL;
200 static SSL3Statistics ssl3stats;
202 /* indexed by SSL3BulkCipher */
203 static const ssl3BulkCipherDef bulk_cipher_defs[] = {
204 /* cipher calg keySz secretSz type ivSz BlkSz keygen */
205 {cipher_null, calg_null, 0, 0, type_stream, 0, 0, kg_null},
206 {cipher_rc4, calg_rc4, 16, 16, type_stream, 0, 0, kg_strong},
207 {cipher_rc4_40, calg_rc4, 16, 5, type_stream, 0, 0, kg_export},
208 {cipher_rc4_56, calg_rc4, 16, 7, type_stream, 0, 0, kg_export},
209 {cipher_rc2, calg_rc2, 16, 16, type_block, 8, 8, kg_strong},
210 {cipher_rc2_40, calg_rc2, 16, 5, type_block, 8, 8, kg_export},
211 {cipher_des, calg_des, 8, 8, type_block, 8, 8, kg_strong},
212 {cipher_3des, calg_3des, 24, 24, type_block, 8, 8, kg_strong},
213 {cipher_des40, calg_des, 8, 5, type_block, 8, 8, kg_export},
214 {cipher_idea, calg_idea, 16, 16, type_block, 8, 8, kg_strong},
215 {cipher_aes_128, calg_aes, 16, 16, type_block, 16,16, kg_strong},
216 {cipher_aes_256, calg_aes, 32, 32, type_block, 16,16, kg_strong},
217 {cipher_camellia_128, calg_camellia,16, 16, type_block, 16,16, kg_strong},
218 {cipher_camellia_256, calg_camellia,32, 32, type_block, 16,16, kg_strong},
219 {cipher_seed, calg_seed, 16, 16, type_block, 16,16, kg_strong},
220 {cipher_missing, calg_null, 0, 0, type_stream, 0, 0, kg_null},
223 static const ssl3KEADef kea_defs[] =
224 { /* indexed by SSL3KeyExchangeAlgorithm */
225 /* kea exchKeyType signKeyType is_limited limit tls_keygen */
226 {kea_null, kt_null, sign_null, PR_FALSE, 0, PR_FALSE},
227 {kea_rsa, kt_rsa, sign_rsa, PR_FALSE, 0, PR_FALSE},
228 {kea_rsa_export, kt_rsa, sign_rsa, PR_TRUE, 512, PR_FALSE},
229 {kea_rsa_export_1024,kt_rsa, sign_rsa, PR_TRUE, 1024, PR_FALSE},
230 {kea_dh_dss, kt_dh, sign_dsa, PR_FALSE, 0, PR_FALSE},
231 {kea_dh_dss_export, kt_dh, sign_dsa, PR_TRUE, 512, PR_FALSE},
232 {kea_dh_rsa, kt_dh, sign_rsa, PR_FALSE, 0, PR_FALSE},
233 {kea_dh_rsa_export, kt_dh, sign_rsa, PR_TRUE, 512, PR_FALSE},
234 {kea_dhe_dss, kt_dh, sign_dsa, PR_FALSE, 0, PR_FALSE},
235 {kea_dhe_dss_export, kt_dh, sign_dsa, PR_TRUE, 512, PR_FALSE},
236 {kea_dhe_rsa, kt_dh, sign_rsa, PR_FALSE, 0, PR_FALSE},
237 {kea_dhe_rsa_export, kt_dh, sign_rsa, PR_TRUE, 512, PR_FALSE},
238 {kea_dh_anon, kt_dh, sign_null, PR_FALSE, 0, PR_FALSE},
239 {kea_dh_anon_export, kt_dh, sign_null, PR_TRUE, 512, PR_FALSE},
240 {kea_rsa_fips, kt_rsa, sign_rsa, PR_FALSE, 0, PR_TRUE },
241 #ifdef NSS_ENABLE_ECC
242 {kea_ecdh_ecdsa, kt_ecdh, sign_ecdsa, PR_FALSE, 0, PR_FALSE},
243 {kea_ecdhe_ecdsa, kt_ecdh, sign_ecdsa, PR_FALSE, 0, PR_FALSE},
244 {kea_ecdh_rsa, kt_ecdh, sign_rsa, PR_FALSE, 0, PR_FALSE},
245 {kea_ecdhe_rsa, kt_ecdh, sign_rsa, PR_FALSE, 0, PR_FALSE},
246 {kea_ecdh_anon, kt_ecdh, sign_null, PR_FALSE, 0, PR_FALSE},
247 #endif /* NSS_ENABLE_ECC */
250 /* must use ssl_LookupCipherSuiteDef to access */
251 static const ssl3CipherSuiteDef cipher_suite_defs[] =
253 /* cipher_suite bulk_cipher_alg mac_alg key_exchange_alg */
255 {SSL_NULL_WITH_NULL_NULL, cipher_null, mac_null, kea_null},
256 {SSL_RSA_WITH_NULL_MD5, cipher_null, mac_md5, kea_rsa},
257 {SSL_RSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_rsa},
258 {SSL_RSA_EXPORT_WITH_RC4_40_MD5,cipher_rc4_40, mac_md5, kea_rsa_export},
259 {SSL_RSA_WITH_RC4_128_MD5, cipher_rc4, mac_md5, kea_rsa},
260 {SSL_RSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_rsa},
261 {SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5,
262 cipher_rc2_40, mac_md5, kea_rsa_export},
263 #if 0 /* not implemented */
264 {SSL_RSA_WITH_IDEA_CBC_SHA, cipher_idea, mac_sha, kea_rsa},
265 {SSL_RSA_EXPORT_WITH_DES40_CBC_SHA,
266 cipher_des40, mac_sha, kea_rsa_export},
267 #endif
268 {SSL_RSA_WITH_DES_CBC_SHA, cipher_des, mac_sha, kea_rsa},
269 {SSL_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_rsa},
270 {SSL_DHE_DSS_WITH_DES_CBC_SHA, cipher_des, mac_sha, kea_dhe_dss},
271 {SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA,
272 cipher_3des, mac_sha, kea_dhe_dss},
273 {TLS_DHE_DSS_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_dhe_dss},
274 #if 0 /* not implemented */
275 {SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA,
276 cipher_des40, mac_sha, kea_dh_dss_export},
277 {SSL_DH_DSS_DES_CBC_SHA, cipher_des, mac_sha, kea_dh_dss},
278 {SSL_DH_DSS_3DES_CBC_SHA, cipher_3des, mac_sha, kea_dh_dss},
279 {SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA,
280 cipher_des40, mac_sha, kea_dh_rsa_export},
281 {SSL_DH_RSA_DES_CBC_SHA, cipher_des, mac_sha, kea_dh_rsa},
282 {SSL_DH_RSA_3DES_CBC_SHA, cipher_3des, mac_sha, kea_dh_rsa},
283 {SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA,
284 cipher_des40, mac_sha, kea_dh_dss_export},
285 {SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA,
286 cipher_des40, mac_sha, kea_dh_rsa_export},
287 #endif
288 {SSL_DHE_RSA_WITH_DES_CBC_SHA, cipher_des, mac_sha, kea_dhe_rsa},
289 {SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA,
290 cipher_3des, mac_sha, kea_dhe_rsa},
291 #if 0
292 {SSL_DH_ANON_EXPORT_RC4_40_MD5, cipher_rc4_40, mac_md5, kea_dh_anon_export},
293 {SSL_DH_ANON_EXPORT_WITH_DES40_CBC_SHA,
294 cipher_des40, mac_sha, kea_dh_anon_export},
295 {SSL_DH_ANON_DES_CBC_SHA, cipher_des, mac_sha, kea_dh_anon},
296 {SSL_DH_ANON_3DES_CBC_SHA, cipher_3des, mac_sha, kea_dh_anon},
297 #endif
300 /* New TLS cipher suites */
301 {TLS_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_rsa},
302 {TLS_DHE_DSS_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dhe_dss},
303 {TLS_DHE_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dhe_rsa},
304 {TLS_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_rsa},
305 {TLS_DHE_DSS_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dhe_dss},
306 {TLS_DHE_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dhe_rsa},
307 #if 0
308 {TLS_DH_DSS_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dh_dss},
309 {TLS_DH_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dh_rsa},
310 {TLS_DH_ANON_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dh_anon},
311 {TLS_DH_DSS_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dh_dss},
312 {TLS_DH_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dh_rsa},
313 {TLS_DH_ANON_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dh_anon},
314 #endif
316 {TLS_RSA_WITH_SEED_CBC_SHA, cipher_seed, mac_sha, kea_rsa},
318 {TLS_RSA_WITH_CAMELLIA_128_CBC_SHA, cipher_camellia_128, mac_sha, kea_rsa},
319 {TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA,
320 cipher_camellia_128, mac_sha, kea_dhe_dss},
321 {TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA,
322 cipher_camellia_128, mac_sha, kea_dhe_rsa},
323 {TLS_RSA_WITH_CAMELLIA_256_CBC_SHA, cipher_camellia_256, mac_sha, kea_rsa},
324 {TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA,
325 cipher_camellia_256, mac_sha, kea_dhe_dss},
326 {TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA,
327 cipher_camellia_256, mac_sha, kea_dhe_rsa},
329 {TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA,
330 cipher_des, mac_sha,kea_rsa_export_1024},
331 {TLS_RSA_EXPORT1024_WITH_RC4_56_SHA,
332 cipher_rc4_56, mac_sha,kea_rsa_export_1024},
334 {SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_rsa_fips},
335 {SSL_RSA_FIPS_WITH_DES_CBC_SHA, cipher_des, mac_sha, kea_rsa_fips},
337 #ifdef NSS_ENABLE_ECC
338 {TLS_ECDH_ECDSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdh_ecdsa},
339 {TLS_ECDH_ECDSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdh_ecdsa},
340 {TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdh_ecdsa},
341 {TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdh_ecdsa},
342 {TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdh_ecdsa},
344 {TLS_ECDHE_ECDSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdhe_ecdsa},
345 {TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdhe_ecdsa},
346 {TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdhe_ecdsa},
347 {TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdhe_ecdsa},
348 {TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdhe_ecdsa},
350 {TLS_ECDH_RSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdh_rsa},
351 {TLS_ECDH_RSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdh_rsa},
352 {TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdh_rsa},
353 {TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdh_rsa},
354 {TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdh_rsa},
356 {TLS_ECDHE_RSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdhe_rsa},
357 {TLS_ECDHE_RSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdhe_rsa},
358 {TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdhe_rsa},
359 {TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdhe_rsa},
360 {TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdhe_rsa},
362 #if 0
363 {TLS_ECDH_anon_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdh_anon},
364 {TLS_ECDH_anon_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdh_anon},
365 {TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdh_anon},
366 {TLS_ECDH_anon_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdh_anon},
367 {TLS_ECDH_anon_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdh_anon},
368 #endif
369 #endif /* NSS_ENABLE_ECC */
372 static const CK_MECHANISM_TYPE kea_alg_defs[] = {
373 0x80000000L,
374 CKM_RSA_PKCS,
375 CKM_DH_PKCS_DERIVE,
376 CKM_KEA_KEY_DERIVE,
377 CKM_ECDH1_DERIVE
380 typedef struct SSLCipher2MechStr {
381 SSLCipherAlgorithm calg;
382 CK_MECHANISM_TYPE cmech;
383 } SSLCipher2Mech;
385 /* indexed by type SSLCipherAlgorithm */
386 static const SSLCipher2Mech alg2Mech[] = {
387 /* calg, cmech */
388 { calg_null , (CK_MECHANISM_TYPE)0x80000000L },
389 { calg_rc4 , CKM_RC4 },
390 { calg_rc2 , CKM_RC2_CBC },
391 { calg_des , CKM_DES_CBC },
392 { calg_3des , CKM_DES3_CBC },
393 { calg_idea , CKM_IDEA_CBC },
394 { calg_fortezza , CKM_SKIPJACK_CBC64 },
395 { calg_aes , CKM_AES_CBC },
396 { calg_camellia , CKM_CAMELLIA_CBC },
397 { calg_seed , CKM_SEED_CBC },
398 /* { calg_init , (CK_MECHANISM_TYPE)0x7fffffffL } */
401 #define mmech_null (CK_MECHANISM_TYPE)0x80000000L
402 #define mmech_md5 CKM_SSL3_MD5_MAC
403 #define mmech_sha CKM_SSL3_SHA1_MAC
404 #define mmech_md5_hmac CKM_MD5_HMAC
405 #define mmech_sha_hmac CKM_SHA_1_HMAC
407 static const ssl3MACDef mac_defs[] = { /* indexed by SSL3MACAlgorithm */
408 /* mac mmech pad_size mac_size */
409 { mac_null, mmech_null, 0, 0 },
410 { mac_md5, mmech_md5, 48, MD5_LENGTH },
411 { mac_sha, mmech_sha, 40, SHA1_LENGTH},
412 {hmac_md5, mmech_md5_hmac, 48, MD5_LENGTH },
413 {hmac_sha, mmech_sha_hmac, 40, SHA1_LENGTH},
416 /* indexed by SSL3BulkCipher */
417 const char * const ssl3_cipherName[] = {
418 "NULL",
419 "RC4",
420 "RC4-40",
421 "RC4-56",
422 "RC2-CBC",
423 "RC2-CBC-40",
424 "DES-CBC",
425 "3DES-EDE-CBC",
426 "DES-CBC-40",
427 "IDEA-CBC",
428 "AES-128",
429 "AES-256",
430 "Camellia-128",
431 "Camellia-256",
432 "SEED-CBC",
433 "missing"
436 #ifdef NSS_ENABLE_ECC
437 /* The ECCWrappedKeyInfo structure defines how various pieces of
438 * information are laid out within wrappedSymmetricWrappingkey
439 * for ECDH key exchange. Since wrappedSymmetricWrappingkey is
440 * a 512-byte buffer (see sslimpl.h), the variable length field
441 * in ECCWrappedKeyInfo can be at most (512 - 8) = 504 bytes.
443 * XXX For now, NSS only supports named elliptic curves of size 571 bits
444 * or smaller. The public value will fit within 145 bytes and EC params
445 * will fit within 12 bytes. We'll need to revisit this when NSS
446 * supports arbitrary curves.
448 #define MAX_EC_WRAPPED_KEY_BUFLEN 504
450 typedef struct ECCWrappedKeyInfoStr {
451 PRUint16 size; /* EC public key size in bits */
452 PRUint16 encodedParamLen; /* length (in bytes) of DER encoded EC params */
453 PRUint16 pubValueLen; /* length (in bytes) of EC public value */
454 PRUint16 wrappedKeyLen; /* length (in bytes) of the wrapped key */
455 PRUint8 var[MAX_EC_WRAPPED_KEY_BUFLEN]; /* this buffer contains the */
456 /* EC public-key params, the EC public value and the wrapped key */
457 } ECCWrappedKeyInfo;
458 #endif /* NSS_ENABLE_ECC */
460 #if defined(TRACE)
462 static char *
463 ssl3_DecodeHandshakeType(int msgType)
465 char * rv;
466 static char line[40];
468 switch(msgType) {
469 case hello_request: rv = "hello_request (0)"; break;
470 case client_hello: rv = "client_hello (1)"; break;
471 case server_hello: rv = "server_hello (2)"; break;
472 case hello_verify_request: rv = "hello_verify_request (3)"; break;
473 case certificate: rv = "certificate (11)"; break;
474 case server_key_exchange: rv = "server_key_exchange (12)"; break;
475 case certificate_request: rv = "certificate_request (13)"; break;
476 case server_hello_done: rv = "server_hello_done (14)"; break;
477 case certificate_verify: rv = "certificate_verify (15)"; break;
478 case client_key_exchange: rv = "client_key_exchange (16)"; break;
479 case finished: rv = "finished (20)"; break;
480 default:
481 sprintf(line, "*UNKNOWN* handshake type! (%d)", msgType);
482 rv = line;
484 return rv;
487 static char *
488 ssl3_DecodeContentType(int msgType)
490 char * rv;
491 static char line[40];
493 switch(msgType) {
494 case content_change_cipher_spec:
495 rv = "change_cipher_spec (20)"; break;
496 case content_alert: rv = "alert (21)"; break;
497 case content_handshake: rv = "handshake (22)"; break;
498 case content_application_data:
499 rv = "application_data (23)"; break;
500 default:
501 sprintf(line, "*UNKNOWN* record type! (%d)", msgType);
502 rv = line;
504 return rv;
507 #endif
509 SSL3Statistics *
510 SSL_GetStatistics(void)
512 return &ssl3stats;
515 typedef struct tooLongStr {
516 #if defined(IS_LITTLE_ENDIAN)
517 PRInt32 low;
518 PRInt32 high;
519 #else
520 PRInt32 high;
521 PRInt32 low;
522 #endif
523 } tooLong;
525 void SSL_AtomicIncrementLong(long * x)
527 if ((sizeof *x) == sizeof(PRInt32)) {
528 PR_ATOMIC_INCREMENT((PRInt32 *)x);
529 } else {
530 tooLong * tl = (tooLong *)x;
531 if (PR_ATOMIC_INCREMENT(&tl->low) == 0)
532 PR_ATOMIC_INCREMENT(&tl->high);
536 static PRBool
537 ssl3_CipherSuiteAllowedForVersion(ssl3CipherSuite cipherSuite,
538 SSL3ProtocolVersion version)
540 switch (cipherSuite) {
541 /* See RFC 4346 A.5. Export cipher suites must not be used in TLS 1.1 or
542 * later. This set of cipher suites is similar to, but different from, the
543 * set of cipher suites considered exportable by SSL_IsExportCipherSuite.
545 case SSL_RSA_EXPORT_WITH_RC4_40_MD5:
546 case SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5:
547 /* SSL_RSA_EXPORT_WITH_DES40_CBC_SHA: never implemented
548 * SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA: never implemented
549 * SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA: never implemented
550 * SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA: never implemented
551 * SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA: never implemented
552 * SSL_DH_ANON_EXPORT_WITH_RC4_40_MD5: never implemented
553 * SSL_DH_ANON_EXPORT_WITH_DES40_CBC_SHA: never implemented
555 return version <= SSL_LIBRARY_VERSION_TLS_1_0;
556 default:
557 return PR_TRUE;
561 /* return pointer to ssl3CipherSuiteDef for suite, or NULL */
562 /* XXX This does a linear search. A binary search would be better. */
563 static const ssl3CipherSuiteDef *
564 ssl_LookupCipherSuiteDef(ssl3CipherSuite suite)
566 int cipher_suite_def_len =
567 sizeof(cipher_suite_defs) / sizeof(cipher_suite_defs[0]);
568 int i;
570 for (i = 0; i < cipher_suite_def_len; i++) {
571 if (cipher_suite_defs[i].cipher_suite == suite)
572 return &cipher_suite_defs[i];
574 PORT_Assert(PR_FALSE); /* We should never get here. */
575 PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE);
576 return NULL;
579 /* Find the cipher configuration struct associate with suite */
580 /* XXX This does a linear search. A binary search would be better. */
581 static ssl3CipherSuiteCfg *
582 ssl_LookupCipherSuiteCfg(ssl3CipherSuite suite, ssl3CipherSuiteCfg *suites)
584 int i;
586 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
587 if (suites[i].cipher_suite == suite)
588 return &suites[i];
590 /* return NULL and let the caller handle it. */
591 PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE);
592 return NULL;
596 /* Initialize the suite->isPresent value for config_match
597 * Returns count of enabled ciphers supported by extant tokens,
598 * regardless of policy or user preference.
599 * If this returns zero, the user cannot do SSL v3.
602 ssl3_config_match_init(sslSocket *ss)
604 ssl3CipherSuiteCfg * suite;
605 const ssl3CipherSuiteDef *cipher_def;
606 SSLCipherAlgorithm cipher_alg;
607 CK_MECHANISM_TYPE cipher_mech;
608 SSL3KEAType exchKeyType;
609 int i;
610 int numPresent = 0;
611 int numEnabled = 0;
612 PRBool isServer;
613 sslServerCerts *svrAuth;
615 PORT_Assert(ss);
616 if (!ss) {
617 PORT_SetError(SEC_ERROR_INVALID_ARGS);
618 return 0;
620 if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
621 return 0;
623 isServer = (PRBool)(ss->sec.isServer != 0);
625 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
626 suite = &ss->cipherSuites[i];
627 if (suite->enabled) {
628 ++numEnabled;
629 /* We need the cipher defs to see if we have a token that can handle
630 * this cipher. It isn't part of the static definition.
632 cipher_def = ssl_LookupCipherSuiteDef(suite->cipher_suite);
633 if (!cipher_def) {
634 suite->isPresent = PR_FALSE;
635 continue;
637 cipher_alg = bulk_cipher_defs[cipher_def->bulk_cipher_alg].calg;
638 PORT_Assert( alg2Mech[cipher_alg].calg == cipher_alg);
639 cipher_mech = alg2Mech[cipher_alg].cmech;
640 exchKeyType =
641 kea_defs[cipher_def->key_exchange_alg].exchKeyType;
642 #ifndef NSS_ENABLE_ECC
643 svrAuth = ss->serverCerts + exchKeyType;
644 #else
645 /* XXX SSLKEAType isn't really a good choice for
646 * indexing certificates. It doesn't work for
647 * (EC)DHE-* ciphers. Here we use a hack to ensure
648 * that the server uses an RSA cert for (EC)DHE-RSA.
650 switch (cipher_def->key_exchange_alg) {
651 case kea_ecdhe_rsa:
652 #if NSS_SERVER_DHE_IMPLEMENTED
653 /* XXX NSS does not yet implement the server side of _DHE_
654 * cipher suites. Correcting the computation for svrAuth,
655 * as the case below does, causes NSS SSL servers to begin to
656 * negotiate cipher suites they do not implement. So, until
657 * server side _DHE_ is implemented, keep this disabled.
659 case kea_dhe_rsa:
660 #endif
661 svrAuth = ss->serverCerts + kt_rsa;
662 break;
663 case kea_ecdh_ecdsa:
664 case kea_ecdh_rsa:
666 * XXX We ought to have different indices for
667 * ECDSA- and RSA-signed EC certificates so
668 * we could support both key exchange mechanisms
669 * simultaneously. For now, both of them use
670 * whatever is in the certificate slot for kt_ecdh
672 default:
673 svrAuth = ss->serverCerts + exchKeyType;
674 break;
676 #endif /* NSS_ENABLE_ECC */
678 /* Mark the suites that are backed by real tokens, certs and keys */
679 suite->isPresent = (PRBool)
680 (((exchKeyType == kt_null) ||
681 ((!isServer || (svrAuth->serverKeyPair &&
682 svrAuth->SERVERKEY &&
683 svrAuth->serverCertChain)) &&
684 PK11_TokenExists(kea_alg_defs[exchKeyType]))) &&
685 ((cipher_alg == calg_null) || PK11_TokenExists(cipher_mech)));
686 if (suite->isPresent)
687 ++numPresent;
690 PORT_Assert(numPresent > 0 || numEnabled == 0);
691 if (numPresent <= 0) {
692 PORT_SetError(SSL_ERROR_NO_CIPHERS_SUPPORTED);
694 return numPresent;
698 /* return PR_TRUE if suite matches policy and enabled state */
699 /* It would be a REALLY BAD THING (tm) if we ever permitted the use
700 ** of a cipher that was NOT_ALLOWED. So, if this is ever called with
701 ** policy == SSL_NOT_ALLOWED, report no match.
703 /* adjust suite enabled to the availability of a token that can do the
704 * cipher suite. */
705 static PRBool
706 config_match(ssl3CipherSuiteCfg *suite, int policy, PRBool enabled)
708 PORT_Assert(policy != SSL_NOT_ALLOWED && enabled != PR_FALSE);
709 if (policy == SSL_NOT_ALLOWED || !enabled)
710 return PR_FALSE;
711 return (PRBool)(suite->enabled &&
712 suite->isPresent &&
713 suite->policy != SSL_NOT_ALLOWED &&
714 suite->policy <= policy);
717 /* return number of cipher suites that match policy and enabled state */
718 /* called from ssl3_SendClientHello and ssl3_ConstructV2CipherSpecsHack */
719 static int
720 count_cipher_suites(sslSocket *ss, int policy, PRBool enabled)
722 int i, count = 0;
724 if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
725 return 0;
727 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
728 if (config_match(&ss->cipherSuites[i], policy, enabled))
729 count++;
731 if (count <= 0) {
732 PORT_SetError(SSL_ERROR_SSL_DISABLED);
734 return count;
738 * Null compression, mac and encryption functions
741 static SECStatus
742 Null_Cipher(void *ctx, unsigned char *output, int *outputLen, int maxOutputLen,
743 const unsigned char *input, int inputLen)
745 *outputLen = inputLen;
746 if (input != output)
747 PORT_Memcpy(output, input, inputLen);
748 return SECSuccess;
752 * SSL3 Utility functions
755 /* allowLargerPeerVersion controls whether the function will select the
756 * highest enabled SSL version or fail when peerVersion is greater than the
757 * highest enabled version.
759 * If allowLargerPeerVersion is true, peerVersion is the peer's highest
760 * enabled version rather than the peer's selected version.
762 SECStatus
763 ssl3_NegotiateVersion(sslSocket *ss, SSL3ProtocolVersion peerVersion,
764 PRBool allowLargerPeerVersion)
766 if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
767 PORT_SetError(SSL_ERROR_SSL_DISABLED);
768 return SECFailure;
771 if (peerVersion < ss->vrange.min ||
772 (peerVersion > ss->vrange.max && !allowLargerPeerVersion)) {
773 PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
774 return SECFailure;
777 ss->version = PR_MIN(peerVersion, ss->vrange.max);
778 PORT_Assert(ssl3_VersionIsSupported(ss->protocolVariant, ss->version));
780 return SECSuccess;
783 static SECStatus
784 ssl3_GetNewRandom(SSL3Random *random)
786 PRUint32 gmt = ssl_Time();
787 SECStatus rv;
789 random->rand[0] = (unsigned char)(gmt >> 24);
790 random->rand[1] = (unsigned char)(gmt >> 16);
791 random->rand[2] = (unsigned char)(gmt >> 8);
792 random->rand[3] = (unsigned char)(gmt);
794 /* first 4 bytes are reserverd for time */
795 rv = PK11_GenerateRandom(&random->rand[4], SSL3_RANDOM_LENGTH - 4);
796 if (rv != SECSuccess) {
797 ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
799 return rv;
802 /* Called by ssl3_SendServerKeyExchange and ssl3_SendCertificateVerify */
803 SECStatus
804 ssl3_SignHashes(SSL3Hashes *hash, SECKEYPrivateKey *key, SECItem *buf,
805 PRBool isTLS)
807 SECStatus rv = SECFailure;
808 PRBool doDerEncode = PR_FALSE;
809 int signatureLen;
810 SECItem hashItem;
812 buf->data = NULL;
813 signatureLen = PK11_SignatureLen(key);
814 if (signatureLen <= 0) {
815 PORT_SetError(SEC_ERROR_INVALID_KEY);
816 goto done;
819 buf->len = (unsigned)signatureLen;
820 buf->data = (unsigned char *)PORT_Alloc(signatureLen);
821 if (!buf->data)
822 goto done; /* error code was set. */
824 switch (key->keyType) {
825 case rsaKey:
826 hashItem.data = hash->md5;
827 hashItem.len = sizeof(SSL3Hashes);
828 break;
829 case dsaKey:
830 doDerEncode = isTLS;
831 hashItem.data = hash->sha;
832 hashItem.len = sizeof(hash->sha);
833 break;
834 #ifdef NSS_ENABLE_ECC
835 case ecKey:
836 doDerEncode = PR_TRUE;
837 hashItem.data = hash->sha;
838 hashItem.len = sizeof(hash->sha);
839 break;
840 #endif /* NSS_ENABLE_ECC */
841 default:
842 PORT_SetError(SEC_ERROR_INVALID_KEY);
843 goto done;
845 PRINT_BUF(60, (NULL, "hash(es) to be signed", hashItem.data, hashItem.len));
847 rv = PK11_Sign(key, buf, &hashItem);
848 if (rv != SECSuccess) {
849 ssl_MapLowLevelError(SSL_ERROR_SIGN_HASHES_FAILURE);
850 } else if (doDerEncode) {
851 SECItem derSig = {siBuffer, NULL, 0};
853 /* This also works for an ECDSA signature */
854 rv = DSAU_EncodeDerSigWithLen(&derSig, buf, buf->len);
855 if (rv == SECSuccess) {
856 PORT_Free(buf->data); /* discard unencoded signature. */
857 *buf = derSig; /* give caller encoded signature. */
858 } else if (derSig.data) {
859 PORT_Free(derSig.data);
863 PRINT_BUF(60, (NULL, "signed hashes", (unsigned char*)buf->data, buf->len));
864 done:
865 if (rv != SECSuccess && buf->data) {
866 PORT_Free(buf->data);
867 buf->data = NULL;
869 return rv;
872 /* Called from ssl3_HandleServerKeyExchange, ssl3_HandleCertificateVerify */
873 SECStatus
874 ssl3_VerifySignedHashes(SSL3Hashes *hash, CERTCertificate *cert,
875 SECItem *buf, PRBool isTLS, void *pwArg)
877 SECKEYPublicKey * key;
878 SECItem * signature = NULL;
879 SECStatus rv;
880 SECItem hashItem;
881 #ifdef NSS_ENABLE_ECC
882 unsigned int len;
883 #endif /* NSS_ENABLE_ECC */
886 PRINT_BUF(60, (NULL, "check signed hashes",
887 buf->data, buf->len));
889 key = CERT_ExtractPublicKey(cert);
890 if (key == NULL) {
891 ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
892 return SECFailure;
895 switch (key->keyType) {
896 case rsaKey:
897 hashItem.data = hash->md5;
898 hashItem.len = sizeof(SSL3Hashes);
899 break;
900 case dsaKey:
901 hashItem.data = hash->sha;
902 hashItem.len = sizeof(hash->sha);
903 /* Allow DER encoded DSA signatures in SSL 3.0 */
904 if (isTLS || buf->len != SECKEY_SignatureLen(key)) {
905 signature = DSAU_DecodeDerSig(buf);
906 if (!signature) {
907 PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
908 return SECFailure;
910 buf = signature;
912 break;
914 #ifdef NSS_ENABLE_ECC
915 case ecKey:
916 hashItem.data = hash->sha;
917 hashItem.len = sizeof(hash->sha);
919 * ECDSA signatures always encode the integers r and s
920 * using ASN (unlike DSA where ASN encoding is used
921 * with TLS but not with SSL3)
923 len = SECKEY_SignatureLen(key);
924 if (len == 0) {
925 SECKEY_DestroyPublicKey(key);
926 PORT_SetError(SEC_ERROR_UNSUPPORTED_ELLIPTIC_CURVE);
927 return SECFailure;
929 signature = DSAU_DecodeDerSigToLen(buf, len);
930 if (!signature) {
931 PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
932 return SECFailure;
934 buf = signature;
935 break;
936 #endif /* NSS_ENABLE_ECC */
938 default:
939 SECKEY_DestroyPublicKey(key);
940 PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
941 return SECFailure;
944 PRINT_BUF(60, (NULL, "hash(es) to be verified",
945 hashItem.data, hashItem.len));
947 rv = PK11_Verify(key, buf, &hashItem, pwArg);
948 SECKEY_DestroyPublicKey(key);
949 if (signature) {
950 SECITEM_FreeItem(signature, PR_TRUE);
952 if (rv != SECSuccess) {
953 ssl_MapLowLevelError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
955 return rv;
959 /* Caller must set hiLevel error code. */
960 /* Called from ssl3_ComputeExportRSAKeyHash
961 * ssl3_ComputeDHKeyHash
962 * which are called from ssl3_HandleServerKeyExchange.
964 SECStatus
965 ssl3_ComputeCommonKeyHash(PRUint8 * hashBuf, unsigned int bufLen,
966 SSL3Hashes *hashes, PRBool bypassPKCS11)
968 SECStatus rv = SECSuccess;
970 #ifndef NO_PKCS11_BYPASS
971 if (bypassPKCS11) {
972 MD5_HashBuf (hashes->md5, hashBuf, bufLen);
973 SHA1_HashBuf(hashes->sha, hashBuf, bufLen);
974 } else
975 #endif
977 rv = PK11_HashBuf(SEC_OID_MD5, hashes->md5, hashBuf, bufLen);
978 if (rv != SECSuccess) {
979 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
980 rv = SECFailure;
981 goto done;
984 rv = PK11_HashBuf(SEC_OID_SHA1, hashes->sha, hashBuf, bufLen);
985 if (rv != SECSuccess) {
986 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
987 rv = SECFailure;
990 done:
991 return rv;
994 /* Caller must set hiLevel error code.
995 ** Called from ssl3_SendServerKeyExchange and
996 ** ssl3_HandleServerKeyExchange.
998 static SECStatus
999 ssl3_ComputeExportRSAKeyHash(SECItem modulus, SECItem publicExponent,
1000 SSL3Random *client_rand, SSL3Random *server_rand,
1001 SSL3Hashes *hashes, PRBool bypassPKCS11)
1003 PRUint8 * hashBuf;
1004 PRUint8 * pBuf;
1005 SECStatus rv = SECSuccess;
1006 unsigned int bufLen;
1007 PRUint8 buf[2*SSL3_RANDOM_LENGTH + 2 + 4096/8 + 2 + 4096/8];
1009 bufLen = 2*SSL3_RANDOM_LENGTH + 2 + modulus.len + 2 + publicExponent.len;
1010 if (bufLen <= sizeof buf) {
1011 hashBuf = buf;
1012 } else {
1013 hashBuf = PORT_Alloc(bufLen);
1014 if (!hashBuf) {
1015 return SECFailure;
1019 memcpy(hashBuf, client_rand, SSL3_RANDOM_LENGTH);
1020 pBuf = hashBuf + SSL3_RANDOM_LENGTH;
1021 memcpy(pBuf, server_rand, SSL3_RANDOM_LENGTH);
1022 pBuf += SSL3_RANDOM_LENGTH;
1023 pBuf[0] = (PRUint8)(modulus.len >> 8);
1024 pBuf[1] = (PRUint8)(modulus.len);
1025 pBuf += 2;
1026 memcpy(pBuf, modulus.data, modulus.len);
1027 pBuf += modulus.len;
1028 pBuf[0] = (PRUint8)(publicExponent.len >> 8);
1029 pBuf[1] = (PRUint8)(publicExponent.len);
1030 pBuf += 2;
1031 memcpy(pBuf, publicExponent.data, publicExponent.len);
1032 pBuf += publicExponent.len;
1033 PORT_Assert((unsigned int)(pBuf - hashBuf) == bufLen);
1035 rv = ssl3_ComputeCommonKeyHash(hashBuf, bufLen, hashes, bypassPKCS11);
1037 PRINT_BUF(95, (NULL, "RSAkey hash: ", hashBuf, bufLen));
1038 PRINT_BUF(95, (NULL, "RSAkey hash: MD5 result", hashes->md5, MD5_LENGTH));
1039 PRINT_BUF(95, (NULL, "RSAkey hash: SHA1 result", hashes->sha, SHA1_LENGTH));
1041 if (hashBuf != buf && hashBuf != NULL)
1042 PORT_Free(hashBuf);
1043 return rv;
1046 /* Caller must set hiLevel error code. */
1047 /* Called from ssl3_HandleServerKeyExchange. */
1048 static SECStatus
1049 ssl3_ComputeDHKeyHash(SECItem dh_p, SECItem dh_g, SECItem dh_Ys,
1050 SSL3Random *client_rand, SSL3Random *server_rand,
1051 SSL3Hashes *hashes, PRBool bypassPKCS11)
1053 PRUint8 * hashBuf;
1054 PRUint8 * pBuf;
1055 SECStatus rv = SECSuccess;
1056 unsigned int bufLen;
1057 PRUint8 buf[2*SSL3_RANDOM_LENGTH + 2 + 4096/8 + 2 + 4096/8];
1059 bufLen = 2*SSL3_RANDOM_LENGTH + 2 + dh_p.len + 2 + dh_g.len + 2 + dh_Ys.len;
1060 if (bufLen <= sizeof buf) {
1061 hashBuf = buf;
1062 } else {
1063 hashBuf = PORT_Alloc(bufLen);
1064 if (!hashBuf) {
1065 return SECFailure;
1069 memcpy(hashBuf, client_rand, SSL3_RANDOM_LENGTH);
1070 pBuf = hashBuf + SSL3_RANDOM_LENGTH;
1071 memcpy(pBuf, server_rand, SSL3_RANDOM_LENGTH);
1072 pBuf += SSL3_RANDOM_LENGTH;
1073 pBuf[0] = (PRUint8)(dh_p.len >> 8);
1074 pBuf[1] = (PRUint8)(dh_p.len);
1075 pBuf += 2;
1076 memcpy(pBuf, dh_p.data, dh_p.len);
1077 pBuf += dh_p.len;
1078 pBuf[0] = (PRUint8)(dh_g.len >> 8);
1079 pBuf[1] = (PRUint8)(dh_g.len);
1080 pBuf += 2;
1081 memcpy(pBuf, dh_g.data, dh_g.len);
1082 pBuf += dh_g.len;
1083 pBuf[0] = (PRUint8)(dh_Ys.len >> 8);
1084 pBuf[1] = (PRUint8)(dh_Ys.len);
1085 pBuf += 2;
1086 memcpy(pBuf, dh_Ys.data, dh_Ys.len);
1087 pBuf += dh_Ys.len;
1088 PORT_Assert((unsigned int)(pBuf - hashBuf) == bufLen);
1090 rv = ssl3_ComputeCommonKeyHash(hashBuf, bufLen, hashes, bypassPKCS11);
1092 PRINT_BUF(95, (NULL, "DHkey hash: ", hashBuf, bufLen));
1093 PRINT_BUF(95, (NULL, "DHkey hash: MD5 result", hashes->md5, MD5_LENGTH));
1094 PRINT_BUF(95, (NULL, "DHkey hash: SHA1 result", hashes->sha, SHA1_LENGTH));
1096 if (hashBuf != buf && hashBuf != NULL)
1097 PORT_Free(hashBuf);
1098 return rv;
1101 static void
1102 ssl3_BumpSequenceNumber(SSL3SequenceNumber *num)
1104 num->low++;
1105 if (num->low == 0)
1106 num->high++;
1109 /* Called twice, only from ssl3_DestroyCipherSpec (immediately below). */
1110 static void
1111 ssl3_CleanupKeyMaterial(ssl3KeyMaterial *mat)
1113 if (mat->write_key != NULL) {
1114 PK11_FreeSymKey(mat->write_key);
1115 mat->write_key = NULL;
1117 if (mat->write_mac_key != NULL) {
1118 PK11_FreeSymKey(mat->write_mac_key);
1119 mat->write_mac_key = NULL;
1121 if (mat->write_mac_context != NULL) {
1122 PK11_DestroyContext(mat->write_mac_context, PR_TRUE);
1123 mat->write_mac_context = NULL;
1127 /* Called from ssl3_SendChangeCipherSpecs() and
1128 ** ssl3_HandleChangeCipherSpecs()
1129 ** ssl3_DestroySSL3Info
1130 ** Caller must hold SpecWriteLock.
1132 void
1133 ssl3_DestroyCipherSpec(ssl3CipherSpec *spec, PRBool freeSrvName)
1135 PRBool freeit = (PRBool)(!spec->bypassCiphers);
1136 /* PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); Don't have ss! */
1137 if (spec->destroy) {
1138 spec->destroy(spec->encodeContext, freeit);
1139 spec->destroy(spec->decodeContext, freeit);
1140 spec->encodeContext = NULL; /* paranoia */
1141 spec->decodeContext = NULL;
1143 if (spec->destroyCompressContext && spec->compressContext) {
1144 spec->destroyCompressContext(spec->compressContext, 1);
1145 spec->compressContext = NULL;
1147 if (spec->destroyDecompressContext && spec->decompressContext) {
1148 spec->destroyDecompressContext(spec->decompressContext, 1);
1149 spec->decompressContext = NULL;
1151 if (freeSrvName && spec->srvVirtName.data) {
1152 SECITEM_FreeItem(&spec->srvVirtName, PR_FALSE);
1154 if (spec->master_secret != NULL) {
1155 PK11_FreeSymKey(spec->master_secret);
1156 spec->master_secret = NULL;
1158 spec->msItem.data = NULL;
1159 spec->msItem.len = 0;
1160 ssl3_CleanupKeyMaterial(&spec->client);
1161 ssl3_CleanupKeyMaterial(&spec->server);
1162 spec->bypassCiphers = PR_FALSE;
1163 spec->destroy=NULL;
1164 spec->destroyCompressContext = NULL;
1165 spec->destroyDecompressContext = NULL;
1168 /* Fill in the pending cipher spec with info from the selected ciphersuite.
1169 ** This is as much initialization as we can do without having key material.
1170 ** Called from ssl3_HandleServerHello(), ssl3_SendServerHello()
1171 ** Caller must hold the ssl3 handshake lock.
1172 ** Acquires & releases SpecWriteLock.
1174 static SECStatus
1175 ssl3_SetupPendingCipherSpec(sslSocket *ss)
1177 ssl3CipherSpec * pwSpec;
1178 ssl3CipherSpec * cwSpec;
1179 ssl3CipherSuite suite = ss->ssl3.hs.cipher_suite;
1180 SSL3MACAlgorithm mac;
1181 SSL3BulkCipher cipher;
1182 SSL3KeyExchangeAlgorithm kea;
1183 const ssl3CipherSuiteDef *suite_def;
1184 PRBool isTLS;
1186 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
1188 ssl_GetSpecWriteLock(ss); /*******************************/
1190 pwSpec = ss->ssl3.pwSpec;
1191 PORT_Assert(pwSpec == ss->ssl3.prSpec);
1193 /* This hack provides maximal interoperability with SSL 3 servers. */
1194 cwSpec = ss->ssl3.cwSpec;
1195 if (cwSpec->mac_def->mac == mac_null) {
1196 /* SSL records are not being MACed. */
1197 cwSpec->version = ss->version;
1200 pwSpec->version = ss->version;
1201 isTLS = (PRBool)(pwSpec->version > SSL_LIBRARY_VERSION_3_0);
1203 SSL_TRC(3, ("%d: SSL3[%d]: Set XXX Pending Cipher Suite to 0x%04x",
1204 SSL_GETPID(), ss->fd, suite));
1206 suite_def = ssl_LookupCipherSuiteDef(suite);
1207 if (suite_def == NULL) {
1208 ssl_ReleaseSpecWriteLock(ss);
1209 return SECFailure; /* error code set by ssl_LookupCipherSuiteDef */
1212 if (IS_DTLS(ss)) {
1213 /* Double-check that we did not pick an RC4 suite */
1214 PORT_Assert((suite_def->bulk_cipher_alg != cipher_rc4) &&
1215 (suite_def->bulk_cipher_alg != cipher_rc4_40) &&
1216 (suite_def->bulk_cipher_alg != cipher_rc4_56));
1219 cipher = suite_def->bulk_cipher_alg;
1220 kea = suite_def->key_exchange_alg;
1221 mac = suite_def->mac_alg;
1222 if (isTLS)
1223 mac += 2;
1225 ss->ssl3.hs.suite_def = suite_def;
1226 ss->ssl3.hs.kea_def = &kea_defs[kea];
1227 PORT_Assert(ss->ssl3.hs.kea_def->kea == kea);
1229 pwSpec->cipher_def = &bulk_cipher_defs[cipher];
1230 PORT_Assert(pwSpec->cipher_def->cipher == cipher);
1232 pwSpec->mac_def = &mac_defs[mac];
1233 PORT_Assert(pwSpec->mac_def->mac == mac);
1235 ss->sec.keyBits = pwSpec->cipher_def->key_size * BPB;
1236 ss->sec.secretKeyBits = pwSpec->cipher_def->secret_key_size * BPB;
1237 ss->sec.cipherType = cipher;
1239 pwSpec->encodeContext = NULL;
1240 pwSpec->decodeContext = NULL;
1242 pwSpec->mac_size = pwSpec->mac_def->mac_size;
1244 pwSpec->compression_method = ss->ssl3.hs.compression;
1245 pwSpec->compressContext = NULL;
1246 pwSpec->decompressContext = NULL;
1248 ssl_ReleaseSpecWriteLock(ss); /*******************************/
1249 return SECSuccess;
1252 #ifdef NSS_ENABLE_ZLIB
1253 #define SSL3_DEFLATE_CONTEXT_SIZE sizeof(z_stream)
1255 static SECStatus
1256 ssl3_MapZlibError(int zlib_error)
1258 switch (zlib_error) {
1259 case Z_OK:
1260 return SECSuccess;
1261 default:
1262 return SECFailure;
1266 static SECStatus
1267 ssl3_DeflateInit(void *void_context)
1269 z_stream *context = void_context;
1270 context->zalloc = NULL;
1271 context->zfree = NULL;
1272 context->opaque = NULL;
1274 return ssl3_MapZlibError(deflateInit(context, Z_DEFAULT_COMPRESSION));
1277 static SECStatus
1278 ssl3_InflateInit(void *void_context)
1280 z_stream *context = void_context;
1281 context->zalloc = NULL;
1282 context->zfree = NULL;
1283 context->opaque = NULL;
1284 context->next_in = NULL;
1285 context->avail_in = 0;
1287 return ssl3_MapZlibError(inflateInit(context));
1290 static SECStatus
1291 ssl3_DeflateCompress(void *void_context, unsigned char *out, int *out_len,
1292 int maxout, const unsigned char *in, int inlen)
1294 z_stream *context = void_context;
1296 if (!inlen) {
1297 *out_len = 0;
1298 return SECSuccess;
1301 context->next_in = (unsigned char*) in;
1302 context->avail_in = inlen;
1303 context->next_out = out;
1304 context->avail_out = maxout;
1305 if (deflate(context, Z_SYNC_FLUSH) != Z_OK) {
1306 return SECFailure;
1308 if (context->avail_out == 0) {
1309 /* We ran out of space! */
1310 SSL_TRC(3, ("%d: SSL3[%d] Ran out of buffer while compressing",
1311 SSL_GETPID()));
1312 return SECFailure;
1315 *out_len = maxout - context->avail_out;
1316 return SECSuccess;
1319 static SECStatus
1320 ssl3_DeflateDecompress(void *void_context, unsigned char *out, int *out_len,
1321 int maxout, const unsigned char *in, int inlen)
1323 z_stream *context = void_context;
1325 if (!inlen) {
1326 *out_len = 0;
1327 return SECSuccess;
1330 context->next_in = (unsigned char*) in;
1331 context->avail_in = inlen;
1332 context->next_out = out;
1333 context->avail_out = maxout;
1334 if (inflate(context, Z_SYNC_FLUSH) != Z_OK) {
1335 PORT_SetError(SSL_ERROR_DECOMPRESSION_FAILURE);
1336 return SECFailure;
1339 *out_len = maxout - context->avail_out;
1340 return SECSuccess;
1343 static SECStatus
1344 ssl3_DestroyCompressContext(void *void_context, PRBool unused)
1346 deflateEnd(void_context);
1347 PORT_Free(void_context);
1348 return SECSuccess;
1351 static SECStatus
1352 ssl3_DestroyDecompressContext(void *void_context, PRBool unused)
1354 inflateEnd(void_context);
1355 PORT_Free(void_context);
1356 return SECSuccess;
1359 #endif /* NSS_ENABLE_ZLIB */
1361 /* Initialize the compression functions and contexts for the given
1362 * CipherSpec. */
1363 static SECStatus
1364 ssl3_InitCompressionContext(ssl3CipherSpec *pwSpec)
1366 /* Setup the compression functions */
1367 switch (pwSpec->compression_method) {
1368 case ssl_compression_null:
1369 pwSpec->compressor = NULL;
1370 pwSpec->decompressor = NULL;
1371 pwSpec->compressContext = NULL;
1372 pwSpec->decompressContext = NULL;
1373 pwSpec->destroyCompressContext = NULL;
1374 pwSpec->destroyDecompressContext = NULL;
1375 break;
1376 #ifdef NSS_ENABLE_ZLIB
1377 case ssl_compression_deflate:
1378 pwSpec->compressor = ssl3_DeflateCompress;
1379 pwSpec->decompressor = ssl3_DeflateDecompress;
1380 pwSpec->compressContext = PORT_Alloc(SSL3_DEFLATE_CONTEXT_SIZE);
1381 pwSpec->decompressContext = PORT_Alloc(SSL3_DEFLATE_CONTEXT_SIZE);
1382 pwSpec->destroyCompressContext = ssl3_DestroyCompressContext;
1383 pwSpec->destroyDecompressContext = ssl3_DestroyDecompressContext;
1384 ssl3_DeflateInit(pwSpec->compressContext);
1385 ssl3_InflateInit(pwSpec->decompressContext);
1386 break;
1387 #endif /* NSS_ENABLE_ZLIB */
1388 default:
1389 PORT_Assert(0);
1390 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1391 return SECFailure;
1394 return SECSuccess;
1397 #ifndef NO_PKCS11_BYPASS
1398 /* Initialize encryption and MAC contexts for pending spec.
1399 * Master Secret already is derived in spec->msItem
1400 * Caller holds Spec write lock.
1402 static SECStatus
1403 ssl3_InitPendingContextsBypass(sslSocket *ss)
1405 ssl3CipherSpec * pwSpec;
1406 const ssl3BulkCipherDef *cipher_def;
1407 void * serverContext = NULL;
1408 void * clientContext = NULL;
1409 BLapiInitContextFunc initFn = (BLapiInitContextFunc)NULL;
1410 int mode = 0;
1411 unsigned int optArg1 = 0;
1412 unsigned int optArg2 = 0;
1413 PRBool server_encrypts = ss->sec.isServer;
1414 CK_ULONG macLength;
1415 SSLCipherAlgorithm calg;
1416 SSLCompressionMethod compression_method;
1417 SECStatus rv;
1419 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
1420 PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
1421 PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
1423 pwSpec = ss->ssl3.pwSpec;
1424 cipher_def = pwSpec->cipher_def;
1425 macLength = pwSpec->mac_size;
1427 /* MAC setup is done when computing the mac, not here.
1428 * Now setup the crypto contexts.
1431 calg = cipher_def->calg;
1432 compression_method = pwSpec->compression_method;
1434 serverContext = pwSpec->server.cipher_context;
1435 clientContext = pwSpec->client.cipher_context;
1437 switch (calg) {
1438 case ssl_calg_null:
1439 pwSpec->encode = Null_Cipher;
1440 pwSpec->decode = Null_Cipher;
1441 pwSpec->destroy = NULL;
1442 goto success;
1444 case ssl_calg_rc4:
1445 initFn = (BLapiInitContextFunc)RC4_InitContext;
1446 pwSpec->encode = (SSLCipher) RC4_Encrypt;
1447 pwSpec->decode = (SSLCipher) RC4_Decrypt;
1448 pwSpec->destroy = (SSLDestroy) RC4_DestroyContext;
1449 break;
1450 case ssl_calg_rc2:
1451 initFn = (BLapiInitContextFunc)RC2_InitContext;
1452 mode = NSS_RC2_CBC;
1453 optArg1 = cipher_def->key_size;
1454 pwSpec->encode = (SSLCipher) RC2_Encrypt;
1455 pwSpec->decode = (SSLCipher) RC2_Decrypt;
1456 pwSpec->destroy = (SSLDestroy) RC2_DestroyContext;
1457 break;
1458 case ssl_calg_des:
1459 initFn = (BLapiInitContextFunc)DES_InitContext;
1460 mode = NSS_DES_CBC;
1461 optArg1 = server_encrypts;
1462 pwSpec->encode = (SSLCipher) DES_Encrypt;
1463 pwSpec->decode = (SSLCipher) DES_Decrypt;
1464 pwSpec->destroy = (SSLDestroy) DES_DestroyContext;
1465 break;
1466 case ssl_calg_3des:
1467 initFn = (BLapiInitContextFunc)DES_InitContext;
1468 mode = NSS_DES_EDE3_CBC;
1469 optArg1 = server_encrypts;
1470 pwSpec->encode = (SSLCipher) DES_Encrypt;
1471 pwSpec->decode = (SSLCipher) DES_Decrypt;
1472 pwSpec->destroy = (SSLDestroy) DES_DestroyContext;
1473 break;
1474 case ssl_calg_aes:
1475 initFn = (BLapiInitContextFunc)AES_InitContext;
1476 mode = NSS_AES_CBC;
1477 optArg1 = server_encrypts;
1478 optArg2 = AES_BLOCK_SIZE;
1479 pwSpec->encode = (SSLCipher) AES_Encrypt;
1480 pwSpec->decode = (SSLCipher) AES_Decrypt;
1481 pwSpec->destroy = (SSLDestroy) AES_DestroyContext;
1482 break;
1484 case ssl_calg_camellia:
1485 initFn = (BLapiInitContextFunc)Camellia_InitContext;
1486 mode = NSS_CAMELLIA_CBC;
1487 optArg1 = server_encrypts;
1488 optArg2 = CAMELLIA_BLOCK_SIZE;
1489 pwSpec->encode = (SSLCipher) Camellia_Encrypt;
1490 pwSpec->decode = (SSLCipher) Camellia_Decrypt;
1491 pwSpec->destroy = (SSLDestroy) Camellia_DestroyContext;
1492 break;
1494 case ssl_calg_seed:
1495 initFn = (BLapiInitContextFunc)SEED_InitContext;
1496 mode = NSS_SEED_CBC;
1497 optArg1 = server_encrypts;
1498 optArg2 = SEED_BLOCK_SIZE;
1499 pwSpec->encode = (SSLCipher) SEED_Encrypt;
1500 pwSpec->decode = (SSLCipher) SEED_Decrypt;
1501 pwSpec->destroy = (SSLDestroy) SEED_DestroyContext;
1502 break;
1504 case ssl_calg_idea:
1505 case ssl_calg_fortezza :
1506 default:
1507 PORT_Assert(0);
1508 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1509 goto bail_out;
1511 rv = (*initFn)(serverContext,
1512 pwSpec->server.write_key_item.data,
1513 pwSpec->server.write_key_item.len,
1514 pwSpec->server.write_iv_item.data,
1515 mode, optArg1, optArg2);
1516 if (rv != SECSuccess) {
1517 PORT_Assert(0);
1518 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1519 goto bail_out;
1522 switch (calg) {
1523 case ssl_calg_des:
1524 case ssl_calg_3des:
1525 case ssl_calg_aes:
1526 case ssl_calg_camellia:
1527 case ssl_calg_seed:
1528 /* For block ciphers, if the server is encrypting, then the client
1529 * is decrypting, and vice versa.
1531 optArg1 = !optArg1;
1532 break;
1533 /* kill warnings. */
1534 case ssl_calg_null:
1535 case ssl_calg_rc4:
1536 case ssl_calg_rc2:
1537 case ssl_calg_idea:
1538 case ssl_calg_fortezza:
1539 break;
1542 rv = (*initFn)(clientContext,
1543 pwSpec->client.write_key_item.data,
1544 pwSpec->client.write_key_item.len,
1545 pwSpec->client.write_iv_item.data,
1546 mode, optArg1, optArg2);
1547 if (rv != SECSuccess) {
1548 PORT_Assert(0);
1549 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1550 goto bail_out;
1553 pwSpec->encodeContext = (ss->sec.isServer) ? serverContext : clientContext;
1554 pwSpec->decodeContext = (ss->sec.isServer) ? clientContext : serverContext;
1556 ssl3_InitCompressionContext(pwSpec);
1558 success:
1559 return SECSuccess;
1561 bail_out:
1562 return SECFailure;
1564 #endif
1566 /* This function should probably be moved to pk11wrap and be named
1567 * PK11_ParamFromIVAndEffectiveKeyBits
1569 static SECItem *
1570 ssl3_ParamFromIV(CK_MECHANISM_TYPE mtype, SECItem *iv, CK_ULONG ulEffectiveBits)
1572 SECItem * param = PK11_ParamFromIV(mtype, iv);
1573 if (param && param->data && param->len >= sizeof(CK_RC2_PARAMS)) {
1574 switch (mtype) {
1575 case CKM_RC2_KEY_GEN:
1576 case CKM_RC2_ECB:
1577 case CKM_RC2_CBC:
1578 case CKM_RC2_MAC:
1579 case CKM_RC2_MAC_GENERAL:
1580 case CKM_RC2_CBC_PAD:
1581 *(CK_RC2_PARAMS *)param->data = ulEffectiveBits;
1582 default: break;
1585 return param;
1588 /* Initialize encryption and MAC contexts for pending spec.
1589 * Master Secret already is derived.
1590 * Caller holds Spec write lock.
1592 static SECStatus
1593 ssl3_InitPendingContextsPKCS11(sslSocket *ss)
1595 ssl3CipherSpec * pwSpec;
1596 const ssl3BulkCipherDef *cipher_def;
1597 PK11Context * serverContext = NULL;
1598 PK11Context * clientContext = NULL;
1599 SECItem * param;
1600 CK_MECHANISM_TYPE mechanism;
1601 CK_MECHANISM_TYPE mac_mech;
1602 CK_ULONG macLength;
1603 CK_ULONG effKeyBits;
1604 SECItem iv;
1605 SECItem mac_param;
1606 SSLCipherAlgorithm calg;
1608 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
1609 PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
1610 PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
1612 pwSpec = ss->ssl3.pwSpec;
1613 cipher_def = pwSpec->cipher_def;
1614 macLength = pwSpec->mac_size;
1617 ** Now setup the MAC contexts,
1618 ** crypto contexts are setup below.
1621 pwSpec->client.write_mac_context = NULL;
1622 pwSpec->server.write_mac_context = NULL;
1623 mac_mech = pwSpec->mac_def->mmech;
1624 mac_param.data = (unsigned char *)&macLength;
1625 mac_param.len = sizeof(macLength);
1626 mac_param.type = 0;
1628 pwSpec->client.write_mac_context = PK11_CreateContextBySymKey(
1629 mac_mech, CKA_SIGN, pwSpec->client.write_mac_key, &mac_param);
1630 if (pwSpec->client.write_mac_context == NULL) {
1631 ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
1632 goto fail;
1634 pwSpec->server.write_mac_context = PK11_CreateContextBySymKey(
1635 mac_mech, CKA_SIGN, pwSpec->server.write_mac_key, &mac_param);
1636 if (pwSpec->server.write_mac_context == NULL) {
1637 ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
1638 goto fail;
1642 ** Now setup the crypto contexts.
1645 calg = cipher_def->calg;
1646 PORT_Assert(alg2Mech[calg].calg == calg);
1648 if (calg == calg_null) {
1649 pwSpec->encode = Null_Cipher;
1650 pwSpec->decode = Null_Cipher;
1651 pwSpec->destroy = NULL;
1652 return SECSuccess;
1654 mechanism = alg2Mech[calg].cmech;
1655 effKeyBits = cipher_def->key_size * BPB;
1658 * build the server context
1660 iv.data = pwSpec->server.write_iv;
1661 iv.len = cipher_def->iv_size;
1662 param = ssl3_ParamFromIV(mechanism, &iv, effKeyBits);
1663 if (param == NULL) {
1664 ssl_MapLowLevelError(SSL_ERROR_IV_PARAM_FAILURE);
1665 goto fail;
1667 serverContext = PK11_CreateContextBySymKey(mechanism,
1668 (ss->sec.isServer ? CKA_ENCRYPT : CKA_DECRYPT),
1669 pwSpec->server.write_key, param);
1670 iv.data = PK11_IVFromParam(mechanism, param, (int *)&iv.len);
1671 if (iv.data)
1672 PORT_Memcpy(pwSpec->server.write_iv, iv.data, iv.len);
1673 SECITEM_FreeItem(param, PR_TRUE);
1674 if (serverContext == NULL) {
1675 ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
1676 goto fail;
1680 * build the client context
1682 iv.data = pwSpec->client.write_iv;
1683 iv.len = cipher_def->iv_size;
1685 param = ssl3_ParamFromIV(mechanism, &iv, effKeyBits);
1686 if (param == NULL) {
1687 ssl_MapLowLevelError(SSL_ERROR_IV_PARAM_FAILURE);
1688 goto fail;
1690 clientContext = PK11_CreateContextBySymKey(mechanism,
1691 (ss->sec.isServer ? CKA_DECRYPT : CKA_ENCRYPT),
1692 pwSpec->client.write_key, param);
1693 iv.data = PK11_IVFromParam(mechanism, param, (int *)&iv.len);
1694 if (iv.data)
1695 PORT_Memcpy(pwSpec->client.write_iv, iv.data, iv.len);
1696 SECITEM_FreeItem(param,PR_TRUE);
1697 if (clientContext == NULL) {
1698 ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
1699 goto fail;
1701 pwSpec->encode = (SSLCipher) PK11_CipherOp;
1702 pwSpec->decode = (SSLCipher) PK11_CipherOp;
1703 pwSpec->destroy = (SSLDestroy) PK11_DestroyContext;
1705 pwSpec->encodeContext = (ss->sec.isServer) ? serverContext : clientContext;
1706 pwSpec->decodeContext = (ss->sec.isServer) ? clientContext : serverContext;
1708 serverContext = NULL;
1709 clientContext = NULL;
1711 ssl3_InitCompressionContext(pwSpec);
1713 return SECSuccess;
1715 fail:
1716 if (serverContext != NULL) PK11_DestroyContext(serverContext, PR_TRUE);
1717 if (clientContext != NULL) PK11_DestroyContext(clientContext, PR_TRUE);
1718 if (pwSpec->client.write_mac_context != NULL) {
1719 PK11_DestroyContext(pwSpec->client.write_mac_context,PR_TRUE);
1720 pwSpec->client.write_mac_context = NULL;
1722 if (pwSpec->server.write_mac_context != NULL) {
1723 PK11_DestroyContext(pwSpec->server.write_mac_context,PR_TRUE);
1724 pwSpec->server.write_mac_context = NULL;
1727 return SECFailure;
1730 /* Complete the initialization of all keys, ciphers, MACs and their contexts
1731 * for the pending Cipher Spec.
1732 * Called from: ssl3_SendClientKeyExchange (for Full handshake)
1733 * ssl3_HandleRSAClientKeyExchange (for Full handshake)
1734 * ssl3_HandleServerHello (for session restart)
1735 * ssl3_HandleClientHello (for session restart)
1736 * Sets error code, but caller probably should override to disambiguate.
1737 * NULL pms means re-use old master_secret.
1739 * This code is common to the bypass and PKCS11 execution paths.
1740 * For the bypass case, pms is NULL.
1742 SECStatus
1743 ssl3_InitPendingCipherSpec(sslSocket *ss, PK11SymKey *pms)
1745 ssl3CipherSpec * pwSpec;
1746 ssl3CipherSpec * cwSpec;
1747 SECStatus rv;
1749 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
1751 ssl_GetSpecWriteLock(ss); /**************************************/
1753 PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
1755 pwSpec = ss->ssl3.pwSpec;
1756 cwSpec = ss->ssl3.cwSpec;
1758 if (pms || (!pwSpec->msItem.len && !pwSpec->master_secret)) {
1759 rv = ssl3_DeriveMasterSecret(ss, pms);
1760 if (rv != SECSuccess) {
1761 goto done; /* err code set by ssl3_DeriveMasterSecret */
1764 #ifndef NO_PKCS11_BYPASS
1765 if (ss->opt.bypassPKCS11 && pwSpec->msItem.len && pwSpec->msItem.data) {
1766 /* Double Bypass succeeded in extracting the master_secret */
1767 const ssl3KEADef * kea_def = ss->ssl3.hs.kea_def;
1768 PRBool isTLS = (PRBool)(kea_def->tls_keygen ||
1769 (pwSpec->version > SSL_LIBRARY_VERSION_3_0));
1770 pwSpec->bypassCiphers = PR_TRUE;
1771 rv = ssl3_KeyAndMacDeriveBypass( pwSpec,
1772 (const unsigned char *)&ss->ssl3.hs.client_random,
1773 (const unsigned char *)&ss->ssl3.hs.server_random,
1774 isTLS,
1775 (PRBool)(kea_def->is_limited));
1776 if (rv == SECSuccess) {
1777 rv = ssl3_InitPendingContextsBypass(ss);
1779 } else
1780 #endif
1781 if (pwSpec->master_secret) {
1782 rv = ssl3_DeriveConnectionKeysPKCS11(ss);
1783 if (rv == SECSuccess) {
1784 rv = ssl3_InitPendingContextsPKCS11(ss);
1786 } else {
1787 PORT_Assert(pwSpec->master_secret);
1788 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1789 rv = SECFailure;
1791 if (rv != SECSuccess) {
1792 goto done;
1795 /* Generic behaviors -- common to all crypto methods */
1796 if (!IS_DTLS(ss)) {
1797 pwSpec->read_seq_num.high = pwSpec->write_seq_num.high = 0;
1798 } else {
1799 if (cwSpec->epoch == PR_UINT16_MAX) {
1800 /* The problem here is that we have rehandshaked too many
1801 * times (you are not allowed to wrap the epoch). The
1802 * spec says you should be discarding the connection
1803 * and start over, so not much we can do here. */
1804 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1805 rv = SECFailure;
1806 goto done;
1808 /* The sequence number has the high 16 bits as the epoch. */
1809 pwSpec->epoch = cwSpec->epoch + 1;
1810 pwSpec->read_seq_num.high = pwSpec->write_seq_num.high =
1811 pwSpec->epoch << 16;
1813 dtls_InitRecvdRecords(&pwSpec->recvdRecords);
1815 pwSpec->read_seq_num.low = pwSpec->write_seq_num.low = 0;
1817 done:
1818 ssl_ReleaseSpecWriteLock(ss); /******************************/
1819 if (rv != SECSuccess)
1820 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
1821 return rv;
1825 * 60 bytes is 3 times the maximum length MAC size that is supported.
1827 static const unsigned char mac_pad_1 [60] = {
1828 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1829 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1830 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1831 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1832 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1833 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1834 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1835 0x36, 0x36, 0x36, 0x36
1837 static const unsigned char mac_pad_2 [60] = {
1838 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1839 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1840 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1841 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1842 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1843 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1844 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1845 0x5c, 0x5c, 0x5c, 0x5c
1848 /* Called from: ssl3_SendRecord()
1849 ** ssl3_HandleRecord()
1850 ** Caller must already hold the SpecReadLock. (wish we could assert that!)
1852 static SECStatus
1853 ssl3_ComputeRecordMAC(
1854 ssl3CipherSpec * spec,
1855 PRBool useServerMacKey,
1856 PRBool isDTLS,
1857 SSL3ContentType type,
1858 SSL3ProtocolVersion version,
1859 SSL3SequenceNumber seq_num,
1860 const SSL3Opaque * input,
1861 int inputLength,
1862 unsigned char * outbuf,
1863 unsigned int * outLength)
1865 const ssl3MACDef * mac_def;
1866 SECStatus rv;
1867 #ifndef NO_PKCS11_BYPASS
1868 PRBool isTLS;
1869 #endif
1870 unsigned int tempLen;
1871 unsigned char temp[MAX_MAC_LENGTH];
1873 temp[0] = (unsigned char)(seq_num.high >> 24);
1874 temp[1] = (unsigned char)(seq_num.high >> 16);
1875 temp[2] = (unsigned char)(seq_num.high >> 8);
1876 temp[3] = (unsigned char)(seq_num.high >> 0);
1877 temp[4] = (unsigned char)(seq_num.low >> 24);
1878 temp[5] = (unsigned char)(seq_num.low >> 16);
1879 temp[6] = (unsigned char)(seq_num.low >> 8);
1880 temp[7] = (unsigned char)(seq_num.low >> 0);
1881 temp[8] = type;
1883 /* TLS MAC includes the record's version field, SSL's doesn't.
1884 ** We decide which MAC defintiion to use based on the version of
1885 ** the protocol that was negotiated when the spec became current,
1886 ** NOT based on the version value in the record itself.
1887 ** But, we use the record'v version value in the computation.
1889 if (spec->version <= SSL_LIBRARY_VERSION_3_0) {
1890 temp[9] = MSB(inputLength);
1891 temp[10] = LSB(inputLength);
1892 tempLen = 11;
1893 #ifndef NO_PKCS11_BYPASS
1894 isTLS = PR_FALSE;
1895 #endif
1896 } else {
1897 /* New TLS hash includes version. */
1898 if (isDTLS) {
1899 SSL3ProtocolVersion dtls_version;
1901 dtls_version = dtls_TLSVersionToDTLSVersion(version);
1902 temp[9] = MSB(dtls_version);
1903 temp[10] = LSB(dtls_version);
1904 } else {
1905 temp[9] = MSB(version);
1906 temp[10] = LSB(version);
1908 temp[11] = MSB(inputLength);
1909 temp[12] = LSB(inputLength);
1910 tempLen = 13;
1911 #ifndef NO_PKCS11_BYPASS
1912 isTLS = PR_TRUE;
1913 #endif
1916 PRINT_BUF(95, (NULL, "frag hash1: temp", temp, tempLen));
1917 PRINT_BUF(95, (NULL, "frag hash1: input", input, inputLength));
1919 mac_def = spec->mac_def;
1920 if (mac_def->mac == mac_null) {
1921 *outLength = 0;
1922 return SECSuccess;
1924 #ifndef NO_PKCS11_BYPASS
1925 if (spec->bypassCiphers) {
1926 /* bypass version */
1927 const SECHashObject *hashObj = NULL;
1928 unsigned int pad_bytes = 0;
1929 PRUint64 write_mac_context[MAX_MAC_CONTEXT_LLONGS];
1931 switch (mac_def->mac) {
1932 case ssl_mac_null:
1933 *outLength = 0;
1934 return SECSuccess;
1935 case ssl_mac_md5:
1936 pad_bytes = 48;
1937 hashObj = HASH_GetRawHashObject(HASH_AlgMD5);
1938 break;
1939 case ssl_mac_sha:
1940 pad_bytes = 40;
1941 hashObj = HASH_GetRawHashObject(HASH_AlgSHA1);
1942 break;
1943 case ssl_hmac_md5: /* used with TLS */
1944 hashObj = HASH_GetRawHashObject(HASH_AlgMD5);
1945 break;
1946 case ssl_hmac_sha: /* used with TLS */
1947 hashObj = HASH_GetRawHashObject(HASH_AlgSHA1);
1948 break;
1949 default:
1950 break;
1952 if (!hashObj) {
1953 PORT_Assert(0);
1954 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1955 return SECFailure;
1958 if (!isTLS) {
1959 /* compute "inner" part of SSL3 MAC */
1960 hashObj->begin(write_mac_context);
1961 if (useServerMacKey)
1962 hashObj->update(write_mac_context,
1963 spec->server.write_mac_key_item.data,
1964 spec->server.write_mac_key_item.len);
1965 else
1966 hashObj->update(write_mac_context,
1967 spec->client.write_mac_key_item.data,
1968 spec->client.write_mac_key_item.len);
1969 hashObj->update(write_mac_context, mac_pad_1, pad_bytes);
1970 hashObj->update(write_mac_context, temp, tempLen);
1971 hashObj->update(write_mac_context, input, inputLength);
1972 hashObj->end(write_mac_context, temp, &tempLen, sizeof temp);
1974 /* compute "outer" part of SSL3 MAC */
1975 hashObj->begin(write_mac_context);
1976 if (useServerMacKey)
1977 hashObj->update(write_mac_context,
1978 spec->server.write_mac_key_item.data,
1979 spec->server.write_mac_key_item.len);
1980 else
1981 hashObj->update(write_mac_context,
1982 spec->client.write_mac_key_item.data,
1983 spec->client.write_mac_key_item.len);
1984 hashObj->update(write_mac_context, mac_pad_2, pad_bytes);
1985 hashObj->update(write_mac_context, temp, tempLen);
1986 hashObj->end(write_mac_context, outbuf, outLength, spec->mac_size);
1987 rv = SECSuccess;
1988 } else { /* is TLS */
1989 #define cx ((HMACContext *)write_mac_context)
1990 if (useServerMacKey) {
1991 rv = HMAC_Init(cx, hashObj,
1992 spec->server.write_mac_key_item.data,
1993 spec->server.write_mac_key_item.len, PR_FALSE);
1994 } else {
1995 rv = HMAC_Init(cx, hashObj,
1996 spec->client.write_mac_key_item.data,
1997 spec->client.write_mac_key_item.len, PR_FALSE);
1999 if (rv == SECSuccess) {
2000 HMAC_Begin(cx);
2001 HMAC_Update(cx, temp, tempLen);
2002 HMAC_Update(cx, input, inputLength);
2003 rv = HMAC_Finish(cx, outbuf, outLength, spec->mac_size);
2004 HMAC_Destroy(cx, PR_FALSE);
2006 #undef cx
2008 } else
2009 #endif
2011 PK11Context *mac_context =
2012 (useServerMacKey ? spec->server.write_mac_context
2013 : spec->client.write_mac_context);
2014 rv = PK11_DigestBegin(mac_context);
2015 rv |= PK11_DigestOp(mac_context, temp, tempLen);
2016 rv |= PK11_DigestOp(mac_context, input, inputLength);
2017 rv |= PK11_DigestFinal(mac_context, outbuf, outLength, spec->mac_size);
2020 PORT_Assert(rv != SECSuccess || *outLength == (unsigned)spec->mac_size);
2022 PRINT_BUF(95, (NULL, "frag hash2: result", outbuf, *outLength));
2024 if (rv != SECSuccess) {
2025 rv = SECFailure;
2026 ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
2028 return rv;
2031 static PRBool
2032 ssl3_ClientAuthTokenPresent(sslSessionID *sid) {
2033 PK11SlotInfo *slot = NULL;
2034 PRBool isPresent = PR_TRUE;
2036 /* we only care if we are doing client auth */
2037 /* If NSS_PLATFORM_CLIENT_AUTH is defined and a platformClientKey is being
2038 * used, u.ssl3.clAuthValid will be false and this function will always
2039 * return PR_TRUE. */
2040 if (!sid || !sid->u.ssl3.clAuthValid) {
2041 return PR_TRUE;
2044 /* get the slot */
2045 slot = SECMOD_LookupSlot(sid->u.ssl3.clAuthModuleID,
2046 sid->u.ssl3.clAuthSlotID);
2047 if (slot == NULL ||
2048 !PK11_IsPresent(slot) ||
2049 sid->u.ssl3.clAuthSeries != PK11_GetSlotSeries(slot) ||
2050 sid->u.ssl3.clAuthSlotID != PK11_GetSlotID(slot) ||
2051 sid->u.ssl3.clAuthModuleID != PK11_GetModuleID(slot) ||
2052 (PK11_NeedLogin(slot) && !PK11_IsLoggedIn(slot, NULL))) {
2053 isPresent = PR_FALSE;
2055 if (slot) {
2056 PK11_FreeSlot(slot);
2058 return isPresent;
2061 /* Caller must hold the spec read lock. */
2062 SECStatus
2063 ssl3_CompressMACEncryptRecord(ssl3CipherSpec * cwSpec,
2064 PRBool isServer,
2065 PRBool isDTLS,
2066 PRBool capRecordVersion,
2067 SSL3ContentType type,
2068 const SSL3Opaque * pIn,
2069 PRUint32 contentLen,
2070 sslBuffer * wrBuf)
2072 const ssl3BulkCipherDef * cipher_def;
2073 SECStatus rv;
2074 PRUint32 macLen = 0;
2075 PRUint32 fragLen;
2076 PRUint32 p1Len, p2Len, oddLen = 0;
2077 PRUint16 headerLen;
2078 int ivLen = 0;
2079 int cipherBytes = 0;
2081 cipher_def = cwSpec->cipher_def;
2082 headerLen = isDTLS ? DTLS_RECORD_HEADER_LENGTH : SSL3_RECORD_HEADER_LENGTH;
2084 if (cipher_def->type == type_block &&
2085 cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
2086 /* Prepend the per-record explicit IV using technique 2b from
2087 * RFC 4346 section 6.2.3.2: The IV is a cryptographically
2088 * strong random number XORed with the CBC residue from the previous
2089 * record.
2091 ivLen = cipher_def->iv_size;
2092 if (ivLen > wrBuf->space - headerLen) {
2093 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2094 return SECFailure;
2096 rv = PK11_GenerateRandom(wrBuf->buf + headerLen, ivLen);
2097 if (rv != SECSuccess) {
2098 ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
2099 return rv;
2101 rv = cwSpec->encode( cwSpec->encodeContext,
2102 wrBuf->buf + headerLen,
2103 &cipherBytes, /* output and actual outLen */
2104 ivLen, /* max outlen */
2105 wrBuf->buf + headerLen,
2106 ivLen); /* input and inputLen*/
2107 if (rv != SECSuccess || cipherBytes != ivLen) {
2108 PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
2109 return SECFailure;
2113 if (cwSpec->compressor) {
2114 int outlen;
2115 rv = cwSpec->compressor(
2116 cwSpec->compressContext,
2117 wrBuf->buf + headerLen + ivLen, &outlen,
2118 wrBuf->space - headerLen - ivLen, pIn, contentLen);
2119 if (rv != SECSuccess)
2120 return rv;
2121 pIn = wrBuf->buf + headerLen + ivLen;
2122 contentLen = outlen;
2126 * Add the MAC
2128 rv = ssl3_ComputeRecordMAC( cwSpec, isServer, isDTLS,
2129 type, cwSpec->version, cwSpec->write_seq_num, pIn, contentLen,
2130 wrBuf->buf + headerLen + ivLen + contentLen, &macLen);
2131 if (rv != SECSuccess) {
2132 ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
2133 return SECFailure;
2135 p1Len = contentLen;
2136 p2Len = macLen;
2137 fragLen = contentLen + macLen; /* needs to be encrypted */
2138 PORT_Assert(fragLen <= MAX_FRAGMENT_LENGTH + 1024);
2141 * Pad the text (if we're doing a block cipher)
2142 * then Encrypt it
2144 if (cipher_def->type == type_block) {
2145 unsigned char * pBuf;
2146 int padding_length;
2147 int i;
2149 oddLen = contentLen % cipher_def->block_size;
2150 /* Assume blockSize is a power of two */
2151 padding_length = cipher_def->block_size - 1 -
2152 ((fragLen) & (cipher_def->block_size - 1));
2153 fragLen += padding_length + 1;
2154 PORT_Assert((fragLen % cipher_def->block_size) == 0);
2156 /* Pad according to TLS rules (also acceptable to SSL3). */
2157 pBuf = &wrBuf->buf[headerLen + ivLen + fragLen - 1];
2158 for (i = padding_length + 1; i > 0; --i) {
2159 *pBuf-- = padding_length;
2161 /* now, if contentLen is not a multiple of block size, fix it */
2162 p2Len = fragLen - p1Len;
2164 if (p1Len < 256) {
2165 oddLen = p1Len;
2166 p1Len = 0;
2167 } else {
2168 p1Len -= oddLen;
2170 if (oddLen) {
2171 p2Len += oddLen;
2172 PORT_Assert( (cipher_def->block_size < 2) || \
2173 (p2Len % cipher_def->block_size) == 0);
2174 memmove(wrBuf->buf + headerLen + ivLen + p1Len, pIn + p1Len, oddLen);
2176 if (p1Len > 0) {
2177 int cipherBytesPart1 = -1;
2178 rv = cwSpec->encode( cwSpec->encodeContext,
2179 wrBuf->buf + headerLen + ivLen, /* output */
2180 &cipherBytesPart1, /* actual outlen */
2181 p1Len, /* max outlen */
2182 pIn, p1Len); /* input, and inputlen */
2183 PORT_Assert(rv == SECSuccess && cipherBytesPart1 == (int) p1Len);
2184 if (rv != SECSuccess || cipherBytesPart1 != (int) p1Len) {
2185 PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
2186 return SECFailure;
2188 cipherBytes += cipherBytesPart1;
2190 if (p2Len > 0) {
2191 int cipherBytesPart2 = -1;
2192 rv = cwSpec->encode( cwSpec->encodeContext,
2193 wrBuf->buf + headerLen + ivLen + p1Len,
2194 &cipherBytesPart2, /* output and actual outLen */
2195 p2Len, /* max outlen */
2196 wrBuf->buf + headerLen + ivLen + p1Len,
2197 p2Len); /* input and inputLen*/
2198 PORT_Assert(rv == SECSuccess && cipherBytesPart2 == (int) p2Len);
2199 if (rv != SECSuccess || cipherBytesPart2 != (int) p2Len) {
2200 PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
2201 return SECFailure;
2203 cipherBytes += cipherBytesPart2;
2205 PORT_Assert(cipherBytes <= MAX_FRAGMENT_LENGTH + 1024);
2207 wrBuf->len = cipherBytes + headerLen;
2208 wrBuf->buf[0] = type;
2209 if (isDTLS) {
2210 SSL3ProtocolVersion version;
2212 version = dtls_TLSVersionToDTLSVersion(cwSpec->version);
2213 wrBuf->buf[1] = MSB(version);
2214 wrBuf->buf[2] = LSB(version);
2215 wrBuf->buf[3] = (unsigned char)(cwSpec->write_seq_num.high >> 24);
2216 wrBuf->buf[4] = (unsigned char)(cwSpec->write_seq_num.high >> 16);
2217 wrBuf->buf[5] = (unsigned char)(cwSpec->write_seq_num.high >> 8);
2218 wrBuf->buf[6] = (unsigned char)(cwSpec->write_seq_num.high >> 0);
2219 wrBuf->buf[7] = (unsigned char)(cwSpec->write_seq_num.low >> 24);
2220 wrBuf->buf[8] = (unsigned char)(cwSpec->write_seq_num.low >> 16);
2221 wrBuf->buf[9] = (unsigned char)(cwSpec->write_seq_num.low >> 8);
2222 wrBuf->buf[10] = (unsigned char)(cwSpec->write_seq_num.low >> 0);
2223 wrBuf->buf[11] = MSB(cipherBytes);
2224 wrBuf->buf[12] = LSB(cipherBytes);
2225 } else {
2226 SSL3ProtocolVersion version = cwSpec->version;
2228 if (capRecordVersion) {
2229 version = PR_MIN(SSL_LIBRARY_VERSION_TLS_1_0, version);
2231 wrBuf->buf[1] = MSB(version);
2232 wrBuf->buf[2] = LSB(version);
2233 wrBuf->buf[3] = MSB(cipherBytes);
2234 wrBuf->buf[4] = LSB(cipherBytes);
2237 ssl3_BumpSequenceNumber(&cwSpec->write_seq_num);
2239 return SECSuccess;
2242 /* Process the plain text before sending it.
2243 * Returns the number of bytes of plaintext that were successfully sent
2244 * plus the number of bytes of plaintext that were copied into the
2245 * output (write) buffer.
2246 * Returns SECFailure on a hard IO error, memory error, or crypto error.
2247 * Does NOT return SECWouldBlock.
2249 * Notes on the use of the private ssl flags:
2250 * (no private SSL flags)
2251 * Attempt to make and send SSL records for all plaintext
2252 * If non-blocking and a send gets WOULD_BLOCK,
2253 * or if the pending (ciphertext) buffer is not empty,
2254 * then buffer remaining bytes of ciphertext into pending buf,
2255 * and continue to do that for all succssive records until all
2256 * bytes are used.
2257 * ssl_SEND_FLAG_FORCE_INTO_BUFFER
2258 * As above, except this suppresses all write attempts, and forces
2259 * all ciphertext into the pending ciphertext buffer.
2260 * ssl_SEND_FLAG_USE_EPOCH (for DTLS)
2261 * Forces the use of the provided epoch
2262 * ssl_SEND_FLAG_CAP_RECORD_VERSION
2263 * Caps the record layer version number of TLS ClientHello to { 3, 1 }
2264 * (TLS 1.0). Some TLS 1.0 servers (which seem to use F5 BIG-IP) ignore
2265 * ClientHello.client_version and use the record layer version number
2266 * (TLSPlaintext.version) instead when negotiating protocol versions. In
2267 * addition, if the record layer version number of ClientHello is { 3, 2 }
2268 * (TLS 1.1) or higher, these servers reset the TCP connections. Set this
2269 * flag to work around such servers.
2271 PRInt32
2272 ssl3_SendRecord( sslSocket * ss,
2273 DTLSEpoch epoch, /* DTLS only */
2274 SSL3ContentType type,
2275 const SSL3Opaque * pIn, /* input buffer */
2276 PRInt32 nIn, /* bytes of input */
2277 PRInt32 flags)
2279 sslBuffer * wrBuf = &ss->sec.writeBuf;
2280 SECStatus rv;
2281 PRInt32 totalSent = 0;
2282 PRBool capRecordVersion;
2284 SSL_TRC(3, ("%d: SSL3[%d] SendRecord type: %s nIn=%d",
2285 SSL_GETPID(), ss->fd, ssl3_DecodeContentType(type),
2286 nIn));
2287 PRINT_BUF(3, (ss, "Send record (plain text)", pIn, nIn));
2289 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
2291 capRecordVersion = ((flags & ssl_SEND_FLAG_CAP_RECORD_VERSION) != 0);
2293 if (capRecordVersion) {
2294 /* ssl_SEND_FLAG_CAP_RECORD_VERSION can only be used with the
2295 * TLS initial ClientHello. */
2296 PORT_Assert(!IS_DTLS(ss));
2297 PORT_Assert(!ss->firstHsDone);
2298 PORT_Assert(type == content_handshake);
2299 PORT_Assert(ss->ssl3.hs.ws == wait_server_hello);
2302 if (ss->ssl3.initialized == PR_FALSE) {
2303 /* This can happen on a server if the very first incoming record
2304 ** looks like a defective ssl3 record (e.g. too long), and we're
2305 ** trying to send an alert.
2307 PR_ASSERT(type == content_alert);
2308 rv = ssl3_InitState(ss);
2309 if (rv != SECSuccess) {
2310 return SECFailure; /* ssl3_InitState has set the error code. */
2314 /* check for Token Presence */
2315 if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) {
2316 PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
2317 return SECFailure;
2320 while (nIn > 0) {
2321 PRUint32 contentLen = PR_MIN(nIn, MAX_FRAGMENT_LENGTH);
2322 unsigned int spaceNeeded;
2323 unsigned int numRecords;
2325 ssl_GetSpecReadLock(ss); /********************************/
2327 if (nIn > 1 && ss->opt.cbcRandomIV &&
2328 ss->ssl3.cwSpec->version < SSL_LIBRARY_VERSION_TLS_1_1 &&
2329 type == content_application_data &&
2330 ss->ssl3.cwSpec->cipher_def->type == type_block /* CBC mode */) {
2331 /* We will split the first byte of the record into its own record,
2332 * as explained in the documentation for SSL_CBC_RANDOM_IV in ssl.h
2334 numRecords = 2;
2335 } else {
2336 numRecords = 1;
2339 spaceNeeded = contentLen + (numRecords * SSL3_BUFFER_FUDGE);
2340 if (ss->ssl3.cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1 &&
2341 ss->ssl3.cwSpec->cipher_def->type == type_block) {
2342 spaceNeeded += ss->ssl3.cwSpec->cipher_def->iv_size;
2344 if (spaceNeeded > wrBuf->space) {
2345 rv = sslBuffer_Grow(wrBuf, spaceNeeded);
2346 if (rv != SECSuccess) {
2347 SSL_DBG(("%d: SSL3[%d]: SendRecord, tried to get %d bytes",
2348 SSL_GETPID(), ss->fd, spaceNeeded));
2349 goto spec_locked_loser; /* sslBuffer_Grow set error code. */
2353 if (numRecords == 2) {
2354 sslBuffer secondRecord;
2356 rv = ssl3_CompressMACEncryptRecord(ss->ssl3.cwSpec,
2357 ss->sec.isServer, IS_DTLS(ss),
2358 capRecordVersion, type, pIn,
2359 1, wrBuf);
2360 if (rv != SECSuccess)
2361 goto spec_locked_loser;
2363 PRINT_BUF(50, (ss, "send (encrypted) record data [1/2]:",
2364 wrBuf->buf, wrBuf->len));
2366 secondRecord.buf = wrBuf->buf + wrBuf->len;
2367 secondRecord.len = 0;
2368 secondRecord.space = wrBuf->space - wrBuf->len;
2370 rv = ssl3_CompressMACEncryptRecord(ss->ssl3.cwSpec,
2371 ss->sec.isServer, IS_DTLS(ss),
2372 capRecordVersion, type,
2373 pIn + 1, contentLen - 1,
2374 &secondRecord);
2375 if (rv == SECSuccess) {
2376 PRINT_BUF(50, (ss, "send (encrypted) record data [2/2]:",
2377 secondRecord.buf, secondRecord.len));
2378 wrBuf->len += secondRecord.len;
2380 } else {
2381 if (!IS_DTLS(ss)) {
2382 rv = ssl3_CompressMACEncryptRecord(ss->ssl3.cwSpec,
2383 ss->sec.isServer,
2384 IS_DTLS(ss),
2385 capRecordVersion,
2386 type, pIn,
2387 contentLen, wrBuf);
2388 } else {
2389 rv = dtls_CompressMACEncryptRecord(ss, epoch,
2390 !!(flags & ssl_SEND_FLAG_USE_EPOCH),
2391 type, pIn,
2392 contentLen, wrBuf);
2395 if (rv == SECSuccess) {
2396 PRINT_BUF(50, (ss, "send (encrypted) record data:",
2397 wrBuf->buf, wrBuf->len));
2401 spec_locked_loser:
2402 ssl_ReleaseSpecReadLock(ss); /************************************/
2404 if (rv != SECSuccess)
2405 return SECFailure;
2407 pIn += contentLen;
2408 nIn -= contentLen;
2409 PORT_Assert( nIn >= 0 );
2411 /* If there's still some previously saved ciphertext,
2412 * or the caller doesn't want us to send the data yet,
2413 * then add all our new ciphertext to the amount previously saved.
2415 if ((ss->pendingBuf.len > 0) ||
2416 (flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) {
2418 rv = ssl_SaveWriteData(ss, wrBuf->buf, wrBuf->len);
2419 if (rv != SECSuccess) {
2420 /* presumably a memory error, SEC_ERROR_NO_MEMORY */
2421 return SECFailure;
2423 wrBuf->len = 0; /* All cipher text is saved away. */
2425 if (!(flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) {
2426 PRInt32 sent;
2427 ss->handshakeBegun = 1;
2428 sent = ssl_SendSavedWriteData(ss);
2429 if (sent < 0 && PR_GetError() != PR_WOULD_BLOCK_ERROR) {
2430 ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE);
2431 return SECFailure;
2433 if (ss->pendingBuf.len) {
2434 flags |= ssl_SEND_FLAG_FORCE_INTO_BUFFER;
2437 } else if (wrBuf->len > 0) {
2438 PRInt32 sent;
2439 ss->handshakeBegun = 1;
2440 sent = ssl_DefSend(ss, wrBuf->buf, wrBuf->len,
2441 flags & ~ssl_SEND_FLAG_MASK);
2442 if (sent < 0) {
2443 if (PR_GetError() != PR_WOULD_BLOCK_ERROR) {
2444 ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE);
2445 return SECFailure;
2447 /* we got PR_WOULD_BLOCK_ERROR, which means none was sent. */
2448 sent = 0;
2450 wrBuf->len -= sent;
2451 if (wrBuf->len) {
2452 if (IS_DTLS(ss)) {
2453 /* DTLS just says no in this case. No buffering */
2454 PR_SetError(PR_WOULD_BLOCK_ERROR, 0);
2455 return SECFailure;
2457 /* now take all the remaining unsent new ciphertext and
2458 * append it to the buffer of previously unsent ciphertext.
2460 rv = ssl_SaveWriteData(ss, wrBuf->buf + sent, wrBuf->len);
2461 if (rv != SECSuccess) {
2462 /* presumably a memory error, SEC_ERROR_NO_MEMORY */
2463 return SECFailure;
2467 totalSent += contentLen;
2469 return totalSent;
2472 #define SSL3_PENDING_HIGH_WATER 1024
2474 /* Attempt to send the content of "in" in an SSL application_data record.
2475 * Returns "len" or SECFailure, never SECWouldBlock, nor SECSuccess.
2478 ssl3_SendApplicationData(sslSocket *ss, const unsigned char *in,
2479 PRInt32 len, PRInt32 flags)
2481 PRInt32 totalSent = 0;
2482 PRInt32 discarded = 0;
2484 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
2485 /* These flags for internal use only */
2486 PORT_Assert(!(flags & (ssl_SEND_FLAG_USE_EPOCH |
2487 ssl_SEND_FLAG_NO_RETRANSMIT)));
2488 if (len < 0 || !in) {
2489 PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
2490 return SECFailure;
2493 if (ss->pendingBuf.len > SSL3_PENDING_HIGH_WATER &&
2494 !ssl_SocketIsBlocking(ss)) {
2495 PORT_Assert(!ssl_SocketIsBlocking(ss));
2496 PORT_SetError(PR_WOULD_BLOCK_ERROR);
2497 return SECFailure;
2500 if (ss->appDataBuffered && len) {
2501 PORT_Assert (in[0] == (unsigned char)(ss->appDataBuffered));
2502 if (in[0] != (unsigned char)(ss->appDataBuffered)) {
2503 PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
2504 return SECFailure;
2506 in++;
2507 len--;
2508 discarded = 1;
2510 while (len > totalSent) {
2511 PRInt32 sent, toSend;
2513 if (totalSent > 0) {
2515 * The thread yield is intended to give the reader thread a
2516 * chance to get some cycles while the writer thread is in
2517 * the middle of a large application data write. (See
2518 * Bugzilla bug 127740, comment #1.)
2520 ssl_ReleaseXmitBufLock(ss);
2521 PR_Sleep(PR_INTERVAL_NO_WAIT); /* PR_Yield(); */
2522 ssl_GetXmitBufLock(ss);
2524 toSend = PR_MIN(len - totalSent, MAX_FRAGMENT_LENGTH);
2526 * Note that the 0 epoch is OK because flags will never require
2527 * its use, as guaranteed by the PORT_Assert above.
2529 sent = ssl3_SendRecord(ss, 0, content_application_data,
2530 in + totalSent, toSend, flags);
2531 if (sent < 0) {
2532 if (totalSent > 0 && PR_GetError() == PR_WOULD_BLOCK_ERROR) {
2533 PORT_Assert(ss->lastWriteBlocked);
2534 break;
2536 return SECFailure; /* error code set by ssl3_SendRecord */
2538 totalSent += sent;
2539 if (ss->pendingBuf.len) {
2540 /* must be a non-blocking socket */
2541 PORT_Assert(!ssl_SocketIsBlocking(ss));
2542 PORT_Assert(ss->lastWriteBlocked);
2543 break;
2546 if (ss->pendingBuf.len) {
2547 /* Must be non-blocking. */
2548 PORT_Assert(!ssl_SocketIsBlocking(ss));
2549 if (totalSent > 0) {
2550 ss->appDataBuffered = 0x100 | in[totalSent - 1];
2553 totalSent = totalSent + discarded - 1;
2554 if (totalSent <= 0) {
2555 PORT_SetError(PR_WOULD_BLOCK_ERROR);
2556 totalSent = SECFailure;
2558 return totalSent;
2560 ss->appDataBuffered = 0;
2561 return totalSent + discarded;
2564 /* Attempt to send buffered handshake messages.
2565 * This function returns SECSuccess or SECFailure, never SECWouldBlock.
2566 * Always set sendBuf.len to 0, even when returning SECFailure.
2568 * Depending on whether we are doing DTLS or not, this either calls
2570 * - ssl3_FlushHandshakeMessages if non-DTLS
2571 * - dtls_FlushHandshakeMessages if DTLS
2573 * Called from SSL3_SendAlert(), ssl3_SendChangeCipherSpecs(),
2574 * ssl3_AppendHandshake(), ssl3_SendClientHello(),
2575 * ssl3_SendHelloRequest(), ssl3_SendServerHelloDone(),
2576 * ssl3_SendFinished(),
2578 static SECStatus
2579 ssl3_FlushHandshake(sslSocket *ss, PRInt32 flags)
2581 if (IS_DTLS(ss)) {
2582 return dtls_FlushHandshakeMessages(ss, flags);
2583 } else {
2584 return ssl3_FlushHandshakeMessages(ss, flags);
2588 /* Attempt to send the content of sendBuf buffer in an SSL handshake record.
2589 * This function returns SECSuccess or SECFailure, never SECWouldBlock.
2590 * Always set sendBuf.len to 0, even when returning SECFailure.
2592 * Called from ssl3_FlushHandshake
2594 static SECStatus
2595 ssl3_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags)
2597 static const PRInt32 allowedFlags = ssl_SEND_FLAG_FORCE_INTO_BUFFER |
2598 ssl_SEND_FLAG_CAP_RECORD_VERSION;
2599 PRInt32 rv = SECSuccess;
2601 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
2602 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
2604 if (!ss->sec.ci.sendBuf.buf || !ss->sec.ci.sendBuf.len)
2605 return rv;
2607 /* only these flags are allowed */
2608 PORT_Assert(!(flags & ~allowedFlags));
2609 if ((flags & ~allowedFlags) != 0) {
2610 PORT_SetError(SEC_ERROR_INVALID_ARGS);
2611 rv = SECFailure;
2612 } else {
2613 rv = ssl3_SendRecord(ss, 0, content_handshake, ss->sec.ci.sendBuf.buf,
2614 ss->sec.ci.sendBuf.len, flags);
2616 if (rv < 0) {
2617 int err = PORT_GetError();
2618 PORT_Assert(err != PR_WOULD_BLOCK_ERROR);
2619 if (err == PR_WOULD_BLOCK_ERROR) {
2620 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2622 } else if (rv < ss->sec.ci.sendBuf.len) {
2623 /* short write should never happen */
2624 PORT_Assert(rv >= ss->sec.ci.sendBuf.len);
2625 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2626 rv = SECFailure;
2627 } else {
2628 rv = SECSuccess;
2631 /* Whether we succeeded or failed, toss the old handshake data. */
2632 ss->sec.ci.sendBuf.len = 0;
2633 return rv;
2637 * Called from ssl3_HandleAlert and from ssl3_HandleCertificate when
2638 * the remote client sends a negative response to our certificate request.
2639 * Returns SECFailure if the application has required client auth.
2640 * SECSuccess otherwise.
2642 static SECStatus
2643 ssl3_HandleNoCertificate(sslSocket *ss)
2645 if (ss->sec.peerCert != NULL) {
2646 if (ss->sec.peerKey != NULL) {
2647 SECKEY_DestroyPublicKey(ss->sec.peerKey);
2648 ss->sec.peerKey = NULL;
2650 CERT_DestroyCertificate(ss->sec.peerCert);
2651 ss->sec.peerCert = NULL;
2653 ssl3_CleanupPeerCerts(ss);
2655 /* If the server has required client-auth blindly but doesn't
2656 * actually look at the certificate it won't know that no
2657 * certificate was presented so we shutdown the socket to ensure
2658 * an error. We only do this if we haven't already completed the
2659 * first handshake because if we're redoing the handshake we
2660 * know the server is paying attention to the certificate.
2662 if ((ss->opt.requireCertificate == SSL_REQUIRE_ALWAYS) ||
2663 (!ss->firstHsDone &&
2664 (ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE))) {
2665 PRFileDesc * lower;
2667 if (ss->sec.uncache)
2668 ss->sec.uncache(ss->sec.ci.sid);
2669 SSL3_SendAlert(ss, alert_fatal, bad_certificate);
2671 lower = ss->fd->lower;
2672 #ifdef _WIN32
2673 lower->methods->shutdown(lower, PR_SHUTDOWN_SEND);
2674 #else
2675 lower->methods->shutdown(lower, PR_SHUTDOWN_BOTH);
2676 #endif
2677 PORT_SetError(SSL_ERROR_NO_CERTIFICATE);
2678 return SECFailure;
2680 return SECSuccess;
2683 /************************************************************************
2684 * Alerts
2688 ** Acquires both handshake and XmitBuf locks.
2689 ** Called from: ssl3_IllegalParameter <-
2690 ** ssl3_HandshakeFailure <-
2691 ** ssl3_HandleAlert <- ssl3_HandleRecord.
2692 ** ssl3_HandleChangeCipherSpecs <- ssl3_HandleRecord
2693 ** ssl3_ConsumeHandshakeVariable <-
2694 ** ssl3_HandleHelloRequest <-
2695 ** ssl3_HandleServerHello <-
2696 ** ssl3_HandleServerKeyExchange <-
2697 ** ssl3_HandleCertificateRequest <-
2698 ** ssl3_HandleServerHelloDone <-
2699 ** ssl3_HandleClientHello <-
2700 ** ssl3_HandleV2ClientHello <-
2701 ** ssl3_HandleCertificateVerify <-
2702 ** ssl3_HandleClientKeyExchange <-
2703 ** ssl3_HandleCertificate <-
2704 ** ssl3_HandleFinished <-
2705 ** ssl3_HandleHandshakeMessage <-
2706 ** ssl3_HandleRecord <-
2709 SECStatus
2710 SSL3_SendAlert(sslSocket *ss, SSL3AlertLevel level, SSL3AlertDescription desc)
2712 uint8 bytes[2];
2713 SECStatus rv;
2715 SSL_TRC(3, ("%d: SSL3[%d]: send alert record, level=%d desc=%d",
2716 SSL_GETPID(), ss->fd, level, desc));
2718 bytes[0] = level;
2719 bytes[1] = desc;
2721 ssl_GetSSL3HandshakeLock(ss);
2722 if (level == alert_fatal) {
2723 if (!ss->opt.noCache && ss->sec.ci.sid && ss->sec.uncache) {
2724 ss->sec.uncache(ss->sec.ci.sid);
2727 ssl_GetXmitBufLock(ss);
2728 rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
2729 if (rv == SECSuccess) {
2730 PRInt32 sent;
2731 sent = ssl3_SendRecord(ss, 0, content_alert, bytes, 2,
2732 desc == no_certificate
2733 ? ssl_SEND_FLAG_FORCE_INTO_BUFFER : 0);
2734 rv = (sent >= 0) ? SECSuccess : (SECStatus)sent;
2736 ssl_ReleaseXmitBufLock(ss);
2737 ssl_ReleaseSSL3HandshakeLock(ss);
2738 return rv; /* error set by ssl3_FlushHandshake or ssl3_SendRecord */
2742 * Send illegal_parameter alert. Set generic error number.
2744 static SECStatus
2745 ssl3_IllegalParameter(sslSocket *ss)
2747 PRBool isTLS;
2749 isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
2750 (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
2751 PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
2752 : SSL_ERROR_BAD_SERVER );
2753 return SECFailure;
2757 * Send handshake_Failure alert. Set generic error number.
2759 static SECStatus
2760 ssl3_HandshakeFailure(sslSocket *ss)
2762 (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure);
2763 PORT_SetError( ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
2764 : SSL_ERROR_BAD_SERVER );
2765 return SECFailure;
2768 static void
2769 ssl3_SendAlertForCertError(sslSocket * ss, PRErrorCode errCode)
2771 SSL3AlertDescription desc = bad_certificate;
2772 PRBool isTLS = ss->version >= SSL_LIBRARY_VERSION_3_1_TLS;
2774 switch (errCode) {
2775 case SEC_ERROR_LIBRARY_FAILURE: desc = unsupported_certificate; break;
2776 case SEC_ERROR_EXPIRED_CERTIFICATE: desc = certificate_expired; break;
2777 case SEC_ERROR_REVOKED_CERTIFICATE: desc = certificate_revoked; break;
2778 case SEC_ERROR_INADEQUATE_KEY_USAGE:
2779 case SEC_ERROR_INADEQUATE_CERT_TYPE:
2780 desc = certificate_unknown; break;
2781 case SEC_ERROR_UNTRUSTED_CERT:
2782 desc = isTLS ? access_denied : certificate_unknown; break;
2783 case SEC_ERROR_UNKNOWN_ISSUER:
2784 case SEC_ERROR_UNTRUSTED_ISSUER:
2785 desc = isTLS ? unknown_ca : certificate_unknown; break;
2786 case SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE:
2787 desc = isTLS ? unknown_ca : certificate_expired; break;
2789 case SEC_ERROR_CERT_NOT_IN_NAME_SPACE:
2790 case SEC_ERROR_PATH_LEN_CONSTRAINT_INVALID:
2791 case SEC_ERROR_CA_CERT_INVALID:
2792 case SEC_ERROR_BAD_SIGNATURE:
2793 default: desc = bad_certificate; break;
2795 SSL_DBG(("%d: SSL3[%d]: peer certificate is no good: error=%d",
2796 SSL_GETPID(), ss->fd, errCode));
2798 (void) SSL3_SendAlert(ss, alert_fatal, desc);
2803 * Send decode_error alert. Set generic error number.
2805 SECStatus
2806 ssl3_DecodeError(sslSocket *ss)
2808 (void)SSL3_SendAlert(ss, alert_fatal,
2809 ss->version > SSL_LIBRARY_VERSION_3_0 ? decode_error
2810 : illegal_parameter);
2811 PORT_SetError( ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
2812 : SSL_ERROR_BAD_SERVER );
2813 return SECFailure;
2816 /* Called from ssl3_HandleRecord.
2817 ** Caller must hold both RecvBuf and Handshake locks.
2819 static SECStatus
2820 ssl3_HandleAlert(sslSocket *ss, sslBuffer *buf)
2822 SSL3AlertLevel level;
2823 SSL3AlertDescription desc;
2824 int error;
2826 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
2827 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
2829 SSL_TRC(3, ("%d: SSL3[%d]: handle alert record", SSL_GETPID(), ss->fd));
2831 if (buf->len != 2) {
2832 (void)ssl3_DecodeError(ss);
2833 PORT_SetError(SSL_ERROR_RX_MALFORMED_ALERT);
2834 return SECFailure;
2836 level = (SSL3AlertLevel)buf->buf[0];
2837 desc = (SSL3AlertDescription)buf->buf[1];
2838 buf->len = 0;
2839 SSL_TRC(5, ("%d: SSL3[%d] received alert, level = %d, description = %d",
2840 SSL_GETPID(), ss->fd, level, desc));
2842 switch (desc) {
2843 case close_notify: ss->recvdCloseNotify = 1;
2844 error = SSL_ERROR_CLOSE_NOTIFY_ALERT; break;
2845 case unexpected_message: error = SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT;
2846 break;
2847 case bad_record_mac: error = SSL_ERROR_BAD_MAC_ALERT; break;
2848 case decryption_failed_RESERVED:
2849 error = SSL_ERROR_DECRYPTION_FAILED_ALERT;
2850 break;
2851 case record_overflow: error = SSL_ERROR_RECORD_OVERFLOW_ALERT; break;
2852 case decompression_failure: error = SSL_ERROR_DECOMPRESSION_FAILURE_ALERT;
2853 break;
2854 case handshake_failure: error = SSL_ERROR_HANDSHAKE_FAILURE_ALERT;
2855 break;
2856 case no_certificate: error = SSL_ERROR_NO_CERTIFICATE; break;
2857 case bad_certificate: error = SSL_ERROR_BAD_CERT_ALERT; break;
2858 case unsupported_certificate:error = SSL_ERROR_UNSUPPORTED_CERT_ALERT;break;
2859 case certificate_revoked: error = SSL_ERROR_REVOKED_CERT_ALERT; break;
2860 case certificate_expired: error = SSL_ERROR_EXPIRED_CERT_ALERT; break;
2861 case certificate_unknown: error = SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT;
2862 break;
2863 case illegal_parameter: error = SSL_ERROR_ILLEGAL_PARAMETER_ALERT;break;
2865 /* All alerts below are TLS only. */
2866 case unknown_ca: error = SSL_ERROR_UNKNOWN_CA_ALERT; break;
2867 case access_denied: error = SSL_ERROR_ACCESS_DENIED_ALERT; break;
2868 case decode_error: error = SSL_ERROR_DECODE_ERROR_ALERT; break;
2869 case decrypt_error: error = SSL_ERROR_DECRYPT_ERROR_ALERT; break;
2870 case export_restriction: error = SSL_ERROR_EXPORT_RESTRICTION_ALERT;
2871 break;
2872 case protocol_version: error = SSL_ERROR_PROTOCOL_VERSION_ALERT; break;
2873 case insufficient_security: error = SSL_ERROR_INSUFFICIENT_SECURITY_ALERT;
2874 break;
2875 case internal_error: error = SSL_ERROR_INTERNAL_ERROR_ALERT; break;
2876 case user_canceled: error = SSL_ERROR_USER_CANCELED_ALERT; break;
2877 case no_renegotiation: error = SSL_ERROR_NO_RENEGOTIATION_ALERT; break;
2879 /* Alerts for TLS client hello extensions */
2880 case unsupported_extension:
2881 error = SSL_ERROR_UNSUPPORTED_EXTENSION_ALERT; break;
2882 case certificate_unobtainable:
2883 error = SSL_ERROR_CERTIFICATE_UNOBTAINABLE_ALERT; break;
2884 case unrecognized_name:
2885 error = SSL_ERROR_UNRECOGNIZED_NAME_ALERT; break;
2886 case bad_certificate_status_response:
2887 error = SSL_ERROR_BAD_CERT_STATUS_RESPONSE_ALERT; break;
2888 case bad_certificate_hash_value:
2889 error = SSL_ERROR_BAD_CERT_HASH_VALUE_ALERT; break;
2890 default: error = SSL_ERROR_RX_UNKNOWN_ALERT; break;
2892 if (level == alert_fatal) {
2893 if (!ss->opt.noCache) {
2894 if (ss->sec.uncache)
2895 ss->sec.uncache(ss->sec.ci.sid);
2897 if ((ss->ssl3.hs.ws == wait_server_hello) &&
2898 (desc == handshake_failure)) {
2899 /* XXX This is a hack. We're assuming that any handshake failure
2900 * XXX on the client hello is a failure to match ciphers.
2902 error = SSL_ERROR_NO_CYPHER_OVERLAP;
2904 PORT_SetError(error);
2905 return SECFailure;
2907 if ((desc == no_certificate) && (ss->ssl3.hs.ws == wait_client_cert)) {
2908 /* I'm a server. I've requested a client cert. He hasn't got one. */
2909 SECStatus rv;
2911 PORT_Assert(ss->sec.isServer);
2912 ss->ssl3.hs.ws = wait_client_key;
2913 rv = ssl3_HandleNoCertificate(ss);
2914 return rv;
2916 return SECSuccess;
2920 * Change Cipher Specs
2921 * Called from ssl3_HandleServerHelloDone,
2922 * ssl3_HandleClientHello,
2923 * and ssl3_HandleFinished
2925 * Acquires and releases spec write lock, to protect switching the current
2926 * and pending write spec pointers.
2929 static SECStatus
2930 ssl3_SendChangeCipherSpecs(sslSocket *ss)
2932 uint8 change = change_cipher_spec_choice;
2933 ssl3CipherSpec * pwSpec;
2934 SECStatus rv;
2935 PRInt32 sent;
2937 SSL_TRC(3, ("%d: SSL3[%d]: send change_cipher_spec record",
2938 SSL_GETPID(), ss->fd));
2940 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
2941 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
2943 rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
2944 if (rv != SECSuccess) {
2945 return rv; /* error code set by ssl3_FlushHandshake */
2947 if (!IS_DTLS(ss)) {
2948 sent = ssl3_SendRecord(ss, 0, content_change_cipher_spec, &change, 1,
2949 ssl_SEND_FLAG_FORCE_INTO_BUFFER);
2950 if (sent < 0) {
2951 return (SECStatus)sent; /* error code set by ssl3_SendRecord */
2953 } else {
2954 rv = dtls_QueueMessage(ss, content_change_cipher_spec, &change, 1);
2955 if (rv != SECSuccess) {
2956 return rv;
2960 /* swap the pending and current write specs. */
2961 ssl_GetSpecWriteLock(ss); /**************************************/
2962 pwSpec = ss->ssl3.pwSpec;
2964 ss->ssl3.pwSpec = ss->ssl3.cwSpec;
2965 ss->ssl3.cwSpec = pwSpec;
2967 SSL_TRC(3, ("%d: SSL3[%d] Set Current Write Cipher Suite to Pending",
2968 SSL_GETPID(), ss->fd ));
2970 /* We need to free up the contexts, keys and certs ! */
2971 /* If we are really through with the old cipher spec
2972 * (Both the read and write sides have changed) destroy it.
2974 if (ss->ssl3.prSpec == ss->ssl3.pwSpec) {
2975 if (!IS_DTLS(ss)) {
2976 ssl3_DestroyCipherSpec(ss->ssl3.pwSpec, PR_FALSE/*freeSrvName*/);
2977 } else {
2978 /* With DTLS, we need to set a holddown timer in case the final
2979 * message got lost */
2980 ss->ssl3.hs.rtTimeoutMs = DTLS_FINISHED_TIMER_MS;
2981 dtls_StartTimer(ss, dtls_FinishedTimerCb);
2984 ssl_ReleaseSpecWriteLock(ss); /**************************************/
2986 return SECSuccess;
2989 /* Called from ssl3_HandleRecord.
2990 ** Caller must hold both RecvBuf and Handshake locks.
2992 * Acquires and releases spec write lock, to protect switching the current
2993 * and pending write spec pointers.
2995 static SECStatus
2996 ssl3_HandleChangeCipherSpecs(sslSocket *ss, sslBuffer *buf)
2998 ssl3CipherSpec * prSpec;
2999 SSL3WaitState ws = ss->ssl3.hs.ws;
3000 SSL3ChangeCipherSpecChoice change;
3002 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
3003 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
3005 SSL_TRC(3, ("%d: SSL3[%d]: handle change_cipher_spec record",
3006 SSL_GETPID(), ss->fd));
3008 if (ws != wait_change_cipher) {
3009 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
3010 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER);
3011 return SECFailure;
3014 if(buf->len != 1) {
3015 (void)ssl3_DecodeError(ss);
3016 PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER);
3017 return SECFailure;
3019 change = (SSL3ChangeCipherSpecChoice)buf->buf[0];
3020 if (change != change_cipher_spec_choice) {
3021 /* illegal_parameter is correct here for both SSL3 and TLS. */
3022 (void)ssl3_IllegalParameter(ss);
3023 PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER);
3024 return SECFailure;
3026 buf->len = 0;
3028 /* Swap the pending and current read specs. */
3029 ssl_GetSpecWriteLock(ss); /*************************************/
3030 prSpec = ss->ssl3.prSpec;
3032 ss->ssl3.prSpec = ss->ssl3.crSpec;
3033 ss->ssl3.crSpec = prSpec;
3034 ss->ssl3.hs.ws = wait_finished;
3036 SSL_TRC(3, ("%d: SSL3[%d] Set Current Read Cipher Suite to Pending",
3037 SSL_GETPID(), ss->fd ));
3039 /* If we are really through with the old cipher prSpec
3040 * (Both the read and write sides have changed) destroy it.
3042 if (ss->ssl3.prSpec == ss->ssl3.pwSpec) {
3043 ssl3_DestroyCipherSpec(ss->ssl3.prSpec, PR_FALSE/*freeSrvName*/);
3045 ssl_ReleaseSpecWriteLock(ss); /*************************************/
3046 return SECSuccess;
3049 /* This method uses PKCS11 to derive the MS from the PMS, where PMS
3050 ** is a PKCS11 symkey. This is used in all cases except the
3051 ** "triple bypass" with RSA key exchange.
3052 ** Called from ssl3_InitPendingCipherSpec. prSpec is pwSpec.
3054 static SECStatus
3055 ssl3_DeriveMasterSecret(sslSocket *ss, PK11SymKey *pms)
3057 ssl3CipherSpec * pwSpec = ss->ssl3.pwSpec;
3058 const ssl3KEADef *kea_def= ss->ssl3.hs.kea_def;
3059 unsigned char * cr = (unsigned char *)&ss->ssl3.hs.client_random;
3060 unsigned char * sr = (unsigned char *)&ss->ssl3.hs.server_random;
3061 PRBool isTLS = (PRBool)(kea_def->tls_keygen ||
3062 (pwSpec->version > SSL_LIBRARY_VERSION_3_0));
3064 * Whenever isDH is true, we need to use CKM_TLS_MASTER_KEY_DERIVE_DH
3065 * which, unlike CKM_TLS_MASTER_KEY_DERIVE, converts arbitrary size
3066 * data into a 48-byte value.
3068 PRBool isDH = (PRBool) ((ss->ssl3.hs.kea_def->exchKeyType == kt_dh) ||
3069 (ss->ssl3.hs.kea_def->exchKeyType == kt_ecdh));
3070 SECStatus rv = SECFailure;
3071 CK_MECHANISM_TYPE master_derive;
3072 CK_MECHANISM_TYPE key_derive;
3073 SECItem params;
3074 CK_FLAGS keyFlags;
3075 CK_VERSION pms_version;
3076 CK_SSL3_MASTER_KEY_DERIVE_PARAMS master_params;
3078 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3079 PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
3080 PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
3081 if (isTLS) {
3082 if(isDH) master_derive = CKM_TLS_MASTER_KEY_DERIVE_DH;
3083 else master_derive = CKM_TLS_MASTER_KEY_DERIVE;
3084 key_derive = CKM_TLS_KEY_AND_MAC_DERIVE;
3085 keyFlags = CKF_SIGN | CKF_VERIFY;
3086 } else {
3087 if (isDH) master_derive = CKM_SSL3_MASTER_KEY_DERIVE_DH;
3088 else master_derive = CKM_SSL3_MASTER_KEY_DERIVE;
3089 key_derive = CKM_SSL3_KEY_AND_MAC_DERIVE;
3090 keyFlags = 0;
3093 if (pms || !pwSpec->master_secret) {
3094 if (isDH) {
3095 master_params.pVersion = NULL;
3096 } else {
3097 master_params.pVersion = &pms_version;
3099 master_params.RandomInfo.pClientRandom = cr;
3100 master_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH;
3101 master_params.RandomInfo.pServerRandom = sr;
3102 master_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH;
3104 params.data = (unsigned char *) &master_params;
3105 params.len = sizeof master_params;
3108 if (pms != NULL) {
3109 #if defined(TRACE)
3110 if (ssl_trace >= 100) {
3111 SECStatus extractRV = PK11_ExtractKeyValue(pms);
3112 if (extractRV == SECSuccess) {
3113 SECItem * keyData = PK11_GetKeyData(pms);
3114 if (keyData && keyData->data && keyData->len) {
3115 ssl_PrintBuf(ss, "Pre-Master Secret",
3116 keyData->data, keyData->len);
3120 #endif
3121 pwSpec->master_secret = PK11_DeriveWithFlags(pms, master_derive,
3122 &params, key_derive, CKA_DERIVE, 0, keyFlags);
3123 if (!isDH && pwSpec->master_secret && ss->opt.detectRollBack) {
3124 SSL3ProtocolVersion client_version;
3125 client_version = pms_version.major << 8 | pms_version.minor;
3127 if (IS_DTLS(ss)) {
3128 client_version = dtls_DTLSVersionToTLSVersion(client_version);
3131 if (client_version != ss->clientHelloVersion) {
3132 /* Destroy it. Version roll-back detected. */
3133 PK11_FreeSymKey(pwSpec->master_secret);
3134 pwSpec->master_secret = NULL;
3137 if (pwSpec->master_secret == NULL) {
3138 /* Generate a faux master secret in the same slot as the old one. */
3139 PK11SlotInfo * slot = PK11_GetSlotFromKey((PK11SymKey *)pms);
3140 PK11SymKey * fpms = ssl3_GenerateRSAPMS(ss, pwSpec, slot);
3142 PK11_FreeSlot(slot);
3143 if (fpms != NULL) {
3144 pwSpec->master_secret = PK11_DeriveWithFlags(fpms,
3145 master_derive, &params, key_derive,
3146 CKA_DERIVE, 0, keyFlags);
3147 PK11_FreeSymKey(fpms);
3151 if (pwSpec->master_secret == NULL) {
3152 /* Generate a faux master secret from the internal slot. */
3153 PK11SlotInfo * slot = PK11_GetInternalSlot();
3154 PK11SymKey * fpms = ssl3_GenerateRSAPMS(ss, pwSpec, slot);
3156 PK11_FreeSlot(slot);
3157 if (fpms != NULL) {
3158 pwSpec->master_secret = PK11_DeriveWithFlags(fpms,
3159 master_derive, &params, key_derive,
3160 CKA_DERIVE, 0, keyFlags);
3161 if (pwSpec->master_secret == NULL) {
3162 pwSpec->master_secret = fpms; /* use the fpms as the master. */
3163 fpms = NULL;
3166 if (fpms) {
3167 PK11_FreeSymKey(fpms);
3170 if (pwSpec->master_secret == NULL) {
3171 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3172 return rv;
3174 #ifndef NO_PKCS11_BYPASS
3175 if (ss->opt.bypassPKCS11) {
3176 SECItem * keydata;
3177 /* In hope of doing a "double bypass",
3178 * need to extract the master secret's value from the key object
3179 * and store it raw in the sslSocket struct.
3181 rv = PK11_ExtractKeyValue(pwSpec->master_secret);
3182 if (rv != SECSuccess) {
3183 #if defined(NSS_SURVIVE_DOUBLE_BYPASS_FAILURE)
3184 /* The double bypass failed.
3185 * Attempt to revert to an all PKCS#11, non-bypass method.
3186 * Do we need any unacquired locks here?
3188 ss->opt.bypassPKCS11 = 0;
3189 rv = ssl3_NewHandshakeHashes(ss);
3190 if (rv == SECSuccess) {
3191 rv = ssl3_UpdateHandshakeHashes(ss, ss->ssl3.hs.messages.buf,
3192 ss->ssl3.hs.messages.len);
3194 #endif
3195 return rv;
3197 /* This returns the address of the secItem inside the key struct,
3198 * not a copy or a reference. So, there's no need to free it.
3200 keydata = PK11_GetKeyData(pwSpec->master_secret);
3201 if (keydata && keydata->len <= sizeof pwSpec->raw_master_secret) {
3202 memcpy(pwSpec->raw_master_secret, keydata->data, keydata->len);
3203 pwSpec->msItem.data = pwSpec->raw_master_secret;
3204 pwSpec->msItem.len = keydata->len;
3205 } else {
3206 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
3207 return SECFailure;
3210 #endif
3211 return SECSuccess;
3216 * Derive encryption and MAC Keys (and IVs) from master secret
3217 * Sets a useful error code when returning SECFailure.
3219 * Called only from ssl3_InitPendingCipherSpec(),
3220 * which in turn is called from
3221 * sendRSAClientKeyExchange (for Full handshake)
3222 * sendDHClientKeyExchange (for Full handshake)
3223 * ssl3_HandleClientKeyExchange (for Full handshake)
3224 * ssl3_HandleServerHello (for session restart)
3225 * ssl3_HandleClientHello (for session restart)
3226 * Caller MUST hold the specWriteLock, and SSL3HandshakeLock.
3227 * ssl3_InitPendingCipherSpec does that.
3230 static SECStatus
3231 ssl3_DeriveConnectionKeysPKCS11(sslSocket *ss)
3233 ssl3CipherSpec * pwSpec = ss->ssl3.pwSpec;
3234 const ssl3KEADef * kea_def = ss->ssl3.hs.kea_def;
3235 unsigned char * cr = (unsigned char *)&ss->ssl3.hs.client_random;
3236 unsigned char * sr = (unsigned char *)&ss->ssl3.hs.server_random;
3237 PRBool isTLS = (PRBool)(kea_def->tls_keygen ||
3238 (pwSpec->version > SSL_LIBRARY_VERSION_3_0));
3239 /* following variables used in PKCS11 path */
3240 const ssl3BulkCipherDef *cipher_def = pwSpec->cipher_def;
3241 PK11SlotInfo * slot = NULL;
3242 PK11SymKey * symKey = NULL;
3243 void * pwArg = ss->pkcs11PinArg;
3244 int keySize;
3245 CK_SSL3_KEY_MAT_PARAMS key_material_params;
3246 CK_SSL3_KEY_MAT_OUT returnedKeys;
3247 CK_MECHANISM_TYPE key_derive;
3248 CK_MECHANISM_TYPE bulk_mechanism;
3249 SSLCipherAlgorithm calg;
3250 SECItem params;
3251 PRBool skipKeysAndIVs = (PRBool)(cipher_def->calg == calg_null);
3253 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3254 PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
3255 PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
3257 if (!pwSpec->master_secret) {
3258 PORT_SetError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3259 return SECFailure;
3262 * generate the key material
3264 key_material_params.ulMacSizeInBits = pwSpec->mac_size * BPB;
3265 key_material_params.ulKeySizeInBits = cipher_def->secret_key_size* BPB;
3266 key_material_params.ulIVSizeInBits = cipher_def->iv_size * BPB;
3268 key_material_params.bIsExport = (CK_BBOOL)(kea_def->is_limited);
3269 /* was: (CK_BBOOL)(cipher_def->keygen_mode != kg_strong); */
3271 key_material_params.RandomInfo.pClientRandom = cr;
3272 key_material_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH;
3273 key_material_params.RandomInfo.pServerRandom = sr;
3274 key_material_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH;
3275 key_material_params.pReturnedKeyMaterial = &returnedKeys;
3277 returnedKeys.pIVClient = pwSpec->client.write_iv;
3278 returnedKeys.pIVServer = pwSpec->server.write_iv;
3279 keySize = cipher_def->key_size;
3281 if (skipKeysAndIVs) {
3282 keySize = 0;
3283 key_material_params.ulKeySizeInBits = 0;
3284 key_material_params.ulIVSizeInBits = 0;
3285 returnedKeys.pIVClient = NULL;
3286 returnedKeys.pIVServer = NULL;
3289 calg = cipher_def->calg;
3290 PORT_Assert( alg2Mech[calg].calg == calg);
3291 bulk_mechanism = alg2Mech[calg].cmech;
3293 params.data = (unsigned char *)&key_material_params;
3294 params.len = sizeof(key_material_params);
3296 if (isTLS) {
3297 key_derive = CKM_TLS_KEY_AND_MAC_DERIVE;
3298 } else {
3299 key_derive = CKM_SSL3_KEY_AND_MAC_DERIVE;
3302 /* CKM_SSL3_KEY_AND_MAC_DERIVE is defined to set ENCRYPT, DECRYPT, and
3303 * DERIVE by DEFAULT */
3304 symKey = PK11_Derive(pwSpec->master_secret, key_derive, &params,
3305 bulk_mechanism, CKA_ENCRYPT, keySize);
3306 if (!symKey) {
3307 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3308 return SECFailure;
3310 /* we really should use the actual mac'ing mechanism here, but we
3311 * don't because these types are used to map keytype anyway and both
3312 * mac's map to the same keytype.
3314 slot = PK11_GetSlotFromKey(symKey);
3316 PK11_FreeSlot(slot); /* slot is held until the key is freed */
3317 pwSpec->client.write_mac_key =
3318 PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive,
3319 CKM_SSL3_SHA1_MAC, returnedKeys.hClientMacSecret, PR_TRUE, pwArg);
3320 if (pwSpec->client.write_mac_key == NULL ) {
3321 goto loser; /* loser sets err */
3323 pwSpec->server.write_mac_key =
3324 PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive,
3325 CKM_SSL3_SHA1_MAC, returnedKeys.hServerMacSecret, PR_TRUE, pwArg);
3326 if (pwSpec->server.write_mac_key == NULL ) {
3327 goto loser; /* loser sets err */
3329 if (!skipKeysAndIVs) {
3330 pwSpec->client.write_key =
3331 PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive,
3332 bulk_mechanism, returnedKeys.hClientKey, PR_TRUE, pwArg);
3333 if (pwSpec->client.write_key == NULL ) {
3334 goto loser; /* loser sets err */
3336 pwSpec->server.write_key =
3337 PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive,
3338 bulk_mechanism, returnedKeys.hServerKey, PR_TRUE, pwArg);
3339 if (pwSpec->server.write_key == NULL ) {
3340 goto loser; /* loser sets err */
3343 PK11_FreeSymKey(symKey);
3344 return SECSuccess;
3347 loser:
3348 if (symKey) PK11_FreeSymKey(symKey);
3349 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3350 return SECFailure;
3353 static SECStatus
3354 ssl3_RestartHandshakeHashes(sslSocket *ss)
3356 SECStatus rv = SECSuccess;
3358 #ifndef NO_PKCS11_BYPASS
3359 if (ss->opt.bypassPKCS11) {
3360 ss->ssl3.hs.messages.len = 0;
3361 MD5_Begin((MD5Context *)ss->ssl3.hs.md5_cx);
3362 SHA1_Begin((SHA1Context *)ss->ssl3.hs.sha_cx);
3363 } else
3364 #endif
3366 rv = PK11_DigestBegin(ss->ssl3.hs.md5);
3367 if (rv != SECSuccess) {
3368 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
3369 return rv;
3371 rv = PK11_DigestBegin(ss->ssl3.hs.sha);
3372 if (rv != SECSuccess) {
3373 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3374 return rv;
3377 return rv;
3380 static SECStatus
3381 ssl3_NewHandshakeHashes(sslSocket *ss)
3383 PK11Context *md5 = NULL;
3384 PK11Context *sha = NULL;
3387 * note: We should probably lookup an SSL3 slot for these
3388 * handshake hashes in hopes that we wind up with the same slots
3389 * that the master secret will wind up in ...
3391 SSL_TRC(30,("%d: SSL3[%d]: start handshake hashes", SSL_GETPID(), ss->fd));
3392 #ifndef NO_PKCS11_BYPASS
3393 if (ss->opt.bypassPKCS11) {
3394 PORT_Assert(!ss->ssl3.hs.messages.buf && !ss->ssl3.hs.messages.space);
3395 ss->ssl3.hs.messages.buf = NULL;
3396 ss->ssl3.hs.messages.space = 0;
3397 } else
3398 #endif
3400 ss->ssl3.hs.md5 = md5 = PK11_CreateDigestContext(SEC_OID_MD5);
3401 ss->ssl3.hs.sha = sha = PK11_CreateDigestContext(SEC_OID_SHA1);
3402 if (md5 == NULL) {
3403 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
3404 goto loser;
3406 if (sha == NULL) {
3407 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3408 goto loser;
3411 if (SECSuccess == ssl3_RestartHandshakeHashes(ss)) {
3412 return SECSuccess;
3415 loser:
3416 if (md5 != NULL) {
3417 PK11_DestroyContext(md5, PR_TRUE);
3418 ss->ssl3.hs.md5 = NULL;
3420 if (sha != NULL) {
3421 PK11_DestroyContext(sha, PR_TRUE);
3422 ss->ssl3.hs.sha = NULL;
3424 return SECFailure;
3429 * Handshake messages
3431 /* Called from ssl3_AppendHandshake()
3432 ** ssl3_StartHandshakeHash()
3433 ** ssl3_HandleV2ClientHello()
3434 ** ssl3_HandleHandshakeMessage()
3435 ** Caller must hold the ssl3Handshake lock.
3437 static SECStatus
3438 ssl3_UpdateHandshakeHashes(sslSocket *ss, const unsigned char *b,
3439 unsigned int l)
3441 SECStatus rv = SECSuccess;
3443 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
3445 PRINT_BUF(90, (NULL, "MD5 & SHA handshake hash input:", b, l));
3447 #ifndef NO_PKCS11_BYPASS
3448 if (ss->opt.bypassPKCS11) {
3449 MD5_Update((MD5Context *)ss->ssl3.hs.md5_cx, b, l);
3450 SHA1_Update((SHA1Context *)ss->ssl3.hs.sha_cx, b, l);
3451 #if defined(NSS_SURVIVE_DOUBLE_BYPASS_FAILURE)
3452 rv = sslBuffer_Append(&ss->ssl3.hs.messages, b, l);
3453 #endif
3454 return rv;
3456 #endif
3457 rv = PK11_DigestOp(ss->ssl3.hs.md5, b, l);
3458 if (rv != SECSuccess) {
3459 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
3460 return rv;
3462 rv = PK11_DigestOp(ss->ssl3.hs.sha, b, l);
3463 if (rv != SECSuccess) {
3464 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3465 return rv;
3467 return rv;
3470 /**************************************************************************
3471 * Append Handshake functions.
3472 * All these functions set appropriate error codes.
3473 * Most rely on ssl3_AppendHandshake to set the error code.
3474 **************************************************************************/
3475 SECStatus
3476 ssl3_AppendHandshake(sslSocket *ss, const void *void_src, PRInt32 bytes)
3478 unsigned char * src = (unsigned char *)void_src;
3479 int room = ss->sec.ci.sendBuf.space - ss->sec.ci.sendBuf.len;
3480 SECStatus rv;
3482 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); /* protects sendBuf. */
3484 if (!bytes)
3485 return SECSuccess;
3486 if (ss->sec.ci.sendBuf.space < MAX_SEND_BUF_LENGTH && room < bytes) {
3487 rv = sslBuffer_Grow(&ss->sec.ci.sendBuf, PR_MAX(MIN_SEND_BUF_LENGTH,
3488 PR_MIN(MAX_SEND_BUF_LENGTH, ss->sec.ci.sendBuf.len + bytes)));
3489 if (rv != SECSuccess)
3490 return rv; /* sslBuffer_Grow has set a memory error code. */
3491 room = ss->sec.ci.sendBuf.space - ss->sec.ci.sendBuf.len;
3494 PRINT_BUF(60, (ss, "Append to Handshake", (unsigned char*)void_src, bytes));
3495 rv = ssl3_UpdateHandshakeHashes(ss, src, bytes);
3496 if (rv != SECSuccess)
3497 return rv; /* error code set by ssl3_UpdateHandshakeHashes */
3499 while (bytes > room) {
3500 if (room > 0)
3501 PORT_Memcpy(ss->sec.ci.sendBuf.buf + ss->sec.ci.sendBuf.len, src,
3502 room);
3503 ss->sec.ci.sendBuf.len += room;
3504 rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
3505 if (rv != SECSuccess) {
3506 return rv; /* error code set by ssl3_FlushHandshake */
3508 bytes -= room;
3509 src += room;
3510 room = ss->sec.ci.sendBuf.space;
3511 PORT_Assert(ss->sec.ci.sendBuf.len == 0);
3513 PORT_Memcpy(ss->sec.ci.sendBuf.buf + ss->sec.ci.sendBuf.len, src, bytes);
3514 ss->sec.ci.sendBuf.len += bytes;
3515 return SECSuccess;
3518 SECStatus
3519 ssl3_AppendHandshakeNumber(sslSocket *ss, PRInt32 num, PRInt32 lenSize)
3521 SECStatus rv;
3522 uint8 b[4];
3523 uint8 * p = b;
3525 switch (lenSize) {
3526 case 4:
3527 *p++ = (num >> 24) & 0xff;
3528 case 3:
3529 *p++ = (num >> 16) & 0xff;
3530 case 2:
3531 *p++ = (num >> 8) & 0xff;
3532 case 1:
3533 *p = num & 0xff;
3535 SSL_TRC(60, ("%d: number:", SSL_GETPID()));
3536 rv = ssl3_AppendHandshake(ss, &b[0], lenSize);
3537 return rv; /* error code set by AppendHandshake, if applicable. */
3540 SECStatus
3541 ssl3_AppendHandshakeVariable(
3542 sslSocket *ss, const SSL3Opaque *src, PRInt32 bytes, PRInt32 lenSize)
3544 SECStatus rv;
3546 PORT_Assert((bytes < (1<<8) && lenSize == 1) ||
3547 (bytes < (1L<<16) && lenSize == 2) ||
3548 (bytes < (1L<<24) && lenSize == 3));
3550 SSL_TRC(60,("%d: append variable:", SSL_GETPID()));
3551 rv = ssl3_AppendHandshakeNumber(ss, bytes, lenSize);
3552 if (rv != SECSuccess) {
3553 return rv; /* error code set by AppendHandshake, if applicable. */
3555 SSL_TRC(60, ("data:"));
3556 rv = ssl3_AppendHandshake(ss, src, bytes);
3557 return rv; /* error code set by AppendHandshake, if applicable. */
3560 SECStatus
3561 ssl3_AppendHandshakeHeader(sslSocket *ss, SSL3HandshakeType t, PRUint32 length)
3563 SECStatus rv;
3565 /* If we already have a message in place, we need to enqueue it.
3566 * This empties the buffer. This is a convenient place to call
3567 * dtls_StageHandshakeMessage to mark the message boundary.
3569 if (IS_DTLS(ss)) {
3570 rv = dtls_StageHandshakeMessage(ss);
3571 if (rv != SECSuccess) {
3572 return rv;
3576 SSL_TRC(30,("%d: SSL3[%d]: append handshake header: type %s",
3577 SSL_GETPID(), ss->fd, ssl3_DecodeHandshakeType(t)));
3578 PRINT_BUF(60, (ss, "MD5 handshake hash:",
3579 (unsigned char*)ss->ssl3.hs.md5_cx, MD5_LENGTH));
3580 PRINT_BUF(95, (ss, "SHA handshake hash:",
3581 (unsigned char*)ss->ssl3.hs.sha_cx, SHA1_LENGTH));
3583 rv = ssl3_AppendHandshakeNumber(ss, t, 1);
3584 if (rv != SECSuccess) {
3585 return rv; /* error code set by AppendHandshake, if applicable. */
3587 rv = ssl3_AppendHandshakeNumber(ss, length, 3);
3588 if (rv != SECSuccess) {
3589 return rv; /* error code set by AppendHandshake, if applicable. */
3592 if (IS_DTLS(ss)) {
3593 /* Note that we make an unfragmented message here. We fragment in the
3594 * transmission code, if necessary */
3595 rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.sendMessageSeq, 2);
3596 if (rv != SECSuccess) {
3597 return rv; /* error code set by AppendHandshake, if applicable. */
3599 ss->ssl3.hs.sendMessageSeq++;
3601 /* 0 is the fragment offset, because it's not fragmented yet */
3602 rv = ssl3_AppendHandshakeNumber(ss, 0, 3);
3603 if (rv != SECSuccess) {
3604 return rv; /* error code set by AppendHandshake, if applicable. */
3607 /* Fragment length -- set to the packet length because not fragmented */
3608 rv = ssl3_AppendHandshakeNumber(ss, length, 3);
3609 if (rv != SECSuccess) {
3610 return rv; /* error code set by AppendHandshake, if applicable. */
3614 return rv; /* error code set by AppendHandshake, if applicable. */
3617 /**************************************************************************
3618 * Consume Handshake functions.
3620 * All data used in these functions is protected by two locks,
3621 * the RecvBufLock and the SSL3HandshakeLock
3622 **************************************************************************/
3624 /* Read up the next "bytes" number of bytes from the (decrypted) input
3625 * stream "b" (which is *length bytes long). Copy them into buffer "v".
3626 * Reduces *length by bytes. Advances *b by bytes.
3628 * If this function returns SECFailure, it has already sent an alert,
3629 * and has set a generic error code. The caller should probably
3630 * override the generic error code by setting another.
3632 SECStatus
3633 ssl3_ConsumeHandshake(sslSocket *ss, void *v, PRInt32 bytes, SSL3Opaque **b,
3634 PRUint32 *length)
3636 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
3637 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
3639 if ((PRUint32)bytes > *length) {
3640 return ssl3_DecodeError(ss);
3642 PORT_Memcpy(v, *b, bytes);
3643 PRINT_BUF(60, (ss, "consume bytes:", *b, bytes));
3644 *b += bytes;
3645 *length -= bytes;
3646 return SECSuccess;
3649 /* Read up the next "bytes" number of bytes from the (decrypted) input
3650 * stream "b" (which is *length bytes long), and interpret them as an
3651 * integer in network byte order. Returns the received value.
3652 * Reduces *length by bytes. Advances *b by bytes.
3654 * Returns SECFailure (-1) on failure.
3655 * This value is indistinguishable from the equivalent received value.
3656 * Only positive numbers are to be received this way.
3657 * Thus, the largest value that may be sent this way is 0x7fffffff.
3658 * On error, an alert has been sent, and a generic error code has been set.
3660 PRInt32
3661 ssl3_ConsumeHandshakeNumber(sslSocket *ss, PRInt32 bytes, SSL3Opaque **b,
3662 PRUint32 *length)
3664 uint8 *buf = *b;
3665 int i;
3666 PRInt32 num = 0;
3668 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
3669 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
3670 PORT_Assert( bytes <= sizeof num);
3672 if ((PRUint32)bytes > *length) {
3673 return ssl3_DecodeError(ss);
3675 PRINT_BUF(60, (ss, "consume bytes:", *b, bytes));
3677 for (i = 0; i < bytes; i++)
3678 num = (num << 8) + buf[i];
3679 *b += bytes;
3680 *length -= bytes;
3681 return num;
3684 /* Read in two values from the incoming decrypted byte stream "b", which is
3685 * *length bytes long. The first value is a number whose size is "bytes"
3686 * bytes long. The second value is a byte-string whose size is the value
3687 * of the first number received. The latter byte-string, and its length,
3688 * is returned in the SECItem i.
3690 * Returns SECFailure (-1) on failure.
3691 * On error, an alert has been sent, and a generic error code has been set.
3693 * RADICAL CHANGE for NSS 3.11. All callers of this function make copies
3694 * of the data returned in the SECItem *i, so making a copy of it here
3695 * is simply wasteful. So, This function now just sets SECItem *i to
3696 * point to the values in the buffer **b.
3698 SECStatus
3699 ssl3_ConsumeHandshakeVariable(sslSocket *ss, SECItem *i, PRInt32 bytes,
3700 SSL3Opaque **b, PRUint32 *length)
3702 PRInt32 count;
3704 PORT_Assert(bytes <= 3);
3705 i->len = 0;
3706 i->data = NULL;
3707 count = ssl3_ConsumeHandshakeNumber(ss, bytes, b, length);
3708 if (count < 0) { /* Can't test for SECSuccess here. */
3709 return SECFailure;
3711 if (count > 0) {
3712 if ((PRUint32)count > *length) {
3713 return ssl3_DecodeError(ss);
3715 i->data = *b;
3716 i->len = count;
3717 *b += count;
3718 *length -= count;
3720 return SECSuccess;
3723 /**************************************************************************
3724 * end of Consume Handshake functions.
3725 **************************************************************************/
3727 /* Extract the hashes of handshake messages to this point.
3728 * Called from ssl3_SendCertificateVerify
3729 * ssl3_SendFinished
3730 * ssl3_HandleHandshakeMessage
3732 * Caller must hold the SSL3HandshakeLock.
3733 * Caller must hold a read or write lock on the Spec R/W lock.
3734 * (There is presently no way to assert on a Read lock.)
3736 static SECStatus
3737 ssl3_ComputeHandshakeHashes(sslSocket * ss,
3738 ssl3CipherSpec *spec, /* uses ->master_secret */
3739 SSL3Hashes * hashes, /* output goes here. */
3740 PRUint32 sender)
3742 SECStatus rv = SECSuccess;
3743 PRBool isTLS = (PRBool)(spec->version > SSL_LIBRARY_VERSION_3_0);
3744 unsigned int outLength;
3745 SSL3Opaque md5_inner[MAX_MAC_LENGTH];
3746 SSL3Opaque sha_inner[MAX_MAC_LENGTH];
3748 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
3750 #ifndef NO_PKCS11_BYPASS
3751 if (ss->opt.bypassPKCS11) {
3752 /* compute them without PKCS11 */
3753 PRUint64 md5_cx[MAX_MAC_CONTEXT_LLONGS];
3754 PRUint64 sha_cx[MAX_MAC_CONTEXT_LLONGS];
3756 #define md5cx ((MD5Context *)md5_cx)
3757 #define shacx ((SHA1Context *)sha_cx)
3759 if (!spec->msItem.data) {
3760 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
3761 return SECFailure;
3764 MD5_Clone (md5cx, (MD5Context *)ss->ssl3.hs.md5_cx);
3765 SHA1_Clone(shacx, (SHA1Context *)ss->ssl3.hs.sha_cx);
3767 if (!isTLS) {
3768 /* compute hashes for SSL3. */
3769 unsigned char s[4];
3771 s[0] = (unsigned char)(sender >> 24);
3772 s[1] = (unsigned char)(sender >> 16);
3773 s[2] = (unsigned char)(sender >> 8);
3774 s[3] = (unsigned char)sender;
3776 if (sender != 0) {
3777 MD5_Update(md5cx, s, 4);
3778 PRINT_BUF(95, (NULL, "MD5 inner: sender", s, 4));
3781 PRINT_BUF(95, (NULL, "MD5 inner: MAC Pad 1", mac_pad_1,
3782 mac_defs[mac_md5].pad_size));
3784 MD5_Update(md5cx, spec->msItem.data, spec->msItem.len);
3785 MD5_Update(md5cx, mac_pad_1, mac_defs[mac_md5].pad_size);
3786 MD5_End(md5cx, md5_inner, &outLength, MD5_LENGTH);
3788 PRINT_BUF(95, (NULL, "MD5 inner: result", md5_inner, outLength));
3790 if (sender != 0) {
3791 SHA1_Update(shacx, s, 4);
3792 PRINT_BUF(95, (NULL, "SHA inner: sender", s, 4));
3795 PRINT_BUF(95, (NULL, "SHA inner: MAC Pad 1", mac_pad_1,
3796 mac_defs[mac_sha].pad_size));
3798 SHA1_Update(shacx, spec->msItem.data, spec->msItem.len);
3799 SHA1_Update(shacx, mac_pad_1, mac_defs[mac_sha].pad_size);
3800 SHA1_End(shacx, sha_inner, &outLength, SHA1_LENGTH);
3802 PRINT_BUF(95, (NULL, "SHA inner: result", sha_inner, outLength));
3803 PRINT_BUF(95, (NULL, "MD5 outer: MAC Pad 2", mac_pad_2,
3804 mac_defs[mac_md5].pad_size));
3805 PRINT_BUF(95, (NULL, "MD5 outer: MD5 inner", md5_inner, MD5_LENGTH));
3807 MD5_Begin(md5cx);
3808 MD5_Update(md5cx, spec->msItem.data, spec->msItem.len);
3809 MD5_Update(md5cx, mac_pad_2, mac_defs[mac_md5].pad_size);
3810 MD5_Update(md5cx, md5_inner, MD5_LENGTH);
3812 MD5_End(md5cx, hashes->md5, &outLength, MD5_LENGTH);
3814 PRINT_BUF(60, (NULL, "MD5 outer: result", hashes->md5, MD5_LENGTH));
3816 if (!isTLS) {
3817 PRINT_BUF(95, (NULL, "SHA outer: MAC Pad 2", mac_pad_2,
3818 mac_defs[mac_sha].pad_size));
3819 PRINT_BUF(95, (NULL, "SHA outer: SHA inner", sha_inner, SHA1_LENGTH));
3821 SHA1_Begin(shacx);
3822 SHA1_Update(shacx, spec->msItem.data, spec->msItem.len);
3823 SHA1_Update(shacx, mac_pad_2, mac_defs[mac_sha].pad_size);
3824 SHA1_Update(shacx, sha_inner, SHA1_LENGTH);
3826 SHA1_End(shacx, hashes->sha, &outLength, SHA1_LENGTH);
3828 PRINT_BUF(60, (NULL, "SHA outer: result", hashes->sha, SHA1_LENGTH));
3830 rv = SECSuccess;
3831 #undef md5cx
3832 #undef shacx
3833 } else
3834 #endif
3836 /* compute hases with PKCS11 */
3837 PK11Context * md5;
3838 PK11Context * sha = NULL;
3839 unsigned char *md5StateBuf = NULL;
3840 unsigned char *shaStateBuf = NULL;
3841 unsigned int md5StateLen, shaStateLen;
3842 unsigned char md5StackBuf[256];
3843 unsigned char shaStackBuf[512];
3845 if (!spec->master_secret) {
3846 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
3847 return SECFailure;
3850 md5StateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.md5, md5StackBuf,
3851 sizeof md5StackBuf, &md5StateLen);
3852 if (md5StateBuf == NULL) {
3853 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
3854 goto loser;
3856 md5 = ss->ssl3.hs.md5;
3858 shaStateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.sha, shaStackBuf,
3859 sizeof shaStackBuf, &shaStateLen);
3860 if (shaStateBuf == NULL) {
3861 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3862 goto loser;
3864 sha = ss->ssl3.hs.sha;
3866 if (!isTLS) {
3867 /* compute hashes for SSL3. */
3868 unsigned char s[4];
3870 s[0] = (unsigned char)(sender >> 24);
3871 s[1] = (unsigned char)(sender >> 16);
3872 s[2] = (unsigned char)(sender >> 8);
3873 s[3] = (unsigned char)sender;
3875 if (sender != 0) {
3876 rv |= PK11_DigestOp(md5, s, 4);
3877 PRINT_BUF(95, (NULL, "MD5 inner: sender", s, 4));
3880 PRINT_BUF(95, (NULL, "MD5 inner: MAC Pad 1", mac_pad_1,
3881 mac_defs[mac_md5].pad_size));
3883 rv |= PK11_DigestKey(md5,spec->master_secret);
3884 rv |= PK11_DigestOp(md5, mac_pad_1, mac_defs[mac_md5].pad_size);
3885 rv |= PK11_DigestFinal(md5, md5_inner, &outLength, MD5_LENGTH);
3886 PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH);
3887 if (rv != SECSuccess) {
3888 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
3889 rv = SECFailure;
3890 goto loser;
3893 PRINT_BUF(95, (NULL, "MD5 inner: result", md5_inner, outLength));
3895 if (sender != 0) {
3896 rv |= PK11_DigestOp(sha, s, 4);
3897 PRINT_BUF(95, (NULL, "SHA inner: sender", s, 4));
3900 PRINT_BUF(95, (NULL, "SHA inner: MAC Pad 1", mac_pad_1,
3901 mac_defs[mac_sha].pad_size));
3903 rv |= PK11_DigestKey(sha, spec->master_secret);
3904 rv |= PK11_DigestOp(sha, mac_pad_1, mac_defs[mac_sha].pad_size);
3905 rv |= PK11_DigestFinal(sha, sha_inner, &outLength, SHA1_LENGTH);
3906 PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH);
3907 if (rv != SECSuccess) {
3908 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3909 rv = SECFailure;
3910 goto loser;
3913 PRINT_BUF(95, (NULL, "SHA inner: result", sha_inner, outLength));
3915 PRINT_BUF(95, (NULL, "MD5 outer: MAC Pad 2", mac_pad_2,
3916 mac_defs[mac_md5].pad_size));
3917 PRINT_BUF(95, (NULL, "MD5 outer: MD5 inner", md5_inner, MD5_LENGTH));
3919 rv |= PK11_DigestBegin(md5);
3920 rv |= PK11_DigestKey(md5, spec->master_secret);
3921 rv |= PK11_DigestOp(md5, mac_pad_2, mac_defs[mac_md5].pad_size);
3922 rv |= PK11_DigestOp(md5, md5_inner, MD5_LENGTH);
3924 rv |= PK11_DigestFinal(md5, hashes->md5, &outLength, MD5_LENGTH);
3925 PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH);
3926 if (rv != SECSuccess) {
3927 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
3928 rv = SECFailure;
3929 goto loser;
3932 PRINT_BUF(60, (NULL, "MD5 outer: result", hashes->md5, MD5_LENGTH));
3934 if (!isTLS) {
3935 PRINT_BUF(95, (NULL, "SHA outer: MAC Pad 2", mac_pad_2,
3936 mac_defs[mac_sha].pad_size));
3937 PRINT_BUF(95, (NULL, "SHA outer: SHA inner", sha_inner, SHA1_LENGTH));
3939 rv |= PK11_DigestBegin(sha);
3940 rv |= PK11_DigestKey(sha,spec->master_secret);
3941 rv |= PK11_DigestOp(sha, mac_pad_2, mac_defs[mac_sha].pad_size);
3942 rv |= PK11_DigestOp(sha, sha_inner, SHA1_LENGTH);
3944 rv |= PK11_DigestFinal(sha, hashes->sha, &outLength, SHA1_LENGTH);
3945 PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH);
3946 if (rv != SECSuccess) {
3947 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3948 rv = SECFailure;
3949 goto loser;
3952 PRINT_BUF(60, (NULL, "SHA outer: result", hashes->sha, SHA1_LENGTH));
3954 rv = SECSuccess;
3956 loser:
3957 if (md5StateBuf) {
3958 if (PK11_RestoreContext(ss->ssl3.hs.md5, md5StateBuf, md5StateLen)
3959 != SECSuccess)
3961 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
3962 rv = SECFailure;
3964 if (md5StateBuf != md5StackBuf) {
3965 PORT_ZFree(md5StateBuf, md5StateLen);
3968 if (shaStateBuf) {
3969 if (PK11_RestoreContext(ss->ssl3.hs.sha, shaStateBuf, shaStateLen)
3970 != SECSuccess)
3972 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3973 rv = SECFailure;
3975 if (shaStateBuf != shaStackBuf) {
3976 PORT_ZFree(shaStateBuf, shaStateLen);
3980 return rv;
3984 * SSL 2 based implementations pass in the initial outbound buffer
3985 * so that the handshake hash can contain the included information.
3987 * Called from ssl2_BeginClientHandshake() in sslcon.c
3989 SECStatus
3990 ssl3_StartHandshakeHash(sslSocket *ss, unsigned char * buf, int length)
3992 SECStatus rv;
3994 ssl_GetSSL3HandshakeLock(ss); /**************************************/
3996 rv = ssl3_InitState(ss);
3997 if (rv != SECSuccess) {
3998 goto done; /* ssl3_InitState has set the error code. */
4001 PORT_Memset(&ss->ssl3.hs.client_random, 0, SSL3_RANDOM_LENGTH);
4002 PORT_Memcpy(
4003 &ss->ssl3.hs.client_random.rand[SSL3_RANDOM_LENGTH - SSL_CHALLENGE_BYTES],
4004 &ss->sec.ci.clientChallenge,
4005 SSL_CHALLENGE_BYTES);
4007 rv = ssl3_UpdateHandshakeHashes(ss, buf, length);
4008 /* if it failed, ssl3_UpdateHandshakeHashes has set the error code. */
4010 done:
4011 ssl_ReleaseSSL3HandshakeLock(ss); /**************************************/
4012 return rv;
4015 /**************************************************************************
4016 * end of Handshake Hash functions.
4017 * Begin Send and Handle functions for handshakes.
4018 **************************************************************************/
4020 /* Called from ssl3_HandleHelloRequest(),
4021 * ssl3_RedoHandshake()
4022 * ssl2_BeginClientHandshake (when resuming ssl3 session)
4023 * dtls_HandleHelloVerifyRequest(with resending=PR_TRUE)
4025 SECStatus
4026 ssl3_SendClientHello(sslSocket *ss, PRBool resending)
4028 sslSessionID * sid;
4029 ssl3CipherSpec * cwSpec;
4030 SECStatus rv;
4031 int i;
4032 int length;
4033 int num_suites;
4034 int actual_count = 0;
4035 PRBool isTLS = PR_FALSE;
4036 PRBool requestingResume = PR_FALSE;
4037 PRInt32 total_exten_len = 0;
4038 unsigned numCompressionMethods;
4039 PRInt32 flags;
4041 SSL_TRC(3, ("%d: SSL3[%d]: send client_hello handshake", SSL_GETPID(),
4042 ss->fd));
4044 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
4045 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
4047 rv = ssl3_InitState(ss);
4048 if (rv != SECSuccess) {
4049 return rv; /* ssl3_InitState has set the error code. */
4051 ss->ssl3.hs.sendingSCSV = PR_FALSE; /* Must be reset every handshake */
4052 PORT_Assert(IS_DTLS(ss) || !resending);
4054 /* We might be starting a session renegotiation in which case we should
4055 * clear previous state.
4057 PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData));
4059 SSL_TRC(30,("%d: SSL3[%d]: reset handshake hashes",
4060 SSL_GETPID(), ss->fd ));
4061 rv = ssl3_RestartHandshakeHashes(ss);
4062 if (rv != SECSuccess) {
4063 return rv;
4067 * During a renegotiation, ss->clientHelloVersion will be used again to
4068 * work around a Windows SChannel bug. Ensure that it is still enabled.
4070 if (ss->firstHsDone) {
4071 if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
4072 PORT_SetError(SSL_ERROR_SSL_DISABLED);
4073 return SECFailure;
4076 if (ss->clientHelloVersion < ss->vrange.min ||
4077 ss->clientHelloVersion > ss->vrange.max) {
4078 PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
4079 return SECFailure;
4083 /* We ignore ss->sec.ci.sid here, and use ssl_Lookup because Lookup
4084 * handles expired entries and other details.
4085 * XXX If we've been called from ssl2_BeginClientHandshake, then
4086 * this lookup is duplicative and wasteful.
4088 sid = (ss->opt.noCache) ? NULL
4089 : ssl_LookupSID(&ss->sec.ci.peer, ss->sec.ci.port, ss->peerID, ss->url);
4091 /* We can't resume based on a different token. If the sid exists,
4092 * make sure the token that holds the master secret still exists ...
4093 * If we previously did client-auth, make sure that the token that holds
4094 * the private key still exists, is logged in, hasn't been removed, etc.
4096 if (sid) {
4097 PRBool sidOK = PR_TRUE;
4098 if (sid->u.ssl3.keys.msIsWrapped) {
4099 /* Session key was wrapped, which means it was using PKCS11, */
4100 PK11SlotInfo *slot = NULL;
4101 if (sid->u.ssl3.masterValid && !ss->opt.bypassPKCS11) {
4102 slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID,
4103 sid->u.ssl3.masterSlotID);
4105 if (slot == NULL) {
4106 sidOK = PR_FALSE;
4107 } else {
4108 PK11SymKey *wrapKey = NULL;
4109 if (!PK11_IsPresent(slot) ||
4110 ((wrapKey = PK11_GetWrapKey(slot,
4111 sid->u.ssl3.masterWrapIndex,
4112 sid->u.ssl3.masterWrapMech,
4113 sid->u.ssl3.masterWrapSeries,
4114 ss->pkcs11PinArg)) == NULL) ) {
4115 sidOK = PR_FALSE;
4117 if (wrapKey) PK11_FreeSymKey(wrapKey);
4118 PK11_FreeSlot(slot);
4119 slot = NULL;
4122 /* If we previously did client-auth, make sure that the token that
4123 ** holds the private key still exists, is logged in, hasn't been
4124 ** removed, etc.
4126 if (sidOK && !ssl3_ClientAuthTokenPresent(sid)) {
4127 sidOK = PR_FALSE;
4130 /* TLS 1.0 (RFC 2246) Appendix E says:
4131 * Whenever a client already knows the highest protocol known to
4132 * a server (for example, when resuming a session), it should
4133 * initiate the connection in that native protocol.
4134 * So we pass sid->version to ssl3_NegotiateVersion() here, except
4135 * when renegotiating.
4137 * Windows SChannel compares the client_version inside the RSA
4138 * EncryptedPreMasterSecret of a renegotiation with the
4139 * client_version of the initial ClientHello rather than the
4140 * ClientHello in the renegotiation. To work around this bug, we
4141 * continue to use the client_version used in the initial
4142 * ClientHello when renegotiating.
4144 if (sidOK) {
4145 if (ss->firstHsDone) {
4147 * The client_version of the initial ClientHello is still
4148 * available in ss->clientHelloVersion. Ensure that
4149 * sid->version is bounded within
4150 * [ss->vrange.min, ss->clientHelloVersion], otherwise we
4151 * can't use sid.
4153 if (sid->version >= ss->vrange.min &&
4154 sid->version <= ss->clientHelloVersion) {
4155 ss->version = ss->clientHelloVersion;
4156 } else {
4157 sidOK = PR_FALSE;
4159 } else {
4160 if (ssl3_NegotiateVersion(ss, sid->version,
4161 PR_FALSE) != SECSuccess) {
4162 sidOK = PR_FALSE;
4167 if (!sidOK) {
4168 SSL_AtomicIncrementLong(& ssl3stats.sch_sid_cache_not_ok );
4169 if (ss->sec.uncache)
4170 (*ss->sec.uncache)(sid);
4171 ssl_FreeSID(sid);
4172 sid = NULL;
4176 if (sid) {
4177 requestingResume = PR_TRUE;
4178 SSL_AtomicIncrementLong(& ssl3stats.sch_sid_cache_hits );
4180 /* Are we attempting a stateless session resume? */
4181 if (sid->version > SSL_LIBRARY_VERSION_3_0 &&
4182 sid->u.ssl3.sessionTicket.ticket.data)
4183 SSL_AtomicIncrementLong(& ssl3stats.sch_sid_stateless_resumes );
4185 PRINT_BUF(4, (ss, "client, found session-id:", sid->u.ssl3.sessionID,
4186 sid->u.ssl3.sessionIDLength));
4188 ss->ssl3.policy = sid->u.ssl3.policy;
4189 } else {
4190 SSL_AtomicIncrementLong(& ssl3stats.sch_sid_cache_misses );
4193 * Windows SChannel compares the client_version inside the RSA
4194 * EncryptedPreMasterSecret of a renegotiation with the
4195 * client_version of the initial ClientHello rather than the
4196 * ClientHello in the renegotiation. To work around this bug, we
4197 * continue to use the client_version used in the initial
4198 * ClientHello when renegotiating.
4200 if (ss->firstHsDone) {
4201 ss->version = ss->clientHelloVersion;
4202 } else {
4203 rv = ssl3_NegotiateVersion(ss, SSL_LIBRARY_VERSION_MAX_SUPPORTED,
4204 PR_TRUE);
4205 if (rv != SECSuccess)
4206 return rv; /* error code was set */
4209 sid = ssl3_NewSessionID(ss, PR_FALSE);
4210 if (!sid) {
4211 return SECFailure; /* memory error is set */
4215 isTLS = (ss->version > SSL_LIBRARY_VERSION_3_0);
4216 ssl_GetSpecWriteLock(ss);
4217 cwSpec = ss->ssl3.cwSpec;
4218 if (cwSpec->mac_def->mac == mac_null) {
4219 /* SSL records are not being MACed. */
4220 cwSpec->version = ss->version;
4222 ssl_ReleaseSpecWriteLock(ss);
4224 if (ss->sec.ci.sid != NULL) {
4225 ssl_FreeSID(ss->sec.ci.sid); /* decrement ref count, free if zero */
4227 ss->sec.ci.sid = sid;
4229 ss->sec.send = ssl3_SendApplicationData;
4231 /* shouldn't get here if SSL3 is disabled, but ... */
4232 if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
4233 PR_NOT_REACHED("No versions of SSL 3.0 or later are enabled");
4234 PORT_SetError(SSL_ERROR_SSL_DISABLED);
4235 return SECFailure;
4238 /* how many suites does our PKCS11 support (regardless of policy)? */
4239 num_suites = ssl3_config_match_init(ss);
4240 if (!num_suites)
4241 return SECFailure; /* ssl3_config_match_init has set error code. */
4243 /* HACK for SCSV in SSL 3.0. On initial handshake, prepend SCSV,
4244 * only if TLS is disabled.
4246 if (!ss->firstHsDone && !isTLS) {
4247 /* Must set this before calling Hello Extension Senders,
4248 * to suppress sending of empty RI extension.
4250 ss->ssl3.hs.sendingSCSV = PR_TRUE;
4253 if (isTLS || (ss->firstHsDone && ss->peerRequestedProtection)) {
4254 PRUint32 maxBytes = 65535; /* 2^16 - 1 */
4255 PRInt32 extLen;
4257 extLen = ssl3_CallHelloExtensionSenders(ss, PR_FALSE, maxBytes, NULL);
4258 if (extLen < 0) {
4259 return SECFailure;
4261 maxBytes -= extLen;
4262 total_exten_len += extLen;
4264 if (total_exten_len > 0)
4265 total_exten_len += 2;
4268 #if defined(NSS_ENABLE_ECC) && !defined(NSS_ECC_MORE_THAN_SUITE_B)
4269 if (!total_exten_len || !isTLS) {
4270 /* not sending the elliptic_curves and ec_point_formats extensions */
4271 ssl3_DisableECCSuites(ss, NULL); /* disable all ECC suites */
4273 #endif
4275 if (IS_DTLS(ss)) {
4276 ssl3_DisableNonDTLSSuites(ss);
4279 /* how many suites are permitted by policy and user preference? */
4280 num_suites = count_cipher_suites(ss, ss->ssl3.policy, PR_TRUE);
4281 if (!num_suites)
4282 return SECFailure; /* count_cipher_suites has set error code. */
4283 if (ss->ssl3.hs.sendingSCSV) {
4284 ++num_suites; /* make room for SCSV */
4287 /* count compression methods */
4288 numCompressionMethods = 0;
4289 for (i = 0; i < compressionMethodsCount; i++) {
4290 if (compressionEnabled(ss, compressions[i]))
4291 numCompressionMethods++;
4294 length = sizeof(SSL3ProtocolVersion) + SSL3_RANDOM_LENGTH +
4295 1 + ((sid == NULL) ? 0 : sid->u.ssl3.sessionIDLength) +
4296 2 + num_suites*sizeof(ssl3CipherSuite) +
4297 1 + numCompressionMethods + total_exten_len;
4298 if (IS_DTLS(ss)) {
4299 length += 1 + ss->ssl3.hs.cookieLen;
4302 rv = ssl3_AppendHandshakeHeader(ss, client_hello, length);
4303 if (rv != SECSuccess) {
4304 return rv; /* err set by ssl3_AppendHandshake* */
4307 if (ss->firstHsDone) {
4308 /* The client hello version must stay unchanged to work around
4309 * the Windows SChannel bug described above. */
4310 PORT_Assert(ss->version == ss->clientHelloVersion);
4312 ss->clientHelloVersion = ss->version;
4313 if (IS_DTLS(ss)) {
4314 PRUint16 version;
4316 version = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion);
4317 rv = ssl3_AppendHandshakeNumber(ss, version, 2);
4318 } else {
4319 rv = ssl3_AppendHandshakeNumber(ss, ss->clientHelloVersion, 2);
4321 if (rv != SECSuccess) {
4322 return rv; /* err set by ssl3_AppendHandshake* */
4325 if (!resending) { /* Don't re-generate if we are in DTLS re-sending mode */
4326 rv = ssl3_GetNewRandom(&ss->ssl3.hs.client_random);
4327 if (rv != SECSuccess) {
4328 return rv; /* err set by GetNewRandom. */
4331 rv = ssl3_AppendHandshake(ss, &ss->ssl3.hs.client_random,
4332 SSL3_RANDOM_LENGTH);
4333 if (rv != SECSuccess) {
4334 return rv; /* err set by ssl3_AppendHandshake* */
4337 if (sid)
4338 rv = ssl3_AppendHandshakeVariable(
4339 ss, sid->u.ssl3.sessionID, sid->u.ssl3.sessionIDLength, 1);
4340 else
4341 rv = ssl3_AppendHandshakeVariable(ss, NULL, 0, 1);
4342 if (rv != SECSuccess) {
4343 return rv; /* err set by ssl3_AppendHandshake* */
4346 if (IS_DTLS(ss)) {
4347 rv = ssl3_AppendHandshakeVariable(
4348 ss, ss->ssl3.hs.cookie, ss->ssl3.hs.cookieLen, 1);
4349 if (rv != SECSuccess) {
4350 return rv; /* err set by ssl3_AppendHandshake* */
4354 rv = ssl3_AppendHandshakeNumber(ss, num_suites*sizeof(ssl3CipherSuite), 2);
4355 if (rv != SECSuccess) {
4356 return rv; /* err set by ssl3_AppendHandshake* */
4359 if (ss->ssl3.hs.sendingSCSV) {
4360 /* Add the actual SCSV */
4361 rv = ssl3_AppendHandshakeNumber(ss, TLS_EMPTY_RENEGOTIATION_INFO_SCSV,
4362 sizeof(ssl3CipherSuite));
4363 if (rv != SECSuccess) {
4364 return rv; /* err set by ssl3_AppendHandshake* */
4366 actual_count++;
4368 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
4369 ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i];
4370 if (config_match(suite, ss->ssl3.policy, PR_TRUE)) {
4371 actual_count++;
4372 if (actual_count > num_suites) {
4373 /* set error card removal/insertion error */
4374 PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
4375 return SECFailure;
4377 rv = ssl3_AppendHandshakeNumber(ss, suite->cipher_suite,
4378 sizeof(ssl3CipherSuite));
4379 if (rv != SECSuccess) {
4380 return rv; /* err set by ssl3_AppendHandshake* */
4385 /* if cards were removed or inserted between count_cipher_suites and
4386 * generating our list, detect the error here rather than send it off to
4387 * the server.. */
4388 if (actual_count != num_suites) {
4389 /* Card removal/insertion error */
4390 PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
4391 return SECFailure;
4394 rv = ssl3_AppendHandshakeNumber(ss, numCompressionMethods, 1);
4395 if (rv != SECSuccess) {
4396 return rv; /* err set by ssl3_AppendHandshake* */
4398 for (i = 0; i < compressionMethodsCount; i++) {
4399 if (!compressionEnabled(ss, compressions[i]))
4400 continue;
4401 rv = ssl3_AppendHandshakeNumber(ss, compressions[i], 1);
4402 if (rv != SECSuccess) {
4403 return rv; /* err set by ssl3_AppendHandshake* */
4407 if (total_exten_len) {
4408 PRUint32 maxBytes = total_exten_len - 2;
4409 PRInt32 extLen;
4411 rv = ssl3_AppendHandshakeNumber(ss, maxBytes, 2);
4412 if (rv != SECSuccess) {
4413 return rv; /* err set by AppendHandshake. */
4416 extLen = ssl3_CallHelloExtensionSenders(ss, PR_TRUE, maxBytes, NULL);
4417 if (extLen < 0) {
4418 return SECFailure;
4420 maxBytes -= extLen;
4421 PORT_Assert(!maxBytes);
4423 if (ss->ssl3.hs.sendingSCSV) {
4424 /* Since we sent the SCSV, pretend we sent empty RI extension. */
4425 TLSExtensionData *xtnData = &ss->xtnData;
4426 xtnData->advertised[xtnData->numAdvertised++] =
4427 ssl_renegotiation_info_xtn;
4430 flags = 0;
4431 if (!ss->firstHsDone && !requestingResume && !IS_DTLS(ss)) {
4432 flags |= ssl_SEND_FLAG_CAP_RECORD_VERSION;
4434 rv = ssl3_FlushHandshake(ss, flags);
4435 if (rv != SECSuccess) {
4436 return rv; /* error code set by ssl3_FlushHandshake */
4439 ss->ssl3.hs.ws = wait_server_hello;
4440 return rv;
4444 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
4445 * ssl3 Hello Request.
4446 * Caller must hold Handshake and RecvBuf locks.
4448 static SECStatus
4449 ssl3_HandleHelloRequest(sslSocket *ss)
4451 sslSessionID *sid = ss->sec.ci.sid;
4452 SECStatus rv;
4454 SSL_TRC(3, ("%d: SSL3[%d]: handle hello_request handshake",
4455 SSL_GETPID(), ss->fd));
4457 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
4458 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
4460 if (ss->ssl3.hs.ws == wait_server_hello)
4461 return SECSuccess;
4462 if (ss->ssl3.hs.ws != idle_handshake || ss->sec.isServer) {
4463 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
4464 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST);
4465 return SECFailure;
4467 if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) {
4468 ssl_GetXmitBufLock(ss);
4469 rv = SSL3_SendAlert(ss, alert_warning, no_renegotiation);
4470 ssl_ReleaseXmitBufLock(ss);
4471 PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED);
4472 return SECFailure;
4475 if (sid) {
4476 if (ss->sec.uncache)
4477 ss->sec.uncache(sid);
4478 ssl_FreeSID(sid);
4479 ss->sec.ci.sid = NULL;
4482 if (IS_DTLS(ss)) {
4483 dtls_RehandshakeCleanup(ss);
4486 ssl_GetXmitBufLock(ss);
4487 rv = ssl3_SendClientHello(ss, PR_FALSE);
4488 ssl_ReleaseXmitBufLock(ss);
4490 return rv;
4493 #define UNKNOWN_WRAP_MECHANISM 0x7fffffff
4495 static const CK_MECHANISM_TYPE wrapMechanismList[SSL_NUM_WRAP_MECHS] = {
4496 CKM_DES3_ECB,
4497 CKM_CAST5_ECB,
4498 CKM_DES_ECB,
4499 CKM_KEY_WRAP_LYNKS,
4500 CKM_IDEA_ECB,
4501 CKM_CAST3_ECB,
4502 CKM_CAST_ECB,
4503 CKM_RC5_ECB,
4504 CKM_RC2_ECB,
4505 CKM_CDMF_ECB,
4506 CKM_SKIPJACK_WRAP,
4507 CKM_SKIPJACK_CBC64,
4508 CKM_AES_ECB,
4509 CKM_CAMELLIA_ECB,
4510 CKM_SEED_ECB,
4511 UNKNOWN_WRAP_MECHANISM
4514 static int
4515 ssl_FindIndexByWrapMechanism(CK_MECHANISM_TYPE mech)
4517 const CK_MECHANISM_TYPE *pMech = wrapMechanismList;
4519 while (mech != *pMech && *pMech != UNKNOWN_WRAP_MECHANISM) {
4520 ++pMech;
4522 return (*pMech == UNKNOWN_WRAP_MECHANISM) ? -1
4523 : (pMech - wrapMechanismList);
4526 static PK11SymKey *
4527 ssl_UnwrapSymWrappingKey(
4528 SSLWrappedSymWrappingKey *pWswk,
4529 SECKEYPrivateKey * svrPrivKey,
4530 SSL3KEAType exchKeyType,
4531 CK_MECHANISM_TYPE masterWrapMech,
4532 void * pwArg)
4534 PK11SymKey * unwrappedWrappingKey = NULL;
4535 SECItem wrappedKey;
4536 #ifdef NSS_ENABLE_ECC
4537 PK11SymKey * Ks;
4538 SECKEYPublicKey pubWrapKey;
4539 ECCWrappedKeyInfo *ecWrapped;
4540 #endif /* NSS_ENABLE_ECC */
4542 /* found the wrapping key on disk. */
4543 PORT_Assert(pWswk->symWrapMechanism == masterWrapMech);
4544 PORT_Assert(pWswk->exchKeyType == exchKeyType);
4545 if (pWswk->symWrapMechanism != masterWrapMech ||
4546 pWswk->exchKeyType != exchKeyType) {
4547 goto loser;
4549 wrappedKey.type = siBuffer;
4550 wrappedKey.data = pWswk->wrappedSymmetricWrappingkey;
4551 wrappedKey.len = pWswk->wrappedSymKeyLen;
4552 PORT_Assert(wrappedKey.len <= sizeof pWswk->wrappedSymmetricWrappingkey);
4554 switch (exchKeyType) {
4556 case kt_rsa:
4557 unwrappedWrappingKey =
4558 PK11_PubUnwrapSymKey(svrPrivKey, &wrappedKey,
4559 masterWrapMech, CKA_UNWRAP, 0);
4560 break;
4562 #ifdef NSS_ENABLE_ECC
4563 case kt_ecdh:
4565 * For kt_ecdh, we first create an EC public key based on
4566 * data stored with the wrappedSymmetricWrappingkey. Next,
4567 * we do an ECDH computation involving this public key and
4568 * the SSL server's (long-term) EC private key. The resulting
4569 * shared secret is treated the same way as Fortezza's Ks, i.e.,
4570 * it is used to recover the symmetric wrapping key.
4572 * The data in wrappedSymmetricWrappingkey is laid out as defined
4573 * in the ECCWrappedKeyInfo structure.
4575 ecWrapped = (ECCWrappedKeyInfo *) pWswk->wrappedSymmetricWrappingkey;
4577 PORT_Assert(ecWrapped->encodedParamLen + ecWrapped->pubValueLen +
4578 ecWrapped->wrappedKeyLen <= MAX_EC_WRAPPED_KEY_BUFLEN);
4580 if (ecWrapped->encodedParamLen + ecWrapped->pubValueLen +
4581 ecWrapped->wrappedKeyLen > MAX_EC_WRAPPED_KEY_BUFLEN) {
4582 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
4583 goto loser;
4586 pubWrapKey.keyType = ecKey;
4587 pubWrapKey.u.ec.size = ecWrapped->size;
4588 pubWrapKey.u.ec.DEREncodedParams.len = ecWrapped->encodedParamLen;
4589 pubWrapKey.u.ec.DEREncodedParams.data = ecWrapped->var;
4590 pubWrapKey.u.ec.publicValue.len = ecWrapped->pubValueLen;
4591 pubWrapKey.u.ec.publicValue.data = ecWrapped->var +
4592 ecWrapped->encodedParamLen;
4594 wrappedKey.len = ecWrapped->wrappedKeyLen;
4595 wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen +
4596 ecWrapped->pubValueLen;
4598 /* Derive Ks using ECDH */
4599 Ks = PK11_PubDeriveWithKDF(svrPrivKey, &pubWrapKey, PR_FALSE, NULL,
4600 NULL, CKM_ECDH1_DERIVE, masterWrapMech,
4601 CKA_DERIVE, 0, CKD_NULL, NULL, NULL);
4602 if (Ks == NULL) {
4603 goto loser;
4606 /* Use Ks to unwrap the wrapping key */
4607 unwrappedWrappingKey = PK11_UnwrapSymKey(Ks, masterWrapMech, NULL,
4608 &wrappedKey, masterWrapMech,
4609 CKA_UNWRAP, 0);
4610 PK11_FreeSymKey(Ks);
4612 break;
4613 #endif
4615 default:
4616 /* Assert? */
4617 SET_ERROR_CODE
4618 goto loser;
4620 loser:
4621 return unwrappedWrappingKey;
4624 /* Each process sharing the server session ID cache has its own array of
4625 * SymKey pointers for the symmetric wrapping keys that are used to wrap
4626 * the master secrets. There is one key for each KEA type. These Symkeys
4627 * correspond to the wrapped SymKeys kept in the server session cache.
4630 typedef struct {
4631 PK11SymKey * symWrapKey[kt_kea_size];
4632 } ssl3SymWrapKey;
4634 static PZLock * symWrapKeysLock = NULL;
4635 static ssl3SymWrapKey symWrapKeys[SSL_NUM_WRAP_MECHS];
4637 SECStatus ssl_FreeSymWrapKeysLock(void)
4639 if (symWrapKeysLock) {
4640 PZ_DestroyLock(symWrapKeysLock);
4641 symWrapKeysLock = NULL;
4642 return SECSuccess;
4644 PORT_SetError(SEC_ERROR_NOT_INITIALIZED);
4645 return SECFailure;
4648 SECStatus
4649 SSL3_ShutdownServerCache(void)
4651 int i, j;
4653 if (!symWrapKeysLock)
4654 return SECSuccess; /* lock was never initialized */
4655 PZ_Lock(symWrapKeysLock);
4656 /* get rid of all symWrapKeys */
4657 for (i = 0; i < SSL_NUM_WRAP_MECHS; ++i) {
4658 for (j = 0; j < kt_kea_size; ++j) {
4659 PK11SymKey ** pSymWrapKey;
4660 pSymWrapKey = &symWrapKeys[i].symWrapKey[j];
4661 if (*pSymWrapKey) {
4662 PK11_FreeSymKey(*pSymWrapKey);
4663 *pSymWrapKey = NULL;
4668 PZ_Unlock(symWrapKeysLock);
4669 ssl_FreeSessionCacheLocks();
4670 return SECSuccess;
4673 SECStatus ssl_InitSymWrapKeysLock(void)
4675 symWrapKeysLock = PZ_NewLock(nssILockOther);
4676 return symWrapKeysLock ? SECSuccess : SECFailure;
4679 /* Try to get wrapping key for mechanism from in-memory array.
4680 * If that fails, look for one on disk.
4681 * If that fails, generate a new one, put the new one on disk,
4682 * Put the new key in the in-memory array.
4684 static PK11SymKey *
4685 getWrappingKey( sslSocket * ss,
4686 PK11SlotInfo * masterSecretSlot,
4687 SSL3KEAType exchKeyType,
4688 CK_MECHANISM_TYPE masterWrapMech,
4689 void * pwArg)
4691 SECKEYPrivateKey * svrPrivKey;
4692 SECKEYPublicKey * svrPubKey = NULL;
4693 PK11SymKey * unwrappedWrappingKey = NULL;
4694 PK11SymKey ** pSymWrapKey;
4695 CK_MECHANISM_TYPE asymWrapMechanism = CKM_INVALID_MECHANISM;
4696 int length;
4697 int symWrapMechIndex;
4698 SECStatus rv;
4699 SECItem wrappedKey;
4700 SSLWrappedSymWrappingKey wswk;
4701 #ifdef NSS_ENABLE_ECC
4702 PK11SymKey * Ks = NULL;
4703 SECKEYPublicKey *pubWrapKey = NULL;
4704 SECKEYPrivateKey *privWrapKey = NULL;
4705 ECCWrappedKeyInfo *ecWrapped;
4706 #endif /* NSS_ENABLE_ECC */
4708 svrPrivKey = ss->serverCerts[exchKeyType].SERVERKEY;
4709 PORT_Assert(svrPrivKey != NULL);
4710 if (!svrPrivKey) {
4711 return NULL; /* why are we here?!? */
4714 symWrapMechIndex = ssl_FindIndexByWrapMechanism(masterWrapMech);
4715 PORT_Assert(symWrapMechIndex >= 0);
4716 if (symWrapMechIndex < 0)
4717 return NULL; /* invalid masterWrapMech. */
4719 pSymWrapKey = &symWrapKeys[symWrapMechIndex].symWrapKey[exchKeyType];
4721 ssl_InitSessionCacheLocks(PR_TRUE);
4723 PZ_Lock(symWrapKeysLock);
4725 unwrappedWrappingKey = *pSymWrapKey;
4726 if (unwrappedWrappingKey != NULL) {
4727 if (PK11_VerifyKeyOK(unwrappedWrappingKey)) {
4728 unwrappedWrappingKey = PK11_ReferenceSymKey(unwrappedWrappingKey);
4729 goto done;
4731 /* slot series has changed, so this key is no good any more. */
4732 PK11_FreeSymKey(unwrappedWrappingKey);
4733 *pSymWrapKey = unwrappedWrappingKey = NULL;
4736 /* Try to get wrapped SymWrapping key out of the (disk) cache. */
4737 /* Following call fills in wswk on success. */
4738 if (ssl_GetWrappingKey(symWrapMechIndex, exchKeyType, &wswk)) {
4739 /* found the wrapped sym wrapping key on disk. */
4740 unwrappedWrappingKey =
4741 ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, exchKeyType,
4742 masterWrapMech, pwArg);
4743 if (unwrappedWrappingKey) {
4744 goto install;
4748 if (!masterSecretSlot) /* caller doesn't want to create a new one. */
4749 goto loser;
4751 length = PK11_GetBestKeyLength(masterSecretSlot, masterWrapMech);
4752 /* Zero length means fixed key length algorithm, or error.
4753 * It's ambiguous.
4755 unwrappedWrappingKey = PK11_KeyGen(masterSecretSlot, masterWrapMech, NULL,
4756 length, pwArg);
4757 if (!unwrappedWrappingKey) {
4758 goto loser;
4761 /* Prepare the buffer to receive the wrappedWrappingKey,
4762 * the symmetric wrapping key wrapped using the server's pub key.
4764 PORT_Memset(&wswk, 0, sizeof wswk); /* eliminate UMRs. */
4766 if (ss->serverCerts[exchKeyType].serverKeyPair) {
4767 svrPubKey = ss->serverCerts[exchKeyType].serverKeyPair->pubKey;
4769 if (svrPubKey == NULL) {
4770 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
4771 goto loser;
4773 wrappedKey.type = siBuffer;
4774 wrappedKey.len = SECKEY_PublicKeyStrength(svrPubKey);
4775 wrappedKey.data = wswk.wrappedSymmetricWrappingkey;
4777 PORT_Assert(wrappedKey.len <= sizeof wswk.wrappedSymmetricWrappingkey);
4778 if (wrappedKey.len > sizeof wswk.wrappedSymmetricWrappingkey)
4779 goto loser;
4781 /* wrap symmetric wrapping key in server's public key. */
4782 switch (exchKeyType) {
4783 case kt_rsa:
4784 asymWrapMechanism = CKM_RSA_PKCS;
4785 rv = PK11_PubWrapSymKey(asymWrapMechanism, svrPubKey,
4786 unwrappedWrappingKey, &wrappedKey);
4787 break;
4789 #ifdef NSS_ENABLE_ECC
4790 case kt_ecdh:
4792 * We generate an ephemeral EC key pair. Perform an ECDH
4793 * computation involving this ephemeral EC public key and
4794 * the SSL server's (long-term) EC private key. The resulting
4795 * shared secret is treated in the same way as Fortezza's Ks,
4796 * i.e., it is used to wrap the wrapping key. To facilitate
4797 * unwrapping in ssl_UnwrapWrappingKey, we also store all
4798 * relevant info about the ephemeral EC public key in
4799 * wswk.wrappedSymmetricWrappingkey and lay it out as
4800 * described in the ECCWrappedKeyInfo structure.
4802 PORT_Assert(svrPubKey->keyType == ecKey);
4803 if (svrPubKey->keyType != ecKey) {
4804 /* something is wrong in sslsecur.c if this isn't an ecKey */
4805 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
4806 rv = SECFailure;
4807 goto ec_cleanup;
4810 privWrapKey = SECKEY_CreateECPrivateKey(
4811 &svrPubKey->u.ec.DEREncodedParams, &pubWrapKey, NULL);
4812 if ((privWrapKey == NULL) || (pubWrapKey == NULL)) {
4813 rv = SECFailure;
4814 goto ec_cleanup;
4817 /* Set the key size in bits */
4818 if (pubWrapKey->u.ec.size == 0) {
4819 pubWrapKey->u.ec.size = SECKEY_PublicKeyStrengthInBits(svrPubKey);
4822 PORT_Assert(pubWrapKey->u.ec.DEREncodedParams.len +
4823 pubWrapKey->u.ec.publicValue.len < MAX_EC_WRAPPED_KEY_BUFLEN);
4824 if (pubWrapKey->u.ec.DEREncodedParams.len +
4825 pubWrapKey->u.ec.publicValue.len >= MAX_EC_WRAPPED_KEY_BUFLEN) {
4826 PORT_SetError(SEC_ERROR_INVALID_KEY);
4827 rv = SECFailure;
4828 goto ec_cleanup;
4831 /* Derive Ks using ECDH */
4832 Ks = PK11_PubDeriveWithKDF(svrPrivKey, pubWrapKey, PR_FALSE, NULL,
4833 NULL, CKM_ECDH1_DERIVE, masterWrapMech,
4834 CKA_DERIVE, 0, CKD_NULL, NULL, NULL);
4835 if (Ks == NULL) {
4836 rv = SECFailure;
4837 goto ec_cleanup;
4840 ecWrapped = (ECCWrappedKeyInfo *) (wswk.wrappedSymmetricWrappingkey);
4841 ecWrapped->size = pubWrapKey->u.ec.size;
4842 ecWrapped->encodedParamLen = pubWrapKey->u.ec.DEREncodedParams.len;
4843 PORT_Memcpy(ecWrapped->var, pubWrapKey->u.ec.DEREncodedParams.data,
4844 pubWrapKey->u.ec.DEREncodedParams.len);
4846 ecWrapped->pubValueLen = pubWrapKey->u.ec.publicValue.len;
4847 PORT_Memcpy(ecWrapped->var + ecWrapped->encodedParamLen,
4848 pubWrapKey->u.ec.publicValue.data,
4849 pubWrapKey->u.ec.publicValue.len);
4851 wrappedKey.len = MAX_EC_WRAPPED_KEY_BUFLEN -
4852 (ecWrapped->encodedParamLen + ecWrapped->pubValueLen);
4853 wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen +
4854 ecWrapped->pubValueLen;
4856 /* wrap symmetricWrapping key with the local Ks */
4857 rv = PK11_WrapSymKey(masterWrapMech, NULL, Ks,
4858 unwrappedWrappingKey, &wrappedKey);
4860 if (rv != SECSuccess) {
4861 goto ec_cleanup;
4864 /* Write down the length of wrapped key in the buffer
4865 * wswk.wrappedSymmetricWrappingkey at the appropriate offset
4867 ecWrapped->wrappedKeyLen = wrappedKey.len;
4869 ec_cleanup:
4870 if (privWrapKey) SECKEY_DestroyPrivateKey(privWrapKey);
4871 if (pubWrapKey) SECKEY_DestroyPublicKey(pubWrapKey);
4872 if (Ks) PK11_FreeSymKey(Ks);
4873 asymWrapMechanism = masterWrapMech;
4874 break;
4875 #endif /* NSS_ENABLE_ECC */
4877 default:
4878 rv = SECFailure;
4879 break;
4882 if (rv != SECSuccess) {
4883 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
4884 goto loser;
4887 PORT_Assert(asymWrapMechanism != CKM_INVALID_MECHANISM);
4889 wswk.symWrapMechanism = masterWrapMech;
4890 wswk.symWrapMechIndex = symWrapMechIndex;
4891 wswk.asymWrapMechanism = asymWrapMechanism;
4892 wswk.exchKeyType = exchKeyType;
4893 wswk.wrappedSymKeyLen = wrappedKey.len;
4895 /* put it on disk. */
4896 /* If the wrapping key for this KEA type has already been set,
4897 * then abandon the value we just computed and
4898 * use the one we got from the disk.
4900 if (ssl_SetWrappingKey(&wswk)) {
4901 /* somebody beat us to it. The original contents of our wswk
4902 * has been replaced with the content on disk. Now, discard
4903 * the key we just created and unwrap this new one.
4905 PK11_FreeSymKey(unwrappedWrappingKey);
4907 unwrappedWrappingKey =
4908 ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, exchKeyType,
4909 masterWrapMech, pwArg);
4912 install:
4913 if (unwrappedWrappingKey) {
4914 *pSymWrapKey = PK11_ReferenceSymKey(unwrappedWrappingKey);
4917 loser:
4918 done:
4919 PZ_Unlock(symWrapKeysLock);
4920 return unwrappedWrappingKey;
4923 /* hexEncode hex encodes |length| bytes from |in| and writes it as |length*2|
4924 * bytes to |out|. */
4925 static void
4926 hexEncode(char *out, const unsigned char *in, unsigned int length)
4928 static const char hextable[] = "0123456789abcdef";
4929 unsigned int i;
4931 for (i = 0; i < length; i++) {
4932 *(out++) = hextable[in[i] >> 4];
4933 *(out++) = hextable[in[i] & 15];
4937 /* Called from ssl3_SendClientKeyExchange(). */
4938 /* Presently, this always uses PKCS11. There is no bypass for this. */
4939 static SECStatus
4940 sendRSAClientKeyExchange(sslSocket * ss, SECKEYPublicKey * svrPubKey)
4942 PK11SymKey * pms = NULL;
4943 SECStatus rv = SECFailure;
4944 SECItem enc_pms = {siBuffer, NULL, 0};
4945 PRBool isTLS;
4947 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
4948 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
4950 /* Generate the pre-master secret ... */
4951 ssl_GetSpecWriteLock(ss);
4952 isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
4954 pms = ssl3_GenerateRSAPMS(ss, ss->ssl3.pwSpec, NULL);
4955 ssl_ReleaseSpecWriteLock(ss);
4956 if (pms == NULL) {
4957 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
4958 goto loser;
4961 /* Get the wrapped (encrypted) pre-master secret, enc_pms */
4962 enc_pms.len = SECKEY_PublicKeyStrength(svrPubKey);
4963 enc_pms.data = (unsigned char*)PORT_Alloc(enc_pms.len);
4964 if (enc_pms.data == NULL) {
4965 goto loser; /* err set by PORT_Alloc */
4968 /* wrap pre-master secret in server's public key. */
4969 rv = PK11_PubWrapSymKey(CKM_RSA_PKCS, svrPubKey, pms, &enc_pms);
4970 if (rv != SECSuccess) {
4971 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
4972 goto loser;
4975 if (ssl_keylog_iob) {
4976 SECStatus extractRV = PK11_ExtractKeyValue(pms);
4977 if (extractRV == SECSuccess) {
4978 SECItem * keyData = PK11_GetKeyData(pms);
4979 if (keyData && keyData->data && keyData->len) {
4980 #ifdef TRACE
4981 if (ssl_trace >= 100) {
4982 ssl_PrintBuf(ss, "Pre-Master Secret",
4983 keyData->data, keyData->len);
4985 #endif
4986 if (ssl_keylog_iob && enc_pms.len >= 8 && keyData->len == 48) {
4987 /* https://developer.mozilla.org/en/NSS_Key_Log_Format */
4989 /* There could be multiple, concurrent writers to the
4990 * keylog, so we have to do everything in a single call to
4991 * fwrite. */
4992 char buf[4 + 8*2 + 1 + 48*2 + 1];
4994 strcpy(buf, "RSA ");
4995 hexEncode(buf + 4, enc_pms.data, 8);
4996 buf[20] = ' ';
4997 hexEncode(buf + 21, keyData->data, 48);
4998 buf[sizeof(buf) - 1] = '\n';
5000 fwrite(buf, sizeof(buf), 1, ssl_keylog_iob);
5001 fflush(ssl_keylog_iob);
5007 rv = ssl3_InitPendingCipherSpec(ss, pms);
5008 PK11_FreeSymKey(pms); pms = NULL;
5010 if (rv != SECSuccess) {
5011 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
5012 goto loser;
5015 rv = ssl3_AppendHandshakeHeader(ss, client_key_exchange,
5016 isTLS ? enc_pms.len + 2 : enc_pms.len);
5017 if (rv != SECSuccess) {
5018 goto loser; /* err set by ssl3_AppendHandshake* */
5020 if (isTLS) {
5021 rv = ssl3_AppendHandshakeVariable(ss, enc_pms.data, enc_pms.len, 2);
5022 } else {
5023 rv = ssl3_AppendHandshake(ss, enc_pms.data, enc_pms.len);
5025 if (rv != SECSuccess) {
5026 goto loser; /* err set by ssl3_AppendHandshake* */
5029 rv = SECSuccess;
5031 loser:
5032 if (enc_pms.data != NULL) {
5033 PORT_Free(enc_pms.data);
5035 if (pms != NULL) {
5036 PK11_FreeSymKey(pms);
5038 return rv;
5041 /* Called from ssl3_SendClientKeyExchange(). */
5042 /* Presently, this always uses PKCS11. There is no bypass for this. */
5043 static SECStatus
5044 sendDHClientKeyExchange(sslSocket * ss, SECKEYPublicKey * svrPubKey)
5046 PK11SymKey * pms = NULL;
5047 SECStatus rv = SECFailure;
5048 PRBool isTLS;
5049 CK_MECHANISM_TYPE target;
5051 SECKEYDHParams dhParam; /* DH parameters */
5052 SECKEYPublicKey *pubKey = NULL; /* Ephemeral DH key */
5053 SECKEYPrivateKey *privKey = NULL; /* Ephemeral DH key */
5055 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
5056 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
5058 isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
5060 /* Copy DH parameters from server key */
5062 if (svrPubKey->keyType != dhKey) {
5063 PORT_SetError(SEC_ERROR_BAD_KEY);
5064 goto loser;
5066 dhParam.prime.data = svrPubKey->u.dh.prime.data;
5067 dhParam.prime.len = svrPubKey->u.dh.prime.len;
5068 dhParam.base.data = svrPubKey->u.dh.base.data;
5069 dhParam.base.len = svrPubKey->u.dh.base.len;
5071 /* Generate ephemeral DH keypair */
5072 privKey = SECKEY_CreateDHPrivateKey(&dhParam, &pubKey, NULL);
5073 if (!privKey || !pubKey) {
5074 ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL);
5075 rv = SECFailure;
5076 goto loser;
5078 PRINT_BUF(50, (ss, "DH public value:",
5079 pubKey->u.dh.publicValue.data,
5080 pubKey->u.dh.publicValue.len));
5082 if (isTLS) target = CKM_TLS_MASTER_KEY_DERIVE_DH;
5083 else target = CKM_SSL3_MASTER_KEY_DERIVE_DH;
5085 /* Determine the PMS */
5087 pms = PK11_PubDerive(privKey, svrPubKey, PR_FALSE, NULL, NULL,
5088 CKM_DH_PKCS_DERIVE, target, CKA_DERIVE, 0, NULL);
5090 if (pms == NULL) {
5091 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
5092 goto loser;
5095 SECKEY_DestroyPrivateKey(privKey);
5096 privKey = NULL;
5098 rv = ssl3_InitPendingCipherSpec(ss, pms);
5099 PK11_FreeSymKey(pms); pms = NULL;
5101 if (rv != SECSuccess) {
5102 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
5103 goto loser;
5106 rv = ssl3_AppendHandshakeHeader(ss, client_key_exchange,
5107 pubKey->u.dh.publicValue.len + 2);
5108 if (rv != SECSuccess) {
5109 goto loser; /* err set by ssl3_AppendHandshake* */
5111 rv = ssl3_AppendHandshakeVariable(ss,
5112 pubKey->u.dh.publicValue.data,
5113 pubKey->u.dh.publicValue.len, 2);
5114 SECKEY_DestroyPublicKey(pubKey);
5115 pubKey = NULL;
5117 if (rv != SECSuccess) {
5118 goto loser; /* err set by ssl3_AppendHandshake* */
5121 rv = SECSuccess;
5124 loser:
5126 if(pms) PK11_FreeSymKey(pms);
5127 if(privKey) SECKEY_DestroyPrivateKey(privKey);
5128 if(pubKey) SECKEY_DestroyPublicKey(pubKey);
5129 return rv;
5136 /* Called from ssl3_HandleServerHelloDone(). */
5137 static SECStatus
5138 ssl3_SendClientKeyExchange(sslSocket *ss)
5140 SECKEYPublicKey * serverKey = NULL;
5141 SECStatus rv = SECFailure;
5142 PRBool isTLS;
5144 SSL_TRC(3, ("%d: SSL3[%d]: send client_key_exchange handshake",
5145 SSL_GETPID(), ss->fd));
5147 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
5148 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
5150 if (ss->sec.peerKey == NULL) {
5151 serverKey = CERT_ExtractPublicKey(ss->sec.peerCert);
5152 if (serverKey == NULL) {
5153 ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
5154 return SECFailure;
5156 } else {
5157 serverKey = ss->sec.peerKey;
5158 ss->sec.peerKey = NULL; /* we're done with it now */
5161 isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
5162 /* enforce limits on kea key sizes. */
5163 if (ss->ssl3.hs.kea_def->is_limited) {
5164 int keyLen = SECKEY_PublicKeyStrength(serverKey); /* bytes */
5166 if (keyLen * BPB > ss->ssl3.hs.kea_def->key_size_limit) {
5167 if (isTLS)
5168 (void)SSL3_SendAlert(ss, alert_fatal, export_restriction);
5169 else
5170 (void)ssl3_HandshakeFailure(ss);
5171 PORT_SetError(SSL_ERROR_PUB_KEY_SIZE_LIMIT_EXCEEDED);
5172 goto loser;
5176 ss->sec.keaType = ss->ssl3.hs.kea_def->exchKeyType;
5177 ss->sec.keaKeyBits = SECKEY_PublicKeyStrengthInBits(serverKey);
5179 switch (ss->ssl3.hs.kea_def->exchKeyType) {
5180 case kt_rsa:
5181 rv = sendRSAClientKeyExchange(ss, serverKey);
5182 break;
5184 case kt_dh:
5185 rv = sendDHClientKeyExchange(ss, serverKey);
5186 break;
5188 #ifdef NSS_ENABLE_ECC
5189 case kt_ecdh:
5190 rv = ssl3_SendECDHClientKeyExchange(ss, serverKey);
5191 break;
5192 #endif /* NSS_ENABLE_ECC */
5194 default:
5195 /* got an unknown or unsupported Key Exchange Algorithm. */
5196 SEND_ALERT
5197 PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
5198 break;
5201 SSL_TRC(3, ("%d: SSL3[%d]: DONE sending client_key_exchange",
5202 SSL_GETPID(), ss->fd));
5204 loser:
5205 if (serverKey)
5206 SECKEY_DestroyPublicKey(serverKey);
5207 return rv; /* err code already set. */
5210 /* Called from ssl3_HandleServerHelloDone(). */
5211 static SECStatus
5212 ssl3_SendCertificateVerify(sslSocket *ss)
5214 SECStatus rv = SECFailure;
5215 PRBool isTLS;
5216 SECItem buf = {siBuffer, NULL, 0};
5217 SSL3Hashes hashes;
5219 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
5220 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
5222 SSL_TRC(3, ("%d: SSL3[%d]: send certificate_verify handshake",
5223 SSL_GETPID(), ss->fd));
5225 ssl_GetSpecReadLock(ss);
5226 rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.pwSpec, &hashes, 0);
5227 ssl_ReleaseSpecReadLock(ss);
5228 if (rv != SECSuccess) {
5229 goto done; /* err code was set by ssl3_ComputeHandshakeHashes */
5232 isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
5233 if (ss->ssl3.platformClientKey) {
5234 #ifdef NSS_PLATFORM_CLIENT_AUTH
5235 rv = ssl3_PlatformSignHashes(&hashes, ss->ssl3.platformClientKey,
5236 &buf, isTLS);
5237 ssl_FreePlatformKey(ss->ssl3.platformClientKey);
5238 ss->ssl3.platformClientKey = (PlatformKey)NULL;
5239 #endif /* NSS_PLATFORM_CLIENT_AUTH */
5240 } else {
5241 rv = ssl3_SignHashes(&hashes, ss->ssl3.clientPrivateKey, &buf, isTLS);
5242 if (rv == SECSuccess) {
5243 PK11SlotInfo * slot;
5244 sslSessionID * sid = ss->sec.ci.sid;
5246 /* Remember the info about the slot that did the signing.
5247 ** Later, when doing an SSL restart handshake, verify this.
5248 ** These calls are mere accessors, and can't fail.
5250 slot = PK11_GetSlotFromPrivateKey(ss->ssl3.clientPrivateKey);
5251 sid->u.ssl3.clAuthSeries = PK11_GetSlotSeries(slot);
5252 sid->u.ssl3.clAuthSlotID = PK11_GetSlotID(slot);
5253 sid->u.ssl3.clAuthModuleID = PK11_GetModuleID(slot);
5254 sid->u.ssl3.clAuthValid = PR_TRUE;
5255 PK11_FreeSlot(slot);
5257 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
5258 ss->ssl3.clientPrivateKey = NULL;
5260 if (rv != SECSuccess) {
5261 goto done; /* err code was set by ssl3_SignHashes */
5264 rv = ssl3_AppendHandshakeHeader(ss, certificate_verify, buf.len + 2);
5265 if (rv != SECSuccess) {
5266 goto done; /* error code set by AppendHandshake */
5268 rv = ssl3_AppendHandshakeVariable(ss, buf.data, buf.len, 2);
5269 if (rv != SECSuccess) {
5270 goto done; /* error code set by AppendHandshake */
5273 done:
5274 if (buf.data)
5275 PORT_Free(buf.data);
5276 return rv;
5279 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
5280 * ssl3 ServerHello message.
5281 * Caller must hold Handshake and RecvBuf locks.
5283 static SECStatus
5284 ssl3_HandleServerHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
5286 sslSessionID *sid = ss->sec.ci.sid;
5287 PRInt32 temp; /* allow for consume number failure */
5288 PRBool suite_found = PR_FALSE;
5289 int i;
5290 int errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
5291 SECStatus rv;
5292 SECItem sidBytes = {siBuffer, NULL, 0};
5293 PRBool sid_match;
5294 PRBool isTLS = PR_FALSE;
5295 SSL3AlertDescription desc = illegal_parameter;
5296 SSL3ProtocolVersion version;
5298 SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello handshake",
5299 SSL_GETPID(), ss->fd));
5300 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
5301 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
5303 rv = ssl3_InitState(ss);
5304 if (rv != SECSuccess) {
5305 errCode = PORT_GetError(); /* ssl3_InitState has set the error code. */
5306 goto alert_loser;
5308 if (ss->ssl3.hs.ws != wait_server_hello) {
5309 errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO;
5310 desc = unexpected_message;
5311 goto alert_loser;
5314 /* clean up anything left from previous handshake. */
5315 if (ss->ssl3.clientCertChain != NULL) {
5316 CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
5317 ss->ssl3.clientCertChain = NULL;
5319 if (ss->ssl3.clientCertificate != NULL) {
5320 CERT_DestroyCertificate(ss->ssl3.clientCertificate);
5321 ss->ssl3.clientCertificate = NULL;
5323 if (ss->ssl3.clientPrivateKey != NULL) {
5324 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
5325 ss->ssl3.clientPrivateKey = NULL;
5327 #ifdef NSS_PLATFORM_CLIENT_AUTH
5328 if (ss->ssl3.platformClientKey) {
5329 ssl_FreePlatformKey(ss->ssl3.platformClientKey);
5330 ss->ssl3.platformClientKey = (PlatformKey)NULL;
5332 #endif /* NSS_PLATFORM_CLIENT_AUTH */
5334 if (ss->ssl3.channelID != NULL) {
5335 SECKEY_DestroyPrivateKey(ss->ssl3.channelID);
5336 ss->ssl3.channelID = NULL;
5338 if (ss->ssl3.channelIDPub != NULL) {
5339 SECKEY_DestroyPublicKey(ss->ssl3.channelIDPub);
5340 ss->ssl3.channelIDPub = NULL;
5343 temp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
5344 if (temp < 0) {
5345 goto loser; /* alert has been sent */
5347 version = (SSL3ProtocolVersion)temp;
5349 if (IS_DTLS(ss)) {
5350 /* RFC 4347 required that you verify that the server versions
5351 * match (Section 4.2.1) in the HelloVerifyRequest and the
5352 * ServerHello.
5354 * RFC 6347 suggests (SHOULD) that servers always use 1.0
5355 * in HelloVerifyRequest and allows the versions not to match,
5356 * especially when 1.2 is being negotiated.
5358 * Therefore we do not check for matching here.
5360 version = dtls_DTLSVersionToTLSVersion(version);
5361 if (version == 0) { /* Insane version number */
5362 goto alert_loser;
5366 rv = ssl3_NegotiateVersion(ss, version, PR_FALSE);
5367 if (rv != SECSuccess) {
5368 desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version
5369 : handshake_failure;
5370 errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
5371 goto alert_loser;
5373 isTLS = (ss->version > SSL_LIBRARY_VERSION_3_0);
5375 rv = ssl3_ConsumeHandshake(
5376 ss, &ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH, &b, &length);
5377 if (rv != SECSuccess) {
5378 goto loser; /* alert has been sent */
5381 rv = ssl3_ConsumeHandshakeVariable(ss, &sidBytes, 1, &b, &length);
5382 if (rv != SECSuccess) {
5383 goto loser; /* alert has been sent */
5385 if (sidBytes.len > SSL3_SESSIONID_BYTES) {
5386 if (isTLS)
5387 desc = decode_error;
5388 goto alert_loser; /* malformed. */
5391 /* find selected cipher suite in our list. */
5392 temp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
5393 if (temp < 0) {
5394 goto loser; /* alert has been sent */
5396 ssl3_config_match_init(ss);
5397 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
5398 ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i];
5399 if (temp == suite->cipher_suite) {
5400 if (!config_match(suite, ss->ssl3.policy, PR_TRUE)) {
5401 break; /* failure */
5403 if (!ssl3_CipherSuiteAllowedForVersion(suite->cipher_suite,
5404 ss->version)) {
5405 desc = handshake_failure;
5406 errCode = SSL_ERROR_CIPHER_DISALLOWED_FOR_VERSION;
5407 goto alert_loser;
5410 suite_found = PR_TRUE;
5411 break; /* success */
5414 if (!suite_found) {
5415 desc = handshake_failure;
5416 errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
5417 goto alert_loser;
5419 ss->ssl3.hs.cipher_suite = (ssl3CipherSuite)temp;
5420 ss->ssl3.hs.suite_def = ssl_LookupCipherSuiteDef((ssl3CipherSuite)temp);
5421 PORT_Assert(ss->ssl3.hs.suite_def);
5422 if (!ss->ssl3.hs.suite_def) {
5423 PORT_SetError(errCode = SEC_ERROR_LIBRARY_FAILURE);
5424 goto loser; /* we don't send alerts for our screw-ups. */
5427 /* find selected compression method in our list. */
5428 temp = ssl3_ConsumeHandshakeNumber(ss, 1, &b, &length);
5429 if (temp < 0) {
5430 goto loser; /* alert has been sent */
5432 suite_found = PR_FALSE;
5433 for (i = 0; i < compressionMethodsCount; i++) {
5434 if (temp == compressions[i]) {
5435 if (!compressionEnabled(ss, compressions[i])) {
5436 break; /* failure */
5438 suite_found = PR_TRUE;
5439 break; /* success */
5442 if (!suite_found) {
5443 desc = handshake_failure;
5444 errCode = SSL_ERROR_NO_COMPRESSION_OVERLAP;
5445 goto alert_loser;
5447 ss->ssl3.hs.compression = (SSLCompressionMethod)temp;
5449 /* Note that if !isTLS and the extra stuff is not extensions, we
5450 * do NOT goto alert_loser.
5451 * There are some old SSL 3.0 implementations that do send stuff
5452 * after the end of the server hello, and we deliberately ignore
5453 * such stuff in the interest of maximal interoperability (being
5454 * "generous in what you accept").
5455 * Update: Starting in NSS 3.12.6, we handle the renegotiation_info
5456 * extension in SSL 3.0.
5458 if (length != 0) {
5459 SECItem extensions;
5460 rv = ssl3_ConsumeHandshakeVariable(ss, &extensions, 2, &b, &length);
5461 if (rv != SECSuccess || length != 0) {
5462 if (isTLS)
5463 goto alert_loser;
5464 } else {
5465 rv = ssl3_HandleHelloExtensions(ss, &extensions.data,
5466 &extensions.len);
5467 if (rv != SECSuccess)
5468 goto alert_loser;
5471 if ((ss->opt.requireSafeNegotiation ||
5472 (ss->firstHsDone && (ss->peerRequestedProtection ||
5473 ss->opt.enableRenegotiation == SSL_RENEGOTIATE_REQUIRES_XTN))) &&
5474 !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
5475 desc = handshake_failure;
5476 errCode = ss->firstHsDone ? SSL_ERROR_RENEGOTIATION_NOT_ALLOWED
5477 : SSL_ERROR_UNSAFE_NEGOTIATION;
5478 goto alert_loser;
5481 /* Any errors after this point are not "malformed" errors. */
5482 desc = handshake_failure;
5484 /* we need to call ssl3_SetupPendingCipherSpec here so we can check the
5485 * key exchange algorithm. */
5486 rv = ssl3_SetupPendingCipherSpec(ss);
5487 if (rv != SECSuccess) {
5488 goto alert_loser; /* error code is set. */
5491 /* We may or may not have sent a session id, we may get one back or
5492 * not and if so it may match the one we sent.
5493 * Attempt to restore the master secret to see if this is so...
5494 * Don't consider failure to find a matching SID an error.
5496 sid_match = (PRBool)(sidBytes.len > 0 &&
5497 sidBytes.len == sid->u.ssl3.sessionIDLength &&
5498 !PORT_Memcmp(sid->u.ssl3.sessionID, sidBytes.data, sidBytes.len));
5500 if (sid_match &&
5501 sid->version == ss->version &&
5502 sid->u.ssl3.cipherSuite == ss->ssl3.hs.cipher_suite) do {
5503 ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec;
5505 SECItem wrappedMS; /* wrapped master secret. */
5507 ss->sec.authAlgorithm = sid->authAlgorithm;
5508 ss->sec.authKeyBits = sid->authKeyBits;
5509 ss->sec.keaType = sid->keaType;
5510 ss->sec.keaKeyBits = sid->keaKeyBits;
5512 /* 3 cases here:
5513 * a) key is wrapped (implies using PKCS11)
5514 * b) key is unwrapped, but we're still using PKCS11
5515 * c) key is unwrapped, and we're bypassing PKCS11.
5517 if (sid->u.ssl3.keys.msIsWrapped) {
5518 PK11SlotInfo *slot;
5519 PK11SymKey * wrapKey; /* wrapping key */
5520 CK_FLAGS keyFlags = 0;
5522 #ifndef NO_PKCS11_BYPASS
5523 if (ss->opt.bypassPKCS11) {
5524 /* we cannot restart a non-bypass session in a
5525 ** bypass socket.
5527 break;
5529 #endif
5530 /* unwrap master secret with PKCS11 */
5531 slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID,
5532 sid->u.ssl3.masterSlotID);
5533 if (slot == NULL) {
5534 break; /* not considered an error. */
5536 if (!PK11_IsPresent(slot)) {
5537 PK11_FreeSlot(slot);
5538 break; /* not considered an error. */
5540 wrapKey = PK11_GetWrapKey(slot, sid->u.ssl3.masterWrapIndex,
5541 sid->u.ssl3.masterWrapMech,
5542 sid->u.ssl3.masterWrapSeries,
5543 ss->pkcs11PinArg);
5544 PK11_FreeSlot(slot);
5545 if (wrapKey == NULL) {
5546 break; /* not considered an error. */
5549 if (ss->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */
5550 keyFlags = CKF_SIGN | CKF_VERIFY;
5553 wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
5554 wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len;
5555 pwSpec->master_secret =
5556 PK11_UnwrapSymKeyWithFlags(wrapKey, sid->u.ssl3.masterWrapMech,
5557 NULL, &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE,
5558 CKA_DERIVE, sizeof(SSL3MasterSecret), keyFlags);
5559 errCode = PORT_GetError();
5560 PK11_FreeSymKey(wrapKey);
5561 if (pwSpec->master_secret == NULL) {
5562 break; /* errorCode set just after call to UnwrapSymKey. */
5564 #ifndef NO_PKCS11_BYPASS
5565 } else if (ss->opt.bypassPKCS11) {
5566 /* MS is not wrapped */
5567 wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
5568 wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len;
5569 memcpy(pwSpec->raw_master_secret, wrappedMS.data, wrappedMS.len);
5570 pwSpec->msItem.data = pwSpec->raw_master_secret;
5571 pwSpec->msItem.len = wrappedMS.len;
5572 #endif
5573 } else {
5574 /* We CAN restart a bypass session in a non-bypass socket. */
5575 /* need to import the raw master secret to session object */
5576 PK11SlotInfo *slot = PK11_GetInternalSlot();
5577 wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
5578 wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len;
5579 pwSpec->master_secret =
5580 PK11_ImportSymKey(slot, CKM_SSL3_MASTER_KEY_DERIVE,
5581 PK11_OriginUnwrap, CKA_ENCRYPT,
5582 &wrappedMS, NULL);
5583 PK11_FreeSlot(slot);
5584 if (pwSpec->master_secret == NULL) {
5585 break;
5589 /* Got a Match */
5590 SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_cache_hits );
5592 /* If we sent a session ticket, then this is a stateless resume. */
5593 if (sid->version > SSL_LIBRARY_VERSION_3_0 &&
5594 sid->u.ssl3.sessionTicket.ticket.data != NULL)
5595 SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_stateless_resumes );
5597 if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn))
5598 ss->ssl3.hs.ws = wait_new_session_ticket;
5599 else
5600 ss->ssl3.hs.ws = wait_change_cipher;
5602 ss->ssl3.hs.isResuming = PR_TRUE;
5604 /* copy the peer cert from the SID */
5605 if (sid->peerCert != NULL) {
5606 ss->sec.peerCert = CERT_DupCertificate(sid->peerCert);
5607 ssl3_CopyPeerCertsFromSID(ss, sid);
5611 /* NULL value for PMS signifies re-use of the old MS */
5612 rv = ssl3_InitPendingCipherSpec(ss, NULL);
5613 if (rv != SECSuccess) {
5614 goto alert_loser; /* err code was set */
5616 goto winner;
5617 } while (0);
5619 if (sid_match)
5620 SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_cache_not_ok );
5621 else
5622 SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_cache_misses );
5624 /* throw the old one away */
5625 sid->u.ssl3.keys.resumable = PR_FALSE;
5626 if (ss->sec.uncache)
5627 (*ss->sec.uncache)(sid);
5628 ssl_FreeSID(sid);
5630 /* get a new sid */
5631 ss->sec.ci.sid = sid = ssl3_NewSessionID(ss, PR_FALSE);
5632 if (sid == NULL) {
5633 goto alert_loser; /* memory error is set. */
5636 sid->version = ss->version;
5637 sid->u.ssl3.sessionIDLength = sidBytes.len;
5638 PORT_Memcpy(sid->u.ssl3.sessionID, sidBytes.data, sidBytes.len);
5640 ss->ssl3.hs.isResuming = PR_FALSE;
5641 ss->ssl3.hs.ws = wait_server_cert;
5643 winner:
5644 /* If we will need a ChannelID key then we make the callback now. This
5645 * allows the handshake to be restarted cleanly if the callback returns
5646 * SECWouldBlock. */
5647 if (ssl3_ExtensionNegotiated(ss, ssl_channel_id_xtn)) {
5648 rv = ss->getChannelID(ss->getChannelIDArg, ss->fd,
5649 &ss->ssl3.channelIDPub, &ss->ssl3.channelID);
5650 if (rv == SECWouldBlock) {
5651 ssl3_SetAlwaysBlock(ss);
5652 return rv;
5654 if (rv != SECSuccess ||
5655 ss->ssl3.channelIDPub == NULL ||
5656 ss->ssl3.channelID == NULL) {
5657 PORT_SetError(SSL_ERROR_GET_CHANNEL_ID_FAILED);
5658 desc = internal_error;
5659 goto alert_loser;
5663 return SECSuccess;
5665 alert_loser:
5666 (void)SSL3_SendAlert(ss, alert_fatal, desc);
5668 loser:
5669 errCode = ssl_MapLowLevelError(errCode);
5670 return SECFailure;
5673 /* ssl3_BigIntGreaterThanOne returns true iff |mpint|, taken as an unsigned,
5674 * big-endian integer is > 1 */
5675 static PRBool
5676 ssl3_BigIntGreaterThanOne(const SECItem* mpint) {
5677 unsigned char firstNonZeroByte = 0;
5678 unsigned int i;
5680 for (i = 0; i < mpint->len; i++) {
5681 if (mpint->data[i]) {
5682 firstNonZeroByte = mpint->data[i];
5683 break;
5687 if (firstNonZeroByte == 0)
5688 return PR_FALSE;
5689 if (firstNonZeroByte > 1)
5690 return PR_TRUE;
5692 /* firstNonZeroByte == 1, therefore mpint > 1 iff the first non-zero byte
5693 * is followed by another byte. */
5694 return (i < mpint->len - 1);
5697 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
5698 * ssl3 ServerKeyExchange message.
5699 * Caller must hold Handshake and RecvBuf locks.
5701 static SECStatus
5702 ssl3_HandleServerKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
5704 PRArenaPool * arena = NULL;
5705 SECKEYPublicKey *peerKey = NULL;
5706 PRBool isTLS;
5707 SECStatus rv;
5708 int errCode = SSL_ERROR_RX_MALFORMED_SERVER_KEY_EXCH;
5709 SSL3AlertDescription desc = illegal_parameter;
5710 SSL3Hashes hashes;
5711 SECItem signature = {siBuffer, NULL, 0};
5713 SSL_TRC(3, ("%d: SSL3[%d]: handle server_key_exchange handshake",
5714 SSL_GETPID(), ss->fd));
5715 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
5716 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
5718 if (ss->ssl3.hs.ws != wait_server_key &&
5719 ss->ssl3.hs.ws != wait_server_cert) {
5720 errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH;
5721 desc = unexpected_message;
5722 goto alert_loser;
5724 if (ss->sec.peerCert == NULL) {
5725 errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH;
5726 desc = unexpected_message;
5727 goto alert_loser;
5730 isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
5732 switch (ss->ssl3.hs.kea_def->exchKeyType) {
5734 case kt_rsa: {
5735 SECItem modulus = {siBuffer, NULL, 0};
5736 SECItem exponent = {siBuffer, NULL, 0};
5738 rv = ssl3_ConsumeHandshakeVariable(ss, &modulus, 2, &b, &length);
5739 if (rv != SECSuccess) {
5740 goto loser; /* malformed. */
5742 rv = ssl3_ConsumeHandshakeVariable(ss, &exponent, 2, &b, &length);
5743 if (rv != SECSuccess) {
5744 goto loser; /* malformed. */
5746 rv = ssl3_ConsumeHandshakeVariable(ss, &signature, 2, &b, &length);
5747 if (rv != SECSuccess) {
5748 goto loser; /* malformed. */
5750 if (length != 0) {
5751 if (isTLS)
5752 desc = decode_error;
5753 goto alert_loser; /* malformed. */
5756 /* failures after this point are not malformed handshakes. */
5757 /* TLS: send decrypt_error if signature failed. */
5758 desc = isTLS ? decrypt_error : handshake_failure;
5761 * check to make sure the hash is signed by right guy
5763 rv = ssl3_ComputeExportRSAKeyHash(modulus, exponent,
5764 &ss->ssl3.hs.client_random,
5765 &ss->ssl3.hs.server_random,
5766 &hashes, ss->opt.bypassPKCS11);
5767 if (rv != SECSuccess) {
5768 errCode =
5769 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
5770 goto alert_loser;
5772 rv = ssl3_VerifySignedHashes(&hashes, ss->sec.peerCert, &signature,
5773 isTLS, ss->pkcs11PinArg);
5774 if (rv != SECSuccess) {
5775 errCode =
5776 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
5777 goto alert_loser;
5781 * we really need to build a new key here because we can no longer
5782 * ignore calling SECKEY_DestroyPublicKey. Using the key may allocate
5783 * pkcs11 slots and ID's.
5785 arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
5786 if (arena == NULL) {
5787 goto no_memory;
5790 peerKey = PORT_ArenaZNew(arena, SECKEYPublicKey);
5791 if (peerKey == NULL) {
5792 PORT_FreeArena(arena, PR_FALSE);
5793 goto no_memory;
5796 peerKey->arena = arena;
5797 peerKey->keyType = rsaKey;
5798 peerKey->pkcs11Slot = NULL;
5799 peerKey->pkcs11ID = CK_INVALID_HANDLE;
5800 if (SECITEM_CopyItem(arena, &peerKey->u.rsa.modulus, &modulus) ||
5801 SECITEM_CopyItem(arena, &peerKey->u.rsa.publicExponent, &exponent))
5803 PORT_FreeArena(arena, PR_FALSE);
5804 goto no_memory;
5806 ss->sec.peerKey = peerKey;
5807 ss->ssl3.hs.ws = wait_cert_request;
5808 return SECSuccess;
5811 case kt_dh: {
5812 SECItem dh_p = {siBuffer, NULL, 0};
5813 SECItem dh_g = {siBuffer, NULL, 0};
5814 SECItem dh_Ys = {siBuffer, NULL, 0};
5816 rv = ssl3_ConsumeHandshakeVariable(ss, &dh_p, 2, &b, &length);
5817 if (rv != SECSuccess) {
5818 goto loser; /* malformed. */
5820 if (dh_p.len < 512/8) {
5821 errCode = SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY;
5822 goto alert_loser;
5824 rv = ssl3_ConsumeHandshakeVariable(ss, &dh_g, 2, &b, &length);
5825 if (rv != SECSuccess) {
5826 goto loser; /* malformed. */
5828 if (dh_g.len > dh_p.len || !ssl3_BigIntGreaterThanOne(&dh_g))
5829 goto alert_loser;
5830 rv = ssl3_ConsumeHandshakeVariable(ss, &dh_Ys, 2, &b, &length);
5831 if (rv != SECSuccess) {
5832 goto loser; /* malformed. */
5834 if (dh_Ys.len > dh_p.len || !ssl3_BigIntGreaterThanOne(&dh_Ys))
5835 goto alert_loser;
5836 rv = ssl3_ConsumeHandshakeVariable(ss, &signature, 2, &b, &length);
5837 if (rv != SECSuccess) {
5838 goto loser; /* malformed. */
5840 if (length != 0) {
5841 if (isTLS)
5842 desc = decode_error;
5843 goto alert_loser; /* malformed. */
5846 PRINT_BUF(60, (NULL, "Server DH p", dh_p.data, dh_p.len));
5847 PRINT_BUF(60, (NULL, "Server DH g", dh_g.data, dh_g.len));
5848 PRINT_BUF(60, (NULL, "Server DH Ys", dh_Ys.data, dh_Ys.len));
5850 /* failures after this point are not malformed handshakes. */
5851 /* TLS: send decrypt_error if signature failed. */
5852 desc = isTLS ? decrypt_error : handshake_failure;
5855 * check to make sure the hash is signed by right guy
5857 rv = ssl3_ComputeDHKeyHash(dh_p, dh_g, dh_Ys,
5858 &ss->ssl3.hs.client_random,
5859 &ss->ssl3.hs.server_random,
5860 &hashes, ss->opt.bypassPKCS11);
5861 if (rv != SECSuccess) {
5862 errCode =
5863 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
5864 goto alert_loser;
5866 rv = ssl3_VerifySignedHashes(&hashes, ss->sec.peerCert, &signature,
5867 isTLS, ss->pkcs11PinArg);
5868 if (rv != SECSuccess) {
5869 errCode =
5870 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
5871 goto alert_loser;
5875 * we really need to build a new key here because we can no longer
5876 * ignore calling SECKEY_DestroyPublicKey. Using the key may allocate
5877 * pkcs11 slots and ID's.
5879 arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
5880 if (arena == NULL) {
5881 goto no_memory;
5884 ss->sec.peerKey = peerKey = PORT_ArenaZNew(arena, SECKEYPublicKey);
5885 if (peerKey == NULL) {
5886 goto no_memory;
5889 peerKey->arena = arena;
5890 peerKey->keyType = dhKey;
5891 peerKey->pkcs11Slot = NULL;
5892 peerKey->pkcs11ID = CK_INVALID_HANDLE;
5894 if (SECITEM_CopyItem(arena, &peerKey->u.dh.prime, &dh_p) ||
5895 SECITEM_CopyItem(arena, &peerKey->u.dh.base, &dh_g) ||
5896 SECITEM_CopyItem(arena, &peerKey->u.dh.publicValue, &dh_Ys))
5898 PORT_FreeArena(arena, PR_FALSE);
5899 goto no_memory;
5901 ss->sec.peerKey = peerKey;
5902 ss->ssl3.hs.ws = wait_cert_request;
5903 return SECSuccess;
5906 #ifdef NSS_ENABLE_ECC
5907 case kt_ecdh:
5908 rv = ssl3_HandleECDHServerKeyExchange(ss, b, length);
5909 return rv;
5910 #endif /* NSS_ENABLE_ECC */
5912 default:
5913 desc = handshake_failure;
5914 errCode = SEC_ERROR_UNSUPPORTED_KEYALG;
5915 break; /* goto alert_loser; */
5918 alert_loser:
5919 (void)SSL3_SendAlert(ss, alert_fatal, desc);
5920 loser:
5921 PORT_SetError( errCode );
5922 return SECFailure;
5924 no_memory: /* no-memory error has already been set. */
5925 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
5926 return SECFailure;
5930 typedef struct dnameNode {
5931 struct dnameNode *next;
5932 SECItem name;
5933 } dnameNode;
5935 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
5936 * ssl3 Certificate Request message.
5937 * Caller must hold Handshake and RecvBuf locks.
5939 static SECStatus
5940 ssl3_HandleCertificateRequest(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
5942 PRArenaPool * arena = NULL;
5943 dnameNode * node;
5944 PRInt32 remaining;
5945 PRBool isTLS = PR_FALSE;
5946 int i;
5947 int errCode = SSL_ERROR_RX_MALFORMED_CERT_REQUEST;
5948 int nnames = 0;
5949 SECStatus rv;
5950 SSL3AlertDescription desc = illegal_parameter;
5951 SECItem cert_types = {siBuffer, NULL, 0};
5952 CERTDistNames ca_list;
5953 #ifdef NSS_PLATFORM_CLIENT_AUTH
5954 CERTCertList * platform_cert_list = NULL;
5955 CERTCertListNode * certNode = NULL;
5956 #endif /* NSS_PLATFORM_CLIENT_AUTH */
5958 SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_request handshake",
5959 SSL_GETPID(), ss->fd));
5960 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
5961 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
5963 if (ss->ssl3.hs.ws != wait_cert_request &&
5964 ss->ssl3.hs.ws != wait_server_key) {
5965 desc = unexpected_message;
5966 errCode = SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST;
5967 goto alert_loser;
5970 PORT_Assert(ss->ssl3.clientCertChain == NULL);
5971 PORT_Assert(ss->ssl3.clientCertificate == NULL);
5972 PORT_Assert(ss->ssl3.clientPrivateKey == NULL);
5973 PORT_Assert(ss->ssl3.platformClientKey == (PlatformKey)NULL);
5975 isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
5976 rv = ssl3_ConsumeHandshakeVariable(ss, &cert_types, 1, &b, &length);
5977 if (rv != SECSuccess)
5978 goto loser; /* malformed, alert has been sent */
5980 PORT_Assert(!ss->requestedCertTypes);
5981 ss->requestedCertTypes = &cert_types;
5983 arena = ca_list.arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
5984 if (arena == NULL)
5985 goto no_mem;
5987 remaining = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
5988 if (remaining < 0)
5989 goto loser; /* malformed, alert has been sent */
5991 if ((PRUint32)remaining > length)
5992 goto alert_loser;
5994 ca_list.head = node = PORT_ArenaZNew(arena, dnameNode);
5995 if (node == NULL)
5996 goto no_mem;
5998 while (remaining > 0) {
5999 PRInt32 len;
6001 if (remaining < 2)
6002 goto alert_loser; /* malformed */
6004 node->name.len = len = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
6005 if (len <= 0)
6006 goto loser; /* malformed, alert has been sent */
6008 remaining -= 2;
6009 if (remaining < len)
6010 goto alert_loser; /* malformed */
6012 node->name.data = b;
6013 b += len;
6014 length -= len;
6015 remaining -= len;
6016 nnames++;
6017 if (remaining <= 0)
6018 break; /* success */
6020 node->next = PORT_ArenaZNew(arena, dnameNode);
6021 node = node->next;
6022 if (node == NULL)
6023 goto no_mem;
6026 ca_list.nnames = nnames;
6027 ca_list.names = PORT_ArenaNewArray(arena, SECItem, nnames);
6028 if (nnames > 0 && ca_list.names == NULL)
6029 goto no_mem;
6031 for(i = 0, node = (dnameNode*)ca_list.head;
6032 i < nnames;
6033 i++, node = node->next) {
6034 ca_list.names[i] = node->name;
6037 if (length != 0)
6038 goto alert_loser; /* malformed */
6040 desc = no_certificate;
6041 ss->ssl3.hs.ws = wait_hello_done;
6043 #ifdef NSS_PLATFORM_CLIENT_AUTH
6044 if (ss->getPlatformClientAuthData != NULL) {
6045 /* XXX Should pass cert_types in this call!! */
6046 rv = (SECStatus)(*ss->getPlatformClientAuthData)(
6047 ss->getPlatformClientAuthDataArg,
6048 ss->fd, &ca_list,
6049 &platform_cert_list,
6050 (void**)&ss->ssl3.platformClientKey,
6051 &ss->ssl3.clientCertificate,
6052 &ss->ssl3.clientPrivateKey);
6053 } else
6054 #endif
6055 if (ss->getClientAuthData == NULL) {
6056 rv = SECFailure; /* force it to send a no_certificate alert */
6057 } else {
6058 /* XXX Should pass cert_types in this call!! */
6059 rv = (SECStatus)(*ss->getClientAuthData)(ss->getClientAuthDataArg,
6060 ss->fd, &ca_list,
6061 &ss->ssl3.clientCertificate,
6062 &ss->ssl3.clientPrivateKey);
6065 switch (rv) {
6066 case SECWouldBlock: /* getClientAuthData has put up a dialog box. */
6067 ssl3_SetAlwaysBlock(ss);
6068 break; /* not an error */
6070 case SECSuccess:
6071 #ifdef NSS_PLATFORM_CLIENT_AUTH
6072 if (!platform_cert_list || CERT_LIST_EMPTY(platform_cert_list) ||
6073 !ss->ssl3.platformClientKey) {
6074 if (platform_cert_list) {
6075 CERT_DestroyCertList(platform_cert_list);
6076 platform_cert_list = NULL;
6078 if (ss->ssl3.platformClientKey) {
6079 ssl_FreePlatformKey(ss->ssl3.platformClientKey);
6080 ss->ssl3.platformClientKey = (PlatformKey)NULL;
6082 /* Fall through to NSS client auth check */
6083 } else {
6084 certNode = CERT_LIST_HEAD(platform_cert_list);
6085 ss->ssl3.clientCertificate = CERT_DupCertificate(certNode->cert);
6087 /* Setting ssl3.clientCertChain non-NULL will cause
6088 * ssl3_HandleServerHelloDone to call SendCertificate.
6089 * Note: clientCertChain should include the EE cert as
6090 * clientCertificate is ignored during the actual sending
6092 ss->ssl3.clientCertChain =
6093 hack_NewCertificateListFromCertList(platform_cert_list);
6094 CERT_DestroyCertList(platform_cert_list);
6095 platform_cert_list = NULL;
6096 if (ss->ssl3.clientCertChain == NULL) {
6097 if (ss->ssl3.clientCertificate != NULL) {
6098 CERT_DestroyCertificate(ss->ssl3.clientCertificate);
6099 ss->ssl3.clientCertificate = NULL;
6101 if (ss->ssl3.platformClientKey) {
6102 ssl_FreePlatformKey(ss->ssl3.platformClientKey);
6103 ss->ssl3.platformClientKey = (PlatformKey)NULL;
6105 goto send_no_certificate;
6107 break; /* not an error */
6109 #endif /* NSS_PLATFORM_CLIENT_AUTH */
6110 /* check what the callback function returned */
6111 if ((!ss->ssl3.clientCertificate) || (!ss->ssl3.clientPrivateKey)) {
6112 /* we are missing either the key or cert */
6113 if (ss->ssl3.clientCertificate) {
6114 /* got a cert, but no key - free it */
6115 CERT_DestroyCertificate(ss->ssl3.clientCertificate);
6116 ss->ssl3.clientCertificate = NULL;
6118 if (ss->ssl3.clientPrivateKey) {
6119 /* got a key, but no cert - free it */
6120 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
6121 ss->ssl3.clientPrivateKey = NULL;
6123 goto send_no_certificate;
6125 /* Setting ssl3.clientCertChain non-NULL will cause
6126 * ssl3_HandleServerHelloDone to call SendCertificate.
6128 ss->ssl3.clientCertChain = CERT_CertChainFromCert(
6129 ss->ssl3.clientCertificate,
6130 certUsageSSLClient, PR_FALSE);
6131 if (ss->ssl3.clientCertChain == NULL) {
6132 if (ss->ssl3.clientCertificate != NULL) {
6133 CERT_DestroyCertificate(ss->ssl3.clientCertificate);
6134 ss->ssl3.clientCertificate = NULL;
6136 if (ss->ssl3.clientPrivateKey != NULL) {
6137 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
6138 ss->ssl3.clientPrivateKey = NULL;
6140 goto send_no_certificate;
6142 break; /* not an error */
6144 case SECFailure:
6145 default:
6146 send_no_certificate:
6147 if (isTLS) {
6148 ss->ssl3.sendEmptyCert = PR_TRUE;
6149 } else {
6150 (void)SSL3_SendAlert(ss, alert_warning, no_certificate);
6152 rv = SECSuccess;
6153 break;
6155 goto done;
6157 no_mem:
6158 rv = SECFailure;
6159 PORT_SetError(SEC_ERROR_NO_MEMORY);
6160 goto done;
6162 alert_loser:
6163 if (isTLS && desc == illegal_parameter)
6164 desc = decode_error;
6165 (void)SSL3_SendAlert(ss, alert_fatal, desc);
6166 loser:
6167 PORT_SetError(errCode);
6168 rv = SECFailure;
6169 done:
6170 ss->requestedCertTypes = NULL;
6171 if (arena != NULL)
6172 PORT_FreeArena(arena, PR_FALSE);
6173 #ifdef NSS_PLATFORM_CLIENT_AUTH
6174 if (platform_cert_list)
6175 CERT_DestroyCertList(platform_cert_list);
6176 #endif
6177 return rv;
6181 * attempt to restart the handshake after asynchronously handling
6182 * a request for the client's certificate.
6184 * inputs:
6185 * cert Client cert chosen by application.
6186 * Note: ssl takes this reference, and does not bump the
6187 * reference count. The caller should drop its reference
6188 * without calling CERT_DestroyCert after calling this function.
6190 * key Private key associated with cert. This function takes
6191 * ownership of the private key, so the caller should drop its
6192 * reference without destroying the private key after this
6193 * function returns.
6195 * certChain DER-encoded certs, client cert and its signers.
6196 * Note: ssl takes this reference, and does not copy the chain.
6197 * The caller should drop its reference without destroying the
6198 * chain. SSL will free the chain when it is done with it.
6200 * Return value: XXX
6202 * XXX This code only works on the initial handshake on a connection, XXX
6203 * It does not work on a subsequent handshake (redo).
6205 * Caller holds 1stHandshakeLock.
6207 SECStatus
6208 ssl3_RestartHandshakeAfterCertReq(sslSocket * ss,
6209 CERTCertificate * cert,
6210 SECKEYPrivateKey * key,
6211 CERTCertificateList *certChain)
6213 SECStatus rv = SECSuccess;
6215 /* XXX This code only works on the initial handshake on a connection,
6216 ** XXX It does not work on a subsequent handshake (redo).
6218 if (ss->handshake != 0) {
6219 ss->handshake = ssl_GatherRecord1stHandshake;
6220 ss->ssl3.clientCertificate = cert;
6221 ss->ssl3.clientPrivateKey = key;
6222 ss->ssl3.clientCertChain = certChain;
6223 if (!cert || !key || !certChain) {
6224 /* we are missing the key, cert, or cert chain */
6225 if (ss->ssl3.clientCertificate) {
6226 CERT_DestroyCertificate(ss->ssl3.clientCertificate);
6227 ss->ssl3.clientCertificate = NULL;
6229 if (ss->ssl3.clientPrivateKey) {
6230 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
6231 ss->ssl3.clientPrivateKey = NULL;
6233 if (ss->ssl3.clientCertChain != NULL) {
6234 CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
6235 ss->ssl3.clientCertChain = NULL;
6237 if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0) {
6238 ss->ssl3.sendEmptyCert = PR_TRUE;
6239 } else {
6240 (void)SSL3_SendAlert(ss, alert_warning, no_certificate);
6243 } else {
6244 if (cert) {
6245 CERT_DestroyCertificate(cert);
6247 if (key) {
6248 SECKEY_DestroyPrivateKey(key);
6250 if (certChain) {
6251 CERT_DestroyCertificateList(certChain);
6253 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
6254 rv = SECFailure;
6256 return rv;
6259 PRBool
6260 ssl3_CanFalseStart(sslSocket *ss) {
6261 PRBool rv;
6263 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
6265 /* XXX: does not take into account whether we are waiting for
6266 * SSL_AuthCertificateComplete or SSL_RestartHandshakeAfterCertReq. If/when
6267 * that is done, this function could return different results each time it
6268 * would be called.
6271 ssl_GetSpecReadLock(ss);
6272 rv = ss->opt.enableFalseStart &&
6273 !ss->sec.isServer &&
6274 !ss->ssl3.hs.isResuming &&
6275 ss->ssl3.cwSpec &&
6277 /* An attacker can control the selected ciphersuite so we only wish to
6278 * do False Start in the case that the selected ciphersuite is
6279 * sufficiently strong that the attack can gain no advantage.
6280 * Therefore we require an 80-bit cipher and a forward-secret key
6281 * exchange. */
6282 ss->ssl3.cwSpec->cipher_def->secret_key_size >= 10 &&
6283 (ss->ssl3.hs.kea_def->kea == kea_dhe_dss ||
6284 ss->ssl3.hs.kea_def->kea == kea_dhe_rsa ||
6285 ss->ssl3.hs.kea_def->kea == kea_ecdhe_ecdsa ||
6286 ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa);
6287 ssl_ReleaseSpecReadLock(ss);
6288 return rv;
6291 static SECStatus ssl3_SendClientSecondRound(sslSocket *ss);
6293 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
6294 * ssl3 Server Hello Done message.
6295 * Caller must hold Handshake and RecvBuf locks.
6297 static SECStatus
6298 ssl3_HandleServerHelloDone(sslSocket *ss)
6300 SECStatus rv;
6301 SSL3WaitState ws = ss->ssl3.hs.ws;
6303 SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello_done handshake",
6304 SSL_GETPID(), ss->fd));
6305 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
6306 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
6308 if (ws != wait_hello_done &&
6309 ws != wait_server_cert &&
6310 ws != wait_server_key &&
6311 ws != wait_cert_request) {
6312 SSL3_SendAlert(ss, alert_fatal, unexpected_message);
6313 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE);
6314 return SECFailure;
6317 rv = ssl3_SendClientSecondRound(ss);
6319 return rv;
6322 /* Called from ssl3_HandleServerHelloDone and ssl3_AuthCertificateComplete.
6324 * Caller must hold Handshake and RecvBuf locks.
6326 static SECStatus
6327 ssl3_SendClientSecondRound(sslSocket *ss)
6329 SECStatus rv;
6330 PRBool sendClientCert;
6332 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
6333 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
6335 sendClientCert = !ss->ssl3.sendEmptyCert &&
6336 ss->ssl3.clientCertChain != NULL &&
6337 (ss->ssl3.platformClientKey ||
6338 ss->ssl3.clientPrivateKey != NULL);
6340 /* We must wait for the server's certificate to be authenticated before
6341 * sending the client certificate in order to disclosing the client
6342 * certificate to an attacker that does not have a valid cert for the
6343 * domain we are connecting to.
6345 * XXX: We should do the same for the NPN extension, but for that we
6346 * need an option to give the application the ability to leak the NPN
6347 * information to get better performance.
6349 * During the initial handshake on a connection, we never send/receive
6350 * application data until we have authenticated the server's certificate;
6351 * i.e. we have fully authenticated the handshake before using the cipher
6352 * specs agreed upon for that handshake. During a renegotiation, we may
6353 * continue sending and receiving application data during the handshake
6354 * interleaved with the handshake records. If we were to send the client's
6355 * second round for a renegotiation before the server's certificate was
6356 * authenticated, then the application data sent/received after this point
6357 * would be using cipher spec that hadn't been authenticated. By waiting
6358 * until the server's certificate has been authenticated during
6359 * renegotiations, we ensure that renegotiations have the same property
6360 * as initial handshakes; i.e. we have fully authenticated the handshake
6361 * before using the cipher specs agreed upon for that handshake for
6362 * application data.
6364 if (ss->ssl3.hs.restartTarget) {
6365 PR_NOT_REACHED("unexpected ss->ssl3.hs.restartTarget");
6366 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
6367 return SECFailure;
6369 if (ss->ssl3.hs.authCertificatePending &&
6370 (sendClientCert || ss->ssl3.sendEmptyCert || ss->firstHsDone)) {
6371 ss->ssl3.hs.restartTarget = ssl3_SendClientSecondRound;
6372 return SECWouldBlock;
6375 ssl_GetXmitBufLock(ss); /*******************************/
6377 if (ss->ssl3.sendEmptyCert) {
6378 ss->ssl3.sendEmptyCert = PR_FALSE;
6379 rv = ssl3_SendEmptyCertificate(ss);
6380 /* Don't send verify */
6381 if (rv != SECSuccess) {
6382 goto loser; /* error code is set. */
6384 } else if (sendClientCert) {
6385 rv = ssl3_SendCertificate(ss);
6386 if (rv != SECSuccess) {
6387 goto loser; /* error code is set. */
6391 rv = ssl3_SendClientKeyExchange(ss);
6392 if (rv != SECSuccess) {
6393 goto loser; /* err is set. */
6396 if (sendClientCert) {
6397 rv = ssl3_SendCertificateVerify(ss);
6398 if (rv != SECSuccess) {
6399 goto loser; /* err is set. */
6403 rv = ssl3_SendChangeCipherSpecs(ss);
6404 if (rv != SECSuccess) {
6405 goto loser; /* err code was set. */
6408 /* XXX: If the server's certificate hasn't been authenticated by this
6409 * point, then we may be leaking this NPN message to an attacker.
6411 if (!ss->firstHsDone) {
6412 rv = ssl3_SendNextProto(ss);
6413 if (rv != SECSuccess) {
6414 goto loser; /* err code was set. */
6417 rv = ssl3_SendEncryptedExtensions(ss);
6418 if (rv != SECSuccess) {
6419 goto loser; /* err code was set. */
6422 rv = ssl3_SendFinished(ss, 0);
6423 if (rv != SECSuccess) {
6424 goto loser; /* err code was set. */
6427 ssl_ReleaseXmitBufLock(ss); /*******************************/
6429 if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn))
6430 ss->ssl3.hs.ws = wait_new_session_ticket;
6431 else
6432 ss->ssl3.hs.ws = wait_change_cipher;
6434 /* Do the handshake callback for sslv3 here, if we can false start. */
6435 if (ss->handshakeCallback != NULL && ssl3_CanFalseStart(ss)) {
6436 (ss->handshakeCallback)(ss->fd, ss->handshakeCallbackData);
6439 return SECSuccess;
6441 loser:
6442 ssl_ReleaseXmitBufLock(ss);
6443 return rv;
6447 * Routines used by servers
6449 static SECStatus
6450 ssl3_SendHelloRequest(sslSocket *ss)
6452 SECStatus rv;
6454 SSL_TRC(3, ("%d: SSL3[%d]: send hello_request handshake", SSL_GETPID(),
6455 ss->fd));
6457 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
6458 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
6460 rv = ssl3_AppendHandshakeHeader(ss, hello_request, 0);
6461 if (rv != SECSuccess) {
6462 return rv; /* err set by AppendHandshake */
6464 rv = ssl3_FlushHandshake(ss, 0);
6465 if (rv != SECSuccess) {
6466 return rv; /* error code set by ssl3_FlushHandshake */
6468 ss->ssl3.hs.ws = wait_client_hello;
6469 return SECSuccess;
6473 * Called from:
6474 * ssl3_HandleClientHello()
6476 static SECComparison
6477 ssl3_ServerNameCompare(const SECItem *name1, const SECItem *name2)
6479 if (!name1 != !name2) {
6480 return SECLessThan;
6482 if (!name1) {
6483 return SECEqual;
6485 if (name1->type != name2->type) {
6486 return SECLessThan;
6488 return SECITEM_CompareItem(name1, name2);
6491 /* Sets memory error when returning NULL.
6492 * Called from:
6493 * ssl3_SendClientHello()
6494 * ssl3_HandleServerHello()
6495 * ssl3_HandleClientHello()
6496 * ssl3_HandleV2ClientHello()
6498 sslSessionID *
6499 ssl3_NewSessionID(sslSocket *ss, PRBool is_server)
6501 sslSessionID *sid;
6503 sid = PORT_ZNew(sslSessionID);
6504 if (sid == NULL)
6505 return sid;
6507 if (is_server) {
6508 const SECItem * srvName;
6509 SECStatus rv = SECSuccess;
6511 ssl_GetSpecReadLock(ss); /********************************/
6512 srvName = &ss->ssl3.prSpec->srvVirtName;
6513 if (srvName->len && srvName->data) {
6514 rv = SECITEM_CopyItem(NULL, &sid->u.ssl3.srvName, srvName);
6516 ssl_ReleaseSpecReadLock(ss); /************************************/
6517 if (rv != SECSuccess) {
6518 PORT_Free(sid);
6519 return NULL;
6522 sid->peerID = (ss->peerID == NULL) ? NULL : PORT_Strdup(ss->peerID);
6523 sid->urlSvrName = (ss->url == NULL) ? NULL : PORT_Strdup(ss->url);
6524 sid->addr = ss->sec.ci.peer;
6525 sid->port = ss->sec.ci.port;
6526 sid->references = 1;
6527 sid->cached = never_cached;
6528 sid->version = ss->version;
6530 sid->u.ssl3.keys.resumable = PR_TRUE;
6531 sid->u.ssl3.policy = SSL_ALLOWED;
6532 sid->u.ssl3.clientWriteKey = NULL;
6533 sid->u.ssl3.serverWriteKey = NULL;
6535 if (is_server) {
6536 SECStatus rv;
6537 int pid = SSL_GETPID();
6539 sid->u.ssl3.sessionIDLength = SSL3_SESSIONID_BYTES;
6540 sid->u.ssl3.sessionID[0] = (pid >> 8) & 0xff;
6541 sid->u.ssl3.sessionID[1] = pid & 0xff;
6542 rv = PK11_GenerateRandom(sid->u.ssl3.sessionID + 2,
6543 SSL3_SESSIONID_BYTES -2);
6544 if (rv != SECSuccess) {
6545 ssl_FreeSID(sid);
6546 ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
6547 return NULL;
6550 return sid;
6553 /* Called from: ssl3_HandleClientHello, ssl3_HandleV2ClientHello */
6554 static SECStatus
6555 ssl3_SendServerHelloSequence(sslSocket *ss)
6557 const ssl3KEADef *kea_def;
6558 SECStatus rv;
6560 SSL_TRC(3, ("%d: SSL3[%d]: begin send server_hello sequence",
6561 SSL_GETPID(), ss->fd));
6563 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
6564 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
6566 rv = ssl3_SendServerHello(ss);
6567 if (rv != SECSuccess) {
6568 return rv; /* err code is set. */
6570 rv = ssl3_SendCertificate(ss);
6571 if (rv != SECSuccess) {
6572 return rv; /* error code is set. */
6574 /* We have to do this after the call to ssl3_SendServerHello,
6575 * because kea_def is set up by ssl3_SendServerHello().
6577 kea_def = ss->ssl3.hs.kea_def;
6578 ss->ssl3.hs.usedStepDownKey = PR_FALSE;
6580 if (kea_def->is_limited && kea_def->exchKeyType == kt_rsa) {
6581 /* see if we can legally use the key in the cert. */
6582 int keyLen; /* bytes */
6584 keyLen = PK11_GetPrivateModulusLen(
6585 ss->serverCerts[kea_def->exchKeyType].SERVERKEY);
6587 if (keyLen > 0 &&
6588 keyLen * BPB <= kea_def->key_size_limit ) {
6589 /* XXX AND cert is not signing only!! */
6590 /* just fall through and use it. */
6591 } else if (ss->stepDownKeyPair != NULL) {
6592 ss->ssl3.hs.usedStepDownKey = PR_TRUE;
6593 rv = ssl3_SendServerKeyExchange(ss);
6594 if (rv != SECSuccess) {
6595 return rv; /* err code was set. */
6597 } else {
6598 #ifndef HACKED_EXPORT_SERVER
6599 PORT_SetError(SSL_ERROR_PUB_KEY_SIZE_LIMIT_EXCEEDED);
6600 return rv;
6601 #endif
6603 #ifdef NSS_ENABLE_ECC
6604 } else if ((kea_def->kea == kea_ecdhe_rsa) ||
6605 (kea_def->kea == kea_ecdhe_ecdsa)) {
6606 rv = ssl3_SendServerKeyExchange(ss);
6607 if (rv != SECSuccess) {
6608 return rv; /* err code was set. */
6610 #endif /* NSS_ENABLE_ECC */
6613 if (ss->opt.requestCertificate) {
6614 rv = ssl3_SendCertificateRequest(ss);
6615 if (rv != SECSuccess) {
6616 return rv; /* err code is set. */
6619 rv = ssl3_SendServerHelloDone(ss);
6620 if (rv != SECSuccess) {
6621 return rv; /* err code is set. */
6624 ss->ssl3.hs.ws = (ss->opt.requestCertificate) ? wait_client_cert
6625 : wait_client_key;
6626 return SECSuccess;
6629 /* An empty TLS Renegotiation Info (RI) extension */
6630 static const PRUint8 emptyRIext[5] = {0xff, 0x01, 0x00, 0x01, 0x00};
6632 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
6633 * ssl3 Client Hello message.
6634 * Caller must hold Handshake and RecvBuf locks.
6636 static SECStatus
6637 ssl3_HandleClientHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
6639 sslSessionID * sid = NULL;
6640 PRInt32 tmp;
6641 unsigned int i;
6642 int j;
6643 SECStatus rv;
6644 int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
6645 SSL3AlertDescription desc = illegal_parameter;
6646 SSL3AlertLevel level = alert_fatal;
6647 SSL3ProtocolVersion version;
6648 SECItem sidBytes = {siBuffer, NULL, 0};
6649 SECItem cookieBytes = {siBuffer, NULL, 0};
6650 SECItem suites = {siBuffer, NULL, 0};
6651 SECItem comps = {siBuffer, NULL, 0};
6652 PRBool haveSpecWriteLock = PR_FALSE;
6653 PRBool haveXmitBufLock = PR_FALSE;
6655 SSL_TRC(3, ("%d: SSL3[%d]: handle client_hello handshake",
6656 SSL_GETPID(), ss->fd));
6658 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
6659 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
6661 /* Get peer name of client */
6662 rv = ssl_GetPeerInfo(ss);
6663 if (rv != SECSuccess) {
6664 return rv; /* error code is set. */
6667 /* Clearing the handshake pointers so that ssl_Do1stHandshake won't
6668 * call ssl2_HandleMessage.
6670 * The issue here is that TLS ordinarily starts out in
6671 * ssl2_HandleV3HandshakeRecord() because of the backward-compatibility
6672 * code paths. That function zeroes these next pointers. But with DTLS,
6673 * we don't even try to do the v2 ClientHello so we skip that function
6674 * and need to reset these values here.
6676 if (IS_DTLS(ss)) {
6677 ss->nextHandshake = 0;
6678 ss->securityHandshake = 0;
6681 /* We might be starting session renegotiation in which case we should
6682 * clear previous state.
6684 PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData));
6685 ss->statelessResume = PR_FALSE;
6687 rv = ssl3_InitState(ss);
6688 if (rv != SECSuccess) {
6689 return rv; /* ssl3_InitState has set the error code. */
6692 if ((ss->ssl3.hs.ws != wait_client_hello) &&
6693 (ss->ssl3.hs.ws != idle_handshake)) {
6694 desc = unexpected_message;
6695 errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO;
6696 goto alert_loser;
6698 if (ss->ssl3.hs.ws == idle_handshake &&
6699 ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) {
6700 desc = no_renegotiation;
6701 level = alert_warning;
6702 errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED;
6703 goto alert_loser;
6706 if (IS_DTLS(ss)) {
6707 dtls_RehandshakeCleanup(ss);
6710 tmp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
6711 if (tmp < 0)
6712 goto loser; /* malformed, alert already sent */
6714 /* Translate the version */
6715 if (IS_DTLS(ss)) {
6716 ss->clientHelloVersion = version =
6717 dtls_DTLSVersionToTLSVersion((SSL3ProtocolVersion)tmp);
6718 } else {
6719 ss->clientHelloVersion = version = (SSL3ProtocolVersion)tmp;
6722 rv = ssl3_NegotiateVersion(ss, version, PR_TRUE);
6723 if (rv != SECSuccess) {
6724 desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version
6725 : handshake_failure;
6726 errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
6727 goto alert_loser;
6730 /* grab the client random data. */
6731 rv = ssl3_ConsumeHandshake(
6732 ss, &ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH, &b, &length);
6733 if (rv != SECSuccess) {
6734 goto loser; /* malformed */
6737 /* grab the client's SID, if present. */
6738 rv = ssl3_ConsumeHandshakeVariable(ss, &sidBytes, 1, &b, &length);
6739 if (rv != SECSuccess) {
6740 goto loser; /* malformed */
6743 /* grab the client's cookie, if present. */
6744 if (IS_DTLS(ss)) {
6745 rv = ssl3_ConsumeHandshakeVariable(ss, &cookieBytes, 1, &b, &length);
6746 if (rv != SECSuccess) {
6747 goto loser; /* malformed */
6751 /* grab the list of cipher suites. */
6752 rv = ssl3_ConsumeHandshakeVariable(ss, &suites, 2, &b, &length);
6753 if (rv != SECSuccess) {
6754 goto loser; /* malformed */
6757 /* grab the list of compression methods. */
6758 rv = ssl3_ConsumeHandshakeVariable(ss, &comps, 1, &b, &length);
6759 if (rv != SECSuccess) {
6760 goto loser; /* malformed */
6763 desc = handshake_failure;
6765 /* Handle TLS hello extensions for SSL3 & TLS. We do not know if
6766 * we are restarting a previous session until extensions have been
6767 * parsed, since we might have received a SessionTicket extension.
6768 * Note: we allow extensions even when negotiating SSL3 for the sake
6769 * of interoperability (and backwards compatibility).
6772 if (length) {
6773 /* Get length of hello extensions */
6774 PRInt32 extension_length;
6775 extension_length = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
6776 if (extension_length < 0) {
6777 goto loser; /* alert already sent */
6779 if (extension_length != length) {
6780 ssl3_DecodeError(ss); /* send alert */
6781 goto loser;
6783 rv = ssl3_HandleHelloExtensions(ss, &b, &length);
6784 if (rv != SECSuccess) {
6785 goto loser; /* malformed */
6788 if (!ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
6789 /* If we didn't receive an RI extension, look for the SCSV,
6790 * and if found, treat it just like an empty RI extension
6791 * by processing a local copy of an empty RI extension.
6793 for (i = 0; i + 1 < suites.len; i += 2) {
6794 PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1];
6795 if (suite_i == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) {
6796 SSL3Opaque * b2 = (SSL3Opaque *)emptyRIext;
6797 PRUint32 L2 = sizeof emptyRIext;
6798 (void)ssl3_HandleHelloExtensions(ss, &b2, &L2);
6799 break;
6803 if (ss->firstHsDone &&
6804 (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_REQUIRES_XTN ||
6805 ss->opt.enableRenegotiation == SSL_RENEGOTIATE_TRANSITIONAL) &&
6806 !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
6807 desc = no_renegotiation;
6808 level = alert_warning;
6809 errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED;
6810 goto alert_loser;
6812 if ((ss->opt.requireSafeNegotiation ||
6813 (ss->firstHsDone && ss->peerRequestedProtection)) &&
6814 !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
6815 desc = handshake_failure;
6816 errCode = SSL_ERROR_UNSAFE_NEGOTIATION;
6817 goto alert_loser;
6820 /* We do stateful resumes only if either of the following
6821 * conditions are satisfied: (1) the client does not support the
6822 * session ticket extension, or (2) the client support the session
6823 * ticket extension, but sent an empty ticket.
6825 if (!ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) ||
6826 ss->xtnData.emptySessionTicket) {
6827 if (sidBytes.len > 0 && !ss->opt.noCache) {
6828 SSL_TRC(7, ("%d: SSL3[%d]: server, lookup client session-id for 0x%08x%08x%08x%08x",
6829 SSL_GETPID(), ss->fd, ss->sec.ci.peer.pr_s6_addr32[0],
6830 ss->sec.ci.peer.pr_s6_addr32[1],
6831 ss->sec.ci.peer.pr_s6_addr32[2],
6832 ss->sec.ci.peer.pr_s6_addr32[3]));
6833 if (ssl_sid_lookup) {
6834 sid = (*ssl_sid_lookup)(&ss->sec.ci.peer, sidBytes.data,
6835 sidBytes.len, ss->dbHandle);
6836 } else {
6837 errCode = SSL_ERROR_SERVER_CACHE_NOT_CONFIGURED;
6838 goto loser;
6841 } else if (ss->statelessResume) {
6842 /* Fill in the client's session ID if doing a stateless resume.
6843 * (When doing stateless resumes, server echos client's SessionID.)
6845 sid = ss->sec.ci.sid;
6846 PORT_Assert(sid != NULL); /* Should have already been filled in.*/
6848 if (sidBytes.len > 0 && sidBytes.len <= SSL3_SESSIONID_BYTES) {
6849 sid->u.ssl3.sessionIDLength = sidBytes.len;
6850 PORT_Memcpy(sid->u.ssl3.sessionID, sidBytes.data,
6851 sidBytes.len);
6852 sid->u.ssl3.sessionIDLength = sidBytes.len;
6853 } else {
6854 sid->u.ssl3.sessionIDLength = 0;
6856 ss->sec.ci.sid = NULL;
6859 /* We only send a session ticket extension if the client supports
6860 * the extension and we are unable to do either a stateful or
6861 * stateless resume.
6863 * TODO: send a session ticket if performing a stateful
6864 * resumption. (As per RFC4507, a server may issue a session
6865 * ticket while doing a (stateless or stateful) session resume,
6866 * but OpenSSL-0.9.8g does not accept session tickets while
6867 * resuming.)
6869 if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) && sid == NULL) {
6870 ssl3_RegisterServerHelloExtensionSender(ss,
6871 ssl_session_ticket_xtn, ssl3_SendSessionTicketXtn);
6874 if (sid != NULL) {
6875 /* We've found a session cache entry for this client.
6876 * Now, if we're going to require a client-auth cert,
6877 * and we don't already have this client's cert in the session cache,
6878 * and this is the first handshake on this connection (not a redo),
6879 * then drop this old cache entry and start a new session.
6881 if ((sid->peerCert == NULL) && ss->opt.requestCertificate &&
6882 ((ss->opt.requireCertificate == SSL_REQUIRE_ALWAYS) ||
6883 (ss->opt.requireCertificate == SSL_REQUIRE_NO_ERROR) ||
6884 ((ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE)
6885 && !ss->firstHsDone))) {
6887 SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_not_ok );
6888 if (ss->sec.uncache)
6889 ss->sec.uncache(sid);
6890 ssl_FreeSID(sid);
6891 sid = NULL;
6895 #ifdef NSS_ENABLE_ECC
6896 /* Disable any ECC cipher suites for which we have no cert. */
6897 ssl3_FilterECCipherSuitesByServerCerts(ss);
6898 #endif
6900 if (IS_DTLS(ss)) {
6901 ssl3_DisableNonDTLSSuites(ss);
6904 #ifdef PARANOID
6905 /* Look for a matching cipher suite. */
6906 j = ssl3_config_match_init(ss);
6907 if (j <= 0) { /* no ciphers are working/supported by PK11 */
6908 errCode = PORT_GetError(); /* error code is already set. */
6909 goto alert_loser;
6911 #endif
6913 /* If we already have a session for this client, be sure to pick the
6914 ** same cipher suite and compression method we picked before.
6915 ** This is not a loop, despite appearances.
6917 if (sid) do {
6918 ssl3CipherSuiteCfg *suite;
6920 /* Check that the cached compression method is still enabled. */
6921 if (!compressionEnabled(ss, sid->u.ssl3.compression))
6922 break;
6924 /* Check that the cached compression method is in the client's list */
6925 for (i = 0; i < comps.len; i++) {
6926 if (comps.data[i] == sid->u.ssl3.compression)
6927 break;
6929 if (i == comps.len)
6930 break;
6932 suite = ss->cipherSuites;
6933 /* Find the entry for the cipher suite used in the cached session. */
6934 for (j = ssl_V3_SUITES_IMPLEMENTED; j > 0; --j, ++suite) {
6935 if (suite->cipher_suite == sid->u.ssl3.cipherSuite)
6936 break;
6938 PORT_Assert(j > 0);
6939 if (j <= 0)
6940 break;
6941 #ifdef PARANOID
6942 /* Double check that the cached cipher suite is still enabled,
6943 * implemented, and allowed by policy. Might have been disabled.
6944 * The product policy won't change during the process lifetime.
6945 * Implemented ("isPresent") shouldn't change for servers.
6947 if (!config_match(suite, ss->ssl3.policy, PR_TRUE))
6948 break;
6949 #else
6950 if (!suite->enabled)
6951 break;
6952 #endif
6953 /* Double check that the cached cipher suite is in the client's list */
6954 for (i = 0; i + 1 < suites.len; i += 2) {
6955 PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1];
6956 if (suite_i == suite->cipher_suite) {
6957 ss->ssl3.hs.cipher_suite = suite->cipher_suite;
6958 ss->ssl3.hs.suite_def =
6959 ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite);
6961 /* Use the cached compression method. */
6962 ss->ssl3.hs.compression = sid->u.ssl3.compression;
6963 goto compression_found;
6966 } while (0);
6968 /* START A NEW SESSION */
6970 #ifndef PARANOID
6971 /* Look for a matching cipher suite. */
6972 j = ssl3_config_match_init(ss);
6973 if (j <= 0) { /* no ciphers are working/supported by PK11 */
6974 errCode = PORT_GetError(); /* error code is already set. */
6975 goto alert_loser;
6977 #endif
6979 /* Select a cipher suite.
6981 ** NOTE: This suite selection algorithm should be the same as the one in
6982 ** ssl3_HandleV2ClientHello().
6984 ** If TLS 1.0 is enabled, we could handle the case where the client
6985 ** offered TLS 1.1 but offered only export cipher suites by choosing TLS
6986 ** 1.0 and selecting one of those export cipher suites. However, a secure
6987 ** TLS 1.1 client should not have export cipher suites enabled at all,
6988 ** and a TLS 1.1 client should definitely not be offering *only* export
6989 ** cipher suites. Therefore, we refuse to negotiate export cipher suites
6990 ** with any client that indicates support for TLS 1.1 or higher when we
6991 ** (the server) have TLS 1.1 support enabled.
6993 for (j = 0; j < ssl_V3_SUITES_IMPLEMENTED; j++) {
6994 ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j];
6995 if (!config_match(suite, ss->ssl3.policy, PR_TRUE) ||
6996 !ssl3_CipherSuiteAllowedForVersion(suite->cipher_suite,
6997 ss->version)) {
6998 continue;
7000 for (i = 0; i + 1 < suites.len; i += 2) {
7001 PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1];
7002 if (suite_i == suite->cipher_suite) {
7003 ss->ssl3.hs.cipher_suite = suite->cipher_suite;
7004 ss->ssl3.hs.suite_def =
7005 ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite);
7006 goto suite_found;
7010 errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
7011 goto alert_loser;
7013 suite_found:
7014 /* Look for a matching compression algorithm. */
7015 for (i = 0; i < comps.len; i++) {
7016 if (!compressionEnabled(ss, comps.data[i]))
7017 continue;
7018 for (j = 0; j < compressionMethodsCount; j++) {
7019 if (comps.data[i] == compressions[j]) {
7020 ss->ssl3.hs.compression =
7021 (SSLCompressionMethod)compressions[j];
7022 goto compression_found;
7026 errCode = SSL_ERROR_NO_COMPRESSION_OVERLAP;
7027 /* null compression must be supported */
7028 goto alert_loser;
7030 compression_found:
7031 suites.data = NULL;
7032 comps.data = NULL;
7034 ss->sec.send = ssl3_SendApplicationData;
7036 /* If there are any failures while processing the old sid,
7037 * we don't consider them to be errors. Instead, We just behave
7038 * as if the client had sent us no sid to begin with, and make a new one.
7040 if (sid != NULL) do {
7041 ssl3CipherSpec *pwSpec;
7042 SECItem wrappedMS; /* wrapped key */
7044 if (sid->version != ss->version ||
7045 sid->u.ssl3.cipherSuite != ss->ssl3.hs.cipher_suite ||
7046 sid->u.ssl3.compression != ss->ssl3.hs.compression) {
7047 break; /* not an error */
7050 if (ss->sec.ci.sid) {
7051 if (ss->sec.uncache)
7052 ss->sec.uncache(ss->sec.ci.sid);
7053 PORT_Assert(ss->sec.ci.sid != sid); /* should be impossible, but ... */
7054 if (ss->sec.ci.sid != sid) {
7055 ssl_FreeSID(ss->sec.ci.sid);
7057 ss->sec.ci.sid = NULL;
7059 /* we need to resurrect the master secret.... */
7061 ssl_GetSpecWriteLock(ss); haveSpecWriteLock = PR_TRUE;
7062 pwSpec = ss->ssl3.pwSpec;
7063 if (sid->u.ssl3.keys.msIsWrapped) {
7064 PK11SymKey * wrapKey; /* wrapping key */
7065 CK_FLAGS keyFlags = 0;
7066 #ifndef NO_PKCS11_BYPASS
7067 if (ss->opt.bypassPKCS11) {
7068 /* we cannot restart a non-bypass session in a
7069 ** bypass socket.
7071 break;
7073 #endif
7075 wrapKey = getWrappingKey(ss, NULL, sid->u.ssl3.exchKeyType,
7076 sid->u.ssl3.masterWrapMech,
7077 ss->pkcs11PinArg);
7078 if (!wrapKey) {
7079 /* we have a SID cache entry, but no wrapping key for it??? */
7080 break;
7083 if (ss->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */
7084 keyFlags = CKF_SIGN | CKF_VERIFY;
7087 wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
7088 wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len;
7090 /* unwrap the master secret. */
7091 pwSpec->master_secret =
7092 PK11_UnwrapSymKeyWithFlags(wrapKey, sid->u.ssl3.masterWrapMech,
7093 NULL, &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE,
7094 CKA_DERIVE, sizeof(SSL3MasterSecret), keyFlags);
7095 PK11_FreeSymKey(wrapKey);
7096 if (pwSpec->master_secret == NULL) {
7097 break; /* not an error */
7099 #ifndef NO_PKCS11_BYPASS
7100 } else if (ss->opt.bypassPKCS11) {
7101 wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
7102 wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len;
7103 memcpy(pwSpec->raw_master_secret, wrappedMS.data, wrappedMS.len);
7104 pwSpec->msItem.data = pwSpec->raw_master_secret;
7105 pwSpec->msItem.len = wrappedMS.len;
7106 #endif
7107 } else {
7108 /* We CAN restart a bypass session in a non-bypass socket. */
7109 /* need to import the raw master secret to session object */
7110 PK11SlotInfo * slot;
7111 wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
7112 wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len;
7113 slot = PK11_GetInternalSlot();
7114 pwSpec->master_secret =
7115 PK11_ImportSymKey(slot, CKM_SSL3_MASTER_KEY_DERIVE,
7116 PK11_OriginUnwrap, CKA_ENCRYPT, &wrappedMS,
7117 NULL);
7118 PK11_FreeSlot(slot);
7119 if (pwSpec->master_secret == NULL) {
7120 break; /* not an error */
7123 ss->sec.ci.sid = sid;
7124 if (sid->peerCert != NULL) {
7125 ss->sec.peerCert = CERT_DupCertificate(sid->peerCert);
7126 ssl3_CopyPeerCertsFromSID(ss, sid);
7130 * Old SID passed all tests, so resume this old session.
7132 * XXX make sure compression still matches
7134 SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_hits );
7135 if (ss->statelessResume)
7136 SSL_AtomicIncrementLong(& ssl3stats.hch_sid_stateless_resumes );
7137 ss->ssl3.hs.isResuming = PR_TRUE;
7139 ss->sec.authAlgorithm = sid->authAlgorithm;
7140 ss->sec.authKeyBits = sid->authKeyBits;
7141 ss->sec.keaType = sid->keaType;
7142 ss->sec.keaKeyBits = sid->keaKeyBits;
7144 /* server sids don't remember the server cert we previously sent,
7145 ** but they do remember the kea type we originally used, so we
7146 ** can locate it again, provided that the current ssl socket
7147 ** has had its server certs configured the same as the previous one.
7149 ss->sec.localCert =
7150 CERT_DupCertificate(ss->serverCerts[sid->keaType].serverCert);
7152 /* Copy cached name in to pending spec */
7153 if (sid != NULL &&
7154 sid->version > SSL_LIBRARY_VERSION_3_0 &&
7155 sid->u.ssl3.srvName.len && sid->u.ssl3.srvName.data) {
7156 /* Set server name from sid */
7157 SECItem *sidName = &sid->u.ssl3.srvName;
7158 SECItem *pwsName = &ss->ssl3.pwSpec->srvVirtName;
7159 if (pwsName->data) {
7160 SECITEM_FreeItem(pwsName, PR_FALSE);
7162 rv = SECITEM_CopyItem(NULL, pwsName, sidName);
7163 if (rv != SECSuccess) {
7164 errCode = PORT_GetError();
7165 desc = internal_error;
7166 goto alert_loser;
7170 /* Clean up sni name array */
7171 if (ssl3_ExtensionNegotiated(ss, ssl_server_name_xtn) &&
7172 ss->xtnData.sniNameArr) {
7173 PORT_Free(ss->xtnData.sniNameArr);
7174 ss->xtnData.sniNameArr = NULL;
7175 ss->xtnData.sniNameArrSize = 0;
7178 ssl_GetXmitBufLock(ss); haveXmitBufLock = PR_TRUE;
7180 rv = ssl3_SendServerHello(ss);
7181 if (rv != SECSuccess) {
7182 errCode = PORT_GetError();
7183 goto loser;
7186 if (haveSpecWriteLock) {
7187 ssl_ReleaseSpecWriteLock(ss);
7188 haveSpecWriteLock = PR_FALSE;
7191 /* NULL value for PMS signifies re-use of the old MS */
7192 rv = ssl3_InitPendingCipherSpec(ss, NULL);
7193 if (rv != SECSuccess) {
7194 errCode = PORT_GetError();
7195 goto loser;
7198 rv = ssl3_SendChangeCipherSpecs(ss);
7199 if (rv != SECSuccess) {
7200 errCode = PORT_GetError();
7201 goto loser;
7203 rv = ssl3_SendFinished(ss, 0);
7204 ss->ssl3.hs.ws = wait_change_cipher;
7205 if (rv != SECSuccess) {
7206 errCode = PORT_GetError();
7207 goto loser;
7210 if (haveXmitBufLock) {
7211 ssl_ReleaseXmitBufLock(ss);
7212 haveXmitBufLock = PR_FALSE;
7215 return SECSuccess;
7216 } while (0);
7218 if (haveSpecWriteLock) {
7219 ssl_ReleaseSpecWriteLock(ss);
7220 haveSpecWriteLock = PR_FALSE;
7223 if (sid) { /* we had a sid, but it's no longer valid, free it */
7224 SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_not_ok );
7225 if (ss->sec.uncache)
7226 ss->sec.uncache(sid);
7227 ssl_FreeSID(sid);
7228 sid = NULL;
7230 SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_misses );
7232 if (ssl3_ExtensionNegotiated(ss, ssl_server_name_xtn)) {
7233 int ret = 0;
7234 if (ss->sniSocketConfig) do { /* not a loop */
7235 ret = SSL_SNI_SEND_ALERT;
7236 /* If extension is negotiated, the len of names should > 0. */
7237 if (ss->xtnData.sniNameArrSize) {
7238 /* Calling client callback to reconfigure the socket. */
7239 ret = (SECStatus)(*ss->sniSocketConfig)(ss->fd,
7240 ss->xtnData.sniNameArr,
7241 ss->xtnData.sniNameArrSize,
7242 ss->sniSocketConfigArg);
7244 if (ret <= SSL_SNI_SEND_ALERT) {
7245 /* Application does not know the name or was not able to
7246 * properly reconfigure the socket. */
7247 errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
7248 desc = unrecognized_name;
7249 break;
7250 } else if (ret == SSL_SNI_CURRENT_CONFIG_IS_USED) {
7251 SECStatus rv = SECSuccess;
7252 SECItem * cwsName, *pwsName;
7254 ssl_GetSpecWriteLock(ss); /*******************************/
7255 pwsName = &ss->ssl3.pwSpec->srvVirtName;
7256 cwsName = &ss->ssl3.cwSpec->srvVirtName;
7257 #ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS
7258 /* not allow name change on the 2d HS */
7259 if (ss->firstHsDone) {
7260 if (ssl3_ServerNameCompare(pwsName, cwsName)) {
7261 ssl_ReleaseSpecWriteLock(ss); /******************/
7262 errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
7263 desc = handshake_failure;
7264 ret = SSL_SNI_SEND_ALERT;
7265 break;
7268 #endif
7269 if (pwsName->data) {
7270 SECITEM_FreeItem(pwsName, PR_FALSE);
7272 if (cwsName->data) {
7273 rv = SECITEM_CopyItem(NULL, pwsName, cwsName);
7275 ssl_ReleaseSpecWriteLock(ss); /**************************/
7276 if (rv != SECSuccess) {
7277 errCode = SSL_ERROR_INTERNAL_ERROR_ALERT;
7278 desc = internal_error;
7279 ret = SSL_SNI_SEND_ALERT;
7280 break;
7282 } else if (ret < ss->xtnData.sniNameArrSize) {
7283 /* Application has configured new socket info. Lets check it
7284 * and save the name. */
7285 SECStatus rv;
7286 SECItem * name = &ss->xtnData.sniNameArr[ret];
7287 int configedCiphers;
7288 SECItem * pwsName;
7290 /* get rid of the old name and save the newly picked. */
7291 /* This code is protected by ssl3HandshakeLock. */
7292 ssl_GetSpecWriteLock(ss); /*******************************/
7293 #ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS
7294 /* not allow name change on the 2d HS */
7295 if (ss->firstHsDone) {
7296 SECItem *cwsName = &ss->ssl3.cwSpec->srvVirtName;
7297 if (ssl3_ServerNameCompare(name, cwsName)) {
7298 ssl_ReleaseSpecWriteLock(ss); /******************/
7299 errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
7300 desc = handshake_failure;
7301 ret = SSL_SNI_SEND_ALERT;
7302 break;
7305 #endif
7306 pwsName = &ss->ssl3.pwSpec->srvVirtName;
7307 if (pwsName->data) {
7308 SECITEM_FreeItem(pwsName, PR_FALSE);
7310 rv = SECITEM_CopyItem(NULL, pwsName, name);
7311 ssl_ReleaseSpecWriteLock(ss); /***************************/
7312 if (rv != SECSuccess) {
7313 errCode = SSL_ERROR_INTERNAL_ERROR_ALERT;
7314 desc = internal_error;
7315 ret = SSL_SNI_SEND_ALERT;
7316 break;
7318 configedCiphers = ssl3_config_match_init(ss);
7319 if (configedCiphers <= 0) {
7320 /* no ciphers are working/supported */
7321 errCode = PORT_GetError();
7322 desc = handshake_failure;
7323 ret = SSL_SNI_SEND_ALERT;
7324 break;
7326 /* Need to tell the client that application has picked
7327 * the name from the offered list and reconfigured the socket.
7329 ssl3_RegisterServerHelloExtensionSender(ss, ssl_server_name_xtn,
7330 ssl3_SendServerNameXtn);
7331 } else {
7332 /* Callback returned index outside of the boundary. */
7333 PORT_Assert(ret < ss->xtnData.sniNameArrSize);
7334 errCode = SSL_ERROR_INTERNAL_ERROR_ALERT;
7335 desc = internal_error;
7336 ret = SSL_SNI_SEND_ALERT;
7337 break;
7339 } while (0);
7340 /* Free sniNameArr. The data that each SECItem in the array
7341 * points into is the data from the input buffer "b". It will
7342 * not be available outside the scope of this or it's child
7343 * functions.*/
7344 if (ss->xtnData.sniNameArr) {
7345 PORT_Free(ss->xtnData.sniNameArr);
7346 ss->xtnData.sniNameArr = NULL;
7347 ss->xtnData.sniNameArrSize = 0;
7349 if (ret <= SSL_SNI_SEND_ALERT) {
7350 /* desc and errCode should be set. */
7351 goto alert_loser;
7354 #ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS
7355 else if (ss->firstHsDone) {
7356 /* Check that we don't have the name is current spec
7357 * if this extension was not negotiated on the 2d hs. */
7358 PRBool passed = PR_TRUE;
7359 ssl_GetSpecReadLock(ss); /*******************************/
7360 if (ss->ssl3.cwSpec->srvVirtName.data) {
7361 passed = PR_FALSE;
7363 ssl_ReleaseSpecReadLock(ss); /***************************/
7364 if (!passed) {
7365 errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
7366 desc = handshake_failure;
7367 goto alert_loser;
7370 #endif
7372 sid = ssl3_NewSessionID(ss, PR_TRUE);
7373 if (sid == NULL) {
7374 errCode = PORT_GetError();
7375 goto loser; /* memory error is set. */
7377 ss->sec.ci.sid = sid;
7379 ss->ssl3.hs.isResuming = PR_FALSE;
7380 ssl_GetXmitBufLock(ss);
7381 rv = ssl3_SendServerHelloSequence(ss);
7382 ssl_ReleaseXmitBufLock(ss);
7383 if (rv != SECSuccess) {
7384 errCode = PORT_GetError();
7385 goto loser;
7388 if (haveXmitBufLock) {
7389 ssl_ReleaseXmitBufLock(ss);
7390 haveXmitBufLock = PR_FALSE;
7393 return SECSuccess;
7395 alert_loser:
7396 if (haveSpecWriteLock) {
7397 ssl_ReleaseSpecWriteLock(ss);
7398 haveSpecWriteLock = PR_FALSE;
7400 (void)SSL3_SendAlert(ss, level, desc);
7401 /* FALLTHRU */
7402 loser:
7403 if (haveSpecWriteLock) {
7404 ssl_ReleaseSpecWriteLock(ss);
7405 haveSpecWriteLock = PR_FALSE;
7408 if (haveXmitBufLock) {
7409 ssl_ReleaseXmitBufLock(ss);
7410 haveXmitBufLock = PR_FALSE;
7413 PORT_SetError(errCode);
7414 return SECFailure;
7418 * ssl3_HandleV2ClientHello is used when a V2 formatted hello comes
7419 * in asking to use the V3 handshake.
7420 * Called from ssl2_HandleClientHelloMessage() in sslcon.c
7422 SECStatus
7423 ssl3_HandleV2ClientHello(sslSocket *ss, unsigned char *buffer, int length)
7425 sslSessionID * sid = NULL;
7426 unsigned char * suites;
7427 unsigned char * random;
7428 SSL3ProtocolVersion version;
7429 SECStatus rv;
7430 int i;
7431 int j;
7432 int sid_length;
7433 int suite_length;
7434 int rand_length;
7435 int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
7436 SSL3AlertDescription desc = handshake_failure;
7438 SSL_TRC(3, ("%d: SSL3[%d]: handle v2 client_hello", SSL_GETPID(), ss->fd));
7440 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
7442 ssl_GetSSL3HandshakeLock(ss);
7444 PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData));
7446 rv = ssl3_InitState(ss);
7447 if (rv != SECSuccess) {
7448 ssl_ReleaseSSL3HandshakeLock(ss);
7449 return rv; /* ssl3_InitState has set the error code. */
7452 if (ss->ssl3.hs.ws != wait_client_hello) {
7453 desc = unexpected_message;
7454 errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO;
7455 goto loser; /* alert_loser */
7458 version = (buffer[1] << 8) | buffer[2];
7459 suite_length = (buffer[3] << 8) | buffer[4];
7460 sid_length = (buffer[5] << 8) | buffer[6];
7461 rand_length = (buffer[7] << 8) | buffer[8];
7462 ss->clientHelloVersion = version;
7464 rv = ssl3_NegotiateVersion(ss, version, PR_TRUE);
7465 if (rv != SECSuccess) {
7466 /* send back which ever alert client will understand. */
7467 desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version : handshake_failure;
7468 errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
7469 goto alert_loser;
7472 /* if we get a non-zero SID, just ignore it. */
7473 if (length !=
7474 SSL_HL_CLIENT_HELLO_HBYTES + suite_length + sid_length + rand_length) {
7475 SSL_DBG(("%d: SSL3[%d]: bad v2 client hello message, len=%d should=%d",
7476 SSL_GETPID(), ss->fd, length,
7477 SSL_HL_CLIENT_HELLO_HBYTES + suite_length + sid_length +
7478 rand_length));
7479 goto loser; /* malformed */ /* alert_loser */
7482 suites = buffer + SSL_HL_CLIENT_HELLO_HBYTES;
7483 random = suites + suite_length + sid_length;
7485 if (rand_length < SSL_MIN_CHALLENGE_BYTES ||
7486 rand_length > SSL_MAX_CHALLENGE_BYTES) {
7487 goto loser; /* malformed */ /* alert_loser */
7490 PORT_Assert(SSL_MAX_CHALLENGE_BYTES == SSL3_RANDOM_LENGTH);
7492 PORT_Memset(&ss->ssl3.hs.client_random, 0, SSL3_RANDOM_LENGTH);
7493 PORT_Memcpy(
7494 &ss->ssl3.hs.client_random.rand[SSL3_RANDOM_LENGTH - rand_length],
7495 random, rand_length);
7497 PRINT_BUF(60, (ss, "client random:", &ss->ssl3.hs.client_random.rand[0],
7498 SSL3_RANDOM_LENGTH));
7499 #ifdef NSS_ENABLE_ECC
7500 /* Disable any ECC cipher suites for which we have no cert. */
7501 ssl3_FilterECCipherSuitesByServerCerts(ss);
7502 #endif
7503 i = ssl3_config_match_init(ss);
7504 if (i <= 0) {
7505 errCode = PORT_GetError(); /* error code is already set. */
7506 goto alert_loser;
7509 /* Select a cipher suite.
7511 ** NOTE: This suite selection algorithm should be the same as the one in
7512 ** ssl3_HandleClientHello().
7514 ** See the comments about export cipher suites in ssl3_HandleClientHello().
7516 for (j = 0; j < ssl_V3_SUITES_IMPLEMENTED; j++) {
7517 ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j];
7518 if (!config_match(suite, ss->ssl3.policy, PR_TRUE) ||
7519 !ssl3_CipherSuiteAllowedForVersion(suite->cipher_suite,
7520 ss->version)) {
7521 continue;
7523 for (i = 0; i+2 < suite_length; i += 3) {
7524 PRUint32 suite_i = (suites[i] << 16)|(suites[i+1] << 8)|suites[i+2];
7525 if (suite_i == suite->cipher_suite) {
7526 ss->ssl3.hs.cipher_suite = suite->cipher_suite;
7527 ss->ssl3.hs.suite_def =
7528 ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite);
7529 goto suite_found;
7533 errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
7534 goto alert_loser;
7536 suite_found:
7538 /* Look for the SCSV, and if found, treat it just like an empty RI
7539 * extension by processing a local copy of an empty RI extension.
7541 for (i = 0; i+2 < suite_length; i += 3) {
7542 PRUint32 suite_i = (suites[i] << 16) | (suites[i+1] << 8) | suites[i+2];
7543 if (suite_i == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) {
7544 SSL3Opaque * b2 = (SSL3Opaque *)emptyRIext;
7545 PRUint32 L2 = sizeof emptyRIext;
7546 (void)ssl3_HandleHelloExtensions(ss, &b2, &L2);
7547 break;
7551 if (ss->opt.requireSafeNegotiation &&
7552 !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
7553 desc = handshake_failure;
7554 errCode = SSL_ERROR_UNSAFE_NEGOTIATION;
7555 goto alert_loser;
7558 ss->ssl3.hs.compression = ssl_compression_null;
7559 ss->sec.send = ssl3_SendApplicationData;
7561 /* we don't even search for a cache hit here. It's just a miss. */
7562 SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_misses );
7563 sid = ssl3_NewSessionID(ss, PR_TRUE);
7564 if (sid == NULL) {
7565 errCode = PORT_GetError();
7566 goto loser; /* memory error is set. */
7568 ss->sec.ci.sid = sid;
7569 /* do not worry about memory leak of sid since it now belongs to ci */
7571 /* We have to update the handshake hashes before we can send stuff */
7572 rv = ssl3_UpdateHandshakeHashes(ss, buffer, length);
7573 if (rv != SECSuccess) {
7574 errCode = PORT_GetError();
7575 goto loser;
7578 ssl_GetXmitBufLock(ss);
7579 rv = ssl3_SendServerHelloSequence(ss);
7580 ssl_ReleaseXmitBufLock(ss);
7581 if (rv != SECSuccess) {
7582 errCode = PORT_GetError();
7583 goto loser;
7586 /* XXX_1 The call stack to here is:
7587 * ssl_Do1stHandshake -> ssl2_HandleClientHelloMessage -> here.
7588 * ssl2_HandleClientHelloMessage returns whatever we return here.
7589 * ssl_Do1stHandshake will continue looping if it gets back either
7590 * SECSuccess or SECWouldBlock.
7591 * SECSuccess is preferable here. See XXX_1 in sslgathr.c.
7593 ssl_ReleaseSSL3HandshakeLock(ss);
7594 return SECSuccess;
7596 alert_loser:
7597 SSL3_SendAlert(ss, alert_fatal, desc);
7598 loser:
7599 ssl_ReleaseSSL3HandshakeLock(ss);
7600 PORT_SetError(errCode);
7601 return SECFailure;
7604 /* The negotiated version number has been already placed in ss->version.
7606 ** Called from: ssl3_HandleClientHello (resuming session),
7607 ** ssl3_SendServerHelloSequence <- ssl3_HandleClientHello (new session),
7608 ** ssl3_SendServerHelloSequence <- ssl3_HandleV2ClientHello (new session)
7610 static SECStatus
7611 ssl3_SendServerHello(sslSocket *ss)
7613 sslSessionID *sid;
7614 SECStatus rv;
7615 PRUint32 maxBytes = 65535;
7616 PRUint32 length;
7617 PRInt32 extensions_len = 0;
7618 SSL3ProtocolVersion version;
7620 SSL_TRC(3, ("%d: SSL3[%d]: send server_hello handshake", SSL_GETPID(),
7621 ss->fd));
7623 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
7624 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
7626 if (!IS_DTLS(ss)) {
7627 PORT_Assert(MSB(ss->version) == MSB(SSL_LIBRARY_VERSION_3_0));
7629 if (MSB(ss->version) != MSB(SSL_LIBRARY_VERSION_3_0)) {
7630 PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
7631 return SECFailure;
7633 } else {
7634 PORT_Assert(MSB(ss->version) == MSB(SSL_LIBRARY_VERSION_DTLS_1_0));
7636 if (MSB(ss->version) != MSB(SSL_LIBRARY_VERSION_DTLS_1_0)) {
7637 PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
7638 return SECFailure;
7642 sid = ss->sec.ci.sid;
7644 extensions_len = ssl3_CallHelloExtensionSenders(ss, PR_FALSE, maxBytes,
7645 &ss->xtnData.serverSenders[0]);
7646 if (extensions_len > 0)
7647 extensions_len += 2; /* Add sizeof total extension length */
7649 length = sizeof(SSL3ProtocolVersion) + SSL3_RANDOM_LENGTH + 1 +
7650 ((sid == NULL) ? 0: sid->u.ssl3.sessionIDLength) +
7651 sizeof(ssl3CipherSuite) + 1 + extensions_len;
7652 rv = ssl3_AppendHandshakeHeader(ss, server_hello, length);
7653 if (rv != SECSuccess) {
7654 return rv; /* err set by AppendHandshake. */
7657 if (IS_DTLS(ss)) {
7658 version = dtls_TLSVersionToDTLSVersion(ss->version);
7659 } else {
7660 version = ss->version;
7663 rv = ssl3_AppendHandshakeNumber(ss, version, 2);
7664 if (rv != SECSuccess) {
7665 return rv; /* err set by AppendHandshake. */
7667 rv = ssl3_GetNewRandom(&ss->ssl3.hs.server_random);
7668 if (rv != SECSuccess) {
7669 ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
7670 return rv;
7672 rv = ssl3_AppendHandshake(
7673 ss, &ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH);
7674 if (rv != SECSuccess) {
7675 return rv; /* err set by AppendHandshake. */
7678 if (sid)
7679 rv = ssl3_AppendHandshakeVariable(
7680 ss, sid->u.ssl3.sessionID, sid->u.ssl3.sessionIDLength, 1);
7681 else
7682 rv = ssl3_AppendHandshakeVariable(ss, NULL, 0, 1);
7683 if (rv != SECSuccess) {
7684 return rv; /* err set by AppendHandshake. */
7687 rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.cipher_suite, 2);
7688 if (rv != SECSuccess) {
7689 return rv; /* err set by AppendHandshake. */
7691 rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.compression, 1);
7692 if (rv != SECSuccess) {
7693 return rv; /* err set by AppendHandshake. */
7695 if (extensions_len) {
7696 PRInt32 sent_len;
7698 extensions_len -= 2;
7699 rv = ssl3_AppendHandshakeNumber(ss, extensions_len, 2);
7700 if (rv != SECSuccess)
7701 return rv; /* err set by ssl3_SetupPendingCipherSpec */
7702 sent_len = ssl3_CallHelloExtensionSenders(ss, PR_TRUE, extensions_len,
7703 &ss->xtnData.serverSenders[0]);
7704 PORT_Assert(sent_len == extensions_len);
7705 if (sent_len != extensions_len) {
7706 if (sent_len >= 0)
7707 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
7708 return SECFailure;
7711 rv = ssl3_SetupPendingCipherSpec(ss);
7712 if (rv != SECSuccess) {
7713 return rv; /* err set by ssl3_SetupPendingCipherSpec */
7716 return SECSuccess;
7720 static SECStatus
7721 ssl3_SendServerKeyExchange(sslSocket *ss)
7723 const ssl3KEADef * kea_def = ss->ssl3.hs.kea_def;
7724 SECStatus rv = SECFailure;
7725 int length;
7726 PRBool isTLS;
7727 SECItem signed_hash = {siBuffer, NULL, 0};
7728 SSL3Hashes hashes;
7729 SECKEYPublicKey * sdPub; /* public key for step-down */
7731 SSL_TRC(3, ("%d: SSL3[%d]: send server_key_exchange handshake",
7732 SSL_GETPID(), ss->fd));
7734 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
7735 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
7737 switch (kea_def->exchKeyType) {
7738 case kt_rsa:
7739 /* Perform SSL Step-Down here. */
7740 sdPub = ss->stepDownKeyPair->pubKey;
7741 PORT_Assert(sdPub != NULL);
7742 if (!sdPub) {
7743 PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
7744 return SECFailure;
7746 rv = ssl3_ComputeExportRSAKeyHash(sdPub->u.rsa.modulus,
7747 sdPub->u.rsa.publicExponent,
7748 &ss->ssl3.hs.client_random,
7749 &ss->ssl3.hs.server_random,
7750 &hashes, ss->opt.bypassPKCS11);
7751 if (rv != SECSuccess) {
7752 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
7753 return rv;
7756 isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
7757 rv = ssl3_SignHashes(&hashes, ss->serverCerts[kt_rsa].SERVERKEY,
7758 &signed_hash, isTLS);
7759 if (rv != SECSuccess) {
7760 goto loser; /* ssl3_SignHashes has set err. */
7762 if (signed_hash.data == NULL) {
7763 /* how can this happen and rv == SECSuccess ?? */
7764 PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
7765 goto loser;
7767 length = 2 + sdPub->u.rsa.modulus.len +
7768 2 + sdPub->u.rsa.publicExponent.len +
7769 2 + signed_hash.len;
7771 rv = ssl3_AppendHandshakeHeader(ss, server_key_exchange, length);
7772 if (rv != SECSuccess) {
7773 goto loser; /* err set by AppendHandshake. */
7776 rv = ssl3_AppendHandshakeVariable(ss, sdPub->u.rsa.modulus.data,
7777 sdPub->u.rsa.modulus.len, 2);
7778 if (rv != SECSuccess) {
7779 goto loser; /* err set by AppendHandshake. */
7782 rv = ssl3_AppendHandshakeVariable(
7783 ss, sdPub->u.rsa.publicExponent.data,
7784 sdPub->u.rsa.publicExponent.len, 2);
7785 if (rv != SECSuccess) {
7786 goto loser; /* err set by AppendHandshake. */
7789 rv = ssl3_AppendHandshakeVariable(ss, signed_hash.data,
7790 signed_hash.len, 2);
7791 if (rv != SECSuccess) {
7792 goto loser; /* err set by AppendHandshake. */
7794 PORT_Free(signed_hash.data);
7795 return SECSuccess;
7797 #ifdef NSS_ENABLE_ECC
7798 case kt_ecdh: {
7799 rv = ssl3_SendECDHServerKeyExchange(ss);
7800 return rv;
7802 #endif /* NSS_ENABLE_ECC */
7804 case kt_dh:
7805 case kt_null:
7806 default:
7807 PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
7808 break;
7810 loser:
7811 if (signed_hash.data != NULL)
7812 PORT_Free(signed_hash.data);
7813 return SECFailure;
7817 static SECStatus
7818 ssl3_SendCertificateRequest(sslSocket *ss)
7820 SECItem * name;
7821 CERTDistNames *ca_list;
7822 const uint8 * certTypes;
7823 SECItem * names = NULL;
7824 SECStatus rv;
7825 int length;
7826 int i;
7827 int calen = 0;
7828 int nnames = 0;
7829 int certTypesLength;
7831 SSL_TRC(3, ("%d: SSL3[%d]: send certificate_request handshake",
7832 SSL_GETPID(), ss->fd));
7834 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
7835 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
7837 /* ssl3.ca_list is initialized to NULL, and never changed. */
7838 ca_list = ss->ssl3.ca_list;
7839 if (!ca_list) {
7840 ca_list = ssl3_server_ca_list;
7843 if (ca_list != NULL) {
7844 names = ca_list->names;
7845 nnames = ca_list->nnames;
7848 for (i = 0, name = names; i < nnames; i++, name++) {
7849 calen += 2 + name->len;
7852 certTypes = certificate_types;
7853 certTypesLength = sizeof certificate_types;
7855 length = 1 + certTypesLength + 2 + calen;
7857 rv = ssl3_AppendHandshakeHeader(ss, certificate_request, length);
7858 if (rv != SECSuccess) {
7859 return rv; /* err set by AppendHandshake. */
7861 rv = ssl3_AppendHandshakeVariable(ss, certTypes, certTypesLength, 1);
7862 if (rv != SECSuccess) {
7863 return rv; /* err set by AppendHandshake. */
7865 rv = ssl3_AppendHandshakeNumber(ss, calen, 2);
7866 if (rv != SECSuccess) {
7867 return rv; /* err set by AppendHandshake. */
7869 for (i = 0, name = names; i < nnames; i++, name++) {
7870 rv = ssl3_AppendHandshakeVariable(ss, name->data, name->len, 2);
7871 if (rv != SECSuccess) {
7872 return rv; /* err set by AppendHandshake. */
7876 return SECSuccess;
7879 static SECStatus
7880 ssl3_SendServerHelloDone(sslSocket *ss)
7882 SECStatus rv;
7884 SSL_TRC(3, ("%d: SSL3[%d]: send server_hello_done handshake",
7885 SSL_GETPID(), ss->fd));
7887 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
7888 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
7890 rv = ssl3_AppendHandshakeHeader(ss, server_hello_done, 0);
7891 if (rv != SECSuccess) {
7892 return rv; /* err set by AppendHandshake. */
7894 rv = ssl3_FlushHandshake(ss, 0);
7895 if (rv != SECSuccess) {
7896 return rv; /* error code set by ssl3_FlushHandshake */
7898 return SECSuccess;
7901 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
7902 * ssl3 Certificate Verify message
7903 * Caller must hold Handshake and RecvBuf locks.
7905 static SECStatus
7906 ssl3_HandleCertificateVerify(sslSocket *ss, SSL3Opaque *b, PRUint32 length,
7907 SSL3Hashes *hashes)
7909 SECItem signed_hash = {siBuffer, NULL, 0};
7910 SECStatus rv;
7911 int errCode = SSL_ERROR_RX_MALFORMED_CERT_VERIFY;
7912 SSL3AlertDescription desc = handshake_failure;
7913 PRBool isTLS;
7915 SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_verify handshake",
7916 SSL_GETPID(), ss->fd));
7917 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
7918 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
7920 if (ss->ssl3.hs.ws != wait_cert_verify || ss->sec.peerCert == NULL) {
7921 desc = unexpected_message;
7922 errCode = SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY;
7923 goto alert_loser;
7926 rv = ssl3_ConsumeHandshakeVariable(ss, &signed_hash, 2, &b, &length);
7927 if (rv != SECSuccess) {
7928 goto loser; /* malformed. */
7931 isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
7933 /* XXX verify that the key & kea match */
7934 rv = ssl3_VerifySignedHashes(hashes, ss->sec.peerCert, &signed_hash,
7935 isTLS, ss->pkcs11PinArg);
7936 if (rv != SECSuccess) {
7937 errCode = PORT_GetError();
7938 desc = isTLS ? decrypt_error : handshake_failure;
7939 goto alert_loser;
7942 signed_hash.data = NULL;
7944 if (length != 0) {
7945 desc = isTLS ? decode_error : illegal_parameter;
7946 goto alert_loser; /* malformed */
7948 ss->ssl3.hs.ws = wait_change_cipher;
7949 return SECSuccess;
7951 alert_loser:
7952 SSL3_SendAlert(ss, alert_fatal, desc);
7953 loser:
7954 PORT_SetError(errCode);
7955 return SECFailure;
7959 /* find a slot that is able to generate a PMS and wrap it with RSA.
7960 * Then generate and return the PMS.
7961 * If the serverKeySlot parameter is non-null, this function will use
7962 * that slot to do the job, otherwise it will find a slot.
7964 * Called from ssl3_DeriveConnectionKeysPKCS11() (above)
7965 * sendRSAClientKeyExchange() (above)
7966 * ssl3_HandleRSAClientKeyExchange() (below)
7967 * Caller must hold the SpecWriteLock, the SSL3HandshakeLock
7969 static PK11SymKey *
7970 ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec,
7971 PK11SlotInfo * serverKeySlot)
7973 PK11SymKey * pms = NULL;
7974 PK11SlotInfo * slot = serverKeySlot;
7975 void * pwArg = ss->pkcs11PinArg;
7976 SECItem param;
7977 CK_VERSION version;
7978 CK_MECHANISM_TYPE mechanism_array[3];
7980 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
7982 if (slot == NULL) {
7983 SSLCipherAlgorithm calg;
7984 /* The specReadLock would suffice here, but we cannot assert on
7985 ** read locks. Also, all the callers who call with a non-null
7986 ** slot already hold the SpecWriteLock.
7988 PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
7989 PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
7991 calg = spec->cipher_def->calg;
7992 PORT_Assert(alg2Mech[calg].calg == calg);
7994 /* First get an appropriate slot. */
7995 mechanism_array[0] = CKM_SSL3_PRE_MASTER_KEY_GEN;
7996 mechanism_array[1] = CKM_RSA_PKCS;
7997 mechanism_array[2] = alg2Mech[calg].cmech;
7999 slot = PK11_GetBestSlotMultiple(mechanism_array, 3, pwArg);
8000 if (slot == NULL) {
8001 /* can't find a slot with all three, find a slot with the minimum */
8002 slot = PK11_GetBestSlotMultiple(mechanism_array, 2, pwArg);
8003 if (slot == NULL) {
8004 PORT_SetError(SSL_ERROR_TOKEN_SLOT_NOT_FOUND);
8005 return pms; /* which is NULL */
8010 /* Generate the pre-master secret ... */
8011 if (IS_DTLS(ss)) {
8012 SSL3ProtocolVersion temp;
8014 temp = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion);
8015 version.major = MSB(temp);
8016 version.minor = LSB(temp);
8017 } else {
8018 version.major = MSB(ss->clientHelloVersion);
8019 version.minor = LSB(ss->clientHelloVersion);
8022 param.data = (unsigned char *)&version;
8023 param.len = sizeof version;
8025 pms = PK11_KeyGen(slot, CKM_SSL3_PRE_MASTER_KEY_GEN, &param, 0, pwArg);
8026 if (!serverKeySlot)
8027 PK11_FreeSlot(slot);
8028 if (pms == NULL) {
8029 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
8031 return pms;
8034 /* Note: The Bleichenbacher attack on PKCS#1 necessitates that we NEVER
8035 * return any indication of failure of the Client Key Exchange message,
8036 * where that failure is caused by the content of the client's message.
8037 * This function must not return SECFailure for any reason that is directly
8038 * or indirectly caused by the content of the client's encrypted PMS.
8039 * We must not send an alert and also not drop the connection.
8040 * Instead, we generate a random PMS. This will cause a failure
8041 * in the processing the finished message, which is exactly where
8042 * the failure must occur.
8044 * Called from ssl3_HandleClientKeyExchange
8046 static SECStatus
8047 ssl3_HandleRSAClientKeyExchange(sslSocket *ss,
8048 SSL3Opaque *b,
8049 PRUint32 length,
8050 SECKEYPrivateKey *serverKey)
8052 PK11SymKey * pms;
8053 #ifndef NO_PKCS11_BYPASS
8054 unsigned char * cr = (unsigned char *)&ss->ssl3.hs.client_random;
8055 unsigned char * sr = (unsigned char *)&ss->ssl3.hs.server_random;
8056 ssl3CipherSpec * pwSpec = ss->ssl3.pwSpec;
8057 unsigned int outLen = 0;
8058 #endif
8059 PRBool isTLS = PR_FALSE;
8060 SECStatus rv;
8061 SECItem enc_pms;
8062 unsigned char rsaPmsBuf[SSL3_RSA_PMS_LENGTH];
8063 SECItem pmsItem = {siBuffer, NULL, 0};
8065 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
8066 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
8068 enc_pms.data = b;
8069 enc_pms.len = length;
8070 pmsItem.data = rsaPmsBuf;
8071 pmsItem.len = sizeof rsaPmsBuf;
8073 if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */
8074 PRInt32 kLen;
8075 kLen = ssl3_ConsumeHandshakeNumber(ss, 2, &enc_pms.data, &enc_pms.len);
8076 if (kLen < 0) {
8077 PORT_SetError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
8078 return SECFailure;
8080 if ((unsigned)kLen < enc_pms.len) {
8081 enc_pms.len = kLen;
8083 isTLS = PR_TRUE;
8084 } else {
8085 isTLS = (PRBool)(ss->ssl3.hs.kea_def->tls_keygen != 0);
8088 #ifndef NO_PKCS11_BYPASS
8089 if (ss->opt.bypassPKCS11) {
8090 /* TRIPLE BYPASS, get PMS directly from RSA decryption.
8091 * Use PK11_PrivDecryptPKCS1 to decrypt the PMS to a buffer,
8092 * then, check for version rollback attack, then
8093 * do the equivalent of ssl3_DeriveMasterSecret, placing the MS in
8094 * pwSpec->msItem. Finally call ssl3_InitPendingCipherSpec with
8095 * ss and NULL, so that it will use the MS we've already derived here.
8098 rv = PK11_PrivDecryptPKCS1(serverKey, rsaPmsBuf, &outLen,
8099 sizeof rsaPmsBuf, enc_pms.data, enc_pms.len);
8100 if (rv != SECSuccess) {
8101 /* triple bypass failed. Let's try for a double bypass. */
8102 goto double_bypass;
8103 } else if (ss->opt.detectRollBack) {
8104 SSL3ProtocolVersion client_version =
8105 (rsaPmsBuf[0] << 8) | rsaPmsBuf[1];
8107 if (IS_DTLS(ss)) {
8108 client_version = dtls_DTLSVersionToTLSVersion(client_version);
8111 if (client_version != ss->clientHelloVersion) {
8112 /* Version roll-back detected. ensure failure. */
8113 rv = PK11_GenerateRandom(rsaPmsBuf, sizeof rsaPmsBuf);
8116 /* have PMS, build MS without PKCS11 */
8117 rv = ssl3_MasterKeyDeriveBypass(pwSpec, cr, sr, &pmsItem, isTLS,
8118 PR_TRUE);
8119 if (rv != SECSuccess) {
8120 pwSpec->msItem.data = pwSpec->raw_master_secret;
8121 pwSpec->msItem.len = SSL3_MASTER_SECRET_LENGTH;
8122 PK11_GenerateRandom(pwSpec->msItem.data, pwSpec->msItem.len);
8124 rv = ssl3_InitPendingCipherSpec(ss, NULL);
8125 } else
8126 #endif
8128 #ifndef NO_PKCS11_BYPASS
8129 double_bypass:
8130 #endif
8132 * unwrap pms out of the incoming buffer
8133 * Note: CKM_SSL3_MASTER_KEY_DERIVE is NOT the mechanism used to do
8134 * the unwrap. Rather, it is the mechanism with which the
8135 * unwrapped pms will be used.
8137 pms = PK11_PubUnwrapSymKey(serverKey, &enc_pms,
8138 CKM_SSL3_MASTER_KEY_DERIVE, CKA_DERIVE, 0);
8139 if (pms != NULL) {
8140 PRINT_BUF(60, (ss, "decrypted premaster secret:",
8141 PK11_GetKeyData(pms)->data,
8142 PK11_GetKeyData(pms)->len));
8143 } else {
8144 /* unwrap failed. Generate a bogus PMS and carry on. */
8145 PK11SlotInfo * slot = PK11_GetSlotFromPrivateKey(serverKey);
8147 ssl_GetSpecWriteLock(ss);
8148 pms = ssl3_GenerateRSAPMS(ss, ss->ssl3.prSpec, slot);
8149 ssl_ReleaseSpecWriteLock(ss);
8150 PK11_FreeSlot(slot);
8153 if (pms == NULL) {
8154 /* last gasp. */
8155 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
8156 return SECFailure;
8159 /* This step will derive the MS from the PMS, among other things. */
8160 rv = ssl3_InitPendingCipherSpec(ss, pms);
8161 PK11_FreeSymKey(pms);
8164 if (rv != SECSuccess) {
8165 SEND_ALERT
8166 return SECFailure; /* error code set by ssl3_InitPendingCipherSpec */
8168 return SECSuccess;
8172 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
8173 * ssl3 ClientKeyExchange message from the remote client
8174 * Caller must hold Handshake and RecvBuf locks.
8176 static SECStatus
8177 ssl3_HandleClientKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
8179 SECKEYPrivateKey *serverKey = NULL;
8180 SECStatus rv;
8181 const ssl3KEADef *kea_def;
8182 ssl3KeyPair *serverKeyPair = NULL;
8183 #ifdef NSS_ENABLE_ECC
8184 SECKEYPublicKey *serverPubKey = NULL;
8185 #endif /* NSS_ENABLE_ECC */
8187 SSL_TRC(3, ("%d: SSL3[%d]: handle client_key_exchange handshake",
8188 SSL_GETPID(), ss->fd));
8190 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
8191 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
8193 if (ss->ssl3.hs.ws != wait_client_key) {
8194 SSL3_SendAlert(ss, alert_fatal, unexpected_message);
8195 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH);
8196 return SECFailure;
8199 kea_def = ss->ssl3.hs.kea_def;
8201 if (ss->ssl3.hs.usedStepDownKey) {
8202 PORT_Assert(kea_def->is_limited /* XXX OR cert is signing only */
8203 && kea_def->exchKeyType == kt_rsa
8204 && ss->stepDownKeyPair != NULL);
8205 if (!kea_def->is_limited ||
8206 kea_def->exchKeyType != kt_rsa ||
8207 ss->stepDownKeyPair == NULL) {
8208 /* shouldn't happen, don't use step down if it does */
8209 goto skip;
8211 serverKeyPair = ss->stepDownKeyPair;
8212 ss->sec.keaKeyBits = EXPORT_RSA_KEY_LENGTH * BPB;
8213 } else
8214 skip:
8215 #ifdef NSS_ENABLE_ECC
8216 /* XXX Using SSLKEAType to index server certifiates
8217 * does not work for (EC)DHE ciphers. Until we have
8218 * an indexing mechanism general enough for all key
8219 * exchange algorithms, we'll need to deal with each
8220 * one seprately.
8222 if ((kea_def->kea == kea_ecdhe_rsa) ||
8223 (kea_def->kea == kea_ecdhe_ecdsa)) {
8224 if (ss->ephemeralECDHKeyPair != NULL) {
8225 serverKeyPair = ss->ephemeralECDHKeyPair;
8226 if (serverKeyPair->pubKey) {
8227 ss->sec.keaKeyBits =
8228 SECKEY_PublicKeyStrengthInBits(serverKeyPair->pubKey);
8231 } else
8232 #endif
8234 sslServerCerts * sc = ss->serverCerts + kea_def->exchKeyType;
8235 serverKeyPair = sc->serverKeyPair;
8236 ss->sec.keaKeyBits = sc->serverKeyBits;
8239 if (serverKeyPair) {
8240 serverKey = serverKeyPair->privKey;
8243 if (serverKey == NULL) {
8244 SEND_ALERT
8245 PORT_SetError(SSL_ERROR_NO_SERVER_KEY_FOR_ALG);
8246 return SECFailure;
8249 ss->sec.keaType = kea_def->exchKeyType;
8251 switch (kea_def->exchKeyType) {
8252 case kt_rsa:
8253 rv = ssl3_HandleRSAClientKeyExchange(ss, b, length, serverKey);
8254 if (rv != SECSuccess) {
8255 SEND_ALERT
8256 return SECFailure; /* error code set */
8258 break;
8261 #ifdef NSS_ENABLE_ECC
8262 case kt_ecdh:
8263 /* XXX We really ought to be able to store multiple
8264 * EC certs (a requirement if we wish to support both
8265 * ECDH-RSA and ECDH-ECDSA key exchanges concurrently).
8266 * When we make that change, we'll need an index other
8267 * than kt_ecdh to pick the right EC certificate.
8269 if (serverKeyPair) {
8270 serverPubKey = serverKeyPair->pubKey;
8272 if (serverPubKey == NULL) {
8273 /* XXX Is this the right error code? */
8274 PORT_SetError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
8275 return SECFailure;
8277 rv = ssl3_HandleECDHClientKeyExchange(ss, b, length,
8278 serverPubKey, serverKey);
8279 if (rv != SECSuccess) {
8280 return SECFailure; /* error code set */
8282 break;
8283 #endif /* NSS_ENABLE_ECC */
8285 default:
8286 (void) ssl3_HandshakeFailure(ss);
8287 PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
8288 return SECFailure;
8290 ss->ssl3.hs.ws = ss->sec.peerCert ? wait_cert_verify : wait_change_cipher;
8291 return SECSuccess;
8295 /* This is TLS's equivalent of sending a no_certificate alert. */
8296 static SECStatus
8297 ssl3_SendEmptyCertificate(sslSocket *ss)
8299 SECStatus rv;
8301 rv = ssl3_AppendHandshakeHeader(ss, certificate, 3);
8302 if (rv == SECSuccess) {
8303 rv = ssl3_AppendHandshakeNumber(ss, 0, 3);
8305 return rv; /* error, if any, set by functions called above. */
8308 SECStatus
8309 ssl3_HandleNewSessionTicket(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
8311 SECStatus rv;
8312 NewSessionTicket session_ticket;
8314 SSL_TRC(3, ("%d: SSL3[%d]: handle session_ticket handshake",
8315 SSL_GETPID(), ss->fd));
8317 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
8318 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
8320 if (ss->ssl3.hs.ws != wait_new_session_ticket) {
8321 SSL3_SendAlert(ss, alert_fatal, unexpected_message);
8322 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET);
8323 return SECFailure;
8326 session_ticket.received_timestamp = ssl_Time();
8327 if (length < 4) {
8328 (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
8329 PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
8330 return SECFailure;
8332 session_ticket.ticket_lifetime_hint =
8333 (PRUint32)ssl3_ConsumeHandshakeNumber(ss, 4, &b, &length);
8335 rv = ssl3_ConsumeHandshakeVariable(ss, &session_ticket.ticket, 2,
8336 &b, &length);
8337 if (length != 0 || rv != SECSuccess) {
8338 (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
8339 PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
8340 return SECFailure; /* malformed */
8343 rv = ssl3_SetSIDSessionTicket(ss->sec.ci.sid, &session_ticket);
8344 if (rv != SECSuccess) {
8345 (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure);
8346 PORT_SetError(SSL_ERROR_INTERNAL_ERROR_ALERT);
8347 return SECFailure;
8349 ss->ssl3.hs.ws = wait_change_cipher;
8350 return SECSuccess;
8353 #ifdef NISCC_TEST
8354 static PRInt32 connNum = 0;
8356 static SECStatus
8357 get_fake_cert(SECItem *pCertItem, int *pIndex)
8359 PRFileDesc *cf;
8360 char * testdir;
8361 char * startat;
8362 char * stopat;
8363 const char *extension;
8364 int fileNum;
8365 PRInt32 numBytes = 0;
8366 PRStatus prStatus;
8367 PRFileInfo info;
8368 char cfn[100];
8370 pCertItem->data = 0;
8371 if ((testdir = PR_GetEnv("NISCC_TEST")) == NULL) {
8372 return SECSuccess;
8374 *pIndex = (NULL != strstr(testdir, "root"));
8375 extension = (strstr(testdir, "simple") ? "" : ".der");
8376 fileNum = PR_ATOMIC_INCREMENT(&connNum) - 1;
8377 if ((startat = PR_GetEnv("START_AT")) != NULL) {
8378 fileNum += atoi(startat);
8380 if ((stopat = PR_GetEnv("STOP_AT")) != NULL &&
8381 fileNum >= atoi(stopat)) {
8382 *pIndex = -1;
8383 return SECSuccess;
8385 sprintf(cfn, "%s/%08d%s", testdir, fileNum, extension);
8386 cf = PR_Open(cfn, PR_RDONLY, 0);
8387 if (!cf) {
8388 goto loser;
8390 prStatus = PR_GetOpenFileInfo(cf, &info);
8391 if (prStatus != PR_SUCCESS) {
8392 PR_Close(cf);
8393 goto loser;
8395 pCertItem = SECITEM_AllocItem(NULL, pCertItem, info.size);
8396 if (pCertItem) {
8397 numBytes = PR_Read(cf, pCertItem->data, info.size);
8399 PR_Close(cf);
8400 if (numBytes != info.size) {
8401 SECITEM_FreeItem(pCertItem, PR_FALSE);
8402 PORT_SetError(SEC_ERROR_IO);
8403 goto loser;
8405 fprintf(stderr, "using %s\n", cfn);
8406 return SECSuccess;
8408 loser:
8409 fprintf(stderr, "failed to use %s\n", cfn);
8410 *pIndex = -1;
8411 return SECFailure;
8413 #endif
8416 * Used by both client and server.
8417 * Called from HandleServerHelloDone and from SendServerHelloSequence.
8419 static SECStatus
8420 ssl3_SendCertificate(sslSocket *ss)
8422 SECStatus rv;
8423 CERTCertificateList *certChain;
8424 int len = 0;
8425 int i;
8426 SSL3KEAType certIndex;
8427 #ifdef NISCC_TEST
8428 SECItem fakeCert;
8429 int ndex = -1;
8430 #endif
8432 SSL_TRC(3, ("%d: SSL3[%d]: send certificate handshake",
8433 SSL_GETPID(), ss->fd));
8435 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
8436 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
8438 if (ss->sec.localCert)
8439 CERT_DestroyCertificate(ss->sec.localCert);
8440 if (ss->sec.isServer) {
8441 sslServerCerts * sc = NULL;
8443 /* XXX SSLKEAType isn't really a good choice for
8444 * indexing certificates (it breaks when we deal
8445 * with (EC)DHE-* cipher suites. This hack ensures
8446 * the RSA cert is picked for (EC)DHE-RSA.
8447 * Revisit this when we add server side support
8448 * for ECDHE-ECDSA or client-side authentication
8449 * using EC certificates.
8451 if ((ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) ||
8452 (ss->ssl3.hs.kea_def->kea == kea_dhe_rsa)) {
8453 certIndex = kt_rsa;
8454 } else {
8455 certIndex = ss->ssl3.hs.kea_def->exchKeyType;
8457 sc = ss->serverCerts + certIndex;
8458 certChain = sc->serverCertChain;
8459 ss->sec.authKeyBits = sc->serverKeyBits;
8460 ss->sec.authAlgorithm = ss->ssl3.hs.kea_def->signKeyType;
8461 ss->sec.localCert = CERT_DupCertificate(sc->serverCert);
8462 } else {
8463 certChain = ss->ssl3.clientCertChain;
8464 ss->sec.localCert = CERT_DupCertificate(ss->ssl3.clientCertificate);
8467 #ifdef NISCC_TEST
8468 rv = get_fake_cert(&fakeCert, &ndex);
8469 #endif
8471 if (certChain) {
8472 for (i = 0; i < certChain->len; i++) {
8473 #ifdef NISCC_TEST
8474 if (fakeCert.len > 0 && i == ndex) {
8475 len += fakeCert.len + 3;
8476 } else {
8477 len += certChain->certs[i].len + 3;
8479 #else
8480 len += certChain->certs[i].len + 3;
8481 #endif
8485 rv = ssl3_AppendHandshakeHeader(ss, certificate, len + 3);
8486 if (rv != SECSuccess) {
8487 return rv; /* err set by AppendHandshake. */
8489 rv = ssl3_AppendHandshakeNumber(ss, len, 3);
8490 if (rv != SECSuccess) {
8491 return rv; /* err set by AppendHandshake. */
8493 if (certChain) {
8494 for (i = 0; i < certChain->len; i++) {
8495 #ifdef NISCC_TEST
8496 if (fakeCert.len > 0 && i == ndex) {
8497 rv = ssl3_AppendHandshakeVariable(ss, fakeCert.data,
8498 fakeCert.len, 3);
8499 SECITEM_FreeItem(&fakeCert, PR_FALSE);
8500 } else {
8501 rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data,
8502 certChain->certs[i].len, 3);
8504 #else
8505 rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data,
8506 certChain->certs[i].len, 3);
8507 #endif
8508 if (rv != SECSuccess) {
8509 return rv; /* err set by AppendHandshake. */
8514 return SECSuccess;
8517 /* This is used to delete the CA certificates in the peer certificate chain
8518 * from the cert database after they've been validated.
8520 static void
8521 ssl3_CleanupPeerCerts(sslSocket *ss)
8523 PRArenaPool * arena = ss->ssl3.peerCertArena;
8524 ssl3CertNode *certs = (ssl3CertNode *)ss->ssl3.peerCertChain;
8526 for (; certs; certs = certs->next) {
8527 CERT_DestroyCertificate(certs->cert);
8529 if (arena) PORT_FreeArena(arena, PR_FALSE);
8530 ss->ssl3.peerCertArena = NULL;
8531 ss->ssl3.peerCertChain = NULL;
8534 static void
8535 ssl3_CopyPeerCertsFromSID(sslSocket *ss, sslSessionID *sid)
8537 PRArenaPool *arena;
8538 ssl3CertNode *lastCert = NULL;
8539 ssl3CertNode *certs = NULL;
8540 int i;
8542 if (!sid->peerCertChain[0])
8543 return;
8544 PORT_Assert(!ss->ssl3.peerCertArena);
8545 PORT_Assert(!ss->ssl3.peerCertChain);
8546 ss->ssl3.peerCertArena = arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
8547 for (i = 0; i < MAX_PEER_CERT_CHAIN_SIZE && sid->peerCertChain[i]; i++) {
8548 ssl3CertNode *c = PORT_ArenaNew(arena, ssl3CertNode);
8549 c->cert = CERT_DupCertificate(sid->peerCertChain[i]);
8550 c->next = NULL;
8551 if (lastCert) {
8552 lastCert->next = c;
8553 } else {
8554 certs = c;
8556 lastCert = c;
8558 ss->ssl3.peerCertChain = certs;
8561 static void
8562 ssl3_CopyPeerCertsToSID(ssl3CertNode *certs, sslSessionID *sid)
8564 int i = 0;
8565 ssl3CertNode *c = certs;
8566 for (; i < MAX_PEER_CERT_CHAIN_SIZE && c; i++, c = c->next) {
8567 PORT_Assert(!sid->peerCertChain[i]);
8568 sid->peerCertChain[i] = CERT_DupCertificate(c->cert);
8572 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
8573 * ssl3 CertificateStatus message.
8574 * Caller must hold Handshake and RecvBuf locks.
8575 * This is always called before ssl3_HandleCertificate, even if the Certificate
8576 * message is sent first.
8578 static SECStatus
8579 ssl3_HandleCertificateStatus(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
8581 PRInt32 status, len;
8582 int errCode;
8583 SSL3AlertDescription desc;
8585 if (!ss->ssl3.hs.may_get_cert_status ||
8586 ss->ssl3.hs.ws != wait_server_cert ||
8587 !ss->ssl3.hs.pending_cert_msg.data ||
8588 ss->ssl3.hs.cert_status.data) {
8589 errCode = SSL_ERROR_RX_UNEXPECTED_CERT_STATUS;
8590 desc = unexpected_message;
8591 goto alert_loser;
8594 /* Consume the CertificateStatusType enum */
8595 status = ssl3_ConsumeHandshakeNumber(ss, 1, &b, &length);
8596 if (status != 1 /* ocsp */) {
8597 goto format_loser;
8600 len = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length);
8601 if (len != length) {
8602 goto format_loser;
8605 if (SECITEM_AllocItem(NULL, &ss->ssl3.hs.cert_status, length) == NULL) {
8606 return SECFailure;
8608 ss->ssl3.hs.cert_status.type = siBuffer;
8609 PORT_Memcpy(ss->ssl3.hs.cert_status.data, b, length);
8611 return SECSuccess;
8613 format_loser:
8614 errCode = SSL_ERROR_BAD_CERT_STATUS_RESPONSE_ALERT;
8615 desc = bad_certificate_status_response;
8617 alert_loser:
8618 (void)SSL3_SendAlert(ss, alert_fatal, desc);
8619 (void)ssl_MapLowLevelError(errCode);
8620 return SECFailure;
8623 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
8624 * ssl3 Certificate message.
8625 * Caller must hold Handshake and RecvBuf locks.
8627 static SECStatus
8628 ssl3_HandleCertificate(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
8630 ssl3CertNode * c;
8631 ssl3CertNode * lastCert = NULL;
8632 PRInt32 remaining = 0;
8633 PRInt32 size;
8634 SECStatus rv;
8635 PRBool isServer = (PRBool)(!!ss->sec.isServer);
8636 PRBool trusted = PR_FALSE;
8637 PRBool isTLS;
8638 SSL3AlertDescription desc;
8639 int errCode = SSL_ERROR_RX_MALFORMED_CERTIFICATE;
8640 SECItem certItem;
8642 SSL_TRC(3, ("%d: SSL3[%d]: handle certificate handshake",
8643 SSL_GETPID(), ss->fd));
8644 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
8645 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
8647 if ((ss->ssl3.hs.ws != wait_server_cert) &&
8648 (ss->ssl3.hs.ws != wait_client_cert)) {
8649 desc = unexpected_message;
8650 errCode = SSL_ERROR_RX_UNEXPECTED_CERTIFICATE;
8651 goto alert_loser;
8654 if (ss->sec.peerCert != NULL) {
8655 if (ss->sec.peerKey) {
8656 SECKEY_DestroyPublicKey(ss->sec.peerKey);
8657 ss->sec.peerKey = NULL;
8659 CERT_DestroyCertificate(ss->sec.peerCert);
8660 ss->sec.peerCert = NULL;
8663 ssl3_CleanupPeerCerts(ss);
8664 isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
8666 /* It is reported that some TLS client sends a Certificate message
8667 ** with a zero-length message body. We'll treat that case like a
8668 ** normal no_certificates message to maximize interoperability.
8670 if (length) {
8671 remaining = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length);
8672 if (remaining < 0)
8673 goto loser; /* fatal alert already sent by ConsumeHandshake. */
8674 if ((PRUint32)remaining > length)
8675 goto decode_loser;
8678 if (!remaining) {
8679 if (!(isTLS && isServer))
8680 goto alert_loser;
8681 /* This is TLS's version of a no_certificate alert. */
8682 /* I'm a server. I've requested a client cert. He hasn't got one. */
8683 rv = ssl3_HandleNoCertificate(ss);
8684 if (rv != SECSuccess) {
8685 errCode = PORT_GetError();
8686 goto loser;
8688 goto server_no_cert;
8691 ss->ssl3.peerCertArena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
8692 if (ss->ssl3.peerCertArena == NULL) {
8693 goto loser; /* don't send alerts on memory errors */
8696 /* First get the peer cert. */
8697 remaining -= 3;
8698 if (remaining < 0)
8699 goto decode_loser;
8701 size = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length);
8702 if (size <= 0)
8703 goto loser; /* fatal alert already sent by ConsumeHandshake. */
8705 if (remaining < size)
8706 goto decode_loser;
8708 certItem.data = b;
8709 certItem.len = size;
8710 b += size;
8711 length -= size;
8712 remaining -= size;
8714 ss->sec.peerCert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL,
8715 PR_FALSE, PR_TRUE);
8716 if (ss->sec.peerCert == NULL) {
8717 /* We should report an alert if the cert was bad, but not if the
8718 * problem was just some local problem, like memory error.
8720 goto ambiguous_err;
8723 /* Now get all of the CA certs. */
8724 while (remaining > 0) {
8725 remaining -= 3;
8726 if (remaining < 0)
8727 goto decode_loser;
8729 size = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length);
8730 if (size <= 0)
8731 goto loser; /* fatal alert already sent by ConsumeHandshake. */
8733 if (remaining < size)
8734 goto decode_loser;
8736 certItem.data = b;
8737 certItem.len = size;
8738 b += size;
8739 length -= size;
8740 remaining -= size;
8742 c = PORT_ArenaNew(ss->ssl3.peerCertArena, ssl3CertNode);
8743 if (c == NULL) {
8744 goto loser; /* don't send alerts on memory errors */
8747 c->cert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL,
8748 PR_FALSE, PR_TRUE);
8749 if (c->cert == NULL) {
8750 goto ambiguous_err;
8753 if (c->cert->trust)
8754 trusted = PR_TRUE;
8756 c->next = NULL;
8757 if (lastCert) {
8758 lastCert->next = c;
8759 } else {
8760 ss->ssl3.peerCertChain = c;
8762 lastCert = c;
8765 if (remaining != 0)
8766 goto decode_loser;
8768 SECKEY_UpdateCertPQG(ss->sec.peerCert);
8770 ss->ssl3.hs.authCertificatePending = PR_FALSE;
8773 * Ask caller-supplied callback function to validate cert chain.
8775 rv = (SECStatus)(*ss->authCertificate)(ss->authCertificateArg, ss->fd,
8776 PR_TRUE, isServer);
8777 if (rv) {
8778 errCode = PORT_GetError();
8779 if (rv != SECWouldBlock) {
8780 if (ss->handleBadCert) {
8781 rv = (*ss->handleBadCert)(ss->badCertArg, ss->fd);
8785 if (rv == SECWouldBlock) {
8786 if (ss->sec.isServer) {
8787 errCode = SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS;
8788 rv = SECFailure;
8789 goto loser;
8792 ss->ssl3.hs.authCertificatePending = PR_TRUE;
8793 rv = SECSuccess;
8795 /* XXX: Async cert validation and False Start don't work together
8796 * safely yet; if we leave False Start enabled, we may end up false
8797 * starting (sending application data) before we
8798 * SSL_AuthCertificateComplete has been called.
8800 ss->opt.enableFalseStart = PR_FALSE;
8803 if (rv != SECSuccess) {
8804 ssl3_SendAlertForCertError(ss, errCode);
8805 goto loser;
8809 ss->sec.ci.sid->peerCert = CERT_DupCertificate(ss->sec.peerCert);
8810 ssl3_CopyPeerCertsToSID(ss->ssl3.peerCertChain, ss->sec.ci.sid);
8812 if (!ss->sec.isServer) {
8813 CERTCertificate *cert = ss->sec.peerCert;
8815 /* set the server authentication and key exchange types and sizes
8816 ** from the value in the cert. If the key exchange key is different,
8817 ** it will get fixed when we handle the server key exchange message.
8819 SECKEYPublicKey * pubKey = CERT_ExtractPublicKey(cert);
8820 ss->sec.authAlgorithm = ss->ssl3.hs.kea_def->signKeyType;
8821 ss->sec.keaType = ss->ssl3.hs.kea_def->exchKeyType;
8822 if (pubKey) {
8823 ss->sec.keaKeyBits = ss->sec.authKeyBits =
8824 SECKEY_PublicKeyStrengthInBits(pubKey);
8825 #ifdef NSS_ENABLE_ECC
8826 if (ss->sec.keaType == kt_ecdh) {
8827 /* Get authKeyBits from signing key.
8828 * XXX The code below uses a quick approximation of
8829 * key size based on cert->signatureWrap.signature.data
8830 * (which contains the DER encoded signature). The field
8831 * cert->signatureWrap.signature.len contains the
8832 * length of the encoded signature in bits.
8834 if (ss->ssl3.hs.kea_def->kea == kea_ecdh_ecdsa) {
8835 ss->sec.authKeyBits =
8836 cert->signatureWrap.signature.data[3]*8;
8837 if (cert->signatureWrap.signature.data[4] == 0x00)
8838 ss->sec.authKeyBits -= 8;
8840 * XXX: if cert is not signed by ecdsa we should
8841 * destroy pubKey and goto bad_cert
8843 } else if (ss->ssl3.hs.kea_def->kea == kea_ecdh_rsa) {
8844 ss->sec.authKeyBits = cert->signatureWrap.signature.len;
8846 * XXX: if cert is not signed by rsa we should
8847 * destroy pubKey and goto bad_cert
8851 #endif /* NSS_ENABLE_ECC */
8852 SECKEY_DestroyPublicKey(pubKey);
8853 pubKey = NULL;
8856 ss->ssl3.hs.ws = wait_cert_request; /* disallow server_key_exchange */
8857 if (ss->ssl3.hs.kea_def->is_limited ||
8858 /* XXX OR server cert is signing only. */
8859 #ifdef NSS_ENABLE_ECC
8860 ss->ssl3.hs.kea_def->kea == kea_ecdhe_ecdsa ||
8861 ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa ||
8862 #endif /* NSS_ENABLE_ECC */
8863 ss->ssl3.hs.kea_def->exchKeyType == kt_dh) {
8864 ss->ssl3.hs.ws = wait_server_key; /* allow server_key_exchange */
8866 } else {
8867 server_no_cert:
8868 ss->ssl3.hs.ws = wait_client_key;
8871 PORT_Assert(rv == SECSuccess);
8872 if (rv != SECSuccess) {
8873 errCode = SEC_ERROR_LIBRARY_FAILURE;
8874 rv = SECFailure;
8875 goto loser;
8878 return rv;
8880 ambiguous_err:
8881 errCode = PORT_GetError();
8882 switch (errCode) {
8883 case PR_OUT_OF_MEMORY_ERROR:
8884 case SEC_ERROR_BAD_DATABASE:
8885 case SEC_ERROR_NO_MEMORY:
8886 if (isTLS) {
8887 desc = internal_error;
8888 goto alert_loser;
8890 goto loser;
8892 ssl3_SendAlertForCertError(ss, errCode);
8893 goto loser;
8895 decode_loser:
8896 desc = isTLS ? decode_error : bad_certificate;
8898 alert_loser:
8899 (void)SSL3_SendAlert(ss, alert_fatal, desc);
8901 loser:
8902 ssl3_CleanupPeerCerts(ss);
8904 if (ss->sec.peerCert != NULL) {
8905 CERT_DestroyCertificate(ss->sec.peerCert);
8906 ss->sec.peerCert = NULL;
8908 (void)ssl_MapLowLevelError(errCode);
8909 return SECFailure;
8912 static SECStatus ssl3_FinishHandshake(sslSocket *ss);
8914 static SECStatus
8915 ssl3_AlwaysFail(sslSocket * ss)
8917 PORT_SetError(PR_INVALID_STATE_ERROR);
8918 return SECFailure;
8921 /* Caller must hold 1stHandshakeLock.
8923 SECStatus
8924 ssl3_AuthCertificateComplete(sslSocket *ss, PRErrorCode error)
8926 SECStatus rv;
8928 PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss));
8930 if (ss->sec.isServer) {
8931 PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS);
8932 return SECFailure;
8935 ssl_GetRecvBufLock(ss);
8936 ssl_GetSSL3HandshakeLock(ss);
8938 if (!ss->ssl3.hs.authCertificatePending) {
8939 PORT_SetError(PR_INVALID_STATE_ERROR);
8940 rv = SECFailure;
8941 goto done;
8944 ss->ssl3.hs.authCertificatePending = PR_FALSE;
8946 if (error != 0) {
8947 ss->ssl3.hs.restartTarget = ssl3_AlwaysFail;
8948 ssl3_SendAlertForCertError(ss, error);
8949 rv = SECSuccess;
8950 } else if (ss->ssl3.hs.restartTarget != NULL) {
8951 sslRestartTarget target = ss->ssl3.hs.restartTarget;
8952 ss->ssl3.hs.restartTarget = NULL;
8953 rv = target(ss);
8954 /* Even if we blocked here, we have accomplished enough to claim
8955 * success. Any remaining work will be taken care of by subsequent
8956 * calls to SSL_ForceHandshake/PR_Send/PR_Read/etc.
8958 if (rv == SECWouldBlock) {
8959 rv = SECSuccess;
8961 } else {
8962 rv = SECSuccess;
8965 done:
8966 ssl_ReleaseSSL3HandshakeLock(ss);
8967 ssl_ReleaseRecvBufLock(ss);
8969 return rv;
8972 static SECStatus
8973 ssl3_ComputeTLSFinished(ssl3CipherSpec *spec,
8974 PRBool isServer,
8975 const SSL3Finished * hashes,
8976 TLSFinished * tlsFinished)
8978 const char * label;
8979 unsigned int len;
8980 SECStatus rv;
8982 label = isServer ? "server finished" : "client finished";
8983 len = 15;
8985 rv = ssl3_TLSPRFWithMasterSecret(spec, label, len, hashes->md5,
8986 sizeof *hashes, tlsFinished->verify_data,
8987 sizeof tlsFinished->verify_data);
8989 return rv;
8992 /* The calling function must acquire and release the appropriate
8993 * lock (e.g., ssl_GetSpecReadLock / ssl_ReleaseSpecReadLock for
8994 * ss->ssl3.crSpec).
8996 SECStatus
8997 ssl3_TLSPRFWithMasterSecret(ssl3CipherSpec *spec, const char *label,
8998 unsigned int labelLen, const unsigned char *val, unsigned int valLen,
8999 unsigned char *out, unsigned int outLen)
9001 SECStatus rv = SECSuccess;
9003 if (spec->master_secret && !spec->bypassCiphers) {
9004 SECItem param = {siBuffer, NULL, 0};
9005 PK11Context *prf_context =
9006 PK11_CreateContextBySymKey(CKM_TLS_PRF_GENERAL, CKA_SIGN,
9007 spec->master_secret, &param);
9008 unsigned int retLen;
9010 if (!prf_context)
9011 return SECFailure;
9013 rv = PK11_DigestBegin(prf_context);
9014 rv |= PK11_DigestOp(prf_context, (unsigned char *) label, labelLen);
9015 rv |= PK11_DigestOp(prf_context, val, valLen);
9016 rv |= PK11_DigestFinal(prf_context, out, &retLen, outLen);
9017 PORT_Assert(rv != SECSuccess || retLen == outLen);
9019 PK11_DestroyContext(prf_context, PR_TRUE);
9020 } else {
9021 /* bypass PKCS11 */
9022 #ifdef NO_PKCS11_BYPASS
9023 PORT_Assert(spec->master_secret);
9024 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
9025 rv = SECFailure;
9026 #else
9027 SECItem inData = { siBuffer, };
9028 SECItem outData = { siBuffer, };
9029 PRBool isFIPS = PR_FALSE;
9031 inData.data = (unsigned char *) val;
9032 inData.len = valLen;
9033 outData.data = out;
9034 outData.len = outLen;
9035 rv = TLS_PRF(&spec->msItem, label, &inData, &outData, isFIPS);
9036 PORT_Assert(rv != SECSuccess || outData.len == outLen);
9037 #endif
9039 return rv;
9042 /* called from ssl3_HandleServerHelloDone
9044 static SECStatus
9045 ssl3_SendNextProto(sslSocket *ss)
9047 SECStatus rv;
9048 int padding_len;
9049 static const unsigned char padding[32] = {0};
9051 if (ss->ssl3.nextProto.len == 0)
9052 return SECSuccess;
9054 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
9055 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
9057 padding_len = 32 - ((ss->ssl3.nextProto.len + 2) % 32);
9059 rv = ssl3_AppendHandshakeHeader(ss, next_proto, ss->ssl3.nextProto.len +
9060 2 + padding_len);
9061 if (rv != SECSuccess) {
9062 return rv; /* error code set by AppendHandshakeHeader */
9064 rv = ssl3_AppendHandshakeVariable(ss, ss->ssl3.nextProto.data,
9065 ss->ssl3.nextProto.len, 1);
9066 if (rv != SECSuccess) {
9067 return rv; /* error code set by AppendHandshake */
9069 rv = ssl3_AppendHandshakeVariable(ss, padding, padding_len, 1);
9070 if (rv != SECSuccess) {
9071 return rv; /* error code set by AppendHandshake */
9073 return rv;
9076 /* called from ssl3_SendFinished
9078 * This function is simply a debugging aid and therefore does not return a
9079 * SECStatus. */
9080 static void
9081 ssl3_RecordKeyLog(sslSocket *ss)
9083 sslSessionID *sid;
9084 SECStatus rv;
9085 SECItem *keyData;
9086 char buf[14 /* "CLIENT_RANDOM " */ +
9087 SSL3_RANDOM_LENGTH*2 /* client_random */ +
9088 1 /* " " */ +
9089 48*2 /* master secret */ +
9090 1 /* new line */];
9091 unsigned int j;
9093 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
9095 sid = ss->sec.ci.sid;
9097 if (!ssl_keylog_iob)
9098 return;
9100 rv = PK11_ExtractKeyValue(ss->ssl3.cwSpec->master_secret);
9101 if (rv != SECSuccess)
9102 return;
9104 ssl_GetSpecReadLock(ss);
9106 /* keyData does not need to be freed. */
9107 keyData = PK11_GetKeyData(ss->ssl3.cwSpec->master_secret);
9108 if (!keyData || !keyData->data || keyData->len != 48) {
9109 ssl_ReleaseSpecReadLock(ss);
9110 return;
9113 /* https://developer.mozilla.org/en/NSS_Key_Log_Format */
9115 /* There could be multiple, concurrent writers to the
9116 * keylog, so we have to do everything in a single call to
9117 * fwrite. */
9119 memcpy(buf, "CLIENT_RANDOM ", 14);
9120 j = 14;
9121 hexEncode(buf + j, ss->ssl3.hs.client_random.rand, SSL3_RANDOM_LENGTH);
9122 j += SSL3_RANDOM_LENGTH*2;
9123 buf[j++] = ' ';
9124 hexEncode(buf + j, keyData->data, 48);
9125 j += 48*2;
9126 buf[j++] = '\n';
9128 PORT_Assert(j == sizeof(buf));
9130 ssl_ReleaseSpecReadLock(ss);
9132 if (fwrite(buf, sizeof(buf), 1, ssl_keylog_iob) != 1)
9133 return;
9134 fflush(ssl_keylog_iob);
9135 return;
9138 /* called from ssl3_SendClientSecondRound
9139 * ssl3_HandleFinished
9141 static SECStatus
9142 ssl3_SendEncryptedExtensions(sslSocket *ss)
9144 static const char CHANNEL_ID_MAGIC[] = "TLS Channel ID signature";
9145 /* This is the ASN.1 prefix for a P-256 public key. Specifically it's:
9146 * SEQUENCE
9147 * SEQUENCE
9148 * OID id-ecPublicKey
9149 * OID prime256v1
9150 * BIT STRING, length 66, 0 trailing bits: 0x04
9152 * The 0x04 in the BIT STRING is the prefix for an uncompressed, X9.62
9153 * public key. Following that are the two field elements as 32-byte,
9154 * big-endian numbers, as required by the Channel ID. */
9155 static const unsigned char P256_SPKI_PREFIX[] = {
9156 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86,
9157 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a,
9158 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03,
9159 0x42, 0x00, 0x04
9161 /* ChannelIDs are always 128 bytes long: 64 bytes of P-256 public key and 64
9162 * bytes of ECDSA signature. */
9163 static const int CHANNEL_ID_PUBLIC_KEY_LENGTH = 64;
9164 static const int CHANNEL_ID_LENGTH = 128;
9166 SECStatus rv = SECFailure;
9167 SECItem *spki = NULL;
9168 SSL3Hashes hashes;
9169 const unsigned char *pub_bytes;
9170 unsigned char signed_data[sizeof(CHANNEL_ID_MAGIC) + sizeof(SSL3Hashes)];
9171 unsigned char digest[SHA256_LENGTH];
9172 SECItem digest_item;
9173 unsigned char signature[64];
9174 SECItem signature_item;
9176 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
9177 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
9179 if (ss->ssl3.channelID == NULL)
9180 return SECSuccess;
9182 PORT_Assert(ssl3_ExtensionNegotiated(ss, ssl_channel_id_xtn));
9184 if (SECKEY_GetPrivateKeyType(ss->ssl3.channelID) != ecKey ||
9185 PK11_SignatureLen(ss->ssl3.channelID) != sizeof(signature)) {
9186 PORT_SetError(SSL_ERROR_INVALID_CHANNEL_ID_KEY);
9187 rv = SECFailure;
9188 goto loser;
9191 ssl_GetSpecReadLock(ss);
9192 rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.cwSpec, &hashes, 0);
9193 ssl_ReleaseSpecReadLock(ss);
9195 if (rv != SECSuccess)
9196 goto loser;
9198 rv = ssl3_AppendHandshakeHeader(ss, encrypted_extensions,
9199 2 + 2 + CHANNEL_ID_LENGTH);
9200 if (rv != SECSuccess)
9201 goto loser; /* error code set by AppendHandshakeHeader */
9202 rv = ssl3_AppendHandshakeNumber(ss, ssl_channel_id_xtn, 2);
9203 if (rv != SECSuccess)
9204 goto loser; /* error code set by AppendHandshake */
9205 rv = ssl3_AppendHandshakeNumber(ss, CHANNEL_ID_LENGTH, 2);
9206 if (rv != SECSuccess)
9207 goto loser; /* error code set by AppendHandshake */
9209 spki = SECKEY_EncodeDERSubjectPublicKeyInfo(ss->ssl3.channelIDPub);
9211 if (spki->len != sizeof(P256_SPKI_PREFIX) + CHANNEL_ID_PUBLIC_KEY_LENGTH ||
9212 memcmp(spki->data, P256_SPKI_PREFIX, sizeof(P256_SPKI_PREFIX) != 0)) {
9213 PORT_SetError(SSL_ERROR_INVALID_CHANNEL_ID_KEY);
9214 rv = SECFailure;
9215 goto loser;
9218 pub_bytes = spki->data + sizeof(P256_SPKI_PREFIX);
9220 memcpy(signed_data, CHANNEL_ID_MAGIC, sizeof(CHANNEL_ID_MAGIC));
9221 memcpy(signed_data + sizeof(CHANNEL_ID_MAGIC), &hashes, sizeof(hashes));
9223 rv = PK11_HashBuf(SEC_OID_SHA256, digest, signed_data, sizeof(signed_data));
9224 if (rv != SECSuccess)
9225 goto loser;
9227 digest_item.data = digest;
9228 digest_item.len = sizeof(digest);
9230 signature_item.data = signature;
9231 signature_item.len = sizeof(signature);
9233 rv = PK11_Sign(ss->ssl3.channelID, &signature_item, &digest_item);
9234 if (rv != SECSuccess)
9235 goto loser;
9237 rv = ssl3_AppendHandshake(ss, pub_bytes, CHANNEL_ID_PUBLIC_KEY_LENGTH);
9238 if (rv != SECSuccess)
9239 goto loser;
9240 rv = ssl3_AppendHandshake(ss, signature, sizeof(signature));
9242 loser:
9243 if (spki)
9244 SECITEM_FreeItem(spki, PR_TRUE);
9245 if (ss->ssl3.channelID) {
9246 SECKEY_DestroyPrivateKey(ss->ssl3.channelID);
9247 ss->ssl3.channelID = NULL;
9249 if (ss->ssl3.channelIDPub) {
9250 SECKEY_DestroyPublicKey(ss->ssl3.channelIDPub);
9251 ss->ssl3.channelIDPub = NULL;
9254 return rv;
9257 /* ssl3_RestartHandshakeAfterChannelIDReq is called to restart a handshake
9258 * after a ChannelID callback returned SECWouldBlock. At this point we have
9259 * processed the server's ServerHello but not yet any further messages. We will
9260 * always get a message from the server after a ServerHello so either they are
9261 * waiting in the buffer or we'll get network I/O. */
9262 SECStatus
9263 ssl3_RestartHandshakeAfterChannelIDReq(sslSocket *ss,
9264 SECKEYPublicKey *channelIDPub,
9265 SECKEYPrivateKey *channelID)
9267 if (ss->handshake == 0) {
9268 SECKEY_DestroyPublicKey(channelIDPub);
9269 SECKEY_DestroyPrivateKey(channelID);
9270 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
9271 return SECFailure;
9274 if (channelIDPub == NULL ||
9275 channelID == NULL) {
9276 if (channelIDPub)
9277 SECKEY_DestroyPublicKey(channelIDPub);
9278 if (channelID)
9279 SECKEY_DestroyPrivateKey(channelID);
9280 PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
9281 return SECFailure;
9284 if (ss->ssl3.channelID)
9285 SECKEY_DestroyPrivateKey(ss->ssl3.channelID);
9286 if (ss->ssl3.channelIDPub)
9287 SECKEY_DestroyPublicKey(ss->ssl3.channelIDPub);
9289 ss->handshake = ssl_GatherRecord1stHandshake;
9290 ss->ssl3.channelID = channelID;
9291 ss->ssl3.channelIDPub = channelIDPub;
9293 return SECSuccess;
9296 /* called from ssl3_HandleServerHelloDone
9297 * ssl3_HandleClientHello
9298 * ssl3_HandleFinished
9300 static SECStatus
9301 ssl3_SendFinished(sslSocket *ss, PRInt32 flags)
9303 ssl3CipherSpec *cwSpec;
9304 PRBool isTLS;
9305 PRBool isServer = ss->sec.isServer;
9306 SECStatus rv;
9307 SSL3Sender sender = isServer ? sender_server : sender_client;
9308 SSL3Finished hashes;
9309 TLSFinished tlsFinished;
9311 SSL_TRC(3, ("%d: SSL3[%d]: send finished handshake", SSL_GETPID(), ss->fd));
9313 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
9314 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
9316 ssl_GetSpecReadLock(ss);
9317 cwSpec = ss->ssl3.cwSpec;
9318 isTLS = (PRBool)(cwSpec->version > SSL_LIBRARY_VERSION_3_0);
9319 rv = ssl3_ComputeHandshakeHashes(ss, cwSpec, &hashes, sender);
9320 if (isTLS && rv == SECSuccess) {
9321 rv = ssl3_ComputeTLSFinished(cwSpec, isServer, &hashes, &tlsFinished);
9323 ssl_ReleaseSpecReadLock(ss);
9324 if (rv != SECSuccess) {
9325 goto fail; /* err code was set by ssl3_ComputeHandshakeHashes */
9328 if (isTLS) {
9329 if (isServer)
9330 ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished;
9331 else
9332 ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished;
9333 ss->ssl3.hs.finishedBytes = sizeof tlsFinished;
9334 rv = ssl3_AppendHandshakeHeader(ss, finished, sizeof tlsFinished);
9335 if (rv != SECSuccess)
9336 goto fail; /* err set by AppendHandshake. */
9337 rv = ssl3_AppendHandshake(ss, &tlsFinished, sizeof tlsFinished);
9338 if (rv != SECSuccess)
9339 goto fail; /* err set by AppendHandshake. */
9340 } else {
9341 if (isServer)
9342 ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes;
9343 else
9344 ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes;
9345 ss->ssl3.hs.finishedBytes = sizeof hashes;
9346 rv = ssl3_AppendHandshakeHeader(ss, finished, sizeof hashes);
9347 if (rv != SECSuccess)
9348 goto fail; /* err set by AppendHandshake. */
9349 rv = ssl3_AppendHandshake(ss, &hashes, sizeof hashes);
9350 if (rv != SECSuccess)
9351 goto fail; /* err set by AppendHandshake. */
9353 rv = ssl3_FlushHandshake(ss, flags);
9354 if (rv != SECSuccess) {
9355 goto fail; /* error code set by ssl3_FlushHandshake */
9358 ssl3_RecordKeyLog(ss);
9360 return SECSuccess;
9362 fail:
9363 return rv;
9366 /* wrap the master secret, and put it into the SID.
9367 * Caller holds the Spec read lock.
9369 SECStatus
9370 ssl3_CacheWrappedMasterSecret(sslSocket *ss, sslSessionID *sid,
9371 ssl3CipherSpec *spec, SSL3KEAType effectiveExchKeyType)
9373 PK11SymKey * wrappingKey = NULL;
9374 PK11SlotInfo * symKeySlot;
9375 void * pwArg = ss->pkcs11PinArg;
9376 SECStatus rv = SECFailure;
9377 PRBool isServer = ss->sec.isServer;
9378 CK_MECHANISM_TYPE mechanism = CKM_INVALID_MECHANISM;
9379 symKeySlot = PK11_GetSlotFromKey(spec->master_secret);
9380 if (!isServer) {
9381 int wrapKeyIndex;
9382 int incarnation;
9384 /* these next few functions are mere accessors and don't fail. */
9385 sid->u.ssl3.masterWrapIndex = wrapKeyIndex =
9386 PK11_GetCurrentWrapIndex(symKeySlot);
9387 PORT_Assert(wrapKeyIndex == 0); /* array has only one entry! */
9389 sid->u.ssl3.masterWrapSeries = incarnation =
9390 PK11_GetSlotSeries(symKeySlot);
9391 sid->u.ssl3.masterSlotID = PK11_GetSlotID(symKeySlot);
9392 sid->u.ssl3.masterModuleID = PK11_GetModuleID(symKeySlot);
9393 sid->u.ssl3.masterValid = PR_TRUE;
9394 /* Get the default wrapping key, for wrapping the master secret before
9395 * placing it in the SID cache entry. */
9396 wrappingKey = PK11_GetWrapKey(symKeySlot, wrapKeyIndex,
9397 CKM_INVALID_MECHANISM, incarnation,
9398 pwArg);
9399 if (wrappingKey) {
9400 mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */
9401 } else {
9402 int keyLength;
9403 /* if the wrappingKey doesn't exist, attempt to create it.
9404 * Note: we intentionally ignore errors here. If we cannot
9405 * generate a wrapping key, it is not fatal to this SSL connection,
9406 * but we will not be able to restart this session.
9408 mechanism = PK11_GetBestWrapMechanism(symKeySlot);
9409 keyLength = PK11_GetBestKeyLength(symKeySlot, mechanism);
9410 /* Zero length means fixed key length algorithm, or error.
9411 * It's ambiguous.
9413 wrappingKey = PK11_KeyGen(symKeySlot, mechanism, NULL,
9414 keyLength, pwArg);
9415 if (wrappingKey) {
9416 PK11_SetWrapKey(symKeySlot, wrapKeyIndex, wrappingKey);
9419 } else {
9420 /* server socket using session cache. */
9421 mechanism = PK11_GetBestWrapMechanism(symKeySlot);
9422 if (mechanism != CKM_INVALID_MECHANISM) {
9423 wrappingKey =
9424 getWrappingKey(ss, symKeySlot, effectiveExchKeyType,
9425 mechanism, pwArg);
9426 if (wrappingKey) {
9427 mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */
9432 sid->u.ssl3.masterWrapMech = mechanism;
9433 PK11_FreeSlot(symKeySlot);
9435 if (wrappingKey) {
9436 SECItem wmsItem;
9438 wmsItem.data = sid->u.ssl3.keys.wrapped_master_secret;
9439 wmsItem.len = sizeof sid->u.ssl3.keys.wrapped_master_secret;
9440 rv = PK11_WrapSymKey(mechanism, NULL, wrappingKey,
9441 spec->master_secret, &wmsItem);
9442 /* rv is examined below. */
9443 sid->u.ssl3.keys.wrapped_master_secret_len = wmsItem.len;
9444 PK11_FreeSymKey(wrappingKey);
9446 return rv;
9449 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
9450 * ssl3 Finished message from the peer.
9451 * Caller must hold Handshake and RecvBuf locks.
9453 static SECStatus
9454 ssl3_HandleFinished(sslSocket *ss, SSL3Opaque *b, PRUint32 length,
9455 const SSL3Hashes *hashes)
9457 sslSessionID * sid = ss->sec.ci.sid;
9458 SECStatus rv = SECSuccess;
9459 PRBool isServer = ss->sec.isServer;
9460 PRBool isTLS;
9461 SSL3KEAType effectiveExchKeyType;
9463 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
9464 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
9466 SSL_TRC(3, ("%d: SSL3[%d]: handle finished handshake",
9467 SSL_GETPID(), ss->fd));
9469 if (ss->ssl3.hs.ws != wait_finished) {
9470 SSL3_SendAlert(ss, alert_fatal, unexpected_message);
9471 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_FINISHED);
9472 return SECFailure;
9475 isTLS = (PRBool)(ss->ssl3.crSpec->version > SSL_LIBRARY_VERSION_3_0);
9476 if (isTLS) {
9477 TLSFinished tlsFinished;
9479 if (length != sizeof tlsFinished) {
9480 (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
9481 PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED);
9482 return SECFailure;
9484 rv = ssl3_ComputeTLSFinished(ss->ssl3.crSpec, !isServer,
9485 hashes, &tlsFinished);
9486 if (!isServer)
9487 ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished;
9488 else
9489 ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished;
9490 ss->ssl3.hs.finishedBytes = sizeof tlsFinished;
9491 if (rv != SECSuccess ||
9492 0 != NSS_SecureMemcmp(&tlsFinished, b, length)) {
9493 (void)SSL3_SendAlert(ss, alert_fatal, decrypt_error);
9494 PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
9495 return SECFailure;
9497 } else {
9498 if (length != sizeof(SSL3Hashes)) {
9499 (void)ssl3_IllegalParameter(ss);
9500 PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED);
9501 return SECFailure;
9504 if (!isServer)
9505 ss->ssl3.hs.finishedMsgs.sFinished[1] = *hashes;
9506 else
9507 ss->ssl3.hs.finishedMsgs.sFinished[0] = *hashes;
9508 ss->ssl3.hs.finishedBytes = sizeof *hashes;
9509 if (0 != NSS_SecureMemcmp(hashes, b, length)) {
9510 (void)ssl3_HandshakeFailure(ss);
9511 PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
9512 return SECFailure;
9516 ssl_GetXmitBufLock(ss); /*************************************/
9518 if ((isServer && !ss->ssl3.hs.isResuming) ||
9519 (!isServer && ss->ssl3.hs.isResuming)) {
9520 PRInt32 flags = 0;
9522 /* Send a NewSessionTicket message if the client sent us
9523 * either an empty session ticket, or one that did not verify.
9524 * (Note that if either of these conditions was met, then the
9525 * server has sent a SessionTicket extension in the
9526 * ServerHello message.)
9528 if (isServer && !ss->ssl3.hs.isResuming &&
9529 ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn)) {
9530 rv = ssl3_SendNewSessionTicket(ss);
9531 if (rv != SECSuccess) {
9532 goto xmit_loser;
9536 rv = ssl3_SendChangeCipherSpecs(ss);
9537 if (rv != SECSuccess) {
9538 goto xmit_loser; /* err is set. */
9540 /* If this thread is in SSL_SecureSend (trying to write some data)
9541 ** then set the ssl_SEND_FLAG_FORCE_INTO_BUFFER flag, so that the
9542 ** last two handshake messages (change cipher spec and finished)
9543 ** will be sent in the same send/write call as the application data.
9545 if (ss->writerThread == PR_GetCurrentThread()) {
9546 flags = ssl_SEND_FLAG_FORCE_INTO_BUFFER;
9549 if (!isServer) {
9550 if (!ss->firstHsDone) {
9551 rv = ssl3_SendNextProto(ss);
9552 if (rv != SECSuccess) {
9553 goto xmit_loser; /* err code was set. */
9556 rv = ssl3_SendEncryptedExtensions(ss);
9557 if (rv != SECSuccess)
9558 goto xmit_loser; /* err code was set. */
9561 if (IS_DTLS(ss)) {
9562 flags |= ssl_SEND_FLAG_NO_RETRANSMIT;
9565 rv = ssl3_SendFinished(ss, flags);
9566 if (rv != SECSuccess) {
9567 goto xmit_loser; /* err is set. */
9571 xmit_loser:
9572 ssl_ReleaseXmitBufLock(ss); /*************************************/
9573 if (rv != SECSuccess) {
9574 return rv;
9577 ss->gs.writeOffset = 0;
9578 ss->gs.readOffset = 0;
9580 if (ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) {
9581 effectiveExchKeyType = kt_rsa;
9582 } else {
9583 effectiveExchKeyType = ss->ssl3.hs.kea_def->exchKeyType;
9586 if (sid->cached == never_cached && !ss->opt.noCache && ss->sec.cache) {
9587 /* fill in the sid */
9588 sid->u.ssl3.cipherSuite = ss->ssl3.hs.cipher_suite;
9589 sid->u.ssl3.compression = ss->ssl3.hs.compression;
9590 sid->u.ssl3.policy = ss->ssl3.policy;
9591 #ifdef NSS_ENABLE_ECC
9592 sid->u.ssl3.negotiatedECCurves = ss->ssl3.hs.negotiatedECCurves;
9593 #endif
9594 sid->u.ssl3.exchKeyType = effectiveExchKeyType;
9595 sid->version = ss->version;
9596 sid->authAlgorithm = ss->sec.authAlgorithm;
9597 sid->authKeyBits = ss->sec.authKeyBits;
9598 sid->keaType = ss->sec.keaType;
9599 sid->keaKeyBits = ss->sec.keaKeyBits;
9600 sid->lastAccessTime = sid->creationTime = ssl_Time();
9601 sid->expirationTime = sid->creationTime + ssl3_sid_timeout;
9602 sid->localCert = CERT_DupCertificate(ss->sec.localCert);
9604 ssl_GetSpecReadLock(ss); /*************************************/
9606 /* Copy the master secret (wrapped or unwrapped) into the sid */
9607 if (ss->ssl3.crSpec->msItem.len && ss->ssl3.crSpec->msItem.data) {
9608 sid->u.ssl3.keys.wrapped_master_secret_len =
9609 ss->ssl3.crSpec->msItem.len;
9610 memcpy(sid->u.ssl3.keys.wrapped_master_secret,
9611 ss->ssl3.crSpec->msItem.data, ss->ssl3.crSpec->msItem.len);
9612 sid->u.ssl3.masterValid = PR_TRUE;
9613 sid->u.ssl3.keys.msIsWrapped = PR_FALSE;
9614 rv = SECSuccess;
9615 } else {
9616 rv = ssl3_CacheWrappedMasterSecret(ss, ss->sec.ci.sid,
9617 ss->ssl3.crSpec,
9618 effectiveExchKeyType);
9619 sid->u.ssl3.keys.msIsWrapped = PR_TRUE;
9621 ssl_ReleaseSpecReadLock(ss); /*************************************/
9623 /* If the wrap failed, we don't cache the sid.
9624 * The connection continues normally however.
9626 ss->ssl3.hs.cacheSID = rv == SECSuccess;
9629 if (ss->ssl3.hs.authCertificatePending) {
9630 if (ss->ssl3.hs.restartTarget) {
9631 PR_NOT_REACHED("ssl3_HandleFinished: unexpected restartTarget");
9632 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
9633 return SECFailure;
9636 ss->ssl3.hs.restartTarget = ssl3_FinishHandshake;
9637 return SECWouldBlock;
9640 rv = ssl3_FinishHandshake(ss);
9641 return rv;
9644 SECStatus
9645 ssl3_FinishHandshake(sslSocket * ss)
9647 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
9648 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
9649 PORT_Assert( ss->ssl3.hs.restartTarget == NULL );
9651 /* The first handshake is now completed. */
9652 ss->handshake = NULL;
9653 ss->firstHsDone = PR_TRUE;
9655 if (ss->ssl3.hs.cacheSID) {
9656 (*ss->sec.cache)(ss->sec.ci.sid);
9657 ss->ssl3.hs.cacheSID = PR_FALSE;
9660 ss->ssl3.hs.ws = idle_handshake;
9662 /* Do the handshake callback for sslv3 here, if we cannot false start. */
9663 if (ss->handshakeCallback != NULL && !ssl3_CanFalseStart(ss)) {
9664 (ss->handshakeCallback)(ss->fd, ss->handshakeCallbackData);
9667 return SECSuccess;
9670 /* This function handles any pending Certificate messages. Certificate messages
9671 * can be pending if we expect a possible CertificateStatus message to follow.
9673 * This function must be called immediately after handling the
9674 * CertificateStatus message, and before handling any ServerKeyExchange or
9675 * CertificateRequest messages.
9677 static SECStatus
9678 ssl3_MaybeHandlePendingCertificateMessage(sslSocket *ss)
9680 SECStatus rv = SECSuccess;
9682 if (ss->ssl3.hs.pending_cert_msg.data) {
9683 rv = ssl3_HandleCertificate(ss, ss->ssl3.hs.pending_cert_msg.data,
9684 ss->ssl3.hs.pending_cert_msg.len);
9685 SECITEM_FreeItem(&ss->ssl3.hs.pending_cert_msg, PR_FALSE);
9687 return rv;
9690 /* Called from ssl3_HandleHandshake() when it has gathered a complete ssl3
9691 * hanshake message.
9692 * Caller must hold Handshake and RecvBuf locks.
9694 SECStatus
9695 ssl3_HandleHandshakeMessage(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
9697 SECStatus rv = SECSuccess;
9698 SSL3HandshakeType type = ss->ssl3.hs.msg_type;
9699 SSL3Hashes hashes; /* computed hashes are put here. */
9700 PRUint8 hdr[4];
9701 PRUint8 dtlsData[8];
9703 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
9704 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
9706 * We have to compute the hashes before we update them with the
9707 * current message.
9709 ssl_GetSpecReadLock(ss); /************************************/
9710 if((type == finished) || (type == certificate_verify)) {
9711 SSL3Sender sender = (SSL3Sender)0;
9712 ssl3CipherSpec *rSpec = ss->ssl3.prSpec;
9714 if (type == finished) {
9715 sender = ss->sec.isServer ? sender_client : sender_server;
9716 rSpec = ss->ssl3.crSpec;
9718 rv = ssl3_ComputeHandshakeHashes(ss, rSpec, &hashes, sender);
9720 ssl_ReleaseSpecReadLock(ss); /************************************/
9721 if (rv != SECSuccess) {
9722 return rv; /* error code was set by ssl3_ComputeHandshakeHashes*/
9724 SSL_TRC(30,("%d: SSL3[%d]: handle handshake message: %s", SSL_GETPID(),
9725 ss->fd, ssl3_DecodeHandshakeType(ss->ssl3.hs.msg_type)));
9726 PRINT_BUF(60, (ss, "MD5 handshake hash:",
9727 (unsigned char*)ss->ssl3.hs.md5_cx, MD5_LENGTH));
9728 PRINT_BUF(95, (ss, "SHA handshake hash:",
9729 (unsigned char*)ss->ssl3.hs.sha_cx, SHA1_LENGTH));
9731 hdr[0] = (PRUint8)ss->ssl3.hs.msg_type;
9732 hdr[1] = (PRUint8)(length >> 16);
9733 hdr[2] = (PRUint8)(length >> 8);
9734 hdr[3] = (PRUint8)(length );
9736 /* Start new handshake hashes when we start a new handshake */
9737 if (ss->ssl3.hs.msg_type == client_hello) {
9738 SSL_TRC(30,("%d: SSL3[%d]: reset handshake hashes",
9739 SSL_GETPID(), ss->fd ));
9740 rv = ssl3_RestartHandshakeHashes(ss);
9741 if (rv != SECSuccess) {
9742 return rv;
9745 /* We should not include hello_request and hello_verify_request messages
9746 * in the handshake hashes */
9747 if ((ss->ssl3.hs.msg_type != hello_request) &&
9748 (ss->ssl3.hs.msg_type != hello_verify_request)) {
9749 rv = ssl3_UpdateHandshakeHashes(ss, (unsigned char*) hdr, 4);
9750 if (rv != SECSuccess) return rv; /* err code already set. */
9752 /* Extra data to simulate a complete DTLS handshake fragment */
9753 if (IS_DTLS(ss)) {
9754 /* Sequence number */
9755 dtlsData[0] = MSB(ss->ssl3.hs.recvMessageSeq);
9756 dtlsData[1] = LSB(ss->ssl3.hs.recvMessageSeq);
9758 /* Fragment offset */
9759 dtlsData[2] = 0;
9760 dtlsData[3] = 0;
9761 dtlsData[4] = 0;
9763 /* Fragment length */
9764 dtlsData[5] = (PRUint8)(length >> 16);
9765 dtlsData[6] = (PRUint8)(length >> 8);
9766 dtlsData[7] = (PRUint8)(length );
9768 rv = ssl3_UpdateHandshakeHashes(ss, (unsigned char*) dtlsData,
9769 sizeof(dtlsData));
9770 if (rv != SECSuccess) return rv; /* err code already set. */
9773 /* The message body */
9774 rv = ssl3_UpdateHandshakeHashes(ss, b, length);
9775 if (rv != SECSuccess) return rv; /* err code already set. */
9778 PORT_SetError(0); /* each message starts with no error. */
9779 switch (ss->ssl3.hs.msg_type) {
9780 case hello_request:
9781 if (length != 0) {
9782 (void)ssl3_DecodeError(ss);
9783 PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_REQUEST);
9784 return SECFailure;
9786 if (ss->sec.isServer) {
9787 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
9788 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST);
9789 return SECFailure;
9791 rv = ssl3_HandleHelloRequest(ss);
9792 break;
9793 case client_hello:
9794 if (!ss->sec.isServer) {
9795 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
9796 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO);
9797 return SECFailure;
9799 rv = ssl3_HandleClientHello(ss, b, length);
9800 break;
9801 case server_hello:
9802 if (ss->sec.isServer) {
9803 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
9804 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO);
9805 return SECFailure;
9807 rv = ssl3_HandleServerHello(ss, b, length);
9808 break;
9809 case hello_verify_request:
9810 if (!IS_DTLS(ss) || ss->sec.isServer) {
9811 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
9812 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_VERIFY_REQUEST);
9813 return SECFailure;
9815 rv = dtls_HandleHelloVerifyRequest(ss, b, length);
9816 break;
9817 case certificate:
9818 if (ss->ssl3.hs.may_get_cert_status) {
9819 /* If we might get a CertificateStatus then we want to postpone the
9820 * processing of the Certificate message until after we have
9821 * processed the CertificateStatus */
9822 if (ss->ssl3.hs.pending_cert_msg.data ||
9823 ss->ssl3.hs.ws != wait_server_cert) {
9824 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
9825 (void)ssl_MapLowLevelError(SSL_ERROR_RX_UNEXPECTED_CERTIFICATE);
9826 return SECFailure;
9828 if (SECITEM_AllocItem(NULL, &ss->ssl3.hs.pending_cert_msg,
9829 length) == NULL) {
9830 return SECFailure;
9832 ss->ssl3.hs.pending_cert_msg.type = siBuffer;
9833 PORT_Memcpy(ss->ssl3.hs.pending_cert_msg.data, b, length);
9834 break;
9836 rv = ssl3_HandleCertificate(ss, b, length);
9837 break;
9838 case certificate_status:
9839 rv = ssl3_HandleCertificateStatus(ss, b, length);
9840 if (rv != SECSuccess)
9841 break;
9842 PORT_Assert(ss->ssl3.hs.pending_cert_msg.data);
9843 rv = ssl3_MaybeHandlePendingCertificateMessage(ss);
9844 break;
9845 case server_key_exchange:
9846 if (ss->sec.isServer) {
9847 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
9848 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH);
9849 return SECFailure;
9851 rv = ssl3_MaybeHandlePendingCertificateMessage(ss);
9852 if (rv != SECSuccess)
9853 break;
9854 rv = ssl3_HandleServerKeyExchange(ss, b, length);
9855 break;
9856 case certificate_request:
9857 if (ss->sec.isServer) {
9858 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
9859 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST);
9860 return SECFailure;
9862 rv = ssl3_MaybeHandlePendingCertificateMessage(ss);
9863 if (rv != SECSuccess)
9864 break;
9865 rv = ssl3_HandleCertificateRequest(ss, b, length);
9866 break;
9867 case server_hello_done:
9868 if (length != 0) {
9869 (void)ssl3_DecodeError(ss);
9870 PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_DONE);
9871 return SECFailure;
9873 if (ss->sec.isServer) {
9874 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
9875 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE);
9876 return SECFailure;
9878 rv = ssl3_MaybeHandlePendingCertificateMessage(ss);
9879 if (rv != SECSuccess)
9880 break;
9881 rv = ssl3_HandleServerHelloDone(ss);
9882 break;
9883 case certificate_verify:
9884 if (!ss->sec.isServer) {
9885 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
9886 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY);
9887 return SECFailure;
9889 rv = ssl3_HandleCertificateVerify(ss, b, length, &hashes);
9890 break;
9891 case client_key_exchange:
9892 if (!ss->sec.isServer) {
9893 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
9894 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH);
9895 return SECFailure;
9897 rv = ssl3_HandleClientKeyExchange(ss, b, length);
9898 break;
9899 case new_session_ticket:
9900 if (ss->sec.isServer) {
9901 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
9902 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET);
9903 return SECFailure;
9905 rv = ssl3_HandleNewSessionTicket(ss, b, length);
9906 break;
9907 case finished:
9908 rv = ssl3_HandleFinished(ss, b, length, &hashes);
9909 break;
9910 default:
9911 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
9912 PORT_SetError(SSL_ERROR_RX_UNKNOWN_HANDSHAKE);
9913 rv = SECFailure;
9916 if (IS_DTLS(ss) && (rv == SECSuccess)) {
9917 /* Increment the expected sequence number */
9918 ss->ssl3.hs.recvMessageSeq++;
9921 return rv;
9924 /* Called only from ssl3_HandleRecord, for each (deciphered) ssl3 record.
9925 * origBuf is the decrypted ssl record content.
9926 * Caller must hold the handshake and RecvBuf locks.
9928 static SECStatus
9929 ssl3_HandleHandshake(sslSocket *ss, sslBuffer *origBuf)
9932 * There may be a partial handshake message already in the handshake
9933 * state. The incoming buffer may contain another portion, or a
9934 * complete message or several messages followed by another portion.
9936 * Each message is made contiguous before being passed to the actual
9937 * message parser.
9939 sslBuffer *buf = &ss->ssl3.hs.msgState; /* do not lose the original buffer pointer */
9940 SECStatus rv;
9942 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
9943 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
9945 if (buf->buf == NULL) {
9946 *buf = *origBuf;
9948 while (buf->len > 0) {
9949 if (ss->ssl3.hs.header_bytes < 4) {
9950 uint8 t;
9951 t = *(buf->buf++);
9952 buf->len--;
9953 if (ss->ssl3.hs.header_bytes++ == 0)
9954 ss->ssl3.hs.msg_type = (SSL3HandshakeType)t;
9955 else
9956 ss->ssl3.hs.msg_len = (ss->ssl3.hs.msg_len << 8) + t;
9957 if (ss->ssl3.hs.header_bytes < 4)
9958 continue;
9960 #define MAX_HANDSHAKE_MSG_LEN 0x1ffff /* 128k - 1 */
9961 if (ss->ssl3.hs.msg_len > MAX_HANDSHAKE_MSG_LEN) {
9962 (void)ssl3_DecodeError(ss);
9963 PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
9964 return SECFailure;
9966 #undef MAX_HANDSHAKE_MSG_LEN
9968 /* If msg_len is zero, be sure we fall through,
9969 ** even if buf->len is zero.
9971 if (ss->ssl3.hs.msg_len > 0)
9972 continue;
9976 * Header has been gathered and there is at least one byte of new
9977 * data available for this message. If it can be done right out
9978 * of the original buffer, then use it from there.
9980 if (ss->ssl3.hs.msg_body.len == 0 && buf->len >= ss->ssl3.hs.msg_len) {
9981 /* handle it from input buffer */
9982 rv = ssl3_HandleHandshakeMessage(ss, buf->buf, ss->ssl3.hs.msg_len);
9983 if (rv == SECFailure) {
9984 /* This test wants to fall through on either
9985 * SECSuccess or SECWouldBlock.
9986 * ssl3_HandleHandshakeMessage MUST set the error code.
9988 return rv;
9990 buf->buf += ss->ssl3.hs.msg_len;
9991 buf->len -= ss->ssl3.hs.msg_len;
9992 ss->ssl3.hs.msg_len = 0;
9993 ss->ssl3.hs.header_bytes = 0;
9994 if (rv != SECSuccess) { /* return if SECWouldBlock. */
9995 return rv;
9997 } else {
9998 /* must be copied to msg_body and dealt with from there */
9999 unsigned int bytes;
10001 PORT_Assert(ss->ssl3.hs.msg_body.len < ss->ssl3.hs.msg_len);
10002 bytes = PR_MIN(buf->len, ss->ssl3.hs.msg_len - ss->ssl3.hs.msg_body.len);
10004 /* Grow the buffer if needed */
10005 rv = sslBuffer_Grow(&ss->ssl3.hs.msg_body, ss->ssl3.hs.msg_len);
10006 if (rv != SECSuccess) {
10007 /* sslBuffer_Grow has set a memory error code. */
10008 return SECFailure;
10011 PORT_Memcpy(ss->ssl3.hs.msg_body.buf + ss->ssl3.hs.msg_body.len,
10012 buf->buf, bytes);
10013 ss->ssl3.hs.msg_body.len += bytes;
10014 buf->buf += bytes;
10015 buf->len -= bytes;
10017 PORT_Assert(ss->ssl3.hs.msg_body.len <= ss->ssl3.hs.msg_len);
10019 /* if we have a whole message, do it */
10020 if (ss->ssl3.hs.msg_body.len == ss->ssl3.hs.msg_len) {
10021 rv = ssl3_HandleHandshakeMessage(
10022 ss, ss->ssl3.hs.msg_body.buf, ss->ssl3.hs.msg_len);
10023 if (rv == SECFailure) {
10024 /* This test wants to fall through on either
10025 * SECSuccess or SECWouldBlock.
10026 * ssl3_HandleHandshakeMessage MUST set error code.
10028 return rv;
10030 ss->ssl3.hs.msg_body.len = 0;
10031 ss->ssl3.hs.msg_len = 0;
10032 ss->ssl3.hs.header_bytes = 0;
10033 if (rv != SECSuccess) { /* return if SECWouldBlock. */
10034 return rv;
10036 } else {
10037 PORT_Assert(buf->len == 0);
10038 break;
10041 } /* end loop */
10043 origBuf->len = 0; /* So ssl3_GatherAppDataRecord will keep looping. */
10044 buf->buf = NULL; /* not a leak. */
10045 return SECSuccess;
10048 /* if cText is non-null, then decipher, check MAC, and decompress the
10049 * SSL record from cText->buf (typically gs->inbuf)
10050 * into databuf (typically gs->buf), and any previous contents of databuf
10051 * is lost. Then handle databuf according to its SSL record type,
10052 * unless it's an application record.
10054 * If cText is NULL, then the ciphertext has previously been deciphered and
10055 * checked, and is already sitting in databuf. It is processed as an SSL
10056 * Handshake message.
10058 * DOES NOT process the decrypted/decompressed application data.
10059 * On return, databuf contains the decrypted/decompressed record.
10061 * Called from ssl3_GatherCompleteHandshake
10062 * ssl3_RestartHandshakeAfterCertReq
10064 * Caller must hold the RecvBufLock.
10066 * This function aquires and releases the SSL3Handshake Lock, holding the
10067 * lock around any calls to functions that handle records other than
10068 * Application Data records.
10070 SECStatus
10071 ssl3_HandleRecord(sslSocket *ss, SSL3Ciphertext *cText, sslBuffer *databuf)
10073 const ssl3BulkCipherDef *cipher_def;
10074 ssl3CipherSpec * crSpec;
10075 SECStatus rv;
10076 unsigned int hashBytes = MAX_MAC_LENGTH + 1;
10077 unsigned int padding_length;
10078 PRBool isTLS;
10079 PRBool padIsBad = PR_FALSE;
10080 SSL3ContentType rType;
10081 SSL3Opaque hash[MAX_MAC_LENGTH];
10082 sslBuffer *plaintext;
10083 sslBuffer temp_buf;
10084 PRUint64 dtls_seq_num;
10085 unsigned int ivLen = 0;
10087 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
10089 if (!ss->ssl3.initialized) {
10090 ssl_GetSSL3HandshakeLock(ss);
10091 rv = ssl3_InitState(ss);
10092 ssl_ReleaseSSL3HandshakeLock(ss);
10093 if (rv != SECSuccess) {
10094 return rv; /* ssl3_InitState has set the error code. */
10098 /* check for Token Presence */
10099 if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) {
10100 PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
10101 return SECFailure;
10104 /* cText is NULL when we're called from ssl3_RestartHandshakeAfterXXX().
10105 * This implies that databuf holds a previously deciphered SSL Handshake
10106 * message.
10108 if (cText == NULL) {
10109 SSL_DBG(("%d: SSL3[%d]: HandleRecord, resuming handshake",
10110 SSL_GETPID(), ss->fd));
10111 rType = content_handshake;
10112 goto process_it;
10115 ssl_GetSpecReadLock(ss); /******************************************/
10117 crSpec = ss->ssl3.crSpec;
10118 cipher_def = crSpec->cipher_def;
10121 * DTLS relevance checks:
10122 * Note that this code currently ignores all out-of-epoch packets,
10123 * which means we lose some in the case of rehandshake +
10124 * loss/reordering. Since DTLS is explicitly unreliable, this
10125 * seems like a good tradeoff for implementation effort and is
10126 * consistent with the guidance of RFC 6347 Sections 4.1 and 4.2.4.1
10128 if (IS_DTLS(ss)) {
10129 DTLSEpoch epoch = (cText->seq_num.high >> 16) & 0xffff;
10131 if (crSpec->epoch != epoch) {
10132 ssl_ReleaseSpecReadLock(ss);
10133 SSL_DBG(("%d: SSL3[%d]: HandleRecord, received packet "
10134 "from irrelevant epoch %d", SSL_GETPID(), ss->fd, epoch));
10135 /* Silently drop the packet */
10136 databuf->len = 0; /* Needed to ensure data not left around */
10137 return SECSuccess;
10140 dtls_seq_num = (((PRUint64)(cText->seq_num.high & 0xffff)) << 32) |
10141 ((PRUint64)cText->seq_num.low);
10143 if (dtls_RecordGetRecvd(&crSpec->recvdRecords, dtls_seq_num) != 0) {
10144 ssl_ReleaseSpecReadLock(ss);
10145 SSL_DBG(("%d: SSL3[%d]: HandleRecord, rejecting "
10146 "potentially replayed packet", SSL_GETPID(), ss->fd));
10147 /* Silently drop the packet */
10148 databuf->len = 0; /* Needed to ensure data not left around */
10149 return SECSuccess;
10153 if (cipher_def->type == type_block &&
10154 crSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
10155 /* Consume the per-record explicit IV. RFC 4346 Section 6.2.3.2 states
10156 * "The receiver decrypts the entire GenericBlockCipher structure and
10157 * then discards the first cipher block corresponding to the IV
10158 * component." Instead, we decrypt the first cipher block and then
10159 * discard it before decrypting the rest.
10161 SSL3Opaque iv[MAX_IV_LENGTH];
10162 int decoded;
10164 ivLen = cipher_def->iv_size;
10165 if (ivLen < 8 || ivLen > sizeof(iv)) {
10166 ssl_ReleaseSpecReadLock(ss);
10167 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
10168 return SECFailure;
10170 if (ivLen > cText->buf->len) {
10171 SSL_DBG(("%d: SSL3[%d]: HandleRecord, IV length check failed",
10172 SSL_GETPID(), ss->fd));
10173 /* must not hold spec lock when calling SSL3_SendAlert. */
10174 ssl_ReleaseSpecReadLock(ss);
10175 SSL3_SendAlert(ss, alert_fatal, bad_record_mac);
10176 /* always log mac error, in case attacker can read server logs. */
10177 PORT_SetError(SSL_ERROR_BAD_MAC_READ);
10178 return SECFailure;
10181 PRINT_BUF(80, (ss, "IV (ciphertext):", cText->buf->buf, ivLen));
10183 /* The decryption result is garbage, but since we just throw away
10184 * the block it doesn't matter. The decryption of the next block
10185 * depends only on the ciphertext of the IV block.
10187 rv = crSpec->decode(crSpec->decodeContext, iv, &decoded,
10188 sizeof(iv), cText->buf->buf, ivLen);
10190 if (rv != SECSuccess) {
10191 /* All decryption failures must be treated like a bad record
10192 * MAC; see RFC 5246 (TLS 1.2).
10194 padIsBad = PR_TRUE;
10198 /* If we will be decompressing the buffer we need to decrypt somewhere
10199 * other than into databuf */
10200 if (crSpec->decompressor) {
10201 temp_buf.buf = NULL;
10202 temp_buf.space = 0;
10203 plaintext = &temp_buf;
10204 } else {
10205 plaintext = databuf;
10208 plaintext->len = 0; /* filled in by decode call below. */
10209 if (plaintext->space < MAX_FRAGMENT_LENGTH) {
10210 rv = sslBuffer_Grow(plaintext, MAX_FRAGMENT_LENGTH + 2048);
10211 if (rv != SECSuccess) {
10212 ssl_ReleaseSpecReadLock(ss);
10213 SSL_DBG(("%d: SSL3[%d]: HandleRecord, tried to get %d bytes",
10214 SSL_GETPID(), ss->fd, MAX_FRAGMENT_LENGTH + 2048));
10215 /* sslBuffer_Grow has set a memory error code. */
10216 /* Perhaps we should send an alert. (but we have no memory!) */
10217 return SECFailure;
10221 PRINT_BUF(80, (ss, "ciphertext:", cText->buf->buf + ivLen,
10222 cText->buf->len - ivLen));
10224 isTLS = (PRBool)(crSpec->version > SSL_LIBRARY_VERSION_3_0);
10226 if (isTLS && cText->buf->len - ivLen > (MAX_FRAGMENT_LENGTH + 2048)) {
10227 ssl_ReleaseSpecReadLock(ss);
10228 SSL3_SendAlert(ss, alert_fatal, record_overflow);
10229 PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
10230 return SECFailure;
10233 /* decrypt from cText buf to plaintext. */
10234 rv = crSpec->decode(
10235 crSpec->decodeContext, plaintext->buf, (int *)&plaintext->len,
10236 plaintext->space, cText->buf->buf + ivLen, cText->buf->len - ivLen);
10238 PRINT_BUF(80, (ss, "cleartext:", plaintext->buf, plaintext->len));
10239 if (rv != SECSuccess) {
10240 /* All decryption failures must be treated like a bad record
10241 * MAC; see RFC 5246 (TLS 1.2).
10243 padIsBad = PR_TRUE;
10246 /* If it's a block cipher, check and strip the padding. */
10247 if (cipher_def->type == type_block && !padIsBad) {
10248 PRUint8 * pPaddingLen = plaintext->buf + plaintext->len - 1;
10249 padding_length = *pPaddingLen;
10250 /* TLS permits padding to exceed the block size, up to 255 bytes. */
10251 if (padding_length + 1 + crSpec->mac_size > plaintext->len)
10252 padIsBad = PR_TRUE;
10253 else {
10254 plaintext->len -= padding_length + 1;
10255 /* In TLS all padding bytes must be equal to the padding length. */
10256 if (isTLS) {
10257 PRUint8 *p;
10258 for (p = pPaddingLen - padding_length; p < pPaddingLen; ++p) {
10259 padIsBad |= *p ^ padding_length;
10265 /* Remove the MAC. */
10266 if (plaintext->len >= crSpec->mac_size)
10267 plaintext->len -= crSpec->mac_size;
10268 else
10269 padIsBad = PR_TRUE; /* really macIsBad */
10271 /* compute the MAC */
10272 rType = cText->type;
10273 rv = ssl3_ComputeRecordMAC( crSpec, (PRBool)(!ss->sec.isServer),
10274 IS_DTLS(ss), rType, cText->version,
10275 IS_DTLS(ss) ? cText->seq_num : crSpec->read_seq_num,
10276 plaintext->buf, plaintext->len, hash, &hashBytes);
10277 if (rv != SECSuccess) {
10278 padIsBad = PR_TRUE; /* really macIsBad */
10281 /* Check the MAC */
10282 if (hashBytes != (unsigned)crSpec->mac_size || padIsBad ||
10283 NSS_SecureMemcmp(plaintext->buf + plaintext->len, hash,
10284 crSpec->mac_size) != 0) {
10285 /* must not hold spec lock when calling SSL3_SendAlert. */
10286 ssl_ReleaseSpecReadLock(ss);
10288 SSL_DBG(("%d: SSL3[%d]: mac check failed", SSL_GETPID(), ss->fd));
10290 if (!IS_DTLS(ss)) {
10291 SSL3_SendAlert(ss, alert_fatal, bad_record_mac);
10292 /* always log mac error, in case attacker can read server logs. */
10293 PORT_SetError(SSL_ERROR_BAD_MAC_READ);
10294 return SECFailure;
10295 } else {
10296 /* Silently drop the packet */
10297 databuf->len = 0; /* Needed to ensure data not left around */
10298 return SECSuccess;
10302 if (!IS_DTLS(ss)) {
10303 ssl3_BumpSequenceNumber(&crSpec->read_seq_num);
10304 } else {
10305 dtls_RecordSetRecvd(&crSpec->recvdRecords, dtls_seq_num);
10308 ssl_ReleaseSpecReadLock(ss); /*****************************************/
10311 * The decrypted data is now in plaintext.
10314 /* possibly decompress the record. If we aren't using compression then
10315 * plaintext == databuf and so the uncompressed data is already in
10316 * databuf. */
10317 if (crSpec->decompressor) {
10318 if (databuf->space < plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION) {
10319 rv = sslBuffer_Grow(
10320 databuf, plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION);
10321 if (rv != SECSuccess) {
10322 SSL_DBG(("%d: SSL3[%d]: HandleRecord, tried to get %d bytes",
10323 SSL_GETPID(), ss->fd,
10324 plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION));
10325 /* sslBuffer_Grow has set a memory error code. */
10326 /* Perhaps we should send an alert. (but we have no memory!) */
10327 PORT_Free(plaintext->buf);
10328 return SECFailure;
10332 rv = crSpec->decompressor(crSpec->decompressContext,
10333 databuf->buf,
10334 (int*) &databuf->len,
10335 databuf->space,
10336 plaintext->buf,
10337 plaintext->len);
10339 if (rv != SECSuccess) {
10340 int err = ssl_MapLowLevelError(SSL_ERROR_DECOMPRESSION_FAILURE);
10341 SSL3_SendAlert(ss, alert_fatal,
10342 isTLS ? decompression_failure : bad_record_mac);
10344 /* There appears to be a bug with (at least) Apache + OpenSSL where
10345 * resumed SSLv3 connections don't actually use compression. See
10346 * comments 93-95 of
10347 * https://bugzilla.mozilla.org/show_bug.cgi?id=275744
10349 * So, if we get a decompression error, and the record appears to
10350 * be already uncompressed, then we return a more specific error
10351 * code to hopefully save somebody some debugging time in the
10352 * future.
10354 if (plaintext->len >= 4) {
10355 unsigned int len = ((unsigned int) plaintext->buf[1] << 16) |
10356 ((unsigned int) plaintext->buf[2] << 8) |
10357 (unsigned int) plaintext->buf[3];
10358 if (len == plaintext->len - 4) {
10359 /* This appears to be uncompressed already */
10360 err = SSL_ERROR_RX_UNEXPECTED_UNCOMPRESSED_RECORD;
10364 PORT_Free(plaintext->buf);
10365 PORT_SetError(err);
10366 return SECFailure;
10369 PORT_Free(plaintext->buf);
10373 ** Having completed the decompression, check the length again.
10375 if (isTLS && databuf->len > (MAX_FRAGMENT_LENGTH + 1024)) {
10376 SSL3_SendAlert(ss, alert_fatal, record_overflow);
10377 PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
10378 return SECFailure;
10381 /* Application data records are processed by the caller of this
10382 ** function, not by this function.
10384 if (rType == content_application_data) {
10385 if (ss->firstHsDone)
10386 return SECSuccess;
10387 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10388 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA);
10389 return SECFailure;
10392 /* It's a record that must be handled by ssl itself, not the application.
10394 process_it:
10395 /* XXX Get the xmit lock here. Odds are very high that we'll be xmiting
10396 * data ang getting the xmit lock here prevents deadlocks.
10398 ssl_GetSSL3HandshakeLock(ss);
10400 /* All the functions called in this switch MUST set error code if
10401 ** they return SECFailure or SECWouldBlock.
10403 switch (rType) {
10404 case content_change_cipher_spec:
10405 rv = ssl3_HandleChangeCipherSpecs(ss, databuf);
10406 break;
10407 case content_alert:
10408 rv = ssl3_HandleAlert(ss, databuf);
10409 break;
10410 case content_handshake:
10411 if (!IS_DTLS(ss)) {
10412 rv = ssl3_HandleHandshake(ss, databuf);
10413 } else {
10414 rv = dtls_HandleHandshake(ss, databuf);
10416 break;
10418 case content_application_data is handled before this switch
10420 default:
10421 SSL_DBG(("%d: SSL3[%d]: bogus content type=%d",
10422 SSL_GETPID(), ss->fd, cText->type));
10423 /* XXX Send an alert ??? */
10424 PORT_SetError(SSL_ERROR_RX_UNKNOWN_RECORD_TYPE);
10425 rv = SECFailure;
10426 break;
10429 ssl_ReleaseSSL3HandshakeLock(ss);
10430 return rv;
10435 * Initialization functions
10438 /* Called from ssl3_InitState, immediately below. */
10439 /* Caller must hold the SpecWriteLock. */
10440 static void
10441 ssl3_InitCipherSpec(sslSocket *ss, ssl3CipherSpec *spec)
10443 spec->cipher_def = &bulk_cipher_defs[cipher_null];
10444 PORT_Assert(spec->cipher_def->cipher == cipher_null);
10445 spec->mac_def = &mac_defs[mac_null];
10446 PORT_Assert(spec->mac_def->mac == mac_null);
10447 spec->encode = Null_Cipher;
10448 spec->decode = Null_Cipher;
10449 spec->destroy = NULL;
10450 spec->compressor = NULL;
10451 spec->decompressor = NULL;
10452 spec->destroyCompressContext = NULL;
10453 spec->destroyDecompressContext = NULL;
10454 spec->mac_size = 0;
10455 spec->master_secret = NULL;
10456 spec->bypassCiphers = PR_FALSE;
10458 spec->msItem.data = NULL;
10459 spec->msItem.len = 0;
10461 spec->client.write_key = NULL;
10462 spec->client.write_mac_key = NULL;
10463 spec->client.write_mac_context = NULL;
10465 spec->server.write_key = NULL;
10466 spec->server.write_mac_key = NULL;
10467 spec->server.write_mac_context = NULL;
10469 spec->write_seq_num.high = 0;
10470 spec->write_seq_num.low = 0;
10472 spec->read_seq_num.high = 0;
10473 spec->read_seq_num.low = 0;
10475 spec->epoch = 0;
10476 dtls_InitRecvdRecords(&spec->recvdRecords);
10478 spec->version = ss->vrange.max;
10481 /* Called from: ssl3_SendRecord
10482 ** ssl3_StartHandshakeHash() <- ssl2_BeginClientHandshake()
10483 ** ssl3_SendClientHello()
10484 ** ssl3_HandleServerHello()
10485 ** ssl3_HandleClientHello()
10486 ** ssl3_HandleV2ClientHello()
10487 ** ssl3_HandleRecord()
10489 ** This function should perhaps acquire and release the SpecWriteLock.
10493 static SECStatus
10494 ssl3_InitState(sslSocket *ss)
10496 SECStatus rv;
10497 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10499 if (ss->ssl3.initialized)
10500 return SECSuccess; /* Function should be idempotent */
10502 ss->ssl3.policy = SSL_ALLOWED;
10504 ssl_GetSpecWriteLock(ss);
10505 ss->ssl3.crSpec = ss->ssl3.cwSpec = &ss->ssl3.specs[0];
10506 ss->ssl3.prSpec = ss->ssl3.pwSpec = &ss->ssl3.specs[1];
10507 ss->ssl3.hs.sendingSCSV = PR_FALSE;
10508 ssl3_InitCipherSpec(ss, ss->ssl3.crSpec);
10509 ssl3_InitCipherSpec(ss, ss->ssl3.prSpec);
10511 ss->ssl3.hs.ws = (ss->sec.isServer) ? wait_client_hello : wait_server_hello;
10512 #ifdef NSS_ENABLE_ECC
10513 ss->ssl3.hs.negotiatedECCurves = SSL3_SUPPORTED_CURVES_MASK;
10514 #endif
10515 ssl_ReleaseSpecWriteLock(ss);
10517 PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData));
10519 if (IS_DTLS(ss)) {
10520 ss->ssl3.hs.sendMessageSeq = 0;
10521 ss->ssl3.hs.recvMessageSeq = 0;
10522 ss->ssl3.hs.rtTimeoutMs = INITIAL_DTLS_TIMEOUT_MS;
10523 ss->ssl3.hs.rtRetries = 0;
10524 ss->ssl3.hs.recvdHighWater = -1;
10525 PR_INIT_CLIST(&ss->ssl3.hs.lastMessageFlight);
10526 dtls_SetMTU(ss, 0); /* Set the MTU to the highest plateau */
10529 rv = ssl3_NewHandshakeHashes(ss);
10530 if (rv == SECSuccess) {
10531 ss->ssl3.initialized = PR_TRUE;
10534 return rv;
10537 /* Returns a reference counted object that contains a key pair.
10538 * Or NULL on failure. Initial ref count is 1.
10539 * Uses the keys in the pair as input.
10541 ssl3KeyPair *
10542 ssl3_NewKeyPair( SECKEYPrivateKey * privKey, SECKEYPublicKey * pubKey)
10544 ssl3KeyPair * pair;
10546 if (!privKey || !pubKey) {
10547 PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
10548 return NULL;
10550 pair = PORT_ZNew(ssl3KeyPair);
10551 if (!pair)
10552 return NULL; /* error code is set. */
10553 pair->refCount = 1;
10554 pair->privKey = privKey;
10555 pair->pubKey = pubKey;
10556 return pair; /* success */
10559 ssl3KeyPair *
10560 ssl3_GetKeyPairRef(ssl3KeyPair * keyPair)
10562 PR_ATOMIC_INCREMENT(&keyPair->refCount);
10563 return keyPair;
10566 void
10567 ssl3_FreeKeyPair(ssl3KeyPair * keyPair)
10569 PRInt32 newCount = PR_ATOMIC_DECREMENT(&keyPair->refCount);
10570 if (!newCount) {
10571 if (keyPair->privKey)
10572 SECKEY_DestroyPrivateKey(keyPair->privKey);
10573 if (keyPair->pubKey)
10574 SECKEY_DestroyPublicKey( keyPair->pubKey);
10575 PORT_Free(keyPair);
10582 * Creates the public and private RSA keys for SSL Step down.
10583 * Called from SSL_ConfigSecureServer in sslsecur.c
10585 SECStatus
10586 ssl3_CreateRSAStepDownKeys(sslSocket *ss)
10588 SECStatus rv = SECSuccess;
10589 SECKEYPrivateKey * privKey; /* RSA step down key */
10590 SECKEYPublicKey * pubKey; /* RSA step down key */
10592 if (ss->stepDownKeyPair)
10593 ssl3_FreeKeyPair(ss->stepDownKeyPair);
10594 ss->stepDownKeyPair = NULL;
10595 #ifndef HACKED_EXPORT_SERVER
10596 /* Sigh, should have a get key strength call for private keys */
10597 if (PK11_GetPrivateModulusLen(ss->serverCerts[kt_rsa].SERVERKEY) >
10598 EXPORT_RSA_KEY_LENGTH) {
10599 /* need to ask for the key size in bits */
10600 privKey = SECKEY_CreateRSAPrivateKey(EXPORT_RSA_KEY_LENGTH * BPB,
10601 &pubKey, NULL);
10602 if (!privKey || !pubKey ||
10603 !(ss->stepDownKeyPair = ssl3_NewKeyPair(privKey, pubKey))) {
10604 ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL);
10605 rv = SECFailure;
10608 #endif
10609 return rv;
10613 /* record the export policy for this cipher suite */
10614 SECStatus
10615 ssl3_SetPolicy(ssl3CipherSuite which, int policy)
10617 ssl3CipherSuiteCfg *suite;
10619 suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
10620 if (suite == NULL) {
10621 return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
10623 suite->policy = policy;
10625 return SECSuccess;
10628 SECStatus
10629 ssl3_GetPolicy(ssl3CipherSuite which, PRInt32 *oPolicy)
10631 ssl3CipherSuiteCfg *suite;
10632 PRInt32 policy;
10633 SECStatus rv;
10635 suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
10636 if (suite) {
10637 policy = suite->policy;
10638 rv = SECSuccess;
10639 } else {
10640 policy = SSL_NOT_ALLOWED;
10641 rv = SECFailure; /* err code was set by Lookup. */
10643 *oPolicy = policy;
10644 return rv;
10647 /* record the user preference for this suite */
10648 SECStatus
10649 ssl3_CipherPrefSetDefault(ssl3CipherSuite which, PRBool enabled)
10651 ssl3CipherSuiteCfg *suite;
10653 suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
10654 if (suite == NULL) {
10655 return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
10657 suite->enabled = enabled;
10658 return SECSuccess;
10661 /* return the user preference for this suite */
10662 SECStatus
10663 ssl3_CipherPrefGetDefault(ssl3CipherSuite which, PRBool *enabled)
10665 ssl3CipherSuiteCfg *suite;
10666 PRBool pref;
10667 SECStatus rv;
10669 suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
10670 if (suite) {
10671 pref = suite->enabled;
10672 rv = SECSuccess;
10673 } else {
10674 pref = SSL_NOT_ALLOWED;
10675 rv = SECFailure; /* err code was set by Lookup. */
10677 *enabled = pref;
10678 return rv;
10681 SECStatus
10682 ssl3_CipherPrefSet(sslSocket *ss, ssl3CipherSuite which, PRBool enabled)
10684 ssl3CipherSuiteCfg *suite;
10686 suite = ssl_LookupCipherSuiteCfg(which, ss->cipherSuites);
10687 if (suite == NULL) {
10688 return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
10690 suite->enabled = enabled;
10691 return SECSuccess;
10694 SECStatus
10695 ssl3_CipherPrefGet(sslSocket *ss, ssl3CipherSuite which, PRBool *enabled)
10697 ssl3CipherSuiteCfg *suite;
10698 PRBool pref;
10699 SECStatus rv;
10701 suite = ssl_LookupCipherSuiteCfg(which, ss->cipherSuites);
10702 if (suite) {
10703 pref = suite->enabled;
10704 rv = SECSuccess;
10705 } else {
10706 pref = SSL_NOT_ALLOWED;
10707 rv = SECFailure; /* err code was set by Lookup. */
10709 *enabled = pref;
10710 return rv;
10713 /* copy global default policy into socket. */
10714 void
10715 ssl3_InitSocketPolicy(sslSocket *ss)
10717 PORT_Memcpy(ss->cipherSuites, cipherSuites, sizeof cipherSuites);
10720 SECStatus
10721 ssl3_GetTLSUniqueChannelBinding(sslSocket *ss,
10722 unsigned char *out,
10723 unsigned int *outLen,
10724 unsigned int outLenMax) {
10725 PRBool isTLS;
10726 int index = 0;
10727 unsigned int len;
10728 SECStatus rv = SECFailure;
10730 *outLen = 0;
10732 ssl_GetSSL3HandshakeLock(ss);
10734 ssl_GetSpecReadLock(ss);
10735 isTLS = (PRBool)(ss->ssl3.cwSpec->version > SSL_LIBRARY_VERSION_3_0);
10736 ssl_ReleaseSpecReadLock(ss);
10738 /* The tls-unique channel binding is the first Finished structure in the
10739 * handshake. In the case of a resumption, that's the server's Finished.
10740 * Otherwise, it's the client's Finished. */
10741 len = ss->ssl3.hs.finishedBytes;
10743 /* Sending or receiving a Finished message will set finishedBytes to a
10744 * non-zero value. */
10745 if (len == 0) {
10746 PORT_SetError(SSL_ERROR_HANDSHAKE_NOT_COMPLETED);
10747 goto loser;
10750 /* If we are in the middle of a renegotiation then the channel binding
10751 * value is poorly defined and depends on the direction that it will be
10752 * used on. Therefore we simply return an error in this case. */
10753 if (ss->firstHsDone && ss->ssl3.hs.ws != idle_handshake) {
10754 PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED);
10755 goto loser;
10758 /* If resuming, then we want the second Finished value in the array, which
10759 * is the server's */
10760 if (ss->ssl3.hs.isResuming)
10761 index = 1;
10763 *outLen = len;
10764 if (outLenMax < len) {
10765 PORT_SetError(SEC_ERROR_OUTPUT_LEN);
10766 goto loser;
10769 if (isTLS) {
10770 memcpy(out, &ss->ssl3.hs.finishedMsgs.tFinished[index], len);
10771 } else {
10772 memcpy(out, &ss->ssl3.hs.finishedMsgs.sFinished[index], len);
10775 rv = SECSuccess;
10777 loser:
10778 ssl_ReleaseSSL3HandshakeLock(ss);
10779 return rv;
10782 /* ssl3_config_match_init must have already been called by
10783 * the caller of this function.
10785 SECStatus
10786 ssl3_ConstructV2CipherSpecsHack(sslSocket *ss, unsigned char *cs, int *size)
10788 int i, count = 0;
10790 PORT_Assert(ss != 0);
10791 if (!ss) {
10792 PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
10793 return SECFailure;
10795 if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
10796 *size = 0;
10797 return SECSuccess;
10799 if (cs == NULL) {
10800 *size = count_cipher_suites(ss, SSL_ALLOWED, PR_TRUE);
10801 return SECSuccess;
10804 /* ssl3_config_match_init was called by the caller of this function. */
10805 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
10806 ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i];
10807 if (config_match(suite, SSL_ALLOWED, PR_TRUE)) {
10808 if (cs != NULL) {
10809 *cs++ = 0x00;
10810 *cs++ = (suite->cipher_suite >> 8) & 0xFF;
10811 *cs++ = suite->cipher_suite & 0xFF;
10813 count++;
10816 *size = count;
10817 return SECSuccess;
10821 ** If ssl3 socket has completed the first handshake, and is in idle state,
10822 ** then start a new handshake.
10823 ** If flushCache is true, the SID cache will be flushed first, forcing a
10824 ** "Full" handshake (not a session restart handshake), to be done.
10826 ** called from SSL_RedoHandshake(), which already holds the handshake locks.
10828 SECStatus
10829 ssl3_RedoHandshake(sslSocket *ss, PRBool flushCache)
10831 sslSessionID * sid = ss->sec.ci.sid;
10832 SECStatus rv;
10834 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
10836 if (!ss->firstHsDone ||
10837 ((ss->version >= SSL_LIBRARY_VERSION_3_0) &&
10838 ss->ssl3.initialized &&
10839 (ss->ssl3.hs.ws != idle_handshake))) {
10840 PORT_SetError(SSL_ERROR_HANDSHAKE_NOT_COMPLETED);
10841 return SECFailure;
10844 if (IS_DTLS(ss)) {
10845 dtls_RehandshakeCleanup(ss);
10848 if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) {
10849 PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED);
10850 return SECFailure;
10852 if (sid && flushCache) {
10853 if (ss->sec.uncache)
10854 ss->sec.uncache(sid); /* remove it from whichever cache it's in. */
10855 ssl_FreeSID(sid); /* dec ref count and free if zero. */
10856 ss->sec.ci.sid = NULL;
10859 ssl_GetXmitBufLock(ss); /**************************************/
10861 /* start off a new handshake. */
10862 rv = (ss->sec.isServer) ? ssl3_SendHelloRequest(ss)
10863 : ssl3_SendClientHello(ss, PR_FALSE);
10865 ssl_ReleaseXmitBufLock(ss); /**************************************/
10866 return rv;
10869 /* Called from ssl_DestroySocketContents() in sslsock.c */
10870 void
10871 ssl3_DestroySSL3Info(sslSocket *ss)
10874 if (ss->ssl3.clientCertificate != NULL)
10875 CERT_DestroyCertificate(ss->ssl3.clientCertificate);
10877 if (ss->ssl3.clientPrivateKey != NULL)
10878 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
10879 #ifdef NSS_PLATFORM_CLIENT_AUTH
10880 if (ss->ssl3.platformClientKey)
10881 ssl_FreePlatformKey(ss->ssl3.platformClientKey);
10882 #endif /* NSS_PLATFORM_CLIENT_AUTH */
10884 if (ss->ssl3.channelID)
10885 SECKEY_DestroyPrivateKey(ss->ssl3.channelID);
10886 if (ss->ssl3.channelIDPub)
10887 SECKEY_DestroyPublicKey(ss->ssl3.channelIDPub);
10889 if (ss->ssl3.peerCertArena != NULL)
10890 ssl3_CleanupPeerCerts(ss);
10892 if (ss->ssl3.clientCertChain != NULL) {
10893 CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
10894 ss->ssl3.clientCertChain = NULL;
10897 /* clean up handshake */
10898 #ifndef NO_PKCS11_BYPASS
10899 if (ss->opt.bypassPKCS11) {
10900 SHA1_DestroyContext((SHA1Context *)ss->ssl3.hs.sha_cx, PR_FALSE);
10901 MD5_DestroyContext((MD5Context *)ss->ssl3.hs.md5_cx, PR_FALSE);
10903 #endif
10904 if (ss->ssl3.hs.md5) {
10905 PK11_DestroyContext(ss->ssl3.hs.md5,PR_TRUE);
10907 if (ss->ssl3.hs.sha) {
10908 PK11_DestroyContext(ss->ssl3.hs.sha,PR_TRUE);
10910 if (ss->ssl3.hs.messages.buf) {
10911 PORT_Free(ss->ssl3.hs.messages.buf);
10912 ss->ssl3.hs.messages.buf = NULL;
10913 ss->ssl3.hs.messages.len = 0;
10914 ss->ssl3.hs.messages.space = 0;
10916 if (ss->ssl3.hs.pending_cert_msg.data) {
10917 SECITEM_FreeItem(&ss->ssl3.hs.pending_cert_msg, PR_FALSE);
10919 if (ss->ssl3.hs.cert_status.data) {
10920 SECITEM_FreeItem(&ss->ssl3.hs.cert_status, PR_FALSE);
10923 /* free the SSL3Buffer (msg_body) */
10924 PORT_Free(ss->ssl3.hs.msg_body.buf);
10926 /* free up the CipherSpecs */
10927 ssl3_DestroyCipherSpec(&ss->ssl3.specs[0], PR_TRUE/*freeSrvName*/);
10928 ssl3_DestroyCipherSpec(&ss->ssl3.specs[1], PR_TRUE/*freeSrvName*/);
10930 /* Destroy the DTLS data */
10931 if (IS_DTLS(ss)) {
10932 dtls_FreeHandshakeMessages(&ss->ssl3.hs.lastMessageFlight);
10933 if (ss->ssl3.hs.recvdFragments.buf) {
10934 PORT_Free(ss->ssl3.hs.recvdFragments.buf);
10938 ss->ssl3.initialized = PR_FALSE;
10940 SECITEM_FreeItem(&ss->ssl3.nextProto, PR_FALSE);
10943 /* End of ssl3con.c */