1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
9 /* TODO(ekr): Implement HelloVerifyRequest on server side. OK for now. */
13 #include "cryptohi.h" /* for DSAU_ stuff */
30 #ifndef NO_PKCS11_BYPASS
35 #ifdef NSS_ENABLE_ZLIB
40 #define PK11_SETATTRS(x,id,v,l) (x)->type = (id); \
41 (x)->pValue=(v); (x)->ulValueLen = (l);
44 static SECStatus ssl3_AuthCertificate(sslSocket *ss);
45 static void ssl3_CleanupPeerCerts(sslSocket *ss);
46 static PK11SymKey *ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec,
47 PK11SlotInfo * serverKeySlot);
48 static SECStatus ssl3_DeriveMasterSecret(sslSocket *ss, PK11SymKey *pms);
49 static SECStatus ssl3_DeriveConnectionKeysPKCS11(sslSocket *ss);
50 static SECStatus ssl3_HandshakeFailure( sslSocket *ss);
51 static SECStatus ssl3_InitState( sslSocket *ss);
52 static SECStatus ssl3_SendCertificate( sslSocket *ss);
53 static SECStatus ssl3_SendCertificateStatus( sslSocket *ss);
54 static SECStatus ssl3_SendEmptyCertificate( sslSocket *ss);
55 static SECStatus ssl3_SendCertificateRequest(sslSocket *ss);
56 static SECStatus ssl3_SendNextProto( sslSocket *ss);
57 static SECStatus ssl3_SendFinished( sslSocket *ss, PRInt32 flags);
58 static SECStatus ssl3_SendServerHello( sslSocket *ss);
59 static SECStatus ssl3_SendServerHelloDone( sslSocket *ss);
60 static SECStatus ssl3_SendServerKeyExchange( sslSocket *ss);
61 static SECStatus ssl3_UpdateHandshakeHashes( sslSocket *ss,
62 const unsigned char *b,
64 static SECStatus ssl3_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags);
65 static int ssl3_OIDToTLSHashAlgorithm(SECOidTag oid);
67 static SECStatus Null_Cipher(void *ctx, unsigned char *output, int *outputLen,
68 int maxOutputLen, const unsigned char *input,
70 #ifndef NO_PKCS11_BYPASS
71 static SECStatus ssl3_AESGCMBypass(ssl3KeyMaterial *keys, PRBool doDecrypt,
72 unsigned char *out, int *outlen, int maxout,
73 const unsigned char *in, int inlen,
74 const unsigned char *additionalData,
75 int additionalDataLen);
78 #define MAX_SEND_BUF_LENGTH 32000 /* watch for 16-bit integer overflow */
79 #define MIN_SEND_BUF_LENGTH 4000
81 /* This list of SSL3 cipher suites is sorted in descending order of
82 * precedence (desirability). It only includes cipher suites we implement.
83 * This table is modified by SSL3_SetPolicy(). The ordering of cipher suites
84 * in this table must match the ordering in SSL_ImplementedCiphers (sslenum.c)
86 static ssl3CipherSuiteCfg cipherSuites[ssl_V3_SUITES_IMPLEMENTED] = {
87 /* cipher_suite policy enabled isPresent */
89 { TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE},
90 { TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE},
91 #endif /* NSS_ENABLE_ECC */
92 { TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE},
93 { TLS_RSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE},
96 { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
97 { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
98 #endif /* NSS_ENABLE_ECC */
99 { TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
100 { TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
101 { TLS_DHE_RSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE},
102 { TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE},
103 { TLS_DHE_DSS_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE},
104 #ifdef NSS_ENABLE_ECC
105 { TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
106 { TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
107 #endif /* NSS_ENABLE_ECC */
108 { TLS_RSA_WITH_CAMELLIA_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
109 { TLS_RSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE},
110 { TLS_RSA_WITH_AES_256_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE},
112 #ifdef NSS_ENABLE_ECC
113 { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
114 { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE},
115 { TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
116 { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
117 { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE},
118 { TLS_ECDHE_RSA_WITH_RC4_128_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
119 #endif /* NSS_ENABLE_ECC */
120 { TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
121 { TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
122 { TLS_DHE_RSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE},
123 { TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE},
124 { TLS_DHE_DSS_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE},
125 { TLS_DHE_DSS_WITH_RC4_128_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
126 #ifdef NSS_ENABLE_ECC
127 { TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
128 { TLS_ECDH_RSA_WITH_RC4_128_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
129 { TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
130 { TLS_ECDH_ECDSA_WITH_RC4_128_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
131 #endif /* NSS_ENABLE_ECC */
132 { TLS_RSA_WITH_SEED_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
133 { TLS_RSA_WITH_CAMELLIA_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
134 { TLS_RSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE},
135 { TLS_RSA_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE},
136 { SSL_RSA_WITH_RC4_128_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE},
137 { SSL_RSA_WITH_RC4_128_MD5, SSL_ALLOWED, PR_TRUE, PR_FALSE},
139 #ifdef NSS_ENABLE_ECC
140 { TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
141 { TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
142 #endif /* NSS_ENABLE_ECC */
143 { SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE},
144 { SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE},
145 #ifdef NSS_ENABLE_ECC
146 { TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
147 { TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
148 #endif /* NSS_ENABLE_ECC */
149 { SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
150 { SSL_RSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE},
153 { SSL_DHE_RSA_WITH_DES_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
154 { SSL_DHE_DSS_WITH_DES_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
155 { SSL_RSA_FIPS_WITH_DES_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
156 { SSL_RSA_WITH_DES_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
157 { TLS_RSA_EXPORT1024_WITH_RC4_56_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
158 { TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
160 { SSL_RSA_EXPORT_WITH_RC4_40_MD5, SSL_ALLOWED, PR_FALSE, PR_FALSE},
161 { SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5, SSL_ALLOWED, PR_FALSE, PR_FALSE},
163 #ifdef NSS_ENABLE_ECC
164 { TLS_ECDHE_ECDSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
165 { TLS_ECDHE_RSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
166 { TLS_ECDH_RSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
167 { TLS_ECDH_ECDSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
168 #endif /* NSS_ENABLE_ECC */
169 { SSL_RSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
170 { TLS_RSA_WITH_NULL_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE},
171 { SSL_RSA_WITH_NULL_MD5, SSL_ALLOWED, PR_FALSE, PR_FALSE},
174 /* This list of SSL3 compression methods is sorted in descending order of
175 * precedence (desirability). It only includes compression methods we
178 static const /*SSLCompressionMethod*/ PRUint8 compressions [] = {
179 #ifdef NSS_ENABLE_ZLIB
180 ssl_compression_deflate,
185 static const int compressionMethodsCount =
186 sizeof(compressions) / sizeof(compressions[0]);
188 /* compressionEnabled returns true iff the compression algorithm is enabled
189 * for the given SSL socket. */
191 compressionEnabled(sslSocket *ss, SSLCompressionMethod compression)
193 switch (compression) {
194 case ssl_compression_null:
195 return PR_TRUE; /* Always enabled */
196 #ifdef NSS_ENABLE_ZLIB
197 case ssl_compression_deflate:
198 return ss->opt.enableDeflate;
205 static const /*SSL3ClientCertificateType */ PRUint8 certificate_types [] = {
207 #ifdef NSS_ENABLE_ECC
209 #endif /* NSS_ENABLE_ECC */
213 /* This block is the contents of the supported_signature_algorithms field of
214 * our TLS 1.2 CertificateRequest message, in wire format. See
215 * https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1
217 * This block contains only sha256 entries because we only support TLS 1.2
218 * CertificateVerify messages that use the handshake hash. */
219 static const PRUint8 supported_signature_algorithms[] = {
220 tls_hash_sha256, tls_sig_rsa,
221 #ifdef NSS_ENABLE_ECC
222 tls_hash_sha256, tls_sig_ecdsa,
224 tls_hash_sha256, tls_sig_dsa,
227 #define EXPORT_RSA_KEY_LENGTH 64 /* bytes */
230 /* This global item is used only in servers. It is is initialized by
231 ** SSL_ConfigSecureServer(), and is used in ssl3_SendCertificateRequest().
233 CERTDistNames *ssl3_server_ca_list = NULL;
234 static SSL3Statistics ssl3stats;
236 /* indexed by SSL3BulkCipher */
237 static const ssl3BulkCipherDef bulk_cipher_defs[] = {
238 /* |--------- Lengths --------| */
239 /* cipher calg k s type i b t n */
245 {cipher_null, calg_null, 0, 0, type_stream, 0, 0, 0, 0},
246 {cipher_rc4, calg_rc4, 16,16, type_stream, 0, 0, 0, 0},
247 {cipher_rc4_40, calg_rc4, 16, 5, type_stream, 0, 0, 0, 0},
248 {cipher_rc4_56, calg_rc4, 16, 7, type_stream, 0, 0, 0, 0},
249 {cipher_rc2, calg_rc2, 16,16, type_block, 8, 8, 0, 0},
250 {cipher_rc2_40, calg_rc2, 16, 5, type_block, 8, 8, 0, 0},
251 {cipher_des, calg_des, 8, 8, type_block, 8, 8, 0, 0},
252 {cipher_3des, calg_3des, 24,24, type_block, 8, 8, 0, 0},
253 {cipher_des40, calg_des, 8, 5, type_block, 8, 8, 0, 0},
254 {cipher_idea, calg_idea, 16,16, type_block, 8, 8, 0, 0},
255 {cipher_aes_128, calg_aes, 16,16, type_block, 16,16, 0, 0},
256 {cipher_aes_256, calg_aes, 32,32, type_block, 16,16, 0, 0},
257 {cipher_camellia_128, calg_camellia, 16,16, type_block, 16,16, 0, 0},
258 {cipher_camellia_256, calg_camellia, 32,32, type_block, 16,16, 0, 0},
259 {cipher_seed, calg_seed, 16,16, type_block, 16,16, 0, 0},
260 {cipher_aes_128_gcm, calg_aes_gcm, 16,16, type_aead, 4, 0,16, 8},
261 {cipher_missing, calg_null, 0, 0, type_stream, 0, 0, 0, 0},
264 static const ssl3KEADef kea_defs[] =
265 { /* indexed by SSL3KeyExchangeAlgorithm */
266 /* kea exchKeyType signKeyType is_limited limit tls_keygen */
267 {kea_null, kt_null, sign_null, PR_FALSE, 0, PR_FALSE},
268 {kea_rsa, kt_rsa, sign_rsa, PR_FALSE, 0, PR_FALSE},
269 {kea_rsa_export, kt_rsa, sign_rsa, PR_TRUE, 512, PR_FALSE},
270 {kea_rsa_export_1024,kt_rsa, sign_rsa, PR_TRUE, 1024, PR_FALSE},
271 {kea_dh_dss, kt_dh, sign_dsa, PR_FALSE, 0, PR_FALSE},
272 {kea_dh_dss_export, kt_dh, sign_dsa, PR_TRUE, 512, PR_FALSE},
273 {kea_dh_rsa, kt_dh, sign_rsa, PR_FALSE, 0, PR_FALSE},
274 {kea_dh_rsa_export, kt_dh, sign_rsa, PR_TRUE, 512, PR_FALSE},
275 {kea_dhe_dss, kt_dh, sign_dsa, PR_FALSE, 0, PR_FALSE},
276 {kea_dhe_dss_export, kt_dh, sign_dsa, PR_TRUE, 512, PR_FALSE},
277 {kea_dhe_rsa, kt_dh, sign_rsa, PR_FALSE, 0, PR_FALSE},
278 {kea_dhe_rsa_export, kt_dh, sign_rsa, PR_TRUE, 512, PR_FALSE},
279 {kea_dh_anon, kt_dh, sign_null, PR_FALSE, 0, PR_FALSE},
280 {kea_dh_anon_export, kt_dh, sign_null, PR_TRUE, 512, PR_FALSE},
281 {kea_rsa_fips, kt_rsa, sign_rsa, PR_FALSE, 0, PR_TRUE },
282 #ifdef NSS_ENABLE_ECC
283 {kea_ecdh_ecdsa, kt_ecdh, sign_ecdsa, PR_FALSE, 0, PR_FALSE},
284 {kea_ecdhe_ecdsa, kt_ecdh, sign_ecdsa, PR_FALSE, 0, PR_FALSE},
285 {kea_ecdh_rsa, kt_ecdh, sign_rsa, PR_FALSE, 0, PR_FALSE},
286 {kea_ecdhe_rsa, kt_ecdh, sign_rsa, PR_FALSE, 0, PR_FALSE},
287 {kea_ecdh_anon, kt_ecdh, sign_null, PR_FALSE, 0, PR_FALSE},
288 #endif /* NSS_ENABLE_ECC */
291 /* must use ssl_LookupCipherSuiteDef to access */
292 static const ssl3CipherSuiteDef cipher_suite_defs[] =
294 /* cipher_suite bulk_cipher_alg mac_alg key_exchange_alg */
296 {SSL_NULL_WITH_NULL_NULL, cipher_null, mac_null, kea_null},
297 {SSL_RSA_WITH_NULL_MD5, cipher_null, mac_md5, kea_rsa},
298 {SSL_RSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_rsa},
299 {TLS_RSA_WITH_NULL_SHA256, cipher_null, hmac_sha256, kea_rsa},
300 {SSL_RSA_EXPORT_WITH_RC4_40_MD5,cipher_rc4_40, mac_md5, kea_rsa_export},
301 {SSL_RSA_WITH_RC4_128_MD5, cipher_rc4, mac_md5, kea_rsa},
302 {SSL_RSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_rsa},
303 {SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5,
304 cipher_rc2_40, mac_md5, kea_rsa_export},
305 #if 0 /* not implemented */
306 {SSL_RSA_WITH_IDEA_CBC_SHA, cipher_idea, mac_sha, kea_rsa},
307 {SSL_RSA_EXPORT_WITH_DES40_CBC_SHA,
308 cipher_des40, mac_sha, kea_rsa_export},
310 {SSL_RSA_WITH_DES_CBC_SHA, cipher_des, mac_sha, kea_rsa},
311 {SSL_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_rsa},
312 {SSL_DHE_DSS_WITH_DES_CBC_SHA, cipher_des, mac_sha, kea_dhe_dss},
313 {SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA,
314 cipher_3des, mac_sha, kea_dhe_dss},
315 {TLS_DHE_DSS_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_dhe_dss},
316 #if 0 /* not implemented */
317 {SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA,
318 cipher_des40, mac_sha, kea_dh_dss_export},
319 {SSL_DH_DSS_DES_CBC_SHA, cipher_des, mac_sha, kea_dh_dss},
320 {SSL_DH_DSS_3DES_CBC_SHA, cipher_3des, mac_sha, kea_dh_dss},
321 {SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA,
322 cipher_des40, mac_sha, kea_dh_rsa_export},
323 {SSL_DH_RSA_DES_CBC_SHA, cipher_des, mac_sha, kea_dh_rsa},
324 {SSL_DH_RSA_3DES_CBC_SHA, cipher_3des, mac_sha, kea_dh_rsa},
325 {SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA,
326 cipher_des40, mac_sha, kea_dh_dss_export},
327 {SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA,
328 cipher_des40, mac_sha, kea_dh_rsa_export},
330 {SSL_DHE_RSA_WITH_DES_CBC_SHA, cipher_des, mac_sha, kea_dhe_rsa},
331 {SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA,
332 cipher_3des, mac_sha, kea_dhe_rsa},
334 {SSL_DH_ANON_EXPORT_RC4_40_MD5, cipher_rc4_40, mac_md5, kea_dh_anon_export},
335 {SSL_DH_ANON_EXPORT_WITH_DES40_CBC_SHA,
336 cipher_des40, mac_sha, kea_dh_anon_export},
337 {SSL_DH_ANON_DES_CBC_SHA, cipher_des, mac_sha, kea_dh_anon},
338 {SSL_DH_ANON_3DES_CBC_SHA, cipher_3des, mac_sha, kea_dh_anon},
342 /* New TLS cipher suites */
343 {TLS_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_rsa},
344 {TLS_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_rsa},
345 {TLS_DHE_DSS_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dhe_dss},
346 {TLS_DHE_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dhe_rsa},
347 {TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_dhe_rsa},
348 {TLS_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_rsa},
349 {TLS_RSA_WITH_AES_256_CBC_SHA256, cipher_aes_256, hmac_sha256, kea_rsa},
350 {TLS_DHE_DSS_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dhe_dss},
351 {TLS_DHE_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dhe_rsa},
352 {TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, cipher_aes_256, hmac_sha256, kea_dhe_rsa},
354 {TLS_DH_DSS_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dh_dss},
355 {TLS_DH_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dh_rsa},
356 {TLS_DH_ANON_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dh_anon},
357 {TLS_DH_DSS_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dh_dss},
358 {TLS_DH_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dh_rsa},
359 {TLS_DH_ANON_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dh_anon},
362 {TLS_RSA_WITH_SEED_CBC_SHA, cipher_seed, mac_sha, kea_rsa},
364 {TLS_RSA_WITH_CAMELLIA_128_CBC_SHA, cipher_camellia_128, mac_sha, kea_rsa},
365 {TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA,
366 cipher_camellia_128, mac_sha, kea_dhe_dss},
367 {TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA,
368 cipher_camellia_128, mac_sha, kea_dhe_rsa},
369 {TLS_RSA_WITH_CAMELLIA_256_CBC_SHA, cipher_camellia_256, mac_sha, kea_rsa},
370 {TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA,
371 cipher_camellia_256, mac_sha, kea_dhe_dss},
372 {TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA,
373 cipher_camellia_256, mac_sha, kea_dhe_rsa},
375 {TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA,
376 cipher_des, mac_sha,kea_rsa_export_1024},
377 {TLS_RSA_EXPORT1024_WITH_RC4_56_SHA,
378 cipher_rc4_56, mac_sha,kea_rsa_export_1024},
380 {SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_rsa_fips},
381 {SSL_RSA_FIPS_WITH_DES_CBC_SHA, cipher_des, mac_sha, kea_rsa_fips},
383 {TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_dhe_rsa},
384 {TLS_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_rsa},
385 {TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_ecdhe_rsa},
386 {TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_ecdhe_ecdsa},
388 #ifdef NSS_ENABLE_ECC
389 {TLS_ECDH_ECDSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdh_ecdsa},
390 {TLS_ECDH_ECDSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdh_ecdsa},
391 {TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdh_ecdsa},
392 {TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdh_ecdsa},
393 {TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdh_ecdsa},
395 {TLS_ECDHE_ECDSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdhe_ecdsa},
396 {TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdhe_ecdsa},
397 {TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdhe_ecdsa},
398 {TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdhe_ecdsa},
399 {TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_ecdhe_ecdsa},
400 {TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdhe_ecdsa},
402 {TLS_ECDH_RSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdh_rsa},
403 {TLS_ECDH_RSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdh_rsa},
404 {TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdh_rsa},
405 {TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdh_rsa},
406 {TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdh_rsa},
408 {TLS_ECDHE_RSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdhe_rsa},
409 {TLS_ECDHE_RSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdhe_rsa},
410 {TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdhe_rsa},
411 {TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdhe_rsa},
412 {TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_ecdhe_rsa},
413 {TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdhe_rsa},
416 {TLS_ECDH_anon_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdh_anon},
417 {TLS_ECDH_anon_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdh_anon},
418 {TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdh_anon},
419 {TLS_ECDH_anon_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdh_anon},
420 {TLS_ECDH_anon_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdh_anon},
422 #endif /* NSS_ENABLE_ECC */
425 static const CK_MECHANISM_TYPE kea_alg_defs[] = {
433 typedef struct SSLCipher2MechStr {
434 SSLCipherAlgorithm calg;
435 CK_MECHANISM_TYPE cmech;
438 /* indexed by type SSLCipherAlgorithm */
439 static const SSLCipher2Mech alg2Mech[] = {
441 { calg_null , (CK_MECHANISM_TYPE)0x80000000L },
442 { calg_rc4 , CKM_RC4 },
443 { calg_rc2 , CKM_RC2_CBC },
444 { calg_des , CKM_DES_CBC },
445 { calg_3des , CKM_DES3_CBC },
446 { calg_idea , CKM_IDEA_CBC },
447 { calg_fortezza , CKM_SKIPJACK_CBC64 },
448 { calg_aes , CKM_AES_CBC },
449 { calg_camellia , CKM_CAMELLIA_CBC },
450 { calg_seed , CKM_SEED_CBC },
451 { calg_aes_gcm , CKM_AES_GCM },
452 /* { calg_init , (CK_MECHANISM_TYPE)0x7fffffffL } */
455 #define mmech_invalid (CK_MECHANISM_TYPE)0x80000000L
456 #define mmech_md5 CKM_SSL3_MD5_MAC
457 #define mmech_sha CKM_SSL3_SHA1_MAC
458 #define mmech_md5_hmac CKM_MD5_HMAC
459 #define mmech_sha_hmac CKM_SHA_1_HMAC
460 #define mmech_sha256_hmac CKM_SHA256_HMAC
462 static const ssl3MACDef mac_defs[] = { /* indexed by SSL3MACAlgorithm */
463 /* pad_size is only used for SSL 3.0 MAC. See RFC 6101 Sec. 5.2.3.1. */
464 /* mac mmech pad_size mac_size */
465 { mac_null, mmech_invalid, 0, 0 },
466 { mac_md5, mmech_md5, 48, MD5_LENGTH },
467 { mac_sha, mmech_sha, 40, SHA1_LENGTH},
468 {hmac_md5, mmech_md5_hmac, 0, MD5_LENGTH },
469 {hmac_sha, mmech_sha_hmac, 0, SHA1_LENGTH},
470 {hmac_sha256, mmech_sha256_hmac, 0, SHA256_LENGTH},
471 { mac_aead, mmech_invalid, 0, 0 },
474 /* indexed by SSL3BulkCipher */
475 const char * const ssl3_cipherName[] = {
495 #ifdef NSS_ENABLE_ECC
496 /* The ECCWrappedKeyInfo structure defines how various pieces of
497 * information are laid out within wrappedSymmetricWrappingkey
498 * for ECDH key exchange. Since wrappedSymmetricWrappingkey is
499 * a 512-byte buffer (see sslimpl.h), the variable length field
500 * in ECCWrappedKeyInfo can be at most (512 - 8) = 504 bytes.
502 * XXX For now, NSS only supports named elliptic curves of size 571 bits
503 * or smaller. The public value will fit within 145 bytes and EC params
504 * will fit within 12 bytes. We'll need to revisit this when NSS
505 * supports arbitrary curves.
507 #define MAX_EC_WRAPPED_KEY_BUFLEN 504
509 typedef struct ECCWrappedKeyInfoStr {
510 PRUint16 size; /* EC public key size in bits */
511 PRUint16 encodedParamLen; /* length (in bytes) of DER encoded EC params */
512 PRUint16 pubValueLen; /* length (in bytes) of EC public value */
513 PRUint16 wrappedKeyLen; /* length (in bytes) of the wrapped key */
514 PRUint8 var[MAX_EC_WRAPPED_KEY_BUFLEN]; /* this buffer contains the */
515 /* EC public-key params, the EC public value and the wrapped key */
517 #endif /* NSS_ENABLE_ECC */
522 ssl3_DecodeHandshakeType(int msgType)
525 static char line[40];
528 case hello_request: rv = "hello_request (0)"; break;
529 case client_hello: rv = "client_hello (1)"; break;
530 case server_hello: rv = "server_hello (2)"; break;
531 case hello_verify_request: rv = "hello_verify_request (3)"; break;
532 case certificate: rv = "certificate (11)"; break;
533 case server_key_exchange: rv = "server_key_exchange (12)"; break;
534 case certificate_request: rv = "certificate_request (13)"; break;
535 case server_hello_done: rv = "server_hello_done (14)"; break;
536 case certificate_verify: rv = "certificate_verify (15)"; break;
537 case client_key_exchange: rv = "client_key_exchange (16)"; break;
538 case finished: rv = "finished (20)"; break;
540 sprintf(line, "*UNKNOWN* handshake type! (%d)", msgType);
547 ssl3_DecodeContentType(int msgType)
550 static char line[40];
553 case content_change_cipher_spec:
554 rv = "change_cipher_spec (20)"; break;
555 case content_alert: rv = "alert (21)"; break;
556 case content_handshake: rv = "handshake (22)"; break;
557 case content_application_data:
558 rv = "application_data (23)"; break;
560 sprintf(line, "*UNKNOWN* record type! (%d)", msgType);
569 SSL_GetStatistics(void)
574 typedef struct tooLongStr {
575 #if defined(IS_LITTLE_ENDIAN)
584 void SSL_AtomicIncrementLong(long * x)
586 if ((sizeof *x) == sizeof(PRInt32)) {
587 PR_ATOMIC_INCREMENT((PRInt32 *)x);
589 tooLong * tl = (tooLong *)x;
590 if (PR_ATOMIC_INCREMENT(&tl->low) == 0)
591 PR_ATOMIC_INCREMENT(&tl->high);
596 ssl3_CipherSuiteAllowedForVersionRange(
597 ssl3CipherSuite cipherSuite,
598 const SSLVersionRange *vrange)
600 switch (cipherSuite) {
601 /* See RFC 4346 A.5. Export cipher suites must not be used in TLS 1.1 or
602 * later. This set of cipher suites is similar to, but different from, the
603 * set of cipher suites considered exportable by SSL_IsExportCipherSuite.
605 case SSL_RSA_EXPORT_WITH_RC4_40_MD5:
606 case SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5:
607 /* SSL_RSA_EXPORT_WITH_DES40_CBC_SHA: never implemented
608 * SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA: never implemented
609 * SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA: never implemented
610 * SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA: never implemented
611 * SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA: never implemented
612 * SSL_DH_ANON_EXPORT_WITH_RC4_40_MD5: never implemented
613 * SSL_DH_ANON_EXPORT_WITH_DES40_CBC_SHA: never implemented
615 return vrange->min <= SSL_LIBRARY_VERSION_TLS_1_0;
616 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256:
617 case TLS_RSA_WITH_AES_256_CBC_SHA256:
618 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
619 case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
620 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
621 case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
622 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256:
623 case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
624 case TLS_RSA_WITH_AES_128_CBC_SHA256:
625 case TLS_RSA_WITH_AES_128_GCM_SHA256:
626 case TLS_RSA_WITH_NULL_SHA256:
627 return vrange->max >= SSL_LIBRARY_VERSION_TLS_1_2;
633 /* return pointer to ssl3CipherSuiteDef for suite, or NULL */
634 /* XXX This does a linear search. A binary search would be better. */
635 static const ssl3CipherSuiteDef *
636 ssl_LookupCipherSuiteDef(ssl3CipherSuite suite)
638 int cipher_suite_def_len =
639 sizeof(cipher_suite_defs) / sizeof(cipher_suite_defs[0]);
642 for (i = 0; i < cipher_suite_def_len; i++) {
643 if (cipher_suite_defs[i].cipher_suite == suite)
644 return &cipher_suite_defs[i];
646 PORT_Assert(PR_FALSE); /* We should never get here. */
647 PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE);
651 /* Find the cipher configuration struct associate with suite */
652 /* XXX This does a linear search. A binary search would be better. */
653 static ssl3CipherSuiteCfg *
654 ssl_LookupCipherSuiteCfg(ssl3CipherSuite suite, ssl3CipherSuiteCfg *suites)
658 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
659 if (suites[i].cipher_suite == suite)
662 /* return NULL and let the caller handle it. */
663 PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE);
668 /* Initialize the suite->isPresent value for config_match
669 * Returns count of enabled ciphers supported by extant tokens,
670 * regardless of policy or user preference.
671 * If this returns zero, the user cannot do SSL v3.
674 ssl3_config_match_init(sslSocket *ss)
676 ssl3CipherSuiteCfg * suite;
677 const ssl3CipherSuiteDef *cipher_def;
678 SSLCipherAlgorithm cipher_alg;
679 CK_MECHANISM_TYPE cipher_mech;
680 SSL3KEAType exchKeyType;
685 sslServerCerts *svrAuth;
689 PORT_SetError(SEC_ERROR_INVALID_ARGS);
692 if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
695 isServer = (PRBool)(ss->sec.isServer != 0);
697 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
698 suite = &ss->cipherSuites[i];
699 if (suite->enabled) {
701 /* We need the cipher defs to see if we have a token that can handle
702 * this cipher. It isn't part of the static definition.
704 cipher_def = ssl_LookupCipherSuiteDef(suite->cipher_suite);
706 suite->isPresent = PR_FALSE;
709 cipher_alg = bulk_cipher_defs[cipher_def->bulk_cipher_alg].calg;
710 PORT_Assert( alg2Mech[cipher_alg].calg == cipher_alg);
711 cipher_mech = alg2Mech[cipher_alg].cmech;
713 kea_defs[cipher_def->key_exchange_alg].exchKeyType;
714 #ifndef NSS_ENABLE_ECC
715 svrAuth = ss->serverCerts + exchKeyType;
717 /* XXX SSLKEAType isn't really a good choice for
718 * indexing certificates. It doesn't work for
719 * (EC)DHE-* ciphers. Here we use a hack to ensure
720 * that the server uses an RSA cert for (EC)DHE-RSA.
722 switch (cipher_def->key_exchange_alg) {
724 #if NSS_SERVER_DHE_IMPLEMENTED
725 /* XXX NSS does not yet implement the server side of _DHE_
726 * cipher suites. Correcting the computation for svrAuth,
727 * as the case below does, causes NSS SSL servers to begin to
728 * negotiate cipher suites they do not implement. So, until
729 * server side _DHE_ is implemented, keep this disabled.
733 svrAuth = ss->serverCerts + kt_rsa;
738 * XXX We ought to have different indices for
739 * ECDSA- and RSA-signed EC certificates so
740 * we could support both key exchange mechanisms
741 * simultaneously. For now, both of them use
742 * whatever is in the certificate slot for kt_ecdh
745 svrAuth = ss->serverCerts + exchKeyType;
748 #endif /* NSS_ENABLE_ECC */
750 /* Mark the suites that are backed by real tokens, certs and keys */
751 suite->isPresent = (PRBool)
752 (((exchKeyType == kt_null) ||
753 ((!isServer || (svrAuth->serverKeyPair &&
754 svrAuth->SERVERKEY &&
755 svrAuth->serverCertChain)) &&
756 PK11_TokenExists(kea_alg_defs[exchKeyType]))) &&
757 ((cipher_alg == calg_null) || PK11_TokenExists(cipher_mech)));
758 if (suite->isPresent)
762 PORT_Assert(numPresent > 0 || numEnabled == 0);
763 if (numPresent <= 0) {
764 PORT_SetError(SSL_ERROR_NO_CIPHERS_SUPPORTED);
770 /* return PR_TRUE if suite matches policy, enabled state and is applicable to
771 * the given version range. */
772 /* It would be a REALLY BAD THING (tm) if we ever permitted the use
773 ** of a cipher that was NOT_ALLOWED. So, if this is ever called with
774 ** policy == SSL_NOT_ALLOWED, report no match.
776 /* adjust suite enabled to the availability of a token that can do the
779 config_match(ssl3CipherSuiteCfg *suite, int policy, PRBool enabled,
780 const SSLVersionRange *vrange)
782 PORT_Assert(policy != SSL_NOT_ALLOWED && enabled != PR_FALSE);
783 if (policy == SSL_NOT_ALLOWED || !enabled)
785 return (PRBool)(suite->enabled &&
787 suite->policy != SSL_NOT_ALLOWED &&
788 suite->policy <= policy &&
789 ssl3_CipherSuiteAllowedForVersionRange(
790 suite->cipher_suite, vrange));
793 /* return number of cipher suites that match policy, enabled state and are
794 * applicable for the configured protocol version range. */
795 /* called from ssl3_SendClientHello and ssl3_ConstructV2CipherSpecsHack */
797 count_cipher_suites(sslSocket *ss, int policy, PRBool enabled)
801 if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
804 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
805 if (config_match(&ss->cipherSuites[i], policy, enabled, &ss->vrange))
809 PORT_SetError(SSL_ERROR_SSL_DISABLED);
815 * Null compression, mac and encryption functions
819 Null_Cipher(void *ctx, unsigned char *output, int *outputLen, int maxOutputLen,
820 const unsigned char *input, int inputLen)
822 if (inputLen > maxOutputLen) {
823 *outputLen = 0; /* Match PK11_CipherOp in setting outputLen */
824 PORT_SetError(SEC_ERROR_OUTPUT_LEN);
827 *outputLen = inputLen;
829 PORT_Memcpy(output, input, inputLen);
834 * SSL3 Utility functions
837 /* allowLargerPeerVersion controls whether the function will select the
838 * highest enabled SSL version or fail when peerVersion is greater than the
839 * highest enabled version.
841 * If allowLargerPeerVersion is true, peerVersion is the peer's highest
842 * enabled version rather than the peer's selected version.
845 ssl3_NegotiateVersion(sslSocket *ss, SSL3ProtocolVersion peerVersion,
846 PRBool allowLargerPeerVersion)
848 if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
849 PORT_SetError(SSL_ERROR_SSL_DISABLED);
853 if (peerVersion < ss->vrange.min ||
854 (peerVersion > ss->vrange.max && !allowLargerPeerVersion)) {
855 PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
859 ss->version = PR_MIN(peerVersion, ss->vrange.max);
860 PORT_Assert(ssl3_VersionIsSupported(ss->protocolVariant, ss->version));
866 ssl3_GetNewRandom(SSL3Random *random)
868 PRUint32 gmt = ssl_Time();
871 random->rand[0] = (unsigned char)(gmt >> 24);
872 random->rand[1] = (unsigned char)(gmt >> 16);
873 random->rand[2] = (unsigned char)(gmt >> 8);
874 random->rand[3] = (unsigned char)(gmt);
876 /* first 4 bytes are reserverd for time */
877 rv = PK11_GenerateRandom(&random->rand[4], SSL3_RANDOM_LENGTH - 4);
878 if (rv != SECSuccess) {
879 ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
884 /* Called by ssl3_SendServerKeyExchange and ssl3_SendCertificateVerify */
886 ssl3_SignHashes(SSL3Hashes *hash, SECKEYPrivateKey *key, SECItem *buf,
889 SECStatus rv = SECFailure;
890 PRBool doDerEncode = PR_FALSE;
896 switch (key->keyType) {
898 hashItem.data = hash->u.raw;
899 hashItem.len = hash->len;
903 /* SEC_OID_UNKNOWN is used to specify the MD5/SHA1 concatenated hash.
904 * In that case, we use just the SHA1 part. */
905 if (hash->hashAlg == SEC_OID_UNKNOWN) {
906 hashItem.data = hash->u.s.sha;
907 hashItem.len = sizeof(hash->u.s.sha);
909 hashItem.data = hash->u.raw;
910 hashItem.len = hash->len;
913 #ifdef NSS_ENABLE_ECC
915 doDerEncode = PR_TRUE;
916 /* SEC_OID_UNKNOWN is used to specify the MD5/SHA1 concatenated hash.
917 * In that case, we use just the SHA1 part. */
918 if (hash->hashAlg == SEC_OID_UNKNOWN) {
919 hashItem.data = hash->u.s.sha;
920 hashItem.len = sizeof(hash->u.s.sha);
922 hashItem.data = hash->u.raw;
923 hashItem.len = hash->len;
926 #endif /* NSS_ENABLE_ECC */
928 PORT_SetError(SEC_ERROR_INVALID_KEY);
931 PRINT_BUF(60, (NULL, "hash(es) to be signed", hashItem.data, hashItem.len));
933 if (hash->hashAlg == SEC_OID_UNKNOWN) {
934 signatureLen = PK11_SignatureLen(key);
935 if (signatureLen <= 0) {
936 PORT_SetError(SEC_ERROR_INVALID_KEY);
940 buf->len = (unsigned)signatureLen;
941 buf->data = (unsigned char *)PORT_Alloc(signatureLen);
943 goto done; /* error code was set. */
945 rv = PK11_Sign(key, buf, &hashItem);
947 rv = SGN_Digest(key, hash->hashAlg, buf, &hashItem);
949 if (rv != SECSuccess) {
950 ssl_MapLowLevelError(SSL_ERROR_SIGN_HASHES_FAILURE);
951 } else if (doDerEncode) {
952 SECItem derSig = {siBuffer, NULL, 0};
954 /* This also works for an ECDSA signature */
955 rv = DSAU_EncodeDerSigWithLen(&derSig, buf, buf->len);
956 if (rv == SECSuccess) {
957 PORT_Free(buf->data); /* discard unencoded signature. */
958 *buf = derSig; /* give caller encoded signature. */
959 } else if (derSig.data) {
960 PORT_Free(derSig.data);
964 PRINT_BUF(60, (NULL, "signed hashes", (unsigned char*)buf->data, buf->len));
966 if (rv != SECSuccess && buf->data) {
967 PORT_Free(buf->data);
973 /* Called from ssl3_HandleServerKeyExchange, ssl3_HandleCertificateVerify */
975 ssl3_VerifySignedHashes(SSL3Hashes *hash, CERTCertificate *cert,
976 SECItem *buf, PRBool isTLS, void *pwArg)
978 SECKEYPublicKey * key;
979 SECItem * signature = NULL;
986 PRINT_BUF(60, (NULL, "check signed hashes",
987 buf->data, buf->len));
989 key = CERT_ExtractPublicKey(cert);
991 ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
995 hashAlg = hash->hashAlg;
996 switch (key->keyType) {
998 encAlg = SEC_OID_PKCS1_RSA_ENCRYPTION;
999 hashItem.data = hash->u.raw;
1000 hashItem.len = hash->len;
1003 encAlg = SEC_OID_ANSIX9_DSA_SIGNATURE;
1004 /* SEC_OID_UNKNOWN is used to specify the MD5/SHA1 concatenated hash.
1005 * In that case, we use just the SHA1 part. */
1006 if (hash->hashAlg == SEC_OID_UNKNOWN) {
1007 hashItem.data = hash->u.s.sha;
1008 hashItem.len = sizeof(hash->u.s.sha);
1010 hashItem.data = hash->u.raw;
1011 hashItem.len = hash->len;
1013 /* Allow DER encoded DSA signatures in SSL 3.0 */
1014 if (isTLS || buf->len != SECKEY_SignatureLen(key)) {
1015 signature = DSAU_DecodeDerSig(buf);
1017 PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
1024 #ifdef NSS_ENABLE_ECC
1026 encAlg = SEC_OID_ANSIX962_EC_PUBLIC_KEY;
1027 /* SEC_OID_UNKNOWN is used to specify the MD5/SHA1 concatenated hash.
1028 * In that case, we use just the SHA1 part.
1029 * ECDSA signatures always encode the integers r and s using ASN.1
1030 * (unlike DSA where ASN.1 encoding is used with TLS but not with
1031 * SSL3). So we can use VFY_VerifyDigestDirect for ECDSA.
1033 if (hash->hashAlg == SEC_OID_UNKNOWN) {
1034 hashAlg = SEC_OID_SHA1;
1035 hashItem.data = hash->u.s.sha;
1036 hashItem.len = sizeof(hash->u.s.sha);
1038 hashItem.data = hash->u.raw;
1039 hashItem.len = hash->len;
1042 #endif /* NSS_ENABLE_ECC */
1045 SECKEY_DestroyPublicKey(key);
1046 PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
1050 PRINT_BUF(60, (NULL, "hash(es) to be verified",
1051 hashItem.data, hashItem.len));
1053 if (hashAlg == SEC_OID_UNKNOWN || key->keyType == dsaKey) {
1054 /* VFY_VerifyDigestDirect requires DSA signatures to be DER-encoded.
1055 * DSA signatures are DER-encoded in TLS but not in SSL3 and the code
1056 * above always removes the DER encoding of DSA signatures when
1057 * present. Thus DSA signatures are always verified with PK11_Verify.
1059 rv = PK11_Verify(key, buf, &hashItem, pwArg);
1061 rv = VFY_VerifyDigestDirect(&hashItem, key, buf, encAlg, hashAlg,
1064 SECKEY_DestroyPublicKey(key);
1066 SECITEM_FreeItem(signature, PR_TRUE);
1068 if (rv != SECSuccess) {
1069 ssl_MapLowLevelError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
1075 /* Caller must set hiLevel error code. */
1076 /* Called from ssl3_ComputeExportRSAKeyHash
1077 * ssl3_ComputeDHKeyHash
1078 * which are called from ssl3_HandleServerKeyExchange.
1080 * hashAlg: either the OID for a hash algorithm or SEC_OID_UNKNOWN to specify
1081 * the pre-1.2, MD5/SHA1 combination hash.
1084 ssl3_ComputeCommonKeyHash(SECOidTag hashAlg,
1085 PRUint8 * hashBuf, unsigned int bufLen,
1086 SSL3Hashes *hashes, PRBool bypassPKCS11)
1088 SECStatus rv = SECSuccess;
1090 #ifndef NO_PKCS11_BYPASS
1092 if (hashAlg == SEC_OID_UNKNOWN) {
1093 MD5_HashBuf (hashes->u.s.md5, hashBuf, bufLen);
1094 SHA1_HashBuf(hashes->u.s.sha, hashBuf, bufLen);
1095 hashes->len = MD5_LENGTH + SHA1_LENGTH;
1096 } else if (hashAlg == SEC_OID_SHA1) {
1097 SHA1_HashBuf(hashes->u.raw, hashBuf, bufLen);
1098 hashes->len = SHA1_LENGTH;
1099 } else if (hashAlg == SEC_OID_SHA256) {
1100 SHA256_HashBuf(hashes->u.raw, hashBuf, bufLen);
1101 hashes->len = SHA256_LENGTH;
1102 } else if (hashAlg == SEC_OID_SHA384) {
1103 SHA384_HashBuf(hashes->u.raw, hashBuf, bufLen);
1104 hashes->len = SHA384_LENGTH;
1105 } else if (hashAlg == SEC_OID_SHA512) {
1106 SHA512_HashBuf(hashes->u.raw, hashBuf, bufLen);
1107 hashes->len = SHA512_LENGTH;
1109 PORT_SetError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
1115 if (hashAlg == SEC_OID_UNKNOWN) {
1116 rv = PK11_HashBuf(SEC_OID_MD5, hashes->u.s.md5, hashBuf, bufLen);
1117 if (rv != SECSuccess) {
1118 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
1123 rv = PK11_HashBuf(SEC_OID_SHA1, hashes->u.s.sha, hashBuf, bufLen);
1124 if (rv != SECSuccess) {
1125 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
1128 hashes->len = MD5_LENGTH + SHA1_LENGTH;
1130 hashes->len = HASH_ResultLenByOidTag(hashAlg);
1131 if (hashes->len > sizeof(hashes->u.raw)) {
1132 ssl_MapLowLevelError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
1136 rv = PK11_HashBuf(hashAlg, hashes->u.raw, hashBuf, bufLen);
1137 if (rv != SECSuccess) {
1138 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
1143 hashes->hashAlg = hashAlg;
1149 /* Caller must set hiLevel error code.
1150 ** Called from ssl3_SendServerKeyExchange and
1151 ** ssl3_HandleServerKeyExchange.
1154 ssl3_ComputeExportRSAKeyHash(SECOidTag hashAlg,
1155 SECItem modulus, SECItem publicExponent,
1156 SSL3Random *client_rand, SSL3Random *server_rand,
1157 SSL3Hashes *hashes, PRBool bypassPKCS11)
1161 SECStatus rv = SECSuccess;
1162 unsigned int bufLen;
1163 PRUint8 buf[2*SSL3_RANDOM_LENGTH + 2 + 4096/8 + 2 + 4096/8];
1165 bufLen = 2*SSL3_RANDOM_LENGTH + 2 + modulus.len + 2 + publicExponent.len;
1166 if (bufLen <= sizeof buf) {
1169 hashBuf = PORT_Alloc(bufLen);
1175 memcpy(hashBuf, client_rand, SSL3_RANDOM_LENGTH);
1176 pBuf = hashBuf + SSL3_RANDOM_LENGTH;
1177 memcpy(pBuf, server_rand, SSL3_RANDOM_LENGTH);
1178 pBuf += SSL3_RANDOM_LENGTH;
1179 pBuf[0] = (PRUint8)(modulus.len >> 8);
1180 pBuf[1] = (PRUint8)(modulus.len);
1182 memcpy(pBuf, modulus.data, modulus.len);
1183 pBuf += modulus.len;
1184 pBuf[0] = (PRUint8)(publicExponent.len >> 8);
1185 pBuf[1] = (PRUint8)(publicExponent.len);
1187 memcpy(pBuf, publicExponent.data, publicExponent.len);
1188 pBuf += publicExponent.len;
1189 PORT_Assert((unsigned int)(pBuf - hashBuf) == bufLen);
1191 rv = ssl3_ComputeCommonKeyHash(hashAlg, hashBuf, bufLen, hashes,
1194 PRINT_BUF(95, (NULL, "RSAkey hash: ", hashBuf, bufLen));
1195 if (hashAlg == SEC_OID_UNKNOWN) {
1196 PRINT_BUF(95, (NULL, "RSAkey hash: MD5 result",
1197 hashes->u.s.md5, MD5_LENGTH));
1198 PRINT_BUF(95, (NULL, "RSAkey hash: SHA1 result",
1199 hashes->u.s.sha, SHA1_LENGTH));
1201 PRINT_BUF(95, (NULL, "RSAkey hash: result",
1202 hashes->u.raw, hashes->len));
1205 if (hashBuf != buf && hashBuf != NULL)
1210 /* Caller must set hiLevel error code. */
1211 /* Called from ssl3_HandleServerKeyExchange. */
1213 ssl3_ComputeDHKeyHash(SECOidTag hashAlg,
1214 SECItem dh_p, SECItem dh_g, SECItem dh_Ys,
1215 SSL3Random *client_rand, SSL3Random *server_rand,
1216 SSL3Hashes *hashes, PRBool bypassPKCS11)
1220 SECStatus rv = SECSuccess;
1221 unsigned int bufLen;
1222 PRUint8 buf[2*SSL3_RANDOM_LENGTH + 2 + 4096/8 + 2 + 4096/8];
1224 bufLen = 2*SSL3_RANDOM_LENGTH + 2 + dh_p.len + 2 + dh_g.len + 2 + dh_Ys.len;
1225 if (bufLen <= sizeof buf) {
1228 hashBuf = PORT_Alloc(bufLen);
1234 memcpy(hashBuf, client_rand, SSL3_RANDOM_LENGTH);
1235 pBuf = hashBuf + SSL3_RANDOM_LENGTH;
1236 memcpy(pBuf, server_rand, SSL3_RANDOM_LENGTH);
1237 pBuf += SSL3_RANDOM_LENGTH;
1238 pBuf[0] = (PRUint8)(dh_p.len >> 8);
1239 pBuf[1] = (PRUint8)(dh_p.len);
1241 memcpy(pBuf, dh_p.data, dh_p.len);
1243 pBuf[0] = (PRUint8)(dh_g.len >> 8);
1244 pBuf[1] = (PRUint8)(dh_g.len);
1246 memcpy(pBuf, dh_g.data, dh_g.len);
1248 pBuf[0] = (PRUint8)(dh_Ys.len >> 8);
1249 pBuf[1] = (PRUint8)(dh_Ys.len);
1251 memcpy(pBuf, dh_Ys.data, dh_Ys.len);
1253 PORT_Assert((unsigned int)(pBuf - hashBuf) == bufLen);
1255 rv = ssl3_ComputeCommonKeyHash(hashAlg, hashBuf, bufLen, hashes,
1258 PRINT_BUF(95, (NULL, "DHkey hash: ", hashBuf, bufLen));
1259 if (hashAlg == SEC_OID_UNKNOWN) {
1260 PRINT_BUF(95, (NULL, "DHkey hash: MD5 result",
1261 hashes->u.s.md5, MD5_LENGTH));
1262 PRINT_BUF(95, (NULL, "DHkey hash: SHA1 result",
1263 hashes->u.s.sha, SHA1_LENGTH));
1265 PRINT_BUF(95, (NULL, "DHkey hash: result",
1266 hashes->u.raw, hashes->len));
1269 if (hashBuf != buf && hashBuf != NULL)
1275 ssl3_BumpSequenceNumber(SSL3SequenceNumber *num)
1282 /* Called twice, only from ssl3_DestroyCipherSpec (immediately below). */
1284 ssl3_CleanupKeyMaterial(ssl3KeyMaterial *mat)
1286 if (mat->write_key != NULL) {
1287 PK11_FreeSymKey(mat->write_key);
1288 mat->write_key = NULL;
1290 if (mat->write_mac_key != NULL) {
1291 PK11_FreeSymKey(mat->write_mac_key);
1292 mat->write_mac_key = NULL;
1294 if (mat->write_mac_context != NULL) {
1295 PK11_DestroyContext(mat->write_mac_context, PR_TRUE);
1296 mat->write_mac_context = NULL;
1300 /* Called from ssl3_SendChangeCipherSpecs() and
1301 ** ssl3_HandleChangeCipherSpecs()
1302 ** ssl3_DestroySSL3Info
1303 ** Caller must hold SpecWriteLock.
1306 ssl3_DestroyCipherSpec(ssl3CipherSpec *spec, PRBool freeSrvName)
1308 PRBool freeit = (PRBool)(!spec->bypassCiphers);
1309 /* PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); Don't have ss! */
1310 if (spec->destroy) {
1311 spec->destroy(spec->encodeContext, freeit);
1312 spec->destroy(spec->decodeContext, freeit);
1313 spec->encodeContext = NULL; /* paranoia */
1314 spec->decodeContext = NULL;
1316 if (spec->destroyCompressContext && spec->compressContext) {
1317 spec->destroyCompressContext(spec->compressContext, 1);
1318 spec->compressContext = NULL;
1320 if (spec->destroyDecompressContext && spec->decompressContext) {
1321 spec->destroyDecompressContext(spec->decompressContext, 1);
1322 spec->decompressContext = NULL;
1324 if (freeSrvName && spec->srvVirtName.data) {
1325 SECITEM_FreeItem(&spec->srvVirtName, PR_FALSE);
1327 if (spec->master_secret != NULL) {
1328 PK11_FreeSymKey(spec->master_secret);
1329 spec->master_secret = NULL;
1331 spec->msItem.data = NULL;
1332 spec->msItem.len = 0;
1333 ssl3_CleanupKeyMaterial(&spec->client);
1334 ssl3_CleanupKeyMaterial(&spec->server);
1335 spec->bypassCiphers = PR_FALSE;
1337 spec->destroyCompressContext = NULL;
1338 spec->destroyDecompressContext = NULL;
1341 /* Fill in the pending cipher spec with info from the selected ciphersuite.
1342 ** This is as much initialization as we can do without having key material.
1343 ** Called from ssl3_HandleServerHello(), ssl3_SendServerHello()
1344 ** Caller must hold the ssl3 handshake lock.
1345 ** Acquires & releases SpecWriteLock.
1348 ssl3_SetupPendingCipherSpec(sslSocket *ss)
1350 ssl3CipherSpec * pwSpec;
1351 ssl3CipherSpec * cwSpec;
1352 ssl3CipherSuite suite = ss->ssl3.hs.cipher_suite;
1353 SSL3MACAlgorithm mac;
1354 SSL3BulkCipher cipher;
1355 SSL3KeyExchangeAlgorithm kea;
1356 const ssl3CipherSuiteDef *suite_def;
1359 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
1361 ssl_GetSpecWriteLock(ss); /*******************************/
1363 pwSpec = ss->ssl3.pwSpec;
1364 PORT_Assert(pwSpec == ss->ssl3.prSpec);
1366 /* This hack provides maximal interoperability with SSL 3 servers. */
1367 cwSpec = ss->ssl3.cwSpec;
1368 if (cwSpec->mac_def->mac == mac_null) {
1369 /* SSL records are not being MACed. */
1370 cwSpec->version = ss->version;
1373 pwSpec->version = ss->version;
1374 isTLS = (PRBool)(pwSpec->version > SSL_LIBRARY_VERSION_3_0);
1376 SSL_TRC(3, ("%d: SSL3[%d]: Set XXX Pending Cipher Suite to 0x%04x",
1377 SSL_GETPID(), ss->fd, suite));
1379 suite_def = ssl_LookupCipherSuiteDef(suite);
1380 if (suite_def == NULL) {
1381 ssl_ReleaseSpecWriteLock(ss);
1382 return SECFailure; /* error code set by ssl_LookupCipherSuiteDef */
1386 /* Double-check that we did not pick an RC4 suite */
1387 PORT_Assert((suite_def->bulk_cipher_alg != cipher_rc4) &&
1388 (suite_def->bulk_cipher_alg != cipher_rc4_40) &&
1389 (suite_def->bulk_cipher_alg != cipher_rc4_56));
1392 cipher = suite_def->bulk_cipher_alg;
1393 kea = suite_def->key_exchange_alg;
1394 mac = suite_def->mac_alg;
1395 if (mac <= ssl_mac_sha && mac != ssl_mac_null && isTLS)
1398 ss->ssl3.hs.suite_def = suite_def;
1399 ss->ssl3.hs.kea_def = &kea_defs[kea];
1400 PORT_Assert(ss->ssl3.hs.kea_def->kea == kea);
1402 pwSpec->cipher_def = &bulk_cipher_defs[cipher];
1403 PORT_Assert(pwSpec->cipher_def->cipher == cipher);
1405 pwSpec->mac_def = &mac_defs[mac];
1406 PORT_Assert(pwSpec->mac_def->mac == mac);
1408 ss->sec.keyBits = pwSpec->cipher_def->key_size * BPB;
1409 ss->sec.secretKeyBits = pwSpec->cipher_def->secret_key_size * BPB;
1410 ss->sec.cipherType = cipher;
1412 pwSpec->encodeContext = NULL;
1413 pwSpec->decodeContext = NULL;
1415 pwSpec->mac_size = pwSpec->mac_def->mac_size;
1417 pwSpec->compression_method = ss->ssl3.hs.compression;
1418 pwSpec->compressContext = NULL;
1419 pwSpec->decompressContext = NULL;
1421 ssl_ReleaseSpecWriteLock(ss); /*******************************/
1425 #ifdef NSS_ENABLE_ZLIB
1426 #define SSL3_DEFLATE_CONTEXT_SIZE sizeof(z_stream)
1429 ssl3_MapZlibError(int zlib_error)
1431 switch (zlib_error) {
1440 ssl3_DeflateInit(void *void_context)
1442 z_stream *context = void_context;
1443 context->zalloc = NULL;
1444 context->zfree = NULL;
1445 context->opaque = NULL;
1447 return ssl3_MapZlibError(deflateInit(context, Z_DEFAULT_COMPRESSION));
1451 ssl3_InflateInit(void *void_context)
1453 z_stream *context = void_context;
1454 context->zalloc = NULL;
1455 context->zfree = NULL;
1456 context->opaque = NULL;
1457 context->next_in = NULL;
1458 context->avail_in = 0;
1460 return ssl3_MapZlibError(inflateInit(context));
1464 ssl3_DeflateCompress(void *void_context, unsigned char *out, int *out_len,
1465 int maxout, const unsigned char *in, int inlen)
1467 z_stream *context = void_context;
1474 context->next_in = (unsigned char*) in;
1475 context->avail_in = inlen;
1476 context->next_out = out;
1477 context->avail_out = maxout;
1478 if (deflate(context, Z_SYNC_FLUSH) != Z_OK) {
1481 if (context->avail_out == 0) {
1482 /* We ran out of space! */
1483 SSL_TRC(3, ("%d: SSL3[%d] Ran out of buffer while compressing",
1488 *out_len = maxout - context->avail_out;
1493 ssl3_DeflateDecompress(void *void_context, unsigned char *out, int *out_len,
1494 int maxout, const unsigned char *in, int inlen)
1496 z_stream *context = void_context;
1503 context->next_in = (unsigned char*) in;
1504 context->avail_in = inlen;
1505 context->next_out = out;
1506 context->avail_out = maxout;
1507 if (inflate(context, Z_SYNC_FLUSH) != Z_OK) {
1508 PORT_SetError(SSL_ERROR_DECOMPRESSION_FAILURE);
1512 *out_len = maxout - context->avail_out;
1517 ssl3_DestroyCompressContext(void *void_context, PRBool unused)
1519 deflateEnd(void_context);
1520 PORT_Free(void_context);
1525 ssl3_DestroyDecompressContext(void *void_context, PRBool unused)
1527 inflateEnd(void_context);
1528 PORT_Free(void_context);
1532 #endif /* NSS_ENABLE_ZLIB */
1534 /* Initialize the compression functions and contexts for the given
1537 ssl3_InitCompressionContext(ssl3CipherSpec *pwSpec)
1539 /* Setup the compression functions */
1540 switch (pwSpec->compression_method) {
1541 case ssl_compression_null:
1542 pwSpec->compressor = NULL;
1543 pwSpec->decompressor = NULL;
1544 pwSpec->compressContext = NULL;
1545 pwSpec->decompressContext = NULL;
1546 pwSpec->destroyCompressContext = NULL;
1547 pwSpec->destroyDecompressContext = NULL;
1549 #ifdef NSS_ENABLE_ZLIB
1550 case ssl_compression_deflate:
1551 pwSpec->compressor = ssl3_DeflateCompress;
1552 pwSpec->decompressor = ssl3_DeflateDecompress;
1553 pwSpec->compressContext = PORT_Alloc(SSL3_DEFLATE_CONTEXT_SIZE);
1554 pwSpec->decompressContext = PORT_Alloc(SSL3_DEFLATE_CONTEXT_SIZE);
1555 pwSpec->destroyCompressContext = ssl3_DestroyCompressContext;
1556 pwSpec->destroyDecompressContext = ssl3_DestroyDecompressContext;
1557 ssl3_DeflateInit(pwSpec->compressContext);
1558 ssl3_InflateInit(pwSpec->decompressContext);
1560 #endif /* NSS_ENABLE_ZLIB */
1563 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1570 #ifndef NO_PKCS11_BYPASS
1571 /* Initialize encryption contexts for pending spec.
1572 * MAC contexts are set up when computing the mac, not here.
1573 * Master Secret already is derived in spec->msItem
1574 * Caller holds Spec write lock.
1577 ssl3_InitPendingContextsBypass(sslSocket *ss)
1579 ssl3CipherSpec * pwSpec;
1580 const ssl3BulkCipherDef *cipher_def;
1581 void * serverContext = NULL;
1582 void * clientContext = NULL;
1583 BLapiInitContextFunc initFn = (BLapiInitContextFunc)NULL;
1585 unsigned int optArg1 = 0;
1586 unsigned int optArg2 = 0;
1587 PRBool server_encrypts = ss->sec.isServer;
1588 SSLCipherAlgorithm calg;
1591 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
1592 PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
1593 PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
1595 pwSpec = ss->ssl3.pwSpec;
1596 cipher_def = pwSpec->cipher_def;
1598 calg = cipher_def->calg;
1600 if (calg == calg_aes_gcm) {
1601 pwSpec->encode = NULL;
1602 pwSpec->decode = NULL;
1603 pwSpec->destroy = NULL;
1604 pwSpec->encodeContext = NULL;
1605 pwSpec->decodeContext = NULL;
1606 pwSpec->aead = ssl3_AESGCMBypass;
1607 ssl3_InitCompressionContext(pwSpec);
1611 serverContext = pwSpec->server.cipher_context;
1612 clientContext = pwSpec->client.cipher_context;
1616 pwSpec->encode = Null_Cipher;
1617 pwSpec->decode = Null_Cipher;
1618 pwSpec->destroy = NULL;
1622 initFn = (BLapiInitContextFunc)RC4_InitContext;
1623 pwSpec->encode = (SSLCipher) RC4_Encrypt;
1624 pwSpec->decode = (SSLCipher) RC4_Decrypt;
1625 pwSpec->destroy = (SSLDestroy) RC4_DestroyContext;
1628 initFn = (BLapiInitContextFunc)RC2_InitContext;
1630 optArg1 = cipher_def->key_size;
1631 pwSpec->encode = (SSLCipher) RC2_Encrypt;
1632 pwSpec->decode = (SSLCipher) RC2_Decrypt;
1633 pwSpec->destroy = (SSLDestroy) RC2_DestroyContext;
1636 initFn = (BLapiInitContextFunc)DES_InitContext;
1638 optArg1 = server_encrypts;
1639 pwSpec->encode = (SSLCipher) DES_Encrypt;
1640 pwSpec->decode = (SSLCipher) DES_Decrypt;
1641 pwSpec->destroy = (SSLDestroy) DES_DestroyContext;
1644 initFn = (BLapiInitContextFunc)DES_InitContext;
1645 mode = NSS_DES_EDE3_CBC;
1646 optArg1 = server_encrypts;
1647 pwSpec->encode = (SSLCipher) DES_Encrypt;
1648 pwSpec->decode = (SSLCipher) DES_Decrypt;
1649 pwSpec->destroy = (SSLDestroy) DES_DestroyContext;
1652 initFn = (BLapiInitContextFunc)AES_InitContext;
1654 optArg1 = server_encrypts;
1655 optArg2 = AES_BLOCK_SIZE;
1656 pwSpec->encode = (SSLCipher) AES_Encrypt;
1657 pwSpec->decode = (SSLCipher) AES_Decrypt;
1658 pwSpec->destroy = (SSLDestroy) AES_DestroyContext;
1661 case ssl_calg_camellia:
1662 initFn = (BLapiInitContextFunc)Camellia_InitContext;
1663 mode = NSS_CAMELLIA_CBC;
1664 optArg1 = server_encrypts;
1665 optArg2 = CAMELLIA_BLOCK_SIZE;
1666 pwSpec->encode = (SSLCipher) Camellia_Encrypt;
1667 pwSpec->decode = (SSLCipher) Camellia_Decrypt;
1668 pwSpec->destroy = (SSLDestroy) Camellia_DestroyContext;
1672 initFn = (BLapiInitContextFunc)SEED_InitContext;
1673 mode = NSS_SEED_CBC;
1674 optArg1 = server_encrypts;
1675 optArg2 = SEED_BLOCK_SIZE;
1676 pwSpec->encode = (SSLCipher) SEED_Encrypt;
1677 pwSpec->decode = (SSLCipher) SEED_Decrypt;
1678 pwSpec->destroy = (SSLDestroy) SEED_DestroyContext;
1682 case ssl_calg_fortezza :
1685 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1688 rv = (*initFn)(serverContext,
1689 pwSpec->server.write_key_item.data,
1690 pwSpec->server.write_key_item.len,
1691 pwSpec->server.write_iv_item.data,
1692 mode, optArg1, optArg2);
1693 if (rv != SECSuccess) {
1695 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1703 case ssl_calg_camellia:
1705 /* For block ciphers, if the server is encrypting, then the client
1706 * is decrypting, and vice versa.
1710 /* kill warnings. */
1715 case ssl_calg_fortezza:
1719 rv = (*initFn)(clientContext,
1720 pwSpec->client.write_key_item.data,
1721 pwSpec->client.write_key_item.len,
1722 pwSpec->client.write_iv_item.data,
1723 mode, optArg1, optArg2);
1724 if (rv != SECSuccess) {
1726 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1730 pwSpec->encodeContext = (ss->sec.isServer) ? serverContext : clientContext;
1731 pwSpec->decodeContext = (ss->sec.isServer) ? clientContext : serverContext;
1733 ssl3_InitCompressionContext(pwSpec);
1743 /* This function should probably be moved to pk11wrap and be named
1744 * PK11_ParamFromIVAndEffectiveKeyBits
1747 ssl3_ParamFromIV(CK_MECHANISM_TYPE mtype, SECItem *iv, CK_ULONG ulEffectiveBits)
1749 SECItem * param = PK11_ParamFromIV(mtype, iv);
1750 if (param && param->data && param->len >= sizeof(CK_RC2_PARAMS)) {
1752 case CKM_RC2_KEY_GEN:
1756 case CKM_RC2_MAC_GENERAL:
1757 case CKM_RC2_CBC_PAD:
1758 *(CK_RC2_PARAMS *)param->data = ulEffectiveBits;
1765 /* ssl3_BuildRecordPseudoHeader writes the SSL/TLS pseudo-header (the data
1766 * which is included in the MAC or AEAD additional data) to |out| and returns
1767 * its length. See https://tools.ietf.org/html/rfc5246#section-6.2.3.3 for the
1768 * definition of the AEAD additional data.
1770 * TLS pseudo-header includes the record's version field, SSL's doesn't. Which
1771 * pseudo-header defintiion to use should be decided based on the version of
1772 * the protocol that was negotiated when the cipher spec became current, NOT
1773 * based on the version value in the record itself, and the decision is passed
1774 * to this function as the |includesVersion| argument. But, the |version|
1775 * argument should be the record's version value.
1778 ssl3_BuildRecordPseudoHeader(unsigned char *out,
1779 SSL3SequenceNumber seq_num,
1780 SSL3ContentType type,
1781 PRBool includesVersion,
1782 SSL3ProtocolVersion version,
1786 out[0] = (unsigned char)(seq_num.high >> 24);
1787 out[1] = (unsigned char)(seq_num.high >> 16);
1788 out[2] = (unsigned char)(seq_num.high >> 8);
1789 out[3] = (unsigned char)(seq_num.high >> 0);
1790 out[4] = (unsigned char)(seq_num.low >> 24);
1791 out[5] = (unsigned char)(seq_num.low >> 16);
1792 out[6] = (unsigned char)(seq_num.low >> 8);
1793 out[7] = (unsigned char)(seq_num.low >> 0);
1796 /* SSL3 MAC doesn't include the record's version field. */
1797 if (!includesVersion) {
1798 out[9] = MSB(length);
1799 out[10] = LSB(length);
1803 /* TLS MAC and AEAD additional data include version. */
1805 SSL3ProtocolVersion dtls_version;
1807 dtls_version = dtls_TLSVersionToDTLSVersion(version);
1808 out[9] = MSB(dtls_version);
1809 out[10] = LSB(dtls_version);
1811 out[9] = MSB(version);
1812 out[10] = LSB(version);
1814 out[11] = MSB(length);
1815 out[12] = LSB(length);
1820 ssl3_AESGCM(ssl3KeyMaterial *keys,
1825 const unsigned char *in,
1827 const unsigned char *additionalData,
1828 int additionalDataLen)
1831 SECStatus rv = SECFailure;
1832 unsigned char nonce[12];
1833 unsigned int uOutLen;
1834 CK_GCM_PARAMS gcmParams;
1836 static const int tagSize = 16;
1837 static const int explicitNonceLen = 8;
1839 /* See https://tools.ietf.org/html/rfc5288#section-3 for details of how the
1840 * nonce is formed. */
1841 memcpy(nonce, keys->write_iv, 4);
1843 memcpy(nonce + 4, in, explicitNonceLen);
1844 in += explicitNonceLen;
1845 inlen -= explicitNonceLen;
1848 if (maxout < explicitNonceLen) {
1849 PORT_SetError(SEC_ERROR_INPUT_LEN);
1852 /* Use the 64-bit sequence number as the explicit nonce. */
1853 memcpy(nonce + 4, additionalData, explicitNonceLen);
1854 memcpy(out, additionalData, explicitNonceLen);
1855 out += explicitNonceLen;
1856 maxout -= explicitNonceLen;
1857 *outlen = explicitNonceLen;
1860 param.type = siBuffer;
1861 param.data = (unsigned char *) &gcmParams;
1862 param.len = sizeof(gcmParams);
1863 gcmParams.pIv = nonce;
1864 gcmParams.ulIvLen = sizeof(nonce);
1865 gcmParams.pAAD = (unsigned char *)additionalData; /* const cast */
1866 gcmParams.ulAADLen = additionalDataLen;
1867 gcmParams.ulTagBits = tagSize * 8;
1870 rv = PK11_Decrypt(keys->write_key, CKM_AES_GCM, ¶m, out, &uOutLen,
1873 rv = PK11_Encrypt(keys->write_key, CKM_AES_GCM, ¶m, out, &uOutLen,
1876 *outlen += (int) uOutLen;
1881 #ifndef NO_PKCS11_BYPASS
1883 ssl3_AESGCMBypass(ssl3KeyMaterial *keys,
1888 const unsigned char *in,
1890 const unsigned char *additionalData,
1891 int additionalDataLen)
1893 SECStatus rv = SECFailure;
1894 unsigned char nonce[12];
1895 unsigned int uOutLen;
1897 CK_GCM_PARAMS gcmParams;
1899 static const int tagSize = 16;
1900 static const int explicitNonceLen = 8;
1902 /* See https://tools.ietf.org/html/rfc5288#section-3 for details of how the
1903 * nonce is formed. */
1904 PORT_Assert(keys->write_iv_item.len == 4);
1905 if (keys->write_iv_item.len != 4) {
1906 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1909 memcpy(nonce, keys->write_iv_item.data, 4);
1911 memcpy(nonce + 4, in, explicitNonceLen);
1912 in += explicitNonceLen;
1913 inlen -= explicitNonceLen;
1916 if (maxout < explicitNonceLen) {
1917 PORT_SetError(SEC_ERROR_INPUT_LEN);
1920 /* Use the 64-bit sequence number as the explicit nonce. */
1921 memcpy(nonce + 4, additionalData, explicitNonceLen);
1922 memcpy(out, additionalData, explicitNonceLen);
1923 out += explicitNonceLen;
1924 maxout -= explicitNonceLen;
1925 *outlen = explicitNonceLen;
1928 gcmParams.pIv = nonce;
1929 gcmParams.ulIvLen = sizeof(nonce);
1930 gcmParams.pAAD = (unsigned char *)additionalData; /* const cast */
1931 gcmParams.ulAADLen = additionalDataLen;
1932 gcmParams.ulTagBits = tagSize * 8;
1934 cx = (AESContext *)keys->cipher_context;
1935 rv = AES_InitContext(cx, keys->write_key_item.data,
1936 keys->write_key_item.len,
1937 (unsigned char *)&gcmParams, NSS_AES_GCM, !doDecrypt,
1939 if (rv != SECSuccess) {
1943 rv = AES_Decrypt(cx, out, &uOutLen, maxout, in, inlen);
1945 rv = AES_Encrypt(cx, out, &uOutLen, maxout, in, inlen);
1947 AES_DestroyContext(cx, PR_FALSE);
1948 *outlen += (int) uOutLen;
1954 /* Initialize encryption and MAC contexts for pending spec.
1955 * Master Secret already is derived.
1956 * Caller holds Spec write lock.
1959 ssl3_InitPendingContextsPKCS11(sslSocket *ss)
1961 ssl3CipherSpec * pwSpec;
1962 const ssl3BulkCipherDef *cipher_def;
1963 PK11Context * serverContext = NULL;
1964 PK11Context * clientContext = NULL;
1966 CK_MECHANISM_TYPE mechanism;
1967 CK_MECHANISM_TYPE mac_mech;
1969 CK_ULONG effKeyBits;
1972 SSLCipherAlgorithm calg;
1974 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
1975 PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
1976 PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
1978 pwSpec = ss->ssl3.pwSpec;
1979 cipher_def = pwSpec->cipher_def;
1980 macLength = pwSpec->mac_size;
1981 calg = cipher_def->calg;
1982 PORT_Assert(alg2Mech[calg].calg == calg);
1984 pwSpec->client.write_mac_context = NULL;
1985 pwSpec->server.write_mac_context = NULL;
1987 if (calg == calg_aes_gcm) {
1988 pwSpec->encode = NULL;
1989 pwSpec->decode = NULL;
1990 pwSpec->destroy = NULL;
1991 pwSpec->encodeContext = NULL;
1992 pwSpec->decodeContext = NULL;
1993 pwSpec->aead = ssl3_AESGCM;
1998 ** Now setup the MAC contexts,
1999 ** crypto contexts are setup below.
2002 mac_mech = pwSpec->mac_def->mmech;
2003 mac_param.data = (unsigned char *)&macLength;
2004 mac_param.len = sizeof(macLength);
2007 pwSpec->client.write_mac_context = PK11_CreateContextBySymKey(
2008 mac_mech, CKA_SIGN, pwSpec->client.write_mac_key, &mac_param);
2009 if (pwSpec->client.write_mac_context == NULL) {
2010 ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
2013 pwSpec->server.write_mac_context = PK11_CreateContextBySymKey(
2014 mac_mech, CKA_SIGN, pwSpec->server.write_mac_key, &mac_param);
2015 if (pwSpec->server.write_mac_context == NULL) {
2016 ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
2021 ** Now setup the crypto contexts.
2024 if (calg == calg_null) {
2025 pwSpec->encode = Null_Cipher;
2026 pwSpec->decode = Null_Cipher;
2027 pwSpec->destroy = NULL;
2030 mechanism = alg2Mech[calg].cmech;
2031 effKeyBits = cipher_def->key_size * BPB;
2034 * build the server context
2036 iv.data = pwSpec->server.write_iv;
2037 iv.len = cipher_def->iv_size;
2038 param = ssl3_ParamFromIV(mechanism, &iv, effKeyBits);
2039 if (param == NULL) {
2040 ssl_MapLowLevelError(SSL_ERROR_IV_PARAM_FAILURE);
2043 serverContext = PK11_CreateContextBySymKey(mechanism,
2044 (ss->sec.isServer ? CKA_ENCRYPT : CKA_DECRYPT),
2045 pwSpec->server.write_key, param);
2046 iv.data = PK11_IVFromParam(mechanism, param, (int *)&iv.len);
2048 PORT_Memcpy(pwSpec->server.write_iv, iv.data, iv.len);
2049 SECITEM_FreeItem(param, PR_TRUE);
2050 if (serverContext == NULL) {
2051 ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
2056 * build the client context
2058 iv.data = pwSpec->client.write_iv;
2059 iv.len = cipher_def->iv_size;
2061 param = ssl3_ParamFromIV(mechanism, &iv, effKeyBits);
2062 if (param == NULL) {
2063 ssl_MapLowLevelError(SSL_ERROR_IV_PARAM_FAILURE);
2066 clientContext = PK11_CreateContextBySymKey(mechanism,
2067 (ss->sec.isServer ? CKA_DECRYPT : CKA_ENCRYPT),
2068 pwSpec->client.write_key, param);
2069 iv.data = PK11_IVFromParam(mechanism, param, (int *)&iv.len);
2071 PORT_Memcpy(pwSpec->client.write_iv, iv.data, iv.len);
2072 SECITEM_FreeItem(param,PR_TRUE);
2073 if (clientContext == NULL) {
2074 ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
2077 pwSpec->encode = (SSLCipher) PK11_CipherOp;
2078 pwSpec->decode = (SSLCipher) PK11_CipherOp;
2079 pwSpec->destroy = (SSLDestroy) PK11_DestroyContext;
2081 pwSpec->encodeContext = (ss->sec.isServer) ? serverContext : clientContext;
2082 pwSpec->decodeContext = (ss->sec.isServer) ? clientContext : serverContext;
2084 serverContext = NULL;
2085 clientContext = NULL;
2087 ssl3_InitCompressionContext(pwSpec);
2092 if (serverContext != NULL) PK11_DestroyContext(serverContext, PR_TRUE);
2093 if (clientContext != NULL) PK11_DestroyContext(clientContext, PR_TRUE);
2094 if (pwSpec->client.write_mac_context != NULL) {
2095 PK11_DestroyContext(pwSpec->client.write_mac_context,PR_TRUE);
2096 pwSpec->client.write_mac_context = NULL;
2098 if (pwSpec->server.write_mac_context != NULL) {
2099 PK11_DestroyContext(pwSpec->server.write_mac_context,PR_TRUE);
2100 pwSpec->server.write_mac_context = NULL;
2106 /* Complete the initialization of all keys, ciphers, MACs and their contexts
2107 * for the pending Cipher Spec.
2108 * Called from: ssl3_SendClientKeyExchange (for Full handshake)
2109 * ssl3_HandleRSAClientKeyExchange (for Full handshake)
2110 * ssl3_HandleServerHello (for session restart)
2111 * ssl3_HandleClientHello (for session restart)
2112 * Sets error code, but caller probably should override to disambiguate.
2113 * NULL pms means re-use old master_secret.
2115 * This code is common to the bypass and PKCS11 execution paths.
2116 * For the bypass case, pms is NULL.
2119 ssl3_InitPendingCipherSpec(sslSocket *ss, PK11SymKey *pms)
2121 ssl3CipherSpec * pwSpec;
2122 ssl3CipherSpec * cwSpec;
2125 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
2127 ssl_GetSpecWriteLock(ss); /**************************************/
2129 PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
2131 pwSpec = ss->ssl3.pwSpec;
2132 cwSpec = ss->ssl3.cwSpec;
2134 if (pms || (!pwSpec->msItem.len && !pwSpec->master_secret)) {
2135 rv = ssl3_DeriveMasterSecret(ss, pms);
2136 if (rv != SECSuccess) {
2137 goto done; /* err code set by ssl3_DeriveMasterSecret */
2140 #ifndef NO_PKCS11_BYPASS
2141 if (ss->opt.bypassPKCS11 && pwSpec->msItem.len && pwSpec->msItem.data) {
2142 /* Double Bypass succeeded in extracting the master_secret */
2143 const ssl3KEADef * kea_def = ss->ssl3.hs.kea_def;
2144 PRBool isTLS = (PRBool)(kea_def->tls_keygen ||
2145 (pwSpec->version > SSL_LIBRARY_VERSION_3_0));
2146 pwSpec->bypassCiphers = PR_TRUE;
2147 rv = ssl3_KeyAndMacDeriveBypass( pwSpec,
2148 (const unsigned char *)&ss->ssl3.hs.client_random,
2149 (const unsigned char *)&ss->ssl3.hs.server_random,
2151 (PRBool)(kea_def->is_limited));
2152 if (rv == SECSuccess) {
2153 rv = ssl3_InitPendingContextsBypass(ss);
2157 if (pwSpec->master_secret) {
2158 rv = ssl3_DeriveConnectionKeysPKCS11(ss);
2159 if (rv == SECSuccess) {
2160 rv = ssl3_InitPendingContextsPKCS11(ss);
2163 PORT_Assert(pwSpec->master_secret);
2164 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2167 if (rv != SECSuccess) {
2171 /* Generic behaviors -- common to all crypto methods */
2173 pwSpec->read_seq_num.high = pwSpec->write_seq_num.high = 0;
2175 if (cwSpec->epoch == PR_UINT16_MAX) {
2176 /* The problem here is that we have rehandshaked too many
2177 * times (you are not allowed to wrap the epoch). The
2178 * spec says you should be discarding the connection
2179 * and start over, so not much we can do here. */
2180 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2184 /* The sequence number has the high 16 bits as the epoch. */
2185 pwSpec->epoch = cwSpec->epoch + 1;
2186 pwSpec->read_seq_num.high = pwSpec->write_seq_num.high =
2187 pwSpec->epoch << 16;
2189 dtls_InitRecvdRecords(&pwSpec->recvdRecords);
2191 pwSpec->read_seq_num.low = pwSpec->write_seq_num.low = 0;
2194 ssl_ReleaseSpecWriteLock(ss); /******************************/
2195 if (rv != SECSuccess)
2196 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
2201 * 60 bytes is 3 times the maximum length MAC size that is supported.
2203 static const unsigned char mac_pad_1 [60] = {
2204 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
2205 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
2206 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
2207 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
2208 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
2209 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
2210 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
2211 0x36, 0x36, 0x36, 0x36
2213 static const unsigned char mac_pad_2 [60] = {
2214 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
2215 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
2216 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
2217 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
2218 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
2219 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
2220 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
2221 0x5c, 0x5c, 0x5c, 0x5c
2224 /* Called from: ssl3_SendRecord()
2225 ** Caller must already hold the SpecReadLock. (wish we could assert that!)
2228 ssl3_ComputeRecordMAC(
2229 ssl3CipherSpec * spec,
2230 PRBool useServerMacKey,
2231 const unsigned char *header,
2232 unsigned int headerLen,
2233 const SSL3Opaque * input,
2235 unsigned char * outbuf,
2236 unsigned int * outLength)
2238 const ssl3MACDef * mac_def;
2241 PRINT_BUF(95, (NULL, "frag hash1: header", header, headerLen));
2242 PRINT_BUF(95, (NULL, "frag hash1: input", input, inputLength));
2244 mac_def = spec->mac_def;
2245 if (mac_def->mac == mac_null) {
2249 #ifndef NO_PKCS11_BYPASS
2250 if (spec->bypassCiphers) {
2251 /* bypass version */
2252 const SECHashObject *hashObj = NULL;
2253 unsigned int pad_bytes = 0;
2254 PRUint64 write_mac_context[MAX_MAC_CONTEXT_LLONGS];
2256 switch (mac_def->mac) {
2262 hashObj = HASH_GetRawHashObject(HASH_AlgMD5);
2266 hashObj = HASH_GetRawHashObject(HASH_AlgSHA1);
2268 case ssl_hmac_md5: /* used with TLS */
2269 hashObj = HASH_GetRawHashObject(HASH_AlgMD5);
2271 case ssl_hmac_sha: /* used with TLS */
2272 hashObj = HASH_GetRawHashObject(HASH_AlgSHA1);
2274 case ssl_hmac_sha256: /* used with TLS */
2275 hashObj = HASH_GetRawHashObject(HASH_AlgSHA256);
2282 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2286 if (spec->version <= SSL_LIBRARY_VERSION_3_0) {
2287 unsigned int tempLen;
2288 unsigned char temp[MAX_MAC_LENGTH];
2290 /* compute "inner" part of SSL3 MAC */
2291 hashObj->begin(write_mac_context);
2292 if (useServerMacKey)
2293 hashObj->update(write_mac_context,
2294 spec->server.write_mac_key_item.data,
2295 spec->server.write_mac_key_item.len);
2297 hashObj->update(write_mac_context,
2298 spec->client.write_mac_key_item.data,
2299 spec->client.write_mac_key_item.len);
2300 hashObj->update(write_mac_context, mac_pad_1, pad_bytes);
2301 hashObj->update(write_mac_context, header, headerLen);
2302 hashObj->update(write_mac_context, input, inputLength);
2303 hashObj->end(write_mac_context, temp, &tempLen, sizeof temp);
2305 /* compute "outer" part of SSL3 MAC */
2306 hashObj->begin(write_mac_context);
2307 if (useServerMacKey)
2308 hashObj->update(write_mac_context,
2309 spec->server.write_mac_key_item.data,
2310 spec->server.write_mac_key_item.len);
2312 hashObj->update(write_mac_context,
2313 spec->client.write_mac_key_item.data,
2314 spec->client.write_mac_key_item.len);
2315 hashObj->update(write_mac_context, mac_pad_2, pad_bytes);
2316 hashObj->update(write_mac_context, temp, tempLen);
2317 hashObj->end(write_mac_context, outbuf, outLength, spec->mac_size);
2319 } else { /* is TLS */
2320 #define cx ((HMACContext *)write_mac_context)
2321 if (useServerMacKey) {
2322 rv = HMAC_Init(cx, hashObj,
2323 spec->server.write_mac_key_item.data,
2324 spec->server.write_mac_key_item.len, PR_FALSE);
2326 rv = HMAC_Init(cx, hashObj,
2327 spec->client.write_mac_key_item.data,
2328 spec->client.write_mac_key_item.len, PR_FALSE);
2330 if (rv == SECSuccess) {
2332 HMAC_Update(cx, header, headerLen);
2333 HMAC_Update(cx, input, inputLength);
2334 rv = HMAC_Finish(cx, outbuf, outLength, spec->mac_size);
2335 HMAC_Destroy(cx, PR_FALSE);
2342 PK11Context *mac_context =
2343 (useServerMacKey ? spec->server.write_mac_context
2344 : spec->client.write_mac_context);
2345 rv = PK11_DigestBegin(mac_context);
2346 rv |= PK11_DigestOp(mac_context, header, headerLen);
2347 rv |= PK11_DigestOp(mac_context, input, inputLength);
2348 rv |= PK11_DigestFinal(mac_context, outbuf, outLength, spec->mac_size);
2351 PORT_Assert(rv != SECSuccess || *outLength == (unsigned)spec->mac_size);
2353 PRINT_BUF(95, (NULL, "frag hash2: result", outbuf, *outLength));
2355 if (rv != SECSuccess) {
2357 ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
2362 /* Called from: ssl3_HandleRecord()
2363 * Caller must already hold the SpecReadLock. (wish we could assert that!)
2366 * originalLen >= inputLen >= MAC size
2369 ssl3_ComputeRecordMACConstantTime(
2370 ssl3CipherSpec * spec,
2371 PRBool useServerMacKey,
2372 const unsigned char *header,
2373 unsigned int headerLen,
2374 const SSL3Opaque * input,
2377 unsigned char * outbuf,
2378 unsigned int * outLen)
2380 CK_MECHANISM_TYPE macType;
2381 CK_NSS_MAC_CONSTANT_TIME_PARAMS params;
2382 SECItem param, inputItem, outputItem;
2386 PORT_Assert(inputLen >= spec->mac_size);
2387 PORT_Assert(originalLen >= inputLen);
2389 if (spec->bypassCiphers) {
2390 /* This function doesn't support PKCS#11 bypass. We fallback on the
2391 * non-constant time version. */
2395 if (spec->mac_def->mac == mac_null) {
2400 macType = CKM_NSS_HMAC_CONSTANT_TIME;
2401 if (spec->version <= SSL_LIBRARY_VERSION_3_0) {
2402 macType = CKM_NSS_SSL3_MAC_CONSTANT_TIME;
2405 params.macAlg = spec->mac_def->mmech;
2406 params.ulBodyTotalLen = originalLen;
2407 params.pHeader = (unsigned char *) header; /* const cast */
2408 params.ulHeaderLen = headerLen;
2410 param.data = (unsigned char*) ¶ms;
2411 param.len = sizeof(params);
2414 inputItem.data = (unsigned char *) input;
2415 inputItem.len = inputLen;
2418 outputItem.data = outbuf;
2419 outputItem.len = *outLen;
2420 outputItem.type = 0;
2422 key = spec->server.write_mac_key;
2423 if (!useServerMacKey) {
2424 key = spec->client.write_mac_key;
2427 rv = PK11_SignWithSymKey(key, macType, ¶m, &outputItem, &inputItem);
2428 if (rv != SECSuccess) {
2429 if (PORT_GetError() == SEC_ERROR_INVALID_ALGORITHM) {
2435 ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
2439 PORT_Assert(outputItem.len == (unsigned)spec->mac_size);
2440 *outLen = outputItem.len;
2445 /* ssl3_ComputeRecordMAC expects the MAC to have been removed from the
2446 * length already. */
2447 inputLen -= spec->mac_size;
2448 return ssl3_ComputeRecordMAC(spec, useServerMacKey, header, headerLen,
2449 input, inputLen, outbuf, outLen);
2453 ssl3_ClientAuthTokenPresent(sslSessionID *sid) {
2454 PK11SlotInfo *slot = NULL;
2455 PRBool isPresent = PR_TRUE;
2457 /* we only care if we are doing client auth */
2458 if (!sid || !sid->u.ssl3.clAuthValid) {
2463 slot = SECMOD_LookupSlot(sid->u.ssl3.clAuthModuleID,
2464 sid->u.ssl3.clAuthSlotID);
2466 !PK11_IsPresent(slot) ||
2467 sid->u.ssl3.clAuthSeries != PK11_GetSlotSeries(slot) ||
2468 sid->u.ssl3.clAuthSlotID != PK11_GetSlotID(slot) ||
2469 sid->u.ssl3.clAuthModuleID != PK11_GetModuleID(slot) ||
2470 (PK11_NeedLogin(slot) && !PK11_IsLoggedIn(slot, NULL))) {
2471 isPresent = PR_FALSE;
2474 PK11_FreeSlot(slot);
2479 /* Caller must hold the spec read lock. */
2481 ssl3_CompressMACEncryptRecord(ssl3CipherSpec * cwSpec,
2484 PRBool capRecordVersion,
2485 SSL3ContentType type,
2486 const SSL3Opaque * pIn,
2487 PRUint32 contentLen,
2490 const ssl3BulkCipherDef * cipher_def;
2492 PRUint32 macLen = 0;
2494 PRUint32 p1Len, p2Len, oddLen = 0;
2497 int cipherBytes = 0;
2498 unsigned char pseudoHeader[13];
2499 unsigned int pseudoHeaderLen;
2501 cipher_def = cwSpec->cipher_def;
2502 headerLen = isDTLS ? DTLS_RECORD_HEADER_LENGTH : SSL3_RECORD_HEADER_LENGTH;
2504 if (cipher_def->type == type_block &&
2505 cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
2506 /* Prepend the per-record explicit IV using technique 2b from
2507 * RFC 4346 section 6.2.3.2: The IV is a cryptographically
2508 * strong random number XORed with the CBC residue from the previous
2511 ivLen = cipher_def->iv_size;
2512 if (ivLen > wrBuf->space - headerLen) {
2513 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2516 rv = PK11_GenerateRandom(wrBuf->buf + headerLen, ivLen);
2517 if (rv != SECSuccess) {
2518 ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
2521 rv = cwSpec->encode( cwSpec->encodeContext,
2522 wrBuf->buf + headerLen,
2523 &cipherBytes, /* output and actual outLen */
2524 ivLen, /* max outlen */
2525 wrBuf->buf + headerLen,
2526 ivLen); /* input and inputLen*/
2527 if (rv != SECSuccess || cipherBytes != ivLen) {
2528 PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
2533 if (cwSpec->compressor) {
2535 rv = cwSpec->compressor(
2536 cwSpec->compressContext,
2537 wrBuf->buf + headerLen + ivLen, &outlen,
2538 wrBuf->space - headerLen - ivLen, pIn, contentLen);
2539 if (rv != SECSuccess)
2541 pIn = wrBuf->buf + headerLen + ivLen;
2542 contentLen = outlen;
2545 pseudoHeaderLen = ssl3_BuildRecordPseudoHeader(
2546 pseudoHeader, cwSpec->write_seq_num, type,
2547 cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_0, cwSpec->version,
2548 isDTLS, contentLen);
2549 PORT_Assert(pseudoHeaderLen <= sizeof(pseudoHeader));
2550 if (cipher_def->type == type_aead) {
2551 const int nonceLen = cipher_def->explicit_nonce_size;
2552 const int tagLen = cipher_def->tag_size;
2554 if (headerLen + nonceLen + contentLen + tagLen > wrBuf->space) {
2555 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2559 cipherBytes = contentLen;
2561 isServer ? &cwSpec->server : &cwSpec->client,
2562 PR_FALSE, /* do encrypt */
2563 wrBuf->buf + headerLen, /* output */
2564 &cipherBytes, /* out len */
2565 wrBuf->space - headerLen, /* max out */
2566 pIn, contentLen, /* input */
2567 pseudoHeader, pseudoHeaderLen);
2568 if (rv != SECSuccess) {
2569 PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
2576 rv = ssl3_ComputeRecordMAC(cwSpec, isServer,
2577 pseudoHeader, pseudoHeaderLen, pIn, contentLen,
2578 wrBuf->buf + headerLen + ivLen + contentLen, &macLen);
2579 if (rv != SECSuccess) {
2580 ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
2585 fragLen = contentLen + macLen; /* needs to be encrypted */
2586 PORT_Assert(fragLen <= MAX_FRAGMENT_LENGTH + 1024);
2589 * Pad the text (if we're doing a block cipher)
2592 if (cipher_def->type == type_block) {
2593 unsigned char * pBuf;
2597 oddLen = contentLen % cipher_def->block_size;
2598 /* Assume blockSize is a power of two */
2599 padding_length = cipher_def->block_size - 1 -
2600 ((fragLen) & (cipher_def->block_size - 1));
2601 fragLen += padding_length + 1;
2602 PORT_Assert((fragLen % cipher_def->block_size) == 0);
2604 /* Pad according to TLS rules (also acceptable to SSL3). */
2605 pBuf = &wrBuf->buf[headerLen + ivLen + fragLen - 1];
2606 for (i = padding_length + 1; i > 0; --i) {
2607 *pBuf-- = padding_length;
2609 /* now, if contentLen is not a multiple of block size, fix it */
2610 p2Len = fragLen - p1Len;
2620 PORT_Assert( (cipher_def->block_size < 2) || \
2621 (p2Len % cipher_def->block_size) == 0);
2622 memmove(wrBuf->buf + headerLen + ivLen + p1Len, pIn + p1Len,
2626 int cipherBytesPart1 = -1;
2627 rv = cwSpec->encode( cwSpec->encodeContext,
2628 wrBuf->buf + headerLen + ivLen, /* output */
2629 &cipherBytesPart1, /* actual outlen */
2630 p1Len, /* max outlen */
2631 pIn, p1Len); /* input, and inputlen */
2632 PORT_Assert(rv == SECSuccess && cipherBytesPart1 == (int) p1Len);
2633 if (rv != SECSuccess || cipherBytesPart1 != (int) p1Len) {
2634 PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
2637 cipherBytes += cipherBytesPart1;
2640 int cipherBytesPart2 = -1;
2641 rv = cwSpec->encode( cwSpec->encodeContext,
2642 wrBuf->buf + headerLen + ivLen + p1Len,
2643 &cipherBytesPart2, /* output and actual outLen */
2644 p2Len, /* max outlen */
2645 wrBuf->buf + headerLen + ivLen + p1Len,
2646 p2Len); /* input and inputLen*/
2647 PORT_Assert(rv == SECSuccess && cipherBytesPart2 == (int) p2Len);
2648 if (rv != SECSuccess || cipherBytesPart2 != (int) p2Len) {
2649 PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
2652 cipherBytes += cipherBytesPart2;
2656 PORT_Assert(cipherBytes <= MAX_FRAGMENT_LENGTH + 1024);
2658 wrBuf->len = cipherBytes + headerLen;
2659 wrBuf->buf[0] = type;
2661 SSL3ProtocolVersion version;
2663 version = dtls_TLSVersionToDTLSVersion(cwSpec->version);
2664 wrBuf->buf[1] = MSB(version);
2665 wrBuf->buf[2] = LSB(version);
2666 wrBuf->buf[3] = (unsigned char)(cwSpec->write_seq_num.high >> 24);
2667 wrBuf->buf[4] = (unsigned char)(cwSpec->write_seq_num.high >> 16);
2668 wrBuf->buf[5] = (unsigned char)(cwSpec->write_seq_num.high >> 8);
2669 wrBuf->buf[6] = (unsigned char)(cwSpec->write_seq_num.high >> 0);
2670 wrBuf->buf[7] = (unsigned char)(cwSpec->write_seq_num.low >> 24);
2671 wrBuf->buf[8] = (unsigned char)(cwSpec->write_seq_num.low >> 16);
2672 wrBuf->buf[9] = (unsigned char)(cwSpec->write_seq_num.low >> 8);
2673 wrBuf->buf[10] = (unsigned char)(cwSpec->write_seq_num.low >> 0);
2674 wrBuf->buf[11] = MSB(cipherBytes);
2675 wrBuf->buf[12] = LSB(cipherBytes);
2677 SSL3ProtocolVersion version = cwSpec->version;
2679 if (capRecordVersion) {
2680 version = PR_MIN(SSL_LIBRARY_VERSION_TLS_1_0, version);
2682 wrBuf->buf[1] = MSB(version);
2683 wrBuf->buf[2] = LSB(version);
2684 wrBuf->buf[3] = MSB(cipherBytes);
2685 wrBuf->buf[4] = LSB(cipherBytes);
2688 ssl3_BumpSequenceNumber(&cwSpec->write_seq_num);
2693 /* Process the plain text before sending it.
2694 * Returns the number of bytes of plaintext that were successfully sent
2695 * plus the number of bytes of plaintext that were copied into the
2696 * output (write) buffer.
2697 * Returns SECFailure on a hard IO error, memory error, or crypto error.
2698 * Does NOT return SECWouldBlock.
2700 * Notes on the use of the private ssl flags:
2701 * (no private SSL flags)
2702 * Attempt to make and send SSL records for all plaintext
2703 * If non-blocking and a send gets WOULD_BLOCK,
2704 * or if the pending (ciphertext) buffer is not empty,
2705 * then buffer remaining bytes of ciphertext into pending buf,
2706 * and continue to do that for all succssive records until all
2708 * ssl_SEND_FLAG_FORCE_INTO_BUFFER
2709 * As above, except this suppresses all write attempts, and forces
2710 * all ciphertext into the pending ciphertext buffer.
2711 * ssl_SEND_FLAG_USE_EPOCH (for DTLS)
2712 * Forces the use of the provided epoch
2713 * ssl_SEND_FLAG_CAP_RECORD_VERSION
2714 * Caps the record layer version number of TLS ClientHello to { 3, 1 }
2715 * (TLS 1.0). Some TLS 1.0 servers (which seem to use F5 BIG-IP) ignore
2716 * ClientHello.client_version and use the record layer version number
2717 * (TLSPlaintext.version) instead when negotiating protocol versions. In
2718 * addition, if the record layer version number of ClientHello is { 3, 2 }
2719 * (TLS 1.1) or higher, these servers reset the TCP connections. Set this
2720 * flag to work around such servers.
2723 ssl3_SendRecord( sslSocket * ss,
2724 DTLSEpoch epoch, /* DTLS only */
2725 SSL3ContentType type,
2726 const SSL3Opaque * pIn, /* input buffer */
2727 PRInt32 nIn, /* bytes of input */
2730 sslBuffer * wrBuf = &ss->sec.writeBuf;
2732 PRInt32 totalSent = 0;
2733 PRBool capRecordVersion;
2735 SSL_TRC(3, ("%d: SSL3[%d] SendRecord type: %s nIn=%d",
2736 SSL_GETPID(), ss->fd, ssl3_DecodeContentType(type),
2738 PRINT_BUF(3, (ss, "Send record (plain text)", pIn, nIn));
2740 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
2742 capRecordVersion = ((flags & ssl_SEND_FLAG_CAP_RECORD_VERSION) != 0);
2744 if (capRecordVersion) {
2745 /* ssl_SEND_FLAG_CAP_RECORD_VERSION can only be used with the
2746 * TLS initial ClientHello. */
2747 PORT_Assert(!IS_DTLS(ss));
2748 PORT_Assert(!ss->firstHsDone);
2749 PORT_Assert(type == content_handshake);
2750 PORT_Assert(ss->ssl3.hs.ws == wait_server_hello);
2753 if (ss->ssl3.initialized == PR_FALSE) {
2754 /* This can happen on a server if the very first incoming record
2755 ** looks like a defective ssl3 record (e.g. too long), and we're
2756 ** trying to send an alert.
2758 PR_ASSERT(type == content_alert);
2759 rv = ssl3_InitState(ss);
2760 if (rv != SECSuccess) {
2761 return SECFailure; /* ssl3_InitState has set the error code. */
2765 /* check for Token Presence */
2766 if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) {
2767 PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
2772 PRUint32 contentLen = PR_MIN(nIn, MAX_FRAGMENT_LENGTH);
2773 unsigned int spaceNeeded;
2774 unsigned int numRecords;
2776 ssl_GetSpecReadLock(ss); /********************************/
2778 if (nIn > 1 && ss->opt.cbcRandomIV &&
2779 ss->ssl3.cwSpec->version < SSL_LIBRARY_VERSION_TLS_1_1 &&
2780 type == content_application_data &&
2781 ss->ssl3.cwSpec->cipher_def->type == type_block /* CBC mode */) {
2782 /* We will split the first byte of the record into its own record,
2783 * as explained in the documentation for SSL_CBC_RANDOM_IV in ssl.h
2790 spaceNeeded = contentLen + (numRecords * SSL3_BUFFER_FUDGE);
2791 if (ss->ssl3.cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1 &&
2792 ss->ssl3.cwSpec->cipher_def->type == type_block) {
2793 spaceNeeded += ss->ssl3.cwSpec->cipher_def->iv_size;
2795 if (spaceNeeded > wrBuf->space) {
2796 rv = sslBuffer_Grow(wrBuf, spaceNeeded);
2797 if (rv != SECSuccess) {
2798 SSL_DBG(("%d: SSL3[%d]: SendRecord, tried to get %d bytes",
2799 SSL_GETPID(), ss->fd, spaceNeeded));
2800 goto spec_locked_loser; /* sslBuffer_Grow set error code. */
2804 if (numRecords == 2) {
2805 sslBuffer secondRecord;
2807 rv = ssl3_CompressMACEncryptRecord(ss->ssl3.cwSpec,
2808 ss->sec.isServer, IS_DTLS(ss),
2809 capRecordVersion, type, pIn,
2811 if (rv != SECSuccess)
2812 goto spec_locked_loser;
2814 PRINT_BUF(50, (ss, "send (encrypted) record data [1/2]:",
2815 wrBuf->buf, wrBuf->len));
2817 secondRecord.buf = wrBuf->buf + wrBuf->len;
2818 secondRecord.len = 0;
2819 secondRecord.space = wrBuf->space - wrBuf->len;
2821 rv = ssl3_CompressMACEncryptRecord(ss->ssl3.cwSpec,
2822 ss->sec.isServer, IS_DTLS(ss),
2823 capRecordVersion, type,
2824 pIn + 1, contentLen - 1,
2826 if (rv == SECSuccess) {
2827 PRINT_BUF(50, (ss, "send (encrypted) record data [2/2]:",
2828 secondRecord.buf, secondRecord.len));
2829 wrBuf->len += secondRecord.len;
2833 rv = ssl3_CompressMACEncryptRecord(ss->ssl3.cwSpec,
2840 rv = dtls_CompressMACEncryptRecord(ss, epoch,
2841 !!(flags & ssl_SEND_FLAG_USE_EPOCH),
2846 if (rv == SECSuccess) {
2847 PRINT_BUF(50, (ss, "send (encrypted) record data:",
2848 wrBuf->buf, wrBuf->len));
2853 ssl_ReleaseSpecReadLock(ss); /************************************/
2855 if (rv != SECSuccess)
2860 PORT_Assert( nIn >= 0 );
2862 /* If there's still some previously saved ciphertext,
2863 * or the caller doesn't want us to send the data yet,
2864 * then add all our new ciphertext to the amount previously saved.
2866 if ((ss->pendingBuf.len > 0) ||
2867 (flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) {
2869 rv = ssl_SaveWriteData(ss, wrBuf->buf, wrBuf->len);
2870 if (rv != SECSuccess) {
2871 /* presumably a memory error, SEC_ERROR_NO_MEMORY */
2874 wrBuf->len = 0; /* All cipher text is saved away. */
2876 if (!(flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) {
2878 ss->handshakeBegun = 1;
2879 sent = ssl_SendSavedWriteData(ss);
2880 if (sent < 0 && PR_GetError() != PR_WOULD_BLOCK_ERROR) {
2881 ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE);
2884 if (ss->pendingBuf.len) {
2885 flags |= ssl_SEND_FLAG_FORCE_INTO_BUFFER;
2888 } else if (wrBuf->len > 0) {
2890 ss->handshakeBegun = 1;
2891 sent = ssl_DefSend(ss, wrBuf->buf, wrBuf->len,
2892 flags & ~ssl_SEND_FLAG_MASK);
2894 if (PR_GetError() != PR_WOULD_BLOCK_ERROR) {
2895 ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE);
2898 /* we got PR_WOULD_BLOCK_ERROR, which means none was sent. */
2904 /* DTLS just says no in this case. No buffering */
2905 PR_SetError(PR_WOULD_BLOCK_ERROR, 0);
2908 /* now take all the remaining unsent new ciphertext and
2909 * append it to the buffer of previously unsent ciphertext.
2911 rv = ssl_SaveWriteData(ss, wrBuf->buf + sent, wrBuf->len);
2912 if (rv != SECSuccess) {
2913 /* presumably a memory error, SEC_ERROR_NO_MEMORY */
2918 totalSent += contentLen;
2923 #define SSL3_PENDING_HIGH_WATER 1024
2925 /* Attempt to send the content of "in" in an SSL application_data record.
2926 * Returns "len" or SECFailure, never SECWouldBlock, nor SECSuccess.
2929 ssl3_SendApplicationData(sslSocket *ss, const unsigned char *in,
2930 PRInt32 len, PRInt32 flags)
2932 PRInt32 totalSent = 0;
2933 PRInt32 discarded = 0;
2935 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
2936 /* These flags for internal use only */
2937 PORT_Assert(!(flags & (ssl_SEND_FLAG_USE_EPOCH |
2938 ssl_SEND_FLAG_NO_RETRANSMIT)));
2939 if (len < 0 || !in) {
2940 PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
2944 if (ss->pendingBuf.len > SSL3_PENDING_HIGH_WATER &&
2945 !ssl_SocketIsBlocking(ss)) {
2946 PORT_Assert(!ssl_SocketIsBlocking(ss));
2947 PORT_SetError(PR_WOULD_BLOCK_ERROR);
2951 if (ss->appDataBuffered && len) {
2952 PORT_Assert (in[0] == (unsigned char)(ss->appDataBuffered));
2953 if (in[0] != (unsigned char)(ss->appDataBuffered)) {
2954 PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
2961 while (len > totalSent) {
2962 PRInt32 sent, toSend;
2964 if (totalSent > 0) {
2966 * The thread yield is intended to give the reader thread a
2967 * chance to get some cycles while the writer thread is in
2968 * the middle of a large application data write. (See
2969 * Bugzilla bug 127740, comment #1.)
2971 ssl_ReleaseXmitBufLock(ss);
2972 PR_Sleep(PR_INTERVAL_NO_WAIT); /* PR_Yield(); */
2973 ssl_GetXmitBufLock(ss);
2975 toSend = PR_MIN(len - totalSent, MAX_FRAGMENT_LENGTH);
2977 * Note that the 0 epoch is OK because flags will never require
2978 * its use, as guaranteed by the PORT_Assert above.
2980 sent = ssl3_SendRecord(ss, 0, content_application_data,
2981 in + totalSent, toSend, flags);
2983 if (totalSent > 0 && PR_GetError() == PR_WOULD_BLOCK_ERROR) {
2984 PORT_Assert(ss->lastWriteBlocked);
2987 return SECFailure; /* error code set by ssl3_SendRecord */
2990 if (ss->pendingBuf.len) {
2991 /* must be a non-blocking socket */
2992 PORT_Assert(!ssl_SocketIsBlocking(ss));
2993 PORT_Assert(ss->lastWriteBlocked);
2997 if (ss->pendingBuf.len) {
2998 /* Must be non-blocking. */
2999 PORT_Assert(!ssl_SocketIsBlocking(ss));
3000 if (totalSent > 0) {
3001 ss->appDataBuffered = 0x100 | in[totalSent - 1];
3004 totalSent = totalSent + discarded - 1;
3005 if (totalSent <= 0) {
3006 PORT_SetError(PR_WOULD_BLOCK_ERROR);
3007 totalSent = SECFailure;
3011 ss->appDataBuffered = 0;
3012 return totalSent + discarded;
3015 /* Attempt to send buffered handshake messages.
3016 * This function returns SECSuccess or SECFailure, never SECWouldBlock.
3017 * Always set sendBuf.len to 0, even when returning SECFailure.
3019 * Depending on whether we are doing DTLS or not, this either calls
3021 * - ssl3_FlushHandshakeMessages if non-DTLS
3022 * - dtls_FlushHandshakeMessages if DTLS
3024 * Called from SSL3_SendAlert(), ssl3_SendChangeCipherSpecs(),
3025 * ssl3_AppendHandshake(), ssl3_SendClientHello(),
3026 * ssl3_SendHelloRequest(), ssl3_SendServerHelloDone(),
3027 * ssl3_SendFinished(),
3030 ssl3_FlushHandshake(sslSocket *ss, PRInt32 flags)
3033 return dtls_FlushHandshakeMessages(ss, flags);
3035 return ssl3_FlushHandshakeMessages(ss, flags);
3039 /* Attempt to send the content of sendBuf buffer in an SSL handshake record.
3040 * This function returns SECSuccess or SECFailure, never SECWouldBlock.
3041 * Always set sendBuf.len to 0, even when returning SECFailure.
3043 * Called from ssl3_FlushHandshake
3046 ssl3_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags)
3048 static const PRInt32 allowedFlags = ssl_SEND_FLAG_FORCE_INTO_BUFFER |
3049 ssl_SEND_FLAG_CAP_RECORD_VERSION;
3050 PRInt32 rv = SECSuccess;
3052 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3053 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
3055 if (!ss->sec.ci.sendBuf.buf || !ss->sec.ci.sendBuf.len)
3058 /* only these flags are allowed */
3059 PORT_Assert(!(flags & ~allowedFlags));
3060 if ((flags & ~allowedFlags) != 0) {
3061 PORT_SetError(SEC_ERROR_INVALID_ARGS);
3064 rv = ssl3_SendRecord(ss, 0, content_handshake, ss->sec.ci.sendBuf.buf,
3065 ss->sec.ci.sendBuf.len, flags);
3068 int err = PORT_GetError();
3069 PORT_Assert(err != PR_WOULD_BLOCK_ERROR);
3070 if (err == PR_WOULD_BLOCK_ERROR) {
3071 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
3073 } else if (rv < ss->sec.ci.sendBuf.len) {
3074 /* short write should never happen */
3075 PORT_Assert(rv >= ss->sec.ci.sendBuf.len);
3076 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
3082 /* Whether we succeeded or failed, toss the old handshake data. */
3083 ss->sec.ci.sendBuf.len = 0;
3088 * Called from ssl3_HandleAlert and from ssl3_HandleCertificate when
3089 * the remote client sends a negative response to our certificate request.
3090 * Returns SECFailure if the application has required client auth.
3091 * SECSuccess otherwise.
3094 ssl3_HandleNoCertificate(sslSocket *ss)
3096 if (ss->sec.peerCert != NULL) {
3097 if (ss->sec.peerKey != NULL) {
3098 SECKEY_DestroyPublicKey(ss->sec.peerKey);
3099 ss->sec.peerKey = NULL;
3101 CERT_DestroyCertificate(ss->sec.peerCert);
3102 ss->sec.peerCert = NULL;
3104 ssl3_CleanupPeerCerts(ss);
3106 /* If the server has required client-auth blindly but doesn't
3107 * actually look at the certificate it won't know that no
3108 * certificate was presented so we shutdown the socket to ensure
3109 * an error. We only do this if we haven't already completed the
3110 * first handshake because if we're redoing the handshake we
3111 * know the server is paying attention to the certificate.
3113 if ((ss->opt.requireCertificate == SSL_REQUIRE_ALWAYS) ||
3114 (!ss->firstHsDone &&
3115 (ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE))) {
3118 if (ss->sec.uncache)
3119 ss->sec.uncache(ss->sec.ci.sid);
3120 SSL3_SendAlert(ss, alert_fatal, bad_certificate);
3122 lower = ss->fd->lower;
3124 lower->methods->shutdown(lower, PR_SHUTDOWN_SEND);
3126 lower->methods->shutdown(lower, PR_SHUTDOWN_BOTH);
3128 PORT_SetError(SSL_ERROR_NO_CERTIFICATE);
3134 /************************************************************************
3139 ** Acquires both handshake and XmitBuf locks.
3140 ** Called from: ssl3_IllegalParameter <-
3141 ** ssl3_HandshakeFailure <-
3142 ** ssl3_HandleAlert <- ssl3_HandleRecord.
3143 ** ssl3_HandleChangeCipherSpecs <- ssl3_HandleRecord
3144 ** ssl3_ConsumeHandshakeVariable <-
3145 ** ssl3_HandleHelloRequest <-
3146 ** ssl3_HandleServerHello <-
3147 ** ssl3_HandleServerKeyExchange <-
3148 ** ssl3_HandleCertificateRequest <-
3149 ** ssl3_HandleServerHelloDone <-
3150 ** ssl3_HandleClientHello <-
3151 ** ssl3_HandleV2ClientHello <-
3152 ** ssl3_HandleCertificateVerify <-
3153 ** ssl3_HandleClientKeyExchange <-
3154 ** ssl3_HandleCertificate <-
3155 ** ssl3_HandleFinished <-
3156 ** ssl3_HandleHandshakeMessage <-
3157 ** ssl3_HandleRecord <-
3161 SSL3_SendAlert(sslSocket *ss, SSL3AlertLevel level, SSL3AlertDescription desc)
3166 SSL_TRC(3, ("%d: SSL3[%d]: send alert record, level=%d desc=%d",
3167 SSL_GETPID(), ss->fd, level, desc));
3172 ssl_GetSSL3HandshakeLock(ss);
3173 if (level == alert_fatal) {
3174 if (!ss->opt.noCache && ss->sec.ci.sid && ss->sec.uncache) {
3175 ss->sec.uncache(ss->sec.ci.sid);
3178 ssl_GetXmitBufLock(ss);
3179 rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
3180 if (rv == SECSuccess) {
3182 sent = ssl3_SendRecord(ss, 0, content_alert, bytes, 2,
3183 desc == no_certificate
3184 ? ssl_SEND_FLAG_FORCE_INTO_BUFFER : 0);
3185 rv = (sent >= 0) ? SECSuccess : (SECStatus)sent;
3187 ssl_ReleaseXmitBufLock(ss);
3188 ssl_ReleaseSSL3HandshakeLock(ss);
3189 return rv; /* error set by ssl3_FlushHandshake or ssl3_SendRecord */
3193 * Send illegal_parameter alert. Set generic error number.
3196 ssl3_IllegalParameter(sslSocket *ss)
3198 (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
3199 PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
3200 : SSL_ERROR_BAD_SERVER );
3205 * Send handshake_Failure alert. Set generic error number.
3208 ssl3_HandshakeFailure(sslSocket *ss)
3210 (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure);
3211 PORT_SetError( ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
3212 : SSL_ERROR_BAD_SERVER );
3217 ssl3_SendAlertForCertError(sslSocket * ss, PRErrorCode errCode)
3219 SSL3AlertDescription desc = bad_certificate;
3220 PRBool isTLS = ss->version >= SSL_LIBRARY_VERSION_3_1_TLS;
3223 case SEC_ERROR_LIBRARY_FAILURE: desc = unsupported_certificate; break;
3224 case SEC_ERROR_EXPIRED_CERTIFICATE: desc = certificate_expired; break;
3225 case SEC_ERROR_REVOKED_CERTIFICATE: desc = certificate_revoked; break;
3226 case SEC_ERROR_INADEQUATE_KEY_USAGE:
3227 case SEC_ERROR_INADEQUATE_CERT_TYPE:
3228 desc = certificate_unknown; break;
3229 case SEC_ERROR_UNTRUSTED_CERT:
3230 desc = isTLS ? access_denied : certificate_unknown; break;
3231 case SEC_ERROR_UNKNOWN_ISSUER:
3232 case SEC_ERROR_UNTRUSTED_ISSUER:
3233 desc = isTLS ? unknown_ca : certificate_unknown; break;
3234 case SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE:
3235 desc = isTLS ? unknown_ca : certificate_expired; break;
3237 case SEC_ERROR_CERT_NOT_IN_NAME_SPACE:
3238 case SEC_ERROR_PATH_LEN_CONSTRAINT_INVALID:
3239 case SEC_ERROR_CA_CERT_INVALID:
3240 case SEC_ERROR_BAD_SIGNATURE:
3241 default: desc = bad_certificate; break;
3243 SSL_DBG(("%d: SSL3[%d]: peer certificate is no good: error=%d",
3244 SSL_GETPID(), ss->fd, errCode));
3246 (void) SSL3_SendAlert(ss, alert_fatal, desc);
3251 * Send decode_error alert. Set generic error number.
3254 ssl3_DecodeError(sslSocket *ss)
3256 (void)SSL3_SendAlert(ss, alert_fatal,
3257 ss->version > SSL_LIBRARY_VERSION_3_0 ? decode_error
3258 : illegal_parameter);
3259 PORT_SetError( ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
3260 : SSL_ERROR_BAD_SERVER );
3264 /* Called from ssl3_HandleRecord.
3265 ** Caller must hold both RecvBuf and Handshake locks.
3268 ssl3_HandleAlert(sslSocket *ss, sslBuffer *buf)
3270 SSL3AlertLevel level;
3271 SSL3AlertDescription desc;
3274 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
3275 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
3277 SSL_TRC(3, ("%d: SSL3[%d]: handle alert record", SSL_GETPID(), ss->fd));
3279 if (buf->len != 2) {
3280 (void)ssl3_DecodeError(ss);
3281 PORT_SetError(SSL_ERROR_RX_MALFORMED_ALERT);
3284 level = (SSL3AlertLevel)buf->buf[0];
3285 desc = (SSL3AlertDescription)buf->buf[1];
3287 SSL_TRC(5, ("%d: SSL3[%d] received alert, level = %d, description = %d",
3288 SSL_GETPID(), ss->fd, level, desc));
3291 case close_notify: ss->recvdCloseNotify = 1;
3292 error = SSL_ERROR_CLOSE_NOTIFY_ALERT; break;
3293 case unexpected_message: error = SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT;
3295 case bad_record_mac: error = SSL_ERROR_BAD_MAC_ALERT; break;
3296 case decryption_failed_RESERVED:
3297 error = SSL_ERROR_DECRYPTION_FAILED_ALERT;
3299 case record_overflow: error = SSL_ERROR_RECORD_OVERFLOW_ALERT; break;
3300 case decompression_failure: error = SSL_ERROR_DECOMPRESSION_FAILURE_ALERT;
3302 case handshake_failure: error = SSL_ERROR_HANDSHAKE_FAILURE_ALERT;
3304 case no_certificate: error = SSL_ERROR_NO_CERTIFICATE; break;
3305 case bad_certificate: error = SSL_ERROR_BAD_CERT_ALERT; break;
3306 case unsupported_certificate:error = SSL_ERROR_UNSUPPORTED_CERT_ALERT;break;
3307 case certificate_revoked: error = SSL_ERROR_REVOKED_CERT_ALERT; break;
3308 case certificate_expired: error = SSL_ERROR_EXPIRED_CERT_ALERT; break;
3309 case certificate_unknown: error = SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT;
3311 case illegal_parameter: error = SSL_ERROR_ILLEGAL_PARAMETER_ALERT;break;
3313 /* All alerts below are TLS only. */
3314 case unknown_ca: error = SSL_ERROR_UNKNOWN_CA_ALERT; break;
3315 case access_denied: error = SSL_ERROR_ACCESS_DENIED_ALERT; break;
3316 case decode_error: error = SSL_ERROR_DECODE_ERROR_ALERT; break;
3317 case decrypt_error: error = SSL_ERROR_DECRYPT_ERROR_ALERT; break;
3318 case export_restriction: error = SSL_ERROR_EXPORT_RESTRICTION_ALERT;
3320 case protocol_version: error = SSL_ERROR_PROTOCOL_VERSION_ALERT; break;
3321 case insufficient_security: error = SSL_ERROR_INSUFFICIENT_SECURITY_ALERT;
3323 case internal_error: error = SSL_ERROR_INTERNAL_ERROR_ALERT; break;
3324 case user_canceled: error = SSL_ERROR_USER_CANCELED_ALERT; break;
3325 case no_renegotiation: error = SSL_ERROR_NO_RENEGOTIATION_ALERT; break;
3327 /* Alerts for TLS client hello extensions */
3328 case unsupported_extension:
3329 error = SSL_ERROR_UNSUPPORTED_EXTENSION_ALERT; break;
3330 case certificate_unobtainable:
3331 error = SSL_ERROR_CERTIFICATE_UNOBTAINABLE_ALERT; break;
3332 case unrecognized_name:
3333 error = SSL_ERROR_UNRECOGNIZED_NAME_ALERT; break;
3334 case bad_certificate_status_response:
3335 error = SSL_ERROR_BAD_CERT_STATUS_RESPONSE_ALERT; break;
3336 case bad_certificate_hash_value:
3337 error = SSL_ERROR_BAD_CERT_HASH_VALUE_ALERT; break;
3338 default: error = SSL_ERROR_RX_UNKNOWN_ALERT; break;
3340 if (level == alert_fatal) {
3341 if (!ss->opt.noCache) {
3342 if (ss->sec.uncache)
3343 ss->sec.uncache(ss->sec.ci.sid);
3345 if ((ss->ssl3.hs.ws == wait_server_hello) &&
3346 (desc == handshake_failure)) {
3347 /* XXX This is a hack. We're assuming that any handshake failure
3348 * XXX on the client hello is a failure to match ciphers.
3350 error = SSL_ERROR_NO_CYPHER_OVERLAP;
3352 PORT_SetError(error);
3355 if ((desc == no_certificate) && (ss->ssl3.hs.ws == wait_client_cert)) {
3356 /* I'm a server. I've requested a client cert. He hasn't got one. */
3359 PORT_Assert(ss->sec.isServer);
3360 ss->ssl3.hs.ws = wait_client_key;
3361 rv = ssl3_HandleNoCertificate(ss);
3368 * Change Cipher Specs
3369 * Called from ssl3_HandleServerHelloDone,
3370 * ssl3_HandleClientHello,
3371 * and ssl3_HandleFinished
3373 * Acquires and releases spec write lock, to protect switching the current
3374 * and pending write spec pointers.
3378 ssl3_SendChangeCipherSpecs(sslSocket *ss)
3380 PRUint8 change = change_cipher_spec_choice;
3381 ssl3CipherSpec * pwSpec;
3385 SSL_TRC(3, ("%d: SSL3[%d]: send change_cipher_spec record",
3386 SSL_GETPID(), ss->fd));
3388 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
3389 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3391 rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
3392 if (rv != SECSuccess) {
3393 return rv; /* error code set by ssl3_FlushHandshake */
3396 sent = ssl3_SendRecord(ss, 0, content_change_cipher_spec, &change, 1,
3397 ssl_SEND_FLAG_FORCE_INTO_BUFFER);
3399 return (SECStatus)sent; /* error code set by ssl3_SendRecord */
3402 rv = dtls_QueueMessage(ss, content_change_cipher_spec, &change, 1);
3403 if (rv != SECSuccess) {
3408 /* swap the pending and current write specs. */
3409 ssl_GetSpecWriteLock(ss); /**************************************/
3410 pwSpec = ss->ssl3.pwSpec;
3412 ss->ssl3.pwSpec = ss->ssl3.cwSpec;
3413 ss->ssl3.cwSpec = pwSpec;
3415 SSL_TRC(3, ("%d: SSL3[%d] Set Current Write Cipher Suite to Pending",
3416 SSL_GETPID(), ss->fd ));
3418 /* We need to free up the contexts, keys and certs ! */
3419 /* If we are really through with the old cipher spec
3420 * (Both the read and write sides have changed) destroy it.
3422 if (ss->ssl3.prSpec == ss->ssl3.pwSpec) {
3424 ssl3_DestroyCipherSpec(ss->ssl3.pwSpec, PR_FALSE/*freeSrvName*/);
3426 /* With DTLS, we need to set a holddown timer in case the final
3427 * message got lost */
3428 ss->ssl3.hs.rtTimeoutMs = DTLS_FINISHED_TIMER_MS;
3429 dtls_StartTimer(ss, dtls_FinishedTimerCb);
3432 ssl_ReleaseSpecWriteLock(ss); /**************************************/
3437 /* Called from ssl3_HandleRecord.
3438 ** Caller must hold both RecvBuf and Handshake locks.
3440 * Acquires and releases spec write lock, to protect switching the current
3441 * and pending write spec pointers.
3444 ssl3_HandleChangeCipherSpecs(sslSocket *ss, sslBuffer *buf)
3446 ssl3CipherSpec * prSpec;
3447 SSL3WaitState ws = ss->ssl3.hs.ws;
3448 SSL3ChangeCipherSpecChoice change;
3450 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
3451 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
3453 SSL_TRC(3, ("%d: SSL3[%d]: handle change_cipher_spec record",
3454 SSL_GETPID(), ss->fd));
3456 if (ws != wait_change_cipher) {
3457 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
3458 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER);
3463 (void)ssl3_DecodeError(ss);
3464 PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER);
3467 change = (SSL3ChangeCipherSpecChoice)buf->buf[0];
3468 if (change != change_cipher_spec_choice) {
3469 /* illegal_parameter is correct here for both SSL3 and TLS. */
3470 (void)ssl3_IllegalParameter(ss);
3471 PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER);
3476 /* Swap the pending and current read specs. */
3477 ssl_GetSpecWriteLock(ss); /*************************************/
3478 prSpec = ss->ssl3.prSpec;
3480 ss->ssl3.prSpec = ss->ssl3.crSpec;
3481 ss->ssl3.crSpec = prSpec;
3482 ss->ssl3.hs.ws = wait_finished;
3484 SSL_TRC(3, ("%d: SSL3[%d] Set Current Read Cipher Suite to Pending",
3485 SSL_GETPID(), ss->fd ));
3487 /* If we are really through with the old cipher prSpec
3488 * (Both the read and write sides have changed) destroy it.
3490 if (ss->ssl3.prSpec == ss->ssl3.pwSpec) {
3491 ssl3_DestroyCipherSpec(ss->ssl3.prSpec, PR_FALSE/*freeSrvName*/);
3493 ssl_ReleaseSpecWriteLock(ss); /*************************************/
3497 /* This method uses PKCS11 to derive the MS from the PMS, where PMS
3498 ** is a PKCS11 symkey. This is used in all cases except the
3499 ** "triple bypass" with RSA key exchange.
3500 ** Called from ssl3_InitPendingCipherSpec. prSpec is pwSpec.
3503 ssl3_DeriveMasterSecret(sslSocket *ss, PK11SymKey *pms)
3505 ssl3CipherSpec * pwSpec = ss->ssl3.pwSpec;
3506 const ssl3KEADef *kea_def= ss->ssl3.hs.kea_def;
3507 unsigned char * cr = (unsigned char *)&ss->ssl3.hs.client_random;
3508 unsigned char * sr = (unsigned char *)&ss->ssl3.hs.server_random;
3509 PRBool isTLS = (PRBool)(kea_def->tls_keygen ||
3510 (pwSpec->version > SSL_LIBRARY_VERSION_3_0));
3512 (PRBool)(isTLS && pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
3514 * Whenever isDH is true, we need to use CKM_TLS_MASTER_KEY_DERIVE_DH
3515 * which, unlike CKM_TLS_MASTER_KEY_DERIVE, converts arbitrary size
3516 * data into a 48-byte value.
3518 PRBool isDH = (PRBool) ((ss->ssl3.hs.kea_def->exchKeyType == kt_dh) ||
3519 (ss->ssl3.hs.kea_def->exchKeyType == kt_ecdh));
3520 SECStatus rv = SECFailure;
3521 CK_MECHANISM_TYPE master_derive;
3522 CK_MECHANISM_TYPE key_derive;
3525 CK_VERSION pms_version;
3526 CK_SSL3_MASTER_KEY_DERIVE_PARAMS master_params;
3528 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3529 PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
3530 PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
3532 if(isDH) master_derive = CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256;
3533 else master_derive = CKM_NSS_TLS_MASTER_KEY_DERIVE_SHA256;
3534 key_derive = CKM_NSS_TLS_KEY_AND_MAC_DERIVE_SHA256;
3535 keyFlags = CKF_SIGN | CKF_VERIFY;
3537 if(isDH) master_derive = CKM_TLS_MASTER_KEY_DERIVE_DH;
3538 else master_derive = CKM_TLS_MASTER_KEY_DERIVE;
3539 key_derive = CKM_TLS_KEY_AND_MAC_DERIVE;
3540 keyFlags = CKF_SIGN | CKF_VERIFY;
3542 if (isDH) master_derive = CKM_SSL3_MASTER_KEY_DERIVE_DH;
3543 else master_derive = CKM_SSL3_MASTER_KEY_DERIVE;
3544 key_derive = CKM_SSL3_KEY_AND_MAC_DERIVE;
3548 if (pms || !pwSpec->master_secret) {
3550 master_params.pVersion = NULL;
3552 master_params.pVersion = &pms_version;
3554 master_params.RandomInfo.pClientRandom = cr;
3555 master_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH;
3556 master_params.RandomInfo.pServerRandom = sr;
3557 master_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH;
3559 params.data = (unsigned char *) &master_params;
3560 params.len = sizeof master_params;
3565 if (ssl_trace >= 100) {
3566 SECStatus extractRV = PK11_ExtractKeyValue(pms);
3567 if (extractRV == SECSuccess) {
3568 SECItem * keyData = PK11_GetKeyData(pms);
3569 if (keyData && keyData->data && keyData->len) {
3570 ssl_PrintBuf(ss, "Pre-Master Secret",
3571 keyData->data, keyData->len);
3576 pwSpec->master_secret = PK11_DeriveWithFlags(pms, master_derive,
3577 ¶ms, key_derive, CKA_DERIVE, 0, keyFlags);
3578 if (!isDH && pwSpec->master_secret && ss->opt.detectRollBack) {
3579 SSL3ProtocolVersion client_version;
3580 client_version = pms_version.major << 8 | pms_version.minor;
3583 client_version = dtls_DTLSVersionToTLSVersion(client_version);
3586 if (client_version != ss->clientHelloVersion) {
3587 /* Destroy it. Version roll-back detected. */
3588 PK11_FreeSymKey(pwSpec->master_secret);
3589 pwSpec->master_secret = NULL;
3592 if (pwSpec->master_secret == NULL) {
3593 /* Generate a faux master secret in the same slot as the old one. */
3594 PK11SlotInfo * slot = PK11_GetSlotFromKey((PK11SymKey *)pms);
3595 PK11SymKey * fpms = ssl3_GenerateRSAPMS(ss, pwSpec, slot);
3597 PK11_FreeSlot(slot);
3599 pwSpec->master_secret = PK11_DeriveWithFlags(fpms,
3600 master_derive, ¶ms, key_derive,
3601 CKA_DERIVE, 0, keyFlags);
3602 PK11_FreeSymKey(fpms);
3606 if (pwSpec->master_secret == NULL) {
3607 /* Generate a faux master secret from the internal slot. */
3608 PK11SlotInfo * slot = PK11_GetInternalSlot();
3609 PK11SymKey * fpms = ssl3_GenerateRSAPMS(ss, pwSpec, slot);
3611 PK11_FreeSlot(slot);
3613 pwSpec->master_secret = PK11_DeriveWithFlags(fpms,
3614 master_derive, ¶ms, key_derive,
3615 CKA_DERIVE, 0, keyFlags);
3616 if (pwSpec->master_secret == NULL) {
3617 pwSpec->master_secret = fpms; /* use the fpms as the master. */
3622 PK11_FreeSymKey(fpms);
3625 if (pwSpec->master_secret == NULL) {
3626 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3629 #ifndef NO_PKCS11_BYPASS
3630 if (ss->opt.bypassPKCS11) {
3632 /* In hope of doing a "double bypass",
3633 * need to extract the master secret's value from the key object
3634 * and store it raw in the sslSocket struct.
3636 rv = PK11_ExtractKeyValue(pwSpec->master_secret);
3637 if (rv != SECSuccess) {
3640 /* This returns the address of the secItem inside the key struct,
3641 * not a copy or a reference. So, there's no need to free it.
3643 keydata = PK11_GetKeyData(pwSpec->master_secret);
3644 if (keydata && keydata->len <= sizeof pwSpec->raw_master_secret) {
3645 memcpy(pwSpec->raw_master_secret, keydata->data, keydata->len);
3646 pwSpec->msItem.data = pwSpec->raw_master_secret;
3647 pwSpec->msItem.len = keydata->len;
3649 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
3659 * Derive encryption and MAC Keys (and IVs) from master secret
3660 * Sets a useful error code when returning SECFailure.
3662 * Called only from ssl3_InitPendingCipherSpec(),
3663 * which in turn is called from
3664 * sendRSAClientKeyExchange (for Full handshake)
3665 * sendDHClientKeyExchange (for Full handshake)
3666 * ssl3_HandleClientKeyExchange (for Full handshake)
3667 * ssl3_HandleServerHello (for session restart)
3668 * ssl3_HandleClientHello (for session restart)
3669 * Caller MUST hold the specWriteLock, and SSL3HandshakeLock.
3670 * ssl3_InitPendingCipherSpec does that.
3674 ssl3_DeriveConnectionKeysPKCS11(sslSocket *ss)
3676 ssl3CipherSpec * pwSpec = ss->ssl3.pwSpec;
3677 const ssl3KEADef * kea_def = ss->ssl3.hs.kea_def;
3678 unsigned char * cr = (unsigned char *)&ss->ssl3.hs.client_random;
3679 unsigned char * sr = (unsigned char *)&ss->ssl3.hs.server_random;
3680 PRBool isTLS = (PRBool)(kea_def->tls_keygen ||
3681 (pwSpec->version > SSL_LIBRARY_VERSION_3_0));
3683 (PRBool)(isTLS && pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
3684 /* following variables used in PKCS11 path */
3685 const ssl3BulkCipherDef *cipher_def = pwSpec->cipher_def;
3686 PK11SlotInfo * slot = NULL;
3687 PK11SymKey * symKey = NULL;
3688 void * pwArg = ss->pkcs11PinArg;
3690 CK_SSL3_KEY_MAT_PARAMS key_material_params;
3691 CK_SSL3_KEY_MAT_OUT returnedKeys;
3692 CK_MECHANISM_TYPE key_derive;
3693 CK_MECHANISM_TYPE bulk_mechanism;
3694 SSLCipherAlgorithm calg;
3696 PRBool skipKeysAndIVs = (PRBool)(cipher_def->calg == calg_null);
3698 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3699 PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
3700 PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
3702 if (!pwSpec->master_secret) {
3703 PORT_SetError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3707 * generate the key material
3709 key_material_params.ulMacSizeInBits = pwSpec->mac_size * BPB;
3710 key_material_params.ulKeySizeInBits = cipher_def->secret_key_size* BPB;
3711 key_material_params.ulIVSizeInBits = cipher_def->iv_size * BPB;
3712 if (cipher_def->type == type_block &&
3713 pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
3714 /* Block ciphers in >= TLS 1.1 use a per-record, explicit IV. */
3715 key_material_params.ulIVSizeInBits = 0;
3716 memset(pwSpec->client.write_iv, 0, cipher_def->iv_size);
3717 memset(pwSpec->server.write_iv, 0, cipher_def->iv_size);
3720 key_material_params.bIsExport = (CK_BBOOL)(kea_def->is_limited);
3722 key_material_params.RandomInfo.pClientRandom = cr;
3723 key_material_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH;
3724 key_material_params.RandomInfo.pServerRandom = sr;
3725 key_material_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH;
3726 key_material_params.pReturnedKeyMaterial = &returnedKeys;
3728 returnedKeys.pIVClient = pwSpec->client.write_iv;
3729 returnedKeys.pIVServer = pwSpec->server.write_iv;
3730 keySize = cipher_def->key_size;
3732 if (skipKeysAndIVs) {
3734 key_material_params.ulKeySizeInBits = 0;
3735 key_material_params.ulIVSizeInBits = 0;
3736 returnedKeys.pIVClient = NULL;
3737 returnedKeys.pIVServer = NULL;
3740 calg = cipher_def->calg;
3741 PORT_Assert( alg2Mech[calg].calg == calg);
3742 bulk_mechanism = alg2Mech[calg].cmech;
3744 params.data = (unsigned char *)&key_material_params;
3745 params.len = sizeof(key_material_params);
3748 key_derive = CKM_NSS_TLS_KEY_AND_MAC_DERIVE_SHA256;
3750 key_derive = CKM_TLS_KEY_AND_MAC_DERIVE;
3752 key_derive = CKM_SSL3_KEY_AND_MAC_DERIVE;
3755 /* CKM_SSL3_KEY_AND_MAC_DERIVE is defined to set ENCRYPT, DECRYPT, and
3756 * DERIVE by DEFAULT */
3757 symKey = PK11_Derive(pwSpec->master_secret, key_derive, ¶ms,
3758 bulk_mechanism, CKA_ENCRYPT, keySize);
3760 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3763 /* we really should use the actual mac'ing mechanism here, but we
3764 * don't because these types are used to map keytype anyway and both
3765 * mac's map to the same keytype.
3767 slot = PK11_GetSlotFromKey(symKey);
3769 PK11_FreeSlot(slot); /* slot is held until the key is freed */
3770 pwSpec->client.write_mac_key =
3771 PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive,
3772 CKM_SSL3_SHA1_MAC, returnedKeys.hClientMacSecret, PR_TRUE, pwArg);
3773 if (pwSpec->client.write_mac_key == NULL ) {
3774 goto loser; /* loser sets err */
3776 pwSpec->server.write_mac_key =
3777 PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive,
3778 CKM_SSL3_SHA1_MAC, returnedKeys.hServerMacSecret, PR_TRUE, pwArg);
3779 if (pwSpec->server.write_mac_key == NULL ) {
3780 goto loser; /* loser sets err */
3782 if (!skipKeysAndIVs) {
3783 pwSpec->client.write_key =
3784 PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive,
3785 bulk_mechanism, returnedKeys.hClientKey, PR_TRUE, pwArg);
3786 if (pwSpec->client.write_key == NULL ) {
3787 goto loser; /* loser sets err */
3789 pwSpec->server.write_key =
3790 PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive,
3791 bulk_mechanism, returnedKeys.hServerKey, PR_TRUE, pwArg);
3792 if (pwSpec->server.write_key == NULL ) {
3793 goto loser; /* loser sets err */
3796 PK11_FreeSymKey(symKey);
3801 if (symKey) PK11_FreeSymKey(symKey);
3802 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3806 /* ssl3_InitHandshakeHashes creates handshake hash contexts and hashes in
3807 * buffered messages in ss->ssl3.hs.messages. */
3809 ssl3_InitHandshakeHashes(sslSocket *ss)
3811 SSL_TRC(30,("%d: SSL3[%d]: start handshake hashes", SSL_GETPID(), ss->fd));
3813 PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_unknown);
3814 #ifndef NO_PKCS11_BYPASS
3815 if (ss->opt.bypassPKCS11) {
3816 PORT_Assert(!ss->ssl3.hs.sha_obj && !ss->ssl3.hs.sha_clone);
3817 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
3818 /* If we ever support ciphersuites where the PRF hash isn't SHA-256
3819 * then this will need to be updated. */
3820 ss->ssl3.hs.sha_obj = HASH_GetRawHashObject(HASH_AlgSHA256);
3821 if (!ss->ssl3.hs.sha_obj) {
3822 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
3825 ss->ssl3.hs.sha_clone = (void (*)(void *, void *))SHA256_Clone;
3826 ss->ssl3.hs.hashType = handshake_hash_single;
3827 ss->ssl3.hs.sha_obj->begin(ss->ssl3.hs.sha_cx);
3829 ss->ssl3.hs.hashType = handshake_hash_combo;
3830 MD5_Begin((MD5Context *)ss->ssl3.hs.md5_cx);
3831 SHA1_Begin((SHA1Context *)ss->ssl3.hs.sha_cx);
3836 PORT_Assert(!ss->ssl3.hs.md5 && !ss->ssl3.hs.sha);
3838 * note: We should probably lookup an SSL3 slot for these
3839 * handshake hashes in hopes that we wind up with the same slots
3840 * that the master secret will wind up in ...
3842 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
3843 /* If we ever support ciphersuites where the PRF hash isn't SHA-256
3844 * then this will need to be updated. */
3845 ss->ssl3.hs.sha = PK11_CreateDigestContext(SEC_OID_SHA256);
3846 if (ss->ssl3.hs.sha == NULL) {
3847 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3850 ss->ssl3.hs.hashType = handshake_hash_single;
3852 if (PK11_DigestBegin(ss->ssl3.hs.sha) != SECSuccess) {
3853 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
3857 /* Both ss->ssl3.hs.md5 and ss->ssl3.hs.sha should be NULL or
3858 * created successfully. */
3859 ss->ssl3.hs.md5 = PK11_CreateDigestContext(SEC_OID_MD5);
3860 if (ss->ssl3.hs.md5 == NULL) {
3861 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
3864 ss->ssl3.hs.sha = PK11_CreateDigestContext(SEC_OID_SHA1);
3865 if (ss->ssl3.hs.sha == NULL) {
3866 PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE);
3867 ss->ssl3.hs.md5 = NULL;
3868 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3871 ss->ssl3.hs.hashType = handshake_hash_combo;
3873 if (PK11_DigestBegin(ss->ssl3.hs.md5) != SECSuccess) {
3874 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
3877 if (PK11_DigestBegin(ss->ssl3.hs.sha) != SECSuccess) {
3878 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3884 if (ss->ssl3.hs.messages.len > 0) {
3885 if (ssl3_UpdateHandshakeHashes(ss, ss->ssl3.hs.messages.buf,
3886 ss->ssl3.hs.messages.len) !=
3890 PORT_Free(ss->ssl3.hs.messages.buf);
3891 ss->ssl3.hs.messages.buf = NULL;
3892 ss->ssl3.hs.messages.len = 0;
3893 ss->ssl3.hs.messages.space = 0;
3900 ssl3_RestartHandshakeHashes(sslSocket *ss)
3902 SECStatus rv = SECSuccess;
3904 SSL_TRC(30,("%d: SSL3[%d]: reset handshake hashes",
3905 SSL_GETPID(), ss->fd ));
3906 ss->ssl3.hs.hashType = handshake_hash_unknown;
3907 ss->ssl3.hs.messages.len = 0;
3908 #ifndef NO_PKCS11_BYPASS
3909 ss->ssl3.hs.sha_obj = NULL;
3910 ss->ssl3.hs.sha_clone = NULL;
3912 if (ss->ssl3.hs.md5) {
3913 PK11_DestroyContext(ss->ssl3.hs.md5,PR_TRUE);
3914 ss->ssl3.hs.md5 = NULL;
3916 if (ss->ssl3.hs.sha) {
3917 PK11_DestroyContext(ss->ssl3.hs.sha,PR_TRUE);
3918 ss->ssl3.hs.sha = NULL;
3924 * Handshake messages
3926 /* Called from ssl3_InitHandshakeHashes()
3927 ** ssl3_AppendHandshake()
3928 ** ssl3_StartHandshakeHash()
3929 ** ssl3_HandleV2ClientHello()
3930 ** ssl3_HandleHandshakeMessage()
3931 ** Caller must hold the ssl3Handshake lock.
3934 ssl3_UpdateHandshakeHashes(sslSocket *ss, const unsigned char *b,
3937 SECStatus rv = SECSuccess;
3939 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
3941 /* We need to buffer the handshake messages until we have established
3942 * which handshake hash function to use. */
3943 if (ss->ssl3.hs.hashType == handshake_hash_unknown) {
3944 return sslBuffer_Append(&ss->ssl3.hs.messages, b, l);
3947 PRINT_BUF(90, (NULL, "handshake hash input:", b, l));
3949 #ifndef NO_PKCS11_BYPASS
3950 if (ss->opt.bypassPKCS11) {
3951 if (ss->ssl3.hs.hashType == handshake_hash_single) {
3952 ss->ssl3.hs.sha_obj->update(ss->ssl3.hs.sha_cx, b, l);
3954 MD5_Update((MD5Context *)ss->ssl3.hs.md5_cx, b, l);
3955 SHA1_Update((SHA1Context *)ss->ssl3.hs.sha_cx, b, l);
3960 if (ss->ssl3.hs.hashType == handshake_hash_single) {
3961 rv = PK11_DigestOp(ss->ssl3.hs.sha, b, l);
3962 if (rv != SECSuccess) {
3963 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
3967 rv = PK11_DigestOp(ss->ssl3.hs.md5, b, l);
3968 if (rv != SECSuccess) {
3969 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
3972 rv = PK11_DigestOp(ss->ssl3.hs.sha, b, l);
3973 if (rv != SECSuccess) {
3974 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3981 /**************************************************************************
3982 * Append Handshake functions.
3983 * All these functions set appropriate error codes.
3984 * Most rely on ssl3_AppendHandshake to set the error code.
3985 **************************************************************************/
3987 ssl3_AppendHandshake(sslSocket *ss, const void *void_src, PRInt32 bytes)
3989 unsigned char * src = (unsigned char *)void_src;
3990 int room = ss->sec.ci.sendBuf.space - ss->sec.ci.sendBuf.len;
3993 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); /* protects sendBuf. */
3997 if (ss->sec.ci.sendBuf.space < MAX_SEND_BUF_LENGTH && room < bytes) {
3998 rv = sslBuffer_Grow(&ss->sec.ci.sendBuf, PR_MAX(MIN_SEND_BUF_LENGTH,
3999 PR_MIN(MAX_SEND_BUF_LENGTH, ss->sec.ci.sendBuf.len + bytes)));
4000 if (rv != SECSuccess)
4001 return rv; /* sslBuffer_Grow has set a memory error code. */
4002 room = ss->sec.ci.sendBuf.space - ss->sec.ci.sendBuf.len;
4005 PRINT_BUF(60, (ss, "Append to Handshake", (unsigned char*)void_src, bytes));
4006 rv = ssl3_UpdateHandshakeHashes(ss, src, bytes);
4007 if (rv != SECSuccess)
4008 return rv; /* error code set by ssl3_UpdateHandshakeHashes */
4010 while (bytes > room) {
4012 PORT_Memcpy(ss->sec.ci.sendBuf.buf + ss->sec.ci.sendBuf.len, src,
4014 ss->sec.ci.sendBuf.len += room;
4015 rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
4016 if (rv != SECSuccess) {
4017 return rv; /* error code set by ssl3_FlushHandshake */
4021 room = ss->sec.ci.sendBuf.space;
4022 PORT_Assert(ss->sec.ci.sendBuf.len == 0);
4024 PORT_Memcpy(ss->sec.ci.sendBuf.buf + ss->sec.ci.sendBuf.len, src, bytes);
4025 ss->sec.ci.sendBuf.len += bytes;
4030 ssl3_AppendHandshakeNumber(sslSocket *ss, PRInt32 num, PRInt32 lenSize)
4038 *p++ = (num >> 24) & 0xff;
4040 *p++ = (num >> 16) & 0xff;
4042 *p++ = (num >> 8) & 0xff;
4046 SSL_TRC(60, ("%d: number:", SSL_GETPID()));
4047 rv = ssl3_AppendHandshake(ss, &b[0], lenSize);
4048 return rv; /* error code set by AppendHandshake, if applicable. */
4052 ssl3_AppendHandshakeVariable(
4053 sslSocket *ss, const SSL3Opaque *src, PRInt32 bytes, PRInt32 lenSize)
4057 PORT_Assert((bytes < (1<<8) && lenSize == 1) ||
4058 (bytes < (1L<<16) && lenSize == 2) ||
4059 (bytes < (1L<<24) && lenSize == 3));
4061 SSL_TRC(60,("%d: append variable:", SSL_GETPID()));
4062 rv = ssl3_AppendHandshakeNumber(ss, bytes, lenSize);
4063 if (rv != SECSuccess) {
4064 return rv; /* error code set by AppendHandshake, if applicable. */
4066 SSL_TRC(60, ("data:"));
4067 rv = ssl3_AppendHandshake(ss, src, bytes);
4068 return rv; /* error code set by AppendHandshake, if applicable. */
4072 ssl3_AppendHandshakeHeader(sslSocket *ss, SSL3HandshakeType t, PRUint32 length)
4076 /* If we already have a message in place, we need to enqueue it.
4077 * This empties the buffer. This is a convenient place to call
4078 * dtls_StageHandshakeMessage to mark the message boundary.
4081 rv = dtls_StageHandshakeMessage(ss);
4082 if (rv != SECSuccess) {
4087 SSL_TRC(30,("%d: SSL3[%d]: append handshake header: type %s",
4088 SSL_GETPID(), ss->fd, ssl3_DecodeHandshakeType(t)));
4090 rv = ssl3_AppendHandshakeNumber(ss, t, 1);
4091 if (rv != SECSuccess) {
4092 return rv; /* error code set by AppendHandshake, if applicable. */
4094 rv = ssl3_AppendHandshakeNumber(ss, length, 3);
4095 if (rv != SECSuccess) {
4096 return rv; /* error code set by AppendHandshake, if applicable. */
4100 /* Note that we make an unfragmented message here. We fragment in the
4101 * transmission code, if necessary */
4102 rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.sendMessageSeq, 2);
4103 if (rv != SECSuccess) {
4104 return rv; /* error code set by AppendHandshake, if applicable. */
4106 ss->ssl3.hs.sendMessageSeq++;
4108 /* 0 is the fragment offset, because it's not fragmented yet */
4109 rv = ssl3_AppendHandshakeNumber(ss, 0, 3);
4110 if (rv != SECSuccess) {
4111 return rv; /* error code set by AppendHandshake, if applicable. */
4114 /* Fragment length -- set to the packet length because not fragmented */
4115 rv = ssl3_AppendHandshakeNumber(ss, length, 3);
4116 if (rv != SECSuccess) {
4117 return rv; /* error code set by AppendHandshake, if applicable. */
4121 return rv; /* error code set by AppendHandshake, if applicable. */
4124 /* ssl3_AppendSignatureAndHashAlgorithm appends the serialisation of
4125 * |sigAndHash| to the current handshake message. */
4127 ssl3_AppendSignatureAndHashAlgorithm(
4128 sslSocket *ss, const SSL3SignatureAndHashAlgorithm* sigAndHash)
4130 unsigned char serialized[2];
4132 serialized[0] = ssl3_OIDToTLSHashAlgorithm(sigAndHash->hashAlg);
4133 if (serialized[0] == 0) {
4134 PORT_SetError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
4138 serialized[1] = sigAndHash->sigAlg;
4140 return ssl3_AppendHandshake(ss, serialized, sizeof(serialized));
4143 /**************************************************************************
4144 * Consume Handshake functions.
4146 * All data used in these functions is protected by two locks,
4147 * the RecvBufLock and the SSL3HandshakeLock
4148 **************************************************************************/
4150 /* Read up the next "bytes" number of bytes from the (decrypted) input
4151 * stream "b" (which is *length bytes long). Copy them into buffer "v".
4152 * Reduces *length by bytes. Advances *b by bytes.
4154 * If this function returns SECFailure, it has already sent an alert,
4155 * and has set a generic error code. The caller should probably
4156 * override the generic error code by setting another.
4159 ssl3_ConsumeHandshake(sslSocket *ss, void *v, PRInt32 bytes, SSL3Opaque **b,
4162 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
4163 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
4165 if ((PRUint32)bytes > *length) {
4166 return ssl3_DecodeError(ss);
4168 PORT_Memcpy(v, *b, bytes);
4169 PRINT_BUF(60, (ss, "consume bytes:", *b, bytes));
4175 /* Read up the next "bytes" number of bytes from the (decrypted) input
4176 * stream "b" (which is *length bytes long), and interpret them as an
4177 * integer in network byte order. Returns the received value.
4178 * Reduces *length by bytes. Advances *b by bytes.
4180 * Returns SECFailure (-1) on failure.
4181 * This value is indistinguishable from the equivalent received value.
4182 * Only positive numbers are to be received this way.
4183 * Thus, the largest value that may be sent this way is 0x7fffffff.
4184 * On error, an alert has been sent, and a generic error code has been set.
4187 ssl3_ConsumeHandshakeNumber(sslSocket *ss, PRInt32 bytes, SSL3Opaque **b,
4194 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
4195 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
4196 PORT_Assert( bytes <= sizeof num);
4198 if ((PRUint32)bytes > *length) {
4199 return ssl3_DecodeError(ss);
4201 PRINT_BUF(60, (ss, "consume bytes:", *b, bytes));
4203 for (i = 0; i < bytes; i++)
4204 num = (num << 8) + buf[i];
4210 /* Read in two values from the incoming decrypted byte stream "b", which is
4211 * *length bytes long. The first value is a number whose size is "bytes"
4212 * bytes long. The second value is a byte-string whose size is the value
4213 * of the first number received. The latter byte-string, and its length,
4214 * is returned in the SECItem i.
4216 * Returns SECFailure (-1) on failure.
4217 * On error, an alert has been sent, and a generic error code has been set.
4219 * RADICAL CHANGE for NSS 3.11. All callers of this function make copies
4220 * of the data returned in the SECItem *i, so making a copy of it here
4221 * is simply wasteful. So, This function now just sets SECItem *i to
4222 * point to the values in the buffer **b.
4225 ssl3_ConsumeHandshakeVariable(sslSocket *ss, SECItem *i, PRInt32 bytes,
4226 SSL3Opaque **b, PRUint32 *length)
4230 PORT_Assert(bytes <= 3);
4233 count = ssl3_ConsumeHandshakeNumber(ss, bytes, b, length);
4234 if (count < 0) { /* Can't test for SECSuccess here. */
4238 if ((PRUint32)count > *length) {
4239 return ssl3_DecodeError(ss);
4249 /* tlsHashOIDMap contains the mapping between TLS hash identifiers and the
4250 * SECOidTag used internally by NSS. */
4251 static const struct {
4254 } tlsHashOIDMap[] = {
4255 { tls_hash_md5, SEC_OID_MD5 },
4256 { tls_hash_sha1, SEC_OID_SHA1 },
4257 { tls_hash_sha224, SEC_OID_SHA224 },
4258 { tls_hash_sha256, SEC_OID_SHA256 },
4259 { tls_hash_sha384, SEC_OID_SHA384 },
4260 { tls_hash_sha512, SEC_OID_SHA512 }
4263 /* ssl3_TLSHashAlgorithmToOID converts a TLS hash identifier into an OID value.
4264 * If the hash is not recognised, SEC_OID_UNKNOWN is returned.
4266 * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
4268 ssl3_TLSHashAlgorithmToOID(int hashFunc)
4272 for (i = 0; i < PR_ARRAY_SIZE(tlsHashOIDMap); i++) {
4273 if (hashFunc == tlsHashOIDMap[i].tlsHash) {
4274 return tlsHashOIDMap[i].oid;
4277 return SEC_OID_UNKNOWN;
4280 /* ssl3_OIDToTLSHashAlgorithm converts an OID to a TLS hash algorithm
4281 * identifier. If the hash is not recognised, zero is returned.
4283 * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
4285 ssl3_OIDToTLSHashAlgorithm(SECOidTag oid)
4289 for (i = 0; i < PR_ARRAY_SIZE(tlsHashOIDMap); i++) {
4290 if (oid == tlsHashOIDMap[i].oid) {
4291 return tlsHashOIDMap[i].tlsHash;
4297 /* ssl3_TLSSignatureAlgorithmForKeyType returns the TLS 1.2 signature algorithm
4298 * identifier for a given KeyType. */
4300 ssl3_TLSSignatureAlgorithmForKeyType(KeyType keyType,
4301 TLSSignatureAlgorithm *out)
4311 *out = tls_sig_ecdsa;
4314 PORT_SetError(SEC_ERROR_INVALID_KEY);
4319 /* ssl3_TLSSignatureAlgorithmForCertificate returns the TLS 1.2 signature
4320 * algorithm identifier for the given certificate. */
4322 ssl3_TLSSignatureAlgorithmForCertificate(CERTCertificate *cert,
4323 TLSSignatureAlgorithm *out)
4325 SECKEYPublicKey *key;
4328 key = CERT_ExtractPublicKey(cert);
4330 ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
4334 keyType = key->keyType;
4335 SECKEY_DestroyPublicKey(key);
4336 return ssl3_TLSSignatureAlgorithmForKeyType(keyType, out);
4339 /* ssl3_CheckSignatureAndHashAlgorithmConsistency checks that the signature
4340 * algorithm identifier in |sigAndHash| is consistent with the public key in
4341 * |cert|. If so, SECSuccess is returned. Otherwise, PORT_SetError is called
4342 * and SECFailure is returned. */
4344 ssl3_CheckSignatureAndHashAlgorithmConsistency(
4345 const SSL3SignatureAndHashAlgorithm *sigAndHash, CERTCertificate* cert)
4348 TLSSignatureAlgorithm sigAlg;
4350 rv = ssl3_TLSSignatureAlgorithmForCertificate(cert, &sigAlg);
4351 if (rv != SECSuccess) {
4354 if (sigAlg != sigAndHash->sigAlg) {
4355 PORT_SetError(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM);
4361 /* ssl3_ConsumeSignatureAndHashAlgorithm reads a SignatureAndHashAlgorithm
4362 * structure from |b| and puts the resulting value into |out|. |b| and |length|
4363 * are updated accordingly.
4365 * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
4367 ssl3_ConsumeSignatureAndHashAlgorithm(sslSocket *ss,
4370 SSL3SignatureAndHashAlgorithm *out)
4372 unsigned char bytes[2];
4375 rv = ssl3_ConsumeHandshake(ss, bytes, sizeof(bytes), b, length);
4376 if (rv != SECSuccess) {
4380 out->hashAlg = ssl3_TLSHashAlgorithmToOID(bytes[0]);
4381 if (out->hashAlg == SEC_OID_UNKNOWN) {
4382 PORT_SetError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
4386 out->sigAlg = bytes[1];
4390 /**************************************************************************
4391 * end of Consume Handshake functions.
4392 **************************************************************************/
4394 /* Extract the hashes of handshake messages to this point.
4395 * Called from ssl3_SendCertificateVerify
4397 * ssl3_HandleHandshakeMessage
4399 * Caller must hold the SSL3HandshakeLock.
4400 * Caller must hold a read or write lock on the Spec R/W lock.
4401 * (There is presently no way to assert on a Read lock.)
4404 ssl3_ComputeHandshakeHashes(sslSocket * ss,
4405 ssl3CipherSpec *spec, /* uses ->master_secret */
4406 SSL3Hashes * hashes, /* output goes here. */
4409 SECStatus rv = SECSuccess;
4410 PRBool isTLS = (PRBool)(spec->version > SSL_LIBRARY_VERSION_3_0);
4411 unsigned int outLength;
4412 SSL3Opaque md5_inner[MAX_MAC_LENGTH];
4413 SSL3Opaque sha_inner[MAX_MAC_LENGTH];
4415 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
4416 hashes->hashAlg = SEC_OID_UNKNOWN;
4418 #ifndef NO_PKCS11_BYPASS
4419 if (ss->opt.bypassPKCS11 &&
4420 ss->ssl3.hs.hashType == handshake_hash_single) {
4421 /* compute them without PKCS11 */
4422 PRUint64 sha_cx[MAX_MAC_CONTEXT_LLONGS];
4424 if (!spec->msItem.data) {
4425 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
4429 ss->ssl3.hs.sha_clone(sha_cx, ss->ssl3.hs.sha_cx);
4430 ss->ssl3.hs.sha_obj->end(sha_cx, hashes->u.raw, &hashes->len,
4431 sizeof(hashes->u.raw));
4433 PRINT_BUF(60, (NULL, "SHA-256: result", hashes->u.raw, hashes->len));
4435 /* If we ever support ciphersuites where the PRF hash isn't SHA-256
4436 * then this will need to be updated. */
4437 hashes->hashAlg = SEC_OID_SHA256;
4439 } else if (ss->opt.bypassPKCS11) {
4440 /* compute them without PKCS11 */
4441 PRUint64 md5_cx[MAX_MAC_CONTEXT_LLONGS];
4442 PRUint64 sha_cx[MAX_MAC_CONTEXT_LLONGS];
4444 #define md5cx ((MD5Context *)md5_cx)
4445 #define shacx ((SHA1Context *)sha_cx)
4447 if (!spec->msItem.data) {
4448 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
4452 MD5_Clone (md5cx, (MD5Context *)ss->ssl3.hs.md5_cx);
4453 SHA1_Clone(shacx, (SHA1Context *)ss->ssl3.hs.sha_cx);
4456 /* compute hashes for SSL3. */
4459 s[0] = (unsigned char)(sender >> 24);
4460 s[1] = (unsigned char)(sender >> 16);
4461 s[2] = (unsigned char)(sender >> 8);
4462 s[3] = (unsigned char)sender;
4465 MD5_Update(md5cx, s, 4);
4466 PRINT_BUF(95, (NULL, "MD5 inner: sender", s, 4));
4469 PRINT_BUF(95, (NULL, "MD5 inner: MAC Pad 1", mac_pad_1,
4470 mac_defs[mac_md5].pad_size));
4472 MD5_Update(md5cx, spec->msItem.data, spec->msItem.len);
4473 MD5_Update(md5cx, mac_pad_1, mac_defs[mac_md5].pad_size);
4474 MD5_End(md5cx, md5_inner, &outLength, MD5_LENGTH);
4476 PRINT_BUF(95, (NULL, "MD5 inner: result", md5_inner, outLength));
4479 SHA1_Update(shacx, s, 4);
4480 PRINT_BUF(95, (NULL, "SHA inner: sender", s, 4));
4483 PRINT_BUF(95, (NULL, "SHA inner: MAC Pad 1", mac_pad_1,
4484 mac_defs[mac_sha].pad_size));
4486 SHA1_Update(shacx, spec->msItem.data, spec->msItem.len);
4487 SHA1_Update(shacx, mac_pad_1, mac_defs[mac_sha].pad_size);
4488 SHA1_End(shacx, sha_inner, &outLength, SHA1_LENGTH);
4490 PRINT_BUF(95, (NULL, "SHA inner: result", sha_inner, outLength));
4491 PRINT_BUF(95, (NULL, "MD5 outer: MAC Pad 2", mac_pad_2,
4492 mac_defs[mac_md5].pad_size));
4493 PRINT_BUF(95, (NULL, "MD5 outer: MD5 inner", md5_inner, MD5_LENGTH));
4496 MD5_Update(md5cx, spec->msItem.data, spec->msItem.len);
4497 MD5_Update(md5cx, mac_pad_2, mac_defs[mac_md5].pad_size);
4498 MD5_Update(md5cx, md5_inner, MD5_LENGTH);
4500 MD5_End(md5cx, hashes->u.s.md5, &outLength, MD5_LENGTH);
4502 PRINT_BUF(60, (NULL, "MD5 outer: result", hashes->u.s.md5, MD5_LENGTH));
4505 PRINT_BUF(95, (NULL, "SHA outer: MAC Pad 2", mac_pad_2,
4506 mac_defs[mac_sha].pad_size));
4507 PRINT_BUF(95, (NULL, "SHA outer: SHA inner", sha_inner, SHA1_LENGTH));
4510 SHA1_Update(shacx, spec->msItem.data, spec->msItem.len);
4511 SHA1_Update(shacx, mac_pad_2, mac_defs[mac_sha].pad_size);
4512 SHA1_Update(shacx, sha_inner, SHA1_LENGTH);
4514 SHA1_End(shacx, hashes->u.s.sha, &outLength, SHA1_LENGTH);
4516 PRINT_BUF(60, (NULL, "SHA outer: result", hashes->u.s.sha, SHA1_LENGTH));
4518 hashes->len = MD5_LENGTH + SHA1_LENGTH;
4524 if (ss->ssl3.hs.hashType == handshake_hash_single) {
4525 /* compute hashes with PKCS11 */
4527 unsigned int stateLen;
4528 unsigned char stackBuf[1024];
4529 unsigned char *stateBuf = NULL;
4531 if (!spec->master_secret) {
4532 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
4536 h = ss->ssl3.hs.sha;
4537 stateBuf = PK11_SaveContextAlloc(h, stackBuf,
4538 sizeof(stackBuf), &stateLen);
4539 if (stateBuf == NULL) {
4540 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4543 rv |= PK11_DigestFinal(h, hashes->u.raw, &hashes->len,
4544 sizeof(hashes->u.raw));
4545 if (rv != SECSuccess) {
4546 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4550 /* If we ever support ciphersuites where the PRF hash isn't SHA-256
4551 * then this will need to be updated. */
4552 hashes->hashAlg = SEC_OID_SHA256;
4557 if (PK11_RestoreContext(h, stateBuf, stateLen) != SECSuccess) {
4558 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4561 if (stateBuf != stackBuf) {
4562 PORT_ZFree(stateBuf, stateLen);
4566 /* compute hashes with PKCS11 */
4568 PK11Context * sha = NULL;
4569 unsigned char *md5StateBuf = NULL;
4570 unsigned char *shaStateBuf = NULL;
4571 unsigned int md5StateLen, shaStateLen;
4572 unsigned char md5StackBuf[256];
4573 unsigned char shaStackBuf[512];
4575 if (!spec->master_secret) {
4576 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
4580 md5StateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.md5, md5StackBuf,
4581 sizeof md5StackBuf, &md5StateLen);
4582 if (md5StateBuf == NULL) {
4583 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4586 md5 = ss->ssl3.hs.md5;
4588 shaStateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.sha, shaStackBuf,
4589 sizeof shaStackBuf, &shaStateLen);
4590 if (shaStateBuf == NULL) {
4591 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4594 sha = ss->ssl3.hs.sha;
4597 /* compute hashes for SSL3. */
4600 s[0] = (unsigned char)(sender >> 24);
4601 s[1] = (unsigned char)(sender >> 16);
4602 s[2] = (unsigned char)(sender >> 8);
4603 s[3] = (unsigned char)sender;
4606 rv |= PK11_DigestOp(md5, s, 4);
4607 PRINT_BUF(95, (NULL, "MD5 inner: sender", s, 4));
4610 PRINT_BUF(95, (NULL, "MD5 inner: MAC Pad 1", mac_pad_1,
4611 mac_defs[mac_md5].pad_size));
4613 rv |= PK11_DigestKey(md5,spec->master_secret);
4614 rv |= PK11_DigestOp(md5, mac_pad_1, mac_defs[mac_md5].pad_size);
4615 rv |= PK11_DigestFinal(md5, md5_inner, &outLength, MD5_LENGTH);
4616 PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH);
4617 if (rv != SECSuccess) {
4618 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4623 PRINT_BUF(95, (NULL, "MD5 inner: result", md5_inner, outLength));
4626 rv |= PK11_DigestOp(sha, s, 4);
4627 PRINT_BUF(95, (NULL, "SHA inner: sender", s, 4));
4630 PRINT_BUF(95, (NULL, "SHA inner: MAC Pad 1", mac_pad_1,
4631 mac_defs[mac_sha].pad_size));
4633 rv |= PK11_DigestKey(sha, spec->master_secret);
4634 rv |= PK11_DigestOp(sha, mac_pad_1, mac_defs[mac_sha].pad_size);
4635 rv |= PK11_DigestFinal(sha, sha_inner, &outLength, SHA1_LENGTH);
4636 PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH);
4637 if (rv != SECSuccess) {
4638 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4643 PRINT_BUF(95, (NULL, "SHA inner: result", sha_inner, outLength));
4645 PRINT_BUF(95, (NULL, "MD5 outer: MAC Pad 2", mac_pad_2,
4646 mac_defs[mac_md5].pad_size));
4647 PRINT_BUF(95, (NULL, "MD5 outer: MD5 inner", md5_inner, MD5_LENGTH));
4649 rv |= PK11_DigestBegin(md5);
4650 rv |= PK11_DigestKey(md5, spec->master_secret);
4651 rv |= PK11_DigestOp(md5, mac_pad_2, mac_defs[mac_md5].pad_size);
4652 rv |= PK11_DigestOp(md5, md5_inner, MD5_LENGTH);
4654 rv |= PK11_DigestFinal(md5, hashes->u.s.md5, &outLength, MD5_LENGTH);
4655 PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH);
4656 if (rv != SECSuccess) {
4657 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4662 PRINT_BUF(60, (NULL, "MD5 outer: result", hashes->u.s.md5, MD5_LENGTH));
4665 PRINT_BUF(95, (NULL, "SHA outer: MAC Pad 2", mac_pad_2,
4666 mac_defs[mac_sha].pad_size));
4667 PRINT_BUF(95, (NULL, "SHA outer: SHA inner", sha_inner, SHA1_LENGTH));
4669 rv |= PK11_DigestBegin(sha);
4670 rv |= PK11_DigestKey(sha,spec->master_secret);
4671 rv |= PK11_DigestOp(sha, mac_pad_2, mac_defs[mac_sha].pad_size);
4672 rv |= PK11_DigestOp(sha, sha_inner, SHA1_LENGTH);
4674 rv |= PK11_DigestFinal(sha, hashes->u.s.sha, &outLength, SHA1_LENGTH);
4675 PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH);
4676 if (rv != SECSuccess) {
4677 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4682 PRINT_BUF(60, (NULL, "SHA outer: result", hashes->u.s.sha, SHA1_LENGTH));
4684 hashes->len = MD5_LENGTH + SHA1_LENGTH;
4689 if (PK11_RestoreContext(ss->ssl3.hs.md5, md5StateBuf, md5StateLen)
4692 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4695 if (md5StateBuf != md5StackBuf) {
4696 PORT_ZFree(md5StateBuf, md5StateLen);
4700 if (PK11_RestoreContext(ss->ssl3.hs.sha, shaStateBuf, shaStateLen)
4703 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4706 if (shaStateBuf != shaStackBuf) {
4707 PORT_ZFree(shaStateBuf, shaStateLen);
4715 * SSL 2 based implementations pass in the initial outbound buffer
4716 * so that the handshake hash can contain the included information.
4718 * Called from ssl2_BeginClientHandshake() in sslcon.c
4721 ssl3_StartHandshakeHash(sslSocket *ss, unsigned char * buf, int length)
4725 ssl_GetSSL3HandshakeLock(ss); /**************************************/
4727 rv = ssl3_InitState(ss);
4728 if (rv != SECSuccess) {
4729 goto done; /* ssl3_InitState has set the error code. */
4731 rv = ssl3_RestartHandshakeHashes(ss);
4732 if (rv != SECSuccess) {
4736 PORT_Memset(&ss->ssl3.hs.client_random, 0, SSL3_RANDOM_LENGTH);
4738 &ss->ssl3.hs.client_random.rand[SSL3_RANDOM_LENGTH - SSL_CHALLENGE_BYTES],
4739 &ss->sec.ci.clientChallenge,
4740 SSL_CHALLENGE_BYTES);
4742 rv = ssl3_UpdateHandshakeHashes(ss, buf, length);
4743 /* if it failed, ssl3_UpdateHandshakeHashes has set the error code. */
4746 ssl_ReleaseSSL3HandshakeLock(ss); /**************************************/
4750 /**************************************************************************
4751 * end of Handshake Hash functions.
4752 * Begin Send and Handle functions for handshakes.
4753 **************************************************************************/
4755 /* Called from ssl3_HandleHelloRequest(),
4756 * ssl3_RedoHandshake()
4757 * ssl2_BeginClientHandshake (when resuming ssl3 session)
4758 * dtls_HandleHelloVerifyRequest(with resending=PR_TRUE)
4761 ssl3_SendClientHello(sslSocket *ss, PRBool resending)
4764 ssl3CipherSpec * cwSpec;
4769 int actual_count = 0;
4770 PRBool isTLS = PR_FALSE;
4771 PRBool requestingResume = PR_FALSE;
4772 PRInt32 total_exten_len = 0;
4773 unsigned numCompressionMethods;
4776 SSL_TRC(3, ("%d: SSL3[%d]: send client_hello handshake", SSL_GETPID(),
4779 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
4780 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
4782 rv = ssl3_InitState(ss);
4783 if (rv != SECSuccess) {
4784 return rv; /* ssl3_InitState has set the error code. */
4786 ss->ssl3.hs.sendingSCSV = PR_FALSE; /* Must be reset every handshake */
4787 PORT_Assert(IS_DTLS(ss) || !resending);
4789 /* We might be starting a session renegotiation in which case we should
4790 * clear previous state.
4792 PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData));
4794 rv = ssl3_RestartHandshakeHashes(ss);
4795 if (rv != SECSuccess) {
4800 * During a renegotiation, ss->clientHelloVersion will be used again to
4801 * work around a Windows SChannel bug. Ensure that it is still enabled.
4803 if (ss->firstHsDone) {
4804 if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
4805 PORT_SetError(SSL_ERROR_SSL_DISABLED);
4809 if (ss->clientHelloVersion < ss->vrange.min ||
4810 ss->clientHelloVersion > ss->vrange.max) {
4811 PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
4816 /* We ignore ss->sec.ci.sid here, and use ssl_Lookup because Lookup
4817 * handles expired entries and other details.
4818 * XXX If we've been called from ssl2_BeginClientHandshake, then
4819 * this lookup is duplicative and wasteful.
4821 sid = (ss->opt.noCache) ? NULL
4822 : ssl_LookupSID(&ss->sec.ci.peer, ss->sec.ci.port, ss->peerID, ss->url);
4824 /* We can't resume based on a different token. If the sid exists,
4825 * make sure the token that holds the master secret still exists ...
4826 * If we previously did client-auth, make sure that the token that holds
4827 * the private key still exists, is logged in, hasn't been removed, etc.
4830 PRBool sidOK = PR_TRUE;
4831 if (sid->u.ssl3.keys.msIsWrapped) {
4832 /* Session key was wrapped, which means it was using PKCS11, */
4833 PK11SlotInfo *slot = NULL;
4834 if (sid->u.ssl3.masterValid && !ss->opt.bypassPKCS11) {
4835 slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID,
4836 sid->u.ssl3.masterSlotID);
4841 PK11SymKey *wrapKey = NULL;
4842 if (!PK11_IsPresent(slot) ||
4843 ((wrapKey = PK11_GetWrapKey(slot,
4844 sid->u.ssl3.masterWrapIndex,
4845 sid->u.ssl3.masterWrapMech,
4846 sid->u.ssl3.masterWrapSeries,
4847 ss->pkcs11PinArg)) == NULL) ) {
4850 if (wrapKey) PK11_FreeSymKey(wrapKey);
4851 PK11_FreeSlot(slot);
4855 /* If we previously did client-auth, make sure that the token that
4856 ** holds the private key still exists, is logged in, hasn't been
4859 if (sidOK && !ssl3_ClientAuthTokenPresent(sid)) {
4863 /* TLS 1.0 (RFC 2246) Appendix E says:
4864 * Whenever a client already knows the highest protocol known to
4865 * a server (for example, when resuming a session), it should
4866 * initiate the connection in that native protocol.
4867 * So we pass sid->version to ssl3_NegotiateVersion() here, except
4868 * when renegotiating.
4870 * Windows SChannel compares the client_version inside the RSA
4871 * EncryptedPreMasterSecret of a renegotiation with the
4872 * client_version of the initial ClientHello rather than the
4873 * ClientHello in the renegotiation. To work around this bug, we
4874 * continue to use the client_version used in the initial
4875 * ClientHello when renegotiating.
4878 if (ss->firstHsDone) {
4880 * The client_version of the initial ClientHello is still
4881 * available in ss->clientHelloVersion. Ensure that
4882 * sid->version is bounded within
4883 * [ss->vrange.min, ss->clientHelloVersion], otherwise we
4886 if (sid->version >= ss->vrange.min &&
4887 sid->version <= ss->clientHelloVersion) {
4888 ss->version = ss->clientHelloVersion;
4893 if (ssl3_NegotiateVersion(ss, sid->version,
4894 PR_FALSE) != SECSuccess) {
4901 SSL_AtomicIncrementLong(& ssl3stats.sch_sid_cache_not_ok );
4902 if (ss->sec.uncache)
4903 (*ss->sec.uncache)(sid);
4910 requestingResume = PR_TRUE;
4911 SSL_AtomicIncrementLong(& ssl3stats.sch_sid_cache_hits );
4913 /* Are we attempting a stateless session resume? */
4914 if (sid->version > SSL_LIBRARY_VERSION_3_0 &&
4915 sid->u.ssl3.sessionTicket.ticket.data)
4916 SSL_AtomicIncrementLong(& ssl3stats.sch_sid_stateless_resumes );
4918 PRINT_BUF(4, (ss, "client, found session-id:", sid->u.ssl3.sessionID,
4919 sid->u.ssl3.sessionIDLength));
4921 ss->ssl3.policy = sid->u.ssl3.policy;
4923 SSL_AtomicIncrementLong(& ssl3stats.sch_sid_cache_misses );
4926 * Windows SChannel compares the client_version inside the RSA
4927 * EncryptedPreMasterSecret of a renegotiation with the
4928 * client_version of the initial ClientHello rather than the
4929 * ClientHello in the renegotiation. To work around this bug, we
4930 * continue to use the client_version used in the initial
4931 * ClientHello when renegotiating.
4933 if (ss->firstHsDone) {
4934 ss->version = ss->clientHelloVersion;
4936 rv = ssl3_NegotiateVersion(ss, SSL_LIBRARY_VERSION_MAX_SUPPORTED,
4938 if (rv != SECSuccess)
4939 return rv; /* error code was set */
4942 sid = ssl3_NewSessionID(ss, PR_FALSE);
4944 return SECFailure; /* memory error is set */
4948 isTLS = (ss->version > SSL_LIBRARY_VERSION_3_0);
4949 ssl_GetSpecWriteLock(ss);
4950 cwSpec = ss->ssl3.cwSpec;
4951 if (cwSpec->mac_def->mac == mac_null) {
4952 /* SSL records are not being MACed. */
4953 cwSpec->version = ss->version;
4955 ssl_ReleaseSpecWriteLock(ss);
4957 if (ss->sec.ci.sid != NULL) {
4958 ssl_FreeSID(ss->sec.ci.sid); /* decrement ref count, free if zero */
4960 ss->sec.ci.sid = sid;
4962 ss->sec.send = ssl3_SendApplicationData;
4964 /* shouldn't get here if SSL3 is disabled, but ... */
4965 if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
4966 PR_NOT_REACHED("No versions of SSL 3.0 or later are enabled");
4967 PORT_SetError(SSL_ERROR_SSL_DISABLED);
4971 /* how many suites does our PKCS11 support (regardless of policy)? */
4972 num_suites = ssl3_config_match_init(ss);
4974 return SECFailure; /* ssl3_config_match_init has set error code. */
4976 /* HACK for SCSV in SSL 3.0. On initial handshake, prepend SCSV,
4977 * only if we're willing to complete an SSL 3.0 handshake.
4979 if (!ss->firstHsDone && ss->vrange.min == SSL_LIBRARY_VERSION_3_0) {
4980 /* Must set this before calling Hello Extension Senders,
4981 * to suppress sending of empty RI extension.
4983 ss->ssl3.hs.sendingSCSV = PR_TRUE;
4986 if (isTLS || (ss->firstHsDone && ss->peerRequestedProtection)) {
4987 PRUint32 maxBytes = 65535; /* 2^16 - 1 */
4990 extLen = ssl3_CallHelloExtensionSenders(ss, PR_FALSE, maxBytes, NULL);
4995 total_exten_len += extLen;
4997 if (total_exten_len > 0)
4998 total_exten_len += 2;
5001 #if defined(NSS_ENABLE_ECC)
5002 if (!total_exten_len || !isTLS) {
5003 /* not sending the elliptic_curves and ec_point_formats extensions */
5004 ssl3_DisableECCSuites(ss, NULL); /* disable all ECC suites */
5009 ssl3_DisableNonDTLSSuites(ss);
5012 /* how many suites are permitted by policy and user preference? */
5013 num_suites = count_cipher_suites(ss, ss->ssl3.policy, PR_TRUE);
5015 return SECFailure; /* count_cipher_suites has set error code. */
5016 if (ss->ssl3.hs.sendingSCSV) {
5017 ++num_suites; /* make room for SCSV */
5020 /* count compression methods */
5021 numCompressionMethods = 0;
5022 for (i = 0; i < compressionMethodsCount; i++) {
5023 if (compressionEnabled(ss, compressions[i]))
5024 numCompressionMethods++;
5027 length = sizeof(SSL3ProtocolVersion) + SSL3_RANDOM_LENGTH +
5028 1 + ((sid == NULL) ? 0 : sid->u.ssl3.sessionIDLength) +
5029 2 + num_suites*sizeof(ssl3CipherSuite) +
5030 1 + numCompressionMethods + total_exten_len;
5032 length += 1 + ss->ssl3.hs.cookieLen;
5035 rv = ssl3_AppendHandshakeHeader(ss, client_hello, length);
5036 if (rv != SECSuccess) {
5037 return rv; /* err set by ssl3_AppendHandshake* */
5040 if (ss->firstHsDone) {
5041 /* The client hello version must stay unchanged to work around
5042 * the Windows SChannel bug described above. */
5043 PORT_Assert(ss->version == ss->clientHelloVersion);
5045 ss->clientHelloVersion = ss->version;
5049 version = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion);
5050 rv = ssl3_AppendHandshakeNumber(ss, version, 2);
5052 rv = ssl3_AppendHandshakeNumber(ss, ss->clientHelloVersion, 2);
5054 if (rv != SECSuccess) {
5055 return rv; /* err set by ssl3_AppendHandshake* */
5058 if (!resending) { /* Don't re-generate if we are in DTLS re-sending mode */
5059 rv = ssl3_GetNewRandom(&ss->ssl3.hs.client_random);
5060 if (rv != SECSuccess) {
5061 return rv; /* err set by GetNewRandom. */
5064 rv = ssl3_AppendHandshake(ss, &ss->ssl3.hs.client_random,
5065 SSL3_RANDOM_LENGTH);
5066 if (rv != SECSuccess) {
5067 return rv; /* err set by ssl3_AppendHandshake* */
5071 rv = ssl3_AppendHandshakeVariable(
5072 ss, sid->u.ssl3.sessionID, sid->u.ssl3.sessionIDLength, 1);
5074 rv = ssl3_AppendHandshakeVariable(ss, NULL, 0, 1);
5075 if (rv != SECSuccess) {
5076 return rv; /* err set by ssl3_AppendHandshake* */
5080 rv = ssl3_AppendHandshakeVariable(
5081 ss, ss->ssl3.hs.cookie, ss->ssl3.hs.cookieLen, 1);
5082 if (rv != SECSuccess) {
5083 return rv; /* err set by ssl3_AppendHandshake* */
5087 rv = ssl3_AppendHandshakeNumber(ss, num_suites*sizeof(ssl3CipherSuite), 2);
5088 if (rv != SECSuccess) {
5089 return rv; /* err set by ssl3_AppendHandshake* */
5092 if (ss->ssl3.hs.sendingSCSV) {
5093 /* Add the actual SCSV */
5094 rv = ssl3_AppendHandshakeNumber(ss, TLS_EMPTY_RENEGOTIATION_INFO_SCSV,
5095 sizeof(ssl3CipherSuite));
5096 if (rv != SECSuccess) {
5097 return rv; /* err set by ssl3_AppendHandshake* */
5101 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
5102 ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i];
5103 if (config_match(suite, ss->ssl3.policy, PR_TRUE, &ss->vrange)) {
5105 if (actual_count > num_suites) {
5106 /* set error card removal/insertion error */
5107 PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
5110 rv = ssl3_AppendHandshakeNumber(ss, suite->cipher_suite,
5111 sizeof(ssl3CipherSuite));
5112 if (rv != SECSuccess) {
5113 return rv; /* err set by ssl3_AppendHandshake* */
5118 /* if cards were removed or inserted between count_cipher_suites and
5119 * generating our list, detect the error here rather than send it off to
5121 if (actual_count != num_suites) {
5122 /* Card removal/insertion error */
5123 PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
5127 rv = ssl3_AppendHandshakeNumber(ss, numCompressionMethods, 1);
5128 if (rv != SECSuccess) {
5129 return rv; /* err set by ssl3_AppendHandshake* */
5131 for (i = 0; i < compressionMethodsCount; i++) {
5132 if (!compressionEnabled(ss, compressions[i]))
5134 rv = ssl3_AppendHandshakeNumber(ss, compressions[i], 1);
5135 if (rv != SECSuccess) {
5136 return rv; /* err set by ssl3_AppendHandshake* */
5140 if (total_exten_len) {
5141 PRUint32 maxBytes = total_exten_len - 2;
5144 rv = ssl3_AppendHandshakeNumber(ss, maxBytes, 2);
5145 if (rv != SECSuccess) {
5146 return rv; /* err set by AppendHandshake. */
5149 extLen = ssl3_CallHelloExtensionSenders(ss, PR_TRUE, maxBytes, NULL);
5154 PORT_Assert(!maxBytes);
5156 if (ss->ssl3.hs.sendingSCSV) {
5157 /* Since we sent the SCSV, pretend we sent empty RI extension. */
5158 TLSExtensionData *xtnData = &ss->xtnData;
5159 xtnData->advertised[xtnData->numAdvertised++] =
5160 ssl_renegotiation_info_xtn;
5164 if (!ss->firstHsDone && !requestingResume && !IS_DTLS(ss)) {
5165 flags |= ssl_SEND_FLAG_CAP_RECORD_VERSION;
5167 rv = ssl3_FlushHandshake(ss, flags);
5168 if (rv != SECSuccess) {
5169 return rv; /* error code set by ssl3_FlushHandshake */
5172 ss->ssl3.hs.ws = wait_server_hello;
5177 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
5178 * ssl3 Hello Request.
5179 * Caller must hold Handshake and RecvBuf locks.
5182 ssl3_HandleHelloRequest(sslSocket *ss)
5184 sslSessionID *sid = ss->sec.ci.sid;
5187 SSL_TRC(3, ("%d: SSL3[%d]: handle hello_request handshake",
5188 SSL_GETPID(), ss->fd));
5190 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
5191 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
5193 if (ss->ssl3.hs.ws == wait_server_hello)
5195 if (ss->ssl3.hs.ws != idle_handshake || ss->sec.isServer) {
5196 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
5197 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST);
5200 if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) {
5201 ssl_GetXmitBufLock(ss);
5202 rv = SSL3_SendAlert(ss, alert_warning, no_renegotiation);
5203 ssl_ReleaseXmitBufLock(ss);
5204 PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED);
5209 if (ss->sec.uncache)
5210 ss->sec.uncache(sid);
5212 ss->sec.ci.sid = NULL;
5216 dtls_RehandshakeCleanup(ss);
5219 ssl_GetXmitBufLock(ss);
5220 rv = ssl3_SendClientHello(ss, PR_FALSE);
5221 ssl_ReleaseXmitBufLock(ss);
5226 #define UNKNOWN_WRAP_MECHANISM 0x7fffffff
5228 static const CK_MECHANISM_TYPE wrapMechanismList[SSL_NUM_WRAP_MECHS] = {
5244 UNKNOWN_WRAP_MECHANISM
5248 ssl_FindIndexByWrapMechanism(CK_MECHANISM_TYPE mech)
5250 const CK_MECHANISM_TYPE *pMech = wrapMechanismList;
5252 while (mech != *pMech && *pMech != UNKNOWN_WRAP_MECHANISM) {
5255 return (*pMech == UNKNOWN_WRAP_MECHANISM) ? -1
5256 : (pMech - wrapMechanismList);
5260 ssl_UnwrapSymWrappingKey(
5261 SSLWrappedSymWrappingKey *pWswk,
5262 SECKEYPrivateKey * svrPrivKey,
5263 SSL3KEAType exchKeyType,
5264 CK_MECHANISM_TYPE masterWrapMech,
5267 PK11SymKey * unwrappedWrappingKey = NULL;
5269 #ifdef NSS_ENABLE_ECC
5271 SECKEYPublicKey pubWrapKey;
5272 ECCWrappedKeyInfo *ecWrapped;
5273 #endif /* NSS_ENABLE_ECC */
5275 /* found the wrapping key on disk. */
5276 PORT_Assert(pWswk->symWrapMechanism == masterWrapMech);
5277 PORT_Assert(pWswk->exchKeyType == exchKeyType);
5278 if (pWswk->symWrapMechanism != masterWrapMech ||
5279 pWswk->exchKeyType != exchKeyType) {
5282 wrappedKey.type = siBuffer;
5283 wrappedKey.data = pWswk->wrappedSymmetricWrappingkey;
5284 wrappedKey.len = pWswk->wrappedSymKeyLen;
5285 PORT_Assert(wrappedKey.len <= sizeof pWswk->wrappedSymmetricWrappingkey);
5287 switch (exchKeyType) {
5290 unwrappedWrappingKey =
5291 PK11_PubUnwrapSymKey(svrPrivKey, &wrappedKey,
5292 masterWrapMech, CKA_UNWRAP, 0);
5295 #ifdef NSS_ENABLE_ECC
5298 * For kt_ecdh, we first create an EC public key based on
5299 * data stored with the wrappedSymmetricWrappingkey. Next,
5300 * we do an ECDH computation involving this public key and
5301 * the SSL server's (long-term) EC private key. The resulting
5302 * shared secret is treated the same way as Fortezza's Ks, i.e.,
5303 * it is used to recover the symmetric wrapping key.
5305 * The data in wrappedSymmetricWrappingkey is laid out as defined
5306 * in the ECCWrappedKeyInfo structure.
5308 ecWrapped = (ECCWrappedKeyInfo *) pWswk->wrappedSymmetricWrappingkey;
5310 PORT_Assert(ecWrapped->encodedParamLen + ecWrapped->pubValueLen +
5311 ecWrapped->wrappedKeyLen <= MAX_EC_WRAPPED_KEY_BUFLEN);
5313 if (ecWrapped->encodedParamLen + ecWrapped->pubValueLen +
5314 ecWrapped->wrappedKeyLen > MAX_EC_WRAPPED_KEY_BUFLEN) {
5315 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
5319 pubWrapKey.keyType = ecKey;
5320 pubWrapKey.u.ec.size = ecWrapped->size;
5321 pubWrapKey.u.ec.DEREncodedParams.len = ecWrapped->encodedParamLen;
5322 pubWrapKey.u.ec.DEREncodedParams.data = ecWrapped->var;
5323 pubWrapKey.u.ec.publicValue.len = ecWrapped->pubValueLen;
5324 pubWrapKey.u.ec.publicValue.data = ecWrapped->var +
5325 ecWrapped->encodedParamLen;
5327 wrappedKey.len = ecWrapped->wrappedKeyLen;
5328 wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen +
5329 ecWrapped->pubValueLen;
5331 /* Derive Ks using ECDH */
5332 Ks = PK11_PubDeriveWithKDF(svrPrivKey, &pubWrapKey, PR_FALSE, NULL,
5333 NULL, CKM_ECDH1_DERIVE, masterWrapMech,
5334 CKA_DERIVE, 0, CKD_NULL, NULL, NULL);
5339 /* Use Ks to unwrap the wrapping key */
5340 unwrappedWrappingKey = PK11_UnwrapSymKey(Ks, masterWrapMech, NULL,
5341 &wrappedKey, masterWrapMech,
5343 PK11_FreeSymKey(Ks);
5354 return unwrappedWrappingKey;
5357 /* Each process sharing the server session ID cache has its own array of
5358 * SymKey pointers for the symmetric wrapping keys that are used to wrap
5359 * the master secrets. There is one key for each KEA type. These Symkeys
5360 * correspond to the wrapped SymKeys kept in the server session cache.
5364 PK11SymKey * symWrapKey[kt_kea_size];
5367 static PZLock * symWrapKeysLock = NULL;
5368 static ssl3SymWrapKey symWrapKeys[SSL_NUM_WRAP_MECHS];
5370 SECStatus ssl_FreeSymWrapKeysLock(void)
5372 if (symWrapKeysLock) {
5373 PZ_DestroyLock(symWrapKeysLock);
5374 symWrapKeysLock = NULL;
5377 PORT_SetError(SEC_ERROR_NOT_INITIALIZED);
5382 SSL3_ShutdownServerCache(void)
5386 if (!symWrapKeysLock)
5387 return SECSuccess; /* lock was never initialized */
5388 PZ_Lock(symWrapKeysLock);
5389 /* get rid of all symWrapKeys */
5390 for (i = 0; i < SSL_NUM_WRAP_MECHS; ++i) {
5391 for (j = 0; j < kt_kea_size; ++j) {
5392 PK11SymKey ** pSymWrapKey;
5393 pSymWrapKey = &symWrapKeys[i].symWrapKey[j];
5395 PK11_FreeSymKey(*pSymWrapKey);
5396 *pSymWrapKey = NULL;
5401 PZ_Unlock(symWrapKeysLock);
5402 ssl_FreeSessionCacheLocks();
5406 SECStatus ssl_InitSymWrapKeysLock(void)
5408 symWrapKeysLock = PZ_NewLock(nssILockOther);
5409 return symWrapKeysLock ? SECSuccess : SECFailure;
5412 /* Try to get wrapping key for mechanism from in-memory array.
5413 * If that fails, look for one on disk.
5414 * If that fails, generate a new one, put the new one on disk,
5415 * Put the new key in the in-memory array.
5418 getWrappingKey( sslSocket * ss,
5419 PK11SlotInfo * masterSecretSlot,
5420 SSL3KEAType exchKeyType,
5421 CK_MECHANISM_TYPE masterWrapMech,
5424 SECKEYPrivateKey * svrPrivKey;
5425 SECKEYPublicKey * svrPubKey = NULL;
5426 PK11SymKey * unwrappedWrappingKey = NULL;
5427 PK11SymKey ** pSymWrapKey;
5428 CK_MECHANISM_TYPE asymWrapMechanism = CKM_INVALID_MECHANISM;
5430 int symWrapMechIndex;
5433 SSLWrappedSymWrappingKey wswk;
5434 #ifdef NSS_ENABLE_ECC
5435 PK11SymKey * Ks = NULL;
5436 SECKEYPublicKey *pubWrapKey = NULL;
5437 SECKEYPrivateKey *privWrapKey = NULL;
5438 ECCWrappedKeyInfo *ecWrapped;
5439 #endif /* NSS_ENABLE_ECC */
5441 svrPrivKey = ss->serverCerts[exchKeyType].SERVERKEY;
5442 PORT_Assert(svrPrivKey != NULL);
5444 return NULL; /* why are we here?!? */
5447 symWrapMechIndex = ssl_FindIndexByWrapMechanism(masterWrapMech);
5448 PORT_Assert(symWrapMechIndex >= 0);
5449 if (symWrapMechIndex < 0)
5450 return NULL; /* invalid masterWrapMech. */
5452 pSymWrapKey = &symWrapKeys[symWrapMechIndex].symWrapKey[exchKeyType];
5454 ssl_InitSessionCacheLocks(PR_TRUE);
5456 PZ_Lock(symWrapKeysLock);
5458 unwrappedWrappingKey = *pSymWrapKey;
5459 if (unwrappedWrappingKey != NULL) {
5460 if (PK11_VerifyKeyOK(unwrappedWrappingKey)) {
5461 unwrappedWrappingKey = PK11_ReferenceSymKey(unwrappedWrappingKey);
5464 /* slot series has changed, so this key is no good any more. */
5465 PK11_FreeSymKey(unwrappedWrappingKey);
5466 *pSymWrapKey = unwrappedWrappingKey = NULL;
5469 /* Try to get wrapped SymWrapping key out of the (disk) cache. */
5470 /* Following call fills in wswk on success. */
5471 if (ssl_GetWrappingKey(symWrapMechIndex, exchKeyType, &wswk)) {
5472 /* found the wrapped sym wrapping key on disk. */
5473 unwrappedWrappingKey =
5474 ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, exchKeyType,
5475 masterWrapMech, pwArg);
5476 if (unwrappedWrappingKey) {
5481 if (!masterSecretSlot) /* caller doesn't want to create a new one. */
5484 length = PK11_GetBestKeyLength(masterSecretSlot, masterWrapMech);
5485 /* Zero length means fixed key length algorithm, or error.
5488 unwrappedWrappingKey = PK11_KeyGen(masterSecretSlot, masterWrapMech, NULL,
5490 if (!unwrappedWrappingKey) {
5494 /* Prepare the buffer to receive the wrappedWrappingKey,
5495 * the symmetric wrapping key wrapped using the server's pub key.
5497 PORT_Memset(&wswk, 0, sizeof wswk); /* eliminate UMRs. */
5499 if (ss->serverCerts[exchKeyType].serverKeyPair) {
5500 svrPubKey = ss->serverCerts[exchKeyType].serverKeyPair->pubKey;
5502 if (svrPubKey == NULL) {
5503 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
5506 wrappedKey.type = siBuffer;
5507 wrappedKey.len = SECKEY_PublicKeyStrength(svrPubKey);
5508 wrappedKey.data = wswk.wrappedSymmetricWrappingkey;
5510 PORT_Assert(wrappedKey.len <= sizeof wswk.wrappedSymmetricWrappingkey);
5511 if (wrappedKey.len > sizeof wswk.wrappedSymmetricWrappingkey)
5514 /* wrap symmetric wrapping key in server's public key. */
5515 switch (exchKeyType) {
5517 asymWrapMechanism = CKM_RSA_PKCS;
5518 rv = PK11_PubWrapSymKey(asymWrapMechanism, svrPubKey,
5519 unwrappedWrappingKey, &wrappedKey);
5522 #ifdef NSS_ENABLE_ECC
5525 * We generate an ephemeral EC key pair. Perform an ECDH
5526 * computation involving this ephemeral EC public key and
5527 * the SSL server's (long-term) EC private key. The resulting
5528 * shared secret is treated in the same way as Fortezza's Ks,
5529 * i.e., it is used to wrap the wrapping key. To facilitate
5530 * unwrapping in ssl_UnwrapWrappingKey, we also store all
5531 * relevant info about the ephemeral EC public key in
5532 * wswk.wrappedSymmetricWrappingkey and lay it out as
5533 * described in the ECCWrappedKeyInfo structure.
5535 PORT_Assert(svrPubKey->keyType == ecKey);
5536 if (svrPubKey->keyType != ecKey) {
5537 /* something is wrong in sslsecur.c if this isn't an ecKey */
5538 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
5543 privWrapKey = SECKEY_CreateECPrivateKey(
5544 &svrPubKey->u.ec.DEREncodedParams, &pubWrapKey, NULL);
5545 if ((privWrapKey == NULL) || (pubWrapKey == NULL)) {
5550 /* Set the key size in bits */
5551 if (pubWrapKey->u.ec.size == 0) {
5552 pubWrapKey->u.ec.size = SECKEY_PublicKeyStrengthInBits(svrPubKey);
5555 PORT_Assert(pubWrapKey->u.ec.DEREncodedParams.len +
5556 pubWrapKey->u.ec.publicValue.len < MAX_EC_WRAPPED_KEY_BUFLEN);
5557 if (pubWrapKey->u.ec.DEREncodedParams.len +
5558 pubWrapKey->u.ec.publicValue.len >= MAX_EC_WRAPPED_KEY_BUFLEN) {
5559 PORT_SetError(SEC_ERROR_INVALID_KEY);
5564 /* Derive Ks using ECDH */
5565 Ks = PK11_PubDeriveWithKDF(svrPrivKey, pubWrapKey, PR_FALSE, NULL,
5566 NULL, CKM_ECDH1_DERIVE, masterWrapMech,
5567 CKA_DERIVE, 0, CKD_NULL, NULL, NULL);
5573 ecWrapped = (ECCWrappedKeyInfo *) (wswk.wrappedSymmetricWrappingkey);
5574 ecWrapped->size = pubWrapKey->u.ec.size;
5575 ecWrapped->encodedParamLen = pubWrapKey->u.ec.DEREncodedParams.len;
5576 PORT_Memcpy(ecWrapped->var, pubWrapKey->u.ec.DEREncodedParams.data,
5577 pubWrapKey->u.ec.DEREncodedParams.len);
5579 ecWrapped->pubValueLen = pubWrapKey->u.ec.publicValue.len;
5580 PORT_Memcpy(ecWrapped->var + ecWrapped->encodedParamLen,
5581 pubWrapKey->u.ec.publicValue.data,
5582 pubWrapKey->u.ec.publicValue.len);
5584 wrappedKey.len = MAX_EC_WRAPPED_KEY_BUFLEN -
5585 (ecWrapped->encodedParamLen + ecWrapped->pubValueLen);
5586 wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen +
5587 ecWrapped->pubValueLen;
5589 /* wrap symmetricWrapping key with the local Ks */
5590 rv = PK11_WrapSymKey(masterWrapMech, NULL, Ks,
5591 unwrappedWrappingKey, &wrappedKey);
5593 if (rv != SECSuccess) {
5597 /* Write down the length of wrapped key in the buffer
5598 * wswk.wrappedSymmetricWrappingkey at the appropriate offset
5600 ecWrapped->wrappedKeyLen = wrappedKey.len;
5603 if (privWrapKey) SECKEY_DestroyPrivateKey(privWrapKey);
5604 if (pubWrapKey) SECKEY_DestroyPublicKey(pubWrapKey);
5605 if (Ks) PK11_FreeSymKey(Ks);
5606 asymWrapMechanism = masterWrapMech;
5608 #endif /* NSS_ENABLE_ECC */
5615 if (rv != SECSuccess) {
5616 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
5620 PORT_Assert(asymWrapMechanism != CKM_INVALID_MECHANISM);
5622 wswk.symWrapMechanism = masterWrapMech;
5623 wswk.symWrapMechIndex = symWrapMechIndex;
5624 wswk.asymWrapMechanism = asymWrapMechanism;
5625 wswk.exchKeyType = exchKeyType;
5626 wswk.wrappedSymKeyLen = wrappedKey.len;
5628 /* put it on disk. */
5629 /* If the wrapping key for this KEA type has already been set,
5630 * then abandon the value we just computed and
5631 * use the one we got from the disk.
5633 if (ssl_SetWrappingKey(&wswk)) {
5634 /* somebody beat us to it. The original contents of our wswk
5635 * has been replaced with the content on disk. Now, discard
5636 * the key we just created and unwrap this new one.
5638 PK11_FreeSymKey(unwrappedWrappingKey);
5640 unwrappedWrappingKey =
5641 ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, exchKeyType,
5642 masterWrapMech, pwArg);
5646 if (unwrappedWrappingKey) {
5647 *pSymWrapKey = PK11_ReferenceSymKey(unwrappedWrappingKey);
5652 PZ_Unlock(symWrapKeysLock);
5653 return unwrappedWrappingKey;
5656 /* hexEncode hex encodes |length| bytes from |in| and writes it as |length*2|
5657 * bytes to |out|. */
5659 hexEncode(char *out, const unsigned char *in, unsigned int length)
5661 static const char hextable[] = "0123456789abcdef";
5664 for (i = 0; i < length; i++) {
5665 *(out++) = hextable[in[i] >> 4];
5666 *(out++) = hextable[in[i] & 15];
5670 /* Called from ssl3_SendClientKeyExchange(). */
5671 /* Presently, this always uses PKCS11. There is no bypass for this. */
5673 sendRSAClientKeyExchange(sslSocket * ss, SECKEYPublicKey * svrPubKey)
5675 PK11SymKey * pms = NULL;
5676 SECStatus rv = SECFailure;
5677 SECItem enc_pms = {siBuffer, NULL, 0};
5680 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
5681 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
5683 /* Generate the pre-master secret ... */
5684 ssl_GetSpecWriteLock(ss);
5685 isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
5687 pms = ssl3_GenerateRSAPMS(ss, ss->ssl3.pwSpec, NULL);
5688 ssl_ReleaseSpecWriteLock(ss);
5690 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
5694 /* Get the wrapped (encrypted) pre-master secret, enc_pms */
5695 enc_pms.len = SECKEY_PublicKeyStrength(svrPubKey);
5696 enc_pms.data = (unsigned char*)PORT_Alloc(enc_pms.len);
5697 if (enc_pms.data == NULL) {
5698 goto loser; /* err set by PORT_Alloc */
5701 /* wrap pre-master secret in server's public key. */
5702 rv = PK11_PubWrapSymKey(CKM_RSA_PKCS, svrPubKey, pms, &enc_pms);
5703 if (rv != SECSuccess) {
5704 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
5708 if (ssl_keylog_iob) {
5709 SECStatus extractRV = PK11_ExtractKeyValue(pms);
5710 if (extractRV == SECSuccess) {
5711 SECItem * keyData = PK11_GetKeyData(pms);
5712 if (keyData && keyData->data && keyData->len) {
5714 if (ssl_trace >= 100) {
5715 ssl_PrintBuf(ss, "Pre-Master Secret",
5716 keyData->data, keyData->len);
5719 if (ssl_keylog_iob && enc_pms.len >= 8 && keyData->len == 48) {
5720 /* https://developer.mozilla.org/en/NSS_Key_Log_Format */
5722 /* There could be multiple, concurrent writers to the
5723 * keylog, so we have to do everything in a single call to
5725 char buf[4 + 8*2 + 1 + 48*2 + 1];
5727 strcpy(buf, "RSA ");
5728 hexEncode(buf + 4, enc_pms.data, 8);
5730 hexEncode(buf + 21, keyData->data, 48);
5731 buf[sizeof(buf) - 1] = '\n';
5733 fwrite(buf, sizeof(buf), 1, ssl_keylog_iob);
5734 fflush(ssl_keylog_iob);
5740 rv = ssl3_InitPendingCipherSpec(ss, pms);
5741 PK11_FreeSymKey(pms); pms = NULL;
5743 if (rv != SECSuccess) {
5744 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
5748 rv = ssl3_AppendHandshakeHeader(ss, client_key_exchange,
5749 isTLS ? enc_pms.len + 2 : enc_pms.len);
5750 if (rv != SECSuccess) {
5751 goto loser; /* err set by ssl3_AppendHandshake* */
5754 rv = ssl3_AppendHandshakeVariable(ss, enc_pms.data, enc_pms.len, 2);
5756 rv = ssl3_AppendHandshake(ss, enc_pms.data, enc_pms.len);
5758 if (rv != SECSuccess) {
5759 goto loser; /* err set by ssl3_AppendHandshake* */
5765 if (enc_pms.data != NULL) {
5766 PORT_Free(enc_pms.data);
5769 PK11_FreeSymKey(pms);
5774 /* Called from ssl3_SendClientKeyExchange(). */
5775 /* Presently, this always uses PKCS11. There is no bypass for this. */
5777 sendDHClientKeyExchange(sslSocket * ss, SECKEYPublicKey * svrPubKey)
5779 PK11SymKey * pms = NULL;
5780 SECStatus rv = SECFailure;
5782 CK_MECHANISM_TYPE target;
5784 SECKEYDHParams dhParam; /* DH parameters */
5785 SECKEYPublicKey *pubKey = NULL; /* Ephemeral DH key */
5786 SECKEYPrivateKey *privKey = NULL; /* Ephemeral DH key */
5788 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
5789 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
5791 isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
5793 /* Copy DH parameters from server key */
5795 if (svrPubKey->keyType != dhKey) {
5796 PORT_SetError(SEC_ERROR_BAD_KEY);
5799 dhParam.prime.data = svrPubKey->u.dh.prime.data;
5800 dhParam.prime.len = svrPubKey->u.dh.prime.len;
5801 dhParam.base.data = svrPubKey->u.dh.base.data;
5802 dhParam.base.len = svrPubKey->u.dh.base.len;
5804 /* Generate ephemeral DH keypair */
5805 privKey = SECKEY_CreateDHPrivateKey(&dhParam, &pubKey, NULL);
5806 if (!privKey || !pubKey) {
5807 ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL);
5811 PRINT_BUF(50, (ss, "DH public value:",
5812 pubKey->u.dh.publicValue.data,
5813 pubKey->u.dh.publicValue.len));
5815 if (isTLS) target = CKM_TLS_MASTER_KEY_DERIVE_DH;
5816 else target = CKM_SSL3_MASTER_KEY_DERIVE_DH;
5818 /* Determine the PMS */
5820 pms = PK11_PubDerive(privKey, svrPubKey, PR_FALSE, NULL, NULL,
5821 CKM_DH_PKCS_DERIVE, target, CKA_DERIVE, 0, NULL);
5824 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
5828 SECKEY_DestroyPrivateKey(privKey);
5831 rv = ssl3_InitPendingCipherSpec(ss, pms);
5832 PK11_FreeSymKey(pms); pms = NULL;
5834 if (rv != SECSuccess) {
5835 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
5839 rv = ssl3_AppendHandshakeHeader(ss, client_key_exchange,
5840 pubKey->u.dh.publicValue.len + 2);
5841 if (rv != SECSuccess) {
5842 goto loser; /* err set by ssl3_AppendHandshake* */
5844 rv = ssl3_AppendHandshakeVariable(ss,
5845 pubKey->u.dh.publicValue.data,
5846 pubKey->u.dh.publicValue.len, 2);
5847 SECKEY_DestroyPublicKey(pubKey);
5850 if (rv != SECSuccess) {
5851 goto loser; /* err set by ssl3_AppendHandshake* */
5859 if(pms) PK11_FreeSymKey(pms);
5860 if(privKey) SECKEY_DestroyPrivateKey(privKey);
5861 if(pubKey) SECKEY_DestroyPublicKey(pubKey);
5869 /* Called from ssl3_HandleServerHelloDone(). */
5871 ssl3_SendClientKeyExchange(sslSocket *ss)
5873 SECKEYPublicKey * serverKey = NULL;
5874 SECStatus rv = SECFailure;
5877 SSL_TRC(3, ("%d: SSL3[%d]: send client_key_exchange handshake",
5878 SSL_GETPID(), ss->fd));
5880 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
5881 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
5883 if (ss->sec.peerKey == NULL) {
5884 serverKey = CERT_ExtractPublicKey(ss->sec.peerCert);
5885 if (serverKey == NULL) {
5886 ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
5890 serverKey = ss->sec.peerKey;
5891 ss->sec.peerKey = NULL; /* we're done with it now */
5894 isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
5895 /* enforce limits on kea key sizes. */
5896 if (ss->ssl3.hs.kea_def->is_limited) {
5897 int keyLen = SECKEY_PublicKeyStrength(serverKey); /* bytes */
5899 if (keyLen * BPB > ss->ssl3.hs.kea_def->key_size_limit) {
5901 (void)SSL3_SendAlert(ss, alert_fatal, export_restriction);
5903 (void)ssl3_HandshakeFailure(ss);
5904 PORT_SetError(SSL_ERROR_PUB_KEY_SIZE_LIMIT_EXCEEDED);
5909 ss->sec.keaType = ss->ssl3.hs.kea_def->exchKeyType;
5910 ss->sec.keaKeyBits = SECKEY_PublicKeyStrengthInBits(serverKey);
5912 switch (ss->ssl3.hs.kea_def->exchKeyType) {
5914 rv = sendRSAClientKeyExchange(ss, serverKey);
5918 rv = sendDHClientKeyExchange(ss, serverKey);
5921 #ifdef NSS_ENABLE_ECC
5923 rv = ssl3_SendECDHClientKeyExchange(ss, serverKey);
5925 #endif /* NSS_ENABLE_ECC */
5928 /* got an unknown or unsupported Key Exchange Algorithm. */
5930 PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
5934 SSL_TRC(3, ("%d: SSL3[%d]: DONE sending client_key_exchange",
5935 SSL_GETPID(), ss->fd));
5939 SECKEY_DestroyPublicKey(serverKey);
5940 return rv; /* err code already set. */
5943 /* Called from ssl3_HandleServerHelloDone(). */
5945 ssl3_SendCertificateVerify(sslSocket *ss)
5947 SECStatus rv = SECFailure;
5950 SECItem buf = {siBuffer, NULL, 0};
5954 SSL3SignatureAndHashAlgorithm sigAndHash;
5956 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
5957 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
5959 SSL_TRC(3, ("%d: SSL3[%d]: send certificate_verify handshake",
5960 SSL_GETPID(), ss->fd));
5962 ssl_GetSpecReadLock(ss);
5963 rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.pwSpec, &hashes, 0);
5964 ssl_ReleaseSpecReadLock(ss);
5965 if (rv != SECSuccess) {
5966 goto done; /* err code was set by ssl3_ComputeHandshakeHashes */
5969 isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
5970 isTLS12 = (PRBool)(ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
5971 keyType = ss->ssl3.clientPrivateKey->keyType;
5972 rv = ssl3_SignHashes(&hashes, ss->ssl3.clientPrivateKey, &buf, isTLS);
5973 if (rv == SECSuccess) {
5974 PK11SlotInfo * slot;
5975 sslSessionID * sid = ss->sec.ci.sid;
5977 /* Remember the info about the slot that did the signing.
5978 ** Later, when doing an SSL restart handshake, verify this.
5979 ** These calls are mere accessors, and can't fail.
5981 slot = PK11_GetSlotFromPrivateKey(ss->ssl3.clientPrivateKey);
5982 sid->u.ssl3.clAuthSeries = PK11_GetSlotSeries(slot);
5983 sid->u.ssl3.clAuthSlotID = PK11_GetSlotID(slot);
5984 sid->u.ssl3.clAuthModuleID = PK11_GetModuleID(slot);
5985 sid->u.ssl3.clAuthValid = PR_TRUE;
5986 PK11_FreeSlot(slot);
5988 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
5989 ss->ssl3.clientPrivateKey = NULL;
5990 if (rv != SECSuccess) {
5991 goto done; /* err code was set by ssl3_SignHashes */
5994 len = buf.len + 2 + (isTLS12 ? 2 : 0);
5996 rv = ssl3_AppendHandshakeHeader(ss, certificate_verify, len);
5997 if (rv != SECSuccess) {
5998 goto done; /* error code set by AppendHandshake */
6001 rv = ssl3_TLSSignatureAlgorithmForKeyType(keyType,
6002 &sigAndHash.sigAlg);
6003 if (rv != SECSuccess) {
6006 /* We always sign using the handshake hash function. It's possible that
6007 * a server could support SHA-256 as the handshake hash but not as a
6008 * signature hash. In that case we wouldn't be able to do client
6009 * certificates with it. The alternative is to buffer all handshake
6011 sigAndHash.hashAlg = hashes.hashAlg;
6013 rv = ssl3_AppendSignatureAndHashAlgorithm(ss, &sigAndHash);
6014 if (rv != SECSuccess) {
6015 goto done; /* err set by AppendHandshake. */
6018 rv = ssl3_AppendHandshakeVariable(ss, buf.data, buf.len, 2);
6019 if (rv != SECSuccess) {
6020 goto done; /* error code set by AppendHandshake */
6025 PORT_Free(buf.data);
6029 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
6030 * ssl3 ServerHello message.
6031 * Caller must hold Handshake and RecvBuf locks.
6034 ssl3_HandleServerHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
6036 sslSessionID *sid = ss->sec.ci.sid;
6037 PRInt32 temp; /* allow for consume number failure */
6038 PRBool suite_found = PR_FALSE;
6040 int errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
6042 SECItem sidBytes = {siBuffer, NULL, 0};
6044 PRBool isTLS = PR_FALSE;
6045 SSL3AlertDescription desc = illegal_parameter;
6046 SSL3ProtocolVersion version;
6048 SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello handshake",
6049 SSL_GETPID(), ss->fd));
6050 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
6051 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
6052 PORT_Assert( ss->ssl3.initialized );
6054 if (ss->ssl3.hs.ws != wait_server_hello) {
6055 errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO;
6056 desc = unexpected_message;
6060 /* clean up anything left from previous handshake. */
6061 if (ss->ssl3.clientCertChain != NULL) {
6062 CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
6063 ss->ssl3.clientCertChain = NULL;
6065 if (ss->ssl3.clientCertificate != NULL) {
6066 CERT_DestroyCertificate(ss->ssl3.clientCertificate);
6067 ss->ssl3.clientCertificate = NULL;
6069 if (ss->ssl3.clientPrivateKey != NULL) {
6070 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
6071 ss->ssl3.clientPrivateKey = NULL;
6074 temp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
6076 goto loser; /* alert has been sent */
6078 version = (SSL3ProtocolVersion)temp;
6081 /* RFC 4347 required that you verify that the server versions
6082 * match (Section 4.2.1) in the HelloVerifyRequest and the
6085 * RFC 6347 suggests (SHOULD) that servers always use 1.0
6086 * in HelloVerifyRequest and allows the versions not to match,
6087 * especially when 1.2 is being negotiated.
6089 * Therefore we do not check for matching here.
6091 version = dtls_DTLSVersionToTLSVersion(version);
6092 if (version == 0) { /* Insane version number */
6097 rv = ssl3_NegotiateVersion(ss, version, PR_FALSE);
6098 if (rv != SECSuccess) {
6099 desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version
6100 : handshake_failure;
6101 errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
6104 isTLS = (ss->version > SSL_LIBRARY_VERSION_3_0);
6106 rv = ssl3_InitHandshakeHashes(ss);
6107 if (rv != SECSuccess) {
6108 desc = internal_error;
6109 errCode = PORT_GetError();
6113 rv = ssl3_ConsumeHandshake(
6114 ss, &ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH, &b, &length);
6115 if (rv != SECSuccess) {
6116 goto loser; /* alert has been sent */
6119 rv = ssl3_ConsumeHandshakeVariable(ss, &sidBytes, 1, &b, &length);
6120 if (rv != SECSuccess) {
6121 goto loser; /* alert has been sent */
6123 if (sidBytes.len > SSL3_SESSIONID_BYTES) {
6125 desc = decode_error;
6126 goto alert_loser; /* malformed. */
6129 /* find selected cipher suite in our list. */
6130 temp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
6132 goto loser; /* alert has been sent */
6134 ssl3_config_match_init(ss);
6135 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
6136 ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i];
6137 if (temp == suite->cipher_suite) {
6138 SSLVersionRange vrange = {ss->version, ss->version};
6139 if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange)) {
6140 /* config_match already checks whether the cipher suite is
6141 * acceptable for the version, but the check is repeated here
6142 * in order to give a more precise error code. */
6143 if (!ssl3_CipherSuiteAllowedForVersionRange(temp, &vrange)) {
6144 desc = handshake_failure;
6145 errCode = SSL_ERROR_CIPHER_DISALLOWED_FOR_VERSION;
6149 break; /* failure */
6152 suite_found = PR_TRUE;
6153 break; /* success */
6157 desc = handshake_failure;
6158 errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
6161 ss->ssl3.hs.cipher_suite = (ssl3CipherSuite)temp;
6162 ss->ssl3.hs.suite_def = ssl_LookupCipherSuiteDef((ssl3CipherSuite)temp);
6163 PORT_Assert(ss->ssl3.hs.suite_def);
6164 if (!ss->ssl3.hs.suite_def) {
6165 PORT_SetError(errCode = SEC_ERROR_LIBRARY_FAILURE);
6166 goto loser; /* we don't send alerts for our screw-ups. */
6169 /* find selected compression method in our list. */
6170 temp = ssl3_ConsumeHandshakeNumber(ss, 1, &b, &length);
6172 goto loser; /* alert has been sent */
6174 suite_found = PR_FALSE;
6175 for (i = 0; i < compressionMethodsCount; i++) {
6176 if (temp == compressions[i]) {
6177 if (!compressionEnabled(ss, compressions[i])) {
6178 break; /* failure */
6180 suite_found = PR_TRUE;
6181 break; /* success */
6185 desc = handshake_failure;
6186 errCode = SSL_ERROR_NO_COMPRESSION_OVERLAP;
6189 ss->ssl3.hs.compression = (SSLCompressionMethod)temp;
6191 /* Note that if !isTLS and the extra stuff is not extensions, we
6192 * do NOT goto alert_loser.
6193 * There are some old SSL 3.0 implementations that do send stuff
6194 * after the end of the server hello, and we deliberately ignore
6195 * such stuff in the interest of maximal interoperability (being
6196 * "generous in what you accept").
6197 * Update: Starting in NSS 3.12.6, we handle the renegotiation_info
6198 * extension in SSL 3.0.
6202 rv = ssl3_ConsumeHandshakeVariable(ss, &extensions, 2, &b, &length);
6203 if (rv != SECSuccess || length != 0) {
6207 rv = ssl3_HandleHelloExtensions(ss, &extensions.data,
6209 if (rv != SECSuccess)
6213 if ((ss->opt.requireSafeNegotiation ||
6214 (ss->firstHsDone && (ss->peerRequestedProtection ||
6215 ss->opt.enableRenegotiation == SSL_RENEGOTIATE_REQUIRES_XTN))) &&
6216 !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
6217 desc = handshake_failure;
6218 errCode = ss->firstHsDone ? SSL_ERROR_RENEGOTIATION_NOT_ALLOWED
6219 : SSL_ERROR_UNSAFE_NEGOTIATION;
6223 /* Any errors after this point are not "malformed" errors. */
6224 desc = handshake_failure;
6226 /* we need to call ssl3_SetupPendingCipherSpec here so we can check the
6227 * key exchange algorithm. */
6228 rv = ssl3_SetupPendingCipherSpec(ss);
6229 if (rv != SECSuccess) {
6230 goto alert_loser; /* error code is set. */
6233 /* We may or may not have sent a session id, we may get one back or
6234 * not and if so it may match the one we sent.
6235 * Attempt to restore the master secret to see if this is so...
6236 * Don't consider failure to find a matching SID an error.
6238 sid_match = (PRBool)(sidBytes.len > 0 &&
6239 sidBytes.len == sid->u.ssl3.sessionIDLength &&
6240 !PORT_Memcmp(sid->u.ssl3.sessionID, sidBytes.data, sidBytes.len));
6243 sid->version == ss->version &&
6244 sid->u.ssl3.cipherSuite == ss->ssl3.hs.cipher_suite) do {
6245 ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec;
6247 SECItem wrappedMS; /* wrapped master secret. */
6249 ss->sec.authAlgorithm = sid->authAlgorithm;
6250 ss->sec.authKeyBits = sid->authKeyBits;
6251 ss->sec.keaType = sid->keaType;
6252 ss->sec.keaKeyBits = sid->keaKeyBits;
6255 * a) key is wrapped (implies using PKCS11)
6256 * b) key is unwrapped, but we're still using PKCS11
6257 * c) key is unwrapped, and we're bypassing PKCS11.
6259 if (sid->u.ssl3.keys.msIsWrapped) {
6261 PK11SymKey * wrapKey; /* wrapping key */
6262 CK_FLAGS keyFlags = 0;
6264 #ifndef NO_PKCS11_BYPASS
6265 if (ss->opt.bypassPKCS11) {
6266 /* we cannot restart a non-bypass session in a
6272 /* unwrap master secret with PKCS11 */
6273 slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID,
6274 sid->u.ssl3.masterSlotID);
6276 break; /* not considered an error. */
6278 if (!PK11_IsPresent(slot)) {
6279 PK11_FreeSlot(slot);
6280 break; /* not considered an error. */
6282 wrapKey = PK11_GetWrapKey(slot, sid->u.ssl3.masterWrapIndex,
6283 sid->u.ssl3.masterWrapMech,
6284 sid->u.ssl3.masterWrapSeries,
6286 PK11_FreeSlot(slot);
6287 if (wrapKey == NULL) {
6288 break; /* not considered an error. */
6291 if (ss->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */
6292 keyFlags = CKF_SIGN | CKF_VERIFY;
6295 wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
6296 wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len;
6297 pwSpec->master_secret =
6298 PK11_UnwrapSymKeyWithFlags(wrapKey, sid->u.ssl3.masterWrapMech,
6299 NULL, &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE,
6300 CKA_DERIVE, sizeof(SSL3MasterSecret), keyFlags);
6301 errCode = PORT_GetError();
6302 PK11_FreeSymKey(wrapKey);
6303 if (pwSpec->master_secret == NULL) {
6304 break; /* errorCode set just after call to UnwrapSymKey. */
6306 #ifndef NO_PKCS11_BYPASS
6307 } else if (ss->opt.bypassPKCS11) {
6308 /* MS is not wrapped */
6309 wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
6310 wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len;
6311 memcpy(pwSpec->raw_master_secret, wrappedMS.data, wrappedMS.len);
6312 pwSpec->msItem.data = pwSpec->raw_master_secret;
6313 pwSpec->msItem.len = wrappedMS.len;
6316 /* We CAN restart a bypass session in a non-bypass socket. */
6317 /* need to import the raw master secret to session object */
6318 PK11SlotInfo *slot = PK11_GetInternalSlot();
6319 wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
6320 wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len;
6321 pwSpec->master_secret =
6322 PK11_ImportSymKey(slot, CKM_SSL3_MASTER_KEY_DERIVE,
6323 PK11_OriginUnwrap, CKA_ENCRYPT,
6325 PK11_FreeSlot(slot);
6326 if (pwSpec->master_secret == NULL) {
6332 SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_cache_hits );
6334 /* If we sent a session ticket, then this is a stateless resume. */
6335 if (sid->version > SSL_LIBRARY_VERSION_3_0 &&
6336 sid->u.ssl3.sessionTicket.ticket.data != NULL)
6337 SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_stateless_resumes );
6339 if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn))
6340 ss->ssl3.hs.ws = wait_new_session_ticket;
6342 ss->ssl3.hs.ws = wait_change_cipher;
6344 ss->ssl3.hs.isResuming = PR_TRUE;
6346 /* copy the peer cert from the SID */
6347 if (sid->peerCert != NULL) {
6348 ss->sec.peerCert = CERT_DupCertificate(sid->peerCert);
6351 /* NULL value for PMS signifies re-use of the old MS */
6352 rv = ssl3_InitPendingCipherSpec(ss, NULL);
6353 if (rv != SECSuccess) {
6354 goto alert_loser; /* err code was set */
6360 SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_cache_not_ok );
6362 SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_cache_misses );
6364 /* throw the old one away */
6365 sid->u.ssl3.keys.resumable = PR_FALSE;
6366 if (ss->sec.uncache)
6367 (*ss->sec.uncache)(sid);
6371 ss->sec.ci.sid = sid = ssl3_NewSessionID(ss, PR_FALSE);
6373 goto alert_loser; /* memory error is set. */
6376 sid->version = ss->version;
6377 sid->u.ssl3.sessionIDLength = sidBytes.len;
6378 PORT_Memcpy(sid->u.ssl3.sessionID, sidBytes.data, sidBytes.len);
6380 ss->ssl3.hs.isResuming = PR_FALSE;
6381 ss->ssl3.hs.ws = wait_server_cert;
6385 (void)SSL3_SendAlert(ss, alert_fatal, desc);
6388 errCode = ssl_MapLowLevelError(errCode);
6392 /* ssl3_BigIntGreaterThanOne returns true iff |mpint|, taken as an unsigned,
6393 * big-endian integer is > 1 */
6395 ssl3_BigIntGreaterThanOne(const SECItem* mpint) {
6396 unsigned char firstNonZeroByte = 0;
6399 for (i = 0; i < mpint->len; i++) {
6400 if (mpint->data[i]) {
6401 firstNonZeroByte = mpint->data[i];
6406 if (firstNonZeroByte == 0)
6408 if (firstNonZeroByte > 1)
6411 /* firstNonZeroByte == 1, therefore mpint > 1 iff the first non-zero byte
6412 * is followed by another byte. */
6413 return (i < mpint->len - 1);
6416 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
6417 * ssl3 ServerKeyExchange message.
6418 * Caller must hold Handshake and RecvBuf locks.
6421 ssl3_HandleServerKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
6423 PLArenaPool * arena = NULL;
6424 SECKEYPublicKey *peerKey = NULL;
6425 PRBool isTLS, isTLS12;
6427 int errCode = SSL_ERROR_RX_MALFORMED_SERVER_KEY_EXCH;
6428 SSL3AlertDescription desc = illegal_parameter;
6430 SECItem signature = {siBuffer, NULL, 0};
6431 SSL3SignatureAndHashAlgorithm sigAndHash;
6433 sigAndHash.hashAlg = SEC_OID_UNKNOWN;
6435 SSL_TRC(3, ("%d: SSL3[%d]: handle server_key_exchange handshake",
6436 SSL_GETPID(), ss->fd));
6437 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
6438 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
6440 if (ss->ssl3.hs.ws != wait_server_key &&
6441 ss->ssl3.hs.ws != wait_server_cert) {
6442 errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH;
6443 desc = unexpected_message;
6446 if (ss->sec.peerCert == NULL) {
6447 errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH;
6448 desc = unexpected_message;
6452 isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
6453 isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
6455 switch (ss->ssl3.hs.kea_def->exchKeyType) {
6458 SECItem modulus = {siBuffer, NULL, 0};
6459 SECItem exponent = {siBuffer, NULL, 0};
6461 rv = ssl3_ConsumeHandshakeVariable(ss, &modulus, 2, &b, &length);
6462 if (rv != SECSuccess) {
6463 goto loser; /* malformed. */
6465 rv = ssl3_ConsumeHandshakeVariable(ss, &exponent, 2, &b, &length);
6466 if (rv != SECSuccess) {
6467 goto loser; /* malformed. */
6470 rv = ssl3_ConsumeSignatureAndHashAlgorithm(ss, &b, &length,
6472 if (rv != SECSuccess) {
6473 goto loser; /* malformed or unsupported. */
6475 rv = ssl3_CheckSignatureAndHashAlgorithmConsistency(
6476 &sigAndHash, ss->sec.peerCert);
6477 if (rv != SECSuccess) {
6481 rv = ssl3_ConsumeHandshakeVariable(ss, &signature, 2, &b, &length);
6482 if (rv != SECSuccess) {
6483 goto loser; /* malformed. */
6487 desc = decode_error;
6488 goto alert_loser; /* malformed. */
6491 /* failures after this point are not malformed handshakes. */
6492 /* TLS: send decrypt_error if signature failed. */
6493 desc = isTLS ? decrypt_error : handshake_failure;
6496 * check to make sure the hash is signed by right guy
6498 rv = ssl3_ComputeExportRSAKeyHash(sigAndHash.hashAlg, modulus, exponent,
6499 &ss->ssl3.hs.client_random,
6500 &ss->ssl3.hs.server_random,
6501 &hashes, ss->opt.bypassPKCS11);
6502 if (rv != SECSuccess) {
6504 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
6507 rv = ssl3_VerifySignedHashes(&hashes, ss->sec.peerCert, &signature,
6508 isTLS, ss->pkcs11PinArg);
6509 if (rv != SECSuccess) {
6511 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
6516 * we really need to build a new key here because we can no longer
6517 * ignore calling SECKEY_DestroyPublicKey. Using the key may allocate
6518 * pkcs11 slots and ID's.
6520 arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
6521 if (arena == NULL) {
6525 peerKey = PORT_ArenaZNew(arena, SECKEYPublicKey);
6526 if (peerKey == NULL) {
6527 PORT_FreeArena(arena, PR_FALSE);
6531 peerKey->arena = arena;
6532 peerKey->keyType = rsaKey;
6533 peerKey->pkcs11Slot = NULL;
6534 peerKey->pkcs11ID = CK_INVALID_HANDLE;
6535 if (SECITEM_CopyItem(arena, &peerKey->u.rsa.modulus, &modulus) ||
6536 SECITEM_CopyItem(arena, &peerKey->u.rsa.publicExponent, &exponent))
6538 PORT_FreeArena(arena, PR_FALSE);
6541 ss->sec.peerKey = peerKey;
6542 ss->ssl3.hs.ws = wait_cert_request;
6547 SECItem dh_p = {siBuffer, NULL, 0};
6548 SECItem dh_g = {siBuffer, NULL, 0};
6549 SECItem dh_Ys = {siBuffer, NULL, 0};
6551 rv = ssl3_ConsumeHandshakeVariable(ss, &dh_p, 2, &b, &length);
6552 if (rv != SECSuccess) {
6553 goto loser; /* malformed. */
6555 if (dh_p.len < 512/8) {
6556 errCode = SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY;
6559 rv = ssl3_ConsumeHandshakeVariable(ss, &dh_g, 2, &b, &length);
6560 if (rv != SECSuccess) {
6561 goto loser; /* malformed. */
6563 if (dh_g.len > dh_p.len || !ssl3_BigIntGreaterThanOne(&dh_g))
6565 rv = ssl3_ConsumeHandshakeVariable(ss, &dh_Ys, 2, &b, &length);
6566 if (rv != SECSuccess) {
6567 goto loser; /* malformed. */
6569 if (dh_Ys.len > dh_p.len || !ssl3_BigIntGreaterThanOne(&dh_Ys))
6572 rv = ssl3_ConsumeSignatureAndHashAlgorithm(ss, &b, &length,
6574 if (rv != SECSuccess) {
6575 goto loser; /* malformed or unsupported. */
6577 rv = ssl3_CheckSignatureAndHashAlgorithmConsistency(
6578 &sigAndHash, ss->sec.peerCert);
6579 if (rv != SECSuccess) {
6583 rv = ssl3_ConsumeHandshakeVariable(ss, &signature, 2, &b, &length);
6584 if (rv != SECSuccess) {
6585 goto loser; /* malformed. */
6589 desc = decode_error;
6590 goto alert_loser; /* malformed. */
6593 PRINT_BUF(60, (NULL, "Server DH p", dh_p.data, dh_p.len));
6594 PRINT_BUF(60, (NULL, "Server DH g", dh_g.data, dh_g.len));
6595 PRINT_BUF(60, (NULL, "Server DH Ys", dh_Ys.data, dh_Ys.len));
6597 /* failures after this point are not malformed handshakes. */
6598 /* TLS: send decrypt_error if signature failed. */
6599 desc = isTLS ? decrypt_error : handshake_failure;
6602 * check to make sure the hash is signed by right guy
6604 rv = ssl3_ComputeDHKeyHash(sigAndHash.hashAlg, dh_p, dh_g, dh_Ys,
6605 &ss->ssl3.hs.client_random,
6606 &ss->ssl3.hs.server_random,
6607 &hashes, ss->opt.bypassPKCS11);
6608 if (rv != SECSuccess) {
6610 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
6613 rv = ssl3_VerifySignedHashes(&hashes, ss->sec.peerCert, &signature,
6614 isTLS, ss->pkcs11PinArg);
6615 if (rv != SECSuccess) {
6617 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
6622 * we really need to build a new key here because we can no longer
6623 * ignore calling SECKEY_DestroyPublicKey. Using the key may allocate
6624 * pkcs11 slots and ID's.
6626 arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
6627 if (arena == NULL) {
6631 ss->sec.peerKey = peerKey = PORT_ArenaZNew(arena, SECKEYPublicKey);
6632 if (peerKey == NULL) {
6636 peerKey->arena = arena;
6637 peerKey->keyType = dhKey;
6638 peerKey->pkcs11Slot = NULL;
6639 peerKey->pkcs11ID = CK_INVALID_HANDLE;
6641 if (SECITEM_CopyItem(arena, &peerKey->u.dh.prime, &dh_p) ||
6642 SECITEM_CopyItem(arena, &peerKey->u.dh.base, &dh_g) ||
6643 SECITEM_CopyItem(arena, &peerKey->u.dh.publicValue, &dh_Ys))
6645 PORT_FreeArena(arena, PR_FALSE);
6648 ss->sec.peerKey = peerKey;
6649 ss->ssl3.hs.ws = wait_cert_request;
6653 #ifdef NSS_ENABLE_ECC
6655 rv = ssl3_HandleECDHServerKeyExchange(ss, b, length);
6657 #endif /* NSS_ENABLE_ECC */
6660 desc = handshake_failure;
6661 errCode = SEC_ERROR_UNSUPPORTED_KEYALG;
6662 break; /* goto alert_loser; */
6666 (void)SSL3_SendAlert(ss, alert_fatal, desc);
6668 PORT_SetError( errCode );
6671 no_memory: /* no-memory error has already been set. */
6672 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
6677 typedef struct dnameNode {
6678 struct dnameNode *next;
6682 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
6683 * ssl3 Certificate Request message.
6684 * Caller must hold Handshake and RecvBuf locks.
6687 ssl3_HandleCertificateRequest(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
6689 PLArenaPool * arena = NULL;
6692 PRBool isTLS = PR_FALSE;
6693 PRBool isTLS12 = PR_FALSE;
6695 int errCode = SSL_ERROR_RX_MALFORMED_CERT_REQUEST;
6698 SSL3AlertDescription desc = illegal_parameter;
6699 SECItem cert_types = {siBuffer, NULL, 0};
6700 SECItem algorithms = {siBuffer, NULL, 0};
6701 CERTDistNames ca_list;
6703 SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_request handshake",
6704 SSL_GETPID(), ss->fd));
6705 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
6706 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
6708 if (ss->ssl3.hs.ws != wait_cert_request &&
6709 ss->ssl3.hs.ws != wait_server_key) {
6710 desc = unexpected_message;
6711 errCode = SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST;
6715 PORT_Assert(ss->ssl3.clientCertChain == NULL);
6716 PORT_Assert(ss->ssl3.clientCertificate == NULL);
6717 PORT_Assert(ss->ssl3.clientPrivateKey == NULL);
6719 isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
6720 isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
6721 rv = ssl3_ConsumeHandshakeVariable(ss, &cert_types, 1, &b, &length);
6722 if (rv != SECSuccess)
6723 goto loser; /* malformed, alert has been sent */
6726 rv = ssl3_ConsumeHandshakeVariable(ss, &algorithms, 2, &b, &length);
6727 if (rv != SECSuccess)
6728 goto loser; /* malformed, alert has been sent */
6729 /* An empty or odd-length value is invalid.
6730 * SignatureAndHashAlgorithm
6731 * supported_signature_algorithms<2..2^16-2>;
6733 if (algorithms.len == 0 || (algorithms.len & 1) != 0)
6737 arena = ca_list.arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
6741 remaining = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
6743 goto loser; /* malformed, alert has been sent */
6745 if ((PRUint32)remaining > length)
6748 ca_list.head = node = PORT_ArenaZNew(arena, dnameNode);
6752 while (remaining > 0) {
6756 goto alert_loser; /* malformed */
6758 node->name.len = len = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
6760 goto loser; /* malformed, alert has been sent */
6763 if (remaining < len)
6764 goto alert_loser; /* malformed */
6766 node->name.data = b;
6772 break; /* success */
6774 node->next = PORT_ArenaZNew(arena, dnameNode);
6780 ca_list.nnames = nnames;
6781 ca_list.names = PORT_ArenaNewArray(arena, SECItem, nnames);
6782 if (nnames > 0 && ca_list.names == NULL)
6785 for(i = 0, node = (dnameNode*)ca_list.head;
6787 i++, node = node->next) {
6788 ca_list.names[i] = node->name;
6792 goto alert_loser; /* malformed */
6794 desc = no_certificate;
6795 ss->ssl3.hs.ws = wait_hello_done;
6797 if (ss->getClientAuthData != NULL) {
6798 /* XXX Should pass cert_types and algorithms in this call!! */
6799 rv = (SECStatus)(*ss->getClientAuthData)(ss->getClientAuthDataArg,
6801 &ss->ssl3.clientCertificate,
6802 &ss->ssl3.clientPrivateKey);
6804 rv = SECFailure; /* force it to send a no_certificate alert */
6807 case SECWouldBlock: /* getClientAuthData has put up a dialog box. */
6808 ssl3_SetAlwaysBlock(ss);
6809 break; /* not an error */
6812 /* check what the callback function returned */
6813 if ((!ss->ssl3.clientCertificate) || (!ss->ssl3.clientPrivateKey)) {
6814 /* we are missing either the key or cert */
6815 if (ss->ssl3.clientCertificate) {
6816 /* got a cert, but no key - free it */
6817 CERT_DestroyCertificate(ss->ssl3.clientCertificate);
6818 ss->ssl3.clientCertificate = NULL;
6820 if (ss->ssl3.clientPrivateKey) {
6821 /* got a key, but no cert - free it */
6822 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
6823 ss->ssl3.clientPrivateKey = NULL;
6825 goto send_no_certificate;
6827 /* Setting ssl3.clientCertChain non-NULL will cause
6828 * ssl3_HandleServerHelloDone to call SendCertificate.
6830 ss->ssl3.clientCertChain = CERT_CertChainFromCert(
6831 ss->ssl3.clientCertificate,
6832 certUsageSSLClient, PR_FALSE);
6833 if (ss->ssl3.clientCertChain == NULL) {
6834 if (ss->ssl3.clientCertificate != NULL) {
6835 CERT_DestroyCertificate(ss->ssl3.clientCertificate);
6836 ss->ssl3.clientCertificate = NULL;
6838 if (ss->ssl3.clientPrivateKey != NULL) {
6839 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
6840 ss->ssl3.clientPrivateKey = NULL;
6842 goto send_no_certificate;
6844 break; /* not an error */
6848 send_no_certificate:
6850 ss->ssl3.sendEmptyCert = PR_TRUE;
6852 (void)SSL3_SendAlert(ss, alert_warning, no_certificate);
6861 PORT_SetError(SEC_ERROR_NO_MEMORY);
6865 if (isTLS && desc == illegal_parameter)
6866 desc = decode_error;
6867 (void)SSL3_SendAlert(ss, alert_fatal, desc);
6869 PORT_SetError(errCode);
6873 PORT_FreeArena(arena, PR_FALSE);
6878 ssl3_CanFalseStart(sslSocket *ss) {
6881 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
6883 /* XXX: does not take into account whether we are waiting for
6884 * SSL_AuthCertificateComplete or SSL_RestartHandshakeAfterCertReq. If/when
6885 * that is done, this function could return different results each time it
6889 ssl_GetSpecReadLock(ss);
6890 rv = ss->opt.enableFalseStart &&
6891 !ss->sec.isServer &&
6892 !ss->ssl3.hs.isResuming &&
6895 /* An attacker can control the selected ciphersuite so we only wish to
6896 * do False Start in the case that the selected ciphersuite is
6897 * sufficiently strong that the attack can gain no advantage.
6898 * Therefore we require an 80-bit cipher and a forward-secret key
6900 ss->ssl3.cwSpec->cipher_def->secret_key_size >= 10 &&
6901 (ss->ssl3.hs.kea_def->kea == kea_dhe_dss ||
6902 ss->ssl3.hs.kea_def->kea == kea_dhe_rsa ||
6903 ss->ssl3.hs.kea_def->kea == kea_ecdhe_ecdsa ||
6904 ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa);
6905 ssl_ReleaseSpecReadLock(ss);
6909 static SECStatus ssl3_SendClientSecondRound(sslSocket *ss);
6911 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
6912 * ssl3 Server Hello Done message.
6913 * Caller must hold Handshake and RecvBuf locks.
6916 ssl3_HandleServerHelloDone(sslSocket *ss)
6919 SSL3WaitState ws = ss->ssl3.hs.ws;
6921 SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello_done handshake",
6922 SSL_GETPID(), ss->fd));
6923 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
6924 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
6926 if (ws != wait_hello_done &&
6927 ws != wait_server_cert &&
6928 ws != wait_server_key &&
6929 ws != wait_cert_request) {
6930 SSL3_SendAlert(ss, alert_fatal, unexpected_message);
6931 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE);
6935 rv = ssl3_SendClientSecondRound(ss);
6940 /* Called from ssl3_HandleServerHelloDone and ssl3_AuthCertificateComplete.
6942 * Caller must hold Handshake and RecvBuf locks.
6945 ssl3_SendClientSecondRound(sslSocket *ss)
6948 PRBool sendClientCert;
6950 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
6951 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
6953 sendClientCert = !ss->ssl3.sendEmptyCert &&
6954 ss->ssl3.clientCertChain != NULL &&
6955 ss->ssl3.clientPrivateKey != NULL;
6957 /* We must wait for the server's certificate to be authenticated before
6958 * sending the client certificate in order to disclosing the client
6959 * certificate to an attacker that does not have a valid cert for the
6960 * domain we are connecting to.
6962 * XXX: We should do the same for the NPN extension, but for that we
6963 * need an option to give the application the ability to leak the NPN
6964 * information to get better performance.
6966 * During the initial handshake on a connection, we never send/receive
6967 * application data until we have authenticated the server's certificate;
6968 * i.e. we have fully authenticated the handshake before using the cipher
6969 * specs agreed upon for that handshake. During a renegotiation, we may
6970 * continue sending and receiving application data during the handshake
6971 * interleaved with the handshake records. If we were to send the client's
6972 * second round for a renegotiation before the server's certificate was
6973 * authenticated, then the application data sent/received after this point
6974 * would be using cipher spec that hadn't been authenticated. By waiting
6975 * until the server's certificate has been authenticated during
6976 * renegotiations, we ensure that renegotiations have the same property
6977 * as initial handshakes; i.e. we have fully authenticated the handshake
6978 * before using the cipher specs agreed upon for that handshake for
6981 if (ss->ssl3.hs.restartTarget) {
6982 PR_NOT_REACHED("unexpected ss->ssl3.hs.restartTarget");
6983 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
6986 if (ss->ssl3.hs.authCertificatePending &&
6987 (sendClientCert || ss->ssl3.sendEmptyCert || ss->firstHsDone)) {
6988 ss->ssl3.hs.restartTarget = ssl3_SendClientSecondRound;
6989 return SECWouldBlock;
6992 ssl_GetXmitBufLock(ss); /*******************************/
6994 if (ss->ssl3.sendEmptyCert) {
6995 ss->ssl3.sendEmptyCert = PR_FALSE;
6996 rv = ssl3_SendEmptyCertificate(ss);
6997 /* Don't send verify */
6998 if (rv != SECSuccess) {
6999 goto loser; /* error code is set. */
7001 } else if (sendClientCert) {
7002 rv = ssl3_SendCertificate(ss);
7003 if (rv != SECSuccess) {
7004 goto loser; /* error code is set. */
7008 rv = ssl3_SendClientKeyExchange(ss);
7009 if (rv != SECSuccess) {
7010 goto loser; /* err is set. */
7013 if (sendClientCert) {
7014 rv = ssl3_SendCertificateVerify(ss);
7015 if (rv != SECSuccess) {
7016 goto loser; /* err is set. */
7020 rv = ssl3_SendChangeCipherSpecs(ss);
7021 if (rv != SECSuccess) {
7022 goto loser; /* err code was set. */
7025 /* XXX: If the server's certificate hasn't been authenticated by this
7026 * point, then we may be leaking this NPN message to an attacker.
7028 if (!ss->firstHsDone) {
7029 rv = ssl3_SendNextProto(ss);
7030 if (rv != SECSuccess) {
7031 goto loser; /* err code was set. */
7035 rv = ssl3_SendFinished(ss, 0);
7036 if (rv != SECSuccess) {
7037 goto loser; /* err code was set. */
7040 ssl_ReleaseXmitBufLock(ss); /*******************************/
7042 if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn))
7043 ss->ssl3.hs.ws = wait_new_session_ticket;
7045 ss->ssl3.hs.ws = wait_change_cipher;
7047 /* Do the handshake callback for sslv3 here, if we can false start. */
7048 if (ss->handshakeCallback != NULL && ssl3_CanFalseStart(ss)) {
7049 (ss->handshakeCallback)(ss->fd, ss->handshakeCallbackData);
7055 ssl_ReleaseXmitBufLock(ss);
7060 * Routines used by servers
7063 ssl3_SendHelloRequest(sslSocket *ss)
7067 SSL_TRC(3, ("%d: SSL3[%d]: send hello_request handshake", SSL_GETPID(),
7070 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
7071 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
7073 rv = ssl3_AppendHandshakeHeader(ss, hello_request, 0);
7074 if (rv != SECSuccess) {
7075 return rv; /* err set by AppendHandshake */
7077 rv = ssl3_FlushHandshake(ss, 0);
7078 if (rv != SECSuccess) {
7079 return rv; /* error code set by ssl3_FlushHandshake */
7081 ss->ssl3.hs.ws = wait_client_hello;
7087 * ssl3_HandleClientHello()
7089 static SECComparison
7090 ssl3_ServerNameCompare(const SECItem *name1, const SECItem *name2)
7092 if (!name1 != !name2) {
7098 if (name1->type != name2->type) {
7101 return SECITEM_CompareItem(name1, name2);
7104 /* Sets memory error when returning NULL.
7106 * ssl3_SendClientHello()
7107 * ssl3_HandleServerHello()
7108 * ssl3_HandleClientHello()
7109 * ssl3_HandleV2ClientHello()
7112 ssl3_NewSessionID(sslSocket *ss, PRBool is_server)
7116 sid = PORT_ZNew(sslSessionID);
7121 const SECItem * srvName;
7122 SECStatus rv = SECSuccess;
7124 ssl_GetSpecReadLock(ss); /********************************/
7125 srvName = &ss->ssl3.prSpec->srvVirtName;
7126 if (srvName->len && srvName->data) {
7127 rv = SECITEM_CopyItem(NULL, &sid->u.ssl3.srvName, srvName);
7129 ssl_ReleaseSpecReadLock(ss); /************************************/
7130 if (rv != SECSuccess) {
7135 sid->peerID = (ss->peerID == NULL) ? NULL : PORT_Strdup(ss->peerID);
7136 sid->urlSvrName = (ss->url == NULL) ? NULL : PORT_Strdup(ss->url);
7137 sid->addr = ss->sec.ci.peer;
7138 sid->port = ss->sec.ci.port;
7139 sid->references = 1;
7140 sid->cached = never_cached;
7141 sid->version = ss->version;
7143 sid->u.ssl3.keys.resumable = PR_TRUE;
7144 sid->u.ssl3.policy = SSL_ALLOWED;
7145 sid->u.ssl3.clientWriteKey = NULL;
7146 sid->u.ssl3.serverWriteKey = NULL;
7150 int pid = SSL_GETPID();
7152 sid->u.ssl3.sessionIDLength = SSL3_SESSIONID_BYTES;
7153 sid->u.ssl3.sessionID[0] = (pid >> 8) & 0xff;
7154 sid->u.ssl3.sessionID[1] = pid & 0xff;
7155 rv = PK11_GenerateRandom(sid->u.ssl3.sessionID + 2,
7156 SSL3_SESSIONID_BYTES -2);
7157 if (rv != SECSuccess) {
7159 ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
7166 /* Called from: ssl3_HandleClientHello, ssl3_HandleV2ClientHello */
7168 ssl3_SendServerHelloSequence(sslSocket *ss)
7170 const ssl3KEADef *kea_def;
7173 SSL_TRC(3, ("%d: SSL3[%d]: begin send server_hello sequence",
7174 SSL_GETPID(), ss->fd));
7176 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
7177 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
7179 rv = ssl3_SendServerHello(ss);
7180 if (rv != SECSuccess) {
7181 return rv; /* err code is set. */
7183 rv = ssl3_SendCertificate(ss);
7184 if (rv != SECSuccess) {
7185 return rv; /* error code is set. */
7187 rv = ssl3_SendCertificateStatus(ss);
7188 if (rv != SECSuccess) {
7189 return rv; /* error code is set. */
7191 /* We have to do this after the call to ssl3_SendServerHello,
7192 * because kea_def is set up by ssl3_SendServerHello().
7194 kea_def = ss->ssl3.hs.kea_def;
7195 ss->ssl3.hs.usedStepDownKey = PR_FALSE;
7197 if (kea_def->is_limited && kea_def->exchKeyType == kt_rsa) {
7198 /* see if we can legally use the key in the cert. */
7199 int keyLen; /* bytes */
7201 keyLen = PK11_GetPrivateModulusLen(
7202 ss->serverCerts[kea_def->exchKeyType].SERVERKEY);
7205 keyLen * BPB <= kea_def->key_size_limit ) {
7206 /* XXX AND cert is not signing only!! */
7207 /* just fall through and use it. */
7208 } else if (ss->stepDownKeyPair != NULL) {
7209 ss->ssl3.hs.usedStepDownKey = PR_TRUE;
7210 rv = ssl3_SendServerKeyExchange(ss);
7211 if (rv != SECSuccess) {
7212 return rv; /* err code was set. */
7215 #ifndef HACKED_EXPORT_SERVER
7216 PORT_SetError(SSL_ERROR_PUB_KEY_SIZE_LIMIT_EXCEEDED);
7220 #ifdef NSS_ENABLE_ECC
7221 } else if ((kea_def->kea == kea_ecdhe_rsa) ||
7222 (kea_def->kea == kea_ecdhe_ecdsa)) {
7223 rv = ssl3_SendServerKeyExchange(ss);
7224 if (rv != SECSuccess) {
7225 return rv; /* err code was set. */
7227 #endif /* NSS_ENABLE_ECC */
7230 if (ss->opt.requestCertificate) {
7231 rv = ssl3_SendCertificateRequest(ss);
7232 if (rv != SECSuccess) {
7233 return rv; /* err code is set. */
7236 rv = ssl3_SendServerHelloDone(ss);
7237 if (rv != SECSuccess) {
7238 return rv; /* err code is set. */
7241 ss->ssl3.hs.ws = (ss->opt.requestCertificate) ? wait_client_cert
7246 /* An empty TLS Renegotiation Info (RI) extension */
7247 static const PRUint8 emptyRIext[5] = {0xff, 0x01, 0x00, 0x01, 0x00};
7249 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
7250 * ssl3 Client Hello message.
7251 * Caller must hold Handshake and RecvBuf locks.
7254 ssl3_HandleClientHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
7256 sslSessionID * sid = NULL;
7261 int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
7262 SSL3AlertDescription desc = illegal_parameter;
7263 SSL3AlertLevel level = alert_fatal;
7264 SSL3ProtocolVersion version;
7265 SECItem sidBytes = {siBuffer, NULL, 0};
7266 SECItem cookieBytes = {siBuffer, NULL, 0};
7267 SECItem suites = {siBuffer, NULL, 0};
7268 SECItem comps = {siBuffer, NULL, 0};
7269 PRBool haveSpecWriteLock = PR_FALSE;
7270 PRBool haveXmitBufLock = PR_FALSE;
7272 SSL_TRC(3, ("%d: SSL3[%d]: handle client_hello handshake",
7273 SSL_GETPID(), ss->fd));
7275 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
7276 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
7277 PORT_Assert( ss->ssl3.initialized );
7279 /* Get peer name of client */
7280 rv = ssl_GetPeerInfo(ss);
7281 if (rv != SECSuccess) {
7282 return rv; /* error code is set. */
7285 /* Clearing the handshake pointers so that ssl_Do1stHandshake won't
7286 * call ssl2_HandleMessage.
7288 * The issue here is that TLS ordinarily starts out in
7289 * ssl2_HandleV3HandshakeRecord() because of the backward-compatibility
7290 * code paths. That function zeroes these next pointers. But with DTLS,
7291 * we don't even try to do the v2 ClientHello so we skip that function
7292 * and need to reset these values here.
7295 ss->nextHandshake = 0;
7296 ss->securityHandshake = 0;
7299 /* We might be starting session renegotiation in which case we should
7300 * clear previous state.
7302 PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData));
7303 ss->statelessResume = PR_FALSE;
7305 if ((ss->ssl3.hs.ws != wait_client_hello) &&
7306 (ss->ssl3.hs.ws != idle_handshake)) {
7307 desc = unexpected_message;
7308 errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO;
7311 if (ss->ssl3.hs.ws == idle_handshake &&
7312 ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) {
7313 desc = no_renegotiation;
7314 level = alert_warning;
7315 errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED;
7320 dtls_RehandshakeCleanup(ss);
7323 tmp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
7325 goto loser; /* malformed, alert already sent */
7327 /* Translate the version */
7329 ss->clientHelloVersion = version =
7330 dtls_DTLSVersionToTLSVersion((SSL3ProtocolVersion)tmp);
7332 ss->clientHelloVersion = version = (SSL3ProtocolVersion)tmp;
7335 rv = ssl3_NegotiateVersion(ss, version, PR_TRUE);
7336 if (rv != SECSuccess) {
7337 desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version
7338 : handshake_failure;
7339 errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
7343 rv = ssl3_InitHandshakeHashes(ss);
7344 if (rv != SECSuccess) {
7345 desc = internal_error;
7346 errCode = PORT_GetError();
7350 /* grab the client random data. */
7351 rv = ssl3_ConsumeHandshake(
7352 ss, &ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH, &b, &length);
7353 if (rv != SECSuccess) {
7354 goto loser; /* malformed */
7357 /* grab the client's SID, if present. */
7358 rv = ssl3_ConsumeHandshakeVariable(ss, &sidBytes, 1, &b, &length);
7359 if (rv != SECSuccess) {
7360 goto loser; /* malformed */
7363 /* grab the client's cookie, if present. */
7365 rv = ssl3_ConsumeHandshakeVariable(ss, &cookieBytes, 1, &b, &length);
7366 if (rv != SECSuccess) {
7367 goto loser; /* malformed */
7371 /* grab the list of cipher suites. */
7372 rv = ssl3_ConsumeHandshakeVariable(ss, &suites, 2, &b, &length);
7373 if (rv != SECSuccess) {
7374 goto loser; /* malformed */
7377 /* grab the list of compression methods. */
7378 rv = ssl3_ConsumeHandshakeVariable(ss, &comps, 1, &b, &length);
7379 if (rv != SECSuccess) {
7380 goto loser; /* malformed */
7383 desc = handshake_failure;
7385 /* Handle TLS hello extensions for SSL3 & TLS. We do not know if
7386 * we are restarting a previous session until extensions have been
7387 * parsed, since we might have received a SessionTicket extension.
7388 * Note: we allow extensions even when negotiating SSL3 for the sake
7389 * of interoperability (and backwards compatibility).
7393 /* Get length of hello extensions */
7394 PRInt32 extension_length;
7395 extension_length = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
7396 if (extension_length < 0) {
7397 goto loser; /* alert already sent */
7399 if (extension_length != length) {
7400 ssl3_DecodeError(ss); /* send alert */
7403 rv = ssl3_HandleHelloExtensions(ss, &b, &length);
7404 if (rv != SECSuccess) {
7405 goto loser; /* malformed */
7408 if (!ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
7409 /* If we didn't receive an RI extension, look for the SCSV,
7410 * and if found, treat it just like an empty RI extension
7411 * by processing a local copy of an empty RI extension.
7413 for (i = 0; i + 1 < suites.len; i += 2) {
7414 PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1];
7415 if (suite_i == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) {
7416 SSL3Opaque * b2 = (SSL3Opaque *)emptyRIext;
7417 PRUint32 L2 = sizeof emptyRIext;
7418 (void)ssl3_HandleHelloExtensions(ss, &b2, &L2);
7423 if (ss->firstHsDone &&
7424 (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_REQUIRES_XTN ||
7425 ss->opt.enableRenegotiation == SSL_RENEGOTIATE_TRANSITIONAL) &&
7426 !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
7427 desc = no_renegotiation;
7428 level = alert_warning;
7429 errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED;
7432 if ((ss->opt.requireSafeNegotiation ||
7433 (ss->firstHsDone && ss->peerRequestedProtection)) &&
7434 !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
7435 desc = handshake_failure;
7436 errCode = SSL_ERROR_UNSAFE_NEGOTIATION;
7440 /* We do stateful resumes only if either of the following
7441 * conditions are satisfied: (1) the client does not support the
7442 * session ticket extension, or (2) the client support the session
7443 * ticket extension, but sent an empty ticket.
7445 if (!ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) ||
7446 ss->xtnData.emptySessionTicket) {
7447 if (sidBytes.len > 0 && !ss->opt.noCache) {
7448 SSL_TRC(7, ("%d: SSL3[%d]: server, lookup client session-id for 0x%08x%08x%08x%08x",
7449 SSL_GETPID(), ss->fd, ss->sec.ci.peer.pr_s6_addr32[0],
7450 ss->sec.ci.peer.pr_s6_addr32[1],
7451 ss->sec.ci.peer.pr_s6_addr32[2],
7452 ss->sec.ci.peer.pr_s6_addr32[3]));
7453 if (ssl_sid_lookup) {
7454 sid = (*ssl_sid_lookup)(&ss->sec.ci.peer, sidBytes.data,
7455 sidBytes.len, ss->dbHandle);
7457 errCode = SSL_ERROR_SERVER_CACHE_NOT_CONFIGURED;
7461 } else if (ss->statelessResume) {
7462 /* Fill in the client's session ID if doing a stateless resume.
7463 * (When doing stateless resumes, server echos client's SessionID.)
7465 sid = ss->sec.ci.sid;
7466 PORT_Assert(sid != NULL); /* Should have already been filled in.*/
7468 if (sidBytes.len > 0 && sidBytes.len <= SSL3_SESSIONID_BYTES) {
7469 sid->u.ssl3.sessionIDLength = sidBytes.len;
7470 PORT_Memcpy(sid->u.ssl3.sessionID, sidBytes.data,
7472 sid->u.ssl3.sessionIDLength = sidBytes.len;
7474 sid->u.ssl3.sessionIDLength = 0;
7476 ss->sec.ci.sid = NULL;
7479 /* We only send a session ticket extension if the client supports
7480 * the extension and we are unable to do either a stateful or
7483 * TODO: send a session ticket if performing a stateful
7484 * resumption. (As per RFC4507, a server may issue a session
7485 * ticket while doing a (stateless or stateful) session resume,
7486 * but OpenSSL-0.9.8g does not accept session tickets while
7489 if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) && sid == NULL) {
7490 ssl3_RegisterServerHelloExtensionSender(ss,
7491 ssl_session_ticket_xtn, ssl3_SendSessionTicketXtn);
7495 /* We've found a session cache entry for this client.
7496 * Now, if we're going to require a client-auth cert,
7497 * and we don't already have this client's cert in the session cache,
7498 * and this is the first handshake on this connection (not a redo),
7499 * then drop this old cache entry and start a new session.
7501 if ((sid->peerCert == NULL) && ss->opt.requestCertificate &&
7502 ((ss->opt.requireCertificate == SSL_REQUIRE_ALWAYS) ||
7503 (ss->opt.requireCertificate == SSL_REQUIRE_NO_ERROR) ||
7504 ((ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE)
7505 && !ss->firstHsDone))) {
7507 SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_not_ok );
7508 if (ss->sec.uncache)
7509 ss->sec.uncache(sid);
7515 #ifdef NSS_ENABLE_ECC
7516 /* Disable any ECC cipher suites for which we have no cert. */
7517 ssl3_FilterECCipherSuitesByServerCerts(ss);
7521 ssl3_DisableNonDTLSSuites(ss);
7525 /* Look for a matching cipher suite. */
7526 j = ssl3_config_match_init(ss);
7527 if (j <= 0) { /* no ciphers are working/supported by PK11 */
7528 errCode = PORT_GetError(); /* error code is already set. */
7533 /* If we already have a session for this client, be sure to pick the
7534 ** same cipher suite and compression method we picked before.
7535 ** This is not a loop, despite appearances.
7538 ssl3CipherSuiteCfg *suite;
7540 SSLVersionRange vrange = {ss->version, ss->version};
7543 /* Check that the cached compression method is still enabled. */
7544 if (!compressionEnabled(ss, sid->u.ssl3.compression))
7547 /* Check that the cached compression method is in the client's list */
7548 for (i = 0; i < comps.len; i++) {
7549 if (comps.data[i] == sid->u.ssl3.compression)
7555 suite = ss->cipherSuites;
7556 /* Find the entry for the cipher suite used in the cached session. */
7557 for (j = ssl_V3_SUITES_IMPLEMENTED; j > 0; --j, ++suite) {
7558 if (suite->cipher_suite == sid->u.ssl3.cipherSuite)
7565 /* Double check that the cached cipher suite is still enabled,
7566 * implemented, and allowed by policy. Might have been disabled.
7567 * The product policy won't change during the process lifetime.
7568 * Implemented ("isPresent") shouldn't change for servers.
7570 if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange))
7573 if (!suite->enabled)
7576 /* Double check that the cached cipher suite is in the client's list */
7577 for (i = 0; i + 1 < suites.len; i += 2) {
7578 PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1];
7579 if (suite_i == suite->cipher_suite) {
7580 ss->ssl3.hs.cipher_suite = suite->cipher_suite;
7581 ss->ssl3.hs.suite_def =
7582 ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite);
7584 /* Use the cached compression method. */
7585 ss->ssl3.hs.compression = sid->u.ssl3.compression;
7586 goto compression_found;
7591 /* START A NEW SESSION */
7594 /* Look for a matching cipher suite. */
7595 j = ssl3_config_match_init(ss);
7596 if (j <= 0) { /* no ciphers are working/supported by PK11 */
7597 errCode = PORT_GetError(); /* error code is already set. */
7602 /* Select a cipher suite.
7604 ** NOTE: This suite selection algorithm should be the same as the one in
7605 ** ssl3_HandleV2ClientHello().
7607 ** If TLS 1.0 is enabled, we could handle the case where the client
7608 ** offered TLS 1.1 but offered only export cipher suites by choosing TLS
7609 ** 1.0 and selecting one of those export cipher suites. However, a secure
7610 ** TLS 1.1 client should not have export cipher suites enabled at all,
7611 ** and a TLS 1.1 client should definitely not be offering *only* export
7612 ** cipher suites. Therefore, we refuse to negotiate export cipher suites
7613 ** with any client that indicates support for TLS 1.1 or higher when we
7614 ** (the server) have TLS 1.1 support enabled.
7616 for (j = 0; j < ssl_V3_SUITES_IMPLEMENTED; j++) {
7617 ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j];
7618 SSLVersionRange vrange = {ss->version, ss->version};
7619 if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange)) {
7622 for (i = 0; i + 1 < suites.len; i += 2) {
7623 PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1];
7624 if (suite_i == suite->cipher_suite) {
7625 ss->ssl3.hs.cipher_suite = suite->cipher_suite;
7626 ss->ssl3.hs.suite_def =
7627 ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite);
7632 errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
7636 /* Select a compression algorithm. */
7637 for (i = 0; i < comps.len; i++) {
7638 if (!compressionEnabled(ss, comps.data[i]))
7640 for (j = 0; j < compressionMethodsCount; j++) {
7641 if (comps.data[i] == compressions[j]) {
7642 ss->ssl3.hs.compression =
7643 (SSLCompressionMethod)compressions[j];
7644 goto compression_found;
7648 errCode = SSL_ERROR_NO_COMPRESSION_OVERLAP;
7649 /* null compression must be supported */
7656 ss->sec.send = ssl3_SendApplicationData;
7658 /* If there are any failures while processing the old sid,
7659 * we don't consider them to be errors. Instead, We just behave
7660 * as if the client had sent us no sid to begin with, and make a new one.
7662 if (sid != NULL) do {
7663 ssl3CipherSpec *pwSpec;
7664 SECItem wrappedMS; /* wrapped key */
7666 if (sid->version != ss->version ||
7667 sid->u.ssl3.cipherSuite != ss->ssl3.hs.cipher_suite ||
7668 sid->u.ssl3.compression != ss->ssl3.hs.compression) {
7669 break; /* not an error */
7672 if (ss->sec.ci.sid) {
7673 if (ss->sec.uncache)
7674 ss->sec.uncache(ss->sec.ci.sid);
7675 PORT_Assert(ss->sec.ci.sid != sid); /* should be impossible, but ... */
7676 if (ss->sec.ci.sid != sid) {
7677 ssl_FreeSID(ss->sec.ci.sid);
7679 ss->sec.ci.sid = NULL;
7681 /* we need to resurrect the master secret.... */
7683 ssl_GetSpecWriteLock(ss); haveSpecWriteLock = PR_TRUE;
7684 pwSpec = ss->ssl3.pwSpec;
7685 if (sid->u.ssl3.keys.msIsWrapped) {
7686 PK11SymKey * wrapKey; /* wrapping key */
7687 CK_FLAGS keyFlags = 0;
7688 #ifndef NO_PKCS11_BYPASS
7689 if (ss->opt.bypassPKCS11) {
7690 /* we cannot restart a non-bypass session in a
7697 wrapKey = getWrappingKey(ss, NULL, sid->u.ssl3.exchKeyType,
7698 sid->u.ssl3.masterWrapMech,
7701 /* we have a SID cache entry, but no wrapping key for it??? */
7705 if (ss->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */
7706 keyFlags = CKF_SIGN | CKF_VERIFY;
7709 wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
7710 wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len;
7712 /* unwrap the master secret. */
7713 pwSpec->master_secret =
7714 PK11_UnwrapSymKeyWithFlags(wrapKey, sid->u.ssl3.masterWrapMech,
7715 NULL, &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE,
7716 CKA_DERIVE, sizeof(SSL3MasterSecret), keyFlags);
7717 PK11_FreeSymKey(wrapKey);
7718 if (pwSpec->master_secret == NULL) {
7719 break; /* not an error */
7721 #ifndef NO_PKCS11_BYPASS
7722 } else if (ss->opt.bypassPKCS11) {
7723 wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
7724 wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len;
7725 memcpy(pwSpec->raw_master_secret, wrappedMS.data, wrappedMS.len);
7726 pwSpec->msItem.data = pwSpec->raw_master_secret;
7727 pwSpec->msItem.len = wrappedMS.len;
7730 /* We CAN restart a bypass session in a non-bypass socket. */
7731 /* need to import the raw master secret to session object */
7732 PK11SlotInfo * slot;
7733 wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
7734 wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len;
7735 slot = PK11_GetInternalSlot();
7736 pwSpec->master_secret =
7737 PK11_ImportSymKey(slot, CKM_SSL3_MASTER_KEY_DERIVE,
7738 PK11_OriginUnwrap, CKA_ENCRYPT, &wrappedMS,
7740 PK11_FreeSlot(slot);
7741 if (pwSpec->master_secret == NULL) {
7742 break; /* not an error */
7745 ss->sec.ci.sid = sid;
7746 if (sid->peerCert != NULL) {
7747 ss->sec.peerCert = CERT_DupCertificate(sid->peerCert);
7751 * Old SID passed all tests, so resume this old session.
7753 * XXX make sure compression still matches
7755 SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_hits );
7756 if (ss->statelessResume)
7757 SSL_AtomicIncrementLong(& ssl3stats.hch_sid_stateless_resumes );
7758 ss->ssl3.hs.isResuming = PR_TRUE;
7760 ss->sec.authAlgorithm = sid->authAlgorithm;
7761 ss->sec.authKeyBits = sid->authKeyBits;
7762 ss->sec.keaType = sid->keaType;
7763 ss->sec.keaKeyBits = sid->keaKeyBits;
7765 /* server sids don't remember the server cert we previously sent,
7766 ** but they do remember the kea type we originally used, so we
7767 ** can locate it again, provided that the current ssl socket
7768 ** has had its server certs configured the same as the previous one.
7771 CERT_DupCertificate(ss->serverCerts[sid->keaType].serverCert);
7773 /* Copy cached name in to pending spec */
7775 sid->version > SSL_LIBRARY_VERSION_3_0 &&
7776 sid->u.ssl3.srvName.len && sid->u.ssl3.srvName.data) {
7777 /* Set server name from sid */
7778 SECItem *sidName = &sid->u.ssl3.srvName;
7779 SECItem *pwsName = &ss->ssl3.pwSpec->srvVirtName;
7780 if (pwsName->data) {
7781 SECITEM_FreeItem(pwsName, PR_FALSE);
7783 rv = SECITEM_CopyItem(NULL, pwsName, sidName);
7784 if (rv != SECSuccess) {
7785 errCode = PORT_GetError();
7786 desc = internal_error;
7791 /* Clean up sni name array */
7792 if (ssl3_ExtensionNegotiated(ss, ssl_server_name_xtn) &&
7793 ss->xtnData.sniNameArr) {
7794 PORT_Free(ss->xtnData.sniNameArr);
7795 ss->xtnData.sniNameArr = NULL;
7796 ss->xtnData.sniNameArrSize = 0;
7799 ssl_GetXmitBufLock(ss); haveXmitBufLock = PR_TRUE;
7801 rv = ssl3_SendServerHello(ss);
7802 if (rv != SECSuccess) {
7803 errCode = PORT_GetError();
7807 if (haveSpecWriteLock) {
7808 ssl_ReleaseSpecWriteLock(ss);
7809 haveSpecWriteLock = PR_FALSE;
7812 /* NULL value for PMS signifies re-use of the old MS */
7813 rv = ssl3_InitPendingCipherSpec(ss, NULL);
7814 if (rv != SECSuccess) {
7815 errCode = PORT_GetError();
7819 rv = ssl3_SendChangeCipherSpecs(ss);
7820 if (rv != SECSuccess) {
7821 errCode = PORT_GetError();
7824 rv = ssl3_SendFinished(ss, 0);
7825 ss->ssl3.hs.ws = wait_change_cipher;
7826 if (rv != SECSuccess) {
7827 errCode = PORT_GetError();
7831 if (haveXmitBufLock) {
7832 ssl_ReleaseXmitBufLock(ss);
7833 haveXmitBufLock = PR_FALSE;
7839 if (haveSpecWriteLock) {
7840 ssl_ReleaseSpecWriteLock(ss);
7841 haveSpecWriteLock = PR_FALSE;
7844 if (sid) { /* we had a sid, but it's no longer valid, free it */
7845 SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_not_ok );
7846 if (ss->sec.uncache)
7847 ss->sec.uncache(sid);
7851 SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_misses );
7853 if (ssl3_ExtensionNegotiated(ss, ssl_server_name_xtn)) {
7855 if (ss->sniSocketConfig) do { /* not a loop */
7856 ret = SSL_SNI_SEND_ALERT;
7857 /* If extension is negotiated, the len of names should > 0. */
7858 if (ss->xtnData.sniNameArrSize) {
7859 /* Calling client callback to reconfigure the socket. */
7860 ret = (SECStatus)(*ss->sniSocketConfig)(ss->fd,
7861 ss->xtnData.sniNameArr,
7862 ss->xtnData.sniNameArrSize,
7863 ss->sniSocketConfigArg);
7865 if (ret <= SSL_SNI_SEND_ALERT) {
7866 /* Application does not know the name or was not able to
7867 * properly reconfigure the socket. */
7868 errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
7869 desc = unrecognized_name;
7871 } else if (ret == SSL_SNI_CURRENT_CONFIG_IS_USED) {
7872 SECStatus rv = SECSuccess;
7873 SECItem * cwsName, *pwsName;
7875 ssl_GetSpecWriteLock(ss); /*******************************/
7876 pwsName = &ss->ssl3.pwSpec->srvVirtName;
7877 cwsName = &ss->ssl3.cwSpec->srvVirtName;
7878 #ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS
7879 /* not allow name change on the 2d HS */
7880 if (ss->firstHsDone) {
7881 if (ssl3_ServerNameCompare(pwsName, cwsName)) {
7882 ssl_ReleaseSpecWriteLock(ss); /******************/
7883 errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
7884 desc = handshake_failure;
7885 ret = SSL_SNI_SEND_ALERT;
7890 if (pwsName->data) {
7891 SECITEM_FreeItem(pwsName, PR_FALSE);
7893 if (cwsName->data) {
7894 rv = SECITEM_CopyItem(NULL, pwsName, cwsName);
7896 ssl_ReleaseSpecWriteLock(ss); /**************************/
7897 if (rv != SECSuccess) {
7898 errCode = SSL_ERROR_INTERNAL_ERROR_ALERT;
7899 desc = internal_error;
7900 ret = SSL_SNI_SEND_ALERT;
7903 } else if (ret < ss->xtnData.sniNameArrSize) {
7904 /* Application has configured new socket info. Lets check it
7905 * and save the name. */
7907 SECItem * name = &ss->xtnData.sniNameArr[ret];
7908 int configedCiphers;
7911 /* get rid of the old name and save the newly picked. */
7912 /* This code is protected by ssl3HandshakeLock. */
7913 ssl_GetSpecWriteLock(ss); /*******************************/
7914 #ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS
7915 /* not allow name change on the 2d HS */
7916 if (ss->firstHsDone) {
7917 SECItem *cwsName = &ss->ssl3.cwSpec->srvVirtName;
7918 if (ssl3_ServerNameCompare(name, cwsName)) {
7919 ssl_ReleaseSpecWriteLock(ss); /******************/
7920 errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
7921 desc = handshake_failure;
7922 ret = SSL_SNI_SEND_ALERT;
7927 pwsName = &ss->ssl3.pwSpec->srvVirtName;
7928 if (pwsName->data) {
7929 SECITEM_FreeItem(pwsName, PR_FALSE);
7931 rv = SECITEM_CopyItem(NULL, pwsName, name);
7932 ssl_ReleaseSpecWriteLock(ss); /***************************/
7933 if (rv != SECSuccess) {
7934 errCode = SSL_ERROR_INTERNAL_ERROR_ALERT;
7935 desc = internal_error;
7936 ret = SSL_SNI_SEND_ALERT;
7939 configedCiphers = ssl3_config_match_init(ss);
7940 if (configedCiphers <= 0) {
7941 /* no ciphers are working/supported */
7942 errCode = PORT_GetError();
7943 desc = handshake_failure;
7944 ret = SSL_SNI_SEND_ALERT;
7947 /* Need to tell the client that application has picked
7948 * the name from the offered list and reconfigured the socket.
7950 ssl3_RegisterServerHelloExtensionSender(ss, ssl_server_name_xtn,
7951 ssl3_SendServerNameXtn);
7953 /* Callback returned index outside of the boundary. */
7954 PORT_Assert(ret < ss->xtnData.sniNameArrSize);
7955 errCode = SSL_ERROR_INTERNAL_ERROR_ALERT;
7956 desc = internal_error;
7957 ret = SSL_SNI_SEND_ALERT;
7961 /* Free sniNameArr. The data that each SECItem in the array
7962 * points into is the data from the input buffer "b". It will
7963 * not be available outside the scope of this or it's child
7965 if (ss->xtnData.sniNameArr) {
7966 PORT_Free(ss->xtnData.sniNameArr);
7967 ss->xtnData.sniNameArr = NULL;
7968 ss->xtnData.sniNameArrSize = 0;
7970 if (ret <= SSL_SNI_SEND_ALERT) {
7971 /* desc and errCode should be set. */
7975 #ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS
7976 else if (ss->firstHsDone) {
7977 /* Check that we don't have the name is current spec
7978 * if this extension was not negotiated on the 2d hs. */
7979 PRBool passed = PR_TRUE;
7980 ssl_GetSpecReadLock(ss); /*******************************/
7981 if (ss->ssl3.cwSpec->srvVirtName.data) {
7984 ssl_ReleaseSpecReadLock(ss); /***************************/
7986 errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
7987 desc = handshake_failure;
7993 sid = ssl3_NewSessionID(ss, PR_TRUE);
7995 errCode = PORT_GetError();
7996 goto loser; /* memory error is set. */
7998 ss->sec.ci.sid = sid;
8000 ss->ssl3.hs.isResuming = PR_FALSE;
8001 ssl_GetXmitBufLock(ss);
8002 rv = ssl3_SendServerHelloSequence(ss);
8003 ssl_ReleaseXmitBufLock(ss);
8004 if (rv != SECSuccess) {
8005 errCode = PORT_GetError();
8009 if (haveXmitBufLock) {
8010 ssl_ReleaseXmitBufLock(ss);
8011 haveXmitBufLock = PR_FALSE;
8017 if (haveSpecWriteLock) {
8018 ssl_ReleaseSpecWriteLock(ss);
8019 haveSpecWriteLock = PR_FALSE;
8021 (void)SSL3_SendAlert(ss, level, desc);
8024 if (haveSpecWriteLock) {
8025 ssl_ReleaseSpecWriteLock(ss);
8026 haveSpecWriteLock = PR_FALSE;
8029 if (haveXmitBufLock) {
8030 ssl_ReleaseXmitBufLock(ss);
8031 haveXmitBufLock = PR_FALSE;
8034 PORT_SetError(errCode);
8039 * ssl3_HandleV2ClientHello is used when a V2 formatted hello comes
8040 * in asking to use the V3 handshake.
8041 * Called from ssl2_HandleClientHelloMessage() in sslcon.c
8044 ssl3_HandleV2ClientHello(sslSocket *ss, unsigned char *buffer, int length)
8046 sslSessionID * sid = NULL;
8047 unsigned char * suites;
8048 unsigned char * random;
8049 SSL3ProtocolVersion version;
8056 int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
8057 SSL3AlertDescription desc = handshake_failure;
8059 SSL_TRC(3, ("%d: SSL3[%d]: handle v2 client_hello", SSL_GETPID(), ss->fd));
8061 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
8063 ssl_GetSSL3HandshakeLock(ss);
8065 PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData));
8067 rv = ssl3_InitState(ss);
8068 if (rv != SECSuccess) {
8069 ssl_ReleaseSSL3HandshakeLock(ss);
8070 return rv; /* ssl3_InitState has set the error code. */
8072 rv = ssl3_RestartHandshakeHashes(ss);
8073 if (rv != SECSuccess) {
8074 ssl_ReleaseSSL3HandshakeLock(ss);
8078 if (ss->ssl3.hs.ws != wait_client_hello) {
8079 desc = unexpected_message;
8080 errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO;
8081 goto loser; /* alert_loser */
8084 version = (buffer[1] << 8) | buffer[2];
8085 suite_length = (buffer[3] << 8) | buffer[4];
8086 sid_length = (buffer[5] << 8) | buffer[6];
8087 rand_length = (buffer[7] << 8) | buffer[8];
8088 ss->clientHelloVersion = version;
8090 rv = ssl3_NegotiateVersion(ss, version, PR_TRUE);
8091 if (rv != SECSuccess) {
8092 /* send back which ever alert client will understand. */
8093 desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version : handshake_failure;
8094 errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
8098 rv = ssl3_InitHandshakeHashes(ss);
8099 if (rv != SECSuccess) {
8100 desc = internal_error;
8101 errCode = PORT_GetError();
8105 /* if we get a non-zero SID, just ignore it. */
8107 SSL_HL_CLIENT_HELLO_HBYTES + suite_length + sid_length + rand_length) {
8108 SSL_DBG(("%d: SSL3[%d]: bad v2 client hello message, len=%d should=%d",
8109 SSL_GETPID(), ss->fd, length,
8110 SSL_HL_CLIENT_HELLO_HBYTES + suite_length + sid_length +
8112 goto loser; /* malformed */ /* alert_loser */
8115 suites = buffer + SSL_HL_CLIENT_HELLO_HBYTES;
8116 random = suites + suite_length + sid_length;
8118 if (rand_length < SSL_MIN_CHALLENGE_BYTES ||
8119 rand_length > SSL_MAX_CHALLENGE_BYTES) {
8120 goto loser; /* malformed */ /* alert_loser */
8123 PORT_Assert(SSL_MAX_CHALLENGE_BYTES == SSL3_RANDOM_LENGTH);
8125 PORT_Memset(&ss->ssl3.hs.client_random, 0, SSL3_RANDOM_LENGTH);
8127 &ss->ssl3.hs.client_random.rand[SSL3_RANDOM_LENGTH - rand_length],
8128 random, rand_length);
8130 PRINT_BUF(60, (ss, "client random:", &ss->ssl3.hs.client_random.rand[0],
8131 SSL3_RANDOM_LENGTH));
8132 #ifdef NSS_ENABLE_ECC
8133 /* Disable any ECC cipher suites for which we have no cert. */
8134 ssl3_FilterECCipherSuitesByServerCerts(ss);
8136 i = ssl3_config_match_init(ss);
8138 errCode = PORT_GetError(); /* error code is already set. */
8142 /* Select a cipher suite.
8144 ** NOTE: This suite selection algorithm should be the same as the one in
8145 ** ssl3_HandleClientHello().
8147 ** See the comments about export cipher suites in ssl3_HandleClientHello().
8149 for (j = 0; j < ssl_V3_SUITES_IMPLEMENTED; j++) {
8150 ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j];
8151 SSLVersionRange vrange = {ss->version, ss->version};
8152 if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange)) {
8155 for (i = 0; i+2 < suite_length; i += 3) {
8156 PRUint32 suite_i = (suites[i] << 16)|(suites[i+1] << 8)|suites[i+2];
8157 if (suite_i == suite->cipher_suite) {
8158 ss->ssl3.hs.cipher_suite = suite->cipher_suite;
8159 ss->ssl3.hs.suite_def =
8160 ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite);
8165 errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
8170 /* Look for the SCSV, and if found, treat it just like an empty RI
8171 * extension by processing a local copy of an empty RI extension.
8173 for (i = 0; i+2 < suite_length; i += 3) {
8174 PRUint32 suite_i = (suites[i] << 16) | (suites[i+1] << 8) | suites[i+2];
8175 if (suite_i == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) {
8176 SSL3Opaque * b2 = (SSL3Opaque *)emptyRIext;
8177 PRUint32 L2 = sizeof emptyRIext;
8178 (void)ssl3_HandleHelloExtensions(ss, &b2, &L2);
8183 if (ss->opt.requireSafeNegotiation &&
8184 !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
8185 desc = handshake_failure;
8186 errCode = SSL_ERROR_UNSAFE_NEGOTIATION;
8190 ss->ssl3.hs.compression = ssl_compression_null;
8191 ss->sec.send = ssl3_SendApplicationData;
8193 /* we don't even search for a cache hit here. It's just a miss. */
8194 SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_misses );
8195 sid = ssl3_NewSessionID(ss, PR_TRUE);
8197 errCode = PORT_GetError();
8198 goto loser; /* memory error is set. */
8200 ss->sec.ci.sid = sid;
8201 /* do not worry about memory leak of sid since it now belongs to ci */
8203 /* We have to update the handshake hashes before we can send stuff */
8204 rv = ssl3_UpdateHandshakeHashes(ss, buffer, length);
8205 if (rv != SECSuccess) {
8206 errCode = PORT_GetError();
8210 ssl_GetXmitBufLock(ss);
8211 rv = ssl3_SendServerHelloSequence(ss);
8212 ssl_ReleaseXmitBufLock(ss);
8213 if (rv != SECSuccess) {
8214 errCode = PORT_GetError();
8218 /* XXX_1 The call stack to here is:
8219 * ssl_Do1stHandshake -> ssl2_HandleClientHelloMessage -> here.
8220 * ssl2_HandleClientHelloMessage returns whatever we return here.
8221 * ssl_Do1stHandshake will continue looping if it gets back either
8222 * SECSuccess or SECWouldBlock.
8223 * SECSuccess is preferable here. See XXX_1 in sslgathr.c.
8225 ssl_ReleaseSSL3HandshakeLock(ss);
8229 SSL3_SendAlert(ss, alert_fatal, desc);
8231 ssl_ReleaseSSL3HandshakeLock(ss);
8232 PORT_SetError(errCode);
8236 /* The negotiated version number has been already placed in ss->version.
8238 ** Called from: ssl3_HandleClientHello (resuming session),
8239 ** ssl3_SendServerHelloSequence <- ssl3_HandleClientHello (new session),
8240 ** ssl3_SendServerHelloSequence <- ssl3_HandleV2ClientHello (new session)
8243 ssl3_SendServerHello(sslSocket *ss)
8247 PRUint32 maxBytes = 65535;
8249 PRInt32 extensions_len = 0;
8250 SSL3ProtocolVersion version;
8252 SSL_TRC(3, ("%d: SSL3[%d]: send server_hello handshake", SSL_GETPID(),
8255 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
8256 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
8259 PORT_Assert(MSB(ss->version) == MSB(SSL_LIBRARY_VERSION_3_0));
8261 if (MSB(ss->version) != MSB(SSL_LIBRARY_VERSION_3_0)) {
8262 PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
8266 PORT_Assert(MSB(ss->version) == MSB(SSL_LIBRARY_VERSION_DTLS_1_0));
8268 if (MSB(ss->version) != MSB(SSL_LIBRARY_VERSION_DTLS_1_0)) {
8269 PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
8274 sid = ss->sec.ci.sid;
8276 extensions_len = ssl3_CallHelloExtensionSenders(ss, PR_FALSE, maxBytes,
8277 &ss->xtnData.serverSenders[0]);
8278 if (extensions_len > 0)
8279 extensions_len += 2; /* Add sizeof total extension length */
8281 length = sizeof(SSL3ProtocolVersion) + SSL3_RANDOM_LENGTH + 1 +
8282 ((sid == NULL) ? 0: sid->u.ssl3.sessionIDLength) +
8283 sizeof(ssl3CipherSuite) + 1 + extensions_len;
8284 rv = ssl3_AppendHandshakeHeader(ss, server_hello, length);
8285 if (rv != SECSuccess) {
8286 return rv; /* err set by AppendHandshake. */
8290 version = dtls_TLSVersionToDTLSVersion(ss->version);
8292 version = ss->version;
8295 rv = ssl3_AppendHandshakeNumber(ss, version, 2);
8296 if (rv != SECSuccess) {
8297 return rv; /* err set by AppendHandshake. */
8299 rv = ssl3_GetNewRandom(&ss->ssl3.hs.server_random);
8300 if (rv != SECSuccess) {
8301 ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
8304 rv = ssl3_AppendHandshake(
8305 ss, &ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH);
8306 if (rv != SECSuccess) {
8307 return rv; /* err set by AppendHandshake. */
8311 rv = ssl3_AppendHandshakeVariable(
8312 ss, sid->u.ssl3.sessionID, sid->u.ssl3.sessionIDLength, 1);
8314 rv = ssl3_AppendHandshakeVariable(ss, NULL, 0, 1);
8315 if (rv != SECSuccess) {
8316 return rv; /* err set by AppendHandshake. */
8319 rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.cipher_suite, 2);
8320 if (rv != SECSuccess) {
8321 return rv; /* err set by AppendHandshake. */
8323 rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.compression, 1);
8324 if (rv != SECSuccess) {
8325 return rv; /* err set by AppendHandshake. */
8327 if (extensions_len) {
8330 extensions_len -= 2;
8331 rv = ssl3_AppendHandshakeNumber(ss, extensions_len, 2);
8332 if (rv != SECSuccess)
8333 return rv; /* err set by ssl3_SetupPendingCipherSpec */
8334 sent_len = ssl3_CallHelloExtensionSenders(ss, PR_TRUE, extensions_len,
8335 &ss->xtnData.serverSenders[0]);
8336 PORT_Assert(sent_len == extensions_len);
8337 if (sent_len != extensions_len) {
8339 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
8343 rv = ssl3_SetupPendingCipherSpec(ss);
8344 if (rv != SECSuccess) {
8345 return rv; /* err set by ssl3_SetupPendingCipherSpec */
8351 /* ssl3_PickSignatureHashAlgorithm selects a hash algorithm to use when signing
8352 * elements of the handshake. (The negotiated cipher suite determines the
8353 * signature algorithm.) Prior to TLS 1.2, the MD5/SHA1 combination is always
8354 * used. With TLS 1.2, a client may advertise its support for signature and
8355 * hash combinations. */
8357 ssl3_PickSignatureHashAlgorithm(sslSocket *ss,
8358 SSL3SignatureAndHashAlgorithm* out)
8360 TLSSignatureAlgorithm sigAlg;
8362 /* hashPreference expresses our preferences for hash algorithms, most
8363 * preferable first. */
8364 static const PRUint8 hashPreference[] = {
8371 switch (ss->ssl3.hs.kea_def->kea) {
8373 case kea_rsa_export:
8374 case kea_rsa_export_1024:
8376 case kea_dh_rsa_export:
8378 case kea_dhe_rsa_export:
8382 sigAlg = tls_sig_rsa;
8385 case kea_dh_dss_export:
8387 case kea_dhe_dss_export:
8388 sigAlg = tls_sig_dsa;
8390 case kea_ecdh_ecdsa:
8391 case kea_ecdhe_ecdsa:
8392 sigAlg = tls_sig_ecdsa;
8395 PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
8398 out->sigAlg = sigAlg;
8400 if (ss->version <= SSL_LIBRARY_VERSION_TLS_1_1) {
8401 /* SEC_OID_UNKNOWN means the MD5/SHA1 combo hash used in TLS 1.1 and
8403 out->hashAlg = SEC_OID_UNKNOWN;
8407 if (ss->ssl3.hs.numClientSigAndHash == 0) {
8408 /* If the client didn't provide any signature_algorithms extension then
8409 * we can assume that they support SHA-1:
8410 * https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
8411 out->hashAlg = SEC_OID_SHA1;
8415 for (i = 0; i < PR_ARRAY_SIZE(hashPreference); i++) {
8416 for (j = 0; j < ss->ssl3.hs.numClientSigAndHash; j++) {
8417 const SSL3SignatureAndHashAlgorithm* sh =
8418 &ss->ssl3.hs.clientSigAndHash[j];
8419 if (sh->sigAlg == sigAlg && sh->hashAlg == hashPreference[i]) {
8420 out->hashAlg = sh->hashAlg;
8426 PORT_SetError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
8432 ssl3_SendServerKeyExchange(sslSocket *ss)
8434 const ssl3KEADef * kea_def = ss->ssl3.hs.kea_def;
8435 SECStatus rv = SECFailure;
8438 SECItem signed_hash = {siBuffer, NULL, 0};
8440 SECKEYPublicKey * sdPub; /* public key for step-down */
8441 SSL3SignatureAndHashAlgorithm sigAndHash;
8443 SSL_TRC(3, ("%d: SSL3[%d]: send server_key_exchange handshake",
8444 SSL_GETPID(), ss->fd));
8446 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
8447 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
8449 if (ssl3_PickSignatureHashAlgorithm(ss, &sigAndHash) != SECSuccess) {
8453 switch (kea_def->exchKeyType) {
8455 /* Perform SSL Step-Down here. */
8456 sdPub = ss->stepDownKeyPair->pubKey;
8457 PORT_Assert(sdPub != NULL);
8459 PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
8462 rv = ssl3_ComputeExportRSAKeyHash(sigAndHash.hashAlg,
8463 sdPub->u.rsa.modulus,
8464 sdPub->u.rsa.publicExponent,
8465 &ss->ssl3.hs.client_random,
8466 &ss->ssl3.hs.server_random,
8467 &hashes, ss->opt.bypassPKCS11);
8468 if (rv != SECSuccess) {
8469 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
8473 isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
8474 rv = ssl3_SignHashes(&hashes, ss->serverCerts[kt_rsa].SERVERKEY,
8475 &signed_hash, isTLS);
8476 if (rv != SECSuccess) {
8477 goto loser; /* ssl3_SignHashes has set err. */
8479 if (signed_hash.data == NULL) {
8480 /* how can this happen and rv == SECSuccess ?? */
8481 PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
8484 length = 2 + sdPub->u.rsa.modulus.len +
8485 2 + sdPub->u.rsa.publicExponent.len +
8486 2 + signed_hash.len;
8488 rv = ssl3_AppendHandshakeHeader(ss, server_key_exchange, length);
8489 if (rv != SECSuccess) {
8490 goto loser; /* err set by AppendHandshake. */
8493 rv = ssl3_AppendHandshakeVariable(ss, sdPub->u.rsa.modulus.data,
8494 sdPub->u.rsa.modulus.len, 2);
8495 if (rv != SECSuccess) {
8496 goto loser; /* err set by AppendHandshake. */
8499 rv = ssl3_AppendHandshakeVariable(
8500 ss, sdPub->u.rsa.publicExponent.data,
8501 sdPub->u.rsa.publicExponent.len, 2);
8502 if (rv != SECSuccess) {
8503 goto loser; /* err set by AppendHandshake. */
8506 if (ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
8507 rv = ssl3_AppendSignatureAndHashAlgorithm(ss, &sigAndHash);
8508 if (rv != SECSuccess) {
8509 goto loser; /* err set by AppendHandshake. */
8513 rv = ssl3_AppendHandshakeVariable(ss, signed_hash.data,
8514 signed_hash.len, 2);
8515 if (rv != SECSuccess) {
8516 goto loser; /* err set by AppendHandshake. */
8518 PORT_Free(signed_hash.data);
8521 #ifdef NSS_ENABLE_ECC
8523 rv = ssl3_SendECDHServerKeyExchange(ss, &sigAndHash);
8526 #endif /* NSS_ENABLE_ECC */
8531 PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
8535 if (signed_hash.data != NULL)
8536 PORT_Free(signed_hash.data);
8542 ssl3_SendCertificateRequest(sslSocket *ss)
8546 CERTDistNames *ca_list;
8547 const PRUint8 *certTypes;
8548 const PRUint8 *sigAlgs;
8549 SECItem * names = NULL;
8555 int certTypesLength;
8558 SSL_TRC(3, ("%d: SSL3[%d]: send certificate_request handshake",
8559 SSL_GETPID(), ss->fd));
8561 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
8562 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
8564 isTLS12 = (PRBool)(ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
8566 /* ssl3.ca_list is initialized to NULL, and never changed. */
8567 ca_list = ss->ssl3.ca_list;
8569 ca_list = ssl3_server_ca_list;
8572 if (ca_list != NULL) {
8573 names = ca_list->names;
8574 nnames = ca_list->nnames;
8577 for (i = 0, name = names; i < nnames; i++, name++) {
8578 calen += 2 + name->len;
8581 certTypes = certificate_types;
8582 certTypesLength = sizeof certificate_types;
8583 sigAlgs = supported_signature_algorithms;
8584 sigAlgsLength = sizeof supported_signature_algorithms;
8586 length = 1 + certTypesLength + 2 + calen;
8588 length += 2 + sigAlgsLength;
8591 rv = ssl3_AppendHandshakeHeader(ss, certificate_request, length);
8592 if (rv != SECSuccess) {
8593 return rv; /* err set by AppendHandshake. */
8595 rv = ssl3_AppendHandshakeVariable(ss, certTypes, certTypesLength, 1);
8596 if (rv != SECSuccess) {
8597 return rv; /* err set by AppendHandshake. */
8600 rv = ssl3_AppendHandshakeVariable(ss, sigAlgs, sigAlgsLength, 2);
8601 if (rv != SECSuccess) {
8602 return rv; /* err set by AppendHandshake. */
8605 rv = ssl3_AppendHandshakeNumber(ss, calen, 2);
8606 if (rv != SECSuccess) {
8607 return rv; /* err set by AppendHandshake. */
8609 for (i = 0, name = names; i < nnames; i++, name++) {
8610 rv = ssl3_AppendHandshakeVariable(ss, name->data, name->len, 2);
8611 if (rv != SECSuccess) {
8612 return rv; /* err set by AppendHandshake. */
8620 ssl3_SendServerHelloDone(sslSocket *ss)
8624 SSL_TRC(3, ("%d: SSL3[%d]: send server_hello_done handshake",
8625 SSL_GETPID(), ss->fd));
8627 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
8628 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
8630 rv = ssl3_AppendHandshakeHeader(ss, server_hello_done, 0);
8631 if (rv != SECSuccess) {
8632 return rv; /* err set by AppendHandshake. */
8634 rv = ssl3_FlushHandshake(ss, 0);
8635 if (rv != SECSuccess) {
8636 return rv; /* error code set by ssl3_FlushHandshake */
8641 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
8642 * ssl3 Certificate Verify message
8643 * Caller must hold Handshake and RecvBuf locks.
8646 ssl3_HandleCertificateVerify(sslSocket *ss, SSL3Opaque *b, PRUint32 length,
8649 SECItem signed_hash = {siBuffer, NULL, 0};
8651 int errCode = SSL_ERROR_RX_MALFORMED_CERT_VERIFY;
8652 SSL3AlertDescription desc = handshake_failure;
8653 PRBool isTLS, isTLS12;
8654 SSL3SignatureAndHashAlgorithm sigAndHash;
8656 SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_verify handshake",
8657 SSL_GETPID(), ss->fd));
8658 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
8659 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
8661 isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
8662 isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
8664 if (ss->ssl3.hs.ws != wait_cert_verify || ss->sec.peerCert == NULL) {
8665 desc = unexpected_message;
8666 errCode = SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY;
8671 rv = ssl3_ConsumeSignatureAndHashAlgorithm(ss, &b, &length,
8673 if (rv != SECSuccess) {
8674 goto loser; /* malformed or unsupported. */
8676 rv = ssl3_CheckSignatureAndHashAlgorithmConsistency(
8677 &sigAndHash, ss->sec.peerCert);
8678 if (rv != SECSuccess) {
8679 errCode = PORT_GetError();
8680 desc = decrypt_error;
8684 /* We only support CertificateVerify messages that use the handshake
8686 if (sigAndHash.hashAlg != hashes->hashAlg) {
8687 errCode = SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM;
8688 desc = decrypt_error;
8693 rv = ssl3_ConsumeHandshakeVariable(ss, &signed_hash, 2, &b, &length);
8694 if (rv != SECSuccess) {
8695 goto loser; /* malformed. */
8698 /* XXX verify that the key & kea match */
8699 rv = ssl3_VerifySignedHashes(hashes, ss->sec.peerCert, &signed_hash,
8700 isTLS, ss->pkcs11PinArg);
8701 if (rv != SECSuccess) {
8702 errCode = PORT_GetError();
8703 desc = isTLS ? decrypt_error : handshake_failure;
8707 signed_hash.data = NULL;
8710 desc = isTLS ? decode_error : illegal_parameter;
8711 goto alert_loser; /* malformed */
8713 ss->ssl3.hs.ws = wait_change_cipher;
8717 SSL3_SendAlert(ss, alert_fatal, desc);
8719 PORT_SetError(errCode);
8724 /* find a slot that is able to generate a PMS and wrap it with RSA.
8725 * Then generate and return the PMS.
8726 * If the serverKeySlot parameter is non-null, this function will use
8727 * that slot to do the job, otherwise it will find a slot.
8729 * Called from ssl3_DeriveConnectionKeysPKCS11() (above)
8730 * sendRSAClientKeyExchange() (above)
8731 * ssl3_HandleRSAClientKeyExchange() (below)
8732 * Caller must hold the SpecWriteLock, the SSL3HandshakeLock
8735 ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec,
8736 PK11SlotInfo * serverKeySlot)
8738 PK11SymKey * pms = NULL;
8739 PK11SlotInfo * slot = serverKeySlot;
8740 void * pwArg = ss->pkcs11PinArg;
8743 CK_MECHANISM_TYPE mechanism_array[3];
8745 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
8748 SSLCipherAlgorithm calg;
8749 /* The specReadLock would suffice here, but we cannot assert on
8750 ** read locks. Also, all the callers who call with a non-null
8751 ** slot already hold the SpecWriteLock.
8753 PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
8754 PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
8756 calg = spec->cipher_def->calg;
8757 PORT_Assert(alg2Mech[calg].calg == calg);
8759 /* First get an appropriate slot. */
8760 mechanism_array[0] = CKM_SSL3_PRE_MASTER_KEY_GEN;
8761 mechanism_array[1] = CKM_RSA_PKCS;
8762 mechanism_array[2] = alg2Mech[calg].cmech;
8764 slot = PK11_GetBestSlotMultiple(mechanism_array, 3, pwArg);
8766 /* can't find a slot with all three, find a slot with the minimum */
8767 slot = PK11_GetBestSlotMultiple(mechanism_array, 2, pwArg);
8769 PORT_SetError(SSL_ERROR_TOKEN_SLOT_NOT_FOUND);
8770 return pms; /* which is NULL */
8775 /* Generate the pre-master secret ... */
8777 SSL3ProtocolVersion temp;
8779 temp = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion);
8780 version.major = MSB(temp);
8781 version.minor = LSB(temp);
8783 version.major = MSB(ss->clientHelloVersion);
8784 version.minor = LSB(ss->clientHelloVersion);
8787 param.data = (unsigned char *)&version;
8788 param.len = sizeof version;
8790 pms = PK11_KeyGen(slot, CKM_SSL3_PRE_MASTER_KEY_GEN, ¶m, 0, pwArg);
8792 PK11_FreeSlot(slot);
8794 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
8799 /* Note: The Bleichenbacher attack on PKCS#1 necessitates that we NEVER
8800 * return any indication of failure of the Client Key Exchange message,
8801 * where that failure is caused by the content of the client's message.
8802 * This function must not return SECFailure for any reason that is directly
8803 * or indirectly caused by the content of the client's encrypted PMS.
8804 * We must not send an alert and also not drop the connection.
8805 * Instead, we generate a random PMS. This will cause a failure
8806 * in the processing the finished message, which is exactly where
8807 * the failure must occur.
8809 * Called from ssl3_HandleClientKeyExchange
8812 ssl3_HandleRSAClientKeyExchange(sslSocket *ss,
8815 SECKEYPrivateKey *serverKey)
8818 #ifndef NO_PKCS11_BYPASS
8819 unsigned char * cr = (unsigned char *)&ss->ssl3.hs.client_random;
8820 unsigned char * sr = (unsigned char *)&ss->ssl3.hs.server_random;
8821 ssl3CipherSpec * pwSpec = ss->ssl3.pwSpec;
8822 unsigned int outLen = 0;
8824 PRBool isTLS = PR_FALSE;
8827 unsigned char rsaPmsBuf[SSL3_RSA_PMS_LENGTH];
8828 SECItem pmsItem = {siBuffer, NULL, 0};
8830 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
8831 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
8832 PORT_Assert( ss->ssl3.prSpec == ss->ssl3.pwSpec );
8835 enc_pms.len = length;
8836 pmsItem.data = rsaPmsBuf;
8837 pmsItem.len = sizeof rsaPmsBuf;
8839 if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */
8841 kLen = ssl3_ConsumeHandshakeNumber(ss, 2, &enc_pms.data, &enc_pms.len);
8843 PORT_SetError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
8846 if ((unsigned)kLen < enc_pms.len) {
8851 isTLS = (PRBool)(ss->ssl3.hs.kea_def->tls_keygen != 0);
8854 #ifndef NO_PKCS11_BYPASS
8855 if (ss->opt.bypassPKCS11) {
8856 /* TRIPLE BYPASS, get PMS directly from RSA decryption.
8857 * Use PK11_PrivDecryptPKCS1 to decrypt the PMS to a buffer,
8858 * then, check for version rollback attack, then
8859 * do the equivalent of ssl3_DeriveMasterSecret, placing the MS in
8860 * pwSpec->msItem. Finally call ssl3_InitPendingCipherSpec with
8861 * ss and NULL, so that it will use the MS we've already derived here.
8864 rv = PK11_PrivDecryptPKCS1(serverKey, rsaPmsBuf, &outLen,
8865 sizeof rsaPmsBuf, enc_pms.data, enc_pms.len);
8866 if (rv != SECSuccess) {
8867 /* triple bypass failed. Let's try for a double bypass. */
8869 } else if (ss->opt.detectRollBack) {
8870 SSL3ProtocolVersion client_version =
8871 (rsaPmsBuf[0] << 8) | rsaPmsBuf[1];
8874 client_version = dtls_DTLSVersionToTLSVersion(client_version);
8877 if (client_version != ss->clientHelloVersion) {
8878 /* Version roll-back detected. ensure failure. */
8879 rv = PK11_GenerateRandom(rsaPmsBuf, sizeof rsaPmsBuf);
8882 /* have PMS, build MS without PKCS11 */
8883 rv = ssl3_MasterKeyDeriveBypass(pwSpec, cr, sr, &pmsItem, isTLS,
8885 if (rv != SECSuccess) {
8886 pwSpec->msItem.data = pwSpec->raw_master_secret;
8887 pwSpec->msItem.len = SSL3_MASTER_SECRET_LENGTH;
8888 PK11_GenerateRandom(pwSpec->msItem.data, pwSpec->msItem.len);
8890 rv = ssl3_InitPendingCipherSpec(ss, NULL);
8894 #ifndef NO_PKCS11_BYPASS
8898 * unwrap pms out of the incoming buffer
8899 * Note: CKM_SSL3_MASTER_KEY_DERIVE is NOT the mechanism used to do
8900 * the unwrap. Rather, it is the mechanism with which the
8901 * unwrapped pms will be used.
8903 pms = PK11_PubUnwrapSymKey(serverKey, &enc_pms,
8904 CKM_SSL3_MASTER_KEY_DERIVE, CKA_DERIVE, 0);
8906 PRINT_BUF(60, (ss, "decrypted premaster secret:",
8907 PK11_GetKeyData(pms)->data,
8908 PK11_GetKeyData(pms)->len));
8910 /* unwrap failed. Generate a bogus PMS and carry on. */
8911 PK11SlotInfo * slot = PK11_GetSlotFromPrivateKey(serverKey);
8913 ssl_GetSpecWriteLock(ss);
8914 pms = ssl3_GenerateRSAPMS(ss, ss->ssl3.prSpec, slot);
8915 ssl_ReleaseSpecWriteLock(ss);
8916 PK11_FreeSlot(slot);
8921 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
8925 /* This step will derive the MS from the PMS, among other things. */
8926 rv = ssl3_InitPendingCipherSpec(ss, pms);
8927 PK11_FreeSymKey(pms);
8930 if (rv != SECSuccess) {
8932 return SECFailure; /* error code set by ssl3_InitPendingCipherSpec */
8938 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
8939 * ssl3 ClientKeyExchange message from the remote client
8940 * Caller must hold Handshake and RecvBuf locks.
8943 ssl3_HandleClientKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
8945 SECKEYPrivateKey *serverKey = NULL;
8947 const ssl3KEADef *kea_def;
8948 ssl3KeyPair *serverKeyPair = NULL;
8949 #ifdef NSS_ENABLE_ECC
8950 SECKEYPublicKey *serverPubKey = NULL;
8951 #endif /* NSS_ENABLE_ECC */
8953 SSL_TRC(3, ("%d: SSL3[%d]: handle client_key_exchange handshake",
8954 SSL_GETPID(), ss->fd));
8956 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
8957 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
8959 if (ss->ssl3.hs.ws != wait_client_key) {
8960 SSL3_SendAlert(ss, alert_fatal, unexpected_message);
8961 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH);
8965 kea_def = ss->ssl3.hs.kea_def;
8967 if (ss->ssl3.hs.usedStepDownKey) {
8968 PORT_Assert(kea_def->is_limited /* XXX OR cert is signing only */
8969 && kea_def->exchKeyType == kt_rsa
8970 && ss->stepDownKeyPair != NULL);
8971 if (!kea_def->is_limited ||
8972 kea_def->exchKeyType != kt_rsa ||
8973 ss->stepDownKeyPair == NULL) {
8974 /* shouldn't happen, don't use step down if it does */
8977 serverKeyPair = ss->stepDownKeyPair;
8978 ss->sec.keaKeyBits = EXPORT_RSA_KEY_LENGTH * BPB;
8981 #ifdef NSS_ENABLE_ECC
8982 /* XXX Using SSLKEAType to index server certifiates
8983 * does not work for (EC)DHE ciphers. Until we have
8984 * an indexing mechanism general enough for all key
8985 * exchange algorithms, we'll need to deal with each
8988 if ((kea_def->kea == kea_ecdhe_rsa) ||
8989 (kea_def->kea == kea_ecdhe_ecdsa)) {
8990 if (ss->ephemeralECDHKeyPair != NULL) {
8991 serverKeyPair = ss->ephemeralECDHKeyPair;
8992 if (serverKeyPair->pubKey) {
8993 ss->sec.keaKeyBits =
8994 SECKEY_PublicKeyStrengthInBits(serverKeyPair->pubKey);
9000 sslServerCerts * sc = ss->serverCerts + kea_def->exchKeyType;
9001 serverKeyPair = sc->serverKeyPair;
9002 ss->sec.keaKeyBits = sc->serverKeyBits;
9005 if (serverKeyPair) {
9006 serverKey = serverKeyPair->privKey;
9009 if (serverKey == NULL) {
9011 PORT_SetError(SSL_ERROR_NO_SERVER_KEY_FOR_ALG);
9015 ss->sec.keaType = kea_def->exchKeyType;
9017 switch (kea_def->exchKeyType) {
9019 rv = ssl3_HandleRSAClientKeyExchange(ss, b, length, serverKey);
9020 if (rv != SECSuccess) {
9022 return SECFailure; /* error code set */
9027 #ifdef NSS_ENABLE_ECC
9029 /* XXX We really ought to be able to store multiple
9030 * EC certs (a requirement if we wish to support both
9031 * ECDH-RSA and ECDH-ECDSA key exchanges concurrently).
9032 * When we make that change, we'll need an index other
9033 * than kt_ecdh to pick the right EC certificate.
9035 if (serverKeyPair) {
9036 serverPubKey = serverKeyPair->pubKey;
9038 if (serverPubKey == NULL) {
9039 /* XXX Is this the right error code? */
9040 PORT_SetError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
9043 rv = ssl3_HandleECDHClientKeyExchange(ss, b, length,
9044 serverPubKey, serverKey);
9045 if (rv != SECSuccess) {
9046 return SECFailure; /* error code set */
9049 #endif /* NSS_ENABLE_ECC */
9052 (void) ssl3_HandshakeFailure(ss);
9053 PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
9056 ss->ssl3.hs.ws = ss->sec.peerCert ? wait_cert_verify : wait_change_cipher;
9061 /* This is TLS's equivalent of sending a no_certificate alert. */
9063 ssl3_SendEmptyCertificate(sslSocket *ss)
9067 rv = ssl3_AppendHandshakeHeader(ss, certificate, 3);
9068 if (rv == SECSuccess) {
9069 rv = ssl3_AppendHandshakeNumber(ss, 0, 3);
9071 return rv; /* error, if any, set by functions called above. */
9075 ssl3_HandleNewSessionTicket(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
9078 NewSessionTicket session_ticket;
9080 SSL_TRC(3, ("%d: SSL3[%d]: handle session_ticket handshake",
9081 SSL_GETPID(), ss->fd));
9083 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
9084 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
9086 if (ss->ssl3.hs.ws != wait_new_session_ticket) {
9087 SSL3_SendAlert(ss, alert_fatal, unexpected_message);
9088 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET);
9092 session_ticket.received_timestamp = ssl_Time();
9094 (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
9095 PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
9098 session_ticket.ticket_lifetime_hint =
9099 (PRUint32)ssl3_ConsumeHandshakeNumber(ss, 4, &b, &length);
9101 rv = ssl3_ConsumeHandshakeVariable(ss, &session_ticket.ticket, 2,
9103 if (length != 0 || rv != SECSuccess) {
9104 (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
9105 PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
9106 return SECFailure; /* malformed */
9109 rv = ssl3_SetSIDSessionTicket(ss->sec.ci.sid, &session_ticket);
9110 if (rv != SECSuccess) {
9111 (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure);
9112 PORT_SetError(SSL_ERROR_INTERNAL_ERROR_ALERT);
9115 ss->ssl3.hs.ws = wait_change_cipher;
9120 static PRInt32 connNum = 0;
9123 get_fake_cert(SECItem *pCertItem, int *pIndex)
9129 const char *extension;
9131 PRInt32 numBytes = 0;
9136 pCertItem->data = 0;
9137 if ((testdir = PR_GetEnv("NISCC_TEST")) == NULL) {
9140 *pIndex = (NULL != strstr(testdir, "root"));
9141 extension = (strstr(testdir, "simple") ? "" : ".der");
9142 fileNum = PR_ATOMIC_INCREMENT(&connNum) - 1;
9143 if ((startat = PR_GetEnv("START_AT")) != NULL) {
9144 fileNum += atoi(startat);
9146 if ((stopat = PR_GetEnv("STOP_AT")) != NULL &&
9147 fileNum >= atoi(stopat)) {
9151 sprintf(cfn, "%s/%08d%s", testdir, fileNum, extension);
9152 cf = PR_Open(cfn, PR_RDONLY, 0);
9156 prStatus = PR_GetOpenFileInfo(cf, &info);
9157 if (prStatus != PR_SUCCESS) {
9161 pCertItem = SECITEM_AllocItem(NULL, pCertItem, info.size);
9163 numBytes = PR_Read(cf, pCertItem->data, info.size);
9166 if (numBytes != info.size) {
9167 SECITEM_FreeItem(pCertItem, PR_FALSE);
9168 PORT_SetError(SEC_ERROR_IO);
9171 fprintf(stderr, "using %s\n", cfn);
9175 fprintf(stderr, "failed to use %s\n", cfn);
9182 * Used by both client and server.
9183 * Called from HandleServerHelloDone and from SendServerHelloSequence.
9186 ssl3_SendCertificate(sslSocket *ss)
9189 CERTCertificateList *certChain;
9192 SSL3KEAType certIndex;
9198 SSL_TRC(3, ("%d: SSL3[%d]: send certificate handshake",
9199 SSL_GETPID(), ss->fd));
9201 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
9202 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
9204 if (ss->sec.localCert)
9205 CERT_DestroyCertificate(ss->sec.localCert);
9206 if (ss->sec.isServer) {
9207 sslServerCerts * sc = NULL;
9209 /* XXX SSLKEAType isn't really a good choice for
9210 * indexing certificates (it breaks when we deal
9211 * with (EC)DHE-* cipher suites. This hack ensures
9212 * the RSA cert is picked for (EC)DHE-RSA.
9213 * Revisit this when we add server side support
9214 * for ECDHE-ECDSA or client-side authentication
9215 * using EC certificates.
9217 if ((ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) ||
9218 (ss->ssl3.hs.kea_def->kea == kea_dhe_rsa)) {
9221 certIndex = ss->ssl3.hs.kea_def->exchKeyType;
9223 sc = ss->serverCerts + certIndex;
9224 certChain = sc->serverCertChain;
9225 ss->sec.authKeyBits = sc->serverKeyBits;
9226 ss->sec.authAlgorithm = ss->ssl3.hs.kea_def->signKeyType;
9227 ss->sec.localCert = CERT_DupCertificate(sc->serverCert);
9229 certChain = ss->ssl3.clientCertChain;
9230 ss->sec.localCert = CERT_DupCertificate(ss->ssl3.clientCertificate);
9234 rv = get_fake_cert(&fakeCert, &ndex);
9238 for (i = 0; i < certChain->len; i++) {
9240 if (fakeCert.len > 0 && i == ndex) {
9241 len += fakeCert.len + 3;
9243 len += certChain->certs[i].len + 3;
9246 len += certChain->certs[i].len + 3;
9251 rv = ssl3_AppendHandshakeHeader(ss, certificate, len + 3);
9252 if (rv != SECSuccess) {
9253 return rv; /* err set by AppendHandshake. */
9255 rv = ssl3_AppendHandshakeNumber(ss, len, 3);
9256 if (rv != SECSuccess) {
9257 return rv; /* err set by AppendHandshake. */
9260 for (i = 0; i < certChain->len; i++) {
9262 if (fakeCert.len > 0 && i == ndex) {
9263 rv = ssl3_AppendHandshakeVariable(ss, fakeCert.data,
9265 SECITEM_FreeItem(&fakeCert, PR_FALSE);
9267 rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data,
9268 certChain->certs[i].len, 3);
9271 rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data,
9272 certChain->certs[i].len, 3);
9274 if (rv != SECSuccess) {
9275 return rv; /* err set by AppendHandshake. */
9284 * Used by server only.
9285 * single-stapling, send only a single cert status
9288 ssl3_SendCertificateStatus(sslSocket *ss)
9292 SECItemArray *statusToSend = NULL;
9293 SSL3KEAType certIndex;
9295 SSL_TRC(3, ("%d: SSL3[%d]: send certificate status handshake",
9296 SSL_GETPID(), ss->fd));
9298 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
9299 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
9300 PORT_Assert( ss->sec.isServer);
9302 if (!ssl3_ExtensionNegotiated(ss, ssl_cert_status_xtn))
9305 /* Use certStatus based on the cert being used. */
9306 if ((ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) ||
9307 (ss->ssl3.hs.kea_def->kea == kea_dhe_rsa)) {
9310 certIndex = ss->ssl3.hs.kea_def->exchKeyType;
9312 if (ss->certStatusArray[certIndex] && ss->certStatusArray[certIndex]->len) {
9313 statusToSend = ss->certStatusArray[certIndex];
9318 /* Use the array's first item only (single stapling) */
9319 len = 1 + statusToSend->items[0].len + 3;
9321 rv = ssl3_AppendHandshakeHeader(ss, certificate_status, len);
9322 if (rv != SECSuccess) {
9323 return rv; /* err set by AppendHandshake. */
9325 rv = ssl3_AppendHandshakeNumber(ss, 1 /*ocsp*/, 1);
9326 if (rv != SECSuccess)
9327 return rv; /* err set by AppendHandshake. */
9329 rv = ssl3_AppendHandshakeVariable(ss,
9330 statusToSend->items[0].data,
9331 statusToSend->items[0].len,
9333 if (rv != SECSuccess)
9334 return rv; /* err set by AppendHandshake. */
9339 /* This is used to delete the CA certificates in the peer certificate chain
9340 * from the cert database after they've been validated.
9343 ssl3_CleanupPeerCerts(sslSocket *ss)
9345 PLArenaPool * arena = ss->ssl3.peerCertArena;
9346 ssl3CertNode *certs = (ssl3CertNode *)ss->ssl3.peerCertChain;
9348 for (; certs; certs = certs->next) {
9349 CERT_DestroyCertificate(certs->cert);
9351 if (arena) PORT_FreeArena(arena, PR_FALSE);
9352 ss->ssl3.peerCertArena = NULL;
9353 ss->ssl3.peerCertChain = NULL;
9356 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
9357 * ssl3 CertificateStatus message.
9358 * Caller must hold Handshake and RecvBuf locks.
9359 * This is always called before ssl3_HandleCertificate, even if the Certificate
9360 * message is sent first.
9363 ssl3_HandleCertificateStatus(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
9365 PRInt32 status, len;
9367 if (ss->ssl3.hs.ws != wait_certificate_status) {
9368 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
9369 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_STATUS);
9373 PORT_Assert(!ss->sec.isServer);
9375 /* Consume the CertificateStatusType enum */
9376 status = ssl3_ConsumeHandshakeNumber(ss, 1, &b, &length);
9377 if (status != 1 /* ocsp */) {
9381 len = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length);
9382 if (len != length) {
9386 #define MAX_CERTSTATUS_LEN 0x1ffff /* 128k - 1 */
9387 if (length > MAX_CERTSTATUS_LEN)
9389 #undef MAX_CERTSTATUS_LEN
9391 /* Array size 1, because we currently implement single-stapling only */
9392 SECITEM_AllocArray(NULL, &ss->sec.ci.sid->peerCertStatus, 1);
9393 if (!ss->sec.ci.sid->peerCertStatus.items)
9396 ss->sec.ci.sid->peerCertStatus.items[0].data = PORT_Alloc(length);
9398 if (!ss->sec.ci.sid->peerCertStatus.items[0].data) {
9399 SECITEM_FreeArray(&ss->sec.ci.sid->peerCertStatus, PR_FALSE);
9403 PORT_Memcpy(ss->sec.ci.sid->peerCertStatus.items[0].data, b, length);
9404 ss->sec.ci.sid->peerCertStatus.items[0].len = length;
9405 ss->sec.ci.sid->peerCertStatus.items[0].type = siBuffer;
9407 return ssl3_AuthCertificate(ss);
9410 return ssl3_DecodeError(ss);
9413 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
9414 * ssl3 Certificate message.
9415 * Caller must hold Handshake and RecvBuf locks.
9418 ssl3_HandleCertificate(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
9421 ssl3CertNode * lastCert = NULL;
9422 PRInt32 remaining = 0;
9425 PRBool isServer = (PRBool)(!!ss->sec.isServer);
9427 SSL3AlertDescription desc;
9428 int errCode = SSL_ERROR_RX_MALFORMED_CERTIFICATE;
9431 SSL_TRC(3, ("%d: SSL3[%d]: handle certificate handshake",
9432 SSL_GETPID(), ss->fd));
9433 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
9434 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
9436 if ((ss->ssl3.hs.ws != wait_server_cert) &&
9437 (ss->ssl3.hs.ws != wait_client_cert)) {
9438 desc = unexpected_message;
9439 errCode = SSL_ERROR_RX_UNEXPECTED_CERTIFICATE;
9443 if (ss->sec.peerCert != NULL) {
9444 if (ss->sec.peerKey) {
9445 SECKEY_DestroyPublicKey(ss->sec.peerKey);
9446 ss->sec.peerKey = NULL;
9448 CERT_DestroyCertificate(ss->sec.peerCert);
9449 ss->sec.peerCert = NULL;
9452 ssl3_CleanupPeerCerts(ss);
9453 isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
9455 /* It is reported that some TLS client sends a Certificate message
9456 ** with a zero-length message body. We'll treat that case like a
9457 ** normal no_certificates message to maximize interoperability.
9460 remaining = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length);
9462 goto loser; /* fatal alert already sent by ConsumeHandshake. */
9463 if ((PRUint32)remaining > length)
9468 if (!(isTLS && isServer)) {
9469 desc = bad_certificate;
9472 /* This is TLS's version of a no_certificate alert. */
9473 /* I'm a server. I've requested a client cert. He hasn't got one. */
9474 rv = ssl3_HandleNoCertificate(ss);
9475 if (rv != SECSuccess) {
9476 errCode = PORT_GetError();
9479 ss->ssl3.hs.ws = wait_client_key;
9483 ss->ssl3.peerCertArena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
9484 if (ss->ssl3.peerCertArena == NULL) {
9485 goto loser; /* don't send alerts on memory errors */
9488 /* First get the peer cert. */
9493 size = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length);
9495 goto loser; /* fatal alert already sent by ConsumeHandshake. */
9497 if (remaining < size)
9501 certItem.len = size;
9506 ss->sec.peerCert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL,
9508 if (ss->sec.peerCert == NULL) {
9509 /* We should report an alert if the cert was bad, but not if the
9510 * problem was just some local problem, like memory error.
9515 /* Now get all of the CA certs. */
9516 while (remaining > 0) {
9521 size = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length);
9523 goto loser; /* fatal alert already sent by ConsumeHandshake. */
9525 if (remaining < size)
9529 certItem.len = size;
9534 c = PORT_ArenaNew(ss->ssl3.peerCertArena, ssl3CertNode);
9536 goto loser; /* don't send alerts on memory errors */
9539 c->cert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL,
9541 if (c->cert == NULL) {
9549 ss->ssl3.peerCertChain = c;
9557 SECKEY_UpdateCertPQG(ss->sec.peerCert);
9559 if (!isServer && ssl3_ExtensionNegotiated(ss, ssl_cert_status_xtn)) {
9560 ss->ssl3.hs.ws = wait_certificate_status;
9563 rv = ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */
9569 errCode = PORT_GetError();
9571 case PR_OUT_OF_MEMORY_ERROR:
9572 case SEC_ERROR_BAD_DATABASE:
9573 case SEC_ERROR_NO_MEMORY:
9575 desc = internal_error;
9580 ssl3_SendAlertForCertError(ss, errCode);
9584 desc = isTLS ? decode_error : bad_certificate;
9587 (void)SSL3_SendAlert(ss, alert_fatal, desc);
9590 (void)ssl_MapLowLevelError(errCode);
9595 ssl3_AuthCertificate(sslSocket *ss)
9598 PRBool isServer = (PRBool)(!!ss->sec.isServer);
9601 ss->ssl3.hs.authCertificatePending = PR_FALSE;
9604 * Ask caller-supplied callback function to validate cert chain.
9606 rv = (SECStatus)(*ss->authCertificate)(ss->authCertificateArg, ss->fd,
9609 errCode = PORT_GetError();
9610 if (rv != SECWouldBlock) {
9611 if (ss->handleBadCert) {
9612 rv = (*ss->handleBadCert)(ss->badCertArg, ss->fd);
9616 if (rv == SECWouldBlock) {
9617 if (ss->sec.isServer) {
9618 errCode = SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS;
9623 ss->ssl3.hs.authCertificatePending = PR_TRUE;
9626 /* XXX: Async cert validation and False Start don't work together
9627 * safely yet; if we leave False Start enabled, we may end up false
9628 * starting (sending application data) before we
9629 * SSL_AuthCertificateComplete has been called.
9631 ss->opt.enableFalseStart = PR_FALSE;
9634 if (rv != SECSuccess) {
9635 ssl3_SendAlertForCertError(ss, errCode);
9640 ss->sec.ci.sid->peerCert = CERT_DupCertificate(ss->sec.peerCert);
9642 if (!ss->sec.isServer) {
9643 CERTCertificate *cert = ss->sec.peerCert;
9645 /* set the server authentication and key exchange types and sizes
9646 ** from the value in the cert. If the key exchange key is different,
9647 ** it will get fixed when we handle the server key exchange message.
9649 SECKEYPublicKey * pubKey = CERT_ExtractPublicKey(cert);
9650 ss->sec.authAlgorithm = ss->ssl3.hs.kea_def->signKeyType;
9651 ss->sec.keaType = ss->ssl3.hs.kea_def->exchKeyType;
9653 ss->sec.keaKeyBits = ss->sec.authKeyBits =
9654 SECKEY_PublicKeyStrengthInBits(pubKey);
9655 #ifdef NSS_ENABLE_ECC
9656 if (ss->sec.keaType == kt_ecdh) {
9657 /* Get authKeyBits from signing key.
9658 * XXX The code below uses a quick approximation of
9659 * key size based on cert->signatureWrap.signature.data
9660 * (which contains the DER encoded signature). The field
9661 * cert->signatureWrap.signature.len contains the
9662 * length of the encoded signature in bits.
9664 if (ss->ssl3.hs.kea_def->kea == kea_ecdh_ecdsa) {
9665 ss->sec.authKeyBits =
9666 cert->signatureWrap.signature.data[3]*8;
9667 if (cert->signatureWrap.signature.data[4] == 0x00)
9668 ss->sec.authKeyBits -= 8;
9670 * XXX: if cert is not signed by ecdsa we should
9671 * destroy pubKey and goto bad_cert
9673 } else if (ss->ssl3.hs.kea_def->kea == kea_ecdh_rsa) {
9674 ss->sec.authKeyBits = cert->signatureWrap.signature.len;
9676 * XXX: if cert is not signed by rsa we should
9677 * destroy pubKey and goto bad_cert
9681 #endif /* NSS_ENABLE_ECC */
9682 SECKEY_DestroyPublicKey(pubKey);
9686 ss->ssl3.hs.ws = wait_cert_request; /* disallow server_key_exchange */
9687 if (ss->ssl3.hs.kea_def->is_limited ||
9688 /* XXX OR server cert is signing only. */
9689 #ifdef NSS_ENABLE_ECC
9690 ss->ssl3.hs.kea_def->kea == kea_ecdhe_ecdsa ||
9691 ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa ||
9692 #endif /* NSS_ENABLE_ECC */
9693 ss->ssl3.hs.kea_def->exchKeyType == kt_dh) {
9694 ss->ssl3.hs.ws = wait_server_key; /* allow server_key_exchange */
9697 ss->ssl3.hs.ws = wait_client_key;
9700 PORT_Assert(rv == SECSuccess);
9701 if (rv != SECSuccess) {
9702 errCode = SEC_ERROR_LIBRARY_FAILURE;
9710 (void)ssl_MapLowLevelError(errCode);
9714 static SECStatus ssl3_FinishHandshake(sslSocket *ss);
9717 ssl3_AlwaysFail(sslSocket * ss)
9719 PORT_SetError(PR_INVALID_STATE_ERROR);
9723 /* Caller must hold 1stHandshakeLock.
9726 ssl3_AuthCertificateComplete(sslSocket *ss, PRErrorCode error)
9730 PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss));
9732 if (ss->sec.isServer) {
9733 PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS);
9737 ssl_GetRecvBufLock(ss);
9738 ssl_GetSSL3HandshakeLock(ss);
9740 if (!ss->ssl3.hs.authCertificatePending) {
9741 PORT_SetError(PR_INVALID_STATE_ERROR);
9746 ss->ssl3.hs.authCertificatePending = PR_FALSE;
9749 ss->ssl3.hs.restartTarget = ssl3_AlwaysFail;
9750 ssl3_SendAlertForCertError(ss, error);
9752 } else if (ss->ssl3.hs.restartTarget != NULL) {
9753 sslRestartTarget target = ss->ssl3.hs.restartTarget;
9754 ss->ssl3.hs.restartTarget = NULL;
9756 /* Even if we blocked here, we have accomplished enough to claim
9757 * success. Any remaining work will be taken care of by subsequent
9758 * calls to SSL_ForceHandshake/PR_Send/PR_Read/etc.
9760 if (rv == SECWouldBlock) {
9768 ssl_ReleaseSSL3HandshakeLock(ss);
9769 ssl_ReleaseRecvBufLock(ss);
9775 ssl3_ComputeTLSFinished(ssl3CipherSpec *spec,
9777 const SSL3Hashes * hashes,
9778 TLSFinished * tlsFinished)
9784 label = isServer ? "server finished" : "client finished";
9787 rv = ssl3_TLSPRFWithMasterSecret(spec, label, len, hashes->u.raw,
9788 hashes->len, tlsFinished->verify_data,
9789 sizeof tlsFinished->verify_data);
9794 /* The calling function must acquire and release the appropriate
9795 * lock (e.g., ssl_GetSpecReadLock / ssl_ReleaseSpecReadLock for
9799 ssl3_TLSPRFWithMasterSecret(ssl3CipherSpec *spec, const char *label,
9800 unsigned int labelLen, const unsigned char *val, unsigned int valLen,
9801 unsigned char *out, unsigned int outLen)
9803 SECStatus rv = SECSuccess;
9805 if (spec->master_secret && !spec->bypassCiphers) {
9806 SECItem param = {siBuffer, NULL, 0};
9807 CK_MECHANISM_TYPE mech = CKM_TLS_PRF_GENERAL;
9808 PK11Context *prf_context;
9809 unsigned int retLen;
9811 if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
9812 mech = CKM_NSS_TLS_PRF_GENERAL_SHA256;
9814 prf_context = PK11_CreateContextBySymKey(mech, CKA_SIGN,
9815 spec->master_secret, ¶m);
9819 rv = PK11_DigestBegin(prf_context);
9820 rv |= PK11_DigestOp(prf_context, (unsigned char *) label, labelLen);
9821 rv |= PK11_DigestOp(prf_context, val, valLen);
9822 rv |= PK11_DigestFinal(prf_context, out, &retLen, outLen);
9823 PORT_Assert(rv != SECSuccess || retLen == outLen);
9825 PK11_DestroyContext(prf_context, PR_TRUE);
9828 #ifdef NO_PKCS11_BYPASS
9829 PORT_Assert(spec->master_secret);
9830 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
9833 SECItem inData = { siBuffer, };
9834 SECItem outData = { siBuffer, };
9835 PRBool isFIPS = PR_FALSE;
9837 inData.data = (unsigned char *) val;
9838 inData.len = valLen;
9840 outData.len = outLen;
9841 if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
9842 rv = TLS_P_hash(HASH_AlgSHA256, &spec->msItem, label, &inData,
9845 rv = TLS_PRF(&spec->msItem, label, &inData, &outData, isFIPS);
9847 PORT_Assert(rv != SECSuccess || outData.len == outLen);
9853 /* called from ssl3_HandleServerHelloDone
9856 ssl3_SendNextProto(sslSocket *ss)
9860 static const unsigned char padding[32] = {0};
9862 if (ss->ssl3.nextProto.len == 0)
9865 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
9866 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
9868 padding_len = 32 - ((ss->ssl3.nextProto.len + 2) % 32);
9870 rv = ssl3_AppendHandshakeHeader(ss, next_proto, ss->ssl3.nextProto.len +
9872 if (rv != SECSuccess) {
9873 return rv; /* error code set by AppendHandshakeHeader */
9875 rv = ssl3_AppendHandshakeVariable(ss, ss->ssl3.nextProto.data,
9876 ss->ssl3.nextProto.len, 1);
9877 if (rv != SECSuccess) {
9878 return rv; /* error code set by AppendHandshake */
9880 rv = ssl3_AppendHandshakeVariable(ss, padding, padding_len, 1);
9881 if (rv != SECSuccess) {
9882 return rv; /* error code set by AppendHandshake */
9887 /* called from ssl3_SendFinished
9889 * This function is simply a debugging aid and therefore does not return a
9892 ssl3_RecordKeyLog(sslSocket *ss)
9896 char buf[14 /* "CLIENT_RANDOM " */ +
9897 SSL3_RANDOM_LENGTH*2 /* client_random */ +
9899 48*2 /* master secret */ +
9903 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
9905 if (!ssl_keylog_iob)
9908 rv = PK11_ExtractKeyValue(ss->ssl3.cwSpec->master_secret);
9909 if (rv != SECSuccess)
9912 ssl_GetSpecReadLock(ss);
9914 /* keyData does not need to be freed. */
9915 keyData = PK11_GetKeyData(ss->ssl3.cwSpec->master_secret);
9916 if (!keyData || !keyData->data || keyData->len != 48) {
9917 ssl_ReleaseSpecReadLock(ss);
9921 /* https://developer.mozilla.org/en/NSS_Key_Log_Format */
9923 /* There could be multiple, concurrent writers to the
9924 * keylog, so we have to do everything in a single call to
9927 memcpy(buf, "CLIENT_RANDOM ", 14);
9929 hexEncode(buf + j, ss->ssl3.hs.client_random.rand, SSL3_RANDOM_LENGTH);
9930 j += SSL3_RANDOM_LENGTH*2;
9932 hexEncode(buf + j, keyData->data, 48);
9936 PORT_Assert(j == sizeof(buf));
9938 ssl_ReleaseSpecReadLock(ss);
9940 if (fwrite(buf, sizeof(buf), 1, ssl_keylog_iob) != 1)
9942 fflush(ssl_keylog_iob);
9946 /* called from ssl3_HandleServerHelloDone
9947 * ssl3_HandleClientHello
9948 * ssl3_HandleFinished
9951 ssl3_SendFinished(sslSocket *ss, PRInt32 flags)
9953 ssl3CipherSpec *cwSpec;
9955 PRBool isServer = ss->sec.isServer;
9957 SSL3Sender sender = isServer ? sender_server : sender_client;
9959 TLSFinished tlsFinished;
9961 SSL_TRC(3, ("%d: SSL3[%d]: send finished handshake", SSL_GETPID(), ss->fd));
9963 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
9964 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
9966 ssl_GetSpecReadLock(ss);
9967 cwSpec = ss->ssl3.cwSpec;
9968 isTLS = (PRBool)(cwSpec->version > SSL_LIBRARY_VERSION_3_0);
9969 rv = ssl3_ComputeHandshakeHashes(ss, cwSpec, &hashes, sender);
9970 if (isTLS && rv == SECSuccess) {
9971 rv = ssl3_ComputeTLSFinished(cwSpec, isServer, &hashes, &tlsFinished);
9973 ssl_ReleaseSpecReadLock(ss);
9974 if (rv != SECSuccess) {
9975 goto fail; /* err code was set by ssl3_ComputeHandshakeHashes */
9980 ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished;
9982 ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished;
9983 ss->ssl3.hs.finishedBytes = sizeof tlsFinished;
9984 rv = ssl3_AppendHandshakeHeader(ss, finished, sizeof tlsFinished);
9985 if (rv != SECSuccess)
9986 goto fail; /* err set by AppendHandshake. */
9987 rv = ssl3_AppendHandshake(ss, &tlsFinished, sizeof tlsFinished);
9988 if (rv != SECSuccess)
9989 goto fail; /* err set by AppendHandshake. */
9992 ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes.u.s;
9994 ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes.u.s;
9995 PORT_Assert(hashes.len == sizeof hashes.u.s);
9996 ss->ssl3.hs.finishedBytes = sizeof hashes.u.s;
9997 rv = ssl3_AppendHandshakeHeader(ss, finished, sizeof hashes.u.s);
9998 if (rv != SECSuccess)
9999 goto fail; /* err set by AppendHandshake. */
10000 rv = ssl3_AppendHandshake(ss, &hashes.u.s, sizeof hashes.u.s);
10001 if (rv != SECSuccess)
10002 goto fail; /* err set by AppendHandshake. */
10004 rv = ssl3_FlushHandshake(ss, flags);
10005 if (rv != SECSuccess) {
10006 goto fail; /* error code set by ssl3_FlushHandshake */
10009 ssl3_RecordKeyLog(ss);
10017 /* wrap the master secret, and put it into the SID.
10018 * Caller holds the Spec read lock.
10021 ssl3_CacheWrappedMasterSecret(sslSocket *ss, sslSessionID *sid,
10022 ssl3CipherSpec *spec, SSL3KEAType effectiveExchKeyType)
10024 PK11SymKey * wrappingKey = NULL;
10025 PK11SlotInfo * symKeySlot;
10026 void * pwArg = ss->pkcs11PinArg;
10027 SECStatus rv = SECFailure;
10028 PRBool isServer = ss->sec.isServer;
10029 CK_MECHANISM_TYPE mechanism = CKM_INVALID_MECHANISM;
10030 symKeySlot = PK11_GetSlotFromKey(spec->master_secret);
10035 /* these next few functions are mere accessors and don't fail. */
10036 sid->u.ssl3.masterWrapIndex = wrapKeyIndex =
10037 PK11_GetCurrentWrapIndex(symKeySlot);
10038 PORT_Assert(wrapKeyIndex == 0); /* array has only one entry! */
10040 sid->u.ssl3.masterWrapSeries = incarnation =
10041 PK11_GetSlotSeries(symKeySlot);
10042 sid->u.ssl3.masterSlotID = PK11_GetSlotID(symKeySlot);
10043 sid->u.ssl3.masterModuleID = PK11_GetModuleID(symKeySlot);
10044 sid->u.ssl3.masterValid = PR_TRUE;
10045 /* Get the default wrapping key, for wrapping the master secret before
10046 * placing it in the SID cache entry. */
10047 wrappingKey = PK11_GetWrapKey(symKeySlot, wrapKeyIndex,
10048 CKM_INVALID_MECHANISM, incarnation,
10051 mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */
10054 /* if the wrappingKey doesn't exist, attempt to create it.
10055 * Note: we intentionally ignore errors here. If we cannot
10056 * generate a wrapping key, it is not fatal to this SSL connection,
10057 * but we will not be able to restart this session.
10059 mechanism = PK11_GetBestWrapMechanism(symKeySlot);
10060 keyLength = PK11_GetBestKeyLength(symKeySlot, mechanism);
10061 /* Zero length means fixed key length algorithm, or error.
10064 wrappingKey = PK11_KeyGen(symKeySlot, mechanism, NULL,
10067 PK11_SetWrapKey(symKeySlot, wrapKeyIndex, wrappingKey);
10071 /* server socket using session cache. */
10072 mechanism = PK11_GetBestWrapMechanism(symKeySlot);
10073 if (mechanism != CKM_INVALID_MECHANISM) {
10075 getWrappingKey(ss, symKeySlot, effectiveExchKeyType,
10078 mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */
10083 sid->u.ssl3.masterWrapMech = mechanism;
10084 PK11_FreeSlot(symKeySlot);
10089 wmsItem.data = sid->u.ssl3.keys.wrapped_master_secret;
10090 wmsItem.len = sizeof sid->u.ssl3.keys.wrapped_master_secret;
10091 rv = PK11_WrapSymKey(mechanism, NULL, wrappingKey,
10092 spec->master_secret, &wmsItem);
10093 /* rv is examined below. */
10094 sid->u.ssl3.keys.wrapped_master_secret_len = wmsItem.len;
10095 PK11_FreeSymKey(wrappingKey);
10100 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
10101 * ssl3 Finished message from the peer.
10102 * Caller must hold Handshake and RecvBuf locks.
10105 ssl3_HandleFinished(sslSocket *ss, SSL3Opaque *b, PRUint32 length,
10106 const SSL3Hashes *hashes)
10108 sslSessionID * sid = ss->sec.ci.sid;
10109 SECStatus rv = SECSuccess;
10110 PRBool isServer = ss->sec.isServer;
10112 SSL3KEAType effectiveExchKeyType;
10114 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
10115 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
10117 SSL_TRC(3, ("%d: SSL3[%d]: handle finished handshake",
10118 SSL_GETPID(), ss->fd));
10120 if (ss->ssl3.hs.ws != wait_finished) {
10121 SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10122 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_FINISHED);
10126 isTLS = (PRBool)(ss->ssl3.crSpec->version > SSL_LIBRARY_VERSION_3_0);
10128 TLSFinished tlsFinished;
10130 if (length != sizeof tlsFinished) {
10131 (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
10132 PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED);
10135 rv = ssl3_ComputeTLSFinished(ss->ssl3.crSpec, !isServer,
10136 hashes, &tlsFinished);
10138 ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished;
10140 ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished;
10141 ss->ssl3.hs.finishedBytes = sizeof tlsFinished;
10142 if (rv != SECSuccess ||
10143 0 != NSS_SecureMemcmp(&tlsFinished, b, length)) {
10144 (void)SSL3_SendAlert(ss, alert_fatal, decrypt_error);
10145 PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
10149 if (length != sizeof(SSL3Finished)) {
10150 (void)ssl3_IllegalParameter(ss);
10151 PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED);
10156 ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes->u.s;
10158 ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes->u.s;
10159 PORT_Assert(hashes->len == sizeof hashes->u.s);
10160 ss->ssl3.hs.finishedBytes = sizeof hashes->u.s;
10161 if (0 != NSS_SecureMemcmp(&hashes->u.s, b, length)) {
10162 (void)ssl3_HandshakeFailure(ss);
10163 PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
10168 ssl_GetXmitBufLock(ss); /*************************************/
10170 if ((isServer && !ss->ssl3.hs.isResuming) ||
10171 (!isServer && ss->ssl3.hs.isResuming)) {
10174 /* Send a NewSessionTicket message if the client sent us
10175 * either an empty session ticket, or one that did not verify.
10176 * (Note that if either of these conditions was met, then the
10177 * server has sent a SessionTicket extension in the
10178 * ServerHello message.)
10180 if (isServer && !ss->ssl3.hs.isResuming &&
10181 ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn)) {
10182 rv = ssl3_SendNewSessionTicket(ss);
10183 if (rv != SECSuccess) {
10188 rv = ssl3_SendChangeCipherSpecs(ss);
10189 if (rv != SECSuccess) {
10190 goto xmit_loser; /* err is set. */
10192 /* If this thread is in SSL_SecureSend (trying to write some data)
10193 ** then set the ssl_SEND_FLAG_FORCE_INTO_BUFFER flag, so that the
10194 ** last two handshake messages (change cipher spec and finished)
10195 ** will be sent in the same send/write call as the application data.
10197 if (ss->writerThread == PR_GetCurrentThread()) {
10198 flags = ssl_SEND_FLAG_FORCE_INTO_BUFFER;
10201 if (!isServer && !ss->firstHsDone) {
10202 rv = ssl3_SendNextProto(ss);
10203 if (rv != SECSuccess) {
10204 goto xmit_loser; /* err code was set. */
10209 flags |= ssl_SEND_FLAG_NO_RETRANSMIT;
10212 rv = ssl3_SendFinished(ss, flags);
10213 if (rv != SECSuccess) {
10214 goto xmit_loser; /* err is set. */
10219 ssl_ReleaseXmitBufLock(ss); /*************************************/
10220 if (rv != SECSuccess) {
10224 ss->gs.writeOffset = 0;
10225 ss->gs.readOffset = 0;
10227 if (ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) {
10228 effectiveExchKeyType = kt_rsa;
10230 effectiveExchKeyType = ss->ssl3.hs.kea_def->exchKeyType;
10233 if (sid->cached == never_cached && !ss->opt.noCache && ss->sec.cache) {
10234 /* fill in the sid */
10235 sid->u.ssl3.cipherSuite = ss->ssl3.hs.cipher_suite;
10236 sid->u.ssl3.compression = ss->ssl3.hs.compression;
10237 sid->u.ssl3.policy = ss->ssl3.policy;
10238 #ifdef NSS_ENABLE_ECC
10239 sid->u.ssl3.negotiatedECCurves = ss->ssl3.hs.negotiatedECCurves;
10241 sid->u.ssl3.exchKeyType = effectiveExchKeyType;
10242 sid->version = ss->version;
10243 sid->authAlgorithm = ss->sec.authAlgorithm;
10244 sid->authKeyBits = ss->sec.authKeyBits;
10245 sid->keaType = ss->sec.keaType;
10246 sid->keaKeyBits = ss->sec.keaKeyBits;
10247 sid->lastAccessTime = sid->creationTime = ssl_Time();
10248 sid->expirationTime = sid->creationTime + ssl3_sid_timeout;
10249 sid->localCert = CERT_DupCertificate(ss->sec.localCert);
10251 ssl_GetSpecReadLock(ss); /*************************************/
10253 /* Copy the master secret (wrapped or unwrapped) into the sid */
10254 if (ss->ssl3.crSpec->msItem.len && ss->ssl3.crSpec->msItem.data) {
10255 sid->u.ssl3.keys.wrapped_master_secret_len =
10256 ss->ssl3.crSpec->msItem.len;
10257 memcpy(sid->u.ssl3.keys.wrapped_master_secret,
10258 ss->ssl3.crSpec->msItem.data, ss->ssl3.crSpec->msItem.len);
10259 sid->u.ssl3.masterValid = PR_TRUE;
10260 sid->u.ssl3.keys.msIsWrapped = PR_FALSE;
10263 rv = ssl3_CacheWrappedMasterSecret(ss, ss->sec.ci.sid,
10265 effectiveExchKeyType);
10266 sid->u.ssl3.keys.msIsWrapped = PR_TRUE;
10268 ssl_ReleaseSpecReadLock(ss); /*************************************/
10270 /* If the wrap failed, we don't cache the sid.
10271 * The connection continues normally however.
10273 ss->ssl3.hs.cacheSID = rv == SECSuccess;
10276 if (ss->ssl3.hs.authCertificatePending) {
10277 if (ss->ssl3.hs.restartTarget) {
10278 PR_NOT_REACHED("ssl3_HandleFinished: unexpected restartTarget");
10279 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
10283 ss->ssl3.hs.restartTarget = ssl3_FinishHandshake;
10284 return SECWouldBlock;
10287 rv = ssl3_FinishHandshake(ss);
10292 ssl3_FinishHandshake(sslSocket * ss)
10294 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
10295 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
10296 PORT_Assert( ss->ssl3.hs.restartTarget == NULL );
10298 /* The first handshake is now completed. */
10299 ss->handshake = NULL;
10300 ss->firstHsDone = PR_TRUE;
10302 if (ss->ssl3.hs.cacheSID) {
10303 (*ss->sec.cache)(ss->sec.ci.sid);
10304 ss->ssl3.hs.cacheSID = PR_FALSE;
10307 ss->ssl3.hs.ws = idle_handshake;
10309 /* Do the handshake callback for sslv3 here, if we cannot false start. */
10310 if (ss->handshakeCallback != NULL && !ssl3_CanFalseStart(ss)) {
10311 (ss->handshakeCallback)(ss->fd, ss->handshakeCallbackData);
10317 /* Called from ssl3_HandleHandshake() when it has gathered a complete ssl3
10318 * hanshake message.
10319 * Caller must hold Handshake and RecvBuf locks.
10322 ssl3_HandleHandshakeMessage(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
10324 SECStatus rv = SECSuccess;
10325 SSL3HandshakeType type = ss->ssl3.hs.msg_type;
10326 SSL3Hashes hashes; /* computed hashes are put here. */
10328 PRUint8 dtlsData[8];
10330 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
10331 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
10333 * We have to compute the hashes before we update them with the
10336 ssl_GetSpecReadLock(ss); /************************************/
10337 if((type == finished) || (type == certificate_verify)) {
10338 SSL3Sender sender = (SSL3Sender)0;
10339 ssl3CipherSpec *rSpec = ss->ssl3.prSpec;
10341 if (type == finished) {
10342 sender = ss->sec.isServer ? sender_client : sender_server;
10343 rSpec = ss->ssl3.crSpec;
10345 rv = ssl3_ComputeHandshakeHashes(ss, rSpec, &hashes, sender);
10347 ssl_ReleaseSpecReadLock(ss); /************************************/
10348 if (rv != SECSuccess) {
10349 return rv; /* error code was set by ssl3_ComputeHandshakeHashes*/
10351 SSL_TRC(30,("%d: SSL3[%d]: handle handshake message: %s", SSL_GETPID(),
10352 ss->fd, ssl3_DecodeHandshakeType(ss->ssl3.hs.msg_type)));
10354 hdr[0] = (PRUint8)ss->ssl3.hs.msg_type;
10355 hdr[1] = (PRUint8)(length >> 16);
10356 hdr[2] = (PRUint8)(length >> 8);
10357 hdr[3] = (PRUint8)(length );
10359 /* Start new handshake hashes when we start a new handshake */
10360 if (ss->ssl3.hs.msg_type == client_hello) {
10361 rv = ssl3_RestartHandshakeHashes(ss);
10362 if (rv != SECSuccess) {
10366 /* We should not include hello_request and hello_verify_request messages
10367 * in the handshake hashes */
10368 if ((ss->ssl3.hs.msg_type != hello_request) &&
10369 (ss->ssl3.hs.msg_type != hello_verify_request)) {
10370 rv = ssl3_UpdateHandshakeHashes(ss, (unsigned char*) hdr, 4);
10371 if (rv != SECSuccess) return rv; /* err code already set. */
10373 /* Extra data to simulate a complete DTLS handshake fragment */
10375 /* Sequence number */
10376 dtlsData[0] = MSB(ss->ssl3.hs.recvMessageSeq);
10377 dtlsData[1] = LSB(ss->ssl3.hs.recvMessageSeq);
10379 /* Fragment offset */
10384 /* Fragment length */
10385 dtlsData[5] = (PRUint8)(length >> 16);
10386 dtlsData[6] = (PRUint8)(length >> 8);
10387 dtlsData[7] = (PRUint8)(length );
10389 rv = ssl3_UpdateHandshakeHashes(ss, (unsigned char*) dtlsData,
10391 if (rv != SECSuccess) return rv; /* err code already set. */
10394 /* The message body */
10395 rv = ssl3_UpdateHandshakeHashes(ss, b, length);
10396 if (rv != SECSuccess) return rv; /* err code already set. */
10399 PORT_SetError(0); /* each message starts with no error. */
10401 if (ss->ssl3.hs.ws == wait_certificate_status &&
10402 ss->ssl3.hs.msg_type != certificate_status) {
10403 /* If we negotiated the certificate_status extension then we deferred
10404 * certificate validation until we get the CertificateStatus messsage.
10405 * But the CertificateStatus message is optional. If the server did
10406 * not send it then we need to validate the certificate now. If the
10407 * server does send the CertificateStatus message then we will
10408 * authenticate the certificate in ssl3_HandleCertificateStatus.
10410 rv = ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */
10411 PORT_Assert(rv != SECWouldBlock);
10412 if (rv != SECSuccess) {
10417 switch (ss->ssl3.hs.msg_type) {
10418 case hello_request:
10420 (void)ssl3_DecodeError(ss);
10421 PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_REQUEST);
10424 if (ss->sec.isServer) {
10425 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10426 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST);
10429 rv = ssl3_HandleHelloRequest(ss);
10432 if (!ss->sec.isServer) {
10433 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10434 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO);
10437 rv = ssl3_HandleClientHello(ss, b, length);
10440 if (ss->sec.isServer) {
10441 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10442 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO);
10445 rv = ssl3_HandleServerHello(ss, b, length);
10447 case hello_verify_request:
10448 if (!IS_DTLS(ss) || ss->sec.isServer) {
10449 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10450 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_VERIFY_REQUEST);
10453 rv = dtls_HandleHelloVerifyRequest(ss, b, length);
10456 rv = ssl3_HandleCertificate(ss, b, length);
10458 case certificate_status:
10459 rv = ssl3_HandleCertificateStatus(ss, b, length);
10461 case server_key_exchange:
10462 if (ss->sec.isServer) {
10463 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10464 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH);
10467 rv = ssl3_HandleServerKeyExchange(ss, b, length);
10469 case certificate_request:
10470 if (ss->sec.isServer) {
10471 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10472 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST);
10475 rv = ssl3_HandleCertificateRequest(ss, b, length);
10477 case server_hello_done:
10479 (void)ssl3_DecodeError(ss);
10480 PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_DONE);
10483 if (ss->sec.isServer) {
10484 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10485 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE);
10488 rv = ssl3_HandleServerHelloDone(ss);
10490 case certificate_verify:
10491 if (!ss->sec.isServer) {
10492 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10493 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY);
10496 rv = ssl3_HandleCertificateVerify(ss, b, length, &hashes);
10498 case client_key_exchange:
10499 if (!ss->sec.isServer) {
10500 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10501 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH);
10504 rv = ssl3_HandleClientKeyExchange(ss, b, length);
10506 case new_session_ticket:
10507 if (ss->sec.isServer) {
10508 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10509 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET);
10512 rv = ssl3_HandleNewSessionTicket(ss, b, length);
10515 rv = ssl3_HandleFinished(ss, b, length, &hashes);
10518 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10519 PORT_SetError(SSL_ERROR_RX_UNKNOWN_HANDSHAKE);
10523 if (IS_DTLS(ss) && (rv != SECFailure)) {
10524 /* Increment the expected sequence number */
10525 ss->ssl3.hs.recvMessageSeq++;
10531 /* Called only from ssl3_HandleRecord, for each (deciphered) ssl3 record.
10532 * origBuf is the decrypted ssl record content.
10533 * Caller must hold the handshake and RecvBuf locks.
10536 ssl3_HandleHandshake(sslSocket *ss, sslBuffer *origBuf)
10539 * There may be a partial handshake message already in the handshake
10540 * state. The incoming buffer may contain another portion, or a
10541 * complete message or several messages followed by another portion.
10543 * Each message is made contiguous before being passed to the actual
10546 sslBuffer *buf = &ss->ssl3.hs.msgState; /* do not lose the original buffer pointer */
10549 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
10550 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
10552 if (buf->buf == NULL) {
10555 while (buf->len > 0) {
10556 if (ss->ssl3.hs.header_bytes < 4) {
10560 if (ss->ssl3.hs.header_bytes++ == 0)
10561 ss->ssl3.hs.msg_type = (SSL3HandshakeType)t;
10563 ss->ssl3.hs.msg_len = (ss->ssl3.hs.msg_len << 8) + t;
10564 if (ss->ssl3.hs.header_bytes < 4)
10567 #define MAX_HANDSHAKE_MSG_LEN 0x1ffff /* 128k - 1 */
10568 if (ss->ssl3.hs.msg_len > MAX_HANDSHAKE_MSG_LEN) {
10569 (void)ssl3_DecodeError(ss);
10570 PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
10573 #undef MAX_HANDSHAKE_MSG_LEN
10575 /* If msg_len is zero, be sure we fall through,
10576 ** even if buf->len is zero.
10578 if (ss->ssl3.hs.msg_len > 0)
10583 * Header has been gathered and there is at least one byte of new
10584 * data available for this message. If it can be done right out
10585 * of the original buffer, then use it from there.
10587 if (ss->ssl3.hs.msg_body.len == 0 && buf->len >= ss->ssl3.hs.msg_len) {
10588 /* handle it from input buffer */
10589 rv = ssl3_HandleHandshakeMessage(ss, buf->buf, ss->ssl3.hs.msg_len);
10590 if (rv == SECFailure) {
10591 /* This test wants to fall through on either
10592 * SECSuccess or SECWouldBlock.
10593 * ssl3_HandleHandshakeMessage MUST set the error code.
10597 buf->buf += ss->ssl3.hs.msg_len;
10598 buf->len -= ss->ssl3.hs.msg_len;
10599 ss->ssl3.hs.msg_len = 0;
10600 ss->ssl3.hs.header_bytes = 0;
10601 if (rv != SECSuccess) { /* return if SECWouldBlock. */
10605 /* must be copied to msg_body and dealt with from there */
10606 unsigned int bytes;
10608 PORT_Assert(ss->ssl3.hs.msg_body.len < ss->ssl3.hs.msg_len);
10609 bytes = PR_MIN(buf->len, ss->ssl3.hs.msg_len - ss->ssl3.hs.msg_body.len);
10611 /* Grow the buffer if needed */
10612 rv = sslBuffer_Grow(&ss->ssl3.hs.msg_body, ss->ssl3.hs.msg_len);
10613 if (rv != SECSuccess) {
10614 /* sslBuffer_Grow has set a memory error code. */
10618 PORT_Memcpy(ss->ssl3.hs.msg_body.buf + ss->ssl3.hs.msg_body.len,
10620 ss->ssl3.hs.msg_body.len += bytes;
10624 PORT_Assert(ss->ssl3.hs.msg_body.len <= ss->ssl3.hs.msg_len);
10626 /* if we have a whole message, do it */
10627 if (ss->ssl3.hs.msg_body.len == ss->ssl3.hs.msg_len) {
10628 rv = ssl3_HandleHandshakeMessage(
10629 ss, ss->ssl3.hs.msg_body.buf, ss->ssl3.hs.msg_len);
10630 if (rv == SECFailure) {
10631 /* This test wants to fall through on either
10632 * SECSuccess or SECWouldBlock.
10633 * ssl3_HandleHandshakeMessage MUST set error code.
10637 ss->ssl3.hs.msg_body.len = 0;
10638 ss->ssl3.hs.msg_len = 0;
10639 ss->ssl3.hs.header_bytes = 0;
10640 if (rv != SECSuccess) { /* return if SECWouldBlock. */
10644 PORT_Assert(buf->len == 0);
10650 origBuf->len = 0; /* So ssl3_GatherAppDataRecord will keep looping. */
10651 buf->buf = NULL; /* not a leak. */
10655 /* These macros return the given value with the MSB copied to all the other
10656 * bits. They use the fact that arithmetic shift shifts-in the sign bit.
10657 * However, this is not ensured by the C standard so you may need to replace
10658 * them with something else for odd compilers. */
10659 #define DUPLICATE_MSB_TO_ALL(x) ( (unsigned)( (int)(x) >> (sizeof(int)*8-1) ) )
10660 #define DUPLICATE_MSB_TO_ALL_8(x) ((unsigned char)(DUPLICATE_MSB_TO_ALL(x)))
10662 /* SECStatusToMask returns, in constant time, a mask value of all ones if
10663 * rv == SECSuccess. Otherwise it returns zero. */
10664 static unsigned int
10665 SECStatusToMask(SECStatus rv)
10668 /* rv ^ SECSuccess is zero iff rv == SECSuccess. Subtracting one results
10669 * in the MSB being set to one iff it was zero before. */
10670 good = rv ^ SECSuccess;
10672 return DUPLICATE_MSB_TO_ALL(good);
10675 /* ssl_ConstantTimeGE returns 0xff if a>=b and 0x00 otherwise. */
10676 static unsigned char
10677 ssl_ConstantTimeGE(unsigned int a, unsigned int b)
10680 return DUPLICATE_MSB_TO_ALL(~a);
10683 /* ssl_ConstantTimeEQ8 returns 0xff if a==b and 0x00 otherwise. */
10684 static unsigned char
10685 ssl_ConstantTimeEQ8(unsigned char a, unsigned char b)
10687 unsigned int c = a ^ b;
10689 return DUPLICATE_MSB_TO_ALL_8(c);
10693 ssl_RemoveSSLv3CBCPadding(sslBuffer *plaintext,
10694 unsigned int blockSize,
10695 unsigned int macSize)
10697 unsigned int paddingLength, good, t;
10698 const unsigned int overhead = 1 /* padding length byte */ + macSize;
10700 /* These lengths are all public so we can test them in non-constant
10702 if (overhead > plaintext->len) {
10706 paddingLength = plaintext->buf[plaintext->len-1];
10707 /* SSLv3 padding bytes are random and cannot be checked. */
10708 t = plaintext->len;
10709 t -= paddingLength+overhead;
10710 /* If len >= paddingLength+overhead then the MSB of t is zero. */
10711 good = DUPLICATE_MSB_TO_ALL(~t);
10712 /* SSLv3 requires that the padding is minimal. */
10713 t = blockSize - (paddingLength+1);
10714 good &= DUPLICATE_MSB_TO_ALL(~t);
10715 plaintext->len -= good & (paddingLength+1);
10716 return (good & SECSuccess) | (~good & SECFailure);
10720 ssl_RemoveTLSCBCPadding(sslBuffer *plaintext, unsigned int macSize)
10722 unsigned int paddingLength, good, t, toCheck, i;
10723 const unsigned int overhead = 1 /* padding length byte */ + macSize;
10725 /* These lengths are all public so we can test them in non-constant
10727 if (overhead > plaintext->len) {
10731 paddingLength = plaintext->buf[plaintext->len-1];
10732 t = plaintext->len;
10733 t -= paddingLength+overhead;
10734 /* If len >= paddingLength+overhead then the MSB of t is zero. */
10735 good = DUPLICATE_MSB_TO_ALL(~t);
10737 /* The padding consists of a length byte at the end of the record and then
10738 * that many bytes of padding, all with the same value as the length byte.
10739 * Thus, with the length byte included, there are paddingLength+1 bytes of
10742 * We can't check just |paddingLength+1| bytes because that leaks
10743 * decrypted information. Therefore we always have to check the maximum
10744 * amount of padding possible. (Again, the length of the record is
10745 * public information so we can use it.) */
10746 toCheck = 255; /* maximum amount of padding. */
10747 if (toCheck > plaintext->len-1) {
10748 toCheck = plaintext->len-1;
10751 for (i = 0; i < toCheck; i++) {
10752 unsigned int t = paddingLength - i;
10753 /* If i <= paddingLength then the MSB of t is zero and mask is
10754 * 0xff. Otherwise, mask is 0. */
10755 unsigned char mask = DUPLICATE_MSB_TO_ALL(~t);
10756 unsigned char b = plaintext->buf[plaintext->len-1-i];
10757 /* The final |paddingLength+1| bytes should all have the value
10758 * |paddingLength|. Therefore the XOR should be zero. */
10759 good &= ~(mask&(paddingLength ^ b));
10762 /* If any of the final |paddingLength+1| bytes had the wrong value,
10763 * one or more of the lower eight bits of |good| will be cleared. We
10764 * AND the bottom 8 bits together and duplicate the result to all the
10769 good <<= sizeof(good)*8-1;
10770 good = DUPLICATE_MSB_TO_ALL(good);
10772 plaintext->len -= good & (paddingLength+1);
10773 return (good & SECSuccess) | (~good & SECFailure);
10777 * originalLength >= macSize
10778 * macSize <= MAX_MAC_LENGTH
10779 * plaintext->len >= macSize
10782 ssl_CBCExtractMAC(sslBuffer *plaintext,
10783 unsigned int originalLength,
10785 unsigned int macSize)
10787 unsigned char rotatedMac[MAX_MAC_LENGTH];
10788 /* macEnd is the index of |plaintext->buf| just after the end of the
10790 unsigned macEnd = plaintext->len;
10791 unsigned macStart = macEnd - macSize;
10792 /* scanStart contains the number of bytes that we can ignore because
10793 * the MAC's position can only vary by 255 bytes. */
10794 unsigned scanStart = 0;
10795 unsigned i, j, divSpoiler;
10796 unsigned char rotateOffset;
10798 if (originalLength > macSize + 255 + 1)
10799 scanStart = originalLength - (macSize + 255 + 1);
10801 /* divSpoiler contains a multiple of macSize that is used to cause the
10802 * modulo operation to be constant time. Without this, the time varies
10803 * based on the amount of padding when running on Intel chips at least.
10805 * The aim of right-shifting macSize is so that the compiler doesn't
10806 * figure out that it can remove divSpoiler as that would require it
10807 * to prove that macSize is always even, which I hope is beyond it. */
10808 divSpoiler = macSize >> 1;
10809 divSpoiler <<= (sizeof(divSpoiler)-1)*8;
10810 rotateOffset = (divSpoiler + macStart - scanStart) % macSize;
10812 memset(rotatedMac, 0, macSize);
10813 for (i = scanStart; i < originalLength;) {
10814 for (j = 0; j < macSize && i < originalLength; i++, j++) {
10815 unsigned char macStarted = ssl_ConstantTimeGE(i, macStart);
10816 unsigned char macEnded = ssl_ConstantTimeGE(i, macEnd);
10817 unsigned char b = 0;
10818 b = plaintext->buf[i];
10819 rotatedMac[j] |= b & macStarted & ~macEnded;
10823 /* Now rotate the MAC. If we knew that the MAC fit into a CPU cache line
10824 * we could line-align |rotatedMac| and rotate in place. */
10825 memset(out, 0, macSize);
10826 for (i = 0; i < macSize; i++) {
10827 unsigned char offset =
10828 (divSpoiler + macSize - rotateOffset + i) % macSize;
10829 for (j = 0; j < macSize; j++) {
10830 out[j] |= rotatedMac[i] & ssl_ConstantTimeEQ8(j, offset);
10835 /* if cText is non-null, then decipher, check MAC, and decompress the
10836 * SSL record from cText->buf (typically gs->inbuf)
10837 * into databuf (typically gs->buf), and any previous contents of databuf
10838 * is lost. Then handle databuf according to its SSL record type,
10839 * unless it's an application record.
10841 * If cText is NULL, then the ciphertext has previously been deciphered and
10842 * checked, and is already sitting in databuf. It is processed as an SSL
10843 * Handshake message.
10845 * DOES NOT process the decrypted/decompressed application data.
10846 * On return, databuf contains the decrypted/decompressed record.
10848 * Called from ssl3_GatherCompleteHandshake
10849 * ssl3_RestartHandshakeAfterCertReq
10851 * Caller must hold the RecvBufLock.
10853 * This function aquires and releases the SSL3Handshake Lock, holding the
10854 * lock around any calls to functions that handle records other than
10855 * Application Data records.
10858 ssl3_HandleRecord(sslSocket *ss, SSL3Ciphertext *cText, sslBuffer *databuf)
10860 const ssl3BulkCipherDef *cipher_def;
10861 ssl3CipherSpec * crSpec;
10863 unsigned int hashBytes = MAX_MAC_LENGTH + 1;
10865 SSL3ContentType rType;
10866 SSL3Opaque hash[MAX_MAC_LENGTH];
10867 SSL3Opaque givenHashBuf[MAX_MAC_LENGTH];
10868 SSL3Opaque *givenHash;
10869 sslBuffer *plaintext;
10870 sslBuffer temp_buf;
10871 PRUint64 dtls_seq_num;
10872 unsigned int ivLen = 0;
10873 unsigned int originalLen = 0;
10875 unsigned int minLength;
10876 unsigned char header[13];
10877 unsigned int headerLen;
10879 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
10881 if (!ss->ssl3.initialized) {
10882 ssl_GetSSL3HandshakeLock(ss);
10883 rv = ssl3_InitState(ss);
10884 ssl_ReleaseSSL3HandshakeLock(ss);
10885 if (rv != SECSuccess) {
10886 return rv; /* ssl3_InitState has set the error code. */
10890 /* check for Token Presence */
10891 if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) {
10892 PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
10896 /* cText is NULL when we're called from ssl3_RestartHandshakeAfterXXX().
10897 * This implies that databuf holds a previously deciphered SSL Handshake
10900 if (cText == NULL) {
10901 SSL_DBG(("%d: SSL3[%d]: HandleRecord, resuming handshake",
10902 SSL_GETPID(), ss->fd));
10903 rType = content_handshake;
10907 ssl_GetSpecReadLock(ss); /******************************************/
10909 crSpec = ss->ssl3.crSpec;
10910 cipher_def = crSpec->cipher_def;
10913 * DTLS relevance checks:
10914 * Note that this code currently ignores all out-of-epoch packets,
10915 * which means we lose some in the case of rehandshake +
10916 * loss/reordering. Since DTLS is explicitly unreliable, this
10917 * seems like a good tradeoff for implementation effort and is
10918 * consistent with the guidance of RFC 6347 Sections 4.1 and 4.2.4.1
10921 DTLSEpoch epoch = (cText->seq_num.high >> 16) & 0xffff;
10923 if (crSpec->epoch != epoch) {
10924 ssl_ReleaseSpecReadLock(ss);
10925 SSL_DBG(("%d: SSL3[%d]: HandleRecord, received packet "
10926 "from irrelevant epoch %d", SSL_GETPID(), ss->fd, epoch));
10927 /* Silently drop the packet */
10928 databuf->len = 0; /* Needed to ensure data not left around */
10932 dtls_seq_num = (((PRUint64)(cText->seq_num.high & 0xffff)) << 32) |
10933 ((PRUint64)cText->seq_num.low);
10935 if (dtls_RecordGetRecvd(&crSpec->recvdRecords, dtls_seq_num) != 0) {
10936 ssl_ReleaseSpecReadLock(ss);
10937 SSL_DBG(("%d: SSL3[%d]: HandleRecord, rejecting "
10938 "potentially replayed packet", SSL_GETPID(), ss->fd));
10939 /* Silently drop the packet */
10940 databuf->len = 0; /* Needed to ensure data not left around */
10946 minLength = crSpec->mac_size;
10947 if (cipher_def->type == type_block) {
10948 /* CBC records have a padding length byte at the end. */
10950 if (crSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
10951 /* With >= TLS 1.1, CBC records have an explicit IV. */
10952 minLength += cipher_def->iv_size;
10954 } else if (cipher_def->type == type_aead) {
10955 minLength = cipher_def->explicit_nonce_size + cipher_def->tag_size;
10958 /* We can perform this test in variable time because the record's total
10959 * length and the ciphersuite are both public knowledge. */
10960 if (cText->buf->len < minLength) {
10961 goto decrypt_loser;
10964 if (cipher_def->type == type_block &&
10965 crSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
10966 /* Consume the per-record explicit IV. RFC 4346 Section 6.2.3.2 states
10967 * "The receiver decrypts the entire GenericBlockCipher structure and
10968 * then discards the first cipher block corresponding to the IV
10969 * component." Instead, we decrypt the first cipher block and then
10970 * discard it before decrypting the rest.
10972 SSL3Opaque iv[MAX_IV_LENGTH];
10975 ivLen = cipher_def->iv_size;
10976 if (ivLen < 8 || ivLen > sizeof(iv)) {
10977 ssl_ReleaseSpecReadLock(ss);
10978 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
10982 PRINT_BUF(80, (ss, "IV (ciphertext):", cText->buf->buf, ivLen));
10984 /* The decryption result is garbage, but since we just throw away
10985 * the block it doesn't matter. The decryption of the next block
10986 * depends only on the ciphertext of the IV block.
10988 rv = crSpec->decode(crSpec->decodeContext, iv, &decoded,
10989 sizeof(iv), cText->buf->buf, ivLen);
10991 good &= SECStatusToMask(rv);
10994 /* If we will be decompressing the buffer we need to decrypt somewhere
10995 * other than into databuf */
10996 if (crSpec->decompressor) {
10997 temp_buf.buf = NULL;
10998 temp_buf.space = 0;
10999 plaintext = &temp_buf;
11001 plaintext = databuf;
11004 plaintext->len = 0; /* filled in by decode call below. */
11005 if (plaintext->space < MAX_FRAGMENT_LENGTH) {
11006 rv = sslBuffer_Grow(plaintext, MAX_FRAGMENT_LENGTH + 2048);
11007 if (rv != SECSuccess) {
11008 ssl_ReleaseSpecReadLock(ss);
11009 SSL_DBG(("%d: SSL3[%d]: HandleRecord, tried to get %d bytes",
11010 SSL_GETPID(), ss->fd, MAX_FRAGMENT_LENGTH + 2048));
11011 /* sslBuffer_Grow has set a memory error code. */
11012 /* Perhaps we should send an alert. (but we have no memory!) */
11017 PRINT_BUF(80, (ss, "ciphertext:", cText->buf->buf + ivLen,
11018 cText->buf->len - ivLen));
11020 isTLS = (PRBool)(crSpec->version > SSL_LIBRARY_VERSION_3_0);
11022 if (isTLS && cText->buf->len - ivLen > (MAX_FRAGMENT_LENGTH + 2048)) {
11023 ssl_ReleaseSpecReadLock(ss);
11024 SSL3_SendAlert(ss, alert_fatal, record_overflow);
11025 PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
11029 rType = cText->type;
11030 if (cipher_def->type == type_aead) {
11031 /* XXX For many AEAD ciphers, the plaintext is shorter than the
11032 * ciphertext by a fixed byte count, but it is not true in general.
11033 * Each AEAD cipher should provide a function that returns the
11034 * plaintext length for a given ciphertext. */
11035 unsigned int decryptedLen =
11036 cText->buf->len - cipher_def->explicit_nonce_size -
11037 cipher_def->tag_size;
11038 headerLen = ssl3_BuildRecordPseudoHeader(
11039 header, IS_DTLS(ss) ? cText->seq_num : crSpec->read_seq_num,
11040 rType, isTLS, cText->version, IS_DTLS(ss), decryptedLen);
11041 PORT_Assert(headerLen <= sizeof(header));
11043 ss->sec.isServer ? &crSpec->client : &crSpec->server,
11044 PR_TRUE, /* do decrypt */
11045 plaintext->buf, /* out */
11046 (int*) &plaintext->len, /* outlen */
11047 plaintext->space, /* maxout */
11048 cText->buf->buf, /* in */
11049 cText->buf->len, /* inlen */
11050 header, headerLen);
11051 if (rv != SECSuccess) {
11055 if (cipher_def->type == type_block &&
11056 ((cText->buf->len - ivLen) % cipher_def->block_size) != 0) {
11057 goto decrypt_loser;
11060 /* decrypt from cText buf to plaintext. */
11061 rv = crSpec->decode(
11062 crSpec->decodeContext, plaintext->buf, (int *)&plaintext->len,
11063 plaintext->space, cText->buf->buf + ivLen, cText->buf->len - ivLen);
11064 if (rv != SECSuccess) {
11065 goto decrypt_loser;
11068 PRINT_BUF(80, (ss, "cleartext:", plaintext->buf, plaintext->len));
11070 originalLen = plaintext->len;
11072 /* If it's a block cipher, check and strip the padding. */
11073 if (cipher_def->type == type_block) {
11074 const unsigned int blockSize = cipher_def->block_size;
11075 const unsigned int macSize = crSpec->mac_size;
11078 good &= SECStatusToMask(ssl_RemoveSSLv3CBCPadding(
11079 plaintext, blockSize, macSize));
11081 good &= SECStatusToMask(ssl_RemoveTLSCBCPadding(
11082 plaintext, macSize));
11086 /* compute the MAC */
11087 headerLen = ssl3_BuildRecordPseudoHeader(
11088 header, IS_DTLS(ss) ? cText->seq_num : crSpec->read_seq_num,
11089 rType, isTLS, cText->version, IS_DTLS(ss),
11090 plaintext->len - crSpec->mac_size);
11091 PORT_Assert(headerLen <= sizeof(header));
11092 if (cipher_def->type == type_block) {
11093 rv = ssl3_ComputeRecordMACConstantTime(
11094 crSpec, (PRBool)(!ss->sec.isServer), header, headerLen,
11095 plaintext->buf, plaintext->len, originalLen,
11098 ssl_CBCExtractMAC(plaintext, originalLen, givenHashBuf,
11100 givenHash = givenHashBuf;
11102 /* plaintext->len will always have enough space to remove the MAC
11103 * because in ssl_Remove{SSLv3|TLS}CBCPadding we only adjust
11104 * plaintext->len if the result has enough space for the MAC and we
11105 * tested the unadjusted size against minLength, above. */
11106 plaintext->len -= crSpec->mac_size;
11108 /* This is safe because we checked the minLength above. */
11109 plaintext->len -= crSpec->mac_size;
11111 rv = ssl3_ComputeRecordMAC(
11112 crSpec, (PRBool)(!ss->sec.isServer), header, headerLen,
11113 plaintext->buf, plaintext->len, hash, &hashBytes);
11115 /* We can read the MAC directly from the record because its location
11116 * is public when a stream cipher is used. */
11117 givenHash = plaintext->buf + plaintext->len;
11120 good &= SECStatusToMask(rv);
11122 if (hashBytes != (unsigned)crSpec->mac_size ||
11123 NSS_SecureMemcmp(givenHash, hash, crSpec->mac_size) != 0) {
11124 /* We're allowed to leak whether or not the MAC check was correct */
11131 /* must not hold spec lock when calling SSL3_SendAlert. */
11132 ssl_ReleaseSpecReadLock(ss);
11134 SSL_DBG(("%d: SSL3[%d]: decryption failed", SSL_GETPID(), ss->fd));
11136 if (!IS_DTLS(ss)) {
11137 SSL3_SendAlert(ss, alert_fatal, bad_record_mac);
11138 /* always log mac error, in case attacker can read server logs. */
11139 PORT_SetError(SSL_ERROR_BAD_MAC_READ);
11142 /* Silently drop the packet */
11143 databuf->len = 0; /* Needed to ensure data not left around */
11148 if (!IS_DTLS(ss)) {
11149 ssl3_BumpSequenceNumber(&crSpec->read_seq_num);
11151 dtls_RecordSetRecvd(&crSpec->recvdRecords, dtls_seq_num);
11154 ssl_ReleaseSpecReadLock(ss); /*****************************************/
11157 * The decrypted data is now in plaintext.
11160 /* possibly decompress the record. If we aren't using compression then
11161 * plaintext == databuf and so the uncompressed data is already in
11163 if (crSpec->decompressor) {
11164 if (databuf->space < plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION) {
11165 rv = sslBuffer_Grow(
11166 databuf, plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION);
11167 if (rv != SECSuccess) {
11168 SSL_DBG(("%d: SSL3[%d]: HandleRecord, tried to get %d bytes",
11169 SSL_GETPID(), ss->fd,
11170 plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION));
11171 /* sslBuffer_Grow has set a memory error code. */
11172 /* Perhaps we should send an alert. (but we have no memory!) */
11173 PORT_Free(plaintext->buf);
11178 rv = crSpec->decompressor(crSpec->decompressContext,
11180 (int*) &databuf->len,
11185 if (rv != SECSuccess) {
11186 int err = ssl_MapLowLevelError(SSL_ERROR_DECOMPRESSION_FAILURE);
11187 SSL3_SendAlert(ss, alert_fatal,
11188 isTLS ? decompression_failure : bad_record_mac);
11190 /* There appears to be a bug with (at least) Apache + OpenSSL where
11191 * resumed SSLv3 connections don't actually use compression. See
11192 * comments 93-95 of
11193 * https://bugzilla.mozilla.org/show_bug.cgi?id=275744
11195 * So, if we get a decompression error, and the record appears to
11196 * be already uncompressed, then we return a more specific error
11197 * code to hopefully save somebody some debugging time in the
11200 if (plaintext->len >= 4) {
11201 unsigned int len = ((unsigned int) plaintext->buf[1] << 16) |
11202 ((unsigned int) plaintext->buf[2] << 8) |
11203 (unsigned int) plaintext->buf[3];
11204 if (len == plaintext->len - 4) {
11205 /* This appears to be uncompressed already */
11206 err = SSL_ERROR_RX_UNEXPECTED_UNCOMPRESSED_RECORD;
11210 PORT_Free(plaintext->buf);
11211 PORT_SetError(err);
11215 PORT_Free(plaintext->buf);
11219 ** Having completed the decompression, check the length again.
11221 if (isTLS && databuf->len > (MAX_FRAGMENT_LENGTH + 1024)) {
11222 SSL3_SendAlert(ss, alert_fatal, record_overflow);
11223 PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
11227 /* Application data records are processed by the caller of this
11228 ** function, not by this function.
11230 if (rType == content_application_data) {
11231 if (ss->firstHsDone)
11233 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
11234 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA);
11238 /* It's a record that must be handled by ssl itself, not the application.
11241 /* XXX Get the xmit lock here. Odds are very high that we'll be xmiting
11242 * data ang getting the xmit lock here prevents deadlocks.
11244 ssl_GetSSL3HandshakeLock(ss);
11246 /* All the functions called in this switch MUST set error code if
11247 ** they return SECFailure or SECWouldBlock.
11250 case content_change_cipher_spec:
11251 rv = ssl3_HandleChangeCipherSpecs(ss, databuf);
11253 case content_alert:
11254 rv = ssl3_HandleAlert(ss, databuf);
11256 case content_handshake:
11257 if (!IS_DTLS(ss)) {
11258 rv = ssl3_HandleHandshake(ss, databuf);
11260 rv = dtls_HandleHandshake(ss, databuf);
11264 case content_application_data is handled before this switch
11267 SSL_DBG(("%d: SSL3[%d]: bogus content type=%d",
11268 SSL_GETPID(), ss->fd, cText->type));
11269 /* XXX Send an alert ??? */
11270 PORT_SetError(SSL_ERROR_RX_UNKNOWN_RECORD_TYPE);
11275 ssl_ReleaseSSL3HandshakeLock(ss);
11281 * Initialization functions
11284 /* Called from ssl3_InitState, immediately below. */
11285 /* Caller must hold the SpecWriteLock. */
11287 ssl3_InitCipherSpec(sslSocket *ss, ssl3CipherSpec *spec)
11289 spec->cipher_def = &bulk_cipher_defs[cipher_null];
11290 PORT_Assert(spec->cipher_def->cipher == cipher_null);
11291 spec->mac_def = &mac_defs[mac_null];
11292 PORT_Assert(spec->mac_def->mac == mac_null);
11293 spec->encode = Null_Cipher;
11294 spec->decode = Null_Cipher;
11295 spec->destroy = NULL;
11296 spec->compressor = NULL;
11297 spec->decompressor = NULL;
11298 spec->destroyCompressContext = NULL;
11299 spec->destroyDecompressContext = NULL;
11300 spec->mac_size = 0;
11301 spec->master_secret = NULL;
11302 spec->bypassCiphers = PR_FALSE;
11304 spec->msItem.data = NULL;
11305 spec->msItem.len = 0;
11307 spec->client.write_key = NULL;
11308 spec->client.write_mac_key = NULL;
11309 spec->client.write_mac_context = NULL;
11311 spec->server.write_key = NULL;
11312 spec->server.write_mac_key = NULL;
11313 spec->server.write_mac_context = NULL;
11315 spec->write_seq_num.high = 0;
11316 spec->write_seq_num.low = 0;
11318 spec->read_seq_num.high = 0;
11319 spec->read_seq_num.low = 0;
11322 dtls_InitRecvdRecords(&spec->recvdRecords);
11324 spec->version = ss->vrange.max;
11327 /* Called from: ssl3_SendRecord
11328 ** ssl3_StartHandshakeHash() <- ssl2_BeginClientHandshake()
11329 ** ssl3_SendClientHello()
11330 ** ssl3_HandleV2ClientHello()
11331 ** ssl3_HandleRecord()
11333 ** This function should perhaps acquire and release the SpecWriteLock.
11338 ssl3_InitState(sslSocket *ss)
11340 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
11342 if (ss->ssl3.initialized)
11343 return SECSuccess; /* Function should be idempotent */
11345 ss->ssl3.policy = SSL_ALLOWED;
11347 ssl_GetSpecWriteLock(ss);
11348 ss->ssl3.crSpec = ss->ssl3.cwSpec = &ss->ssl3.specs[0];
11349 ss->ssl3.prSpec = ss->ssl3.pwSpec = &ss->ssl3.specs[1];
11350 ss->ssl3.hs.sendingSCSV = PR_FALSE;
11351 ssl3_InitCipherSpec(ss, ss->ssl3.crSpec);
11352 ssl3_InitCipherSpec(ss, ss->ssl3.prSpec);
11354 ss->ssl3.hs.ws = (ss->sec.isServer) ? wait_client_hello : wait_server_hello;
11355 #ifdef NSS_ENABLE_ECC
11356 ss->ssl3.hs.negotiatedECCurves = ssl3_GetSupportedECCurveMask(ss);
11358 ssl_ReleaseSpecWriteLock(ss);
11360 PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData));
11363 ss->ssl3.hs.sendMessageSeq = 0;
11364 ss->ssl3.hs.recvMessageSeq = 0;
11365 ss->ssl3.hs.rtTimeoutMs = INITIAL_DTLS_TIMEOUT_MS;
11366 ss->ssl3.hs.rtRetries = 0;
11367 ss->ssl3.hs.recvdHighWater = -1;
11368 PR_INIT_CLIST(&ss->ssl3.hs.lastMessageFlight);
11369 dtls_SetMTU(ss, 0); /* Set the MTU to the highest plateau */
11372 PORT_Assert(!ss->ssl3.hs.messages.buf && !ss->ssl3.hs.messages.space);
11373 ss->ssl3.hs.messages.buf = NULL;
11374 ss->ssl3.hs.messages.space = 0;
11376 ss->ssl3.initialized = PR_TRUE;
11380 /* Returns a reference counted object that contains a key pair.
11381 * Or NULL on failure. Initial ref count is 1.
11382 * Uses the keys in the pair as input.
11385 ssl3_NewKeyPair( SECKEYPrivateKey * privKey, SECKEYPublicKey * pubKey)
11387 ssl3KeyPair * pair;
11389 if (!privKey || !pubKey) {
11390 PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
11393 pair = PORT_ZNew(ssl3KeyPair);
11395 return NULL; /* error code is set. */
11396 pair->refCount = 1;
11397 pair->privKey = privKey;
11398 pair->pubKey = pubKey;
11399 return pair; /* success */
11403 ssl3_GetKeyPairRef(ssl3KeyPair * keyPair)
11405 PR_ATOMIC_INCREMENT(&keyPair->refCount);
11410 ssl3_FreeKeyPair(ssl3KeyPair * keyPair)
11412 PRInt32 newCount = PR_ATOMIC_DECREMENT(&keyPair->refCount);
11414 if (keyPair->privKey)
11415 SECKEY_DestroyPrivateKey(keyPair->privKey);
11416 if (keyPair->pubKey)
11417 SECKEY_DestroyPublicKey( keyPair->pubKey);
11418 PORT_Free(keyPair);
11425 * Creates the public and private RSA keys for SSL Step down.
11426 * Called from SSL_ConfigSecureServer in sslsecur.c
11429 ssl3_CreateRSAStepDownKeys(sslSocket *ss)
11431 SECStatus rv = SECSuccess;
11432 SECKEYPrivateKey * privKey; /* RSA step down key */
11433 SECKEYPublicKey * pubKey; /* RSA step down key */
11435 if (ss->stepDownKeyPair)
11436 ssl3_FreeKeyPair(ss->stepDownKeyPair);
11437 ss->stepDownKeyPair = NULL;
11438 #ifndef HACKED_EXPORT_SERVER
11439 /* Sigh, should have a get key strength call for private keys */
11440 if (PK11_GetPrivateModulusLen(ss->serverCerts[kt_rsa].SERVERKEY) >
11441 EXPORT_RSA_KEY_LENGTH) {
11442 /* need to ask for the key size in bits */
11443 privKey = SECKEY_CreateRSAPrivateKey(EXPORT_RSA_KEY_LENGTH * BPB,
11445 if (!privKey || !pubKey ||
11446 !(ss->stepDownKeyPair = ssl3_NewKeyPair(privKey, pubKey))) {
11447 ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL);
11456 /* record the export policy for this cipher suite */
11458 ssl3_SetPolicy(ssl3CipherSuite which, int policy)
11460 ssl3CipherSuiteCfg *suite;
11462 suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
11463 if (suite == NULL) {
11464 return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
11466 suite->policy = policy;
11472 ssl3_GetPolicy(ssl3CipherSuite which, PRInt32 *oPolicy)
11474 ssl3CipherSuiteCfg *suite;
11478 suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
11480 policy = suite->policy;
11483 policy = SSL_NOT_ALLOWED;
11484 rv = SECFailure; /* err code was set by Lookup. */
11490 /* record the user preference for this suite */
11492 ssl3_CipherPrefSetDefault(ssl3CipherSuite which, PRBool enabled)
11494 ssl3CipherSuiteCfg *suite;
11496 suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
11497 if (suite == NULL) {
11498 return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
11500 suite->enabled = enabled;
11504 /* return the user preference for this suite */
11506 ssl3_CipherPrefGetDefault(ssl3CipherSuite which, PRBool *enabled)
11508 ssl3CipherSuiteCfg *suite;
11512 suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
11514 pref = suite->enabled;
11517 pref = SSL_NOT_ALLOWED;
11518 rv = SECFailure; /* err code was set by Lookup. */
11525 ssl3_CipherPrefSet(sslSocket *ss, ssl3CipherSuite which, PRBool enabled)
11527 ssl3CipherSuiteCfg *suite;
11529 suite = ssl_LookupCipherSuiteCfg(which, ss->cipherSuites);
11530 if (suite == NULL) {
11531 return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
11533 suite->enabled = enabled;
11538 ssl3_CipherPrefGet(sslSocket *ss, ssl3CipherSuite which, PRBool *enabled)
11540 ssl3CipherSuiteCfg *suite;
11544 suite = ssl_LookupCipherSuiteCfg(which, ss->cipherSuites);
11546 pref = suite->enabled;
11549 pref = SSL_NOT_ALLOWED;
11550 rv = SECFailure; /* err code was set by Lookup. */
11556 /* copy global default policy into socket. */
11558 ssl3_InitSocketPolicy(sslSocket *ss)
11560 PORT_Memcpy(ss->cipherSuites, cipherSuites, sizeof cipherSuites);
11563 /* ssl3_config_match_init must have already been called by
11564 * the caller of this function.
11567 ssl3_ConstructV2CipherSpecsHack(sslSocket *ss, unsigned char *cs, int *size)
11571 PORT_Assert(ss != 0);
11573 PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
11576 if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
11581 *size = count_cipher_suites(ss, SSL_ALLOWED, PR_TRUE);
11585 /* ssl3_config_match_init was called by the caller of this function. */
11586 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
11587 ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i];
11588 if (config_match(suite, SSL_ALLOWED, PR_TRUE, &ss->vrange)) {
11591 *cs++ = (suite->cipher_suite >> 8) & 0xFF;
11592 *cs++ = suite->cipher_suite & 0xFF;
11602 ** If ssl3 socket has completed the first handshake, and is in idle state,
11603 ** then start a new handshake.
11604 ** If flushCache is true, the SID cache will be flushed first, forcing a
11605 ** "Full" handshake (not a session restart handshake), to be done.
11607 ** called from SSL_RedoHandshake(), which already holds the handshake locks.
11610 ssl3_RedoHandshake(sslSocket *ss, PRBool flushCache)
11612 sslSessionID * sid = ss->sec.ci.sid;
11615 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
11617 if (!ss->firstHsDone ||
11618 ((ss->version >= SSL_LIBRARY_VERSION_3_0) &&
11619 ss->ssl3.initialized &&
11620 (ss->ssl3.hs.ws != idle_handshake))) {
11621 PORT_SetError(SSL_ERROR_HANDSHAKE_NOT_COMPLETED);
11626 dtls_RehandshakeCleanup(ss);
11629 if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) {
11630 PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED);
11633 if (sid && flushCache) {
11634 if (ss->sec.uncache)
11635 ss->sec.uncache(sid); /* remove it from whichever cache it's in. */
11636 ssl_FreeSID(sid); /* dec ref count and free if zero. */
11637 ss->sec.ci.sid = NULL;
11640 ssl_GetXmitBufLock(ss); /**************************************/
11642 /* start off a new handshake. */
11643 rv = (ss->sec.isServer) ? ssl3_SendHelloRequest(ss)
11644 : ssl3_SendClientHello(ss, PR_FALSE);
11646 ssl_ReleaseXmitBufLock(ss); /**************************************/
11650 /* Called from ssl_DestroySocketContents() in sslsock.c */
11652 ssl3_DestroySSL3Info(sslSocket *ss)
11655 if (ss->ssl3.clientCertificate != NULL)
11656 CERT_DestroyCertificate(ss->ssl3.clientCertificate);
11658 if (ss->ssl3.clientPrivateKey != NULL)
11659 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
11661 if (ss->ssl3.peerCertArena != NULL)
11662 ssl3_CleanupPeerCerts(ss);
11664 if (ss->ssl3.clientCertChain != NULL) {
11665 CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
11666 ss->ssl3.clientCertChain = NULL;
11669 /* clean up handshake */
11670 #ifndef NO_PKCS11_BYPASS
11671 if (ss->opt.bypassPKCS11) {
11672 if (ss->ssl3.hs.hashType == handshake_hash_combo) {
11673 SHA1_DestroyContext((SHA1Context *)ss->ssl3.hs.sha_cx, PR_FALSE);
11674 MD5_DestroyContext((MD5Context *)ss->ssl3.hs.md5_cx, PR_FALSE);
11675 } else if (ss->ssl3.hs.hashType == handshake_hash_single) {
11676 ss->ssl3.hs.sha_obj->destroy(ss->ssl3.hs.sha_cx, PR_FALSE);
11680 if (ss->ssl3.hs.md5) {
11681 PK11_DestroyContext(ss->ssl3.hs.md5,PR_TRUE);
11683 if (ss->ssl3.hs.sha) {
11684 PK11_DestroyContext(ss->ssl3.hs.sha,PR_TRUE);
11686 if (ss->ssl3.hs.clientSigAndHash) {
11687 PORT_Free(ss->ssl3.hs.clientSigAndHash);
11689 if (ss->ssl3.hs.messages.buf) {
11690 PORT_Free(ss->ssl3.hs.messages.buf);
11691 ss->ssl3.hs.messages.buf = NULL;
11692 ss->ssl3.hs.messages.len = 0;
11693 ss->ssl3.hs.messages.space = 0;
11696 /* free the SSL3Buffer (msg_body) */
11697 PORT_Free(ss->ssl3.hs.msg_body.buf);
11699 /* free up the CipherSpecs */
11700 ssl3_DestroyCipherSpec(&ss->ssl3.specs[0], PR_TRUE/*freeSrvName*/);
11701 ssl3_DestroyCipherSpec(&ss->ssl3.specs[1], PR_TRUE/*freeSrvName*/);
11703 /* Destroy the DTLS data */
11705 dtls_FreeHandshakeMessages(&ss->ssl3.hs.lastMessageFlight);
11706 if (ss->ssl3.hs.recvdFragments.buf) {
11707 PORT_Free(ss->ssl3.hs.recvdFragments.buf);
11711 ss->ssl3.initialized = PR_FALSE;
11713 SECITEM_FreeItem(&ss->ssl3.nextProto, PR_FALSE);
11716 /* End of ssl3con.c */